Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: embed pictures use the kernel's shared SVG sanitizer (#849)

nyblnetdfda71faf8b1
diff --git a/scripts/test-type-sinks-browser.mjs b/scripts/test-type-sinks-browser.mjs
index af444b37..a347b90f 100644
--- a/scripts/test-type-sinks-browser.mjs
+++ b/scripts/test-type-sinks-browser.mjs
@@ -34,6 +34,14 @@ const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}
const SHELL = new URL('../type/dist-single/Bento_Type.bento.html', import.meta.url).href
const RUN = 'window.__pwned=(window.__pwned||0)+1'
+// The attributes an embed picture refuses although slides' diagrams keep them
+// (EMBED_POLICY.refuseAttrs). Written out HERE, not read from the policy, so
+// emptying the policy's list cannot empty the check. Hygiene rather than a
+// boundary: remote url() and on* are refused by the base walk regardless.
+const REFUSED = ['baseprofile', 'color-interpolation', 'color-interpolation-filters', 'cursor', 'enable-background',
+ 'font', 'font-size-adjust', 'font-stretch', 'font-variant', 'isolation', 'media', 'mix-blend-mode',
+ 'pointer-events', 'requiredextensions', 'requiredfeatures', 'systemlanguage', 'tabindex', 'target',
+ 'title', 'type', 'unicode-bidi', 'white-space', 'zoomandpan']
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>`,
@@ -51,6 +59,15 @@ const HOSTILE = {
// 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>`,
+ // an embed's picture may hold NO remote reference (a fetch out of a
+ // self-contained file is a read receipt) and NO data-* (names like
+ // data-bento-preview and data-el-id are what the shell and editor look up)
+ 'remote https image': `<svg width="80" height="80"><image href="https://rc.test/i.png" width="70" height="70"/><rect width="10" height="10"/></svg>`,
+ // strictValues: a backslash anywhere in a value is refused (the base walk
+ // already decodes escapes before judging url(), so this is defence in depth)
+ 'escaped values': `<svg width="80" height="80"><rect fill="r\\65 d" stroke="u\\72l(#g)" width="70" height="70"/></svg>`,
+ 'slides-only attributes': `<svg width="80" height="80"><rect ${REFUSED.map((a) => `${a}="1"`).join(' ')} width="70" height="70"/></svg>`,
+ 'data-* attributes': `<svg width="80" height="80" data-bento-preview="1"><rect data-el-id="x" data-note="n1" width="70" height="70"/></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>`
@@ -88,16 +105,19 @@ try {
const before = requests.length
await p.evaluate((j) => window.bento.loadDoc(j), docWith(view))
await p.waitForTimeout(500)
- const scan = await p.evaluate(() => {
+ const scan = await p.evaluate((REFUSED) => {
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,
+ bad: document.querySelectorAll('#paper .t-embed script, #paper .t-embed foreignObject, #paper .t-embed style, #paper .t-embed-view a').length,
boxes: els.length,
svg: !!document.querySelector('#paper .t-embed-view svg'),
+ data: [...document.querySelectorAll('#paper .t-embed-view svg, #paper .t-embed-view svg *')].filter((e) => [...e.attributes].some((a) => /^data-/i.test(a.name))).length,
+ esc: [...document.querySelectorAll('#paper .t-embed-view svg, #paper .t-embed-view svg *')].filter((e) => [...e.attributes].some((a) => a.value.includes('\\'))).length,
+ extra: [...document.querySelectorAll('#paper .t-embed-view svg *')].filter((e) => [...e.attributes].some((a) => REFUSED.includes(a.name.toLowerCase()))).length,
}
- })
+ }, REFUSED)
// 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(() => {}) }
@@ -105,17 +125,21 @@ try {
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 printed = await p.evaluate((REFUSED) => {
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 }
- })
+ bad: d.querySelectorAll('.t-embed script, .t-embed foreignObject, .t-embed style, .t-embed a').length,
+ js: all.filter((e) => [...e.attributes].some((a) => /javascript:/i.test(a.value))).length,
+ data: d.querySelectorAll('.t-embed svg').length ? [...d.querySelectorAll('.t-embed svg, .t-embed svg *')].filter((e) => [...e.attributes].some((a) => /^data-/i.test(a.name))).length : 0,
+ esc: [...d.querySelectorAll('.t-embed svg, .t-embed svg *')].filter((e) => [...e.attributes].some((a) => a.value.includes('\\'))).length,
+ extra: [...d.querySelectorAll('.t-embed svg *')].filter((e) => [...e.attributes].some((a) => REFUSED.includes(a.name.toLowerCase()))).length }
+ }, REFUSED)
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})`)
+ ok(scan.svg && scan.on === 0 && scan.js === 0 && scan.bad === 0 && scan.data === 0 && ran === 0 && fetched === 0 && stayed
+ && printed.on === 0 && printed.bad === 0 && printed.js === 0 && printed.data === 0
+ && scan.esc === 0 && scan.extra === 0 && printed.esc === 0 && printed.extra === 0,
+ `${name}: the picture still RENDERS (${scan.svg}), no navigation on click (${stayed}), inert in the editor (on* ${scan.on}, js/remote ${scan.js}, data-* ${scan.data}, escapes ${scan.esc}, refused attrs ${scan.extra}, script/foreign/style/a ${scan.bad}, ran ${ran}, fetched ${fetched}) and in print (on* ${printed.on}, ${printed.bad}, js ${printed.js}, data-* ${printed.data}, escapes ${printed.esc}, refused attrs ${printed.extra})`)
await p.close()
}
diff --git a/type/src/svgsafe.ts b/type/src/svgsafe.ts
index be5ee5e3..833a5e89 100644
--- a/type/src/svgsafe.ts
+++ b/type/src/svgsafe.ts
@@ -3,12 +3,13 @@
//
// 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.
+// Built on the kernel's shared sanitizer (kernel/src/svgsafe.ts — bento/slides'
+// sanitizeSvg, which is released and has held up, lifted so both apps audit
+// one walk): parse inert, walk every element, keep a tag or an attribute only
+// if its NAME is on a list. An embed's picture needs less than a slide's
+// diagram, so EMBED_POLICY TIGHTENS slides' default — a policy can only
+// tighten — to no <style> element or attribute, no <a>, no data-*, and no
+// remote reference of any kind.
//
// 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
@@ -17,86 +18,26 @@
// 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);
+// Guarded by scripts/test-type-sinks-browser.mjs (and, for the shared walk,
+// scripts/test-sanitize.ts and scripts/test-svgsafe-policy-browser.mjs).
+
+import { cleanSvgElement, type SvgPolicy } from '../../kernel/src/svgsafe.ts';
+
+/** An embed's picture needs less than a slide's diagram, so type TIGHTENS slides' default. */
+export const EMBED_POLICY: SvgPolicy = {
+ scopeStyle: null, // no <style> element, no style attribute
+ refuseTags: ['a'], // no navigation out of a picture
+ refuseAttrs: [
+ 'baseprofile', 'color-interpolation', 'color-interpolation-filters', 'cursor', 'enable-background',
+ 'font', 'font-size-adjust', 'font-stretch', 'font-variant', 'isolation', 'media', 'mix-blend-mode',
+ 'pointer-events', 'requiredextensions', 'requiredfeatures', 'systemlanguage', 'tabindex', 'target',
+ 'title', 'type', 'unicode-bidi', 'white-space', 'zoomandpan',
+ ], // hygiene, not a boundary: 'title' is the ATTRIBUTE (the <title> element stays)
+ dataAttrs: false,
+ remoteHref: false, // #refs, and inline rasters on image/feImage only
+ strictValues: true, // no escapes, no foreign schemes, url(#…) only (defence in depth: the base walk decodes escapes before judging url())
};
-/** 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.
@@ -106,32 +47,7 @@ export function sanitizeEmbedSvg(markup: string): Element | 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;
+ if (!cleanSvgElement(root, EMBED_POLICY)) return null;
// nothing outside the one <svg> survives
for (const n of Array.from(parsed.body.childNodes)) if (n !== root) n.remove();
return root;