8143a5114d
代理是选配、不进 items 也不参与门禁,但客户端各任务链读的是本地 app.json 的
proxy_url,用户自填值与后台不一致时排查成本高。改法:
- 后台 PUT/DELETE /api/admin/user-secrets/{userId}/modules/{moduleKey} 代填/解锁,
写入后该行 source=admin;数据权限走 resolveVisibleUserIds,超管不限;
- 客户端 save/clear 命中锁定行时服务端直接拒绝并给出原因(只置灰挡不住直接调接口);
- 密钥包把代理单独放 proxy 字段下发(仍不进 items、不影响 complete 判定),
锁定时带 full 明文,客户端据此幂等地对齐本地配置;解锁 = 删除该行。
只开放代理代填:密钥模块要客户端提交任务时携带本地明文,代填会把用户卡死。
213 lines
7.3 KiB
TypeScript
213 lines
7.3 KiB
TypeScript
import { test } from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { http } from '../src/shared/api/http.ts'
|
|
import {
|
|
clearApiSecretCache,
|
|
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_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, '登出清理应重置服务端代理状态')
|
|
})
|