# HTML Sanitizer and Paste Cleanup

> The always-on, server-safe allow-list sanitizer of the rich text editors, its restriction-only hook, and paste cleanup for Word, Google Docs and plain text.

Canonical: https://salmonui.dev/docs/editors/html-sanitizer-and-paste

Every HTML string that enters or leaves `RichTextEditor`, `BlockEditor` and
`RichTextContent` goes through one sanitizer. It is always on and
cannot be turned off. It is a pure function from `@salmonui/rich-text`: no
DOM, no dependencies, linear in the input size (a 1 MB document in about
40 ms), and the same on the server and in the browser.

```ts
import { sanitizeHtml } from '@salmonui/rich-text';

sanitizeHtml('<p onclick="x">Hi <b>there</b><script>alert(1)</script></p>');
// '<p>Hi <strong>there</strong></p>'
```

### Live demo: Paste cleanup and sanitizing

Live demo: https://salmonui.dev/demos/editors/rich-text-paste

RichTextEditor paste cleanup - Word and Google Docs clipboard HTML normalized in clean, keep, plain text and prompt modes, denied tags, keepWordFormatting, and the always-on sanitizer removing scripts, handlers and unsafe URLs with a restriction-only sanitize hook.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { RichTextEditor, type RichTextEditorActions, type SanitizeHook } from '@salmonui/rich-text';
import '@salmonui/rich-text/styles.css';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

// Clipboard HTML as Word and Google Docs put it on the clipboard (shortened).
const SAMPLES = {
  word:
    '<html xmlns:o="urn:schemas-microsoft-com:office:office"><body><!--StartFragment-->' +
    '<p class="MsoNormal"><b><span style="font-size:14.0pt;font-family:Calibri;color:#1F3864;mso-bidi-font-weight:normal">Quarterly plan</span></b><o:p></o:p></p>' +
    '<p class="MsoListParagraphCxSpFirst" style="mso-list:l0 level1 lfo1"><span style="mso-list:Ignore">1.<span style="font:7.0pt Times">&nbsp;</span></span>Hire two engineers<o:p></o:p></p>' +
    '<p class="MsoListParagraphCxSpLast" style="mso-list:l0 level1 lfo1"><span style="mso-list:Ignore">2.<span style="font:7.0pt Times">&nbsp;</span></span>Ship the <i>editor</i> <span style="background:yellow;mso-highlight:yellow">beta</span><o:p></o:p></p>' +
    '<!--EndFragment--></body></html>',
  googleDocs:
    '<meta charset="utf-8"><b style="font-weight:normal;" id="docs-internal-guid-1a2b3c"><p dir="ltr"><span style="font-weight:700;color:#cc0000;">Launch checklist</span></p>' +
    '<ul><li dir="ltr"><p dir="ltr"><span style="font-style:italic;">Write the post</span></p></li><li dir="ltr"><p dir="ltr"><span style="text-decoration:underline;">Review</span> with <a href="https://example.com/team">the team</a></p></li></ul></b>',
  unsafe:
    '<p onclick="alert(1)">Click <a href="javascript:alert(1)">here</a> or <a href="https://example.com" target="_blank">there</a>.</p>' +
    '<img src="javascript:alert(1)" onerror="alert(1)"><script>alert(1)</script><iframe src="https://evil.example"></iframe><p style="color:red;background:url(x)">Styled text</p>',
} as const;

const INITIAL = '<p>Paste below this line.</p><p></p>';

type Mode = 'clean' | 'keep' | 'plainText' | 'prompt';
const MODES = (['clean', 'keep', 'plainText', 'prompt'] as const).map((value) => ({ value, label: value }));

/** Restriction-only hook: links never open a new window. */
const noNewWindows: SanitizeHook = (element) => (element.tag === 'a' && element.attrs['href'] ? { attrs: { href: element.attrs['href'] } } : undefined);

function pasteHtml(actions: RichTextEditorActions | null, html: string): boolean {
  const target = actions?.engine.view?.dom;
  if (!actions || !target) return false;
  // Paste at the end of the document, like a user who clicks below the text.
  const end = actions.engine.state.doc.content.size - 1;
  actions.setSelection(end);
  actions.focus();
  const data = new DataTransfer();
  data.setData('text/html', html);
  data.setData('text/plain', html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim());
  const event = new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true });
  // Some engines ignore clipboardData in the constructor.
  if (!event.clipboardData) Object.defineProperty(event, 'clipboardData', { value: data });
  target.dispatchEvent(event);
  return true;
}

export default function RichTextPasteDemo() {
  const [log, push] = useEventLog();
  const [mode, setMode] = useState<Mode>('clean');
  const [keepWord, setKeepWord] = useState(false);
  const [noLinks, setNoLinks] = useState(false);
  const [hook, setHook] = useState(false);
  const [html, setHtml] = useState(INITIAL);
  const actions = useRef<RichTextEditorActions | null>(null);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <fieldset style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', border: 0, margin: 0, padding: 0 }}>
        <legend style={{ fontWeight: 600, padding: 0 }}>pasteCleanup</legend>
        <label>
          mode{' '}
          <Select aria-label="mode" data={MODES} value={mode} onValueChange={(value) => value != null && setMode(value as Mode)} />
        </label>
        <Checkbox checked={keepWord} onCheckedChange={(checked) => setKeepWord(checked)}>
          keepWordFormatting
        </Checkbox>
        <Checkbox checked={noLinks} onCheckedChange={(checked) => setNoLinks(checked)}>
          deniedTags: [&apos;a&apos;]
        </Checkbox>
        <Checkbox checked={hook} onCheckedChange={(checked) => setHook(checked)}>
          sanitize hook: no new windows
        </Checkbox>
      </fieldset>
      <div role="group" aria-label="Paste a sample" style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {(
          [
            ['word', 'Paste a Word sample'],
            ['googleDocs', 'Paste a Google Docs sample'],
            ['unsafe', 'Paste unsafe HTML'],
          ] as const
        ).map(([key, label]) => (
          <Button variant="outline" key={key} type="button" onClick={() => push(pasteHtml(actions.current, SAMPLES[key]) ? `pasted the ${key} sample (${mode})` : 'the editor is still loading')}>
            {label}
          </Button>
        ))}
      </div>
      <RichTextEditor
        aria-label="Paste target"
        defaultValue={INITIAL}
        actionsRef={actions}
        onChange={setHtml}
        toolbar={['undo', 'redo', '|', 'bold', 'italic', 'underline', 'fontColor', '|', 'orderedList', 'unorderedList', 'link', 'sourceCode']}
        pasteCleanup={{ mode, keepWordFormatting: keepWord, ...(noLinks ? { deniedTags: ['a'] } : {}) }}
        {...(hook ? { sanitize: noNewWindows } : {})}
        style={{ minBlockSize: 220 }}
      />
      <details open>
        <summary>Editor HTML (after cleanup and sanitizing)</summary>
        <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12 }}>{html}</pre>
      </details>
      <EventLog entries={log} />
    </div>
  );
}
```

## What survives

The allow-list is exactly the editors' vocabulary:

- Blocks: `p`, `h1`..`h6` (with `text-align`, `line-height` and
  `data-indent`), `blockquote`, `hr`, `pre` with one `code`
  (`class="language-*"`), `ul` / `ol` (`start`, `list-style-type`),
  checklists (`ul data-type="checklist"`, `li data-checked`), `figure` with
  `img` and `figcaption`, `audio`, `video`, tables (`td` / `th` with
  `colspan`, `rowspan`, `data-colwidth`; sections become one `<tbody>`),
  callouts (`div data-type="callout" data-tone`), toggles (`details` /
  `summary`).
- Inline: `strong`, `em`, `u`, `s`, `sub`, `sup`, `code`, `mark`, `br`, `a`
  (`href`, `title`, `target="_blank"` with `rel="noopener noreferrer"`
  added), `img` (`src`, `alt`, `title`, integer `width` / `height`), spans
  with one of `font-family`, `font-size`, `color`, `background-color`, and
  mention and label atoms.
- Block ids (`data-block-id`) for `BlockEditor`.

Everything else is removed. Unknown elements are unwrapped and keep their
text; `script`, `style`, `template`, `noscript`, `iframe` (unless its host is
in `embedHosts`), `object`, `embed`, `svg`, `math`, `head`, `title`, form
controls and `select` go with their content. Comments, event handlers and
any other attribute are dropped. `b`, `i`, `del`, `strike`, `ins` and `font`
become their vocabulary equivalents, and `font-weight`, `font-style`,
`text-decoration` and `vertical-align` styles become marks.

URLs: links allow `http`, `https`, `mailto`, `tel`, relative URLs and `#`;
images also `blob:` and `data:image/(png|jpeg|gif|webp|avif)`; audio and
video `blob:`. Whitespace, tabs, newlines and character references are
resolved first, as the browser does, so `jav&#x09;ascript:` or
`&#106;avascript:` are recognized and refused. Style values are validated per
property (colors as hex, `rgb()`, `hsl()`, names or `var(--salmon-*)`;
lengths in `px`, `em`, `rem`, `pt` or `%`; font names only); `url()`,
`expression()`, escapes and comments never pass. Text is always escaped, and
the output re-parses to itself (`sanitizeHtml(sanitizeHtml(x)) ===
sanitizeHtml(x)`), so there is no mutation XSS through a second parse.

`sanitizeUrl(url, 'link' | 'image' | 'media' | 'embed')` exposes the URL
rules on their own, for example to validate a link field.

## Extending it: the `sanitize` hook

`sanitize` runs after the built-in rules,
on every element of the sanitized tree, parents before children. It can only
remove or further restrict content:

```ts
import type { SanitizeHook } from '@salmonui/rich-text';

const noImagesNoNewWindows: SanitizeHook = (element) => {
  if (element.tag === 'img') return null;          // remove with content
  if (element.tag === 'u') return 'unwrap';        // keep the text
  if (element.tag === 'a') return { attrs: { href: element.attrs.href! } }; // drop target and title
  return undefined;                                // keep
};

<RichTextEditor sanitize={noImagesNoNewWindows} />
```

The hook sees a frozen copy (`tag`, `attrs`, `parent`). A returned `attrs`
may only keep names the element already has, and every value is validated
again by the built-in rules: a hook cannot add an `onclick` or turn a link
into `javascript:`. Pass the same hook to the editors, `RichTextContent` and
`sanitizeHtml`, and keep it stable.

## Paste cleanup

`pasteCleanup` on both editors decides what pasted HTML keeps:

| `mode` | Keeps |
| --- | --- |
| `'clean'` (default) | Structure, marks and links; drops fonts, sizes, colors and alignment |
| `'keep'` | Everything the vocabulary allows, validated |
| `'plainText'` | Text only: paragraphs and line breaks |
| `'prompt'` | Asks each time (keep, clean or plain text) |

`allowedTags` / `deniedTags` (vocabulary names: `strong`, not `b`) unwrap
other elements, keeping their text; `allowedAttributes` /
`deniedAttributes` remove attributes (`style` counts as one; a link without
`href` is unwrapped). `keepWordFormatting: true` keeps Word and Google Docs
formatting in `'clean'` mode.

Word content (desktop and online) is normalized: `mso-*` styles, `o:p`,
`Mso*` classes, conditional comments and VML go, and list paragraphs
(`MsoListParagraph` with `mso-list` levels) become real nested `ul` / `ol`
with their start number and numbering style. Google Docs content loses the
`docs-internal-guid` wrapper, its styled spans become marks, nested lists
move into their items, and checkbox lists become checklists. Office link
styling (blue, underlined) is not kept as an underline.

The same functions work outside the editors, for an import pipeline or a
server:

```ts
import { cleanPastedHtml, detectPasteSource, pasteNeedsPrompt, plainTextToHtml, htmlToText } from '@salmonui/rich-text';

detectPasteSource(html);                        // 'word' | 'googleDocs' | 'html'
cleanPastedHtml(html, { mode: 'clean', deniedTags: ['table'] });
plainTextToHtml('Line 1\nLine 2\n\nNext');      // '<p>Line 1<br>Line 2</p><p>Next</p>'
htmlToText('<p>a</p><ul><li>b</li></ul>');      // 'a\nb' (what the character count counts)
```

With `mode: 'prompt'` an editor calls `pasteNeedsPrompt(html, options)`,
asks, and passes the chosen mode; `cleanPastedHtml` itself never asks and
treats `'prompt'` as `'clean'`. Every mode ends in the sanitizer.
