3987b8d7fe
- 此前全树 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。
193 lines
11 KiB
TypeScript
193 lines
11 KiB
TypeScript
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 读取')
|
||
})
|