import { test } from 'node:test' import assert from 'node:assert/strict' import { readFileSync, readdirSync, statSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { resolve, dirname, join, relative } from 'node:path' import { safeHttpUrl } from '../src/shared/utils/safe-url.ts' import { createRowId } from '../src/shared/utils/row-id.ts' const here = dirname(fileURLToPath(import.meta.url)) const srcRoot = resolve(here, '../src') /** 静态常量出口(构建期写死,不经服务端/客户端透传) */ const STATIC_HREF_ALLOWLIST = new Set(['ALIPRICE_URL']) function listVueFiles(dir: string, acc: string[] = []): string[] { for (const entry of readdirSync(dir)) { const full = join(dir, entry) if (statSync(full).isDirectory()) listVueFiles(full, acc) else if (entry.endsWith('.vue')) acc.push(full) } return acc } /** 找出「函数体里调过 safeHttpUrl」的本地包装函数名(如 sourceFileHref)。 */ function vettedWrapperNames(sources: string[]): Set { const names = new Set() for (const source of sources) { // 顶层函数以行首 } 收尾(与本仓 vue 文件书写一致),按函数体取,避免把邻近函数的调用算进来 for (const match of source.matchAll(/function\s+(\w+)\s*\([^)]*\)\s*\{([\s\S]*?)\n\}/g)) { if (match[2].includes('safeHttpUrl(')) names.add(match[1]) } } return names } type HrefBinding = { file: string; line: string } function collectHrefBindings(sources: Record): HrefBinding[] { const found: HrefBinding[] = [] for (const [file, content] of Object.entries(sources)) { for (const line of content.split(/\r?\n/)) { if (line.includes(':href="')) found.push({ file, line }) } } return found } function unvettedBindings(bindings: HrefBinding[], wrappers: Set): HrefBinding[] { return bindings.filter(({ line }) => { const expr = (line.match(/:href="([^"]*)"/)?.[1] ?? '').trim() if (expr.includes('safeHttpUrl(')) return false if (/^[A-Z0-9_]+$/.test(expr) && STATIC_HREF_ALLOWLIST.has(expr)) return false const callName = expr.match(/^(\w+)\(/)?.[1] if (callName && wrappers.has(callName)) return false return true }) } test('test_safe_http_url_allows_only_http_and_https', () => { assert.equal(safeHttpUrl('https://cdn.example.com/a.mp4'), 'https://cdn.example.com/a.mp4') assert.equal(safeHttpUrl('http://127.0.0.1:5173/x'), 'http://127.0.0.1:5173/x') // 相对路径按当前页面补全后判定协议,保持原样返回(交给浏览器解析) assert.equal(safeHttpUrl('/newApi/api/files/x'), '/newApi/api/files/x') }) test('test_safe_http_url_blocks_pseudo_protocols', () => { for (const bad of [ 'javascript:alert(1)', 'JavaScript:alert(1)', ' javascript:alert(1) ', 'java\tscript:alert(1)', 'data:text/html,', 'vbscript:msgbox(1)', 'file:///C:/Windows/win.ini', 'http://[bad', ]) { assert.equal(safeHttpUrl(bad), '#', `${bad} 必须被拦成 #`) } }) test('test_safe_http_url_handles_empty_input', () => { for (const empty of [undefined, null, '', ' ']) { assert.equal(safeHttpUrl(empty as string | null | undefined), '#') } }) test('test_safe_http_url_uses_page_origin_when_window_exists', () => { const previous = (globalThis as Record).window ;(globalThis as Record).window = { location: { href: 'https://app.example.com/#group-front' } } try { assert.equal(safeHttpUrl('/api/result.zip'), '/api/result.zip') // 带 origin 的伪协议不会因为「相对路径」被放行 assert.equal(safeHttpUrl('javascript:alert(1)'), '#') } finally { if (previous === undefined) delete (globalThis as Record).window else (globalThis as Record).window = previous } }) test('test_create_row_id_is_unique_per_call', () => { const ids = new Set() for (let i = 0; i < 2000; i += 1) ids.add(createRowId('asset')) assert.equal(ids.size, 2000, '同一页会话内行 id 不能重复') for (const id of ids) assert.match(id, /^asset:/) }) test('test_create_row_id_falls_back_without_random_uuid', () => { const cryptoGlobal = (globalThis as { crypto?: Crypto }).crypto if (!cryptoGlobal) return // 没有 crypto 全局时走的就是降级路径 const restore = Object.getOwnPropertyDescriptor(cryptoGlobal, 'randomUUID') try { // 1) randomUUID 缺失(http 非安全上下文下 WebView 不提供) Object.defineProperty(cryptoGlobal, 'randomUUID', { value: undefined, configurable: true, writable: true }) const missing = createRowId('row') assert.match(missing, /^row:[0-9a-z]+-[0-9a-z]+-[0-9a-z]+$/, '降级实现要带前缀且分三段') // 2) 存在但会抛(部分内核在非安全上下文直接抛错) Object.defineProperty(cryptoGlobal, 'randomUUID', { value: () => { throw new Error('not a secure context') }, configurable: true, writable: true, }) const thrown = createRowId('row') assert.match(thrown, /^row:/, '抛错也必须产出可用 id') assert.notEqual(thrown, missing) } finally { if (restore) Object.defineProperty(cryptoGlobal, 'randomUUID', restore) else delete (cryptoGlobal as unknown as Record).randomUUID } }) test('test_every_dynamic_href_outlet_goes_through_safe_http_url', () => { const files = listVueFiles(srcRoot) const sources: Record = {} for (const file of files) { sources[relative(srcRoot, file).replace(/\\/g, '/')] = readFileSync(file, 'utf-8') } const bindings = collectHrefBindings(sources) assert.ok(bindings.length >= 4, `扫描到的 :href 出口只有 ${bindings.length} 处,检测面失效`) const violations = unvettedBindings(bindings, vettedWrapperNames(Object.values(sources))) assert.deepEqual(violations, [], '存在未经协议过滤的动态 :href') }) test('test_href_outlet_detector_actually_flags_raw_binding', () => { const wrappers = vettedWrapperNames(['function sourceFileHref(item) {\n return safeHttpUrl(item?.url)\n}']) assert.deepEqual([...wrappers], ['sourceFileHref'], '包装函数识别失效') const synthetic: HrefBinding[] = [ { file: 'a.vue', line: '' }, { file: 'b.vue', line: '' }, { file: 'c.vue', line: '' }, { file: 'd.vue', line: '' }, ] const violations = unvettedBindings(synthetic, wrappers) assert.deepEqual(violations.map((v) => v.file), ['d.vue'], '检测必须只漏放原始绑定') })