Skip to content

Commit 11f66bd

Browse files
committed
fix(web): harden mermaid render cache and sanitizing
1 parent c1d6e0e commit 11f66bd

1 file changed

Lines changed: 74 additions & 23 deletions

File tree

‎apps/web/src/components/chat/MermaidDiagram.tsx‎

Lines changed: 74 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@ import DOMPurify from "dompurify";
22
import type { Mermaid } from "mermaid";
33
import { use } from "react";
44

5-
import { fnv1a32 } from "../../lib/diffRendering";
6-
import { LRUCache } from "../../lib/lruCache";
7-
85
type MermaidRenderResult =
96
| { readonly status: "rendered"; readonly svg: string }
10-
| { readonly status: "error"; readonly message: string };
7+
| { readonly status: "error"; readonly message: string; readonly retryable: boolean };
118

129
let mermaidModulePromise: Promise<Mermaid> | null = null;
1310
let renderQueue: Promise<unknown> = Promise.resolve();
1411
let nextDiagramId = 0;
15-
const renderCache = new LRUCache<Promise<MermaidRenderResult>>(64, 8 * 1024 * 1024);
12+
const MAX_CACHED_RENDERS = 64;
13+
// Keyed by the full source so distinct diagrams never share an entry. Pending
14+
// renders are never evicted, because use() must get the same promise on retry.
15+
const renderCache = new Map<string, Promise<MermaidRenderResult>>();
16+
const settledRenders = new WeakSet<Promise<MermaidRenderResult>>();
1617

1718
// Mermaid is ~1MB, so it only loads once a diagram is actually shown.
1819
function loadMermaid(): Promise<Mermaid> {
@@ -26,27 +27,47 @@ function loadMermaid(): Promise<Mermaid> {
2627
}
2728

2829
// Diagrams can come from untrusted PR descriptions, so strip anything that can
29-
// navigate or run script on top of Mermaid's own strict sanitization.
30+
// navigate, run script, or fetch remote content on top of Mermaid's own strict
31+
// sanitization. HTML labels inside foreignObject stay, since authors can enable
32+
// them per diagram. Only local url(#id) references survive in CSS.
3033
function sanitizeMermaidSvg(svg: string): string {
3134
return DOMPurify.sanitize(svg, {
32-
FORBID_ATTR: ["href", "xlink:href", "onerror", "onload", "onclick"],
33-
FORBID_TAGS: ["foreignObject", "script"],
34-
USE_PROFILES: { svg: true, svgFilters: true },
35-
});
35+
ADD_TAGS: ["foreignObject"],
36+
HTML_INTEGRATION_POINTS: { foreignobject: true },
37+
FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
38+
FORBID_TAGS: ["a", "img", "image", "script"],
39+
USE_PROFILES: { svg: true, svgFilters: true, html: true },
40+
}).replace(/url\(\s*(?!['"]?#)[^)]*\)/gi, "none");
3641
}
3742

3843
async function renderMermaid(
3944
source: string,
4045
theme: "light" | "dark",
4146
): Promise<MermaidRenderResult> {
4247
const id = `mermaid-diagram-${nextDiagramId++}`;
48+
let mermaid: Mermaid;
49+
try {
50+
mermaid = await loadMermaid();
51+
} catch {
52+
return { status: "error", message: "Mermaid failed to load.", retryable: true };
53+
}
4354
try {
44-
const mermaid = await loadMermaid();
4555
// initialize() mutates global config, so renders run one at a time.
4656
mermaid.initialize({
4757
startOnLoad: false,
4858
securityLevel: "strict",
4959
suppressErrorRendering: true,
60+
// HTML labels are mounted while Mermaid lays them out, before sanitizing,
61+
// so diagram directives must not turn them back on.
62+
secure: [
63+
"secure",
64+
"securityLevel",
65+
"startOnLoad",
66+
"maxTextSize",
67+
"suppressErrorRendering",
68+
"maxEdges",
69+
"htmlLabels",
70+
],
5071
htmlLabels: false,
5172
flowchart: { htmlLabels: false },
5273
theme: theme === "dark" ? "dark" : "default",
@@ -58,35 +79,67 @@ async function renderMermaid(
5879
return {
5980
status: "error",
6081
message: error instanceof Error ? error.message : "The diagram could not be rendered.",
82+
retryable: false,
6183
};
6284
} finally {
6385
document.getElementById(`d${id}`)?.remove();
6486
}
6587
}
6688

6789
function mermaidRenderPromise(source: string, theme: "light" | "dark") {
68-
const key = `${fnv1a32(source).toString(36)}:${source.length}:${theme}`;
90+
const key = `${theme}\n${source}`;
6991
const cached = renderCache.get(key);
70-
if (cached) return cached;
92+
if (cached) {
93+
renderCache.delete(key);
94+
renderCache.set(key, cached);
95+
return cached;
96+
}
7197
const result = renderQueue.then(() => renderMermaid(source, theme));
7298
renderQueue = result;
73-
renderCache.set(key, result, source.length * 8);
99+
void result.then((settled) => {
100+
settledRenders.add(result);
101+
// A failed load retries the next time the diagram mounts.
102+
if (settled.status === "error" && settled.retryable && renderCache.get(key) === result) {
103+
renderCache.delete(key);
104+
}
105+
});
106+
renderCache.set(key, result);
107+
if (renderCache.size > MAX_CACHED_RENDERS) {
108+
for (const [oldKey, oldResult] of renderCache) {
109+
if (settledRenders.has(oldResult)) {
110+
renderCache.delete(oldKey);
111+
break;
112+
}
113+
}
114+
}
74115
return result;
75116
}
76117

77-
/** Converts a rendered diagram into a standalone image URL with fixed size and background. */
78-
function mermaidSvgImageUrl(svg: string, background: string): string {
79-
const document = new DOMParser().parseFromString(svg, "image/svg+xml");
80-
const element = document.documentElement;
118+
const imageUrls = new WeakMap<MermaidRenderResult, string>();
119+
120+
/**
121+
* Converts a rendered diagram into a standalone image with fixed size and background.
122+
* A blob URL, unlike a data URL, passes the desktop connect-src policy that media
123+
* save and copy actions fetch through.
124+
*/
125+
function mermaidImageUrl(result: MermaidRenderResult & { status: "rendered" }): string {
126+
const cached = imageUrls.get(result);
127+
if (cached) return cached;
128+
const svgDocument = new DOMParser().parseFromString(result.svg, "image/svg+xml");
129+
const element = svgDocument.documentElement;
81130
const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);
82131
if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {
83132
element.setAttribute("width", String(viewBox[2]));
84133
element.setAttribute("height", String(viewBox[3]));
85134
}
86135
element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
87136
element.style.maxWidth = "none";
88-
element.style.backgroundColor = background;
89-
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(element))}`;
137+
element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;
138+
const url = URL.createObjectURL(
139+
new Blob([new XMLSerializer().serializeToString(element)], { type: "image/svg+xml" }),
140+
);
141+
imageUrls.set(result, url);
142+
return url;
90143
}
91144

92145
/** Suspends until the diagram renders; failures show the parser message above the source. */
@@ -118,9 +171,7 @@ export function MermaidDiagram({
118171
type="button"
119172
aria-label="Expand diagram"
120173
className="flex w-full cursor-zoom-in justify-center rounded-md focus-visible:outline-2 focus-visible:outline-ring [&_svg]:h-auto [&_svg]:max-w-full"
121-
onClick={() =>
122-
onExpand(mermaidSvgImageUrl(result.svg, getComputedStyle(document.body).backgroundColor))
123-
}
174+
onClick={() => onExpand(mermaidImageUrl(result))}
124175
dangerouslySetInnerHTML={{ __html: result.svg }}
125176
/>
126177
</div>

0 commit comments

Comments
 (0)