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:
@@ -5,10 +5,20 @@ import { unwrap } from './envelope'
|
||||
export interface AdminUserSecretModule {
|
||||
moduleKey: string
|
||||
moduleLabel: string
|
||||
/** 货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip)。 */
|
||||
/**
|
||||
* 货源:按模块分域,后端 `UserSecretModule.channelOrDefault` 已归一——
|
||||
* LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip)。
|
||||
* ⚠ 界面不得用一张合表渲染这两域(代理行贴出「龙抬头」就是这么来的),
|
||||
* 走 `user-secret-model.ts` 的 `moduleSourceLabel`。
|
||||
*/
|
||||
channel?: string | null
|
||||
/** 脱敏值:代理列为 `scheme://host`,不含提取链接里的 key/pwd。 */
|
||||
masked: string
|
||||
/** 完整明文值:仅代理列有值(后端对密钥列不下发明文)。 */
|
||||
/**
|
||||
* 完整明文值:后台侧**恒为空**(2026-11-02 `SecretMasking.maskProxy` 收口,代理链接里带着账密)。
|
||||
* 字段保留只为接口兼容;界面**不得**读它、更不得拿它做"masked 空就回落原文"的兜底,
|
||||
* 也不许有任何复制/导出整条链接的旁路。
|
||||
*/
|
||||
full: string
|
||||
exists: boolean
|
||||
/** 是否由后台代填并锁定:锁定时客户端不可修改或清空。 */
|
||||
@@ -100,13 +110,22 @@ export async function deleteUserSecret(userId: number): Promise<void> {
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 代填并锁定该用户某模块配置(当前仅代理):PUT /api/admin/user-secrets/{userId}/modules/{moduleKey} */
|
||||
/**
|
||||
* 代填并锁定该用户某模块配置(当前仅代理):PUT /api/admin/user-secrets/{userId}/modules/{moduleKey}
|
||||
* `value` 是**一次性写载荷**(代理为现拼的提取链接,带着 key/pwd):调用方不得把它渲染回界面、
|
||||
* 不得打进日志;`channel` 是同一单的货源(代理=供应商 key),后端据此选解析分支——
|
||||
* 不给则由后端按链接域名识别,识别不出回落默认供应商,会静默换执行方,所以本面一律显式带上。
|
||||
*/
|
||||
export async function saveUserSecretModule(
|
||||
userId: number,
|
||||
moduleKey: string,
|
||||
value: string,
|
||||
channel?: string,
|
||||
): Promise<AdminUserSecretModule> {
|
||||
const { data } = await http.put(`/api/admin/user-secrets/${userId}/modules/${moduleKey}`, { value })
|
||||
const { data } = await http.put(`/api/admin/user-secrets/${userId}/modules/${moduleKey}`, {
|
||||
value,
|
||||
...(channel ? { channel } : {}),
|
||||
})
|
||||
return unwrap<AdminUserSecretModule>(data)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { saveUserSecretModule } from '@/api/user-secrets'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import {
|
||||
PROXY_MODULE_KEY,
|
||||
buildProxyEntryPayload,
|
||||
emptyProxyEntryDraft,
|
||||
validateProxyEntry,
|
||||
type ProxyEntryDraft,
|
||||
} from './user-secret-model.ts'
|
||||
|
||||
/**
|
||||
* 后台代填/改代理(2026-11-02 脱敏后重做的交互)。
|
||||
*
|
||||
* 旧交互是 `window.prompt` 预填 `row.proxy.full` 整条提取链接——后端把这条读路套上
|
||||
* `SecretMasking.maskProxy` 之后 `full` 恒空,预填必然是空的,照旧保存等于把空串顶上去、
|
||||
* 或让管理员去别处翻原文。现在收**账密**、链接在本机现拼现发:
|
||||
* - 青果:填 Authkey + Authpwd,`composeQingguoLink` 拼(青果产品页没有可复制的链接);
|
||||
* - 极客:填极客自己的提取链接(它有可复制的链接)。
|
||||
* 拼好的链接是一次性写载荷,只进 PUT 请求体:不回显、不回填、不进 tooltip、不给复制/导出旁路;
|
||||
* 保存成功即清空输入位,重开必然要从头再填(这是脱敏的应然后果,界面直接把它说出来)。
|
||||
*/
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
userId: number | null
|
||||
username: string
|
||||
/** 后端已登记的供应商(只是预选中的单选框,不是凭据)。 */
|
||||
provider?: string | null
|
||||
locked?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const draft = reactive<ProxyEntryDraft>(emptyProxyEntryDraft())
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
function resetDraft() {
|
||||
Object.assign(draft, emptyProxyEntryDraft(props.provider))
|
||||
errorText.value = ''
|
||||
}
|
||||
|
||||
// 开与关都重刷:关的时候把已经打进内存的账密/链接抹掉,不留到下一次。
|
||||
watch(() => props.modelValue, resetDraft)
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (props.userId == null) return
|
||||
errorText.value = validateProxyEntry(draft)
|
||||
if (errorText.value) return
|
||||
const payload = buildProxyEntryPayload(draft)
|
||||
if (!payload) {
|
||||
errorText.value = '代理配置不完整,请重新填写'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
await saveUserSecretModule(props.userId, PROXY_MODULE_KEY, payload.value, payload.channel)
|
||||
showAdminFeedback(props.locked ? '已更新锁定代理' : '已代填并锁定代理', 'success')
|
||||
emit('saved')
|
||||
close()
|
||||
} catch (error) {
|
||||
// 文案以接口返回的 message 为准,前端不解释后端状态码
|
||||
errorText.value = actionableErrorText(error)
|
||||
showAdminFeedback(errorText.value, 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
Object.assign(draft, { authkey: '', authpwd: '', link: '' })
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="modelValue" class="modal-mask" @click.self="close">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="proxy-entry-title">
|
||||
<h3 id="proxy-entry-title">{{ locked ? '改代理' : '代填代理' }}</h3>
|
||||
<p class="modal-note">
|
||||
为「{{ username || '该用户' }}」写入代理。出于凭据保护,后台不再下发已存的提取链接原文,
|
||||
这里每次都重新填写;保存后界面只显示脱敏后的地址(不含 key/pwd)。
|
||||
</p>
|
||||
|
||||
<div class="form-group">
|
||||
<label>代理供应商</label>
|
||||
<div class="radio-row">
|
||||
<label class="radio-item">
|
||||
<input v-model="draft.provider" type="radio" value="qingguo" />
|
||||
<span>青果</span>
|
||||
</label>
|
||||
<label class="radio-item">
|
||||
<input v-model="draft.provider" type="radio" value="jikip" />
|
||||
<span>极客</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="draft.provider === 'qingguo'">
|
||||
<div class="form-group">
|
||||
<label>Authkey</label>
|
||||
<input v-model="draft.authkey" type="text" autocomplete="off" placeholder="青果产品页的 Authkey" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Authpwd</label>
|
||||
<input v-model="draft.authpwd" type="password" autocomplete="new-password" placeholder="青果产品页的 Authpwd" />
|
||||
<span class="field-hint">青果只填 Authkey 会被判鉴权拒绝,两把都要填。</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="form-group">
|
||||
<label>极客提取链接</label>
|
||||
<input
|
||||
v-model="draft.link"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
placeholder="https://api.jikip.com/ip-get?..."
|
||||
/>
|
||||
<span class="field-hint">极客有可复制的提取链接,整条粘贴进来即可。</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p v-if="errorText" class="modal-error">{{ errorText }}</p>
|
||||
<div class="modal-actions">
|
||||
<button class="btn" type="button" :disabled="busy" @click="save">
|
||||
{{ busy ? '保存中…' : '保存' }}
|
||||
</button>
|
||||
<button class="btn btn-ghost" type="button" :disabled="busy" @click="close">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 与密钥列表页同一视觉语言(本页不用 el-* 标签:新增 el-* 要同步改按需注册表)。 */
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(520px, 100%);
|
||||
max-height: 84vh;
|
||||
padding: 22px 24px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
|
||||
overflow-y: auto;
|
||||
color: #24384d;
|
||||
font-family: inherit;
|
||||
}
|
||||
.modal h3 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.modal-note {
|
||||
margin: 0 0 14px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input[type='text'],
|
||||
.form-group input[type='password'] {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.radio-row {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
}
|
||||
.radio-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 500;
|
||||
color: #24384d;
|
||||
}
|
||||
.field-hint {
|
||||
color: #7d8fa1;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.modal-error {
|
||||
margin: 0 0 10px;
|
||||
color: #b04a5a;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-ghost {
|
||||
background: #ffffff;
|
||||
border-color: #c7d7e5;
|
||||
color: #4f78a5;
|
||||
}
|
||||
</style>
|
||||
@@ -3,16 +3,22 @@ import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import ProxyEntryDialog from './ProxyEntryDialog.vue'
|
||||
import {
|
||||
checkUserSecret,
|
||||
clearUserSecretModule,
|
||||
deleteUserSecret,
|
||||
fetchUserSecretList,
|
||||
saveUserSecretModule,
|
||||
type AdminUserSecretModule,
|
||||
type AdminUserSecretRow,
|
||||
type GroupOption,
|
||||
} from '@/api/user-secrets'
|
||||
import {
|
||||
PROXY_MODULE_KEY,
|
||||
llmSourceLabel,
|
||||
proxyDisplayText,
|
||||
proxySourceLabel,
|
||||
} from './user-secret-model.ts'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
@@ -37,8 +43,10 @@ const groupFilter = ref<number | null>(null)
|
||||
const groupOptions = ref<GroupOption[]>([])
|
||||
/** 正在检测的行 userId,用于按钮 loading 态。 */
|
||||
const checkingId = ref<number | null>(null)
|
||||
/** 正在代填/解锁代理的行 userId,避免重复点击。 */
|
||||
/** 正在解锁代理的行 userId,避免重复点击(代填在弹窗里自己管 busy)。 */
|
||||
const proxyBusyId = ref<number | null>(null)
|
||||
/** 代填/改代理弹窗的目标行(脱敏后没有原文可预填,只能重填账密)。 */
|
||||
const proxyDialog = ref<{ userId: number; username: string; provider: string | null; locked: boolean } | null>(null)
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
@@ -87,32 +95,28 @@ function moduleStatusMeta(module: AdminUserSecretModule | undefined) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 单格悬停详情:完整值(代理为全量地址)+ 锁定说明 + 检测消息 + 检测时间 + 耗时。 */
|
||||
/**
|
||||
* 单格悬停详情:后端下发的**脱敏值** + 锁定说明 + 检测消息 + 检测时间 + 耗时。
|
||||
* ⚠ 只读 `masked`:`full` 在后台侧恒空(2026-11-02 `SecretMasking.maskProxy` 收口),
|
||||
* 这里不做任何「masked 空就回落原文」的兜底,也不给复制整条链接的旁路。
|
||||
*/
|
||||
function moduleTooltip(module: AdminUserSecretModule | undefined) {
|
||||
if (!module || !module.exists) return '未配置'
|
||||
const parts: string[] = []
|
||||
if (module.full) parts.push(module.full)
|
||||
if (module.locked) parts.push('已由后台代填并锁定:客户端不可修改或清空')
|
||||
const display = String(module.masked || '').trim()
|
||||
if (display) {
|
||||
parts.push(isProxyModule(module) ? `代理地址(已脱敏,不含 key/pwd):${display}` : `密钥:${display}`)
|
||||
}
|
||||
if (module.locked) parts.push('已由后台代填并锁定:客户端不可修改或清空,改代理需重新填写账密')
|
||||
if (module.checkMessage) parts.push(module.checkMessage)
|
||||
if (module.checkedAt) parts.push(`检测时间:${formatDateTime(module.checkedAt)}`)
|
||||
if (module.checkLatencyMs != null) parts.push(`耗时:${module.checkLatencyMs}ms`)
|
||||
return parts.join(';') || '暂无检测记录'
|
||||
}
|
||||
|
||||
/** 货源标签:LLM 密钥显示渠道(龙抬头/贞贞),代理显示供应商(青果/极客)。 */
|
||||
function sourceLabel(channel: string | null | undefined) {
|
||||
switch (String(channel || '').trim().toLowerCase()) {
|
||||
case 'longtaitou':
|
||||
return '龙抬头'
|
||||
case 't8star':
|
||||
return '贞贞'
|
||||
case 'qingguo':
|
||||
return '青果'
|
||||
case 'jikip':
|
||||
return '极客'
|
||||
default:
|
||||
return '—'
|
||||
}
|
||||
/** 该格是不是代理模块:按后端下发的 moduleKey 判,货源标签与文案都走这一条口径。 */
|
||||
function isProxyModule(module: AdminUserSecretModule) {
|
||||
return String(module.moduleKey || '').trim().toLowerCase() === PROXY_MODULE_KEY
|
||||
}
|
||||
|
||||
/** 分组列文案:优先分组名;未建分组的用户回退展示所属主管,便于判断归属。 */
|
||||
@@ -206,38 +210,33 @@ async function remove(row: AdminUserSecretRow) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 代填并锁定代理:写入后客户端只能查看,修改/清空会被服务端拒绝。 */
|
||||
async function fillProxy(row: AdminUserSecretRow) {
|
||||
const who = row.username || `UID ${row.userId}`
|
||||
const value = window.prompt(
|
||||
`代填「${who}」的代理地址(保存后客户端不可修改或清空,如需变更先解锁):`,
|
||||
row.proxy?.full || '',
|
||||
)
|
||||
if (value == null) return
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) {
|
||||
ElMessage.warning('代理地址不能为空')
|
||||
return
|
||||
}
|
||||
proxyBusyId.value = row.userId
|
||||
try {
|
||||
await saveUserSecretModule(row.userId, 'proxy', trimmed)
|
||||
ElMessage.success(row.proxy?.locked ? '已更新锁定代理' : '已代填并锁定代理')
|
||||
load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '代填失败', 'error')
|
||||
} finally {
|
||||
proxyBusyId.value = null
|
||||
/**
|
||||
* 打开代填/改代理弹窗。
|
||||
* ⚠ 不预填任何已有值:后台侧 `full` 恒空(代理链接里带着 key/pwd,2026-11-02 收口后不再下发),
|
||||
* 所以这一单的语义就是「重新填账密」,界面上也没有把原文取回来的旁路。
|
||||
*/
|
||||
function openProxyDialog(row: AdminUserSecretRow) {
|
||||
proxyDialog.value = {
|
||||
userId: row.userId,
|
||||
username: row.username || `UID ${row.userId}`,
|
||||
provider: row.proxy?.channel ?? null,
|
||||
locked: Boolean(row.proxy?.locked),
|
||||
}
|
||||
}
|
||||
|
||||
/** 弹窗保存成功:关掉并重新取数(列表只拿脱敏值,不参与拼装)。 */
|
||||
function onProxySaved() {
|
||||
proxyDialog.value = null
|
||||
load()
|
||||
}
|
||||
|
||||
/** 解锁代理:清空后台代填值,该用户恢复自行配置。 */
|
||||
async function unlockProxy(row: AdminUserSecretRow) {
|
||||
const who = row.username || `UID ${row.userId}`
|
||||
if (!(await openAdminConfirm({ message: `确定解除「${who}」的代理锁定吗?解锁后当前后台代理值会被清空,客户端恢复自行配置。`, danger: true }))) return
|
||||
proxyBusyId.value = row.userId
|
||||
try {
|
||||
await clearUserSecretModule(row.userId, 'proxy')
|
||||
await clearUserSecretModule(row.userId, PROXY_MODULE_KEY)
|
||||
ElMessage.success('已解锁')
|
||||
load()
|
||||
} catch (error) {
|
||||
@@ -328,7 +327,7 @@ onMounted(load)
|
||||
<span v-if="row.similarAsin?.exists" class="mono-mask" :title="moduleTooltip(row.similarAsin)">{{ row.similarAsin.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span v-if="row.similarAsin?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
|
||||
{{ sourceLabel(row.similarAsin.channel) }}
|
||||
{{ llmSourceLabel(row.similarAsin.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusMeta(row.similarAsin).tone" :title="moduleTooltip(row.similarAsin)">
|
||||
{{ moduleStatusMeta(row.similarAsin).label }}
|
||||
@@ -340,7 +339,7 @@ onMounted(load)
|
||||
<span v-if="row.appearancePatent?.exists" class="mono-mask" :title="moduleTooltip(row.appearancePatent)">{{ row.appearancePatent.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span v-if="row.appearancePatent?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
|
||||
{{ sourceLabel(row.appearancePatent.channel) }}
|
||||
{{ llmSourceLabel(row.appearancePatent.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusMeta(row.appearancePatent).tone" :title="moduleTooltip(row.appearancePatent)">
|
||||
{{ moduleStatusMeta(row.appearancePatent).label }}
|
||||
@@ -349,11 +348,11 @@ onMounted(load)
|
||||
</td>
|
||||
<td>
|
||||
<div class="module-cell module-cell--stack">
|
||||
<span v-if="row.proxy?.exists" class="mono-mask mono-full" :title="moduleTooltip(row.proxy)">{{ row.proxy.full || row.proxy.masked }}</span>
|
||||
<span v-if="row.proxy?.exists" class="mono-mask" :title="moduleTooltip(row.proxy)">{{ proxyDisplayText(row.proxy) }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span class="module-cell-pills">
|
||||
<span v-if="row.proxy?.exists" class="wh-pill is-source" title="该用户代理所属供应商">
|
||||
{{ sourceLabel(row.proxy.channel) }}
|
||||
{{ proxySourceLabel(row.proxy.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusMeta(row.proxy).tone" :title="moduleTooltip(row.proxy)">
|
||||
{{ moduleStatusMeta(row.proxy).label }}
|
||||
@@ -387,8 +386,7 @@ onMounted(load)
|
||||
<button
|
||||
class="btn btn-sm btn-ghost"
|
||||
type="button"
|
||||
:disabled="proxyBusyId === row.userId"
|
||||
@click="fillProxy(row)"
|
||||
@click="openProxyDialog(row)"
|
||||
>
|
||||
{{ row.proxy?.locked ? '改代理' : '代填代理' }}
|
||||
</button>
|
||||
@@ -416,6 +414,16 @@ onMounted(load)
|
||||
</div>
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<ProxyEntryDialog
|
||||
:model-value="proxyDialog != null"
|
||||
:user-id="proxyDialog?.userId ?? null"
|
||||
:username="proxyDialog?.username ?? ''"
|
||||
:provider="proxyDialog?.provider ?? null"
|
||||
:locked="Boolean(proxyDialog?.locked)"
|
||||
@update:model-value="(open: boolean) => { if (!open) proxyDialog = null }"
|
||||
@saved="onProxySaved"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -601,7 +609,7 @@ h3 {
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
/* 代理列:完整地址独占一行,状态药丸另起一行,避免长地址被药丸挤压折行 */
|
||||
/* 代理列:脱敏地址独占一行,状态药丸另起一行(列宽按最长药丸文案留的,不按整条链接) */
|
||||
.module-cell--stack {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
@@ -612,18 +620,9 @@ h3 {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
/* 代理列展示完整明文:允许折行显示,不截断、不省略 */
|
||||
.module-cell .mono-full {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.45;
|
||||
cursor: text;
|
||||
user-select: all;
|
||||
}
|
||||
/* 代理列只显示后端脱敏后的 scheme://host(短串,单行足够)。
|
||||
这里**不许**再出现"允许折行展示完整明文 + user-select:all"那套样式:
|
||||
它等于给整条带 key/pwd 的链接做了一键全选复制的旁路(2026-11-02 脱敏收口时一并拆掉)。 */
|
||||
.mono-mask {
|
||||
font-family: Consolas, "Cascadia Mono", monospace;
|
||||
font-size: 12.5px;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 密钥管理页的纯逻辑模型(货源标签 + 代理重填)。
|
||||
*
|
||||
* 两条收口都在这个文件里,页模板只调这里导出的函数,不各写各的字典:
|
||||
*
|
||||
* 1. **货源标签按模块分字典**(2026-11-02 修):原先 `UserSecretsPage.vue` 里是一整张
|
||||
* `sourceLabel()`,把 LLM 渠道(longtaitou/t8star)与代理供应商(qingguo/jikip)混在同一个
|
||||
* switch 上,于是「按值匹配」的字典会把它认识的**任何**值贴到**任何**列上——代理行因此能长出
|
||||
* 「龙抬头」这种标签。后端 VO 的 `channel` 本来就是按模块归一的(`UserSecretModule.channelOrDefault`
|
||||
* 代理走 `ProxyProvider`、密钥走 `LlmChannel`),所以错标只会来自前端这张合表。
|
||||
* 现在两张表互不相通:代理列只认供应商、密钥列只认渠道,跨域的值一律落到「—」而不是被硬认下来。
|
||||
*
|
||||
* 2. **代理列不再显示、也不再回传原文**(2026-11-02 后端 `SecretMasking.maskProxy` 收口):
|
||||
* `AdminUserSecretModuleVo.full` 后台侧恒为空,界面只读 `masked`(`scheme://host`,不含
|
||||
* key/pwd)。因此原先「代填/改代理」用 `window.prompt` 预填整条链接的交互已失效
|
||||
* (预填必然是空的,保存还会把空串顶上去)——改成重新填账密:青果填 Authkey/Authpwd、
|
||||
* 由 `composeQingguoLink` 现拼;极客按其产品口径填自家提取链接。
|
||||
* ⚠ 拼出来的链接是一次性写请求的载荷,**不得**回显、回填、进 tooltip、进剪贴板。
|
||||
*
|
||||
* 零 `@/` 别名依赖:本文件被 `node --test` 直测(那颗 runner 不认 Vite 别名)。
|
||||
*/
|
||||
import { composeQingguoLink } from '../../shared/utils/qingguo-link.ts'
|
||||
|
||||
export type LlmChannelKey = 'longtaitou' | 't8star'
|
||||
export type ProxyProviderKey = 'qingguo' | 'jikip'
|
||||
|
||||
/** 代理模块 key(与后端 `UserSecretModule.PROXY.key()` 同值):写请求的路径段与「这一格是代理」的判据。 */
|
||||
export const PROXY_MODULE_KEY = 'proxy'
|
||||
|
||||
/** 后端 `ProxyProvider.DEFAULT`=极客:新建默认极客,青果手动切(2026-10-30 拍板)。 */
|
||||
export const DEFAULT_PROXY_PROVIDER: ProxyProviderKey = 'jikip'
|
||||
|
||||
/** 认不出的货源一律这个占位,不许回退成"某个具体渠道名"(那正是错标的来源)。 */
|
||||
export const UNKNOWN_SOURCE_LABEL = '—'
|
||||
|
||||
const LLM_CHANNEL_LABELS: Record<LlmChannelKey, string> = {
|
||||
longtaitou: '龙抬头',
|
||||
t8star: '贞贞',
|
||||
}
|
||||
|
||||
const PROXY_PROVIDER_LABELS: Record<ProxyProviderKey, string> = {
|
||||
qingguo: '青果',
|
||||
jikip: '极客',
|
||||
}
|
||||
|
||||
function normalizeKey(raw: unknown): string {
|
||||
return String(raw ?? '').trim().toLowerCase()
|
||||
}
|
||||
|
||||
function known<T extends string>(table: Record<T, string>, raw: unknown): string | null {
|
||||
const key = normalizeKey(raw)
|
||||
return Object.prototype.hasOwnProperty.call(table, key)
|
||||
? table[key as T]
|
||||
: null
|
||||
}
|
||||
|
||||
/** LLM 密钥列的渠道名:只查 LLM 字典,代理供应商的值在这里认不出。 */
|
||||
export function llmSourceLabel(channel: string | null | undefined): string {
|
||||
return known(LLM_CHANNEL_LABELS, channel) ?? UNKNOWN_SOURCE_LABEL
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理列的供应商名:只查供应商字典。
|
||||
* 传进 LLM 渠道值(`longtaitou`/`t8star`)必须返回占位——这条是"代理行贴龙抬头"的直接判据。
|
||||
*/
|
||||
export function proxySourceLabel(channel: string | null | undefined): string {
|
||||
return known(PROXY_PROVIDER_LABELS, channel) ?? UNKNOWN_SOURCE_LABEL
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一为可选供应商;未知值不猜,返回 null 让调用方保持原选择。
|
||||
*/
|
||||
export function asProxyProvider(raw: unknown): ProxyProviderKey | null {
|
||||
const key = normalizeKey(raw)
|
||||
return key === 'qingguo' || key === 'jikip' ? key : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理列的唯一显示文本:后端下发的 `masked`(青果形状 `https://overseas.proxy.qg.net`)。
|
||||
* 刻意**不读** `full`,也不做任何"masked 空就回落到原文"的兜底——回落等于把脱敏前的行为留在界面里。
|
||||
*/
|
||||
export function proxyDisplayText(module: { masked?: string | null } | null | undefined): string {
|
||||
const masked = String(module?.masked ?? '').trim()
|
||||
return masked || UNKNOWN_SOURCE_LABEL
|
||||
}
|
||||
|
||||
/** 代填/改代理的表单草稿:青果用前三个字段,极客用 `link`。 */
|
||||
export interface ProxyEntryDraft {
|
||||
provider: ProxyProviderKey
|
||||
authkey: string
|
||||
authpwd: string
|
||||
link: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 空草稿:`provider` 用后端已登记的那一列预置(只是选中的单选框,不是凭据),
|
||||
* 三个输入位**一律空**——脱敏后没有任何原文可回填。
|
||||
*/
|
||||
export function emptyProxyEntryDraft(currentProvider?: string | null): ProxyEntryDraft {
|
||||
return {
|
||||
provider: asProxyProvider(currentProvider) ?? DEFAULT_PROXY_PROVIDER,
|
||||
authkey: '',
|
||||
authpwd: '',
|
||||
link: '',
|
||||
}
|
||||
}
|
||||
|
||||
/** 与后端 `PROXY_FORMAT_HINT` 同一句口径:本函数只做前置提示,真判仍在服务端。 */
|
||||
const PROXY_LINK_FORMAT_HINT =
|
||||
'代理地址格式不正确,请填写 http://host:port 形式的代理地址,或代理服务商的提取链接(https://...)'
|
||||
|
||||
/** http(s) + 有主机名:镜像后端 `validateProxyValue`,不在前端扩大判死范围。 */
|
||||
function isHttpUrl(raw: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(raw)
|
||||
return (parsed.protocol === 'http:' || parsed.protocol === 'https:') && Boolean(parsed.hostname)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验草稿,返回给界面显示的文案(空串=可以提交)。
|
||||
* 点名"缺哪把":缺 pwd 时青果回 `API_AUTH_DENY`,所以两把都得填,不能只填 key 就当配好了。
|
||||
*/
|
||||
export function validateProxyEntry(draft: ProxyEntryDraft): string {
|
||||
if (!asProxyProvider(draft.provider)) return '请选择代理供应商'
|
||||
if (draft.provider === 'qingguo') {
|
||||
if (!String(draft.authkey || '').trim()) return '请填写青果 Authkey'
|
||||
if (!String(draft.authpwd || '').trim()) return '请填写青果 Authpwd(只填 Authkey 青果会判鉴权拒绝)'
|
||||
return ''
|
||||
}
|
||||
const link = String(draft.link || '').trim()
|
||||
if (!link) return '请填写极客提取链接'
|
||||
if (!isHttpUrl(link)) return PROXY_LINK_FORMAT_HINT
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装 PUT `/api/admin/user-secrets/{userId}/modules/proxy` 的请求体。
|
||||
* 不合法返回 null(调用方不得把 null 顶上去,更不得拿旧值凑数)。
|
||||
*/
|
||||
export function buildProxyEntryPayload(
|
||||
draft: ProxyEntryDraft,
|
||||
): { value: string; channel: ProxyProviderKey } | null {
|
||||
if (validateProxyEntry(draft)) return null
|
||||
if (draft.provider === 'qingguo') {
|
||||
return { value: composeQingguoLink(draft.authkey, draft.authpwd), channel: 'qingguo' }
|
||||
}
|
||||
return { value: String(draft.link || '').trim(), channel: 'jikip' }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 青果提取链接的拼装(后管侧镜像)。
|
||||
*
|
||||
* 正本在**用户端那棵前端树**的同名文件 `src/shared/utils/qingguo-link.ts`。两棵前端树各自独立构建
|
||||
* (各自的 vite root 与 tsconfig include),跨树 import 会把用户端拖进后管的产物图(本仓
|
||||
* `src/config/workspace.ts` 的边界尺子也判这种耦合为违规),所以这里按**同名同形**镜像一份,
|
||||
* 而不是另起一套新逻辑:口径只有一条
|
||||
* `https://overseas.proxy.qg.net/get?key=<Authkey>&pwd=<Authpwd>`
|
||||
* 改这一条 URL 时必须两边同改(用户端那份有 `node --test` 判据钉着)。
|
||||
*
|
||||
* 业务背景(2026-10-31 用户口径、2026-11-02 后台脱敏收口):青果**没有**可填的提取链接,
|
||||
* 产品页只给 Authkey / Authpwd 两个值;后台「代填/改代理」因此改成收这两个值、在这里拼,
|
||||
* 界面上任何时候都不再把拼好的链接回显或留档(链接里带着 pwd)。
|
||||
*
|
||||
* ⚠ 本文件保持**零依赖**:`node --test` 不认 Vite 的 `@/` 别名,带别名的模块进不了
|
||||
* `tests/*.test.ts`,这条拼装规则就没法被用例钉住。
|
||||
*/
|
||||
export const QINGGUO_EXTRACT_URL = 'https://overseas.proxy.qg.net/get'
|
||||
|
||||
export function composeQingguoLink(account: string, password: string): string {
|
||||
const key = (account || '').trim()
|
||||
if (!key) return ''
|
||||
const pwd = (password || '').trim()
|
||||
const query = `key=${encodeURIComponent(key)}` + (pwd ? `&pwd=${encodeURIComponent(pwd)}` : '')
|
||||
return `${QINGGUO_EXTRACT_URL}?${query}`
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* 密钥管理列表页的脱敏与货源标签判据(2026-11-02 后端 `SecretMasking.maskProxy` 收口的界面侧)。
|
||||
*
|
||||
* 跑真组件+真 pinia store,API 用假数据顶掉:夹具里那条 `full` **故意带着假账密**
|
||||
* (形状等同收口前的旧回包),用来证明界面这一侧不会把原文渲染出来——后端不下发是必要条件,
|
||||
* 但界面留着 `row.proxy.full || row.proxy.masked` 那种回落时,旧包/灰度包照样会漏。
|
||||
*
|
||||
* 假值一律 fakekey/fakepwd(本仓有尺子按长度+高熵认凭据,长十六进制串哪怕编的也会点红)。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/user-secret-proxy-mask.mount.test.ts`
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia, type Pinia } from 'pinia'
|
||||
|
||||
import UserSecretsPage from '@/pages/account/UserSecretsPage.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
|
||||
const secretsApi = vi.hoisted(() => ({
|
||||
fetchUserSecretList: vi.fn(),
|
||||
checkUserSecret: vi.fn(),
|
||||
deleteUserSecret: vi.fn(),
|
||||
saveUserSecretModule: vi.fn(),
|
||||
clearUserSecretModule: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/user-secrets', () => secretsApi)
|
||||
|
||||
const FAKE_KEY = 'fakekey'
|
||||
const FAKE_PWD = 'fakepwd'
|
||||
/** 收口前的旧回包形状:整条青果提取链接原文,查询段里带着 key/pwd。 */
|
||||
const LEGACY_PROXY_LINK = `https://overseas.proxy.qg.net/get?key=${FAKE_KEY}&pwd=${FAKE_PWD}`
|
||||
/** 收口后后端实际下发的脱敏值。 */
|
||||
const MASKED_PROXY = 'https://overseas.proxy.qg.net'
|
||||
|
||||
function moduleCell(moduleKey: string, over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
moduleKey,
|
||||
moduleLabel: moduleKey,
|
||||
channel: null,
|
||||
masked: 'abcd****wxyz',
|
||||
full: '',
|
||||
exists: true,
|
||||
locked: false,
|
||||
checkStatus: 'passed',
|
||||
checkCode: '',
|
||||
checkMessage: '',
|
||||
checkLatencyMs: 12,
|
||||
checkedAt: '2026-11-02T10:00:00',
|
||||
updatedAt: '2026-11-02T10:00:00',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function row(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
userId: 7,
|
||||
username: 'alice',
|
||||
groups: [],
|
||||
leaderUsername: '',
|
||||
similarAsin: moduleCell('similar-asin'),
|
||||
appearancePatent: moduleCell('appearance-patent'),
|
||||
proxy: moduleCell('proxy', { masked: MASKED_PROXY }),
|
||||
status: 'passed',
|
||||
statusMessage: '',
|
||||
createdAt: '2026-11-01T09:00:00',
|
||||
updatedAt: '2026-11-02T10:00:00',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function pageOf(items: unknown[]) {
|
||||
return { items, total: items.length, page: 1, pageSize: 15, groupOptions: [] }
|
||||
}
|
||||
|
||||
/** 按表头文字取该行对应 <td> 的文本(不靠列序数:加列就会全体错位)。 */
|
||||
function cellText(wrapper: ReturnType<typeof mount>, header: string): string {
|
||||
const headers = wrapper.findAll('thead th').map((th) => th.text().trim())
|
||||
const index = headers.findIndex((label) => label.includes(header))
|
||||
expect(index, `表头里找不到「${header}」`).toBeGreaterThanOrEqual(0)
|
||||
return wrapper.findAll('tbody tr')[0].findAll('td')[index].text()
|
||||
}
|
||||
|
||||
describe('密钥管理页:代理列脱敏+货源标签分域', () => {
|
||||
let pinia: Pinia
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
useCompanyTabStore().setActiveId(1)
|
||||
})
|
||||
|
||||
async function mountWith(proxyChannel: string | null, fullValue: string = LEGACY_PROXY_LINK) {
|
||||
secretsApi.fetchUserSecretList.mockResolvedValue(pageOf([
|
||||
row({
|
||||
similarAsin: moduleCell('similar-asin', { channel: 'longtaitou' }),
|
||||
appearancePatent: moduleCell('appearance-patent', { channel: 't8star' }),
|
||||
proxy: moduleCell('proxy', { channel: proxyChannel, masked: MASKED_PROXY, full: fullValue }),
|
||||
}),
|
||||
]))
|
||||
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
it('代理列不渲染 key/pwd:整棵树(含 title 属性)都没有这两个值', async () => {
|
||||
const wrapper = await mountWith('qingguo')
|
||||
const markup = wrapper.html()
|
||||
expect(markup).not.toContain(FAKE_KEY)
|
||||
expect(markup).not.toContain(FAKE_PWD)
|
||||
expect(markup).not.toContain('key=')
|
||||
expect(markup).not.toContain('pwd=')
|
||||
// 脱敏值照常显示,页面不是把整列抹白了事
|
||||
expect(cellText(wrapper, '代理设置')).toContain(MASKED_PROXY)
|
||||
})
|
||||
|
||||
it('代理列即便拿到旧形状的回包也只显示 masked,不回落原文', async () => {
|
||||
const wrapper = await mountWith('qingguo', LEGACY_PROXY_LINK)
|
||||
expect(cellText(wrapper, '代理设置')).toContain(MASKED_PROXY)
|
||||
expect(cellText(wrapper, '代理设置')).not.toContain('get?')
|
||||
})
|
||||
|
||||
it('masked 为空时留占位符:不许把 full 当兜底渲染出来', async () => {
|
||||
// 后端对识别不了的形状(如无 host 的脏值)会给出空 masked;
|
||||
// 界面这一侧若写成 `masked || full`,脱敏就等于没做——这一支就是钉住那条回落。
|
||||
secretsApi.fetchUserSecretList.mockResolvedValue(pageOf([
|
||||
row({
|
||||
proxy: moduleCell('proxy', { channel: 'qingguo', masked: '', full: LEGACY_PROXY_LINK }),
|
||||
}),
|
||||
]))
|
||||
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
expect(cellText(wrapper, '代理设置')).toContain('—')
|
||||
expect(cellText(wrapper, '代理设置')).not.toContain(FAKE_KEY)
|
||||
expect(wrapper.html()).not.toContain(FAKE_KEY)
|
||||
expect(wrapper.html()).not.toContain(FAKE_PWD)
|
||||
})
|
||||
|
||||
it('代理行贴的是供应商,不是 LLM 渠道名;密钥行仍显示渠道名', async () => {
|
||||
const wrapper = await mountWith('qingguo')
|
||||
const proxyCell = cellText(wrapper, '代理设置')
|
||||
expect(proxyCell).toContain('青果')
|
||||
expect(proxyCell).not.toContain('龙抬头')
|
||||
expect(proxyCell).not.toContain('贞贞')
|
||||
expect(cellText(wrapper, '货源查询密钥')).toContain('龙抬头')
|
||||
expect(cellText(wrapper, '外观专利密钥')).toContain('贞贞')
|
||||
})
|
||||
|
||||
it('代理行的 channel 被写成 LLM 渠道值时也不许贴出渠道名(合表就是这么错的)', async () => {
|
||||
const wrapper = await mountWith('longtaitou')
|
||||
const proxyCell = cellText(wrapper, '代理设置')
|
||||
expect(proxyCell).not.toContain('龙抬头')
|
||||
// 认不出的货源留占位,而不是硬认下一个具体名字
|
||||
expect(proxyCell).toContain('—')
|
||||
// 同一行上的密钥列不受影响
|
||||
expect(cellText(wrapper, '货源查询密钥')).toContain('龙抬头')
|
||||
})
|
||||
|
||||
it('页面上没有把原文带出界面的旁路:无复制/导出整条代理链接的入口', async () => {
|
||||
const wrapper = await mountWith('qingguo')
|
||||
const labels = wrapper.findAll('button').map((button) => button.text().trim())
|
||||
expect(labels.some((label) => /复制|导出/.test(label)), `出现复制/导出入口:${labels.join('/')}`).toBe(false)
|
||||
})
|
||||
|
||||
it('「改代理」打开的是重填表单:三个输入位都空,不给原文预填', async () => {
|
||||
const wrapper = await mountWith('qingguo')
|
||||
const openButton = wrapper.findAll('button').find((button) => button.text().trim() === '代填代理')
|
||||
expect(openButton, '行内应有「代填代理」入口').toBeDefined()
|
||||
await openButton!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const inputs = wrapper.findAll('.modal input[type="text"], .modal input[type="password"]')
|
||||
expect(inputs.length, '弹窗里应有账密/链接输入位').toBeGreaterThan(0)
|
||||
for (const input of inputs) {
|
||||
expect((input.element as HTMLInputElement).value, '不得预填任何已有值').toBe('')
|
||||
}
|
||||
expect(wrapper.html()).not.toContain(FAKE_KEY)
|
||||
expect(wrapper.html()).not.toContain(FAKE_PWD)
|
||||
})
|
||||
|
||||
it('保存把现拼的链接与这一单的供应商一起发出去,界面不留原文', async () => {
|
||||
secretsApi.saveUserSecretModule.mockResolvedValue(moduleCell('proxy', { channel: 'qingguo' }))
|
||||
const wrapper = await mountWith('qingguo')
|
||||
const openButton = wrapper.findAll('button').find((button) => button.text().trim() === '代填代理')
|
||||
await openButton!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const fields = wrapper.findAll('.modal input[type="text"], .modal input[type="password"]')
|
||||
await fields[0].setValue(FAKE_KEY)
|
||||
await fields[1].setValue(FAKE_PWD)
|
||||
const saveButton = wrapper.findAll('.modal button').find((button) => button.text().trim() === '保存')
|
||||
expect(saveButton, '弹窗里应有「保存」').toBeDefined()
|
||||
await saveButton!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(secretsApi.saveUserSecretModule).toHaveBeenCalledTimes(1)
|
||||
const [userId, moduleKey, value, channel] = secretsApi.saveUserSecretModule.mock.calls[0]
|
||||
expect(userId).toBe(7)
|
||||
expect(moduleKey).toBe('proxy')
|
||||
expect(value).toBe(`https://overseas.proxy.qg.net/get?key=${FAKE_KEY}&pwd=${FAKE_PWD}`)
|
||||
expect(channel).toBe('qingguo')
|
||||
// 写请求发完,界面上仍然看不到那两个值
|
||||
expect(wrapper.html()).not.toContain(FAKE_KEY)
|
||||
expect(wrapper.html()).not.toContain(FAKE_PWD)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
DEFAULT_PROXY_PROVIDER,
|
||||
UNKNOWN_SOURCE_LABEL,
|
||||
buildProxyEntryPayload,
|
||||
emptyProxyEntryDraft,
|
||||
llmSourceLabel,
|
||||
proxyDisplayText,
|
||||
proxySourceLabel,
|
||||
validateProxyEntry,
|
||||
} from '../src/pages/account/user-secret-model.ts'
|
||||
import { QINGGUO_EXTRACT_URL, composeQingguoLink } from '../src/shared/utils/qingguo-link.ts'
|
||||
|
||||
// 密钥管理页(后管)两条收口的判据(2026-11-02):
|
||||
// ① 货源标签按模块分字典——代理列只认供应商,LLM 渠道名不许出现在代理行上;
|
||||
// ② 代理列只显示后端脱敏值(masked),界面既不回落原文、也没有可预填的整条链接。
|
||||
// 夹具里的 key/pwd 全是假值(fakekey/fakepwd),本仓有尺子按长度+高熵认凭据。
|
||||
|
||||
test('代理列只认供应商:LLM 渠道值在代理列认不出', () => {
|
||||
assert.equal(proxySourceLabel('qingguo'), '青果')
|
||||
assert.equal(proxySourceLabel('JIKIP'), '极客', '后端值大小写不一时应归一')
|
||||
assert.equal(proxySourceLabel(' qingguo '), '青果')
|
||||
// 这一条就是截图上「代理行贴了龙抬头」的形状:合表按值匹配会认下来,分表必须认不出
|
||||
assert.equal(proxySourceLabel('longtaitou'), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(proxySourceLabel('t8star'), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(proxySourceLabel(''), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(proxySourceLabel(null), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(proxySourceLabel(undefined), UNKNOWN_SOURCE_LABEL)
|
||||
})
|
||||
|
||||
test('LLM 列只认渠道:代理供应商名不许贴到密钥列上', () => {
|
||||
assert.equal(llmSourceLabel('longtaitou'), '龙抬头')
|
||||
assert.equal(llmSourceLabel('t8star'), '贞贞')
|
||||
assert.equal(llmSourceLabel('qingguo'), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(llmSourceLabel('jikip'), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(llmSourceLabel('nonsense'), UNKNOWN_SOURCE_LABEL)
|
||||
// 两张表除占位符外不得有任何共同输出:合表就是从这个性质破掉的
|
||||
const proxyLabels = ['qingguo', 'jikip'].map(proxySourceLabel)
|
||||
assert.deepEqual(proxyLabels.filter((label) => label !== UNKNOWN_SOURCE_LABEL), ['青果', '极客'])
|
||||
})
|
||||
|
||||
test('代理列文本只取 masked,绝不回落到原文字段', () => {
|
||||
const link = composeQingguoLink('fakekey', 'fakepwd')
|
||||
const masked = 'https://overseas.proxy.qg.net' // 后端 SecretMasking.maskProxy 的输出形状
|
||||
assert.equal(proxyDisplayText({ masked, full: '' }), masked)
|
||||
// 万一某个旧回包还带着 full:界面也不许把它渲染出来(回落原文=脱敏白做)
|
||||
assert.equal(proxyDisplayText({ masked, full: link }), masked)
|
||||
const shown = proxyDisplayText({ masked, full: link })
|
||||
assert.ok(!shown.includes('fakekey'), `显示文本里漏出了 key:${shown}`)
|
||||
assert.ok(!shown.includes('fakepwd'), `显示文本里漏出了 pwd:${shown}`)
|
||||
assert.ok(!shown.includes('get?'), `显示文本里漏出了提取链接的查询段:${shown}`)
|
||||
})
|
||||
|
||||
test('masked 为空时显示占位符,不猜原文', () => {
|
||||
assert.equal(proxyDisplayText({ masked: '', full: composeQingguoLink('fakekey', 'fakepwd') }), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(proxyDisplayText({ masked: null }), UNKNOWN_SOURCE_LABEL)
|
||||
assert.equal(proxyDisplayText(undefined), UNKNOWN_SOURCE_LABEL)
|
||||
})
|
||||
|
||||
test('青果链接拼装口径:overseas 域+key+pwd,特殊字符按 URL 组件编码', () => {
|
||||
assert.equal(composeQingguoLink('fakekey', 'fakepwd'), `${QINGGUO_EXTRACT_URL}?key=fakekey&pwd=fakepwd`)
|
||||
assert.equal(composeQingguoLink(' fakekey ', ' fakepwd '), `${QINGGUO_EXTRACT_URL}?key=fakekey&pwd=fakepwd`)
|
||||
// pwd 里的 @ 与 : 不编码会把 host 切歪(AGENTS 铁律 25 实录)
|
||||
const encoded = composeQingguoLink('fakekey', 'p@ss:1')
|
||||
assert.ok(encoded.includes('pwd=p%40ss%3A1'), encoded)
|
||||
})
|
||||
|
||||
test('改代理每次从空表开始:没有原文可预填', () => {
|
||||
const draft = emptyProxyEntryDraft('qingguo')
|
||||
assert.equal(draft.provider, 'qingguo')
|
||||
assert.deepEqual([draft.authkey, draft.authpwd, draft.link], ['', '', ''])
|
||||
// 供应商值认不出时不猜成凭据,只回落到后端默认供应商(极客)
|
||||
assert.equal(emptyProxyEntryDraft('longtaitou').provider, DEFAULT_PROXY_PROVIDER)
|
||||
assert.equal(emptyProxyEntryDraft(null).provider, DEFAULT_PROXY_PROVIDER)
|
||||
})
|
||||
|
||||
test('青果要两把都填:缺哪把就点名哪把', () => {
|
||||
assert.equal(validateProxyEntry({ provider: 'qingguo', authkey: '', authpwd: 'fakepwd', link: '' }), '请填写青果 Authkey')
|
||||
assert.match(validateProxyEntry({ provider: 'qingguo', authkey: 'fakekey', authpwd: ' ', link: '' }), /Authpwd/)
|
||||
assert.equal(validateProxyEntry({ provider: 'qingguo', authkey: 'fakekey', authpwd: 'fakepwd', link: '' }), '')
|
||||
assert.equal(buildProxyEntryPayload({ provider: 'qingguo', authkey: 'fakekey', authpwd: 'fakepwd', link: '' })?.value,
|
||||
composeQingguoLink('fakekey', 'fakepwd'))
|
||||
assert.equal(buildProxyEntryPayload({ provider: 'qingguo', authkey: 'fakekey', authpwd: '', link: '' }), null,
|
||||
'不合法时不得产出载荷(拿空串顶上去等于把配置清空)')
|
||||
})
|
||||
|
||||
test('极客填自家提取链接:形状与后端 validateProxyValue 同口径、不扩大判死', () => {
|
||||
const draft = { provider: 'jikip' as const, authkey: '', authpwd: '', link: 'https://api.example.test/ip-get?appkey=fakekey' }
|
||||
assert.equal(validateProxyEntry(draft), '')
|
||||
assert.deepEqual(buildProxyEntryPayload(draft), { value: 'https://api.example.test/ip-get?appkey=fakekey', channel: 'jikip' })
|
||||
assert.match(validateProxyEntry({ ...draft, link: '' }), /极客提取链接/)
|
||||
assert.match(validateProxyEntry({ ...draft, link: 'ftp://api.example.test/ip-get' }), /格式不正确/)
|
||||
assert.match(validateProxyEntry({ ...draft, link: 'not a url' }), /格式不正确/)
|
||||
// 静态代理地址(http://host:port)同样是后端认的形态,前端不许判死
|
||||
assert.equal(validateProxyEntry({ ...draft, link: 'http://1.2.3.4:8080' }), '')
|
||||
})
|
||||
|
||||
test('载荷带上这一单的供应商:channel 缺失会被后端按域名识别,识别不出就静默换供应商', () => {
|
||||
assert.equal(buildProxyEntryPayload({ provider: 'qingguo', authkey: 'fakekey', authpwd: 'fakepwd', link: '' })?.channel, 'qingguo')
|
||||
assert.equal(buildProxyEntryPayload({ provider: 'jikip', authkey: '', authpwd: '', link: 'https://api.example.test/ip-get' })?.channel, 'jikip')
|
||||
})
|
||||
@@ -33,7 +33,7 @@ public final class SecretMasking {
|
||||
try {
|
||||
URI uri = URI.create(value.trim());
|
||||
if (uri.getHost() == null || uri.getHost().isBlank()) {
|
||||
return mask(value);
|
||||
return hostOnlyOrHidden(value);
|
||||
}
|
||||
StringBuilder masked = new StringBuilder();
|
||||
masked.append(uri.getScheme() == null ? "http" : uri.getScheme()).append("://");
|
||||
@@ -46,7 +46,37 @@ public final class SecretMasking {
|
||||
}
|
||||
return masked.toString();
|
||||
} catch (Exception ex) {
|
||||
return mask(value);
|
||||
return hostOnlyOrHidden(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析不出 host 的代理串(无 scheme 的 {@code host/get?key=..&pwd=..}、脏值、纯凭据串)走这里。
|
||||
*
|
||||
* <p>不能套 {@link #mask}:它保前 4 <b>和后 4</b>,而青果链接的 {@code pwd=} 就挂在末尾——
|
||||
* 那等于把口令尾 4 位交给界面与日志(2026-11-02 后管「密钥管理」列的残余外漏形状)。
|
||||
* 这里只肯交出「像 host 的那一段」,其余一个字符都不给。</p>
|
||||
*/
|
||||
private static String hostOnlyOrHidden(String value) {
|
||||
String text = value.trim();
|
||||
int scheme = text.indexOf("://");
|
||||
String rest = scheme >= 0 ? text.substring(scheme + 3) : text;
|
||||
int at = rest.lastIndexOf('@');
|
||||
if (at >= 0) {
|
||||
rest = rest.substring(at + 1);
|
||||
}
|
||||
int cut = rest.length();
|
||||
for (char boundary : new char[]{'/', '?', '#'}) {
|
||||
int index = rest.indexOf(boundary);
|
||||
if (index >= 0) {
|
||||
cut = Math.min(cut, index);
|
||||
}
|
||||
}
|
||||
String host = rest.substring(0, cut);
|
||||
// 没有点号的不认 host(多半是裸凭据),带 = 的更可能是整串 query
|
||||
if (host.isBlank() || !host.contains(".") || host.contains("=")) {
|
||||
return "****";
|
||||
}
|
||||
return "****" + host;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -18,10 +18,10 @@ public class AdminUserSecretModuleVo {
|
||||
@Schema(description = "货源:LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip)")
|
||||
private String channel;
|
||||
|
||||
@Schema(description = "脱敏值")
|
||||
@Schema(description = "脱敏值(代理列为 scheme://host[:port],不含链接里的 key/pwd)")
|
||||
private String masked;
|
||||
|
||||
@Schema(description = "完整明文值:仅代理列返回(含账号密码),密钥列为空")
|
||||
@Schema(description = "完整明文值:后台侧一律不再下发(2026-11-02 收口,代理链接里带账密);字段保留只为界面兼容,恒为空")
|
||||
private String full;
|
||||
|
||||
@Schema(description = "是否已配置")
|
||||
|
||||
+138
-26
@@ -8,6 +8,7 @@ import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.config.SimilarAsinProperties;
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyLinkKey;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyProvider;
|
||||
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
|
||||
@@ -56,10 +57,25 @@ public class UserApiSecretCheckService {
|
||||
public static final String CODE_TIMEOUT = "timeout";
|
||||
public static final String CODE_PROVIDER_ERROR = "provider_error";
|
||||
public static final String CODE_INSUFFICIENT_BALANCE = "insufficient_balance";
|
||||
/**
|
||||
* 青果通道被占满({@code NO_AVAILABLE_CHANNEL}):隧道转发按存活周期只给一条通道,
|
||||
* 检测里这一次提取就是在抢通道;抢不到是「稍后再点」,不是「密钥坏了」,必须与
|
||||
* {@link #CODE_PROVIDER_ERROR} 分开——混成一个码,界面只能显示「无法判定」(现网 uid=1301)。
|
||||
*/
|
||||
public static final String CODE_CHANNEL_BUSY = "channel_busy";
|
||||
/** 隧道端点拿到了,但服务端组不出可验连的地址(链接未带 key/pwd,或账密含会切歪 host 的分隔符)。 */
|
||||
public static final String CODE_TUNNEL_UNVERIFIED = "tunnel_unverified";
|
||||
|
||||
/** 供应商欠费提示文案(前后端都按 code 识别展示)。 */
|
||||
public static final String INSUFFICIENT_BALANCE_MESSAGE = "代理服务商余额不足,请充值后重试";
|
||||
|
||||
/** 通道被自己占用的提示文案:说人话,并给出可执行的下一步(等存活周期释放)。 */
|
||||
public static final String CHANNEL_BUSY_MESSAGE = "青果通道正被你自己的采集占着,等约 3 分钟释放后再点检测";
|
||||
|
||||
/** 提取成功但服务端无法验连的提示文案:如实说"没验成",不拿它冒充 passed。 */
|
||||
public static final String TUNNEL_UNVERIFIED_MESSAGE = "青果提取成功,但这条链接里没有可用于隧道验连的 key/pwd,"
|
||||
+ "服务端无法确认代理是否可用(青果只支持账密档,请在密钥设置里补全提取链接)";
|
||||
|
||||
/** 超时与网络不可达提示文案:面向用户展示,技术细节只进服务端日志。 */
|
||||
public static final String TIMEOUT_MESSAGE = "检测超时:上游服务响应超时,请稍后重试";
|
||||
public static final String NETWORK_ERROR_MESSAGE = "网络不可达:无法连接上游服务,请检查网络后重试";
|
||||
@@ -78,6 +94,12 @@ public class UserApiSecretCheckService {
|
||||
private static final Pattern IP_PORT_PATTERN =
|
||||
Pattern.compile("(\\d{1,3}(?:\\.\\d{1,3}){3}):(\\d{2,5})");
|
||||
|
||||
/** 供应商文案里可能回显的凭据型查询参数(值一律盖掉)。 */
|
||||
private static final Pattern CREDENTIAL_PARAM_PATTERN =
|
||||
Pattern.compile("(?i)\\b(key|pwd|password|passwd|token|secret)=([^&\\s\"]+)");
|
||||
/** 短于这个长度的值不按原文替换:像 "0"/"ab" 这种会误伤正常文案。 */
|
||||
private static final int MIN_REDACT_LENGTH = 4;
|
||||
|
||||
private final AppearancePatentProperties appearancePatentProperties;
|
||||
private final SimilarAsinProperties similarAsinProperties;
|
||||
private final UserSecretProperties userSecretProperties;
|
||||
@@ -168,13 +190,19 @@ public class UserApiSecretCheckService {
|
||||
|
||||
/**
|
||||
* 代理配置探测(按「提取链接」语义,与品牌检测的实际用法一致):
|
||||
* 先 GET 用户链接真实提取一次——余额不足报余额不足、解析不出 IP 报配置错误;
|
||||
* 提取到 IP(可含账密)后经该代理请求一次自家域名,拿到任意 HTTP 响应即转发可用。
|
||||
* 先 GET 用户链接真实提取一次——余额不足报余额不足、通道占用报通道占用、解析不出 IP 报配置错误;
|
||||
* 提取到端点后经它请求一次自家域名,拿到任意 HTTP 响应才算转发可用。
|
||||
* 兼容纯静态代理地址(无 path/query 的 host:port)直接探测。
|
||||
*
|
||||
* <p>2026-09-13 修复:旧实现把提取链接直接交给 HttpClientPool 当静态代理使用,链接无
|
||||
* 显式端口时解析失败会静默回退直连,探测到的是自家站点的直连响应——40 个用户全部
|
||||
* 「假通过」(3-39ms + HTTP 301),余额不足 / 链接失效都测不出来。
|
||||
* 「假通过」(3-39ms + HTTP 301),余额不足 / 链接失效都测不出来。</p>
|
||||
*
|
||||
* <p>2026-11-02 修复(青果):那次修复只覆盖了极客,青果分支仍在看不到账密的借口下
|
||||
* 「提取成功=passed」短路。现在青果也走真实的经隧道转发探测,供应商返回码逐档落独立
|
||||
* code(见 {@link #classifyProviderRejection})。副作用要如实登记:这一次提取会占掉
|
||||
* 青果那唯一一条通道(存活周期约 3 分钟),所以「点检测」本身是有一次通道成本的,
|
||||
* 服务层的新鲜期复用({@code reuseFreshOutcome})是它唯一的挡箭牌。</p>
|
||||
*/
|
||||
private CheckOutcome probeProxy(String proxyUrl) {
|
||||
return probeProxy(proxyUrl, null);
|
||||
@@ -200,8 +228,8 @@ public class UserApiSecretCheckService {
|
||||
}
|
||||
|
||||
// 提取链接:先真实提取一次。刻意读响应体而不依赖 2xx——
|
||||
// 青果的失败码(API_AUTH_DENY / BALANCE_INSUFFICIENT)走 HTTP 4xx,
|
||||
// 交给 RestClient 抛异常会把「密钥没授权」误报成「接口无法访问」。
|
||||
// 青果的失败码(API_AUTH_DENY / BALANCE_INSUFFICIENT / NO_AVAILABLE_CHANNEL)走 HTTP 4xx,
|
||||
// 交给 RestClient 抛异常会把「密钥没授权」「通道被占」统统误报成「接口无法访问」。
|
||||
StatusAndBody extract;
|
||||
try {
|
||||
extract = clientFor(null).get().uri(normalized)
|
||||
@@ -216,7 +244,7 @@ public class UserApiSecretCheckService {
|
||||
"代理提取接口无法访问,请检查提取链接或稍后重试", (int) latency, false);
|
||||
}
|
||||
long extractLatency = System.currentTimeMillis() - startMillis;
|
||||
CheckOutcome rejection = classifyProviderRejection(provider, extract.body(), (int) extractLatency);
|
||||
CheckOutcome rejection = classifyProviderRejection(provider, extract.body(), (int) extractLatency, normalized);
|
||||
if (rejection != null) {
|
||||
log.warn("[user-secret][check] 代理提取被供应商拒绝 provider={} httpStatus={} code={}",
|
||||
provider.key(), extract.statusCode(), rejection.code());
|
||||
@@ -225,33 +253,95 @@ public class UserApiSecretCheckService {
|
||||
String extractedProxyUrl = extractProxyUrlFromBody(extract.body());
|
||||
if (extractedProxyUrl == null) {
|
||||
log.warn("[user-secret][check] 代理提取响应未解析出 IP provider={} httpStatus={} 响应前 150 字={}",
|
||||
provider.key(), extract.statusCode(), abbreviate(extract.body(), 150));
|
||||
provider.key(), extract.statusCode(),
|
||||
redactCredentials(abbreviate(extract.body(), 150), normalized));
|
||||
return new CheckOutcome(STATUS_FAILED, CODE_INVALID_KEY,
|
||||
"链接未返回可用 IP,请检查代理提取配置", (int) extractLatency, false);
|
||||
}
|
||||
if (provider == ProxyProvider.QINGGUO) {
|
||||
// 青果通道提取返回的是**隧道端点**(如 tunpool-xxx.qg.net:16359),连它要用
|
||||
// Authkey/Authpwd 做 Basic 认证,而这对账密只存在用户本机、不上报服务端;
|
||||
// 所以这里只验"提取接口可用且拿到端点",连接态由客户端的实际任务证明。
|
||||
log.info("[user-secret][check] 青果提取成功,跳过经隧道探测(端点鉴权在客户端)endpoint={}",
|
||||
SecretMasking.maskProxy(extractedProxyUrl));
|
||||
return new CheckOutcome(STATUS_PASSED, CODE_OK,
|
||||
"提取成功(青果隧道端点,连接鉴权在客户端)", (int) extractLatency, false);
|
||||
return probeQingguoTunnel(normalized, extractedProxyUrl, startMillis);
|
||||
}
|
||||
return probeThroughProxy(extractedProxyUrl, startMillis);
|
||||
}
|
||||
|
||||
/**
|
||||
* 青果隧道真探(2026-11-02 改):旧实现在这里短路返回 {@code passed/ok}「提取成功(青果隧道端点,
|
||||
* 连接鉴权在客户端)」,依据是「这对账密只存在用户本机、不上报服务端」——那句注释已经过期:
|
||||
* 青果只做账密档(AGENTS.md 铁律 25),用户填进来并存下来的提取链接里就带着 {@code key=} 与 {@code pwd=}。
|
||||
* 服务端既然拿得到凭据,就必须拿它经隧道打一次自家域名,否则「提取成功」永远冒充「代理可用」。
|
||||
* 现网 uid=1301(2026-11-02 13:08)是同一条路上另一半的坑:提取回 {@code NO_AVAILABLE_CHANNEL}
|
||||
* 被落成一坨 {@code provider_error},界面只剩「无法判定」——所以本方法连同
|
||||
* {@link #classifyProviderRejection} 一起改:探测要真打,失败要一档一码。
|
||||
*
|
||||
* <p>组出来的带鉴权地址只在内存里存在,日志与文案一律只出现 {@link SecretMasking#maskProxy} 之后的端点。</p>
|
||||
*/
|
||||
CheckOutcome probeQingguoTunnel(String extractLink, String endpointUrl, long startMillis) {
|
||||
String tunnelProxyUrl = qingguoTunnelProxyUrl(extractLink, endpointUrl);
|
||||
if (tunnelProxyUrl == null) {
|
||||
int latency = (int) (System.currentTimeMillis() - startMillis);
|
||||
log.warn("[user-secret][check] 青果隧道无法组链验连(链接未带可用 key/pwd)endpoint={}",
|
||||
SecretMasking.maskProxy(endpointUrl));
|
||||
return new CheckOutcome(STATUS_ERROR, CODE_TUNNEL_UNVERIFIED, TUNNEL_UNVERIFIED_MESSAGE, latency, false);
|
||||
}
|
||||
log.info("[user-secret][check] 青果隧道探测开始 endpoint={}(账密来自本条链接,不入日志)",
|
||||
SecretMasking.maskProxy(tunnelProxyUrl));
|
||||
return probeThroughProxy(tunnelProxyUrl, startMillis);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给青果隧道端点补上链接里的 key/pwd:补不出安全可解析的地址就返回 null(宁可不验,也不猜一条
|
||||
* 会把 host 切歪的地址——{@code pwd} 里含 {@code @}/{@code :} 时 userinfo 会吞掉主机名)。
|
||||
*/
|
||||
static String qingguoTunnelProxyUrl(String extractLink, String endpointUrl) {
|
||||
if (endpointUrl == null || !looksLikeStaticProxy(endpointUrl)) {
|
||||
return null;
|
||||
}
|
||||
String key = ProxyLinkKey.fromUrl(extractLink);
|
||||
String pwd = ProxyLinkKey.passwordFromUrl(extractLink);
|
||||
if (!urlSafeCredential(key) || !urlSafeCredential(pwd)) {
|
||||
return null;
|
||||
}
|
||||
int schemeEnd = endpointUrl.indexOf("://");
|
||||
if (schemeEnd < 0) {
|
||||
return null;
|
||||
}
|
||||
return endpointUrl.substring(0, schemeEnd + 3) + key + ":" + pwd + "@" + endpointUrl.substring(schemeEnd + 3);
|
||||
}
|
||||
|
||||
/** 能原样嵌进 userinfo 的凭据判定:URL 分隔符与控制字符/空白一律不算(青果的 Authkey/Authpwd 本就不含它们)。 */
|
||||
private static boolean urlSafeCredential(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c <= ' ' || c == ':' || c == '@' || c == '/' || c == '?' || c == '#' || c == '%' || c == '&') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商拒付/鉴权失败的独立分类(两家错误码词表不同):
|
||||
* <ul>
|
||||
* <li>青果:code 为字符串。BALANCE_INSUFFICIENT=余额不足;INVALID_KEY/UNAVAILABLE_KEY/KEY_BLOCK/
|
||||
* ACCESS_DENY/API_AUTH_DENY=密钥不可用或未授权;REQUEST_LIMIT_EXCEEDED=限流;
|
||||
* INVALID_PARAMETER=参数错;其余业务失败按上游异常。</li>
|
||||
* <li>青果:code 为字符串,逐码分档,**一档一个 code**——
|
||||
* BALANCE_INSUFFICIENT=余额不足;INVALID_KEY/UNAVAILABLE_KEY/KEY_BLOCK=密钥本身不可用;
|
||||
* API_AUTH_DENY/ACCESS_DENY=这一条链接的鉴权没过(多数是 pwd 没填);
|
||||
* NO_AVAILABLE_CHANNEL=通道被自己的采集占着({@link #CODE_CHANNEL_BUSY},稍后再点);
|
||||
* REQUEST_LIMIT_EXCEEDED=限流;INVALID_PARAMETER=参数错;其余业务失败按上游异常。</li>
|
||||
* <li>极客:沿用历史口径(code=-1 或 message 含「余额不足」=余额不足)。</li>
|
||||
* </ul>
|
||||
* 返回 null 表示不是拒付/鉴权类失败,继续走 IP 解析。
|
||||
*
|
||||
* <p>供应商文案可能整条回显请求链接(含 key/pwd),出口前一律过 {@link #redactCredentials}。</p>
|
||||
*/
|
||||
CheckOutcome classifyProviderRejection(ProxyProvider provider, String body, int latencyMs) {
|
||||
return classifyProviderRejection(provider, body, latencyMs, null);
|
||||
}
|
||||
|
||||
/** {@code extractLink} 只用于抹掉供应商文案里回显的本条链接凭据,不参与判定。 */
|
||||
CheckOutcome classifyProviderRejection(ProxyProvider provider, String body, int latencyMs, String extractLink) {
|
||||
if (provider == ProxyProvider.QINGGUO) {
|
||||
JsonNode root = parseJson(body);
|
||||
if (root == null || !root.isObject()) {
|
||||
@@ -262,21 +352,25 @@ public class UserApiSecretCheckService {
|
||||
if (code.isEmpty() || "SUCCESS".equalsIgnoreCase(code) || "0".equals(code)) {
|
||||
return null;
|
||||
}
|
||||
String message = text(root.get("message"));
|
||||
String message = redactCredentials(text(root.get("message")), extractLink);
|
||||
String detail = message == null || message.isBlank() ? "" : ":" + abbreviate(message, 120);
|
||||
String upper = code.toUpperCase(java.util.Locale.ROOT);
|
||||
return switch (upper) {
|
||||
case "BALANCE_INSUFFICIENT" ->
|
||||
new CheckOutcome(STATUS_FAILED, CODE_INSUFFICIENT_BALANCE, INSUFFICIENT_BALANCE_MESSAGE, latencyMs, false);
|
||||
case "INVALID_KEY", "UNAVAILABLE_KEY", "KEY_BLOCK", "ACCESS_DENY", "API_AUTH_DENY" ->
|
||||
new CheckOutcome(STATUS_FAILED, CODE_FORBIDDEN,
|
||||
"青果密钥不可用或未授权(" + upper + ")" + detail, latencyMs, false);
|
||||
case "REQUEST_LIMIT_EXCEEDED" ->
|
||||
new CheckOutcome(STATUS_ERROR, CODE_RATE_LIMITED, "青果提取触发限流,本次无法判定" + detail, latencyMs, false);
|
||||
case "NO_AVAILABLE_CHANNEL" ->
|
||||
// 通道被占满(存活期内一个通道只给一个端点):不是密钥问题,稍后重试即可
|
||||
new CheckOutcome(STATUS_ERROR, CODE_PROVIDER_ERROR,
|
||||
"青果通道已全部占用,请等当前通道释放(约 3 分钟)后重试" + detail, latencyMs, false);
|
||||
// 通道被占满(存活期内一个通道只给一个端点):不是密钥问题,等释放后重点一次即可
|
||||
new CheckOutcome(STATUS_ERROR, CODE_CHANNEL_BUSY, CHANNEL_BUSY_MESSAGE, latencyMs, false);
|
||||
case "INVALID_KEY", "UNAVAILABLE_KEY", "KEY_BLOCK" ->
|
||||
new CheckOutcome(STATUS_FAILED, CODE_INVALID_KEY,
|
||||
"青果密钥不可用或已失效(" + upper + "),请核对提取链接里的 key" + detail, latencyMs, false);
|
||||
case "API_AUTH_DENY", "ACCESS_DENY" ->
|
||||
new CheckOutcome(STATUS_FAILED, CODE_FORBIDDEN,
|
||||
"青果拒绝了这条链接的鉴权(" + upper + "),请检查提取链接里的 pwd(青果只支持账密档,pwd 必填)"
|
||||
+ detail, latencyMs, false);
|
||||
case "REQUEST_LIMIT_EXCEEDED" ->
|
||||
new CheckOutcome(STATUS_ERROR, CODE_RATE_LIMITED,
|
||||
"青果提取接口请求过于频繁(限流),请等约 1 分钟后再点检测" + detail, latencyMs, false);
|
||||
case "INVALID_PARAMETER" ->
|
||||
new CheckOutcome(STATUS_FAILED, CODE_BAD_REQUEST, "青果提取参数不正确" + detail, latencyMs, false);
|
||||
default ->
|
||||
@@ -289,6 +383,24 @@ public class UserApiSecretCheckService {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 抹掉文案里回显的链接凭据:先按参数名把 {@code key=…}/{@code pwd=…} 的值盖掉,
|
||||
* 再按这把 key/pwd 的原文逐处替换(供应商可能只回显裸值、不带参数名)。
|
||||
* 返回值用于日志与界面,绝不带凭据原文。
|
||||
*/
|
||||
static String redactCredentials(String text, String extractLink) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return text;
|
||||
}
|
||||
String redacted = CREDENTIAL_PARAM_PATTERN.matcher(text).replaceAll("$1=****");
|
||||
for (String secret : new String[]{ProxyLinkKey.fromUrl(extractLink), ProxyLinkKey.passwordFromUrl(extractLink)}) {
|
||||
if (secret != null && secret.length() >= MIN_REDACT_LENGTH && redacted.contains(secret)) {
|
||||
redacted = redacted.replace(secret, "****");
|
||||
}
|
||||
}
|
||||
return redacted;
|
||||
}
|
||||
|
||||
/** 经指定代理请求自家域名:任意 HTTP 响应即转发可用;407 为代理自身认证失败;网络异常不可达。 */
|
||||
private CheckOutcome probeThroughProxy(String proxyUrl, long startMillis) {
|
||||
try {
|
||||
|
||||
+22
-45
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.usersecret.service;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.text.SecretMasking;
|
||||
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
@@ -78,7 +79,6 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
public static final String ROW_STATUS_UNKNOWN = "unknown";
|
||||
|
||||
private static final String STATUS_UNKNOWN = "unknown";
|
||||
private static final int MASK_MIN_LENGTH = 8;
|
||||
private static final int MESSAGE_MAX_LENGTH = 500;
|
||||
/** 「输入值检测」结果暂存键前缀:保存同一个值时沿用该结果,避免用户检完还要再检一次。 */
|
||||
private static final String VERIFIED_KEY_PREFIX = "aiimage:user-secret-verified";
|
||||
@@ -711,6 +711,14 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
probed++;
|
||||
sleepQuietly(200L);
|
||||
}
|
||||
if (UserApiSecretCheckService.CODE_CHANNEL_BUSY.equals(outcome.code())) {
|
||||
// 通道被占不是「密钥坏了」:这一轮问不出结论,就既不改状态也不推通知。
|
||||
// 青果通道数只有 1 条(2026-11-02 控制台核实),而巡检本身就要占一条——
|
||||
// 若把 channel_busy 落库,用户早上看到的「代理异常」其实是我们自己 04:30
|
||||
// 那一枪把他的通道占了(现网 uid=1301 的「无法判定」就是这个形状)。
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
applyCheckOutcome(row.getUserId(), module.get().key(), outcome);
|
||||
checked++;
|
||||
if (adminAudience != null) {
|
||||
@@ -1157,6 +1165,10 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
.last("limit 1"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台侧的模块单元(列表行 + 代填回包):值一律脱敏,**不再下发代理明文**(见下方 2026-11-02 收口注释)。
|
||||
* 客户端侧另走 {@link #toItem}——那里锁定的代理要把完整地址发给配置的主人本人。
|
||||
*/
|
||||
private AdminUserSecretModuleVo toModuleVo(UserSecretModule module, UserApiSecretEntity row) {
|
||||
AdminUserSecretModuleVo vo = new AdminUserSecretModuleVo();
|
||||
vo.setModuleKey(module.key());
|
||||
@@ -1174,10 +1186,11 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
String plain = decryptQuietly(row.getSecretValue());
|
||||
vo.setChannel(module.channelOrDefault(row.getChannel(), plain));
|
||||
vo.setMasked(maskValue(module, plain));
|
||||
// 后台代理列要求完整可见(含账号密码),密钥列不下发明文
|
||||
if (module == UserSecretModule.PROXY) {
|
||||
vo.setFull(plain);
|
||||
}
|
||||
// 2026-11-02 收口:后台列表/代填回包一律**不再下发代理明文**(full 留空)。
|
||||
// 之前这一列把用户填的提取链接原文交给界面,而青果/极客的链接里就带着 key= 与 pwd=
|
||||
// ——等于把凭据摊在管理员屏幕、浏览器 DOM 与接口响应里(同页 LLM 列一直是脱敏的)。
|
||||
// 管理员要改代理只能重新粘贴完整链接(后管「改代理」的预填因此变空,属预期的行为收紧);
|
||||
// 客户端侧的锁定代理仍按 toItem 下发完整地址(那是用户自己的配置、发给本人)。
|
||||
vo.setExists(hasText(plain));
|
||||
vo.setLocked(isAdminLocked(row));
|
||||
vo.setCheckStatus(hasText(row.getCheckStatus()) ? row.getCheckStatus() : STATUS_UNKNOWN);
|
||||
@@ -1304,47 +1317,11 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
}
|
||||
}
|
||||
|
||||
/** 脱敏单出口:一律走 {@link SecretMasking},不在这里长第二份实现(代理列与日志必须同口径)。 */
|
||||
private String maskValue(UserSecretModule module, String plainValue) {
|
||||
if (module == UserSecretModule.PROXY) {
|
||||
return maskProxy(plainValue);
|
||||
}
|
||||
return mask(plainValue);
|
||||
}
|
||||
|
||||
private String mask(String value) {
|
||||
if (!hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
String text = value.trim();
|
||||
if (text.length() <= MASK_MIN_LENGTH) {
|
||||
return "****";
|
||||
}
|
||||
return text.substring(0, 4) + "****" + text.substring(text.length() - 4);
|
||||
}
|
||||
|
||||
/** 代理掩码:隐去账号密码,保留 scheme://host:port 便于运维核对。 */
|
||||
private String maskProxy(String value) {
|
||||
if (!hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
URI uri = URI.create(value.trim());
|
||||
if (uri.getHost() == null || uri.getHost().isBlank()) {
|
||||
return mask(value);
|
||||
}
|
||||
StringBuilder masked = new StringBuilder();
|
||||
masked.append(uri.getScheme() == null ? "http" : uri.getScheme()).append("://");
|
||||
if (uri.getUserInfo() != null && !uri.getUserInfo().isBlank()) {
|
||||
masked.append("***@");
|
||||
}
|
||||
masked.append(uri.getHost());
|
||||
if (uri.getPort() > 0) {
|
||||
masked.append(':').append(uri.getPort());
|
||||
}
|
||||
return masked.toString();
|
||||
} catch (Exception ex) {
|
||||
return mask(value);
|
||||
}
|
||||
return module == UserSecretModule.PROXY
|
||||
? SecretMasking.maskProxy(plainValue)
|
||||
: SecretMasking.mask(plainValue);
|
||||
}
|
||||
|
||||
private String truncate(String value, int maxLength) {
|
||||
|
||||
+36
-1
@@ -7,6 +7,8 @@ import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyProvider;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -33,6 +35,7 @@ public class UserProxyBalanceService {
|
||||
private final Map<Long, CachedProxyBalance> cache = new ConcurrentHashMap<>();
|
||||
|
||||
private final UserProxyPlanService userProxyPlanService;
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final JikipProxyClient jikipProxyClient;
|
||||
private final NotificationDispatchService notificationDispatchService;
|
||||
private final UserSecretProperties userSecretProperties;
|
||||
@@ -45,6 +48,27 @@ public class UserProxyBalanceService {
|
||||
if (cached != null && now - cached.cachedAt() < CACHE_MILLIS) {
|
||||
return cached.balance();
|
||||
}
|
||||
UserApiSecretBalanceVo vo = loadByProvider(userId);
|
||||
cache.put(userId, new CachedProxyBalance(vo, now));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按供应商分档取余量:这套余量口径**只属于 jikip**(套餐 IP 余量+账户余额,走 find-balance)。
|
||||
*
|
||||
* <p>青果必须原样拒:它的余额接口是控制台档 {@code https://www.qg.net/api/merchant/getBalance},
|
||||
* 公共参数要 {@code domain}+{@code appid}+{@code time}+{@code sign=md5(appid+domain+time+appkey)},
|
||||
* 而用户在这里只填 Authkey/Authpwd(铁律 25 口径)——2026-11-02 实测提取域上的
|
||||
* {@code /balance} 对 key/pwd 直接 {@code API_AUTH_DENY},{@code /traffic}、{@code /package} 是
|
||||
* {@code NO_ROUTE}。此前青果账号走到这里会落进"否则查平台套餐"那一条,界面显示的是
|
||||
* **别人家的 jikip 余量**(串档),所以这一档宁可返回"查不了",也不许借用极客的数。</p>
|
||||
*/
|
||||
private UserApiSecretBalanceVo loadByProvider(Long userId) {
|
||||
ProxyProvider provider = ProxyProvider.detectFromUrl(
|
||||
userApiSecretService.findPlainValue(userId, UserSecretModule.PROXY.key()));
|
||||
if (provider == ProxyProvider.QINGGUO) {
|
||||
return qingguoUnsupported();
|
||||
}
|
||||
UserProxyPlanEntity plan = userProxyPlanService.getEntity(userId);
|
||||
UserApiSecretBalanceVo vo;
|
||||
if (plan != null) {
|
||||
@@ -59,7 +83,18 @@ public class UserProxyBalanceService {
|
||||
vo.setScope("platform");
|
||||
vo.setLow(false);
|
||||
}
|
||||
cache.put(userId, new CachedProxyBalance(vo, now));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 青果档的余量答复:不打供应商、不冒充平台套餐,只把"去哪看"说清楚。 */
|
||||
private UserApiSecretBalanceVo qingguoUnsupported() {
|
||||
UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
|
||||
vo.setAvailable(false);
|
||||
vo.setScope("none");
|
||||
vo.setLow(false);
|
||||
vo.setMessage("青果不提供余量/余额查询(它的余额接口要控制台 Appid 与 Appkey 签名,"
|
||||
+ "这里填的 Authkey/Authpwd 只能提取)。用量请看青果控制台,"
|
||||
+ "通道与密钥是否正常请点「代理设置」里的「检测」。");
|
||||
return vo;
|
||||
}
|
||||
|
||||
|
||||
+33
-5
@@ -4,8 +4,9 @@ import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 从代理提取链接里取供应商 Key(青果白名单 API 复用它,无需用户再填一次)。
|
||||
* 链接本身是凭据载体,调用方不得把返回值写进日志。
|
||||
* 从代理提取链接里取供应商凭据(Key 与密码)——这是全仓唯一读这对值的入口。
|
||||
* 青果白名单 API 复用 {@link #fromUrl(String)},隧道验连复用 {@link #passwordFromUrl(String)}。
|
||||
* 链接本身是凭据载体,调用方不得把返回值写进日志/界面文案。
|
||||
*/
|
||||
public final class ProxyLinkKey {
|
||||
|
||||
@@ -14,7 +15,25 @@ public final class ProxyLinkKey {
|
||||
|
||||
/** 取 {@code key} 查询参数(大小写不敏感,兼容 Key);没有返回 null。 */
|
||||
public static String fromUrl(String url) {
|
||||
if (url == null || url.isBlank()) {
|
||||
return param(url, "key");
|
||||
}
|
||||
|
||||
/**
|
||||
* 取账密档的密码参数:青果的提取链接用 {@code pwd},极客旧链接用 {@code password}。
|
||||
* 返回值已 URL 解码,调用方不得写进日志。
|
||||
*/
|
||||
public static String passwordFromUrl(String url) {
|
||||
return param(url, "pwd", "password");
|
||||
}
|
||||
|
||||
/**
|
||||
* 按参数名(大小写不敏感)取链接查询串里的值,取第一个命中的非空项;没有返回 null。
|
||||
*
|
||||
* <p>查询串里存的是 URL 编码后的值,这里按 URL 组件解码返回;需要重新拼进 URL 的调用方
|
||||
* 要自己按组件编码(AGENTS.md 铁律 25:{@code pwd} 里的 {@code @}/{@code :} 会把 host 切歪)。</p>
|
||||
*/
|
||||
public static String param(String url, String... names) {
|
||||
if (url == null || url.isBlank() || names == null || names.length == 0) {
|
||||
return null;
|
||||
}
|
||||
int queryStart = url.indexOf('?');
|
||||
@@ -32,12 +51,12 @@ public final class ProxyLinkKey {
|
||||
continue;
|
||||
}
|
||||
String name = pair.substring(0, separator);
|
||||
if (!"key".equalsIgnoreCase(name)) {
|
||||
if (!matchesAny(name, names)) {
|
||||
continue;
|
||||
}
|
||||
String value = pair.substring(separator + 1);
|
||||
if (value.isEmpty()) {
|
||||
return null;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
@@ -47,4 +66,13 @@ public final class ProxyLinkKey {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean matchesAny(String name, String[] names) {
|
||||
for (String candidate : names) {
|
||||
if (candidate != null && candidate.equalsIgnoreCase(name.trim())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.nanri.aiimage.common.text;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* 代理串脱敏的残余外漏面:{@link SecretMasking#maskProxy} 的回落分支**一个凭据字符都不许给**。
|
||||
*
|
||||
* <p>钉住的形状:脏值(无 scheme 的 {@code host/get?key=..&pwd=..}、裸凭据串)过去回落到
|
||||
* {@link SecretMasking#mask},而它保前 4 <b>和后 4</b>——青果的 {@code pwd=} 恰好挂在末尾,
|
||||
* 于是后管「密钥管理」列与日志里都会留下口令尾 4 位。改成只交「像 host 的那一段」。</p>
|
||||
*/
|
||||
class SecretMaskingTest {
|
||||
|
||||
@Test
|
||||
void 正常链接保留scheme与hostPort() {
|
||||
assertThat(SecretMasking.maskProxy("http://u:pass@proxy.example.com:9000/get?k=1"))
|
||||
.isEqualTo("http://***@proxy.example.com:9000");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 无scheme的提取链接不吐出pwd尾字符() {
|
||||
String masked = SecretMasking.maskProxy(
|
||||
"overseas.proxy.qg.net/get?key=fakekey&pwd=SuperSecret99");
|
||||
|
||||
assertThat(masked).isEqualTo("****overseas.proxy.qg.net");
|
||||
assertThat(masked).doesNotContain("SuperSecret99").doesNotContain("fakekey")
|
||||
.doesNotContain("ret99");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 裸凭据串只给掩码不给字符() {
|
||||
assertThat(SecretMasking.maskProxy("abcdef1234567890")).isEqualTo("****");
|
||||
assertThat(SecretMasking.maskProxy("key=fakekey&pwd=fakepwd")).isEqualTo("****");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 带账号密码的host形状只留host() {
|
||||
assertThat(SecretMasking.maskProxy("user:pass@10.0.0.1:8080")).isEqualTo("****10.0.0.1:8080");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 空值仍是空串不打异常() {
|
||||
assertThat(SecretMasking.maskProxy(null)).isEmpty();
|
||||
assertThat(SecretMasking.maskProxy(" ")).isEmpty();
|
||||
}
|
||||
}
|
||||
+138
@@ -302,6 +302,144 @@ class UserApiSecretCheckServiceTest {
|
||||
"{\"code\":\"SUCCESS\",\"data\":[]}", 60)).isNull();
|
||||
}
|
||||
|
||||
// ---------- 2026-11-02:青果检测不再「提取成功=passed」,且一档一码(现网 uid=1301 的「无法判定」就是这么来的)
|
||||
|
||||
/**
|
||||
* 通道占用必须是独立码:混进 {@code provider_error} 后界面只剩「无法判定」,
|
||||
* 用户既不知道是自己在占用、也不知道等 3 分钟就好。
|
||||
*/
|
||||
@Test
|
||||
void qingguoChannelBusyIsItsOwnCodeWithHumanMessage() {
|
||||
UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection(
|
||||
com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO,
|
||||
"{\"code\":\"NO_AVAILABLE_CHANNEL\",\"message\":\"没有可用的空闲通道\",\"request_id\":\"x\"}", 88);
|
||||
|
||||
assertThat(outcome).isNotNull();
|
||||
assertThat(outcome.code()).isEqualTo(UserApiSecretCheckService.CODE_CHANNEL_BUSY);
|
||||
assertThat(outcome.code()).isNotEqualTo(UserApiSecretCheckService.CODE_PROVIDER_ERROR);
|
||||
assertThat(outcome.status()).isEqualTo(UserApiSecretCheckService.STATUS_ERROR);
|
||||
assertThat(outcome.message())
|
||||
.isEqualTo(UserApiSecretCheckService.CHANNEL_BUSY_MESSAGE)
|
||||
.contains("青果通道正被你自己的采集占着")
|
||||
.contains("3 分钟");
|
||||
}
|
||||
|
||||
/**
|
||||
* 五档失败各自可辨(欠费/通道占用/限流/密钥失效/鉴权未过)——
|
||||
* 把任意一档改回 provider_error 或彼此合并,本例即红。
|
||||
*/
|
||||
@Test
|
||||
void qingguoFailureCodesArePairwiseDistinguishable() {
|
||||
java.util.Map<String, String> byProviderCode = new java.util.LinkedHashMap<>();
|
||||
byProviderCode.put("BALANCE_INSUFFICIENT", UserApiSecretCheckService.CODE_INSUFFICIENT_BALANCE);
|
||||
byProviderCode.put("NO_AVAILABLE_CHANNEL", UserApiSecretCheckService.CODE_CHANNEL_BUSY);
|
||||
byProviderCode.put("REQUEST_LIMIT_EXCEEDED", UserApiSecretCheckService.CODE_RATE_LIMITED);
|
||||
byProviderCode.put("INVALID_KEY", UserApiSecretCheckService.CODE_INVALID_KEY);
|
||||
byProviderCode.put("API_AUTH_DENY", UserApiSecretCheckService.CODE_FORBIDDEN);
|
||||
|
||||
java.util.Set<String> resolved = new java.util.LinkedHashSet<>();
|
||||
for (java.util.Map.Entry<String, String> entry : byProviderCode.entrySet()) {
|
||||
UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection(
|
||||
com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO,
|
||||
"{\"code\":\"" + entry.getKey() + "\",\"message\":\"m\",\"request_id\":\"x\"}", 50);
|
||||
assertThat(outcome).as(entry.getKey()).isNotNull();
|
||||
assertThat(outcome.code()).isEqualTo(entry.getValue());
|
||||
// 说人话:文案不得只剩「无法判定」这种界面兜底词,也不得是英文异常串
|
||||
assertThat(outcome.message()).doesNotContain("无法判定");
|
||||
resolved.add(outcome.code());
|
||||
}
|
||||
assertThat(resolved).hasSize(5).doesNotContain(UserApiSecretCheckService.CODE_PROVIDER_ERROR);
|
||||
}
|
||||
|
||||
/** 限流与欠费不是「密钥坏了」:前者 error(放行但警示),后者 failed(拦下)。 */
|
||||
@Test
|
||||
void qingguoRateLimitedStaysJudgementAndBalanceStaysBlocking() {
|
||||
UserApiSecretCheckService.CheckOutcome limited = service.classifyProviderRejection(
|
||||
com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO,
|
||||
"{\"code\":\"REQUEST_LIMIT_EXCEEDED\",\"message\":\"请求过于频繁\"}", 40);
|
||||
assertThat(limited.status()).isEqualTo(UserApiSecretCheckService.STATUS_ERROR);
|
||||
assertThat(limited.message()).contains("限流").contains("1 分钟");
|
||||
|
||||
UserApiSecretCheckService.CheckOutcome broke = service.classifyProviderRejection(
|
||||
com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO,
|
||||
"{\"code\":\"BALANCE_INSUFFICIENT\",\"message\":\"余额不足\"}", 40);
|
||||
assertThat(broke.status()).isEqualTo(UserApiSecretCheckService.STATUS_FAILED);
|
||||
}
|
||||
|
||||
/** 供应商文案整条回显请求链接时,出口前必须抹掉 key/pwd 原文(假凭据,不涉真值)。 */
|
||||
@Test
|
||||
void providerRejectionMessageNeverEchoesLinkCredentials() {
|
||||
String extractLink = "https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd";
|
||||
UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection(
|
||||
com.nanri.aiimage.modules.usersecret.support.ProxyProvider.QINGGUO,
|
||||
"{\"code\":\"INVALID_KEY\",\"message\":\"Key 无效: https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd\"}",
|
||||
70, extractLink);
|
||||
|
||||
assertThat(outcome).isNotNull();
|
||||
assertThat(outcome.code()).isEqualTo(UserApiSecretCheckService.CODE_INVALID_KEY);
|
||||
assertThat(outcome.message()).doesNotContain("fakekey").doesNotContain("fakepwd").contains("****");
|
||||
// 参数名形状之外的裸值也要盖掉(供应商只回显值、不带 key= 前缀的形态)
|
||||
assertThat(UserApiSecretCheckService.redactCredentials("裸值 fakekey 与 fakepwd 都要抹", extractLink))
|
||||
.doesNotContain("fakekey").doesNotContain("fakepwd");
|
||||
}
|
||||
|
||||
/** 极客链接不带凭据型参数名时,通用抹除不能把正常参数吃成 ****。 */
|
||||
@Test
|
||||
void redactKeepsNonCredentialQueryParamsIntact() {
|
||||
assertThat(UserApiSecretCheckService.redactCredentials(
|
||||
"https://overseas.proxy.qg.net/get?num=1&format=json", null))
|
||||
.contains("num=1").contains("format=json");
|
||||
}
|
||||
|
||||
// ---------- 青果隧道组链:账密就在链接里,所以必须真经隧道打一次(旧短路已废)
|
||||
|
||||
/** 隧道端点 + 链接里的 key/pwd = 可直接验连的代理地址;日志侧只允许出现掩码形态。 */
|
||||
@Test
|
||||
void qingguoTunnelProxyUrlSplicesLinkCredentialsIntoEndpoint() {
|
||||
String tunnelUrl = UserApiSecretCheckService.qingguoTunnelProxyUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd&format=json",
|
||||
"http://tun1.qg.net:16359");
|
||||
|
||||
assertThat(tunnelUrl).isEqualTo("http://fakekey:fakepwd@tun1.qg.net:16359");
|
||||
// 组出来的地址含凭据:任何日志/文案只能用它掩码后的形态
|
||||
assertThat(com.nanri.aiimage.common.text.SecretMasking.maskProxy(tunnelUrl))
|
||||
.isEqualTo("http://***@tun1.qg.net:16359")
|
||||
.doesNotContain("fakekey").doesNotContain("fakepwd");
|
||||
}
|
||||
|
||||
/** 补不出安全地址就返回 null:缺 pwd、账密含会切歪 host 的分隔符、端点没端口,一律不猜。 */
|
||||
@Test
|
||||
void qingguoTunnelProxyUrlRefusesMissingOrUnsafeCredentials() {
|
||||
// 白名单档(只有 key、没有 pwd):青果只做账密档,组不出鉴权地址
|
||||
assertThat(UserApiSecretCheckService.qingguoTunnelProxyUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey", "http://tun1.qg.net:16359")).isNull();
|
||||
// pwd 里的 @ 会把 userinfo 吞进 host(AGENTS.md 铁律 25 实录)
|
||||
assertThat(UserApiSecretCheckService.qingguoTunnelProxyUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey&pwd=a%40b", "http://tun1.qg.net:16359")).isNull();
|
||||
assertThat(UserApiSecretCheckService.qingguoTunnelProxyUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fake%3Akey&pwd=fakepwd", "http://tun1.qg.net:16359")).isNull();
|
||||
// 端点缺端口:不是可连的代理地址
|
||||
assertThat(UserApiSecretCheckService.qingguoTunnelProxyUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd", "http://tun1.qg.net")).isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* 组不出链时的结论必须如实是「没验成」(error/tunnel_unverified),
|
||||
* **不得**退回旧的 passed/ok 短路——那正是本次要消灭的假通过。
|
||||
*/
|
||||
@Test
|
||||
void qingguoTunnelWithoutUsableCredentialsReportsUnverifiedNotPassed() {
|
||||
UserApiSecretCheckService.CheckOutcome outcome = service.probeQingguoTunnel(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey", "http://tun1.qg.net:16359",
|
||||
System.currentTimeMillis());
|
||||
|
||||
assertThat(outcome.status()).isEqualTo(UserApiSecretCheckService.STATUS_ERROR);
|
||||
assertThat(outcome.code()).isEqualTo(UserApiSecretCheckService.CODE_TUNNEL_UNVERIFIED);
|
||||
assertThat(outcome.status()).isNotEqualTo(UserApiSecretCheckService.STATUS_PASSED);
|
||||
assertThat(outcome.message()).contains("无法确认").doesNotContain("fakekey");
|
||||
assertThat(outcome.viaProxy()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jikipBalanceShortageStillClassified() {
|
||||
UserApiSecretCheckService.CheckOutcome outcome = service.classifyProviderRejection(
|
||||
|
||||
+97
-5
@@ -550,7 +550,70 @@ class UserApiSecretServiceTest {
|
||||
assertThat(rowVo.getSimilarAsin().getFull()).isNull();
|
||||
assertThat(rowVo.getProxy().getExists()).isTrue();
|
||||
assertThat(rowVo.getProxy().getMasked()).isEqualTo("http://***@1.2.3.4:8080");
|
||||
assertThat(rowVo.getProxy().getFull()).isEqualTo("http://user:pass@1.2.3.4:8080");
|
||||
// 2026-11-02 收口:后台读路不再下发代理明文(链接里就带着账密)
|
||||
assertThat(rowVo.getProxy().getFull()).isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* 后管列表的代理列:响应体里不得出现提取链接的 key/pwd 原文(同页 LLM 列一直是脱敏的,
|
||||
* 代理列此前把 {@code https://overseas.proxy.qg.net/get?key=…&pwd=…} 整串交给界面)。
|
||||
* 断言打在真正发出去的 JSON 上,不是只打 VO 字段——界面拿到的是序列化后的字节。
|
||||
*/
|
||||
@Test
|
||||
void adminPageProxyColumnNeverShipsExtractLinkCredentials() throws Exception {
|
||||
UserApiSecretService service = newService();
|
||||
when(mapper.selectList(any())).thenReturn(List.of(
|
||||
row(1L, "proxy", "enc:https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd", "error")));
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(1L);
|
||||
user.setUsername("张三");
|
||||
when(adminUserMapper.selectById(1L)).thenReturn(user);
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
AdminUserSecretModuleVo proxy = service
|
||||
.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered())
|
||||
.getItems().get(0).getProxy();
|
||||
|
||||
assertThat(proxy.getExists()).isTrue();
|
||||
assertThat(proxy.getMasked()).isEqualTo("https://overseas.proxy.qg.net");
|
||||
assertThat(proxy.getFull()).isNull();
|
||||
|
||||
// 断言打在序列化后的响应体上;用 Boot 同款 mapper(new ObjectMapper() 不挂 jsr310,日期会直接炸)
|
||||
String body = com.fasterxml.jackson.databind.json.JsonMapper.builder()
|
||||
.addModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule())
|
||||
.build()
|
||||
.writeValueAsString(proxy);
|
||||
assertThat(body).doesNotContain("fakekey").doesNotContain("fakepwd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理行的「货源」只可能是供应商:后端把 LLM 渠道词表贴到 proxy 行上(现网看到「龙抬头」)
|
||||
* 从来不是这里的产出——存量脏值(channel 列写着 longtaitou)也会被 {@code channelOrDefault}
|
||||
* 按链接域名归一到 qingguo/jikip。界面那一列拿到什么,由本例钉住。
|
||||
*/
|
||||
@Test
|
||||
void adminPageProxyChannelIsProviderNeverLlmChannel() {
|
||||
UserApiSecretService service = newService();
|
||||
UserApiSecretEntity dirty = row(1L, "proxy",
|
||||
"enc:https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd", "error");
|
||||
dirty.setChannel("longtaitou");
|
||||
when(mapper.selectList(any())).thenReturn(List.of(dirty));
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(1L);
|
||||
user.setUsername("张三");
|
||||
when(adminUserMapper.selectById(1L)).thenReturn(user);
|
||||
AdminUserEntity operator = new AdminUserEntity();
|
||||
operator.setId(88L);
|
||||
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
AdminUserSecretModuleVo proxy = service
|
||||
.adminPage(operator, new AdminUserSecretQuery(), ReadScope.unfiltered())
|
||||
.getItems().get(0).getProxy();
|
||||
|
||||
assertThat(proxy.getChannel()).isEqualTo("qingguo");
|
||||
assertThat(proxy.getChannel()).isNotIn("longtaitou", "t8star");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -914,7 +977,7 @@ class UserApiSecretServiceTest {
|
||||
assertThat(existing.getSecretValue()).isEqualTo("enc:http://1.2.3.4:8080");
|
||||
}
|
||||
|
||||
/** 后台代填:写入 source=admin(锁定)并把完整地址回给后台列表。 */
|
||||
/** 后台代填:写入 source=admin(锁定),回包只给脱敏值——代填的链接里带着账密,不再原文回显。 */
|
||||
@Test
|
||||
void adminSaveModuleLocksProxyAndReturnsLockedVo() {
|
||||
UserApiSecretService service = newService();
|
||||
@@ -940,7 +1003,7 @@ class UserApiSecretServiceTest {
|
||||
assertThat(stored.getSource()).isEqualTo(UserApiSecretService.SOURCE_ADMIN);
|
||||
assertThat(vo.getExists()).isTrue();
|
||||
assertThat(vo.getLocked()).isTrue();
|
||||
assertThat(vo.getFull()).isEqualTo("https://api.jikip.com/ip-get?num=1&key=abc");
|
||||
assertThat(vo.getFull()).isNull();
|
||||
assertThat(vo.getMasked()).isEqualTo("https://api.jikip.com");
|
||||
}
|
||||
|
||||
@@ -1119,6 +1182,35 @@ class UserApiSecretServiceTest {
|
||||
anyString(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* 巡检遇到「青果通道被占」必须**什么都不改**:既不落 error 也不推通知。
|
||||
*
|
||||
* <p>通道被占不是密钥坏了,而是"此刻问不出结论"——巡检自己那一发真提取就要占掉唯一一条通道
|
||||
* (2026-11-02 青果控制台核实:通道数 1 个、存活周期 3 分钟)。把 channel_busy 落库等于
|
||||
* 用户早上看到的「代理异常」是我们自己造成的(现网 uid=1301 那条「无法判定」就是这形状)。</p>
|
||||
*/
|
||||
@Test
|
||||
void schedulerWritesNothingWhenQingguoChannelIsBusy() {
|
||||
UserApiSecretService service = newService();
|
||||
String cipher = "enc:https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd";
|
||||
stubInspectionStore(Map.of(11L, storedRow(11L, "proxy", cipher)));
|
||||
when(checkService.probe(any(), anyString(), any())).thenReturn(
|
||||
outcome("error", UserApiSecretCheckService.CODE_CHANNEL_BUSY,
|
||||
"青果通道正被你自己的采集占着,等约 3 分钟释放后再点检测", 70));
|
||||
when(mapper.selectList(any())).thenReturn(List.of(
|
||||
inspectionRow(1L, 11L, "proxy", cipher)), List.of());
|
||||
stubAdminNotificationPath();
|
||||
|
||||
var summary = service.checkAllForScheduler(500, 20);
|
||||
|
||||
assertThat(summary.checked()).isEqualTo(0);
|
||||
assertThat(summary.skipped()).isEqualTo(1);
|
||||
assertThat(summary.probed()).isEqualTo(1);
|
||||
assertThat(inspectionWrites).isEmpty();
|
||||
verify(notificationDispatchService, never()).pushToUser(any(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
/** 只有一个账号在用的密钥保持原口径:仍然点名「用户密钥异常:{用户名}」,去重键与改动前一致。 */
|
||||
@Test
|
||||
void schedulerKeepsNamedAdminAlertWhenSecretIsUsedByOneAccount() {
|
||||
@@ -1252,8 +1344,8 @@ class UserApiSecretServiceTest {
|
||||
}
|
||||
|
||||
private UserProxyBalanceService newBalanceService() {
|
||||
return new UserProxyBalanceService(userProxyPlanService, jikipProxyClient,
|
||||
notificationDispatchService, userSecretProperties);
|
||||
return new UserProxyBalanceService(userProxyPlanService, mock(UserApiSecretService.class),
|
||||
jikipProxyClient, notificationDispatchService, userSecretProperties);
|
||||
}
|
||||
|
||||
private UserProxyPlanEntity proxyPlan(long userId, String planId, String jikipUserId) {
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 用户级代理余量按供应商分档:jikip 的数只能给 jikip 账号看。
|
||||
*
|
||||
* <p>钉住的现网缺陷:青果账号走到这套余量口径里会落进「否则查平台套餐」那一条,
|
||||
* 设置弹窗显示的是别人家的极客余量(串档),用户据此判断"我还有量",实际青果那边
|
||||
* 通道早被占满。青果不提供可鉴权的余量/余额查询(余额接口是控制台 appid/appkey 签名档),
|
||||
* 所以这一档必须返回"查不了"、并且一次都不许打极客接口。</p>
|
||||
*/
|
||||
class UserProxyBalanceServiceTest {
|
||||
|
||||
private static final Long USER_ID = 7L;
|
||||
private static final String QINGGUO_LINK = "https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd";
|
||||
private static final String QINGGUO_SHARE_LINK = "https://share.proxy.qg.net/get?key=fakekey";
|
||||
private static final String JIKIP_LINK = "https://api.jikip.com/ip-get?key=fakekey";
|
||||
|
||||
private final UserProxyPlanService userProxyPlanService = mock(UserProxyPlanService.class);
|
||||
private final UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||
private final JikipProxyClient jikipProxyClient = mock(JikipProxyClient.class);
|
||||
private final NotificationDispatchService notificationDispatchService =
|
||||
mock(NotificationDispatchService.class);
|
||||
private final UserSecretProperties userSecretProperties = mock(UserSecretProperties.class);
|
||||
|
||||
private final UserProxyBalanceService service = new UserProxyBalanceService(
|
||||
userProxyPlanService, userApiSecretService, jikipProxyClient,
|
||||
notificationDispatchService, userSecretProperties);
|
||||
|
||||
private void storedProxyLink(String link) {
|
||||
when(userApiSecretService.findPlainValue(anyLong(), anyString())).thenReturn(link);
|
||||
}
|
||||
|
||||
private static UserApiSecretBalanceVo jikipReply(String surplus, String balance) {
|
||||
UserApiSecretBalanceVo vo = new UserApiSecretBalanceVo();
|
||||
vo.setAvailable(true);
|
||||
vo.setSurplus(surplus);
|
||||
vo.setBalance(balance);
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Test
|
||||
void 青果账号不打极客接口也不借用平台套餐() {
|
||||
storedProxyLink(QINGGUO_LINK);
|
||||
|
||||
UserApiSecretBalanceVo vo = service.balance(USER_ID);
|
||||
|
||||
assertThat(vo.getAvailable()).isFalse();
|
||||
assertThat(vo.getScope()).isEqualTo("none");
|
||||
assertThat(vo.getLow()).isFalse();
|
||||
assertThat(vo.getMessage()).contains("青果不提供").contains("检测");
|
||||
verifyNoInteractions(jikipProxyClient);
|
||||
verifyNoInteractions(userProxyPlanService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 青果分享域名的存量链接同样认得不会被当成极客() {
|
||||
storedProxyLink(QINGGUO_SHARE_LINK);
|
||||
|
||||
assertThat(service.balance(USER_ID).getScope()).isEqualTo("none");
|
||||
verifyNoInteractions(jikipProxyClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 极客账号填了套餐就查自己那份() {
|
||||
storedProxyLink(JIKIP_LINK);
|
||||
UserProxyPlanEntity plan = new UserProxyPlanEntity();
|
||||
plan.setUserId(USER_ID);
|
||||
plan.setPlanId("plan-1");
|
||||
plan.setJikipUserId("jiku-1");
|
||||
when(userProxyPlanService.getEntity(USER_ID)).thenReturn(plan);
|
||||
when(jikipProxyClient.fetchBalance(any(JikipProxyClient.PlanRef.class)))
|
||||
.thenReturn(jikipReply("120", "30"));
|
||||
|
||||
UserApiSecretBalanceVo vo = service.balance(USER_ID);
|
||||
|
||||
assertThat(vo.getScope()).isEqualTo("user");
|
||||
assertThat(vo.getSurplus()).isEqualTo("120");
|
||||
verify(jikipProxyClient).fetchBalance(new JikipProxyClient.PlanRef("plan-1", "jiku-1"));
|
||||
verify(jikipProxyClient, never()).fetchBalance();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 极客账号没填套餐才落平台套餐() {
|
||||
storedProxyLink(JIKIP_LINK);
|
||||
when(userProxyPlanService.getEntity(USER_ID)).thenReturn(null);
|
||||
when(jikipProxyClient.fetchBalance()).thenReturn(jikipReply("900", "900"));
|
||||
|
||||
UserApiSecretBalanceVo vo = service.balance(USER_ID);
|
||||
|
||||
assertThat(vo.getScope()).isEqualTo("platform");
|
||||
assertThat(vo.getLow()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 同一用户五分钟内复用缓存不再打供应商() {
|
||||
storedProxyLink(JIKIP_LINK);
|
||||
when(userProxyPlanService.getEntity(USER_ID)).thenReturn(null);
|
||||
when(jikipProxyClient.fetchBalance()).thenReturn(jikipReply("900", "900"));
|
||||
|
||||
service.balance(USER_ID);
|
||||
service.balance(USER_ID);
|
||||
|
||||
verify(jikipProxyClient, times(1)).fetchBalance();
|
||||
}
|
||||
|
||||
@Test
|
||||
void 改过代理配置后缓存作废下一次按新供应商走() {
|
||||
storedProxyLink(JIKIP_LINK);
|
||||
when(userProxyPlanService.getEntity(USER_ID)).thenReturn(null);
|
||||
when(jikipProxyClient.fetchBalance()).thenReturn(jikipReply("900", "900"));
|
||||
service.balance(USER_ID);
|
||||
|
||||
service.invalidate(USER_ID);
|
||||
storedProxyLinkAfter(QINGGUO_LINK);
|
||||
UserApiSecretBalanceVo vo = service.balance(USER_ID);
|
||||
|
||||
assertThat(vo.getScope()).isEqualTo("none");
|
||||
}
|
||||
|
||||
private void storedProxyLinkAfter(String link) {
|
||||
when(userApiSecretService.findPlainValue(ArgumentMatchers.eq(USER_ID), anyString()))
|
||||
.thenReturn(link);
|
||||
}
|
||||
}
|
||||
+17
@@ -26,4 +26,21 @@ class ProxyLinkKeyTest {
|
||||
assertThat(ProxyLinkKey.fromUrl("")).isNull();
|
||||
assertThat(ProxyLinkKey.fromUrl(null)).isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* 隧道验连要用链接里的密码:青果的参数名是 {@code pwd},极客旧链接是 {@code password},
|
||||
* 两者都要认(AGENTS.md 铁律 25:青果只做账密档,pwd 必填)。
|
||||
*/
|
||||
@Test
|
||||
void passwordReadsPwdThenLegacyPasswordParam() {
|
||||
assertThat(ProxyLinkKey.passwordFromUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey&pwd=fakepwd")).isEqualTo("fakepwd");
|
||||
assertThat(ProxyLinkKey.passwordFromUrl(
|
||||
"https://api.jikip.com/ip-get?password=fakepwd")).isEqualTo("fakepwd");
|
||||
assertThat(ProxyLinkKey.passwordFromUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=fakekey")).isNull();
|
||||
// 大小写不敏感 + 值按 URL 组件解码(含 %40 的 pwd 解码后才能判定它不能直接拼进 userinfo)
|
||||
assertThat(ProxyLinkKey.passwordFromUrl("https://overseas.proxy.qg.net/get?PWD=fake%40pwd"))
|
||||
.isEqualTo("fake@pwd");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 渠道回显')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user