🔒 sanitize user-written HTML before rendering it
Browse files at this commit78600ff830024ee1a878ecc5781f4350050dff4cParent: aafb3af- fix
- 🔒 sanitize user-written HTML before rendering it
6 changed files +125 -2
- bun.lock +5 -0
- package.json +1 -0
- src/components/homework/homework-submissions-panel.tsx +2 -1
- src/components/messages/gmail-mail-detail.tsx +2 -1
- src/lib/rich-text.test.tsx +27 -0
- src/lib/rich-text.ts +88 -0
bun.lockmodified+5 -0
| @@ -11,6 +11,7 @@ | |||
| 11 | "@tanstack/solid-table": "^8.21.3", | 11 | "@tanstack/solid-table": "^8.21.3", |
| 12 | "class-variance-authority": "^0.7.1", | 12 | "class-variance-authority": "^0.7.1", |
| 13 | "clsx": "^2.1.1", | 13 | "clsx": "^2.1.1", |
| 14 | + "dompurify": "^3.4.15", | ||
| 14 | "pdfjs-dist": "^6.1.200", | 15 | "pdfjs-dist": "^6.1.200", |
| 15 | "pixelarticons": "^2.4.1", | 16 | "pixelarticons": "^2.4.1", |
| 16 | "solid-js": "^1.9.14", | 17 | "solid-js": "^1.9.14", |
| @@ -289,6 +290,8 @@ | |||
| 289 | 290 | ||
| 290 | "@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], | 291 | "@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], |
| 291 | 292 | ||
| 293 | + "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], | ||
| 294 | + | ||
| 292 | "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], | 295 | "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], |
| 293 | 296 | ||
| 294 | "@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="], | 297 | "@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="], |
| @@ -389,6 +392,8 @@ | |||
| 389 | 392 | ||
| 390 | "dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="], | 393 | "dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="], |
| 391 | 394 | ||
| 395 | + "dompurify": ["dompurify@3.4.15", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw=="], | ||
| 396 | + | ||
| 392 | "electron-to-chromium": ["electron-to-chromium@1.5.389", "", {}, "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg=="], | 397 | "electron-to-chromium": ["electron-to-chromium@1.5.389", "", {}, "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg=="], |
| 393 | 398 | ||
| 394 | "enhanced-resolve": ["enhanced-resolve@5.24.3", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-PwKooW9JUzh5chmYfHM3IQl5OkK2u2Nm011MgeZrss3JmFraUx/fqrf78kk8GUMYoibx/14MdwTl/1WKkG7TpQ=="], | 399 | "enhanced-resolve": ["enhanced-resolve@5.24.3", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-PwKooW9JUzh5chmYfHM3IQl5OkK2u2Nm011MgeZrss3JmFraUx/fqrf78kk8GUMYoibx/14MdwTl/1WKkG7TpQ=="], |
package.jsonmodified+1 -0
| @@ -20,6 +20,7 @@ | |||
| 20 | "@tanstack/solid-table": "^8.21.3", | 20 | "@tanstack/solid-table": "^8.21.3", |
| 21 | "class-variance-authority": "^0.7.1", | 21 | "class-variance-authority": "^0.7.1", |
| 22 | "clsx": "^2.1.1", | 22 | "clsx": "^2.1.1", |
| 23 | + "dompurify": "^3.4.15", | ||
| 23 | "pdfjs-dist": "^6.1.200", | 24 | "pdfjs-dist": "^6.1.200", |
| 24 | "pixelarticons": "^2.4.1", | 25 | "pixelarticons": "^2.4.1", |
| 25 | "solid-js": "^1.9.14", | 26 | "solid-js": "^1.9.14", |
src/components/homework/homework-submissions-panel.tsxmodified+2 -1
| @@ -21,6 +21,7 @@ import { fileTypeMeta } from "@/lib/file-type"; | |||
| 21 | import { formatDateTime } from "@/lib/format"; | 21 | import { formatDateTime } from "@/lib/format"; |
| 22 | import { formatBytes } from "@/lib/upload-limits"; | 22 | import { formatBytes } from "@/lib/upload-limits"; |
| 23 | import { usePreferences, useT } from "@/stores/preferences-context"; | 23 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 24 | +import { sanitizeRichText } from "@/lib/rich-text"; | ||
| 24 | 25 | ||
| 25 | export function HomeworkSubmissionsPanel(props: { homeworkId: string; courseId: string }) { | 26 | export function HomeworkSubmissionsPanel(props: { homeworkId: string; courseId: string }) { |
| 26 | const t = useT(); | 27 | const t = useT(); |
| @@ -185,7 +186,7 @@ export function HomeworkSubmissionsPanel(props: { homeworkId: string; courseId: | |||
| 185 | when={submission().text} | 186 | when={submission().text} |
| 186 | fallback={<p class="mt-2 text-sm text-text-subtle">{t("homework.noAnswer")}</p>} | 187 | fallback={<p class="mt-2 text-sm text-text-subtle">{t("homework.noAnswer")}</p>} |
| 187 | > | 188 | > |
| 188 | - {(text) => <div class="mt-2 text-sm leading-relaxed" innerHTML={text()} />} | 189 | + {(text) => <div class="mt-2 text-sm leading-relaxed" innerHTML={sanitizeRichText(text())} />} |
| 189 | </Show> | 190 | </Show> |
| 190 | </div> | 191 | </div> |
| 191 | {/* Skipped entirely (not just an empty placeholder) when there are no files — this is a read-only view, so a "no files" row would just be dead weight. */} | 192 | {/* Skipped entirely (not just an empty placeholder) when there are no files — this is a read-only view, so a "no files" row would just be dead weight. */} |
src/components/messages/gmail-mail-detail.tsxmodified+2 -1
| @@ -8,6 +8,7 @@ import { postMessage } from "@/api/messages"; | |||
| 8 | import { formatApiError } from "@/api/client"; | 8 | import { formatApiError } from "@/api/client"; |
| 9 | import { personLabel } from "@/lib/person"; | 9 | import { personLabel } from "@/lib/person"; |
| 10 | import { useT } from "@/stores/preferences-context"; | 10 | import { useT } from "@/stores/preferences-context"; |
| 11 | +import { sanitizeRichText } from "@/lib/rich-text"; | ||
| 11 | 12 | ||
| 12 | interface GmailMailDetailProps { | 13 | interface GmailMailDetailProps { |
| 13 | message: Message; | 14 | message: Message; |
| @@ -276,7 +277,7 @@ export function GmailMailDetail(props: GmailMailDetailProps) { | |||
| 276 | 277 | ||
| 277 | {/* Email Body Card */} | 278 | {/* Email Body Card */} |
| 278 | <div class="rounded-xl border border-border-line bg-surface-base p-6 leading-relaxed text-sm text-foreground/90 whitespace-pre-wrap min-h-[140px]"> | 279 | <div class="rounded-xl border border-border-line bg-surface-base p-6 leading-relaxed text-sm text-foreground/90 whitespace-pre-wrap min-h-[140px]"> |
| 279 | - <div innerHTML={props.message.body} /> | 280 | + <div innerHTML={sanitizeRichText(props.message.body)} /> |
| 280 | </div> | 281 | </div> |
| 281 | 282 | ||
| 282 | {/* Gmail Style Inline Reply Area */} | 283 | {/* Gmail Style Inline Reply Area */} |
src/lib/rich-text.test.tsxadded+27 -0
| @@ -0,0 +1,27 @@ | |||
| 1 | +import { isRichTextEmpty, richTextExcerpt, sanitizeRichText, toRichTextHtml } from "@/lib/rich-text"; | ||
| 2 | + | ||
| 3 | +describe("rich-text", () => { | ||
| 4 | + it("strips scripts, handlers and unknown tags but keeps formatting", () => { | ||
| 5 | + const html = sanitizeRichText('<h2>Plan</h2><p onclick="x()">Hi <strong>there</strong><img src=x onerror=alert(1)><script>alert(1)</script></p>'); | ||
| 6 | + expect(html).toBe("<h2>Plan</h2><p>Hi <strong>there</strong></p>"); | ||
| 7 | + }); | ||
| 8 | + | ||
| 9 | + it("drops javascript links and opens real ones in a new tab", () => { | ||
| 10 | + expect(sanitizeRichText('<a href="javascript:alert(1)">x</a>')).not.toContain("javascript"); | ||
| 11 | + expect(sanitizeRichText('<a href="https://example.com">x</a>')).toBe('<a href="https://example.com" target="_blank" rel="noopener noreferrer">x</a>'); | ||
| 12 | + }); | ||
| 13 | + | ||
| 14 | + it("turns imported markdown-ish text into blocks", () => { | ||
| 15 | + expect(toRichTextHtml("## Unit 1\n\nFirst line\nsecond line\n\n- a\n- b\n1. one")).toBe( | ||
| 16 | + "<h2>Unit 1</h2><p>First line<br>second line</p><ul><li>a</li><li>b</li></ul><ol><li>one</li></ol>", | ||
| 17 | + ); | ||
| 18 | + expect(toRichTextHtml("a < b")).toBe("<p>a < b</p>"); | ||
| 19 | + }); | ||
| 20 | + | ||
| 21 | + it("reads excerpts and emptiness from the text, not the markup", () => { | ||
| 22 | + expect(richTextExcerpt("<h2>Title</h2><p>Body text</p>")).toBe("Title Body text"); | ||
| 23 | + expect(richTextExcerpt("<p>abcdef</p>", 3)).toBe("abc…"); | ||
| 24 | + expect(isRichTextEmpty("<p><br></p>")).toBe(true); | ||
| 25 | + expect(isRichTextEmpty("<p>x</p>")).toBe(false); | ||
| 26 | + }); | ||
| 27 | +}); | ||
src/lib/rich-text.tsadded+88 -0
| @@ -0,0 +1,88 @@ | |||
| 1 | +import DOMPurify from "dompurify"; | ||
| 2 | + | ||
| 3 | +// Note bodies are stored as HTML written by the contentEditable editor, and | ||
| 4 | +// course notes render for every enrolled student — so anything that reaches | ||
| 5 | +// `innerHTML`, stored or pasted, goes through this allow-list first. | ||
| 6 | +const ALLOWED_TAGS = ["p", "div", "br", "h2", "h3", "strong", "b", "em", "i", "u", "s", "strike", "ul", "ol", "li", "blockquote", "pre", "code", "a", "span"]; | ||
| 7 | +const ALLOWED_ATTR = ["href", "target", "rel"]; | ||
| 8 | + | ||
| 9 | +export function sanitizeRichText(html: string): string { | ||
| 10 | + const clean = DOMPurify.sanitize(html, { ALLOWED_TAGS, ALLOWED_ATTR, ALLOW_DATA_ATTR: false }); | ||
| 11 | + // Links open outside the app without handing it the opener. | ||
| 12 | + const template = document.createElement("template"); | ||
| 13 | + template.innerHTML = clean; | ||
| 14 | + for (const link of template.content.querySelectorAll("a")) { | ||
| 15 | + link.setAttribute("target", "_blank"); | ||
| 16 | + link.setAttribute("rel", "noopener noreferrer"); | ||
| 17 | + } | ||
| 18 | + return template.innerHTML; | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +/** Plain text of a stored body, whitespace collapsed — for card excerpts, never rendered as HTML. */ | ||
| 22 | +export function richTextExcerpt(html: string, maxLength = 280): string { | ||
| 23 | + const doc = new DOMParser().parseFromString(html.replace(/<\/(p|div|h2|h3|li|blockquote|pre)>|<br\s*\/?>/gi, "$& "), "text/html"); | ||
| 24 | + const text = (doc.body.textContent ?? "").replace(/\s+/g, " ").trim(); | ||
| 25 | + return text.length > maxLength ? `${text.slice(0, maxLength).trimEnd()}…` : text; | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/** True when a body holds no visible text — an editor left with `<p><br></p>` counts as empty. */ | ||
| 29 | +export function isRichTextEmpty(html: string): boolean { | ||
| 30 | + return richTextExcerpt(html, 1) === ""; | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +const HTML_TAG = /<\/?[a-z][a-z0-9]*(\s[^>]*)?>/i; | ||
| 34 | + | ||
| 35 | +const escapeHtml = (text: string) => | ||
| 36 | + text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """); | ||
| 37 | + | ||
| 38 | +/** | ||
| 39 | + * HTML for a stored note body. Editor-written bodies are HTML already; bodies | ||
| 40 | + * from the Note Import Assistant (and older plain-text notes) are Markdown-ish | ||
| 41 | + * text, which used to be shown with `pre-wrap`. Those get their headings, | ||
| 42 | + * lists and paragraphs back as real blocks instead of one run-on line. | ||
| 43 | + */ | ||
| 44 | +export function toRichTextHtml(stored: string | null | undefined): string { | ||
| 45 | + if (!stored?.trim()) return ""; | ||
| 46 | + if (HTML_TAG.test(stored)) return sanitizeRichText(stored); | ||
| 47 | + | ||
| 48 | + const out: string[] = []; | ||
| 49 | + type OpenList = { tag: "ul" | "ol"; items: string[] }; | ||
| 50 | + let list = null as OpenList | null; | ||
| 51 | + let paragraph: string[] = []; | ||
| 52 | + const flushParagraph = () => { | ||
| 53 | + if (paragraph.length) out.push(`<p>${paragraph.join("<br>")}</p>`); | ||
| 54 | + paragraph = []; | ||
| 55 | + }; | ||
| 56 | + const flushList = () => { | ||
| 57 | + if (list) out.push(`<${list.tag}>${list.items.map((item) => `<li>${item}</li>`).join("")}</${list.tag}>`); | ||
| 58 | + list = null; | ||
| 59 | + }; | ||
| 60 | + | ||
| 61 | + for (const raw of stored.replace(/\r\n?/g, "\n").split("\n")) { | ||
| 62 | + const line = raw.trimEnd(); | ||
| 63 | + const heading = /^(#{1,6})\s+(.*)$/.exec(line); | ||
| 64 | + const bullet = /^\s*[-*•]\s+(.*)$/.exec(line); | ||
| 65 | + const numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line); | ||
| 66 | + if (!line.trim()) { | ||
| 67 | + flushParagraph(); | ||
| 68 | + flushList(); | ||
| 69 | + } else if (heading) { | ||
| 70 | + flushParagraph(); | ||
| 71 | + flushList(); | ||
| 72 | + out.push(`<${heading[1].length <= 2 ? "h2" : "h3"}>${escapeHtml(heading[2])}</${heading[1].length <= 2 ? "h2" : "h3"}>`); | ||
| 73 | + } else if (bullet || numbered) { | ||
| 74 | + flushParagraph(); | ||
| 75 | + const tag = bullet ? "ul" : "ol"; | ||
| 76 | + if ((list as OpenList | null)?.tag !== tag) flushList(); | ||
| 77 | + const open: OpenList = (list as OpenList | null) ?? { tag, items: [] }; | ||
| 78 | + list = open; | ||
| 79 | + open.items.push(escapeHtml((bullet ?? numbered)![1])); | ||
| 80 | + } else { | ||
| 81 | + flushList(); | ||
| 82 | + paragraph.push(escapeHtml(line)); | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + flushParagraph(); | ||
| 86 | + flushList(); | ||
| 87 | + return out.join(""); | ||
| 88 | +} | ||