Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: one svg sanitizer, lifted from slides; an app's policy only tightens it (#847)
nyblnet6a98061fd2a0
diff --git a/.github/workflows/ci-slides.yml b/.github/workflows/ci-slides.ymlindex a4136b41..18912893 100644--- a/.github/workflows/ci-slides.yml+++ b/.github/workflows/ci-slides.yml@@ -55,6 +55,11 @@ jobs:# surface (canvas, panels, present, speaker, print, the saved file with# JS off) the payload origin is never requested; a raw url() is.run: node scripts/test-slides-css-egress-browser.mjs+ - name: The shared svg sanitizer's policy options only tighten+ # kernel/src/svgsafe.ts, lifted from slides' renderer: slides' lists are+ # the default, and every option an app adds (type's embed pictures use+ # all of them) removes what the default keeps and never keeps more.+ run: node scripts/test-svgsafe-policy-browser.mjsslides-font-browser:runs-on: ubuntu-latestdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 80db1e79..583ba6bb 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -11882,3 +11882,32 @@ own rig run against the extension's copy.clearing. Measured: libsecret's clear silently skips items in a lockedkeyring, so the re-count is what keeps a wipe from reporting success whilekeys remain.++## 2026-10-24 — One svg sanitizer in kernel; an app's policy only tightens it++kernel/src/svgsafe.ts holds the untrusted-svg sanitizer, lifted verbatim from+slides' renderer, so there is one implementation to audit instead of one per app.+Type asked for this, at security's suggestion; slides agreed and named the+couplings below.++- **Slides' behaviour is the default.** Every policy option refuses more: a tag,+ an attribute, `data-*`, remote hrefs, or escapes and foreign schemes in a+ value. No option can add a name to a list. scripts/test-svgsafe-policy-browser.mjs+ holds that: each option removes what the default keeps, and nothing an option+ keeps was refused by the default.+- **`scopeStyle` is required, and it only scopes.** There is no safe default+ scope for a kept `<style>`, so a caller either passes its scoping (slides:+ `css => scopeCss(css, scope)`) or `null`, which refuses `<style>` elements and+ `style` attributes. The walk runs sanitizeSvgCss itself and hands the hook+ the result, so an app passing `css => css` keeps a sanitized sheet, never a+ raw one. Without that, this hook would be the one option able to loosen+ (security's condition on #847).+- **What stays in the app** is what isn't security: how it parses input into an+ inert document, and scopeCss (hard-won detail #7).+- **One decoder.** slides' colour gate reads values through the kernel's+ `cssDecodeIdentEscapes`, the same function the svg-css path uses. Two copies+ could disagree about what an escaped `u\72l(` says. Measured: making the+ kernel's decoder a no-op turns the egress rig red at the chart colour sinks.+- **render.ts re-exports** SVG_TAGS, svgAttrAllowed, svgHrefAllowed,+ svgUrlRefsAllowed and sanitizeSvgCss, so callers and rigs keep importing them+ from the renderer.diff --git a/kernel/src/svgsafe.ts b/kernel/src/svgsafe.tsnew file mode 100644index 00000000..c299594d--- /dev/null+++ b/kernel/src/svgsafe.ts@@ -0,0 +1,560 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// UNTRUSTED SVG, made safe by allowlist: ONE sanitizer every app imports.+// Lifted verbatim from bento/slides' renderer (released, and held to+// scripts/test-sanitize.ts and the browser egress rigs), so there is one+// implementation to audit instead of one per app.+//+// What stays with each app is what is not security: how it parses its input+// into an inert document, and how it SCOPES a kept <style> sheet (slides'+// scopeCss, hard-won detail #7). Both come in through the policy.+//+// THE POLICY ONLY TIGHTENS. Slides' lists and rules are the default: a caller+// that passes nothing extra gets exactly slides' behaviour, and every option+// refuses MORE (a tag, an attribute, data-* names, remote hrefs, escapes or+// foreign schemes in a value). No option can add a name to a list. The one+// required field is `scopeStyle`, because there is no safe default scope: a+// caller either says how its kept sheets are scoped or refuses <style> outright.+// It is handed CSS the walk has ALREADY sanitized, so it can only scope: an app+// passing `css => css` keeps a sanitized, unscoped sheet, never a raw one+// (security, 2026-10-24).+//+// cssDecodeIdentEscapes is exported because slides' colour gate (render.ts,+// the themed-value sink) reads values through the SAME decoder. The two gates+// must agree on what an escaped `u\72l(` says, or one spelling slips past one.+//+// DOM-only where it walks or probes (DOMParser output, CSSStyleSheet); the pure+// decisions (svgAttrAllowed, svgHrefAllowed, svgUrlRefsAllowed, sanitizeSvgCss+// without a CSSOM) run in node, which is how the rigs pin them.++/**+ * The svg vocabulary an untrusted diagram may use. AN ALLOWLIST, and that is+ * the whole point of this rewrite.+ *+ * The first version of this sanitizer named five tags and three attributes,+ * and a verifier walked through the gap five ways in Chrome 141 (2026-08-09):+ * `<form action="javascript:…">` under a full-slide transparent submit button+ * (ONE click anywhere on the slide), `<button formaction="javascript:…">`,+ * `<meta http-equiv="refresh">` — which actually navigated the reader's page+ * off to an attacker host, and which the html parser lets break out of foreign+ * content so `<svg><rect/><meta …></svg>` reaches the body too — `<base href>`+ * (a media `src` is documented as possibly relative, so retargeting resolution+ * is a live fetch), and `<link rel=stylesheet>`. Not one of those is on this+ * list, so not one of them had to be named, and neither does whatever the next+ * browser ships.+ *+ * Sized against the content that exists: every svg asset in `starterdeck.ts`+ * (userSpaceOnUse patterns, feTurbulence + feColorMatrix grain, feGaussianBlur+ * bokeh, radialGradient auroras) draws unchanged through it. NO html tag is on+ * the list — an svg element's markup is svg, and the html tags that reach it+ * are exactly the carriers: `foreignObject` children, and the foreign-content+ * breakout list, which is where `meta` came from. A diagram that wants a name+ * added here is a one-line change; a diagram that wants `<form>` is not a+ * diagram. An element not on the list is REMOVED WHOLE rather than unwrapped:+ * unwrapping would spill a refused element's text onto the slide, and "refuse"+ * is the rule this list exists to state.+ *+ * `template` is on nobody's list twice over — its children live in `.content`,+ * not `childNodes`, so the walk below would never have seen them while+ * `importNode(n, true)` copied them wholesale.+ */+export const SVG_TAGS = new Set([+ // structure. `style` stays: it cannot execute, its text is run through+ // sanitizeSvgCss, and sanitizeSvg SCOPES it to the element instance (hard-won+ // detail #7) so its rules cannot leak into every other svg on the page.+ // That scoping is passed IN — the sanitizer has no element to name on its+ // own. An earlier version of this comment credited scopeCss directly, which+ // was false: scopeCss's only caller took `el.css`, the model field, and the+ // markup path below was never scoped at all.+ 'svg', 'g', 'defs', 'symbol', 'use', 'switch', 'desc', 'title', 'metadata', 'style', 'view', 'a',+ // shapes and text+ 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',+ 'text', 'tspan', 'textpath', 'image',+ // paint servers, clipping, masking+ 'lineargradient', 'radialgradient', 'stop', 'pattern', 'solidcolor',+ 'clippath', 'mask', 'marker',+ // filters+ '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',+ // SMIL — judged by what they WRITE, see the attributeName rule below+ 'animate', 'animatemotion', 'animatetransform', 'set', 'mpath',+])++/** SMIL: these can WRITE an attribute, so they are judged by their target. */+const SVG_ANIM = new Set(['animate', 'set', 'animatetransform', 'animatemotion'])++/**+ * Attributes an untrusted svg may keep. Same argument as SVG_TAGS: `action`,+ * `formaction`, `http-equiv`, `srcdoc` and every `on*` are refused because they+ * were never permitted, not because a list enumerates them.+ *+ * Matched case-INSENSITIVELY, which is what makes the html parser's foreign-+ * content case fixups (`viewBox`, `attributeName`, `stdDeviation`,+ * `patternUnits`) line up with the lowercase entries here.+ */+const SVG_ATTRS = new Set([+ // core+ 'id', 'class', 'style', 'lang', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink',+ 'role', 'title', 'version', 'baseprofile', 'tabindex', 'media', 'type', 'target',+ 'href', 'xlink:href',+ // geometry+ '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', 'zoomandpan',+ // coordinate systems, paint servers, markers+ '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',+ 'systemlanguage', 'requiredfeatures', 'requiredextensions',+ // presentation+ 'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap',+ 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset',+ 'stroke-opacity', 'opacity', 'color', 'color-interpolation', 'color-interpolation-filters',+ 'display', 'visibility', 'overflow', 'cursor', 'pointer-events', 'shape-rendering',+ 'text-rendering', 'image-rendering', 'vector-effect', 'paint-order', 'mix-blend-mode',+ 'isolation', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',+ 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'word-spacing',+ 'text-anchor', 'text-decoration', 'dominant-baseline', 'alignment-baseline',+ 'baseline-shift', 'writing-mode', 'direction', 'unicode-bidi', 'white-space',+ 'clip', 'clip-path', 'clip-rule', 'mask', 'marker', 'marker-start', 'marker-mid',+ 'marker-end', 'filter', 'stop-color', 'stop-opacity', 'flood-color', 'flood-opacity',+ 'lighting-color', 'enable-background',+ // filter primitives+ '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',+ // SMIL timing+ 'attributename', 'attributetype', 'from', 'to', 'by', 'dur', 'begin', 'end', 'min',+ 'max', 'restart', 'repeatcount', 'repeatdur', 'calcmode', 'keytimes', 'keysplines',+ 'keypoints', 'path', 'additive', 'accumulate', 'origin',+])++/**+ * `data-*` names this renderer, its editor and the kernel read. An author svg+ * carrying one would answer a `[data-el-id="…"]` lookup that is already+ * ambiguous between the canvas and the sidebar thumbnails (hard-won detail #3),+ * so the open `data-*` door below stops short of them.+ *+ * `data-bento` is reserved as a PREFIX, not as one name: the shell's own marks+ * are `data-bento-transient` (kernel `serializeBody` deletes those nodes from+ * the clone it saves) and `data-bento-preview` (which save.ts removes+ * unconditionally, replace-never-append). Reserving the exact string only would+ * have left an author element able to answer either query.+ */+const SVG_DATA_RESERVED = /^data-(el-id|flip-id|slide-id|autoplay|r|c)$|^data-bento/++/**+ * `aria-*` is open-ended by design and inert; `data-*` is how a diagram's own+ * `<style>` selects its parts. Everything else is the list.+ *+ * Exported for `scripts/test-sanitize.ts` — this is a pure decision, so it is+ * pinned in node while the walk that applies it is measured in a browser.+ */+export function svgAttrAllowed(name: string): boolean {+ const n = name.toLowerCase()+ if (n.startsWith('aria-')) return true+ if (n.startsWith('data-')) return !SVG_DATA_RESERVED.test(n)+ return SVG_ATTRS.has(n)+}++/**+ * Tags whose href may leave this document. An `<image>` or `<feImage>` paints+ * a picture and an `<a>` navigates on a click the reader made; every other+ * href in svg (`use`, `pattern`, gradient inheritance, `mpath`, `textPath`)+ * pulls a SUBTREE out of the target document, which is both a fetch and a+ * trust boundary.+ */+const SVG_HREF_REMOTE = new Set(['a', 'image', 'feimage'])++/**+ * May an untrusted svg keep this href?+ *+ * Same-document fragments must survive — gradients, markers and `<use>` all+ * paint through `url(#…)`, and dropping those refs is what would render a+ * diagram blank. Beyond that only the tags above, and only http(s) or a+ * `data:image/` (which the browser loads script-disabled). Everything else+ * goes: `javascript:` obviously, but the bare relative form too, because+ * `//host/x` is relative as well and is a network fetch out of a file the+ * reader believes is self-contained (PLATFORM §1).+ *+ * ASCII whitespace and control characters come out before the test, because a+ * browser ignores them inside a scheme: `java	script:alert(1)` navigates.+ *+ * Exported for `scripts/test-sanitize.ts`: the walk below needs a DOM, this+ * decision does not. `tag` defaults to the permissive case so a caller asking+ * only "is this url shape allowed anywhere" gets that answer.+ */+export function svgHrefAllowed(value: string, tag = 'image'): boolean {+ const v = value.replace(/[\u0000-\u0020]/g, '').toLowerCase()+ if (v.startsWith('#')) return true+ if (!SVG_HREF_REMOTE.has(tag.toLowerCase())) return false+ return /^https?:/.test(v) || v.startsWith('data:image/')+}++/** Every `url(…)` target in a CSS-ish string, quotes and padding removed. */+function urlTargets(value: string): string[] {+ return Array.from(cssDecodeIdentEscapes(value).matchAll(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi))+ .map((m) => m[2].replace(/[\u0000-\u0020]/g, '').toLowerCase())+}+++/**+ * CSS escapes that spell IDENTIFIER characters, decoded: `\75 ` is `u`, `\72`+ * is `r`, `\l` is `l`. The browser decodes escapes inside an ident before it+ * decides what the token is, so a check over the raw text has to read the+ * letters the browser will read. Escapes for anything else (`\28` for a+ * paren, `\22` for a quote) are left as they are: inside an ident they are+ * just part of the name, never syntax, and decoding them here would invent+ * syntax the browser never sees.+ */+export function cssDecodeIdentEscapes(css: string): string {+ return css.replace(/\\([0-9a-fA-F]{1,6})[ \t\n\r\f]?|\\([^\n\r\f0-9a-fA-F])/g, (m, hexs: string | undefined, ch: string | undefined) => {+ const c = hexs ? String.fromCodePoint(Math.min(parseInt(hexs, 16), 0x10ffff)) : ch!+ return /^[-\w]$/.test(c) || c.codePointAt(0)! >= 0x80 ? c : m+ })+}++/**+ * The CSS functions an untrusted svg sheet or style value may call, as an+ * ALLOWLIST, for the reason the at-rules below are one. A function that takes+ * an image can fetch, and some take the address as a bare string with no+ * `url(` in it; a list of the dangerous ones would be one browser release from+ * incomplete. Everything a diagram draws with is here: colour, maths,+ * transforms, gradients, filters, shapes, easing, grid sizing, font-face+ * descriptors, custom properties. `url` is policed on its own (in-document+ * `#` and `data:image/` targets only).+ */+const CSS_FN_ALLOWED = new Set([+ 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color', 'color-mix', 'light-dark',+ 'calc', 'min', 'max', 'clamp', 'round', 'mod', 'rem', 'abs', 'sign', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'pow', 'sqrt', 'hypot', 'log', 'exp',+ 'var', 'env',+ 'translate', 'translatex', 'translatey', 'translatez', 'translate3d', 'rotate', 'rotatex', 'rotatey', 'rotatez', 'rotate3d',+ 'scale', 'scalex', 'scaley', 'scalez', 'scale3d', 'skew', 'skewx', 'skewy', 'matrix', 'matrix3d', 'perspective',+ 'cubic-bezier', 'steps', 'linear',+ 'linear-gradient', 'radial-gradient', 'conic-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient', 'repeating-conic-gradient',+ '-webkit-linear-gradient', '-webkit-radial-gradient', '-webkit-repeating-linear-gradient', '-webkit-repeating-radial-gradient',+ 'blur', 'brightness', 'contrast', 'drop-shadow', 'grayscale', 'hue-rotate', 'invert', 'opacity', 'saturate', 'sepia',+ 'circle', 'ellipse', 'inset', 'polygon', 'path', 'rect', 'xywh', 'ray',+ 'counter', 'counters', 'minmax', 'repeat', 'fit-content', 'local', 'format', 'tech', 'selector',+ 'url',+])++/** A function call in CSS text: a name (letters, escapes, non-ASCII) then `(`.+ * `pre` is the character before it, so a caller can tell a call written+ * straight after a colon. */+const CSS_FN_CALL = /(^|[^\w\\-])((?:[-\w]|\\[\s\S]|[^\x00-\x7f])+)\(/g++/**+ * Selector pseudo-classes and pseudo-elements that take an argument. After a+ * colon, a name on THIS list is a selector (`:not(`, `::part(`), not a value;+ * none of them can fetch. Every other call after a colon is a value+ * (`fill:rgb(`, `width:calc(`) and is judged by CSS_FN_ALLOWED like any other.+ * The text pass used to spare EVERY colon-preceded call, which left+ * `prop:fn(` with no space to the CSSOM check alone — caught there in every+ * browser, but this pass is meant to fail closed on its own.+ */+const CSS_PSEUDO_FNS = new Set([+ 'not', 'is', 'where', 'has', 'matches', '-webkit-any', '-moz-any',+ 'nth-child', 'nth-last-child', 'nth-of-type', 'nth-last-of-type', 'nth-col', 'nth-last-col',+ 'lang', 'dir', 'host', 'host-context', 'state', 'active-view-transition-type',+ 'slotted', 'part', 'cue', 'cue-region', 'highlight',+ 'view-transition-group', 'view-transition-image-pair', 'view-transition-old', 'view-transition-new',+])++/** May this sheet call `name`? `pre` is the character in front of it. */+function cssCallAllowed(pre: string, name: string): boolean {+ if (name.includes('\\')) return false+ const n = name.toLowerCase()+ return CSS_FN_ALLOWED.has(n) || (pre === ':' && CSS_PSEUDO_FNS.has(n))+}++/**+ * Neutralise every function call a sheet may not make: RENAMED to one no+ * browser implements, so the declaration it sits in is invalid and CSS drops+ * it (the same fail-closed move as the at-rules). A name still holding an+ * escape after decoding is refused on sight.+ */+function cssRefuseFunctions(css: string): string {+ return css.replace(CSS_FN_CALL, (m, pre: string, name: string) =>+ cssCallAllowed(pre, name) ? m : `${pre}bento-refused(`)+}++/** Does this CSS text carry a fetch — an off-list function, or a url() to+ * anything but `#…` / `data:image/…`? Escapes are decoded first. */+function cssFetches(text: string): boolean {+ const t = cssDecodeIdentEscapes(text)+ if (urlTargets(t).some((u) => !(u.startsWith('#') || u.startsWith('data:image/')))) return true+ return Array.from(t.matchAll(CSS_FN_CALL)).some((m) => !cssCallAllowed(m[1], m[2]))+}++/**+ * The browser's own reading of a sheet, where there is a browser. A+ * constructed CSSStyleSheet is parsed but never applied, so nothing in it+ * loads, and its rules serialise CANONICALLY: escapes decoded, a bare-string+ * image function written with `url(…)`. Every top-level rule's cssText (which+ * carries its nested rules: @media, @supports, @layer, nesting) is checked for+ * a fetch the text filter missed. There should never be one; if there is, the+ * whole sheet is dropped rather than trusted. `null` = no CSSOM here (the node+ * rigs), where the text filter, which fails closed on its own, is the answer.+ */+function cssomFindsFetch(css: string): boolean | null {+ if (typeof CSSStyleSheet === 'undefined') return null+ try {+ const sheet = new CSSStyleSheet()+ sheet.replaceSync(css)+ return Array.from(sheet.cssRules).some((r) => cssFetches(r.cssText))+ } catch {+ return true // the browser would not parse it: keep none of it+ }+}++/**+ * `url(#grad)` is the gradient/marker idiom every diagram is built on;+ * `url(https://…)` in the same attribute is a live fetch out of a self-+ * contained file, and a read receipt for a mailed deck. So attribute values+ * are checked for their url targets, not just their scheme — `fill`,+ * `filter`, `clip-path`, `mask` and `style` all take one.+ *+ * Exported for `scripts/test-sanitize.ts`.+ */+export function svgUrlRefsAllowed(value: string, attr = ''): boolean {+ const n = attr.toLowerCase()+ const allowed = (t: string) => t.startsWith('#') || t.startsWith('data:image/')+ // aria-* and data-* are text, never parsed as CSS: an accessible label that+ // reads "f(x) = 2" is not a function call, so only a url() is looked at+ if (n.startsWith('aria-') || n.startsWith('data-')) return urlTargets(value).every(allowed)+ if (cssFetches(value)) return false+ // `style` is a declaration block: where there is a browser, its own parse+ // (on a detached element, which loads nothing) is checked too+ if (n === 'style' && typeof document !== 'undefined') {+ const probe = document.createElement('div')+ probe.style.cssText = value+ if (cssFetches(probe.style.cssText)) return false+ }+ return true+}++/**+ * At-rules an untrusted sheet may keep — layout, motion and typography, which+ * is what a diagram's own CSS is for.+ *+ * An ALLOWLIST, and the reason is measured. The first pass cut `@import` by+ * name; Chrome 141 fetched anyway (2026-08-09 — the probe server logged the+ * request), because a CSS at-keyword is an IDENT and an ident may be written+ * with escapes: `@\69mport "https://…";` is the same at-rule and matches no+ * regex spelling `import`. `@im\port` and `@\49MPORT` are two more spellings of+ * it, and there is no end to that list — so the question asked here is which+ * at-rules are WANTED.+ *+ * It also covers the fetch spelled as a bare string, which the url() rewrite+ * below cannot see: `@import "https://…"` has no `url(` in it.+ */+const CSS_AT_ALLOWED = new Set([+ 'media', 'supports', 'layer', 'container', 'scope', 'page', 'starting-style',+ 'font-face', 'font-feature-values', 'counter-style', 'property',+ 'keyframes', '-webkit-keyframes', '-moz-keyframes',+])++/**+ * CSS an untrusted svg may carry, in a `<style>` element or in the model's+ * `css` field. Neutralised rather than refused: a diagram's rules are how it+ * draws, so dropping the sheet costs the artwork, while dropping one fetch+ * costs nothing that was legitimate.+ *+ * A refused at-rule is RENAMED to one no browser implements rather than cut+ * out. CSS error recovery discards an unknown at-rule whole — its prelude, and+ * its block if it has one — so the payload goes and the rest of the sheet still+ * parses, and this stays a string rewrite with no brace matching in it. It is+ * also what makes the missing-semicolon form (`@import "x.css"` with a newline+ * where the `;` should be) a non-case: the parser, not this regex, decides+ * where the at-rule ends.+ *+ * An external `url()` is the same fetch with different syntax (`@font-face`+ * src, `background-image`, `fill`) — rewritten to `none`, which is a valid+ * value everywhere url() is legal, so a sheet stays parseable. Both are the+ * no-CDN rule (PLATFORM §1) and, for a deck sent by mail, a read receipt with+ * the reader's IP on it.+ *+ * The at-keyword scan requires the `@` to start a token, so an `@` inside a+ * value (`content:"a@b"`) is left alone.+ */+export function sanitizeSvgCss(css: string): string {+ const atFiltered = css.replace(/(^|[\s{};,)])@([-\w\\]+)/g, (_m, pre: string, kw: string) =>+ // Written plainly AND wanted. An escape inside the keyword is refused on+ // sight: nobody spells `@media` as `@\6dedia`, so decoding one would only+ // be a second chance to disagree with the browser about what the ident says.+ (/^-?[a-zA-Z][-\w]*$/.test(kw) && CSS_AT_ALLOWED.has(kw.toLowerCase())+ ? `${pre}@${kw}`+ : `${pre}@bento-refused `))+ // Function names are read the way the browser reads them — escapes decoded —+ // before anything is judged, then every function off the allowlist is+ // refused, then url() targets are checked on the decoded text.+ const fnFiltered = cssRefuseFunctions(cssDecodeIdentEscapes(atFiltered))+ const out = fnFiltered.replace(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi, (m, _q: string, target: string) => {+ const v = String(target).replace(/[\u0000-\u0020]/g, '').toLowerCase()+ return v.startsWith('#') || v.startsWith('data:image/') ? m : 'none'+ })+ // …and where there is a browser, its own parse is the last word+ return cssomFindsFetch(out) === true ? '' : out+}++// --- the walk, and the per-app policy ------------------------------------------------++/**+ * How an app tightens the walk. Every field but `scopeStyle` is optional and+ * defaults to slides' behaviour; each one only ever refuses more.+ */+export interface SvgPolicy {+ /**+ * The app's SCOPING for a kept `<style>` element (slides: `css =>+ * scopeCss(css, scope)`). The walk runs sanitizeSvgCss first and hands this+ * the result, so it never sees, and can never keep, unsanitized CSS. `null`+ * refuses `<style>` elements AND `style` attributes outright.+ */+ scopeStyle: ((sanitizedCss: string) => string) | null+ /** Tags refused on top of SVG_TAGS. */+ refuseTags?: Iterable<string>+ /** Attributes refused on top of svgAttrAllowed. */+ refuseAttrs?: Iterable<string>+ /** `false` refuses every `data-*` attribute (default: the open, reserved-aware door). */+ dataAttrs?: boolean+ /**+ * `false` keeps an href only if it is a same-document `#ref`, or an inline+ * raster (`data:image/png|jpeg|gif|webp;base64,`) on `<image>`/`<feImage>`:+ * no http(s), no svg-as-data, no `<a>` navigation.+ */+ remoteHref?: boolean+ /**+ * `true` also refuses any non-href value carrying a CSS escape, a+ * `javascript:`/`vbscript:` or non-raster `data:` scheme anywhere, a url()+ * that is not a `#ref`, `@import`, `expression(` or an image-set.+ */+ strictValues?: boolean+}++interface Rules {+ tag: (t: string) => boolean+ attr: (n: string) => boolean+ scopeStyle: ((sanitizedCss: string) => string) | null+ remoteHref: boolean+ strictValues: boolean+}++function rulesOf(p: SvgPolicy): Rules {+ const tags = new Set(Array.from(p.refuseTags ?? [], (t) => t.toLowerCase()))+ const attrs = new Set(Array.from(p.refuseAttrs ?? [], (a) => a.toLowerCase()))+ if (p.scopeStyle === null) { tags.add('style'); attrs.add('style') }+ const data = p.dataAttrs !== false+ return {+ tag: (t) => SVG_TAGS.has(t) && !tags.has(t),+ attr: (n) => svgAttrAllowed(n) && !attrs.has(n) && (data || !n.startsWith('data-')),+ scopeStyle: p.scopeStyle,+ remoteHref: p.remoteHref !== false,+ strictValues: p.strictValues === true,+ }+}++const RASTER_DATA = /^data:image\/(png|jpe?g|gif|webp);base64,/++/** remoteHref:false: a `#ref` anywhere, an inline raster only on image/feImage. */+function localHrefAllowed(value: string, tag: string): boolean {+ const v = value.replace(/[\u0000-\u0020]/g, '').toLowerCase()+ if (v.startsWith('#')) return true+ return (tag === 'image' || tag === 'feimage') && RASTER_DATA.test(v)+}++/** strictValues: a presentation or SMIL value a picture needs, and no more. */+function strictValueAllowed(value: string): boolean {+ if (value.includes('\\')) return false+ if (/javascript:|vbscript:|data:(?!image\/(png|jpe?g|gif|webp);base64,)/i.test(value.replace(/[\u0000-\u0020]/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)+}++/**+ * Judge one element of an INERT parsed document, and everything under it.+ * `false` = the caller removes it. An element not on the list is removed WHOLE,+ * never unwrapped (see SVG_TAGS).+ */+function cleanElement(el: Element, r: Rules): boolean {+ const tag = el.localName.toLowerCase()+ if (!r.tag(tag)) return false++ for (const attr of Array.from(el.attributes)) {+ const name = attr.name.toLowerCase()+ if (!r.attr(name)) { el.removeAttribute(attr.name); continue }+ if (SVG_ANIM.has(tag) && name === 'attributename') {+ // An animation WRITES an attribute, and it writes it long after this+ // walk has finished — so it is judged by its target. Anything off the+ // allowlist (`onclick`, `formaction`) is refused here even though+ // Blink declines to apply an on* through SMIL today: the refusal must+ // not rest on a browser's restraint. `href`/`style` ARE on the+ // allowlist and still refused, because their values are policed once,+ // below, and an animation is a second chance to set them.+ const target = attr.value.trim().toLowerCase()+ if (!r.attr(target) || /(^|:)(href|style)$/.test(target)) return false+ continue+ }+ if (!svgUrlRefsAllowed(attr.value, name) || (name === 'style' && /@import|expression\s*\(/i.test(attr.value))) {+ el.removeAttribute(attr.name)+ continue+ }+ if (name !== 'href' && name !== 'xlink:href') {+ if (r.strictValues && !strictValueAllowed(attr.value)) el.removeAttribute(attr.name)+ continue+ }+ if (r.remoteHref ? svgHrefAllowed(attr.value, tag) : localHrefAllowed(attr.value, tag)) continue+ // a <use> IS its href, and one that cannot be resolved in-document+ // instances a subtree from a document that is not ours to trust; a dead+ // <a> or <image> is merely inert, so it keeps its place in the layout.+ if (tag === 'use') return false+ el.removeAttribute(attr.name)+ }++ if (tag === 'style') {+ // Assigning textContent also discards any element children, which the+ // html parser really does build here: inside foreign content the+ // tokenizer stays in the data state, so `<svg><style><img src=x+ // onerror=…></style>` parses that img as an ELEMENT, not as css text.+ // Sanitized HERE, always; the app's hook only scopes the result. (r.tag+ // refused 'style' already when scopeStyle is null.)+ el.textContent = r.scopeStyle!(sanitizeSvgCss(el.textContent ?? ''))+ return true+ }+ cleanChildren(el, r)+ return true+}++function cleanChildren(node: Node, r: Rules): void {+ for (const child of Array.from(node.childNodes)) {+ if (child.nodeType === Node.TEXT_NODE) continue+ if (child.nodeType !== Node.ELEMENT_NODE || !cleanElement(child as Element, r)) child.remove()+ }+}++/**+ * Sanitize every child of `node` (an inert parsed document's body, say) in+ * place: refused elements, comments and processing instructions are removed,+ * text is kept. The caller imports the survivors; it never re-parses a string.+ */+export function cleanSvgChildren(node: Node, policy: SvgPolicy): void {+ cleanChildren(node, rulesOf(policy))+}++/** The same for one element itself. `false` = the caller removes it. */+export function cleanSvgElement(el: Element, policy: SvgPolicy): boolean {+ return cleanElement(el, rulesOf(policy))+}diff --git a/scripts/test-svgsafe-policy-browser.mjs b/scripts/test-svgsafe-policy-browser.mjsnew file mode 100644index 00000000..947debe9--- /dev/null+++ b/scripts/test-svgsafe-policy-browser.mjs@@ -0,0 +1,130 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// kernel/src/svgsafe.ts: every policy option ONLY TIGHTENS slides' default.+//+// Run: node scripts/test-svgsafe-policy-browser.mjs (PLAYWRIGHT_MODULE, as in CI)+//+// The default policy is slides' renderer, held by test-sanitize.ts and the egress+// rigs. This rig holds the options an app adds on top of it (type's embed+// pictures use all of them), in Chromium, because the walk runs on parsed DOM:+// - each option REMOVES something the default keeps (it is not a no-op);+// - under every option and under all of them at once, every kept element and+// attribute was also kept by the default (no option is ever looser).++import { execFileSync } from 'node:child_process'+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')+let checks = 0, failures = 0+const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }++// bundle the module for the page (esbuild, as the other kernel rigs)+const dir = mkdtempSync(join(tmpdir(), 'svgsafe-'))+const entry = join(dir, 'entry.ts'), out = join(dir, 'bundle.js')+await import('node:fs').then((fs) => fs.writeFileSync(entry,+ `import { cleanSvgChildren } from ${JSON.stringify(join(ROOT, 'kernel/src/svgsafe.ts'))}\n` ++ `;(globalThis as any).__run = (markup: string, policy: any) => {\n` ++ ` const doc = new DOMParser().parseFromString(markup, 'text/html')\n` ++ ` try { cleanSvgChildren(doc.body, policy) } catch (e) { return ['THREW: ' + e] }\n` ++ ` // what was KEPT: every element by its tag path (no sibling indexes, which a\n` ++ ` // removed sibling would shift), with its attributes; compared as multisets\n` ++ ` const kept: string[] = []\n` ++ ` const walk = (n: Element, path: string) => Array.from(n.children).forEach((c) => {\n` ++ ` const p = path + '/' + c.localName\n` ++ ` kept.push(p); for (const a of Array.from(c.attributes)) kept.push(p + '@' + a.name.toLowerCase() + '=' + a.value)\n` ++ ` walk(c, p) })\n` ++ ` walk(doc.body, '')\n` ++ ` return kept\n}\n` ++ `;(globalThis as any).__sheetOf = (markup: string) => {\n` ++ ` const doc = new DOMParser().parseFromString(markup, 'text/html')\n` ++ ` cleanSvgChildren(doc.body, { scopeStyle: (css: string) => css })\n` ++ ` return doc.body.querySelector('style')?.textContent ?? null\n}\n`))+execFileSync(join(ROOT, 'slides/node_modules/.bin/esbuild'), [entry, '--bundle', '--format=iife', '--log-level=error', `--outfile=${out}`])+const bundle = readFileSync(out, 'utf8')+rmSync(dir, { recursive: true, force: true })++const S = 'script'+const scoped = 'css => css' // the default's scopeStyle hook: a no-op scope (scoping is not under test)+const OPTIONS = {+ 'scopeStyle: null': { scopeStyle: null },+ 'refuseTags: [a]': { refuseTags: ['a'] },+ 'refuseAttrs: [cursor, title]': { refuseAttrs: ['cursor', 'title'] },+ 'dataAttrs: false': { dataAttrs: false },+ 'remoteHref: false': { remoteHref: false },+ 'strictValues: true': { strictValues: true },+}+// one input per option where the DEFAULT keeps something that option must remove+const BITES = {+ 'scopeStyle: null': '<svg><style>rect{fill:red}</style><rect width="5" height="5" style="fill:red"/></svg>',+ 'refuseTags: [a]': '<svg><a href="#x"><circle r="5"/></a></svg>',+ 'refuseAttrs: [cursor, title]': '<svg><rect width="5" height="5" cursor="pointer" title="t"/></svg>',+ 'dataAttrs: false': '<svg><rect width="5" height="5" data-part="bar"/></svg>',+ 'remoteHref: false': '<svg><image href="https://example.test/x.png" width="5" height="5"/><image href="data:image/svg+xml;base64,PHN2Zy8+" width="5" height="5"/></svg>',+ 'strictValues: true': '<svg><rect width="5" height="5" fill="url(data:image/png;base64,iVBORw0KGgo=)" font-family="A\\42 C"/></svg>',+}+// a broad set: benign pictures and hostile markup alike+const INPUTS = [+ ...Object.values(BITES),+ '<svg viewBox="0 0 10 10"><defs><linearGradient id="g"><stop offset="0" stop-color="#f00"/></linearGradient></defs><rect width="10" height="10" fill="url(#g)"/></svg>',+ '<svg viewBox="0 0 10 10"><symbol id="s"><circle r="2"/></symbol><use href="#s"/><use href="https://example.test/s.svg#a"/></svg>',+ '<svg><circle r="5"><animate attributeName="r" from="2" to="4" dur="1s"/><set attributeName="onclick" to="x"/></circle></svg>',+ '<svg><a href="https://example.test"><text>x</text></a><a href="javascript:alert(1)"><text>y</text></a></svg>',+ `<svg><${S}>x()</${S}><foreignObject><img src=x onerror=x()></foreignObject><circle/onmouseover="x()" r="1"/></svg>`,+ '<svg><style>@import "https://example.test/x.css"; rect{fill:url(https://example.test/p)}</style></svg>',+ '<svg><rect width="5" height="5" data-el-id="x" data-foo="y" aria-label="f(x)" tabindex="0" style="fill:url(#g)"/></svg>',+ '<svg><feImage href="https://example.test/x.png"/><image href="data:image/png;base64,iVBORw0KGgo="/></svg>',+]++/** What `tight` keeps beyond `base`, counting repeats (a multiset difference). */+function beyond(base, tight) {+ const left = new Map()+ for (const k of base) left.set(k, (left.get(k) ?? 0) + 1)+ return tight.filter((k) => { const n = left.get(k) ?? 0; if (n) { left.set(k, n - 1); return false } return true })+}++const pw = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+const browser = await pw.chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH })+try {+ const page = await browser.newPage()+ await page.setContent('<!doctype html><html><body></body></html>')+ await page.addScriptTag({ content: bundle })+ const run = (markup, extra) => page.evaluate(([m, e, hook]) => {+ const policy = { scopeStyle: eval(hook), ...e }+ return globalThis.__run(m, policy)+ }, [markup, extra, scoped])++ console.log('\neach option removes something the default keeps')+ for (const [name, opt] of Object.entries(OPTIONS)) {+ const base = await run(BITES[name], {}), tight = await run(BITES[name], opt)+ ok(tight.length < base.length && beyond(base, tight).length === 0, `${name}: ${base.length - tight.length} kept item(s) fewer`)+ }++ console.log('\nnever looser: whatever an option keeps, the default kept too')+ const all = Object.assign({}, ...Object.values(OPTIONS))+ for (const [name, opt] of [...Object.entries(OPTIONS), ['all options at once', all]]) {+ let extra = []+ for (const x of INPUTS) {+ extra.push(...beyond(await run(x, {}), await run(x, opt)))+ }+ ok(extra.length === 0, `${name}, over ${INPUTS.length} inputs${extra.length ? ' — kept beyond the default: ' + extra.slice(0, 3).join('; ') : ''}`)+ }++ console.log('\nthe style hook only scopes: the walk sanitizes every kept sheet itself (security)')+ // an app passing the identity hook still gets a SANITIZED sheet, never the raw one+ const raw = '<svg><style>@import "https://example.test/x.css"; rect{fill:url(https://example.test/p)} @\\69mport "https://example.test/y.css";</style></svg>'+ const text = await page.evaluate((m) => globalThis.__sheetOf(m), raw)+ // both at-rules renamed (the escaped one too), so the parser drops them whole;+ // the url() to a remote target rewritten to none+ ok(typeof text === 'string' && !/@import|@\\69/i.test(text) && (text.match(/@bento-refused/g) ?? []).length === 2 && !/url\(\s*['"]?https/i.test(text) && text.includes('fill:none'),+ `with css => css as the hook, the kept sheet is still sanitized: ${JSON.stringify(text).slice(0, 90)}`)+ const noHook = await page.evaluate((m) => { try { return globalThis.__run(m, { scopeStyle: null }) } catch (e) { return String(e) } }, BITES['scopeStyle: null'])+ ok(Array.isArray(noHook) && !noHook.some((k) => k.endsWith('/style') || k.includes('@style=')), 'scopeStyle: null drops <style> and style= alike')+} finally {+ await browser.close()+}+console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/slides/src/render.ts b/slides/src/render.tsindex bdb03f51..aff92db7 100644--- a/slides/src/render.ts+++ b/slides/src/render.ts@@ -12,6 +12,11 @@ import { resolveMathHtml } from './maths/delimiters.ts'import { renderCodeInto } from './code'import { formatDate } from './datefmt'import { cropImgStyle, isIdentityCrop } from './crop'+// the shared svg sanitizer (kernel/src/svgsafe.ts, lifted from here): names+// re-exported so callers and rigs keep importing them from the renderer, and+// cssDecodeIdentEscapes is the SAME decoder the colour gate below reads with+import { SVG_TAGS, svgAttrAllowed, svgHrefAllowed, svgUrlRefsAllowed, sanitizeSvgCss, cssDecodeIdentEscapes, cleanSvgChildren } from '../../kernel/src/svgsafe.ts'+export { SVG_TAGS, svgAttrAllowed, svgHrefAllowed, svgUrlRefsAllowed, sanitizeSvgCss }const SVG_NS = 'http://www.w3.org/2000/svg'@@ -442,386 +447,6 @@ function stripAllTags(html: string): string {// System Access handle ⌘S writes through, so "the document can run script" is// the document AND the file on disk.-/**- * The svg vocabulary an untrusted diagram may use. AN ALLOWLIST, and that is- * the whole point of this rewrite.- *- * The first version of this sanitizer named five tags and three attributes,- * and a verifier walked through the gap five ways in Chrome 141 (2026-08-09):- * `<form action="javascript:…">` under a full-slide transparent submit button- * (ONE click anywhere on the slide), `<button formaction="javascript:…">`,- * `<meta http-equiv="refresh">` — which actually navigated the reader's page- * off to an attacker host, and which the html parser lets break out of foreign- * content so `<svg><rect/><meta …></svg>` reaches the body too — `<base href>`- * (a media `src` is documented as possibly relative, so retargeting resolution- * is a live fetch), and `<link rel=stylesheet>`. Not one of those is on this- * list, so not one of them had to be named, and neither does whatever the next- * browser ships.- *- * Sized against the content that exists: every svg asset in `starterdeck.ts`- * (userSpaceOnUse patterns, feTurbulence + feColorMatrix grain, feGaussianBlur- * bokeh, radialGradient auroras) draws unchanged through it. NO html tag is on- * the list — an svg element's markup is svg, and the html tags that reach it- * are exactly the carriers: `foreignObject` children, and the foreign-content- * breakout list, which is where `meta` came from. A diagram that wants a name- * added here is a one-line change; a diagram that wants `<form>` is not a- * diagram. An element not on the list is REMOVED WHOLE rather than unwrapped:- * unwrapping would spill a refused element's text onto the slide, and "refuse"- * is the rule this list exists to state.- *- * `template` is on nobody's list twice over — its children live in `.content`,- * not `childNodes`, so the walk below would never have seen them while- * `importNode(n, true)` copied them wholesale.- */-export const SVG_TAGS = new Set([- // structure. `style` stays: it cannot execute, its text is run through- // sanitizeSvgCss, and sanitizeSvg SCOPES it to the element instance (hard-won- // detail #7) so its rules cannot leak into every other svg on the page.- // That scoping is passed IN — the sanitizer has no element to name on its- // own. An earlier version of this comment credited scopeCss directly, which- // was false: scopeCss's only caller took `el.css`, the model field, and the- // markup path below was never scoped at all.- 'svg', 'g', 'defs', 'symbol', 'use', 'switch', 'desc', 'title', 'metadata', 'style', 'view', 'a',- // shapes and text- 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',- 'text', 'tspan', 'textpath', 'image',- // paint servers, clipping, masking- 'lineargradient', 'radialgradient', 'stop', 'pattern', 'solidcolor',- 'clippath', 'mask', 'marker',- // filters- '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',- // SMIL — judged by what they WRITE, see the attributeName rule below- 'animate', 'animatemotion', 'animatetransform', 'set', 'mpath',-])--/** SMIL: these can WRITE an attribute, so they are judged by their target. */-const SVG_ANIM = new Set(['animate', 'set', 'animatetransform', 'animatemotion'])--/**- * Attributes an untrusted svg may keep. Same argument as SVG_TAGS: `action`,- * `formaction`, `http-equiv`, `srcdoc` and every `on*` are refused because they- * were never permitted, not because a list enumerates them.- *- * Matched case-INSENSITIVELY, which is what makes the html parser's foreign-- * content case fixups (`viewBox`, `attributeName`, `stdDeviation`,- * `patternUnits`) line up with the lowercase entries here.- */-const SVG_ATTRS = new Set([- // core- 'id', 'class', 'style', 'lang', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink',- 'role', 'title', 'version', 'baseprofile', 'tabindex', 'media', 'type', 'target',- 'href', 'xlink:href',- // geometry- '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', 'zoomandpan',- // coordinate systems, paint servers, markers- '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',- 'systemlanguage', 'requiredfeatures', 'requiredextensions',- // presentation- 'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap',- 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset',- 'stroke-opacity', 'opacity', 'color', 'color-interpolation', 'color-interpolation-filters',- 'display', 'visibility', 'overflow', 'cursor', 'pointer-events', 'shape-rendering',- 'text-rendering', 'image-rendering', 'vector-effect', 'paint-order', 'mix-blend-mode',- 'isolation', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',- 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'word-spacing',- 'text-anchor', 'text-decoration', 'dominant-baseline', 'alignment-baseline',- 'baseline-shift', 'writing-mode', 'direction', 'unicode-bidi', 'white-space',- 'clip', 'clip-path', 'clip-rule', 'mask', 'marker', 'marker-start', 'marker-mid',- 'marker-end', 'filter', 'stop-color', 'stop-opacity', 'flood-color', 'flood-opacity',- 'lighting-color', 'enable-background',- // filter primitives- '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',- // SMIL timing- 'attributename', 'attributetype', 'from', 'to', 'by', 'dur', 'begin', 'end', 'min',- 'max', 'restart', 'repeatcount', 'repeatdur', 'calcmode', 'keytimes', 'keysplines',- 'keypoints', 'path', 'additive', 'accumulate', 'origin',-])--/**- * `data-*` names this renderer, its editor and the kernel read. An author svg- * carrying one would answer a `[data-el-id="…"]` lookup that is already- * ambiguous between the canvas and the sidebar thumbnails (hard-won detail #3),- * so the open `data-*` door below stops short of them.- *- * `data-bento` is reserved as a PREFIX, not as one name: the shell's own marks- * are `data-bento-transient` (kernel `serializeBody` deletes those nodes from- * the clone it saves) and `data-bento-preview` (which save.ts removes- * unconditionally, replace-never-append). Reserving the exact string only would- * have left an author element able to answer either query.- */-const SVG_DATA_RESERVED = /^data-(el-id|flip-id|slide-id|autoplay|r|c)$|^data-bento/--/**- * `aria-*` is open-ended by design and inert; `data-*` is how a diagram's own- * `<style>` selects its parts. Everything else is the list.- *- * Exported for `scripts/test-sanitize.ts` — this is a pure decision, so it is- * pinned in node while the walk that applies it is measured in a browser.- */-export function svgAttrAllowed(name: string): boolean {- const n = name.toLowerCase()- if (n.startsWith('aria-')) return true- if (n.startsWith('data-')) return !SVG_DATA_RESERVED.test(n)- return SVG_ATTRS.has(n)-}--/**- * Tags whose href may leave this document. An `<image>` or `<feImage>` paints- * a picture and an `<a>` navigates on a click the reader made; every other- * href in svg (`use`, `pattern`, gradient inheritance, `mpath`, `textPath`)- * pulls a SUBTREE out of the target document, which is both a fetch and a- * trust boundary.- */-const SVG_HREF_REMOTE = new Set(['a', 'image', 'feimage'])--/**- * May an untrusted svg keep this href?- *- * Same-document fragments must survive — gradients, markers and `<use>` all- * paint through `url(#…)`, and dropping those refs is what would render a- * diagram blank. Beyond that only the tags above, and only http(s) or a- * `data:image/` (which the browser loads script-disabled). Everything else- * goes: `javascript:` obviously, but the bare relative form too, because- * `//host/x` is relative as well and is a network fetch out of a file the- * reader believes is self-contained (PLATFORM §1).- *- * ASCII whitespace and control characters come out before the test, because a- * browser ignores them inside a scheme: `java	script:alert(1)` navigates.- *- * Exported for `scripts/test-sanitize.ts`: the walk below needs a DOM, this- * decision does not. `tag` defaults to the permissive case so a caller asking- * only "is this url shape allowed anywhere" gets that answer.- */-export function svgHrefAllowed(value: string, tag = 'image'): boolean {- const v = value.replace(/[\u0000-\u0020]/g, '').toLowerCase()- if (v.startsWith('#')) return true- if (!SVG_HREF_REMOTE.has(tag.toLowerCase())) return false- return /^https?:/.test(v) || v.startsWith('data:image/')-}--/** Every `url(…)` target in a CSS-ish string, quotes and padding removed. */-function urlTargets(value: string): string[] {- return Array.from(cssDecodeIdentEscapes(value).matchAll(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi))- .map((m) => m[2].replace(/[\u0000-\u0020]/g, '').toLowerCase())-}---/**- * CSS escapes that spell IDENTIFIER characters, decoded: `\75 ` is `u`, `\72`- * is `r`, `\l` is `l`. The browser decodes escapes inside an ident before it- * decides what the token is, so a check over the raw text has to read the- * letters the browser will read. Escapes for anything else (`\28` for a- * paren, `\22` for a quote) are left as they are: inside an ident they are- * just part of the name, never syntax, and decoding them here would invent- * syntax the browser never sees.- */-function cssDecodeIdentEscapes(css: string): string {- return css.replace(/\\([0-9a-fA-F]{1,6})[ \t\n\r\f]?|\\([^\n\r\f0-9a-fA-F])/g, (m, hexs: string | undefined, ch: string | undefined) => {- const c = hexs ? String.fromCodePoint(Math.min(parseInt(hexs, 16), 0x10ffff)) : ch!- return /^[-\w]$/.test(c) || c.codePointAt(0)! >= 0x80 ? c : m- })-}--/**- * The CSS functions an untrusted svg sheet or style value may call, as an- * ALLOWLIST, for the reason the at-rules below are one. A function that takes- * an image can fetch, and some take the address as a bare string with no- * `url(` in it; a list of the dangerous ones would be one browser release from- * incomplete. Everything a diagram draws with is here: colour, maths,- * transforms, gradients, filters, shapes, easing, grid sizing, font-face- * descriptors, custom properties. `url` is policed on its own (in-document- * `#` and `data:image/` targets only).- */-const CSS_FN_ALLOWED = new Set([- 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'color', 'color-mix', 'light-dark',- 'calc', 'min', 'max', 'clamp', 'round', 'mod', 'rem', 'abs', 'sign', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'pow', 'sqrt', 'hypot', 'log', 'exp',- 'var', 'env',- 'translate', 'translatex', 'translatey', 'translatez', 'translate3d', 'rotate', 'rotatex', 'rotatey', 'rotatez', 'rotate3d',- 'scale', 'scalex', 'scaley', 'scalez', 'scale3d', 'skew', 'skewx', 'skewy', 'matrix', 'matrix3d', 'perspective',- 'cubic-bezier', 'steps', 'linear',- 'linear-gradient', 'radial-gradient', 'conic-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient', 'repeating-conic-gradient',- '-webkit-linear-gradient', '-webkit-radial-gradient', '-webkit-repeating-linear-gradient', '-webkit-repeating-radial-gradient',- 'blur', 'brightness', 'contrast', 'drop-shadow', 'grayscale', 'hue-rotate', 'invert', 'opacity', 'saturate', 'sepia',- 'circle', 'ellipse', 'inset', 'polygon', 'path', 'rect', 'xywh', 'ray',- 'counter', 'counters', 'minmax', 'repeat', 'fit-content', 'local', 'format', 'tech', 'selector',- 'url',-])--/** A function call in CSS text: a name (letters, escapes, non-ASCII) then `(`.- * `pre` is the character before it, so a caller can tell a call written- * straight after a colon. */-const CSS_FN_CALL = /(^|[^\w\\-])((?:[-\w]|\\[\s\S]|[^\x00-\x7f])+)\(/g--/**- * Selector pseudo-classes and pseudo-elements that take an argument. After a- * colon, a name on THIS list is a selector (`:not(`, `::part(`), not a value;- * none of them can fetch. Every other call after a colon is a value- * (`fill:rgb(`, `width:calc(`) and is judged by CSS_FN_ALLOWED like any other.- * The text pass used to spare EVERY colon-preceded call, which left- * `prop:fn(` with no space to the CSSOM check alone — caught there in every- * browser, but this pass is meant to fail closed on its own.- */-const CSS_PSEUDO_FNS = new Set([- 'not', 'is', 'where', 'has', 'matches', '-webkit-any', '-moz-any',- 'nth-child', 'nth-last-child', 'nth-of-type', 'nth-last-of-type', 'nth-col', 'nth-last-col',- 'lang', 'dir', 'host', 'host-context', 'state', 'active-view-transition-type',- 'slotted', 'part', 'cue', 'cue-region', 'highlight',- 'view-transition-group', 'view-transition-image-pair', 'view-transition-old', 'view-transition-new',-])--/** May this sheet call `name`? `pre` is the character in front of it. */-function cssCallAllowed(pre: string, name: string): boolean {- if (name.includes('\\')) return false- const n = name.toLowerCase()- return CSS_FN_ALLOWED.has(n) || (pre === ':' && CSS_PSEUDO_FNS.has(n))-}--/**- * Neutralise every function call a sheet may not make: RENAMED to one no- * browser implements, so the declaration it sits in is invalid and CSS drops- * it (the same fail-closed move as the at-rules). A name still holding an- * escape after decoding is refused on sight.- */-function cssRefuseFunctions(css: string): string {- return css.replace(CSS_FN_CALL, (m, pre: string, name: string) =>- cssCallAllowed(pre, name) ? m : `${pre}bento-refused(`)-}--/** Does this CSS text carry a fetch — an off-list function, or a url() to- * anything but `#…` / `data:image/…`? Escapes are decoded first. */-function cssFetches(text: string): boolean {- const t = cssDecodeIdentEscapes(text)- if (urlTargets(t).some((u) => !(u.startsWith('#') || u.startsWith('data:image/')))) return true- return Array.from(t.matchAll(CSS_FN_CALL)).some((m) => !cssCallAllowed(m[1], m[2]))-}--/**- * The browser's own reading of a sheet, where there is a browser. A- * constructed CSSStyleSheet is parsed but never applied, so nothing in it- * loads, and its rules serialise CANONICALLY: escapes decoded, a bare-string- * image function written with `url(…)`. Every top-level rule's cssText (which- * carries its nested rules: @media, @supports, @layer, nesting) is checked for- * a fetch the text filter missed. There should never be one; if there is, the- * whole sheet is dropped rather than trusted. `null` = no CSSOM here (the node- * rigs), where the text filter, which fails closed on its own, is the answer.- */-function cssomFindsFetch(css: string): boolean | null {- if (typeof CSSStyleSheet === 'undefined') return null- try {- const sheet = new CSSStyleSheet()- sheet.replaceSync(css)- return Array.from(sheet.cssRules).some((r) => cssFetches(r.cssText))- } catch {- return true // the browser would not parse it: keep none of it- }-}--/**- * `url(#grad)` is the gradient/marker idiom every diagram is built on;- * `url(https://…)` in the same attribute is a live fetch out of a self-- * contained file, and a read receipt for a mailed deck. So attribute values- * are checked for their url targets, not just their scheme — `fill`,- * `filter`, `clip-path`, `mask` and `style` all take one.- *- * Exported for `scripts/test-sanitize.ts`.- */-export function svgUrlRefsAllowed(value: string, attr = ''): boolean {- const n = attr.toLowerCase()- const allowed = (t: string) => t.startsWith('#') || t.startsWith('data:image/')- // aria-* and data-* are text, never parsed as CSS: an accessible label that- // reads "f(x) = 2" is not a function call, so only a url() is looked at- if (n.startsWith('aria-') || n.startsWith('data-')) return urlTargets(value).every(allowed)- if (cssFetches(value)) return false- // `style` is a declaration block: where there is a browser, its own parse- // (on a detached element, which loads nothing) is checked too- if (n === 'style' && typeof document !== 'undefined') {- const probe = document.createElement('div')- probe.style.cssText = value- if (cssFetches(probe.style.cssText)) return false- }- return true-}--/**- * At-rules an untrusted sheet may keep — layout, motion and typography, which- * is what a diagram's own CSS is for.- *- * An ALLOWLIST, and the reason is measured. The first pass cut `@import` by- * name; Chrome 141 fetched anyway (2026-08-09 — the probe server logged the- * request), because a CSS at-keyword is an IDENT and an ident may be written- * with escapes: `@\69mport "https://…";` is the same at-rule and matches no- * regex spelling `import`. `@im\port` and `@\49MPORT` are two more spellings of- * it, and there is no end to that list — so the question asked here is which- * at-rules are WANTED.- *- * It also covers the fetch spelled as a bare string, which the url() rewrite- * below cannot see: `@import "https://…"` has no `url(` in it.- */-const CSS_AT_ALLOWED = new Set([- 'media', 'supports', 'layer', 'container', 'scope', 'page', 'starting-style',- 'font-face', 'font-feature-values', 'counter-style', 'property',- 'keyframes', '-webkit-keyframes', '-moz-keyframes',-])--/**- * CSS an untrusted svg may carry, in a `<style>` element or in the model's- * `css` field. Neutralised rather than refused: a diagram's rules are how it- * draws, so dropping the sheet costs the artwork, while dropping one fetch- * costs nothing that was legitimate.- *- * A refused at-rule is RENAMED to one no browser implements rather than cut- * out. CSS error recovery discards an unknown at-rule whole — its prelude, and- * its block if it has one — so the payload goes and the rest of the sheet still- * parses, and this stays a string rewrite with no brace matching in it. It is- * also what makes the missing-semicolon form (`@import "x.css"` with a newline- * where the `;` should be) a non-case: the parser, not this regex, decides- * where the at-rule ends.- *- * An external `url()` is the same fetch with different syntax (`@font-face`- * src, `background-image`, `fill`) — rewritten to `none`, which is a valid- * value everywhere url() is legal, so a sheet stays parseable. Both are the- * no-CDN rule (PLATFORM §1) and, for a deck sent by mail, a read receipt with- * the reader's IP on it.- *- * The at-keyword scan requires the `@` to start a token, so an `@` inside a- * value (`content:"a@b"`) is left alone.- */-export function sanitizeSvgCss(css: string): string {- const atFiltered = css.replace(/(^|[\s{};,)])@([-\w\\]+)/g, (_m, pre: string, kw: string) =>- // Written plainly AND wanted. An escape inside the keyword is refused on- // sight: nobody spells `@media` as `@\6dedia`, so decoding one would only- // be a second chance to disagree with the browser about what the ident says.- (/^-?[a-zA-Z][-\w]*$/.test(kw) && CSS_AT_ALLOWED.has(kw.toLowerCase())- ? `${pre}@${kw}`- : `${pre}@bento-refused `))- // Function names are read the way the browser reads them — escapes decoded —- // before anything is judged, then every function off the allowlist is- // refused, then url() targets are checked on the decoded text.- const fnFiltered = cssRefuseFunctions(cssDecodeIdentEscapes(atFiltered))- const out = fnFiltered.replace(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi, (m, _q: string, target: string) => {- const v = String(target).replace(/[\u0000-\u0020]/g, '').toLowerCase()- return v.startsWith('#') || v.startsWith('data:image/') ? m : 'none'- })- // …and where there is a browser, its own parse is the last word- return cssomFindsFetch(out) === true ? '' : out-}/*** Author svg markup → nodes this document can safely hold.@@ -856,60 +481,11 @@ export function sanitizeSvg(markup: string, scope: string): DocumentFragment {const out = document.createDocumentFragment()if (!markup) return outconst parsed = new DOMParser().parseFromString(markup, 'text/html')-- const walk = (node: Node) => {- for (const child of Array.from(node.childNodes)) {- if (child.nodeType === Node.TEXT_NODE) continue- if (child.nodeType !== Node.ELEMENT_NODE) { child.remove(); continue }- const el = child as Element- const tag = el.localName.toLowerCase()- if (!SVG_TAGS.has(tag)) { el.remove(); continue }-- let gone = false- for (const attr of Array.from(el.attributes)) {- const name = attr.name.toLowerCase()- if (!svgAttrAllowed(name)) { el.removeAttribute(attr.name); continue }- if (SVG_ANIM.has(tag) && name === 'attributename') {- // An animation WRITES an attribute, and it writes it long after this- // walk has finished — so it is judged by its target. Anything off the- // allowlist (`onclick`, `formaction`) is refused here even though- // Blink declines to apply an on* through SMIL today: the refusal must- // not rest on a browser's restraint. `href`/`style` ARE on the- // allowlist and still refused, because their values are policed once,- // below, and an animation is a second chance to set them.- const target = attr.value.trim().toLowerCase()- if (!svgAttrAllowed(target) || /(^|:)(href|style)$/.test(target)) { gone = true; break }- continue- }- if (!svgUrlRefsAllowed(attr.value, name) || (name === 'style' && /@import|expression\s*\(/i.test(attr.value))) {- el.removeAttribute(attr.name)- continue- }- if (name !== 'href' && name !== 'xlink:href') continue- if (svgHrefAllowed(attr.value, tag)) continue- // a <use> IS its href, and one that cannot be resolved in-document- // instances a subtree from a document that is not ours to trust; a dead- // <a> or <image> is merely inert, so it keeps its place in the layout.- if (tag === 'use') { gone = true; break }- el.removeAttribute(attr.name)- }- if (gone) { el.remove(); continue }-- if (tag === 'style') {- // Assigning textContent also discards any element children, which the- // html parser really does build here: inside foreign content the- // tokenizer stays in the data state, so `<svg><style><img src=x- // onerror=…></style>` parses that img as an ELEMENT, not as css text.- // Scoped as well as sanitized. An svg <style> applies DOCUMENT-WIDE, so- // one diagram's rules reach every other svg on the page — the exact- // hazard scopeCss exists for, which until now only `el.css` got.- el.textContent = scopeCss(sanitizeSvgCss(el.textContent ?? ''), scope)- continue- }- walk(el)- }- }- walk(parsed.body)+ // Scoped as well as sanitized. An svg <style> applies DOCUMENT-WIDE, so one+ // diagram's rules would reach every other svg on the page — the exact hazard+ // scopeCss exists for, which once only `el.css` got.+ // (the walk sanitizes each sheet itself; this hook only scopes it)+ cleanSvgChildren(parsed.body, { scopeStyle: (css) => scopeCss(css, scope) })// importNode, not a bare append: the nodes live in the inert parsed document,// and relying on DOM4's implicit adopt is a trap for the next edit.for (const n of Array.from(parsed.body.childNodes)) out.appendChild(document.importNode(n, true))