Repository navigation
feat(markdown): render svg fences as inline SVG (fixes #421) #455
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
kahme247
merged 2 commits into
ompweb-dev:main
from
anhnt256:feat/render-svg-fences-inline
Nov 22, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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,<script>alert(4)</script>"><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,<svg><script>alert(1)</script></svg>" /> | ||
| <image href="data:image/svg+xml,<svg><script>alert(2)</script></svg>" /> | ||
| <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</); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) { | ||
| 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 }} | ||
| /> | ||
| ); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
hrefandxlink:hrefagainstUNSAFE_HREF, butstyleattributes get a free pass. An element withstyle="background: url('javascript:alert(1)')"or the classic IEexpression(alert(1))would survive. Modern browsers mostly neuter CSS-based XSS, but "mostly" is a scary word in security.🩹 The Fix:
📏 Severity: suggestion