Skip to content

Commit f3044f7

Browse files
fix(fields): sanitize html and richtext values with rehype-sanitize (#13431)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoB32mdoaBcgWwPv4cxRdT6W)_ ## What The `html` / `richtext` display pipeline (`HtmlCellRenderer`, used by the grid, kanban, detail and readonly form surfaces) now sanitizes stored values with `rehype-sanitize`, the sanitizer `@object-ui/fields` already ships for its `markdown` pipeline, instead of a hand-written pattern filter. How a value reaches the DOM (new module `packages/fields/src/widgets/sanitizedHtml.tsx`): 1. Parse with the browser's own parser (`DOMParser`, `text/html`). A parsed document has no browsing context, so nothing in it runs or loads. 2. Convert the DOM nodes to hast. `hastscript` maps attribute names to the property names the schema is written in. 3. Sanitize with `rehype-sanitize` and `RICH_TEXT_SANITIZE_SCHEMA`: the GitHub-style `defaultSchema`, with script, style, frame, object, embed, template, SVG and MathML elements removed together with their content. 4. Render the sanitized tree as React elements with `hast-util-to-jsx-runtime`, the renderer `react-markdown` uses. The renderer no longer uses `dangerouslySetInnerHTML`. One sanitizer: `MarkdownContent` now passes the same `RICH_TEXT_SANITIZE_SCHEMA` to `rehype-sanitize`, so both display pipelines read one allow-list. **Dependencies:** no new sanitizer. `hastscript` and `hast-util-to-jsx-runtime` become direct dependencies of `@object-ui/fields`. Both were already in the lockfile at the same versions (`react-markdown` and `rehype-sanitize` already pull them in), so the lockfile diff only records the two importer entries. **Behaviour changes a reader can see:** - A link whose URL is refused renders without an `href`. The old filter rewrote it to `#`. - Stored `id` and `name` values are prefixed with `user-content-`. - `style`, `class` outside the schema's few named values, and elements outside the allow-list (for example `u`, `font`) are dropped; the text inside an unknown element is kept. - With no `DOMParser` (a non-browser render) the value renders as plain text. ## Tests - New `packages/fields/src/widgets/__tests__/sanitizedHtml.test.tsx` renders through `HtmlCellRenderer` and checks the DOM structurally: no `on*` attribute, no script-bearing URL in any URL attribute, no embedding or foreign-content element, no `style`. It covers each class of markup that can carry script: attributes, URLs, SVG and MathML, embedding elements, styles, and form and navigation elements. A formatted document (headings, emphasis, links, nested lists, quote, code block, table with `align` and `colspan`, image, rule, definition list, details) round-trips byte for byte. - Three existing pins expected the old `href="#"` rewrite. `cellRenderers.childlessContainer-8580` now pins the new sanitizer's bytes, and the 5452 / 5498 pins read a dropped `href` as empty. ## Gates (local, at the head of this branch) - `pnpm exec vitest run packages/fields/`: 276 files passed, 1 skipped; 4286 tests passed, 7 skipped - `pnpm --filter @object-ui/fields type-check` and `lint`: exit 0 - the richtext consumers in `app-shell`, `plugin-grid`, `plugin-detail`, `plugin-form`, `components` and `apps/console`: 7 files, 59 tests passed - `check:phantom-deps`, `check:unused-deps`, `check:lockfile-integrity`, `check:lockfile-dedupe`, `check:new-line-citations`, `check:control-bytes`, `check-changeset-presence`, `check-changeset-no-major`, `check:changeset-claims`, `check:pending-changeset-literals`, `check:test-path-roots`, `check:unreferenced-sources`, `check:esm-specifiers`, `check:node-esm-load`, `check:side-effects-array`, `check:sdui-registration-pins`, `check:docs-route-closure`, `check:readme-exports`, `check:eager-closure`, `check:shell-escape-residue`, `check:doc-fences`, `check:doc-json`, `check:doc-snippets`: all exit 0 - `check-governed-queue-guard --test` on the diff: not a governed surface ## Bundle Measured with `node scripts/check-eager-closure-budget.mjs` on a local console build, this branch against its base with only `packages/fields/src` swapped: the eager closure is about 1.0 KB gzipped smaller. `ui-components` grows by about 0.3 KB and `vendor-markdown` shrinks by about 1.3 KB, because the hast utilities were already in the eager `vendor-markdown` chunk. The `Bundle Analysis` check on this PR is the live reading. ## Other `dangerouslySetInnerHTML` sites in `packages/` None of the others renders a stored field value, so this PR leaves them alone. They render author metadata, translation strings, generated CSS, Mermaid SVG (`securityLevel: 'strict'`) or highlighter output, or an escaped preview of the comment input. ## Checklist - [x] Adds no product-specific widget, dialog, hook or string (see AGENTS.md › Product-neutral renderer) Draft: this is a security-boundary change and waits for the maintainer's approval before it is marked ready. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Fw91y6wN8SAu43vfrsAqHg Co-authored-by: Claude <noreply@anthropic.com>
1 parent 06ce712 commit f3044f7

12 files changed

Lines changed: 422 additions & 48 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
`html` and `richtext` values are now sanitized with `rehype-sanitize`, the sanitizer the `markdown` pipeline already used, instead of a hand-written pattern filter.
6+
7+
A stored value is parsed with the browser's HTML parser, filtered against one allow-list of elements, attributes and URL protocols, and rendered as React elements. Both display pipelines share that allow-list. Headings, paragraphs, emphasis, lists, quotes, code, tables, links and images keep their formatting. Event-handler attributes, `style`, script-bearing URLs, embedded frames and objects, and SVG and MathML content are dropped. A link whose URL is refused now renders without an `href`, where it used to point at `#`. Stored `id` and `name` values are prefixed with `user-content-`.

‎content/docs/fields/rich-text.mdx‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,14 @@ metadata keys — they are runtime widget props. See [Field Widget Props](/docs/
9494
- **Tables**: Markdown tables
9595

9696
### HTML
97-
- Full HTML editing support
98-
- Sanitization for security
99-
- Style preservation
100-
- Embedded media support
97+
- Headings, paragraphs, emphasis, lists, quotes, code, tables, links and images
98+
- Sanitized on display against an allow-list (`rehype-sanitize`, GitHub-style):
99+
links keep `http`, `https`, `mailto` and relative URLs, and images keep `http`,
100+
`https` and relative URLs
101+
- Inline `style`, event-handler attributes, embedded frames, objects and SVG or
102+
MathML content are not rendered; an element outside the allow-list shows its text
103+
without its tag
104+
- The `markdown` and `html` / `richtext` display pipelines share the same allow-list
101105

102106
## Cell Renderer
103107

‎packages/fields/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838
"@object-ui/react": "workspace:*",
3939
"@object-ui/types": "workspace:*",
4040
"@objectstack/spec": "^18.0.0-next.1",
41+
"hast-util-to-jsx-runtime": "^2.3.6",
42+
"hastscript": "^9.0.1",
4143
"lucide-react": "^1.43.0",
4244
"react-markdown": "^10.1.0",
4345
"rehype-sanitize": "^6.0.0",

‎packages/fields/src/__tests__/cellRenderers.childlessContainer-8580.test.tsx‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
* case in this file. What refuses it is the POPULATED block: real markdown
5252
* still renders its elements, real HTML still renders SANITISED — pinned to
5353
* the sanitiser's exact output bytes, so a repair that shortcut the populated
54-
* branch past `sanitizeHtml` fails on bytes, not on a count — and real
54+
* branch past the sanitizer fails on bytes, not on a count — and real
5555
* richtext still renders. Each was RUN against the caricature; the observed
5656
* failure sentences are recorded in the PR.
5757
*
@@ -127,8 +127,8 @@ const HOSTILE_HTML =
127127
'<img src="x" onerror="alert(2)">' +
128128
'<a href="javascript:alert(3)">go</a>';
129129

130-
/** What `sanitizeHtml` makes of {@link HOSTILE_HTML} — the bytes, not a count. */
131-
const HOSTILE_HTML_SANITISED = '<p>ok</p><img src="x"><a href="#">go</a>';
130+
/** What the sanitizer makes of {@link HOSTILE_HTML} — the bytes, not a count. */
131+
const HOSTILE_HTML_SANITISED = '<p>ok</p><img src="x"><a>go</a>';
132132

133133
/** What a WYSIWYG editor actually emits, beyond the seed's two tags. */
134134
const WYSIWYG_DOCUMENT = [
@@ -241,10 +241,10 @@ describe('objectui#8580 — a rich-content cell holding [] or {} says what it ho
241241

242242
const prose = container.querySelector('div.prose');
243243
expect(prose, 'html: a populated value must still open its prose container').not.toBeNull();
244-
// The bytes, not a count: this is what `sanitizeHtml` produces for the
244+
// The bytes, not a count: this is what the sanitizer produces for the
245245
// hostile document, so a populated branch that stopped running through
246246
// it — or a sanitiser that changed — fails here on content.
247-
expect(prose?.innerHTML, 'html: the populated branch must still run through sanitizeHtml').toBe(HOSTILE_HTML_SANITISED);
247+
expect(prose?.innerHTML, 'html: the populated branch must still run through the sanitizer').toBe(HOSTILE_HTML_SANITISED);
248248
expect(prose?.querySelector('script'), 'html: script blocks must still be stripped').toBeNull();
249249
expect(affordance(container), 'html: a populated value must NOT render the affordance').toBeNull();
250250
});
@@ -254,7 +254,7 @@ describe('objectui#8580 — a rich-content cell holding [] or {} says what it ho
254254

255255
const prose = container.querySelector('div.prose');
256256
expect(prose, 'richtext: a populated value must still open its prose container').not.toBeNull();
257-
expect(prose?.innerHTML, 'richtext: the populated branch must still run through sanitizeHtml').toBe(HOSTILE_HTML_SANITISED);
257+
expect(prose?.innerHTML, 'richtext: the populated branch must still run through the sanitizer').toBe(HOSTILE_HTML_SANITISED);
258258
expect(affordance(container), 'richtext: a populated value must NOT render the affordance').toBeNull();
259259
});
260260

‎packages/fields/src/__tests__/readonly-richtext-display-5498.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,8 @@ describe('negative controls — nothing else became a markup renderer (objectui#
230230
expect(prose.querySelector('script')).toBeNull();
231231
expect(prose.innerHTML).not.toContain('alert(1)');
232232
expect(prose.innerHTML).not.toContain('onerror');
233-
expect(prose.querySelector('a')?.getAttribute('href')).not.toContain('javascript:');
233+
// A dropped `href` reads `null`; a rewritten one must not name the scheme.
234+
expect(prose.querySelector('a')?.getAttribute('href') ?? '').not.toContain('javascript:');
234235
// …and the benign content around it survived, so the assertion above is
235236
// not passing because the whole value was dropped.
236237
expect(prose.textContent).toContain('ok');

‎packages/fields/src/__tests__/richtext-cell-renderer-5452.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,8 @@ describe('rich-content cell renderers (objectui#5452)', () => {
125125

126126
expect(prose.querySelector('script')).toBeNull();
127127
expect(prose.innerHTML).not.toContain('onerror');
128-
expect(prose.querySelector('a')?.getAttribute('href')).not.toContain('javascript:');
128+
// A dropped `href` reads `null`; a rewritten one must not name the scheme.
129+
expect(prose.querySelector('a')?.getAttribute('href') ?? '').not.toContain('javascript:');
129130
expect(prose.textContent).toContain('ok');
130131
});
131132

‎packages/fields/src/widgets/MarkdownContent.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,18 @@ import React from 'react';
22
import ReactMarkdown from 'react-markdown';
33
import remarkGfm from 'remark-gfm';
44
import rehypeSanitize from 'rehype-sanitize';
5+
import { RICH_TEXT_SANITIZE_SCHEMA } from './sanitizedHtml.js';
56

67
/**
78
* Heavy markdown renderer, split into its own module so it can be lazy-loaded
89
* by the cell/detail renderers (react-markdown pulls in ~100-200 KB). GitHub
9-
* Flavored Markdown + sanitization (defense against XSS in stored content).
10+
* Flavored Markdown + sanitization (defense against XSS in stored content),
11+
* against the same schema the `html` / `richtext` pipeline uses.
1012
*/
1113
export default function MarkdownContent({ value }: { value: string }) {
1214
return (
1315
<div className="prose prose-sm max-w-none dark:prose-invert break-words">
14-
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}>
16+
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[[rehypeSanitize, RICH_TEXT_SANITIZE_SCHEMA]]}>
1517
{value}
1618
</ReactMarkdown>
1719
</div>

‎packages/fields/src/widgets/RichTextField.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ function resolveRichTextFieldType(field: unknown): string {
261261
* It now renders through {@link richTextCellRenderer} — literally the same
262262
* components `getCellRenderer` resolves, one table shared by both (see
263263
* `./richTextDisplay.tsx`), so the html/richtext path carries that renderer's
264-
* `sanitizeHtml` trust boundary rather than a second hand-rolled escape, and a
264+
* sanitizing trust boundary rather than a second hand-rolled escape, and a
265265
* future change to either pipeline moves both surfaces at once.
266266
*
267267
* ## Host plumbing (objectui#4810)
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* The `html` / `richtext` display pipeline's trust boundary
11+
* (`../sanitizedHtml.tsx`), read through the renderer every read surface uses.
12+
*
13+
* Two halves, and both are load-bearing:
14+
*
15+
* - HOSTILE: each class of stored markup that can carry script comes out
16+
* inert. The assertions are STRUCTURAL — no `on*` attribute anywhere, no
17+
* script-bearing URL in any attribute, none of the embedding / foreign
18+
* content elements, no `style` — read off the rendered DOM, so they hold
19+
* for any spelling of a payload within its class, not just the one
20+
* written here.
21+
* - FORMATTING: a representative rich-text document renders back byte for
22+
* byte. A sanitizer that drops everything passes the first half; this
23+
* half is what refuses it.
24+
*/
25+
26+
import React from 'react';
27+
import { describe, it, expect, afterEach } from 'vitest';
28+
import { render, cleanup } from '@testing-library/react';
29+
import '@testing-library/jest-dom';
30+
import { HtmlCellRenderer, RICH_TEXT_CELL_RENDERERS } from '../richTextDisplay';
31+
import { RICH_TEXT_SANITIZE_SCHEMA } from '../sanitizedHtml';
32+
33+
afterEach(cleanup);
34+
35+
function renderHtml(value: string): HTMLElement {
36+
const { container } = render(
37+
<HtmlCellRenderer value={value} field={{ name: 'notes', type: 'richtext' } as never} />,
38+
);
39+
const prose = container.querySelector<HTMLElement>('div.prose');
40+
expect(prose, 'a populated value opens its prose container').not.toBeNull();
41+
return prose!;
42+
}
43+
44+
/** Elements whose presence alone means the value was not neutralised. */
45+
const FORBIDDEN_ELEMENTS =
46+
'script, style, iframe, frame, object, embed, applet, svg, math, link, meta, base, form, template, noscript';
47+
48+
/** Attributes that take a URL, in either namespace. */
49+
const URL_ATTRIBUTES = ['href', 'src', 'action', 'formaction', 'data', 'xlink:href', 'srcset', 'cite', 'poster', 'background'];
50+
51+
/** Everything a hostile value must NOT have left in the DOM. */
52+
function expectInert(prose: HTMLElement, label: string) {
53+
expect(prose.querySelector(FORBIDDEN_ELEMENTS), `${label}: no embedding or foreign-content element`).toBeNull();
54+
for (const element of Array.from(prose.querySelectorAll('*'))) {
55+
for (const attribute of Array.from(element.attributes)) {
56+
const name = attribute.name.toLowerCase();
57+
expect(name.startsWith('on'), `${label}: <${element.localName}> keeps no ${name}`).toBe(false);
58+
expect(name, `${label}: <${element.localName}> keeps no style`).not.toBe('style');
59+
expect(name, `${label}: <${element.localName}> keeps no srcdoc`).not.toBe('srcdoc');
60+
if (URL_ATTRIBUTES.includes(name)) {
61+
// Normalised the way a URL parser reads it: control characters and
62+
// whitespace removed, case folded.
63+
const url = Array.from(attribute.value)
64+
.filter((char) => char.charCodeAt(0) > 0x20)
65+
.join('')
66+
.toLowerCase();
67+
expect(url, `${label}: <${element.localName} ${name}> is not a script URL`).not.toMatch(
68+
/^(javascript|vbscript|data):/,
69+
);
70+
}
71+
}
72+
}
73+
}
74+
75+
const HOSTILE: ReadonlyArray<readonly [string, string]> = [
76+
// Slash-separated attributes: no whitespace before the handler name.
77+
['slash-separated img handler', '<p>a</p><img/src=x/onerror=alert(1)>'],
78+
['slash-separated svg handler', '<svg/onload=alert(1)>'],
79+
['slash before a quoted handler', '<img src="x"/onerror="alert(1)">'],
80+
['handler on an allowed element', '<p onclick="alert(1)" onmouseover=alert(1)>text</p>'],
81+
['mixed-case handler', '<a href="https://x.test" OnClIcK="alert(1)">x</a>'],
82+
// Unquoted and otherwise disguised script URLs.
83+
['unquoted javascript href', '<a href=javascript:alert(1)>x</a>'],
84+
['mixed-case javascript href', '<a href="JaVaScRiPt:alert(1)">x</a>'],
85+
['leading-space javascript href', '<a href=" javascript:alert(1)">x</a>'],
86+
['tab inside the scheme', '<a href="java\tscript:alert(1)">x</a>'],
87+
['vbscript href', '<a href="vbscript:msgbox(1)">x</a>'],
88+
['data URL href', '<a href="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">x</a>'],
89+
['javascript img src', '<img src="javascript:alert(1)">'],
90+
// Entity-encoded schemes.
91+
['decimal-entity scheme', '<a href="&#106;avascript:alert(1)">x</a>'],
92+
['hex-entity scheme', '<a href="&#x6A;&#x61;&#x76;&#x61;script&colon;alert(1)">x</a>'],
93+
['entity-encoded tab in the scheme', '<a href="jav&#x09;ascript:alert(1)">x</a>'],
94+
['padded decimal entities', '<a href="&#0000106&#0000097vascript:alert(1)">x</a>'],
95+
// SVG and MathML.
96+
['svg animate handler', '<svg><animate onbegin=alert(1) attributeName=x dur=1s></svg>'],
97+
['svg link', '<svg><a xlink:href="javascript:alert(1)"><text x="0" y="20">x</text></a></svg>'],
98+
['svg set href', '<svg><a><set attributeName="href" to="javascript:alert(1)"/><text>x</text></a></svg>'],
99+
['svg foreignObject', '<svg><foreignObject><img src=x onerror=alert(1)></foreignObject></svg>'],
100+
['math link', '<math><mi xlink:href="javascript:alert(1)">x</mi></math>'],
101+
['math href', '<math href="javascript:alert(1)"><mtext>x</mtext></math>'],
102+
['math style breakout', '<math><mtext><table><mglyph><style><img src=x onerror=alert(1)>'],
103+
// Embedding elements.
104+
['iframe src', '<iframe src="javascript:alert(1)"></iframe>'],
105+
['iframe srcdoc', '<iframe srcdoc="<script>alert(1)</script>"></iframe>'],
106+
['object data', '<object data="javascript:alert(1)"></object>'],
107+
['embed src', '<embed src="javascript:alert(1)">'],
108+
['frameset', '<frameset onload=alert(1)><frame src="javascript:alert(1)"></frameset>'],
109+
// Styles.
110+
['style attribute with a script URL', '<div style="background:url(javascript:alert(1))">x</div>'],
111+
['style element with a script URL', '<style>p{background:url(javascript:alert(1))}</style><p>x</p>'],
112+
['style attribute with an expression', '<p style="width:expression(alert(1))">x</p>'],
113+
// Script and its neighbours.
114+
['script block', '<p>ok</p><script>alert(1)</script>'],
115+
['script with a src', '<script src="https://evil.test/x.js"></script>'],
116+
['nested script tags', '<scr<script>ipt>alert(1)</scr</script>ipt>'],
117+
['noscript breakout', '<noscript><p title="</noscript><img src=x onerror=alert(1)>">'],
118+
['template content', '<template><img src=x onerror=alert(1)></template>'],
119+
// Navigation and form vectors.
120+
['form action', '<form action="javascript:alert(1)"><button>go</button></form>'],
121+
['button formaction', '<button formaction="javascript:alert(1)">go</button>'],
122+
['meta refresh', '<meta http-equiv="refresh" content="0;url=javascript:alert(1)">'],
123+
['base href', '<base href="javascript:alert(1)//"><a href="/x">x</a>'],
124+
['link import', '<link rel="import" href="https://evil.test/x.html">'],
125+
['comment breakout', '<!--<img src="--><img src=x onerror=alert(1)//">'],
126+
];
127+
128+
describe('html / richtext display: stored markup comes out inert', () => {
129+
for (const [label, payload] of HOSTILE) {
130+
it(label, () => {
131+
expectInert(renderHtml(payload), label);
132+
});
133+
}
134+
135+
it('hides the body of a stripped element rather than printing it as text', () => {
136+
const prose = renderHtml('<p>kept</p><script>alert(1)</script><style>p{}</style><svg><text>svg</text></svg>');
137+
expect(prose.textContent).toBe('kept');
138+
});
139+
140+
it('prefixes stored ids so they cannot shadow the page’s own', () => {
141+
const prose = renderHtml('<h2 id="root">Title</h2><a name="main">x</a>');
142+
expect(prose.querySelector('h2')?.id).toBe('user-content-root');
143+
expect(prose.querySelector('a')?.getAttribute('name')).toBe('user-content-main');
144+
});
145+
146+
it('html and richtext share the one renderer', () => {
147+
expect(RICH_TEXT_CELL_RENDERERS.richtext).toBe(RICH_TEXT_CELL_RENDERERS.html);
148+
});
149+
150+
it('the schema strips the script-bearing elements with their content', () => {
151+
for (const tag of ['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math']) {
152+
expect(RICH_TEXT_SANITIZE_SCHEMA.strip, tag).toContain(tag);
153+
}
154+
});
155+
});
156+
157+
/**
158+
* What a rich-text document is made of, already in the canonical form the
159+
* pipeline serialises back (lower-case tags, double-quoted attributes, an
160+
* image's `src` after its other attributes), so the comparison below is byte
161+
* for byte.
162+
*/
163+
const FORMATTED_DOCUMENT = [
164+
'<h1>Account review</h1>',
165+
'<h2>Summary</h2>',
166+
'<p>Body with <strong>bold</strong>, <em>emphasis</em>, <b>b</b>, <i>i</i>, <del>removed</del>, ',
167+
'<sub>sub</sub>, <sup>sup</sup> and <code>inline code</code>.<br>Second line.</p>',
168+
'<h3>Links</h3>',
169+
'<p><a href="https://objectstack.ai/docs?x=1#top">absolute</a>, <a href="mailto:sales@example.com">mail</a>, ',
170+
'<a href="/app/crm/lead/1">relative</a> and <a href="http://example.com">plain http</a>.</p>',
171+
'<ul><li>one</li><li>two<ul><li>nested</li></ul></li></ul>',
172+
'<ol start="3"><li>three</li><li>four</li></ol>',
173+
'<blockquote><p>Quoted text.</p></blockquote>',
174+
'<pre><code>const x = 1;\n</code></pre>',
175+
'<table><thead><tr><th>Stage</th><th align="right">Amount</th></tr></thead>',
176+
'<tbody><tr><td>Won</td><td align="right">1,000</td></tr><tr><td colspan="2">Total</td></tr></tbody></table>',
177+
'<p><img alt="Logo" width="120" height="40" title="Logo" src="https://cdn.example.com/logo.png"></p>',
178+
'<hr>',
179+
'<dl><dt>Term</dt><dd>Definition</dd></dl>',
180+
'<details><summary>More</summary><p>Hidden detail.</p></details>',
181+
].join('');
182+
183+
describe('html / richtext display: a formatted document keeps its formatting', () => {
184+
it('round-trips byte for byte', () => {
185+
expect(renderHtml(FORMATTED_DOCUMENT).innerHTML).toBe(FORMATTED_DOCUMENT);
186+
});
187+
188+
it('keeps the safe part of a mixed value', () => {
189+
const prose = renderHtml(
190+
'<p onclick="alert(1)">Hello <strong>world</strong></p><a href="javascript:alert(1)">bad</a><a href="https://ok.test">good</a>',
191+
);
192+
expect(prose.innerHTML).toBe('<p>Hello <strong>world</strong></p><a>bad</a><a href="https://ok.test">good</a>');
193+
});
194+
195+
it('keeps the text of an element it does not allow', () => {
196+
expect(renderHtml('<p><u>underlined</u> and <font color="red">coloured</font></p>').innerHTML).toBe(
197+
'<p>underlined and coloured</p>',
198+
);
199+
});
200+
201+
it('renders plain text that holds no markup as text', () => {
202+
expect(renderHtml('5 < 6 & 7 > 3').textContent).toBe('5 < 6 & 7 > 3');
203+
});
204+
});

0 commit comments

Comments
 (0)