用户端(四面9分批次): 三条全局错误出口、URL 白名单收口、令牌键单点、uid 短路进门禁
- 此前全树 0 处全局错误处理器:装 app.config.errorHandler + window error + unhandledrejection, 每条都留可诊断记录、界面只出中文、处理器自身异常不重抛也不白屏(9 例判据)。 - safeHttpUrl 未覆盖的 3 处(两个品牌 Tab 与 useVersionUpdate 直装服务端 file_url)收口; 令牌键 aiimage_auth_token 由 4 处各自定义 + 2 处内联收成唯一定义点。 - 「localStorage 有 uid 就免校验」改走 auth-gate 单点,剩余例外台账化且同口径必须能抓到 评审点名的原写法(6 例);卸载配对 3 处补齐 + 全树判据(7 例)。 - task-status-text 把 CANCELLED 显示成"执行中"改对,CANCELED/CANCELLED 两拼写都映射(4 例)。 - 主审计补的四处修复:新判据里两处拿数组和 0 比(怎么写都红);静默 catch 的"用户可见出口" 符号表认不出本仓 userNotice 与注入式 notify,把真报了用户的 catch 判成静默; 新错误出口带来的 2 个 try/catch 按棘轮合同写理由进基线(296→298,silent 一格没涨)。 - 验收:node --test 820 例 0 红、npx vue-tsc --noEmit rc=0。
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import { AUTH_TOKEN_KEY, AUTO_LOGIN_KEY, UID_KEY, USERNAME_KEY } from '../src/shared/auth/session-keys.ts'
|
||||
|
||||
/**
|
||||
* 令牌键名收成 1 个常量(2026-10-09 评审安全面:`aiimage_auth_token` 有 4 处各自定义 + 2 处内联字符串)。
|
||||
*
|
||||
* 散着的键名不是风格问题:改名要同时命中 6 处,漏一处的表现是"登录成功但请求不带令牌"
|
||||
* 或"下线了但旧键还留着令牌"。这里钉三件事:值本身、唯一定义点、以及每个消费点确实 import 它。
|
||||
*
|
||||
* 键值改动要连着后端与已发布客户端一起改,所以值也钉住(不是恒绿断言,是防手滑)。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
/** 令牌键的字面量写法(单/双引号都算,反引号也算)。 */
|
||||
const TOKEN_LITERAL = /['"`]aiimage_auth_token['"`]/
|
||||
|
||||
/** 定义点:`const|export const 名字 = 'aiimage_auth_token'`。 */
|
||||
const TOKEN_DEFINITION = /\b(?:export\s+)?const\s+[A-Za-z0-9_]+\s*=\s*['"`]aiimage_auth_token['"`]/
|
||||
|
||||
/** 应当引用统一常量的消费点(构造名做锚点,不锚行号)。 */
|
||||
const CONSUMERS: Array<{ file: string; importOf: RegExp; construct: RegExp }> = [
|
||||
{ file: 'src/shared/api/http.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\.\/auth\/session-keys\.ts'/, construct: /localStorage\.getItem\(AUTH_TOKEN_KEY\)/ },
|
||||
{ file: 'src/shared/api/types/modules/permission.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\.\/\.\.\/\.\.\/auth\/session-keys\.ts'/, construct: /function getAuthToken\(\)/ },
|
||||
{ file: 'src/shared/auth/ensure-auth.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\/session-keys\.ts'/, construct: /export async function ensureAuth\(\)/ },
|
||||
{ file: 'src/shared/auth/kick-handler.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\/session-keys\.ts'/, construct: /function clearLocalSession\(\)/ },
|
||||
{ file: 'src/shared/auth/user-token-sync.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'@\/shared\/auth\/session-keys\.ts'/, construct: /function readToken\(\)/ },
|
||||
{ file: 'src/pages/login/DesktopLoginPage.vue', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'@\/shared\/auth\/session-keys'/, construct: /async function submitLogin|void loginWithDevice|setItem\(AUTH_TOKEN_KEY/ },
|
||||
]
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function read(relFromRoot: string): string {
|
||||
return readFileSync(join(ROOT, ...relFromRoot.split('/')), 'utf-8')
|
||||
}
|
||||
|
||||
/** 找出"字面量出现在统一出口之外"的文件(判据与注入自证共用同一个函数)。 */
|
||||
function literalOutsideSingleSource(entries: Array<{ rel: string; source: string }>): string[] {
|
||||
return entries
|
||||
.filter(({ rel, source }) => rel !== 'src/shared/auth/session-keys.ts' && TOKEN_LITERAL.test(source))
|
||||
.map(({ rel, source }) => `${rel}: ${source.split(/\r?\n/).find((line) => TOKEN_LITERAL.test(line))?.trim().slice(0, 100)}`)
|
||||
}
|
||||
|
||||
const ENTRIES = sourceFiles(SRC).map((file) => ({
|
||||
rel: relative(ROOT, file).split(sep).join('/'),
|
||||
source: readFileSync(file, 'utf-8'),
|
||||
}))
|
||||
|
||||
test('键名常量本身:值与形状钉住(改名要连着后端和已发布客户端,不是随手能动的)', () => {
|
||||
assert.equal(AUTH_TOKEN_KEY, 'aiimage_auth_token')
|
||||
assert.equal(UID_KEY, 'uid')
|
||||
assert.equal(USERNAME_KEY, 'username')
|
||||
assert.equal(AUTO_LOGIN_KEY, 'aiimage_auto_login')
|
||||
})
|
||||
|
||||
test('全树只有 session-keys.ts 一处定义令牌键名,内联字面量清零', () => {
|
||||
const definitions = ENTRIES.filter(({ source }) => TOKEN_DEFINITION.test(source))
|
||||
assert.deepEqual(definitions.map(({ rel }) => rel), ['src/shared/auth/session-keys.ts'],
|
||||
`令牌键名的定义点应当只有一个,实测:${definitions.map(({ rel }) => rel).join(', ')}`)
|
||||
assert.deepEqual(literalOutsideSingleSource(ENTRIES), [], '这些地方还在自己写令牌键名')
|
||||
})
|
||||
|
||||
test('分母自证:扫描器真的在扫整棵树(命中数塌了就不许报"清零")', () => {
|
||||
const literalSites = ENTRIES.filter(({ source }) => TOKEN_LITERAL.test(source)).length
|
||||
assert.ok(literalSites >= 1, `全树连一处令牌键名字面量都没扫到——扫描器或目录树坏了,"零违规"不作数`)
|
||||
assert.ok(ENTRIES.length > 100, `只扫到 ${ENTRIES.length} 个源文件,分母不对`)
|
||||
const importSites = ENTRIES.filter(({ source }) => /AUTH_TOKEN_KEY/.test(source)).length
|
||||
assert.ok(importSites >= 7, `只有 ${importSites} 个文件提到 AUTH_TOKEN_KEY(定义 + 6 个消费点,下限 7)——引用没接上`)
|
||||
// 定义点自己必须带着那个值(防止有人把 session-keys 掏空来"清零"字面量)
|
||||
const sessionKeys = read('src/shared/auth/session-keys.ts')
|
||||
assert.match(sessionKeys, /export const AUTH_TOKEN_KEY = 'aiimage_auth_token'/)
|
||||
})
|
||||
|
||||
test('6 个消费点确实 import 统一常量,没有本地副本', () => {
|
||||
const problems: string[] = []
|
||||
for (const { file, importOf, construct } of CONSUMERS) {
|
||||
const source = read(file)
|
||||
if (!importOf.test(source)) problems.push(`${file} 没有 import 统一的 AUTH_TOKEN_KEY`)
|
||||
if (!construct.test(source)) problems.push(`${file} 的锚点构造没找到(改形状了,判据要跟着改)`)
|
||||
if (/\bconst\s+AUTH_TOKEN_KEY\s*=/.test(source)) problems.push(`${file} 还留着自己的 AUTH_TOKEN_KEY 定义`)
|
||||
}
|
||||
assert.deepEqual(problems, [], problems.join('\n'))
|
||||
})
|
||||
|
||||
test('注入自证:往消费点塞一条内联字面量一定被判红', () => {
|
||||
const target = ENTRIES.find(({ rel }) => rel === 'src/shared/api/http.ts')
|
||||
assert.ok(target, 'http.ts 没进分母')
|
||||
const anchor = 'const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || \'\''
|
||||
assert.equal(target.source.split(anchor).length - 1, 1, '锚点不唯一,注入自证不作数')
|
||||
const injected = target.source.replace(anchor, "const token = window.localStorage.getItem('aiimage_auth_token') || ''")
|
||||
assert.notEqual(injected, target.source, '注入没生效,这条自证是假的')
|
||||
assert.deepEqual(literalOutsideSingleSource([{ rel: target.rel, source: injected }]), [`${target.rel}: ${injected.split(/\r?\n/).find((l) => TOKEN_LITERAL.test(l))?.trim().slice(0, 100)}`],
|
||||
'内联字面量没被抓出来')
|
||||
// 合法写法(引用常量)必须放得过
|
||||
assert.deepEqual(literalOutsideSingleSource([{ rel: target.rel, source: target.source }]), [])
|
||||
})
|
||||
@@ -24,7 +24,14 @@ const BASELINE = {
|
||||
// 同一批另两处(pywebview addEventListener 的外层兜底、isSessionExpiredNav 的外层兜底)挡的是
|
||||
// 不可能发生的事(内层 lsGet 已自带兜底、URLSearchParams 对字符串永不抛),本轮直接摘掉,
|
||||
// 所以这里只 +1 而不是 +3。静默数 silent 一格没动(仍 <=84),逐文件台账也对平。
|
||||
blocks: 296,
|
||||
blocks: 298,
|
||||
// 298 = 296 + 全局错误出口 app-error.ts 的两支新 try/catch(10-09 装 app.config.errorHandler /
|
||||
// window.onerror / unhandledrejection 时引入),两支都不是"吞":
|
||||
// ① String(reason) 对无 toString 的对象/Symbol 会抛,兜法返回一句中文占位文本,
|
||||
// 该文本随后可见(进界面提示 + 内存环 + 控制台);
|
||||
// ② guardRun 挡的是"处理器自己崩了把页面带白屏",兜法是 console.error + 一次中文提示,
|
||||
// 且刻意不向上重抛(重抛会让 Vue 再进一次同一个处理器)。
|
||||
// silent 一格没涨(两支都有用户可见出口),台账无需新增条目。
|
||||
silent: 84,
|
||||
/** 逐文件台账:只钉总数与文件数两个标量的棘轮,会被「A 加一条 + B 减一条」整段绕过。 */
|
||||
perFile: {
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import {
|
||||
APP_ERROR_NOTICE_COOLDOWN_MS,
|
||||
APP_ERROR_NOTICE_TEXT,
|
||||
APP_ERROR_RECORD_LIMIT,
|
||||
clearAppErrorRecords,
|
||||
describeAppError,
|
||||
disposeGlobalErrorGuard,
|
||||
errorRawText,
|
||||
getAppErrorRecords,
|
||||
installGlobalErrorGuard,
|
||||
userTextForError,
|
||||
} from '../src/shared/utils/app-error.ts'
|
||||
import type { ErrorGuardApp } from '../src/shared/utils/app-error.ts'
|
||||
|
||||
/**
|
||||
* 全局错误处理器(2026-10-09 评审稳定面 5.0 的第一条:全树 `app.config.errorHandler`、
|
||||
* `unhandledrejection`、`window.onerror` 各 0 处;非零对照 `router.onError` 恰 1 处)。
|
||||
*
|
||||
* 这条判据主要跑行为:造一个假 app 与假 window 把三个出口装上,然后真去触发它们,
|
||||
* 看"用户看到的话"和"可诊断的记录"是否都出来——静态计数只能证明代码在场,证明不了它会响。
|
||||
* 静态那半边留给接线(main.ts 装了、App.vue 卸了),同样配非零对照与注入自证。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
const CJK = /[㐀-䶿一-鿿]/
|
||||
|
||||
interface FakeHost {
|
||||
added: Array<{ type: string; listener: (event: never) => void }>
|
||||
removed: string[]
|
||||
emit: (type: string, event: unknown) => void
|
||||
}
|
||||
|
||||
/** 每个假世界自己的时钟起点:模块级冷却状态会跨用例,起点不隔开就会互相吃掉提示。 */
|
||||
let worldSeq = 0
|
||||
|
||||
function makeWorld() {
|
||||
const notices: string[] = []
|
||||
const lines: string[] = []
|
||||
const listeners = new Map<string, Array<(event: never) => void>>()
|
||||
const removed: string[] = []
|
||||
worldSeq += 1
|
||||
let clock = worldSeq * 10_000_000
|
||||
const host = {
|
||||
addEventListener: (type: string, listener: (event: never) => void) => {
|
||||
listeners.set(type, [...(listeners.get(type) ?? []), listener])
|
||||
},
|
||||
removeEventListener: (type: string) => {
|
||||
removed.push(type)
|
||||
listeners.delete(type)
|
||||
},
|
||||
}
|
||||
const app: ErrorGuardApp = { config: {} }
|
||||
const emit = (type: string, event: unknown) => {
|
||||
for (const listener of listeners.get(type) ?? []) (listener as (e: unknown) => void)(event)
|
||||
}
|
||||
const advance = (ms: number) => { clock += ms }
|
||||
const dispose = installGlobalErrorGuard(app, {
|
||||
notify: (text) => notices.push(text),
|
||||
record: (line) => lines.push(line),
|
||||
now: () => clock,
|
||||
}, host)
|
||||
const fakeHost: FakeHost = {
|
||||
added: [...listeners.entries()].map(([type, ls]) => ({ type, listener: ls[0] })),
|
||||
removed,
|
||||
emit,
|
||||
}
|
||||
return { app, notices, lines, dispose, advance, fakeHost, listenerTypes: () => [...listeners.keys()].sort() }
|
||||
}
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const ENTRIES = sourceFiles(SRC).map((file) => ({
|
||||
rel: relative(ROOT, file).split(sep).join('/'),
|
||||
source: readFileSync(file, 'utf-8'),
|
||||
}))
|
||||
|
||||
function read(rel: string): string {
|
||||
return ENTRIES.find((e) => e.rel === rel)?.source ?? readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
}
|
||||
|
||||
/** 三个出口的在场判据(装配面)。`from` 用于注入自证:把装配删掉就该判红。 */
|
||||
function guardWiring(source: string) {
|
||||
// `addEventListener(` 与可选链写法 `addEventListener?.(` 都算(源码里用的是后者)
|
||||
return {
|
||||
vueErrorHandler: /app\.config\.errorHandler\s*=|config\.errorHandler\s*=\s*\(?\s*(?:err|error)\b/.test(source),
|
||||
rejection: /addEventListener\??\.?\(\s*['"]unhandledrejection['"]/.test(source),
|
||||
windowError: /addEventListener\??\.?\(\s*['"]error['"]/.test(source),
|
||||
}
|
||||
}
|
||||
|
||||
test('装上的那一刻三个出口都在,卸载时全部摘掉', () => {
|
||||
clearAppErrorRecords()
|
||||
const world = makeWorld()
|
||||
assert.equal(typeof world.app.config.errorHandler, 'function', 'app.config.errorHandler 没装上')
|
||||
assert.deepEqual(world.listenerTypes(), ['error', 'unhandledrejection'], 'window 上的两个出口少一个')
|
||||
world.dispose()
|
||||
assert.equal(world.app.config.errorHandler, undefined, '卸载后 errorHandler 还挂着')
|
||||
assert.deepEqual(world.fakeHost.removed.sort(), ['error', 'unhandledrejection'], '卸载没有 removeEventListener 配对')
|
||||
})
|
||||
|
||||
test('三个出口都真的响:记录一定落,界面只说中文', () => {
|
||||
clearAppErrorRecords()
|
||||
const world = makeWorld()
|
||||
// ① Vue 渲染期抛错(英文异常原文,绝不能出现在界面上)
|
||||
world.app.config.errorHandler?.(new Error('Cannot read properties of undefined'), null, 'render')
|
||||
// 越过冷却再发第二条,避免被去重吃掉(去重本身另有用例)
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
// ② 顶层同步异常
|
||||
world.fakeHost.emit('error', { message: 'Uncaught ReferenceError: x is not defined', error: undefined })
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
// ③ 没人接的 Promise
|
||||
world.fakeHost.emit('unhandledrejection', { reason: 'Network Error' })
|
||||
|
||||
assert.equal(world.notices.length, 3, `三条错误只出声 ${world.notices.length} 次`)
|
||||
for (const text of world.notices) {
|
||||
assert.ok(CJK.test(text), `界面提示必须含中文:${text}`)
|
||||
for (const english of ['Cannot read properties', 'ReferenceError', 'Network Error', 'Uncaught']) {
|
||||
assert.ok(!text.includes(english), `英文异常原文漏到了界面上:${text}`)
|
||||
}
|
||||
}
|
||||
// 记录里必须有原文与出处(否则支持同学拿什么对后端日志)
|
||||
assert.equal(world.lines.length, 3, '记录条数与错误条数不一致,有错误被吞了')
|
||||
assert.match(world.lines[0], /^\[vue:render\] Cannot read properties of undefined/)
|
||||
assert.match(world.lines[1], /^\[window\.error\] Uncaught ReferenceError/)
|
||||
assert.match(world.lines[2], /^\[unhandledrejection\] Network Error/)
|
||||
assert.equal(getAppErrorRecords().length, 3, '内存环里也该留着这 3 条')
|
||||
})
|
||||
|
||||
test('中文原文照原样透出,不做无谓改写', () => {
|
||||
const world = makeWorld()
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
world.app.config.errorHandler?.(new Error('任务已被取消,请重新提交'), null, 'watcher')
|
||||
assert.deepEqual(world.notices, ['任务已被取消,请重新提交'])
|
||||
assert.equal(userTextForError('Similar ASIN result rows are empty'), APP_ERROR_NOTICE_TEXT)
|
||||
assert.equal(errorRawText(null), '')
|
||||
assert.equal(describeAppError('vue:x', null), '[vue:x] (没有错误原文)')
|
||||
})
|
||||
|
||||
test('同一个错在渲染循环里刷屏时:只说一次,但被压掉的条数记在案', () => {
|
||||
const world = makeWorld()
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
world.app.config.errorHandler?.(new Error(`loop ${i}`), null, 'render')
|
||||
}
|
||||
assert.equal(world.notices.length, 1, '5 条同场错误刷出了多条弹窗')
|
||||
assert.equal(world.lines.length, 5, '被去重的那几条不能连记录一起消失')
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
world.app.config.errorHandler?.(new Error('after cooldown'), null, 'render')
|
||||
assert.deepEqual(world.notices[1], `${APP_ERROR_NOTICE_TEXT}(同样的问题这期间还出现过 4 次)`)
|
||||
})
|
||||
|
||||
test('处理器自己抛了也不许把页面搞白屏:兜住、留痕、再说一句中文', () => {
|
||||
const notices: string[] = []
|
||||
const lines: string[] = []
|
||||
const boom = {
|
||||
addEventListener: () => { /* 假 window 不需要 */ },
|
||||
removeEventListener: () => { /* 同上 */ },
|
||||
}
|
||||
const app: ErrorGuardApp = { config: {} }
|
||||
installGlobalErrorGuard(app, {
|
||||
notify: (text) => {
|
||||
notices.push(text)
|
||||
if (notices.length === 1) throw new Error('弹窗组件挂了')
|
||||
},
|
||||
record: (line) => lines.push(line),
|
||||
now: () => (worldSeq += 1) * 10_000_000,
|
||||
}, boom)
|
||||
// 第一条:notify 抛错 → 处理器不得把异常抛回 Vue,否则这次渲染直接白屏
|
||||
assert.doesNotThrow(() => app.config.errorHandler?.(new Error('first'), null, 'render'))
|
||||
assert.ok(notices.some((text) => CJK.test(text)), '处理器自身异常时没给出中文提示')
|
||||
// 第二条:同样的路径再来一次,依然不抛
|
||||
assert.doesNotThrow(() => app.config.errorHandler?.(new Error('second'), null, 'render'))
|
||||
})
|
||||
|
||||
test('记录环有上限:挤掉最老的而不是无限攒', () => {
|
||||
clearAppErrorRecords()
|
||||
const world = makeWorld()
|
||||
for (let i = 0; i < APP_ERROR_RECORD_LIMIT + 8; i += 1) {
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
world.app.config.errorHandler?.(new Error(`e${i}`), null, 'render')
|
||||
}
|
||||
const records = getAppErrorRecords()
|
||||
assert.equal(records.length, APP_ERROR_RECORD_LIMIT, `记录环长到了 ${records.length}`)
|
||||
assert.match(records[records.length - 1], /e27/)
|
||||
assert.ok(!records.some((line) => line.includes('[vue:render] e0')), '最老的一条没被挤掉')
|
||||
})
|
||||
|
||||
test('接线钉子:main.ts 装了、App.vue 卸了,全树三个出口都在场', () => {
|
||||
const main = read('src/main.ts')
|
||||
const appVue = read('src/App.vue')
|
||||
assert.match(main, /installGlobalErrorGuard\(\s*app\s*,/, 'main.ts 没把处理器装到 app 上')
|
||||
assert.match(main, /notify:.*ElMessage\.error/s, '界面出口没接 ElMessage')
|
||||
assert.match(appVue, /onBeforeUnmount\(\(\)\s*=>\s*\{[^}]*disposeGlobalErrorGuard\(\)/, 'App.vue 没有卸载配对')
|
||||
const present = {
|
||||
vueErrorHandler: ENTRIES.filter(({ source }) => guardWiring(source).vueErrorHandler).length,
|
||||
rejection: ENTRIES.filter(({ source }) => guardWiring(source).rejection).length,
|
||||
windowError: ENTRIES.filter(({ source }) => guardWiring(source).windowError).length,
|
||||
}
|
||||
assert.ok(present.vueErrorHandler >= 1, 'app.config.errorHandler 全树 0 处——评审那条缺陷没修上')
|
||||
assert.ok(present.rejection >= 1, 'unhandledrejection 全树 0 处')
|
||||
assert.ok(present.windowError >= 1, '顶层 error 出口全树 0 处')
|
||||
// 非零对照:证明扫描器真的会数东西,而不是扫了个空
|
||||
const routerOnError = ENTRIES.filter(({ source }) => /router\.onError\(/.test(source)).length
|
||||
assert.equal(routerOnError, 1, `router.onError 对照面应为 1 处,实测 ${routerOnError}——扫描口径变了`)
|
||||
assert.ok(ENTRIES.length > 100, `只扫到 ${ENTRIES.length} 个源文件,分母不对`)
|
||||
})
|
||||
|
||||
test('注入自证:把装配删掉,接线判据立刻变红', () => {
|
||||
const main = read('src/main.ts')
|
||||
assert.ok(/installGlobalErrorGuard\(\s*app\s*,/.test(main), 'main.ts 的装配形状变了,判据要跟着改')
|
||||
const stripped = main.replace(/installGlobalErrorGuard\([\s\S]*?\n\}\)/, '/* 装配被删掉 */')
|
||||
assert.notEqual(stripped, main, '注入没生效,这条自证是假的')
|
||||
assert.ok(!/installGlobalErrorGuard\(\s*app\s*,/.test(stripped), '删掉装配后仍判成"已装",上面那条就是恒绿')
|
||||
assert.ok(!/onBeforeUnmount\(\(\)\s*=>\s*\{[^}]*disposeGlobalErrorGuard\(\)/.test(
|
||||
read('src/App.vue').replace('disposeGlobalErrorGuard()', '/* 卸载被删掉 */')), '卸载判据删掉了装配也照样绿')
|
||||
// 真装了的那份源码必须能被同口径认出来
|
||||
assert.deepEqual(guardWiring(read('src/shared/utils/app-error.ts')).vueErrorHandler, true, 'app-error.ts 里的赋值没被判成已装')
|
||||
assert.deepEqual(guardWiring(read('src/shared/utils/app-error.ts')).rejection, true, 'unhandledrejection 注册没被认出')
|
||||
})
|
||||
|
||||
test('disposeGlobalErrorGuard 走的是同一条卸载路(App.vue 里调的是它)', () => {
|
||||
const world = makeWorld()
|
||||
assert.deepEqual(world.listenerTypes(), ['error', 'unhandledrejection'])
|
||||
disposeGlobalErrorGuard()
|
||||
assert.deepEqual(world.listenerTypes(), [], 'disposeGlobalErrorGuard 没摘掉监听')
|
||||
})
|
||||
@@ -32,8 +32,12 @@ export interface CatchScan {
|
||||
silent: SilentCatch[]
|
||||
}
|
||||
|
||||
/** 用户可见提示的符号名(本仓只有 Element Plus 这一套)。 */
|
||||
const TOAST_SYMBOLS = new Set(['ElMessage', 'ElNotification', 'ElMessageBox'])
|
||||
/** 用户可见提示的符号名:Element Plus 那一套,加上本仓自己的提示出口 `userNotice`,
|
||||
* 以及注入式提示句柄(`app-error.ts` 的 `deps.notify(...)`——生产里传的就是 userNotice,
|
||||
* 扫描器看不穿注入,于是把"报了用户"误判成"只 log",这是尺子的盲区而不是代码的静默)。
|
||||
* 放宽的边界由 tests/catch-silence-ratchet.test.ts 的分母自证兜着:
|
||||
* api-secret-store.ts 与 DesktopLoginPage.vue 的静默数必须仍然 >0,抓不到就是这条规则放得太开。 */
|
||||
const TOAST_SYMBOLS = new Set(['ElMessage', 'ElNotification', 'ElMessageBox', 'userNotice', 'notify'])
|
||||
|
||||
function walk(node: any, cb: (n: any) => void): void {
|
||||
cb(node)
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* 跳转/下载出口的白名单校验扫描器(判据在 tests/url-outlet-guard.test.ts)。
|
||||
*
|
||||
* 为什么按 AST 而不是 grep:`window.location.href = 服务端返回的 file_url` 这类口子写法差别很大
|
||||
* (`window.open(x)`、`saveUrlWithProgress(url, ...)`、`bridge.save_file_from_url(url, ...)`、
|
||||
* 先存进变量再跳),grep 只能盯一种形状;而真正要判的是
|
||||
* **"这次跳转的地址过没过白名单"**——校验可能写在同一个函数的开头,也可能被抽成本地小函数
|
||||
* (本仓的收口写法就是这样)。所以按"宿主函数"判,再把具名本地函数的守卫沿调用链传上去
|
||||
* (不动点迭代):函数改名、换排版、加参数都不会让尺子失明。
|
||||
*
|
||||
* 口径:
|
||||
* ① 出口 = `open(` / `saveUrlWithProgress(` / `save_file_from_url(` 调用、`*.location.href =` 赋值、
|
||||
* `*.location.assign(`/`*.location.replace(` 调用;
|
||||
* ② 出口任一祖先函数体里出现 `isHttpUrl(` 或 `safeHttpUrl(` → 已校验;
|
||||
* ③ 祖先函数调用了本文件里"已校验"的具名函数 → 也算已校验。
|
||||
*/
|
||||
import { createRequire } from 'node:module'
|
||||
import { extractScript, parseModule } from './task-terminal-ast-ruler.ts'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const ts = require('typescript')
|
||||
|
||||
/** 白名单校验函数名(src/shared/utils/safe-url.ts 的出口) */
|
||||
export const GUARD_NAMES = new Set(['isHttpUrl', 'safeHttpUrl'])
|
||||
|
||||
export interface UrlOutlet {
|
||||
file: string
|
||||
line: number
|
||||
/** 出口形状的名字,报错时给可读证据 */
|
||||
kind: string
|
||||
/** 最内层具名宿主函数(找不到=模块顶层) */
|
||||
host: string
|
||||
/** 命中的那条语句(截断) */
|
||||
snippet: string
|
||||
/** 是否过了白名单(按祖先函数与调用链判) */
|
||||
guarded: boolean
|
||||
}
|
||||
|
||||
export interface OutletScan {
|
||||
file: string
|
||||
outlets: UrlOutlet[]
|
||||
unguarded: UrlOutlet[]
|
||||
}
|
||||
|
||||
function walk(node: any, cb: (n: any) => void): void {
|
||||
cb(node)
|
||||
ts.forEachChild(node, (child: any) => walk(child, cb))
|
||||
}
|
||||
|
||||
/** 调用点的名字:`foo(...)` 取 foo,`a.b(...)` 取 b(`window.open` 就当 open)。 */
|
||||
function calledName(call: any): string {
|
||||
const callee = call.expression
|
||||
if (!callee) return ''
|
||||
if (ts.isIdentifier(callee)) return callee.text
|
||||
if (ts.isPropertyAccessExpression(callee) && callee.name) return callee.name.text
|
||||
return ''
|
||||
}
|
||||
|
||||
function calleeText(call: any): string {
|
||||
const callee = call.expression
|
||||
return callee && typeof callee.getText === 'function' ? callee.getText() : ''
|
||||
}
|
||||
|
||||
/** `x.location.href = ...` / `location.href = ...` 这类赋值出口。 */
|
||||
function isLocationHrefAssignment(node: any): boolean {
|
||||
if (!ts.isBinaryExpression(node)) return false
|
||||
if (node.operatorToken?.kind !== ts.SyntaxKind.EqualsToken) return false
|
||||
const left = node.left
|
||||
if (!ts.isPropertyAccessExpression(left) || left.name?.text !== 'href') return false
|
||||
const base = left.expression
|
||||
return ts.isPropertyAccessExpression(base) && base.name?.text === 'location'
|
||||
}
|
||||
|
||||
function outletKindOf(node: any): string | null {
|
||||
if (ts.isCallExpression(node)) {
|
||||
const name = calledName(node)
|
||||
if (name === 'open') return 'window.open'
|
||||
if (name === 'saveUrlWithProgress') return 'saveUrlWithProgress'
|
||||
if (name === 'save_file_from_url') return 'bridge.save_file_from_url'
|
||||
if ((name === 'assign' || name === 'replace') && /\.location$/.test(calleeText(node))) return `location.${name}`
|
||||
return null
|
||||
}
|
||||
if (isLocationHrefAssignment(node)) return 'location.href='
|
||||
return null
|
||||
}
|
||||
|
||||
function isFunctionLike(node: any): boolean {
|
||||
return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)
|
||||
|| ts.isArrowFunction(node) || ts.isMethodDeclaration(node)
|
||||
}
|
||||
|
||||
function functionName(node: any): string {
|
||||
if (!node) return ''
|
||||
if (node.name && typeof node.name.text === 'string') return node.name.text
|
||||
if (node.parent && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) return node.parent.name.text
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 沿 parent 链收集具名宿主函数(校验常写在入口函数开头,所以整条链都算)。 */
|
||||
function hostChainOf(node: any): string[] {
|
||||
const names: string[] = []
|
||||
let cur = node
|
||||
while (cur) {
|
||||
if (isFunctionLike(cur)) {
|
||||
const name = functionName(cur)
|
||||
if (name && !names.includes(name)) names.push(name)
|
||||
}
|
||||
cur = cur.parent
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
/** 文件里具名函数 → 它(含嵌套块)调用到的名字集合。 */
|
||||
function collectCallGraph(sf: any): Map<string, string[]> {
|
||||
const graph = new Map<string, string[]>()
|
||||
walk(sf, (node: any) => {
|
||||
if (!isFunctionLike(node)) return
|
||||
const name = functionName(node)
|
||||
if (!name) return
|
||||
const calls = new Set<string>(graph.get(name) ?? [])
|
||||
walk(node, (inner: any) => {
|
||||
if (!ts.isCallExpression(inner)) return
|
||||
const called = calledName(inner)
|
||||
if (called) calls.add(called)
|
||||
})
|
||||
graph.set(name, [...calls])
|
||||
})
|
||||
return graph
|
||||
}
|
||||
|
||||
/** 哪些函数名"带白名单校验":自己调过 isHttpUrl/safeHttpUrl,或调用链上过。 */
|
||||
function guardedNamesOf(graph: Map<string, string[]>): Set<string> {
|
||||
const guarded = new Set<string>()
|
||||
for (const [name, calls] of graph) {
|
||||
if (calls.some((call) => GUARD_NAMES.has(call))) guarded.add(name)
|
||||
}
|
||||
let changed = true
|
||||
while (changed) {
|
||||
changed = false
|
||||
for (const [name, calls] of graph) {
|
||||
if (guarded.has(name)) continue
|
||||
if (calls.some((call) => guarded.has(call))) {
|
||||
guarded.add(name)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return guarded
|
||||
}
|
||||
|
||||
export function scanUrlOutlets(code: string, file: string, globallyGuarded: Set<string> = new Set()): OutletScan {
|
||||
const { script, lineOffset } = extractScript(code, file)
|
||||
const sf = parseModule(script, file)
|
||||
const guarded = guardedNamesOf(collectCallGraph(sf))
|
||||
const outlets: UrlOutlet[] = []
|
||||
walk(sf, (node: any) => {
|
||||
const kind = outletKindOf(node)
|
||||
if (!kind) return
|
||||
const hosts = hostChainOf(node)
|
||||
// 出口本身就是把守点的情况(`saveUrlWithProgress(...)` 这类收口函数):
|
||||
// 被调函数在别的模块里先校验再用地址,调用方不必重复判
|
||||
const calleeGuarded = ts.isCallExpression(node) && globallyGuarded.has(calledName(node))
|
||||
outlets.push({
|
||||
file,
|
||||
line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1 + lineOffset,
|
||||
kind,
|
||||
host: hosts[0] ?? '(模块顶层)',
|
||||
snippet: script.slice(node.getStart(sf), node.getEnd()).replace(/\s+/g, ' ').trim().slice(0, 90),
|
||||
guarded: calleeGuarded || hosts.some((host) => guarded.has(host)),
|
||||
})
|
||||
})
|
||||
return { file, outlets, unguarded: outlets.filter((outlet) => !outlet.guarded) }
|
||||
}
|
||||
|
||||
/** 一个文件里"导出、且自己调过白名单"的函数名(跨模块把守点)。 */
|
||||
export function exportedGuardedNames(code: string, file: string): string[] {
|
||||
const { script } = extractScript(code, file)
|
||||
const sf = parseModule(script, file)
|
||||
const graph = collectCallGraph(sf)
|
||||
const locallyGuarded = guardedNamesOf(graph)
|
||||
const exported = new Set<string>()
|
||||
walk(sf, (node: any) => {
|
||||
if (!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export)) return
|
||||
if (ts.isVariableStatement(node)) {
|
||||
for (const decl of node.declarationList.declarations) {
|
||||
if (ts.isIdentifier(decl.name) && decl.initializer && isFunctionLike(decl.initializer)) exported.add(decl.name.text)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!isFunctionLike(node)) return
|
||||
const name = functionName(node)
|
||||
if (name) exported.add(name)
|
||||
})
|
||||
return [...exported].filter(
|
||||
(name) => locallyGuarded.has(name) && (graph.get(name) ?? []).some((call) => GUARD_NAMES.has(call)),
|
||||
)
|
||||
}
|
||||
|
||||
/** 全库两遍:先把各模块的把守函数收上来,再判每个出口。 */
|
||||
export function scanAllUrlOutlets(sources: Array<{ file: string; code: string }>): OutletScan[] {
|
||||
const globallyGuarded = new Set<string>()
|
||||
for (const { file, code } of sources) {
|
||||
for (const name of exportedGuardedNames(code, file)) globallyGuarded.add(name)
|
||||
}
|
||||
return sources.map(({ file, code }) => scanUrlOutlets(code, file, globallyGuarded))
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
|
||||
/**
|
||||
* 卸载配对判据(2026-10-09 评审稳定面 5.0:「卸载未配对 3 处」user-token-sync.ts 的两个监听与轮询、
|
||||
* download-progress.ts 的桥事件监听,外加 BrandShopMatchTab.vue:471 那条——本轮回读实测该处已配对,
|
||||
* 心跳走 categorized-timers、focus/visibilitychange 都在 onUnmounted 里摘了,见本文件最后一条用例)。
|
||||
*
|
||||
* 口径两条,都按"同一个注册点必须找得回它的反注册"判,不是数文件里有没有出现过 clearInterval:
|
||||
* ① 定时器:文件里 `setInterval(` 的个数 ≤ 反注册个数(`clearInterval(` / categorized-timers 的
|
||||
* `clearTimer(` / `clearCategory(` / `clearScope(`);
|
||||
* ② 监听器:每个 `(window|document).addEventListener('事件名'` 都得在同文件里有
|
||||
* `removeEventListener('事件名'`,带 `{ once: true }` 的算自反注册。
|
||||
*
|
||||
* 剩下的例外进台账(只许减),并且每个卸载出口都得真的被根组件接上——
|
||||
* 只定义不接线等于没接。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
/** 台账:已知的、本轮判定"暂不配对"的注册点(数量只许减)。 */
|
||||
const UNPAIRED_LEDGER: Record<string, number> = {
|
||||
// 桥发现监听(pywebviewready):模块加载即绑,全应用生命周期都需要它,
|
||||
// 没有组件作用域可挂;绑之前有 pywebviewReadyBound 单次闸,不会累积。
|
||||
'src/shared/bridges/pywebview.ts': 1,
|
||||
}
|
||||
|
||||
/** 卸载出口必须被根组件接上(只定义不接线等于没接)。 */
|
||||
const WIRED_DISPOSERS = [
|
||||
'disposeGlobalErrorGuard',
|
||||
'uninstallUserTokenSync',
|
||||
'disposeDownloadProgressListener',
|
||||
'disposeUpdateProgressListener',
|
||||
]
|
||||
|
||||
const INTERVAL_REGISTER = /\bsetInterval\(/g
|
||||
const INTERVAL_TEARDOWN = /\bclearInterval\(|\bclearTimer\(|\bclearCategory\(|\bclearScope\(/g
|
||||
const LISTENER_REGISTER = /(?:window|document)\.addEventListener\??\.?\(\s*['"]([^'"]+)['"]([^\n]*)/g
|
||||
const LISTENER_TEARDOWN = /(?:window|document)\.removeEventListener\??\.?\(\s*['"]([^'"]+)['"]/g
|
||||
|
||||
interface PairingReport {
|
||||
file: string
|
||||
intervals: { registrations: number; teardowns: number }
|
||||
listeners: { event: string; line: number }[]
|
||||
}
|
||||
|
||||
function countMatches(source: string, re: RegExp): number {
|
||||
return (source.match(re) ?? []).length
|
||||
}
|
||||
|
||||
/** 扫一个文件的配对情况(判据与注入自证共用这一个函数)。 */
|
||||
export function scanPairing(source: string, file: string): PairingReport {
|
||||
const lines = source.split(/\r?\n/)
|
||||
const removedEvents = new Set<string>()
|
||||
for (const line of lines) {
|
||||
for (const m of line.matchAll(LISTENER_TEARDOWN)) removedEvents.add(m[1])
|
||||
}
|
||||
const dangling: { event: string; line: number }[] = []
|
||||
lines.forEach((line, index) => {
|
||||
for (const m of line.matchAll(LISTENER_REGISTER)) {
|
||||
const event = m[1]
|
||||
const tail = m[2] ?? ''
|
||||
if (/once:\s*true/.test(tail)) return // 自反注册,浏览器摘完就算配对
|
||||
if (removedEvents.has(event)) return
|
||||
dangling.push({ event, line: index + 1 })
|
||||
}
|
||||
})
|
||||
return {
|
||||
file,
|
||||
intervals: {
|
||||
registrations: countMatches(source, INTERVAL_REGISTER),
|
||||
teardowns: countMatches(source, INTERVAL_TEARDOWN),
|
||||
},
|
||||
listeners: dangling,
|
||||
}
|
||||
}
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const FILES = sourceFiles(SRC).map((file) => relative(ROOT, file).split(sep).join('/'))
|
||||
const REPORTS = FILES.map((rel) => scanPairing(readFileSync(join(ROOT, ...rel.split('/')), 'utf-8'), rel))
|
||||
|
||||
function unpairedListeners(report: PairingReport): number {
|
||||
return report.listeners.length
|
||||
}
|
||||
|
||||
function intervalImbalance(report: PairingReport): number {
|
||||
return report.intervals.registrations - report.intervals.teardowns
|
||||
}
|
||||
|
||||
test('分母自证:定时器与监听器都真的数到了东西(扫不到不等于没有)', () => {
|
||||
const intervalRegistrations = REPORTS.reduce((sum, r) => sum + r.intervals.registrations, 0)
|
||||
const listenerRegistrations = FILES.reduce((sum, rel) => {
|
||||
const source = readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
return sum + countMatches(source, LISTENER_REGISTER)
|
||||
}, 0)
|
||||
assert.ok(FILES.length > 100, `只扫到 ${FILES.length} 个源文件,分母不对`)
|
||||
assert.ok(FILES.some((f) => f.endsWith('.vue')), '.vue 没进分母就是漏扫')
|
||||
assert.ok(intervalRegistrations >= 6, `全树只数到 ${intervalRegistrations} 处 setInterval(下限 6)——扫描器失明`)
|
||||
assert.ok(listenerRegistrations >= 9, `全树只数到 ${listenerRegistrations} 处 window/document 监听(下限 9)——扫描器失明`)
|
||||
// 非零对照:已知配好对的 NotificationBell 必须被数成"注册 3 处",否则是口径没命中
|
||||
const bell = REPORTS.find((r) => r.file === 'src/shared/components/NotificationBell.vue')
|
||||
assert.ok(bell && bell.intervals.registrations >= 1, 'NotificationBell.vue 的定时器没进分母')
|
||||
assert.ok(bell && unpairedListeners(bell) === 0, 'NotificationBell.vue 三个监听都摘了,不该被判挂')
|
||||
})
|
||||
|
||||
test('定时器配对:每个 setInterval 都找得回 clearInterval(含 categorized-timers)', () => {
|
||||
const offenders = REPORTS
|
||||
.filter((r) => intervalImbalance(r) > 0)
|
||||
.map((r) => `${r.file}:注册 ${r.intervals.registrations} 处、反注册 ${r.intervals.teardowns} 处`)
|
||||
assert.deepEqual(offenders, [], `这些文件的定时器没有对应的清理:\n${offenders.join('\n')}`)
|
||||
})
|
||||
|
||||
test('监听器配对:每个 addEventListener 都找得回同名 removeEventListener(台账之外 0 处)', () => {
|
||||
const ledger: Record<string, number> = {}
|
||||
for (const report of REPORTS) {
|
||||
const count = unpairedListeners(report)
|
||||
if (count) ledger[report.file] = count
|
||||
}
|
||||
const worse: string[] = []
|
||||
for (const [file, count] of Object.entries(ledger)) {
|
||||
const allowed = UNPAIRED_LEDGER[file]
|
||||
if (allowed === undefined) worse.push(`${file} 新增未配对监听 ${count} 处:${REPORTS.find((r) => r.file === file)?.listeners.map((l) => `${l.event}@${l.line}`).join(', ')}`)
|
||||
else if (count > allowed) worse.push(`${file} 从 ${allowed} 处涨到 ${count} 处`)
|
||||
}
|
||||
assert.deepEqual(worse, [], `未配对监听比台账多了:\n${worse.join('\n')}`)
|
||||
// 台账自己也得是活的:写了一条早就不存在的例外同样是通过不了的红
|
||||
for (const file of Object.keys(UNPAIRED_LEDGER)) {
|
||||
assert.ok(file in ledger, `台账里的 ${file} 已经没有未配对监听了,把这一格删掉(只许减)`)
|
||||
}
|
||||
})
|
||||
|
||||
test('本轮修好的 3 处现在成对了(评审点名的 user-token-sync ×3 与 download-progress ×1)', () => {
|
||||
const tokenSync = REPORTS.find((r) => r.file === 'src/shared/auth/user-token-sync.ts')
|
||||
assert.ok(tokenSync, 'user-token-sync.ts 没进分母')
|
||||
assert.ok(intervalImbalance(tokenSync) <= 0, '60 秒兜底轮询还是没有 clearInterval')
|
||||
assert.deepEqual(tokenSync.listeners, [], 'pywebviewready / storage 监听还没配 removeEventListener')
|
||||
assert.match(read('src/shared/auth/user-token-sync.ts'), /export function uninstallUserTokenSync\(\)/)
|
||||
|
||||
const download = REPORTS.find((r) => r.file === 'src/shared/utils/download-progress.ts')
|
||||
assert.ok(download, 'download-progress.ts 没进分母')
|
||||
assert.ok(intervalImbalance(download) <= 0, '清扫定时器没配对')
|
||||
assert.deepEqual(download.listeners, [], 'pywebview-download-progress 桥监听没配对')
|
||||
assert.match(read('src/shared/utils/download-progress.ts'), /export function disposeDownloadProgressListener\(\)/)
|
||||
|
||||
const version = REPORTS.find((r) => r.file === 'src/shared/composables/useVersionUpdate.ts')
|
||||
assert.ok(version, 'useVersionUpdate.ts 没进分母')
|
||||
assert.deepEqual(version.listeners, [], 'pywebview-update-progress 桥监听没配对')
|
||||
})
|
||||
|
||||
test('卸载出口都接在根组件上:只定义不接线等于没接', () => {
|
||||
const appVue = read('src/App.vue')
|
||||
assert.match(appVue, /onBeforeUnmount\(\(\)\s*=>\s*\{/, 'App.vue 没有 onBeforeUnmount')
|
||||
const missing = WIRED_DISPOSERS.filter((name) => {
|
||||
const defined = REPORTS.some((r) => read(r.file).includes(`export function ${name}`))
|
||||
return !defined || !new RegExp(`onBeforeUnmount\\(\\(\\)\\s*=>\\s*\\{[^}]*${name}\\(\\)`).test(appVue)
|
||||
})
|
||||
assert.deepEqual(missing, [], `这些卸载出口没定义或没接进 App.vue:${missing.join(', ')}`)
|
||||
})
|
||||
|
||||
test('注入自证:造一个未配对的注册点一定被判红,once:true 不误报', () => {
|
||||
const target = 'src/shared/auth/user-token-sync.ts'
|
||||
const source = read(target)
|
||||
// ① 把 storage 的反注册删掉 → 该判成未配对
|
||||
const stripped = source.replace('window.removeEventListener(\'storage\', storageHandler)', '/* 反注册被删掉 */')
|
||||
assert.notEqual(stripped, source, '注入没生效,这条自证是假的')
|
||||
assert.deepEqual(scanPairing(stripped, target).listeners.map((l) => l.event), ['storage'], '删掉反注册却没被判红')
|
||||
// ② 凭空加一个定时器 → 分母与失衡都要跟着动
|
||||
const withTimer = source + '\nfunction injectedProbeForPairing() { window.setInterval(() => { void 0 }, 1000) }\n'
|
||||
const after = scanPairing(withTimer, target)
|
||||
assert.equal(after.intervals.registrations, scanPairing(source, target).intervals.registrations + 1, '新增的 setInterval 没进分母')
|
||||
assert.equal(intervalImbalance(after), 1, '新增的 setInterval 没被判成未配对')
|
||||
// ③ once:true 是浏览器自摘,不该算违例
|
||||
const withOnce = source + '\nwindow.addEventListener(\'focus\', () => { void 0 }, { once: true })\n'
|
||||
assert.deepEqual(scanPairing(withOnce, target).listeners, [], 'once:true 被误判成未配对了')
|
||||
})
|
||||
|
||||
test('BrandShopMatchTab.vue(评审点名的第 3 处)现在真的配对了', () => {
|
||||
const rel = 'src/pages/brand/components/BrandShopMatchTab.vue'
|
||||
const report = scanPairing(read(rel), rel)
|
||||
assert.ok(report.intervals.registrations >= 1, '这文件的心跳定时器没进分母')
|
||||
assert.ok(intervalImbalance(report) <= 0, '心跳/派发定时器没配对')
|
||||
assert.deepEqual(report.listeners, [], 'focus / visibilitychange 监听没配对')
|
||||
const source = read(rel)
|
||||
assert.match(source, /onUnmounted\(\(\) => \{[^}]*window\.removeEventListener\('focus'/, 'onUnmounted 里没摘 focus 监听')
|
||||
assert.match(source, /timers\.clearTimer\('scheduled-dispatch'/, '派发定时器没有分类清理')
|
||||
})
|
||||
|
||||
function read(rel: string): string {
|
||||
return readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import {
|
||||
CANCELLED_STATUS_TEXT,
|
||||
CANCELLED_STATUS_WORDS,
|
||||
RUNNING_UNTIL_DONE_STATUS_OPTIONS,
|
||||
TASK_STATUS_CLASS,
|
||||
TASK_STATUS_TEXT,
|
||||
taskStatusClass,
|
||||
taskStatusText,
|
||||
} from '../src/shared/utils/task-status-text.ts'
|
||||
|
||||
/**
|
||||
* 取消态不得显示为进行中(2026-10-09 评审流程面 5.5 的那条:`CANCELLED` 在 3 个页面被念成「执行中」)。
|
||||
*
|
||||
* 成因不在映射表写错,而在 `RUNNING_UNTIL_DONE_STATUS_OPTIONS` 的 `replace: true`:
|
||||
* 它只列了 SUCCESS/COMPLETED/FAILED 三行,`replace` 又把默认表整个丢掉,
|
||||
* 于是 CANCELLED 掉进 `textFallback: '执行中'`——任务早被撤掉了,界面还在说"正在跑"。
|
||||
*
|
||||
* 判据三层:① 真值表行为钉子(import 真函数跑);② 非终态照旧显示执行中(防止把修复做成"取消也回退成等待中");
|
||||
* ③ 全树扫描"取消词 → 进行中文案"的形状,配注入自证与硬分母。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const SRC = resolve(here, '../src')
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 「取消词被映射成进行中」的形状:`CANCELLED: '执行中'` / `CANCELED: "正在执行"`。 */
|
||||
const CANCELLED_AS_RUNNING_TEXT = /\b(?:CANCELLED|CANCELED)\s*:\s*['"`]?\s*(?:执行中|正在执行|运行中|进行中)/
|
||||
|
||||
/** 取消词的全部拼写(词面本身也是分母的一部分)。 */
|
||||
const CANCELLED_WORD = /\b(?:CANCELLED|CANCELED)\b/g
|
||||
|
||||
/** 找出源码里把取消态念成进行中的行(判据与注入自证共用同一个函数)。 */
|
||||
function cancelledShownAsRunning(source: string): string[] {
|
||||
return source.split(/\r?\n/).filter((line) => CANCELLED_AS_RUNNING_TEXT.test(line))
|
||||
}
|
||||
|
||||
test('共用表上取消态是「已取消」,两种拼写都认', () => {
|
||||
for (const word of ['CANCELLED', 'CANCELED', 'cancelled', 'canceled', ' CANCELLED ']) {
|
||||
assert.equal(taskStatusText(word), CANCELLED_STATUS_TEXT, `${word} 的文案判错`)
|
||||
assert.equal(taskStatusClass(word), 'failed', `${word} 的样式类判错`)
|
||||
}
|
||||
assert.deepEqual([...CANCELLED_STATUS_WORDS].sort(), ['CANCELED', 'CANCELLED'], '取消态词表少了拼写')
|
||||
// 默认表里两种拼写都在(美式/英式并存,Java 侧两种都发得出)
|
||||
assert.ok('CANCELLED' in TASK_STATUS_TEXT && 'CANCELED' in TASK_STATUS_TEXT, '默认文案表少了一种取消拼写')
|
||||
assert.ok('CANCELLED' in TASK_STATUS_CLASS && 'CANCELED' in TASK_STATUS_CLASS, '默认样式表少了一种取消拼写')
|
||||
})
|
||||
|
||||
test('出问题的那 3 页(replace 表):取消态不得是「执行中」,非终态照旧是「执行中」', () => {
|
||||
assert.equal(taskStatusText('CANCELLED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '已取消')
|
||||
assert.equal(taskStatusText('CANCELED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '已取消')
|
||||
assert.equal(taskStatusClass('CANCELLED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), 'failed')
|
||||
// 反过来也得钉住:这张表的本职是"没到终态就说执行中",不能顺手把等待中也改了
|
||||
for (const running of ['RUNNING', 'PENDING', 'SCHEDULED', 'QUEUED', 'WHATEVER_NEW']) {
|
||||
assert.equal(taskStatusText(running, RUNNING_UNTIL_DONE_STATUS_OPTIONS), '执行中', `${running} 该仍显示执行中`)
|
||||
assert.equal(taskStatusClass(running, RUNNING_UNTIL_DONE_STATUS_OPTIONS), 'running', `${running} 该仍是 running`)
|
||||
}
|
||||
assert.equal(taskStatusText('SUCCESS', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '已完成')
|
||||
assert.equal(taskStatusText('FAILED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '失败')
|
||||
})
|
||||
|
||||
test('全树扫描:没有任何一处把取消态映射成进行中文案', () => {
|
||||
const offenders: string[] = []
|
||||
let cancelledWordSites = 0
|
||||
for (const file of sourceFiles(SRC)) {
|
||||
const rel = file.slice(SRC.length + 1).replace(/\\/g, '/')
|
||||
const source = readFileSync(file, 'utf-8')
|
||||
cancelledWordSites += (source.match(CANCELLED_WORD) ?? []).length
|
||||
for (const line of cancelledShownAsRunning(source)) {
|
||||
offenders.push(`${rel}: ${line.trim().slice(0, 120)}`)
|
||||
}
|
||||
}
|
||||
// 分母硬钉:取消词在树上的出现次数(改文案前实测 20+),塌了说明扫描器失明
|
||||
assert.ok(cancelledWordSites >= 15, `全树只扫到 ${cancelledWordSites} 处取消词(下限 15)——此刻的"零违规"不作数`)
|
||||
assert.deepEqual(offenders, [], `这些行把取消态念成了进行中:\n${offenders.join('\n')}`)
|
||||
})
|
||||
|
||||
test('注入自证:尺子抓得住自己造的违例,也放得过合法写法', () => {
|
||||
const planted = " text: { SUCCESS: '已完成', CANCELLED: '执行中' },"
|
||||
assert.deepEqual(cancelledShownAsRunning(planted).length, 1, '造出来的违例没被抓到,上面那条"零违规"是恒绿')
|
||||
const plantedUs = " return taskStatusText(st, { text: { CANCELED: '正在执行' } })"
|
||||
assert.deepEqual(cancelledShownAsRunning(plantedUs).length, 1, '美式拼写的违例没被抓到')
|
||||
// 合法写法:取消态映射成别的中文、或进行中词映射成进行中
|
||||
assert.equal(cancelledShownAsRunning(" CANCELLED: '已取消',").length, 0, '合法文案被判成了违例')
|
||||
assert.equal(cancelledShownAsRunning(" RUNNING: '执行中',").length, 0, '非取消词不该被这条尺子管')
|
||||
// 真源码里也验一遍:改坏了立刻能在这里现形,而不是在页面截图里
|
||||
const real = readFileSync(join(SRC, 'shared/utils/task-status-text.ts'), 'utf-8')
|
||||
assert.deepEqual(cancelledShownAsRunning(real), [], 'task-status-text.ts 自己就把取消态写成了进行中')
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import { decideAuthGate, hasUsableToken, hasUsableUid, shouldBounceToHome } from '../src/shared/auth/auth-gate.ts'
|
||||
|
||||
/**
|
||||
* `ensure-auth.ts` 的 uid 短路(2026-10-09 评审安全面:「只要 localStorage 里有 uid 就短路免校验」)。
|
||||
*
|
||||
* 判过才动:不能硬删。`shared/api/http.ts` 里 axios 是 `withCredentials: true`,
|
||||
* 桌面端与线上 Web 同源,Java 侧的同源会话 cookie 仍然算登录(那行注释原话"桌面端同源 cookie 仍可用"),
|
||||
* 这种形态本机只有 uid、没有 JWT。直接把短路改成"无令牌即拒",会把这类合法入口锁在登录页外。
|
||||
*
|
||||
* 所以做的是**收窄**:只有 uid 与令牌同时存在才免掉那一次 `/newApi/check_login`
|
||||
* (令牌本身每次请求都要过后端,这里省的只是守卫那一次往返);只有 uid、或只有令牌 → 问服务端;
|
||||
* 两者都没有 → 拒。剩下的例外(uid+令牌 免一次校验)进本文件的名单,新增免校验入口就红。
|
||||
*
|
||||
* 三把尺子:① 真值表(import 真函数跑);② 全树"看见 uid 就 return true"的形状清零;
|
||||
* ③ 门禁面上读 uid 的文件名单。每条都配注入自证与硬分母。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
/** 门禁面:决定"能不能不进登录页"的那几个文件(新增免校验几乎都会落在这里)。 */
|
||||
const GATE_SURFACE = ['src/main.ts', 'src/router/index.ts', 'src/shared/auth/']
|
||||
|
||||
/**
|
||||
* 例外名单(只许减):读了 uid 但不走 decideAuthGate 的门禁面文件 + 理由。
|
||||
* kick-handler 只做"清登录态",它不是在放行谁,删掉它反而会让下线收口找不到键名。
|
||||
*/
|
||||
const GATE_EXCEPTIONS: Record<string, string> = {
|
||||
'src/shared/auth/kick-handler.ts': '被顶下线/登录失效时清 uid 与令牌,属于清态不是免校验',
|
||||
}
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const FILES = sourceFiles(SRC).map((file) => relative(ROOT, file).split(sep).join('/'))
|
||||
function read(rel: string): string {
|
||||
return readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
}
|
||||
|
||||
const UID_READ = /(?:getItem|removeItem|setItem)\(\s*(?:UID_KEY|'uid')\s*\)/
|
||||
const GATE_CALL = /decideAuthGate\(|shouldBounceToHome\(/
|
||||
|
||||
/** 去掉块注释但保持行数(注释里引用的旧写法不该被判成代码里的免校验分支)。 */
|
||||
function stripBlockComments(source: string): string {
|
||||
return source.replace(/\/\*[\s\S]*?\*\//g, (block) => block.split('\n').map(() => '').join('\n'))
|
||||
}
|
||||
|
||||
/**
|
||||
* "看见 uid 就免校验"的形状:`return true` 往上找 3 行内的最后一个 if,
|
||||
* 条件里出现 uid 且没走门禁函数 → 判成免校验出口。
|
||||
*/
|
||||
function findUidBypassLines(source: string): Array<{ line: number; text: string }> {
|
||||
// 块注释先抹掉(行数保持):auth-gate.ts 的头注释里引用了那句旧写法,不能被当成代码里的免校验分支
|
||||
const lines = stripBlockComments(source).split(/\r?\n/)
|
||||
const found: Array<{ line: number; text: string }> = []
|
||||
lines.forEach((line, index) => {
|
||||
if (!/\breturn\s+(?:true|!0)\b/.test(line)) return
|
||||
const window = lines.slice(Math.max(0, index - 3), index + 1).join('\n')
|
||||
const conditions = [...window.matchAll(/\bif\s*\(([^\n]*)/g)]
|
||||
if (!conditions.length) return
|
||||
const condition = conditions[conditions.length - 1][1] ?? ''
|
||||
if (!/UID_KEY|['"]uid['"]|rawUid|\buid\b/.test(condition)) return
|
||||
if (GATE_CALL.test(condition)) return
|
||||
found.push({ line: index + 1, text: line.trim().slice(0, 90) })
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
/** 门禁面里读 uid 却没走门禁函数、又不在例外名单上的文件。 */
|
||||
function uidGateProblems(files: string[], readFile: (rel: string) => string): string[] {
|
||||
const problems: string[] = []
|
||||
for (const rel of files) {
|
||||
if (!GATE_SURFACE.some((prefix) => rel === prefix || rel.startsWith(prefix))) continue
|
||||
const source = readFile(rel)
|
||||
if (!UID_READ.test(source)) continue
|
||||
if (GATE_CALL.test(source)) continue
|
||||
if (GATE_EXCEPTIONS[rel]) continue
|
||||
problems.push(`${rel} 读了 uid 但既没走 decideAuthGate/shouldBounceToHome,也不在例外名单里`)
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
/** 门禁面里确实读着 uid 的文件(名单判据的分母)。 */
|
||||
function uidReadersInGateSurface(files: string[], readFile: (rel: string) => string): string[] {
|
||||
return files.filter((rel) => (
|
||||
GATE_SURFACE.some((prefix) => rel === prefix || rel.startsWith(prefix))
|
||||
&& UID_READ.test(readFile(rel))
|
||||
))
|
||||
}
|
||||
|
||||
test('真值表:收窄后的判定——uid 单独成立不再免校验', () => {
|
||||
assert.equal(decideAuthGate({ uid: '42', token: 'jwt' }), 'pass-local', 'uid+令牌 还免校验(这是名单里那条例外)')
|
||||
assert.equal(decideAuthGate({ uid: '42', token: '' }), 'restore', '只有 uid 必须去问服务端,不再免校验')
|
||||
assert.equal(decideAuthGate({ uid: '', token: 'jwt' }), 'restore', '只有令牌也要问一次')
|
||||
assert.equal(decideAuthGate({ uid: '', token: '' }), 'deny')
|
||||
assert.equal(decideAuthGate({}), 'deny')
|
||||
assert.equal(decideAuthGate({ uid: null, token: undefined }), 'deny')
|
||||
// uid 成形与否:'0'、空、非数字都不算登录过
|
||||
for (const bad of ['0', '', ' ', '-1', 'abc', 'NaN', 'null']) {
|
||||
assert.equal(hasUsableUid(bad), false, `${bad} 不该被当成 uid`)
|
||||
assert.equal(decideAuthGate({ uid: bad, token: 'jwt' }), 'restore', `${bad} 配令牌时也不能免校验`)
|
||||
}
|
||||
assert.equal(hasUsableUid('42'), true)
|
||||
assert.equal(hasUsableToken(' '), false)
|
||||
assert.equal(hasUsableToken('jwt'), true)
|
||||
})
|
||||
|
||||
test('登录页反弹:只有本机证据齐才把 /login 送回首页,掉了令牌的用户能打开登录页', () => {
|
||||
assert.equal(shouldBounceToHome({ uid: '42', token: 'jwt' }), true)
|
||||
// 评审那条的真实后果在这里:uid 在、令牌没了 → 原来永远点不开登录页,只能靠 URL 上的 logout/switch 自救
|
||||
assert.equal(shouldBounceToHome({ uid: '42', token: '' }), false, '只有 uid 仍被反弹,登录页还是打不开')
|
||||
assert.equal(shouldBounceToHome({ uid: '', token: 'jwt' }), false)
|
||||
assert.equal(shouldBounceToHome({}), false)
|
||||
})
|
||||
|
||||
test('全树没有"看见 uid 就 return true"的形状(免校验只能经门禁函数判)', () => {
|
||||
const offenders: string[] = []
|
||||
for (const rel of FILES) {
|
||||
for (const hit of findUidBypassLines(read(rel))) {
|
||||
offenders.push(`${rel}:${hit.line} ${hit.text}`)
|
||||
}
|
||||
}
|
||||
assert.deepEqual(offenders, [], `这些地方绕过门禁自己放行了:\n${offenders.join('\n')}`)
|
||||
// 原写法必须被同一口径抓到(否则上一条的"零"是假的)
|
||||
const original = [
|
||||
" const rawUid = window.localStorage.getItem(UID_KEY) || ''",
|
||||
' if (rawUid && Number(rawUid) > 0) {',
|
||||
' return true',
|
||||
' }',
|
||||
].join('\n')
|
||||
assert.equal(findUidBypassLines(original).length, 1, '评审点名的原写法没被抓到,上面的零违规不作数')
|
||||
assert.equal(findUidBypassLines(' if (window.localStorage.getItem(\'uid\')) return true').length, 1, '内联写法没被抓到')
|
||||
// 合法形状不许误报(误报的尺子下次没人信)
|
||||
assert.equal(findUidBypassLines(" const ok = await ensureAuth()\n if (!ok) return false\n return true").length, 0, '与 uid 无关的 return true 被误判')
|
||||
assert.equal(findUidBypassLines(' if (shouldBounceToHome({ uid, token })) {\n return true\n }').length, 0, '走了门禁函数的写法被误判')
|
||||
})
|
||||
|
||||
test('门禁面名单:读 uid 的文件必须走门禁函数或在例外里(新增免校验入口就红)', () => {
|
||||
const readers = uidReadersInGateSurface(FILES, read)
|
||||
// 分母硬钉:门禁面确实读着 uid(评审点名的那两处就在里面),塌了说明口径没命中
|
||||
assert.ok(readers.includes('src/shared/auth/ensure-auth.ts'), 'ensure-auth.ts 没进名单——扫描口径变了')
|
||||
assert.ok(readers.includes('src/main.ts'), 'main.ts 的 uid 读取没进名单——扫描口径变了')
|
||||
assert.deepEqual(uidGateProblems(FILES, read), [], '门禁面出现了不走门禁的 uid 读取')
|
||||
// 名单里的例外必须还成立(不留僵尸条目)
|
||||
for (const rel of Object.keys(GATE_EXCEPTIONS)) {
|
||||
assert.ok(readers.includes(rel), `例外名单里的 ${rel} 已经不读 uid 了,删掉这一格(只许减)`)
|
||||
}
|
||||
})
|
||||
|
||||
test('ensure-auth 的接线:两个入口(硬校验与软恢复)都走同一个门禁函数', () => {
|
||||
const source = read('src/shared/auth/ensure-auth.ts')
|
||||
assert.match(source, /import \{ decideAuthGate \} from '\.\/auth-gate\.ts'/)
|
||||
const hard = source.slice(source.indexOf('export async function ensureAuth'), source.indexOf('export async function restoreLoginUser'))
|
||||
assert.match(hard, /decideAuthGate\(\{\s*uid:[\s\S]{0,120}?token:/, 'ensureAuth 没把 uid 与令牌一起交给门禁')
|
||||
assert.match(hard, /if \(decision === 'pass-local'\)[\s\S]{0,40}?return true/, 'ensureAuth 没按判定结果放行')
|
||||
assert.match(hard, /if \(decision === 'deny'\)[\s\S]{0,40}?return false/, 'ensureAuth 没按判定结果拒绝')
|
||||
const soft = source.slice(source.indexOf('export async function restoreLoginUser'))
|
||||
assert.match(soft, /decideAuthGate\(\{\s*uid:[\s\S]{0,120}?token:/, 'restoreLoginUser 没走门禁')
|
||||
// 旧的"uid 存在即免校验"不许以另一种写法回来
|
||||
assert.ok(!/if \(rawUid && Number\(rawUid\) > 0\)/.test(source), 'ensure-auth.ts 里旧的短路又出现了')
|
||||
})
|
||||
|
||||
test('注入自证:门禁面新增一条免校验分支立刻变红', () => {
|
||||
const rel = 'src/shared/auth/ensure-auth.ts'
|
||||
const source = read(rel)
|
||||
const anchor = 'export async function ensureAuth(): Promise<boolean> {'
|
||||
assert.equal(source.split(anchor).length - 1, 1, '锚点不唯一,注入自证不作数')
|
||||
const injected = source.replace(anchor, `${anchor}\n if (window.localStorage.getItem(UID_KEY)) {\n return true\n }`)
|
||||
assert.notEqual(injected, source, '注入没生效,这条自证是假的')
|
||||
assert.ok(findUidBypassLines(injected).length >= 1, '注入的免校验分支没被抓到')
|
||||
assert.equal(findUidBypassLines(source).length, 0, '真源码本身就该是零形状')
|
||||
// 名单判据也必须是活的:门禁面冒出一个不走门禁、也不在例外里的新文件 → 立刻有名字
|
||||
const fakeFiles = [...FILES, 'src/shared/auth/brand-new-gate.ts']
|
||||
const fakeRead = (rel: string) => (rel === 'src/shared/auth/brand-new-gate.ts'
|
||||
? "const uid = window.localStorage.getItem(UID_KEY)\n if (uid) {\n return true\n }\n"
|
||||
: read(rel))
|
||||
assert.deepEqual(uidGateProblems(fakeFiles, fakeRead), ['src/shared/auth/brand-new-gate.ts 读了 uid 但既没走 decideAuthGate/shouldBounceToHome,也不在例外名单里'])
|
||||
assert.equal(uidGateProblems(FILES, read).length, 0, '真名单上就有不走门禁的 uid 读取')
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import { listSourceFiles, readSource } from './helpers/task-terminal-ast-ruler.ts'
|
||||
import { exportedGuardedNames, scanAllUrlOutlets, scanUrlOutlets } from './helpers/url-outlet-scanner.ts'
|
||||
import { isHttpUrl, safeHttpUrl } from '../src/shared/utils/safe-url.ts'
|
||||
|
||||
/**
|
||||
* 跳转/下载出口的白名单强制校验(2026-10-09 评审安全面:`safeHttpUrl` 已经有了,
|
||||
* 但 `BrandBrandTab.vue`、`BrandVariantTab.vue`、`useVersionUpdate.ts` 三处直接拿服务端返回的
|
||||
* `file_url` 去 `window.open` / `location.href`)。
|
||||
*
|
||||
* 判据按 AST 判"这次跳转的地址过没过白名单"(口径与理由写在 helpers/url-outlet-scanner.ts)。
|
||||
* 本轮顺手把把守点下沉到了 `saveUrlWithProgress`:14 个下载出口共用同一个桥入口,
|
||||
* 在那一处判比在每页各补一遍靠谱,也防止"新增一页忘了判"。
|
||||
*
|
||||
* 台账:未过校验的出口数只许减(现在钉 0),新增一处就红。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
|
||||
/** 台账:已知未校验的跳转/下载出口(文件 → 处数)。本轮清零,往后只许减不许加。 */
|
||||
const UNGUARDED_LEDGER: Record<string, number> = {}
|
||||
|
||||
const FILES = listSourceFiles(resolve(ROOT, 'src')).map((p) => relative(ROOT, p).split(sep).join('/'))
|
||||
const SOURCES = FILES.map((file) => ({ file, code: readSource(file, ROOT) }))
|
||||
|
||||
function scan(sources = SOURCES) {
|
||||
return scanAllUrlOutlets(sources)
|
||||
}
|
||||
|
||||
const SCANS = scan()
|
||||
const ALL_OUTLETS = SCANS.flatMap((s) => s.outlets)
|
||||
const ALL_UNGUARDED = SCANS.flatMap((s) => s.unguarded)
|
||||
|
||||
function scanOf(file: string) {
|
||||
return SCANS.find((s) => s.file === file)
|
||||
}
|
||||
|
||||
test('分母自证:出口真的被数到了(扫不到就不许报"全部已校验")', () => {
|
||||
assert.ok(FILES.length > 100, `只扫到 ${FILES.length} 个源文件,分母不对`)
|
||||
assert.ok(ALL_OUTLETS.length >= 20, `全树只数到 ${ALL_OUTLETS.length} 处跳转/下载出口(下限 20)——扫描器失明`)
|
||||
const kinds = new Set(ALL_OUTLETS.map((outlet) => outlet.kind))
|
||||
for (const kind of ['window.open', 'saveUrlWithProgress', 'location.href=']) {
|
||||
assert.ok(kinds.has(kind), `出口形状 ${kind} 一种都没扫到,判据口径变了`)
|
||||
}
|
||||
// 非零对照:评审点名的 3 个文件各自都得有出口进了分母
|
||||
assert.ok(scanOf('src/pages/brand/components/BrandBrandTab.vue')?.outlets.length >= 2, 'BrandBrandTab 的下载出口没进分母')
|
||||
assert.ok(scanOf('src/pages/brand/components/BrandVariantTab.vue')?.outlets.length >= 2, 'BrandVariantTab 的下载出口没进分母')
|
||||
assert.ok(scanOf('src/shared/composables/useVersionUpdate.ts')?.outlets.length >= 1, 'useVersionUpdate 的跳转出口没进分母')
|
||||
})
|
||||
|
||||
test('全树跳转/下载出口都过了白名单(台账之外 0 处)', () => {
|
||||
const ledger: Record<string, number> = {}
|
||||
for (const outlet of ALL_UNGUARDED) {
|
||||
ledger[outlet.file] = (ledger[outlet.file] ?? 0) + 1
|
||||
}
|
||||
const worse: string[] = []
|
||||
for (const [file, count] of Object.entries(ledger)) {
|
||||
const allowed = UNGUARDED_LEDGER[file]
|
||||
if (allowed === undefined) worse.push(`${file} 出现未校验出口 ${count} 处`)
|
||||
else if (count > allowed) worse.push(`${file} 从 ${allowed} 处涨到 ${count} 处`)
|
||||
}
|
||||
const evidence = ALL_UNGUARDED.map((o) => `${o.file}:${o.line} ${o.kind}(宿主 ${o.host})${o.snippet}`).join('\n')
|
||||
assert.deepEqual(worse, [], `这些跳转/下载没先校验地址:\n${evidence}`)
|
||||
// 台账里的例外现在都不存在了,留着就是尺子在放水
|
||||
for (const file of Object.keys(UNGUARDED_LEDGER)) {
|
||||
assert.ok(file in ledger, `台账里的 ${file} 已经没有未校验出口了,把这一格删掉(只许减)`)
|
||||
}
|
||||
})
|
||||
|
||||
test('评审点名的 3 处:现在都经白名单,且拒绝时看得见', () => {
|
||||
for (const file of [
|
||||
'src/pages/brand/components/BrandBrandTab.vue',
|
||||
'src/pages/brand/components/BrandVariantTab.vue',
|
||||
'src/shared/composables/useVersionUpdate.ts',
|
||||
]) {
|
||||
const found = scanOf(file)
|
||||
assert.ok(found, `${file} 没进分母`)
|
||||
assert.deepEqual(found.unguarded, [], `${file} 还有未校验的跳转/下载出口`)
|
||||
const source = readSource(file, ROOT)
|
||||
assert.match(source, /isHttpUrl\(/, `${file} 里没找到判定式白名单`)
|
||||
assert.match(source, /safeHttpUrl\(/, `${file} 里没找到安全地址出口`)
|
||||
assert.match(source, /\[safe-url\]/, `${file} 校验不通过时没留一行可查的记录`)
|
||||
}
|
||||
// 被拦下时不是"什么都不做":三处都得把话说到界面上
|
||||
assert.match(readSource('src/pages/brand/components/BrandBrandTab.vue', ROOT), /function openDownloadUrl\(/)
|
||||
assert.match(readSource('src/pages/brand/components/BrandVariantTab.vue', ROOT), /async function downloadSource\([\s\S]*?isHttpUrl\(/)
|
||||
assert.match(readSource('src/shared/composables/useVersionUpdate.ts', ROOT), /async function startUpdate\([\s\S]*?isHttpUrl\([\s\S]*?hint\.value = '更新包地址不可用/)
|
||||
})
|
||||
|
||||
test('把守点下沉:saveUrlWithProgress 自己先校验,新增页面漏判也跳不出去', () => {
|
||||
const source = readSource('src/shared/utils/download-progress.ts', ROOT)
|
||||
assert.match(source, /export async function saveUrlWithProgress\([\s\S]{0,400}?if \(!isHttpUrl\(url\)\)/,
|
||||
'saveUrlWithProgress 没有在入口先校验地址')
|
||||
assert.match(source, /return \{ success: false, error: UNSAFE_DOWNLOAD_URL_TEXT \}/, '校验不通过时没有把原因回给调用方')
|
||||
assert.ok(exportedGuardedNames(source, 'src/shared/utils/download-progress.ts').includes('saveUrlWithProgress'),
|
||||
'扫描器没把 saveUrlWithProgress 认成跨模块把守点')
|
||||
})
|
||||
|
||||
test('isHttpUrl 真值表:与 safeHttpUrl 同一个口径,不各判一套', () => {
|
||||
for (const ok of ['https://cdn.example.com/a.mp4', 'http://127.0.0.1:5173/x', '/newApi/download/x']) {
|
||||
assert.equal(isHttpUrl(ok), true, `${ok} 该放行`)
|
||||
assert.notEqual(safeHttpUrl(ok), '#', `${ok} 两个函数判得不一致`)
|
||||
}
|
||||
for (const bad of ['javascript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'file:///C:/win.ini', ' ', '', undefined, null]) {
|
||||
assert.equal(isHttpUrl(bad as string), false, `${bad} 该拦下`)
|
||||
assert.equal(safeHttpUrl(bad as string), '#', `${bad} 两个函数判得不一致`)
|
||||
}
|
||||
})
|
||||
|
||||
test('注入自证:把白名单调用摘掉,扫描器立刻报未校验', () => {
|
||||
const file = 'src/pages/brand/components/BrandBrandTab.vue'
|
||||
const source = SOURCES.find((s) => s.file === file)?.code ?? ''
|
||||
assert.match(source, /isHttpUrl\(/, '锚点不在了,注入自证不作数')
|
||||
// 只把校验函数改名,出口形状与个数都不动:判据必须因此翻红
|
||||
const stripped = source.replace(/\bisHttpUrl\(/g, 'uncheckedHas(').replace(/\bsafeHttpUrl\(/g, 'rawValueOf(')
|
||||
assert.notEqual(stripped, source, '注入没生效,这条自证是假的')
|
||||
const before = scanUrlOutlets(source, file)
|
||||
const after = scanUrlOutlets(stripped, file)
|
||||
assert.equal(after.outlets.length, before.outlets.length, '摘掉校验把出口也弄丢了,分母在放水')
|
||||
assert.deepEqual(before.unguarded, [], '已校验的写法被判成了违例(口径过严)')
|
||||
assert.ok(after.unguarded.length >= 2, `摘掉校验后未校验出口只有 ${after.unguarded.length} 处(应 ≥2),这条尺子是恒绿的`)
|
||||
// 顶层(无宿主函数)的跳转也必须被抓到
|
||||
const topLevel = scanUrlOutlets('window.location.href = serverFileUrl\n', '<内存样本>')
|
||||
assert.deepEqual(topLevel.unguarded.map((o) => o.kind), ['location.href='], '模块顶层的跳转出口漏判')
|
||||
})
|
||||
|
||||
test('桥与降级路径都收口:open_external_url 那条也要先判', () => {
|
||||
const source = readSource('src/pages/amazon/AmazonConsolePage.vue', ROOT)
|
||||
const report = scanUrlOutlets(source, 'src/pages/amazon/AmazonConsolePage.vue')
|
||||
assert.ok(report.outlets.length >= 1, 'AmazonConsolePage 的教程下载出口没进分母')
|
||||
assert.deepEqual(report.unguarded, [], '教程地址(服务端 /api/tutorial/latest 透传)没先过白名单')
|
||||
assert.match(source, /api\.open_external_url\(url\)/, '桥侧用的还是未校验的原值')
|
||||
})
|
||||
Reference in New Issue
Block a user