Skip to content
Closed
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
4 changes: 3 additions & 1 deletion lib/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ const escapeHtml = (s: string): string =>
function safeUrl(raw: string): string | null {
const u = raw.trim();
if (/^(https?:|mailto:)/i.test(u)) return u;
if (/^\/(?!\/)/.test(u)) return u; // "/path" but not "//host"
// "/path", but not "//host" or "/\host": browsers normalise the backslash to a
// slash, so href="/\evil.com" resolves to "//evil.com" (an off-site redirect).
if (/^\/(?![/\\])/.test(u)) return u;
if (/^#/.test(u)) return u;
return null;
}
Expand Down
23 changes: 23 additions & 0 deletions tests/markdown.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import assert from "node:assert/strict";
import test from "node:test";

import { renderMarkdown } from "../lib/markdown.ts";

test("markdown blocks the backslash protocol-relative redirect", () => {
// href="/\evil.com" is normalised by browsers to "//evil.com" (off-site).
const link = renderMarkdown("[click](/\\evil.com)");
assert.ok(!/href="\/\\/.test(link), "backslash URL must not become a link href");
assert.ok(!link.includes("evil.com") || !link.includes("href"), "must not link off-site");
const img = renderMarkdown("![x](/\\evil.com)");
assert.ok(!/src="\/\\/.test(img), "backslash URL must not become an img src");
});

test("markdown still blocks // and still allows legit relative/absolute links", () => {
assert.ok(!renderMarkdown("[x](//evil.com)").includes("href"), "// stays blocked");
assert.ok(renderMarkdown("[x](/safe/path)").includes('href="/safe/path"'), "/path still works");
assert.ok(renderMarkdown("[x](https://good.com)").includes('href="https://good.com"'), "https still works");
});

test("markdown blocks javascript: URIs", () => {
assert.ok(!renderMarkdown("[x](javascript:alert(1))").toLowerCase().includes("javascript"));
});
Loading