import { App } from '@capacitor/app' import { Browser } from '@capacitor/browser' import { Capacitor } from '@capacitor/core' import type { Router } from 'vue-router' const ssoPaths = new Set(['/sso/callback', '/sso/bind']) const nativeSsoStateKey = 'jiaowu_native_sso_state' export function beginNativeSsoLogin() { if (!Capacitor.isNativePlatform()) return null const bytes = crypto.getRandomValues(new Uint8Array(32)) const state = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') localStorage.setItem(nativeSsoStateKey, state) return state } export function nativeSsoLoginState() { return Capacitor.isNativePlatform() ? localStorage.getItem(nativeSsoStateKey) : null } export function clearNativeSsoLoginState() { localStorage.removeItem(nativeSsoStateKey) } function appLinkRoute(url: string) { try { const target = new URL(url) if (target.protocol === 'mingxu:' && target.host === 'open' && ssoPaths.has(target.pathname)) { return target.pathname + target.search + target.hash } const publicBase = new URL( String(import.meta.env.VITE_PUBLIC_BASE_URL ?? location.origin), ) return target.protocol === 'https:' && target.origin === publicBase.origin && ssoPaths.has(target.pathname) ? target.pathname + target.search + target.hash : null } catch { return null } } async function handleAppUrl(router: Router, url: string) { const route = appLinkRoute(url) if (!route) return await Browser.close().catch(() => undefined) await router.replace(route) } export async function initializeNativeAppLinks(router: Router) { if (!Capacitor.isNativePlatform()) return await App.addListener('appUrlOpen', event => { void handleAppUrl(router, event.url) }) const launchUrl = await App.getLaunchUrl() if (launchUrl?.url) await handleAppUrl(router, launchUrl.url) } export async function openSsoLogin(url: string) { if (!Capacitor.isNativePlatform()) { window.location.assign(url) return } await Browser.open({ url, toolbarColor: '#173a50' }) }