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
8 changes: 7 additions & 1 deletion frontend/src/components/MarkdownRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ function escapeAttribute(str: string): string {
return escapeHtml(str).replace(/'/g, ''');
}

function sanitizeCodeLanguage(language: string): string {
// A fence info string is untrusted Markdown input. Only retain characters
// valid for the single syntax-highlighting class we generate from it.
return /^[A-Za-z0-9][A-Za-z0-9_+.#-]{0,63}$/.test(language) ? language : '';
}

function prepareUrl(url: string, kind: 'link' | 'image' = 'link'): string | null {
let finalUrl = url.trim().replace(/^<|>$/g, '');
const lower = finalUrl.toLowerCase();
Expand Down Expand Up @@ -163,7 +169,7 @@ function markdownToHtml(md: string, mentionNames: readonly string[] = []): strin
if (!inCodeBlock) {
flushList(); flushBlockquote(); flushTable();
inCodeBlock = true;
codeLang = line.slice(3).trim();
codeLang = sanitizeCodeLanguage(line.slice(3).trim());
codeLines = [];
} else {
const codeContent = escapeHtml(codeLines.join('\n'));
Expand Down
15 changes: 15 additions & 0 deletions frontend/tests/markdownRendererSecurity.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';

const renderer = readFileSync(
new URL('../src/components/MarkdownRenderer.tsx', import.meta.url),
'utf8',
);

test('code fence language is constrained before being interpolated into HTML', () => {
assert.match(renderer, /function sanitizeCodeLanguage\(language: string\): string/);
assert.match(renderer, /return \/\^\[A-Za-z0-9\]/);
assert.match(renderer, /codeLang = sanitizeCodeLanguage\(line\.slice\(3\)\.trim\(\)\)/);
assert.match(renderer, /class="language-\$\{codeLang\}"/);
});