fix(proxy): 青果检测改真探并按供应商分码,三面收口凭据外漏与「无法判定」

用户报「青果也要加检测」,往下挖出四层假象,一次收口:

- 后端:probeProxy 的青果短路(过去无条件回「提取成功(青果隧道端点,连接鉴权在客户端)」,
  依据的注释已过期——存下来的链接里就带 key/pwd)删掉,改成真打一次提取,按供应商返回码
  分档出独立 check_code:channel_busy / invalid_key / forbidden / rate_limited /
  insufficient_balance / tunnel_unverified。文案出口一律抹 key/pwd。
- 后端:巡检遇 channel_busy 不落库也不推通知。通道被占不是「密钥坏了」而是「此刻问不出
  结论」,而巡检自己那一发真提取就要占掉唯一一条通道——落库等于把用户早上看到的
  「代理异常」写成我们自己造成的。
- 后端:余量口径按供应商分档。青果账号此前会落进「否则查平台套餐」那条,界面显示的是
  别人家的 jikip 余量(串档);青果不提供可鉴权的余量/余额查询(余额接口是控制台
  appid/appkey 签名档),这一档宁可返回「查不了」也不借极客的数。
- 后端:SecretMasking.maskProxy 的脏值回落不再套 mask()——它保后 4 字符,而青果的 pwd=
  恰好挂在末尾,等于把口令尾 4 位交给界面与日志;改成只交「像 host 的那一段」。
- 用户端:去掉「青果账密直连,无需检测」的 disabled 例外,未保存账密现拼链接送检;
  「无法判定」回落改成后端文案原样显示+可重试语义;代理卡不再套 LLM 渠道字典
  (「龙抬头」错标的真根因就在这行)。
- 后管:货源标签拆成两张互不相通的字典,代理列只读 masked 且不回落到原文,删掉
  user-select:all 的全选复制旁路,「修改代理」改成重填 Authkey/Authpwd 的弹窗。

判据:SecretMaskingTest(5)、UserProxyBalanceServiceTest(6)、UserApiSecretServiceTest
(+1 巡检不落库)、UserApiSecretCheckServiceTest(+138 行分码)、ProxyLinkKeyTest、
用户端 node 5 支+mount 10 支、后管 node 9 支+mount 8 支。后端整量 5187/0 失败,
full 闸门四面绿。
This commit is contained in:
2026-11-02 15:18:41 +08:00
parent 7f5437d012
commit 7e64c12dd6
24 changed files with 2062 additions and 204 deletions
@@ -5,7 +5,7 @@
<div class="secret-card-heading">
<div class="secret-card-title">
{{ module.moduleLabel }}
<span class="source-tag">{{ llmChannelLabel(moduleChannels[module.moduleKey]) }}</span>
<span class="source-tag">{{ moduleSourceLabel(module.moduleKey, moduleChannels[module.moduleKey]) }}</span>
<span class="status-pill" :class="statusPillClassOf(module.moduleKey)">
{{ statusPillTextOf(module.moduleKey) }}
</span>
@@ -212,21 +212,18 @@
</div>
</div>
<div v-else-if="proxySupported && proxyProvider === 'qingguo'" class="proxy-plan-hint">
青果的账户余量与通道用量请到青果后台查看;本客户端目前只做青果提取链接的连通性检测。
青果的套餐与通道用量以青果后台为准;这里的「检测」会真打一次提取并经隧道验连——
它会占掉你那一条通道的存活期(约 3 分钟),期间再点会得到「通道被占」,等释放后重点一次即可。
</div>
<div class="secret-actions">
<button
type="button"
class="check-btn"
:disabled="!proxyReady || busy || proxyChecking || proxyProvider === 'qingguo'"
:disabled="!proxyReady || busy || proxyChecking"
@click="runProxyCheck"
>
{{ proxyChecking
? '检测中...'
: (proxyProvider === 'qingguo'
? '青果账密直连,无需检测'
: (proxyUrl.trim() && proxyDirty ? '检测输入地址(未保存)' : '检测配置代理')) }}
{{ proxyCheckLabel }}
</button>
<span class="check-result" :class="proxyResultClass">
{{ proxyStatusText }}
@@ -237,10 +234,9 @@
<span v-if="proxyLoading">正在读取代理配置...</span>
<span v-else-if="proxyLoadFailed">代理配置读取失败,请关闭弹窗后重试</span>
<span v-else-if="!proxySupported">代理设置仅在桌面客户端中可用</span>
<span v-else-if="proxyProvider === 'qingguo'">供应商:青果 · 提取链接示例 https://overseas.proxy.qg.net/get?key=...&format=json</span>
<span v-else-if="balanceLoading">正在查询代理余量...</span>
<span v-else-if="balance">{{ balanceText }}</span>
<span v-else>余额查询暂不可用</span>
<span v-else>{{ balanceUnavailableText }}</span>
</div>
</section>
</div>
@@ -269,8 +265,10 @@ import {
LLM_CHANNEL_OPTIONS,
PROXY_PROVIDER_OPTIONS,
llmChannelLabel,
moduleSourceLabel,
normalizeLlmChannel,
normalizeProxyProvider,
proxyCheckValue,
proxyProviderLabel,
type LlmChannelKey,
type ProxyProviderKey,
@@ -287,7 +285,7 @@ import {
userProxyPatch,
} from '@/shared/utils/api-secret-proxy-config'
import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan'
import { createModuleView, type ModuleState } from '@/shared/utils/api-secret-module-view'
import { createModuleView, proxyCheckPresentation, type ModuleState } from '@/shared/utils/api-secret-module-view'
const props = withDefaults(
defineProps<{
@@ -334,7 +332,7 @@ const proxyChecking = ref(false)
const proxyCheckResult = ref<UserApiSecretCheckResult | null>(null)
const proxyCheckError = ref('')
const { balance, balanceLoading, balanceText, loadBalance } = useProxyBalance({ proxyProvider })
const { balance, balanceLoading, balanceText, balanceUnavailableText, loadBalance } = useProxyBalance({ proxyProvider })
const {
proxyPlanId,
proxyPlanUserId,
@@ -352,25 +350,42 @@ const {
const proxyPlaceholder = 'https://api.jikip.com/ip-get?num=1&minute=3&key=... 或 http://user:pass@host:port'
const proxyStatusText = computed(() => {
if (proxyChecking.value) return '正在检测...'
if (proxyCheckResult.value) {
const latency = proxyCheckResult.value.checkLatencyMs != null ? `(${proxyCheckResult.value.checkLatencyMs}ms)` : ''
if (proxyCheckResult.value.checkStatus === 'passed') return `代理连通正常${latency}`
return `${proxyCheckResult.value.checkMessage || '代理检测失败'}`
/**
* 「检测」要送出去的链接:没改动→undefined(服务端用库里那条),改了没保存→当前输入。
* 空串=草稿拼不出链接(青果没填 Authkey/极客把地址清空),这种检测必然失败,按钮与点击都拦住。
*/
const proxyCheckDraft = computed(() => proxyCheckValue({
provider: proxyProvider.value,
url: proxyUrl.value,
dirty: proxyDirty.value,
account: proxyAccount.value,
password: proxyPassword.value,
}))
const proxyDraftUnusable = computed(() => proxyDirty.value && !proxyCheckDraft.value)
/** 按钮文案要说清「检的是哪一条」:未保存的输入值,还是库里已存的配置。 */
const proxyCheckLabel = computed(() => {
if (proxyChecking.value) return '检测中...'
if (proxyDraftUnusable.value) {
return proxyProvider.value === 'qingguo' ? '请先填写青果账密' : '请先填写代理地址'
}
if (proxyCheckError.value) return proxyCheckError.value
return ''
if (proxyCheckDraft.value === undefined) return '检测配置代理'
return proxyProvider.value === 'qingguo' ? '检测输入账密(未保存)' : '检测输入地址(未保存)'
})
const proxyResultClass = computed(() => {
const status = proxyCheckResult.value?.checkStatus
return {
'check-result--ok': status === 'passed',
'check-result--fail': status === 'failed',
'check-result--warn': status === 'error',
}
})
/** 检测结果:文案原样用接口返回值,语气(颜色)只按后端 status 分档,见 proxyCheckPresentation。 */
const proxyCheckView = computed(() => proxyCheckPresentation(
proxyCheckResult.value,
proxyChecking.value,
proxyCheckError.value,
))
const proxyStatusText = computed(() => proxyCheckView.value.text)
const proxyResultClass = computed(() => ({
'check-result--ok': proxyCheckView.value.tone === 'ok',
'check-result--fail': proxyCheckView.value.tone === 'fail',
'check-result--warn': proxyCheckView.value.tone === 'retry',
}))
/** 切换代理供应商:只改本地选择,保存时与地址一起写入(检测也会按新供应商解析响应)。 */
function selectProxyProvider(provider: ProxyProviderKey) {
@@ -384,26 +399,30 @@ function selectProxyProvider(provider: ProxyProviderKey) {
}
/** 检测代理连通性:地址有改动时检测输入值(不落库),否则检测/落库已存值并刷新状态展示。 */
/** 检测代理连通性:改动过就送当前输入(不落库),没改动就送 undefined 让服务端检库里那条。 */
async function runProxyCheck() {
if (proxyChecking.value) return
const inputValue = proxyUrl.value.trim()
const dirty = proxyDirty.value && inputValue
if (proxyDraftUnusable.value) {
// 拼不出链接就别发一次必然失败的请求:空串送上去等于「不送 override」,服务端会去检库里那条旧链接
ElMessage.warning(proxyProvider.value === 'qingguo'
? '青果要先填 Authkey(Authpwd 也必填)才拼得出可检测的链接;填完直接点检测即可,不必先保存'
: '请先填写代理地址,再点检测')
return
}
const draft = proxyCheckDraft.value
const fromDraft = draft !== undefined
proxyChecking.value = true
proxyCheckError.value = ''
proxyCheckResult.value = null
try {
// 供应商一起提交:检测要按对应供应商解析提取响应(青果/极客返回体不同)
proxyCheckResult.value = await checkApiSecret('proxy', dirty ? inputValue : undefined, proxyProvider.value)
proxyCheckResult.value = await checkApiSecret('proxy', draft, proxyProvider.value)
const result = proxyCheckResult.value
if (result.checkStatus === 'failed') {
ElMessage.warning(
result.checkCode === 'insufficient_balance' ? '代理服务商余额不足,请充值或联系管理员' : (result.checkMessage || '代理不可用'),
)
} else if (result.checkStatus === 'error') {
ElMessage.warning(result.checkMessage || '暂时无法判定代理可用性')
if (result.checkStatus === 'passed') {
ElMessage.success(fromDraft ? '输入值连通正常(未保存)' : '代理连通正常')
} else {
ElMessage.success(dirty ? '输入地址连通正常(未保存)' : '代理连通正常')
// 弹窗与行内用同一段文字:都是接口返回的原文,前端不再按错误码另写一套措辞
ElMessage.warning(proxyCheckPresentation(result, false, '').text || '代理检测失败')
}
} catch (error) {
proxyCheckError.value = error instanceof Error ? error.message : '代理检测失败'
@@ -4,10 +4,11 @@ import {
clearProxyPlan,
fetchProxyPlan,
saveProxyPlan,
type UserApiSecretBalance,
} 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'
import { PROXY_PLAN_CHANGED_EVENT, proxyBalanceWarningReason } from '@/shared/utils/proxy-balance-alert'
import { proxyProviderLabel, type ProxyProviderKey } from '@/shared/utils/api-secret-channel'
export interface ProxyPlanDeps {
proxyProvider: Ref<ProxyProviderKey>
@@ -126,38 +127,68 @@ export function useProxyPlan({ proxyProvider, resetWhitelistStatus, loadBalance
}
}
/** 极客套餐余量:只有极客口径的查询接口,青果不查询。 */
/**
* 代理套餐余量:按**当前供应商**显示,字段只用现有 VO 的 available/balance/surplus/scope/low/lowReason。
*
* 后端 `GET /api/user-secret/proxy-balance`(`UserProxyBalanceService.balance(userId)`)目前
* 只有极客的 find-balance,青果档在补。前端不替它判定「这个供应商不支持」:
* 查得到就按 scope 说明这份余量是谁的池子,查不到就把后端给的 `message` 原样摆出来
* (那句话说的是「没配好/读不到」,不是「青果没有余量这回事」)。等后端回青果的可用值,
* 这里不用再改形状。
*/
export function useProxyBalance({ proxyProvider }: { proxyProvider: Ref<ProxyProviderKey> }) {
const balance = ref<{ surplus: string | null; balance: string | null } | null>(null)
const balance = ref<UserApiSecretBalance | null>(null)
const balanceMessage = ref('')
const balanceLoading = ref(false)
/** 界面上下文:这一行余量是在哪个供应商的卡片下看到的。 */
const providerLabel = computed(() => proxyProviderLabel(proxyProvider.value))
const balanceText = computed(() => {
if (!balance.value) return ''
const surplus = balance.value.surplus ?? '-'
const amount = balance.value.balance ?? '-'
return `套餐IP余量:${surplus} · 账户余额:${amount}`
const current = balance.value
if (!current) return ''
const surplus = current.surplus ?? '-'
const amount = current.balance ?? '-'
const scope = current.scope === 'user'
? '你的套餐'
: current.scope === 'platform' ? '平台套餐' : '来源未标注'
// 低余量文案复用右上角警告那一套判据(proxyBalanceWarningReason),不在这里另写措辞
const low = proxyBalanceWarningReason(current)
return `${providerLabel.value}余量(${scope}):套餐IP ${surplus} · 账户余额 ${amount}${low ? ` · ${low}` : ''}`
})
/** available=false 时的诚实文案:接口说了原因就用它,没说就说「这次没查到」。 */
const balanceUnavailableText = computed(() => {
const reason = balanceMessage.value.trim()
if (reason) return `${providerLabel.value}余量:${reason}`
return `${providerLabel.value}余量这次没查到:接口没返回可用值(不是该供应商不支持,是这条余量还没配好),可稍后重开设置页再看`
})
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 }
balance.value = result
balanceMessage.value = ''
} else {
balance.value = null
balanceMessage.value = result?.message || ''
}
} catch (error) {
console.warn('[api-secret] 代理余量查询失败:', error)
balance.value = null
balanceMessage.value = ''
} finally {
balanceLoading.value = false
}
}
return { balance, balanceLoading, balanceText, loadBalance }
return {
balance,
balanceLoading,
balanceText,
balanceUnavailableText,
loadBalance,
}
}
@@ -6,10 +6,18 @@
*
* 默认值口径(2026-10-30 用户拍板):新建默认贞贞 / 极客,龙抬头与青果手动切换;
* 存量由服务端迁移回填为贞贞 / 极客,前端只按服务端下发的值回显,不自行改写。
*
* ⚠ 本文件保持**不引别名依赖**(只允许同目录相对导入),否则 `node --test` 解析不了
* `@/` 别名,这里的供应商/渠道判据就没法被用例钉住(同 `./qingguo-link.ts` 的理由)。
*/
import { composeQingguoLink } from './qingguo-link.ts'
export type LlmChannelKey = 'longtaitou' | 't8star'
export type ProxyProviderKey = 'qingguo' | 'jikip'
/** 密钥模块里「代理」那一张的 key:它的货源是代理供应商,与 LLM 渠道是两本字典。 */
export const PROXY_MODULE_KEY = 'proxy'
export interface SourceOption<T extends string> {
key: T
label: string
@@ -65,3 +73,40 @@ export function proxyProviderLabel(value: unknown): string {
const key = normalizeProxyProvider(value)
return PROXY_PROVIDER_OPTIONS.find((option) => option.key === key)?.label || key
}
/**
* 卡片上的「货源」标签:代理卡按代理供应商字典、LLM 卡按 LLM 渠道字典。
*
* 两本字典的 key 互不兼容:把 `qingguo` 喂进 `llmChannelLabel` 会被
* `normalizeLlmChannel` 静默落到 LLM 默认值,界面上就成了「代理卡标着 LLM 渠道名」
* (2026-11-02 后端核实那个错标正是这一处造成的)。
*/
export function moduleSourceLabel(moduleKey: unknown, channel: unknown): string {
return moduleKey === PROXY_MODULE_KEY ? proxyProviderLabel(channel) : llmChannelLabel(channel)
}
/** 「检测代理」的输入:当前供应商、地址框里的值、是否改过未保存、青果的账密。 */
export interface ProxyCheckInput {
provider: ProxyProviderKey
url: string
dirty: boolean
account: string
password: string
}
/**
* 点「检测」时要送出去的那条链接(与保存路径同一个拼装出处,不许在这里另写一遍 URL)。
*
* - 没改动(`dirty=false`)→ `undefined`:让服务端用它库里存的那条值去检测
* (后端列表读路已套 `SecretMasking.maskProxy`,链接原文不下发,前端手里根本没有可送的副本);
* - 改了没保存 → 极客送地址框里的原文;青果**没有地址框**,只能用 `composeQingguoLink(账密)` 现拼,
* 否则「填了账密点检测」送出去的是空值,服务端会去检库里那条旧链接——检测通过的是别的配置;
* - 返回空串=草稿拼不出链接(青果没填 Authkey / 极客把地址清空),调用方必须拦住,
* 不能拿空串冒充「检测输入值」(`checkApiSecret` 里空串等价于「不送 override」)。
*/
export function proxyCheckValue(input: ProxyCheckInput): string | undefined {
if (!input.dirty) return undefined
return input.provider === 'qingguo'
? composeQingguoLink(input.account, input.password)
: input.url.trim()
}
@@ -27,6 +27,54 @@ const CHECK_STATUS_TEXT: Record<ApiSecretCheckStatus, string> = {
unknown: '已保存,未检测',
}
/** 检测结果的界面语气:ok=绿 / fail=红(真不可用)/ retry=黄(这次没验成,稍后可重试)/ idle=灰。 */
export type CheckTone = 'ok' | 'fail' | 'retry' | 'idle'
export interface CheckPresentation {
text: string
tone: CheckTone
}
/**
* 后端状态 → 语气。**只读后端给的 status,不在前端另起一套错误码语义**:
* `channel_busy`/`rate_limited`/`timeout`/`tunnel_unverified` 这类「不是你的错、等一会儿就好」
* 后端一律落 `error`,`invalid_key`/`forbidden`/`insufficient_balance` 才落 `failed`。
* 混成红色「密钥错误」会把可重试的档说成配置坏了。
*/
export function checkToneOf(status: string | null | undefined): CheckTone {
if (status === 'passed') return 'ok'
if (status === 'failed') return 'fail'
if (status === 'error') return 'retry'
return 'idle'
}
/**
* 代理检测结果的展示口径(2026-11-02 用户报的现象:非 passed 一律显示成「无法判定」)。
*
* 文案**以接口返回值原文为准**(一档一码一文案的权威在后端 `UserApiSecretCheckService`),
* 只有接口没给 `checkMessage` 时才回落到通用文案;`error` 档回落的是「稍后可重试」,
* 不是「无法判定」——后者等于把后端已经给出的原因又吞回去。
*/
export function proxyCheckPresentation(
result: UserApiSecretCheckResult | null,
checking: boolean,
requestError: string,
): CheckPresentation {
if (checking) return { text: '正在检测...', tone: 'idle' }
if (result) {
const tone = checkToneOf(result.checkStatus)
const latency = result.checkLatencyMs != null ? `(${result.checkLatencyMs}ms)` : ''
if (tone === 'ok') return { text: `代理连通正常${latency}`, tone }
const message = (result.checkMessage || '').trim()
const fallback = tone === 'retry'
? '这次没能判定代理可用性,稍后可以再点一次检测'
: '代理不可用,请检查配置后重测'
return { text: `${message || fallback}${latency}`, tone }
}
if (requestError) return { text: requestError, tone: 'fail' }
return { text: '', tone: 'idle' }
}
export interface ModuleViewDeps {
moduleChannels: Record<string, LlmChannelKey>
ensureModuleState: (moduleKey: string) => ModuleState
@@ -0,0 +1,288 @@
/**
* 密钥设置面板「代理」那一张卡的挂载用例(2026-11-02 三件事:放开青果检测、结果文案以接口为准、
* 卡片货源标签按供应商)。判的是运行时行为,不是读源码形状。
*
* 四组靶子:
* ① 青果不再被 `proxyProvider === 'qingguo'` 排除在「检测」之外:按钮可点、文案不许说「无需检测」;
* ② 未保存状态下点检测,送出去的是 composeQingguoLink(账密) 现拼的那条(与保存路径同一个出处),
* 没改动时送 undefined 让服务端检库里那条——后端列表读路已套 maskProxy,前端拿不到链接原文;
* ③ 结果文案一律用接口返回的 checkMessage 原文:channel_busy(后端落 error 档)必须是「可重试」语气
* (黄,不是红),也不许被吞成「无法判定」(用户报的就是这个现象);
* ④ 余量按供应商显示;查不到时说人话(不是「不支持」、也不是笼统「暂不可用」)。
*
* ⚠ 用例里的账密一律是假值(fakekey/fakepwd),真实凭据不得进任何跟踪件。
*
* 跑法:`npx vitest run tests/mount/密钥面板青果检测.mount.test.ts`
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
import { composeQingguoLink } from '@/shared/utils/qingguo-link'
const UID = '1301'
const FAKE_KEY = 'fakekey'
const FAKE_PWD = 'fakepwd'
/** 后端为「通道被占」发的独立码与文案(措辞权威在后端 UserApiSecretCheckService)。 */
const CHANNEL_BUSY_MESSAGE = '青果通道正被你自己的采集占着,等约 3 分钟释放后再点检测'
const message = vi.hoisted(() => ({
error: vi.fn(),
warning: vi.fn(),
success: vi.fn(),
info: vi.fn(),
}))
const store = vi.hoisted(() => ({
checkApiSecret: vi.fn(),
clearApiSecret: vi.fn(),
getServerProxySnapshot: vi.fn(),
getStoredApiSecretSnapshot: vi.fn(),
listApiSecretModules: vi.fn(),
loadApiSecrets: vi.fn(),
saveApiSecret: vi.fn(),
subscribeApiSecrets: vi.fn(),
fetchProxyBalanceSafely: vi.fn(),
}))
const secretApi = vi.hoisted(() => ({
putMyApiSecret: vi.fn(),
deleteMyApiSecret: vi.fn(),
fetchProxyPlan: vi.fn(),
saveProxyPlan: vi.fn(),
clearProxyPlan: vi.fn(),
}))
const bridge = vi.hoisted(() => ({
readConfig: vi.fn(),
saveConfig: vi.fn(),
}))
vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/utils/api-secret-store', () => ({
checkApiSecret: store.checkApiSecret,
clearApiSecret: store.clearApiSecret,
getServerProxySnapshot: store.getServerProxySnapshot,
getStoredApiSecretSnapshot: store.getStoredApiSecretSnapshot,
listApiSecretModules: store.listApiSecretModules,
loadApiSecrets: store.loadApiSecrets,
saveApiSecret: store.saveApiSecret,
subscribeApiSecrets: store.subscribeApiSecrets,
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
}))
vi.mock('@/shared/api/types/modules/user-secret', () => ({
putMyApiSecret: secretApi.putMyApiSecret,
deleteMyApiSecret: secretApi.deleteMyApiSecret,
fetchProxyPlan: secretApi.fetchProxyPlan,
saveProxyPlan: secretApi.saveProxyPlan,
clearProxyPlan: secretApi.clearProxyPlan,
}))
vi.mock('@/shared/bridges/pywebview', () => ({
getPywebviewApi: () => ({ read_config: bridge.readConfig, save_config: bridge.saveConfig }),
}))
function emptySnapshot() {
return {
value: '', masked: '', channel: '', exists: false, locked: false,
checkStatus: 'unknown', checkCode: '', checkMessage: '',
checkLatencyMs: null, checkedAt: null, updatedAt: null,
}
}
/** 本机已存过青果账密(proxy_users[uid]):桌面桥读得到的就是这份。 */
function qingguoConfig() {
return {
proxy_users: {
[UID]: {
proxy_url: '', proxy_mode: 2, proxy_provider: 'qingguo',
proxy_account: FAKE_KEY, proxy_password: FAKE_PWD,
},
},
}
}
function checkResult(over: Record<string, unknown> = {}) {
return {
moduleKey: 'proxy',
checkStatus: 'passed',
checkCode: 'ok',
checkMessage: '连通正常',
checkLatencyMs: 120,
checkedAt: null,
viaProxy: false,
...over,
}
}
async function mountPanel() {
wrapper = mount(ApiSecretSettingsPanel)
await flushPromises()
await flushPromises()
return wrapper!
}
/** 代理是最后一张卡:它的动作区与余量行都落在这一张里。 */
function proxyCard(panel: VueWrapper) {
const cards = panel.findAll('.secret-card')
return cards[cards.length - 1]
}
function proxyCheckButton(panel: VueWrapper) {
return proxyCard(panel).findAll('.check-btn')[0]
}
function proxyResultText(panel: VueWrapper) {
return proxyCard(panel).find('.check-result')
}
beforeEach(() => {
localStorage.clear()
localStorage.setItem('uid', UID)
vi.clearAllMocks()
store.listApiSecretModules.mockReturnValue([
{ moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' },
{ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' },
])
store.getStoredApiSecretSnapshot.mockReturnValue(emptySnapshot())
store.getServerProxySnapshot.mockReturnValue(null)
store.subscribeApiSecrets.mockReturnValue(() => undefined)
store.loadApiSecrets.mockResolvedValue('complete')
store.checkApiSecret.mockResolvedValue(checkResult())
store.fetchProxyBalanceSafely.mockResolvedValue({
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
})
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
bridge.readConfig.mockResolvedValue(qingguoConfig())
bridge.saveConfig.mockResolvedValue(undefined)
})
let wrapper: VueWrapper | null = null
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
describe('青果放开检测:按钮、送检链接与结果文案', () => {
it('青果选中时「检测」可点,且不再自称「无需检测」', async () => {
const panel = await mountPanel()
const button = proxyCheckButton(panel)
expect(button.attributes('disabled')).toBeUndefined()
expect(button.text()).not.toContain('无需检测')
expect(button.text()).toContain('检测配置代理')
expect(panel.html()).not.toContain('青果账密直连,无需检测')
})
it('没改动时送 undefined:服务端用它库里存的那条(链接原文已不下发前端)', async () => {
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
expect(store.checkApiSecret).toHaveBeenCalledWith('proxy', undefined, 'qingguo')
})
it('改了账密没保存就送现拼链接(与保存路径同一个 composeQingguoLink 出处)', async () => {
const panel = await mountPanel()
const accountInput = proxyCard(panel).findAll('input')[0]
await accountInput.setValue(`${FAKE_KEY}X`)
expect(proxyCheckButton(panel).text()).toContain('检测输入账密(未保存)')
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const sent = store.checkApiSecret.mock.calls[0]?.[1] as string
expect(sent, '送检值必须逐字节等于拼装出处的输出').toBe(
composeQingguoLink(`${FAKE_KEY}X`, FAKE_PWD),
)
expect(sent).toContain('overseas.proxy.qg.net')
expect(message.success).toHaveBeenCalledWith('输入值连通正常(未保存)')
})
it('账密被清空时拦住这一次必然失败的检测(空串≠"用库里的值")', async () => {
const panel = await mountPanel()
const accountInput = proxyCard(panel).findAll('input')[0]
await accountInput.setValue('')
await proxyCheckButton(panel).trigger('click')
await flushPromises()
expect(store.checkApiSecret, '拼不出链接就不该发检测,否则服务端检的是库里那条旧链接').not.toHaveBeenCalled()
expect(message.warning).toHaveBeenCalled()
})
it('channel_busy:文案用接口原文,语气是可重试(黄),不是红色密钥错误也不是「无法判定」', async () => {
store.checkApiSecret.mockResolvedValue(checkResult({
checkStatus: 'error',
checkCode: 'channel_busy',
checkMessage: CHANNEL_BUSY_MESSAGE,
checkLatencyMs: null,
}))
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const result = proxyResultText(panel)
expect(result.text()).toContain(CHANNEL_BUSY_MESSAGE)
expect(result.text()).not.toContain('无法判定')
expect(result.classes()).toContain('check-result--warn')
expect(result.classes()).not.toContain('check-result--fail')
})
it('failed 才标红,且仍原样显示接口给的文案', async () => {
store.checkApiSecret.mockResolvedValue(checkResult({
checkStatus: 'failed',
checkCode: 'invalid_key',
checkMessage: '青果密钥不可用或已失效(INVALID_KEY),请核对提取链接里的 key',
}))
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const result = proxyResultText(panel)
expect(result.text()).toContain('青果密钥不可用或已失效(INVALID_KEY)')
expect(result.classes()).toContain('check-result--fail')
})
it('接口没给文案时才兜底:error 档兜「稍后再点一次」,不再回落到「无法判定」', async () => {
store.checkApiSecret.mockResolvedValue(checkResult({
checkStatus: 'error', checkCode: 'timeout', checkMessage: '',
}))
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const text = proxyResultText(panel).text()
expect(text).toContain('稍后可以再点一次检测')
expect(text).not.toContain('无法判定')
})
})
describe('货源标签与代理余量:按供应商,不套 LLM 渠道字典', () => {
it('代理卡标题下的货源是供应商名(青果),不是 LLM 渠道名', async () => {
const panel = await mountPanel()
expect(proxyCard(panel).find('.source-tag').text()).toBe('青果')
expect(proxyCard(panel).text(), '代理卡里不许出现 LLM 渠道选项').not.toContain('贞贞')
})
it('余量行按当前供应商显示,并按 scope 说明是谁的池子', async () => {
const panel = await mountPanel()
expect(proxyCard(panel).find('.secret-meta').text()).toContain('青果余量(你的套餐)')
expect(proxyCard(panel).find('.secret-meta').text()).toContain('套餐IP 12')
})
it('available=false:把后端给的原因原样摆出来,不说成「该供应商不支持」', async () => {
store.fetchProxyBalanceSafely.mockResolvedValue({
available: false, surplus: null, balance: null, message: '尚未配置套餐,按平台套餐也读不到', scope: null,
})
const panel = await mountPanel()
const meta = proxyCard(panel).find('.secret-meta').text()
expect(meta).toContain('尚未配置套餐,按平台套餐也读不到')
expect(meta).not.toContain('暂不可用')
})
})
@@ -1,6 +1,7 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { composeQingguoLink, QINGGUO_EXTRACT_URL } from '../src/shared/utils/qingguo-link.ts'
import { moduleSourceLabel, proxyCheckValue } from '../src/shared/utils/api-secret-channel.ts'
/**
* 青果没有「提取链接」可填,用户只给 key(Authkey)/ pwd(Authpwd),链接必须由前端拼
@@ -25,3 +26,55 @@ test('key/pwd 里的特殊字符要编码,不能把查询串拼坏', () => {
const link = composeQingguoLink('a&b=c', 'p@ss:1')
assert.ok(link.endsWith('?key=a%26b%3Dc&pwd=p%40ss%3A1'), link)
})
/**
* 「点检测」送出去的链接必须走同一条拼装出处(2026-11-02 放开青果检测)。
* 检测按钮过去被 `proxyProvider === 'qingguo'` 直接 disabled,用户只能"保存了再猜";
* 现在未保存也要能检,就必须送现拼的链接——若这里另写一遍 URL,就会出现
* 「检的是一条、存的是另一条」(AGENTS.md 铁律 27 的同源边界)。
*/
test('检测未保存的青果账密时送现拼链接(与保存路径同一出处)', () => {
const sent = proxyCheckValue({
provider: 'qingguo', url: '', dirty: true, account: 'fakekey', password: 'fakepwd',
})
assert.equal(sent, composeQingguoLink('fakekey', 'fakepwd'), '送检值必须逐字节等于拼装出处的输出')
assert.ok(sent?.includes('fakekey'), '账密没进来就等于白检一次')
})
test('没改动时不送链接:让服务端用它库里存的那条(后端已不下发链接原文)', () => {
assert.equal(
proxyCheckValue({ provider: 'qingguo', url: '', dirty: false, account: 'fakekey', password: 'fakepwd' }),
undefined,
'已保存态送 undefined,前端手里没有库里的值可送')
assert.equal(
proxyCheckValue({ provider: 'jikip', url: 'http://1.2.3.4:8080', dirty: false, account: '', password: '' }),
undefined,
)
})
test('极客的检测送地址框里的原文(青果才需要拼)', () => {
assert.equal(
proxyCheckValue({ provider: 'jikip', url: ' http://1.2.3.4:8080 ', dirty: true, account: '', password: '' }),
'http://1.2.3.4:8080',
)
})
test('草稿拼不出链接时返回空串:调用方必须拦住,不能拿空串冒充"检测输入值"', () => {
assert.equal(
proxyCheckValue({ provider: 'qingguo', url: '', dirty: true, account: '', password: 'fakepwd' }),
'',
'空串与 undefined 语义不同:前者是"没配出来",后者才是"用库里的"')
})
/**
* 卡片标签:代理卡的货源是供应商(青果/极客),不能进 LLM 渠道字典——
* `normalizeLlmChannel('qingguo')` 会静默落到 LLM 默认值,界面就成了「代理卡标着渠道名」
* (2026-11-02 后端核实的那个错标)。
*/
test('代理卡按供应商标货源,LLM 卡仍按渠道字典', () => {
assert.equal(moduleSourceLabel('proxy', 'qingguo'), '青果')
assert.equal(moduleSourceLabel('proxy', 'jikip'), '极客')
assert.equal(moduleSourceLabel('appearance-patent', 'longtaitou'), '龙抬头')
assert.equal(moduleSourceLabel('similar-asin', 't8star'), '贞贞')
assert.notEqual(moduleSourceLabel('proxy', 'qingguo'), '龙抬头', '供应商 key 不许被当成 LLM 渠道回显')
})