feat(phase-4): 外观专利/货源两个提交入口加建单前密钥门禁(B72-02)

服务端建单口 `UserApiSecretService#requireSubmitSecret` 已经拒缺密钥的单,但界面要等
用户上传完 Excel、点了提交才看到那句中文——白跑一趟昂贵动作。本笔把同一句话提到提交前,
形状照 `ensureBrandCheckProxyReady()` 的先例(`ElMessageBox.alert` +关窗 reject 由
`.then(()=>{},()=>{})` 收尾,不新增 catch)。

三条边界,都是把它写成"能拦但拦错东西"的风险点:
- **前置排在一切昂贵动作之前**:`parseFiles()` 里早于 `parsing.value = true`、早于
  `parseAppearancePatent(`/`parseSimilarAsin(` 建单调用(铁律 27 边界 b)。
- **unknown 放行**:`getApiSecretGateState()==='unknown'` 是"从未成功拉到服务端数据",
  网络抖动不等于未配置,拦人就是把上游抖动说成用户没配——与商标代理前置同口径。
- **文案与服务端同源**:模块名取服务端下发的 `moduleLabel`(`listApiSecretModules()`),
  句子逐字对齐 requireSubmitSecret,前端不再另起一份叫法;查的是本模块快照
  (`getStoredApiSecretSnapshot(moduleKey)`),不拿全局完整性一档误伤另一个模块。

顺手摘掉两处「本地无明文不再阻断」的 console.log 死分支——日志不等于拦住用户。
`pushToPythonQueue()` 里同名那句不动:它启动的是已建好的单,不是建单入口。

判据:`tests/pre-submit-llm-key-gate.test.ts`(4 例,两个 Tab 共用同一份
`gateViolations()` 判据,反向自证喂进实现时用的同一把尺子:摘前置/挪到建单之后/
让 unknown 拦人/硬编模块名,各自报出自己那条违规)。node --test 4 passed;
`npm test` 全面 1007 passed/0 fail;`npm run test:mount` 55 passed;
`npx vue-tsc --noEmit` rc=0。该仓无入库 lint 脚本 ⇒ 以类型检查+测试为准,不伪造 lint 绿。
This commit is contained in:
2026-11-03 16:20:38 +08:00
parent b9d23d5936
commit fee4df5bf6
3 changed files with 294 additions and 11 deletions
@@ -135,7 +135,13 @@ import { checkParseResult, checkQueuePayload } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { formatDateTime } from '@/shared/utils/datetime'
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { ensureBrandCheckProxy, getStoredApiSecret } from '@/shared/utils/api-secret-store'
import {
ensureBrandCheckProxy,
getApiSecretGateState,
getStoredApiSecret,
getStoredApiSecretSnapshot,
listApiSecretModules,
} from '@/shared/utils/api-secret-store'
// ---- 文件选择 / 上传(公共组合式函数)----
const {
@@ -536,15 +542,42 @@ async function ensureBrandCheckProxyReady(): Promise<boolean> {
return false
}
/** 模块名取服务端下发的 label,前端不再另起一份叫法;默认清单里必有本模块,兜底句只为满足类型。 */
function llmKeyModuleLabel(): string {
return listApiSecretModules().find((info) => info.moduleKey === 'appearance-patent')?.moduleLabel || '对应模块密钥'
}
/**
* 创建任务前确认这个模块的 LLM 密钥已配置:服务端建单口(UserApiSecretService#requireSubmitSecret)
* 也会拒,但那时 Excel 已上传、单已建一半,用户白等一趟,所以把同一句话提到提交前说。
* 门禁状态 unknown(从未成功拉到服务端数据)不拦——网络抖动不等于未配置,与 ensureBrandCheckProxy 同口径。
*/
async function ensureLlmApiKeyReady(): Promise<boolean> {
if (getApiSecretGateState() === 'unknown') return true
const snapshot = getStoredApiSecretSnapshot('appearance-patent')
// exists + 检测通过才算配好;error(上游无法判定)按放行,与 computeApiSecretsComplete 同一判据
const configured = (snapshot.exists && (snapshot.checkStatus === 'passed' || snapshot.checkStatus === 'error'))
|| Boolean(effectiveLlmApiKey())
if (configured) return true
await ElMessageBox.alert(
`该账号还没有配置${llmKeyModuleLabel()}:这一单要用它跑 LLM 检测,`
+ '缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。',
'未配置密钥,无法创建任务',
{ type: 'warning', confirmButtonText: '知道了' },
).then(
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
() => undefined,
() => undefined,
)
return false
}
async function parseFiles() {
if (!uploadedFiles.value.length) {
ElMessage.warning('请先选择 Excel')
return
}
if (!effectiveLlmApiKey()) {
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
console.log('[appearance-patent] 本地无密钥明文,提交时由服务端按用户密钥兜底')
}
if (!(await ensureLlmApiKeyReady())) return
parsing.value = true
try {
if (!(await ensureBrandCheckProxyReady())) {
@@ -132,7 +132,7 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { userNotice } from '@/shared/utils/user-notice'
import { ElMessage } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { retryClientTask } from '@/shared/api/task-retry'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
@@ -170,7 +170,12 @@ import { passGuard } from '@/shared/dispatch-guard-ui'
import { getCollectRouting, type CollectChannel } from '@/shared/api/types/modules/collect-routing'
import { formatDateTime } from '@/shared/utils/datetime'
import { isCompletedTask, resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
import {
getApiSecretGateState,
getStoredApiSecret,
getStoredApiSecretSnapshot,
listApiSecretModules,
} from '@/shared/utils/api-secret-store'
// ---- 文件选择 / 上传(公共组合式函数)----
const {
@@ -529,15 +534,42 @@ function toTaskSummary(result: SimilarAsinParseVo): TaskSummary {
}
}
/** 模块名取服务端下发的 label,前端不再另起一份叫法;默认清单里必有本模块,兜底句只为满足类型。 */
function llmKeyModuleLabel(): string {
return listApiSecretModules().find((info) => info.moduleKey === 'similar-asin')?.moduleLabel || '对应模块密钥'
}
/**
* 创建任务前确认这个模块的 LLM 密钥已配置:服务端建单口(UserApiSecretService#requireSubmitSecret)
* 也会拒,但那时 Excel 已上传、单已建一半,用户白等一趟,所以把同一句话提到提交前说。
* 门禁状态 unknown(从未成功拉到服务端数据)不拦——网络抖动不等于未配置,与商标 Tab 的代理前置同口径。
*/
async function ensureLlmApiKeyReady(): Promise<boolean> {
if (getApiSecretGateState() === 'unknown') return true
const snapshot = getStoredApiSecretSnapshot('similar-asin')
// exists + 检测通过才算配好;error(上游无法判定)按放行,与 computeApiSecretsComplete 同一判据
const configured = (snapshot.exists && (snapshot.checkStatus === 'passed' || snapshot.checkStatus === 'error'))
|| Boolean(effectiveLlmApiKey())
if (configured) return true
await ElMessageBox.alert(
`该账号还没有配置${llmKeyModuleLabel()}:这一单要用它跑 LLM 检测,`
+ '缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。',
'未配置密钥,无法创建任务',
{ type: 'warning', confirmButtonText: '知道了' },
).then(
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
() => undefined,
() => undefined,
)
return false
}
async function parseFiles() {
if (!uploadedFiles.value.length) {
ElMessage.warning('请先选择 Excel')
return
}
if (!effectiveLlmApiKey()) {
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
console.log('[similar-asin] 本地无密钥明文,提交时由服务端按用户密钥兜底')
}
if (!(await ensureLlmApiKeyReady())) return
if (!getRequiredAlipriceCredentials()) return
parsing.value = true
try {
@@ -0,0 +1,218 @@
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'
/**
* 提交前置:没配 LLM 密钥就别把单建出去(BACKLOG B72-02 / 蓝图 Phase 4 ③)。
*
* 服务端建单口 `UserApiSecretService#requireSubmitSecret` 已经会拒这一单,但那是用户上传完
* Excel、点了提交之后才吃到的错误;执行侧的老写法更是直接「保留原始行」把单跑完——表照样出、
* 行数照样扣,只是整列 LLM 检测结论是空的(AGENTS.md 铁律 27)。所以这里要在**建单之前**把
* 同一句话说清,且文案与服务端同源:模块名取服务端下发的 `moduleLabel`,前端不另起一份叫法。
*
* 三把尺子:① 接线次序(前置必须早于 `parsing.value = true` 与建单调用);② 弹窗文案的四个
* 服务端片段+不硬编模块名;③ `unknown`(从未成功拉到服务端数据)必须软失败放行——网络抖动
* 不等于未配置。反向自证逐条把实现改坏,确认每条都真的会红。
*/
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const read = (rel: string) => readFileSync(resolve(repoRoot, rel), 'utf-8')
interface TabSpec {
name: string
file: string
moduleKey: string
/** 建单落库的那次调用,用于判「前置是否早于建单」。 */
createCall: string
}
const TABS: TabSpec[] = [
{
name: '外观专利 Tab',
file: 'src/pages/brand/components/BrandAppearancePatentTab.vue',
moduleKey: 'appearance-patent',
createCall: 'parseAppearancePatent(',
},
{
name: '相似 ASIN Tab',
file: 'src/pages/brand/components/BrandSimilarAsinTab.vue',
moduleKey: 'similar-asin',
createCall: 'parseSimilarAsin(',
},
]
const GATE_CALL = 'if (!(await ensureLlmApiKeyReady())) return'
/** 截取函数体:先按括号配平跳过参数列表,再按花括号配平取函数体;找不到签名返回 null 交给调用方判红。 */
function functionBodyOrNull(source: string, signature: string): string | null {
const start = source.indexOf(signature)
if (start < 0) return null
const openParen = source.indexOf('(', start)
let parenDepth = 0
let cursor = openParen
for (; cursor < source.length; cursor += 1) {
if (source[cursor] === '(') parenDepth += 1
else if (source[cursor] === ')') {
parenDepth -= 1
if (parenDepth === 0) break
}
}
const openBrace = source.indexOf('{', cursor)
let depth = 0
for (let i = openBrace; i < source.length; i += 1) {
if (source[i] === '{') depth += 1
else if (source[i] === '}') {
depth -= 1
if (depth === 0) return source.slice(openBrace, i + 1)
}
}
return null
}
/** 对整份 Tab 源码取违规清单:空清单=接线正确。反向自证喂进来的也是同一份判据,不另写一套。 */
function gateViolations(source: string, spec: TabSpec): string[] {
const out: string[] = []
const parseBody = functionBodyOrNull(source, 'async function parseFiles(')
const guardBody = functionBodyOrNull(source, 'async function ensureLlmApiKeyReady(')
const labelBody = functionBodyOrNull(source, 'function llmKeyModuleLabel(')
if (!parseBody) out.push(`${spec.name} 找不到 parseFiles`)
if (!guardBody) out.push(`${spec.name} 缺少密钥前置函数 ensureLlmApiKeyReady`)
if (!labelBody) out.push(`${spec.name} 缺少模块名取数函数 llmKeyModuleLabel`)
if (parseBody) {
const gateIdx = parseBody.indexOf('ensureLlmApiKeyReady()')
const createIdx = parseBody.indexOf(spec.createCall)
const parsingIdx = parseBody.indexOf('parsing.value = true')
if (gateIdx < 0) out.push(`${spec.name} 的 parseFiles 没接密钥前置`)
if (createIdx < 0) out.push(`${spec.name} 的 parseFiles 找不到建单调用 ${spec.createCall}`)
if (gateIdx >= 0 && createIdx >= 0 && gateIdx > createIdx) {
out.push(`${spec.name}:密钥前置落在了建单之后,单已经建出去了才提示`)
}
if (gateIdx >= 0 && parsingIdx >= 0 && gateIdx > parsingIdx) {
out.push(`${spec.name}:密钥前置晚于 parsing.value = true,没做在昂贵动作之前`)
}
if (parseBody.includes('本地无密钥明文')) {
out.push(`${spec.name}:parseFiles 仍留着「本地无明文不再阻断」的死分支(console.log 不等于拦住用户)`)
}
}
if (guardBody) {
if (!/getApiSecretGateState\(\)\s*===\s*'unknown'\s*\)\s*return true/.test(guardBody)) {
out.push(`${spec.name}:unknown 没有 return true 放行——门禁状态读不到时不该拦用户提交`)
}
const unknownIdx = guardBody.indexOf("'unknown'")
const alertIdx = guardBody.indexOf('ElMessageBox.alert')
if (alertIdx < 0) out.push(`${spec.name}:缺密钥时没有弹窗提示,只是静默 return`)
if (unknownIdx >= 0 && alertIdx >= 0 && unknownIdx > alertIdx) {
out.push(`${spec.name}:unknown 的放行判断晚于弹窗,等于仍然拦人`)
}
// 文案四个片段与服务端 requireSubmitSecret 逐字同源
for (const fragment of ['该账号还没有配置', '这一单要用它跑 LLM 检测', '没有检测结论的结果表', '请先在「密钥设置」里填好并保存']) {
if (!guardBody.includes(fragment)) out.push(`${spec.name}:弹窗文案缺服务端同源片段「${fragment}」`)
}
if (!guardBody.includes('密钥设置')) out.push(`${spec.name}:弹窗没告诉用户去哪里补密钥`)
if (!guardBody.includes('${llmKeyModuleLabel()}')) {
out.push(`${spec.name}:弹窗模块名没有取 listApiSecretModules 的 label(前端另起叫法=两套文案)`)
}
if (!guardBody.includes(`getStoredApiSecretSnapshot('${spec.moduleKey}')`)) {
out.push(`${spec.name}:前置应查本模块(${spec.moduleKey})的快照,不能拿全局完整性一档误伤别的模块`)
}
if (!guardBody.includes("checkStatus === 'passed'") || !guardBody.includes("checkStatus === 'error'")) {
out.push(`${spec.name}:检测状态判据与 computeApiSecretsComplete 不同源(error=无法判定应按放行)`)
}
for (const hardcoded of ['外观专利密钥', '货源查询密钥']) {
if (guardBody.includes(hardcoded) || labelBody?.includes(hardcoded)) {
out.push(`${spec.name}:模块名「${hardcoded}」被硬编进前端文案`)
}
}
const tail = guardBody.slice(Math.max(alertIdx, 0))
const swallowed = (tail.match(/\(\) => undefined,/g) ?? []).length
if (alertIdx >= 0 && swallowed < 2) {
out.push(`${spec.name}:弹窗关闭会以 reject 收尾,必须用 .then(成功, 失败) 双回调接住(两个 () => undefined)`)
}
if (/catch\s*[({]/.test(guardBody)) {
out.push(`${spec.name}:给弹窗 reject 加了 catch——本仓对无声出口有棘轮,请用 .then 双回调`)
}
}
if (labelBody) {
if (!labelBody.includes('listApiSecretModules()')) {
out.push(`${spec.name}:模块名不是从 listApiSecretModules()(服务端下发 label)取的`)
}
if (!labelBody.includes(`moduleKey === '${spec.moduleKey}'`)) {
out.push(`${spec.name}:模块名查错了 key,应当查 ${spec.moduleKey}`)
}
}
return out
}
for (const spec of TABS) {
test(`${spec.name}:提交前密钥门禁已接线(次序+文案+unknown 放行)`, () => {
assert.deepEqual(gateViolations(read(spec.file), spec), [], '接线不合规')
})
}
/** 摘掉前置这一行——接线判据必须报「没接密钥前置」。 */
function dropGate(source: string): string {
return source.replace(` ${GATE_CALL}\n`, '')
}
/** 把前置挪到建单调用之后——单已经建出去了才提示,次序判据必须报「建单之后」。 */
function moveGateAfterCreate(source: string, spec: TabSpec): string {
const withoutGate = dropGate(source)
const createIdx = withoutGate.indexOf(spec.createCall)
assert.ok(createIdx >= 0, '建单调用锚点丢了')
const lineEnd = withoutGate.indexOf('\n', createIdx)
return withoutGate.slice(0, lineEnd + 1) + ` ${GATE_CALL}\n` + withoutGate.slice(lineEnd + 1)
}
/** 让 unknown 也拦人——放行判据必须报 unknown。 */
function unknownBlocks(source: string): string {
const mutated = source.replace(
"if (getApiSecretGateState() === 'unknown') return true",
"if (getApiSecretGateState() === 'unknown') return false",
)
assert.notEqual(mutated, source, 'unknown 分支锚点丢了,注入没生效')
return mutated
}
test('反向自证:摘掉前置/挪到建单之后/让 unknown 拦人,判据逐条变红且红在该红的原因上', () => {
for (const spec of TABS) {
const source = read(spec.file)
assert.deepEqual(gateViolations(source, spec), [], `${spec.name} 正本本就该是零违规,否则下面的自证不可信`)
const dropped = dropGate(source)
assert.notEqual(dropped, source, `${spec.name} 的前置调用行没被摘掉,注入是假的`)
const droppedViolations = gateViolations(dropped, spec)
assert.ok(droppedViolations.length > 0, `${spec.name}:摘掉前置后判据仍全绿=这条判据是摆设`)
assert.ok(droppedViolations.some((v) => v.includes('没接密钥前置')),
`${spec.name}:摘掉前置的读数应落在「没接密钥前置」,实测 ${droppedViolations.join(' / ')}`)
const moved = moveGateAfterCreate(source, spec)
assert.notEqual(moved, source, `${spec.name} 的前置没被挪动,注入是假的`)
const movedViolations = gateViolations(moved, spec)
assert.ok(movedViolations.some((v) => v.includes('建单之后')),
`${spec.name}:前置挪到建单之后应落在「建单之后」,实测 ${movedViolations.join(' / ')}`)
const blocked = unknownBlocks(source)
const blockedViolations = gateViolations(blocked, spec)
assert.ok(blockedViolations.length > 0, `${spec.name}:unknown 改成拦人后判据仍全绿=这条判据是摆设`)
assert.ok(blockedViolations.some((v) => v.includes('unknown')),
`${spec.name}:unknown 拦人应落在 unknown 那条,实测 ${blockedViolations.join(' / ')}`)
}
})
test('反向自证:把模块名硬编回文案,判据要报「被硬编」', () => {
for (const spec of TABS) {
const source = read(spec.file)
const hardcoded = source.replace('${llmKeyModuleLabel()}', '外观专利密钥')
assert.notEqual(hardcoded, source, '插值锚点丢了')
const violations = gateViolations(hardcoded, spec)
assert.ok(violations.some((v) => v.includes('没有取 listApiSecretModules')),
`硬编模块名后应报「没有取 label」,实测 ${violations.join(' / ')}`)
assert.ok(violations.some((v) => v.includes('被硬编进前端文案')),
`硬编模块名后应报「被硬编」,实测 ${violations.join(' / ')}`)
}
})