Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: an embed's picture is kept by allowlist, and a footnote id cannot leave its attribute (#828)

nyblnete1259e248dbe
diff --git a/.github/workflows/ci-type.yml b/.github/workflows/ci-type.yml
index c6d561a1..9e3f7430 100644
--- a/.github/workflows/ci-type.yml
+++ b/.github/workflows/ci-type.yml
@@ -167,3 +167,24 @@ jobs:
# emits inert markup, the frame inherits the hash-only CSP and carries
# its own script-src 'none', and the real shell prints under the CSP.
run: node scripts/test-type-printframe-browser.mjs
+
+ type-sinks-browser:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - name: Install browser test runtime
+ # Pinned outside app packages: browser automation is not shipped in documents.
+ run: |
+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]
+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps chromium
+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"
+ - name: Build the tested standalone document
+ run: |
+ npm ci --prefix type
+ npm run build:single --prefix type
+ - name: Embed pictures and footnote ids never become script in the editor or print
+ run: node scripts/test-type-sinks-browser.mjs
diff --git a/scripts/test-type-embed.ts b/scripts/test-type-embed.ts
index e14233fc..dc0ff983 100644
--- a/scripts/test-type-embed.ts
+++ b/scripts/test-type-embed.ts
@@ -120,5 +120,24 @@ console.log('\n— embedded documents don\'t carry sharing keys —');
ok(nblob.includes('deck-1'), 'and the inner document is still there to open');
}
+// ─────────────────────────────── a footnote id is ESCAPED into its attribute
+// A synced op never passes parseDoc, so the escape at render is the layer it
+// meets. Unescaped, an id could close data-note="…" and add an event handler
+// (it did: measured in the editor). Asserted on the string render produces.
+{
+ const { blockHtml } = await import('../type/src/render.ts');
+ const NID = 'n1" onmouseover="window.__pwned=1" data-x="';
+ const html = blockHtml({ id: 'b1', kind: 'para', text: 'Hello world', notes: [{ id: NID, at: 5 }] } as never);
+ ok(html.includes('data-note='), 'control: the note marker IS rendered for the hostile id');
+ ok(!/data-note="[^"]*"\s+onmouseover=/.test(html) && !html.includes('" onmouseover="'),
+ `a footnote id cannot close its attribute: the quote is escaped (${html.match(/data-note="[^>]*/)?.[0].slice(0, 60)})`);
+ const { parseDoc } = await import('../type/src/model.ts');
+ const r = parseDoc(JSON.stringify({ format: 'bento/type', docId: 'd', title: 't', footnotes: { [NID]: 'x', ok1: 'y' },
+ body: [{ id: 'b1', kind: 'para', text: 'Hello world', notes: [{ id: NID, at: 2 }, { id: 'ok1', at: 5 }] }] }));
+ ok(r.ok && !Object.hasOwn(r.doc.footnotes, NID) && Object.hasOwn(r.doc.footnotes, 'ok1')
+ && (r.doc.body[0].notes ?? []).map(n => n.id).join() === 'ok1',
+ 'and a FILE cannot carry such an id at all: parseDoc keeps only ids of a safe charset (a normal id survives)');
+}
+
console.log(`\n${checks - bad}/${checks} checks passed`);
if (bad) process.exit(1);
diff --git a/scripts/test-type-sinks-browser.mjs b/scripts/test-type-sinks-browser.mjs
new file mode 100644
index 00000000..af444b37
--- /dev/null
+++ b/scripts/test-type-sinks-browser.mjs
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// No document value becomes script in bento/type's editor: an embed's picture
+// is kept by ALLOWLIST, and a footnote id cannot leave its attribute.
+//
+// npm run build:single --prefix type && node scripts/test-type-sinks-browser.mjs
+//
+// Two paths a document's own values took into live markup, both measured
+// running in the editor before the fix:
+// - an embed's SVG passed a handler check that wanted whitespace before
+// "on…=" — the HTML tokenizer also starts an attribute after `/`, so
+// `<circle/onmouseover=…>` rendered and ran;
+// - a footnote id was written unescaped into data-note="…".
+// The embed view is now walked by svgsafe.ts (allowlist of tag and attribute
+// NAMES, modelled on slides' sanitizeSvg) and imported as nodes; the note id is
+// escaped at render (the layer a synced op meets — pinned in
+// scripts/test-type-embed.ts) and limited to a safe charset by parseDoc.
+//
+// WHAT THIS PROVES, in the packaged editor: every hostile picture renders with
+// no on* attribute, no javascript:/remote href, no script/foreignObject, and
+// hovering and clicking every element of it runs NOTHING (a page-global counter
+// is the oracle); the same holds for what print emits. Positive control: a
+// benign diagram — gradient, url(#…) fill, <use href="#…">, text — still
+// renders with all of those intact, so the sanitizer is not passing by
+// deleting everything. And a hostile footnote id in a file runs nothing.
+//
+// Mutations (run, judged by exit code): the editor sink back on the old
+// whitespace-only check (innerHTML of safeView) → red; on* names allowed in
+// svgsafe.ts → red.
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0, failures = 0
+const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }
+const SHELL = new URL('../type/dist-single/Bento_Type.bento.html', import.meta.url).href
+const RUN = 'window.__pwned=(window.__pwned||0)+1'
+
+const HOSTILE = {
+ 'slash before on*': `<svg width="120" height="120"><circle/onmouseover="${RUN}" cx="60" cy="60" r="50"/></svg>`,
+ 'quote before on*': `<svg width="120" height="120"><rect x="1"onclick="${RUN}" width="100" height="100"/></svg>`,
+ 'on* on the root': `<svg onload="${RUN}" width="50" height="50"><rect width="40" height="40"/></svg>`,
+ 'script inside': `<svg width="50" height="50"><script>${RUN}</script><rect width="40" height="40"/></svg>`,
+ 'foreignObject + img onerror': `<svg width="50" height="50"><foreignObject width="50" height="50"><img src="x:" onerror="${RUN}"></foreignObject></svg>`,
+ 'animate href to javascript:': `<svg width="80" height="80"><a><rect width="70" height="70"/><animate attributeName="href" values="javascript:${RUN}" begin="0s"/></a></svg>`,
+ 'set attributeName on*': `<svg width="80" height="80"><rect width="70" height="70"><set attributeName="onmouseover" to="${RUN}"/></rect></svg>`,
+ 'use with javascript: href': `<svg width="80" height="80"><use href="javascript:${RUN}"/><rect width="70" height="70"/></svg>`,
+ 'image with javascript: href': `<svg width="80" height="80"><image href="javascript:${RUN}" width="70" height="70"/></svg>`,
+ 'remote url() fill': `<svg width="80" height="80"><rect width="70" height="70" fill="url(http://rc.test/x)"/></svg>`,
+ 'css-escaped url() fill': `<svg width="80" height="80"><rect width="70" height="70" fill="\\75 rl(http://rc.test/y)"/></svg>`,
+ 'style element @import': `<svg width="80" height="80"><style>@import url(http://rc.test/z);</style><rect width="70" height="70"/></svg>`,
+ // values no scheme check refuses (no javascript:, no url()) — only the rule
+ // that judges an animation by the attribute it WRITES stops these
+ 'use animated to a remote href': `<svg width="80" height="80"><defs><rect id="a" width="60" height="60"/></defs><use href="#a"><animate attributeName="href" to="https://rc.test/x.svg#a" begin="0s" fill="freeze"/></use></svg>`,
+ 'a animated to a scheme-relative href': `<svg width="80" height="80"><a href="#x"><rect width="70" height="70"/><animate attributeName="href" to="//rc.test/p" begin="0s" fill="freeze"/></a></svg>`,
+}
+const BENIGN = `<svg width="200" height="120" viewBox="0 0 200 120"><defs><linearGradient id="g"><stop offset="0" stop-color="#f7a600"/><stop offset="1" stop-color="#5b8def"/></linearGradient><circle id="c" r="10"/></defs><rect width="200" height="120" fill="url(#g)"/><use href="#c" x="30" y="30"/><text x="10" y="110">Q3</text></svg>`
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+const requests = []
+const open = async () => {
+ const p = await browser.newPage({ viewport: { width: 1440, height: 900 } })
+ await p.route(/^https?:/, (r) => { requests.push(r.request().url()); r.abort() })
+ await p.goto(SHELL)
+ await p.waitForFunction(() => window.bento?.doc)
+ return p
+}
+const docWith = (view) => JSON.stringify({ format: 'bento/type', docId: 'd-' + Math.random().toString(36).slice(2), title: 't',
+ body: [{ id: 'e1', kind: 'embed', text: '', embed: { app: 'bento/dash', view, doc: {} } }, { id: 'p1', kind: 'para', text: 'After.' }] })
+
+try {
+ console.log('\n1. a benign diagram still renders (positive control)\n')
+ {
+ const p = await open()
+ await p.evaluate((j) => window.bento.loadDoc(j), docWith(BENIGN))
+ await p.waitForTimeout(400)
+ const r = await p.evaluate(() => {
+ const svg = document.querySelector('#paper .t-embed-view svg')
+ return svg ? { grad: !!svg.querySelector('linearGradient stop'), fill: svg.querySelector('rect')?.getAttribute('fill'),
+ use: svg.querySelector('use')?.getAttribute('href'), text: svg.querySelector('text')?.textContent } : null
+ })
+ ok(!!r && r.grad && r.fill === 'url(#g)' && r.use === '#c' && r.text === 'Q3',
+ `the benign diagram keeps its gradient, url(#g) fill, <use href="#c"> and text (${JSON.stringify(r)})`)
+ await p.close()
+ }
+
+ console.log('\n2. hostile pictures render inert in the editor and in print\n')
+ for (const [name, view] of Object.entries(HOSTILE)) {
+ const p = await open()
+ const before = requests.length
+ await p.evaluate((j) => window.bento.loadDoc(j), docWith(view))
+ await p.waitForTimeout(500)
+ const scan = await p.evaluate(() => {
+ const els = [...document.querySelectorAll('#paper .t-embed, #paper .t-embed *')]
+ return {
+ on: els.filter((e) => [...e.attributes].some((a) => /^on/i.test(a.name))).length,
+ js: els.filter((e) => [...e.attributes].some((a) => /^(href|xlink:href|values|to|from)$/i.test(a.name) && /javascript:|https?:/i.test(a.value))).length,
+ bad: document.querySelectorAll('#paper .t-embed script, #paper .t-embed foreignObject, #paper .t-embed style').length,
+ boxes: els.length,
+ svg: !!document.querySelector('#paper .t-embed-view svg'),
+ }
+ })
+ // hover and click every element of the picture (or its placeholder)
+ const targets = await p.$$('#paper .t-embed, #paper .t-embed *')
+ for (const t of targets) { await t.hover({ force: true }).catch(() => {}); await t.click({ force: true, timeout: 500 }).catch(() => {}) }
+ await p.waitForTimeout(300)
+ await p.waitForTimeout(300) // let a frozen animation land before reading
+ const ran = await p.evaluate(() => window.__pwned || 0)
+ const stayed = p.url() === SHELL
+ const printed = await p.evaluate(() => {
+ const d = new DOMParser().parseFromString(window.bento.printHtml(), 'text/html')
+ const all = [...d.querySelectorAll('.t-embed, .t-embed *')]
+ return { on: all.filter((e) => [...e.attributes].some((a) => /^on/i.test(a.name))).length,
+ bad: d.querySelectorAll('.t-embed script, .t-embed foreignObject, .t-embed style').length,
+ js: all.filter((e) => [...e.attributes].some((a) => /javascript:/i.test(a.value))).length }
+ })
+ const fetched = requests.slice(before).filter((u) => u.includes('rc.test')).length
+ ok(scan.svg && scan.on === 0 && scan.js === 0 && scan.bad === 0 && ran === 0 && fetched === 0 && stayed
+ && printed.on === 0 && printed.bad === 0 && printed.js === 0,
+ `${name}: the picture still RENDERS (${scan.svg}), no navigation on click (${stayed}), inert in the editor (on* ${scan.on}, js/remote ${scan.js}, script/foreign/style ${scan.bad}, ran ${ran}, fetched ${fetched}) and in print (on* ${printed.on}, ${printed.bad}, js ${printed.js})`)
+ await p.close()
+ }
+
+ console.log('\n3. a hostile footnote id in a FILE runs nothing\n')
+ {
+ const p = await open()
+ const NID = `n1" onmouseover="${RUN}" data-x="`
+ await p.evaluate((j) => window.bento.loadDoc(j), JSON.stringify({ format: 'bento/type', docId: 'd-n', title: 't',
+ footnotes: { [NID]: 'evil', ok1: 'fine' }, body: [{ id: 'b1', kind: 'para', text: 'Hello world', notes: [{ id: NID, at: 2 }, { id: 'ok1', at: 5 }] }] }))
+ await p.waitForTimeout(400)
+ for (const t of await p.$$('#paper [data-note]')) await t.hover({ force: true }).catch(() => {})
+ await p.waitForTimeout(200)
+ const r = await p.evaluate(() => ({ markers: document.querySelectorAll('#paper [data-note]').length,
+ on: [...document.querySelectorAll('#paper *')].filter((e) => [...e.attributes].some((a) => /^on/i.test(a.name))).length, ran: window.__pwned || 0 }))
+ ok(r.markers >= 1 && r.on === 0 && r.ran === 0, `no handler and nothing runs; the ordinary note still renders (markers ${r.markers}, on* ${r.on}, ran ${r.ran})`)
+ await p.close()
+ }
+} finally {
+ await browser.close()
+}
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/type/src/embed.ts b/type/src/embed.ts
index 8e599b42..df1dedee 100644
--- a/type/src/embed.ts
+++ b/type/src/embed.ts
@@ -26,6 +26,7 @@
// every renderer in every file to cover the matrix, and version skew between
// the embedded copy and the real app.
+import { sanitizeEmbedSvg, sanitizeEmbedSvgHtml } from './svgsafe.ts';
import { uid, embedSafe, type Block } from './model.ts';
import { t } from './i18n.ts';
import { registerTool, type FeatureContext } from './features.ts';
@@ -113,15 +114,19 @@ export function renderEmbed(b: Block): HTMLElement {
}
if (e.w) host.style.setProperty('--embed-w', `${e.w}px`);
- const view = safeView(e.view);
- if (view === null) {
+ // The ALLOWLIST walk (svgsafe.ts) alone decides what of the picture is kept,
+ // and the result is IMPORTED as nodes, never re-parsed from a string. (Not
+ // gated on safeView: that pattern check also refuses a same-document
+ // `<use href="#…">`, so in front of the walk it blanked benign diagrams.)
+ const svg = sanitizeEmbedSvg(e.view);
+ if (svg === null) {
// An embed whose picture was refused still says what it is and still
// carries its source, so a person can open it in the app that made it.
host.append(placeholder(t('This embed could not be displayed safely.')));
} else {
const box = document.createElement('div');
box.className = 't-embed-view';
- box.innerHTML = view;
+ box.appendChild(document.importNode(svg, true));
host.appendChild(box);
}
@@ -153,7 +158,10 @@ function placeholder(text: string): HTMLElement {
export function embedHtml(b: Block): string {
const e = embedOf(b);
if (!e) return '';
- const view = safeView(e.view);
+ // The allowlist walk wherever there is a DOM — the editor's page, print and
+ // the preview all render through this string. In node (no DOM, nothing
+ // reaches a browser from there) safeView's refusal stands in.
+ const view = typeof DOMParser === 'undefined' ? safeView(e.view) : sanitizeEmbedSvgHtml(e.view);
const cap = `From ${APPS[e.app] ?? e.app}`;
return `<figure class="t-embed" data-id="${esc(b.id)}" data-atomic="1">`
+ (view === null ? `<div class="t-embed-missing">${esc('This embed could not be displayed safely.')}</div>`
diff --git a/type/src/fields.ts b/type/src/fields.ts
index e206742e..fd8c1d8d 100644
--- a/type/src/fields.ts
+++ b/type/src/fields.ts
@@ -407,7 +407,8 @@ export function fieldAtoms(b: Block): Map<number, string> {
m.set(f.at,
prev + `<span class="${FIELD_CLASS} ${UNBOUND_CLASS}" data-field="${esc(f.name)}"`
+ ` data-fkey="${esc(fkeyOf(b.id, f.at))}"`
- + (f.pad ? ` data-pad="${f.pad}"` : '')
+ // a NUMBER, always: a synced field ref never passed readFieldRefs
+ + (typeof f.pad === 'number' && f.pad > 0 ? ` data-pad="${Math.trunc(f.pad)}"` : '')
+ ` contenteditable="false">${esc(f.name)}</span>`);
}
return m;
diff --git a/type/src/inline.ts b/type/src/inline.ts
index b21ecdce..72eaa766 100644
--- a/type/src/inline.ts
+++ b/type/src/inline.ts
@@ -323,7 +323,8 @@ const ESC: Record<string, string> = {
// immediately. Text needs & < > ; an attribute value needs the quotes as well,
// because those are what end it.
const esc = (s: string) => s.replace(/[&<>]/g, c => ESC[c]);
-const escAttr = (s: string) => s.replace(/[&<>"']/g, c => ESC[c]);
+/** For a double- OR single-quoted attribute value: every quote is escaped. */
+export const escAttr = (s: string) => s.replace(/[&<>"']/g, c => ESC[c]);
/**
* An href safe to put in the document's HTML.
diff --git a/type/src/model.ts b/type/src/model.ts
index cd47cae4..e5533b86 100644
--- a/type/src/model.ts
+++ b/type/src/model.ts
@@ -566,6 +566,10 @@ function scrubEmbeds(doc: Record<string, unknown>, depth: number): Record<string
return changed ? { ...doc, body: next } : doc;
}
+/** A footnote id a FILE may carry: what uid() mints and nothing that could
+ * leave an attribute. Render escapes ids too — a synced op never passes here. */
+const NOTE_ID = /^[A-Za-z0-9_.:-]{1,80}$/;
+
export const uid = (p = 'b'): string => {
const r = globalThis.crypto?.randomUUID?.();
return r ? `${p}-${r.slice(0, 8)}` : `${p}-${Math.random().toString(36).slice(2, 10)}`;
@@ -669,7 +673,7 @@ export function parseDoc(raw: string): ParseResult {
&& typeof m.to === 'number' && typeof m.t === 'string'), text.length)
: undefined;
const notes = Array.isArray(b.notes)
- ? (b.notes as NoteRef[]).filter(n => isObj(n) && typeof n.id === 'string' && typeof n.at === 'number')
+ ? (b.notes as NoteRef[]).filter(n => isObj(n) && typeof n.id === 'string' && NOTE_ID.test(n.id) && typeof n.at === 'number')
.map(n => ({ id: n.id, at: Math.max(0, Math.min(n.at, text.length)) }))
.sort((x, y) => x.at - y.at)
: undefined;
@@ -809,7 +813,7 @@ export function parseDoc(raw: string): ParseResult {
const footnotes: Record<string, string> = {};
if (isObj(json.footnotes)) {
- for (const [k, v] of Object.entries(json.footnotes)) if (typeof v === 'string') footnotes[k] = v;
+ for (const [k, v] of Object.entries(json.footnotes)) if (typeof v === 'string' && NOTE_ID.test(k)) footnotes[k] = v;
}
// a reference to a note that is not there would render as a marker with
// nothing behind it — drop the reference, keep the text
diff --git a/type/src/render.ts b/type/src/render.ts
index 05f0f231..4aeeea6a 100644
--- a/type/src/render.ts
+++ b/type/src/render.ts
@@ -8,7 +8,7 @@
// Everything it emits is reconstructible from the model, which is what lets the
// editor re-render a block at any moment without asking whether it is safe.
-import { toHtml, fromDom, type Mark } from './inline.ts';
+import { toHtml, fromDom, escAttr, type Mark } from './inline.ts';
import { isList, MAX_LIST_LEVEL, type Block, type TypeDoc } from './model.ts';
import { captionPrefixHtml, isXrefAtom, refAtoms, readXrefs, numberXrefs } from './xref.ts';
import { blockStyle } from './layout.ts';
@@ -127,8 +127,11 @@ const decorate = (b: Block, base: string): string => {
return out;
};
+// The note id comes from the document — a file, or a collaborator's synced op
+// that never passed parseDoc — so it is ESCAPED into its attribute: unescaped,
+// an id could close the quote and add an event handler (it did, in the editor).
const noteMarker = (id: string) =>
- `<sup class="t-note" data-note="${id}" contenteditable="false">•</sup>`;
+ `<sup class="t-note" data-note="${escAttr(id)}" contenteditable="false">•</sup>`;
/** One block, as HTML. Marks become tags; note refs become atoms. */
export function blockHtml(b: Block): string {
diff --git a/type/src/svgsafe.ts b/type/src/svgsafe.ts
new file mode 100644
index 00000000..be5ee5e3
--- /dev/null
+++ b/type/src/svgsafe.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// An embed's picture (an SVG from another Bento app) made safe by ALLOWLIST.
+//
+// Modelled on bento/slides' sanitizeSvg (slides/src/render.ts), which is
+// released and has held up — parse inert, walk every element, keep a tag or an
+// attribute only if its NAME is on a list — and kept STRICTER than it, because
+// an embed's picture needs less: no <style> element or attribute (so no CSS to
+// police beyond presentation values), no <a>, no remote reference of any kind.
+// To be replaced by a shared kernel module when slides' sanitizer is lifted.
+//
+// WHY A WALK, NOT A PATTERN. The earlier check (embed.ts safeView) looked for
+// an event handler as whitespace + "on…=". The HTML tokenizer also begins an
+// attribute name after `/` and after a closed quote, so `<circle/onmouseover=…>`
+// passed and ran (measured, in the editor). Reading `el.attributes` after the
+// browser parsed the markup is right whatever the separators were, and an on*
+// attribute is never kept because it was never on the list.
+//
+// Guarded by scripts/test-type-sinks-browser.mjs.
+
+const TAGS = new Set([
+ 'svg', 'g', 'defs', 'symbol', 'use', 'switch', 'desc', 'title', 'metadata', 'view',
+ 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
+ 'text', 'tspan', 'textpath', 'image',
+ 'lineargradient', 'radialgradient', 'stop', 'pattern', 'solidcolor',
+ 'clippath', 'mask', 'marker',
+ 'filter', 'feblend', 'fecolormatrix', 'fecomponenttransfer', 'fecomposite',
+ 'feconvolvematrix', 'fediffuselighting', 'fedisplacementmap', 'fedistantlight',
+ 'fedropshadow', 'feflood', 'fefunca', 'fefuncb', 'fefuncg', 'fefuncr',
+ 'fegaussianblur', 'feimage', 'femerge', 'femergenode', 'femorphology',
+ 'feoffset', 'fepointlight', 'fespecularlighting', 'fespotlight', 'fetile',
+ 'feturbulence',
+ 'animate', 'animatemotion', 'animatetransform', 'set', 'mpath',
+]);
+
+/** SMIL elements WRITE an attribute later, so they are judged by their target. */
+const ANIM = new Set(['animate', 'set', 'animatetransform', 'animatemotion']);
+
+const ATTRS = new Set([
+ 'id', 'class', 'lang', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'role', 'version',
+ 'href', 'xlink:href',
+ 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height',
+ 'd', 'points', 'pathlength', 'dx', 'dy', 'rotate', 'textlength', 'lengthadjust',
+ 'transform', 'transform-origin', 'transform-box', 'viewbox', 'preserveaspectratio',
+ 'refx', 'refy', 'markerwidth', 'markerheight', 'markerunits', 'orient',
+ 'gradientunits', 'gradienttransform', 'spreadmethod', 'fx', 'fy', 'fr', 'offset',
+ 'patternunits', 'patterncontentunits', 'patterntransform', 'clippathunits',
+ 'maskunits', 'maskcontentunits', 'primitiveunits', 'filterunits',
+ 'startoffset', 'method', 'spacing', 'side',
+ 'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap',
+ 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset',
+ 'stroke-opacity', 'opacity', 'color', 'display', 'visibility', 'overflow',
+ 'shape-rendering', 'text-rendering', 'image-rendering', 'vector-effect', 'paint-order',
+ 'font-family', 'font-size', 'font-style', 'font-weight', 'letter-spacing', 'word-spacing',
+ 'text-anchor', 'text-decoration', 'dominant-baseline', 'alignment-baseline', 'baseline-shift',
+ 'writing-mode', 'direction', 'clip', 'clip-path', 'clip-rule', 'mask', 'marker',
+ 'marker-start', 'marker-mid', 'marker-end', 'filter', 'stop-color', 'stop-opacity',
+ 'flood-color', 'flood-opacity', 'lighting-color',
+ 'in', 'in2', 'result', 'mode', 'values', 'tablevalues', 'slope', 'intercept',
+ 'amplitude', 'exponent', 'operator', 'k1', 'k2', 'k3', 'k4', 'order', 'kernelmatrix',
+ 'divisor', 'bias', 'targetx', 'targety', 'edgemode', 'kernelunitlength', 'preservealpha',
+ 'surfacescale', 'diffuseconstant', 'specularconstant', 'specularexponent', 'scale',
+ 'xchannelselector', 'ychannelselector', 'stddeviation', 'radius', 'basefrequency',
+ 'numoctaves', 'seed', 'stitchtiles', 'azimuth', 'elevation', 'pointsatx', 'pointsaty',
+ 'pointsatz', 'limitingconeangle', 'z',
+ 'attributename', 'attributetype', 'from', 'to', 'by', 'dur', 'begin', 'end', 'min',
+ 'max', 'restart', 'repeatcount', 'repeatdur', 'calcmode', 'keytimes', 'keysplines',
+ 'keypoints', 'path', 'additive', 'accumulate', 'origin',
+]);
+
+/** Exported for the rig: a pure decision. */
+export const attrAllowed = (name: string): boolean => {
+ const n = name.toLowerCase();
+ return n.startsWith('aria-') || ATTRS.has(n);
+};
+
+/** href: a same-document `#ref` anywhere; an inline raster only on image/feImage. */
+function hrefAllowed(value: string, tag: string): boolean {
+ const v = value.replace(/[\u0000- ]/g, '').toLowerCase();
+ if (v.startsWith('#')) return true;
+ return (tag === 'image' || tag === 'feimage') && /^data:image\/(png|jpe?g|gif|webp);base64,/.test(v);
+}
+
+/**
+ * A presentation or SMIL value: no CSS escape (a backslash is how `url(` and
+ * friends are spelled past a naive check, and a picture never needs one), and
+ * every url() a same-document `#ref`. `values`/`from`/`to`/`by` are checked
+ * too: an animation's values are written into its target later.
+ */
+function valueAllowed(value: string): boolean {
+ if (value.includes('\\')) return false;
+ if (/javascript:|vbscript:|data:(?!image\/(png|jpe?g|gif|webp);base64,)/i.test(value.replace(/[\u0000- ]/g, ''))) return false;
+ for (const m of value.matchAll(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi)) {
+ if (!m[2].trim().startsWith('#')) return false;
+ }
+ return !/@import|expression\s*\(|image-set\s*\(|-webkit-image-set/i.test(value);
+}
+
+/**
+ * The sanitized <svg>, as an element of an INERT document — the caller imports
+ * it (never re-parses a string), or null when the markup is not an svg at all.
+ */
+export function sanitizeEmbedSvg(markup: string): Element | null {
+ if (typeof DOMParser === 'undefined' || typeof markup !== 'string') return null;
+ const parsed = new DOMParser().parseFromString(markup.trim(), 'text/html');
+ const root = parsed.body.firstElementChild;
+ if (!root || root.localName.toLowerCase() !== 'svg') return null;
+ const clean = (el: Element): boolean => { // false = remove this element
+ const tag = el.localName.toLowerCase();
+ if (!TAGS.has(tag)) return false;
+ for (const attr of Array.from(el.attributes)) {
+ const name = attr.name.toLowerCase();
+ if (!attrAllowed(name)) { el.removeAttribute(attr.name); continue; }
+ if (ANIM.has(tag) && name === 'attributename') {
+ const target = attr.value.trim().toLowerCase();
+ if (!attrAllowed(target) || /(^|:)(href|style)$/.test(target)) return false;
+ continue;
+ }
+ if (name === 'href' || name === 'xlink:href') {
+ if (hrefAllowed(attr.value, tag)) continue;
+ if (tag === 'use') return false; // a <use> IS its href
+ el.removeAttribute(attr.name);
+ continue;
+ }
+ if (!valueAllowed(attr.value)) el.removeAttribute(attr.name);
+ }
+ for (const child of Array.from(el.childNodes)) {
+ if (child.nodeType === 3) continue; // text
+ if (child.nodeType !== 1 || !clean(child as Element)) child.remove();
+ }
+ return true;
+ };
+ if (!clean(root)) return null;
+ // nothing outside the one <svg> survives
+ for (const n of Array.from(parsed.body.childNodes)) if (n !== root) n.remove();
+ return root;
+}
+
+/** The same, serialized — for the string-built print and preview documents. */
+export function sanitizeEmbedSvgHtml(markup: string): string | null {
+ const el = sanitizeEmbedSvg(markup);
+ return el ? el.outerHTML : null;
+}