Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 42 additions & 8 deletions src/web/mdrender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) ? `<img class="md-img" src="${url}" alt="${label}" />` : "");
} else {
parts.push(/^(https?:\/\/|\/)/i.test(url) ? `<a href="${url}" target="_blank" rel="noopener noreferrer">${label}</a>` : 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) =>
Expand All @@ -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 `<img class="md-img" src="${url}" alt="${alt}" />`;
return "";
});
out = inlineLinks(out, true);
out = out.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
out = out.replace(/(^|[^*])\*([^*\n]+)\*/g, "$1<em>$2</em>");
// [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 `<a href="${url}" target="_blank" rel="noopener noreferrer">${text}</a>`;
return text;
});
out = inlineLinks(out, false);
return out;
}

Expand Down
51 changes: 51 additions & 0 deletions tests/mdrender-link-scaling.test.ts
Original file line number Diff line number Diff line change
@@ -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), `<p>${source}</p>`);
});
}

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<string, unknown> };
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<typeof makeMdRender>;
for (const [, source] of malformed) assert.equal(boundedRender(detached.render, source), `<p>${source}</p>`);
});

const compatibility = [
["[outer [inner](https://example.test)", '<p><a href="https://example.test" target="_blank" rel="noopener noreferrer">outer [inner</a></p>'],
["[bad](not [good](https://example.test))", '<p>[bad](not <a href="https://example.test" target="_blank" rel="noopener noreferrer">good</a>)</p>'],
["[bad]([good with spaces](https://example.test))", '<p>[bad](<a href="https://example.test" target="_blank" rel="noopener noreferrer">good with spaces</a>)</p>'],
["![outer ![inner](https://example.test/a.png)", '<p><img class="md-img" src="https://example.test/a.png" alt="outer ![inner" /></p>'],
["[](/no-label) ![](https://example.test/empty.png)", '<p>[](/no-label) <img class="md-img" src="https://example.test/empty.png" alt="" /></p>'],
["[x](https://example.test/[path](tail))", '<p><a href="https://example.test/[path](tail" target="_blank" rel="noopener noreferrer">x</a>)</p>'],
["[x](bad url) [ok](/safe)", '<p>[x](bad url) <a href="/safe" target="_blank" rel="noopener noreferrer">ok</a></p>'],
["[x](javascript:alert(1))", "<p>x)</p>"],
] as const;

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