219 lines
11 KiB
TypeScript
219 lines
11 KiB
TypeScript
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').replace(/\r\n/g, '\n')
|
||
|
||
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(' / ')}`)
|
||
}
|
||
})
|