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:
@@ -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