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: stabilize artifact html scripts (#14120)

YuTengjing5dc7c2592ce2
diff --git a/src/features/Conversation/utils/markdown.test.ts b/src/features/Conversation/utils/markdown.test.ts
index d179fb65d19..b42d7a1190e 100644
--- a/src/features/Conversation/utils/markdown.test.ts
+++ b/src/features/Conversation/utils/markdown.test.ts
@@ -322,6 +322,35 @@ Content 2 still going`;
<lobeArtifact identifier="generating" type="text/markdown" title="Generating">Content 2 still going`);
});
+
+ it('should preserve HTML script blocks while flattening artifact markup', () => {
+ const input = `<lobeArtifact identifier="snake-game" type="text/html" title="Snake Game">
+<!DOCTYPE html>
+<html>
+<body>
+<script>
+// Move the snake every frame
+const url = " // keep string content untouched";
+window.snakeStarted = true;
+</script
+ bar>
+</body>
+</html>
+</lobeArtifact>`;
+
+ const output = processWithArtifact(input);
+
+ expect(output).toContain(`<script>
+// Move the snake every frame
+const url = " // keep string content untouched";
+window.snakeStarted = true;
+</script
+ bar>`);
+ expect(output).not.toContain('// Move the snake every framewindow.snakeStarted = true;');
+ expect(output).toContain(
+ '<lobeArtifact identifier="snake-game" type="text/html" title="Snake Game"><!DOCTYPE html><html><body><script>',
+ );
+ });
});
describe('outer code block removal', () => {
diff --git a/src/features/Conversation/utils/markdown.ts b/src/features/Conversation/utils/markdown.ts
index 2f7d7baceb0..9e2bfd6c7ab 100644
--- a/src/features/Conversation/utils/markdown.ts
+++ b/src/features/Conversation/utils/markdown.ts
@@ -1,5 +1,24 @@
import { ARTIFACT_THINKING_TAG_REGEX } from '@lobechat/const';
+const ARTIFACT_TAG_REGEX_GLOBAL =
+ /<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/g;
+const HTML_SCRIPT_TAG_REGEX = /<script\b[^>]*>[\S\s]*?<\/script(?:\s[^>]*)?>/gi;
+const SCRIPT_PLACEHOLDER_PREFIX = '____LOBE_ARTIFACT_SCRIPT_BLOCK_';
+
+const removeArtifactLineBreaks = (content: string) => {
+ const scripts: string[] = [];
+ const contentWithoutScripts = content.replaceAll(HTML_SCRIPT_TAG_REGEX, (script) => {
+ const index = scripts.length;
+ scripts.push(script);
+ return `${SCRIPT_PLACEHOLDER_PREFIX}${index}____`;
+ });
+
+ return scripts.reduce(
+ (result, script, index) => result.replace(`${SCRIPT_PLACEHOLDER_PREFIX}${index}____`, script),
+ contentWithoutScripts.replaceAll(/\r?\n|\r/g, ''),
+ );
+};
+
/**
* Replace all line breaks in the matched `lobeArtifact` tag with an empty string
*/
@@ -48,11 +67,7 @@ export const processWithArtifact = (input: string = '') => {
// If the input contains `lobeArtifact` tags, replace all line breaks with an empty string
// Use global regex to handle multiple artifacts in the same message
- const ARTIFACT_TAG_REGEX_GLOBAL =
- /<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/g;
- output = output.replaceAll(ARTIFACT_TAG_REGEX_GLOBAL, (match) =>
- match.replaceAll(/\r?\n|\r/g, ''),
- );
+ output = output.replaceAll(ARTIFACT_TAG_REGEX_GLOBAL, removeArtifactLineBreaks);
// if not match, check if it's start with <lobeArtifact but not closed
const regex = /<lobeArtifact\b(?:(?!\/?>)[\s\S])*$/;
diff --git a/src/features/Portal/Artifacts/Body/Renderer/HTML.test.ts b/src/features/Portal/Artifacts/Body/Renderer/HTML.test.ts
new file mode 100644
index 00000000000..7da5e01af1e
--- /dev/null
+++ b/src/features/Portal/Artifacts/Body/Renderer/HTML.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { injectSandboxStorageShim } from './HTML';
+
+describe('injectSandboxStorageShim', () => {
+ it('should inject the storage shim before user scripts in head', () => {
+ const html = `<!DOCTYPE html>
+<html>
+<head>
+ <script>localStorage.getItem('snakeHighScore');</script>
+</head>
+<body></body>
+</html>`;
+
+ const result = injectSandboxStorageShim(html);
+
+ expect(result.indexOf('data-lobe-artifact-storage-shim')).toBeGreaterThan(-1);
+ expect(result.indexOf('data-lobe-artifact-storage-shim')).toBeLessThan(
+ result.indexOf("localStorage.getItem('snakeHighScore')"),
+ );
+ });
+
+ it('should not inject the storage shim twice', () => {
+ const html = '<html><head></head><body></body></html>';
+ const result = injectSandboxStorageShim(injectSandboxStorageShim(html));
+
+ expect(result.match(/data-lobe-artifact-storage-shim/g)).toHaveLength(1);
+ });
+
+ it('should not inject into head-like strings inside scripts', () => {
+ const html = `<!DOCTYPE html>
+<html>
+<body>
+ <script>
+ const template = "<head><title>Preview</title></head>";
+ </script>
+</body>
+</html>`;
+
+ const result = injectSandboxStorageShim(html);
+
+ expect(result).toContain('const template = "<head><title>Preview</title></head>";');
+ expect(result.indexOf('data-lobe-artifact-storage-shim')).toBeLessThan(
+ result.indexOf('const template'),
+ );
+ });
+});
diff --git a/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx b/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
index 3d09c2bbca1..85c794f591a 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
@@ -6,6 +6,96 @@ interface HTMLRendererProps {
width?: string;
}
+const SANDBOX_STORAGE_SHIM = `<script data-lobe-artifact-storage-shim>
+(() => {
+ if (window.__lobeArtifactStorageShim) return;
+ Object.defineProperty(window, '__lobeArtifactStorageShim', { value: true });
+
+ const createStorage = () => {
+ const data = Object.create(null);
+
+ return {
+ clear() {
+ for (const key of Object.keys(data)) delete data[key];
+ },
+ getItem(key) {
+ const normalizedKey = String(key);
+ return Object.prototype.hasOwnProperty.call(data, normalizedKey) ? data[normalizedKey] : null;
+ },
+ key(index) {
+ return Object.keys(data)[index] ?? null;
+ },
+ get length() {
+ return Object.keys(data).length;
+ },
+ removeItem(key) {
+ delete data[String(key)];
+ },
+ setItem(key, value) {
+ data[String(key)] = String(value);
+ },
+ };
+ };
+
+ const defineStorage = (name) => {
+ try {
+ void window[name];
+ return;
+ } catch {
+ Object.defineProperty(window, name, {
+ configurable: true,
+ value: createStorage(),
+ });
+ }
+ };
+
+ defineStorage('localStorage');
+ defineStorage('sessionStorage');
+})();
+</script>`;
+
+const SCRIPT_TAG_REGEX = /<script\b/i;
+const HEAD_TAG_REGEX = /<head(?:\s[^>]*)?>/i;
+const HTML_TAG_REGEX = /<html(?:\s[^>]*)?>/i;
+
+const findTagBeforeFirstScript = (htmlContent: string, tagRegex: RegExp) => {
+ const firstScriptIndex = htmlContent.search(SCRIPT_TAG_REGEX);
+ const searchableContent =
+ firstScriptIndex === -1 ? htmlContent : htmlContent.slice(0, firstScriptIndex);
+ const match = searchableContent.match(tagRegex);
+
+ if (!match?.[0] || match.index === undefined) return;
+
+ return {
+ index: match.index,
+ value: match[0],
+ };
+};
+
+const insertAfterTag = (htmlContent: string, tag: { index: number; value: string }) => {
+ const insertIndex = tag.index + tag.value.length;
+ return `${htmlContent.slice(0, insertIndex)}\n${SANDBOX_STORAGE_SHIM}${htmlContent.slice(
+ insertIndex,
+ )}`;
+};
+
+export const injectSandboxStorageShim = (htmlContent: string) => {
+ if (htmlContent.includes('data-lobe-artifact-storage-shim')) return htmlContent;
+
+ const headTag = findTagBeforeFirstScript(htmlContent, HEAD_TAG_REGEX);
+ if (headTag) return insertAfterTag(htmlContent, headTag);
+
+ const htmlTag = findTagBeforeFirstScript(htmlContent, HTML_TAG_REGEX);
+ if (htmlTag) {
+ const insertIndex = htmlTag.index + htmlTag.value.length;
+ return `${htmlContent.slice(0, insertIndex)}\n<head>${SANDBOX_STORAGE_SHIM}</head>${htmlContent.slice(
+ insertIndex,
+ )}`;
+ }
+
+ return `${SANDBOX_STORAGE_SHIM}\n${htmlContent}`;
+};
+
// Security boundary: the iframe runs in a unique opaque origin because the
// sandbox attribute does NOT include `allow-same-origin`. This blocks
// `window.parent.*` access (the GHSA-xq4x-622m-q8fq XSS-to-RCE path on
@@ -27,7 +117,7 @@ const HTMLRenderer = memo<HTMLRendererProps>(({ htmlContent, width = '100%', hei
return (
<iframe
sandbox="allow-scripts allow-forms allow-modals"
- srcDoc={htmlContent}
+ srcDoc={injectSandboxStorageShim(htmlContent)}
style={{ border: 'none', height, width }}
title="html-renderer"
/>