8323245567
A 号在桌面端配好密钥后登出,B 号登录时服务端与本地都缺这些配置, 任务只能整批失败。现在登出前把当前账号的明文密钥与代理存进本机 app.json,B 首次加载时只补服务端空缺的模块(fill-only,后台锁定的 代理不覆盖),并写回 B 的本地镜像与 proxy_users;检测状态不继承, 设置页提示逐项点「检测」确认。 同时修掉登出顺序反了的问题:原来先移除 uid 再清镜像,镜像键带 uid,实际删的是 uid=0 的键,A 的明文镜像会留在本机;换号/会话过期 后内存里的 A 明文也会被 B 继续读到。现在先留快照、再清缓存、最后 移除 uid,并在 uid 变化时作废旧会话缓存、给在飞的加载加 epoch 栅栏。
478 lines
17 KiB
TypeScript
478 lines
17 KiB
TypeScript
import { test } from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { http } from '../src/shared/api/http.ts'
|
||
import {
|
||
captureApiSecretsForInheritance,
|
||
clearApiSecretCache,
|
||
ensureBrandCheckProxy,
|
||
getServerProxySnapshot,
|
||
getStoredApiSecret,
|
||
getStoredApiSecretSnapshot,
|
||
listApiSecretModules,
|
||
loadApiSecrets,
|
||
saveApiSecret,
|
||
takeApiSecretInheritanceNotice,
|
||
} from '../src/shared/utils/api-secret-store.ts'
|
||
|
||
type RequestConfig = { url?: string; method?: string; data?: unknown }
|
||
type MockTest = Parameters<typeof test>[1] extends (t: infer T) => unknown ? T : never
|
||
|
||
function createStorage() {
|
||
const store = new Map<string, string>()
|
||
return {
|
||
getItem: (key: string) => (store.has(key) ? (store.get(key) as string) : null),
|
||
setItem: (key: string, value: string) => {
|
||
store.set(key, String(value))
|
||
},
|
||
removeItem: (key: string) => {
|
||
store.delete(key)
|
||
},
|
||
}
|
||
}
|
||
|
||
function setupWindow() {
|
||
const localStorage = createStorage()
|
||
const sessionStorage = createStorage()
|
||
// 密钥按登录用户隔离:uid 必须存在(与真实前端 localStorage.uid 一致)
|
||
localStorage.setItem('uid', '42')
|
||
;(globalThis as Record<string, unknown>).window = {
|
||
localStorage,
|
||
sessionStorage,
|
||
location: { origin: 'http://localhost' },
|
||
}
|
||
return { localStorage, sessionStorage }
|
||
}
|
||
|
||
function mockRequest(t: MockTest, impl: (config: RequestConfig) => Promise<unknown>) {
|
||
t.mock.method(http, 'request', impl as never)
|
||
}
|
||
|
||
const okResponse = (data: unknown) => Promise.resolve({ data: { success: true, message: 'ok', data } })
|
||
|
||
function serverItem(moduleKey: string, overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
moduleKey,
|
||
moduleLabel: moduleKey === 'appearance-patent' ? '外观专利密钥' : '货源查询密钥',
|
||
masked: '',
|
||
exists: false,
|
||
checkStatus: 'unknown',
|
||
checkCode: '',
|
||
checkMessage: '',
|
||
checkLatencyMs: null,
|
||
checkedAt: null,
|
||
updatedAt: null,
|
||
...overrides,
|
||
}
|
||
}
|
||
|
||
function bundleResponse(items: unknown[]) {
|
||
return okResponse({
|
||
items,
|
||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||
complete: false,
|
||
})
|
||
}
|
||
|
||
const LEGACY_MIRROR_KEY = 'brand:api-secret:42:appearance-patent'
|
||
|
||
/** 桌面桥(pywebview)模拟:后台锁定代理回填本地配置依赖 read_config/save_config。 */
|
||
function attachDesktopBridge(
|
||
readConfig: () => Record<string, unknown>,
|
||
saveConfig: (patch: Record<string, unknown>) => Record<string, unknown>,
|
||
) {
|
||
const win = (globalThis as Record<string, unknown>).window as Record<string, unknown>
|
||
win.pywebview = {
|
||
api: { read_config: readConfig, save_config: saveConfig },
|
||
}
|
||
}
|
||
|
||
function lockedProxyBundle(proxy: Record<string, unknown>) {
|
||
return {
|
||
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
|
||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||
complete: false,
|
||
proxy: { ...serverItem('proxy'), ...proxy },
|
||
}
|
||
}
|
||
|
||
test('test_secret_store_reads_legacy_value_before_load', () => {
|
||
const { localStorage } = setupWindow()
|
||
clearApiSecretCache()
|
||
localStorage.setItem(LEGACY_MIRROR_KEY, JSON.stringify({ value: 'legacy-key-1', retention: 'forever' }))
|
||
|
||
assert.equal(getStoredApiSecret('appearance-patent'), 'legacy-key-1')
|
||
})
|
||
|
||
test('test_secret_store_load_failure_returns_unknown_and_keeps_cache', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
clearApiSecretCache()
|
||
localStorage.setItem(LEGACY_MIRROR_KEY, JSON.stringify({ value: 'legacy-key-2' }))
|
||
mockRequest(t, () => Promise.reject(new Error('服务不可用')))
|
||
|
||
const state = await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(state, 'unknown')
|
||
assert.equal(getStoredApiSecret('appearance-patent'), 'legacy-key-2')
|
||
})
|
||
|
||
test('test_secret_store_migrates_legacy_value_once_and_clears_local', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
clearApiSecretCache()
|
||
localStorage.setItem(LEGACY_MIRROR_KEY, JSON.stringify({ value: 'legacy-key-3' }))
|
||
const calls: string[] = []
|
||
mockRequest(t, (config) => {
|
||
calls.push(config.url || '')
|
||
if ((config.url || '').includes('/migrate')) {
|
||
return okResponse({ migrated: 1 })
|
||
}
|
||
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||
})
|
||
|
||
const state = await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(state, 'incomplete')
|
||
assert.ok(calls.some((url) => url.includes('/api/user-secrets/migrate')), '应调用迁移接口')
|
||
assert.equal(localStorage.getItem(LEGACY_MIRROR_KEY), null, '迁移后应清理旧记录')
|
||
})
|
||
|
||
test('test_secret_store_save_keeps_plain_value_locally', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
mockRequest(t, () =>
|
||
okResponse(serverItem('appearance-patent', { masked: 'sk-a****1234', exists: true })),
|
||
)
|
||
|
||
await saveApiSecret('appearance-patent', 'sk-abc123456')
|
||
|
||
assert.equal(getStoredApiSecret('appearance-patent'), 'sk-abc123456')
|
||
const snapshot = getStoredApiSecretSnapshot('appearance-patent')
|
||
assert.equal(snapshot.masked, 'sk-a****1234')
|
||
assert.equal(snapshot.exists, true)
|
||
})
|
||
|
||
test('test_secret_store_save_rejects_empty_value', async () => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
await assert.rejects(() => saveApiSecret('similar-asin', ' '), /密钥不能为空/)
|
||
})
|
||
|
||
test('test_secret_store_locked_proxy_aligns_local_config_once', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
const fullUrl = 'https://api.jikip.com/ip-get?num=1&key=abc'
|
||
let config: Record<string, unknown> = { proxy_users: { '42': { proxy_url: '', proxy_mode: 2 } } }
|
||
const saveCalls: Array<Record<string, unknown>> = []
|
||
attachDesktopBridge(
|
||
() => config,
|
||
(patch) => {
|
||
saveCalls.push(patch)
|
||
const patchUsers = patch.proxy_users as Record<string, unknown> | undefined
|
||
config = {
|
||
...config,
|
||
...patch,
|
||
proxy_users: { ...(config.proxy_users as Record<string, unknown>), ...(patchUsers || {}) },
|
||
}
|
||
return config
|
||
},
|
||
)
|
||
mockRequest(t, (req) => {
|
||
if ((req.url || '').includes('/migrate')) return okResponse({ migrated: 0 })
|
||
return okResponse(lockedProxyBundle({ exists: true, locked: true, full: fullUrl, masked: 'https://api.jikip.com' }))
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(saveCalls.length, 1, '首次加载应把后台锁定代理写入本地配置')
|
||
const users = saveCalls[0].proxy_users as Record<string, { proxy_url: string; proxy_mode: number }>
|
||
assert.equal(users['42'].proxy_url, fullUrl)
|
||
assert.equal(users['42'].proxy_mode, 2, '写入时应保留用户原有的代理模式')
|
||
const snapshot = getServerProxySnapshot()
|
||
assert.equal(snapshot?.locked, true)
|
||
assert.equal(snapshot?.full, fullUrl)
|
||
|
||
await loadApiSecrets({ force: true })
|
||
assert.equal(saveCalls.length, 1, '本地配置已一致时不应重复写入')
|
||
})
|
||
|
||
test('test_secret_store_backfills_legacy_global_proxy_to_server', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=legacy'
|
||
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
|
||
let bundleCalls = 0
|
||
// 老版本只把代理存在全局 proxy_url,proxy_users 里没有该用户
|
||
attachDesktopBridge(() => ({ proxy_url: globalUrl, proxy_mode: 2 }), (patch) => patch)
|
||
mockRequest(t, (req) => {
|
||
if ((req.url || '').includes('/migrate')) {
|
||
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
|
||
return okResponse({ migrated: 1 })
|
||
}
|
||
bundleCalls += 1
|
||
return okResponse({
|
||
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
|
||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||
complete: false,
|
||
// 补报前无代理;补报后服务端有了代理
|
||
proxy: bundleCalls > 1
|
||
? { ...serverItem('proxy'), exists: true, masked: 'https://api.jikip.com' }
|
||
: undefined,
|
||
})
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
const proxyMigrate = migratePayloads
|
||
.flatMap((payload) => payload.items || [])
|
||
.find((item) => item.moduleKey === 'proxy')
|
||
assert.equal(proxyMigrate?.value, globalUrl, '旧版全局代理应补报到服务端')
|
||
assert.equal(getServerProxySnapshot()?.exists, true, '补报后应重拉服务端代理快照')
|
||
})
|
||
|
||
test('test_secret_store_user_proxy_wins_over_legacy_global', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
const userUrl = 'https://api.jikip.com/ip-get?num=1&key=user'
|
||
const globalUrl = 'https://api.jikip.com/ip-get?num=2&key=global'
|
||
const migratePayloads: Array<{ items?: Array<{ moduleKey?: string; value?: string }> }> = []
|
||
attachDesktopBridge(
|
||
() => ({ proxy_users: { '42': { proxy_url: userUrl, proxy_mode: 1 } }, proxy_url: globalUrl, proxy_mode: 2 }),
|
||
(patch) => patch,
|
||
)
|
||
mockRequest(t, (req) => {
|
||
if ((req.url || '').includes('/migrate')) {
|
||
migratePayloads.push(req.data as { items?: Array<{ moduleKey?: string; value?: string }> })
|
||
return okResponse({ migrated: 1 })
|
||
}
|
||
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
const proxyMigrate = migratePayloads
|
||
.flatMap((payload) => payload.items || [])
|
||
.find((item) => item.moduleKey === 'proxy')
|
||
assert.equal(proxyMigrate?.value, userUrl, '用户自己的代理优先于旧版全局代理')
|
||
})
|
||
|
||
test('test_secret_store_brand_check_proxy_missing_is_visible', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
mockRequest(t, () => bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')]))
|
||
|
||
const result = await ensureBrandCheckProxy()
|
||
|
||
assert.deepEqual(result, { ok: false, state: 'missing' })
|
||
})
|
||
|
||
test('test_secret_store_brand_check_proxy_present_passes', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
mockRequest(t, () =>
|
||
okResponse({
|
||
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
|
||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||
complete: false,
|
||
proxy: { ...serverItem('proxy'), exists: true, masked: 'https://api.jikip.com' },
|
||
}),
|
||
)
|
||
|
||
const result = await ensureBrandCheckProxy()
|
||
|
||
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()
|
||
mockRequest(t, () =>
|
||
okResponse(lockedProxyBundle({ exists: true, locked: true, full: 'https://api.jikip.com/ip-get?num=1&key=abc' })),
|
||
)
|
||
|
||
const state = await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(state, 'incomplete')
|
||
assert.equal(getServerProxySnapshot()?.locked, true)
|
||
assert.deepEqual(
|
||
listApiSecretModules().map((item) => item.moduleKey),
|
||
['appearance-patent', 'similar-asin'],
|
||
'代理不进模块卡片(不占门禁)',
|
||
)
|
||
clearApiSecretCache()
|
||
assert.equal(getServerProxySnapshot(), null, '登出清理应重置服务端代理状态')
|
||
})
|