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): render HTML in calendar invite descriptions (#7296)
gbirman2f1430f12cf8
diff --git a/apps/web/src/components/ui/components/EmailInvitation.docs.tsx b/apps/web/src/components/ui/components/EmailInvitation.docs.tsxindex ce750ed7b1..60d5d35b9a 100644--- a/apps/web/src/components/ui/components/EmailInvitation.docs.tsx+++ b/apps/web/src/components/ui/components/EmailInvitation.docs.tsx@@ -83,6 +83,30 @@ function InvitationStates() {}// #endregion+// #region demo:descriptions+function InvitationDescriptions() {+ return (+ <div class="w-full max-w-2xl">+ <CalendarInviteCard+ invitation={{+ ...invitationFixture,+ description:+ '<p>Meeting details with <strong>bold text</strong> and <a href="https://example.com">meeting notes</a>.</p><ul><li>Review the proposal</li><li>Agree on next steps</li></ul><p>Bring your questions.</p>',+ }}+ timeZone="America/Los_Angeles"+ />+ <CalendarInviteCard+ invitation={{+ ...invitationFixture,+ description: 'Email <[email protected]> for questions\nOwner: <TBD>',+ }}+ timeZone="America/Los_Angeles"+ />+ </div>+ );+}+// #endregion+export default defineDoc({name: 'EmailInvitation',category: 'Data Display',@@ -100,6 +124,12 @@ export default defineDoc({],},demos: [+ {+ id: 'descriptions',+ title: 'Rich HTML and plain text descriptions',+ render: InvitationDescriptions,+ fill: true,+ },{id: 'interactive',title: 'Selected, pending, and failed responses',diff --git a/apps/web/src/features/calendar/utils/calendar-description-sanitizer.ts b/apps/web/src/features/calendar/utils/calendar-description-sanitizer.tsnew file mode 100644index 0000000000..6d2efe216e--- /dev/null+++ b/apps/web/src/features/calendar/utils/calendar-description-sanitizer.ts@@ -0,0 +1,352 @@+import { findNextAutoLinkMatch } from '@core/component/LexicalMarkdown/plugins/links/autoLink';++/**+ * Formatting a description keeps across the provider boundary. Anything the+ * editor or a provider adds beyond this — classes, inline styles, mention+ * data attributes, media, scripts — is dropped, so the stored string is+ * portable HTML that carries no reader or author identities.+ */+const KEPT_TAGS = new Set([+ 'p',+ 'br',+ 'a',+ 'b',+ 'strong',+ 'i',+ 'em',+ 'u',+ 's',+ 'ul',+ 'ol',+ 'li',+]);+const INLINE_TAGS = new Set(['a', 'b', 'strong', 'i', 'em', 'u', 's', 'br']);+const LIST_TAGS = new Set(['ul', 'ol']);+/** Containers whose line structure is worth keeping as a paragraph. */+const PARAGRAPH_LIKE_TAGS = new Set([+ 'div',+ 'h1',+ 'h2',+ 'h3',+ 'h4',+ 'h5',+ 'h6',+ 'pre',+ 'blockquote',+ 'address',+ 'section',+ 'article',+ 'header',+ 'footer',+ 'figure',+ 'figcaption',+ 'tr',+ 'dt',+ 'dd',+ 'summary',+ 'details',+]);+/** Removed together with their content. */+const DROPPED_TAGS = new Set([+ 'script',+ 'style',+ 'iframe',+ 'frame',+ 'frameset',+ 'object',+ 'embed',+ 'applet',+ 'base',+ 'meta',+ 'link',+ 'noscript',+ 'template',+ 'svg',+ 'math',+ 'head',+ 'title',+ 'textarea',+ 'select',+ 'option',+ 'input',+ 'button',+ 'form',+ 'img',+ 'picture',+ 'source',+ 'video',+ 'audio',+ 'canvas',+]);+const LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']);++/**+ * A tag a description would only contain if it were authored as HTML. Plain+ * text legitimately holds angle brackets — `<[email protected]>`, `<TBD>` — so+ * "looks like a tag" is not enough to treat the whole string as markup.+ */+const HTML_TAG_PATTERN =+ /<(?:!--|\/?(?:a|abbr|b|big|blockquote|body|br|center|cite|code|dd|del|details|div|dl|dt|em|figure|font|h[1-6]|head|hr|html|i|iframe|img|ins|li|link|meta|ol|p|pre|s|script|section|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|template|tfoot|th|thead|title|tr|tt|u|ul)(?=[\s/>]))/i;++function parseHtml(html: string): Document {+ return new DOMParser().parseFromString(html, 'text/html');+}++/**+ * Plain text is still parsed as HTML so provider-escaped entities decode, but+ * its angle brackets are literal characters, never tags.+ */+function parsePlainText(text: string): Document {+ return parseHtml(text.replace(/</g, '<').replace(/>/g, '>'));+}++function safeHref(value: string | null): string | undefined {+ if (!value) return undefined;+ // Browsers tolerate whitespace and control characters inside a scheme+ // ("java\nscript:"), so strip them before parsing.+ const compact = Array.from(value)+ .filter((char) => char.charCodeAt(0) > 0x20)+ .join('');+ try {+ const url = new URL(compact);+ return LINK_SCHEMES.has(url.protocol) ? url.href : undefined;+ } catch {+ return undefined;+ }+}++function unwrap(element: Element) {+ element.replaceWith(...Array.from(element.childNodes));+}++function isBlock(node: Node): boolean {+ return (+ node.nodeType === Node.ELEMENT_NODE &&+ !INLINE_TAGS.has((node as Element).localName)+ );+}++/** A paragraph left with nothing in it. `<p><br></p>` is a deliberate blank line and stays. */+function isEmptyParagraph(element: Element): boolean {+ return (+ element.localName === 'p' &&+ element.firstElementChild === null &&+ (element.textContent ?? '').trim() === ''+ );+}++function replaceWithParagraph(element: Element) {+ const paragraph = element.ownerDocument.createElement('p');+ paragraph.append(...Array.from(element.childNodes));+ if (isEmptyParagraph(paragraph)) {+ element.remove();+ return;+ }+ element.replaceWith(paragraph);+}++/** Convert newlines in text nodes to `<br>` for descriptions stored as plain text. */+function breakLines(parent: Node) {+ const doc = parent.ownerDocument;+ if (!doc) return;+ const walker = doc.createTreeWalker(parent, NodeFilter.SHOW_TEXT);+ const textNodes: Text[] = [];+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ if ((node.textContent ?? '').includes('\n')) textNodes.push(node as Text);+ }+ for (const textNode of textNodes) {+ const lines = (textNode.textContent ?? '').split('\n');+ const replacement: Node[] = [];+ lines.forEach((line, index) => {+ if (index > 0) replacement.push(doc.createElement('br'));+ if (line) replacement.push(doc.createTextNode(line));+ });+ textNode.replaceWith(...replacement);+ }+}++/** Lists may only hold list items, and list items only live inside lists. */+function normalizeList(list: Element) {+ const doc = list.ownerDocument;+ let orphanItem: Element | undefined;+ for (const child of Array.from(list.childNodes)) {+ if (child.nodeType === Node.ELEMENT_NODE) {+ const element = child as Element;+ if (element.localName === 'li') {+ orphanItem = undefined;+ continue;+ }+ if (LIST_TAGS.has(element.localName)) {+ // A nested list belongs to the preceding item.+ const previous = element.previousElementSibling;+ if (previous?.localName === 'li') {+ previous.appendChild(element);+ continue;+ }+ }+ } else if ((child.textContent ?? '').trim() === '') {+ child.remove();+ continue;+ }+ if (!orphanItem) {+ orphanItem = doc.createElement('li');+ list.insertBefore(orphanItem, child);+ }+ orphanItem.appendChild(child);+ }+}++function sanitizeChildren(parent: Element) {+ for (const child of Array.from(parent.childNodes)) {+ if (child.nodeType === Node.TEXT_NODE) continue;+ if (child.nodeType !== Node.ELEMENT_NODE) {+ child.remove();+ continue;+ }+ const element = child as Element;+ const tag = element.localName;+ if (DROPPED_TAGS.has(tag)) {+ element.remove();+ continue;+ }+ sanitizeChildren(element);++ if (KEPT_TAGS.has(tag)) {+ const href = tag === 'a' ? safeHref(element.getAttribute('href')) : null;+ for (const name of element.getAttributeNames()) {+ element.removeAttribute(name);+ }+ if (tag === 'a') {+ if (!href) {+ unwrap(element);+ continue;+ }+ element.setAttribute('href', href);+ }+ if (tag === 'li' && !LIST_TAGS.has(parent.localName)) {+ replaceWithParagraph(element);+ continue;+ }+ if (tag === 'p' && isEmptyParagraph(element)) {+ element.remove();+ continue;+ }+ if (LIST_TAGS.has(tag)) normalizeList(element);+ continue;+ }++ if (+ PARAGRAPH_LIKE_TAGS.has(tag) &&+ !Array.from(element.childNodes).some(isBlock)+ ) {+ replaceWithParagraph(element);+ continue;+ }+ unwrap(element);+ }+}++/** Gather top-level runs of text and inline elements into paragraphs. */+function wrapInlineRuns(parent: Element) {+ const doc = parent.ownerDocument;+ let run: Node[] = [];+ const flush = () => {+ if (run.length === 0) return;+ const hasContent = run.some((node) =>+ node.nodeType === Node.ELEMENT_NODE+ ? (node as Element).localName !== 'br'+ : (node.textContent ?? '').trim() !== ''+ );+ if (hasContent) {+ const paragraph = doc.createElement('p');+ parent.insertBefore(paragraph, run[0]);+ paragraph.append(...run);+ } else {+ for (const node of run) node.parentNode?.removeChild(node);+ }+ run = [];+ };+ for (const child of Array.from(parent.childNodes)) {+ if (isBlock(child)) {+ flush();+ continue;+ }+ run.push(child);+ }+ flush();+}++/** The autolink strictness shared by the app's editors: bare hosts on common+ * TLDs link, but code-like tokens such as `parser.ts` do not. */+const DESCRIPTION_AUTO_LINK_MODE = 'common-tlds';++/**+ * Wrap the URLs and bare emails in a plain-text string as anchors so the detail+ * view can open them — emails become `mailto:` links, which `openExternalUrl`+ * routes to the in-app composer. Returns null when nothing was linked so the+ * caller can leave the original text node untouched.+ */+function linkifyText(text: string, doc: Document): Node[] | null {+ const nodes: Node[] = [];+ let rest = text;+ let linked = false;+ while (rest) {+ const match = findNextAutoLinkMatch(rest, DESCRIPTION_AUTO_LINK_MODE);+ if (!match || match.lastIndex <= match.index) {+ nodes.push(doc.createTextNode(rest));+ break;+ }+ linked = true;+ const before = rest.slice(0, match.index);+ if (before) nodes.push(doc.createTextNode(before));+ const anchor = doc.createElement('a');+ anchor.setAttribute('href', match.url);+ anchor.textContent = rest.slice(match.index, match.lastIndex);+ nodes.push(anchor);+ rest = rest.slice(match.lastIndex);+ }+ return linked ? nodes : null;+}++/** Turn bare URLs in text into anchors, leaving text inside existing links alone. */+function linkifyBareUrls(body: HTMLElement) {+ const doc = body.ownerDocument;+ const walker = doc.createTreeWalker(body, NodeFilter.SHOW_TEXT, {+ acceptNode: (node) =>+ node.parentElement?.closest('a')+ ? NodeFilter.FILTER_REJECT+ : NodeFilter.FILTER_ACCEPT,+ });+ const textNodes: Text[] = [];+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ textNodes.push(node as Text);+ }+ for (const textNode of textNodes) {+ const replacement = linkifyText(textNode.textContent ?? '', doc);+ if (replacement) textNode.replaceWith(...replacement);+ }+}++export function sanitizeDocument(doc: Document, plainText: boolean) {+ if (plainText) breakLines(doc.body);+ sanitizeChildren(doc.body);+ linkifyBareUrls(doc.body);+ wrapInlineRuns(doc.body);+}++/**+ * Reduce a stored description — provider text, provider HTML, or this+ * editor's own output — to the portable subset. A description without any+ * HTML tag is plain text: its angle brackets are kept as text and its line+ * breaks become `<br>`.+ *+ * Safe to render with `innerHTML`: active elements, event handlers, and+ * non-http(s)/mailto/tel links never survive.+ */+export function sanitizeCalendarDescription(raw: string): string {+ if (raw.trim() === '') return '';+ const plainText = !HTML_TAG_PATTERN.test(raw);+ const doc = plainText ? parsePlainText(raw) : parseHtml(raw);+ sanitizeDocument(doc, plainText);+ return doc.body.innerHTML;+}diff --git a/apps/web/src/features/calendar/utils/calendar-description.ts b/apps/web/src/features/calendar/utils/calendar-description.tsindex aea9698b27..becdc45ebf 100644--- a/apps/web/src/features/calendar/utils/calendar-description.ts+++ b/apps/web/src/features/calendar/utils/calendar-description.ts@@ -1,361 +1,20 @@-import { findNextAutoLinkMatch } from '@core/component/LexicalMarkdown/plugins/links/linksPlugin';import { editorIsEmpty } from '@core/component/LexicalMarkdown/utils';import { convertDocumentMentionsToLinks } from '@core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks';import { getWebOrigin } from '@core/util/webOrigin';import { $generateHtmlFromNodes } from '@lexical/html';import type { LexicalEditor } from 'lexical';-/**- * Formatting a description keeps across the provider boundary. Anything the- * editor or a provider adds beyond this — classes, inline styles, mention- * data attributes, media, scripts — is dropped, so the stored string is- * portable HTML that carries no reader or author identities.- */-const KEPT_TAGS = new Set([- 'p',- 'br',- 'a',- 'b',- 'strong',- 'i',- 'em',- 'u',- 's',- 'ul',- 'ol',- 'li',-]);-const INLINE_TAGS = new Set(['a', 'b', 'strong', 'i', 'em', 'u', 's', 'br']);-const LIST_TAGS = new Set(['ul', 'ol']);-/** Containers whose line structure is worth keeping as a paragraph. */-const PARAGRAPH_LIKE_TAGS = new Set([- 'div',- 'h1',- 'h2',- 'h3',- 'h4',- 'h5',- 'h6',- 'pre',- 'blockquote',- 'address',- 'section',- 'article',- 'header',- 'footer',- 'figure',- 'figcaption',- 'tr',- 'dt',- 'dd',- 'summary',- 'details',-]);-/** Removed together with their content. */-const DROPPED_TAGS = new Set([- 'script',- 'style',- 'iframe',- 'frame',- 'frameset',- 'object',- 'embed',- 'applet',- 'base',- 'meta',- 'link',- 'noscript',- 'template',- 'svg',- 'math',- 'head',- 'title',- 'textarea',- 'select',- 'option',- 'input',- 'button',- 'form',- 'img',- 'picture',- 'source',- 'video',- 'audio',- 'canvas',-]);-const LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']);+import {+ sanitizeCalendarDescription,+ sanitizeDocument,+} from './calendar-description-sanitizer';-/**- * A tag a description would only contain if it were authored as HTML. Plain- * text legitimately holds angle brackets — `<[email protected]>`, `<TBD>` — so- * "looks like a tag" is not enough to treat the whole string as markup.- */-const HTML_TAG_PATTERN =- /<(?:!--|\/?(?:a|abbr|b|big|blockquote|body|br|center|cite|code|dd|del|details|div|dl|dt|em|figure|font|h[1-6]|head|hr|html|i|iframe|img|ins|li|link|meta|ol|p|pre|s|script|section|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|template|tfoot|th|thead|title|tr|tt|u|ul)(?=[\s/>]))/i;+export { sanitizeCalendarDescription } from './calendar-description-sanitizer';function parseHtml(html: string): Document {return new DOMParser().parseFromString(html, 'text/html');}-/**- * Plain text is still parsed as HTML so provider-escaped entities decode, but- * its angle brackets are literal characters, never tags.- */-function parsePlainText(text: string): Document {- return parseHtml(text.replace(/</g, '<').replace(/>/g, '>'));-}--function safeHref(value: string | null): string | undefined {- if (!value) return undefined;- // Browsers tolerate whitespace and control characters inside a scheme- // ("java\nscript:"), so strip them before parsing.- const compact = Array.from(value)- .filter((char) => char.charCodeAt(0) > 0x20)- .join('');- try {- const url = new URL(compact);- return LINK_SCHEMES.has(url.protocol) ? url.href : undefined;- } catch {- return undefined;- }-}--function unwrap(element: Element) {- element.replaceWith(...Array.from(element.childNodes));-}--function isBlock(node: Node): boolean {- return (- node.nodeType === Node.ELEMENT_NODE &&- !INLINE_TAGS.has((node as Element).localName)- );-}--/** A paragraph left with nothing in it. `<p><br></p>` is a deliberate blank line and stays. */-function isEmptyParagraph(element: Element): boolean {- return (- element.localName === 'p' &&- element.firstElementChild === null &&- (element.textContent ?? '').trim() === ''- );-}--function replaceWithParagraph(element: Element) {- const paragraph = element.ownerDocument.createElement('p');- paragraph.append(...Array.from(element.childNodes));- if (isEmptyParagraph(paragraph)) {- element.remove();- return;- }- element.replaceWith(paragraph);-}--/** Convert newlines in text nodes to `<br>` for descriptions stored as plain text. */-function breakLines(parent: Node) {- const doc = parent.ownerDocument;- if (!doc) return;- const walker = doc.createTreeWalker(parent, NodeFilter.SHOW_TEXT);- const textNodes: Text[] = [];- for (let node = walker.nextNode(); node; node = walker.nextNode()) {- if ((node.textContent ?? '').includes('\n')) textNodes.push(node as Text);- }- for (const textNode of textNodes) {- const lines = (textNode.textContent ?? '').split('\n');- const replacement: Node[] = [];- lines.forEach((line, index) => {- if (index > 0) replacement.push(doc.createElement('br'));- if (line) replacement.push(doc.createTextNode(line));- });- textNode.replaceWith(...replacement);- }-}--/** Lists may only hold list items, and list items only live inside lists. */-function normalizeList(list: Element) {- const doc = list.ownerDocument;- let orphanItem: Element | undefined;- for (const child of Array.from(list.childNodes)) {- if (child.nodeType === Node.ELEMENT_NODE) {- const element = child as Element;- if (element.localName === 'li') {- orphanItem = undefined;- continue;- }- if (LIST_TAGS.has(element.localName)) {- // A nested list belongs to the preceding item.- const previous = element.previousElementSibling;- if (previous?.localName === 'li') {- previous.appendChild(element);- continue;- }- }- } else if ((child.textContent ?? '').trim() === '') {- child.remove();- continue;- }- if (!orphanItem) {- orphanItem = doc.createElement('li');- list.insertBefore(orphanItem, child);- }- orphanItem.appendChild(child);- }-}--function sanitizeChildren(parent: Element) {- for (const child of Array.from(parent.childNodes)) {- if (child.nodeType === Node.TEXT_NODE) continue;- if (child.nodeType !== Node.ELEMENT_NODE) {- child.remove();- continue;- }- const element = child as Element;- const tag = element.localName;- if (DROPPED_TAGS.has(tag)) {- element.remove();- continue;- }- sanitizeChildren(element);-- if (KEPT_TAGS.has(tag)) {- const href = tag === 'a' ? safeHref(element.getAttribute('href')) : null;- for (const name of element.getAttributeNames()) {- element.removeAttribute(name);- }- if (tag === 'a') {- if (!href) {- unwrap(element);- continue;- }- element.setAttribute('href', href);- }- if (tag === 'li' && !LIST_TAGS.has(parent.localName)) {- replaceWithParagraph(element);- continue;- }- if (tag === 'p' && isEmptyParagraph(element)) {- element.remove();- continue;- }- if (LIST_TAGS.has(tag)) normalizeList(element);- continue;- }-- if (- PARAGRAPH_LIKE_TAGS.has(tag) &&- !Array.from(element.childNodes).some(isBlock)- ) {- replaceWithParagraph(element);- continue;- }- unwrap(element);- }-}--/** Gather top-level runs of text and inline elements into paragraphs. */-function wrapInlineRuns(parent: Element) {- const doc = parent.ownerDocument;- let run: Node[] = [];- const flush = () => {- if (run.length === 0) return;- const hasContent = run.some((node) =>- node.nodeType === Node.ELEMENT_NODE- ? (node as Element).localName !== 'br'- : (node.textContent ?? '').trim() !== ''- );- if (hasContent) {- const paragraph = doc.createElement('p');- parent.insertBefore(paragraph, run[0]);- paragraph.append(...run);- } else {- for (const node of run) node.parentNode?.removeChild(node);- }- run = [];- };- for (const child of Array.from(parent.childNodes)) {- if (isBlock(child)) {- flush();- continue;- }- run.push(child);- }- flush();-}--/** The autolink strictness shared by the app's editors: bare hosts on common- * TLDs link, but code-like tokens such as `parser.ts` do not. */-const DESCRIPTION_AUTO_LINK_MODE = 'common-tlds';--/**- * Wrap the URLs and bare emails in a plain-text string as anchors so the detail- * view can open them — emails become `mailto:` links, which `openExternalUrl`- * routes to the in-app composer. Returns null when nothing was linked so the- * caller can leave the original text node untouched.- */-function linkifyText(text: string, doc: Document): Node[] | null {- const nodes: Node[] = [];- let rest = text;- let linked = false;- while (rest) {- const match = findNextAutoLinkMatch(rest, DESCRIPTION_AUTO_LINK_MODE);- if (!match || match.lastIndex <= match.index) {- nodes.push(doc.createTextNode(rest));- break;- }- linked = true;- const before = rest.slice(0, match.index);- if (before) nodes.push(doc.createTextNode(before));- const anchor = doc.createElement('a');- anchor.setAttribute('href', match.url);- anchor.textContent = rest.slice(match.index, match.lastIndex);- nodes.push(anchor);- rest = rest.slice(match.lastIndex);- }- return linked ? nodes : null;-}--/** Turn bare URLs in text into anchors, leaving text inside existing links alone. */-function linkifyBareUrls(body: HTMLElement) {- const doc = body.ownerDocument;- const walker = doc.createTreeWalker(body, NodeFilter.SHOW_TEXT, {- acceptNode: (node) =>- node.parentElement?.closest('a')- ? NodeFilter.FILTER_REJECT- : NodeFilter.FILTER_ACCEPT,- });- const textNodes: Text[] = [];- for (let node = walker.nextNode(); node; node = walker.nextNode()) {- textNodes.push(node as Text);- }- for (const textNode of textNodes) {- const replacement = linkifyText(textNode.textContent ?? '', doc);- if (replacement) textNode.replaceWith(...replacement);- }-}--function sanitizeDocument(doc: Document, plainText: boolean) {- if (plainText) breakLines(doc.body);- sanitizeChildren(doc.body);- linkifyBareUrls(doc.body);- wrapInlineRuns(doc.body);-}--/**- * Reduce a stored description — provider text, provider HTML, or this- * editor's own output — to the portable subset. A description without any- * HTML tag is plain text: its angle brackets are kept as text and its line- * breaks become `<br>`.- *- * Safe to render with `innerHTML`: active elements, event handlers, and- * non-http(s)/mailto/tel links never survive.- */-export function sanitizeCalendarDescription(raw: string): string {- if (raw.trim() === '') return '';- const plainText = !HTML_TAG_PATTERN.test(raw);- const doc = plainText ? parsePlainText(raw) : parseHtml(raw);- sanitizeDocument(doc, plainText);- return doc.body.innerHTML;-}-const APP_LINK_PATTERN = /^\/app\/([a-z0-9_-]+)\/([A-Za-z0-9_-]+)\/?$/i;/** Which Macro entity an `/app/<block>/<id>` link opens, if it is one. */diff --git a/apps/web/src/features/email-message/components/calendar-invite-card.test.tsx b/apps/web/src/features/email-message/components/calendar-invite-card.test.tsxindex c0ec466a0f..1f3c5d413c 100644--- a/apps/web/src/features/email-message/components/calendar-invite-card.test.tsx+++ b/apps/web/src/features/email-message/components/calendar-invite-card.test.tsx@@ -14,7 +14,10 @@ vi.mock('@ui', async () => ({<button {...props} />),}));-afterEach(cleanup);+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});const resolved: InvitationResolution = {kind: 'resolved',eventId: 'event',@@ -158,4 +161,117 @@ describe('native invitation card', () => {expect(screen.queryByRole('button', { name: 'Yes' })).toBeNull();expect(screen.getByText(/Responses are paused/)).toBeTruthy();});+ it('renders formatted descriptions and keeps lists outside paragraphs', () => {+ const htmlInvitation = {+ ...invitationFixture,+ description:+ '<p>Meeting details with <strong>bold</strong> and <a href="https://example.com">link</a></p><ul><li>First item</li><li>Second item</li></ul>',+ };+ render(() => <CalendarInviteCard invitation={htmlInvitation} />);+ const description = screen.getByText(/Meeting details/);+ expect(description.querySelector('strong')?.textContent).toBe('bold');+ expect(+ screen.getByRole('link', { name: 'link' }).getAttribute('href')+ ).toBe('https://example.com/');+ expect(+ screen.getByText('First item').closest('ul')?.previousElementSibling+ ).toBe(description);+ expect(screen.getByText('Second item').tagName).toBe('LI');+ expect(description.textContent).not.toContain('<strong>');+ });+ it('removes active markup and unsafe URLs from descriptions', () => {+ const { container } = render(() => (+ <CalendarInviteCard+ invitation={{+ ...invitationFixture,+ description:+ '<p onclick="alert(1)">Safe text<script>alert(1)</script><img src="x" onerror="alert(1)"><a href="javascript:alert(1)">unsafe link</a></p>',+ }}+ />+ ));+ expect(screen.getByText(/Safe text/).textContent).toBe(+ 'Safe textunsafe link'+ );+ expect(+ container.querySelector('script, img, [onclick], [onerror]')+ ).toBeNull();+ expect(screen.queryByRole('link', { name: 'unsafe link' })).toBeNull();+ });+ it.each([+ 'https://example.com/',+ 'mailto:[email protected]',+ 'tel:+15555550100',+ ])('opens description links through the host: %s', (url) => {+ const openExternal = vi.fn();+ render(() => (+ <CalendarInviteCard+ invitation={{+ ...invitationFixture,+ description: `<p><a href="${url}"><strong>Details</strong></a></p>`,+ }}+ actions={{ openExternal }}+ />+ ));+ expect(fireEvent.click(screen.getByText('Details'))).toBe(false);+ expect(openExternal).toHaveBeenCalledExactlyOnceWith(url);+ });+ it('opens links in a new tab when the card has no host action', () => {+ const open = vi.spyOn(window, 'open').mockReturnValue(null);+ render(() => (+ <CalendarInviteCard+ invitation={{+ ...invitationFixture,+ description: '<p><a href="https://example.com">Meeting notes</a></p>',+ }}+ />+ ));+ expect(+ fireEvent.click(screen.getByRole('link', { name: 'Meeting notes' }))+ ).toBe(false);+ expect(open).toHaveBeenCalledExactlyOnceWith(+ 'https://example.com/',+ '_blank',+ 'noopener,noreferrer'+ );+ });+ it('escapes angle brackets in plain text descriptions', () => {+ const plainTextInvitation = {+ ...invitationFixture,+ description: 'Email <[email protected]> for questions\nOwner: <TBD>',+ };+ render(() => <CalendarInviteCard invitation={plainTextInvitation} />);+ const description = screen.getByText(/Email/);+ expect(description.textContent).toContain('<[email protected]>');+ expect(description.textContent).toContain('Owner: <TBD>');+ expect(description.querySelector('br')).not.toBeNull();+ expect(description.querySelector('bob, tbd')).toBeNull();+ });+ it('updates the sanitized description when the calendar resolves newer details', () => {+ const [resolution, setResolution] = createSignal<InvitationResolution>({+ kind: 'loading',+ });+ render(() => (+ <CalendarInviteCard+ invitation={{+ ...invitationFixture,+ description: '<p>Original details</p>',+ }}+ actions={{+ get resolution() {+ return resolution();+ },+ }}+ />+ ));+ expect(screen.getByText('Original details')).toBeTruthy();+ setResolution({+ ...resolved,+ current: {+ ...invitationFixture,+ description: '<p><strong>Updated details</strong></p>',+ },+ });+ expect(screen.queryByText('Original details')).toBeNull();+ expect(screen.getByText('Updated details').tagName).toBe('STRONG');+ });});diff --git a/apps/web/src/features/email-message/components/calendar-invite-card.tsx b/apps/web/src/features/email-message/components/calendar-invite-card.tsxindex aaa07ae59d..f4da6aa19b 100644--- a/apps/web/src/features/email-message/components/calendar-invite-card.tsx+++ b/apps/web/src/features/email-message/components/calendar-invite-card.tsx@@ -1,3 +1,4 @@+import { openExternalUrl } from '@core/util/url';import CalendarBlank from '@phosphor/calendar-blank.svg';import Check from '@phosphor/check.svg';import Clock from '@phosphor/clock.svg';@@ -8,8 +9,9 @@ import Users from '@phosphor/users.svg';import VideoCamera from '@phosphor/video-camera.svg';import X from '@phosphor/x.svg';import { Button } from '@ui';-import { createSignal, For, type JSX, Show } from 'solid-js';+import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';import { match } from 'ts-pattern';+import { sanitizeCalendarDescription } from '../../calendar/utils/calendar-description-sanitizer';import {type CalendarInvitation,type CalendarInvitationActions,@@ -50,7 +52,7 @@ function MetaRow(props: { icon: JSX.Element; children: JSX.Element }) {);}-/** Native host UI: no provider fetches, parser, grid, or HTML injection. */+/** Native host UI with sanitized descriptions and host-supplied actions. */export function CalendarInviteCard(props: {invitation: CalendarInvitation;actions?: CalendarInvitationActions;@@ -65,6 +67,16 @@ export function CalendarInviteCard(props: {};const invite = () =>displayedInvitation(props.invitation, props.actions?.resolution);+ const descriptionHtml = createMemo(() =>+ sanitizeCalendarDescription(invite().description ?? '')+ );+ const openDescriptionLink = (event: MouseEvent) => {+ const anchor =+ event.target instanceof Element ? event.target.closest('a[href]') : null;+ if (!(anchor instanceof HTMLAnchorElement)) return;+ event.preventDefault();+ (props.actions?.openExternal ?? openExternalUrl)(anchor.href);+ };const cancelled = () =>props.actions?.resolution?.kind === 'cancelled' ||invitationIsCancelled(props.invitation) ||@@ -236,12 +248,12 @@ export function CalendarInviteCard(props: {</ul><Show when={!cancelled() && invite().description}><div class="flex flex-col items-start gap-1.5">- <p- class="whitespace-pre-wrap break-words text-ink-muted [overflow-wrap:anywhere]"+ <div+ class="break-words text-ink-muted [overflow-wrap:anywhere] [&_a]:text-accent [&_a]:underline [&_ul]:list-disc [&_ul]:pl-6 [&_ol]:list-decimal [&_ol]:pl-6"classList={{ 'line-clamp-2': !descriptionExpanded() }}- >- {invite().description}- </p>+ innerHTML={descriptionHtml()}+ onClick={openDescriptionLink}+ /><Buttonvariant="ghost"class="h-auto border-0 p-0 text-xs font-medium text-accent"diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.tsnew file mode 100644index 0000000000..db08942a05--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/autoLink.ts@@ -0,0 +1,108 @@+import linkify, { type Match } from 'linkify-it';++export const strictLinkifier = new linkify(undefined, {+ fuzzyLink: false,+});++const commonTldLinkifier = new linkify(undefined, {+ fuzzyLink: true,+}).tlds(+ [+ 'app',+ 'biz',+ 'ca',+ 'co',+ 'com',+ 'dev',+ 'edu',+ 'gov',+ 'info',+ 'io',+ 'me',+ 'net',+ 'org',+ 'shop',+ 'site',+ 'store',+ 'tv',+ 'uk',+ 'us',+ 'xyz',+ ],+ false+);++const fuzzyLinkifier = new linkify(undefined, {+ fuzzyLink: true,+});++export type AutoLinkMatchMode = 'protocol' | 'common-tlds' | 'fuzzy';++function getAutoLinkifier(mode: AutoLinkMatchMode) {+ switch (mode) {+ case 'common-tlds':+ return commonTldLinkifier;+ case 'fuzzy':+ return fuzzyLinkifier;+ case 'protocol':+ return strictLinkifier;+ }+}++const ALLOWED_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);+const URL_SCHEME_PATTERN = /^([a-z][a-z\d+.-]*):/i;++/**+ * Normalize user-entered links and reject protocols that links must not open.+ * Bare hosts retain the existing behavior of defaulting to HTTPS.+ */+export function normalizeLinkUrl(input: string): string | null {+ const trimmed = input.trim();+ if (!trimmed) return null;++ // The URL parser ignores ASCII tabs and newlines in protocols. Use the same+ // view when detecting a scheme so values such as `java\nscript:` cannot be+ // mistaken for a bare host and rewritten as HTTPS.+ const schemeProbe = trimmed.replace(/[\t\n\r]/g, '');+ const schemeMatch = URL_SCHEME_PATTERN.exec(schemeProbe);+ const scheme = schemeMatch?.[1]?.toLowerCase();+ const remainder = schemeMatch ? schemeProbe.slice(schemeMatch[0].length) : '';+ const isHostWithPort =+ scheme !== undefined &&+ (scheme === 'localhost' || scheme.includes('.')) &&+ /^\d+(?:[/?#]|$)/.test(remainder);+ const candidate = scheme && !isHostWithPort ? trimmed : `https://${trimmed}`;++ try {+ const parsed = new URL(candidate);+ if (!ALLOWED_LINK_PROTOCOLS.has(parsed.protocol)) return null;++ if (parsed.protocol === 'mailto:') return trimmed;++ const [basePath, ...queryParts] = candidate.split(/([#?])/);+ const encodedBase = basePath+ .split('/')+ .map((segment) => (segment.includes(':') ? segment : encodeURI(segment)))+ .join('/');+ return encodedBase + queryParts.join('');+ } catch {+ return null;+ }+}++export function findNextAutoLinkMatch(+ text: string,+ mode: AutoLinkMatchMode = 'protocol'+): Match | null {+ const linkifier = getAutoLinkifier(mode);+ if (!linkifier.test(text)) return null;+ const match = linkifier.match(text);+ if (!match) return null;+ const firstMatch = match[0];+ const url = normalizeLinkUrl(+ firstMatch.schema === '' ? firstMatch.raw : firstMatch.url+ );+ if (!url) return null;+ firstMatch.url = url;+ return firstMatch;+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.tsindex 698e79f27d..865eb38b81 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts@@ -31,97 +31,18 @@ import {PASTE_COMMAND,TextNode,} from 'lexical';-import linkify, { type Match } from 'linkify-it';--const strictLinkifier = new linkify(undefined, {- fuzzyLink: false,-});--const commonTldLinkifier = new linkify(undefined, {- fuzzyLink: true,-}).tlds(- [- 'app',- 'biz',- 'ca',- 'co',- 'com',- 'dev',- 'edu',- 'gov',- 'info',- 'io',- 'me',- 'net',- 'org',- 'shop',- 'site',- 'store',- 'tv',- 'uk',- 'us',- 'xyz',- ],- false-);--const fuzzyLinkifier = new linkify(undefined, {- fuzzyLink: true,-});--export type AutoLinkMatchMode = 'protocol' | 'common-tlds' | 'fuzzy';--function getAutoLinkifier(mode: AutoLinkMatchMode) {- switch (mode) {- case 'common-tlds':- return commonTldLinkifier;- case 'fuzzy':- return fuzzyLinkifier;- case 'protocol':- return strictLinkifier;- }-}--const ALLOWED_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);-const URL_SCHEME_PATTERN = /^([a-z][a-z\d+.-]*):/i;--/**- * Normalize user-entered links and reject protocols that links must not open.- * Bare hosts retain the existing behavior of defaulting to HTTPS.- */-export function normalizeLinkUrl(input: string): string | null {- const trimmed = input.trim();- if (!trimmed) return null;-- // The URL parser ignores ASCII tabs and newlines in protocols. Use the same- // view when detecting a scheme so values such as `java\nscript:` cannot be- // mistaken for a bare host and rewritten as HTTPS.- const schemeProbe = trimmed.replace(/[\t\n\r]/g, '');- const schemeMatch = URL_SCHEME_PATTERN.exec(schemeProbe);- const scheme = schemeMatch?.[1]?.toLowerCase();- const remainder = schemeMatch ? schemeProbe.slice(schemeMatch[0].length) : '';- const isHostWithPort =- scheme !== undefined &&- (scheme === 'localhost' || scheme.includes('.')) &&- /^\d+(?:[/?#]|$)/.test(remainder);- const candidate = scheme && !isHostWithPort ? trimmed : `https://${trimmed}`;-- try {- const parsed = new URL(candidate);- if (!ALLOWED_LINK_PROTOCOLS.has(parsed.protocol)) return null;-- if (parsed.protocol === 'mailto:') return trimmed;-- const [basePath, ...queryParts] = candidate.split(/([#?])/);- const encodedBase = basePath- .split('/')- .map((segment) => (segment.includes(':') ? segment : encodeURI(segment)))- .join('/');- return encodedBase + queryParts.join('');- } catch {- return null;- }-}+import {+ type AutoLinkMatchMode,+ findNextAutoLinkMatch,+ normalizeLinkUrl,+ strictLinkifier,+} from './autoLink';++export {+ type AutoLinkMatchMode,+ findNextAutoLinkMatch,+ normalizeLinkUrl,+} from './autoLink';/*** Link information interface between lexical and the UI.@@ -183,23 +104,6 @@ function getLinkFromDom(};}-export function findNextAutoLinkMatch(- text: string,- mode: AutoLinkMatchMode = 'protocol'-): Match | null {- const linkifier = getAutoLinkifier(mode);- if (!linkifier.test(text)) return null;- const match = linkifier.match(text);- if (!match) return null;- const firstMatch = match[0];- const url = normalizeLinkUrl(- firstMatch.schema === '' ? firstMatch.raw : firstMatch.url- );- if (!url) return null;- firstMatch.url = url;- return firstMatch;-}-function $handleAppendToMatch(prevSibling: AutoLinkNode,textNode: TextNode,diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex c3742f61f3..e3bcc05efc 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2888,6 +2888,11 @@ after the feature shipped gets a card; older invitations render as plain email.A newly arrived scheduling update shows RSVP and Join only once its calendar state hasbeen checked. A series invitation shows its current or next live occurrence.+Descriptions render sanitized rich text, including emphasis, links, and lists.+Plain-text line breaks and literal angle brackets (such as `<[email protected]>`)+remain readable. Use `Show more` / `Show less` to expand or collapse the description;+description links use the host's normal link-opening behavior.+A connected, resolved invitation shows the responding address and Yes / Maybe / No.Calendars connected through a linked inbox also resolve here, using that inbox'saddress for responses. Access is limited to the delegated inbox; another inbox owned