From 4c40406d366af1583a3ba2327366b7a62d765537 Mon Sep 17 00:00:00 2001 From: vastsa Date: Tue, 27 Oct 2026 15:41:34 +0800 Subject: [PATCH] fix: escape failed Markdown previews and restore lint checks Escape untrusted text on renderer failures and add regression coverage. Keep brace-expansion overrides compatible with minimatch major versions and clear existing lint errors. Refs vastsa/FileCodeBox#557 --- README.md | 9 +++ package-lock.json | 33 +++++++- package.json | 7 +- pnpm-lock.yaml | 33 ++++++-- src/composables/useAdminSession.ts | 4 +- src/utils/content-preview.ts | 11 ++- src/views/manage/McpView.vue | 1 - tests/content-preview.test.mjs | 123 +++++++++++++++++++++++++++++ 8 files changed, 204 insertions(+), 17 deletions(-) create mode 100644 tests/content-preview.test.mjs diff --git a/README.md b/README.md index 8b6a280..527d53f 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,15 @@ repository's default branch. Every push is also checked with a production build. pnpm build ``` +### Run Regression Tests + +```sh +pnpm test +``` + +Uses Node's built-in test runner with isolated VM modules to cover Markdown preview +sanitization boundaries and safe fallback behavior (including issue #557). + ### Lint with [ESLint](https://eslint.org/) ```sh diff --git a/package-lock.json b/package-lock.json index 44aa851..7827b2f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2498,16 +2498,16 @@ "license": "ISC" }, "node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "version": "5.0.12", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" } }, "node_modules/braces": { @@ -2703,6 +2703,13 @@ "node": ">= 6" } }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://nexus3.bilibili.co/repository/npm-public/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -4072,6 +4079,24 @@ "node": "*" } }, + "node_modules/minimatch/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/minimatch/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://nexus3.bilibili.co/repository/npm-public/minipass/-/minipass-7.1.3.tgz", diff --git a/package.json b/package.json index 815eae7..5488c83 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "build-only": "vite build", "type-check": "vue-tsc --build --force", "check:architecture": "node scripts/check-architecture.mjs", + "test": "node --experimental-vm-modules --test tests/*.test.mjs", "lint": "eslint . --fix", "format": "prettier --write src/" }, @@ -58,7 +59,8 @@ }, "overrides": { "@babel/core": "7.29.7", - "brace-expansion": "5.0.6", + "brace-expansion@1": "1.1.21", + "brace-expansion@5": "5.0.12", "esbuild": "0.28.1", "form-data": "4.0.6", "js-yaml": "4.2.0", @@ -68,7 +70,8 @@ "pnpm": { "overrides": { "@babel/core": "7.29.7", - "brace-expansion": "5.0.6", + "brace-expansion@1": "1.1.21", + "brace-expansion@5": "5.0.12", "esbuild": "0.28.1", "form-data": "4.0.6", "js-yaml": "4.2.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d862766..209c723 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,7 +6,8 @@ settings: overrides: '@babel/core': 7.29.7 - brace-expansion: 5.0.6 + brace-expansion@1: 1.1.21 + brace-expansion@5: 5.0.12 esbuild: 0.28.1 form-data: 4.0.6 js-yaml: 4.2.0 @@ -914,6 +915,9 @@ packages: axios@1.18.0: resolution: {integrity: sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==} + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -933,9 +937,12 @@ packages: boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} - brace-expansion@5.0.6: - resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} - engines: {node: 18 || 20 || >=22} + brace-expansion@1.1.21: + resolution: {integrity: sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==} + + brace-expansion@5.0.12: + resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} + engines: {node: 20 || >=22} braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} @@ -987,6 +994,9 @@ packages: resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} engines: {node: '>= 6'} + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} @@ -2726,6 +2736,8 @@ snapshots: - debug - supports-color + balanced-match@1.0.2: {} + balanced-match@4.0.4: {} baseline-browser-mapping@2.11.21: {} @@ -2736,7 +2748,12 @@ snapshots: boolbase@1.0.0: {} - brace-expansion@5.0.6: + brace-expansion@1.1.21: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + + brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -2794,6 +2811,8 @@ snapshots: commander@4.1.1: {} + concat-map@0.0.1: {} + convert-source-map@2.0.0: {} copy-anything@4.0.5: @@ -3243,11 +3262,11 @@ snapshots: minimatch@10.2.5: dependencies: - brace-expansion: 5.0.6 + brace-expansion: 5.0.12 minimatch@3.1.5: dependencies: - brace-expansion: 5.0.6 + brace-expansion: 1.1.21 minipass@7.1.3: {} diff --git a/src/composables/useAdminSession.ts b/src/composables/useAdminSession.ts index b70069b..992266e 100644 --- a/src/composables/useAdminSession.ts +++ b/src/composables/useAdminSession.ts @@ -13,7 +13,9 @@ export function useAdminSession() { adminStore.login(response.detail) return true } - } catch {} + } catch { + // Verification failures fall through to clear the local session below. + } adminStore.logout() return false diff --git a/src/utils/content-preview.ts b/src/utils/content-preview.ts index 6f0bb9a..c42dfeb 100644 --- a/src/utils/content-preview.ts +++ b/src/utils/content-preview.ts @@ -22,8 +22,8 @@ const MARKDOWN_ALLOWED_TAGS = [ const MARKDOWN_ALLOWED_ATTR = ['href', 'src', 'alt', 'title', 'class'] -type MarkedRenderer = typeof import('marked')['marked'] -type DOMPurifyModule = typeof import('dompurify')['default'] +type MarkedRenderer = (typeof import('marked'))['marked'] +type DOMPurifyModule = (typeof import('dompurify'))['default'] let markdownRendererLoader: Promise<{ marked: MarkedRenderer @@ -52,6 +52,13 @@ export async function renderMarkdownPreview(content: string): Promise { }) } catch (error) { console.error('Markdown 渲染失败:', error) + // The result is consumed by v-html, even when parsing or loading dependencies fails. + // Escape without DOMPurify so a failed renderer can never expose raw HTML. return content + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') } } diff --git a/src/views/manage/McpView.vue b/src/views/manage/McpView.vue index d9d4882..c382955 100644 --- a/src/views/manage/McpView.vue +++ b/src/views/manage/McpView.vue @@ -101,7 +101,6 @@ import { useInjectedDarkMode } from '@/composables' import { CopyIcon, FileTextIcon, - NetworkIcon, RefreshCwIcon, SparklesIcon, UploadIcon diff --git a/tests/content-preview.test.mjs b/tests/content-preview.test.mjs new file mode 100644 index 0000000..efa399d --- /dev/null +++ b/tests/content-preview.test.mjs @@ -0,0 +1,123 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test, mock } from 'node:test' +import { URL } from 'node:url' +import { createContext, SourceTextModule, SyntheticModule } from 'node:vm' +import { marked } from 'marked' +import ts from 'typescript' + +const source = readFileSync(new URL('../src/utils/content-preview.ts', import.meta.url), 'utf8') +const { outputText } = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } +}) + +// Isolate the cached loader and inject failures without changing the production API. +async function createRenderer({ parse = marked, sanitize = mock.fn(), failedImport } = {}) { + const logError = mock.fn() + const context = createContext({ console: { error: logError } }) + const module = new SourceTextModule(outputText, { + context, + importModuleDynamically: async (specifier) => { + if (specifier === failedImport) throw new Error('Failed to load renderer chunk') + assert.ok(['marked', 'dompurify'].includes(specifier)) + const exports = specifier === 'marked' ? { marked: parse } : { default: { sanitize } } + const dependency = new SyntheticModule( + Object.keys(exports), + function () { + for (const [name, value] of Object.entries(exports)) this.setExport(name, value) + }, + { context } + ) + await dependency.link(() => assert.fail('Unexpected static import')) + await dependency.evaluate() + return dependency + } + }) + await module.link(() => assert.fail('Unexpected static import')) + await module.evaluate() + return { render: module.namespace.renderMarkdownPreview, logError } +} + +const unsafeContent = ' & \'text\'\n' +const escapedContent = + '<img src=x onerror="alert(1)"> & 'text'\n<script>alert(2)</script>' + +function assertSafeFallback(actual, expected = escapedContent) { + assert.equal(actual, expected) + assert.doesNotMatch(actual, /[<>]/) +} + +test('issue #557: deeply nested blockquotes fall back to escaped text', async () => { + const content = '>'.repeat(5000) + '\n\n' + unsafeContent + const sanitize = mock.fn() + const { render, logError } = await createRenderer({ sanitize }) + + assertSafeFallback(await render(content), '>'.repeat(5000) + '\n\n' + escapedContent) + assert.equal(sanitize.mock.callCount(), 0) + assert.equal(logError.mock.callCount(), 1) + assert.equal(logError.mock.calls[0].arguments[1].name, 'RangeError') +}) + +for (const asyncFailure of [false, true]) { + test(`escapes text when marked ${asyncFailure ? 'rejects' : 'throws'}`, async () => { + const error = new Error('Parse failed') + const parse = asyncFailure + ? () => Promise.reject(error) + : () => { + throw error + } + const sanitize = mock.fn() + const { render } = await createRenderer({ parse, sanitize }) + + assertSafeFallback(await render(unsafeContent)) + assert.equal(sanitize.mock.callCount(), 0) + }) +} + +for (const failedImport of ['marked', 'dompurify']) { + test(`escapes text when the ${failedImport} chunk fails to load`, async () => { + const { render } = await createRenderer({ failedImport }) + + assertSafeFallback(await render(unsafeContent)) + // A cached rejected loader must also remain safe on subsequent previews. + assertSafeFallback(await render(unsafeContent)) + }) +} + +test('escapes text when sanitization throws', async () => { + const { render } = await createRenderer({ + sanitize: () => { + throw new Error('Sanitization failed') + } + }) + + assertSafeFallback(await render(unsafeContent)) +}) + +test('fallback preserves empty text, Unicode, whitespace and literal entities', async () => { + const { render } = await createRenderer({ failedImport: 'dompurify' }) + + assert.equal(await render(''), '') + assert.equal(await render('中文\n\t text'), '中文\n\t text') + assertSafeFallback( + await render('<img> & < <>&"\''), + '&lt;img&gt; &amp; &#60; <>&"'' + ) +}) + +test('successful Markdown rendering returns only the sanitizer result', async () => { + const safeHtml = '

Title

\n

bold

\n' + const sanitize = mock.fn(() => safeHtml) + const { render, logError } = await createRenderer({ sanitize }) + const content = '# Title\n\n**bold**\n\n' + + assert.equal(await render(content), safeHtml) + assert.equal(logError.mock.callCount(), 0) + assert.equal(sanitize.mock.callCount(), 1) + const [rawHtml, options] = sanitize.mock.calls[0].arguments + assert.equal(rawHtml, await marked(content)) + assert.ok(options.ALLOWED_TAGS.includes('h1')) + assert.ok(!options.ALLOWED_TAGS.includes('script')) + assert.ok(!options.ALLOWED_ATTR.includes('onerror')) + assert.ok(!options.ALLOWED_URI_REGEXP.test('javascript:alert(1)')) +})