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 }
}
+133 -26
View File
@@ -18,11 +18,20 @@ import {
putMyApiSecret,
type ApiSecretCheckStatus,
type ApiSecretModuleKey,
type UserApiSecretBundle,
type UserApiSecretCheckResult,
type UserApiSecretItem,
} from '../api/types/modules/user-secret.ts'
import {
captureSecretsForInheritance,
inheritSecretsFromDevice,
type ApiSecretInheritanceHost,
type ApiSecretInheritanceNotice,
} from './api-secret-inheritance.ts'
import type { DesktopConfigUpdate } from '../bridges/pywebview.ts'
export type { ApiSecretModuleKey, ApiSecretCheckStatus }
export type { ApiSecretInheritanceNotice } from './api-secret-inheritance.ts'
export type { UserApiSecretCheckResult }
@@ -90,10 +99,26 @@ let bundleLoaded = false
let inflightLoad: Promise<ApiSecretLoadState> | null = null
/** 服务端代理状态(后台锁定/检测展示用);未成功加载过为 null。 */
let serverProxy: ServerProxySnapshot | null = null
/** 本次登录继承到的配置摘要:设置页消费一次,不落盘(避免多一个明文旁路)。 */
let inheritanceNotice: ApiSecretInheritanceNotice | null = null
/** 登出/切号会让在飞的密钥加载失效,防止 A 的响应落到 B 的会话里。 */
let cacheEpoch = 0
/** 上一次读到的登录 uid:会话过期后直接换号登录时,内存里的旧账号明文必须就地作废。 */
let cachedUid = ''
function currentUid(): string {
if (typeof window === 'undefined') return '0'
return window.localStorage.getItem('uid') || '0'
const uid = window.localStorage.getItem('uid') || '0'
if (cachedUid && cachedUid !== uid) {
memory.clear()
bundleLoaded = false
inflightLoad = null
serverProxy = null
inheritanceNotice = null
cacheEpoch += 1
}
cachedUid = uid
return uid
}
function buildMirrorKey(moduleKey: string) {
@@ -385,39 +410,63 @@ export function ensureApiSecretsLoaded(): Promise<ApiSecretLoadState> {
return loadApiSecrets()
}
async function applyServerBundle(bundle: UserApiSecretBundle | null | undefined): Promise<void> {
if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) {
requiredModules = bundle.requiredModules
}
for (const item of bundle?.items || []) {
if (item?.moduleKey) {
applyServerItem(item.moduleKey, item)
}
}
serverProxy = toServerProxy(bundle?.proxy)
if (serverProxy?.locked && serverProxy.full) {
// 后台锁定代理:把后台值对齐到本地配置(客户端任务链读本地),先比对、幂等、失败静默
await syncLockedProxyToLocal(serverProxy.full)
}
}
async function doLoad(): Promise<ApiSecretLoadState> {
// 换号(含会话过期后直接登录 B)时先作废旧账号缓存,再取 epoch:
// 反序会把本次加载自己判成“过期响应”,继承与门禁都走不到。
currentUid()
const epoch = cacheEpoch
try {
const bundle = await fetchMyApiSecrets()
if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) {
requiredModules = bundle.requiredModules
}
for (const item of bundle?.items || []) {
if (item?.moduleKey) {
applyServerItem(item.moduleKey, item)
}
}
serverProxy = toServerProxy(bundle?.proxy)
if (serverProxy?.locked && serverProxy.full) {
// 后台锁定代理:把后台值对齐到本地配置(客户端任务链读本地),先比对、幂等、失败静默
await syncLockedProxyToLocal(serverProxy.full)
}
let bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle)
if (epoch !== cacheEpoch) return 'unknown'
bundleLoaded = true
notify()
const migrated = await tryMigrateLocalSecrets(bundle?.items || [])
if (epoch !== cacheEpoch) return 'unknown'
if (migrated > 0) {
const refreshed = await fetchMyApiSecrets()
for (const item of refreshed?.items || []) {
if (item?.moduleKey) {
applyServerItem(item.moduleKey, item)
}
}
bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle)
if (epoch !== cacheEpoch) return 'unknown'
notify()
}
// 继承必须排在旧本地密钥迁移之后:两者都走 fill-only,谁先占住服务端空缺谁生效,
// 而当前账号自己的旧记录理应优先于上一个账号留下的快照。
if (bundle && Array.isArray(bundle.items)) {
const inherited = await tryInheritSecretsFromDevice(bundle.items, bundle.proxy)
if (epoch !== cacheEpoch) return 'unknown'
if (inherited > 0) {
bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle)
if (epoch !== cacheEpoch) return 'unknown'
notify()
}
}
const backfilled = await tryBackfillProxyToServer()
if (epoch !== cacheEpoch) return 'unknown'
if (backfilled) {
// 补报已写入服务端:重拉一次让 serverProxy 反映新状态,
// 否则任务提交前的代理检查会拿到上一轮的空快照。
const refreshed = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
serverProxy = toServerProxy(refreshed?.proxy)
notify()
}
@@ -513,16 +562,27 @@ async function readConfigForBackfill(): Promise<Record<string, unknown> | null>
* 若这里只认 proxy_users[uid],这些账号的代理永远补报不到服务端,外观专利任务会在
* 商标维度整批判失败(2026-10-25 账号 1210 的 32300/32309 就是这么来的)。
*/
function readLocalProxyUrl(config: Record<string, unknown> | null | undefined): string {
if (!config) return ''
const uid = currentUid()
function readLocalProxyEntry(
config: Record<string, unknown> | null | undefined,
uid = currentUid(),
): { url: string; mode: 1 | 2 } {
if (!config) return { url: '', mode: 1 }
if (uid !== '0') {
const users = (config.proxy_users ?? {}) as Record<string, unknown>
const own = (users[uid] ?? {}) as Record<string, unknown>
const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : ''
if (ownUrl) return ownUrl
if (ownUrl) {
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
}
}
return typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
return {
url: typeof config.proxy_url === 'string' ? config.proxy_url.trim() : '',
mode: Number(config.proxy_mode) === 2 ? 2 : 1,
}
}
function readLocalProxyUrl(config: Record<string, unknown> | null | undefined): string {
return readLocalProxyEntry(config).url
}
function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null {
@@ -570,6 +630,51 @@ async function syncLockedProxyToLocal(full: string): Promise<void> {
}
}
const inheritanceHost: ApiSecretInheritanceHost = {
currentUid,
isDesktopStorage: isNativeDesktopStorage,
moduleKeys: () => new Set<string>([...DEFAULT_REQUIRED_MODULES, ...requiredModules]),
readSecret: (moduleKey) => readEntry(moduleKey).value,
writeSecret: (moduleKey, value) => {
const entry = readEntry(moduleKey)
updateEntry(moduleKey, { value: entry.value || value })
},
readConfig: () => readConfigForBackfill(),
saveConfig: async (patch) => {
const api = window.pywebview?.api
if (!api?.save_config) return
await Promise.resolve(api.save_config(patch as DesktopConfigUpdate))
},
readLocalProxy: readLocalProxyEntry,
}
/**
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。
*
* 只走桌面真实桥(网页形态没有本地任务链,也不该把明文留给浏览器);
* 必须在本页内存/本地镜像被 clearApiSecretCache 清掉、且 localStorage.uid 被移除之前调用,
* 否则读到的会是空值或另一个 uid 的镜像。
*/
export function captureApiSecretsForInheritance(): Promise<void> {
return captureSecretsForInheritance(inheritanceHost)
}
async function tryInheritSecretsFromDevice(
serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<number> {
const outcome = await inheritSecretsFromDevice(inheritanceHost, serverItems, serverProxyItem)
if (outcome.notice) inheritanceNotice = outcome.notice
return outcome.count
}
/** 设置页消费一次继承提示(内存态,不落盘)。 */
export function takeApiSecretInheritanceNotice(): ApiSecretInheritanceNotice | null {
const notice = inheritanceNotice
inheritanceNotice = null
return notice
}
/** 保存密钥到服务端;成功后刷新本地缓存(失败不写本地,避免本地有值服务端没有的假象)。 */
export async function saveApiSecret(moduleKey: ApiSecretModuleKey, value: string): Promise<ApiSecretSnapshot> {
const trimmed = value.trim()
@@ -623,6 +728,8 @@ export function clearApiSecretCache(): void {
bundleLoaded = false
inflightLoad = null
serverProxy = null
inheritanceNotice = null
cacheEpoch += 1
}
/** 供测试与调试:模块级状态快照。 */