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
4 changes: 4 additions & 0 deletions components/MarkdownCode.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { HTMLAttributes } from "react";
import { MermaidBlock, CodeBlock } from "./MermaidBlock";
import { SvgBlock } from "./SvgBlock";

/** Build the `code` renderer shared by MarkdownBody and FileViewer's
* ReactMarkdown configs (the two previously inlined near-identical copies).
Expand All @@ -23,6 +24,9 @@ export function markdownCodeRenderer(options: {
if (lang === "mermaid") {
return <MermaidBlock code={raw.replace(/\n$/, "")} isStreaming={options.isStreaming} defaultPreview={options.defaultPreview} />;
}
if (lang === "svg") {
return <SvgBlock code={raw.replace(/\n$/, "")} isStreaming={options.isStreaming} />;
}
return <CodeBlock code={raw.replace(/\n$/, "")} lang={lang} isStreaming={options.isStreaming} />;
}
return (
Expand Down
114 changes: 114 additions & 0 deletions components/SvgBlock.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import "../tests/setup-dom.mjs";
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";

// SvgBlock parses at render time with the browser globals; jsdom provides
// them on window, so expose them before importing the component.
globalThis.DOMParser = window.DOMParser;
globalThis.XMLSerializer = window.XMLSerializer;

const { SvgBlock, parseSvgMarkup } = await import("./SvgBlock.tsx");
const { markdownCodeRenderer } = await import("./MarkdownCode.tsx");

const validSvg = `<svg viewBox="0 0 420 90" font-family="system-ui, sans-serif">
<text x="0" y="18" font-size="13" fill="var(--muted)">svg block renders inline</text>
<rect x="0" y="30" width="400" height="46" rx="6" fill="none" stroke="var(--border)"/>
</svg>`;

test("parseSvgMarkup keeps a valid svg and normalizes its root", () => {
const markup = parseSvgMarkup(validSvg);
assert.match(markup, /<svg[^>]*viewBox="0 0 420 90"/);
assert.match(markup, /max-width:100%;height:auto/);
assert.match(markup, /fill="currentColor"/);
assert.match(markup, /xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
// Theme-variable fills survive sanitization.
assert.match(markup, /fill="var\(--muted\)"/);
});

test("parseSvgMarkup strips script, event handlers, foreignObject, style and javascript hrefs", () => {
const markup = parseSvgMarkup(`<svg viewBox="0 0 10 10" onload="alert(1)" xmlns:xlink="http://www.w3.org/1999/xlink">
<script>alert(2)</script>
<style>rect { fill: red; }</style>
<foreignObject><div>evil</div></foreignObject>
<a href="javascript:alert(3)"><text>x</text></a>
<a xlink:href="data:text/html,&lt;script&gt;alert(4)&lt;/script&gt;"><text>y</text></a>
<rect width="10" height="10" />
</svg>`);
assert.doesNotMatch(markup, /<script/);
assert.doesNotMatch(markup, /onload/);
assert.doesNotMatch(markup, /foreignObject/);
assert.doesNotMatch(markup, /<style/);
assert.doesNotMatch(markup, /javascript:/);
assert.doesNotMatch(markup, /data:text\/html/);
assert.match(markup, /<rect/);
});

test("parseSvgMarkup blocks data: svg hrefs, vbscript: hrefs and dangerous style urls", () => {
const markup = parseSvgMarkup(`<svg viewBox="0 0 10 10" xmlns:xlink="http://www.w3.org/1999/xlink">
<use xlink:href="data:image/svg+xml,&lt;svg&gt;&lt;script&gt;alert(1)&lt;/script&gt;&lt;/svg&gt;" />
<image href="data:image/svg+xml,&lt;svg&gt;&lt;script&gt;alert(2)&lt;/script&gt;&lt;/svg&gt;" />
<a href="vbscript:alert(3)"><text>x</text></a>
<rect width="10" height="10" style="background: url('javascript:alert(4)')" />
<circle r="5" style="width: expression(alert(5))" />
<ellipse rx="5" ry="5" style="fill: red" />
</svg>`);
assert.doesNotMatch(markup, /data:image\/svg\+xml/);
assert.doesNotMatch(markup, /vbscript:/);
assert.doesNotMatch(markup, /javascript:/);
assert.doesNotMatch(markup, /expression\(/);
// The elements survive with the dangerous attributes removed…
assert.match(markup, /<use/);
assert.match(markup, /<image/);
assert.match(markup, /<rect/);
assert.match(markup, /<circle/);
// …while a benign style attribute is kept.
assert.match(markup, /fill: red/);
});

test("parseSvgMarkup keeps an explicit root fill instead of forcing currentColor", () => {
const markup = parseSvgMarkup(`<svg viewBox="0 0 10 10" fill="red"><rect width="10" height="10" /></svg>`);
assert.match(markup, /fill="red"/);
assert.doesNotMatch(markup, /fill="currentColor"/);
});

test("parseSvgMarkup returns null for malformed markup and non-svg roots", () => {
assert.equal(parseSvgMarkup(`<svg viewBox="0 0 10 10"><rect`), null);
assert.equal(parseSvgMarkup(`<html><body>not svg</body></html>`), null);
assert.equal(parseSvgMarkup(``), null);
});

test("SvgBlock renders a valid fence inline with theme aliases on the wrapper", () => {
const html = renderToStaticMarkup(React.createElement(SvgBlock, { code: validSvg }));
assert.match(html, /markdown-svg-block/);
assert.match(html, /<svg[^>]*viewBox="0 0 420 90"/);
assert.match(html, /--muted:var\(--text-muted\)/);
assert.doesNotMatch(html, /markdown-code-block/);
});

test("SvgBlock falls back to the code block for malformed svg", () => {
const html = renderToStaticMarkup(React.createElement(SvgBlock, { code: `<svg viewBox="0 0 10 10"><rect` }));
assert.match(html, /markdown-code-block/);
assert.match(html, />svg</);
});

test("markdown code renderer dispatches svg to SvgBlock and leaves mermaid and json alone", () => {
const Code = markdownCodeRenderer({});
const svgHtml = renderToStaticMarkup(
React.createElement(Code, { className: "language-svg", children: validSvg }),
);
assert.match(svgHtml, /markdown-svg-block/);

const mermaidHtml = renderToStaticMarkup(
React.createElement(Code, { className: "language-mermaid", children: "graph TD\n A-->B" }),
);
assert.match(mermaidHtml, />(Preview|mermaidBlock\.preview)</);
assert.doesNotMatch(mermaidHtml, /markdown-svg-block/);

const jsonHtml = renderToStaticMarkup(
React.createElement(Code, { className: "language-json", children: `{\n "a": 1\n}` }),
);
assert.match(jsonHtml, /markdown-code-block/);
assert.match(jsonHtml, />json</);
});
112 changes: 112 additions & 0 deletions components/SvgBlock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"use client";

import { useMemo, type CSSProperties } from "react";
import { CodeBlock } from "./MermaidBlock";

interface SvgBlockProps {
code: string;
isStreaming?: boolean;
}

// omp/ompweb theme variable aliases. The TUI-facing svg conventions use
// --fg / --muted / --surface / --c1..--c6, which do not exist in the web
// theme; without aliases those fills resolve to nothing and the drawing
// turns black on a dark background. --c1..--c6 map to status colours as an
// approximation (#421).
const SVG_THEME_ALIASES: Record<string, string> = {
"--fg": "var(--text)",
"--muted": "var(--text-muted)",
"--surface": "var(--bg-panel)",
"--c1": "var(--accent)",
"--c2": "var(--status-success)",
"--c3": "var(--status-warning)",
"--c4": "var(--status-error)",
"--c5": "var(--status-modified)",
"--c6": "var(--status-renamed)",
};

// script and foreignObject can run code or embed foreign content; style is
// stripped too — inline SVG CSS applies to the whole document, so a <style>
// block inside a fence could restyle the app. The reference implementation
// in #421 leaves <style> in place; this PR removes it.
const UNSAFE_TAGS = ["script", "foreignObject", "style"];
// Block every data: URI, not just data:text/html: a <use> or <image> can
// reference data:image/svg+xml,<svg><script>…</script></svg> and the browser
// parses and executes the nested SVG's scripts. vbscript: is dead in modern
// browsers but still honored by some embedded WebViews — block it too.
const UNSAFE_HREF = /^\s*(javascript|vbscript|data:)/i;
const UNSAFE_ATTRIBUTE = /^on/i;
// A style attribute can smuggle code through url(javascript:…) or the legacy
// IE expression(…); match inside url(…) rather than at the value start,
// since the URL sits after a property name (background: url(…)).
const UNSAFE_STYLE = /expression\s*\(|url\s*\(\s*['"]?\s*(javascript|vbscript|data):/i;

function sanitizeSvg(root: Element): void {
for (const tag of UNSAFE_TAGS) {
for (const el of root.querySelectorAll(tag)) el.remove();
}
// querySelectorAll("*") covers descendants only — the root itself can also
// carry an on* handler or a javascript: href, so sweep it too.
for (const el of [root, ...root.querySelectorAll("*")]) {
for (const attr of [...el.attributes]) {
if (UNSAFE_ATTRIBUTE.test(attr.name)) {
el.removeAttribute(attr.name);
continue;
}
if (/^(href|xlink:href)$/i.test(attr.name) && UNSAFE_HREF.test(attr.value)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 The Roast: The attribute sweep checks href and xlink:href against UNSAFE_HREF, but style attributes get a free pass. An element with style="background: url('javascript:alert(1)')" or the classic IE expression(alert(1)) would survive. Modern browsers mostly neuter CSS-based XSS, but "mostly" is a scary word in security.

🩹 The Fix:

Suggested change
if (/^(href|xlink:href)$/i.test(attr.name) && UNSAFE_HREF.test(attr.value)) {
if (/^(href|xlink:href|style)$/i.test(attr.name) && (UNSAFE_HREF.test(attr.value) || /expression\s*\(/i.test(attr.value))) {

📏 Severity: suggestion

el.removeAttribute(attr.name);
}
if (/^style$/i.test(attr.name) && UNSAFE_STYLE.test(attr.value)) {
el.removeAttribute(attr.name);
}
}
}
}

/**
* Parse + sanitize an SVG fence into embeddable markup, or null when the
* source is not a well-formed `<svg>` document (malformed input, or a fence
* still streaming half-written markup). Pure except for DOMParser /
* XMLSerializer, so tests drive it directly.
*/
export function parseSvgMarkup(code: string): string | null {
let doc: Document;
try {
doc = new DOMParser().parseFromString(code, "image/svg+xml");
} catch {
return null;
}
if (doc.querySelector("parsererror")) return null;
const root = doc.documentElement;
if (!root || root.nodeName.toLowerCase() !== "svg") return null;
sanitizeSvg(root);
const style = root.getAttribute("style");
root.setAttribute("style", `${style ? `${style};` : ""}max-width:100%;height:auto`);
if (!root.hasAttribute("fill")) root.setAttribute("fill", "currentColor");
if (!root.hasAttribute("xmlns")) root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
return new XMLSerializer().serializeToString(root);
}

export function SvgBlock({ code, isStreaming }: SvgBlockProps) {
const markup = useMemo(() => parseSvgMarkup(code), [code]);

// Streaming generates half-written markup; fall back to the code block until
// the fence closes.
if (!markup) {
return <CodeBlock code={code} lang="svg" isStreaming={isStreaming} />;
}
return (
<div
className="markdown-svg-block"
style={{
...SVG_THEME_ALIASES,
color: "var(--text)",
display: "flex",
justifyContent: "center",
overflow: "auto",
padding: "4px 0",
} as CSSProperties}
dangerouslySetInnerHTML={{ __html: markup }}
/>
);
}