fix(cr2-frontend): 代理归属回退、换号继承确认与请求竞态收口

- CR-04:全局代理加 proxy_uid 归属,跨账号不再静默回退/补报
- CR-12:取消静默继承,设置页显式确认;同 OS 作用域、locked 代理排除、无效快照清除、uid+epoch 双校验、登出 capture 超时
- CR-26/27:关键词分页初始值与档位一致;两页面请求序号闸丢弃旧响应

vue-tsc 两前端 rc=0;定向 35 + 8 + 2 例全绿。
This commit is contained in:
2026-10-26 11:33:37 +08:00
parent b5e4c45add
commit b963561043
16 changed files with 1245 additions and 136 deletions
@@ -102,8 +102,8 @@
<span>自动登录</span>
</label>
</div>
<button type="submit" class="btn-login" id="btnLogin" :disabled="loggingIn">
{{ loggingIn ? '登录中...' : '登录' }}
<button type="submit" class="btn-login" id="btnLogin" :disabled="loggingIn || logoutCleanupPending">
{{ loggingIn ? '登录中...' : logoutCleanupPending ? '正在退出...' : '登录' }}
</button>
</form>
</div>
@@ -136,6 +136,11 @@ const username = ref('')
const password = ref('')
const passwordVisible = ref(false)
const loggingIn = ref(false)
/**
* 登出清理进行中(CR-12):继承快照 capture 有超时,但等它返回前不能允许再提交登录,
* 否则新账号 B 的 token/uid 会被上一轮 clearSignedOutState 删掉。
*/
const logoutCleanupPending = ref(false)
const errorMessage = ref('')
const kickedNotice = ref(false)
const expiredNotice = ref(false)
@@ -407,7 +412,8 @@ function toggleUpdate() {
}
async function submitLogin() {
if (loggingIn.value) return
// 登出清理未完成时禁止提交:清理函数会删 token/uid,晚到的登录会被它清掉(CR-12)
if (loggingIn.value || logoutCleanupPending.value) return
const account = username.value.trim()
if (!account || !password.value) {
errorMessage.value = '请输入账号和密码'
@@ -480,7 +486,9 @@ async function submitLogin() {
onMounted(() => {
const params = new URLSearchParams(window.location.search || '')
if (params.get('logout') === '1' || params.get('switch') === '1') {
logoutCleanupPending.value = true
const clearSignedOutState = () => {
logoutCleanupPending.value = false
// 清缓存必须在移除 uid 之前:镜像键带 uid,反序会按 uid=0 删错位置,
// 把本账号的明文镜像留在磁盘上给下一个账号(或网页脚本)读到。
clearApiSecretCache()
@@ -33,14 +33,18 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
import NotificationBell from '@/shared/components/NotificationBell.vue'
import {
confirmApiSecretInheritance,
declineApiSecretInheritance,
getPendingApiSecretInheritance,
getStoredApiSecretSnapshot,
listApiSecretModules,
loadApiSecrets,
takeApiSecretInheritanceNotice,
type ApiSecretInheritanceNotice,
type ApiSecretModuleKey,
} from '@/shared/utils/api-secret-store'
@@ -51,22 +55,71 @@ const submitting = ref(false)
const username = ref('')
const hint = ref('填写密钥后请先点「检测」确认可用再保存(检测通过的输入值保存时会沿用同一结果),全部检测通过后即可进入工具台。')
function inheritanceLabels(moduleKeys: string[], proxy: boolean): string[] {
const labels = listApiSecretModules()
.filter((module) => moduleKeys.includes(module.moduleKey))
.map((module) => module.moduleLabel)
if (proxy) labels.push('代理设置')
return labels
}
function showInheritanceNotice(inherited: ApiSecretInheritanceNotice | null): void {
if (!inherited) return
const labels = inheritanceLabels(inherited.moduleKeys, inherited.proxy)
// 共享电脑上不把上一个账号的用户名展示给新账号(CR-12)
hint.value = labels.length
? `已继承本机上一个账号的${labels.join('、')},请点击上方对应模块的「检测」确认后保存进入。`
: '已继承本机上一个账号的密钥配置,请点击上方「检测」逐项确认后保存进入。'
}
/**
* 继承确认(CR-12):同机换号不再静默继承上一个账号的密钥/代理。
* 只在本机确实有快照、且当前账号服务端还有空缺时弹一次确认;取消即清快照。
*/
async function promptPendingInheritance(): Promise<void> {
const pending = getPendingApiSecretInheritance()
if (!pending) {
showInheritanceNotice(takeApiSecretInheritanceNotice())
return
}
const labels = inheritanceLabels(pending.moduleKeys, pending.proxy)
const detail = labels.length ? `留下的${labels.join('、')}` : '留下的密钥配置'
const confirmed = () => {
void confirmApiSecretInheritance().then((notice) => {
if (!notice) {
hint.value = '未继承:服务端已有的项不会被覆盖,请手动填写并检测本账号密钥。'
return
}
showInheritanceNotice(notice)
})
}
const declined = () => {
void declineApiSecretInheritance().then(() => {
hint.value = '已跳过本机配置继承,请填写当前账号自己的密钥并检测后保存进入。'
})
}
// 两参 then:取消/关闭只走拒绝分支,不会把「确认过程中的网络失败」误当成用户拒绝而清快照
void ElMessageBox.confirm(
`检测到本机上一个账号${detail}。是否导入到当前账号?`
+ '仅在同一台电脑、同一 Windows 用户下、且确认这是你自己的配置时才选择「继承」;'
+ '服务端已有的密钥/代理不会被覆盖,后台锁定的代理也不会继承。',
'本机配置继承确认',
{
type: 'warning',
confirmButtonText: '继承',
cancelButtonText: '不继承',
distinguishCancelAndClose: true,
},
).then(confirmed, declined)
}
onMounted(() => {
try {
username.value = window.localStorage.getItem('username') || ''
} catch {
/* 忽略存储异常 */
}
const inherited = takeApiSecretInheritanceNotice()
if (inherited) {
const labels = listApiSecretModules()
.filter((module) => inherited.moduleKeys.includes(module.moduleKey))
.map((module) => module.moduleLabel)
if (inherited.proxy) labels.push('代理设置')
hint.value = labels.length
? `已继承本机账号「${inherited.fromUsername || inherited.fromUid}」的${labels.join('、')},请点击上方对应模块的「检测」确认后保存进入。`
: `已继承本机账号「${inherited.fromUsername || inherited.fromUid}」的密钥配置,请点击上方「检测」逐项确认后保存进入。`
}
void promptPendingInheritance()
})
/**
@@ -74,7 +74,14 @@ export interface DesktopConfigUpdate {
proxy_url?: string;
proxy_mode?: ProxyMode;
current_uid?: string;
/** 全局 proxy_url 的归属 uid(CR-04:只有 owner 匹配才允许回退)。 */
proxy_uid?: string;
/** 显式共享白名单:整机共享或指定 uid 列表(CR-04)。 */
proxy_shared?: boolean;
proxy_shared_uids?: string[];
proxy_users?: Record<string, { proxy_url?: string; proxy_mode?: number }>;
/** 本机继承快照的作用域标记(CR-12:同一 app.json 才能继承)。 */
api_secret_os_scope?: string;
/** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */
api_secret_inherit?: Record<string, unknown> | null;
aliprice_usename?: string;
@@ -1,11 +1,20 @@
/**
* 本机账号切换时的密钥继承:A 登出时留快照,B 登录后只补 B 服务端空缺的模块。
* 本机账号切换时的密钥继承:A 登出时留快照,B 登录后**经用户显式确认**只补 B 服务端空缺的模块。
*
* 安全口径(CR-12):
* - 不再静默继承:doLoad 只把可继承的快照登记成 pending,必须由设置页确认后才调 migrate;
* - 同 OS 用户限制:快照只从桌面原生 app.json 读,且带 `osUserScope`(该文件自己的作用域标记)。
* 作用域缺失/不一致(例如把别的 Windows 用户的 app.json 拷过来)一律视为无效并清键;
* - 后台锁定的代理不参与继承:服务端已锁定时客户端不得再用上一个账号的出口;
* - 无效/过期(>30 天)/结构不符的快照立即从 app.json 清掉,不让明文密钥无限期留在本机;
* - 每个 await 之后都比 uid 与 epoch:登出/切号期间晚到的响应不得写进新账号。
*
* 这里不直接读写密钥镜像或服务端接口,全部经 host 回调交给 api-secret-store:
* 两边共用同一份内存/镜像与「当前账号」,又不会互相 import 成环。
* 只服务桌面客户端(由 host.isDesktopStorage 判定);网页形态不参与。
*/
import { migrateMyApiSecrets, type UserApiSecretItem } from '../api/types/modules/user-secret.ts'
import { withTimeout } from './promise-timeout.ts'
export type SecretProxyMode = 1 | 2
@@ -17,8 +26,19 @@ export interface ApiSecretInheritanceNotice {
proxy: boolean
}
/** 待确认的继承快照摘要:设置页据此弹确认框,确认前不写服务端。 */
export interface PendingApiSecretInheritance {
fromUid: string
fromUsername: string
savedAt: number
moduleKeys: string[]
proxy: boolean
}
export interface ApiSecretInheritanceHost {
currentUid(): string
/** 登出/切号/清缓存都会 +1;与 uid 一起作为「响应是否还属于当前会话」的判据。 */
currentEpoch(): number
isDesktopStorage(): boolean
/** 参与继承的模块 key(服务端必填清单 + 默认清单)。 */
moduleKeys(): Set<string>
@@ -35,107 +55,191 @@ export interface ApiSecretInheritanceHost {
export interface InheritanceOutcome {
count: number
notice: ApiSecretInheritanceNotice | null
/** 快照是否已被消费/清掉;false 表示会话已变或失败,调用方应保留 pending 以便重试。 */
cleared: boolean
}
type InheritedSecretStash = {
schema: 1
export type InheritedSecretStash = {
schema: 2
fromUid: string
fromUsername: string
savedAt: number
osUserScope: string
secrets: Record<string, string>
proxyUrl: string
proxyMode: SecretProxyMode
}
export type InheritanceStashRead =
| { state: 'none' }
| { state: 'invalid' }
| { state: 'valid'; stash: InheritedSecretStash }
const INHERIT_STASH_KEY = 'api_secret_inherit'
/** 作用域标记住在同一个 app.json 里;app.json 本身按 OS 用户分目录,标记用于拒绝跨文件搬来的快照。 */
const OS_SCOPE_KEY = 'api_secret_os_scope'
const INHERIT_SCHEMA = 2
/** 继承快照的有效期:太久以前的登出记录不再往新账号上写(避免半年前的密钥复活)。 */
const INHERIT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000
/** 原生桥单次调用预算:登出不能被一个卡死的 read_config/save_config 拖住。 */
const BRIDGE_TIMEOUT_MS = 1000
function readInheritedSecretStash(
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null
}
function text(value: unknown): string {
return typeof value === 'string' ? value.trim() : ''
}
function newOsScope(): string {
const cryptoBox = typeof globalThis !== 'undefined'
? (globalThis as { crypto?: { randomUUID?: () => string } }).crypto
: undefined
if (cryptoBox?.randomUUID) return cryptoBox.randomUUID()
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
}
/** 当前 app.json 的作用域标记;缺失时由 capture 首次写入。 */
export function readOsUserScope(config: Record<string, unknown> | null | undefined): string {
return text(config?.[OS_SCOPE_KEY])
}
function sessionCurrent(host: ApiSecretInheritanceHost, uid: string, epoch: number): boolean {
return host.currentUid() === uid && host.currentEpoch() === epoch
}
/**
* 解析继承快照。结构不符、过期、作用域不一致一律返回 invalid:
* 调用方必须立即把 `api_secret_inherit` 清掉,不能让明文继续留在 app.json。
*/
export function readInheritedSecretStash(
config: Record<string, unknown> | null | undefined,
allowed: Set<string>,
): InheritedSecretStash | null {
): InheritanceStashRead {
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() : ''
if (raw == null) return { state: 'none' }
const record = asRecord(raw)
if (!record) return { state: 'invalid' }
if (record.schema !== INHERIT_SCHEMA) return { state: 'invalid' }
const fromUid = text(record.fromUid)
const savedAt = typeof record.savedAt === 'number' ? record.savedAt : 0
if (!fromUid || !savedAt || Date.now() - savedAt > INHERIT_MAX_AGE_MS) return null
const osUserScope = text(record.osUserScope)
const currentScope = readOsUserScope(config)
if (!fromUid || !savedAt || !osUserScope || !currentScope) return { state: 'invalid' }
// 同一份 app.json 内 scope 必须对得上;未来时间戳同样视为结构异常
if (osUserScope !== currentScope) return { state: 'invalid' }
if (savedAt > Date.now() + 5 * 60 * 1000) return { state: 'invalid' }
if (Date.now() - savedAt > INHERIT_MAX_AGE_MS) return { state: 'invalid' }
const secretRecord = asRecord(record.secrets)
if (!secretRecord) return { state: 'invalid' }
const proxyRaw = record.proxyUrl
if (proxyRaw != null && typeof proxyRaw !== 'string') return { state: 'invalid' }
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()
}
for (const [moduleKey, value] of Object.entries(secretRecord)) {
if (allowed.has(moduleKey) && typeof value === 'string' && value.trim()) {
secrets[moduleKey] = value.trim()
}
}
const proxyUrl = text(proxyRaw)
if (!Object.keys(secrets).length && !proxyUrl) return { state: 'invalid' }
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,
state: 'valid',
stash: {
schema: 2,
fromUid,
fromUsername: text(record.fromUsername),
savedAt,
osUserScope,
secrets,
proxyUrl,
proxyMode: Number(record.proxyMode) === 2 ? 2 : 1,
},
}
}
/** 设置页确认框用的摘要(不含明文)。 */
export function toPendingInheritance(stash: InheritedSecretStash): PendingApiSecretInheritance {
return {
fromUid: stash.fromUid,
fromUsername: stash.fromUsername,
savedAt: stash.savedAt,
moduleKeys: Object.keys(stash.secrets),
proxy: Boolean(stash.proxyUrl),
}
}
/**
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。
* 登出瞬间把当前账号的密钥与代理留一份到客户端 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 epoch = host.currentEpoch()
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)
const config = await withTimeout(host.readConfig(), BRIDGE_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 登出时读取本机配置失败,继承快照将不含代理:', error)
return null
})
// 等配置期间可能已经被登出清理:旧账号的快照不能盖到新账号的作用域上
if (!sessionCurrent(host, uid, epoch)) return
const proxy = host.readLocalProxy(config, uid)
const osUserScope = readOsUserScope(config) || newOsScope()
const stash: InheritedSecretStash | null = Object.keys(secrets).length || proxy.url
? {
schema: 1,
schema: 2,
fromUid: uid,
fromUsername: window.localStorage.getItem('username') || '',
savedAt: Date.now(),
osUserScope,
secrets,
proxyUrl: proxy.url,
proxyMode: proxy.mode,
}
: null
await host.saveConfig({ [INHERIT_STASH_KEY]: stash }).catch((error) => {
console.warn('[api-secret] 登出时保存继承快照失败(不影响登出):', error)
await withTimeout(host.saveConfig({ [OS_SCOPE_KEY]: osUserScope, [INHERIT_STASH_KEY]: stash }), BRIDGE_TIMEOUT_MS)
.catch((error) => {
console.warn('[api-secret] 登出时保存继承快照失败(不影响登出):', error)
})
}
/** 立即清掉 app.json 里的继承快照(无效快照、用户拒绝、已消费三条路径共用)。 */
export async function clearInheritedSecrets(host: ApiSecretInheritanceHost): Promise<void> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return
await withTimeout(host.saveConfig({ [INHERIT_STASH_KEY]: null }), BRIDGE_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 清理本机继承快照失败:', error)
})
}
/**
* 本机上一个账号留下的配置:只补当前账号服务端空缺的模块,已有值一律不覆盖
* 应用已确认的继承快照:只补当前账号服务端空缺的模块,已有值一律不覆盖
* (服务端 migrate 接口本身也是 fill-only,后台锁定的代理不会被顶掉)。
* 检测状态不继承:那不是配置,不能跨账号冒充已通过。
*
* 每个 await 之后都同时比 uid 与 epoch:确认框打开期间用户可能已经切号/登出,
* 晚到的 migrate 响应或写回都不能落到新账号。
*/
export async function inheritSecretsFromDevice(
export async function applyInheritedSecrets(
host: ApiSecretInheritanceHost,
stash: InheritedSecretStash,
config: Record<string, unknown> | null | undefined,
serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<InheritanceOutcome> {
if (typeof window === 'undefined' || !host.isDesktopStorage()) return { count: 0, notice: null }
if (typeof window === 'undefined' || !host.isDesktopStorage()) {
return { count: 0, notice: null, cleared: false }
}
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 }
if (uid === '0') return { count: 0, notice: null, cleared: false }
const epoch = host.currentEpoch()
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)) {
@@ -143,22 +247,26 @@ export async function inheritSecretsFromDevice(
}
// 本机已有代理时以本机为准:它会被代理补报逻辑上报给当前账号,
// 这里再塞上一个账号的代理会让「服务端查商标」和「客户端跑任务」走两条不同的出口。
// 服务端已存在/后台已锁定的代理同样不继承(CR-12:locked 代理必须排除)。
const ownProxy = host.readLocalProxy(config, uid).url
const inheritProxy = Boolean(stash.proxyUrl)
&& Boolean(config)
&& !serverProxyItem?.exists
&& !host.readLocalProxy(config, uid).url
&& !serverProxyItem?.locked
&& !ownProxy
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 }
await clearInheritedSecrets(host)
return { count: 0, notice: null, cleared: true }
}
const result = await migrateMyApiSecrets(pending).catch((error) => {
console.warn('[api-secret] 继承本机账号密钥失败(下次加载重试):', error)
console.warn('[api-secret] 继承本机账号密钥失败(下次确认时重试):', error)
return null
})
if (!sessionCurrent(host, uid, epoch)) return { count: 0, notice: null, cleared: false }
const migrated = Number(result?.migrated || 0)
if (!result || migrated <= 0) return { count: 0, notice: null }
if (!result || migrated <= 0) return { count: 0, notice: null, cleared: false }
// migrate 的 await 结束后已经重新比过 uid/epoch,这里才允许把明文写回当前会话的本地镜像
for (const item of pending) {
if (item.moduleKey !== 'proxy') host.writeSecret(item.moduleKey, item.value)
}
@@ -169,12 +277,13 @@ export async function inheritSecretsFromDevice(
await host.saveConfig(patch).catch((error) => {
console.warn('[api-secret] 继承配置已写入服务端,但写回本机配置失败:', error)
})
if (!sessionCurrent(host, uid, epoch)) return { count: 0, notice: null, cleared: false }
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 }
console.log(`[api-secret] 已确认继承本机账号 ${stash.fromUsername || stash.fromUid} 的 ${migrated} 项配置`)
return { count: migrated, notice, cleared: true }
}
+283 -56
View File
@@ -23,15 +23,24 @@ import {
type UserApiSecretItem,
} from '../api/types/modules/user-secret.ts'
import {
applyInheritedSecrets,
captureSecretsForInheritance,
inheritSecretsFromDevice,
clearInheritedSecrets,
readInheritedSecretStash,
toPendingInheritance,
type ApiSecretInheritanceHost,
type ApiSecretInheritanceNotice,
type InheritedSecretStash,
type PendingApiSecretInheritance,
} from './api-secret-inheritance.ts'
import { withTimeout } from './promise-timeout.ts'
import type { DesktopConfigUpdate } from '../bridges/pywebview.ts'
export type { ApiSecretModuleKey, ApiSecretCheckStatus }
export type { ApiSecretInheritanceNotice } from './api-secret-inheritance.ts'
export type {
ApiSecretInheritanceNotice,
PendingApiSecretInheritance,
} from './api-secret-inheritance.ts'
export type { UserApiSecretCheckResult }
@@ -79,6 +88,10 @@ const LEGACY_MODULE_KEYS = ['appearance-patent', 'appearance-patent-token', 'sim
const MIGRATED_FLAG_PREFIX = 'brand:api-secret-migrated'
const DEFAULT_REQUIRED_MODULES: ApiSecretModuleKey[] = ['appearance-patent', 'similar-asin']
const FETCH_TIMEOUT_MS = 4000
/** 登出继承快照的整体预算:原生桥卡死也必须让登出清理继续走。 */
const CAPTURE_TIMEOUT_MS = 2500
/** 读/写 app.json 的单次预算:doLoad 不能被一个永不返回的桥调用挂住。 */
const CONFIG_TIMEOUT_MS = 3000
const memory = new Map<string, ApiSecretCacheEntry>()
const listeners = new Set<() => void>()
@@ -101,6 +114,14 @@ let inflightLoad: Promise<ApiSecretLoadState> | null = null
let serverProxy: ServerProxySnapshot | null = null
/** 本次登录继承到的配置摘要:设置页消费一次,不落盘(避免多一个明文旁路)。 */
let inheritanceNotice: ApiSecretInheritanceNotice | null = null
/**
* 本机上一个账号留下、等待用户显式确认的继承快照(CR-12)。
* 确认前不写服务端、不写本地镜像;登出/切号时连同摘要一起作废。
*/
let pendingInheritance: {
summary: PendingApiSecretInheritance
stash: InheritedSecretStash
} | null = null
/** 登出/切号会让在飞的密钥加载失效,防止 A 的响应落到 B 的会话里。 */
let cacheEpoch = 0
/** 上一次读到的登录 uid:会话过期后直接换号登录时,内存里的旧账号明文必须就地作废。 */
@@ -115,12 +136,18 @@ function currentUid(): string {
inflightLoad = null
serverProxy = null
inheritanceNotice = null
pendingInheritance = null
cacheEpoch += 1
}
cachedUid = uid
return uid
}
/** 响应回写前的统一闸门:uid 与 epoch 必须同时还是发起请求时那一个。 */
function sessionCurrent(uid: string, epoch: number): boolean {
return currentUid() === uid && cacheEpoch === epoch
}
function buildMirrorKey(moduleKey: string) {
return `${MIRROR_PREFIX}:${currentUid()}:${moduleKey}`
}
@@ -412,8 +439,12 @@ export function ensureApiSecretsLoaded(): Promise<ApiSecretLoadState> {
async function applyServerBundle(
bundle: UserApiSecretBundle | null | undefined,
uid: string,
epoch: number,
): Promise<void> {
// 先用调用方发请求时的 uid/epoch 验身,再动内存/镜像:
// 不能在这里重新 currentUid()——那会把「已经换成 B」当成合法会话,把 A 的包写进 B。
if (!sessionCurrent(uid, epoch)) return
if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) {
requiredModules = bundle.requiredModules
}
@@ -424,54 +455,50 @@ async function applyServerBundle(
}
serverProxy = toServerProxy(bundle?.proxy)
// 登出/换号可能发生在读配置的等待里:旧账号的锁定代理绝不能写进新账号的本地配置
if (epoch !== cacheEpoch) return
if (!sessionCurrent(uid, epoch)) return
if (serverProxy?.locked && serverProxy.full) {
// 后台锁定代理:把后台值对齐到本地配置(客户端任务链读本地),先比对、幂等、失败静默
await syncLockedProxyToLocal(serverProxy.full)
await syncLockedProxyToLocal(serverProxy.full, uid, epoch)
// write 之前再比一次:sync 内部的 await 期间可能已经切号/登出
if (!sessionCurrent(uid, epoch)) return
}
}
async function doLoad(): Promise<ApiSecretLoadState> {
// 换号(含会话过期后直接登录 B)时先作废旧账号缓存,再取 epoch:
// 反序会把本次加载自己判成“过期响应”,继承与门禁都走不到。
currentUid()
const uid = currentUid()
const epoch = cacheEpoch
try {
let bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle, epoch)
if (epoch !== cacheEpoch) return 'unknown'
if (!sessionCurrent(uid, epoch)) return 'unknown'
await applyServerBundle(bundle, uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
bundleLoaded = true
notify()
const migrated = await tryMigrateLocalSecrets(bundle?.items || [])
if (epoch !== cacheEpoch) return 'unknown'
const migrated = await tryMigrateLocalSecrets(bundle?.items || [], uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
if (migrated > 0) {
bundle = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
await applyServerBundle(bundle, epoch)
if (epoch !== cacheEpoch) return 'unknown'
if (!sessionCurrent(uid, epoch)) return 'unknown'
await applyServerBundle(bundle, uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
notify()
}
// 继承必须排在旧本地密钥迁移之后:两者都走 fill-only,谁先占住服务端空缺谁生效,
// 而当前账号自己的旧记录理应优先于上一个账号留下的快照。
// CR-12:这里只登记待确认快照,不再自动 migrate——明文是否跨账号复用必须由用户拍板。
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, epoch)
if (epoch !== cacheEpoch) return 'unknown'
notify()
}
await stageInheritance(bundle.items, bundle.proxy, uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
}
const backfilled = await tryBackfillProxyToServer()
if (epoch !== cacheEpoch) return 'unknown'
const backfilled = await tryBackfillProxyToServer(uid, epoch)
if (!sessionCurrent(uid, epoch)) return 'unknown'
if (backfilled) {
// 补报已写入服务端:重拉一次让 serverProxy 反映新状态,
// 否则任务提交前的代理检查会拿到上一轮的空快照。
const refreshed = await fetchMyApiSecrets()
if (epoch !== cacheEpoch) return 'unknown'
if (!sessionCurrent(uid, epoch)) return 'unknown'
serverProxy = toServerProxy(refreshed?.proxy)
notify()
}
@@ -483,7 +510,11 @@ async function doLoad(): Promise<ApiSecretLoadState> {
}
/** 旧本地密钥一次性迁移:仅当服务端空缺且有本地明文时上报;失败静默,下次加载重试。 */
async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise<number> {
async function tryMigrateLocalSecrets(
serverItems: UserApiSecretItem[],
uid: string,
epoch: number,
): Promise<number> {
if (typeof window === 'undefined') return 0
try {
if (window.localStorage.getItem(migratedFlagKey()) === '1') {
@@ -505,6 +536,8 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
return 0
}
const result = await migrateMyApiSecrets(pending)
// 等接口期间可能已登出/切号:旧账号的明文不能再写进当前账号的本地镜像
if (!sessionCurrent(uid, epoch)) return 0
const migrated = Number(result?.migrated || 0)
// 迁移成功后本地保留明文(供提交任务直接使用),只清理旧记录与标记
for (const item of pending) {
@@ -527,17 +560,25 @@ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise
*
* @returns 是否真的补报了一条(migrated > 0);调用方据此决定要不要重拉服务端快照。
*/
async function tryBackfillProxyToServer(): Promise<boolean> {
async function tryBackfillProxyToServer(uid: string, epoch: number): Promise<boolean> {
try {
const uid = currentUid()
if (uid === '0') return false
const config = await readConfigForBackfill()
const config = await withTimeout(readConfigForBackfill(), CONFIG_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 读取本机代理配置失败(下次加载重试):', error)
return null
})
if (!config) return false
// 等配置期间可能已经登出/换号:补报请求会带新账号令牌,必须放弃旧账号的本地代理
if (currentUid() !== uid) return false
const url = readLocalProxyUrl(config)
if (!sessionCurrent(uid, epoch)) return false
// 升级一次性归属迁移:老版本只存全局 proxy_url、没有 proxy_uid。
// 第一个读到它的账号把它认领成自己的(写入 proxy_users[uid] + proxy_uid 并清空全局),
// 之后其他账号再登录就不会静默回退到这个代理(CR-04)。
const ownedConfig = await claimLegacyGlobalProxy(config, uid)
if (!sessionCurrent(uid, epoch)) return false
const url = readLocalProxyUrl(ownedConfig, uid)
if (!url) return false
const result = await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }])
if (!sessionCurrent(uid, epoch)) return false
return Number(result?.migrated || 0) > 0
} catch (error) {
console.warn('[api-secret] 代理配置补报失败(下次加载重试):', error)
@@ -564,17 +605,96 @@ async function readConfigForBackfill(): Promise<Record<string, unknown> | null>
return (await api.read_config()) as Record<string, unknown> | null
}
/** 写回本机配置:与 readConfigForBackfill 同一套桥选择;写成功返回 true。 */
async function saveConfigForBackfill(patch: Record<string, unknown>): Promise<boolean> {
if (typeof window === 'undefined') return false
const direct = window.pywebview?.api
if (direct?.save_config) {
await direct.save_config(patch as DesktopConfigUpdate)
return true
}
if (typeof document === 'undefined') return false
const { getPywebviewApi } = await import('../bridges/pywebview.ts')
const api = getPywebviewApi()
if (!api?.save_config) return false
await api.save_config(patch as DesktopConfigUpdate)
return true
}
/**
* 读取当前登录用户的本地代理地址:proxy_users[uid] 优先,用户项为空时回退全局 proxy_url。
* 回退口径与客户端任务链 `resolve_current_proxy` 一致——老版本把代理存在全局 proxy_url,
* 若这里只认 proxy_users[uid],这些账号的代理永远补报不到服务端,外观专利任务会在
* 商标维度整批判失败(2026-10-25 账号 1210 的 32300/32309 就是这么来的)。
* 无归属的全局 proxy_url 一次性归给当前 uid(CR-04)。
*
* 老版本把代理存在全局 proxy_url(2026-10-25 账号 1210 的 32300/32309 就靠这条路径补报),
* 但全局字段本身不带归属,A 留下的代理会被 B 静默继承。升级时由第一个读到它的账号认领:
* 写入 `proxy_users[uid]` 与 `proxy_uid`,随后清空全局 `proxy_url`。
* 认领失败(桥没有 save_config 或写入抛错)时不回退——宁可不补报,也不把出口写给别的账号。
*/
async function claimLegacyGlobalProxy(
config: Record<string, unknown> | null | undefined,
uid: string,
): Promise<Record<string, unknown> | null | undefined> {
if (!config || uid === '0') return config
const globalUrl = typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
const owner = typeof config.proxy_uid === 'string' ? config.proxy_uid.trim() : ''
// 归属 0 等同未登录时的匿名全局,按"无归属"处理;只有明确归属到别的 uid 才绝不碰
if (!globalUrl || (owner && owner !== '0')) return config
const users = (config.proxy_users ?? {}) as Record<string, unknown>
const own = users[uid]
const ownRecord = own && typeof own === 'object' && !Array.isArray(own)
? own as Record<string, unknown>
: {}
const ownUrl = typeof ownRecord.proxy_url === 'string' ? ownRecord.proxy_url.trim() : ''
if (ownUrl && !isSharedProxy(config, uid)) {
// 当前账号已有自己的代理:全局字段是历史残留,归给当前 uid 后清空,
// 避免下一个账号把它当成"无主代理"认领走。
// 若全局是显式共享(proxy_shared/proxy_shared_uids)则保留给其他账号。
const cleared = await saveConfigForBackfill({ proxy_url: '', proxy_uid: uid }).catch((error) => {
console.warn('[api-secret] 清理本机残留全局代理失败(下次加载重试):', error)
return false
})
return cleared ? { ...config, proxy_url: '', proxy_uid: uid } : config
}
const mode = Number(config.proxy_mode) === 2 ? 2 : 1
const saved = await saveConfigForBackfill({
proxy_url: '',
proxy_uid: uid,
proxy_users: { [uid]: { ...ownRecord, proxy_url: globalUrl, proxy_mode: mode } },
}).catch((error) => {
console.warn('[api-secret] 全局代理归属迁移失败(不静默回退给当前账号):', error)
return false
})
if (!saved) return config
return {
...config,
proxy_url: '',
proxy_uid: uid,
proxy_users: { ...users, [uid]: { ...ownRecord, proxy_url: globalUrl, proxy_mode: mode } },
}
}
/** 显式共享白名单:`proxy_shared=true`(整机共享)或 `proxy_shared_uids` 包含当前 uid。 */
function isSharedProxy(config: Record<string, unknown> | null | undefined, uid: string): boolean {
if (!config) return false
if (config.proxy_shared === true) return true
return Array.isArray(config.proxy_shared_uids)
&& config.proxy_shared_uids.some((item) => String(item).trim() === uid)
}
/**
* 读取当前登录用户的本地代理地址。
*
* 回退顺序(CR-04):proxy_users[uid] → 全局 proxy_url **且归属就是当前 uid**
* (或显式共享白名单 `proxy_shared=true` / `proxy_shared_uids` 包含当前 uid)。
* 全局字段未归属/归属别人时返回空,绝不再把上一个账号的出口补报给当前账号。
* 未登录(uid=0)只认匿名全局或共享白名单,不碰实名归属的代理。
*/
function readLocalProxyEntry(
config: Record<string, unknown> | null | undefined,
uid = currentUid(),
): { url: string; mode: 1 | 2 } {
if (!config) return { url: '', mode: 1 }
const globalUrl = typeof config.proxy_url === 'string' ? config.proxy_url.trim() : ''
const globalMode: 1 | 2 = Number(config.proxy_mode) === 2 ? 2 : 1
if (uid !== '0') {
const users = (config.proxy_users ?? {}) as Record<string, unknown>
const own = (users[uid] ?? {}) as Record<string, unknown>
@@ -583,14 +703,25 @@ function readLocalProxyEntry(
return { url: ownUrl, mode: Number(own.proxy_mode) === 2 ? 2 : 1 }
}
}
return {
url: typeof config.proxy_url === 'string' ? config.proxy_url.trim() : '',
mode: Number(config.proxy_mode) === 2 ? 2 : 1,
const owner = typeof config.proxy_uid === 'string' ? config.proxy_uid.trim() : ''
const shared = isSharedProxy(config, uid)
if (!globalUrl) return { url: '', mode: 1 }
if (uid === '0') {
// 未登录没有"账号归属"可言:只认匿名全局(无归属/归属 0)或显式共享
return !owner || owner === '0' || shared
? { url: globalUrl, mode: globalMode }
: { url: '', mode: 1 }
}
return owner === uid || shared
? { url: globalUrl, mode: globalMode }
: { url: '', mode: 1 }
}
function readLocalProxyUrl(config: Record<string, unknown> | null | undefined): string {
return readLocalProxyEntry(config).url
function readLocalProxyUrl(
config: Record<string, unknown> | null | undefined,
uid = currentUid(),
): string {
return readLocalProxyEntry(config, uid).url
}
function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null {
@@ -615,15 +746,18 @@ function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxy
* 让客户端各任务链与后台值保持一致。先读后比对、幂等;失败静默,下次加载重试。
* 只走桌面端真实桥(window.pywebview):Web 降级桥的配置与桌面 app.json 无关。
*/
async function syncLockedProxyToLocal(full: string): Promise<void> {
async function syncLockedProxyToLocal(
full: string,
uidAtStart: string,
epochAtStart: number,
): Promise<void> {
try {
if (typeof window === 'undefined') return
const api = window.pywebview?.api
if (!api?.read_config || !api?.save_config) return
const uidAtStart = currentUid()
const config = (await api.read_config()) as Record<string, unknown> | null
if (currentUid() !== uidAtStart) return
if (readLocalProxyUrl(config) === full) return
if (!sessionCurrent(uidAtStart, epochAtStart)) return
if (readLocalProxyUrl(config, uidAtStart) === full) return
const uid = uidAtStart
if (uid === '0') {
const mode = Number(config?.proxy_mode) === 2 ? 2 : 1
@@ -635,6 +769,8 @@ async function syncLockedProxyToLocal(full: string): Promise<void> {
// save_config 对 proxy_users 只做 uid 级合并(保留其他用户),故同一对象内要带齐原有模式
const mode = Number(own.proxy_mode) === 2 ? 2 : 1
await api.save_config({ proxy_users: { [uid]: { proxy_url: full, proxy_mode: mode } } })
// save 的 await 之后不再有写操作;保留一次检查让"迟到响应不落到新账号"的口径可被测试钉住
if (!sessionCurrent(uidAtStart, epochAtStart)) return
} catch (error) {
console.warn('[api-secret] 锁定代理写入本地配置失败(下次加载重试):', error)
}
@@ -642,40 +778,130 @@ async function syncLockedProxyToLocal(full: string): Promise<void> {
const inheritanceHost: ApiSecretInheritanceHost = {
currentUid,
currentEpoch: () => cacheEpoch,
isDesktopStorage: isNativeDesktopStorage,
moduleKeys: () => new Set<string>([...DEFAULT_REQUIRED_MODULES, ...requiredModules]),
readSecret: (moduleKey) => readEntry(moduleKey).value,
// 只有 applyInheritedSecrets 在 migrate 的 await 之后重新比过 uid/epoch 才会调到这里
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))
},
saveConfig: (patch) => saveConfigForBackfill(patch),
readLocalProxy: readLocalProxyEntry,
}
/**
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号继承。
* 登出瞬间把当前账号的密钥与代理留一份到客户端 app.json,供本机下一个账号**确认后**继承。
*
* 只走桌面真实桥(网页形态没有本地任务链,也不该把明文留给浏览器);
* 必须在本页内存/本地镜像被 clearApiSecretCache 清掉、且 localStorage.uid 被移除之前调用,
* 否则读到的会是空值或另一个 uid 的镜像。
*
* 外层再加一道整体超时:桥卡死时调用方(登录页)必须能继续清 token/uid,
* 不能让登出停在"还在清"的状态里(CR-12)。
*/
export function captureApiSecretsForInheritance(): Promise<void> {
return captureSecretsForInheritance(inheritanceHost)
return withTimeout(captureSecretsForInheritance(inheritanceHost), CAPTURE_TIMEOUT_MS)
}
async function tryInheritSecretsFromDevice(
/**
* 读取本机继承快照并登记为待确认(CR-12:不再自动 migrate)。
* 无效/过期/作用域不符的快照在这里立即清掉,避免明文密钥无限期留在 app.json。
*/
async function stageInheritance(
serverItems: UserApiSecretItem[],
serverProxyItem: UserApiSecretItem | null | undefined,
): Promise<number> {
const outcome = await inheritSecretsFromDevice(inheritanceHost, serverItems, serverProxyItem)
if (outcome.notice) inheritanceNotice = outcome.notice
return outcome.count
uid: string,
epoch: number,
): Promise<void> {
if (!isNativeDesktopStorage()) {
pendingInheritance = null
return
}
const config = await withTimeout(readConfigForBackfill(), CONFIG_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 读取本机继承快照失败(下次加载重试):', error)
return null
})
if (!sessionCurrent(uid, epoch)) return
const parsed = readInheritedSecretStash(config, inheritanceHost.moduleKeys())
if (parsed.state === 'none') {
pendingInheritance = null
return
}
if (parsed.state === 'invalid' || parsed.stash.fromUid === uid) {
await clearInheritedSecrets(inheritanceHost)
if (sessionCurrent(uid, epoch)) pendingInheritance = null
return
}
const stash = parsed.stash
const serverHas = new Set(serverItems.filter((item) => item?.exists).map((item) => item.moduleKey))
const secretNeeded = Object.keys(stash.secrets).some((moduleKey) => !serverHas.has(moduleKey))
const proxyNeeded = Boolean(stash.proxyUrl) && !serverProxyItem?.exists && !serverProxyItem?.locked
if (!secretNeeded && !proxyNeeded) {
// 服务端已经没有可补的项:快照没有存在价值,立即清掉
await clearInheritedSecrets(inheritanceHost)
if (sessionCurrent(uid, epoch)) pendingInheritance = null
return
}
if (!sessionCurrent(uid, epoch)) return
pendingInheritance = { summary: toPendingInheritance(stash), stash }
}
/** 设置页读取待确认的继承摘要(不含明文)。确认前不会写服务端。 */
export function getPendingApiSecretInheritance(): PendingApiSecretInheritance | null {
return pendingInheritance?.summary || null
}
/**
* 用户点「继承」后执行迁移:只补服务端空缺项,服务端已锁定/已存在的代理不继承。
* 成功返回本次继承摘要;网络失败或会话已变时保留 pending 供下次重试。
*/
export async function confirmApiSecretInheritance(): Promise<ApiSecretInheritanceNotice | null> {
const pending = pendingInheritance
if (!pending || !isNativeDesktopStorage()) return null
const uid = currentUid()
const epoch = cacheEpoch
const config = await withTimeout(readConfigForBackfill(), CONFIG_TIMEOUT_MS).catch((error) => {
console.warn('[api-secret] 确认继承时读取本机配置失败(保留快照待重试):', error)
return null
})
if (!config || !sessionCurrent(uid, epoch)) return null
const bundle = await fetchMyApiSecrets().catch((error) => {
console.warn('[api-secret] 确认继承时拉取服务端密钥失败(保留快照待重试):', error)
return null
})
if (!bundle || !sessionCurrent(uid, epoch)) return null
const outcome = await applyInheritedSecrets(
inheritanceHost,
pending.stash,
config,
bundle.items || [],
bundle.proxy,
)
if (!sessionCurrent(uid, epoch)) return null
if (outcome.cleared) pendingInheritance = null
if (!outcome.notice) return null
inheritanceNotice = outcome.notice
const refreshed = await fetchMyApiSecrets().catch((error) => {
console.warn('[api-secret] 继承后刷新服务端密钥失败(下次加载会重试):', error)
return null
})
if (refreshed && sessionCurrent(uid, epoch)) {
await applyServerBundle(refreshed, uid, epoch)
if (sessionCurrent(uid, epoch)) {
bundleLoaded = true
notify()
}
}
return outcome.notice
}
/** 用户点「不继承」:立即清掉本机快照,明文不再留在 app.json。 */
export async function declineApiSecretInheritance(): Promise<void> {
pendingInheritance = null
await clearInheritedSecrets(inheritanceHost)
}
/** 设置页消费一次继承提示(内存态,不落盘)。 */
@@ -739,6 +965,7 @@ export function clearApiSecretCache(): void {
inflightLoad = null
serverProxy = null
inheritanceNotice = null
pendingInheritance = null
cacheEpoch += 1
}
@@ -0,0 +1,33 @@
/**
* 给桌面桥调用加一道硬超时。
*
* 登出时要把本账号配置留给本机下一个账号,但原生桥(read_config/save_config)在
* 主进程卡死或 pywebview 未就绪时可能永不返回。没有超时,登出清理会一直等,
* 令牌与 uid 留在 localStorage 里,用户还能在原页面继续操作(CR-12)。
*
* 超时只负责让调用方继续走清理,不取消底层 promise:桥调用本身没有取消接口,
* 晚到的结果最多是写了一份已经过期的继承快照,不会回写登录态。
*/
export class PromiseTimeoutError extends Error {
constructor(timeoutMs: number) {
super(`操作超过 ${timeoutMs}ms 未完成`)
this.name = 'PromiseTimeoutError'
}
}
export function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
if (!(timeoutMs > 0)) return promise
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new PromiseTimeoutError(timeoutMs)), timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
},
)
})
}