From 1c0cc350be55c36f2c6c80cf3492658cffa55d05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com> Date: Fri, 30 Oct 2026 12:07:39 +0800 Subject: [PATCH] =?UTF-8?q?refactor(user-secret):=20=E5=AF=86=E9=92=A5?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E9=9D=A2=E6=9D=BF=201114=E2=86=92775=20?= =?UTF-8?q?=E8=A1=8C=EF=BC=8C=E5=8E=8B=E5=9B=9E=E5=8F=AF=E8=AF=BB=E6=80=A7?= =?UTF-8?q?=E6=A3=98=E8=BD=AE=E7=BA=BF=E5=86=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可读性棘轮不允许登记新增超长文件(新增只能拆)。按职责抽出四个模块: - useProxyWhitelist:白名单 IP/代加动作与可用态; - useProxyPlan:极客套餐读取/保存/清除与余量查询(含余额查询的既有降级); - api-secret-module-view:模块卡片的描述/占位/状态文案派生; - api-secret-proxy-config:proxy_users[uid] 的读取与写入补丁。 行为与文案一字未改;静默 catch 随 loadBalance 搬家,逐文件台账同步迁移 (面板 1→0、useProxyPlan=1,总数与 blocks 不变)。 --- .../components/ApiSecretSettingsPanel.vue | 448 +++--------------- .../src/shared/composables/useProxyPlan.ts | 163 +++++++ .../shared/composables/useProxyWhitelist.ts | 161 +++++++ .../shared/utils/api-secret-module-view.ts | 124 +++++ .../shared/utils/api-secret-proxy-config.ts | 68 +++ .../tests/catch-silence-ratchet.test.ts | 7 +- 6 files changed, 577 insertions(+), 394 deletions(-) create mode 100644 frontend-vue/src/shared/composables/useProxyPlan.ts create mode 100644 frontend-vue/src/shared/composables/useProxyWhitelist.ts create mode 100644 frontend-vue/src/shared/utils/api-secret-module-view.ts create mode 100644 frontend-vue/src/shared/utils/api-secret-proxy-config.ts diff --git a/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue b/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue index 239be4438..a47fb36a6 100644 --- a/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue +++ b/frontend-vue/src/shared/components/ApiSecretSettingsPanel.vue @@ -302,14 +302,12 @@ import { ElMessage } from 'element-plus' import { checkApiSecret, clearApiSecret, - fetchProxyBalanceSafely, getServerProxySnapshot, getStoredApiSecretSnapshot, listApiSecretModules, loadApiSecrets, saveApiSecret, subscribeApiSecrets, - type ApiSecretCheckStatus, type ApiSecretModuleKey, type ApiSecretSnapshot, type ServerProxySnapshot, @@ -320,7 +318,6 @@ import { DEFAULT_PROXY_PROVIDER, LLM_CHANNEL_OPTIONS, PROXY_PROVIDER_OPTIONS, - detectProxyProviderFromUrl, llmChannelLabel, normalizeLlmChannel, normalizeProxyProvider, @@ -330,16 +327,13 @@ import { } from '@/shared/utils/api-secret-channel' import { getPywebviewApi, type ProxyMode, type DesktopConfigUpdate } from '@/shared/bridges/pywebview' import { - addProxyWhitelist, deleteMyApiSecret, putMyApiSecret, - fetchProxyPlan, - saveProxyPlan, - clearProxyPlan, - type UserProxyWhitelistResult, } from '@/shared/api/types/modules/user-secret' -import { fetchPublicIp } from '@/shared/utils/public-ip' -import { PROXY_PLAN_CHANGED_EVENT } from '@/shared/utils/proxy-balance-alert' +import { proxyUserId, readUserProxy, userProxyPatch } from '@/shared/utils/api-secret-proxy-config' +import { useProxyWhitelist } from '@/shared/composables/useProxyWhitelist' +import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan' +import { createModuleView, type ModuleState } from '@/shared/utils/api-secret-module-view' const props = withDefaults( defineProps<{ @@ -351,15 +345,6 @@ const props = withDefaults( }, ) -type ModuleState = { - input: string - checking: boolean - result: UserApiSecretCheckResult | null - error: string - /** 最近一次检测的来源:saved=密钥配置里已保存的密钥,input=输入框里的未保存值。 */ - lastCheckSource: 'saved' | 'input' | '' -} - const modules = ref(listApiSecretModules()) const moduleStates = reactive>({}) /** 每个模块当前选择的渠道:默认龙抬头,加载后以服务端已存值为准。 */ @@ -395,20 +380,53 @@ const proxyChecking = ref(false) const proxyCheckResult = ref(null) const proxyCheckError = ref('') -const proxyPlanId = ref('') -const proxyPlanUserId = ref('') -const proxyPlanKey = ref('') -const proxyPlanKeyConfigured = ref(false) -const proxyPlanKeyMasked = ref(null) -const proxyPlanConfigured = ref(false) -const proxyPlanLoading = ref(false) -const proxyPlanSaving = ref(false) +/** 套餐保存/清除后要清的白名单提示:套餐与白名单互相引用,用可变槽位解初始化顺序。 */ +const resetWhitelistSink: { fn: () => void } = { fn: () => {} } -const whitelistIp = ref('') -const whitelistFetching = ref(false) -const whitelistAdding = ref(false) -const whitelistResult = ref(null) -const whitelistError = ref('') +const { balance, balanceLoading, balanceText, loadBalance } = useProxyBalance({ proxyProvider }) +const { + proxyPlanId, + proxyPlanUserId, + proxyPlanKey, + proxyPlanKeyConfigured, + proxyPlanKeyMasked, + proxyPlanConfigured, + proxyPlanLoading, + proxyPlanSaving, + proxyPlanKeyPlaceholder, + loadProxyPlan, + saveProxyPlanInfo, + clearProxyPlanInfo, +} = useProxyPlan({ proxyProvider, resetWhitelistStatus: () => resetWhitelistSink.fn(), loadBalance }) + +const whitelist = useProxyWhitelist({ + proxyReady, + proxyProvider, + proxyMode, + proxyDirty, + proxyUrl, + proxyLocked, + proxyPlanConfigured, + proxyPlanKeyConfigured, + syncProxyToServer, +}) +const { + whitelistIp, + whitelistFetching, + whitelistAdding, + whitelistResult, + whitelistError, + whitelistVisible, + whitelistProviderLabel, + whitelistReady, + whitelistHint, + whitelistStatusText, + whitelistResultClass, + fetchCurrentIp, + resetWhitelistStatus, + addToWhitelist, +} = whitelist +resetWhitelistSink.fn = resetWhitelistStatus const proxyPlaceholder = computed(() => proxyProvider.value === 'qingguo' @@ -436,52 +454,6 @@ const proxyResultClass = computed(() => { } }) -/** 白名单区:青果的 API 鉴权白名单始终相关;极客只有白名单授权(本地代理模式 1)才需要。 */ -const whitelistVisible = computed(() => - proxyReady.value - && (proxyProvider.value === 'qingguo' || (proxyProvider.value === 'jikip' && proxyMode.value === 1)), -) - -const whitelistProviderLabel = computed(() => (proxyProvider.value === 'qingguo' ? '青果' : '极客')) - -const whitelistReady = computed(() => { - if (!whitelistVisible.value || !whitelistIp.value.trim() || proxyDirty.value) return false - if (!proxyUrl.value.trim()) return false - if (proxyProvider.value === 'jikip') { - return proxyPlanConfigured.value && proxyPlanKeyConfigured.value - } - return true -}) - -const whitelistHint = computed(() => { - if (proxyDirty.value) { - return '代理设置有未保存的修改:先保存代理设置,再加入白名单(服务端按已保存的配置代加)。' - } - if (!proxyUrl.value.trim()) { - return '先在上方填写并保存代理提取链接,再加入白名单(服务端按已保存的配置代加)。' - } - if (proxyProvider.value === 'qingguo') { - return '青果用已保存的代理提取链接里的 Key 代加白名单,立即生效;刚改过提取链接时先保存代理设置。' - } - if (!proxyPlanKeyConfigured.value) { - return '先在下方「极客套餐信息」填写套餐 ID 和套餐 key(极客「套餐列表」里查看),再点加入白名单。' - } - return '极客白名单 1-2 分钟内生效;换网络或公网 IP 变化后需要重新加入。' -}) - -const proxyPlanKeyPlaceholder = computed(() => ( - proxyPlanKeyConfigured.value - ? `套餐 key 已保存(${proxyPlanKeyMasked.value || '****'}),输入新值可覆盖` - : '套餐 key(白名单添加用,极客套餐列表里查看)' -)) - -const whitelistStatusText = computed(() => whitelistError.value || whitelistResult.value?.message || '') - -const whitelistResultClass = computed(() => ({ - 'check-result--ok': Boolean(whitelistResult.value) && !whitelistError.value, - 'check-result--fail': Boolean(whitelistError.value), -})) - /** 切换代理供应商:只改本地选择,保存时与地址一起写入(检测也会按新供应商解析响应)。 */ function selectProxyProvider(provider: ProxyProviderKey) { if (proxyProvider.value === provider) return @@ -493,67 +465,6 @@ function selectProxyProvider(provider: ProxyProviderKey) { whitelistError.value = '' } -/** 自动填当前出口 IP;失败只提示可手填,不写任何猜测值。 */ -function fetchCurrentIp() { - if (whitelistFetching.value) return - whitelistFetching.value = true - whitelistError.value = '' - whitelistResult.value = null - fetchPublicIp() - .then((ip) => { - whitelistIp.value = ip - }) - .catch((error) => { - whitelistError.value = error instanceof Error ? error.message : '获取当前 IP 失败,请手动填写' - }) - .finally(() => { - whitelistFetching.value = false - }) -} - -function resetWhitelistStatus() { - whitelistResult.value = null - whitelistError.value = '' -} - -/** 加入白名单:服务端按已存代理配置选供应商;极客用套餐 ID+key,青果用链接里的 key。 */ -function addToWhitelist() { - if (whitelistAdding.value) return - const ip = whitelistIp.value.trim() - if (!ip) { - ElMessage.warning('请先获取或填写当前出口 IP') - return - } - if (proxyProvider.value === 'jikip' && !proxyPlanKeyConfigured.value) { - ElMessage.warning('请先在极客套餐信息里填写套餐 key') - return - } - whitelistAdding.value = true - whitelistError.value = '' - whitelistResult.value = null - // 老版本只把代理存在本机:代加前先把当前链接+供应商同步到服务端,否则服务端没有 Key 可代加 - const ensureServerConfig = proxyUrl.value.trim() && !proxyLocked.value - ? syncProxyToServer(proxyUrl.value.trim()) - : Promise.resolve(false) - ensureServerConfig - .then((synced) => { - // 上报失败时不能拿服务端旧链接里的 Key 代加;toast 已由 syncProxyToServer 给出 - if (proxyUrl.value.trim() && !proxyLocked.value && !synced) return null - return addProxyWhitelist(ip) - }) - .then((result) => { - if (!result) return - whitelistResult.value = result - ElMessage.success(result.message || '已加入白名单') - }) - .catch((error) => { - whitelistError.value = error instanceof Error ? error.message : '加入白名单失败' - ElMessage.error(whitelistError.value) - }) - .finally(() => { - whitelistAdding.value = false - }) -} /** 检测代理连通性:地址有改动时检测输入值(不落库),否则检测/落库已存值并刷新状态展示。 */ async function runProxyCheck() { @@ -584,26 +495,11 @@ async function runProxyCheck() { } } -const balance = ref<{ surplus: string | null; balance: string | null } | null>(null) -const balanceLoading = ref(false) - const proxyModeOptions: Array<{ value: ProxyMode; label: string }> = [ { value: 1, label: '白名单' }, { value: 2, label: '账号密码' }, ] -const MODULE_DESCRIPTIONS: Record = { - 'appearance-patent': '仅用于外观专利检测,保存在服务端并绑定当前账号。', - 'similar-asin': '仅用于货源查询,保存在服务端并绑定当前账号。', -} - -const balanceText = computed(() => { - if (!balance.value) return '' - const surplus = balance.value.surplus ?? '-' - const amount = balance.value.balance ?? '-' - return `套餐IP余量:${surplus} · 账户余额:${amount}` -}) - function ensureModuleState(moduleKey: string) { if (!moduleStates[moduleKey]) { moduleStates[moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' } @@ -645,89 +541,11 @@ function snapshotOf(moduleKey: string): ApiSecretSnapshot { return snapshots.value[moduleKey] || getStoredApiSecretSnapshot(moduleKey as ApiSecretModuleKey) } -function descriptionOf(moduleKey: string) { - return MODULE_DESCRIPTIONS[moduleKey] || '保存在服务端并绑定当前账号。' -} - -function placeholderOf(moduleKey: string) { - const snapshot = snapshotOf(moduleKey) - if (snapshot.exists) { - return `已保存(${snapshot.masked || '****'}),输入新值可覆盖` - } - return moduleChannels[moduleKey] === 'longtaitou' - ? '请输入龙抬头接口密钥(sk-...)' - : '请输入贞贞接口密钥(sk-...)' -} - -const CHECK_STATUS_TEXT: Record = { - passed: '检测通过', - failed: '检测失败', - error: '暂时无法判定', - unknown: '已保存,未检测', -} - -function statusPillTextOf(moduleKey: string) { - const state = ensureModuleState(moduleKey) - if (state.checking) return '检测中' - const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus - if (status === 'passed') return '可用' - if (status === 'failed') return '不可用' - if (status === 'error') return '待确认' - return snapshotOf(moduleKey).exists ? '未检测' : '未配置' -} - -function statusPillClassOf(moduleKey: string) { - const state = ensureModuleState(moduleKey) - const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus - return { - 'status-pill--ok': status === 'passed', - 'status-pill--fail': status === 'failed', - 'status-pill--warn': status === 'error', - } -} - -function formatTime(millis: number | null) { - if (!millis) return '' - const date = new Date(millis) - const hour = String(date.getHours()).padStart(2, '0') - const minute = String(date.getMinutes()).padStart(2, '0') - return `${hour}:${minute}` -} - -function statusTextOf(moduleKey: string) { - const state = ensureModuleState(moduleKey) - if (state.checking) return state.input.trim() ? '正在检测输入值...' : '正在检测配置密钥...' - if (state.result) { - const latency = state.result.checkLatencyMs != null ? `(${state.result.checkLatencyMs}ms)` : '' - const suffix = state.result.viaProxy === true ? ' · 经代理' : '' - const snapshot = snapshotOf(moduleKey) - // 明确展示本次检测的对象:输入值(未保存)或该用户密钥配置里保存的密钥(脱敏) - const prefix = state.lastCheckSource === 'input' - ? '输入值(未保存):' - : `配置密钥${snapshot.masked ? ` ${snapshot.masked}` : ''}:` - if (state.result.checkStatus === 'passed') return `${prefix}检测通过${latency}${suffix}` - if (state.result.checkCode === 'insufficient_balance') return `${prefix}欠费:${state.result.checkMessage || '代理服务商余额不足'}${suffix}` - return `${prefix}${state.result.checkMessage || '检测失败'}${suffix}` - } - if (state.error) return state.error - const snapshot = snapshotOf(moduleKey) - if (!snapshot.exists) return '当前未保存,请填写后保存' - const status = CHECK_STATUS_TEXT[snapshot.checkStatus] || '已保存' - const time = formatTime(snapshot.checkedAt) - const message = snapshot.checkStatus === 'unknown' ? '' : `:${snapshot.checkMessage || ''}` - const masked = snapshot.masked ? `配置密钥 ${snapshot.masked} · ` : '' - return `${masked}${status}${message}${time ? ` · ${time}` : ''}` -} - -function resultClassOf(moduleKey: string) { - const state = ensureModuleState(moduleKey) - const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus - return { - 'check-result--ok': status === 'passed', - 'check-result--fail': status === 'failed', - 'check-result--warn': status === 'error', - } -} +const { descriptionOf, placeholderOf, statusPillTextOf, statusPillClassOf, statusTextOf, resultClassOf } = createModuleView({ + moduleChannels, + ensureModuleState, + snapshotOf, +}) async function runCheck(moduleKey: ApiSecretModuleKey) { const state = ensureModuleState(moduleKey) @@ -777,60 +595,6 @@ async function clearModule(moduleKey: ApiSecretModuleKey) { } } -function proxyUserId() { - if (typeof window === 'undefined') return '0' - return window.localStorage.getItem('uid') || '0' -} - -/** 代理地址按登录用户隔离:proxy_users[uid],各自计费各自复用; - * 用户项为空(含老版本只存了全局 proxy_url 的账号)回退全局,口径与客户端任务链 - * `resolve_current_proxy` 一致——否则这些账号的代理既显示不出来,也补报不到服务端。 */ -function readUserProxy(config: Record | null | undefined) { - const uid = proxyUserId() - 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 { - url: ownUrl, - mode: Number(own.proxy_mode) === 2 ? 2 : 1, - provider: normalizeProxyProvider(own.proxy_provider ?? detectProxyProviderFromUrl(ownUrl)), - account: typeof own.proxy_account === 'string' ? own.proxy_account : '', - password: typeof own.proxy_password === 'string' ? own.proxy_password : '', - } - } - } - const url = typeof config?.proxy_url === 'string' ? config.proxy_url : '' - return { - url, - mode: Number(config?.proxy_mode) === 2 ? 2 : 1, - provider: normalizeProxyProvider(config?.proxy_provider ?? detectProxyProviderFromUrl(url)), - account: typeof config?.proxy_account === 'string' ? config.proxy_account : '', - password: typeof config?.proxy_password === 'string' ? config.proxy_password : '', - } -} - -function userProxyPatch( - nextProxyUrl: string, - nextProxyMode: ProxyMode, - provider: ProxyProviderKey, - account: string, - password: string, -) { - // 极客不需要这对账密:切过去时一并清空,避免残留串到别的供应商 - const credentials = provider === 'qingguo' - ? { proxy_account: account.trim(), proxy_password: password } - : { proxy_account: '', proxy_password: '' } - const uid = proxyUserId() - if (uid === '0') { - return { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode, proxy_provider: provider, ...credentials } - } - const users: Record = {} - users[uid] = { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode, proxy_provider: provider, ...credentials } - return { proxy_users: users } -} - async function loadProxyConfig() { proxyLoading.value = true proxyLoadFailed.value = false @@ -884,108 +648,6 @@ async function syncProxyToServer(url: string): Promise { } } -async function loadProxyPlan() { - if (proxyProvider.value !== 'jikip') { - proxyPlanConfigured.value = false - return - } - proxyPlanLoading.value = true - try { - const result = await fetchProxyPlan().catch((error) => { - console.warn('[api-secret] 代理套餐配置读取失败:', error) - return null - }) - if (!result) return - proxyPlanId.value = result.planId || '' - proxyPlanUserId.value = result.jikipUserId || '' - proxyPlanKeyConfigured.value = Boolean(result.jikipPlanKeyConfigured) - proxyPlanKeyMasked.value = result.jikipPlanKeyMasked || null - proxyPlanConfigured.value = Boolean(result.configured) - } finally { - proxyPlanLoading.value = false - } -} - -async function saveProxyPlanInfo() { - const planId = proxyPlanId.value.trim() - const jikipUserId = proxyPlanUserId.value.trim() - if (!planId || !jikipUserId) { - ElMessage.warning('请同时填写套餐 ID 和用户 ID') - return - } - proxyPlanSaving.value = true - const hadKey = proxyPlanKeyConfigured.value - try { - const result = await saveProxyPlan(planId, jikipUserId, proxyPlanKey.value).catch((error) => { - ElMessage.error(error instanceof Error ? error.message : '套餐信息保存失败') - return null - }) - if (!result) return - proxyPlanConfigured.value = Boolean(result.configured) - proxyPlanKeyConfigured.value = Boolean(result.jikipPlanKeyConfigured) - proxyPlanKeyMasked.value = result.jikipPlanKeyMasked || null - proxyPlanKey.value = '' - whitelistResult.value = null - whitelistError.value = '' - if (hadKey && !result.jikipPlanKeyConfigured) { - ElMessage.warning('套餐 ID 已变更,旧套餐 key 已清空,请重新填写') - } else { - ElMessage.success('套餐信息已保存,余量将按你的套餐查询') - } - window.dispatchEvent(new Event(PROXY_PLAN_CHANGED_EVENT)) - await loadBalance() - } finally { - proxyPlanSaving.value = false - } -} - -async function clearProxyPlanInfo() { - if (proxyPlanSaving.value) return - proxyPlanSaving.value = true - try { - const cleared = await clearProxyPlan().then(() => true).catch((error) => { - ElMessage.error(error instanceof Error ? error.message : '套餐信息清除失败') - return false - }) - if (!cleared) return - proxyPlanId.value = '' - proxyPlanUserId.value = '' - proxyPlanKey.value = '' - proxyPlanKeyConfigured.value = false - proxyPlanKeyMasked.value = null - proxyPlanConfigured.value = false - whitelistResult.value = null - whitelistError.value = '' - ElMessage.success('已清除套餐信息,余量恢复为平台默认套餐') - window.dispatchEvent(new Event(PROXY_PLAN_CHANGED_EVENT)) - await loadBalance() - } finally { - proxyPlanSaving.value = false - } -} - -async function loadBalance() { - // 余量接口目前只有极客口径(jikip find-balance);青果不在客户端查询 - if (proxyProvider.value !== 'jikip') { - balance.value = null - return - } - balanceLoading.value = true - try { - const result = await fetchProxyBalanceSafely() - if (result?.available) { - balance.value = { surplus: result.surplus, balance: result.balance } - } else { - balance.value = null - } - } catch (error) { - console.warn('[api-secret] 代理余量查询失败:', error) - balance.value = null - } finally { - balanceLoading.value = false - } -} - /** * 保存:逐模块保存非空输入(空输入保留服务端原值),代理仅在改动时保存。 * 检测一律由用户手动点击触发;保存时服务端会沿用「刚检测过的同一个输入值」的结果, diff --git a/frontend-vue/src/shared/composables/useProxyPlan.ts b/frontend-vue/src/shared/composables/useProxyPlan.ts new file mode 100644 index 000000000..f1ec99f1c --- /dev/null +++ b/frontend-vue/src/shared/composables/useProxyPlan.ts @@ -0,0 +1,163 @@ +import { computed, ref, type Ref } from 'vue' +import { ElMessage } from 'element-plus' +import { + clearProxyPlan, + fetchProxyPlan, + saveProxyPlan, +} from '@/shared/api/types/modules/user-secret' +import { fetchProxyBalanceSafely } from '@/shared/utils/api-secret-store' +import { PROXY_PLAN_CHANGED_EVENT } from '@/shared/utils/proxy-balance-alert' +import type { ProxyProviderKey } from '@/shared/utils/api-secret-channel' + +export interface ProxyPlanDeps { + proxyProvider: Ref + resetWhitelistStatus: () => void + loadBalance: () => Promise +} + +/** 极客套餐信息:读取/保存/清除,白名单与余量都按这份套餐口径。 */ +export function useProxyPlan({ proxyProvider, resetWhitelistStatus, loadBalance }: ProxyPlanDeps) { + const proxyPlanId = ref('') + const proxyPlanUserId = ref('') + const proxyPlanKey = ref('') + const proxyPlanKeyConfigured = ref(false) + const proxyPlanKeyMasked = ref(null) + const proxyPlanConfigured = ref(false) + const proxyPlanLoading = ref(false) + const proxyPlanSaving = ref(false) + + const proxyPlanKeyPlaceholder = computed(() => ( + proxyPlanKeyConfigured.value + ? `套餐 key 已保存(${proxyPlanKeyMasked.value || '****'}),输入新值可覆盖` + : '套餐 key(白名单添加用,极客套餐列表里查看)' + )) + + async function loadProxyPlan() { + if (proxyProvider.value !== 'jikip') { + proxyPlanConfigured.value = false + return + } + proxyPlanLoading.value = true + try { + const result = await fetchProxyPlan().catch((error) => { + console.warn('[api-secret] 代理套餐配置读取失败:', error) + return null + }) + if (!result) return + proxyPlanId.value = result.planId || '' + proxyPlanUserId.value = result.jikipUserId || '' + proxyPlanKeyConfigured.value = Boolean(result.jikipPlanKeyConfigured) + proxyPlanKeyMasked.value = result.jikipPlanKeyMasked || null + proxyPlanConfigured.value = Boolean(result.configured) + } finally { + proxyPlanLoading.value = false + } + } + + async function saveProxyPlanInfo() { + const planId = proxyPlanId.value.trim() + const jikipUserId = proxyPlanUserId.value.trim() + if (!planId || !jikipUserId) { + ElMessage.warning('请同时填写套餐 ID 和用户 ID') + return + } + proxyPlanSaving.value = true + const hadKey = proxyPlanKeyConfigured.value + try { + const result = await saveProxyPlan(planId, jikipUserId, proxyPlanKey.value).catch((error) => { + ElMessage.error(error instanceof Error ? error.message : '套餐信息保存失败') + return null + }) + if (!result) return + proxyPlanConfigured.value = Boolean(result.configured) + proxyPlanKeyConfigured.value = Boolean(result.jikipPlanKeyConfigured) + proxyPlanKeyMasked.value = result.jikipPlanKeyMasked || null + proxyPlanKey.value = '' + resetWhitelistStatus() + if (hadKey && !result.jikipPlanKeyConfigured) { + ElMessage.warning('套餐 ID 已变更,旧套餐 key 已清空,请重新填写') + } else { + ElMessage.success('套餐信息已保存,余量将按你的套餐查询') + } + window.dispatchEvent(new Event(PROXY_PLAN_CHANGED_EVENT)) + await loadBalance() + } finally { + proxyPlanSaving.value = false + } + } + + async function clearProxyPlanInfo() { + if (proxyPlanSaving.value) return + proxyPlanSaving.value = true + try { + const cleared = await clearProxyPlan().then(() => true).catch((error) => { + ElMessage.error(error instanceof Error ? error.message : '套餐信息清除失败') + return false + }) + if (!cleared) return + proxyPlanId.value = '' + proxyPlanUserId.value = '' + proxyPlanKey.value = '' + proxyPlanKeyConfigured.value = false + proxyPlanKeyMasked.value = null + proxyPlanConfigured.value = false + resetWhitelistStatus() + ElMessage.success('已清除套餐信息,余量恢复为平台默认套餐') + window.dispatchEvent(new Event(PROXY_PLAN_CHANGED_EVENT)) + await loadBalance() + } finally { + proxyPlanSaving.value = false + } + } + + return { + proxyPlanId, + proxyPlanUserId, + proxyPlanKey, + proxyPlanKeyConfigured, + proxyPlanKeyMasked, + proxyPlanConfigured, + proxyPlanLoading, + proxyPlanSaving, + proxyPlanKeyPlaceholder, + loadProxyPlan, + saveProxyPlanInfo, + clearProxyPlanInfo, + } +} + +/** 极客套餐余量:只有极客口径的查询接口,青果不查询。 */ +export function useProxyBalance({ proxyProvider }: { proxyProvider: Ref }) { + const balance = ref<{ surplus: string | null; balance: string | null } | null>(null) + const balanceLoading = ref(false) + + const balanceText = computed(() => { + if (!balance.value) return '' + const surplus = balance.value.surplus ?? '-' + const amount = balance.value.balance ?? '-' + return `套餐IP余量:${surplus} · 账户余额:${amount}` + }) + + async function loadBalance() { + if (proxyProvider.value !== 'jikip') { + balance.value = null + return + } + balanceLoading.value = true + try { + const result = await fetchProxyBalanceSafely() + if (result?.available) { + balance.value = { surplus: result.surplus, balance: result.balance } + } else { + balance.value = null + } + } catch (error) { + console.warn('[api-secret] 代理余量查询失败:', error) + balance.value = null + } finally { + balanceLoading.value = false + } + } + + return { balance, balanceLoading, balanceText, loadBalance } +} diff --git a/frontend-vue/src/shared/composables/useProxyWhitelist.ts b/frontend-vue/src/shared/composables/useProxyWhitelist.ts new file mode 100644 index 000000000..108ac0a70 --- /dev/null +++ b/frontend-vue/src/shared/composables/useProxyWhitelist.ts @@ -0,0 +1,161 @@ +import { computed, ref, type ComputedRef, type Ref } from 'vue' +import { ElMessage } from 'element-plus' +import { + addProxyWhitelist, + type UserProxyWhitelistResult, +} from '@/shared/api/types/modules/user-secret' +import { fetchPublicIp } from '@/shared/utils/public-ip' +import type { ProxyMode } from '@/shared/bridges/pywebview' +import type { ProxyProviderKey } from '@/shared/utils/api-secret-channel' + +export interface ProxyWhitelistDeps { + proxyReady: Ref + proxyProvider: Ref + proxyMode: Ref + proxyDirty: Ref + proxyUrl: Ref + proxyLocked: ComputedRef + proxyPlanConfigured: Ref + proxyPlanKeyConfigured: Ref + syncProxyToServer: (url: string) => Promise +} + +/** 代理供应商白名单:当前出口 IP、代加动作与可用态判定。 */ +export function useProxyWhitelist(deps: ProxyWhitelistDeps) { + const { + proxyReady, + proxyProvider, + proxyMode, + proxyDirty, + proxyUrl, + proxyLocked, + proxyPlanConfigured, + proxyPlanKeyConfigured, + syncProxyToServer, + } = deps + + const whitelistIp = ref('') + const whitelistFetching = ref(false) + const whitelistAdding = ref(false) + const whitelistResult = ref(null) + const whitelistError = ref('') + + /** 白名单区:青果的 API 鉴权白名单始终相关;极客只有白名单授权(本地代理模式 1)才需要。 */ + const whitelistVisible = computed(() => + proxyReady.value + && (proxyProvider.value === 'qingguo' || (proxyProvider.value === 'jikip' && proxyMode.value === 1)), + ) + + const whitelistProviderLabel = computed(() => (proxyProvider.value === 'qingguo' ? '青果' : '极客')) + + const whitelistReady = computed(() => { + if (!whitelistVisible.value || !whitelistIp.value.trim() || proxyDirty.value) return false + if (!proxyUrl.value.trim()) return false + if (proxyProvider.value === 'jikip') { + return proxyPlanConfigured.value && proxyPlanKeyConfigured.value + } + return true + }) + + const whitelistHint = computed(() => { + if (proxyDirty.value) { + return '代理设置有未保存的修改:先保存代理设置,再加入白名单(服务端按已保存的配置代加)。' + } + if (!proxyUrl.value.trim()) { + return '先在上方填写并保存代理提取链接,再加入白名单(服务端按已保存的配置代加)。' + } + if (proxyProvider.value === 'qingguo') { + return '青果用已保存的代理提取链接里的 Key 代加白名单,立即生效;刚改过提取链接时先保存代理设置。' + } + if (!proxyPlanKeyConfigured.value) { + return '先在下方「极客套餐信息」填写套餐 ID 和套餐 key(极客「套餐列表」里查看),再点加入白名单。' + } + return '极客白名单 1-2 分钟内生效;换网络或公网 IP 变化后需要重新加入。' + }) + + const whitelistStatusText = computed(() => whitelistError.value || whitelistResult.value?.message || '') + + const whitelistResultClass = computed(() => ({ + 'check-result--ok': Boolean(whitelistResult.value) && !whitelistError.value, + 'check-result--fail': Boolean(whitelistError.value), + })) + + /** 自动填当前出口 IP;失败只提示可手填,不写任何猜测值。 */ + function fetchCurrentIp() { + if (whitelistFetching.value) return + whitelistFetching.value = true + whitelistError.value = '' + whitelistResult.value = null + fetchPublicIp() + .then((ip) => { + whitelistIp.value = ip + }) + .catch((error) => { + whitelistError.value = error instanceof Error ? error.message : '获取当前 IP 失败,请手动填写' + }) + .finally(() => { + whitelistFetching.value = false + }) + } + + function resetWhitelistStatus() { + whitelistResult.value = null + whitelistError.value = '' + } + + /** 加入白名单:服务端按已存代理配置选供应商;极客用套餐 ID+key,青果用链接里的 key。 */ + function addToWhitelist() { + if (whitelistAdding.value) return + const ip = whitelistIp.value.trim() + if (!ip) { + ElMessage.warning('请先获取或填写当前出口 IP') + return + } + if (proxyProvider.value === 'jikip' && !proxyPlanKeyConfigured.value) { + ElMessage.warning('请先在极客套餐信息里填写套餐 key') + return + } + whitelistAdding.value = true + whitelistError.value = '' + whitelistResult.value = null + // 老版本只把代理存在本机:代加前先把当前链接+供应商同步到服务端,否则服务端没有 Key 可代加 + const ensureServerConfig = proxyUrl.value.trim() && !proxyLocked.value + ? syncProxyToServer(proxyUrl.value.trim()) + : Promise.resolve(false) + ensureServerConfig + .then((synced) => { + // 上报失败时不能拿服务端旧链接里的 Key 代加;toast 已由 syncProxyToServer 给出 + if (proxyUrl.value.trim() && !proxyLocked.value && !synced) return null + return addProxyWhitelist(ip) + }) + .then((result) => { + if (!result) return + whitelistResult.value = result + ElMessage.success(result.message || '已加入白名单') + }) + .catch((error) => { + whitelistError.value = error instanceof Error ? error.message : '加入白名单失败' + ElMessage.error(whitelistError.value) + }) + .finally(() => { + whitelistAdding.value = false + }) + } + + return { + whitelistIp, + whitelistFetching, + whitelistAdding, + whitelistResult, + whitelistError, + whitelistVisible, + whitelistProviderLabel, + whitelistReady, + whitelistHint, + whitelistStatusText, + whitelistResultClass, + fetchCurrentIp, + resetWhitelistStatus, + addToWhitelist, + } +} diff --git a/frontend-vue/src/shared/utils/api-secret-module-view.ts b/frontend-vue/src/shared/utils/api-secret-module-view.ts new file mode 100644 index 000000000..3b8c4cb13 --- /dev/null +++ b/frontend-vue/src/shared/utils/api-secret-module-view.ts @@ -0,0 +1,124 @@ +import type { + ApiSecretCheckStatus, + ApiSecretSnapshot, + UserApiSecretCheckResult, +} from '@/shared/utils/api-secret-store' +import type { LlmChannelKey } from '@/shared/utils/api-secret-channel' + +/** 模块卡片的状态形状(与面板内的 reactive 记录同构)。 */ +export interface ModuleState { + input: string + checking: boolean + result: UserApiSecretCheckResult | null + error: string + /** 最近一次检测的来源:saved=密钥配置里已保存的密钥,input=输入框里的未保存值。 */ + lastCheckSource: 'saved' | 'input' | '' +} + +const MODULE_DESCRIPTIONS: Record = { + 'appearance-patent': '仅用于外观专利检测,保存在服务端并绑定当前账号。', + 'similar-asin': '仅用于货源查询,保存在服务端并绑定当前账号。', +} + +const CHECK_STATUS_TEXT: Record = { + passed: '检测通过', + failed: '检测失败', + error: '暂时无法判定', + unknown: '已保存,未检测', +} + +export interface ModuleViewDeps { + moduleChannels: Record + ensureModuleState: (moduleKey: string) => ModuleState + snapshotOf: (moduleKey: string) => ApiSecretSnapshot +} + +/** 模块卡片的展示派生值:描述/占位/状态文案与样式类。 */ +export function createModuleView({ moduleChannels, ensureModuleState, snapshotOf }: ModuleViewDeps) { + function descriptionOf(moduleKey: string) { + return MODULE_DESCRIPTIONS[moduleKey] || '保存在服务端并绑定当前账号。' + } + + function placeholderOf(moduleKey: string) { + const snapshot = snapshotOf(moduleKey) + if (snapshot.exists) { + return `已保存(${snapshot.masked || '****'}),输入新值可覆盖` + } + return moduleChannels[moduleKey] === 'longtaitou' + ? '请输入龙抬头接口密钥(sk-...)' + : '请输入贞贞接口密钥(sk-...)' + } + + function statusPillTextOf(moduleKey: string) { + const state = ensureModuleState(moduleKey) + if (state.checking) return '检测中' + const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus + if (status === 'passed') return '可用' + if (status === 'failed') return '不可用' + if (status === 'error') return '待确认' + return snapshotOf(moduleKey).exists ? '未检测' : '未配置' + } + + function statusPillClassOf(moduleKey: string) { + const state = ensureModuleState(moduleKey) + const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus + return { + 'status-pill--ok': status === 'passed', + 'status-pill--fail': status === 'failed', + 'status-pill--warn': status === 'error', + } + } + + function formatTime(millis: number | null) { + if (!millis) return '' + const date = new Date(millis) + const hour = String(date.getHours()).padStart(2, '0') + const minute = String(date.getMinutes()).padStart(2, '0') + return `${hour}:${minute}` + } + + function statusTextOf(moduleKey: string) { + const state = ensureModuleState(moduleKey) + if (state.checking) return state.input.trim() ? '正在检测输入值...' : '正在检测配置密钥...' + if (state.result) { + const latency = state.result.checkLatencyMs != null ? `(${state.result.checkLatencyMs}ms)` : '' + const suffix = state.result.viaProxy === true ? ' · 经代理' : '' + const snapshot = snapshotOf(moduleKey) + // 明确展示本次检测的对象:输入值(未保存)或该用户密钥配置里保存的密钥(脱敏) + const prefix = state.lastCheckSource === 'input' + ? '输入值(未保存):' + : `配置密钥${snapshot.masked ? ` ${snapshot.masked}` : ''}:` + if (state.result.checkStatus === 'passed') return `${prefix}检测通过${latency}${suffix}` + if (state.result.checkCode === 'insufficient_balance') return `${prefix}欠费:${state.result.checkMessage || '代理服务商余额不足'}${suffix}` + return `${prefix}${state.result.checkMessage || '检测失败'}${suffix}` + } + if (state.error) return state.error + const snapshot = snapshotOf(moduleKey) + if (!snapshot.exists) return '当前未保存,请填写后保存' + const status = CHECK_STATUS_TEXT[snapshot.checkStatus] || '已保存' + const time = formatTime(snapshot.checkedAt) + const message = snapshot.checkStatus === 'unknown' ? '' : `:${snapshot.checkMessage || ''}` + const masked = snapshot.masked ? `配置密钥 ${snapshot.masked} · ` : '' + return `${masked}${status}${message}${time ? ` · ${time}` : ''}` + } + + function resultClassOf(moduleKey: string) { + const state = ensureModuleState(moduleKey) + const status = state.result?.checkStatus || snapshotOf(moduleKey).checkStatus + return { + 'check-result--ok': status === 'passed', + 'check-result--fail': status === 'failed', + 'check-result--warn': status === 'error', + } + } + + return { + descriptionOf, + placeholderOf, + statusPillTextOf, + statusPillClassOf, + formatTime, + statusTextOf, + resultClassOf, + } +} diff --git a/frontend-vue/src/shared/utils/api-secret-proxy-config.ts b/frontend-vue/src/shared/utils/api-secret-proxy-config.ts new file mode 100644 index 000000000..4929cee4f --- /dev/null +++ b/frontend-vue/src/shared/utils/api-secret-proxy-config.ts @@ -0,0 +1,68 @@ +import type { ProxyMode } from '@/shared/bridges/pywebview' +import { + detectProxyProviderFromUrl, + normalizeProxyProvider, + type ProxyProviderKey, +} from '@/shared/utils/api-secret-channel' + +export interface UserProxyView { + url: string + mode: ProxyMode + provider: ProxyProviderKey + account: string + password: string +} + +export function proxyUserId(): string { + if (typeof window === 'undefined') return '0' + return window.localStorage.getItem('uid') || '0' +} + +/** 代理地址按登录用户隔离:proxy_users[uid],各自计费各自复用; + * 用户项为空(含老版本只存了全局 proxy_url 的账号)回退全局,口径与客户端任务链 + * `resolve_current_proxy` 一致——否则这些账号的代理既显示不出来,也补报不到服务端。 */ +export function readUserProxy(config: Record | null | undefined): UserProxyView { + const uid = proxyUserId() + 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 { + url: ownUrl, + mode: Number(own.proxy_mode) === 2 ? 2 : 1, + provider: normalizeProxyProvider(own.proxy_provider ?? detectProxyProviderFromUrl(ownUrl)), + account: typeof own.proxy_account === 'string' ? own.proxy_account : '', + password: typeof own.proxy_password === 'string' ? own.proxy_password : '', + } + } + } + const url = typeof config?.proxy_url === 'string' ? config.proxy_url : '' + return { + url, + mode: Number(config?.proxy_mode) === 2 ? 2 : 1, + provider: normalizeProxyProvider(config?.proxy_provider ?? detectProxyProviderFromUrl(url)), + account: typeof config?.proxy_account === 'string' ? config.proxy_account : '', + password: typeof config?.proxy_password === 'string' ? config.proxy_password : '', + } +} + +export function userProxyPatch( + nextProxyUrl: string, + nextProxyMode: ProxyMode, + provider: ProxyProviderKey, + account: string, + password: string, +) { + // 极客不需要这对账密:切过去时一并清空,避免残留串到别的供应商 + const credentials = provider === 'qingguo' + ? { proxy_account: account.trim(), proxy_password: password } + : { proxy_account: '', proxy_password: '' } + const uid = proxyUserId() + if (uid === '0') { + return { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode, proxy_provider: provider, ...credentials } + } + const users: Record = {} + users[uid] = { proxy_url: nextProxyUrl, proxy_mode: nextProxyMode, proxy_provider: provider, ...credentials } + return { proxy_users: users } +} diff --git a/frontend-vue/tests/catch-silence-ratchet.test.ts b/frontend-vue/tests/catch-silence-ratchet.test.ts index 0c37cb084..6104585a1 100644 --- a/frontend-vue/tests/catch-silence-ratchet.test.ts +++ b/frontend-vue/tests/catch-silence-ratchet.test.ts @@ -42,6 +42,10 @@ const BASELINE = { // 防同一任务执行两次。 // silent 一格没涨:两支都有用户可见出口,只进 blocks。 blocks: 303, + // 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处 + // 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进 + // useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动, + // 属"给可读性让路"的逐条搬家记名。 // 298 = 296 + 全局错误出口 app-error.ts 的两支新 try/catch(10-09 装 app.config.errorHandler / // window.onerror / unhandledrejection 时引入),两支都不是"吞": // ① String(reason) 对无 toString 的对象/Symbol 会抛,兜法返回一句中文占位文本, @@ -86,7 +90,8 @@ const BASELINE = { 'src/shared/auth/ensure-auth.ts': 1, 'src/shared/auth/kick-handler.ts': 4, 'src/shared/bridges/web-fallback.ts': 2, - 'src/shared/components/ApiSecretSettingsPanel.vue': 1, + 'src/shared/components/ApiSecretSettingsPanel.vue': 0, + 'src/shared/composables/useProxyPlan.ts': 1, 'src/shared/components/ExpiryNotice.vue': 2, 'src/shared/components/NotificationBell.vue': 0, 'src/shared/composables/useLiveTaskBoard.ts': 1,