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:
@@ -119,7 +119,7 @@ import { COMPANY_NAME_STORAGE_KEY, writeCompanyIdentity } from '@/shared/auth/co
|
||||
import { clearAccountExpiry, writeAccountExpiry } from '@/shared/auth/account-expiry'
|
||||
import { AUTH_TOKEN_KEY } from '@/shared/auth/session-keys'
|
||||
import { useVersionUpdate } from '@/shared/composables/useVersionUpdate'
|
||||
import { clearApiSecretCache } from '@/shared/utils/api-secret-store'
|
||||
import { captureApiSecretsForInheritance, clearApiSecretCache } from '@/shared/utils/api-secret-store'
|
||||
import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue'
|
||||
import UpdateLogList from '@/shared/components/UpdateLogList.vue'
|
||||
import VersionPicker from '@/shared/components/VersionPicker.vue'
|
||||
@@ -480,27 +480,33 @@ async function submitLogin() {
|
||||
onMounted(() => {
|
||||
const params = new URLSearchParams(window.location.search || '')
|
||||
if (params.get('logout') === '1' || params.get('switch') === '1') {
|
||||
// 登出/切号:uid 不彻底清除会被路由守卫当“已登录”自动带回首页(见 src/main.ts 守卫)
|
||||
try {
|
||||
window.localStorage.removeItem(AUTH_TOKEN_KEY)
|
||||
window.localStorage.removeItem('uid')
|
||||
window.localStorage.removeItem('username')
|
||||
window.localStorage.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||
clearAccountExpiry()
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
// 清空密钥缓存:内存 + 本地镜像(旧 v1 记录保留,供下次登录自动迁移)
|
||||
clearApiSecretCache()
|
||||
// 同步清掉客户端的登录用户标记:Python 端回退到全局/默认代理池
|
||||
try {
|
||||
const bridge = (window as unknown as { pywebview?: { api?: { save_config?: (data: Record<string, unknown>) => Promise<unknown> } } }).pywebview
|
||||
if (bridge?.api && typeof bridge.api.save_config === 'function') {
|
||||
void bridge.api.save_config({ current_uid: '' })
|
||||
const clearSignedOutState = () => {
|
||||
// 清缓存必须在移除 uid 之前:镜像键带 uid,反序会按 uid=0 删错位置,
|
||||
// 把本账号的明文镜像留在磁盘上给下一个账号(或网页脚本)读到。
|
||||
clearApiSecretCache()
|
||||
// 登出/切号:uid 不彻底清除会被路由守卫当“已登录”自动带回首页(见 src/main.ts 守卫)
|
||||
try {
|
||||
window.localStorage.removeItem(AUTH_TOKEN_KEY)
|
||||
window.localStorage.removeItem('uid')
|
||||
window.localStorage.removeItem('username')
|
||||
window.localStorage.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||
clearAccountExpiry()
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
// 同步清掉客户端的登录用户标记:Python 端回退到全局/默认代理池
|
||||
try {
|
||||
const bridge = (window as unknown as { pywebview?: { api?: { save_config?: (data: Record<string, unknown>) => Promise<unknown> } } }).pywebview
|
||||
if (bridge?.api && typeof bridge.api.save_config === 'function') {
|
||||
void bridge.api.save_config({ current_uid: '' })
|
||||
}
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
// 先把本账号的密钥/代理留给本机下一个账号(桌面端),再清缓存与 uid;
|
||||
// capture 失败也必须照常登出,所以成功/失败两条路都走同一个清理函数。
|
||||
void captureApiSecretsForInheritance().then(clearSignedOutState, clearSignedOutState)
|
||||
// 显式登出/切号后不再自动登录(保留记住的账号,仅关闭自动登录)
|
||||
autoLogin.value = false
|
||||
lsSet(AUTO_LOGIN_KEY, '0')
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
getStoredApiSecretSnapshot,
|
||||
listApiSecretModules,
|
||||
loadApiSecrets,
|
||||
takeApiSecretInheritanceNotice,
|
||||
type ApiSecretModuleKey,
|
||||
} from '@/shared/utils/api-secret-store'
|
||||
|
||||
@@ -56,6 +57,16 @@ onMounted(() => {
|
||||
} 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}」的密钥配置,请点击上方「检测」逐项确认后保存进入。`
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
|
||||
@@ -75,6 +75,8 @@ export interface DesktopConfigUpdate {
|
||||
proxy_mode?: ProxyMode;
|
||||
current_uid?: string;
|
||||
proxy_users?: Record<string, { proxy_url?: string; proxy_mode?: number }>;
|
||||
/** 登出时留给本机下个账号的密钥快照(结构由 shared/utils/api-secret-store 定义)。 */
|
||||
api_secret_inherit?: Record<string, unknown> | null;
|
||||
aliprice_usename?: string;
|
||||
aliprice_pwd?: string;
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
/** 供测试与调试:模块级状态快照。 */
|
||||
|
||||
@@ -138,6 +138,23 @@ test('登录页认停用/删除标记:各有判定入口、各自关自动登
|
||||
)
|
||||
})
|
||||
|
||||
test('登出先留继承快照再清缓存,且清缓存必须早于移除 uid', () => {
|
||||
const cleanupStart = loginPageSource.indexOf('const clearSignedOutState = () => {')
|
||||
const captureCall = loginPageSource.indexOf('void captureApiSecretsForInheritance()')
|
||||
assert.ok(cleanupStart > 0, '登出清理函数不见了')
|
||||
assert.ok(captureCall > cleanupStart, '登出时应先调用继承快照再执行清理')
|
||||
const cleanupBody = loginPageSource.slice(cleanupStart, captureCall)
|
||||
const clearAt = cleanupBody.indexOf('clearApiSecretCache()')
|
||||
const removeUidAt = cleanupBody.indexOf("removeItem('uid')")
|
||||
assert.ok(clearAt > 0, '登出清理没有清密钥缓存')
|
||||
assert.ok(removeUidAt > clearAt, '密钥镜像键带 uid,先移除 uid 会删错键、把本账号明文留在本机')
|
||||
assert.match(
|
||||
loginPageSource,
|
||||
/captureApiSecretsForInheritance\(\)\.then\(clearSignedOutState, clearSignedOutState\)/,
|
||||
'继承快照失败也必须照常登出',
|
||||
)
|
||||
})
|
||||
|
||||
test('停用/删除文案必须互不冒充:停用句不说删除、删除句不说停用', () => {
|
||||
const disabledLine = loginPageSource
|
||||
.split('\n')
|
||||
|
||||
@@ -2,6 +2,7 @@ import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { http } from '../src/shared/api/http.ts'
|
||||
import {
|
||||
captureApiSecretsForInheritance,
|
||||
clearApiSecretCache,
|
||||
ensureBrandCheckProxy,
|
||||
getServerProxySnapshot,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
listApiSecretModules,
|
||||
loadApiSecrets,
|
||||
saveApiSecret,
|
||||
takeApiSecretInheritanceNotice,
|
||||
} from '../src/shared/utils/api-secret-store.ts'
|
||||
|
||||
type RequestConfig = { url?: string; method?: string; data?: unknown }
|
||||
@@ -279,6 +281,181 @@ test('test_secret_store_brand_check_proxy_present_passes', async (t) => {
|
||||
assert.deepEqual(result, { ok: true, state: 'server' })
|
||||
})
|
||||
|
||||
function seedDesktopMirror(
|
||||
localStorage: ReturnType<typeof createStorage>,
|
||||
uid: string,
|
||||
moduleKey: string,
|
||||
value: string,
|
||||
) {
|
||||
localStorage.setItem(`brand:api-secret-cache:${uid}:${moduleKey}`, JSON.stringify({
|
||||
schema: 2,
|
||||
value,
|
||||
masked: '',
|
||||
exists: true,
|
||||
locked: false,
|
||||
checkStatus: 'passed',
|
||||
checkCode: '',
|
||||
checkMessage: '',
|
||||
checkLatencyMs: null,
|
||||
checkedAt: null,
|
||||
updatedAt: null,
|
||||
}))
|
||||
}
|
||||
|
||||
/** 与 app_client/main.py::save_config 一致:顶层浅合并,proxy_users 再按 uid 深合并。 */
|
||||
function mergeDesktopConfig(current: Record<string, unknown>, patch: Record<string, unknown>) {
|
||||
const next = { ...current, ...patch }
|
||||
const users = patch.proxy_users as Record<string, unknown> | undefined
|
||||
if (users) {
|
||||
next.proxy_users = {
|
||||
...(current.proxy_users as Record<string, unknown> | undefined),
|
||||
...users,
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
test('test_secret_store_inherits_previous_account_config_on_desktop', async (t) => {
|
||||
const { localStorage } = setupWindow()
|
||||
clearApiSecretCache()
|
||||
const aliceProxy = 'https://api.jikip.com/ip-get?num=1&key=alice'
|
||||
let config: Record<string, unknown> = {
|
||||
current_uid: '42',
|
||||
proxy_users: { '42': { proxy_url: aliceProxy, proxy_mode: 2 } },
|
||||
}
|
||||
attachDesktopBridge(
|
||||
() => config,
|
||||
(patch) => {
|
||||
config = mergeDesktopConfig(config, patch)
|
||||
return config
|
||||
},
|
||||
)
|
||||
localStorage.setItem('username', 'alice')
|
||||
seedDesktopMirror(localStorage, '42', 'appearance-patent', 'sk-alice-appearance')
|
||||
seedDesktopMirror(localStorage, '42', 'similar-asin', 'sk-alice-similar')
|
||||
|
||||
await captureApiSecretsForInheritance()
|
||||
const stash = config.api_secret_inherit as Record<string, unknown> | null
|
||||
assert.equal(stash?.fromUid, '42', '登出时应把当前账号配置留成本机继承快照')
|
||||
|
||||
// 真实登出顺序:先清缓存(此时 uid 仍是 42),再移除 uid;登录 B 后 uid=43
|
||||
clearApiSecretCache()
|
||||
localStorage.removeItem('uid')
|
||||
localStorage.setItem('uid', '43')
|
||||
localStorage.setItem('username', 'bob')
|
||||
|
||||
const serverKeys = new Set<string>()
|
||||
let serverHasProxy = false
|
||||
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
|
||||
mockRequest(t, (req) => {
|
||||
if ((req.url || '').includes('/migrate')) {
|
||||
const payload = req.data as { items?: Array<{ moduleKey?: string; value?: string }> }
|
||||
migratePayloads.push(payload)
|
||||
for (const item of payload.items || []) {
|
||||
if (item.moduleKey === 'proxy') serverHasProxy = true
|
||||
else if (item.moduleKey) serverKeys.add(item.moduleKey)
|
||||
}
|
||||
return okResponse({ migrated: payload.items?.length || 0 })
|
||||
}
|
||||
return okResponse({
|
||||
items: ['appearance-patent', 'similar-asin'].map((moduleKey) =>
|
||||
serverItem(moduleKey, { exists: serverKeys.has(moduleKey) })),
|
||||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||||
complete: serverKeys.size === 2,
|
||||
proxy: serverHasProxy
|
||||
? { ...serverItem('proxy'), exists: true, masked: 'https://api.jikip.com' }
|
||||
: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
await loadApiSecrets({ force: true })
|
||||
|
||||
const migrated = migratePayloads.flatMap((payload) => payload.items || [])
|
||||
assert.equal(
|
||||
migrated.find((item) => item.moduleKey === 'appearance-patent')?.value,
|
||||
'sk-alice-appearance',
|
||||
'上一个账号的外观专利密钥应继承给当前账号',
|
||||
)
|
||||
assert.equal(
|
||||
migrated.find((item) => item.moduleKey === 'similar-asin')?.value,
|
||||
'sk-alice-similar',
|
||||
'上一个账号的货源查询密钥应继承给当前账号',
|
||||
)
|
||||
assert.equal(
|
||||
migrated.find((item) => item.moduleKey === 'proxy')?.value,
|
||||
aliceProxy,
|
||||
'服务端缺代理时应继承上一个账号的代理',
|
||||
)
|
||||
assert.equal(getStoredApiSecret('appearance-patent'), 'sk-alice-appearance', '继承后当前账号本地应能直接取到明文')
|
||||
const users = config.proxy_users as Record<string, { proxy_url: string; proxy_mode: number }>
|
||||
assert.equal(users['43'].proxy_url, aliceProxy, '继承的代理应写进当前 uid 的本地配置')
|
||||
assert.equal(users['43'].proxy_mode, 2, '代理模式应一并继承')
|
||||
assert.equal(config.api_secret_inherit, null, '继承成功后快照应消费掉,避免被更后面的账号重复使用')
|
||||
|
||||
const notice = takeApiSecretInheritanceNotice()
|
||||
assert.equal(notice?.fromUid, '42')
|
||||
assert.equal(notice?.fromUsername, 'alice')
|
||||
assert.equal(notice?.proxy, true)
|
||||
assert.deepEqual(notice?.moduleKeys.slice().sort(), ['appearance-patent', 'similar-asin'])
|
||||
})
|
||||
|
||||
test('test_secret_store_inheritance_never_overwrites_existing_account_config', async (t) => {
|
||||
const { localStorage } = setupWindow()
|
||||
clearApiSecretCache()
|
||||
localStorage.setItem('uid', '43')
|
||||
const config: Record<string, unknown> = {
|
||||
current_uid: '43',
|
||||
api_secret_inherit: {
|
||||
schema: 1,
|
||||
fromUid: '42',
|
||||
fromUsername: 'alice',
|
||||
savedAt: Date.now(),
|
||||
secrets: { 'appearance-patent': 'sk-alice-appearance', 'similar-asin': 'sk-alice-similar' },
|
||||
proxyUrl: 'https://api.jikip.com/ip-get?num=1&key=alice',
|
||||
proxyMode: 2,
|
||||
},
|
||||
}
|
||||
attachDesktopBridge(() => config, (patch) => {
|
||||
Object.assign(config, patch)
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'api_secret_inherit')) {
|
||||
config.api_secret_inherit = patch.api_secret_inherit
|
||||
}
|
||||
return config
|
||||
})
|
||||
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
|
||||
mockRequest(t, (req) => {
|
||||
if ((req.url || '').includes('/migrate')) {
|
||||
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
|
||||
return okResponse({ migrated: 1 })
|
||||
}
|
||||
return okResponse({
|
||||
items: [
|
||||
serverItem('appearance-patent', { exists: true, masked: 'sk-b****5678' }),
|
||||
serverItem('similar-asin'),
|
||||
],
|
||||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||||
complete: false,
|
||||
proxy: { ...serverItem('proxy'), exists: true, masked: 'https://api.jikip.com' },
|
||||
})
|
||||
})
|
||||
|
||||
await loadApiSecrets({ force: true })
|
||||
|
||||
const migrated = migratePayloads.flatMap((payload) => payload.items || [])
|
||||
assert.deepEqual(
|
||||
migrated.map((item) => item.moduleKey),
|
||||
['similar-asin'],
|
||||
'只补当前账号空缺的模块,已有密钥和已有代理都不能被上一个账号覆盖',
|
||||
)
|
||||
assert.equal(getStoredApiSecret('appearance-patent'), '', '当前账号已有密钥时不得把上一个账号的明文塞进本地')
|
||||
assert.equal(config.api_secret_inherit, null, '没有需要补的项时也应消费快照')
|
||||
assert.equal(
|
||||
(config.proxy_users as Record<string, unknown> | undefined)?.['43'],
|
||||
undefined,
|
||||
'当前账号已有服务端代理时不得改写本地代理配置',
|
||||
)
|
||||
})
|
||||
|
||||
test('test_secret_store_locked_proxy_not_in_module_cards', async (t) => {
|
||||
setupWindow()
|
||||
clearApiSecretCache()
|
||||
|
||||
Reference in New Issue
Block a user