YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(chat): sanitize raw HTML in chat markdown
Manas Raghuwanshibd90b1b682fa
diff --git a/apps/screenpipe-app-tauri/bun.lock b/apps/screenpipe-app-tauri/bun.lockindex 408fe4b43..161f46e04 100644--- a/apps/screenpipe-app-tauri/bun.lock+++ b/apps/screenpipe-app-tauri/bun.lock@@ -70,6 +70,7 @@"react-markdown": "^9.1.0","react-syntax-highlighter": "^15.6.6","rehype-raw": "^7.0.0",+ "rehype-sanitize": "^6.0.0","remark-gfm": "^4.0.1","remark-math": "^6.0.0","remark-parse": "^11.0.0",@@ -1899,6 +1900,8 @@"hast-util-raw": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-from-parse5": "^8.0.0", "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "parse5": "^7.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw=="],+ "hast-util-sanitize": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="],+"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^6.0.0", "space-separated-tokens": "^2.0.0", "style-to-object": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, ""],"hast-util-to-parse5": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA=="],@@ -2657,6 +2660,8 @@"rehype-raw": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="],+ "rehype-sanitize": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="],+"remark-frontmatter": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-frontmatter": "^2.0.0", "micromark-extension-frontmatter": "^2.0.0", "unified": "^11.0.0" } }, "sha512-XTFYvNASMe5iPN0719nPrdItC9aU0ssC4v14mH1BCi1u0n1gAocqcujWUrByftZTbLhRtiKRyjYTSIOcr69UVQ=="],"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],diff --git a/apps/screenpipe-app-tauri/components/chat/markdown-block.test.tsx b/apps/screenpipe-app-tauri/components/chat/markdown-block.test.tsxindex 1780ecfdc..58c703af1 100644--- a/apps/screenpipe-app-tauri/components/chat/markdown-block.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/markdown-block.test.tsx@@ -378,6 +378,65 @@ describe("MarkdownBlock", () => {);});+ describe.each([false, true])("raw HTML sanitization (isUser=%s)", (isUser) => {+ const renderHtml = (text: string) =>+ render(<MarkdownBlock text={text} isUser={isUser} />).container;++ it.each([+ ["iframe", `<iframe srcdoc="<h1>INJECTED</h1>"></iframe>`],+ ["form", `<form action="https://example.com/collect"><input type="password" name="pw"></form>`],+ ["meta refresh", `<meta http-equiv="refresh" content="0;url=https://example.com">`],+ ["object", `<object data="https://example.com/x.swf"></object>`],+ ["embed", `<embed src="https://example.com/x.swf">`],+ ["style", `<style>body{background:#f00}</style>`],+ ["base", `<base href="https://example.com/">`],+ ])("does not create live %s elements", (_name, html) => {+ const container = renderHtml(`before\n\n${html}\n\nafter`);+ expect(+ container.querySelector("iframe, form, meta, object, embed, style, base, input[type=password]"),+ ).toBeNull();+ expect(container.textContent).not.toContain("body{background");+ expect(container).toHaveTextContent("before");+ expect(container).toHaveTextContent("after");+ });++ it("strips inline styles from allowed tags", () => {+ const container = renderHtml(`<b style="position:fixed;inset:0">bold</b>`);+ const bold = container.querySelector("b");+ expect(bold).toHaveTextContent("bold");+ expect(bold?.getAttribute("style")).toBeNull();+ });++ it("neutralizes javascript: URLs in raw HTML attributes", () => {+ const container = renderHtml(+ `<a href="javascript:alert(1)">click</a> <img src="https://example.com/x.png" longdesc="javascript:alert(1)">`,+ );+ expect(container.querySelector("a[href^='javascript']")).toBeNull();+ expect(container.querySelector("img")?.getAttribute("longdesc")).toBeNull();+ });++ it("keeps safe formatting and collapsible details", () => {+ const container = renderHtml(+ `<details><summary>More</summary>\n\nhidden **body**\n\n</details>\n\n<kbd>Cmd</kbd> H<sub>2</sub>O x<sup>2</sup> <b>bold</b> <i>it</i> <u>u</u> <mark>m</mark> <small>s</small>`,+ );+ expect(container.querySelector("details summary")).toHaveTextContent("More");+ expect(container.querySelector("details strong")).toHaveTextContent("body");+ for (const tag of ["kbd", "sub", "sup", "b", "i", "u", "mark", "small"]) {+ expect(container.querySelector(tag)).not.toBeNull();+ }+ });+ });++ it.each([+ ["GFM footnote", "claim[^1]\n\n[^1]: source", "a[data-footnote-ref]"],+ ["raw HTML anchor", `<a href="#sec">jump</a>\n\n<h2 id="sec">Sec</h2>`, "a"],+ ])("keeps %s in-page links pointing at their targets", (_name, text, selector) => {+ const { container } = render(<MarkdownBlock text={text} isUser={false} />);+ const href = container.querySelector(selector)?.getAttribute("href") ?? "";+ expect(href.startsWith("#user-content-")).toBe(true);+ expect(container.querySelector(`[id="${href.slice(1)}"]`)).not.toBeNull();+ });+it("renders complete Markdown blocks immediately and keeps the unfinished tail cheap", () => {vi.useFakeTimers();const first = "## finding\n\n[artifact](https://example.com)";diff --git a/apps/screenpipe-app-tauri/components/chat/markdown-block.tsx b/apps/screenpipe-app-tauri/components/chat/markdown-block.tsxindex c6ea6fb56..3e8936cbc 100644--- a/apps/screenpipe-app-tauri/components/chat/markdown-block.tsx+++ b/apps/screenpipe-app-tauri/components/chat/markdown-block.tsx@@ -8,6 +8,7 @@ import { ChatMarkdown } from "@screenpipe/workflows-ui/chat";export { stableStreamingMarkdownPrefix } from "@screenpipe/workflows-ui/chat";import { emit } from "@tauri-apps/api/event";import rehypeRaw from "rehype-raw";+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import remarkGfm from "remark-gfm";import type { Options as ReactMarkdownOptions } from "react-markdown";import {@@ -29,6 +30,50 @@ import { ChatWebLink } from "@/components/chat/chat-web-link";import { useGT } from "gt-react";+// Chat text comes from AI replies built on captured screens, pages, and+// files, so raw HTML must not become live DOM in the app window. rehype-raw+// keeps the formatting tags the system prompt asks for (e.g. <details>);+// GitHub's allowlist then drops iframes, forms, meta, scripts, styles, and+// event-handler attributes. href/src protocols are left to `urlTransform`,+// which react-markdown applies after rehype and which already allows+// screenpipe:// and local file links that the default protocol list would+// strip; attributes urlTransform never sees keep the default protocol check.+const CLOBBER_PREFIX = "user-content-";+const chatSanitizeSchema = {+ ...defaultSchema,+ tagNames: [...(defaultSchema.tagNames ?? []), "u", "mark", "small"],+ protocols: { ...defaultSchema.protocols, href: [], src: [] },+ clobberPrefix: CLOBBER_PREFIX,+ strip: [...(defaultSchema.strip ?? []), "style"],+};++// The sanitizer prefixes ids so raw HTML cannot clobber globals. GFM+// footnotes are emitted unprefixed (see remarkRehypeOptions) so every id is+// prefixed exactly once; in-page links are re-pointed at the prefixed ids.+type HastNode = {+ type: string;+ tagName?: string;+ properties?: Record<string, unknown>;+ children?: HastNode[];+};+function prefixInPageLinks(node: HastNode) {+ const href = node.properties?.href;+ if (node.tagName === "a" && typeof href === "string" && href.length > 1 && href.startsWith("#")) {+ node.properties!.href = `#${CLOBBER_PREFIX}${href.slice(1)}`;+ }+ node.children?.forEach(prefixInPageLinks);+}+const rehypePrefixInPageLinks = () => prefixInPageLinks;++const chatRemarkRehypeOptions: ReactMarkdownOptions["remarkRehypeOptions"] = {+ clobberPrefix: "",+};+const chatRehypePlugins: NonNullable<ReactMarkdownOptions["rehypePlugins"]> = [+ rehypeRaw,+ [rehypeSanitize, chatSanitizeSchema],+ rehypePrefixInPageLinks,+];+// The transport snapshots text every 80 ms. Parse only complete blocks// (blank-line / closed-fence boundaries) and commit each one on the same// snapshot so headings, lists, and links do not sit as raw source. Each@@ -259,7 +304,8 @@ export function MarkdownBlock({className={markdownClassName}remarkPlugins={remarkPlugins}urlTransform={resolvedUrlTransform}- rehypePlugins={[rehypeRaw]}+ remarkRehypeOptions={chatRemarkRehypeOptions}+ rehypePlugins={chatRehypePlugins}components={markdownComponents}>{block}diff --git a/apps/screenpipe-app-tauri/package.json b/apps/screenpipe-app-tauri/package.jsonindex 341321bf0..878619108 100644--- a/apps/screenpipe-app-tauri/package.json+++ b/apps/screenpipe-app-tauri/package.json@@ -152,6 +152,7 @@"react-markdown": "^9.1.0","react-syntax-highlighter": "^15.6.6","rehype-raw": "^7.0.0",+ "rehype-sanitize": "^6.0.0","remark-gfm": "^4.0.1","remark-math": "^6.0.0","remark-parse": "^11.0.0",