/** * 用户密钥前端存取:服务端为准 + 本地缓存。 * * - 服务端(/api/user-secrets)是唯一权威:按登录用户绑定,客户端只缓存元数据与最近输入的值; * - `getStoredApiSecret` / `getStoredApiSecretSnapshot` 保持同步读语义(提交任务瞬间立即取用), * 读取顺序:内存 → 本地镜像 → 旧版 v1 记录(`brand:api-secret:{uid}:{moduleKey}`); * - 本地镜像(localStorage)在浏览器形态只存脱敏值与状态位,明文只活在本页内存; * 桌面形态(有 window.pywebview.api 原生存储)维持原有整条镜像,不动既有流程; * - 保存/清空/检测走异步接口;服务端拉取失败一律软失败(返回 unknown,不阻断使用); * - 旧版本地密钥在首次加载时自动迁移到服务端(只填空缺、不覆盖)。 */ import { checkMyApiSecret, deleteMyApiSecret, fetchMyApiSecrets, fetchProxyBalance, migrateMyApiSecrets, putMyApiSecret, type ApiSecretCheckStatus, type ApiSecretModuleKey, type UserApiSecretCheckResult, type UserApiSecretItem, } from '../api/types/modules/user-secret.ts' export type { ApiSecretModuleKey, ApiSecretCheckStatus } export type { UserApiSecretCheckResult } /** 门禁状态:complete=可放行 / incomplete=需拦截引导配置 / unknown=未知(软失败,放行)。 */ export type ApiSecretLoadState = 'complete' | 'incomplete' | 'unknown' export interface ApiSecretSnapshot { /** * 本地明文(来自用户输入或旧记录迁移),只存内存 Map; * 浏览器形态的磁盘镜像不含此字段,服务端不回传明文,换机/刷新后可能为空。 */ value: string /** 服务端脱敏值(权威展示,如 sk-a****1234)。 */ masked: string exists: boolean /** 是否由后台代填并锁定:锁定时客户端不可修改或清空(当前仅代理模块)。 */ locked: boolean checkStatus: ApiSecretCheckStatus checkCode: string checkMessage: string checkLatencyMs: number | null checkedAt: number | null updatedAt: number | null } /** 代理状态:由服务端单独下发(不在 items 内、不参与门禁);锁定时带完整地址。 */ export interface ServerProxySnapshot extends ApiSecretSnapshot { /** 后台锁定的完整代理地址(未锁定时为空串)。 */ full: string } /** 商标检测前置代理检查结果:unknown 表示服务端读不到,按软失败放行(与密钥门禁同口径)。 */ export interface BrandCheckProxyStatus { ok: boolean state: 'server' | 'missing' | 'unknown' } interface ApiSecretCacheEntry extends ApiSecretSnapshot { schema: 2 } const MIRROR_PREFIX = 'brand:api-secret-cache' const LEGACY_PREFIX = 'brand:api-secret' const LEGACY_MODULE_KEYS = ['appearance-patent', 'appearance-patent-token', 'similar-asin'] const MIGRATED_FLAG_PREFIX = 'brand:api-secret-migrated' const DEFAULT_REQUIRED_MODULES: ApiSecretModuleKey[] = ['appearance-patent', 'similar-asin'] const FETCH_TIMEOUT_MS = 4000 const memory = new Map() const listeners = new Set<() => void>() export interface ApiSecretModuleInfo { moduleKey: string moduleLabel: string } const DEFAULT_MODULE_INFOS: ApiSecretModuleInfo[] = [ { moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' }, { moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' }, ] let moduleInfos: ApiSecretModuleInfo[] = [...DEFAULT_MODULE_INFOS] let requiredModules: string[] = [...DEFAULT_REQUIRED_MODULES] let bundleLoaded = false let inflightLoad: Promise | null = null /** 服务端代理状态(后台锁定/检测展示用);未成功加载过为 null。 */ let serverProxy: ServerProxySnapshot | null = null function currentUid(): string { if (typeof window === 'undefined') return '0' return window.localStorage.getItem('uid') || '0' } function buildMirrorKey(moduleKey: string) { return `${MIRROR_PREFIX}:${currentUid()}:${moduleKey}` } function buildLegacyKey(moduleKey: string) { return `${LEGACY_PREFIX}:${currentUid()}:${moduleKey}` } /** * 形态判定:桌面客户端(pywebview)会注入 window.pywebview.api 并提供原生 app.json 存储, * 其本地明文缓存是既有任务链路依赖(重启后仍能取用);纯浏览器形态没有原生存储, * localStorage 是同页脚本可直接读到的明文落点,必须收紧。 * * 这里刻意用内联的 window 断言而不是 import hasPywebview():静态引入 bridges/pywebview * 会把 web-fallback → http 拉进 node 测试环境(本模块被单测直接 import)。 */ function isNativeDesktopStorage(): boolean { if (typeof window === 'undefined') return false return Boolean((window as unknown as { pywebview?: { api?: unknown } }).pywebview?.api) } function emptyEntry(): ApiSecretCacheEntry { return { schema: 2, value: '', masked: '', exists: false, locked: false, checkStatus: 'unknown', checkCode: '', checkMessage: '', checkLatencyMs: null, checkedAt: null, updatedAt: null, } } function normalizeCheckStatus(value: unknown): ApiSecretCheckStatus { switch (value) { case 'passed': case 'failed': case 'error': case 'unknown': return value default: return 'unknown' } } function readMirror(moduleKey: string): ApiSecretCacheEntry | null { if (typeof window === 'undefined') return null try { const raw = window.localStorage.getItem(buildMirrorKey(moduleKey)) if (!raw) return null const parsed = JSON.parse(raw) as Partial if (parsed.schema !== 2) return null const entry: ApiSecretCacheEntry = { schema: 2, value: typeof parsed.value === 'string' ? parsed.value : '', masked: typeof parsed.masked === 'string' ? parsed.masked : '', exists: Boolean(parsed.exists), locked: Boolean(parsed.locked), checkStatus: normalizeCheckStatus(parsed.checkStatus), checkCode: typeof parsed.checkCode === 'string' ? parsed.checkCode : '', checkMessage: typeof parsed.checkMessage === 'string' ? parsed.checkMessage : '', checkLatencyMs: typeof parsed.checkLatencyMs === 'number' ? parsed.checkLatencyMs : null, checkedAt: typeof parsed.checkedAt === 'number' ? parsed.checkedAt : null, updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : null, } // 浏览器形态:历史版本可能已把明文写进磁盘,读到就顺手抹掉(明文只留内存) if (entry.value && !isNativeDesktopStorage()) { entry.value = '' writeMirror(moduleKey, entry) } return entry } catch { return null } } /** 磁盘镜像写入:浏览器形态只写脱敏值与状态位,明文不落地;桌面形态维持既有整条镜像。 */ function writeMirror(moduleKey: string, entry: ApiSecretCacheEntry) { if (typeof window === 'undefined') return const persisted: ApiSecretCacheEntry = isNativeDesktopStorage() ? entry : { ...entry, value: '' } try { window.localStorage.setItem(buildMirrorKey(moduleKey), JSON.stringify(persisted)) } catch { /* 本地镜像写入失败不影响主流程 */ } } function removeMirror(moduleKey: string) { if (typeof window === 'undefined') return try { window.localStorage.removeItem(buildMirrorKey(moduleKey)) } catch { /* 忽略 */ } } /** 读取旧版 v1 明文(sessionStorage 优先,兼容历史 session 保留策略)。 */ function readLegacyPlainValue(moduleKey: string): string { if (typeof window === 'undefined') return '' for (const storage of [window.sessionStorage, window.localStorage]) { try { const raw = storage.getItem(buildLegacyKey(moduleKey)) if (!raw) continue const parsed = JSON.parse(raw) as { value?: unknown } if (typeof parsed?.value === 'string' && parsed.value.trim()) { return parsed.value.trim() } } catch { /* 忽略损坏的历史记录 */ } } return '' } function clearLegacyKeys() { if (typeof window === 'undefined') return for (const moduleKey of [...LEGACY_MODULE_KEYS, 'common']) { for (const storage of [window.sessionStorage, window.localStorage]) { try { storage.removeItem(buildLegacyKey(moduleKey)) } catch { /* 忽略 */ } } } } function migratedFlagKey() { return `${MIGRATED_FLAG_PREFIX}:${currentUid()}:v1` } function readEntry(moduleKey: string): ApiSecretCacheEntry { const cached = memory.get(moduleKey) if (cached) return cached const fromMirror = readMirror(moduleKey) if (fromMirror) { memory.set(moduleKey, fromMirror) return fromMirror } const legacyValue = readLegacyPlainValue(moduleKey) if (legacyValue) { const entry = emptyEntry() entry.value = legacyValue memory.set(moduleKey, entry) return entry } return emptyEntry() } function updateEntry(moduleKey: string, patch: Partial) { const next: ApiSecretCacheEntry = { ...readEntry(moduleKey), ...patch, schema: 2 } memory.set(moduleKey, next) writeMirror(moduleKey, next) notify() } function notify() { for (const listener of listeners) { try { listener() } catch { /* 单个监听器异常不影响其他订阅者 */ } } } function toMillis(value: string | null): number | null { if (!value) return null const parsed = Date.parse(value) return Number.isNaN(parsed) ? null : parsed } function applyServerItem(moduleKey: string, item: UserApiSecretItem) { const current = readEntry(moduleKey) const next: ApiSecretCacheEntry = { schema: 2, // 明文仅来自本地输入/迁移,服务端不下发 value: current.value, masked: item.masked || '', exists: Boolean(item.exists), locked: Boolean(item.locked), checkStatus: normalizeCheckStatus(item.checkStatus), checkCode: item.checkCode || '', checkMessage: item.checkMessage || '', checkLatencyMs: typeof item.checkLatencyMs === 'number' ? item.checkLatencyMs : null, checkedAt: toMillis(item.checkedAt), updatedAt: toMillis(item.updatedAt), } memory.set(moduleKey, next) writeMirror(moduleKey, next) if (item.moduleLabel && !moduleInfos.some((info) => info.moduleKey === moduleKey)) { moduleInfos = [...moduleInfos, { moduleKey, moduleLabel: item.moduleLabel }] } } /** 界面展示用的模块清单(默认两个,服务端返回新模块时自动追加)。 */ export function listApiSecretModules(): ApiSecretModuleInfo[] { return [...moduleInfos] } /** 完整性:全部必填模块均检测通过;error(无法判定)视为放行,防上游抖动锁死客户端。 */ export function computeApiSecretsComplete(): boolean { for (const moduleKey of requiredModules) { const entry = memory.get(moduleKey) || readEntry(moduleKey) if (!entry.exists) return false if (entry.checkStatus !== 'passed' && entry.checkStatus !== 'error') return false } return requiredModules.length > 0 } /** 门禁状态:从未成功拉到服务端数据 → unknown(软失败放行)。 */ export function getApiSecretGateState(): ApiSecretLoadState { if (!bundleLoaded) return 'unknown' return computeApiSecretsComplete() ? 'complete' : 'incomplete' } /** 同步读明文(提交任务瞬间调用);未加载时降级读本地镜像/旧记录。 */ export function getStoredApiSecret(moduleKey: ApiSecretModuleKey): string { return readEntry(moduleKey).value } /** 同步读完整快照(含服务端脱敏值/检测状态)。 */ export function getStoredApiSecretSnapshot(moduleKey: ApiSecretModuleKey): ApiSecretSnapshot { const entry = readEntry(moduleKey) const { schema: _schema, ...snapshot } = entry return snapshot } /** 同步读服务端代理状态(含后台锁定标记与锁定时的完整地址)。 */ export function getServerProxySnapshot(): ServerProxySnapshot | null { return serverProxy } /** * 创建商标检测任务前的代理检查:服务端没有代理时先尝试把本地代理补报上去, * 仍没有就返回 missing 交给页面弹窗拦截。服务端读不到(unknown)不拦—— * 那种情况下任务创建本身会报错,不能把网络抖动误判成"未配置代理"。 */ export async function ensureBrandCheckProxy(): Promise { const state = await loadApiSecrets({ force: true }) if (getServerProxySnapshot()?.exists) { return { ok: true, state: 'server' } } if (state === 'unknown') { return { ok: true, state: 'unknown' } } return { ok: false, state: 'missing' } } export function subscribeApiSecrets(listener: () => void): () => void { listeners.add(listener) return () => { listeners.delete(listener) } } /** 加载服务端密钥包;force=true 绕过 in-flight 复用但串行等待(登录后重拉用)。 */ export function loadApiSecrets(options: { force?: boolean } = {}): Promise { if (inflightLoad && !options.force) { return inflightLoad } const previous = inflightLoad const task = (async (): Promise => { if (previous && options.force) { // 等上一轮结束,避免并发覆盖 await previous.catch(() => undefined) } return doLoad() })().finally(() => { if (inflightLoad === task) { inflightLoad = null } }) inflightLoad = task return task } /** 复用同一次 in-flight 加载(路由守卫调用)。 */ export function ensureApiSecretsLoaded(): Promise { if (bundleLoaded || inflightLoad) { return inflightLoad || Promise.resolve(getApiSecretGateState()) } return loadApiSecrets() } async function doLoad(): Promise { try { const bundle = await fetchMyApiSecrets() if (Array.isArray(bundle?.requiredModules) && bundle.requiredModules.length) { requiredModules = bundle.requiredModules } for (const item of bundle?.items || []) { if (item?.moduleKey) { applyServerItem(item.moduleKey, item) } } serverProxy = toServerProxy(bundle?.proxy) if (serverProxy?.locked && serverProxy.full) { // 后台锁定代理:把后台值对齐到本地配置(客户端任务链读本地),先比对、幂等、失败静默 await syncLockedProxyToLocal(serverProxy.full) } bundleLoaded = true notify() const migrated = await tryMigrateLocalSecrets(bundle?.items || []) if (migrated > 0) { const refreshed = await fetchMyApiSecrets() for (const item of refreshed?.items || []) { if (item?.moduleKey) { applyServerItem(item.moduleKey, item) } } notify() } const backfilled = await tryBackfillProxyToServer() if (backfilled) { // 补报已写入服务端:重拉一次让 serverProxy 反映新状态, // 否则任务提交前的代理检查会拿到上一轮的空快照。 const refreshed = await fetchMyApiSecrets() serverProxy = toServerProxy(refreshed?.proxy) notify() } return computeApiSecretsComplete() ? 'complete' : 'incomplete' } catch (error) { console.warn('[api-secret] 服务端密钥拉取失败,本次按未知处理(不阻断使用):', error) return 'unknown' } } /** 旧本地密钥一次性迁移:仅当服务端空缺且有本地明文时上报;失败静默,下次加载重试。 */ async function tryMigrateLocalSecrets(serverItems: UserApiSecretItem[]): Promise { if (typeof window === 'undefined') return 0 try { if (window.localStorage.getItem(migratedFlagKey()) === '1') { clearLegacyKeys() return 0 } const serverHas = new Map(serverItems.map((item) => [item.moduleKey, Boolean(item.exists)])) const pending: Array<{ moduleKey: string; value: string }> = [] for (const moduleKey of DEFAULT_REQUIRED_MODULES) { if (serverHas.get(moduleKey)) continue const legacyValue = readLegacyPlainValue(moduleKey) if (legacyValue) { pending.push({ moduleKey, value: legacyValue }) } } if (!pending.length) { window.localStorage.setItem(migratedFlagKey(), '1') clearLegacyKeys() return 0 } const result = await migrateMyApiSecrets(pending) const migrated = Number(result?.migrated || 0) // 迁移成功后本地保留明文(供提交任务直接使用),只清理旧记录与标记 for (const item of pending) { const entry = readEntry(item.moduleKey) updateEntry(item.moduleKey, { value: entry.value || item.value }) } window.localStorage.setItem(migratedFlagKey(), '1') clearLegacyKeys() console.log(`[api-secret] 本地密钥迁移完成,写入 ${migrated} 条`) return migrated } catch (error) { console.warn('[api-secret] 本地密钥迁移失败,将在下次加载时重试:', error) return 0 } } /** * 本地代理配置补报服务端(只写空缺、不覆盖;后台密钥管理观测/检测用)。 * 未登录、无本地代理时静默跳过;失败静默,下次加载重试。 * * @returns 是否真的补报了一条(migrated > 0);调用方据此决定要不要重拉服务端快照。 */ async function tryBackfillProxyToServer(): Promise { try { if (currentUid() === '0') return false const config = await readConfigForBackfill() if (!config) return false const url = readLocalProxyUrl(config) if (!url) return false const result = await migrateMyApiSecrets([{ moduleKey: 'proxy', value: url }]) return Number(result?.migrated || 0) > 0 } catch (error) { console.warn('[api-secret] 代理配置补报失败(下次加载重试):', error) return false } } /** * 读代理补报所需的本地配置:桌面真实桥优先(与 syncLockedProxyToLocal 同口径), * 纯浏览器再走降级桥。静态 import 会把 web-fallback 的 @ 别名依赖拖进 node 用例, * 所以降级那条只在需要时才动态加载。 */ async function readConfigForBackfill(): Promise | null> { if (typeof window === 'undefined') return null const direct = window.pywebview?.api if (direct?.read_config) { return (await direct.read_config()) as Record | null } // 无 DOM 的 node 用例不是浏览器环境:降级桥模块带着 @ 别名依赖,加载只会留下噪声报错 if (typeof document === 'undefined') return null const { getPywebviewApi } = await import('../bridges/pywebview.ts') const api = getPywebviewApi() if (!api?.read_config) return null return (await api.read_config()) as Record | null } /** * 读取当前登录用户的本地代理地址:proxy_users[uid] 优先,用户项为空时回退全局 proxy_url。 * 回退口径与客户端任务链 `resolve_current_proxy` 一致——老版本把代理存在全局 proxy_url, * 若这里只认 proxy_users[uid],这些账号的代理永远补报不到服务端,外观专利任务会在 * 商标维度整批判失败(2026-10-25 账号 1210 的 32300/32309 就是这么来的)。 */ function readLocalProxyUrl(config: Record | null | undefined): string { if (!config) return '' const uid = currentUid() if (uid !== '0') { const users = (config.proxy_users ?? {}) as Record const own = (users[uid] ?? {}) as Record const ownUrl = typeof own.proxy_url === 'string' ? own.proxy_url.trim() : '' if (ownUrl) return ownUrl } return typeof config.proxy_url === 'string' ? config.proxy_url.trim() : '' } function toServerProxy(proxy: UserApiSecretItem | null | undefined): ServerProxySnapshot | null { if (!proxy) return null return { value: '', masked: proxy.masked || '', exists: Boolean(proxy.exists), locked: Boolean(proxy.locked), full: typeof proxy.full === 'string' ? proxy.full.trim() : '', checkStatus: normalizeCheckStatus(proxy.checkStatus), checkCode: proxy.checkCode || '', checkMessage: proxy.checkMessage || '', checkLatencyMs: typeof proxy.checkLatencyMs === 'number' ? proxy.checkLatencyMs : null, checkedAt: toMillis(proxy.checkedAt), updatedAt: toMillis(proxy.updatedAt), } } /** * 后台代填并锁定的代理:把完整地址写入本地 app.json(proxy_users[uid],未登录回退全局), * 让客户端各任务链与后台值保持一致。先读后比对、幂等;失败静默,下次加载重试。 * 只走桌面端真实桥(window.pywebview):Web 降级桥的配置与桌面 app.json 无关。 */ async function syncLockedProxyToLocal(full: string): Promise { try { if (typeof window === 'undefined') return const api = window.pywebview?.api if (!api?.read_config || !api?.save_config) return const config = (await api.read_config()) as Record | null if (readLocalProxyUrl(config) === full) return const uid = currentUid() if (uid === '0') { const mode = Number(config?.proxy_mode) === 2 ? 2 : 1 await api.save_config({ proxy_url: full, proxy_mode: mode }) return } const users = (config?.proxy_users ?? {}) as Record const own = (users[uid] ?? {}) as Record // save_config 对 proxy_users 只做 uid 级合并(保留其他用户),故同一对象内要带齐原有模式 const mode = Number(own.proxy_mode) === 2 ? 2 : 1 await api.save_config({ proxy_users: { [uid]: { proxy_url: full, proxy_mode: mode } } }) } catch (error) { console.warn('[api-secret] 锁定代理写入本地配置失败(下次加载重试):', error) } } /** 保存密钥到服务端;成功后刷新本地缓存(失败不写本地,避免本地有值服务端没有的假象)。 */ export async function saveApiSecret(moduleKey: ApiSecretModuleKey, value: string): Promise { const trimmed = value.trim() if (!trimmed) { throw new Error('密钥不能为空') } const item = await putMyApiSecret(moduleKey, trimmed) applyServerItem(moduleKey, item) updateEntry(moduleKey, { value: trimmed, exists: true }) bundleLoaded = true return getStoredApiSecretSnapshot(moduleKey) } export async function clearApiSecret(moduleKey: ApiSecretModuleKey): Promise { await deleteMyApiSecret(moduleKey) removeMirror(moduleKey) memory.delete(moduleKey) notify() } /** 检测连通性:value 非空时只检测输入值(不落库);为空时检测服务端已存值并刷新本地状态。 */ export async function checkApiSecret( moduleKey: ApiSecretModuleKey, value?: string, ): Promise { const override = value?.trim() const result = await checkMyApiSecret(moduleKey, override || undefined) if (!override) { updateEntry(moduleKey, { checkStatus: normalizeCheckStatus(result.checkStatus), checkCode: result.checkCode || '', checkMessage: result.checkMessage || '', checkLatencyMs: typeof result.checkLatencyMs === 'number' ? result.checkLatencyMs : null, checkedAt: toMillis(result.checkedAt) ?? Date.now(), }) } return result } /** 服务端余量查询(jikip 套餐 IP 余量 / 账户余额)。 */ export async function fetchProxyBalanceSafely() { return fetchProxyBalance() } /** 登出清理:内存与镜像一并清空(旧 v1 记录保留,供下次登录迁移)。 */ export function clearApiSecretCache(): void { for (const moduleKey of [...DEFAULT_REQUIRED_MODULES]) { removeMirror(moduleKey) } memory.clear() bundleLoaded = false inflightLoad = null serverProxy = null } /** 供测试与调试:模块级状态快照。 */ export function __debugApiSecretState() { return { requiredModules: [...requiredModules], bundleLoaded, entries: Object.fromEntries(memory.entries()), } }