Added defense-in-depth security layers for Mermaid rendering: DOMPurify SVG Sanitization: - Sanitize SVG output after mermaid.render() - Remove script tags, iframes, objects, embeds - Remove event handlers (onerror, onclick, onload, etc.) - Use SVG profile for allowed elements Label Sanitization: - Added sanitizeMermaidLabel() function - Remove HTML tags from all labels - Remove dangerous protocols (javascript:, data:, vbscript:) - Remove control characters - Escape Mermaid special characters - Truncate to 200 chars for DoS prevention - Applied to all node labels in diagrams Comprehensive XSS Testing: - 15 test cases covering all attack vectors - Script tag injection variants - Event handler injection - JavaScript/data URL injection - SVG with embedded scripts - HTML entity bypass attempts - All tests passing Files modified: - apps/web/src/components/mindmap/MermaidViewer.tsx - apps/web/src/components/mindmap/hooks/useGraphData.ts - apps/web/src/components/mindmap/MermaidViewer.test.tsx (new) Fixes #200 Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
151 lines
4.2 KiB
TypeScript
151 lines
4.2 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
|
|
"use client";
|
|
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import mermaid from "mermaid";
|
|
import DOMPurify from "dompurify";
|
|
|
|
interface MermaidViewerProps {
|
|
diagram: string;
|
|
className?: string;
|
|
onNodeClick?: (nodeId: string) => void;
|
|
}
|
|
|
|
export function MermaidViewer({
|
|
diagram,
|
|
className = "",
|
|
onNodeClick,
|
|
}: MermaidViewerProps): React.JSX.Element {
|
|
const containerRef = useRef<HTMLDivElement>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
const renderDiagram = useCallback(async () => {
|
|
if (!containerRef.current || !diagram) {
|
|
setIsLoading(false);
|
|
return;
|
|
}
|
|
|
|
setIsLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
// Initialize mermaid with theme based on document
|
|
const isDark = document.documentElement.classList.contains("dark");
|
|
mermaid.initialize({
|
|
startOnLoad: false,
|
|
theme: isDark ? "dark" : "default",
|
|
flowchart: {
|
|
useMaxWidth: true,
|
|
htmlLabels: false,
|
|
curve: "basis",
|
|
},
|
|
securityLevel: "strict",
|
|
});
|
|
|
|
// Generate unique ID for this render
|
|
const id = `mermaid-${String(Date.now())}`;
|
|
|
|
// Render the diagram
|
|
const { svg } = await mermaid.render(id, diagram);
|
|
|
|
// Sanitize SVG output with DOMPurify for defense-in-depth
|
|
// Configure DOMPurify to allow SVG elements but remove scripts and dangerous attributes
|
|
const sanitizedSvg = DOMPurify.sanitize(svg, {
|
|
USE_PROFILES: { svg: true, svgFilters: true },
|
|
ADD_TAGS: ["use"], // Allow SVG use elements
|
|
FORBID_TAGS: ["script", "iframe", "object", "embed", "base"],
|
|
FORBID_ATTR: [
|
|
"onerror",
|
|
"onload",
|
|
"onclick",
|
|
"onmouseover",
|
|
"onfocus",
|
|
"onblur",
|
|
"onchange",
|
|
"oninput",
|
|
],
|
|
});
|
|
|
|
const container = containerRef.current;
|
|
if (container) {
|
|
container.innerHTML = sanitizedSvg;
|
|
|
|
// Add click handlers to nodes if callback provided
|
|
if (onNodeClick) {
|
|
const nodes = container.querySelectorAll(".node");
|
|
nodes.forEach((node) => {
|
|
node.addEventListener("click", () => {
|
|
const nodeId = node.id.replace(/^flowchart-/, "").replace(/-\d+$/, "");
|
|
if (nodeId) {
|
|
onNodeClick(nodeId);
|
|
}
|
|
});
|
|
(node as HTMLElement).style.cursor = "pointer";
|
|
});
|
|
}
|
|
}
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Failed to render diagram");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
}, [diagram, onNodeClick]);
|
|
|
|
useEffect(() => {
|
|
void renderDiagram();
|
|
}, [renderDiagram]);
|
|
|
|
// Re-render on theme change
|
|
useEffect(() => {
|
|
const observer = new MutationObserver((mutations) => {
|
|
mutations.forEach((mutation) => {
|
|
if (mutation.attributeName === "class") {
|
|
void renderDiagram();
|
|
}
|
|
});
|
|
});
|
|
|
|
observer.observe(document.documentElement, { attributes: true });
|
|
|
|
return (): void => {
|
|
observer.disconnect();
|
|
};
|
|
}, [renderDiagram]);
|
|
|
|
if (!diagram) {
|
|
return (
|
|
<div className={`flex items-center justify-center p-8 text-gray-500 ${className}`}>
|
|
No diagram data available
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (error) {
|
|
return (
|
|
<div className={`flex flex-col items-center justify-center p-8 ${className}`}>
|
|
<div className="text-red-500 mb-2">Failed to render diagram</div>
|
|
<div className="text-sm text-gray-500">{error}</div>
|
|
<pre className="mt-4 p-4 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-w-full">
|
|
{diagram}
|
|
</pre>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className={`relative ${className}`}>
|
|
{isLoading && (
|
|
<div className="absolute inset-0 flex items-center justify-center bg-white/50 dark:bg-gray-900/50">
|
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500" />
|
|
</div>
|
|
)}
|
|
<div
|
|
ref={containerRef}
|
|
className="mermaid-container overflow-auto"
|
|
style={{ minHeight: "200px" }}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|