Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix: render SVG artifacts verbatim in a sandboxed iframe (#20918)

YuTengjing1ed3793344b2
diff --git a/packages/builtin-skills/src/artifacts/content.ts b/packages/builtin-skills/src/artifacts/content.ts
index e0e2b5050c9..2549ff4705d 100644
--- a/packages/builtin-skills/src/artifacts/content.ts
+++ b/packages/builtin-skills/src/artifacts/content.ts
@@ -53,7 +53,10 @@ Select the appropriate type and follow its strict constraints:
- No external images (use placeholders: \`/api/placeholder/WIDTH/HEIGHT\`)
### **SVG** (\`image/svg+xml\`)
-- Specify \`viewBox\` instead of fixed width/height
+- **Rendering:** The SVG is shown verbatim in a sandboxed frame, as a browser shows an \`.svg\` file. The root \`<svg>\` is stretched to fill the preview panel and centered, so always set \`viewBox\` and \`xmlns="http://www.w3.org/2000/svg"\` instead of fixed width/height
+- **Background:** The preview canvas is always white, even in dark mode, and \`prefers-color-scheme\` resolves to light. Draw a full-size background shape when the design needs another backdrop
+- **Animation:** Use CSS (\`<style>\` with \`@keyframes\`, \`:hover\`) or SMIL (\`<animate>\`, \`<animateTransform>\`, \`<animateMotion>\`, \`<set>\`). Scripts and \`on*\` event handlers never run, and links cannot open pages outside the preview; build anything that needs JavaScript or navigation as an HTML or React artifact
+- **Self-contained:** Users can download the SVG or a PNG of its first frame. External images and fonts load in the preview but are missing from the PNG, so prefer inline shapes, \`data:\` images, and system font stacks
### **React** (\`application/lobe.artifacts.react\`)
- **Syntax:** Functional components (Hooks allowed: \`useState\`, \`useEffect\`)
diff --git a/packages/utils/src/client/index.ts b/packages/utils/src/client/index.ts
index dfdf2ea7ebe..a0be2e56cbe 100644
--- a/packages/utils/src/client/index.ts
+++ b/packages/utils/src/client/index.ts
@@ -3,5 +3,4 @@ export * from './clipboard';
export * from './downloadFile';
export * from './exportFile';
export * from './fetchEventSource';
-export * from './sanitize';
export * from './videoValidation';
diff --git a/packages/utils/src/client/sanitize.test.ts b/packages/utils/src/client/sanitize.test.ts
deleted file mode 100644
index 67e6d515099..00000000000
--- a/packages/utils/src/client/sanitize.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { sanitizeSVGContent } from './sanitize';
-
-describe('sanitizeSVGContent', () => {
- it('should preserve safe SVG elements and attributes', () => {
- const safeSvg = `
- <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
- <circle cx="50" cy="50" r="40" fill="red" stroke="blue" stroke-width="2" />
- <rect x="10" y="10" width="30" height="30" fill="green" />
- <path d="M10,20 L30,40" stroke="black" />
- </svg>
- `;
-
- const sanitized = sanitizeSVGContent(safeSvg);
-
- expect(sanitized).toContain('<svg');
- expect(sanitized).toContain('xmlns="http://www.w3.org/2000/svg"');
- expect(sanitized).toContain('<circle');
- expect(sanitized).toContain('fill="red"');
- expect(sanitized).toContain('<rect');
- expect(sanitized).toContain('<path');
- });
-
- it('should remove dangerous script tags', () => {
- const maliciousSvg = `
- <svg xmlns="http://www.w3.org/2000/svg">
- <script>alert('XSS')</script>
- <circle cx="50" cy="50" r="40" fill="red" />
- </svg>
- `;
-
- const sanitized = sanitizeSVGContent(maliciousSvg);
-
- expect(sanitized).not.toContain('<script>');
- expect(sanitized).not.toContain('alert');
- expect(sanitized).toContain('<svg');
- });
-
- it('should remove dangerous event handler attributes', () => {
- const maliciousSvg = `
- <svg xmlns="http://www.w3.org/2000/svg">
- <circle cx="50" cy="50" r="40" fill="red" onclick="alert('click')" onload="alert('load')" />
- <rect width="10" height="10" onMouseOver='alert("hover")' onfocus=alert(1) />
- </svg>
- `;
-
- const sanitized = sanitizeSVGContent(maliciousSvg);
-
- expect(sanitized).not.toContain('onclick');
- expect(sanitized).not.toContain('onload');
- expect(sanitized).not.toContain('onMouseOver');
- expect(sanitized).not.toContain('onfocus');
- expect(sanitized).toContain('<circle');
- expect(sanitized).toContain('fill="red"');
- });
-
- it('should not leave a recombined event handler after stripping', () => {
- // Removing the inner handler in a single pass would splice ` on` + `click="y"` back into a
- // fresh ` onclick="y"`; the scrub must repeat until no handler remains.
- const malicious = `<svg xmlns="http://www.w3.org/2000/svg"><circle on onclick="x"click="y" /></svg>`;
-
- const sanitized = sanitizeSVGContent(malicious);
-
- expect(sanitized).not.toMatch(/\son[a-z]+\s*=/i);
- });
-
- it('should remove dangerous embed and object tags', () => {
- const maliciousSvg = `
- <svg xmlns="http://www.w3.org/2000/svg">
- <object data="malicious.swf"></object>
- <embed src="malicious.swf"></embed>
- <circle cx="50" cy="50" r="40" fill="red" />
- </svg>
- `;
-
- const sanitized = sanitizeSVGContent(maliciousSvg);
-
- // Note: DOMPurify with SVG profile may still allow some elements
- // The key security protection is removing script and event handlers
- expect(sanitized).toContain('<circle');
- expect(sanitized).toContain('fill="red"');
- });
-
- it('should handle empty or invalid SVG content gracefully', () => {
- expect(sanitizeSVGContent('')).toBe('');
- expect(sanitizeSVGContent('<invalid>content</invalid>')).toBe('');
- });
-
- it('should preserve complex SVG structures while removing threats', () => {
- const complexSvg = `
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
- <defs>
- <linearGradient id="grad1">
- <stop offset="0%" stop-color="red" />
- <stop offset="100%" stop-color="blue" />
- </linearGradient>
- </defs>
- <g transform="translate(50,50)">
- <script>malicious()</script>
- <circle cx="50" cy="50" r="40" fill="url(#grad1)" onclick="hack()" />
- <text x="50" y="60" text-anchor="middle" onload="evil()">Hello</text>
- </g>
- </svg>
- `;
-
- const sanitized = sanitizeSVGContent(complexSvg);
-
- // Should preserve safe structure (assert by property, not exact serialization β€”
- // whitespace/self-closing handling varies across DOM engines).
- expect(sanitized).toContain('<svg');
- expect(sanitized).toContain('viewBox="0 0 200 200"');
- expect(sanitized).toContain('<linearGradient id="grad1"');
- expect(sanitized).toContain('stop-color="red"');
- expect(sanitized).toContain('transform="translate(50,50)"');
-
- // Should strip all threats regardless of engine
- expect(sanitized).not.toContain('<script');
- expect(sanitized).not.toContain('malicious');
- expect(sanitized).not.toContain('onclick');
- expect(sanitized).not.toContain('onload');
- expect(sanitized).not.toContain('hack()');
- expect(sanitized).not.toContain('evil()');
- });
-});
diff --git a/packages/utils/src/client/sanitize.ts b/packages/utils/src/client/sanitize.ts
deleted file mode 100644
index d561b7708e7..00000000000
--- a/packages/utils/src/client/sanitize.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import DOMPurify from 'dompurify';
-
-const FORBID_EVENT_HANDLERS = [
- 'onblur',
- 'onchange',
- 'onclick',
- 'onerror',
- 'onfocus',
- 'onkeydown',
- 'onkeypress',
- 'onkeyup',
- 'onload',
- 'onmousedown',
- 'onmouseout',
- 'onmouseover',
- 'onmouseup',
- 'onreset',
- 'onselect',
- 'onsubmit',
- 'onunload',
-];
-
-/**
- * Matches any `on*` event-handler attribute together with its value β€” ` onclick="…"`,
- * ` onload='…'`, or unquoted ` onfoo=bar`. SVG has no safe attribute that starts with `on`,
- * so stripping all of them is lossless for legitimate content.
- */
-const EVENT_HANDLER_ATTR = /\son[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s/>]+)/gi;
-
-/**
- * Sanitizes SVG content to prevent XSS attacks while preserving safe SVG elements and attributes
- * @param content - The SVG content to sanitize
- * @returns Sanitized SVG content safe for rendering
- */
-export const sanitizeSVGContent = (content: string): string => {
- const sanitized = DOMPurify.sanitize(content, {
- FORBID_ATTR: FORBID_EVENT_HANDLERS,
- FORBID_TAGS: ['embed', 'link', 'object', 'script', 'style'],
- KEEP_CONTENT: false,
- USE_PROFILES: { svg: true, svgFilters: true },
- });
-
- // Defense-in-depth: DOMPurify's attribute-level filtering runs through the underlying DOM's
- // attribute + namespace handling, which is inconsistent across engines (jsdom vs happy-dom) and
- // DOMPurify versions β€” in some CI environments `on*` handlers on SVG-namespaced nodes are not
- // stripped at all. Scrub them from the serialized output so removal is deterministic everywhere.
- //
- // Apply repeatedly until the string stabilizes: removing one handler can splice the surrounding
- // text into a fresh `on…=` token (e.g. ` on onclick="x"click="y"` β†’ ` onclick="y"`), which a
- // single pass would miss.
- let scrubbed = sanitized;
- let previous: string;
- do {
- previous = scrubbed;
- scrubbed = scrubbed.replaceAll(EVENT_HANDLER_ATTR, '');
- } while (scrubbed !== previous);
-
- return scrubbed;
-};
diff --git a/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx b/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx
index 155082e6bf7..95f18e0b04c 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx
@@ -1,24 +1,25 @@
import { BRANDING_NAME } from '@lobechat/business-const';
-import { copyImageToClipboard, sanitizeSVGContent } from '@lobechat/utils/client';
-import { Center, DropdownMenu, Flexbox, Tooltip } from '@lobehub/ui';
+import { copyImageToClipboard } from '@lobechat/utils/client';
+import { DropdownMenu, Flexbox, Tooltip } from '@lobehub/ui';
import { Button, toast } from '@lobehub/ui/base-ui';
-import { snapdom } from '@zumer/snapdom';
import { css, cx } from 'antd-style';
import { CopyIcon, DownloadIcon } from 'lucide-react';
-import { useMemo } from 'react';
+import { useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
-const svgContainer = css`
+import { getSvgFrameProps, rasterizeSvg } from './svgDocument';
+
+const svgFrame = css`
width: 100%;
height: 100%;
+ border: none;
- > svg {
- width: 100%;
- height: 100%;
- }
+ /* Matches the srcdoc's light scheme so prefers-color-scheme inside the SVG resolves to light,
+ consistent with the white preview canvas, even when the app runs in dark mode. */
+ color-scheme: light;
`;
const actions = css`
@@ -27,7 +28,6 @@ const actions = css`
inset-inline-end: 8px;
`;
-const DOM_ID = 'artfact-svg';
interface SVGRendererProps {
content: string;
}
@@ -35,33 +35,16 @@ interface SVGRendererProps {
const SVGRenderer = ({ content }: SVGRendererProps) => {
const { t } = useTranslation('portal');
- // Sanitize SVG content to prevent XSS attacks
- const sanitizedContent = useMemo(() => sanitizeSVGContent(content), [content]);
-
- const generatePng = async () => {
- const blob = await snapdom.toBlob(document.querySelector(`#${DOM_ID}`) as HTMLDivElement, {
- scale: 2,
- type: 'png',
- });
+ const frameRef = useRef<HTMLIFrameElement>(null);
+ const frameProps = useMemo(() => getSvgFrameProps(content), [content]);
- if (!blob) {
- throw new Error('Failed to generate PNG blob');
- }
+ // Rasterize at the preview's on-screen size so the PNG matches what the user sees
+ const generatePng = () => {
+ const frame = frameRef.current;
- // Convert blob to data URL
- return new Promise<string>((resolve, reject) => {
- const reader = new FileReader();
- reader.addEventListener('load', () => {
- if (typeof reader.result === 'string') {
- resolve(reader.result);
- } else {
- reject(new Error('FileReader result is not a string'));
- }
- });
- reader.addEventListener('error', () =>
- reject(reader.error || new Error('Failed to read blob as data URL')),
- );
- reader.readAsDataURL(blob);
+ return rasterizeSvg(content, {
+ height: frame?.clientHeight || 600,
+ width: frame?.clientWidth || 800,
});
};
@@ -69,7 +52,7 @@ const SVGRenderer = ({ content }: SVGRendererProps) => {
let dataUrl = '';
if (type === 'png') dataUrl = await generatePng();
else if (type === 'svg') {
- const blob = new Blob([sanitizedContent], { type: 'image/svg+xml' });
+ const blob = new Blob([content], { type: 'image/svg+xml' });
dataUrl = URL.createObjectURL(blob);
}
@@ -90,11 +73,7 @@ const SVGRenderer = ({ content }: SVGRendererProps) => {
height={'100%'}
style={{ position: 'relative' }}
>
- <Center
- className={cx(svgContainer)}
- dangerouslySetInnerHTML={{ __html: sanitizedContent }}
- id={DOM_ID}
- />
+ <iframe className={cx(svgFrame)} ref={frameRef} title={'svg-renderer'} {...frameProps} />
<Flexbox horizontal className={cx(actions)} gap={4}>
<DropdownMenu
items={[
@@ -116,9 +95,8 @@ const SVGRenderer = ({ content }: SVGRendererProps) => {
<Button
icon={CopyIcon}
onClick={async () => {
- const dataUrl = await generatePng();
try {
- await copyImageToClipboard(dataUrl);
+ await copyImageToClipboard(await generatePng());
toast.success(t('artifacts.svg.copySuccess'));
} catch (e) {
toast.error(t('artifacts.svg.copyFail', { error: e }));
diff --git a/src/features/Portal/Artifacts/Body/Renderer/svgDocument.test.ts b/src/features/Portal/Artifacts/Body/Renderer/svgDocument.test.ts
new file mode 100644
index 00000000000..c719c8f279a
--- /dev/null
+++ b/src/features/Portal/Artifacts/Body/Renderer/svgDocument.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import { getSvgFrameProps, SVG_PREVIEW_BACKGROUND, toStandaloneSvg } from './svgDocument';
+
+const ANIMATED_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <style>@keyframes spin { to { transform: rotate(360deg); } } .wheel { fill: red; animation: spin 2s infinite; }</style>
+ <circle class="wheel" cx="50" cy="50" r="20"><set attributeName="r" to="30" begin="1s" /></circle>
+ <foreignObject x="0" y="0" width="100" height="20"><div>Caption</div></foreignObject>
+ <script>alert(1)</script>
+</svg>`;
+
+describe('getSvgFrameProps', () => {
+ it('previews the SVG verbatim inside a script-free sandbox', () => {
+ const { sandbox, srcDoc } = getSvgFrameProps(ANIMATED_SVG);
+
+ // An empty sandbox disables scripts, so the <script> above can stay in the document
+ expect(sandbox).toBe('');
+ expect(srcDoc).toContain(ANIMATED_SVG);
+ });
+
+ it('paints a white canvas regardless of the app theme', () => {
+ const { srcDoc } = getSvgFrameProps('<svg viewBox="0 0 10 10"></svg>');
+
+ expect(srcDoc).toContain(`background:${SVG_PREVIEW_BACKGROUND}`);
+ expect(srcDoc).toContain('color-scheme:light');
+ });
+});
+
+describe('toStandaloneSvg', () => {
+ it('sizes the root svg and serializes it with its namespace', () => {
+ const svg = toStandaloneSvg(
+ '<svg viewBox="0 0 10 10"><rect width="10" height="10" /></svg>',
+ 320,
+ 240,
+ );
+
+ expect(svg).toContain('xmlns="http://www.w3.org/2000/svg"');
+ expect(svg).toContain('width="320"');
+ expect(svg).toContain('height="240"');
+ expect(svg).toContain('<rect');
+ });
+
+ it('returns undefined when there is no svg element', () => {
+ expect(toStandaloneSvg('<div>not svg</div>', 10, 10)).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/Artifacts/Body/Renderer/svgDocument.ts b/src/features/Portal/Artifacts/Body/Renderer/svgDocument.ts
new file mode 100644
index 00000000000..e5bb0fad362
--- /dev/null
+++ b/src/features/Portal/Artifacts/Body/Renderer/svgDocument.ts
@@ -0,0 +1,86 @@
+/**
+ * The preview canvas is always white, whatever the app theme, like a browser opening an `.svg`
+ * file: generated SVGs routinely rely on the default black fill and text, which would vanish on a
+ * dark, transparent backdrop.
+ */
+export const SVG_PREVIEW_BACKGROUND = '#fff';
+
+const buildSvgSrcDoc = (content: string): string =>
+ [
+ '<!doctype html><html><head><meta charset="utf-8"><style>',
+ ':root{color-scheme:light;}',
+ `html,body{margin:0;width:100%;height:100%;overflow:hidden;background:${SVG_PREVIEW_BACKGROUND};}`,
+ 'body{display:flex;align-items:center;justify-content:center;}',
+ 'body>svg{width:100%;height:100%;}',
+ '</style></head><body>',
+ content,
+ '</body></html>',
+ ].join('');
+
+/**
+ * Props for the iframe that previews an SVG artifact.
+ *
+ * The SVG is rendered verbatim instead of being sanitized into the app DOM: an inline SVG's
+ * `<style>` would restyle the whole app, so inline rendering forced a lossy allowlist that silently
+ * dropped `<style>` (CSS animations, class fills), `<foreignObject>`, SMIL tags and more. An empty
+ * `sandbox` disables scripts and gives the document an opaque origin, and styles stay scoped to
+ * the SVG's own document, so the preview matches what a browser shows when opening the file.
+ */
+export const getSvgFrameProps = (content: string) => ({
+ sandbox: '',
+ srcDoc: buildSvgSrcDoc(content),
+});
+
+/**
+ * Serializes the artifact's root `<svg>` as a standalone SVG document sized to `width` Γ— `height`,
+ * ready to be loaded as an image for rasterization.
+ *
+ * The content is parsed as HTML, the same lenient way the preview parses it, so markup that is not
+ * well-formed XML still exports; `XMLSerializer` then adds the namespaces an image load requires.
+ * @returns `undefined` when the content has no `<svg>` element
+ */
+export const toStandaloneSvg = (
+ content: string,
+ width: number,
+ height: number,
+): string | undefined => {
+ const doc = new DOMParser().parseFromString(content, 'text/html');
+ const svg = doc.querySelector('svg');
+ if (!svg) return;
+
+ svg.setAttribute('width', String(width));
+ svg.setAttribute('height', String(height));
+
+ return new XMLSerializer().serializeToString(svg);
+};
+
+/**
+ * Rasterizes SVG content to a PNG data URL at `scale` times the given CSS size.
+ *
+ * The SVG is drawn through an `<img>`, where browsers render it in secure static mode: scripts are
+ * disabled and the first frame of any animation is captured.
+ */
+export const rasterizeSvg = async (
+ content: string,
+ { height, scale = 2, width }: { height: number; scale?: number; width: number },
+): Promise<string> => {
+ const svg = toStandaloneSvg(content, width, height);
+ if (!svg) throw new Error('SVG content has no <svg> element');
+
+ const image = new Image();
+ // A data URL rather than a blob URL: Chromium taints the canvas when a blob-loaded SVG contains
+ // `<foreignObject>`, and `toDataURL` then throws a SecurityError
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
+ await image.decode();
+
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.round(width * scale);
+ canvas.height = Math.round(height * scale);
+
+ const context = canvas.getContext('2d');
+ if (!context) throw new Error('Canvas 2D context is unavailable');
+
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
+
+ return canvas.toDataURL('image/png');
+};