Compare commits
6 Commits
8f206a6019
...
37f51df37d
| Author | SHA1 | Date | |
|---|---|---|---|
| 37f51df37d | |||
| 0114a5b7a7 | |||
| e26a157037 | |||
| 2cbd99ed4f | |||
| 7e64c12dd6 | |||
| 7f5437d012 |
@@ -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,25 @@ 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,
|
||||
moduleStatusBand,
|
||||
proxyDisplayText,
|
||||
proxySourceLabel,
|
||||
rowDetailLines,
|
||||
rowStatusBand,
|
||||
} 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 +46,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)))
|
||||
|
||||
@@ -47,72 +58,42 @@ const STATUS_OPTIONS = [
|
||||
{ value: 'passed', label: '检测通过' },
|
||||
{ value: 'failed', label: '检测失败' },
|
||||
{ value: 'incomplete', label: '未配齐' },
|
||||
{ value: 'error', label: '无法判定' },
|
||||
// 后端的行级值仍是 error:这一档现在既可能是「问不出结论」,也可能是「通道还没释放、等一会再点」,
|
||||
// 界面按码把后者补成「可重试」(见 user-secret-model.ts 的档位表),筛选项就得把两档都点名。
|
||||
{ value: 'error', label: '无法判定/可重试' },
|
||||
{ value: 'unknown', label: '未检测' },
|
||||
]
|
||||
|
||||
/** 行级状态药丸:三类都检测通过才显示「检测通过」。 */
|
||||
function rowStatusMeta(status: string) {
|
||||
switch (status) {
|
||||
case 'passed':
|
||||
return { label: '检测通过', tone: 'is-allowed' }
|
||||
case 'failed':
|
||||
return { label: '检测失败', tone: 'is-blocked' }
|
||||
case 'incomplete':
|
||||
return { label: '未配齐', tone: 'is-warn' }
|
||||
case 'error':
|
||||
return { label: '无法判定', tone: 'is-warn' }
|
||||
default:
|
||||
return { label: '未检测', tone: 'is-unknown' }
|
||||
}
|
||||
}
|
||||
/* 状态药丸的档位表在 `user-secret-model.ts`(唯一出处,页面不带第二张表):
|
||||
行级传整行而不是 `row.status`——后端把 failed/incomplete 都判掉之后就只剩一个「error」,
|
||||
这一行到底是「查不出」还是「等青果释放」只有逐格的 `check_code` 说得清。 */
|
||||
|
||||
/** 单格状态药丸:未配置时统一灰色;欠费单独标识。 */
|
||||
function moduleStatusMeta(module: AdminUserSecretModule | undefined) {
|
||||
if (!module || !module.exists) {
|
||||
return { label: '未配置', tone: 'is-unknown' }
|
||||
}
|
||||
switch (module.checkStatus) {
|
||||
case 'passed':
|
||||
return { label: '通过', tone: 'is-allowed' }
|
||||
case 'failed':
|
||||
if (module.checkCode === 'insufficient_balance') {
|
||||
return { label: '欠费', tone: 'is-warn' }
|
||||
}
|
||||
return { label: '失败', tone: 'is-blocked' }
|
||||
case 'error':
|
||||
return { label: '无法判定', tone: 'is-warn' }
|
||||
default:
|
||||
return { label: '未检测', tone: 'is-unknown' }
|
||||
}
|
||||
}
|
||||
|
||||
/** 单格悬停详情:完整值(代理为全量地址)+ 锁定说明 + 检测消息 + 检测时间 + 耗时。 */
|
||||
/**
|
||||
* 单格悬停详情:后端下发的**脱敏值** + 锁定说明 + **检测结果原文 `check_message`** + 检测时间 + 耗时。
|
||||
* 运维要判「是欠费还是被自己的采集占着」,靠的就是这句后端原文——档名只是扫一眼用的短词,
|
||||
* 前端一律不按码自己拼句子。
|
||||
* ⚠ 只读 `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('已由后台代填并锁定:客户端不可修改或清空')
|
||||
if (module.checkMessage) parts.push(module.checkMessage)
|
||||
const display = String(module.masked || '').trim()
|
||||
if (display) {
|
||||
parts.push(isProxyModule(module) ? `代理地址(已脱敏,不含 key/pwd):${display}` : `密钥:${display}`)
|
||||
}
|
||||
if (module.locked) parts.push('已由后台代填并锁定:客户端不可修改或清空,改代理需重新填写账密')
|
||||
// 后端的这句话就是给人看的结论,原样透出(不动一个字、不按码另拼一句)
|
||||
const message = String(module.checkMessage || '').trim()
|
||||
if (message) parts.push(message)
|
||||
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
|
||||
}
|
||||
|
||||
/** 分组列文案:优先分组名;未建分组的用户回退展示所属主管,便于判断归属。 */
|
||||
@@ -122,9 +103,15 @@ function groupTextOf(row: AdminUserSecretRow) {
|
||||
return '—'
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级悬停详情:后端的行级摘要 + 逐格的 `check_message` 原文 + 更新时间。
|
||||
* 行级状态一旦补成「可重试」,管理员得能立刻看出是哪一格在等、后端原话怎么说;
|
||||
* 逐格那句一律取后端下发文本(`rowDetailLines` 只搬运、不改写、不另拼一句)。
|
||||
*/
|
||||
function rowStatusTooltip(row: AdminUserSecretRow) {
|
||||
const parts: string[] = []
|
||||
if (row.statusMessage) parts.push(row.statusMessage)
|
||||
parts.push(...rowDetailLines(row))
|
||||
if (row.updatedAt) parts.push(`最近更新:${formatDateTime(row.updatedAt)}`)
|
||||
return parts.join(';') || '暂无检测记录'
|
||||
}
|
||||
@@ -181,7 +168,9 @@ async function check(row: AdminUserSecretRow) {
|
||||
if (failed.length) {
|
||||
ElMessage.warning(failed[0].checkMessage || '存在检测失败项')
|
||||
} else if (errors.length) {
|
||||
ElMessage.warning('部分配置本次无法判定')
|
||||
// 后端这句话会区分「通道被你自己占着,等约 3 分钟」与「真的问不出结论」;
|
||||
// 硬写「无法判定」等于把可重试那一族又抹回一坨(现网 uid=1 就是这个形状)。
|
||||
ElMessage.warning(errors[0].checkMessage || '部分配置本次无法判定')
|
||||
} else {
|
||||
ElMessage.success('检测通过')
|
||||
}
|
||||
@@ -206,38 +195,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,10 +312,10 @@ 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 }}
|
||||
<span class="wh-pill" :class="moduleStatusBand(row.similarAsin).tone" :title="moduleTooltip(row.similarAsin)">
|
||||
{{ moduleStatusBand(row.similarAsin).label }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
@@ -340,23 +324,23 @@ 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 }}
|
||||
<span class="wh-pill" :class="moduleStatusBand(row.appearancePatent).tone" :title="moduleTooltip(row.appearancePatent)">
|
||||
{{ moduleStatusBand(row.appearancePatent).label }}
|
||||
</span>
|
||||
</div>
|
||||
</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 }}
|
||||
<span class="wh-pill" :class="moduleStatusBand(row.proxy).tone" :title="moduleTooltip(row.proxy)">
|
||||
{{ moduleStatusBand(row.proxy).label }}
|
||||
</span>
|
||||
<span
|
||||
v-if="row.proxy?.locked"
|
||||
@@ -369,8 +353,8 @@ onMounted(load)
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="wh-pill" :class="rowStatusMeta(row.status).tone" :title="rowStatusTooltip(row)">
|
||||
{{ rowStatusMeta(row.status).label }}
|
||||
<span class="wh-pill" :class="rowStatusBand(row).tone" :title="rowStatusTooltip(row)">
|
||||
{{ rowStatusBand(row).label }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
@@ -387,8 +371,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 +399,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 +594,7 @@ h3 {
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
/* 代理列:完整地址独占一行,状态药丸另起一行,避免长地址被药丸挤压折行 */
|
||||
/* 代理列:脱敏地址独占一行,状态药丸另起一行(列宽按最长药丸文案留的,不按整条链接) */
|
||||
.module-cell--stack {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
@@ -612,18 +605,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;
|
||||
@@ -673,6 +657,13 @@ h3 {
|
||||
border-color: #f0dfae;
|
||||
color: #8f6d1e;
|
||||
}
|
||||
/* 「等一会再点」这一族(无可用通道/限流/超时/网络/上游):既不红(密钥没坏)
|
||||
也不黄(不是欠费)更不是灰(不是查不出),独立一档青色——三种处置一眼分开。 */
|
||||
.wh-pill.is-retry {
|
||||
background: #e6f2f7;
|
||||
border-color: #b6d8e6;
|
||||
color: #2b6b86;
|
||||
}
|
||||
.wh-pill.is-unknown {
|
||||
background: #f0f3f6;
|
||||
border-color: #d6dee6;
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* 密钥管理页的纯逻辑模型(货源标签 + 代理重填 + 检测结果档位)。
|
||||
*
|
||||
* 三条收口都在这个文件里,页模板只调这里导出的函数,不各写各的字典:
|
||||
*
|
||||
* 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、进剪贴板。
|
||||
*
|
||||
* 3. **检测结果按 `check_code` 分档渲染**(2026-11-02 加,见下方档位表):状态列原先只看
|
||||
* `check_status`,把后端新分出来的一族「等一会再点就行」的码(`channel_busy` 等)一律显示成
|
||||
* 「无法判定」,管理员分不清「被自己占着」「密钥坏了」「欠费」三种完全不同的处置。
|
||||
* 码表只在这一份文件里(页面不再自带第二张表),句子一律用后端的 `check_message` 原文。
|
||||
*
|
||||
* 零 `@/` 别名依赖:本文件被 `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'
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* 检测结果的渲染档位(2026-11-02 加,起因是现网 uid=1 的 proxy 行)
|
||||
*
|
||||
* 后端 `UserApiSecretCheckService` 把青果检测从「无条件假通过」改成真提取后**按供应商返回码分档**,
|
||||
* 于是 `check_code` 成了这一格到底怎么了的最细信号;而界面当时只认 `check_status` 三档
|
||||
* (passed/failed/error),`error` 一律写成「无法判定」——`channel_busy`(青果通道被自己的采集
|
||||
* 占着,等约 3 分钟就能重试)因此被显示成「查不出」,管理员既看不出「等一会就行」,
|
||||
* 也分不清它和「密钥坏了」「欠费」是三种完全不同的处置。
|
||||
*
|
||||
* 所以现在**按码建表、按状态兜底**:
|
||||
* - 认得的码 ⇒ 各有自己的档位(可重试这一族另给独立配色,既不红也不黄);
|
||||
* - 「无法判定」只留给真正没有结论的情况(空码/这表里没有的码 + `check_status=error`);
|
||||
* - `check_status=unknown`(后端 upsert 后的初值,等于「从没检测过」)仍是「未检测」,
|
||||
* 不许冒充「无法判定」——那是两件事,前者点一次检测就有答案,后者点了也还是没答案。
|
||||
*
|
||||
* ⚠ 措辞的权威在后端:给人看的那句中文在 `check_message` 里,界面只出**档名**(一个词),
|
||||
* 绝不按码自己拼句子;句子通过 `moduleTooltip`/行级 tooltip 原样透出。
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/** 药丸配色档位,对应 `UserSecretsPage.vue` 里 `.wh-pill.is-*` 那套样式类。 */
|
||||
export type StatusTone = 'is-allowed' | 'is-blocked' | 'is-warn' | 'is-retry' | 'is-unknown'
|
||||
|
||||
/** 一个渲染档位:档名 + 配色。档名是给管理员扫一眼用的短词,不是解释句。 */
|
||||
export interface StatusBand {
|
||||
label: string
|
||||
tone: StatusTone
|
||||
}
|
||||
|
||||
/** 单格「没配」与「没检测」是两档,但都用灰色:都不代表密钥本身有问题。 */
|
||||
export const NOT_CONFIGURED_BAND: StatusBand = { label: '未配置', tone: 'is-unknown' }
|
||||
export const NOT_CHECKED_BAND: StatusBand = { label: '未检测', tone: 'is-unknown' }
|
||||
/** 真的问不出结论(空码/未知码 + `check_status=error`)才落到这一档。 */
|
||||
export const INDETERMINATE_BAND: StatusBand = { label: '无法判定', tone: 'is-warn' }
|
||||
/** 后端 `STATUS_PASSED`(或码 `ok`):唯一可以当成「这项配好了」的一档。 */
|
||||
export const PASSED_BAND: StatusBand = { label: '通过', tone: 'is-allowed' }
|
||||
/** 后端新增了一档、前端还没登记码名时的兜底:按状态给个不撒谎的词,不当场判死。 */
|
||||
const GENERIC_FAILED_BAND: StatusBand = { label: '失败', tone: 'is-blocked' }
|
||||
|
||||
/** 后端 `UserApiSecretCheckService` 的 `CODE_*` 全集(2026-11-02 逐条对着源码登记)。 */
|
||||
const CHECK_CODE_BANDS: Record<string, StatusBand> = {
|
||||
ok: PASSED_BAND,
|
||||
/** 通道被自己的采集占着:等释放后重点一次,密钥没坏——这一档就是本次要修的错渲染。 */
|
||||
channel_busy: { label: '无可用通道', tone: 'is-retry' },
|
||||
rate_limited: { label: '限流重试', tone: 'is-retry' },
|
||||
timeout: { label: '超时重试', tone: 'is-retry' },
|
||||
/** 传输层失败:后端两个分支都给这个码(提取接口不可达=failed、探测异常=error),都可重试。 */
|
||||
network_error: { label: '网络重试', tone: 'is-retry' },
|
||||
server_error: { label: '上游重试', tone: 'is-retry' },
|
||||
/** 欠费(现网 21 行):修之前就只有 `check_status=failed` 这一条路径认得它,改后按码认、不再吊在状态上。 */
|
||||
insufficient_balance: { label: '欠费', tone: 'is-warn' },
|
||||
/** 提取成功但链接里组不出可验连的地址(没带 key/pwd):要用户重填,不是「查不出」。 */
|
||||
tunnel_unverified: { label: '链接缺账密', tone: 'is-warn' },
|
||||
invalid_key: { label: '密钥失效', tone: 'is-blocked' },
|
||||
forbidden: { label: '鉴权被拒', tone: 'is-blocked' },
|
||||
bad_request: { label: '参数被拒', tone: 'is-blocked' },
|
||||
provider_error: { label: '供应商报错', tone: 'is-blocked' },
|
||||
}
|
||||
|
||||
/** 行级档位:后端 `UserApiSecretService` 按 failed > incomplete > passed > error > unknown 聚合,界面不重排这个优先级。 */
|
||||
const ROW_STATUS_BANDS: Record<string, StatusBand> = {
|
||||
passed: { label: '检测通过', tone: 'is-allowed' },
|
||||
failed: { label: '检测失败', tone: 'is-blocked' },
|
||||
incomplete: { label: '未配齐', tone: 'is-warn' },
|
||||
error: INDETERMINATE_BAND,
|
||||
}
|
||||
/** 行级「可重试」:仅当整行的问题**只**出在可重试那一族码上时替换掉「无法判定」(后端给不了这一档,前端按格子的码补)。 */
|
||||
const ROW_RETRY_BAND: StatusBand = { label: '可重试', tone: 'is-retry' }
|
||||
|
||||
/** 单模块的可比较形状(不引 `@/api/*`:本文件要能被零别名的 `node --test` 直测)。 */
|
||||
interface CheckModuleLike {
|
||||
exists?: boolean | null
|
||||
moduleLabel?: string | null
|
||||
checkStatus?: string | null
|
||||
checkCode?: string | null
|
||||
checkMessage?: string | null
|
||||
}
|
||||
|
||||
/** 一行的可比较形状:只用到行状态 + 三个格子。 */
|
||||
interface SecretRowLike {
|
||||
status?: string | null
|
||||
similarAsin?: CheckModuleLike | null
|
||||
appearancePatent?: CheckModuleLike | null
|
||||
proxy?: CheckModuleLike | null
|
||||
}
|
||||
|
||||
/** 按归一后的键查档位表:空键与表里没有的键都返回 null(调用方兜底,绝不硬认一档)。 */
|
||||
function bandOf(table: Record<string, StatusBand>, raw: unknown): StatusBand | null {
|
||||
const key = normalizeKey(raw)
|
||||
if (!key || !Object.prototype.hasOwnProperty.call(table, key)) return null
|
||||
return table[key] ?? null
|
||||
}
|
||||
|
||||
/** 码 → 档位;空码或这表里没有的码返回 null(由调用方按状态兜底,不硬认一档)。 */
|
||||
export function checkCodeBand(code: string | null | undefined): StatusBand | null {
|
||||
return bandOf(CHECK_CODE_BANDS, code)
|
||||
}
|
||||
|
||||
/** 这一档是不是「等一等再点」那一族(可重试):配色与行级补档都读这一个判据,不散落码名。 */
|
||||
export function isRetryBand(band: StatusBand | null | undefined): boolean {
|
||||
return band?.tone === 'is-retry'
|
||||
}
|
||||
|
||||
/**
|
||||
* 单格状态药丸:先看是否已配置,再看 `check_status=passed`,然后**按 `check_code` 分档**,
|
||||
* 都不认才按状态兜底。
|
||||
*/
|
||||
export function moduleStatusBand(module: CheckModuleLike | null | undefined): StatusBand {
|
||||
if (!module || !module.exists) return NOT_CONFIGURED_BAND
|
||||
const status = normalizeKey(module.checkStatus)
|
||||
if (status === 'passed') return PASSED_BAND
|
||||
const band = checkCodeBand(module.checkCode)
|
||||
if (band) return band
|
||||
if (status === 'error') return INDETERMINATE_BAND
|
||||
if (status === 'failed') return GENERIC_FAILED_BAND
|
||||
// ''/unknown/后端下一版新增的状态值:宁可说「未检测」,也不替后端编造一个结论
|
||||
return NOT_CHECKED_BAND
|
||||
}
|
||||
|
||||
/** 行级状态药丸:后端聚合成 `error` 时,若这一行**没有结论的格子全是可重试那一族**,补成「可重试」。 */
|
||||
export function rowStatusBand(row: SecretRowLike | null | undefined): StatusBand {
|
||||
const status = normalizeKey(row?.status)
|
||||
if (status === 'error' && awaitsRetryOnly(row)) return ROW_RETRY_BAND
|
||||
// 行级 `unknown`=后端还没问过(不是「问了问不出」),留「未检测」这一档,与筛选项里那一行同词
|
||||
return bandOf(ROW_STATUS_BANDS, status) ?? NOT_CHECKED_BAND
|
||||
}
|
||||
|
||||
/**
|
||||
* 这一行是不是「点一次就有答案」:后端把 error 之上的 failed/incomplete 都判掉了才轮到 error,
|
||||
* 所以这里只需再确认剩下那些没通过的格子都落在可重试档——混进一格「链接缺账密」就不算可重试,
|
||||
* 那一格不会自己好,把整行说成「可重试」等于让管理员一直等。
|
||||
*/
|
||||
function awaitsRetryOnly(row: SecretRowLike | null | undefined): boolean {
|
||||
const pending = modulesOf(row).filter(
|
||||
(module) => Boolean(module?.exists) && normalizeKey(module?.checkStatus) !== 'passed',
|
||||
)
|
||||
return pending.length > 0 && pending.every((module) => isRetryBand(moduleStatusBand(module)))
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级 tooltip 的明细:逐格把**后端原文** `check_message` 抄出来(运维判「是欠费还是被自己占着」就靠这句)。
|
||||
* 前端不拼句子、不改一个字;没检测过的格子没有这句话,自然不出现。
|
||||
*/
|
||||
export function rowDetailLines(row: SecretRowLike | null | undefined): string[] {
|
||||
return modulesOf(row)
|
||||
.filter((module) => Boolean(module?.exists))
|
||||
.map((module) => {
|
||||
const message = String(module?.checkMessage ?? '').trim()
|
||||
if (!message) return ''
|
||||
const label = String(module?.moduleLabel ?? '').trim()
|
||||
return label ? `${label}:${message}` : message
|
||||
})
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function modulesOf(row: SecretRowLike | null | undefined): CheckModuleLike[] {
|
||||
return [row?.similarAsin, row?.appearancePatent, row?.proxy].filter(Boolean) as CheckModuleLike[]
|
||||
}
|
||||
|
||||
/** 后端 `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}`
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 252,
|
||||
"cases": 1753,
|
||||
"pins": 456,
|
||||
"reads": 651
|
||||
"files": 253,
|
||||
"cases": 1772,
|
||||
"pins": 457,
|
||||
"reads": 652
|
||||
},
|
||||
"files": {
|
||||
"admin-scaffold.test.ts": {
|
||||
@@ -1266,6 +1266,11 @@
|
||||
"cases": 4,
|
||||
"pins": 0,
|
||||
"reads": 1
|
||||
},
|
||||
"密钥货源标签与代理脱敏.test.ts": {
|
||||
"cases": 19,
|
||||
"pins": 1,
|
||||
"reads": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,262 @@
|
||||
/**
|
||||
* 密钥管理列表页「检测结果分档」的界面侧判据(2026-11-02)。
|
||||
*
|
||||
* 现网证据:库里 uid=1 的 proxy 行是 `check_status=error / check_code=channel_busy`,
|
||||
* 数据是对的、界面不认识这个码,于是渲染成「无法判定」——管理员分不清
|
||||
* 「被自己的采集占着(等 3 分钟再点)」「密钥坏了」「欠费」这三种完全不同的处置。
|
||||
*
|
||||
* 这一支跑真组件+真 pinia store,API 用假数据顶掉,逐档核对:
|
||||
* ① 药丸文字与配色类名(`is-retry` 是新档,既不红也不黄);
|
||||
* ② 悬停详情里能看到后端 `check_message` 原文(措辞权威在后端,界面只搬运);
|
||||
* ③ 一格上的两颗药丸分别取 `channel`(货源)与 `check_status`/`check_code`(状态)——
|
||||
* 把状态当渠道渲染(或反过来)会在这里红。
|
||||
*
|
||||
* 夹具里的凭据一律假值(fakekey/fakepwd/sk-fake),本仓有尺子按长度+高熵认凭据。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/user-secret-status-band.mount.test.ts`
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } 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)
|
||||
|
||||
/** 后端那句人话(CHANNEL_BUSY_MESSAGE 的形状):措辞权威在后端,界面只原样透出。 */
|
||||
const BUSY_MESSAGE = '通道正被你自己的采集占着,等约 3 分钟释放后再点检测'
|
||||
const BALANCE_MESSAGE = '代理服务商余额不足,请充值后重试'
|
||||
const MASKED_PROXY = 'https://overseas.proxy.qg.net'
|
||||
|
||||
function moduleCell(moduleKey: string, over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
moduleKey,
|
||||
moduleLabel: moduleKey,
|
||||
channel: null,
|
||||
masked: 'sk-f****9BgQ',
|
||||
full: '',
|
||||
exists: true,
|
||||
locked: false,
|
||||
checkStatus: 'passed',
|
||||
checkCode: 'ok',
|
||||
checkMessage: '连通正常',
|
||||
checkLatencyMs: 12,
|
||||
checkedAt: '2026-11-02T15:51:07',
|
||||
updatedAt: '2026-11-02T15:51:07',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function row(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
userId: 7,
|
||||
username: 'alice',
|
||||
groups: [],
|
||||
leaderUsername: '',
|
||||
similarAsin: moduleCell('similar-asin', { moduleLabel: '货源查询密钥', channel: 'longtaitou' }),
|
||||
appearancePatent: moduleCell('appearance-patent', { moduleLabel: '外观专利密钥', channel: 't8star' }),
|
||||
proxy: moduleCell('proxy', { moduleLabel: '代理设置', channel: 'qingguo', masked: MASKED_PROXY }),
|
||||
status: 'passed',
|
||||
statusMessage: '三项均检测通过',
|
||||
createdAt: '2026-11-01T09:00:00',
|
||||
updatedAt: '2026-11-02T15:51:07',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
/** 表头文字定位列(不靠列序数:加列就会全体错位),返回该格里的药丸。 */
|
||||
function pills(wrapper: VueWrapper<Element>, header: 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].findAll('.wh-pill').map((pill) => ({
|
||||
text: pill.text().trim(),
|
||||
classes: pill.classes(),
|
||||
title: pill.attributes('title') ?? '',
|
||||
}))
|
||||
}
|
||||
|
||||
function cellText(wrapper: VueWrapper<Element>, header: string): string {
|
||||
const headers = wrapper.findAll('thead th').map((th) => th.text().trim())
|
||||
const index = headers.findIndex((label) => label.includes(header))
|
||||
return wrapper.findAll('tbody tr')[0].findAll('td')[index].text()
|
||||
}
|
||||
|
||||
describe('密钥管理页:检测结果按 check_code 分档渲染', () => {
|
||||
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(rowValue: Record<string, unknown>) {
|
||||
secretsApi.fetchUserSecretList.mockResolvedValue({ items: [rowValue], total: 1, page: 1, pageSize: 15, groupOptions: [] })
|
||||
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
/** 现网 uid=1 那一行的形状:error + channel_busy。 */
|
||||
function busyRow() {
|
||||
return row({
|
||||
status: 'error',
|
||||
statusMessage: '存在无法判定的检测结果',
|
||||
proxy: moduleCell('proxy', {
|
||||
moduleLabel: '代理设置',
|
||||
channel: 'qingguo',
|
||||
masked: MASKED_PROXY,
|
||||
checkStatus: 'error',
|
||||
checkCode: 'channel_busy',
|
||||
checkMessage: BUSY_MESSAGE,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
it('channel_busy 渲染成「无可用通道」+独立配色,不再掉进「无法判定」', async () => {
|
||||
const wrapper = await mountWith(busyRow())
|
||||
const proxyPills = pills(wrapper, '代理设置')
|
||||
const statusPill = proxyPills[proxyPills.length - 1]
|
||||
expect(statusPill.text).toBe('无可用通道')
|
||||
expect(statusPill.classes).toContain('is-retry')
|
||||
expect(cellText(wrapper, '代理设置')).not.toContain('无法判定')
|
||||
// 供应商那颗药丸还在原位:改的是状态档,不是把货源档挤掉
|
||||
expect(proxyPills[0].text).toBe('青果')
|
||||
expect(proxyPills[0].classes).toContain('is-source')
|
||||
})
|
||||
|
||||
it('整行只剩「等一等」那一族时,行级状态列补成「可重试」', async () => {
|
||||
const wrapper = await mountWith(busyRow())
|
||||
const rowPill = pills(wrapper, '状态')[0]
|
||||
expect(rowPill.text).toBe('可重试')
|
||||
expect(rowPill.classes).toContain('is-retry')
|
||||
expect(rowPill.text).not.toBe('无法判定')
|
||||
})
|
||||
|
||||
it('混进一格「不会自己好」的问题时,行级不许谎报可重试', async () => {
|
||||
const wrapper = await mountWith({
|
||||
...busyRow(),
|
||||
appearancePatent: moduleCell('appearance-patent', {
|
||||
moduleLabel: '外观专利密钥',
|
||||
channel: 't8star',
|
||||
checkStatus: 'error',
|
||||
checkCode: 'tunnel_unverified',
|
||||
checkMessage: '这条链接里没有可用于隧道验连的账密,请重新填写',
|
||||
}),
|
||||
})
|
||||
expect(pills(wrapper, '状态')[0].text).toBe('无法判定')
|
||||
expect(pills(wrapper, '外观专利密钥').at(-1)!.text).toBe('链接缺账密')
|
||||
})
|
||||
|
||||
it('悬停能看到后端 check_message 原文:单格与行级 tooltip 都带上', async () => {
|
||||
const wrapper = await mountWith(busyRow())
|
||||
const proxyStatusTitle = pills(wrapper, '代理设置').at(-1)!.title
|
||||
expect(proxyStatusTitle).toContain(BUSY_MESSAGE)
|
||||
expect(proxyStatusTitle).toContain(MASKED_PROXY, '脱敏值仍然在同一条 tooltip 里')
|
||||
const rowTitle = pills(wrapper, '状态')[0].title
|
||||
expect(rowTitle).toContain('存在无法判定的检测结果', '后端行级摘要不动')
|
||||
expect(rowTitle).toContain(`代理设置:${BUSY_MESSAGE}`, '运维判「是欠费还是被自己占着」就靠这句')
|
||||
})
|
||||
|
||||
it('欠费(现网 21 行)保留自己那一档,不被新码表挤去「无法判定」', async () => {
|
||||
const wrapper = await mountWith(row({
|
||||
status: 'failed',
|
||||
statusMessage: '存在检测失败的配置',
|
||||
proxy: moduleCell('proxy', {
|
||||
moduleLabel: '代理设置',
|
||||
channel: 'qingguo',
|
||||
masked: MASKED_PROXY,
|
||||
checkStatus: 'failed',
|
||||
checkCode: 'insufficient_balance',
|
||||
checkMessage: BALANCE_MESSAGE,
|
||||
}),
|
||||
}))
|
||||
const balancePill = pills(wrapper, '代理设置').at(-1)!
|
||||
expect(balancePill.text).toBe('欠费')
|
||||
expect(balancePill.classes).toContain('is-warn')
|
||||
expect(pills(wrapper, '状态')[0].text).toBe('检测失败', '行级优先级是后端的:failed 永远压过 error')
|
||||
expect(pills(wrapper, '代理设置').at(-1)!.title).toContain(BALANCE_MESSAGE)
|
||||
})
|
||||
|
||||
it('密钥坏了与查不出是两档:invalid_key 红、空码/未知码才是「无法判定」', async () => {
|
||||
const wrapper = await mountWith(row({
|
||||
status: 'error',
|
||||
similarAsin: moduleCell('similar-asin', { moduleLabel: '货源查询密钥', channel: 'longtaitou', checkStatus: 'failed', checkCode: 'invalid_key', checkMessage: '密钥无效(401)' }),
|
||||
appearancePatent: moduleCell('appearance-patent', { moduleLabel: '外观专利密钥', channel: 't8star', checkStatus: 'error', checkCode: '', checkMessage: '' }),
|
||||
proxy: moduleCell('proxy', { moduleLabel: '代理设置', channel: 'qingguo', masked: MASKED_PROXY, checkStatus: 'error', checkCode: 'a_code_not_registered', checkMessage: '' }),
|
||||
}))
|
||||
expect(pills(wrapper, '货源查询密钥').at(-1)!.text).toBe('密钥失效')
|
||||
expect(pills(wrapper, '货源查询密钥').at(-1)!.classes).toContain('is-blocked')
|
||||
expect(pills(wrapper, '外观专利密钥').at(-1)!.text).toBe('无法判定')
|
||||
expect(pills(wrapper, '代理设置').at(-1)!.text).toBe('无法判定')
|
||||
})
|
||||
|
||||
it('没配与没检测不许冒充「无法判定」', async () => {
|
||||
const wrapper = await mountWith(row({
|
||||
status: 'unknown',
|
||||
statusMessage: '存在尚未检测的配置',
|
||||
similarAsin: moduleCell('similar-asin', { moduleLabel: '货源查询密钥', exists: false, checkStatus: 'unknown', checkCode: '', checkMessage: '' }),
|
||||
appearancePatent: moduleCell('appearance-patent', { moduleLabel: '外观专利密钥', channel: 't8star', checkStatus: 'unknown', checkCode: '', checkMessage: '' }),
|
||||
}))
|
||||
expect(pills(wrapper, '货源查询密钥').at(-1)!.text).toBe('未配置')
|
||||
expect(cellText(wrapper, '货源查询密钥')).toContain('未配置')
|
||||
expect(pills(wrapper, '外观专利密钥').at(-1)!.text).toBe('未检测')
|
||||
expect(pills(wrapper, '状态')[0].text).toBe('未检测')
|
||||
})
|
||||
|
||||
it('一格上的两颗药丸不同源:货源取 channel、状态取 check_status/check_code', async () => {
|
||||
// 把代理供应商值塞进 LLM 行的 channel:货源那颗药丸必须认不出(走「—」),
|
||||
// 状态那颗仍按 check_code 出「鉴权被拒」——两值互不串门,才是「不同源」的正证。
|
||||
const wrapper = await mountWith(row({
|
||||
status: 'failed',
|
||||
similarAsin: moduleCell('similar-asin', { moduleLabel: '货源查询密钥', channel: 'qingguo', checkStatus: 'failed', checkCode: 'forbidden', checkMessage: '密钥被拒绝(403)' }),
|
||||
appearancePatent: moduleCell('appearance-patent', { moduleLabel: '外观专利密钥', channel: 't8star', checkStatus: 'passed', checkCode: 'ok' }),
|
||||
}))
|
||||
const similarPills = pills(wrapper, '货源查询密钥')
|
||||
expect(similarPills[0].text).toBe('—')
|
||||
expect(similarPills[1].text).toBe('鉴权被拒')
|
||||
// 反向:把状态词塞进渠道位也不会被认成货源
|
||||
const llmPills = pills(wrapper, '外观专利密钥')
|
||||
expect(llmPills[0].text).toBe('贞贞')
|
||||
expect(llmPills[1].text).toBe('通过')
|
||||
expect(llmPills[0].classes).toContain('is-source')
|
||||
expect(llmPills[1].classes).toContain('is-allowed')
|
||||
})
|
||||
|
||||
it('筛选项把 error 这一档的两个可能读法都点名(选了要能筛到无可用通道的行)', async () => {
|
||||
const wrapper = await mountWith(busyRow())
|
||||
const options = wrapper.findAll('.secrets-filter-row select')[0].findAll('option').map((option) => option.text().trim())
|
||||
expect(options).toContain('无法判定/可重试')
|
||||
expect(options).not.toContain('无法判定')
|
||||
})
|
||||
|
||||
it('立即检测的 toast 用后端那句原文,不再硬写「无法判定」', async () => {
|
||||
secretsApi.fetchUserSecretList.mockResolvedValue({ items: [busyRow()], total: 1, page: 1, pageSize: 15, groupOptions: [] })
|
||||
secretsApi.checkUserSecret.mockResolvedValue([
|
||||
{ moduleKey: 'proxy', checkStatus: 'error', checkCode: 'channel_busy', checkMessage: BUSY_MESSAGE, checkLatencyMs: 30, checkedAt: '2026-11-02T15:51:07', viaProxy: false },
|
||||
])
|
||||
const wrapper = mount(UserSecretsPage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
const checkButton = wrapper.findAll('button').find((button) => button.text().trim() === '立即检测')
|
||||
expect(checkButton, '行内应有「立即检测」入口').toBeDefined()
|
||||
await checkButton!.trigger('click')
|
||||
await flushPromises()
|
||||
// ElMessage 真渲染进 body:读的是那一句后端原文,不是界面自己拼的「部分配置本次无法判定」
|
||||
const shown = document.body.textContent ?? ''
|
||||
expect(shown).toContain(BUSY_MESSAGE)
|
||||
expect(shown).not.toContain('部分配置本次无法判定')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,278 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
import {
|
||||
DEFAULT_PROXY_PROVIDER,
|
||||
INDETERMINATE_BAND,
|
||||
NOT_CHECKED_BAND,
|
||||
PASSED_BAND,
|
||||
UNKNOWN_SOURCE_LABEL,
|
||||
buildProxyEntryPayload,
|
||||
checkCodeBand,
|
||||
emptyProxyEntryDraft,
|
||||
isRetryBand,
|
||||
llmSourceLabel,
|
||||
moduleStatusBand,
|
||||
proxyDisplayText,
|
||||
proxySourceLabel,
|
||||
rowDetailLines,
|
||||
rowStatusBand,
|
||||
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),界面既不回落原文、也没有可预填的整条链接;
|
||||
// ③ 检测结果按 `check_code` 分档——后端今天把青果检测分成一族供应商码,界面只认
|
||||
// `check_status` 三档就会把「通道被自己占着」和「密钥坏了」「欠费」挤成同一句「无法判定」。
|
||||
// 夹具里的 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')
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* ③ 检测结果按 check_code 分档(2026-11-02)
|
||||
*
|
||||
* 码集与状态取自后端 `UserApiSecretCheckService` 的 `CODE_*`/`STATUS_*`(逐条对着源码抄):
|
||||
* `channel_busy`、`tunnel_unverified`、`rate_limited`、`timeout`、`network_error`、`server_error`
|
||||
* 落 `error`;`insufficient_balance`、`invalid_key`、`forbidden`、`bad_request`、`provider_error`、
|
||||
* `network_error`(提取接口不可达那一支)落 `failed`;`ok` 落 `passed`。
|
||||
* 界面只看 `check_status` 的话,前一半全被挤成「无法判定」——现网 uid=1 的 proxy 行就是这么花的。
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
/** 后端 2026-11-02 那一版实际会下发的码全集(新增码时这张清单要一起长)。 */
|
||||
const BACKEND_CHECK_CODES = [
|
||||
'ok',
|
||||
'channel_busy',
|
||||
'invalid_key',
|
||||
'forbidden',
|
||||
'bad_request',
|
||||
'rate_limited',
|
||||
'server_error',
|
||||
'network_error',
|
||||
'timeout',
|
||||
'provider_error',
|
||||
'insufficient_balance',
|
||||
'tunnel_unverified',
|
||||
]
|
||||
|
||||
/** 已配置的一格(默认 error + 空码:那是「问了问不出」的形状,不是任何一档码)。 */
|
||||
function checkedModule(over: Record<string, unknown> = {}) {
|
||||
return { exists: true, moduleLabel: '代理设置', checkStatus: 'error', checkCode: '', checkMessage: '', ...over }
|
||||
}
|
||||
|
||||
test('后端分出的每一档码都不许掉进「无法判定」(逐码扫全集)', () => {
|
||||
const offenders: string[] = []
|
||||
for (const code of BACKEND_CHECK_CODES) {
|
||||
// 同一个码在 error/failed 两个状态下都扫一遍:`network_error` 后端就两支都用
|
||||
for (const status of ['error', 'failed']) {
|
||||
const band = moduleStatusBand(checkedModule({ checkCode: code, checkStatus: status }))
|
||||
if (band.label === INDETERMINATE_BAND.label) offenders.push(`${status}/${code}`)
|
||||
}
|
||||
}
|
||||
assert.deepEqual(offenders, [], '这些码又被当成「无法判定」渲染:' + offenders.join(', '))
|
||||
})
|
||||
|
||||
test('逐码档位表:档名与配色都登记在案(可重试那一族既不正红也不黄)', () => {
|
||||
const table: Array<[string, string, string]> = [
|
||||
['ok', '通过', 'is-allowed'],
|
||||
['channel_busy', '无可用通道', 'is-retry'],
|
||||
['rate_limited', '限流重试', 'is-retry'],
|
||||
['timeout', '超时重试', 'is-retry'],
|
||||
['network_error', '网络重试', 'is-retry'],
|
||||
['server_error', '上游重试', 'is-retry'],
|
||||
['insufficient_balance', '欠费', 'is-warn'],
|
||||
['tunnel_unverified', '链接缺账密', 'is-warn'],
|
||||
['invalid_key', '密钥失效', 'is-blocked'],
|
||||
['forbidden', '鉴权被拒', 'is-blocked'],
|
||||
['bad_request', '参数被拒', 'is-blocked'],
|
||||
['provider_error', '供应商报错', 'is-blocked'],
|
||||
]
|
||||
assert.deepEqual(table.map((row) => row[0]).sort(), [...BACKEND_CHECK_CODES].sort(), '这张表与码集不同步:漏档就红')
|
||||
for (const [code, label, tone] of table) {
|
||||
const band = moduleStatusBand(checkedModule({ checkCode: code }))
|
||||
assert.equal(band.label, label, `码 ${code} 的档名变了`)
|
||||
assert.equal(band.tone, tone, `码 ${code} 的配色变了`)
|
||||
assert.ok(band.label.length <= 5, `档名「${band.label}」超过 5 字:状态列 130px 会把药丸裁掉`)
|
||||
}
|
||||
})
|
||||
|
||||
test('变异钉子:把 channel_busy 改回「不认识」立刻红', () => {
|
||||
const busy = moduleStatusBand(checkedModule({ checkCode: 'channel_busy' }))
|
||||
const blank = moduleStatusBand(checkedModule({ checkCode: '' }))
|
||||
// 这一条就是今天的线上形状:认不出码 ⇒ 与空码同档 ⇒ 显示「无法判定」
|
||||
assert.notDeepEqual(busy, blank, 'channel_busy 与空码同档=又回到「error 一律无法判定」')
|
||||
assert.ok(isRetryBand(busy), 'channel_busy 必须落在可重试那一族')
|
||||
assert.equal(busy.tone, 'is-retry')
|
||||
assert.notEqual(busy.tone, INDETERMINATE_BAND.tone, '可重试与查不出必须是两种配色')
|
||||
})
|
||||
|
||||
test('欠费(现网 21 行)有自己的一档,且不再吊在 check_status=failed 上', () => {
|
||||
const broke = checkedModule({ checkCode: 'insufficient_balance' })
|
||||
assert.deepEqual(moduleStatusBand(broke), { label: '欠费', tone: 'is-warn' })
|
||||
// 后端哪天把欠费落成 error,界面仍然说欠费(按码判档,不看状态脸色)
|
||||
assert.deepEqual(moduleStatusBand({ ...broke, checkStatus: 'error' }), { label: '欠费', tone: 'is-warn' })
|
||||
assert.notEqual(moduleStatusBand(broke).label, INDETERMINATE_BAND.label)
|
||||
})
|
||||
|
||||
test('「无法判定」只留给真没结论:空码与未知码才落这一档', () => {
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkCode: '' })), INDETERMINATE_BAND)
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkCode: ' ' })), INDETERMINATE_BAND)
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkCode: 'a_code_backend_has_not_invented_yet' })), INDETERMINATE_BAND)
|
||||
// 没问过的格子不是「问不出」:后端 upsert 后 check_status=unknown,这里留「未检测」
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkStatus: 'unknown' })), NOT_CHECKED_BAND)
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkStatus: '' })), NOT_CHECKED_BAND)
|
||||
assert.notDeepEqual(NOT_CHECKED_BAND, INDETERMINATE_BAND, '「未检测」与「无法判定」是两件事,不许并档')
|
||||
// 未配置优先于一切状态
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ exists: false, checkCode: 'channel_busy' })), { label: '未配置', tone: 'is-unknown' })
|
||||
assert.deepEqual(moduleStatusBand(undefined), { label: '未配置', tone: 'is-unknown' })
|
||||
// 后端新增一档状态而前端没登记:failed 兜底成「失败」,不把坏说成查不出
|
||||
assert.equal(moduleStatusBand(checkedModule({ checkStatus: 'failed', checkCode: 'brand_new_code' })).tone, 'is-blocked')
|
||||
})
|
||||
|
||||
test('passed 状态一律「通过」:码位上留着旧值也不许翻档', () => {
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkStatus: 'passed', checkCode: 'ok' })), PASSED_BAND)
|
||||
// 后端 applyCheckOutcome 状态与码是同一条 UPDATE,留旧码属异常;此时以状态为准,不给管理员一个假红灯
|
||||
assert.deepEqual(moduleStatusBand(checkedModule({ checkStatus: 'passed', checkCode: 'timeout' })), PASSED_BAND)
|
||||
})
|
||||
|
||||
test('码名归一:大小写与首尾空格不改变档位', () => {
|
||||
assert.deepEqual(checkCodeBand(' CHANNEL_BUSY '), checkCodeBand('channel_busy'))
|
||||
assert.deepEqual(checkCodeBand('Insufficient_Balance')?.label, '欠费')
|
||||
assert.equal(checkCodeBand(null), null)
|
||||
assert.equal(checkCodeBand(undefined), null)
|
||||
assert.equal(checkCodeBand(''), null)
|
||||
})
|
||||
|
||||
test('行级状态:整行只剩可重试那一族时补成「可重试」,混进别的就还「无法判定」', () => {
|
||||
const busyRow = {
|
||||
status: 'error',
|
||||
similarAsin: checkedModule({ moduleLabel: '货源查询密钥', checkStatus: 'passed', checkCode: 'ok' }),
|
||||
appearancePatent: checkedModule({ moduleLabel: '外观专利密钥', checkStatus: 'passed', checkCode: 'ok' }),
|
||||
proxy: checkedModule({ checkStatus: 'error', checkCode: 'channel_busy' }),
|
||||
}
|
||||
assert.deepEqual(rowStatusBand(busyRow), { label: '可重试', tone: 'is-retry' })
|
||||
// 另一格是「链接缺账密」:那一格不会自己好,把整行说成可重试等于让管理员一直等
|
||||
assert.deepEqual(rowStatusBand({ ...busyRow, appearancePatent: checkedModule({ checkCode: 'tunnel_unverified' }) }), INDETERMINATE_BAND)
|
||||
// 后端行级聚合的其余取值原样保留(优先级是后端的,界面不重排)
|
||||
assert.deepEqual(rowStatusBand({ status: 'passed' }), { label: '检测通过', tone: 'is-allowed' })
|
||||
assert.deepEqual(rowStatusBand({ status: 'failed' }), { label: '检测失败', tone: 'is-blocked' })
|
||||
assert.deepEqual(rowStatusBand({ status: 'incomplete' }), { label: '未配齐', tone: 'is-warn' })
|
||||
assert.deepEqual(rowStatusBand({ status: 'unknown' }), NOT_CHECKED_BAND)
|
||||
assert.deepEqual(rowStatusBand({ status: 'error' }), INDETERMINATE_BAND, '行级 error 但一格码都认不出时仍是「无法判定」')
|
||||
assert.deepEqual(rowStatusBand(null), NOT_CHECKED_BAND)
|
||||
})
|
||||
|
||||
test('行级明细逐字搬后端 check_message:前端不改写、不另拼句子', () => {
|
||||
const busyMessage = '后端原话:通道被占,等约 3 分钟再点'
|
||||
const lines = rowDetailLines({
|
||||
status: 'error',
|
||||
similarAsin: checkedModule({ moduleLabel: '货源查询密钥', checkStatus: 'passed', checkCode: 'ok', checkMessage: '连通正常' }),
|
||||
appearancePatent: checkedModule({ moduleLabel: '外观专利密钥', exists: false, checkMessage: '' }),
|
||||
proxy: checkedModule({ checkStatus: 'error', checkCode: 'channel_busy', checkMessage: busyMessage }),
|
||||
})
|
||||
assert.deepEqual(lines, ['货源查询密钥:连通正常', `代理设置:${busyMessage}`])
|
||||
assert.ok(lines[1].endsWith(busyMessage), `后端那句被改写了:${lines[1]}`)
|
||||
// 没有 message 的格子不占位(否则 tooltip 里一串空段,运维读不到重点)
|
||||
assert.deepEqual(rowDetailLines({ proxy: checkedModule({ checkMessage: ' ' }) }), [])
|
||||
})
|
||||
|
||||
test('页面只有一张码表:不留旧 switch、tooltip 取后端 checkMessage、is-retry 真有条配色', () => {
|
||||
const page = readSource('src/pages/account/UserSecretsPage.vue')
|
||||
// ① 页面不得自带第二张表:两处各判各的,后端加分档时界面只会漏(今天漏的就是 channel_busy)
|
||||
for (const code of BACKEND_CHECK_CODES) {
|
||||
// 'ok' 这种两字母串当子串查必然误报(token/lock 里就有),它也不是会漏进旧 switch 的那族
|
||||
if (code.length < 4) continue
|
||||
assert.ok(!page.includes(code), `页面里又写了一遍码名 ${code}`)
|
||||
}
|
||||
assert.ok(!/case 'error':/.test(page), "页面里还留着按状态硬分档的旧 switch('error' 一律「无法判定」)")
|
||||
assert.match(page, /moduleStatusBand\(/, '单格药丸必须走模型那一档')
|
||||
assert.match(page, /rowStatusBand\(row\)/, '行级药丸必须吃整行:后端只剩一个 error,逐格码才说得清')
|
||||
// ② 悬停那句必须是后端原文,且不许开回 `full` 那条旁路
|
||||
assert.match(page, /module\.checkMessage/, 'tooltip 要的是后端那句人话(运维判欠费还是被自己占着就靠它)')
|
||||
assert.ok(!/module\.full/.test(page), '不得读 full:后台侧恒空,读它等于把脱敏前的行为留在界面里')
|
||||
// ③ 新档位得真有条样式,否则 is-retry 渲染出来是无框无底的裸文本
|
||||
assert.match(page, /\.wh-pill\.is-retry\s*\{[^}]*background/, '页面没有 .is-retry 这一档配色')
|
||||
})
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -180,6 +180,11 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
|
||||
}
|
||||
|
||||
public AppearancePatentParseVo parseAndCreateTask(AppearancePatentParseRequest request, String deviceId) {
|
||||
// 密钥闸门排在解析之前:Excel 解析与建单四段都要花时间与配额,而缺密钥的单跑完也只是
|
||||
// 一张没有 LLM 结论的表(判据见 UserApiSecretService#requireSubmitSecret)。
|
||||
requireUserId(request.getUserId());
|
||||
userApiSecretService.requireSubmitSecret(request.getUserId(),
|
||||
UserSecretModule.APPEARANCE_PATENT, request.getApiKey());
|
||||
return parsePipeline().parseAndCreateTask(request, deviceId);
|
||||
}
|
||||
|
||||
|
||||
+17
-1
@@ -1322,8 +1322,24 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
|
||||
task == null ? null : task.getId(), operation, owner, currentInstanceId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属实例 id:<b>优先读显式列 {@code owner_instance_id}</b>,列缺失时才回落 {@code resultJson} 快照。
|
||||
*
|
||||
* <p>原先只读快照,而快照是建单那一刻写死的、任务转交后不再同步(转交写的是列)。
|
||||
* 本方法给出的值同时是 worker 侧转交作业的目标实例({@code TaskFileJobService#handOffToOwner}
|
||||
* 按 {@code TaskOwnerMismatchException#getOwnerInstanceId()} 改挂),读陈旧快照会把作业转交给
|
||||
* 已经不管这行的实例,死锁只是换了个方向。与 {@code AppearancePatentTaskOwnership#ownerFromTask}
|
||||
* 同一口径。
|
||||
*/
|
||||
private String ownerFromTask(FileTaskEntity task) {
|
||||
if (task == null || task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
if (task == null) {
|
||||
return null;
|
||||
}
|
||||
String column = task.getOwnerInstanceId();
|
||||
if (column != null && !column.isBlank()) {
|
||||
return column.trim();
|
||||
}
|
||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
|
||||
+5
@@ -75,6 +75,7 @@ import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
||||
import com.nanri.aiimage.modules.task.service.TaskVisibleFailureNotice;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -390,6 +391,10 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
if (request.getUserId() == null || request.getUserId() <= 0) {
|
||||
throw new BusinessException("user_id 不合法");
|
||||
}
|
||||
// 密钥闸门排在解析之前:解析、建单四段都要花时间与配额,而缺密钥的单跑完只是
|
||||
// 一张没有 LLM 结论的表(判据见 UserApiSecretService#requireSubmitSecret)。
|
||||
userApiSecretService.requireSubmitSecret(request.getUserId(),
|
||||
UserSecretModule.SIMILAR_ASIN, request.getApiKey());
|
||||
if (request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||
throw new BusinessException("请先上传 Excel 文件");
|
||||
}
|
||||
|
||||
+19
-3
@@ -115,8 +115,25 @@ public class SimilarAsinTaskOwnershipSupport {
|
||||
return context == null ? null : context.ownerInstanceId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属实例 id:<b>优先读显式列 {@code owner_instance_id}</b>,列缺失时才回落 {@code resultJson} 快照。
|
||||
*
|
||||
* <p>原先只读快照,而快照是 parse 那一刻写死的、任务转交后不再同步
|
||||
* ({@code TaskClientPullService.claim} 转交的是列)。两列一旦背离,本方法会把已不归属本机的
|
||||
* 任务判给本机、或把已归属本机的任务判给别台;worker 侧按本方法给出的值转交作业时会转错实例
|
||||
* (外观专利 2026-11-02 现网 33179/33149 即此形状,见
|
||||
* {@code TaskFileJobService#handOffToOwner})。与 {@code AppearancePatentTaskOwnership#ownerFromTask}
|
||||
* 同一口径,四台不得再各读各的。
|
||||
*/
|
||||
public String ownerFromTask(FileTaskEntity task) {
|
||||
if (task == null || task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
if (task == null) {
|
||||
return null;
|
||||
}
|
||||
String column = task.getOwnerInstanceId();
|
||||
if (column != null && !column.isBlank()) {
|
||||
return column.trim();
|
||||
}
|
||||
if (task.getResultJson() == null || task.getResultJson().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
@@ -125,6 +142,7 @@ public class SimilarAsinTaskOwnershipSupport {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[similar-asin] read task owner failed taskId={} err={}", task.getId(), ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -133,8 +151,6 @@ public class SimilarAsinTaskOwnershipSupport {
|
||||
* isJobOwnedByCurrentInstance / ownerFromTask 兼容这条 ownerInstanceId)。
|
||||
* 同时把 fallback 信号写到 task_scope_state.state_json,便于排查。
|
||||
*/
|
||||
}
|
||||
|
||||
public void bindTaskToCurrentOwnerForLocalFallback(FileTaskEntity task, String scopeHash, Integer chunkIndex) {
|
||||
if (task == null || task.getId() == null) {
|
||||
throw new IllegalStateException("Cannot bind local fallback without a task ID");
|
||||
|
||||
+91
-2
@@ -71,11 +71,36 @@ public class TaskFileJobService {
|
||||
return existing;
|
||||
}
|
||||
if ("PENDING".equals(existing.getStatus())) {
|
||||
// 归属对账:调用方传进来的 scopeKey 是按任务**当前** owner 现算的
|
||||
// (各模块的 buildTaskOwnerScopeKey),而 existing 那两列是入队那一刻的快照。
|
||||
// 任务转交过之后不在这里对齐,就会留下「领取按 job.owner、执行校验按
|
||||
// biz_file_task.owner_instance_id」的互斥死锁(2026-11-02 现网 33179/33149:
|
||||
// 单机 12 小时 6381 条拒绝、作业永不终态),而 Python 超时恢复每 2 分钟
|
||||
// 就会走到这一格一次——只补发事件不修归属,等于每 2 分钟确认一遍死锁还在。
|
||||
String expectedOwner = ownerFromScopeKey(scopeKey);
|
||||
TaskFileJobEntity pending = existing;
|
||||
if (expectedOwner != null && !expectedOwner.equals(
|
||||
existing.getOwner() == null ? null : existing.getOwner().trim())) {
|
||||
taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
.eq(TaskFileJobEntity::getId, existing.getId())
|
||||
.eq(TaskFileJobEntity::getStatus, "PENDING")
|
||||
.set(TaskFileJobEntity::getScopeKey, scopeKey)
|
||||
.set(TaskFileJobEntity::getOwner, expectedOwner)
|
||||
.set(TaskFileJobEntity::getErrorMessage, null)
|
||||
.set(TaskFileJobEntity::getUpdatedAt, now));
|
||||
pending = taskFileJobMapper.selectById(existing.getId());
|
||||
log.warn("[task-file-job] PENDING 作业归属与任务当前 owner 背离,已按入队 scopeKey 对账"
|
||||
+ " jobId={} taskId={} moduleType={} from={} to={}",
|
||||
existing.getId(), taskId, moduleType, existing.getOwner(), expectedOwner);
|
||||
if (pending == null) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// PENDING 僵尸兜底:job 入队时若 MQ 发送失败且本地兜底未生效(或消息被
|
||||
// 非 owner 实例静默吞掉),job 会永远停留在 PENDING、无人处理。
|
||||
// 补发一次 dispatch 事件,让调度链重试(幂等:consumer 侧 claim 有状态翻转保护)。
|
||||
publishDispatchEvent(existing);
|
||||
return existing;
|
||||
publishDispatchEvent(pending);
|
||||
return pending;
|
||||
}
|
||||
// 终态失败:retryCount 已达上限的 FAILED job 不再重置为 PENDING,
|
||||
// 否则 finalize 路径会把它反复拉回排队,导致 retryCount 无限累加、任务永远卡在 RUNNING。
|
||||
@@ -1019,6 +1044,70 @@ public class TaskFileJobService {
|
||||
return owner.isBlank() ? null : owner;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #ownerFromScopeKey} 的逆操作:把 scope_key 最后一个 {@code :owner:} 之后的尾段换成指定实例。
|
||||
* 无标记时原样返回——那种 scope_key 本来就不携带归属信息,不该被凭空造出一个 owner 段。
|
||||
*/
|
||||
static String withOwnerInScopeKey(String scopeKey, String owner) {
|
||||
if (scopeKey == null || scopeKey.isBlank() || owner == null || owner.isBlank()) {
|
||||
return scopeKey;
|
||||
}
|
||||
int index = scopeKey.lastIndexOf(OWNER_MARKER);
|
||||
if (index < 0) {
|
||||
return scopeKey;
|
||||
}
|
||||
return (scopeKey.substring(0, index + OWNER_MARKER.length()) + owner.trim()).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把作业改挂到任务的当前归属实例:{@code owner} 列与 {@code scope_key} 的尾段一起换。
|
||||
*
|
||||
* <p><b>为什么必须两个来源一起改。</b>领取按 {@code biz_task_file_job.owner}
|
||||
* ({@link #claimRunnableJobsForOwner}),执行时的归属校验却按 {@code biz_file_task.owner_instance_id}。
|
||||
* 任务转交后两列一旦背离,就是互斥死锁:能领到这行的实例必被校验拒,校验放过的实例必领不到这行。
|
||||
* 2026-11-02 现网任务 33179/33149 即此形状——作业停在 PENDING、每 15 秒被拒一次,
|
||||
* 单机 12 小时 6381 条拒绝,而拒绝走的 {@link #deferRunning} 既不计 retry_count
|
||||
* 也不计 stuck_requeue_count 还每轮刷新 updated_at,两条兜底(卡死重排 20 次判死、
|
||||
* PENDING 遗骸回收)因此永远不触发:这行既不失败也不完成。
|
||||
*
|
||||
* <p><b>为什么不需要额外计数兜底。</b>转交后 {@code job.owner} 与校验读的那个值重合,
|
||||
* 拒绝条件按构造不再成立;要再触发一次,必须任务先合法地再转交一回。
|
||||
*
|
||||
* <p>CAS 按调用方观测到的旧 owner 回撞:期间任务又转交、或作业被别的实例改挂,本次就不生效,
|
||||
* 由下一轮拒绝重新转交,不覆盖别人的改动。
|
||||
*
|
||||
* @return true=本次确实改挂了;false=无需改挂、行已不在预期状态或目标实例为空
|
||||
*/
|
||||
public boolean handOffToOwner(Long jobId, String observedOwner, String targetOwner) {
|
||||
if (jobId == null || jobId <= 0 || targetOwner == null || targetOwner.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
TaskFileJobEntity job = taskFileJobMapper.selectById(jobId);
|
||||
if (job == null) {
|
||||
return false;
|
||||
}
|
||||
String normalizedTarget = targetOwner.trim();
|
||||
String currentOwner = job.getOwner() == null ? "" : job.getOwner().trim();
|
||||
if (normalizedTarget.equals(currentOwner)) {
|
||||
return false;
|
||||
}
|
||||
String normalizedObserved = observedOwner == null ? "" : observedOwner.trim();
|
||||
LambdaUpdateWrapper<TaskFileJobEntity> wrapper = new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
.eq(TaskFileJobEntity::getId, jobId)
|
||||
.eq(TaskFileJobEntity::getStatus, "RUNNING")
|
||||
.set(TaskFileJobEntity::getOwner, normalizedTarget)
|
||||
.set(TaskFileJobEntity::getScopeKey, withOwnerInScopeKey(job.getScopeKey(), normalizedTarget))
|
||||
.set(TaskFileJobEntity::getErrorMessage, null)
|
||||
.set(TaskFileJobEntity::getUpdatedAt, LocalDateTime.now());
|
||||
if (normalizedObserved.isEmpty()) {
|
||||
wrapper.and(w -> w.isNull(TaskFileJobEntity::getOwner)
|
||||
.or().eq(TaskFileJobEntity::getOwner, ""));
|
||||
} else {
|
||||
wrapper.eq(TaskFileJobEntity::getOwner, normalizedObserved);
|
||||
}
|
||||
return taskFileJobMapper.update(null, wrapper) > 0;
|
||||
}
|
||||
|
||||
private TaskFileJobEntity findJob(Long taskId, String moduleType, Long resultId, String jobType) {
|
||||
if (taskId == null || moduleType == null || moduleType.isBlank() || resultId == null || jobType == null || jobType.isBlank()) {
|
||||
return null;
|
||||
|
||||
+12
-3
@@ -375,9 +375,18 @@ public class TaskResultFileJobWorker {
|
||||
}
|
||||
} catch (TaskOwnerMismatchException ex) {
|
||||
// 归属校验失败不是"生成失败":不能计入 retryCount,否则任务会在归属机
|
||||
// 一切正常的情况下被本机重试耗尽判死。退回 PENDING 交还归属实例。
|
||||
log.warn("[task-file-job] process rejected because task belongs to another instance jobId={} taskId={} moduleType={} owner={} current={}",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), ex.getOwnerInstanceId(), ex.getCurrentInstanceId());
|
||||
// 一切正常的情况下被本机重试耗尽判死。
|
||||
// 但也不能只退回 PENDING —— 那是无限空转:领取按 job.owner、这一道校验按任务的
|
||||
// owner_instance_id,两列一旦背离,能领到这行的实例必被校验拒、校验放过的实例
|
||||
// 必领不到这行(2026-11-02 现网 33179/33149:作业停 PENDING 每 15 秒被拒一次,
|
||||
// 单机 12 小时 6381 条拒绝,而 deferRunning 不计任何计数还刷 updated_at,
|
||||
// 卡死重排与 PENDING 遗骸两条兜底因此永不触发——既不失败也不完成)。
|
||||
// 异常携带的 ownerInstanceId 就是校验刚读到的任务当前归属,按它改挂即可闭合。
|
||||
boolean handedOff = taskFileJobService.handOffToOwner(
|
||||
job.getId(), ownerFromScopeKey(job.getScopeKey()), ex.getOwnerInstanceId());
|
||||
log.warn("[task-file-job] process rejected because task belongs to another instance jobId={} taskId={} moduleType={} owner={} current={} handedOff={}",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), ex.getOwnerInstanceId(),
|
||||
ex.getCurrentInstanceId(), handedOff);
|
||||
taskFileJobService.deferRunning(job.getId(), ex.getMessage());
|
||||
} catch (Exception ex) {
|
||||
TaskFileJobEntity latest = taskFileJobService.findById(job.getId());
|
||||
|
||||
+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 = "是否已配置")
|
||||
|
||||
+143
-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,27 @@ 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 分钟释放),"
|
||||
+ "也可能是这把 key 的套餐到期/无余量,或后台把鉴权切成了 IP 白名单档(账密提取于是永远拿不到通道)。"
|
||||
+ "请到青果控制台核对通道数、有效期与鉴权方式后再点检测。";
|
||||
|
||||
/** 提取成功但服务端无法验连的提示文案:如实说"没验成",不拿它冒充 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 +96,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 +192,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 +230,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 +246,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 +255,98 @@ 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})——
|
||||
* **成因不止一种**:同账号其他提取占着(约 3 分钟释放)、套餐到期/无余量、
|
||||
* 或后台把该 key 的鉴权切成 IP 白名单档。2026-11-02 实测:零并发单发仍回此码,
|
||||
* 所以文案不许断言"是你自己的采集占着"(那是猜的,会把人引去等一个不会来的释放);
|
||||
* 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 +357,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 +388,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 {
|
||||
|
||||
+44
-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";
|
||||
@@ -292,6 +292,28 @@ public class UserApiSecretService implements UserSecretCleanupPort {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建单前置:这一单要拿谁的密钥跑 LLM,此刻就得说清。调用方带的密钥(显式覆盖/老任务形状)
|
||||
* 与该用户存好的密钥,两者有一个非空即放行;<b>都为空必须当场拒</b>。
|
||||
*
|
||||
* <p>为什么不能放过去:执行侧读到空密钥走的是「保留原始行」的静默降级
|
||||
* ({@code AppearancePatentLlmSubmissionSupport#readApiKey} 那两条 log.warn)——单子照样跑完、
|
||||
* 表照样出、行数照样扣,只是整列 LLM 结论是空的。用户买到一张没有检测过的结果表却看不出来,
|
||||
* 比一句「没配密钥」的失败更难发现。
|
||||
*
|
||||
* <p>调用方须先校验 userId(各模块自己的入口文案为准),这里不重复判。
|
||||
*/
|
||||
public void requireSubmitSecret(Long userId, UserSecretModule module, String callerSuppliedValue) {
|
||||
if (hasText(callerSuppliedValue)) {
|
||||
return;
|
||||
}
|
||||
if (!findPlainValue(userId, module.key()).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
throw new BusinessException("该账号还没有配置" + module.label() + ":这一单要用它跑 LLM 检测,"
|
||||
+ "缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。");
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务执行兜底读取「货源」:未配置返回空串(调用方按模块默认值处理)。
|
||||
* 代理模块额外做链接域名识别,兜住老数据(只有链接、没有供应商列)的存量行。
|
||||
@@ -689,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) {
|
||||
@@ -1135,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());
|
||||
@@ -1152,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);
|
||||
@@ -1282,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;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -47,7 +47,12 @@ public enum UserSecretModule {
|
||||
return this == PROXY;
|
||||
}
|
||||
|
||||
/** 新建配置的默认货源:LLM 模块=龙抬头,代理=青果(2026-10-29 用户拍板)。 */
|
||||
/**
|
||||
* 新建配置的默认货源:LLM 模块=龙抬头,代理=**极客**(`ProxyProvider.DEFAULT`,
|
||||
* 2026-10-30 用户拍板把 10-29 那句"默认青果"改回极客,青果手动切)。
|
||||
* 这里刻意只跟着 {@link ProxyProvider#DEFAULT} 取值、不写死供应商名:上一版注释就是
|
||||
* 因为写死了"青果"而与代码相反,下一个人照它判断"这行没写 channel 就是青果"会做错事。
|
||||
*/
|
||||
public String defaultChannel() {
|
||||
return isProxy() ? ProxyProvider.DEFAULT.key() : LlmChannel.DEFAULT.key();
|
||||
}
|
||||
|
||||
+5
-2
@@ -38,7 +38,7 @@ import org.junit.jupiter.api.Test;
|
||||
*
|
||||
* <p>扫描一律打在 {@link SourceScan#withoutComments} 剥掉注释的源码上,且判据是"必须存在/等于 N"
|
||||
* 那一形:不剥注释的话,谁在 {@code @Operation} 描述或行尾注释里提一句出口名,就能把护栏喂饱。
|
||||
* 分母(写 126 / 读 63,另有 1 支在册豁免)同样钉死,扫描器坏掉与"真的没人漏接"不会一起恒绿。
|
||||
* 分母(写 128 / 读 64,另有 1 支在册豁免)同样钉死,扫描器坏掉与"真的没人漏接"不会一起恒绿。
|
||||
* 这 190 支里有 39 支是 DTO 形态——只 grep 文本上的 {@code getUserId()} 会把它们整批看漏,
|
||||
* 所以 {@link #dtoTypesWithUserId()} 必须先建一遍"哪些请求类声明了 userId 字段"的索引。</p>
|
||||
*/
|
||||
@@ -92,7 +92,10 @@ class RequestSuppliedIdentityOutletTest {
|
||||
void theScanCoversBothVerbsWithPinnedDenominators() {
|
||||
Scan scan = scanAll();
|
||||
// 28 支进度轮询走 require,其余写类/读类走 resolve;两边都算"已接出口"。
|
||||
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(126);
|
||||
// 128 而不是 126:2026-11-01「失败任务在原任务上重试」新增两支写类端点(TaskRetryController
|
||||
// POST /api/tasks/{taskId}/retry + AppearancePatentController POST /tasks/{taskId}/retry),
|
||||
// 两边都是 @RequestParam("user_id") 先过 resolveOwnershipUserId——记账变大是覆盖面变大,不是放宽分母。
|
||||
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(128);
|
||||
// 64 而不是 63:2026-10-29 随本地采集开关恢复 GET /tasks/{taskId}/queue-payload,
|
||||
// 该 handler 同时接上 resolveOwnershipUserId(不是放宽分母)。
|
||||
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(64);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
+38
-1
@@ -33,6 +33,7 @@ import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
@@ -60,8 +61,11 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -135,6 +139,8 @@ class AppearancePatentCreateTaskSnapshotTest {
|
||||
final TransientPayloadStorageService transientPayloadStorageService = mock(TransientPayloadStorageService.class);
|
||||
final AppearancePatentProperties properties = mock(AppearancePatentProperties.class);
|
||||
final InstanceMetadata instanceMetadata = mock(InstanceMetadata.class);
|
||||
/** 密钥闸门所在的协作者:默认空转(放行),拒单用例显式把它改成抛。 */
|
||||
final UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||
boolean sharedWriteEnabled = true;
|
||||
|
||||
AppearancePatentTaskService service() {
|
||||
@@ -227,7 +233,7 @@ class AppearancePatentCreateTaskSnapshotTest {
|
||||
mock(TaskDistributedLockService.class),
|
||||
instanceMetadata,
|
||||
mock(TaskProgressLightAssembler.class),
|
||||
mock(UserApiSecretService.class));
|
||||
userApiSecretService);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -486,6 +492,37 @@ class AppearancePatentCreateTaskSnapshotTest {
|
||||
assertTrue(harness.events.isEmpty(), "user_id 不合法时不得有任何落库");
|
||||
}
|
||||
|
||||
/**
|
||||
* 缺 LLM 密钥的单必须在建单口拒掉:执行侧读到空密钥是「保留原始行」的静默降级,
|
||||
* 单子跑完、表也出,只是整列检测结论是空的——用户买到一张没检测过的结果却看不出来。
|
||||
* 判据是「闸门排在解析之前」:源文件一次都不该被打开,更不该落库。
|
||||
*/
|
||||
@Test
|
||||
void 缺密钥的单不解析也不建单() throws Exception {
|
||||
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
|
||||
doThrow(new com.nanri.aiimage.common.exception.BusinessException("该账号还没有配置外观专利密钥"))
|
||||
.when(harness.userApiSecretService)
|
||||
.requireSubmitSecret(any(), any(), any());
|
||||
|
||||
assertThrows(com.nanri.aiimage.common.exception.BusinessException.class,
|
||||
() -> harness.service().parseAndCreateTask(
|
||||
request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "d"));
|
||||
|
||||
verify(harness.localFileStorageService, never()).findLocalSourceFile(any());
|
||||
assertTrue(harness.events.isEmpty(), "缺密钥不得解析 Excel、不得建单:" + harness.events);
|
||||
}
|
||||
|
||||
/** 正向对照(防改过头):请求体自带密钥的老形状照常放行,且按本模块的密钥问闸门。 */
|
||||
@Test
|
||||
void 建单前按模块与请求密钥问一次闸门() throws Exception {
|
||||
Harness harness = harnessWithFiles("uploads/main.xlsx", mixedWorkbook(), null, null);
|
||||
|
||||
harness.service().parseAndCreateTask(request(7L, List.of(source("uploads/main.xlsx", "17.xlsx"))), "d");
|
||||
|
||||
verify(harness.userApiSecretService).requireSubmitSecret(7L,
|
||||
UserSecretModule.APPEARANCE_PATENT, "sk-test-0001");
|
||||
}
|
||||
|
||||
@Test
|
||||
void golden文件已入库且非空() {
|
||||
assertNotNull(GOLDEN_CREATE);
|
||||
|
||||
+4
@@ -18,6 +18,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -73,6 +74,9 @@ class SimilarAsinTaskServiceGroupRefTest {
|
||||
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||
@Mock private SimilarAsinImageEmbedder imageEmbedder;
|
||||
|
||||
/** 建单口的 LLM 密钥闸门所在协作者:不声明就注入不进(默认 null ⇒ 闸门调用直接 NPE)。 */
|
||||
@Mock private UserApiSecretService userApiSecretService;
|
||||
|
||||
@InjectMocks private SimilarAsinTaskService service;
|
||||
|
||||
@BeforeAll
|
||||
|
||||
+4
@@ -16,6 +16,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -77,6 +78,9 @@ class SimilarAsinTaskServiceParseDelegationTest {
|
||||
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||
@Mock private SimilarAsinImageEmbedder imageEmbedder;
|
||||
|
||||
/** 建单口的 LLM 密钥闸门所在协作者:不声明就注入不进(默认 null ⇒ 闸门调用直接 NPE)。 */
|
||||
@Mock private UserApiSecretService userApiSecretService;
|
||||
|
||||
@InjectMocks private SimilarAsinTaskService service;
|
||||
|
||||
@BeforeAll
|
||||
|
||||
+4
@@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -68,6 +69,9 @@ class SimilarAsinTaskServiceParseLimitsTest {
|
||||
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||
@Mock private SimilarAsinImageEmbedder imageEmbedder;
|
||||
|
||||
/** 建单口的 LLM 密钥闸门所在协作者:不声明就注入不进(默认 null ⇒ 闸门调用直接 NPE)。 */
|
||||
@Mock private UserApiSecretService userApiSecretService;
|
||||
|
||||
@InjectMocks private SimilarAsinTaskService service;
|
||||
|
||||
@BeforeAll
|
||||
|
||||
+4
@@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -73,6 +74,9 @@ class SimilarAsinTaskServiceParsePreviewTest {
|
||||
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||
@Mock private SimilarAsinImageEmbedder imageEmbedder;
|
||||
|
||||
/** 建单口的 LLM 密钥闸门所在协作者:不声明就注入不进(默认 null ⇒ 闸门调用直接 NPE)。 */
|
||||
@Mock private UserApiSecretService userApiSecretService;
|
||||
|
||||
@InjectMocks private SimilarAsinTaskService service;
|
||||
|
||||
@BeforeAll
|
||||
|
||||
+4
@@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -69,6 +70,9 @@ class SimilarAsinTaskServicePreviewConfigTest {
|
||||
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||
@Mock private SimilarAsinImageEmbedder imageEmbedder;
|
||||
|
||||
/** 建单口的 LLM 密钥闸门所在协作者:不声明就注入不进(默认 null ⇒ 闸门调用直接 NPE)。 */
|
||||
@Mock private UserApiSecretService userApiSecretService;
|
||||
|
||||
@InjectMocks private SimilarAsinTaskService service;
|
||||
|
||||
@BeforeAll
|
||||
|
||||
+4
@@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -70,6 +71,9 @@ class SimilarAsinTaskServiceWorkbookControlTest {
|
||||
@Mock private TransientPayloadStorageService transientPayloadStorageService;
|
||||
@Mock private SimilarAsinImageEmbedder imageEmbedder;
|
||||
|
||||
/** 建单口的 LLM 密钥闸门所在协作者:不声明就注入不进(默认 null ⇒ 闸门调用直接 NPE)。 */
|
||||
@Mock private UserApiSecretService userApiSecretService;
|
||||
|
||||
@InjectMocks private SimilarAsinTaskService service;
|
||||
|
||||
@BeforeAll
|
||||
|
||||
+34
-2
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.config.InstanceMetadata;
|
||||
import com.nanri.aiimage.config.SimilarAsinProperties;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
@@ -30,6 +31,7 @@ import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
@@ -53,6 +55,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
@@ -60,7 +63,10 @@ import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* 相似 ASIN 建单段的现网行为快照(重构蓝图 Phase 4 开工前置)。
|
||||
@@ -394,11 +400,37 @@ class SimilarAsinCreateTaskSnapshotTest {
|
||||
assertEquals(original, read(GOLDEN_CREATE), "恢复原始 golden");
|
||||
}
|
||||
|
||||
/**
|
||||
* 缺 LLM 密钥的单必须在建单口拒掉:执行侧读到空密钥走的是「保留原始行」的静默降级
|
||||
* (单子跑完、表也出,只是整列检测结论是空的),用户买到一张没检测过的结果却看不出来。
|
||||
* 判据是「闸门排在解析之前」:源文件一次都不该被打开,头行一次都不该落库。
|
||||
*/
|
||||
@Test
|
||||
void missingSecretRejectsBeforeParse() {
|
||||
doThrow(new BusinessException("该账号还没有配置货源查询密钥"))
|
||||
.when(userApiSecretService).requireSubmitSecret(any(), any(), any());
|
||||
|
||||
assertThrows(BusinessException.class, () -> service.parseAndCreateTask(
|
||||
request(List.of(source("uploads/20261023/one.xlsx", "one.xlsx"))), "snapshot-device"));
|
||||
|
||||
verify(localFileStorageService, never()).findLocalSourceFile(any());
|
||||
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
|
||||
}
|
||||
|
||||
/** 正向对照(防改过头):请求体自带密钥的老形状照样问闸门,且带的是这一单的值。 */
|
||||
@Test
|
||||
void parseAsksGateWithModuleAndRequestKey() {
|
||||
// 不 stub 源文件:闸门之后第一道就是「源文件不存在」,正好证明闸门排在解析之前
|
||||
assertThrows(BusinessException.class, () -> service.parseAndCreateTask(
|
||||
request(List.of(source("uploads/20261023/one.xlsx", "one.xlsx"))), "snapshot-device"));
|
||||
|
||||
verify(userApiSecretService).requireSubmitSecret(9L, UserSecretModule.SIMILAR_ASIN, "unit-test-key");
|
||||
}
|
||||
|
||||
/** 只在显式点名时写 golden:默认跑测试永远不许改是非源。 */
|
||||
@Test
|
||||
@EnabledIfEnvironmentVariable(named = "SHUFU_SNAPSHOT_WRITE", matches = "true")
|
||||
void write_golden_on_demand() throws Exception {
|
||||
Files.createDirectories(GOLDEN_CREATE.getParentFile().toPath());
|
||||
void write_golden_on_demand() throws Exception { Files.createDirectories(GOLDEN_CREATE.getParentFile().toPath());
|
||||
Files.writeString(GOLDEN_CREATE.toPath(), runAll(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskFileJobMapper;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskFileJobDispatchEvent;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 跨实例 owner 死锁的防回归判据(2026-11-02 现网任务 33179/33149)。
|
||||
*
|
||||
* <p>形状:领取按 {@code biz_task_file_job.owner},执行时的归属校验按
|
||||
* {@code biz_file_task.owner_instance_id}。任务转交后两列背离——能领到这行的实例必被校验拒,
|
||||
* 校验放过的实例必领不到这行;拒绝走的 {@code deferRunning} 既不计 retry_count 也不计
|
||||
* stuck_requeue_count 还每轮刷新 updated_at,两条兜底因此永不触发,作业既不失败也不完成
|
||||
* (单机 12 小时 6381 条拒绝)。
|
||||
*
|
||||
* <p>把 {@link TaskFileJobService#handOffToOwner} 改回「只退回 PENDING 不改挂」、
|
||||
* 或把 {@link TaskFileJobService#enqueueAssembleResult} 的 PENDING 分支改回「只补发事件不对账」,
|
||||
* 本类即红。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class TaskFileJobOwnerHandOffTest {
|
||||
|
||||
private static final String STALE_OWNER = "server-110";
|
||||
private static final String TASK_OWNER = "server-121";
|
||||
|
||||
@Mock private TaskFileJobMapper taskFileJobMapper;
|
||||
@Mock private ApplicationEventPublisher applicationEventPublisher;
|
||||
|
||||
private TaskFileJobService service;
|
||||
|
||||
@BeforeAll
|
||||
static void initializeTableInfo() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
TaskFileJobEntity.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
}
|
||||
|
||||
private static TaskFileJobEntity job(Long id, Long taskId, String status, String owner) {
|
||||
TaskFileJobEntity entity = new TaskFileJobEntity();
|
||||
entity.setId(id);
|
||||
entity.setTaskId(taskId);
|
||||
entity.setModuleType("APPEARANCE_PATENT");
|
||||
entity.setResultId(36102L);
|
||||
entity.setJobType("ASSEMBLE_RESULT");
|
||||
entity.setStatus(status);
|
||||
entity.setOwner(owner);
|
||||
entity.setScopeKey(owner == null ? "task:" + taskId : "task:" + taskId + ":owner:" + owner);
|
||||
entity.setRetryCount(0);
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
return entity;
|
||||
}
|
||||
|
||||
// ==================== withOwnerInScopeKey:ownerFromScopeKey 的逆操作 ====================
|
||||
|
||||
@Test
|
||||
void test_scope_key_只换最后一个_owner_尾段() {
|
||||
assertEquals("task:33179:owner:" + TASK_OWNER,
|
||||
TaskFileJobService.withOwnerInScopeKey("task:33179:owner:" + STALE_OWNER, TASK_OWNER));
|
||||
// Java 侧 ownerFromScopeKey 用 lastIndexOf,所以逆操作也必须只改最后一段
|
||||
assertEquals("task:1:owner:x:owner:" + TASK_OWNER,
|
||||
TaskFileJobService.withOwnerInScopeKey("task:1:owner:x:owner:" + STALE_OWNER, TASK_OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_scope_key_无标记或目标为空时不得凭空造_owner_段() {
|
||||
assertEquals("task:1:plain", TaskFileJobService.withOwnerInScopeKey("task:1:plain", TASK_OWNER));
|
||||
assertEquals("task:1:owner:" + STALE_OWNER,
|
||||
TaskFileJobService.withOwnerInScopeKey("task:1:owner:" + STALE_OWNER, " "));
|
||||
assertNull(TaskFileJobService.withOwnerInScopeKey(null, TASK_OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_逆操作与提取函数必须互逆() {
|
||||
String rebuilt = TaskFileJobService.withOwnerInScopeKey(
|
||||
"task:33179:owner:" + STALE_OWNER, TASK_OWNER);
|
||||
assertEquals(TASK_OWNER, TaskFileJobService.ownerFromScopeKey(rebuilt),
|
||||
"改挂之后按同一枚谓词读回来必须是目标实例,否则转交等于没转");
|
||||
}
|
||||
|
||||
// ==================== handOffToOwner ====================
|
||||
|
||||
@Test
|
||||
void test_改挂必须同时落_owner_列与_scope_key_且按旧_owner_做_cas() {
|
||||
when(taskFileJobMapper.selectById(23815L))
|
||||
.thenReturn(job(23815L, 33179L, "RUNNING", STALE_OWNER));
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
assertTrue(service.handOffToOwner(23815L, STALE_OWNER, TASK_OWNER));
|
||||
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskFileJobEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(taskFileJobMapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<TaskFileJobEntity> wrapper = captor.getValue();
|
||||
String setClause = wrapper.getSqlSet();
|
||||
assertTrue(setClause.contains("owner"), "必须改 owner 列: " + setClause);
|
||||
assertTrue(setClause.contains("scope_key"), "必须同步改 scope_key,否则 lastIndexOf 读回的还是旧实例: " + setClause);
|
||||
assertTrue(setClause.contains("error_message"), "必须清掉那条误导性的归属拒绝文案: " + setClause);
|
||||
assertTrue(wrapper.getCustomSqlSegment().contains("status = "), "只能改挂自己手里的 RUNNING 行: " + wrapper.getCustomSqlSegment());
|
||||
assertTrue(wrapper.getCustomSqlSegment().contains("owner = "), "必须按观测到的旧 owner 回撞: " + wrapper.getCustomSqlSegment());
|
||||
assertTrue(wrapper.getParamNameValuePairs().containsValue("task:33179:owner:" + TASK_OWNER),
|
||||
"scope_key 参数必须是换过尾段的值: " + wrapper.getParamNameValuePairs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_已经挂在目标实例上时不得再发更新() {
|
||||
// 空转的代价就是每轮刷 updated_at:两列重合后必须一口都不动
|
||||
when(taskFileJobMapper.selectById(23815L))
|
||||
.thenReturn(job(23815L, 33179L, "RUNNING", TASK_OWNER));
|
||||
|
||||
assertFalse(service.handOffToOwner(23815L, STALE_OWNER, TASK_OWNER));
|
||||
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_目标实例为空或行已消失时拒绝改挂() {
|
||||
assertFalse(service.handOffToOwner(23815L, STALE_OWNER, null));
|
||||
assertFalse(service.handOffToOwner(23815L, STALE_OWNER, " "));
|
||||
assertFalse(service.handOffToOwner(null, STALE_OWNER, TASK_OWNER));
|
||||
verify(taskFileJobMapper, never()).selectById(any());
|
||||
|
||||
when(taskFileJobMapper.selectById(23815L)).thenReturn(null);
|
||||
assertFalse(service.handOffToOwner(23815L, STALE_OWNER, TASK_OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_cas_未命中时返回失败而不抛() {
|
||||
// 期间任务又转交、或行被别的实例改挂:update 打空,由下一轮拒绝重新转交
|
||||
when(taskFileJobMapper.selectById(23815L))
|
||||
.thenReturn(job(23815L, 33179L, "RUNNING", STALE_OWNER));
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(0);
|
||||
|
||||
assertFalse(service.handOffToOwner(23815L, STALE_OWNER, TASK_OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_旧_owner_为空时_cas_必须走_is_null_而不是空串等值() {
|
||||
when(taskFileJobMapper.selectById(1L)).thenReturn(job(1L, 900L, "RUNNING", null));
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
assertTrue(service.handOffToOwner(1L, null, TASK_OWNER));
|
||||
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskFileJobEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(taskFileJobMapper).update(isNull(), captor.capture());
|
||||
assertTrue(captor.getValue().getCustomSqlSegment().contains("owner IS NULL"),
|
||||
"存量行 owner 为 NULL,等值空串永远打不中: " + captor.getValue().getCustomSqlSegment());
|
||||
}
|
||||
|
||||
// ==================== enqueueAssembleResult 的 PENDING 对账 ====================
|
||||
|
||||
@Test
|
||||
void test_pending_作业重新入队时必须按入队_scope_key_对账归属() {
|
||||
// Python 超时恢复每 2 分钟就会走到这一格一次。只补发事件不对账,等于每 2 分钟确认一遍死锁还在。
|
||||
TaskFileJobEntity pending = job(23815L, 33179L, "PENDING", STALE_OWNER);
|
||||
when(taskFileJobMapper.selectOne(any())).thenReturn(pending);
|
||||
when(taskFileJobMapper.selectById(23815L))
|
||||
.thenReturn(job(23815L, 33179L, "PENDING", TASK_OWNER));
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
TaskFileJobEntity result = service.enqueueAssembleResult(
|
||||
33179L, "APPEARANCE_PATENT", 36102L, "task:33179:owner:" + TASK_OWNER);
|
||||
|
||||
assertEquals(TASK_OWNER, result.getOwner(), "返回的必须是对账后的行");
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskFileJobEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(taskFileJobMapper, times(1)).update(isNull(), captor.capture());
|
||||
assertTrue(captor.getValue().getSqlSet().contains("owner"), "对账必须写 owner 列");
|
||||
assertTrue(captor.getValue().getCustomSqlSegment().contains("status = "),
|
||||
"只能对账仍在 PENDING 的行,别抢正在跑的那台: " + captor.getValue().getCustomSqlSegment());
|
||||
verify(applicationEventPublisher).publishEvent(any(TaskFileJobDispatchEvent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_pending_作业归属已重合时不得发更新() {
|
||||
TaskFileJobEntity pending = job(23815L, 33179L, "PENDING", TASK_OWNER);
|
||||
when(taskFileJobMapper.selectOne(any())).thenReturn(pending);
|
||||
|
||||
TaskFileJobEntity result = service.enqueueAssembleResult(
|
||||
33179L, "APPEARANCE_PATENT", 36102L, "task:33179:owner:" + TASK_OWNER);
|
||||
|
||||
assertEquals(23815L, result.getId());
|
||||
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
verify(applicationEventPublisher).publishEvent(any(TaskFileJobDispatchEvent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_pending_作业入队_scope_key_不带_owner_段时不得凭空对账() {
|
||||
TaskFileJobEntity pending = job(23815L, 33179L, "PENDING", STALE_OWNER);
|
||||
when(taskFileJobMapper.selectOne(any())).thenReturn(pending);
|
||||
|
||||
service.enqueueAssembleResult(33179L, "APPEARANCE_PATENT", 36102L, "task:33179");
|
||||
|
||||
verify(taskFileJobMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.nanri.aiimage.testutil.SourceScan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* 「任务归属实例」校验源必须四台同源的绊线(2026-11-02)。
|
||||
*
|
||||
* <p>起因:现网任务 33179/33149 的跨实例死锁。领取按 {@code biz_task_file_job.owner}、
|
||||
* 执行时校验按 {@code biz_file_task.owner_instance_id},两列一旦背离就是互斥死锁
|
||||
* (能领到这行的实例必被校验拒、校验放过的实例必领不到这行)。而四台的校验源当时是三样:
|
||||
* 外观专利读列(正确)、相似ASIN 与发布<b>只读 {@code resultJson} 快照</b>、
|
||||
* 店铺采集回落 {@code requestJson}。快照是建单那一刻写死的、任务转交后不再同步,
|
||||
* 于是 worker 侧按异常携带的 owner 转交作业时会转交给已经不管这行的实例——死锁只是换了个方向。
|
||||
*
|
||||
* <p>判据形状:每台的归属读取方法都必须<b>先读 {@code owner_instance_id} 列</b>,
|
||||
* 只在列缺失时才回落 JSON 快照。把任何一台改回「只读快照」,本类即红。
|
||||
* 之所以打在源码上而不是四份单测夹具:这条谓词的正确性在于「读哪个字段」,
|
||||
* 用 mock 造四份任务实体各测一遍,改回读快照时那四份夹具照样全绿。
|
||||
*/
|
||||
class TaskOwnerReadSourceGuardrailTest {
|
||||
|
||||
/** 从方法签名起做括号配对,取出方法体(注释已由 withoutComments 剥掉)。 */
|
||||
private static String methodBody(String source, String signature) {
|
||||
int start = source.indexOf(signature);
|
||||
assertThat(start).as("必须存在方法 " + signature).isGreaterThan(-1);
|
||||
int open = source.indexOf('{', start);
|
||||
assertThat(open).as(signature + " 的方法体起点").isGreaterThan(-1);
|
||||
int depth = 0;
|
||||
for (int i = open; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '{') {
|
||||
depth++;
|
||||
} else if (c == '}') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
return source.substring(open + 1, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AssertionError(signature + " 括号未闭合");
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0} 的 {1} 必须先读 owner_instance_id 列")
|
||||
@CsvSource({
|
||||
"AppearancePatentTaskOwnership.java, ownerFromTask(FileTaskEntity task)",
|
||||
"SimilarAsinTaskOwnershipSupport.java, ownerFromTask(FileTaskEntity task)",
|
||||
"PublishTaskService.java, ownerFromTask(FileTaskEntity task)",
|
||||
"ShopDataCrawlTaskService.java, ownerInstanceIdOf(FileTaskEntity task)",
|
||||
})
|
||||
void ownershipReadMustStartFromTheExplicitColumn(String fileName, String signature) {
|
||||
String source = SourceScan.withoutComments(SourceScan.sourceText(fileName));
|
||||
String body = methodBody(source, signature);
|
||||
|
||||
assertThat(body)
|
||||
.as(fileName + " 的 " + signature + " 必须读显式列,而不是只读 JSON 快照")
|
||||
.contains("getOwnerInstanceId()");
|
||||
int columnRead = body.indexOf("getOwnerInstanceId()");
|
||||
int jsonRead = body.indexOf("readTree(");
|
||||
if (jsonRead >= 0) {
|
||||
assertThat(columnRead)
|
||||
.as(fileName + " 必须先读列再读 JSON 快照(列是转交后唯一被更新的来源)")
|
||||
.isLessThan(jsonRead);
|
||||
}
|
||||
// jsonRead < 0 也合法:那一台已经把快照回落后移到别的方法里,列就是唯一来源。
|
||||
// 真正不允许的是反过来——只读快照,那正是相似ASIN 与发布当时的形状。
|
||||
}
|
||||
|
||||
@Test
|
||||
void 转交作业的目标实例必须来自异常携带的任务当前_owner() {
|
||||
String source = SourceScan.withoutComments(SourceScan.sourceText("TaskResultFileJobWorker.java"));
|
||||
String body = methodBody(source, "catch (TaskOwnerMismatchException ex)");
|
||||
|
||||
assertThat(body)
|
||||
.as("只 deferRunning 就是 2026-11-02 那 6381 条空转拒绝的形状")
|
||||
.contains("handOffToOwner");
|
||||
assertThat(body)
|
||||
.as("改挂目标必须取任务当前 owner,取作业自己的旧 owner 等于原地不动")
|
||||
.contains("ex.getOwnerInstanceId()");
|
||||
assertThat(body.indexOf("handOffToOwner"))
|
||||
.as("必须先改挂再退回:deferRunning 把行翻成 PENDING,而改挂的 CAS 只认 RUNNING")
|
||||
.isLessThan(body.indexOf("deferRunning"));
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.config.InstanceMetadata;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentResultFileJobHandler;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskService;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* worker 侧归属拒绝的处理顺序判据(2026-11-02 现网任务 33179/33149)。
|
||||
*
|
||||
* <p>被 {@code TaskOwnerMismatchException} 拒掉时,必须<b>先</b>把作业改挂到任务当前 owner、
|
||||
* <b>再</b>退回 PENDING。顺序反了就不生效:{@code handOffToOwner} 的 CAS 只认 RUNNING 行,
|
||||
* 而 {@code deferRunning} 恰好把行翻成 PENDING——先 defer 的话改挂永远打不中,
|
||||
* 于是回到「每 15 秒领一次、每次都被拒、永不终态」的死锁原状。
|
||||
*
|
||||
* <p>改挂目标必须取异常携带的 {@code ownerInstanceId}(校验刚读到的任务当前归属),
|
||||
* 不能取作业自己的旧 owner——那是原地不动,等于没修。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class TaskResultFileJobWorkerOwnerHandOffTest {
|
||||
|
||||
@Mock private TaskFileJobService taskFileJobService;
|
||||
@Mock private TaskDistributedLockService taskDistributedLockService;
|
||||
@Mock private InstanceMetadata instanceMetadata;
|
||||
@Mock private AppearancePatentTaskService appearancePatentTaskService;
|
||||
|
||||
private TaskResultFileJobWorker worker;
|
||||
private TaskFileJobEntity job;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ResultFileJobHandlerRegistry registry = new ResultFileJobHandlerRegistry(
|
||||
List.of(new AppearancePatentResultFileJobHandler(appearancePatentTaskService)));
|
||||
worker = new TaskResultFileJobWorker(
|
||||
taskFileJobService,
|
||||
taskDistributedLockService,
|
||||
mock(FileResultMapper.class),
|
||||
mock(TaskFileJobLocalDispatcher.class),
|
||||
instanceMetadata,
|
||||
registry);
|
||||
job = new TaskFileJobEntity();
|
||||
job.setId(23815L);
|
||||
job.setTaskId(33179L);
|
||||
job.setResultId(36102L);
|
||||
job.setModuleType("APPEARANCE_PATENT");
|
||||
job.setJobType("ASSEMBLE_RESULT");
|
||||
job.setStatus("RUNNING");
|
||||
job.setOwner("server-110");
|
||||
job.setScopeKey("task:33179:owner:server-110");
|
||||
job.setRetryCount(1);
|
||||
job.setUpdatedAt(LocalDateTime.now());
|
||||
}
|
||||
|
||||
private void stubRejectedByTaskOwner() throws Exception {
|
||||
when(taskFileJobService.findById(23815L)).thenReturn(null);
|
||||
when(taskDistributedLockService.acquire(eq("APPEARANCE_PATENT"), eq(33179L), anyLong()))
|
||||
.thenReturn(mock(TaskDistributedLockService.LockHandle.class));
|
||||
when(appearancePatentTaskService.processResultFileJob(job)).thenThrow(
|
||||
new TaskOwnerMismatchException(33179L, "assemble result file", "server-121", "server-110"));
|
||||
}
|
||||
|
||||
private void processInternal() throws Exception {
|
||||
Method method = TaskResultFileJobWorker.class
|
||||
.getDeclaredMethod("processInternal", TaskFileJobEntity.class);
|
||||
method.setAccessible(true);
|
||||
try {
|
||||
method.invoke(worker, job);
|
||||
} catch (InvocationTargetException ex) {
|
||||
throw (Exception) ex.getCause();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_归属被拒时必须先改挂再退回() throws Exception {
|
||||
stubRejectedByTaskOwner();
|
||||
|
||||
assertDoesNotThrow(this::processInternal);
|
||||
|
||||
InOrder order = inOrder(taskFileJobService);
|
||||
order.verify(taskFileJobService).handOffToOwner(23815L, "server-110", "server-121");
|
||||
order.verify(taskFileJobService).deferRunning(eq(23815L), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_改挂目标必须取任务当前_owner_而不是作业旧_owner() throws Exception {
|
||||
stubRejectedByTaskOwner();
|
||||
|
||||
processInternal();
|
||||
|
||||
ArgumentCaptor<String> target = ArgumentCaptor.forClass(String.class);
|
||||
verify(taskFileJobService).handOffToOwner(eq(23815L), anyString(), target.capture());
|
||||
assertEquals("server-121", target.getValue(),
|
||||
"取成 server-110 就是原地转交,死锁只是换了个方向");
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_归属被拒不得计入_retry_预算() throws Exception {
|
||||
// 计入 retry_count 会让任务在归属机一切正常时被本机重试耗尽判死(原注释的语义,改动后仍须成立)
|
||||
stubRejectedByTaskOwner();
|
||||
|
||||
processInternal();
|
||||
|
||||
verify(taskFileJobService, never()).markFailed(any(TaskFileJobEntity.class), anyString());
|
||||
verify(taskFileJobService, never()).requeue(anyLong(), anyString());
|
||||
}
|
||||
}
|
||||
+141
@@ -302,6 +302,147 @@ 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("IP 白名单")
|
||||
// 2026-11-02 实测:零并发单发 overseas.proxy.qg.net 仍回 NO_AVAILABLE_CHANNEL,
|
||||
// 所以文案不许把"被自己的采集占着"当唯一事实——那会把用户引去等一个不会来的释放。
|
||||
.doesNotContain("青果通道正被你自己的采集占着");
|
||||
}
|
||||
|
||||
/**
|
||||
* 五档失败各自可辨(欠费/通道占用/限流/密钥失效/鉴权未过)——
|
||||
* 把任意一档改回 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(
|
||||
|
||||
+138
-5
@@ -9,6 +9,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
@@ -29,6 +30,7 @@ import com.nanri.aiimage.modules.usersecret.model.entity.UserApiSecretEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.AdminUserSecretModuleVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -50,6 +52,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -325,6 +328,44 @@ class UserApiSecretServiceTest {
|
||||
verify(mapper, never()).selectOne(any());
|
||||
}
|
||||
|
||||
/**
|
||||
* 建单闸门:这一单要拿谁的密钥跑 LLM。两侧都空必须当场拒——放过去就是
|
||||
* 「保留原始行」的静默降级:表照出、行数照扣,只是整列检测结论是空的。
|
||||
*/
|
||||
@Test
|
||||
void requireSubmitSecretRejectsWhenNeitherSideHasKey() {
|
||||
UserApiSecretService service = newService();
|
||||
when(mapper.selectOne(any())).thenReturn(null);
|
||||
|
||||
BusinessException error = assertThrows(BusinessException.class,
|
||||
() -> service.requireSubmitSecret(7L, UserSecretModule.SIMILAR_ASIN, " "));
|
||||
|
||||
// 空白 caller 值不算「带了密钥」;文案要说清缺哪把、去哪配
|
||||
assertThat(error.getMessage()).contains("货源查询密钥").contains("密钥设置");
|
||||
}
|
||||
|
||||
@Test
|
||||
void requireSubmitSecretPassesWhenCallerCarriesKey() {
|
||||
UserApiSecretService service = newService();
|
||||
|
||||
service.requireSubmitSecret(7L, UserSecretModule.APPEARANCE_PATENT, "sk-caller");
|
||||
|
||||
// 显式带密钥的形状(老任务/覆盖提交)不得被拦,连库都不该读
|
||||
verify(mapper, never()).selectOne(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requireSubmitSecretPassesWhenUserHasStoredKey() {
|
||||
UserApiSecretService service = newService();
|
||||
UserApiSecretEntity row = new UserApiSecretEntity();
|
||||
row.setUserId(7L);
|
||||
row.setModuleKey("appearance-patent");
|
||||
row.setSecretValue("enc:sk-stored");
|
||||
when(mapper.selectOne(any())).thenReturn(row);
|
||||
|
||||
service.requireSubmitSecret(7L, UserSecretModule.APPEARANCE_PATENT, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void migrateSkipsWhenServerValueExists() {
|
||||
UserApiSecretService service = newService();
|
||||
@@ -509,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
|
||||
@@ -873,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();
|
||||
@@ -899,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");
|
||||
}
|
||||
|
||||
@@ -1078,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() {
|
||||
@@ -1211,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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
* 那条数是 {@code grep -rl 'sourceText('} 数出来的,而第 9 支是 {@code SourceScan.java:22} 里
|
||||
* {@code public static String sourceText(String fileName)} 这行<b>被调方自己的声明</b>——它不是调用点。
|
||||
* 所以真实形状是 <b>调用点/调用方/引用方三类数各自成立</b>(2026-10-28 v1.1 Phase 0 起调用方 16 支、
|
||||
* 裸名 22 个,增量逐笔登记在 {@code REGISTERED_BARE_NAMES} 的注释里)。下面第 3 格把这些数同时钉住,
|
||||
* 裸名 23 个,增量逐笔登记在 {@code REGISTERED_BARE_NAMES} 的注释里)。下面第 3 格把这些数同时钉住,
|
||||
* 免得下一个人拿 {@code grep} 再数一遍又把声明算进去。</p>
|
||||
*/
|
||||
class SourceScanTest {
|
||||
@@ -77,7 +77,12 @@ class SourceScanTest {
|
||||
"TaskCenterQueryService.java",
|
||||
"TaskHeartbeatService.java",
|
||||
"AppearancePatentDeliverySupport.java",
|
||||
"RequestTraceFilter.java");
|
||||
"RequestTraceFilter.java",
|
||||
// —— 2026-11-02 跨实例归属死锁根治追加(1 名)——
|
||||
// TaskOwnerReadSourceGuardrailTest 要钉「被拒时必须先改挂再退回」这一枚顺序,
|
||||
// 顺序错在 deferRunning 把行翻成 PENDING 之后 handOffToOwner 的 CAS 就打不中,
|
||||
// 用 mock 造不出这个先后(它要跑的正是 catch 块里两行的次序),只能打在源码连线上。
|
||||
"TaskResultFileJobWorker.java");
|
||||
|
||||
@TempDir
|
||||
Path tmp;
|
||||
@@ -93,7 +98,7 @@ class SourceScanTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void census_唯一裸名恰为22且与已登记集合相等() {
|
||||
void census_唯一裸名恰为23且与已登记集合相等() {
|
||||
Set<String> found = SourceScan.censusSourceTextCallSites().stream()
|
||||
.map(SourceScan.CallSite::bareName)
|
||||
.collect(Collectors.toSet());
|
||||
@@ -101,11 +106,11 @@ class SourceScanTest {
|
||||
assertThat(found)
|
||||
.as("唯一裸名集合必须与类头台账逐字相等——多一个说明有人新引了单文件口径,少一个说明尺子漏扫")
|
||||
.isEqualTo(REGISTERED_BARE_NAMES)
|
||||
.hasSize(22);
|
||||
.hasSize(23);
|
||||
}
|
||||
|
||||
@Test
|
||||
void census_调用方文件恰为16而声明件在外() {
|
||||
void census_调用方文件恰为17而声明件在外() {
|
||||
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites();
|
||||
Set<String> callerFiles = sites.stream()
|
||||
.map(SourceScan.CallSite::relativeFile)
|
||||
@@ -114,8 +119,9 @@ class SourceScanTest {
|
||||
String declarationFile = "src/test/java/com/nanri/aiimage/testutil/SourceScan.java";
|
||||
|
||||
assertThat(callerFiles)
|
||||
.as("真实字面量调用点落在 16 支调用方文件里(8 支既有 + 2026-10-28 v1.1 Phase 0 预置契约 8 支)")
|
||||
.hasSize(16);
|
||||
.as("真实字面量调用点落在 17 支调用方文件里(8 支既有 + 2026-10-28 v1.1 Phase 0 预置契约 8 支"
|
||||
+ " + 2026-11-02 归属死锁绊线 1 支)")
|
||||
.hasSize(17);
|
||||
assertThat(callerFiles)
|
||||
.as("plan 原文记的「9 支」= grep -rl 'sourceText(' 的条数,第 9 支是被调方自己的声明行"
|
||||
+ "(SourceScan.java:22 的 `public static String sourceText(String fileName)`),"
|
||||
|
||||
@@ -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>
|
||||
@@ -42,16 +42,23 @@
|
||||
|
||||
<div class="secret-field">
|
||||
<label class="field-label" :for="`secret-input-${module.moduleKey}`">接口密钥</label>
|
||||
<input
|
||||
:id="`secret-input-${module.moduleKey}`"
|
||||
v-model="moduleStates[module.moduleKey].input"
|
||||
class="secret-input"
|
||||
type="password"
|
||||
:placeholder="placeholderOf(module.moduleKey)"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy"
|
||||
/>
|
||||
<div class="password-field">
|
||||
<input
|
||||
:id="`secret-input-${module.moduleKey}`"
|
||||
v-model="moduleStates[module.moduleKey].input"
|
||||
class="secret-input"
|
||||
:type="llmVisibility.inputTypeOf(module.moduleKey)"
|
||||
:placeholder="placeholderOf(module.moduleKey)"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy"
|
||||
/>
|
||||
<SecretVisibilityToggle
|
||||
:visible="llmVisibility.visibleOf(module.moduleKey)"
|
||||
:disabled="busy"
|
||||
@toggle="llmVisibility.toggle(module.moduleKey)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="channelSwitchNeedsValue(module.moduleKey)" class="inline-warn">
|
||||
@@ -136,21 +143,29 @@
|
||||
:disabled="busy || proxyLocked"
|
||||
@input="proxyDirty = true"
|
||||
/>
|
||||
<input
|
||||
v-model="proxyPassword"
|
||||
class="secret-input"
|
||||
type="password"
|
||||
placeholder="Authpwd"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy || proxyLocked"
|
||||
@input="proxyDirty = true"
|
||||
/>
|
||||
<div class="password-field">
|
||||
<input
|
||||
v-model="proxyPassword"
|
||||
class="secret-input"
|
||||
:type="proxyPasswordType"
|
||||
placeholder="Authpwd"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="busy || proxyLocked"
|
||||
@input="proxyDirty = true"
|
||||
/>
|
||||
<SecretVisibilityToggle
|
||||
:visible="proxyPasswordVisible"
|
||||
:disabled="busy || proxyLocked"
|
||||
@toggle="toggleProxyPasswordVisibility"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="proxy-plan-hint">
|
||||
青果没有可填的提取链接:保存时用 Authkey / Authpwd 自动拼出
|
||||
<code>overseas.proxy.qg.net/get?key=…&format=json</code>(Basic 认证也带在同一条链接里),
|
||||
本地与后台密钥各存一份。服务端的商标检测用的就是这条链接,不填账密它会按「未配置代理」拦下任务。
|
||||
Authpwd 默认掩码,点输入框右侧的眼睛可核对;保存成功后自动回到掩码。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -178,15 +193,22 @@
|
||||
/>
|
||||
</div>
|
||||
<div class="proxy-plan-row proxy-plan-row--single">
|
||||
<input
|
||||
v-model="proxyPlanKey"
|
||||
class="secret-input"
|
||||
type="password"
|
||||
:placeholder="proxyPlanKeyPlaceholder"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||||
/>
|
||||
<div class="password-field">
|
||||
<input
|
||||
v-model="proxyPlanKey"
|
||||
class="secret-input"
|
||||
:type="planKeyType"
|
||||
:placeholder="proxyPlanKeyPlaceholder"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||||
/>
|
||||
<SecretVisibilityToggle
|
||||
:visible="planKeyVisible"
|
||||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||||
@toggle="togglePlanKeyVisibility"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="secret-actions">
|
||||
<button
|
||||
@@ -212,21 +234,18 @@
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="proxySupported && proxyProvider === 'qingguo'" class="proxy-plan-hint">
|
||||
青果的账户余量与通道用量请到青果后台查看;本客户端目前只做青果提取链接的连通性检测。
|
||||
青果的套餐与通道用量以青果后台为准;这里的「检测」会真打一次提取并经隧道验连——
|
||||
它会占掉你那一条通道的存活期(约 3 分钟),期间再点会得到「无可用通道」。若隔几分钟仍报同一句,多半不是被占,而是这把 key 的套餐到期/无余量,或后台把鉴权切成了 IP 白名单档——去青果控制台核对通道数与有效期。
|
||||
</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 +256,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 +287,10 @@ import {
|
||||
LLM_CHANNEL_OPTIONS,
|
||||
PROXY_PROVIDER_OPTIONS,
|
||||
llmChannelLabel,
|
||||
moduleSourceLabel,
|
||||
normalizeLlmChannel,
|
||||
normalizeProxyProvider,
|
||||
proxyCheckValue,
|
||||
proxyProviderLabel,
|
||||
type LlmChannelKey,
|
||||
type ProxyProviderKey,
|
||||
@@ -287,7 +307,9 @@ 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 { useKeyedSecretVisibility, useSecretVisibility } from '@/shared/composables/useSecretVisibility'
|
||||
import SecretVisibilityToggle from '@/shared/components/SecretVisibilityToggle.vue'
|
||||
import { createModuleView, proxyCheckPresentation, type ModuleState } from '@/shared/utils/api-secret-module-view'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -324,6 +346,32 @@ const proxyProvider = ref<ProxyProviderKey>(DEFAULT_PROXY_PROVIDER)
|
||||
/** 青果隧道端点的代理账密(Authkey/Authpwd):只存本机 app.json,不上报服务端。 */
|
||||
const proxyAccount = ref('')
|
||||
const proxyPassword = ref('')
|
||||
/**
|
||||
* 面板里每一把"掩码输入"的显隐,同一个出处(2026-11-02 用户点名:填错了看不见,只能靠猜)。
|
||||
* 眼睛只切自己那一格的 type;状态不落 localStorage、不进日志与上报,
|
||||
* 重新读取本机配置 / 切供应商 / 保存成功 / 组件卸载全部回到掩码(与「保存成功即清空输入」同一口径)。
|
||||
*
|
||||
* LLM 那两把(外观专利/货源查询)共用同一段循环模板 ⇒ 必须按键隔离,
|
||||
* 否则点一张卡的眼睛会把另一张也摊成明文。
|
||||
*/
|
||||
const {
|
||||
visible: proxyPasswordVisible,
|
||||
inputType: proxyPasswordType,
|
||||
toggle: toggleProxyPasswordVisibility,
|
||||
reset: resetProxyPasswordVisibility,
|
||||
} = useSecretVisibility()
|
||||
const {
|
||||
visible: planKeyVisible,
|
||||
inputType: planKeyType,
|
||||
toggle: togglePlanKeyVisibility,
|
||||
reset: resetPlanKeyVisibility,
|
||||
} = useSecretVisibility()
|
||||
const llmVisibility = useKeyedSecretVisibility()
|
||||
function resetSecretVisibility() {
|
||||
resetProxyPasswordVisibility()
|
||||
resetPlanKeyVisibility()
|
||||
llmVisibility.resetAll()
|
||||
}
|
||||
const proxyLoading = ref(false)
|
||||
const proxyLoadFailed = ref(false)
|
||||
const proxyReady = ref(false)
|
||||
@@ -334,7 +382,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 +400,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) {
|
||||
@@ -381,29 +446,35 @@ function selectProxyProvider(provider: ProxyProviderKey) {
|
||||
proxyDirty.value = true
|
||||
proxyCheckResult.value = null
|
||||
proxyCheckError.value = ''
|
||||
// 换的是「哪一家的账密」,明文状态没有理由跟着走过去
|
||||
resetSecretVisibility()
|
||||
}
|
||||
|
||||
|
||||
/** 检测代理连通性:地址有改动时检测输入值(不落库),否则检测/落库已存值并刷新状态展示。 */
|
||||
/** 检测代理连通性:改动过就送当前输入(不落库),没改动就送 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 : '代理检测失败'
|
||||
@@ -513,6 +584,8 @@ async function loadProxyConfig() {
|
||||
proxyLoadFailed.value = false
|
||||
proxyReady.value = false
|
||||
proxyDirty.value = false
|
||||
// 每次重新读取本机配置=换号或重开弹窗:读到的可能就是另一个账号的 Authpwd,不许还亮着明文
|
||||
resetSecretVisibility()
|
||||
|
||||
const api = getPywebviewApi()
|
||||
proxySupported.value = Boolean(api?.read_config && api?.save_config)
|
||||
@@ -633,6 +706,9 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
|
||||
}
|
||||
|
||||
// 保存后不再自动检测:检测一律由用户手动点击「检测」触发
|
||||
// 保存成功=账密已落到本机与服务端,界面没有理由还把 Authpwd 亮着明文;
|
||||
// 失败分支不动(那时用户正需要核对填错在哪一位)。
|
||||
resetSecretVisibility()
|
||||
refreshSnapshots()
|
||||
return true
|
||||
} catch (error) {
|
||||
@@ -677,6 +753,8 @@ onMounted(() => {
|
||||
|
||||
onUnmounted(() => {
|
||||
if (unsubscribe) unsubscribe()
|
||||
// 卸载即回到掩码:弹窗若是 v-show 留着复用,重载路径上不该还显示着上一个账号的明文
|
||||
resetSecretVisibility()
|
||||
})
|
||||
|
||||
defineExpose({ saveAll, reload })
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
class="password-toggle"
|
||||
:class="{ 'is-visible': visible }"
|
||||
:aria-pressed="visible"
|
||||
:aria-label="visible ? '隐藏密码' : '显示密码'"
|
||||
:disabled="disabled"
|
||||
@click="emit('toggle')"
|
||||
>
|
||||
<svg class="icon-eye" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"></path>
|
||||
<circle cx="12" cy="12" r="3"></circle>
|
||||
</svg>
|
||||
<svg class="icon-eye-off" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="m2 2 20 20"></path>
|
||||
<path d="M10.733 5.076a10.744 10.744 0 0 1 9.205 6.272 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-1.651 2.59"></path>
|
||||
<path d="M14.084 14.158a3 3 0 0 1-4.242-4.242"></path>
|
||||
<path d="M17.479 17.499a10.75 10.75 0 0 1-5.479 1.501c-4.478 0-8.268-2.943-9.876-6.652a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 2.646-3.393"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 密钥输入框的「眼睛」:与登录页 `DesktopLoginPage.vue` 同一组 class 名与同一对 svg 路径,
|
||||
* 只是从那一页的 inline 收成可复用件(青果 Authpwd 是第一个消费者,其余掩码档以后直接用它,
|
||||
* 不再各自手搓一份显隐逻辑)。
|
||||
*
|
||||
* 本件不认识密钥原文,只有 `visible` 进、`toggle` 出——它改不动绑定值,也发不出请求。
|
||||
* 配色刻意用 `color: inherit` + 透明度,深浅两套界面都能落(登录页浅、密钥卡深)。
|
||||
* 定位靠父级的 `position: relative` 容器(口径同登录页的 `.password-field`)。
|
||||
*/
|
||||
withDefaults(defineProps<{
|
||||
/** 当前是否明文(由 `useSecretVisibility()` 提供,本件不自存状态)。 */
|
||||
visible: boolean
|
||||
/** 输入框禁用时眼睛一起禁用,免得只读态还能翻出明文。 */
|
||||
disabled?: boolean
|
||||
}>(), {
|
||||
disabled: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ (event: 'toggle'): void }>()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.password-toggle {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
opacity: .7;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.password-toggle:hover:not(:disabled) {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.password-toggle:focus-visible {
|
||||
outline: 1px solid currentColor;
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.password-toggle:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: .35;
|
||||
}
|
||||
|
||||
.password-toggle svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.password-toggle .icon-eye-off {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.password-toggle.is-visible .icon-eye {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.password-toggle.is-visible .icon-eye-off {
|
||||
display: block;
|
||||
}
|
||||
</style>
|
||||
@@ -189,6 +189,15 @@
|
||||
opacity: .72;
|
||||
}
|
||||
|
||||
/* 带「眼睛」的密钥输入框:容器给绝对定位锚,右侧留出不被按钮盖住的空隙(口径同登录页 .password-field)。 */
|
||||
.password-field {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.password-field .secret-input {
|
||||
padding-right: 48px;
|
||||
}
|
||||
|
||||
.secret-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { computed, ref, type ComputedRef, type Ref } from 'vue'
|
||||
|
||||
/** 密钥输入框的 `type`:默认掩码,只有用户亲自点过眼睛才是 text。 */
|
||||
export type SecretInputType = 'password' | 'text'
|
||||
|
||||
export interface SecretVisibility {
|
||||
/** 当前是否明文。只活在内存里,随组件实例一起消失。 */
|
||||
visible: Ref<boolean>
|
||||
/** 直接绑到输入框 `:type` 的派生值。 */
|
||||
inputType: ComputedRef<SecretInputType>
|
||||
/** 眼睛按钮的唯一写入口。 */
|
||||
toggle: () => void
|
||||
/** 回到掩码:换供应商/重新读取本机配置/保存成功后都必须叫一次。 */
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 「显示/隐藏这一把密钥」的状态机,单独一个出处(2026-11-02 用户点名青果 Authpwd 没有查看手段)。
|
||||
* 抽出来的理由与 `NotificationLevelIcon.vue` 一样:写死在模板里就得抄第二遍,
|
||||
* 而登录页 `DesktopLoginPage.vue` 那份 inline 已经是第一遍——以后只改一处的结局是两处开始不一致。
|
||||
*
|
||||
* 三条红线:
|
||||
* - 默认必须是掩码,明文只在用户点过眼睛之后存在;
|
||||
* - 这个状态一律不落 localStorage、不进日志与上报(「用户点了显示密码」不是需要上报的事件);
|
||||
* - 它只管可见性、拿不到也存不住密钥原文,所以切换本身不可能改到绑定值。
|
||||
*
|
||||
* 零副作用、零依赖(除 Vue 响应式),`node --test` 可直接测。
|
||||
*/
|
||||
export function useSecretVisibility(): SecretVisibility {
|
||||
const visible = ref(false)
|
||||
return {
|
||||
visible,
|
||||
inputType: computed<SecretInputType>(() => (visible.value ? 'text' : 'password')),
|
||||
toggle: () => {
|
||||
visible.value = !visible.value
|
||||
},
|
||||
reset: () => {
|
||||
visible.value = false
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export interface KeyedSecretVisibility {
|
||||
/** 直接绑到循环里那个输入框 `:type`:没点过眼睛的键永远是 password。 */
|
||||
inputTypeOf: (key: string) => SecretInputType
|
||||
/** 眼睛图标该画睁眼还是闭眼。 */
|
||||
visibleOf: (key: string) => boolean
|
||||
/** 只翻这一个键——「显示外观专利密钥」不该顺手把货源查询那把也亮出来。 */
|
||||
toggle: (key: string) => void
|
||||
/** 全回掩码:保存成功、重读本机配置、卸载时都要叫。 */
|
||||
resetAll: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环渲染的密钥卡(外观专利/货源查询共用同一段模板)用的按键显隐。
|
||||
*
|
||||
* <p>为什么不能复用上面那个单槽位:单槽一共享,点一张卡的眼睛会把**所有**卡都变明文,
|
||||
* 那是"我只核对我手里这把"这个动作被放大成"把用户没打算看的两把也摊在屏幕上"。</p>
|
||||
*/
|
||||
export function useKeyedSecretVisibility(): KeyedSecretVisibility {
|
||||
const visibleByKey = ref<Record<string, boolean>>({})
|
||||
return {
|
||||
inputTypeOf: (key: string) => (visibleByKey.value[key] ? 'text' : 'password'),
|
||||
visibleOf: (key: string) => visibleByKey.value[key] === true,
|
||||
toggle: (key: string) => {
|
||||
visibleByKey.value = { ...visibleByKey.value, [key]: !visibleByKey.value[key] }
|
||||
},
|
||||
resetAll: () => {
|
||||
visibleByKey.value = {}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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,270 @@
|
||||
/**
|
||||
* 密钥设置面板「青果 Authpwd 眼睛」的挂载用例(2026-11-02 用户看图点名:Authkey 是明文可见的,
|
||||
* Authpwd 却是 •••••••• 且没有任何查看手段,填错了只能靠猜)。
|
||||
*
|
||||
* 五组靶子:
|
||||
* ① 默认掩码,点眼睛变明文,再点回掩码(`useSecretVisibility` 的两态开关在界面上真的成立);
|
||||
* ② 切换眼睛**不动绑定值**、**不产生改动标记**、**不发保存/送检请求**(点一下眼睛就冒出
|
||||
* 「检测输入账密(未保存)」=把可见性误判成用户改了代理);
|
||||
* ③ 眼睛只管 Authpwd 这一格:Authkey 照旧明文、各模块密钥照旧掩码,不做全站唯一的特例化扩散;
|
||||
* ④ 保存成功即回到掩码(沿用该面板「保存成功即清空输入」的口径),且输入值不丢;
|
||||
* ⑤ 卸载后重新挂载(重开弹窗/换号后重读配置)不得留一个还显示着明文的重载路径。
|
||||
*
|
||||
* ⚠ 用例里的账密一律是假值(fakekey/fakepwd),真实凭据不得进任何跟踪件。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/密钥面板authpwd显隐.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'
|
||||
|
||||
const UID = '1301'
|
||||
const FAKE_KEY = 'fakekey'
|
||||
const FAKE_PWD = 'fakepwd'
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
let wrapper: VueWrapper | null = null
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
/** 青果账密那一行:[0]=Authkey、[1]=Authpwd。 */
|
||||
function accountInput(panel: VueWrapper) {
|
||||
return proxyCard(panel).findAll('input')[0]
|
||||
}
|
||||
|
||||
function passwordInput(panel: VueWrapper) {
|
||||
return proxyCard(panel).findAll('input')[1]
|
||||
}
|
||||
|
||||
function eyeButton(panel: VueWrapper) {
|
||||
return proxyCard(panel).find('.password-toggle')
|
||||
}
|
||||
|
||||
/** 读输入框当前值:VTU 的 DOMWrapper 上没有取值的语法糖,别拿 text() 冒充。 */
|
||||
function valueOf(node: { element: Element }) {
|
||||
return (node.element as HTMLInputElement).value
|
||||
}
|
||||
|
||||
function proxyCheckButton(panel: VueWrapper) {
|
||||
return proxyCard(panel).findAll('.check-btn')[0]
|
||||
}
|
||||
|
||||
async function saveAll(panel: VueWrapper, options: { requireAll?: boolean } = {}) {
|
||||
const exposed = panel.vm as unknown as { saveAll: (o?: { requireAll?: boolean }) => Promise<boolean> }
|
||||
const saved = await exposed.saveAll(options)
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
return saved
|
||||
}
|
||||
|
||||
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.putMyApiSecret.mockResolvedValue({})
|
||||
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
|
||||
bridge.readConfig.mockResolvedValue(qingguoConfig())
|
||||
bridge.saveConfig.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount()
|
||||
wrapper = null
|
||||
})
|
||||
|
||||
describe('Authpwd 眼睛:两态切换', () => {
|
||||
it('默认掩码,点一次变明文,再点一次回掩码', async () => {
|
||||
const panel = await mountPanel()
|
||||
const pwd = passwordInput(panel)
|
||||
|
||||
expect(pwd.attributes('type')).toBe('password')
|
||||
expect(eyeButton(panel).attributes('aria-pressed')).toBe('false')
|
||||
|
||||
await eyeButton(panel).trigger('click')
|
||||
expect(pwd.attributes('type'), '点眼睛就是把这一格的 type 换掉').toBe('text')
|
||||
expect(eyeButton(panel).attributes('aria-pressed')).toBe('true')
|
||||
expect(eyeButton(panel).attributes('aria-label')).toBe('隐藏密码')
|
||||
|
||||
await eyeButton(panel).trigger('click')
|
||||
expect(pwd.attributes('type')).toBe('password')
|
||||
expect(eyeButton(panel).attributes('aria-pressed')).toBe('false')
|
||||
})
|
||||
|
||||
it('切换眼睛不动绑定值、不记成改动、也不发保存或送检请求', async () => {
|
||||
const panel = await mountPanel()
|
||||
const pwd = passwordInput(panel)
|
||||
const storageKeys = Object.keys(localStorage)
|
||||
|
||||
await eyeButton(panel).trigger('click')
|
||||
await eyeButton(panel).trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(valueOf(pwd), '可见性切换不该吃掉一个字符').toBe(FAKE_PWD)
|
||||
expect(valueOf(accountInput(panel))).toBe(FAKE_KEY)
|
||||
expect(proxyCheckButton(panel).text(), '点眼睛不等于「改了代理」:按钮不许开始自称检的是未保存输入值')
|
||||
.toContain('检测配置代理')
|
||||
expect(store.checkApiSecret).not.toHaveBeenCalled()
|
||||
expect(bridge.saveConfig).not.toHaveBeenCalled()
|
||||
expect(secretApi.putMyApiSecret).not.toHaveBeenCalled()
|
||||
expect(Object.keys(localStorage), '「用户点了显示密码」不配拥有一个持久化键').toEqual(storageKeys)
|
||||
})
|
||||
|
||||
it('只切 Authpwd 这一格:Authkey 照旧明文、模块密钥照旧掩码', async () => {
|
||||
const panel = await mountPanel()
|
||||
|
||||
await eyeButton(panel).trigger('click')
|
||||
|
||||
expect(passwordInput(panel).attributes('type')).toBe('text')
|
||||
expect(accountInput(panel).attributes('type')).toBe('text')
|
||||
for (const card of panel.findAll('.secret-card').slice(0, -1)) {
|
||||
expect(card.find('input').attributes('type'), '别的密钥不跟着这次改动放开').toBe('password')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('Authpwd 眼睛:复位口径', () => {
|
||||
it('保存成功后回到掩码,且账密输入值不丢', async () => {
|
||||
const panel = await mountPanel()
|
||||
const pwd = passwordInput(panel)
|
||||
|
||||
await eyeButton(panel).trigger('click')
|
||||
expect(pwd.attributes('type')).toBe('text')
|
||||
await pwd.setValue(`${FAKE_PWD}Z`)
|
||||
|
||||
expect(await saveAll(panel)).toBe(true)
|
||||
expect(bridge.saveConfig).toHaveBeenCalledTimes(1)
|
||||
expect(pwd.attributes('type'), '保存成功=配置已落地,界面没理由还亮着明文').toBe('password')
|
||||
expect(valueOf(pwd)).toBe(`${FAKE_PWD}Z`)
|
||||
})
|
||||
|
||||
it('卸载后重新挂载(重开弹窗/换号重读配置)不带出明文', async () => {
|
||||
const first = await mountPanel()
|
||||
await eyeButton(first).trigger('click')
|
||||
expect(passwordInput(first).attributes('type')).toBe('text')
|
||||
|
||||
first.unmount()
|
||||
const again = await mountPanel()
|
||||
|
||||
expect(passwordInput(again).attributes('type')).toBe('password')
|
||||
expect(eyeButton(again).attributes('aria-pressed')).toBe('false')
|
||||
expect(valueOf(passwordInput(again)), '重读到的还是那把假密码,只是重新盖上').toBe(FAKE_PWD)
|
||||
})
|
||||
|
||||
it('后台锁定代理时眼睛跟着输入框一起禁用', async () => {
|
||||
store.getServerProxySnapshot.mockReturnValue({
|
||||
...emptySnapshot(), exists: true, locked: true, channel: 'qingguo', full: '',
|
||||
})
|
||||
const panel = await mountPanel()
|
||||
|
||||
expect(passwordInput(panel).attributes('disabled')).toBeDefined()
|
||||
expect(eyeButton(panel).attributes('disabled'), '只读态不该还能把明文翻出来').toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -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('暂不可用')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
import { useKeyedSecretVisibility, useSecretVisibility } from '../src/shared/composables/useSecretVisibility.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const repoRoot = resolve(here, '..')
|
||||
|
||||
/** 去掉注释再扫出口:注释里写「不落 localStorage」是说明,不是真的存储调用。 */
|
||||
function stripComments(source: string): string {
|
||||
return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* 密钥输入框「眼睛」的状态机(2026-11-02 用户点名:青果 Authpwd 是 •••••••• 且没有查看手段)。
|
||||
* 判的是这台状态本身的形状;它落到界面上的行为在 tests/mount/密钥面板authpwd显隐.mount.test.ts。
|
||||
*/
|
||||
test('默认掩码,点一次眼睛变明文,再点一次回掩码', () => {
|
||||
const visibility = useSecretVisibility()
|
||||
const seen: string[] = []
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
seen.push(visibility.inputType.value)
|
||||
visibility.toggle()
|
||||
}
|
||||
assert.deepEqual(seen, ['password', 'text', 'password'], '眼睛必须是自复位的两态开关,不能越点越亮')
|
||||
})
|
||||
|
||||
test('reset 一律回到掩码(换号/重读配置/保存成功都走它),且重复调用不改变语义', () => {
|
||||
const visibility = useSecretVisibility()
|
||||
assert.equal(visibility.inputType.value, 'password')
|
||||
visibility.toggle()
|
||||
assert.equal(visibility.inputType.value, 'text')
|
||||
visibility.reset()
|
||||
assert.equal(visibility.inputType.value, 'password', 'reset 后必须掩码')
|
||||
visibility.reset()
|
||||
assert.equal(visibility.inputType.value, 'password', 'reset 幂等:不能把掩码翻成明文')
|
||||
// 复位后眼睛仍可用(下一次点击还是明文,不是卡死在掩码)
|
||||
visibility.toggle()
|
||||
assert.equal(visibility.inputType.value, 'text')
|
||||
})
|
||||
|
||||
test('状态机只交出可见性,不交出任何能带走密钥原文的口子', () => {
|
||||
const visibility = useSecretVisibility()
|
||||
assert.deepEqual(
|
||||
Object.keys(visibility).sort(),
|
||||
['inputType', 'reset', 'toggle', 'visible'],
|
||||
'成员集固定:多一个口子就多一条把原文带进日志/上报的路',
|
||||
)
|
||||
visibility.toggle()
|
||||
assert.equal(typeof visibility.visible.value, 'boolean')
|
||||
assert.ok(visibility.inputType.value === 'text' || visibility.inputType.value === 'password')
|
||||
})
|
||||
|
||||
test('显隐状态不落本机存储、不进日志、不发上报', () => {
|
||||
const source = stripComments(readFileSync(
|
||||
resolve(repoRoot, 'src/shared/composables/useSecretVisibility.ts'),
|
||||
'utf-8',
|
||||
))
|
||||
for (const outlet of [
|
||||
'localStorage', 'sessionStorage', 'indexedDB', 'document.cookie', 'caches',
|
||||
'console.', 'fetch(', 'XMLHttpRequest', 'sendBeacon', 'WebSocket',
|
||||
]) {
|
||||
assert.ok(!source.includes(outlet), `状态机里不该出现出口 ${outlet}:把「用户点了显示密码」变成持久态或事件是没必要的隐私面`)
|
||||
}
|
||||
})
|
||||
|
||||
test('眼睛按钮件自己也不留第二条持久化/上报出口', () => {
|
||||
const source = stripComments(readFileSync(
|
||||
resolve(repoRoot, 'src/shared/components/SecretVisibilityToggle.vue'),
|
||||
'utf-8',
|
||||
))
|
||||
for (const outlet of ['localStorage', 'sessionStorage', 'console.', 'fetch(', 'sendBeacon']) {
|
||||
assert.ok(!source.includes(outlet), `眼睛按钮不该出现出口 ${outlet}:它只 emit('toggle')`)
|
||||
}
|
||||
assert.match(source, /\$emit\('toggle'\)|emit\('toggle'\)/, '唯一的对外动作就是 toggle')
|
||||
})
|
||||
test('按键显隐:点一张卡的眼睛不许把另一张也摊成明文', () => {
|
||||
const keyed = useKeyedSecretVisibility()
|
||||
assert.equal(keyed.inputTypeOf('appearance-patent'), 'password', '未知键必须默认掩码')
|
||||
keyed.toggle('appearance-patent')
|
||||
assert.equal(keyed.inputTypeOf('appearance-patent'), 'text')
|
||||
assert.equal(keyed.visibleOf('appearance-patent'), true)
|
||||
assert.equal(keyed.inputTypeOf('goods-source'), 'password', '隔壁那张卡不许跟着亮')
|
||||
assert.equal(keyed.visibleOf('goods-source'), false)
|
||||
})
|
||||
|
||||
test('resetAll 把所有键一次收回掩码(保存成功/重读配置/卸载都走它)', () => {
|
||||
const keyed = useKeyedSecretVisibility()
|
||||
keyed.toggle('appearance-patent')
|
||||
keyed.toggle('goods-source')
|
||||
keyed.resetAll()
|
||||
assert.deepEqual(
|
||||
[keyed.inputTypeOf('appearance-patent'), keyed.inputTypeOf('goods-source')],
|
||||
['password', 'password'],
|
||||
)
|
||||
keyed.resetAll()
|
||||
assert.equal(keyed.inputTypeOf('appearance-patent'), 'password', '重复 resetAll 不许翻转成明文')
|
||||
})
|
||||
|
||||
test('面板里不许再出现没挂眼睛的裸密码框', () => {
|
||||
const source = stripComments(readFileSync(
|
||||
resolve(repoRoot, 'src/shared/components/ApiSecretSettingsPanel.vue'),
|
||||
'utf-8',
|
||||
))
|
||||
assert.ok(!/type="password"/.test(source),
|
||||
'又留下一个 •••• 且没有查看手段的字段(本会话用户点名的就是这个形状)⇒ 新密码框必须走 useSecretVisibility / useKeyedSecretVisibility')
|
||||
const toggles = (source.match(/<SecretVisibilityToggle/g) || []).length
|
||||
assert.ok(toggles >= 3, `面板里 Authpwd/套餐 key/LLM 循环都该有眼睛,实际只数到 ${toggles} 个`)
|
||||
})
|
||||
@@ -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