/** * 本机账号切换时的密钥继承:A 登出时留快照,B 登录后只补 B 服务端空缺的模块。 * * 这里不直接读写密钥镜像或服务端接口,全部经 host 回调交给 api-secret-store: * 两边共用同一份内存/镜像与「当前账号」,又不会互相 import 成环。 * 只服务桌面客户端(由 host.isDesktopStorage 判定);网页形态不参与。 */ import { migrateMyApiSecrets, type UserApiSecretItem } from '../api/types/modules/user-secret.ts' export type SecretProxyMode = 1 | 2 /** 本机账号切换后继承到的配置摘要:供设置页提示「继承了什么、还需检测」。 */ export interface ApiSecretInheritanceNotice { fromUid: string fromUsername: string moduleKeys: string[] proxy: boolean } export interface ApiSecretInheritanceHost { currentUid(): string isDesktopStorage(): boolean /** 参与继承的模块 key(服务端必填清单 + 默认清单)。 */ moduleKeys(): Set readSecret(moduleKey: string): string writeSecret(moduleKey: string, value: string): void readConfig(): Promise | null> saveConfig(patch: Record): Promise readLocalProxy( config: Record | null | undefined, uid: string, ): { url: string; mode: SecretProxyMode } } export interface InheritanceOutcome { count: number notice: ApiSecretInheritanceNotice | null } type InheritedSecretStash = { schema: 1 fromUid: string fromUsername: string savedAt: number secrets: Record proxyUrl: string proxyMode: SecretProxyMode } const INHERIT_STASH_KEY = 'api_secret_inherit' /** 继承快照的有效期:太久以前的登出记录不再往新账号上写(避免半年前的密钥复活)。 */ const INHERIT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000 function readInheritedSecretStash( config: Record | null | undefined, allowed: Set, ): InheritedSecretStash | null { const raw = config?.[INHERIT_STASH_KEY] if (!raw || typeof raw !== 'object') return null const record = raw as Record if (record.schema !== 1) return null const fromUid = typeof record.fromUid === 'string' ? record.fromUid.trim() : '' const savedAt = typeof record.savedAt === 'number' ? record.savedAt : 0 if (!fromUid || !savedAt || Date.now() - savedAt > INHERIT_MAX_AGE_MS) return null const secrets: Record = {} if (record.secrets && typeof record.secrets === 'object') { for (const [moduleKey, value] of Object.entries(record.secrets as Record)) { if (allowed.has(moduleKey) && typeof value === 'string' && value.trim()) { secrets[moduleKey] = value.trim() } } } return { schema: 1, fromUid, fromUsername: typeof record.fromUsername === 'string' ? record.fromUsername.trim() : '', savedAt, secrets, proxyUrl: typeof record.proxyUrl === 'string' ? record.proxyUrl.trim() : '', proxyMode: Number(record.proxyMode) === 2 ? 2 : 1, } } /** * 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。 * 调用方必须在本页内存/本地镜像被清掉、且 uid 被移除之前调用。 */ export async function captureSecretsForInheritance(host: ApiSecretInheritanceHost): Promise { if (typeof window === 'undefined' || !host.isDesktopStorage()) return const uid = host.currentUid() if (uid === '0') return const secrets: Record = {} for (const moduleKey of host.moduleKeys()) { const value = host.readSecret(moduleKey).trim() if (value) secrets[moduleKey] = value } const config = await host.readConfig().catch((error) => { console.warn('[api-secret] 登出时读取本机代理失败,继承快照将不含代理:', error) return null }) const proxy = host.readLocalProxy(config, uid) const stash: InheritedSecretStash | null = Object.keys(secrets).length || proxy.url ? { schema: 1, fromUid: uid, fromUsername: window.localStorage.getItem('username') || '', savedAt: Date.now(), secrets, proxyUrl: proxy.url, proxyMode: proxy.mode, } : null await host.saveConfig({ [INHERIT_STASH_KEY]: stash }).catch((error) => { console.warn('[api-secret] 登出时保存继承快照失败(不影响登出):', error) }) } /** * 本机上一个账号留下的配置:只补当前账号服务端空缺的模块,已有值一律不覆盖 * (服务端 migrate 接口本身也是 fill-only,后台锁定的代理不会被顶掉)。 * 检测状态不继承:那不是配置,不能跨账号冒充已通过。 */ export async function inheritSecretsFromDevice( host: ApiSecretInheritanceHost, serverItems: UserApiSecretItem[], serverProxyItem: UserApiSecretItem | null | undefined, ): Promise { if (typeof window === 'undefined' || !host.isDesktopStorage()) return { count: 0, notice: null } const uid = host.currentUid() if (uid === '0') return { count: 0, notice: null } const config = await host.readConfig().catch((error) => { console.warn('[api-secret] 读取本机继承快照失败(下次加载重试):', error) return null }) // 等配置期间可能已经登出/换号:旧账号的快照不能写进新账号的服务端 if (host.currentUid() !== uid) return { count: 0, notice: null } const stash = readInheritedSecretStash(config, host.moduleKeys()) if (!stash || stash.fromUid === uid) return { count: 0, notice: null } const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey)) const pending: Array<{ moduleKey: string; value: string }> = [] for (const [moduleKey, value] of Object.entries(stash.secrets)) { if (!serverHas.has(moduleKey)) pending.push({ moduleKey, value }) } // 本机已有代理时以本机为准:它会被代理补报逻辑上报给当前账号, // 这里再塞上一个账号的代理会让「服务端查商标」和「客户端跑任务」走两条不同的出口。 const inheritProxy = Boolean(stash.proxyUrl) && !serverProxyItem?.exists && !host.readLocalProxy(config, uid).url if (inheritProxy) pending.push({ moduleKey: 'proxy', value: stash.proxyUrl }) if (!pending.length) { await host.saveConfig({ [INHERIT_STASH_KEY]: null }).catch((error) => { console.warn('[api-secret] 清理已无用的继承快照失败:', error) }) return { count: 0, notice: null } } const result = await migrateMyApiSecrets(pending).catch((error) => { console.warn('[api-secret] 继承本机账号密钥失败(下次加载重试):', error) return null }) const migrated = Number(result?.migrated || 0) if (!result || migrated <= 0) return { count: 0, notice: null } for (const item of pending) { if (item.moduleKey !== 'proxy') host.writeSecret(item.moduleKey, item.value) } const patch: Record = { [INHERIT_STASH_KEY]: null } if (inheritProxy) { patch.proxy_users = { [uid]: { proxy_url: stash.proxyUrl, proxy_mode: stash.proxyMode } } } await host.saveConfig(patch).catch((error) => { console.warn('[api-secret] 继承配置已写入服务端,但写回本机配置失败:', error) }) const notice: ApiSecretInheritanceNotice = { fromUid: stash.fromUid, fromUsername: stash.fromUsername, moduleKeys: pending.filter((item) => item.moduleKey !== 'proxy').map((item) => item.moduleKey), proxy: inheritProxy, } console.log(`[api-secret] 已继承本机账号 ${stash.fromUsername || stash.fromUid} 的 ${migrated} 项配置`) return { count: migrated, notice } }