e265c188f7
- 本地代理回填兼容旧版全局 proxy_url,补报成功后重拉服务端快照 - 创建任务前检查服务端代理,缺失时弹窗拦截并引导配置 - 商标查询失败的真实原因写入结果原因列,不再只显示查询失败
301 lines
11 KiB
TypeScript
301 lines
11 KiB
TypeScript
import { test } from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { http } from '../src/shared/api/http.ts'
|
||
import {
|
||
clearApiSecretCache,
|
||
ensureBrandCheckProxy,
|
||
getServerProxySnapshot,
|
||
getStoredApiSecret,
|
||
getStoredApiSecretSnapshot,
|
||
listApiSecretModules,
|
||
loadApiSecrets,
|
||
saveApiSecret,
|
||
} 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' })
|
||
})
|
||
|
||
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, '登出清理应重置服务端代理状态')
|
||
})
|