457af3607f
- 用户密钥新增 channel 列(V180):LLM 行存渠道 longtaitou/t8star,代理行存供应商 qingguo/jikip;存量与新建默认均回填 t8star/jikip(默认仍走贞贞与极客,手动可切) - 外观专利/货源查询按任务归属用户的密钥渠道路由 LLM 主机(渠道经 SecretUsageContext 下到工作线程,不逐层改签名);切到龙抬头时模型映射 gemini-3.1-flash-lite 并补 enable_thinking + thinking_budget=medium(对齐贞贞现网口径),检测链路刻意不思考 - 代理检测按供应商解析:青果 code 为字符串、隧道端点支持 域名:端口、 NO_AVAILABLE_CHANNEL 归为可重试;青果只验提取成功(账密只在客户端本地) - 密钥设置页:每个模块加渠道分段选择、代理卡加供应商选择与青果 Authkey/Authpwd (只存本机,不上报),切换渠道未重填密钥时拦住保存;换号继承带渠道与供应商 - 后管密钥管理三列显示渠道/供应商标签
923 lines
35 KiB
TypeScript
923 lines
35 KiB
TypeScript
import { test } from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { http } from '../src/shared/api/http.ts'
|
||
import {
|
||
captureApiSecretsForInheritance,
|
||
checkApiSecret,
|
||
clearApiSecretCache,
|
||
confirmApiSecretInheritance,
|
||
declineApiSecretInheritance,
|
||
ensureBrandCheckProxy,
|
||
getPendingApiSecretInheritance,
|
||
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 }> }> = []
|
||
const saveCalls: Array<Record<string, unknown>> = []
|
||
let config: Record<string, unknown> = { proxy_url: globalUrl, proxy_mode: 2 }
|
||
let bundleCalls = 0
|
||
// 老版本只把代理存在全局 proxy_url,proxy_users 里没有该用户
|
||
attachDesktopBridge(
|
||
() => config,
|
||
(patch) => {
|
||
saveCalls.push(patch)
|
||
config = mergeDesktopConfig(config, patch)
|
||
return config
|
||
},
|
||
)
|
||
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, '补报后应重拉服务端代理快照')
|
||
// CR-04:升级时一次性归属迁移——全局 proxy 归给第一个读到它的 uid,并清空全局
|
||
assert.equal(config.proxy_uid, '42', '全局代理应被当前 uid 认领')
|
||
assert.equal(config.proxy_url, '', '认领后应清空无归属的全局 proxy_url')
|
||
assert.equal(
|
||
(config.proxy_users as Record<string, { proxy_url: string }>)['42'].proxy_url,
|
||
globalUrl,
|
||
'认领结果应写入 proxy_users[uid]',
|
||
)
|
||
assert.ok(saveCalls.some((patch) => patch.proxy_uid === '42'), '归属迁移必须落盘,不能只在内存里认领')
|
||
})
|
||
|
||
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,
|
||
channel = '',
|
||
) {
|
||
localStorage.setItem(`brand:api-secret-cache:${uid}:${moduleKey}`, JSON.stringify({
|
||
schema: 2,
|
||
value,
|
||
masked: '',
|
||
channel,
|
||
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
|
||
}
|
||
|
||
/** 可变的桌面 app.json:读当前值、写回按原生 save_config 口径合并,并记录每次 patch。 */
|
||
function attachConfigStore(initial: Record<string, unknown>) {
|
||
let config = initial
|
||
const saveCalls: Array<Record<string, unknown>> = []
|
||
attachDesktopBridge(
|
||
() => config,
|
||
(patch) => {
|
||
saveCalls.push(patch)
|
||
config = mergeDesktopConfig(config, patch)
|
||
return config
|
||
},
|
||
)
|
||
return {
|
||
get config() {
|
||
return config
|
||
},
|
||
saveCalls,
|
||
}
|
||
}
|
||
|
||
/** 合法的本机继承快照(schema 2 + 同作用域),测试按需覆盖字段。 */
|
||
function validInheritanceConfig(overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
current_uid: '43',
|
||
api_secret_os_scope: 'scope-1',
|
||
api_secret_inherit: {
|
||
schema: 2,
|
||
fromUid: '42',
|
||
fromUsername: 'alice',
|
||
savedAt: Date.now(),
|
||
osUserScope: 'scope-1',
|
||
secrets: { 'appearance-patent': 'sk-alice-appearance' },
|
||
proxyUrl: '',
|
||
proxyMode: 1,
|
||
...overrides,
|
||
},
|
||
}
|
||
}
|
||
|
||
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', '登出时应把当前账号配置留成本机继承快照')
|
||
assert.equal(stash?.schema, 2, '快照必须带当前 schema 与 OS 作用域')
|
||
assert.equal(stash?.osUserScope, config.api_secret_os_scope, '快照作用域必须与本机 app.json 一致')
|
||
|
||
// 真实登出顺序:先清缓存(此时 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 })
|
||
|
||
// CR-12:加载只登记待确认,不再自动继承
|
||
assert.deepEqual(migratePayloads, [], '用户未确认前不得调用 migrate')
|
||
const pending = getPendingApiSecretInheritance()
|
||
assert.equal(pending?.fromUid, '42')
|
||
assert.equal(pending?.fromUsername, 'alice')
|
||
assert.equal(pending?.proxy, true)
|
||
assert.deepEqual(pending?.moduleKeys.slice().sort(), ['appearance-patent', 'similar-asin'])
|
||
assert.equal(getStoredApiSecret('appearance-patent'), '', '确认前不得把上一个账号的明文写进本地镜像')
|
||
|
||
const notice = await confirmApiSecretInheritance()
|
||
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, '确认继承后快照应消费掉,避免被更后面的账号重复使用')
|
||
assert.equal(getPendingApiSecretInheritance(), null, '确认后不应再有待确认摘要')
|
||
|
||
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'])
|
||
assert.equal(takeApiSecretInheritanceNotice()?.fromUid, '42', '设置页应能消费到本次继承提示')
|
||
})
|
||
|
||
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_os_scope: 'scope-1',
|
||
api_secret_inherit: {
|
||
schema: 2,
|
||
fromUid: '42',
|
||
fromUsername: 'alice',
|
||
savedAt: Date.now(),
|
||
osUserScope: 'scope-1',
|
||
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 })
|
||
|
||
assert.deepEqual(migratePayloads, [], '用户未确认前不得自动继承')
|
||
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42', '应登记待确认快照')
|
||
await confirmApiSecretInheritance()
|
||
|
||
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_declines_inheritance_and_clears_stash', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const store = attachConfigStore(validInheritanceConfig())
|
||
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 bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42', '应先登记待确认快照')
|
||
await declineApiSecretInheritance()
|
||
|
||
assert.equal(store.config.api_secret_inherit, null, '用户选择不继承后快照必须立即清掉')
|
||
assert.equal(getPendingApiSecretInheritance(), null)
|
||
assert.deepEqual(migratePayloads, [], '拒绝继承不得调用 migrate')
|
||
})
|
||
|
||
test('test_secret_store_expired_inheritance_snapshot_is_cleared', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const store = attachConfigStore(validInheritanceConfig({
|
||
savedAt: Date.now() - 31 * 24 * 60 * 60 * 1000,
|
||
}))
|
||
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 bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(store.config.api_secret_inherit, null, '过期快照必须立即从 app.json 清掉(明文不许长期留存)')
|
||
assert.equal(getPendingApiSecretInheritance(), null)
|
||
assert.deepEqual(migratePayloads, [])
|
||
})
|
||
|
||
test('test_secret_store_malformed_inheritance_snapshot_is_cleared', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const store = attachConfigStore(validInheritanceConfig({ schema: 1 }))
|
||
mockRequest(t, () => bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')]))
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(store.config.api_secret_inherit, null, '结构不符(旧 schema/缺作用域)必须立即清掉')
|
||
assert.equal(getPendingApiSecretInheritance(), null)
|
||
})
|
||
|
||
test('test_secret_store_inheritance_scope_mismatch_is_cleared', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
// 别的 OS 用户 app.json 里拷来的快照:作用域标记对不上
|
||
const store = attachConfigStore(validInheritanceConfig({ osUserScope: 'scope-from-another-os-user' }))
|
||
mockRequest(t, () => bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')]))
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(store.config.api_secret_inherit, null, '跨 OS 用户作用域的快照必须清掉')
|
||
assert.equal(getPendingApiSecretInheritance(), null)
|
||
})
|
||
|
||
test('test_secret_store_locked_server_proxy_is_not_inherited', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const stashProxy = 'https://api.jikip.com/ip-get?num=1&key=alice'
|
||
const store = attachConfigStore(validInheritanceConfig({ proxyUrl: stashProxy, proxyMode: 2 }))
|
||
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)
|
||
return okResponse({ migrated: payload.items?.length || 0 })
|
||
}
|
||
return okResponse({
|
||
items: [serverItem('appearance-patent'), serverItem('similar-asin')],
|
||
requiredModules: ['appearance-patent', 'similar-asin'],
|
||
complete: false,
|
||
// 后台锁定但 exists 仍为 false:只靠 exists 判断会漏掉 locked 这一条
|
||
proxy: { ...serverItem('proxy'), exists: false, locked: true },
|
||
})
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
const notice = await confirmApiSecretInheritance()
|
||
|
||
const migrated = migratePayloads.flatMap((payload) => payload.items || [])
|
||
assert.equal(
|
||
migrated.some((item) => item.moduleKey === 'proxy'),
|
||
false,
|
||
'后台锁定的代理不得被上一个账号的快照覆盖',
|
||
)
|
||
assert.equal(notice?.proxy, false, '继承摘要要如实说明代理没有继承')
|
||
assert.equal(
|
||
(store.config.proxy_users as Record<string, unknown> | undefined)?.['43'],
|
||
undefined,
|
||
'锁定代理场景不得把快照代理写进本地配置',
|
||
)
|
||
})
|
||
|
||
test('test_secret_store_inheritance_write_aborts_when_uid_changes', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const store = attachConfigStore(validInheritanceConfig())
|
||
let releaseMigrate: ((value: unknown) => void) | null = null
|
||
let markStarted: (() => void) | null = null
|
||
const migrateStarted = new Promise<void>((resolve) => {
|
||
markStarted = resolve
|
||
})
|
||
mockRequest(t, (req) => {
|
||
if ((req.url || '').includes('/migrate')) {
|
||
markStarted?.()
|
||
return new Promise((resolve) => {
|
||
releaseMigrate = resolve
|
||
})
|
||
}
|
||
return bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
assert.equal(getPendingApiSecretInheritance()?.fromUid, '42')
|
||
const confirmPromise = confirmApiSecretInheritance()
|
||
await migrateStarted
|
||
// migrate 在飞时切号:晚到的成功响应不得把 A 的明文写进 B 的本地镜像
|
||
localStorage.setItem('uid', '44')
|
||
releaseMigrate?.({ data: { success: true, message: 'ok', data: { migrated: 1 } } })
|
||
|
||
const notice = await confirmPromise
|
||
assert.equal(notice, null, '会话已变时确认流程必须返回空')
|
||
assert.equal(getStoredApiSecret('appearance-patent'), '', '切号后不得写入上一个账号的明文')
|
||
assert.equal(
|
||
(store.config.proxy_users as Record<string, unknown> | undefined)?.['43'],
|
||
undefined,
|
||
'切号后不得写回上一个账号的代理',
|
||
)
|
||
assert.ok(store.config.api_secret_inherit, '会话已变时快照应保留给正确账号重试,而不是被误清')
|
||
})
|
||
|
||
test('test_secret_store_does_not_backfill_foreign_global_proxy', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const aliceProxy = 'https://api.jikip.com/ip-get?num=1&key=alice'
|
||
const store = attachConfigStore({
|
||
proxy_users: { '43': {} },
|
||
proxy_url: aliceProxy,
|
||
proxy_uid: '42',
|
||
})
|
||
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 bundleResponse([serverItem('appearance-patent'), serverItem('similar-asin')])
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(
|
||
migratePayloads.flatMap((payload) => payload.items || []).some((item) => item.moduleKey === 'proxy'),
|
||
false,
|
||
'全局代理归属 uid=42 时,uid=43 不得静默补报',
|
||
)
|
||
assert.equal(store.config.proxy_uid, '42', '不得把别人的全局代理改归属到当前账号')
|
||
assert.deepEqual(store.config.proxy_users, { '43': {} }, '也不得写进当前 uid 的 proxy_users')
|
||
assert.deepEqual(store.saveCalls, [], '归属不符时不应发生任何配置写回')
|
||
})
|
||
|
||
test('test_secret_store_backfills_global_proxy_owned_by_current_uid', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const ownProxy = 'https://api.jikip.com/ip-get?num=1&key=owned'
|
||
const store = attachConfigStore({ proxy_url: ownProxy, proxy_uid: '43' })
|
||
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 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, ownProxy, 'proxy_uid 等于当前 uid 时应允许回退全局代理')
|
||
assert.deepEqual(store.saveCalls, [], '已有归属时无需再做一次性迁移')
|
||
})
|
||
|
||
test('test_secret_store_backfills_shared_global_proxy_whitelist', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
localStorage.setItem('uid', '43')
|
||
clearApiSecretCache()
|
||
const sharedProxy = 'https://api.jikip.com/ip-get?num=1&key=shared'
|
||
attachConfigStore({
|
||
proxy_url: sharedProxy,
|
||
proxy_uid: '42',
|
||
proxy_shared_uids: ['43'],
|
||
})
|
||
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 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, sharedProxy, '显式共享白名单内的账号可以回退全局代理')
|
||
})
|
||
|
||
test('test_secret_store_capture_times_out_instead_of_blocking_logout', async () => {
|
||
const { localStorage } = setupWindow()
|
||
clearApiSecretCache()
|
||
localStorage.setItem('username', 'alice')
|
||
seedDesktopMirror(localStorage, '42', 'appearance-patent', 'sk-alice-appearance')
|
||
const saveCalls: Array<Record<string, unknown>> = []
|
||
// 原生桥卡死:read_config 永不返回。capture 自身必须超时,否则登录页会一直停在清理中
|
||
attachDesktopBridge(
|
||
(() => new Promise(() => {})) as unknown as () => Record<string, unknown>,
|
||
(patch) => {
|
||
saveCalls.push(patch)
|
||
return patch
|
||
},
|
||
)
|
||
const start = Date.now()
|
||
|
||
await captureApiSecretsForInheritance()
|
||
|
||
assert.ok(Date.now() - start < 5000, 'capture 超时必须及时返回,不能拖住登出清理')
|
||
const saved = saveCalls[0]?.api_secret_inherit as Record<string, unknown> | undefined
|
||
assert.equal(saved?.fromUid, '42', '读配置超时也不影响把已取到的密钥留成本机快照')
|
||
assert.equal(saved?.proxyUrl, '', '读不到配置时不写代理,避免把不确定的出口留给下一个账号')
|
||
})
|
||
|
||
|
||
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, '登出清理应重置服务端代理状态')
|
||
})
|
||
|
||
test('test_secret_store_save_sends_channel_and_keeps_it', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
let body: Record<string, unknown> | null = null
|
||
mockRequest(t, (config) => {
|
||
body = (config.data || {}) as Record<string, unknown>
|
||
return okResponse(serverItem('appearance-patent', { masked: 'sk-a****1234', exists: true, channel: 'longtaitou' }))
|
||
})
|
||
|
||
await saveApiSecret('appearance-patent', 'sk-abc123456', 'longtaitou')
|
||
|
||
assert.equal(body?.channel, 'longtaitou', '保存必须把渠道一起提交,否则服务端按默认渠道落库')
|
||
assert.equal(getStoredApiSecretSnapshot('appearance-patent').channel, 'longtaitou')
|
||
})
|
||
|
||
test('test_secret_store_check_passes_channel', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
let body: Record<string, unknown> | null = null
|
||
mockRequest(t, (config) => {
|
||
body = (config.data || {}) as Record<string, unknown>
|
||
return okResponse({
|
||
moduleKey: 'similar-asin',
|
||
checkStatus: 'passed',
|
||
checkCode: 'ok',
|
||
checkMessage: '连通正常',
|
||
checkLatencyMs: 120,
|
||
checkedAt: null,
|
||
viaProxy: false,
|
||
})
|
||
})
|
||
|
||
const result = await checkApiSecret('similar-asin', 'sk-abc123456', 't8star')
|
||
|
||
assert.equal(body?.channel, 't8star', '检测要按所选渠道发起,别拿默认渠道的结论冒充')
|
||
assert.equal(body?.value, 'sk-abc123456')
|
||
assert.equal(result.checkStatus, 'passed')
|
||
})
|
||
|
||
test('test_secret_store_snapshot_without_channel_stays_empty', async (t) => {
|
||
setupWindow()
|
||
clearApiSecretCache()
|
||
mockRequest(t, () => bundleResponse([
|
||
serverItem('appearance-patent', { exists: true, masked: 'sk-a****1234' }),
|
||
serverItem('similar-asin'),
|
||
]))
|
||
|
||
await loadApiSecrets({ force: true })
|
||
|
||
assert.equal(
|
||
getStoredApiSecretSnapshot('appearance-patent').channel,
|
||
'',
|
||
'老版本后端不下发渠道时保留空串,由界面按默认值展示',
|
||
)
|
||
})
|
||
|
||
test('test_secret_store_inheritance_keeps_channel_and_proxy_provider', async (t) => {
|
||
const { localStorage } = setupWindow()
|
||
clearApiSecretCache()
|
||
const aliceProxy = 'https://overseas.proxy.qg.net/get?key=alice&format=json'
|
||
let config: Record<string, unknown> = {
|
||
current_uid: '42',
|
||
proxy_users: { '42': { proxy_url: aliceProxy, proxy_mode: 1, proxy_provider: 'qingguo' } },
|
||
}
|
||
attachDesktopBridge(
|
||
() => config,
|
||
(patch) => {
|
||
config = mergeDesktopConfig(config, patch)
|
||
return config
|
||
},
|
||
)
|
||
localStorage.setItem('username', 'alice')
|
||
// 龙抬头的密钥:换号继承时必须把渠道一起带走,否则下一个账号会把它按「存量=贞贞」落库
|
||
seedDesktopMirror(localStorage, '42', 'appearance-patent', 'sk-alice-longtaitou', 'longtaitou')
|
||
|
||
await captureApiSecretsForInheritance()
|
||
clearApiSecretCache()
|
||
localStorage.removeItem('uid')
|
||
localStorage.setItem('uid', '43')
|
||
localStorage.setItem('username', 'bob')
|
||
|
||
let migratePayload: Record<string, unknown> | null = null
|
||
mockRequest(t, (req) => {
|
||
if ((req.url || '').includes('/migrate')) {
|
||
migratePayload = req.data as Record<string, unknown>
|
||
return okResponse({ migrated: 1 })
|
||
}
|
||
return bundleResponse([
|
||
serverItem('appearance-patent'),
|
||
serverItem('similar-asin', { exists: true, masked: 'sk-c****9999' }),
|
||
])
|
||
})
|
||
|
||
await loadApiSecrets({ force: true })
|
||
await confirmApiSecretInheritance()
|
||
|
||
const items = ((migratePayload?.items || []) as Array<Record<string, unknown>>)
|
||
const appearance = items.find((item) => item.moduleKey === 'appearance-patent')
|
||
assert.equal(appearance?.channel, 'longtaitou', '继承要带上渠道,不能按新建默认落库')
|
||
const proxy = items.find((item) => item.moduleKey === 'proxy')
|
||
assert.equal(proxy?.channel, 'qingguo', '代理继承要带上供应商')
|
||
const users = (config.proxy_users || {}) as Record<string, Record<string, unknown>>
|
||
assert.equal(users['43']?.proxy_provider, 'qingguo', '写回本机配置时供应商不能丢')
|
||
})
|