From 619b5299ccf32f9625b53617b9e0bfc3bb867402 Mon Sep 17 00:00:00 2001 From: Afloat Date: Fri, 20 Nov 2026 16:51:47 +0800 Subject: [PATCH] fix(web): avoid repeated scans of malformed Markdown links --- src/web/mdrender.ts | 50 +++++++++++++++++++++++----- tests/mdrender-link-scaling.test.ts | 51 +++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 8 deletions(-) create mode 100644 tests/mdrender-link-scaling.test.ts diff --git a/src/web/mdrender.ts b/src/web/mdrender.ts index d414cf5f23..5348899132 100644 --- a/src/web/mdrender.ts +++ b/src/web/mdrender.ts @@ -34,6 +34,46 @@ export function makeMdRender(): MdRenderApi { .replace(/"/g, """); } + function inlineLinks(s: string, image: boolean): string { + const marker = image ? "![" : "["; + const parts: string[] = []; + let copied = 0; + let search = 0; + let urlEnd = 0; + while (search < s.length) { + const start = s.indexOf(marker, search); + if (start < 0) break; + const labelStart = start + marker.length; + const labelEnd = s.indexOf("]", labelStart); + if (labelEnd < 0) break; + // Every opening marker before this first ']' has the same closing delimiter. + // Skip that whole label on failure instead of retrying all of its suffixes. + search = labelEnd + 1; + if (s[labelEnd + 1] !== "(" || (!image && labelEnd === labelStart)) continue; + const urlStart = labelEnd + 2; + search = urlStart; + // Reuse the next URL terminator when nested starts share one long invalid URL. + // Both cursors only move forward, even for "[x]([x](... invalid". + if (urlEnd < urlStart) { + urlEnd = urlStart; + while (urlEnd < s.length && s[urlEnd] !== ")" && !/\s/.test(s[urlEnd])) urlEnd += 1; + } + if (urlEnd === s.length) break; + if (urlEnd === urlStart || s[urlEnd] !== ")") continue; + const label = s.slice(labelStart, labelEnd); + const url = s.slice(urlStart, urlEnd); + parts.push(s.slice(copied, start)); + if (image) { + parts.push(/^(?:https?:\/\/|\/__bili\/blog-assets\/)/i.test(url) ? `${label}` : ""); + } else { + parts.push(/^(https?:\/\/|\/)/i.test(url) ? `${label}` : label); + } + copied = search = urlEnd + 1; + } + parts.push(s.slice(copied)); + return parts.join(""); + } + function inlineMd(s: string): string { let out = escape(s); out = out.replace(/`([^`]+)`/g, (_m, code: string) => @@ -43,18 +83,12 @@ export function makeMdRender(): MdRenderApi { // panel's own bundled-asset route (/__bili/blog-assets/*, see // web/blogfeed.ts). Quotes are already escaped by escape, so attribute // injection is impossible. - out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, alt: string, url: string) => { - if (/^(?:https?:\/\/|\/__bili\/blog-assets\/)/i.test(url)) return `${alt}`; - return ""; - }); + out = inlineLinks(out, true); out = out.replace(/\*\*([^*]+)\*\*/g, "$1"); out = out.replace(/(^|[^*])\*([^*\n]+)\*/g, "$1$2"); // [text](url) — only http/https/relative URLs survive; anything else // degrades to plain bracketed text (no javascript: vectors). - out = out.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_m, text: string, url: string) => { - if (/^(https?:\/\/|\/)/i.test(url)) return `${text}`; - return text; - }); + out = inlineLinks(out, false); return out; } diff --git a/tests/mdrender-link-scaling.test.ts b/tests/mdrender-link-scaling.test.ts new file mode 100644 index 0000000000..03b1837845 --- /dev/null +++ b/tests/mdrender-link-scaling.test.ts @@ -0,0 +1,51 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { runInNewContext } from "node:vm"; +import { build } from "esbuild"; +import { markdownToHtml } from "../src/web/markdown.ts"; +import { makeMdRender } from "../src/web/mdrender.ts"; + +const malformed = [ + ["unclosed link labels", "[".repeat(200_000)], + ["unclosed image labels", "![".repeat(100_000)], + ["nested link starts before an invalid URL", "[x](".repeat(30_000) + " invalid"], + ["nested URL starts sharing whitespace before a closing parenthesis", "[x](".repeat(200_000) + " )"], +] as const; + +function boundedRender(render: (source: string) => string, source: string): string { + // Interrupt the synchronous old regex path without hanging the test runner. These inputs + // need only a short scan; the budget leaves ample room for a loaded CI machine. + return runInNewContext("render(source)", { render, source }, { timeout: 2_000 }) as string; +} + +for (const [name, source] of malformed) { + test(`server Markdown finishes ${name} without rescanning every suffix`, () => { + assert.equal(boundedRender(markdownToHtml, source), `

${source}

`); + }); +} + +test("the minified detached browser renderer finishes the same malformed link inputs", async () => { + const built = await build({ entryPoints: ["src/web/mdrender.ts"], bundle: true, format: "cjs", minify: true, write: false, logLevel: "silent" }); + const module_ = { exports: {} as Record }; + new Function("module", "exports", built.outputFiles[0]!.text)(module_, module_.exports); + const bundled = module_.exports.makeMdRender as typeof makeMdRender; + const detached = new Function(`return (${bundled.toString()})();`)() as ReturnType; + for (const [, source] of malformed) assert.equal(boundedRender(detached.render, source), `

${source}

`); +}); + +const compatibility = [ + ["[outer [inner](https://example.test)", '

outer [inner

'], + ["[bad](not [good](https://example.test))", '

[bad](not good)

'], + ["[bad]([good with spaces](https://example.test))", '

[bad](good with spaces)

'], + ["![outer ![inner](https://example.test/a.png)", '

outer ![inner

'], + ["[](/no-label) ![](https://example.test/empty.png)", '

[](/no-label)

'], + ["[x](https://example.test/[path](tail))", '

x)

'], + ["[x](bad url) [ok](/safe)", '

[x](bad url) ok

'], + ["[x](javascript:alert(1))", "

x)

"], +] as const; + +for (const [source, expected] of compatibility) { + test(`link scanning preserves existing delimiter and URL rules: ${source}`, () => { + assert.equal(markdownToHtml(source), expected); + }); +}