fix(secrets): 同机换号继承上一账号的密钥与代理

A 号在桌面端配好密钥后登出,B 号登录时服务端与本地都缺这些配置,
任务只能整批失败。现在登出前把当前账号的明文密钥与代理存进本机
app.json,B 首次加载时只补服务端空缺的模块(fill-only,后台锁定的
代理不覆盖),并写回 B 的本地镜像与 proxy_users;检测状态不继承,
设置页提示逐项点「检测」确认。

同时修掉登出顺序反了的问题:原来先移除 uid 再清镜像,镜像键带
uid,实际删的是 uid=0 的键,A 的明文镜像会留在本机;换号/会话过期
后内存里的 A 明文也会被 B 继续读到。现在先留快照、再清缓存、最后
移除 uid,并在 uid 变化时作废旧会话缓存、给在飞的加载加 epoch 栅栏。
This commit is contained in:
2026-10-25 22:37:13 +08:00
parent 9b2469ec33
commit 8323245567
7 changed files with 544 additions and 46 deletions
@@ -0,0 +1,178 @@
/**
* 本机账号切换时的密钥继承: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<string>
readSecret(moduleKey: string): string
writeSecret(moduleKey: string, value: string): void
readConfig(): Promise<Record<string, unknown> | null>
saveConfig(patch: Record<string, unknown>): Promise<unknown>
readLocalProxy(
config: Record<string, unknown> | 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<string, string>
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<string, unknown> | null | undefined,
allowed: Set<string>,
): InheritedSecretStash | null {
const raw = config?.[INHERIT_STASH_KEY]
if (!raw || typeof raw !== 'object') return null
const record = raw as Record<string, unknown>
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<string, string> = {}
if (record.secrets && typeof record.secrets === 'object') {
for (const [moduleKey, value] of Object.entries(record.secrets as Record<string, unknown>)) {
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<void> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return
const uid = host.currentUid()
if (uid === '0') return
const secrets: Record<string, string> = {}
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<InheritanceOutcome> {
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
})
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<string, unknown> = { [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 }
}