Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Treat every document as untrusted input (#277)
nyblnet89b4462bceef
diff --git a/.claude/launch.json b/.claude/launch.jsonindex 98516b18..416342a5 100644--- a/.claude/launch.json+++ b/.claude/launch.json@@ -1,27 +1,61 @@{"version": "0.0.1","configurations": [+ {+ "name": "serve-dash-wt",+ "runtimeExecutable": "python3",+ "runtimeArgs": [+ "-m",+ "http.server",+ "5188",+ "--directory",+ "/Users/andy/devel/bento/.claude/worktrees/bento-dash/dash/dist-single"+ ],+ "port": 5188+ },{"name": "spaces-dev",+ "comment": "LOOPBACK ONLY. Vite already defaults to loopback, but the flag is written out so every entry in this file states its interface \u2014 the one entry that stayed silent is the one that kept binding the wildcard.","cwd": "spaces","runtimeExecutable": "npm",- "runtimeArgs": ["run", "dev", "--", "--port", "5196", "--strictPort"],+ "runtimeArgs": [+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ "5196",+ "--strictPort"+ ],"port": 5196},{"name": "serve-spaces-built",+ "comment": "LOOPBACK ONLY. http.server defaults to 0.0.0.0 (measured: TCP *:<port> LISTEN, reachable from the LAN), so every entry here pins the interface \u2014 a preview server has no reason to be a LAN service, whatever it happens to be serving today.","runtimeExecutable": "python3",- "runtimeArgs": ["-m", "http.server", "5195", "--directory", "spaces/dist-single"],+ "runtimeArgs": [+ "-m",+ "http.server",+ "5195",+ "--bind",+ "127.0.0.1",+ "--directory",+ "spaces/dist-single"+ ],"port": 5195},{"name": "slides-dev",+ "comment": "LOOPBACK ONLY, see spaces-dev.","cwd": "slides","runtimeExecutable": "npm","runtimeArgs": ["run","dev","--",+ "--host",+ "127.0.0.1","--port","5199","--strictPort"@@ -30,12 +64,15 @@},{"name": "serve-built",+ "comment": "LOOPBACK ONLY, see serve-spaces-built.","cwd": "slides","runtimeExecutable": "python3","runtimeArgs": ["-m","http.server","5198",+ "--bind",+ "127.0.0.1","--directory","dist-single"],@@ -43,11 +80,14 @@},{"name": "serve-testing",+ "comment": "LOOPBACK ONLY, and the highest-value of the http.server entries after working/: .gitignore describes testing/ as 'local test decks \u2014 never committed (may contain confidential content)'. It bound the wildcard until now (measured: TCP *:5197 LISTEN, LAN curl 200).","runtimeExecutable": "python3","runtimeArgs": ["-m","http.server","5197",+ "--bind",+ "127.0.0.1","--directory","testing"],@@ -55,11 +95,14 @@},{"name": "serve-site-src",+ "comment": "LOOPBACK ONLY, see serve-spaces-built.","runtimeExecutable": "python3","runtimeArgs": ["-m","http.server","5192",+ "--bind",+ "127.0.0.1","--directory","site-src"],@@ -67,11 +110,14 @@},{"name": "serve-site",+ "comment": "LOOPBACK ONLY, see serve-spaces-built.","runtimeExecutable": "python3","runtimeArgs": ["-m","http.server","5195",+ "--bind",+ "127.0.0.1","--directory","site"],@@ -79,11 +125,14 @@},{"name": "serve-working",+ "comment": "LOOPBACK ONLY. working/ is the gitignored secrets drawer \u2014 the live guestbook ADMIN_KEY bearer token and the room's owner ECDSA private key sit in it, and http.server serves a directory listing. http.server defaults to 0.0.0.0, so without --bind anyone on the same cafe/office LAN could walk the listing and take both while this entry runs.","runtimeExecutable": "python3","runtimeArgs": ["-m","http.server","5194",+ "--bind",+ "127.0.0.1","--directory","working"],@@ -91,15 +140,16 @@},{"name": "serve-working2",+ "comment": "LOOPBACK ONLY, same secrets as serve-working. `serve -l 5193` listens on the WILDCARD (measured: `*:5193`) while logging 'Accepting connections at http://localhost:5193' \u2014 the line reads as loopback and is not, so the misconfiguration is invisible. The tcp://host:port form is the only way to pin the interface.","runtimeExecutable": "npx","runtimeArgs": ["--yes","serve","-l",- "5193",+ "tcp://127.0.0.1:5193","working"],"port": 5193}]-}\ No newline at end of file+}diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9296c2fa..94dc47b9 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -202,6 +202,49 @@ jobs:# file carrying a script tag.run: node scripts/test-preview.ts+ - name: Untrusted-markup sanitizer rig+ # Every deck is untrusted input somebody may open, paste or receive over+ # collab, and script in that page owns the collab keys, the plaintext+ # autosave store and the write handle to the file on disk. An audit+ # measured `<svg onload>`, a rect `onclick`, `<img onerror>` in a+ # foreignObject and `<form action="javascript:">` all executing.+ #+ # The sanitizer is an ALLOWLIST, so what this pins is the DEFAULT: the+ # first version was a denylist that passed 40 checks with the critical+ # still open, because the rig tested call sites with source regexes+ # instead of the policy. These checks drive the real walk, and the+ # browser half needs Chrome — it self-skips where there is none, so the+ # node half still gates.+ run: |+ slides/node_modules/.bin/esbuild scripts/test-sanitize.ts --bundle --platform=node --format=esm \+ --outfile="$RUNNER_TEMP/test-sanitize.mjs"+ node "$RUNNER_TEMP/test-sanitize.mjs"++ - name: Export-secrets rig+ # "Copy document JSON" shipped the room's owner private key while the+ # tooltip recommended pasting it into an AI chat, and "Save as+ # template…" wrote plaintext out of a password-protected deck. Both are+ # invisible in the product: the file looks right. This scans the source+ # for the two shapes — an export that forgets to strip collab secrets,+ # and a user-facing path that reaches serializeFile instead of+ # serializeAuto — so a NEW export path cannot reintroduce either.+ run: node scripts/test-export-secrets.ts++ - name: Blob content-address rig+ # Encrypted assets are fetched by content address from a relay the+ # threat model treats as untrusted. Nothing verified that what came+ # back matched what was asked for, and the substitution was cached to+ # disk, so one poisoned response persisted.+ run: node scripts/test-blobs.ts++ - name: tray/ios bridge rig+ # The iOS host opens ANY self-contained HTML document and treats those+ # documents as mutually untrusted, so a page-supplied filename reaching+ # appendingPathComponent was an arbitrary write inside the container —+ # including over another deck the user would later open and trust.+ # Source-shape checks; the Swift half self-skips without a toolchain.+ run: node scripts/test-tray-bridge.ts+- name: WebExtension package rig# Validates the store package without writing it: every file the# manifest names exists, every icon is the size it claims, no unexpecteddiff --git a/.gitignore b/.gitignoreindex a88988f8..cbe671c2 100644--- a/.gitignore+++ b/.gitignore@@ -24,6 +24,22 @@ site/working/.dev.vars+# secrets, matched by FILENAME anywhere in the tree. The directory rules above+# (working/, the daemon's own .dev.vars) only hold while the secret stays put,+# and this project has twice shipped what a path-scoped rule stopped covering+# (the built shell under the renamed tray dir, below). Here the escape is a+# flag, not a rename: `scripts/build-guestbook.mjs --out <anywhere>` writes+# guestbook-owner-keys.json — the room's owner ECDSA private key — next to+# --out, so one invocation outside working/ hands a `git add -A` the key.+guestbook-owner-keys.json+guestbook-admin-key.txt+release-key.json+*.key+*.pem+.env+.env.*+.dev.vars.*+# make-og.mjs intermediate (the SVG rasterised into site-src/og.png)scripts/.cache/diff --git a/CLAUDE.md b/CLAUDE.mdindex 8985ae4d..ffd60491 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -474,8 +474,12 @@ names provisional.**Guestbook is a v2 room now**: public deck carries a PUBLIC writer invite(anyone writes, individually keyed); the OWNER deck lives in gitignoredworking/guestbook-live/guestbook-owner.bento.html (moderation = open it →- People → Remove). Daemon ROLL_HOURS=0 — rolls are manual (re-mint would- orphan the held owner file); build-guestbook.mjs emits public + owner decks.+ People → Remove) — but only while the daemon is NOT auto-rolling, since every+ roll re-mints the room and orphans that owner file. It IS auto-rolling for+ launch (wrangler.toml `ROLL_HOURS="0.5"`, cron `*/30`), so moderation is off+ until the cadence goes manual and a fresh pair is re-seeded. Cadence lives in+ server/guestbook-daemon/wrangler.toml, explained in that dir's README — never+ restate the numbers elsewhere; build-guestbook.mjs emits public + owner decks.**Share exports** (invite/viewonly/presentonly/template) pass a filenamesuffix and NEVER retain the FSA handle (`writeUpdatedFileAs` opts.keepHandle— retaining it made a later ⌘S overwrite the export with the full doc).diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 8f1400ae..b54c146b 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -13,13 +13,23 @@ verify the manifest signature against the public key embedded in every shell.printed). Losing it orphans the update channel for every shipped file;leaking it hands the update channel to an attacker. Never commit it, neverput it in CI secrets.-2. **Two repos** (GitHub Pages needs a public repo on the free plan; source- stays private until launch): private `nyblnet/bento` (this repo, `main`- only) + public `nyblnet/bento-site` (the published site — a sibling clone- at `../bento-site`, deployed by Pages from its `main` branch, root). The- `CNAME` file in the site sets the custom domain; after the certificate is- issued, tick *Enforce HTTPS* (mandatory for `.page` anyway). Release- artifacts never enter the source repo's history.+2. **Two repos, BOTH PUBLIC**: `nyblnet/bento` (this repo, `main` only) ++ `nyblnet/bento-site` (the published site — a sibling clone at+ `../bento-site`, deployed by Pages from its `main` branch, root). They are+ separate so release artifacts never enter the source repo's history, not for+ secrecy — this is an open-source project and the source repo is world+ readable, including its full history.++ Said plainly because the stale wording here ("source stays private until+ launch") outlived the launch and was believed: a 2026-08-09 audit treated+ this repo's history as private on the strength of it, and had to be+ corrected by an anonymous fetch returning 200. **Nothing in a commit is+ private.** The signing key, the guestbook admin token and the room owner+ keys stay out by `.gitignore` and by never being committed — never by+ repository visibility.++ The `CNAME` file in the site sets the custom domain; after the certificate+ is issued, tick *Enforce HTTPS* (mandatory for `.page` anyway).3. **DNS at the registrar** for the apex `bento.page`:- `A` records → `185.199.108.153`, `185.199.109.153`, `185.199.110.153`, `185.199.111.153`- `AAAA` records → `2606:50c0:8000::153`, `2606:50c0:8001::153`, `2606:50c0:8002::153`, `2606:50c0:8003::153`diff --git a/docs/collab-design.md b/docs/collab-design.mdindex a4549a8d..ba62df8f 100644--- a/docs/collab-design.md+++ b/docs/collab-design.md@@ -348,9 +348,16 @@ already gives key-holders content integrity; `g` adds *authorization*.cooperative locally (editing UI disabled), enforced over the network.- A malicious *relay* could still withhold/reorder frames or serve a stalesnapshot; it cannot forge writer ops (no private key) nor read content.- Optional client-side `g` verification (defence against a hostile relay- injecting old ciphertext) is a later, additive hardening — not required for- the read-only guarantee.+- **Client-side verification is REQUIRED, not optional hardening.** An earlier+ draft of this document called it "not required for the read-only guarantee";+ that sentence was the assumption behind a real hole. Relay enforcement only+ covers what the relay *persists*. Every reader holds the room key, so a+ read-only copy can encrypt a well-formed op batch and send it — and a blind+ relay, which cannot tell the ciphertext of an op batch from the ciphertext of+ a presence beat, fans it out. Live peers would apply it. So a client in a+ signed room must accept only frames the relay vouched for (see "Phase 1 wire+ format"), and drop the rest. Legacy `r` rooms have no signatures at all and+ stay on the pre-signing trust model — gating them would drop every frame.- `writerPriv` in a writer file is only as protected as the file. Anyone witha writer copy can write — expected: the writer file *is* the write cap.@@ -389,6 +396,20 @@ the read capability.*- The relay pins the verified key PER SOCKET and checks every persistedframe's `g` against it. Direct (hash-matching) keys cover the owner andlegacy 1.0.2 shared-writer rooms unchanged.+- **The relay STAMPS what it verified**, so a client can tell a checked frame+ from one that merely passed through: a persisted frame comes back carrying+ its sequence number, and a signed frame it fanned out comes back with its+ signature echoed. In a signed room the client accepts only stamped frames —+ that is the client half of the read-only guarantee described under *Threat+ model / limits*, and it is why the stamp exists at all. (The relay is being+ changed concurrently; treat the stamp fields in `sync/online.ts` as the+ authority for their exact names.)+- **Blob write tickets**: a writer that understands them announces `bt=1` on+ connect, and the relay — which only mints a ticket once it has seen such a+ writer — hands one back on the room's ready message (`wt`), reissuing it when+ a member is revoked. The client uses it to authorize blob uploads, so blob+ writes are gated by the same per-socket verification as ops instead of by+ mere possession of the room key.- Revocation: owner sends `{ctl:'revoke', p, o, g}`; the relay stores `p` in a`rev` set, closes matching sockets, fans out `{ctl:'revoked', p}` (clientsseeing their own key stand down permanently), and refuses future connects/diff --git a/docs/security.md b/docs/security.mdindex 120d7391..a150efd6 100644--- a/docs/security.md+++ b/docs/security.md@@ -82,10 +82,16 @@ and the *public* half of the writer key.Independently of collaboration, a document can be **password-encrypted atrest**: the on-disk `#bento-doc` block holds a `bento/enc` envelope —AES-GCM-256 over the document JSON, with the key derived from your password via-**PBKDF2-SHA-256, 300,000 iterations**-([`slides/src/save.ts`](../slides/src/save.ts)). The password is held only in-memory so autosave and self-update keep writing encrypted. This protects the-file itself; it is orthogonal to the room key that protects live frames.+**PBKDF2-SHA-256, 600,000 iterations** (the current OWASP figure for+PBKDF2-HMAC-SHA256; [`kernel/src/save.ts`](../kernel/src/save.ts)). The password+is held only in memory so autosave and self-update keep writing encrypted. This+protects the file itself; it is orthogonal to the room key that protects live+frames.++**Files encrypted by older builds still open.** The iteration count travels in+the envelope itself (`it`), and decryption derives with *that* number — so a deck+written at the previous 300,000 is unaffected, and re-saving it re-encrypts at+the current count.## Signed writes — read-only that the relay enforces (v0.9.18)diff --git a/kernel/src/save.ts b/kernel/src/save.tsindex ec409193..fe45f5f4 100644--- a/kernel/src/save.ts+++ b/kernel/src/save.ts@@ -208,6 +208,39 @@ export function previewAllowed(body: string, encrypted = isEncryptionActive()):const SCRIPT_OPEN = '<scr' + 'ipt'const SCRIPT_CLOSE_START = '</scr' + 'ipt'const NOSCRIPT_CLOSE = '</nosc' + 'ript'+const STYLE_OPEN = '<sty' + 'le'+const STYLE_CLOSE_START = '</sty' + 'le'++/**+ * The preview's one stylesheet, and nothing hiding inside it.+ *+ * `<style>` is a RAW TEXT element: its content is not escaped on the way out, so+ * whatever a provider puts in it is written to the file verbatim. Every app's+ * preview has one (slides and dash hoist repeated declarations into it, spaces+ * writes a sheet), and every one of them builds declarations out of AUTHOR+ * data — colours, fonts, sizes. A single `</style>` in one of those values ends+ * the element early and everything after it is live markup in the reader's DOM,+ * outside `#bento-doc`, at parse time, before the remover runs.+ *+ * A flat "refuse any `<style`" would be simpler and would refuse EVERY preview,+ * so the rule is shaped like the tokenizer instead: at most one style element,+ * no `<` anywhere in its text (the breakout attempt is itself a `<`), and no+ * second opener or stray closer anywhere around it. That last clause is what+ * catches the tidy version of the attack, which re-opens a style after the+ * markup it smuggled in and leaves the tag counts balanced.+ */+function styleIsInert(lower: string): boolean {+ const open = lower.indexOf(STYLE_OPEN)+ if (open < 0) return !lower.includes(STYLE_CLOSE_START)+ if (lower.slice(0, open).includes(STYLE_CLOSE_START)) return false+ const gt = lower.indexOf('>', open)+ if (gt < 0) return false+ const end = lower.indexOf(STYLE_CLOSE_START, gt)+ if (end < 0) return false+ const rest = lower.slice(end + STYLE_CLOSE_START.length)+ return !lower.slice(gt + 1, end).includes('<') &&+ !rest.includes(STYLE_OPEN) && !rest.includes(STYLE_CLOSE_START)+}/*** Refuse any preview markup that could unbalance the file.@@ -224,13 +257,15 @@ const NOSCRIPT_CLOSE = '</nosc' + 'ript'** The app sanitizes its own output; this is the kernel refusing to take its* word for it. Dropping the preview costs a thumbnail. Emitting it anyway could- * brick the file.+ * brick the file — or, through the preview's own stylesheet, put live markup in+ * the reader's DOM; see styleIsInert for the half escaping cannot reach.** Exported for `scripts/test-preview.ts`, like previewAllowed.*/export function previewIsSafe(html: string): boolean {const lower = html.toLowerCase()- return !lower.includes(SCRIPT_OPEN) && !lower.includes(SCRIPT_CLOSE_START) && !lower.includes(NOSCRIPT_CLOSE)+ if (lower.includes(SCRIPT_OPEN) || lower.includes(SCRIPT_CLOSE_START) || lower.includes(NOSCRIPT_CLOSE)) return false+ return styleIsInert(lower)}/**@@ -346,7 +381,23 @@ export interface EncEnvelope {data: string}-const ENC_ITERATIONS = 300_000+/**+ * PBKDF2 rounds for NEW envelopes only.+ *+ * A .bento.html is offline at-rest storage: the ciphertext sits in a file that+ * gets mailed, synced and backed up, so an attacker guesses passwords at their+ * own pace with no rate limit anywhere. 300k was half of current guidance+ * (OWASP: 600k for PBKDF2-HMAC-SHA256), and it is the cheapest possible thing+ * to fix — one number, and the cost lands on a keypress the user already waits+ * through.+ *+ * READING IS UNAFFECTED, deliberately: the count travels in the envelope (`it`)+ * and `decryptEnvelope` derives with THAT number, never this one. Every deck+ * encrypted by an older build keeps opening with its own 300k, and re-saving it+ * re-encrypts at the new count. A file that stops opening would be far worse+ * than a weak KDF, so `scripts/test-preview.ts` pins a real 300k envelope.+ */+const ENC_ITERATIONS = 600_000const eb64 = {enc(bytes: Uint8Array): string {diff --git a/scripts/build-guestbook.mjs b/scripts/build-guestbook.mjsindex 2b30e0e9..8d1319e2 100644--- a/scripts/build-guestbook.mjs+++ b/scripts/build-guestbook.mjs@@ -39,8 +39,14 @@ const rnd = (n) => { const b = new Uint8Array(n); crypto.getRandomValues(b); ret// owner can remove a vandal's device key from the People panel), and the PUBLIC// deck carries an owner-signed INVITE so anyone who opens it can write. The// owner's private key never enters the public file — it lands in a separate-// gitignored owner deck next to the admin token. Rolls are MANUAL now-// (daemon ROLL_HOURS=0): a re-mint would invalidate the held owner file.+// gitignored owner deck next to the admin token.+//+// A roll re-mints the room, which INVALIDATES that held owner file, so this+// builder's output only stays moderatable while the daemon is not auto-rolling.+// It is auto-rolling during launch (wrangler.toml ROLL_HOURS="0.5", cron */30):+// re-seed a freshly built pair once the cadence goes back to manual. The+// deployed cadence lives in server/guestbook-daemon/wrangler.toml — do not+// restate it here, that is how this comment went stale.const EC = { name: 'ECDSA', namedCurve: 'P-256' }const SIG = { name: 'ECDSA', hash: 'SHA-256' }const keypair = async () => {diff --git a/scripts/test-blobs.ts b/scripts/test-blobs.tsnew file mode 100644index 00000000..afecba3d--- /dev/null+++ b/scripts/test-blobs.ts@@ -0,0 +1,91 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Encrypted asset blob rig.+//+// node scripts/test-blobs.ts (Node ≥ 23.6 strips types natively)+//+// WHAT THIS PROVES. `getBlob` fetches an asset from the relay's blob store by+// its content address and hands the bytes to the renderer. Every guard in that+// path except one is about CORRUPTION, and corruption is loud: AES-GCM fails,+// the asset resolves to nothing, the user sees an empty element.+//+// SUBSTITUTION is the quiet one. The relay stores ciphertext it cannot read,+// but it chooses which ciphertext answers which address — so it can serve the+// room's blob B when asked for A. B decrypts perfectly (same room key, valid+// GCM tags), so the header check, the tag check and the length check all pass,+// and the deck renders a different picture with no error anywhere. Worse, the+// swap is written to IndexedDB under A's key, so it survives the relay going+// honest again.+//+// The only thing that can catch it is the address itself: it IS+// HMAC(roomKey, sha256(plaintext)), so recomputing it over what arrived proves+// the bytes are the bytes that were asked for. This rig pins that check.+//+// The IndexedDB half of the same check (a cache hit is re-verified, so an entry+// poisoned by a build that predates this is re-fetched rather than trusted) is+// the same three lines against the same helper, and is not reachable from node+// — there is no indexedDB here, so cacheGet always misses.++import { blobKey, encodeBlob, getBlob, type BlobEndpoint } from '../slides/src/sync/blobs.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const endpoint: BlobEndpoint = { base: 'https://relay.invalid', room: 'w-test', tok: 'tok' }+const roomKey = crypto.getRandomValues(new Uint8Array(32))+const otherRoomKey = crypto.getRandomValues(new Uint8Array(32))++// two distinct "assets" — think two images the same room uploaded+const assetA = new Uint8Array(4096).map((_, i) => i & 0xff)+const assetB = new Uint8Array(4096).map((_, i) => (i * 7 + 3) & 0xff)++const keyA = await blobKey(roomKey, assetA)+const keyB = await blobKey(roomKey, assetB)+ok(keyA !== keyB, 'distinct assets get distinct addresses')++/** Whatever the relay decides to answer with, regardless of the address asked. */+let served: Uint8Array | null = null+globalThis.fetch = (async () => (+ served ? new Response(served as unknown as BodyInit) : new Response('missing', { status: 404 })+)) as typeof fetch++const same = (a: Uint8Array | null, b: Uint8Array) =>+ !!a && a.length === b.length && a.every((v, i) => v === b[i])++// ------------------------------------------------------------- honest relay+served = await encodeBlob(roomKey, assetA)+ok(same(await getBlob(endpoint, roomKey, keyA), assetA),+ 'an honest answer round-trips byte for byte')++// -------------------------------------------------------- the substitution+// B is a perfectly valid blob of this room: right key, intact tags. Only the+// address it is served under is a lie. Before the content-address check this+// returned B's bytes and cached them under A.+served = await encodeBlob(roomKey, assetB)+ok((await getBlob(endpoint, roomKey, keyA)) === null,+ 'a valid blob served under another blob\'s address is REFUSED, not rendered')+ok(same(await getBlob(endpoint, roomKey, keyB), assetB),+ 'and the same bytes are still accepted under their own address')++// ------------------------------------------------------- corruption, still loud+served = await encodeBlob(otherRoomKey, assetA)+ok((await getBlob(endpoint, roomKey, keyA)) === null,+ 'a blob sealed with a foreign key is refused (GCM, unchanged)')++served = await encodeBlob(roomKey, assetA)+served[served.length - 1] ^= 0xff+ok((await getBlob(endpoint, roomKey, keyA)) === null,+ 'a flipped ciphertext bit is refused (GCM, unchanged)')++served = null+ok((await getBlob(endpoint, roomKey, keyA)) === null,+ 'a 404 reads as unavailable rather than throwing')++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-clipboard.ts b/scripts/test-clipboard.tsindex 13970a4a..e8dd64a5 100644--- a/scripts/test-clipboard.ts+++ b/scripts/test-clipboard.ts@@ -1,10 +1,28 @@#!/usr/bin/env node// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors-// Clipboard transport is plain JSON, so this regression rig runs without a DOM.+// Clipboard transport is plain JSON, so this regression rig needs no DOM — but+// it is BUNDLED, not run directly, because render.ts imports './model'+// extensionless (same as scripts/test-sanitize.ts):+//+// slides/node_modules/.bin/esbuild scripts/test-clipboard.ts --bundle \+// --platform=node --format=esm --outfile="$TMPDIR/test-clipboard.mjs" \+// && node "$TMPDIR/test-clipboard.mjs"+//+// render.ts is imported on purpose. The point of the validator is that what it+// emits is renderable, and the three renderer entry points that used to throw+// on its output — renderTableHtml, resolveFields, resolveAsset — are all pure+// string functions, so the rig can call them for real instead of asserting+// about them.import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from '../slides/src/editor/clipboard.ts'-import { defaultText, newDoc, type BentoDoc } from '../slides/src/model.ts'+import {+ defaultChart, defaultImage, defaultMedia, defaultShape, defaultTable, defaultText,+ newDoc, type BentoDoc, type SlideElement, type TableElement,+} from '../slides/src/model.ts'+import { MODEL_KEYS } from '../slides/src/modelkeys.generated.ts'+import { cssColor, renderTableHtml, resolveAsset, resolveFields } from '../slides/src/render.ts'+import { CHECKED_KEYS, LIMITS, REQUIRED_KEYS, sanitizeElement, sanitizeSlide } from '../slides/src/untrusted.ts'let checks = 0let failures = 0@@ -69,5 +87,257 @@ console.log('\nslide clipboard')ok(font != null && target.assets![font.asset] === source.assets!['font-acme'], 'pasted slide font points at its source bytes')}+// --- the clipboard is a public channel ---------------------------------------+// Any page with a Copy button can leave a `__bento:"clip"` payload on it, so+// parseClip rebuilds one through untrusted.ts instead of trusting its shape.+// Everything below FAILS against the pre-check parseClip, which handed the+// parsed JSON straight to insertElements/insertSlides.++/** Key-order-independent deep compare — the rebuild re-emits type and id first. */+function canon(v: unknown): string {+ const sort = (x: unknown): unknown => {+ if (Array.isArray(x)) return x.map(sort)+ if (x && typeof x === 'object') {+ return Object.fromEntries(Object.keys(x as object).sort().map((k) => [k, sort((x as any)[k])]))+ }+ return x+ }+ return JSON.stringify(sort(v))+}++/** One of every element type, with the optional properties a real deck uses. */+function richElements(): SlideElement[] {+ return [+ defaultText({+ id: 'text-1', html: '<b>Bold</b> & fine', fontFamily: "'Acme', sans-serif",+ letterSpacing: 1.5, role: 'title', placeholder: 'Click to add title',+ // color(srgb …) is what a deck converted from a design tool actually+ // carries — the longest colour notation in OneMarket, at 45 characters+ color: 'color(srgb 0.156863 0.188235 0.227451 / 0.55)',+ colorGradient: { angle: 90, stops: [{ at: 0, color: '#FFFFFF' }, { at: 1, color: 'rgba(0,0,0,0.5)' }] },+ textStroke: { width: 2, color: '#000000', fill: 'none' },+ shadow: [{ x: 0, y: 2, blur: 8, color: 'rgba(0,0,0,0.3)' }],+ fx: { enter: 'fade-up', enterDur: 0.6, order: 1, countUp: true, ken: { dir: 'out', scale: 1.06, duration: 8 } },+ }),+ defaultShape('path', {+ id: 'shape-1', d: 'M0,0 C10,10 20,-5 30,0 Z', pathBox: [0, 0, 30, 10],+ // an svg paint may reference a gradient/filter in the document's own+ // markup, quotes and all: OneMarket_Commercial_Architecture slide 21,+ // element `topo-0`. Dropping it left render.ts writing fill="undefined",+ // which paints the shape BLACK.+ fill: 'url("#core-glow")',+ strokeStyle: 'dashed', lineStart: 'arrow', lineEnd: 'dot', strokeDash: 6,+ fillGradient: { angle: 45, stops: [{ at: 0, color: '#F7A600' }] },+ from: { el: 'text-1', side: 'auto' }, to: { el: 'img-1', side: 'left' },+ fx: { loop: { type: 'motion-path', path: 'M0,0 L10,10', duration: 4, ease: 'sine-in-out', speeds: [1, 2] } },+ }),+ defaultImage('asset:pic', { id: 'img-1', fit: 'cover', radius: 8, blend: 'multiply', blur: 2, backdropFilter: 6 }),+ defaultChart({ series: [{ type: 'bar', data: [1, 2, 3] }], xAxis: { data: ['a', 'b', 'c'] } },+ { id: 'chart-1', source: { tableId: 'table-1' } }),+ defaultTable({ id: 'table-1' }),+ { id: 'svg-1', type: 'svg', x: 0, y: 0, w: 100, h: 100, rotation: 0, opacity: 1,+ markup: '<svg><circle r="4"/></svg>', css: '.a{fill:red}', group: 'era-1', showOnHover: 'era-1' },+ defaultMedia('video', 'https://example.com/clip.mp4', { id: 'media-1', autoplay: true, poster: 'asset:pic' }),+ ]+}++console.log('\nlegitimate payloads survive the check')+{+ const doc = newDoc()+ doc.slides[0].elements = richElements()+ const payload = parseClip(serializeElements(doc.slides[0].elements, doc))!+ ok(canon(payload.elements) === canon(richElements()), 'every element type round-trips property-for-property')++ doc.slides[0].notes = 'speaker notes'+ doc.slides[0].hover = { type: 'focus-group', dim: 0.3 }+ doc.slides[0].comments = [{ id: 'c1', author: 'Ada', text: 'tighten this', at: '2026-01-01T00:00:00Z', x: 10, y: 20, replies: [{ id: 'r1', author: 'Bob', text: 'ok', at: '2026-01-02T00:00:00Z' }] }]+ const slideClip = parseClip(serializeSlides(doc.slides, doc))!+ ok(canon(slideClip.slides) === canon(doc.slides), 'a whole slide round-trips, comments and hover included')+}++console.log('\nhostile clipboard payloads')+{+ const clip = (elements: unknown[]) => parseClip(JSON.stringify({ __bento: 'clip', kind: 'elements', elements }))+ const one = (el: Record<string, unknown>) => clip([el])!.elements![0] as any++ ok(parseClip(JSON.stringify({ __bento: 'clip', kind: 'evil', elements: [] })) === null,+ 'rejects a payload whose kind is neither literal')+ ok(parseClip(JSON.stringify({ __bento: 'clip', kind: 'elements', elements: { length: 1 } })) === null,+ 'rejects an elements payload that is not an array')+ ok(clip([{ type: 'script', id: 'x', src: 'evil.js' }]) === null, 'drops an element whose type is not in the format')+ ok(clip([{ type: 'text' }]) === null, 'drops an element with no usable id')++ // renderTableHtml interpolates cell colours into style="" with no escaping,+ // so a quote in one closes the attribute and the rest is an event handler.+ const table = one({+ type: 'table', id: 'tbl-1', x: 0, y: 0, w: 100, h: 100, columns: [{ w: 1 }],+ rows: [{ cells: [{ html: 'hi', color: 'red" onmouseover="alert(1)', align: 'left" onclick="x()' }] }],+ style: { borderColor: '#000;}</style><script>x()</script>', fontSize: 18 },+ })+ ok(table.rows[0].cells[0].html === 'hi', 'keeps the cell content beside a rejected colour')+ ok(table.rows[0].cells[0].color === undefined, 'drops a cell colour that would close the style attribute')+ ok(table.rows[0].cells[0].align === undefined, 'drops a cell alignment that is not one of the three literals')+ ok(table.style.borderColor === undefined && table.style.fontSize === 18, 'drops a table border colour carrying markup, keeps the rest of the style')++ const img = one({+ type: 'image', id: 'img-2', x: '40', y: 12, w: 100, h: 100, opacity: 3,+ src: 'asset:pic', fit: 'cover;position:fixed;inset:0', onload: 'alert(1)',+ })+ ok(img.fit === undefined, 'drops a fit that would inject extra declarations into the <img> cssText')+ ok(img.x === 40 && img.y === 12, 'coerces a numeric string, keeps a real number')+ ok(!('onload' in img), 'drops a key the format does not define')+ ok(img.opacity === undefined, 'drops an out-of-range opacity')+ ok(clip([{ type: 'image', id: 'img-3', x: 0, y: 0, w: 1, h: 1, src: 'javascript:alert(1)' }]) === null,+ 'a javascript: src takes the whole image with it — an <img> has nothing left to be')++ const svg = one({ type: 'svg', id: 'svg-2', x: 0, y: 0, w: 10, h: 10, markup: { toString: 1 }, css: 'x'.repeat(LIMITS.css + 1) })+ ok(svg.markup === undefined && svg.css === undefined, 'drops non-string markup and oversized css')+ ok(clip([{ type: 'text', id: 't-2', html: 'x'.repeat(LIMITS.html + 1) }]) === null, 'drops rich text past the size ceiling')++ let deep: unknown = { v: 1 }+ for (let i = 0; i < 40; i++) deep = { a: deep }+ ok(clip([{ type: 'chart', id: 'ch-2', option: deep }]) === null, 'drops a chart option nested past the depth ceiling')+ ok(one({ type: 'chart', id: 'ch-3', option: { series: [{ type: 'bar', data: [1, 2] }] } }).option !== undefined, 'keeps an ordinary chart option')++ const poisoned = parseClip('{"__bento":"clip","kind":"elements","elements":[{"type":"text","id":"p1","html":"x","__proto__":{"pwned":true}}]}')+ ok(poisoned !== null && ({} as any).pwned === undefined, 'a __proto__ key in a pasted element never reaches Object.prototype')++ const fontClip = parseClip(JSON.stringify({+ __bento: 'clip', kind: 'elements', elements: [{ type: 'text', id: 'f1', html: 'a', x: 0, y: 0, w: 1, h: 1 }],+ // fonts.ts interpolates weight/style RAW into an @font-face rule+ fonts: [{ family: 'Acme', asset: 'a1', weight: 'normal;}body{display:none' }, { family: 'NoBytes' }],+ assets: { a1: 'data:font/woff2;base64,QUJD', 'bad"key': 'data:,x' },+ }))!+ ok(fontClip.fonts!.length === 1 && (fontClip.fonts![0] as any).weight === undefined, 'drops a font weight that would inject CSS rules, and a font with no asset')+ ok(fontClip.assets!.a1 != null && fontClip.assets!['bad"key'] === undefined, 'drops an asset key that could break out of an attribute')++ const target = newDoc()+ insertElements(fontClip, target, target.slides[0])+ ok(target.fonts!.length === 1 && target.assets!.a1 != null, 'the checked payload still merges its font and bytes')+}++// --- what the validator emits must be RENDERABLE ----------------------------+// A rebuilt element used to be allowed out with its mandatory keys missing,+// which is worse than a hostile value: renderTableHtml/resolveFields/+// resolveAsset throw on it, and a throw inside renderSlide takes down the whole+// slide, not just the paste. Each case below is measured twice — the renderer+// really does throw on the pre-fix shape, and the validator really does refuse+// to produce it.++console.log('\nthe validator never emits an element the renderer throws on')+{+ const doc = newDoc()+ const clip = (elements: unknown[]) => parseClip(JSON.stringify({ __bento: 'clip', kind: 'elements', elements }))+ const throws = (fn: () => unknown) => { try { fn(); return false } catch { return true } }+ const fields = { page: 1, pages: 1, title: '', date: new Date(), author: '', company: '', subject: '', event: '' }++ const box = { x: 0, y: 0, w: 100, h: 100, rotation: 0, opacity: 1 }+ const crashers: Array<[string, Record<string, unknown>, () => unknown]> = [+ ['a table row whose cells are not an array',+ { type: 'table', id: 'c-1', ...box, columns: [{ w: 1 }], rows: [{ cells: 'x' }] },+ () => renderTableHtml({ ...box, type: 'table', id: 'c-1', columns: [{ w: 1 }], rows: [{}] } as unknown as TableElement, doc)],+ ['a table whose columns are not an array',+ { type: 'table', id: 'c-2', ...box, columns: 'x', rows: [{ cells: [{ html: 'a' }] }] },+ () => renderTableHtml({ ...box, type: 'table', id: 'c-2', rows: [{ cells: [{ html: 'a' }] }] } as unknown as TableElement, doc)],+ ['a table with no columns at all',+ { type: 'table', id: 'c-3', ...box },+ () => renderTableHtml({ ...box, type: 'table', id: 'c-3' } as unknown as TableElement, doc)],+ ['a text element with no html',+ { type: 'text', id: 'c-4', ...box },+ () => resolveFields(undefined as unknown as string, fields)],+ ['an image with no src',+ { type: 'image', id: 'c-5', ...box },+ () => resolveAsset(doc, undefined as unknown as string)],+ ]+ for (const [label, payload, preFix] of crashers) {+ ok(throws(preFix), `render.ts still throws on ${label} (the shape this drops)`)+ ok(clip([payload]) === null, `drops ${label}`)+ }++ // gradients: cssLinearGradient/gradientRef both walk `stops` with no guard+ ok(sanitizeElement({ type: 'text', id: 'g-1', ...box, html: 'h', colorGradient: { angle: 90 } })?.type === 'text',+ 'a gradient with no stops loses the GRADIENT, not the text element')+ ok((sanitizeElement({ type: 'text', id: 'g-1', ...box, html: 'h', colorGradient: { angle: 90 } }) as any).colorGradient === undefined,+ 'and the stop-less gradient itself is gone')+ ok((sanitizeElement({ type: 'text', id: 'g-2', ...box, html: 'h', shadow: { x: 1, y: 1 } }) as any).shadow === undefined,+ 'a shadow with no blur or colour is dropped whole, not left to write drop-shadow(undefined)')++ // every name in the required table must be a real key of that element type+ const bogus = Object.entries(REQUIRED_KEYS).flatMap(([type, keys]) =>+ keys.filter((k) => !(MODEL_KEYS.element as Record<string, readonly string[]>)[type]?.includes(k)).map((k) => `${type}.${k}`))+ ok(bogus.length === 0, `every required key names a real format property (bogus: ${bogus.join(', ') || 'none'})`)++ // and each one, removed on its own, must cost the element+ const minimal: Record<string, Record<string, unknown>> = {+ text: { html: 'hi' },+ shape: { shape: 'rect', fill: '#fff' },+ image: { src: 'asset:pic' },+ chart: { option: { series: [] } },+ table: { columns: [{ w: 1 }], rows: [{ cells: [{ html: 'a' }] }] },+ media: { kind: 'video', src: 'https://example.com/a.mp4' },+ }+ for (const [type, keys] of Object.entries(REQUIRED_KEYS)) {+ ok(sanitizeElement({ type, id: `m-${type}`, ...box, ...minimal[type] }) !== null,+ `a minimal ${type} with only its mandatory keys survives`)+ for (const key of keys) {+ const without = { type, id: `m-${type}`, ...box, ...minimal[type] }+ delete without[key]+ ok(sanitizeElement(without) === null, `a ${type} missing ${key} is dropped`)+ }+ }+}++console.log('\ncolours are judged by the same rule in both layers')+{+ const box = { x: 0, y: 0, w: 100, h: 100, rotation: 0, opacity: 1 }+ const el = (p: Record<string, unknown>) => sanitizeElement({ type: 'shape', id: 's', ...box, shape: 'rect', fill: '#fff', ...p }) as any++ // CSS_BREAKOUT alone allows '(' ')' and ':', so a colour could append CSS+ // functions to whatever declaration it lands in. render.ts:applyElementFrame+ // interpolates shadow colours straight into style.filter.+ ok(el({ shadow: { blur: 4, color: 'red) url(https://evil.example/f.svg#f' } }).shadow === undefined,+ 'drops a shadow colour that would smuggle a url() into style.filter')+ ok(el({ fill: 'url(https://evil.example/track.svg#g)' }) === null,+ 'a remote url() paint is not a colour — and fill is mandatory, so the shape goes with it')+ ok(el({ fill: 'url("#core-glow")' }).fill === 'url("#core-glow")',+ 'keeps a quoted reference to a gradient defined in this document')+ ok(el({ fill: "url('#core-glow')" }).fill === "url('#core-glow')" && el({ fill: 'url(#core-glow)' }).fill === 'url(#core-glow)',+ 'keeps the single-quoted and bare forms too')+ ok(el({ stroke: 'color(srgb 0.98 0.68 0.25 / 0.55)' }).stroke === 'color(srgb 0.98 0.68 0.25 / 0.55)',+ 'keeps a modern color() notation')+ ok(el({ fill: 'expression(alert(1))' }) === null && el({ stroke: 'x'.repeat(LIMITS.color + 1) }).stroke === undefined,+ 'drops an expression() colour and one past the length ceiling')++ // the two layers must AGREE: anything untrusted.ts keeps as a colour,+ // render.ts must also accept, or the document holds a value that renders as+ // a fallback and the stricter layer is the one nobody can see.+ const FB = ' fallback'+ const disagreements = [+ '#fff', 'rgba(0,0,0,0.5)', 'color(srgb 0.98 0.68 0.25 / 0.55)', 'transparent', 'none', 'burlywood',+ ].filter((v) => {+ const kept = (sanitizeElement({ type: 'table', id: 'tc', ...box, columns: [{ w: 1 }], rows: [{ cells: [{ html: 'a', bg: v }] }] }) as any)+ .rows[0].cells[0].bg+ return kept !== undefined && cssColor(kept, FB) === FB+ })+ ok(disagreements.length === 0, `no colour survives here that render.ts would reject (${disagreements.join(', ') || 'none'})`)++ ok(sanitizeSlide({ id: 'sl', background: 'linear-gradient(180deg, rgba(15,20,27,1) 0%, rgba(30,42,58,1) 100%)', elements: [] })?.background != null,+ 'a slide background may still be a multi-stop gradient')+ ok(sanitizeSlide({ id: 'sl', background: 'url(https://evil.example/beacon.png)', elements: [] })?.background === undefined,+ 'but not a remote url() that fetches on paste')+}++console.log('\nkey coverage')+{+ // A field added to model.ts without a check here would be dropped from every+ // paste — silently, which is the failure mode this whole file exists to stop.+ const missing = [+ ...new Set(Object.values(MODEL_KEYS.element).flat().filter((k) => !CHECKED_KEYS.element.includes(k))),+ ]+ ok(missing.length === 0, `every element property in the format has a check (missing: ${missing.join(', ') || 'none'})`)+ const slideMissing = MODEL_KEYS.slide.filter((k) => !CHECKED_KEYS.slide.includes(k))+ ok(slideMissing.length === 0, `every slide property in the format has a check (missing: ${slideMissing.join(', ') || 'none'})`)+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.tsnew file mode 100644index 00000000..ba187866--- /dev/null+++ b/scripts/test-export-secrets.ts@@ -0,0 +1,240 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Export-safety rig.+//+// node scripts/test-export-secrets.ts (Node ≥ 23.6 strips types natively)+//+// WHAT THIS PROVES. Two properties of every path a person can use to send a+// deck somewhere — save-as, share copy, template, the JSON on the clipboard:+//+// 1. NO CAPABILITY TRAVELS BY ACCIDENT. Everything under `doc.collab` is a+// bearer token. `ownerPriv` revokes members, `writerPriv` writes to the+// room, and the symmetric `key` decrypts every frame and blob the relay+// has ever stored. An export that forgets one hands that power to whoever+// receives the file, and the file looks completely ordinary afterwards.+// 2. A PASSWORD IS HONOURED. `serializeFile` writes the document in the+// clear; `serializeAuto` encrypts it when a password is active. They are+// one identifier apart and nothing at runtime complains.+//+// Both failures are silent AND unrecoverable — the copy is already on somebody+// else's disk. Measured, 2026-08-09, before this rig existed: "Copy document+// JSON" put ownerPriv, writerPriv and the room key on the clipboard under a+// tooltip that recommended pasting it into an AI chat, and "Save as template…"+// called serializeFile, so a password-protected deck exported a plaintext+// template that still THUMBNAILED as locked (the preview veto fired correctly,+// which is what made it look protected).+//+// This rig reads SOURCE. slides/src/editor/editor.ts cannot be imported under+// node — extensionless bundler imports, DOM at module scope — and both rules+// are decisions about which function a call site reaches, which is exactly+// what source shows. The encryption itself is pinned by scripts/test-preview.ts+// and the splice contract by scripts/shell-gate.mjs.++import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const read = (rel: string) => readFileSync(join(root, rel), 'utf8')++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) {+ failures+++ console.error(` ✗ ${msg}`)+ } else {+ console.log(` ✓ ${msg}`)+ }+}++// --- reading the source -----------------------------------------------------++/**+ * Blank out comments and string bodies while keeping every offset, so brace+ * matching cannot be thrown by a `{` that lives inside a message, a comment or+ * a template. Offsets stay 1:1 with the original, which is what gets sliced.+ */+function mask(src: string): string {+ const out = src.split('')+ const blank = (i: number) => { if (src[i] !== '\n') out[i] = ' ' }+ // template-literal nesting: `${ … }` drops back to code, and code inside it+ // may open another template+ const stack: string[] = []+ let i = 0+ while (i < src.length) {+ const c = src[i]+ const two = src.slice(i, i + 2)+ const inTemplate = stack[stack.length - 1] === '`'+ if (!stack.length && two === '//') {+ while (i < src.length && src[i] !== '\n') blank(i++)+ continue+ }+ if (!stack.length && two === '/*') {+ while (i < src.length && src.slice(i, i + 2) !== '*/') blank(i++)+ blank(i); blank(i + 1); i += 2+ continue+ }+ if (c === '\\' && stack.length) { blank(i); blank(i + 1); i += 2; continue }+ if (!stack.length && (c === '"' || c === "'" || c === '`')) { stack.push(c); i++; continue }+ if (stack.length && c === stack[stack.length - 1]) { stack.pop(); i++; continue }+ if (inTemplate && two === '${') { stack.push('}'); i += 2; continue }+ if (stack[stack.length - 1] === '}' && c === '}') { stack.pop(); i++; continue }+ if (stack.length) blank(i)+ i+++ }+ return out.join('')+}++/** Source of every function/method body in `src`, keyed by name. */+function bodies(src: string): Map<string, string> {+ const masked = mask(src)+ const found = new Map<string, string>()+ // class methods (two-space indent) and module-level functions+ const decl = /^(?: (?:private |public |protected )?(?:static )?(?:async )?([A-Za-z_$][\w$]*)\s*\(|(?:export )?(?:async )?function ([A-Za-z_$][\w$]*)\s*\()/gm+ for (const m of masked.matchAll(decl)) {+ const name = m[1] ?? m[2]+ // Step over the parameter list first: `opts: { keepRoom?: boolean } = {}`+ // otherwise reads as the body, and the checks below then pass vacuously+ // against a two-word type literal.+ let p = m.index! + m[0].length - 1+ for (let depth = 0; p < masked.length; p++) {+ if (masked[p] === '(') depth+++ else if (masked[p] === ')' && --depth === 0) break+ }+ const open = masked.indexOf('{', p)+ if (open < 0) continue+ let depth = 0+ let i = open+ for (; i < masked.length; i++) {+ if (masked[i] === '{') depth+++ else if (masked[i] === '}' && --depth === 0) break+ }+ found.set(name, src.slice(open, i + 1))+ }+ return found+}++const EDITOR = 'slides/src/editor/editor.ts'+const editorSrc = read(EDITOR)+const editor = bodies(editorSrc)+const editorMasked = mask(editorSrc)++// The parse is load-bearing for every check below: a rename that makes it find+// nothing would turn this whole file green.+ok(editor.size > 40 && editor.has('copyDocJson') && editor.has('saveAsTemplate'),+ `parsed ${editor.size} function bodies out of ${EDITOR}`)++const body = (name: string): string => {+ const b = editor.get(name)+ if (b === undefined) { failures++; checks++; console.error(` ✗ ${EDITOR} has no ${name}() — this rig cannot check it`) }+ return b ?? ''+}++// --- 1. the strip list is complete ------------------------------------------+//+// Derived from the MODEL, not typed out here: a new private field added to+// `collab` fails this until the stripper covers it.++console.log('\nthe strip list')++const collabBlock = (() => {+ const src = read('slides/src/model.ts')+ const start = src.indexOf(' collab?: {')+ const masked = mask(src)+ let depth = 0+ let i = masked.indexOf('{', start)+ const open = i+ for (; i < masked.length; i++) {+ if (masked[i] === '{') depth+++ else if (masked[i] === '}' && --depth === 0) break+ }+ return src.slice(open, i + 1)+})()++const collabFields = [...collabBlock.matchAll(/^ {4}([A-Za-z_$][\w$]*)\??:/gm)].map((m) => m[1])+// Private key material: anything ending in -Priv, plus the delegation keypair.+// `key` and `room` are the read capability — a copy that must follow the live+// session keeps them, so they are only covered by the drop-the-block default.+const privateFields = collabFields.filter((f) => /Priv$/.test(f) || f === 'invite')++ok(collabFields.includes('key') && privateFields.length >= 3,+ `model.ts declares ${collabFields.length} collab fields, ${privateFields.length} of them private (${privateFields.join(', ')})`)++const stripper = body('stripCollabSecrets')+for (const f of privateFields) {+ ok(new RegExp(`delete doc\\.collab\\.${f}\\b`).test(stripper),+ `stripCollabSecrets drops ${f} from a copy that keeps the room`)+}+ok(/delete doc\.collab\b(?!\.)/.test(stripper),+ 'stripCollabSecrets drops the whole block by default — the room key is a capability too')++// --- 2. no export carries the session ---------------------------------------++console.log('\nexports')++// Everything that hands the document to somebody else. Named rather than+// discovered so that a DELETED strip and a deleted export do not look alike.+const EXPORTS = ['savePresentationPackage', 'saveReaderCopy', 'saveEditorCopy', 'saveAsTemplate', 'copyDocJson']+for (const name of EXPORTS) {+ ok(/stripCollabSecrets\(/.test(body(name)),+ `${name}() strips the session before the copy leaves`)+}++ok(!/writeText\(JSON\.stringify\(this\.store\.doc\)/.test(body('copyDocJson')),+ 'copyDocJson() copies a stripped CLONE, never the live document')++// The catch-all: any method that clones the document and then hands it to an+// outbound sink is an export, named in the list above or not. saveAsNewDeck is+// the one clone that legitimately keeps a session — it mints a brand new one.+const SINK = /writeUpdatedFileAs?\(|clipboard\.writeText\(|downloadFile\(/+for (const [name, src] of editor) {+ if (!/JSON\.parse\(JSON\.stringify\(this\.store\.doc\)\)/.test(src) || !SINK.test(mask(src))) continue+ ok(/stripCollabSecrets\(|await mintCollab\(\)/.test(src),+ `${name}() clones the document and sends it — and settles its collab first`)+}++// The paste side of the JSON round-trip. Adopting the pasted block would wipe+// the user's own credentials (our copy sends none) or move the deck into a+// room that came from somewhere else.+const paste = body('openReplaceJson')+ok(/const keep = this\.store\.doc\.collab/.test(paste) &&+ /next\.collab = keep/.test(paste) && /delete next\.collab/.test(paste),+ 'openReplaceJson() keeps THIS document\'s collab instead of adopting the pasted one')+// …and settles it BEFORE the swap: replaceDoc's events reach the sync session+// synchronously, so a fix-up afterwards would already have re-attached the+// session to the pasted credentials.+// Masked, because the comment above the code names both of them.+const pasteCode = mask(paste)+ok(pasteCode.indexOf('next.collab = keep') < pasteCode.indexOf('replaceDoc(') && !/loadDoc/.test(pasteCode),+ 'openReplaceJson() decides the session before replaceDoc, not after')++// --- 3. no user-facing path writes plaintext --------------------------------++console.log('\npasswords')++// serializeFile has exactly one legitimate caller left in the app: the+// documented window.bento.serialize() tooling hook, which is synchronous by+// contract and never writes a file for a person.+const callers = ['slides/src/editor/editor.ts', 'slides/src/main.ts', 'slides/src/save.ts', 'slides/src/autosave.ts', 'slides/src/present.ts']+ .filter((f) => /\bserializeFile\(/.test(mask(read(f))))+ok(callers.length === 1 && callers[0] === 'slides/src/main.ts',+ `serializeFile() is called from ${callers.join(', ') || 'nowhere'} — and only there`)+ok(/serialize:\s*\(\)\s*=>\s*\{[^}]*\bserializeFile\(store\.doc\)/.test(read('slides/src/main.ts')),+ 'that one caller is window.bento.serialize(), the documented tooling hook')++ok(!/\bserializeFile\b/.test(editorMasked),+ 'editor.ts does not even import serializeFile — every path in it writes a real file for a person')++for (const [name, src] of editor) {+ for (const call of mask(src).matchAll(/writeUpdatedFileAs?\(/g)) {+ const arg = src.slice(call.index! + call[0].length, call.index! + call[0].length + 22)+ ok(arg.startsWith('await serializeAuto('),+ `${name}() writes through serializeAuto — an active password reaches the file`)+ }+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-preview.ts b/scripts/test-preview.tsindex a0b81cfb..6322668e 100644--- a/scripts/test-preview.ts+++ b/scripts/test-preview.ts@@ -18,11 +18,19 @@// 2. THE OUTPUT REFUSAL. The preview is generated from author content. A// script tag reaching the file unbalances it and breaks the frozen// splice contract every shipped updater relies on. `</noscript>` is-// still refused: it costs nothing and older files carry one.+// still refused: it costs nothing and older files carry one. The same+// refusal covers the preview's own `<style>`, which is the hole escaping+// cannot close: a raw text element is written to the file VERBATIM, so a+// `</style>` inside one author-supplied declaration ends it early and the+// rest becomes live markup in every reader's DOM, outside #bento-doc.+// 3. THE AT-REST KDF. Its iteration count may be raised, and raising it must+// never cost a file. The count lives in the envelope, so an encrypted deck+// written by any older build has to keep opening with ITS number — a deck+// that stops opening is unrecoverable in a way a weak KDF is not.//// The rest of the feature — laying the page out, fitting it to a viewport,// staying inside the byte budget — needs a DOM and is verified in a browser-// and against the real macOS thumbnailer (`qlmanage -t`). These two are pure+// and against the real macOS thumbnailer (`qlmanage -t`). These are pure// decisions, so they get pinned here where a regression costs one CI run// instead of one release.//@@ -30,7 +38,7 @@// preview-carrying FILE still satisfies the splice contract and asserts that// both rules below are still wired into the save path at all.-import { previewAllowed, previewIsSafe, setEncryptionPassword } from '../kernel/src/save.ts'+import { decryptEnvelope, previewAllowed, previewIsSafe, setEncryptionPassword } from '../kernel/src/save.ts'let failures = 0let checks = 0@@ -49,6 +57,8 @@ function ok(cond: boolean, msg: string) {const SCRIPT_CLOSE = '</scr' + 'ipt>'const SCRIPT_OPEN = '<scr' + 'ipt>'const NOSCRIPT_CLOSE = '</nosc' + 'ript>'+const STYLE_OPEN = '<sty' + 'le>'+const STYLE_CLOSE = '</sty' + 'le>'const PLAIN = JSON.stringify({ format: 'bento/slides', docId: 'x', title: 'Q3 board' })const ENVELOPE = JSON.stringify({@@ -111,5 +121,56 @@ ok(previewIsSafe('<div>' + '</NOSC' + 'RIPT>' + '</div>') === false, 'an upper-cok(previewIsSafe('<div>' + '<scr' + 'ipt type="application/bento+json" id="bento-doc">{}</div>') === false,'a forged #bento-doc opening tag is refused')+// --- 3. the stylesheet, which escaping cannot protect -----------------------+//+// Every app's preview hoists repeated declarations into ONE <style> (slides and+// dash) or writes a scoped sheet (spaces), and those declarations are built+// from author data. A <style> is a raw text element, so nothing escapes what+// goes in it: `}</style><img src=x onerror=…>{` inside one colour ends the+// element and the rest lands in the reader's live DOM. The first check below is+// the one that keeps this honest — refusing every preview that contains a+// <style> would "fix" the hole by deleting the feature.++console.log('\nstylesheet refusal')++const SHEET = `<div class="p">${STYLE_OPEN}._0{color:#1E2A3A}._1{font-size:18px}${STYLE_CLOSE}<div class="_0 _1">Q3</div></div>`+ok(previewIsSafe(SHEET) === true, 'a preview carrying its hoisted stylesheet is accepted')+ok(previewIsSafe(`<div>${STYLE_OPEN}@media print{._0{color:red}}${STYLE_CLOSE}</div>`) === true,+ 'braces, at-rules and selectors inside the sheet are ordinary CSS')++ok(previewIsSafe(`<div>${STYLE_OPEN}._0{color:red}${STYLE_CLOSE}<img src=x onerror=alert(1)>{}${STYLE_CLOSE}</div>`) === false,+ 'a declaration that closes the stylesheet early is refused')+ok(previewIsSafe(`<div>${STYLE_OPEN}._0{color:red}${STYLE_CLOSE}<img src=x onerror=alert(1)>${STYLE_OPEN}{}${STYLE_CLOSE}</div>`) === false,+ 'the tidy version — re-open a sheet after the smuggled markup, tags balanced — is refused too')+ok(previewIsSafe(`<div>${STYLE_OPEN}._0{content:"<b>"}${STYLE_CLOSE}</div>`) === false,+ 'a "<" inside the sheet is refused whether or not it closes anything')+ok(previewIsSafe(`<div>${STYLE_CLOSE}<img src=x onerror=alert(1)></div>`) === false,+ 'a closer with no sheet to close is refused')+ok(previewIsSafe(`<div>${'<STY' + 'LE>'}._0{color:red}${'</STY' + 'LE>'}<b>x</b>${'</STY' + 'LE>'}</div>`) === false,+ 'the same, upper-case — an HTML parser does not care about case')++// --- 4. the at-rest KDF ------------------------------------------------------+//+// A real envelope minted by the 300k build, kept as bytes. Raising+// ENC_ITERATIONS must not touch it: the count is in the file, and this is the+// only proof that decryption reads it from there rather than from the constant.++console.log('\nat-rest KDF')++const LEGACY_PASSWORD = 'correct horse battery staple'+const LEGACY_ENVELOPE = {+ format: 'bento/enc' as const, v: 1 as const, it: 300000,+ salt: 'zcBz9Vbqwj+iUtehuL5l/g==',+ iv: 'Cqufag7LTNkRg6Lu',+ data: '+IrsgJlM1O3yUyEvjDhl+2gLpXJzdKH9nV8JSInKsKkJFKIZfkC9uxu0Wdq0E6Ds5+U3q3lJ7DrEaN5j+jBKH8HLjAFWFyQ3y5uMYgHO6g==',+}++const opened = await decryptEnvelope(LEGACY_ENVELOPE, LEGACY_PASSWORD)+ok(JSON.parse(opened ?? 'null')?.title === 'Q3 board',+ 'a deck encrypted at 300k still opens after the iteration count is raised')+ok((await decryptEnvelope(LEGACY_ENVELOPE, 'wrong')) === null, 'the wrong password still fails closed')+ok((await decryptEnvelope({ ...LEGACY_ENVELOPE, it: 600_000 }, LEGACY_PASSWORD)) === null,+ 'and the count is what does it — deriving with any other number cannot open the same bytes')+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-sanitize.ts b/scripts/test-sanitize.tsnew file mode 100644index 00000000..11f8ba95--- /dev/null+++ b/scripts/test-sanitize.ts@@ -0,0 +1,635 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Untrusted-document rig: what a deck may put into the reader's DOM.+//+// slides/node_modules/.bin/esbuild scripts/test-sanitize.ts --bundle \+// --platform=node --format=esm --outfile="$TMPDIR/test-sanitize.mjs" \+// && node "$TMPDIR/test-sanitize.mjs"+//+// (Bundled, not run directly: render.ts imports './model' extensionless, the+// same reason the spaces undo rig is bundled in CI. Source paths below are+// therefore resolved from the REPO ROOT — import.meta.url would point at the+// bundle.)+//+// WHAT THIS PROVES. Every deck is untrusted input: mailed, downloaded, pasted,+// or delivered as a collab op into a file already open. Script running in this+// page is not a defaced slide — it holds `doc.collab.key`, the owner/writer+// private keys, the plaintext IndexedDB autosave store and the File System+// Access handle ⌘S writes through. It is the document AND the file on disk.+//+// Three places used to hand author data straight to the DOM:+//+// 1. AN `svg` ELEMENT'S MARKUP, assigned with innerHTML. Measured in Chrome+// 141 (2026-08-09): a deck whose svg element carried `<svg onload="…">`+// ran it — from a DETACHED div, before anything was inserted anywhere.+// The `svgAsImage` sibling path (a data-URI <img>) was inert all along,+// which is why only the live path changed.+// 2. TABLE CELL COLOURS, PADDINGS AND ALIGNMENTS, interpolated into a `style`+// attribute unescaped. Same measurement: a cell whose `bg` read+// `red" onmouseover="steal()` produced a `<td>` with a real `onmouseover`+// attribute — on the canvas, in present, in print and in every thumbnail.+// 3. `canvas.startTextEdit`, which swaps the RESOLVED text for the model's+// raw html so the author edits `{{page:2}}` rather than "06". It assigned+// `model.html` unsanitized, so double-clicking a text box was enough.+//+// WHY THE SVG SECTION LOOKS LIKE THIS. The first fix for (1) was a DENYLIST —+// five tags, `on*`, three url attributes — and this rig pinned it with source+// regexes over the call sites. A verifier then measured script still executing+// through the real renderSlide → renderElement → sanitizeSvg path in six ways,+// and every one of them passed all forty checks, because a source regex knows+// the sanitizer is CALLED and nothing about what it PERMITS. So:+//+// * the policy is now an allowlist, and the allowlist itself is exercised+// here in node, where it is pure data (SVG_TAGS, svgAttrAllowed,+// svgHrefAllowed, svgUrlRefsAllowed, sanitizeSvgCss);+// * the WALK is exercised in a real browser, against the real renderSlide,+// with payloads that either run or do not. `--headless=new --dump-dom`+// over a throwaway http server on 127.0.0.1, so a "did this deck phone+// home" claim is answered by a request log and not by reading the code.+//+// The browser half needs Chrome. Where there is none it says so loudly and+// skips; the node half still fails on every one of the six bypasses, because+// every one of them is a question about the policy.++import { execFileSync, spawn, spawnSync } from 'node:child_process'+import fs from 'node:fs'+import http from 'node:http'+import os from 'node:os'+import path from 'node:path'+import {+ renderTableHtml,+ sanitizeHtml,+ sanitizeSvgCss,+ svgAttrAllowed,+ svgHrefAllowed,+ svgUrlRefsAllowed,+ SVG_TAGS,+} from '../slides/src/render.ts'+import { defaultTable, newDoc } from '../slides/src/model.ts'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) {+ failures+++ console.error(` ✗ ${msg}`)+ } else {+ console.log(` ✓ ${msg}`)+ }+}++const repoFile = (rel: string): string => {+ const file = path.resolve(rel)+ if (!fs.existsSync(file)) throw new Error(`run this rig from the repo root — ${rel} not found`)+ return file+}++// --- 1. the svg policy -------------------------------------------------------+//+// Pure data and pure functions, so the decisions can be inspected here while+// the walk that applies them is measured in a browser below. Both directions+// matter equally: a sanitizer that drops `url(#…)` refs renders every+// gradient-filled diagram blank, which is the failure that gets a sanitizer+// deleted again.++console.log('\nsvg tag allowlist')++ok(['svg', 'g', 'path', 'rect', 'circle', 'defs', 'pattern', 'lineargradient', 'radialgradient', 'stop',+ 'clippath', 'mask', 'marker', 'filter', 'feturbulence', 'fecolormatrix', 'fegaussianblur',+ 'text', 'tspan', 'use', 'image', 'style', 'animate'].every((t) => SVG_TAGS.has(t)),+ 'the svg vocabulary the starter deck draws with is permitted')++for (const tag of ['script', 'foreignobject', 'iframe', 'object', 'embed', 'form', 'button', 'input',+ 'meta', 'base', 'link', 'template', 'frame', 'frameset', 'audio', 'video', 'math']) {+ ok(!SVG_TAGS.has(tag), `<${tag}> is not permitted`)+}++console.log('\nsvg attribute allowlist')++ok(['id', 'class', 'd', 'viewbox', 'fill', 'stroke-width', 'transform', 'patternunits', 'stddeviation',+ 'basefrequency', 'gradienttransform', 'preserveaspectratio', 'stop-color', 'clip-path', 'href',+ 'xlink:href', 'attributename'].every(svgAttrAllowed),+ 'the attributes real artwork carries are permitted, in the html parser’s casing too')+ok(svgAttrAllowed('viewBox') && svgAttrAllowed('attributeName') && svgAttrAllowed('stdDeviation'),+ 'and matching is case-insensitive, which is how the parser’s foreign-content fixups line up')+ok(svgAttrAllowed('aria-label') && svgAttrAllowed('role'), 'aria-* and role are permitted')+ok(svgAttrAllowed('data-part'), 'a diagram’s own data-* CSS hook is permitted')++for (const attr of ['action', 'formaction', 'http-equiv', 'srcdoc', 'onclick', 'onload', 'onerror',+ 'onbegin', 'formtarget', 'ping', 'rel', 'src', 'data-el-id', 'data-flip-id']) {+ ok(!svgAttrAllowed(attr), `${attr} is not permitted`)+}+// data-bento is reserved as a PREFIX. The shell's own marks are the full names:+// kernel serializeBody DELETES every [data-bento-transient] node from the clone+// it saves, and save.ts removes [data-bento-preview] unconditionally. Reserving+// the bare string would have left an author element answering either query.+for (const attr of ['data-bento', 'data-bento-transient', 'data-bento-preview', 'data-bento-state']) {+ ok(!svgAttrAllowed(attr), `${attr} is reserved to the shell, not lent to a diagram`)+}++console.log('\nsvg href policy')++ok(svgHrefAllowed('#grad-1'), 'a same-document fragment is kept — gradients and markers paint through url(#…)')+ok(svgHrefAllowed('https://example.com/a.png'), 'https is kept for an <image>')+ok(svgHrefAllowed('HTTP://EXAMPLE.COM/a.png'), 'scheme matching is case-insensitive')+ok(svgHrefAllowed('data:image/png;base64,iVBOR'), 'a data:image is kept — the browser loads it script-disabled')+ok(svgHrefAllowed('https://example.com/x', 'a'), 'and an <a> may point at the web — the reader clicks it')++ok(!svgHrefAllowed('javascript:alert(1)'), 'javascript: is refused')+ok(!svgHrefAllowed('JaVaScRiPt:alert(1)'), 'so is the mixed-case spelling')+ok(!svgHrefAllowed(' javascript:alert(1)'), 'leading whitespace does not smuggle it past')+ok(!svgHrefAllowed('java\tscript:alert(1)'), 'nor does a tab inside the scheme, which browsers ignore')+ok(!svgHrefAllowed('java\u0000script:alert(1)'), 'nor a NUL')+ok(!svgHrefAllowed('data:text/html,<svg onload=alert(1)>'), 'a data: that is not an image is refused')+ok(!svgHrefAllowed('//evil.example/x.svg'), 'protocol-relative is refused — it is a fetch out of a self-contained file')+ok(!svgHrefAllowed('sprites.svg#icon'), 'and so is the plain relative form, for the same reason')+ok(!svgHrefAllowed(''), 'an empty href is not a url')+ok(!svgHrefAllowed('https://evil.example/x.svg#s', 'use'),+ 'a <use> may not instance a subtree out of another document, however ordinary the scheme')+ok(!svgHrefAllowed('https://evil.example/x.svg#g', 'lineargradient'),+ 'nor may a gradient inherit from one')++console.log('\nurl() targets')++ok(svgUrlRefsAllowed('url(#bp-dots-i)'), 'fill="url(#…)" survives — it is the whole pattern/gradient idiom')+ok(svgUrlRefsAllowed('none') && svgUrlRefsAllowed('#F7A600'), 'a value with no url() at all is untouched')+ok(!svgUrlRefsAllowed('url(https://evil.example/paint.svg#g)'), 'an external paint server is refused')+ok(!svgUrlRefsAllowed("url('//evil.example/x')"), 'quoted and protocol-relative is still refused')+ok(!svgUrlRefsAllowed('url( \u0000https://evil.example/x )'), 'padding and control characters do not hide it')++console.log('\nsvg css')++ok(!/@import/i.test(sanitizeSvgCss('@import url("https://evil.example/t.css");\n.p{fill:red}')),+ '@import is removed — a live fetch out of a self-contained file, and a read receipt for a mailed deck')+ok(sanitizeSvgCss('@import "x.css";\n.p{fill:red}').includes('.p{fill:red}'),+ 'the rest of the sheet survives: dropping it would cost the artwork')+ok(sanitizeSvgCss('.p{fill:url(#g)}') === '.p{fill:url(#g)}', 'url(#…) inside the sheet is untouched')+ok(sanitizeSvgCss('.p{background:url(https://evil.example/b.png)}').includes('background:none'),+ 'an external url() becomes none — valid everywhere url() is legal, so the sheet still parses')+ok(!sanitizeSvgCss('@font-face{src:url(https://evil.example/f.woff2)}').includes('evil.example'),+ 'and a webfont fetch goes the same way')++// The at-rule half is an ALLOWLIST because cutting `@import` by name did not+// work. Measured against the allowlist-tags build on 2026-08-09, Chrome 141:+// `@\69mport "http://…";` inside an svg <style> FETCHED — the probe server+// logged the request — because a CSS at-keyword is an ident and an ident takes+// escapes. The bare-string form has no `url(` in it either, so the url() rewrite+// above never saw it.+const escaped = sanitizeSvgCss('@\\69mport "https://evil.example/t.css";\n.p{fill:red}')+ok(!/@\\?[\\\w]*import/i.test(escaped) && escaped.includes('@bento-refused'),+ 'an at-keyword written with a CSS escape is refused — @\\69mport is @import')+ok(escaped.includes('.p{fill:red}'), 'and the sheet around it still parses')+ok(sanitizeSvgCss('@im\\port url(x);').includes('@bento-refused'), 'so is @im\\port')+ok(sanitizeSvgCss('@\\49MPORT "x";').includes('@bento-refused'), 'and @\\49MPORT')+ok(!sanitizeSvgCss('@import "https://evil.example/t.css";').includes('evil.example')+ || sanitizeSvgCss('@import "https://evil.example/t.css";').startsWith('@bento-refused'),+ 'the bare-STRING import is refused too — the url() rewrite cannot see that one')+ok(sanitizeSvgCss('@import "https://evil.example/t.css"\n.p{fill:red}').includes('@bento-refused'),+ 'and so is the form with no semicolon, which the old regex required')+ok(!sanitizeSvgCss('@document url-prefix();.p{fill:red}').includes('@document'),+ 'an at-rule nobody asked for is refused by default, which is the point of a list')++for (const at of ['@media screen{.p{fill:red}}', '@supports (fill:red){.p{fill:red}}',+ '@keyframes spin{to{transform:rotate(1turn)}}', '@-webkit-keyframes spin{to{opacity:0}}',+ '@font-face{font-family:X;src:local("X")}', '@layer base{.p{fill:red}}']) {+ ok(sanitizeSvgCss(at) === at, `${at.slice(0, at.indexOf(' ') > 0 ? at.indexOf(' ') : at.indexOf('{'))} is kept — motion and layout are what a diagram's sheet is for`)+}+ok(sanitizeSvgCss('.p::before{content:"a@b"}') === '.p::before{content:"a@b"}',+ 'an @ that does not start a token is not an at-rule')++// --- 2. the table, end to end ------------------------------------------------+//+// renderTableHtml is a string builder with no DOM in it, so the real output can+// be inspected here. Every value below is what a received deck can contain: the+// model's `string` and `number` are types, not promises.++console.log('\ntable style attribute')++const doc = newDoc()+const hostile = defaultTable()+hostile.rows[1].cells[0] = { html: 'ok', bg: 'red" onmouseover="steal()', color: '#0F0' }+hostile.rows[1].cells[1] = { html: 'two', align: 'right;background:url(https://evil.example/p)' as never }+hostile.rows[1].cells[2] = { html: 'three', color: 'expression(alert(1))' }+hostile.style.cellPadY = '0;position:fixed;inset:0' as never+hostile.style.borderColor = 'x" onclick="steal()'+hostile.style.fontFamily = 'Inter;}</sty' + 'le><b>x'+const out = renderTableHtml(hostile, doc)++/** One cell's opening tag — everything a parser reads before the first ">". */+const cellTag = (r: number, c: number) => {+ const at = out.indexOf(`<td data-r="${r}" data-c="${c}"`)+ return at < 0 ? '' : out.slice(at, out.indexOf('>', at) + 1)+}++ok(!/\son[a-z]+\s*=/i.test(out), 'no event-handler attribute is minted anywhere in the table')+ok(!out.includes('onmouseover="steal()') && !out.includes('onclick="steal()'),+ 'the two handler payloads are gone, not merely renamed')+ok(!out.includes('evil.example'), 'an alignment carrying a url() cannot reach the stylesheet')+ok(!/expression\(/i.test(out), 'nor can expression()')+ok(!out.includes('position:fixed'), 'a padding that is not a number cannot add declarations')+ok(cellTag(1, 0).includes('background:transparent'), 'the rejected colour falls back rather than being "cleaned"')+ok(cellTag(1, 1).includes('text-align:left'), 'the rejected alignment falls back to the format default')+ok(out.includes('font-family:inherit'), 'and the rejected font stack falls back too')+// The structural version of the same claim, and the one that fails loudly on+// the old output: a `=` cannot occur inside a validated style value, so three+// of them is exactly data-r, data-c and style. The old cell had four.+ok((cellTag(1, 0).match(/=/g) ?? []).length === 3, 'the cell tag still carries three attributes and no fourth')++console.log('\ntable, unremarkable content')++const plain = defaultTable()+plain.rows[1].cells[0] = { html: 'Revenue', align: 'right', color: '#1E2A3A', bg: 'rgba(30,42,58,0.05)', bold: true }+const good = renderTableHtml(plain, doc)+ok(good.includes('text-align:right'), 'a real alignment survives')+ok(good.includes('color:#1E2A3A'), 'a hex colour survives')+ok(good.includes('background:rgba(30,42,58,0.05)'), 'an rgba() colour survives — the zebra stripe is one')+ok(good.includes(`font-family:${doc.theme.fontFamily.replace(/"/g, '"')}`), "the deck's font stack survives")+ok(good.includes('font-size:18px') && good.includes('padding:11px 16px'), 'so do the numeric style fields')+ok(good.includes('>Revenue<'), 'and the cell text is still there')++const cjk = defaultTable()+cjk.style.fontFamily = 'ヒラギノ角ゴ ProN, sans-serif'+ok(renderTableHtml(cjk, doc).includes('ヒラギノ角ゴ'),+ 'a non-ASCII font family survives — a character allowlist would have eaten it')++// --- 3. the raw-html swap ----------------------------------------------------+//+// startTextEdit shows the model's raw html so the author edits the TOKEN and+// not the computed value. Sanitizing there is only free if the two things the+// swap exists for are not markup — and they are not, which is the point.++console.log('\ntokens survive the sanitizer')++const RAW = '{{page:2}} of {{pages}} — $E=mc^2$ and $$\\frac{a}{b}$$'+ok(sanitizeHtml(RAW).includes('{{page:2}}'), 'a zero-padded page field round-trips')+ok(sanitizeHtml(RAW).includes('$E=mc^2$'), 'inline TeX source round-trips')+ok(sanitizeHtml(RAW).includes('$$\\frac{a}{b}$$'), 'display TeX source round-trips')++// --- 4. the walk, in a browser ----------------------------------------------+//+// Everything above is a decision. This is the machinery, and the machinery is+// where the bypasses lived: a policy is only as good as the walk that reaches+// every node. So the payloads below go through the REAL renderSlide into a+// REAL document, and the ones that are supposed to run are given every chance+// to — inserted, clicked, submitted — while a local server logs whether the+// page reached for anything.+//+// The `MUST NOT execute` cases each have a number: they are the six the+// verifier measured against the denylist build (2026-08-09, Chrome 141). 1, 2+// and 3 ran or navigated for real there; 4 fetched; 5 and 6 survived the walk+// intact and were refused only by Blink's own restraint, which is not a+// security boundary.++const CHROME = [+ process.env.BENTO_CHROME,+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ '/Applications/Chromium.app/Contents/MacOS/Chromium',+ '/usr/bin/google-chrome',+ '/usr/bin/google-chrome-stable',+ '/usr/bin/chromium',+ '/usr/bin/chromium-browser',+].find((p): p is string => !!p && fs.existsSync(p))+ ?? (spawnSync('which', ['google-chrome']).status === 0 ? 'google-chrome' : undefined)++/**+ * The page that does the work. Bundled by esbuild against the repo's own+ * render.ts, so this is the shipping code path and not a re-implementation of+ * it. Written without backticks or `${` so it can live in a template literal.+ */+const probeSource = (renderPath: string, modelPath: string) => `+import { renderSlide } from ${JSON.stringify(renderPath)}+import { newDoc } from ${JSON.stringify(modelPath)}++const O = location.origin+const pwned: number[] = []+;(window as any).__pwn = (n: number) => { pwned.push(n) }++const results: Array<[string, boolean]> = []+const check = (name: string, pass: boolean) => { results.push([name, pass]) }++/** The shipping path: model → renderSlide → renderElement → sanitizeSvg. */+function draw(markup: string, css?: string): HTMLElement {+ const doc = newDoc()+ const slide = doc.slides[0]+ slide.elements = [{+ id: 'sv1', type: 'svg', x: 0, y: 0, w: 200, h: 200,+ rotation: 0, opacity: 1, markup, ...(css ? { css } : {}),+ } as any]+ const surface = renderSlide(slide, doc)+ document.body.appendChild(surface)+ return surface+}++if (location.pathname === '/meta.html') {+ // Finding 2, the live half: if the meta survives the walk, Chrome navigates+ // this document to /pwned.html and the dumped DOM is somebody else's page.+ draw('<svg><rect width="10" height="10"/><meta http-equiv="refresh" content="0;url=/pwned.html"></svg>')+ draw('<div>x</div><meta http-equiv="refresh" content="0;url=/pwned.html">')+} else {+ try {+ const baseBefore = document.baseURI++ // Several payloads below open with a throwaway <div>, and it is not padding:+ // a LEADING <link>, <meta>, <base> or <template> is hoisted into <head> by+ // DOMParser, and the walk only ever sees parsed.body. Tested at the front of+ // the string, every one of them passes against a sanitizer that does nothing+ // — measured on the denylist build, which "passed" three of these until the+ // div went in. One line of body content is what puts them in the walk's way.++ // --- 1. form-driven javascript: (action / formaction / input type=image) ---+ const shot = draw(+ '<form action="javascript:window.__pwn(11)"><button type="submit">go</button></form>' ++ '<form><button type="submit" formaction="javascript:window.__pwn(12)">go</button></form>' ++ '<form action="javascript:window.__pwn(13)">' ++ '<input type="image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="></form>'+ )+ check('1 — no <form>, <button> or <input> survives the walk',+ shot.querySelectorAll('form, button, input').length === 0)++ // --- 2. meta refresh (structure here, navigation in the second run) --------+ const metas = draw('<svg><rect width="10" height="10"/><meta http-equiv="refresh" content="0;url=/pwned.html"></svg>' ++ '<div>x</div><meta http-equiv="refresh" content="0;url=/pwned.html">')+ check('2 — no <meta> survives the walk', metas.querySelectorAll('meta').length === 0)++ // --- 3. base href ----------------------------------------------------------+ const based = draw('<div>x</div><base href="' + O + '/evil/"><svg><rect width="10" height="10"/></svg>')+ check('3 — no <base> survives the walk', based.querySelectorAll('base').length === 0)+ check('3 — relative urls still resolve against this document', document.baseURI === baseBefore)++ // --- 4. network out of a self-contained file -------------------------------+ draw('<div>x</div><link rel="stylesheet" href="' + O + '/tracker.css">' ++ '<svg><style>@import url("' + O + '/imported.css");.q{fill:red}</sty' + 'le>' ++ '<rect class="q" width="10" height="10" fill="url(' + O + '/paint.svg#g)"/></svg>')+ draw('<svg><rect width="10" height="10"/></svg>', '@import url("' + O + '/model-css.css");.z{fill:red}')++ // 4, the spellings that beat a regex written around the word "import".+ // Both of these FETCHED against the build that cut @import by name+ // (2026-08-09, Chrome 141): an at-keyword is an ident, and an ident takes+ // escapes; and the string form carries no url( for the url() rewrite to+ // find. This is why CSS at-rules are an allowlist now.+ draw('<svg><style>@\\\\69mport "' + O + '/esc-import.css";.q{fill:red}</sty' + 'le>' ++ '<rect width="10" height="10"/></svg>')+ draw('<svg><style>@import "' + O + '/str-import.css";.q{fill:red}</sty' + 'le>' ++ '<rect width="10" height="10"/></svg>')+ // no semicolon where the parser wants one, and a <style> in HTML context+ // rather than inside the svg — same sheet, same policy, different route in.+ draw('<svg><style>@import "' + O + '/nosemi-import.css"\\n.q{fill:red}</sty' + 'le></svg>')+ draw('<div>x</div><style>@\\\\69mport "' + O + '/html-style.css";</style>')++ // and the sheet a real diagram writes still animates+ const sheet = draw('<svg><style>@keyframes bp-spin{to{transform:rotate(1turn)}}' ++ '@media (min-width:1px){.q{fill:url(#g)}}</sty' + 'le>' ++ '<rect class="q" width="10" height="10"/></svg>')+ check('a diagram keeps @keyframes and @media — the allowlist is not a ban on CSS',+ (sheet.querySelector('style')?.textContent ?? '').includes('@keyframes bp-spin') &&+ (sheet.querySelector('style')?.textContent ?? '').includes('@media (min-width:1px)'))++ // --- 5. SMIL retargeting ---------------------------------------------------+ const smil = draw('<svg><rect id="sm" width="10" height="10">' ++ '<set attributeName="onclick" to="window.__pwn(51)"/>' ++ '<animate attributeName="href" to="javascript:window.__pwn(52)" dur="1s" fill="freeze"/>' ++ '</rect></svg>')+ check('5 — an animation that would write an on* handler is gone',+ smil.querySelectorAll('set, animate').length === 0)+ check('5 — and nothing in the subtree carries an onclick',+ !Array.from(smil.querySelectorAll('*')).some((e) => e.hasAttribute('onclick')))++ // --- 6. template ------------------------------------------------------------+ const tpl = draw('<div>x</div><template><img src="x" onerror="window.__pwn(61)"><svg onload="window.__pwn(62)"></svg></template>')+ check('6 — no <template> survives, so nothing hides in .content',+ tpl.querySelectorAll('template').length === 0 && !tpl.innerHTML.includes('__pwn'))++ // --- 7. the xlink spelling of everything above -----------------------------+ //+ // href and xlink:href are the same attribute to a browser, and a policy+ // that only knows the short name is a policy with a second door in it.+ const xl = draw('<svg xmlns:xlink="http://www.w3.org/1999/xlink">' ++ '<a id="xa" xlink:href="javascript:window.__pwn(81)"><rect width="10" height="10"/></a>' ++ '<image id="xi" xlink:href="' + O + '/xlink-remote.png" width="10" height="10"/>' ++ '<use id="xu" xlink:href="' + O + '/xlink.svg#s"/>' ++ '<rect id="xr" width="10" height="10"><animate attributeName="xlink:href" to="javascript:window.__pwn(82)" dur="1s"/></rect>' ++ '</svg>')+ check('7 — a javascript: xlink:href loses its href just as a plain one does',+ !!xl.querySelector('#xa') && !xl.querySelector('#xa')!.hasAttribute('xlink:href'))+ check('7 — a <use> reaching out of the document by xlink:href is dropped whole',+ !xl.querySelector('#xu'))+ check('7 — an animation retargeting xlink:href is gone',+ xl.querySelectorAll('animate').length === 0)++ // --- 8. the html integration points --------------------------------------+ //+ // <desc>, <title> and <foreignObject> are where the parser LEAVES foreign+ // content and resumes html rules, so a <script> written inside one is a real+ // html script element and not svg text. The walk has to recurse into them.+ const desc = draw('<svg><desc><scr' + 'ipt>window.__pwn(91)</scr' + 'ipt>' ++ '<img src="' + O + '/desc-img.png" onerror="window.__pwn(92)"></desc>' ++ '<title><img src="' + O + '/title-img.png"></title><rect width="10" height="10"/></svg>')+ check('8 — nothing survives inside <desc> or <title>, where html parsing resumes',+ desc.querySelectorAll('script, img').length === 0 && !!desc.querySelector('rect'))++ // --- 9. an svg carried as a data: image ------------------------------------+ //+ // data:image/ is allowed on an <image> href on purpose. An svg loaded THAT+ // way is script-disabled by the browser, and this is the check that says so+ // rather than assuming it.+ draw('<svg><image width="99" height="99" href="data:image/svg+xml,' ++ encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="99" height="99" onload="top.__pwn(101)">' ++ '<rect width="9" height="9" fill="red"/></svg>') + '"/></svg>')++ // --- 0. the case round one did fix, still fixed ----------------------------+ const classic = draw('<svg onload="window.__pwn(1)"><rect id="clicky" width="10" height="10" onclick="window.__pwn(2)"/>' ++ '<scr' + 'ipt>window.__pwn(3)</scr' + 'ipt>' ++ '<foreignObject><img src="x" onerror="window.__pwn(4)"></foreignObject></svg>')+ check('0 — script and foreignObject are gone and no on* handler is left',+ classic.querySelectorAll('script, foreignObject').length === 0 &&+ !Array.from(classic.querySelectorAll('*')).some((e) =>+ Array.from(e.attributes).some((a) => a.name.toLowerCase().startsWith('on'))))++ // --- refs -------------------------------------------------------------------+ const refs = draw('<svg><a id="ok" href="https://example.com/x">t</a>' ++ '<a id="bad" href="javascript:window.__pwn(71)">t</a>' ++ '<image id="img" href="' + O + '/remote.png" width="10" height="10"/>' ++ '<image id="jsimg" href="javascript:window.__pwn(72)" width="10" height="10"/>' ++ '<use id="localuse" href="#ok"/><use id="remoteuse" href="' + O + '/x.svg#s"/></svg>')+ check('an <a> to the web is kept', refs.querySelector('#ok')!.getAttribute('href') === 'https://example.com/x')+ check('a javascript: <a> loses its href but keeps its place in the layout',+ !!refs.querySelector('#bad') && !refs.querySelector('#bad')!.hasAttribute('href'))+ check('an http <image> is kept', !!refs.querySelector('#img'))+ check('a javascript: <image> loses its href', !refs.querySelector('#jsimg')!.hasAttribute('href'))+ check('a same-document <use> is kept', !!refs.querySelector('#localuse'))+ check('a <use> pointing out of this document is dropped whole', !refs.querySelector('#remoteuse'))++ // --- the artwork that has to keep drawing ----------------------------------+ const art = draw('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" preserveAspectRatio="none">' ++ '<defs><pattern id="bp-dots-i" width="28" height="28" patternUnits="userSpaceOnUse">' ++ '<circle cx="1.5" cy="1.5" r="1.4" fill="#FFFFFF" opacity="0.07"/></pattern>' ++ '<radialGradient id="bp-ga-am"><stop offset="0" stop-color="#FFEED6" stop-opacity="0.15"/></radialGradient>' ++ '<filter id="bp-grain"><feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" stitchTiles="stitch"/>' ++ '<feColorMatrix type="matrix" values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.045 0"/></filter></defs>' ++ '<sty' + 'le>.dot{fill:url(#bp-ga-am)}</sty' + 'le>' ++ '<rect width="1280" height="720" fill="url(#bp-dots-i)" filter="url(#bp-grain)"/></svg>')+ check('a pattern keeps its id — url(#…) resolves document-globally',+ !!art.querySelector('pattern#bp-dots-i') && !!art.querySelector('radialGradient#bp-ga-am'))+ check('and the rect still points at it', art.querySelector('rect')!.getAttribute('fill') === 'url(#bp-dots-i)')+ check('feTurbulence keeps baseFrequency and feColorMatrix keeps values',+ art.querySelector('feTurbulence')!.getAttribute('baseFrequency') === '0.9' &&+ !!art.querySelector('feColorMatrix')!.getAttribute('values'))+ check('viewBox and preserveAspectRatio survive the parser round-trip',+ art.querySelector('svg')!.getAttribute('viewBox') === '0 0 1280 720')+ check('the svg <style> is kept — scopeCss is what stops it leaking',+ (art.querySelector('style')?.textContent ?? '').includes('.dot{fill:url(#bp-ga-am)}'))++ const sloppy = draw('<svg viewBox="0 0 20 20"><rect width="10" height="10"><circle cx="5" cy="5" r="2"/></svg>')+ check('an unclosed tag still draws — text/html, not the fatal xml parser',+ !!sloppy.querySelector('svg') && !!sloppy.querySelector('circle'))++ // Give every payload its chance: insertion alone is not the only trigger.+ // Measured on the pre-sanitizer build, where the difference showed: a+ // form-driven javascript: needs the submit button CLICKED, and an+ // onclick on a rect needs a click dispatched at the rect. Only the+ // javascript: anchors are clicked — clicking an ordinary one navigates the+ // probe away and it reports nothing at all.+ for (const el of Array.from(document.querySelectorAll('button, input'))) (el as HTMLElement).click()+ for (const f of Array.from(document.querySelectorAll('form'))) {+ try { (f as HTMLFormElement).requestSubmit() } catch { /* no submitter */ }+ }+ for (const a of Array.from(document.querySelectorAll('a'))) {+ const href = (a.getAttribute('href') ?? a.getAttribute('xlink:href') ?? '').toLowerCase()+ if (href.startsWith('javascript:')) (a as HTMLElement).click()+ }+ // Never inside an <a>: a click that bubbles to the ALLOWED+ // https://example.com anchor navigates, and a probe that navigated reports+ // nothing at all (measured — the dump held the rendered slides and no+ // results block).+ for (const el of Array.from(document.querySelectorAll('#clicky, [onclick], [onmouseover]'))) {+ if (!el.closest('a')) el.dispatchEvent(new MouseEvent('click', { bubbles: true }))+ }++ } catch (err) {+ // A probe that dies half way through would otherwise report only the+ // checks it reached, all of them passing.+ check('the probe ran to the end (it threw: ' + String(err) + ')', false)+ }++ setTimeout(() => {+ check('nothing executed: ' + (pwned.length ? pwned.join(',') : 'clean'), pwned.length === 0)+ const pre = document.createElement('pre')+ pre.id = 'bento-results'+ // btoa is Latin-1 only and every check name here has an em dash in it:+ // encode to utf-8 bytes first or this throws and the rig reports nothing.+ const utf8 = new TextEncoder().encode(JSON.stringify(results))+ pre.textContent = 'BENTO-RESULTS:' + btoa(String.fromCharCode(...utf8)) + ':END'+ document.body.appendChild(pre)+ }, 400)+}+`++async function runBrowserSection(chrome: string) {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-sanitize-'))+ const entry = path.join(tmp, 'probe.ts')+ fs.writeFileSync(entry, probeSource(repoFile('slides/src/render.ts'), repoFile('slides/src/model.ts')))+ execFileSync(repoFile('slides/node_modules/.bin/esbuild'), [+ entry, '--bundle', '--format=esm', '--outfile=' + path.join(tmp, 'probe.js'),+ ], { stdio: 'pipe' })+ const bundle = fs.readFileSync(path.join(tmp, 'probe.js'), 'utf8')++ // Written by concatenation: never a literal script-close in a source file+ // (AGENTS.md #1). This one is not spliced into a deck, but the habit is the+ // rule.+ // The trailing <img> is a LOAD GATE, and it is load-bearing: the new headless+ // ignores --virtual-time-budget, so `--dump-dom` fires at the load event and+ // a probe that reports from a timer reports nothing at all (measured — the+ // dump held every rendered slide and no results block). The server answers+ // /slow.gif late, load waits for it, and the probe's timer lands first.+ const page = (marker: string) =>+ '<!doctype html><meta charset="utf-8"><title>bento sanitize probe</title>' ++ '<body>' + marker ++ '<scr' + 'ipt type="module" src="/probe.js"></scr' + 'ipt>' ++ '<img src="/slow.gif" width="1" height="1" alt=""></body>'++ const hits: string[] = []+ const server = http.createServer((req, res) => {+ const url = (req.url ?? '/').split('?')[0]+ hits.push(url)+ if (url === '/probe.js') { res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(bundle); return }+ if (url === '/probe.html') { res.writeHead(200, { 'content-type': 'text/html' }); res.end(page('BENTO-PROBE')); return }+ if (url === '/meta.html') { res.writeHead(200, { 'content-type': 'text/html' }); res.end(page('BENTO-STAYED')); return }+ if (url === '/pwned.html') { res.writeHead(200, { 'content-type': 'text/html' }); res.end('<!doctype html>BENTO-NAVIGATED'); return }+ if (url.endsWith('.css')) { res.writeHead(200, { 'content-type': 'text/css' }); res.end('.tracked{fill:red}'); return }+ const gif = () => {+ res.writeHead(200, { 'content-type': 'image/gif' })+ res.end(Buffer.from('R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==', 'base64'))+ }+ if (url === '/slow.gif') { setTimeout(gif, 1500); return }+ gif()+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const port = (server.address() as { port: number }).port++ // spawn, never spawnSync: the server above lives in THIS process, so a+ // synchronous child blocks the event loop that has to answer Chrome's+ // request for /probe.js — measured as a hang, not as a failure.+ const load = (route: string) => new Promise<string>((resolve) => {+ const child = spawn(chrome, [+ '--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run',+ '--no-default-browser-check', '--disable-background-networking',+ '--disable-component-update', '--disable-sync', '--disable-default-apps',+ '--user-data-dir=' + path.join(tmp, 'profile'),+ '--virtual-time-budget=4000', '--dump-dom',+ `http://127.0.0.1:${port}${route}`,+ ], { stdio: ['ignore', 'pipe', 'ignore'] })+ let dom = ''+ child.stdout.on('data', (b: Buffer) => { dom += b.toString('utf8') })+ const done = setTimeout(() => child.kill('SIGKILL'), 45_000)+ child.on('close', () => { clearTimeout(done); resolve(dom) })+ })++ try {+ const dom = await load('/probe.html')+ const blob = /BENTO-RESULTS:([A-Za-z0-9+/=]+):END/.exec(dom)+ if (!blob) {+ const dumped = path.join(os.tmpdir(), 'bento-sanitize-dump.html')+ fs.writeFileSync(dumped, dom)+ ok(false, `the browser probe reported results (it did not — dumped DOM in ${dumped})`)+ } else {+ for (const [name, pass] of JSON.parse(Buffer.from(blob[1], 'base64').toString('utf8')) as Array<[string, boolean]>) {+ ok(pass, name)+ }+ }++ // Finding 2's live half. A page that navigated is somebody else's page.+ const metaDom = await load('/meta.html')+ ok(!metaDom.includes('BENTO-NAVIGATED') && metaDom.includes('BENTO-STAYED'),+ '2 — a meta refresh in a deck does not navigate the reader off the document')++ ok(!hits.includes('/tracker.css'), '4 — a <link rel=stylesheet> in a deck never fetches')+ ok(!hits.includes('/imported.css'), '4 — nor does @import inside the svg <style>')+ ok(!hits.includes('/model-css.css'), "4 — nor @import in the model's own css field")+ ok(!hits.includes('/paint.svg'), '4 — nor an external paint server in fill="url(…)"')+ ok(!hits.includes('/esc-import.css'), '4 — nor @\\69mport, which fetched until at-rules became an allowlist')+ ok(!hits.includes('/str-import.css'), '4 — nor the bare-string @import, which carries no url() to rewrite')+ ok(!hits.includes('/nosemi-import.css'), '4 — nor the form with no semicolon')+ ok(!hits.includes('/html-style.css'), '4 — nor a <style> that reached the body in html context')+ ok(!hits.includes('/desc-img.png') && !hits.includes('/title-img.png'),+ '8 — nothing inside <desc> or <title> fetches either')+ ok(!hits.includes('/xlink.svg'), '7 — nor an xlink:href <use> pointing out of the document')+ ok(hits.includes('/remote.png'), 'an <image href="http(s)://…"> still loads — that one is allowed on purpose')+ ok(hits.includes('/xlink-remote.png'), 'and so does the xlink:href spelling of it — the policy is not a ban on pictures')+ } finally {+ server.close()+ fs.rmSync(tmp, { recursive: true, force: true })+ }+}++console.log('\nthe walk, in a browser')+if (!CHROME) {+ console.log(' ⚠ SKIPPED — no Chrome found. Set BENTO_CHROME to a binary to run this section;')+ console.log(' it is the only half that can prove a payload does not RUN.')+} else {+ await runBrowserSection(CHROME)+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-tray-bridge.ts b/scripts/test-tray-bridge.tsnew file mode 100644index 00000000..917a392f--- /dev/null+++ b/scripts/test-tray-bridge.ts@@ -0,0 +1,268 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// iOS tray bridge rig — the untrusted-name filter, the handle routing, and the+// JS reply encoder.+//+// node scripts/test-tray-bridge.ts+//+// WHAT THIS PROVES. These functions guard the boundary where a DOCUMENT — which+// this host treats as untrusted, since it opens any self-contained HTML file —+// reaches native file writes and native JS eval. None of the failures is+// visible: a traversal write lands before the export picker appears, so the user+// is shown a picker for a different file than the one written; an export vended+// under the open document's own name overwrites the original silently; a+// mis-encoded reply either hangs a promise forever or mutates the document on+// its way back to the page. Nothing downstream notices.+//+// The functions are EXTRACTED FROM THE REAL SOURCE rather than copied here, so+// this cannot pass against a stale duplicate of code that has since regressed.+// It fails against the pre-fix EditorViewController.swift: safeFileName did not+// exist, the encoder escaped only '"', and an export whose suggested name+// reduced onto the open file's name routed to the in-place overwrite.+//+// Two halves. The SHAPE checks read the source and always run, so a Linux CI+// runner still catches the call sites drifting back. The BEHAVIOUR checks+// compile the real function bodies and run them, and need a Swift toolchain —+// they skip cleanly without one.++import { readFileSync, writeFileSync, mkdtempSync, existsSync } from 'node:fs'+import { execFileSync, spawnSync } from 'node:child_process'+import { tmpdir } from 'node:os'+import { join, dirname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++// Walk up to the repo root rather than assuming a fixed depth, so the rig runs+// from wherever it is invoked.+const REL = 'tray/ios/EditorViewController.swift'+let SRC = ''+for (const from of [dirname(fileURLToPath(import.meta.url)), process.cwd()]) {+ for (let d = from; d !== resolve(d, '..'); d = resolve(d, '..')) {+ if (existsSync(join(d, REL))) { SRC = join(d, REL); break }+ }+ if (SRC) break+}+if (!SRC) { console.log(` FAIL could not find ${REL}`); process.exit(1) }++let failures = 0+let checks = 0+function ok(cond, msg) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++// ------------------------------------------------------------------ extraction+// Brace-matched slice of one declaration out of the Swift source.+function slice(src, decl) {+ const at = src.indexOf(decl)+ if (at < 0) throw new Error(`${decl} not found in ${SRC} — did it get renamed?`)+ let depth = 0+ for (let j = src.indexOf('{', at); j < src.length; j++) {+ if (src[j] === '{') depth+++ else if (src[j] === '}' && --depth === 0) return src.slice(at, j + 1)+ }+ throw new Error(`unbalanced braces reading ${decl}`)+}+const extractFunc = (src, name) => slice(src, `private func ${name}(`).replace(/^private /, '')++const swift = readFileSync(SRC, 'utf8')++// ----------------------------------------------------------------- shape checks+// Each of these is a call site that was, or could again be, the bug.+const handler = slice(swift, 'func userContentController(')++ok(!/appendingPathComponent\(suggestedFilename\)/.test(swift)+ && /appendingPathComponent\(safeFileName\(suggestedFilename\)/.test(swift),+ 'the download destination filters suggestedFilename instead of trusting WebKit')++ok(!/==\s*document\.fileURL\.lastPathComponent/.test(handler),+ 'read/write do not route on a bare filename comparison')+ok((handler.match(/targetsOpenDocument\(/g) || []).length === 2,+ 'both read and write route through targetsOpenDocument')++ok(!/return\s+"\\""\\""/.test(swift) && /else\s*{\s*return\s+"null"\s*}/.test(swift),+ 'jsString falls back to null, never to a claim that the file is empty')++// pendingExportName held the sanitised name and was then read back on the very+// next line and never again — a stored property that only a local needed, and+// one nothing stops a later edit from consulting after it has gone stale.+ok(!/private var pendingExportName/.test(swift),+ 'no stored property shadows the export name the page was handed')++if (spawnSync('swiftc', ['--version']).status !== 0) {+ console.log(' skip no Swift toolchain on this machine — behaviour checks not run')+ console.log(`\n${checks - failures}/${checks} checks passed`)+ process.exit(failures ? 1 : 0)+}++// ------------------------------------------------------------------- behaviour+// exportName and targetsOpenDocument read two properties of the view controller.+// Those two references are REBOUND to harness variables so the real bodies can+// run outside UIKit; the rebinding is asserted, so a rename fails the rig loudly+// rather than quietly leaving it testing nothing.+function extractBound(name) {+ const before = extractFunc(swift, name)+ const after = before.replace(/document\.fileURL\.lastPathComponent/g, 'openName')+ if (after === before) throw new Error(`${name} no longer reads the open document's name`)+ return after+}++const harness = `import Foundation+var openName = ""+var openDocumentVended = false+${extractFunc(swift, 'safeFileName')}+${extractFunc(swift, 'jsString')}+${extractBound('exportName')}+${extractBound('targetsOpenDocument')}++func b64(_ s: String) -> String { Data(s.utf8).base64EncodedString() }++// stdin: "<mode> <base64 utf8 arg>…" per line, "-" standing in for an empty+// argument so the positions never shift. stdout, per line:+// name <raw> -> "nil" | "ok <b64 name> <0|1 inside the temp dir>"+// js <raw> -> "ok <b64 literal>"+// export <open name> <suggested> -> "ok <b64 vended name>"+// route <open name> <name> <0|1> -> "ok <b64 1|0>"+let dir = FileManager.default.temporaryDirectory+while let line = readLine(strippingNewline: true) {+ let p = line.split(separator: " ").map(String.init)+ func arg(_ i: Int) -> String {+ guard i < p.count, p[i] != "-", let d = Data(base64Encoded: p[i]),+ let s = String(data: d, encoding: .utf8) else { return "" }+ return s+ }+ switch p[0] {+ case "name":+ guard let out = safeFileName(arg(1)) else { print("nil"); continue }+ // The property exportCopy asserts, evaluated on the real URL machinery+ // for every name the filter lets through.+ let inside = dir.appendingPathComponent(out).standardizedFileURL.path+ .hasPrefix(dir.standardizedFileURL.path + "/")+ print("ok " + b64(out) + " " + (inside ? "1" : "0"))+ case "export":+ openName = arg(1)+ print("ok " + b64(exportName(arg(2))))+ case "route":+ openName = arg(1)+ openDocumentVended = arg(3) == "1"+ print("ok " + b64(targetsOpenDocument(arg(2)) ? "1" : "0"))+ default:+ print("ok " + b64(jsString(arg(1))))+ }+}+`++const work = mkdtempSync(join(tmpdir(), 'bento-tray-rig-'))+writeFileSync(join(work, 'harness.swift'), harness)+execFileSync('swiftc', ['-swift-version', '5', '-o', join(work, 'harness'), join(work, 'harness.swift')],+ { stdio: 'inherit' })++const b64 = (s) => Buffer.from(s, 'utf8').toString('base64')+function run(cases) {+ const stdin = cases.map((c) => c.map((v, i) => (i === 0 ? v : b64(v) || '-')).join(' ')).join('\n') + '\n'+ const out = execFileSync(join(work, 'harness'), { input: stdin, encoding: 'utf8' })+ return out.split('\n').filter(Boolean).map((line) => {+ if (line === 'nil') return null+ const [, val, inside] = line.split(' ')+ return { value: Buffer.from(val, 'base64').toString('utf8'), inside: inside === '1' }+ })+}++// ------------------------------------------------------------- names: refused+// Every one of these reaches appendingPathComponent unchanged in the old code.+const attacks = [+ '../Documents/Notes.bento.html', // the Documents folder is user-visible in Files+ '../../Library/Preferences/x.plist',+ '..',+ '.',+ '.hidden.html',+ '/',+ '',+ 'a/../../b.html',+ 'foo/', // lastPathComponent would hand back "foo"+]+const refused = run(attacks.map((a) => ['name', a]))+attacks.forEach((a, i) => {+ const got = refused[i]+ // "foo/" and "a/../../b.html" reduce to a legitimate single component; what+ // matters is that nothing escapes, not that every input is refused.+ if (got === null) ok(true, `refused ${JSON.stringify(a)}`)+ else ok(got.inside && !got.value.includes('/'),+ `${JSON.stringify(a)} reduced to ${JSON.stringify(got.value)}, still inside the temp dir`)+})+ok(refused[0] === null || refused[0].value === 'Notes.bento.html',+ 'a traversal into Documents/ cannot address Documents/')+ok(refused[2] === null && refused[3] === null && refused[4] === null,+ '"..", "." and a dotfile are all refused outright')+ok(refused[5] === null && refused[6] === null, 'bare "/" and "" are refused')++// -------------------------------------------------------------- names: allowed+const good = ['Deck.bento.html', 'Q4 review (final).bento.html', '日本語.bento.html',+ 'read-only copy.bento.html', 'a..b.html']+const allowed = run(good.map((g) => ['name', g]))+good.forEach((g, i) => {+ ok(allowed[i] !== null && allowed[i].value === g, `passes a real export name ${JSON.stringify(g)}`)+ ok(allowed[i] !== null && allowed[i].inside, `${JSON.stringify(g)} resolves inside the temp dir`)+})++// ------------------------------------------------------- handles: export names+// The vended name IS the handle, so an export may not be vended under the open+// document's name — Bento suggests a name derived from the deck TITLE, so a deck+// saved as its own title collides on an ordinary "Duplicate as new deck…".+const OPEN = 'Notes.bento.html'+const vended = run([+ ['export', OPEN, OPEN], // the collision that loses the original+ ['export', OPEN, 'Notes (read-only).bento.html'],+ ['export', OPEN, '../Notes.bento.html'], // traversal that REDUCES onto it+ ['export', OPEN, ''], // no suggestion at all+ ['export', OPEN, '../../etc/passwd'],+])+ok(vended[0].value !== OPEN, `an export suggested "${OPEN}" is not vended as "${OPEN}"`)+ok(vended[0].value.endsWith('.bento.html'),+ `the disambiguated name keeps the double extension (${JSON.stringify(vended[0].value)})`)+ok(vended[1].value === 'Notes (read-only).bento.html', 'a non-colliding export name is untouched')+ok(vended[2].value !== OPEN, 'a traversal that reduces onto the open name is disambiguated too')+ok(vended[3].value !== OPEN && vended[3].value !== '', 'a missing suggestion still vends a usable name')+ok(vended.every((v) => !v.value.includes('/')), 'no vended export name carries a path separator')++// ------------------------------------------------------------ handles: routing+const routed = run([+ ['route', OPEN, OPEN, '1'],+ ['route', OPEN, OPEN, '0'], // no handle vended for it yet+ ['route', OPEN, vended[0].value, '1'], // the export handle from above+ ['route', OPEN, 'Something else.bento.html', '1'],+ ['route', OPEN, '', '1'], // a write with no name at all+])+ok(routed[0].value === '1', 'the open document\u2019s own handle still writes in place')+ok(routed[1].value === '0', 'a name the page invented before any handle was vended cannot address the file')+ok(routed[2].value === '0', 'the disambiguated export handle routes to the export picker')+ok(routed[3].value === '0' && routed[4].value === '0', 'other names route to the export picker')++// ------------------------------------------------------------------- js encoder+// The payloads that actually flow: `read` returns the whole document HTML.+const payloads = [+ 'plain',+ '<!doctype html>\n<html>\n <body>hi</body>\n</html>\n', // newline = syntax error before+ '{"t":"a \\u003cscript\\u003e b"}', // save.ts escapes < this way+ 'quote " and backslash \\ together',+ 'line \u2028 and paragraph \u2029 separator',+ 'tab\tand\rreturn and \0 nul',+ 'emoji 🍱 and 日本語',+]+const encoded = run(payloads.map((p) => ['js', p]))+payloads.forEach((p, i) => {+ const lit = encoded[i].value+ let round+ try { round = JSON.parse(lit) } catch { round = Symbol('unparseable') }+ ok(round === p, `round-trips ${JSON.stringify(p).slice(0, 46)}…`)+ ok(!/[\n\r\u2028\u2029]/.test(lit),+ `emits no raw line terminator for ${JSON.stringify(p).slice(0, 46)}…`)+})+// The literal must be safe to paste into the reply call, which is what the old+// hand-escaping got wrong.+const call = `window.__bentoNativeReply(1, true, ${encoded[1].value})`+ok(!/\n/.test(call), 'the assembled reply call is a single line')++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/server/guestbook-daemon/README.md b/server/guestbook-daemon/README.mdindex c5fe41e5..180a99d4 100644--- a/server/guestbook-daemon/README.md+++ b/server/guestbook-daemon/README.md@@ -2,7 +2,8 @@The sustainable home of the public guestbook (see `working/guestbook-design.md`):a Cloudflare Worker that serves the current epoch from Workers KV, archives the live-room daily (read-only CRDT replay), and rolls epochs with fresh credentials.+room on a cron (read-only CRDT replay), and rolls epochs with fresh credentials.+Deployed cadence today is every 30 minutes for both — see *Deployed cadence* below.## One-time setup@@ -32,13 +33,32 @@ curl -X POST -H "Authorization: Bearer $ADMIN_KEY" https://bento.page/guestbook-```- **snapshot** — join the room read-only, archive real content to KV- `archives/` (pruned to the newest 90). Runs daily at 01:00 UTC via cron regardless.+ `archives/` (pruned to the newest 90). The cron fires it on every run.- **roll** — snapshot, then mint epoch N+1 with fresh room+key and a freshshell fetched from the live release. Old room orphans instantly.Automatic cadence: set `ROLL_HOURS` in wrangler.toml (0 = manual).- **kill** — serve a redirect to /404.html instead of the file. Un-kill byseeding or rolling.+## Deployed cadence++**Not the daily one this file used to describe.** The launch-phase settings in+wrangler.toml are `crons = ["*/30 * * * *"]` and `ROLL_HOURS = "0.5"`: snapshot+*and* roll every 30 minutes, so the room time-shards under load and spam clears+itself. Rolls happen at CRON GRANULARITY — the scheduled handler rolls on the+first tick where `now - lastRoll >= ROLL_HOURS` (worker.js `scheduled`), so a+value *larger* than the cron interval works fine and just rounds up to a tick;+what buys nothing is a value BELOW the interval (0.25 with a 30-min cron still+rolls every 30 min). Consequence while this is on: every roll mints a new epoch+with new owner credentials, which ORPHANS the locally held owner deck in+`working/guestbook-live/` — so People→Remove moderation is unavailable until+the cadence goes back to `ROLL_HOURS = "0"` and a v2 owner-moderated epoch is+re-armed locally (`scripts/build-guestbook.mjs` + seed).++wrangler.toml is the single source of truth for the cadence; CLAUDE.md and+`scripts/build-guestbook.mjs` point here rather than restating it, because for a+while they said "manual rolls" and the deployed worker did not.+## Notes- The CRDT engine is bundled from `slides/src/sync/crdt.ts`; the deck@@ -46,8 +66,12 @@ curl -X POST -H "Authorization: Bearer $ADMIN_KEY" https://bento.page/guestbook-Epoch fonts carry forward from the previous epoch's embedded assets.- The daemon holds the room key — as does everyone with the file. Theguestbook's key is public by design; this is no privacy regression.-- The static copy in the bento-site repo remains as a fallback for when KV- is empty and as the pre-proxy path. After the route is live, the daemon's- KV copy is authoritative.+- `ORIGIN_FALLBACK` (the "static copy in the bento-site repo" this file used to+ promise) is DEAD as a fallback. The mirror dropped `guestbook.bento.html` in+ v1.0.12 and publish-site.mjs keeps it out of ordinary publishes, and the+ mirror's `CNAME bento.page` makes Pages 301 the fallback URL straight back to+ `bento.page/guestbook.bento.html` — this worker's own route. An empty KV is+ therefore an outage, not a degraded mode: re-seed. Details in wrangler.toml+ beside the var.- Local dev: `npx wrangler dev --port 8788` (+ `.dev.vars` with ADMIN_KEY).Never pipe wrangler dev output through `head` (SIGPIPE kills it).diff --git a/server/guestbook-daemon/src/worker.js b/server/guestbook-daemon/src/worker.jsindex 1e4cb81e..1fdbdfda 100644--- a/server/guestbook-daemon/src/worker.js+++ b/server/guestbook-daemon/src/worker.js@@ -198,7 +198,14 @@ export default {},})}- // KV empty: fall through to the static copy on GitHub Pages+ // KV empty. This was "fall through to the static copy on GitHub Pages",+ // and there is no longer a copy to fall through to: the mirror dropped+ // guestbook.bento.html in v1.0.12 and publish-site.mjs keeps it out, and+ // the mirror's `CNAME bento.page` makes Pages 301 this URL straight back+ // to bento.page/guestbook.bento.html — the route we are answering. So an+ // empty KV is an OUTAGE, not a degraded mode: re-seed (README "Arming /+ // operating"). Left in place because the daemon is live and this deploy+ // cannot be tested from a dev machine; see wrangler.toml beside the var.return fetch(env.ORIGIN_FALLBACK + '/guestbook.bento.html')}diff --git a/server/guestbook-daemon/wrangler.toml b/server/guestbook-daemon/wrangler.tomlindex e8eeece7..2c341510 100644--- a/server/guestbook-daemon/wrangler.toml+++ b/server/guestbook-daemon/wrangler.toml@@ -23,7 +23,22 @@ id = "ac9eeb2800ea4e848ccf303e31d6620f"[vars]# where a fresh shell is fetched from at roll time (never bundled)SHELL_URL = "https://bento.page/releases/slides/Bento_Slides.bento.html"-# fallback origin if R2 has no current file (GitHub Pages direct)+# Fallback origin when KV holds no current epoch (GitHub Pages direct).+#+# THIS FALLBACK NO LONGER RESOLVES TO A FILE, and the deploy cannot be tested,+# so it is documented rather than changed. Two things happened to it:+# · guestbook.bento.html was DELETED from the public mirror in release+# v1.0.12, and publish-site.mjs now deliberately excludes it from the+# mirror whenever the build has no local epoch — so it will not come back+# on an ordinary publish.+# · the mirror repo carries CNAME bento.page, so Pages 301s every+# nyblnet.github.io/bento-site/* request to bento.page/* (measured:+# .../bento-site/guestbook.bento.html → 301 → bento.page/guestbook.bento.html).+# That redirect target is THIS worker's own route, so the KV-empty path points+# back at the request it is meant to rescue. Whatever the platform does with a+# same-route subrequest, it cannot answer with a guestbook.+# Operationally: an empty KV is an OUTAGE, not a degraded mode — re-seed+# (README "Arming / operating"), do not wait for the fallback.ORIGIN_FALLBACK = "https://nyblnet.github.io/bento-site"# relay host baked into newly minted epochsSYNC_HOST = "wss://sync.bento.page"diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.tsindex 38835226..8eb13930 100644--- a/slides/src/editor/canvas.ts+++ b/slides/src/editor/canvas.ts@@ -1047,7 +1047,15 @@ export class SlideCanvas {// even when the text did NOT change, and only a re-render can do that.this.editingShowedRaw = falseif (model?.type === 'text' && typeof model.html === 'string' && /\{\{|\$/.test(model.html)) {- inner.innerHTML = model.html+ // SANITIZED, even though the point of the swap is to show what the model+ // holds. This is the only place raw model html reaches the live canvas —+ // the render path has always cleaned it — so without this, double-+ // clicking a text box in a deck someone sent you ran its script, and the+ // `{{`-or-`$` gate is no barrier at all: one literal dollar sign opens it.+ // Nothing is lost: the sanitizer unwraps tags and strips attributes, so a+ // {{page:2}} token and `$E=mc^2$` TeX source are plain text to it and+ // survive verbatim, which is the entire purpose of showing the raw html.+ inner.innerHTML = sanitizeHtml(model.html)this.editingShowedRaw = true}this.editing = nodediff --git a/slides/src/editor/clipboard.ts b/slides/src/editor/clipboard.tsindex 414c9e54..e477eb91 100644--- a/slides/src/editor/clipboard.ts+++ b/slides/src/editor/clipboard.ts@@ -8,10 +8,16 @@// fonts) travel inside the payload, so pasting into another deck brings the// pixels and typefaces along; asset-key collisions with different content are// remapped so nothing clobbers the target deck.+//+// Reading that channel is the untrusted direction — the clipboard is public,+// and a payload on it need not have come from a Bento deck. parseClip rebuilds+// what it finds through untrusted.ts before anything reaches the document, so+// that a fragment the format cannot express never becomes part of one.import type { BentoDoc, Slide, SlideElement, TextElement } from '../model'import { uid } from '../model'import { firstFamily } from '../fonts'+import { LIMITS, sanitizeAssets, sanitizeElement, sanitizeFonts, sanitizeSlide } from '../untrusted'export interface ClipPayload {__bento: 'clip'@@ -73,9 +79,54 @@ export function serializeSlides(slides: Slide[], doc: BentoDoc): string {return JSON.stringify(payload)}+/**+ * Read a clip payload off the system clipboard — the ONE place foreign+ * document fragments enter the deck, and so the place they are checked.+ *+ * Nothing about clipboard text says a Bento deck wrote it: any page with a+ * Copy button can leave a `__bento:"clip"` payload there, and this used to+ * hand whatever it contained to insertElements/insertSlides unread. So the+ * payload is REBUILT through untrusted.ts — known kind, known element types,+ * known keys, values of the right shape — and anything that does not conform+ * is dropped rather than repaired.+ *+ * This is the model-shape layer, not the escaping layer: render.ts escapes and+ * validates what it writes into markup on its own (it has to — a deck opened+ * from disk never passes through here). What this adds is that the DOCUMENT+ * never holds the value in the first place, which is the part every future+ * renderer inherits for free.+ *+ * A payload with nothing left after the rebuild returns null, so the paste+ * handler falls through to its plain-text branch: the JSON lands as a visible+ * text element instead of silently doing nothing. That fallback is a poor fit+ * for the SIZE ceiling — an over-budget but perfectly legitimate slide copy+ * deserves "that paste is too large", not 4000 characters of raw JSON — so the+ * ceiling is set where real payloads cannot reach it (LIMITS.clipText).+ */export function parseClip(text: string): ClipPayload | null {- if (!text || text.length > 40_000_000) return null- try { const p = JSON.parse(text); return p && p.__bento === 'clip' ? p as ClipPayload : null } catch { return null }+ if (!text || text.length > LIMITS.clipText) return null+ let raw: unknown+ try { raw = JSON.parse(text) } catch { return null }+ if (!raw || typeof raw !== 'object') return null+ const p = raw as Record<string, unknown>+ if (p.__bento !== 'clip') return null+ if (p.kind !== 'elements' && p.kind !== 'slides') return null++ const payload: ClipPayload = {+ __bento: 'clip', kind: p.kind,+ assets: sanitizeAssets(p.assets),+ fonts: sanitizeFonts(p.fonts),+ }+ if (p.kind === 'elements') {+ if (!Array.isArray(p.elements) || p.elements.length > LIMITS.elements) return null+ payload.elements = p.elements.map(sanitizeElement).filter((el): el is SlideElement => el !== null)+ if (!payload.elements.length) return null+ } else {+ if (!Array.isArray(p.slides) || p.slides.length > LIMITS.slides) return null+ payload.slides = p.slides.map(sanitizeSlide).filter((s): s is Slide => s !== null)+ if (!payload.slides.length) return null+ }+ return payload}/** Merge payload assets into doc; on same-key-different-value, remap to a fresh key. */diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 234340ee..8a5792f7 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -8,16 +8,19 @@ import {FORMAT_VERSION,MEDIA_EMBED_BUDGET,applyChartPalette, applyLayout, builtinLayouts, defaultChart, defaultImage, defaultMedia, defaultShape, defaultTable, defaultText,- instantiateLayout, isLightBg, layoutElementIds, newDocId, paginates, inLinearFlow, parseDoc, readableInk, syncLinkedChart, uid,- type ChartElement, type ShapeKind, type Slide, type SlideElement, type TableElement,-} from '../model'+ instantiateLayout, isLightBg, layoutElementIds, newDocId, parseDoc, readableInk, syncLinkedChart, uid,+ paginates, inLinearFlow,+ type ChartElement, type ShapeKind, type Slide, type SlideElement, type TableElement } from '../model'import { APP_VERSION, applyUpdate, applyUpdateInPlace, autoCheckEnabled, canUpdateInPlace, checkForUpdates, compareVersions, offlineEnabled, setAutoCheck, setOffline } from '../update'import { CHART_PRESETS } from '../charts'import { renderSlide, renderThumbnail } from '../render'import { SlideCanvas } from './canvas'import { PropsPanel } from './panels'import { startPresentation } from '../present'-import { adoptFileHandle, canWriteInPlace, currentFileName, fileBase, hasFileHandle, isEncryptionActive, openedFileName, saveFile, serializeAuto, serializeFile, setEncryptionPassword, writeUpdatedFile, writeUpdatedFileAs } from '../save'+// serializeFile (plain output) is deliberately NOT imported here: every path+// in this file writes a real file for a person, so all of them must inherit an+// active password. serializeAuto is the only encryption-aware serializer.+import { adoptFileHandle, canWriteInPlace, currentFileName, fileBase, hasFileHandle, isEncryptionActive, openedFileName, saveFile, serializeAuto, setEncryptionPassword, writeUpdatedFile, writeUpdatedFileAs } from '../save'import { addVersion, clearRecovery, clearVersions, docContentKey, getRecovery, listVersions, pruneOld, putRecovery, type Snapshot } from '../autosave'import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from './clipboard'import { openSpeakerWindow, speakerIdleBody } from '../screens'@@ -733,7 +736,7 @@ export class Editor {t('Restore an earlier auto-saved version of this deck (kept locally in this browser).'),() => void this.openVersionHistory())item(ICONS.code, t('Copy document JSON'),- t('Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.'),+ t('Copies this deck as plain JSON — content only, no live-session keys. Edit it in another tool, then bring it back with Replace from JSON.'),() => void this.copyDocJson())item(ICONS.code, t('Replace from JSON…'),t('Paste edited document JSON to replace this deck’s content — ⌘Z undoes.'),@@ -801,7 +804,7 @@ export class Editor {private async savePresentationPackage() {const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDocclone.readonly = true- delete clone.collab // a sealed package must not join (or leak) the live room+ stripCollabSecrets(clone) // a sealed package must not join (or leak) the live roomtry {const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'presentonly' })if (ok) this.toast(t('Presentation package saved — it opens straight into the show'))@@ -822,9 +825,7 @@ export class Editor {}const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDocclone.collab = { ...c, role: 'reader', on: true, sync: undefined }- delete clone.collab.writerPriv // the muzzle — no write capability travels- delete clone.collab.ownerPriv // v2: neither the owner key…- delete clone.collab.invite // …nor any invite (delegation) material+ stripCollabSecrets(clone, { keepRoom: true })try {const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'viewonly' })if (ok) this.toast(t('Read-only copy saved — it follows the live session, view only'))@@ -848,8 +849,12 @@ export class Editor {this.canvas.commitTextEdit()this.session?.stampInto(this.store.doc) // copies rejoin as true forksconst clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc+ // Strip FIRST, then delegate: the invite is the only private material an+ // editor copy is allowed to carry. A v2 room is verified through the+ // owner→invite→member chain, so a stray `writerPriv` (room-wide write key+ // from a pre-v2 mint) would be a second, UNREVOKABLE way in.+ stripCollabSecrets(clone, { keepRoom: true })clone.collab!.invite = await mintInvite(c.ownerPriv, 'writer')- delete clone.collab!.ownerPrivclone.collab!.on = truetry {const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'invite' })@@ -859,9 +864,19 @@ export class Editor {}}+ /**+ * The document as loose data (the AI/tooling round-trip). It leaves WITHOUT+ * the live session: this text is pasted into chats, tickets and scratch+ * files, and `collab` is a bearer capability — the room key decrypts every+ * frame and blob the relay holds, and the private halves grant writing and+ * member revocation on top. Nothing about the round-trip needs a room, and+ * openReplaceJson keeps THIS document's, so dropping the block costs nothing.+ */private async copyDocJson() {+ const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc+ stripCollabSecrets(clone)try {- await navigator.clipboard.writeText(JSON.stringify(this.store.doc))+ await navigator.clipboard.writeText(JSON.stringify(clone))this.toast(t('Document JSON copied'))} catch {this.toast(t('Couldn’t access the clipboard'))@@ -885,8 +900,22 @@ export class Editor {applyB.className = 'ed-btn ed-btn-primary'applyB.textContent = t('Apply')applyB.addEventListener('click', () => {- const ok = (window as unknown as { bento?: { loadDoc?: (j: string) => boolean } }).bento?.loadDoc?.(ta.value)- if (ok) {+ // parseDoc + replaceDoc rather than window.bento.loadDoc (which is the+ // same two calls) because the collab decision has to be made BEFORE the+ // swap: replaceDoc's events reach the sync session synchronously, and it+ // re-attaches to whatever `collab` the new document holds.+ //+ // The live session belongs to THIS document, not to the pasted text. The+ // copy side sends no collab at all, so adopting the pasted one would+ // either wipe the user's room credentials (paste of our own JSON) or+ // silently move the deck into a room that came from somewhere else.+ // Content is imported; identity and capability are not.+ const next = parseDoc(ta.value)+ if (next) {+ const keep = this.store.doc.collab+ if (keep) next.collab = keep+ else delete next.collab+ this.store.replaceDoc(next)this.toast(t('Document replaced — ⌘Z undoes'))overlay.remove()} else {@@ -974,10 +1003,14 @@ export class Editor {private async saveAsTemplate() {const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDocclone.template = true- delete clone.collab // instances mint their own credentials+ stripCollabSecrets(clone) // instances mint their own credentialsdelete (clone as { docId?: string }).docIdtry {- const ok = await writeUpdatedFileAs(serializeFile(clone), clone, { suffix: 'template' })+ // serializeAuto, never serializeFile: a template is the copy people hand+ // around, and a password-protected deck saved as one wrote its body in+ // PLAINTEXT while the preview veto still made the file thumbnail as+ // locked — it looked protected and was readable in any text editor.+ const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'template' })if (ok) this.toast(t('Template saved — every open of it starts a fresh deck'))} catch (err) {console.error(err)@@ -1460,8 +1493,7 @@ export class Editor {// numbering a hidden slide has no number at all, so show the marker// alone; with office-suite numbering it keeps one, struck through — the// same affordance PowerPoint uses. Either way it must be obvious at a- // glance, because a slide you forgot you hid is one you rediscover- // mid-presentation.+ // glance, because a slide you forgot you hid is found mid-presentation.num.textContent = paginates(slide, this.store.doc) ? String(this.linearNumber(i)) : '—'num.title = t('Hidden — skipped while presenting and left out of PDF export')} else {@@ -2988,6 +3020,31 @@ function releaseNotes(notes: string): HTMLElement {return box}+/**+ * Take the live session out of a copy that is about to leave this machine.+ * ONE list, in one place: every field under `collab` is a bearer capability,+ * so a hand-out that forgets one of them grants the recipient write access to+ * the room, the power to revoke its members, or the ability to decrypt every+ * frame and blob the relay has ever stored — and the file looks completely+ * ordinary afterwards. Divergent per-export copies of this list are how one+ * export path ends up leaking what the other three strip.+ *+ * The default is to drop the block outright (sealed packages, templates, the+ * JSON on the clipboard: none of them may join anything). `keepRoom` is for+ * the copies that are MEANT to follow the session — they keep the room, the+ * symmetric read key and the public keys, and lose only the private halves.+ */+function stripCollabSecrets(doc: import('../model').BentoDoc, opts: { keepRoom?: boolean } = {}) {+ if (!doc.collab) return+ if (!opts.keepRoom) {+ delete doc.collab+ return+ }+ delete doc.collab.writerPriv // the muzzle — no write capability travels+ delete doc.collab.ownerPriv // v2: neither the owner key…+ delete doc.collab.invite // …nor any invite (delegation) material+}+/** Deep-clone an element with a fresh id (same-slide duplicates must not share ids). */function cloneElement(el: SlideElement): SlideElement {return { ...JSON.parse(JSON.stringify(el)), id: uid(el.type[0]), x: el.x + 24, y: el.y + 24 }diff --git a/slides/src/preview.ts b/slides/src/preview.tsindex 9314f17e..d1a4d42f 100644--- a/slides/src/preview.ts+++ b/slides/src/preview.ts@@ -279,6 +279,14 @@ function hoistRepeats(root: HTMLElement) {const movable = ({ decls }: { decls: string[] }, i: number) => {const props = decls.map(propOf)const p = props[i]+ // A `<` in a declaration must stay inline. The stylesheet is raw text, so a+ // hoisted `</style>` would close it early and the rest would parse as live+ // markup (kernel previewIsSafe/styleIsInert refuses the whole preview for+ // exactly that). Inline, the same bytes are attribute text and get escaped.+ // Not only hardening: imagesToBackgrounds writes background-image:url("<src>"),+ // and a single-quoted `data:image/svg+xml,<svg xmlns='…'>` image is a legal+ // src containing `<` — hoisting it cost that deck its thumbnail outright.+ if (decls[i].includes('<')) return falseif (props.indexOf(p) !== props.lastIndexOf(p)) return falseconst root_ = p.slice(0, p.indexOf('-') < 0 ? p.length : p.indexOf('-'))if (p !== root_ && SHORTHANDS.has(root_) && props.includes(root_)) return falsediff --git a/slides/src/render.ts b/slides/src/render.tsindex e6b66d00..86cd4c78 100644--- a/slides/src/render.ts+++ b/slides/src/render.ts@@ -417,6 +417,7 @@ const ALLOWED_TAGS = new Set(['B', 'I', 'U', 'BR', 'SPAN', 'DIV', 'P', 'STRONG',/** Keep pasted/edited rich text down to a safe inline subset. */export function sanitizeHtml(html: string): string {+ if (typeof document === 'undefined') return stripAllTags(html)const tpl = document.createElement('template')tpl.innerHTML = htmlconst walk = (node: Node) => {@@ -442,22 +443,426 @@ export function sanitizeHtml(html: string): string {return out.innerHTML}+/** No-DOM fallback (node rigs): drop every tag, keep the words. */+function stripAllTags(html: string): string {+ return String(html).replace(/<[^>]*>/g, '')+}++// --- untrusted svg ----------------------------------------------------------+//+// An `svg` element's markup is opaque author content that goes into the page as+// markup — the one element type whose content is not text we lay out but nodes+// the browser builds. Every deck is untrusted input: mailed, pasted, or+// delivered as a collab op. Script running in this page holds `doc.collab.key`,+// `ownerPriv`/`writerPriv`, the plaintext IndexedDB autosave store and the File+// 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, and scopeCss (hard-won detail+ // #7) is what keeps its rules from leaking into every other svg on the page.+ '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(value.matchAll(/url\(\s*(['"]?)([^'")]*)\1\s*\)/gi))+ .map((m) => m[2].replace(/[\u0000-\u0020]/g, '').toLowerCase())+}++/**+ * `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): boolean {+ return urlTargets(value).every((t) => t.startsWith('#') || t.startsWith('data:image/'))+}++/**+ * 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 `))+ return atFiltered.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'+ })+}++/**+ * Author svg markup → nodes this document can safely hold.+ *+ * AT RENDER, EVERY RENDER — not on the load path. An svg element also arrives+ * from a clipboard paste and from a collab op, and rendering is the one place+ * all three meet. Sanitizing here also keeps the FORMAT additive: nothing is+ * stamped on the model, so a file cleaned by this build is byte-identical to+ * one an older build wrote.+ *+ * Parsed INERT. `div.innerHTML = hostile` looks safe because the div is+ * detached and is not: the elements it creates belong to the live document, so+ * their resources load and `<img src=x onerror=…>` fires from a div that was+ * never inserted (measured for spaces, 2026-08-03 — same reason+ * spaces/src/sanitize.ts parses through DOMParser). `text/html`, not+ * `image/svg+xml`: the XML parser is FATAL on the first unclosed tag, and+ * refusing to draw a slightly sloppy diagram is a worse answer than drawing it.+ * The HTML parser applies the browser's own foreign-content rules, so+ * `foreignObject`, `clipPath`, `viewBox` and `xlink:href` come back correctly+ * cased and namespaced.+ *+ * `id` is deliberately never stripped: svg gradients and markers resolve+ * through document-global `url(#…)`, so an id sweep blanks the artwork.+ */+export function sanitizeSvg(markup: string): DocumentFragment {+ const out = document.createDocumentFragment()+ if (!markup) return out+ const 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 === '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.+ el.textContent = sanitizeSvgCss(el.textContent ?? '')+ continue+ }+ walk(el)+ }+ }+ walk(parsed.body)+ // 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))+ return out+}+const VALIGN: Record<string, string> = { top: 'flex-start', middle: 'center', bottom: 'flex-end' }+/** The three alignments the format defines. Anything else is data, not a value. */+const ALIGN: Record<string, string> = { left: 'left', center: 'center', right: 'right' }++/**+ * A colour string safe to paste into a `style` attribute, or the fallback.+ *+ * A table's colours are ordinary untrusted input — the rows of a mailed deck, a+ * paste, a collab op — so the model's `string` says nothing about the value, and+ * escaping for markup does not cover where it lands. Inside `style="…"` the+ * dangerous characters are `"` (which ends the attribute and lets the next word+ * be an event handler) and `;`/`}` (which start a new declaration); `<` means+ * nothing there. A cell whose `bg` read `x" onmouseover="…` used to mint a real+ * handler on the canvas, in present, in print AND in every thumbnail.+ *+ * So: an allowlist of the characters colour notations actually use, no `url(`,+ * and a length cap. Anything else falls back rather than being "cleaned" — a+ * colour we do not recognise is not worth guessing at. Same rule and same+ * reasons as dash's preview (`dash/src/preview.ts` cssColor); `url` is matched+ * as `url(` rather than as a word because `burlywood` is a colour.+ *+ * Exported for `scripts/test-sanitize.ts`.+ */+export function cssColor(v: unknown, fallback: string): string {+ if (typeof v !== 'string') return fallback+ const s = v.trim()+ if (!s || s.length > 48) return fallback+ if (!/^[#a-zA-Z0-9(),.%\s/-]+$/.test(s)) return fallback+ if (/url\s*\(|expression|@|\\/i.test(s)) return fallback+ return s+}++/** A model number as a CSS length: finite and in range, or the fallback. */+export function cssNum(v: unknown, fallback: number, max = 4096): number {+ const n = Number(v)+ return Number.isFinite(n) ? Math.min(Math.max(n, 0), max) : fallback+}++/**+ * An author font stack, reduced to what a stylesheet can hold. Rejected by+ * CHARACTER rather than by allowlist, unlike cssColor: font names are ordinary+ * words in any script (`ヒラギノ角ゴ` is a font family), so the test is for the+ * few characters that end a declaration or start a fetch.+ */+function cssFont(v: unknown, fallback: string): string {+ if (typeof v !== 'string') return fallback+ const s = v.trim()+ if (!s || s.length > 160) return fallback+ return /[;{}<>()\\]/.test(s) ? fallback : s+}+/*** Render a table element as a real HTML <table> string (table-layout: fixed).* Column widths are fractional weights normalised to %. Cells carry data-r /* data-c so the editor can target them for in-cell editing.+ *+ * Every author value is escaped for the attribute AND validated for the CSS it+ * lands in (cssColor/cssNum/cssFont/ALIGN) — see cssColor for what that stops.+ * Markup as a string, not DOM built and serialized, is kept deliberately: it is+ * what makes this whole function testable in node with no DOM at all, which is+ * what `scripts/test-sanitize.ts` exercises.*/export function renderTableHtml(el: TableElement, doc: BentoDoc): string {- const st = el.style- const esc = (s: string) => s.replace(/"/g, '"')- const totalW = el.columns.reduce((s, c) => s + (c.w || 0), 0) || 1+ const st = el.style ?? ({} as TableElement['style'])+ const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"')+ const totalW = el.columns.reduce((s, c) => s + cssNum(c.w, 0), 0) || 1const cols = el.columns- .map((c) => `<col style="width:${(((c.w || 0) / totalW) * 100).toFixed(4)}%">`)+ .map((c) => `<col style="width:${((cssNum(c.w, 0) / totalW) * 100).toFixed(4)}%">`).join('')- const font = esc(st.fontFamily || doc.theme.fontFamily)- const border = st.borderWidth ? `border:${st.borderWidth}px solid ${st.borderColor};` : ''+ const font = esc(cssFont(st.fontFamily || doc.theme.fontFamily, 'inherit'))+ const bw = cssNum(st.borderWidth, 0, 64)+ const border = bw ? `border:${bw}px solid ${cssColor(st.borderColor, 'transparent')};` : ''+ const padY = cssNum(st.cellPadY, 0, 512)+ const padX = cssNum(st.cellPadX, 0, 512)const rowsHtml = el.rows.map((row, r) => {const isHeader = el.header && r === 0@@ -465,30 +870,31 @@ export function renderTableHtml(el: TableElement, doc: BentoDoc): string {const stripe = !isHeader && st.zebra && bodyIndex % 2 === 1 ? st.zebra : ''const cells = row.cells.map((cell, c) => {- const align = cell.align || 'left'- const bg = cell.bg || (isHeader ? st.headerBg : stripe || 'transparent')- const color = cell.color || (isHeader ? st.headerColor : st.color)+ const align = ALIGN[cell.align as string] ?? 'left'+ const bg = cssColor(cell.bg || (isHeader ? st.headerBg : stripe || 'transparent'), 'transparent')+ const color = cssColor(cell.color || (isHeader ? st.headerColor : st.color), 'inherit')const weight = cell.bold || isHeader ? 700 : 400return (- `<td data-r="${r}" data-c="${c}" style="${border}padding:${st.cellPadY}px ${st.cellPadX}px;` ++ `<td data-r="${r}" data-c="${c}" style="${border}padding:${padY}px ${padX}px;` +`text-align:${align};vertical-align:middle;color:${color};background:${bg};` +`font-weight:${weight};overflow:hidden;word-break:break-word;">` +// dir="auto" per cell for the same reason text elements carry it:// a table of Arabic terms is otherwise laid out as if it were// English. Per cell, so a bilingual table stays correct in both// columns.- `<div class="bento-cell-inner" dir="auto">${sanitizeHtml(cell.html || '') || '<br>'}</div></td>`+ `<div class="bento-cell-inner" dir="auto">${sanitizeHtml(String(cell.html ?? '')) || '<br>'}</div></td>`)}).join('')return `<tr data-r="${r}">${cells}</tr>`}).join('')- const radius = st.radius ? `border-radius:${st.radius}px;overflow:hidden;` : ''+ const rad = cssNum(st.radius, 0, 512)+ const radius = rad ? `border-radius:${rad}px;overflow:hidden;` : ''return (`<div class="bento-table-wrap" style="width:100%;height:100%;${radius}">` +`<table class="bento-table" style="width:100%;height:100%;border-collapse:collapse;` +- `table-layout:fixed;font-family:${font};font-size:${st.fontSize}px;line-height:1.3;">` ++ `table-layout:fixed;font-family:${font};font-size:${cssNum(st.fontSize, 16, 512)}px;line-height:1.3;">` +`<colgroup>${cols}</colgroup>${rowsHtml}</table></div>`)}@@ -662,7 +1068,11 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptsnode.appendChild(img)break}- node.innerHTML = markup+ // NOT innerHTML: this markup is author content, and assigning it ran+ // whatever the deck carried in a <script> or an onload — see sanitizeSvg.+ // The <img> branch above is inert already (an image is script-disabled),+ // which is why only this path changes.+ node.appendChild(sanitizeSvg(markup))const svg = node.querySelector('svg')if (svg) {svg.style.width = '100%'@@ -670,7 +1080,10 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOptssvg.style.display = 'block'if (el.css) {const style = document.createElementNS(SVG_NS, 'style')- style.textContent = scopeCss(el.css, `[data-el-id="${CSS.escape(el.id)}"]`)+ // Same sheet, same policy: this lands in the very `<style>` element+ // sanitizeSvg cleans, so leaving `css` unfiltered would have left an+ // @import sitting beside the one that was just removed.+ style.textContent = scopeCss(sanitizeSvgCss(el.css), `[data-el-id="${CSS.escape(el.id)}"]`)svg.prepend(style)}}diff --git a/slides/src/sync/blobs.ts b/slides/src/sync/blobs.tsindex d90998d4..65a6e17d 100644--- a/slides/src/sync/blobs.ts+++ b/slides/src/sync/blobs.ts@@ -264,17 +264,43 @@ export async function putBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, bytes: Ui}}+/** Does `plain` actually hash to the address we asked for? One SHA-256 plus+ * one HMAC over bytes we have just decrypted anyway — negligible beside the+ * AES-GCM pass that produced them, and it runs once per fetch, not per use+ * (the cache is keyed by the same address). */+async function addressMatches(rawRoomKey: Uint8Array, key: string, plain: Uint8Array): Promise<boolean> {+ return (await blobKey(rawRoomKey, plain)) === key+}+/** Fetch and decrypt, cache-first. Null means "not available right now" —- * callers render a placeholder rather than a broken image, and may retry. */+ * callers render a placeholder rather than a broken image, and may retry.+ * A blob that fails its content-address check reads as unavailable too: a+ * placeholder is recoverable, the wrong picture is not. */export async function getBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, key: string): Promise<Uint8Array | null> {const hit = await cacheGet(key)- if (hit) return hittry {+ // The hit is checked as well, so a cache written before this verification+ // existed (or edited under us in IndexedDB) heals: falling through re-fetches+ // and cachePut, keyed by the address, overwrites the bad entry.+ // INSIDE the try like the post-fetch check below: addressMatches can throw+ // (measured — crypto.subtle.importKey('raw', new Uint8Array(0), HMAC) rejects+ // with DataError on an empty room key), and the contract above promises null,+ // not a rejection. session.resolveBlobs has try/finally and no catch, so a+ // throw here escapes as an unhandled rejection.+ if (hit && await addressMatches(rawRoomKey, key, hit)) return hitconst res = await fetch(url(e, key))if (!res.ok) return nullconst enc = new Uint8Array(await res.arrayBuffer())const plain = await decodeBlob(rawRoomKey, enc)- if (plain) void cachePut(key, plain)+ if (!plain) return null+ // GCM proves someone holding the room key sealed these bytes. It does NOT+ // prove they are the bytes this address names, and nothing else here did:+ // the relay is free to answer address A with the room's blob B, and every+ // check above passes. The picture silently becomes a different picture and+ // cachePut writes the swap to disk permanently. The address is the only+ // binding between reference and content, so verify it before both.+ if (!await addressMatches(rawRoomKey, key, plain)) return null+ void cachePut(key, plain)return plain} catch {return nulldiff --git a/slides/src/untrusted.ts b/slides/src/untrusted.tsnew file mode 100644index 00000000..543cbae4--- /dev/null+++ b/slides/src/untrusted.ts@@ -0,0 +1,527 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Shape validation for document fragments that arrive from OUTSIDE the deck.+//+// WHY THIS EXISTS. The system clipboard is not a trusted channel: any web page+// with a Copy button can put a Bento clip payload on it, and one ⌘V into an+// open editor used to splice whatever it carried straight into the document.+// That is worse than junk data, because model values are interpolated into+// markup and CSS all over the renderer.+//+// This is the SECOND layer, not the only one. render.ts now escapes and+// validates every value renderTableHtml writes into a `style` attribute+// (cssColor/cssNum/cssFont — see scripts/test-sanitize.ts), so the specific+// `red" onmouseover="…` cell colour no longer mints a handler. But that gate+// covers one function and one field family: `fit` still lands raw in an+// <img>'s cssText, a font's `weight` raw in an @font-face rule (fonts.ts),+// and every renderer written after this one inherits whatever the model was+// allowed to hold. A value that cannot BE in the document cannot be+// mis-rendered by code nobody has written yet, so the model itself is held to+// a shape here — and where the two layers judge the same kind of value, they+// judge it by the same rule (see `color` below).+//+// So a foreign fragment is REBUILT here, key by key, against the format's own+// key table (modelkeys.generated.ts — derived from model.ts and pinned by CI,+// so it cannot drift the way a hand-written list would). An unknown element+// type, an unknown key, an enum that is not one of the literals, a string+// where a number belongs: DROPPED, never repaired. Repairing an attacker's+// value keeps it in the document with our blessing; dropping it costs a paste+// one property, which renders as a plain element. The single exception is+// numeric coercion ("12" → 12), which cannot smuggle anything.+//+// Dropping a property is not always enough, though: an element the format+// requires a key for is not a plain element without it, it is one the renderer+// throws on. Those keys are named in REQUIRED_ELEMENT_KEYS and take the whole+// element with them; nested objects do the same through `shape`'s `required`.+//+// Deliberately DOM-free and with no idea what a clipboard is: the other+// untrusted intake — remote CRDT ops off the relay — can adopt the same+// checks, key by key, through `checkElementProp`.++import type { Slide, SlideElement } from './model'+import { MODEL_KEYS } from './modelkeys.generated'++/** Reject. JSON has no `undefined`, so it can never collide with a real value. */+const DROP = undefined+type Check = (v: unknown) => unknown++/**+ * Assigning `out['__proto__'] = x` on a plain object walks the setter and+ * changes the prototype — so this key is skipped everywhere a foreign object+ * is copied, including inside a chart option's free-form JSON.+ */+const PROTO = '__proto__'++/**+ * Ceilings. None of these is a security boundary on its own; they exist so a+ * payload that passes every shape check still cannot be a denial of service —+ * an editor that hangs on ⌘V is as lost as one that runs a script.+ */+export const LIMITS = {+ /** ids, group tags, asset keys, a slide's `background` shorthand */+ scalar: 200,+ /** one colour notation. The longest in a real deck (OneMarket, 21 slides,+ * ~1400 colour-typed values) is 45: `color(srgb 0.156863 0.188235 … / 0.55)`.+ * render.ts:cssColor caps at 48 — it FALLS BACK past that, this DROPS, so a+ * little more headroom here costs a degraded colour rather than a lost one. */+ color: 64,+ /** a CSS font stack names several families */+ fontStack: 300,+ /** placeholder prompts and comment prose */+ prose: 4_000,+ /** rich text of one text element or table cell */+ html: 64 * 1024,+ /** raw <svg> markup of one svg element (a detailed map runs to ~1MB) */+ markup: 4 * 1024 * 1024,+ /** css injected inside one svg element */+ css: 128 * 1024,+ /** one asset: a data: URI (image, font, embedded clip) or raw svg markup */+ asset: 32 * 1024 * 1024,+ assets: 2_000,+ /** the whole clipboard string, before it is even parsed. Sized off what a+ * legitimate copy can reach, not off a round number: one embedded clip is+ * MEDIA_EMBED_BUDGET (8MB) → ~10.7MB of base64, so five media slides is+ * ~54MB. Costs nothing at that size — JSON.parse of a 64MB payload measured+ * 21ms (node 24, M-series, 2026-08-09) — and the 40MB it replaces turned an+ * oversized-but-real slide copy into 4000 characters of raw JSON pasted as+ * a text element (editor.ts's plain-text fallback). */+ clipText: 64 * 1024 * 1024,+ elements: 5_000,+ slides: 500,+ rows: 2_000,+ cols: 200,+ comments: 500,+ stops: 64,+ speeds: 2_000,+ /** a chart option is free-form JSON — bounded, not typed */+ optionNodes: 20_000,+ optionDepth: 12,+}++/**+ * Characters that end a CSS value or an HTML attribute early. A colour, a+ * blend mode or a font weight never needs one; a payload that carries one is+ * aiming at the unescaped interpolations in render.ts / fonts.ts.+ */+const CSS_BREAKOUT = /["'<>{};]/+/** Path data is numbers and command letters. Nothing else is a path. */+const PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9\s,.+\-eE]*$/+/** A scheme we know how to serve; anything else (javascript:, …) is dropped. */+const SAFE_SCHEME = /^(?:data|asset|blob|https?):/i+const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i++const isPlainObject = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v)++/** Finite number, or a numeric string coerced to one. Out of range = DROP. */+const num = (min: number, max: number): Check => (v) => {+ const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v+ return typeof n === 'number' && Number.isFinite(n) && n >= min && n <= max ? n : DROP+}+const bool: Check = (v) => (typeof v === 'boolean' ? v : DROP)+const oneOf = (...allowed: string[]): Check => (v) =>+ typeof v === 'string' && allowed.includes(v) ? v : DROP+/** Free text that reaches the DOM as text, never as markup. */+const str = (max: number): Check => (v) => (typeof v === 'string' && v.length <= max ? v : DROP)+/** A value that ends up inside a CSS declaration or an HTML attribute. */+const cssValue = (max = LIMITS.scalar): Check => (v) =>+ typeof v === 'string' && v.length <= max && !CSS_BREAKOUT.test(v) ? v : DROP+/**+ * A COLOUR, judged by exactly the rule render.ts:cssColor applies when it+ * writes one into markup — same allowlist, same `url(`/`expression`/`@`/`\`+ * rejection. Kept in step deliberately: CSS_BREAKOUT alone permits `(`, `)`+ * and `:`, which is strictly weaker, and the weaker of two layers is the one+ * that decides. Measured on the pre-change validator: a shadow colour of+ * `red) url(https://evil/f.svg#f` passed here and reached `style.filter`+ * through render.ts:applyElementFrame, which interpolates it raw — a paste+ * that fetches a remote file. Colours are the one model field that reaches+ * CSS in a dozen places, so they get one rule rather than a per-site one.+ */+const COLOR_CHARS = /^[#a-zA-Z0-9(),.%\s/-]+$/+const COLOR_TRICKS = /url\s*\(|expression|@|\\/i+const color = (max = LIMITS.color): Check => (v) => {+ if (typeof v !== 'string') return DROP+ const s = v.trim()+ return s && s.length <= max && COLOR_CHARS.test(s) && !COLOR_TRICKS.test(s) ? v : DROP+}+/**+ * An svg PAINT (`fill` / `stroke`): a colour, or a reference to a gradient or+ * filter defined inside this document's own markup. The quoted form is what+ * real files carry — OneMarket_Commercial_Architecture slide 21, element+ * `topo-0`, paints `fill: url("#core-glow")`, and the pre-change validator+ * dropped it (CSS_BREAKOUT rejects `"`), leaving render.ts:shapeSvg to write+ * `fill="undefined"` and paint the shape BLACK. Only a bare fragment id is+ * allowed: `url(https://evil/track.svg#g)` is a network fetch the paste never+ * asked for, and it is a colour rule that would otherwise wave it through.+ */+const LOCAL_PAINT_REF = /^url\(\s*(?:"#[\w.:-]+"|'#[\w.:-]+'|#[\w.:-]+)\s*\)$/+const paint: Check = (v) =>+ typeof v === 'string' && v.length <= LIMITS.color && LOCAL_PAINT_REF.test(v.trim()) ? v : color()(v)+/**+ * A font stack, which legitimately quotes multi-word families ('Segoe UI').+ * Quotes are therefore allowed here — renderTableHtml escapes them, and+ * injectFonts passes the family through JSON.stringify — but a brace or a+ * semicolon still ends a declaration, so those are not.+ */+const fontStack: Check = (v) =>+ typeof v === 'string' && v.length <= LIMITS.fontStack && !/[<>{};]/.test(v) ? v : DROP+const pathData: Check = (v) =>+ typeof v === 'string' && v.length <= LIMITS.html && PATH_DATA.test(v) ? v : DROP+/**+ * src / poster: a data: URI, an asset: key, a URL, or a relative path.+ *+ * A schemed value is NOT held to CSS_BREAKOUT — a data: URI legitimately+ * carries quotes and semicolons, so demanding they be absent would reject the+ * embedded-image case this field exists for. That means `https://evil/a">…`+ * survives, and it is safe only because of a property of the CONSUMERS: every+ * one of them assigns it as a DOM property (`img.src`, `video.src`,+ * resolveAsset → the same), where the string is a value and never re-parsed as+ * markup. A renderer that string-builds `<img src="${el.src}">` would turn+ * this into an attribute breakout, so it must escape or re-check — noted here+ * because the safety lives at the call site, not in this value.+ */+const mediaRef: Check = (v) => {+ if (typeof v !== 'string' || v.length > LIMITS.asset) return DROP+ if (HAS_SCHEME.test(v)) return SAFE_SCHEME.test(v) ? v : DROP+ return CSS_BREAKOUT.test(v) ? DROP : v // a bare path still lands in an attribute+}++/**+ * Rebuild an object from a key table, dropping every key and value it fails.+ *+ * `required` names the keys the format does not make optional. Without it a+ * nested object whose every key failed came back as `{}` — a shadow with no+ * blur, a gradient with no stops — and the renderer then interpolated+ * `undefined` into a CSS declaration or called `.map` on nothing. Measured:+ * `colorGradient:{angle:90}` survived the pre-change validator and+ * render.ts:cssLinearGradient threw "Cannot read properties of undefined+ * (reading 'map')". A half-object is not a repairable object.+ */+function shape(+ keys: readonly string[], checks: Record<string, Check>, required: readonly string[] = [],+): Check {+ return (v) => {+ if (!isPlainObject(v)) return DROP+ const out: Record<string, unknown> = {}+ for (const key of Object.keys(v)) {+ if (key === PROTO || !keys.includes(key)) continue+ const val = checks[key]?.(v[key])+ if (val !== DROP) out[key] = val+ }+ return required.every((key) => out[key] !== DROP) ? out : DROP+ }+}++/**+ * A homogeneous array. One bad entry drops the WHOLE array, because these+ * arrays are positional — a table's cells line up with its columns, a chart's+ * data with its labels — and silently closing a hole would misalign the rest.+ */+const list = (max: number, item: Check): Check => (v) => {+ if (!Array.isArray(v) || v.length > max) return DROP+ const out: unknown[] = []+ for (const entry of v) {+ const val = item(entry)+ if (val === DROP) return DROP+ out.push(val)+ }+ return out+}++const gradient = shape(MODEL_KEYS.gradient, {+ angle: num(-3600, 3600),+ stops: list(LIMITS.stops, shape(+ ['at', 'color'], { at: num(0, 1), color: color() }, ['at', 'color'],+ )),+}, ['stops'])++const shadowSpec = shape(MODEL_KEYS.shadow, {+ x: num(-1e4, 1e4), y: num(-1e4, 1e4), blur: num(0, 1e4), color: color(),+}, ['blur', 'color'])++const fx = shape(MODEL_KEYS.fx, {+ enter: oneOf('fade-up', 'fade', 'fade-down', 'slide-left', 'slide-right', 'slide-up', 'slide-down'),+ enterDur: num(0, 600),+ order: num(-1e4, 1e4),+ countUp: bool,+ ambient: oneOf('kenburns'),+ ken: shape(MODEL_KEYS.fxKen, {+ dir: oneOf('drift', 'out', 'in'), scale: num(0, 100), duration: num(0, 3600),+ }),+ loop: shape(MODEL_KEYS.fxLoop, {+ type: oneOf('dash-march', 'motion-path'),+ path: pathData,+ duration: num(0, 3600),+ delay: num(0, 3600),+ distance: num(-1e5, 1e5),+ ease: cssValue(64),+ speeds: list(LIMITS.speeds, num(0.001, 1000)),+ }, ['type']), // anim.ts dispatches on it; a loop with no type animates nothing+})++const tableStyle = shape(MODEL_KEYS.tableStyle, {+ headerBg: color(), headerColor: color(), zebra: color(),+ borderColor: color(), borderWidth: num(0, 1e3),+ cellPadX: num(0, 1e3), cellPadY: num(0, 1e3),+ fontSize: num(0, 4000), fontFamily: fontStack, color: color(), radius: num(0, 1e5),+})++// `cells` is required: renderTableHtml walks `row.cells.map` with no guard+const tableRows = list(LIMITS.rows, shape(MODEL_KEYS.tableRow, {+ cells: list(LIMITS.cols, shape(MODEL_KEYS.tableCell, {+ html: str(LIMITS.html),+ align: oneOf('left', 'center', 'right'),+ color: color(), bg: color(), bold: bool,+ })),+}, ['cells']))++/**+ * A chart option is free-form ECharts-shaped JSON that charts-lite interprets+ * key by key, so there is no key table to check it against. What CAN be+ * checked is that it IS plain, bounded JSON — nothing exotic, nothing so deep+ * or so large that drawing it hangs the editor. Anything unexpected anywhere+ * inside drops the WHOLE option (a chart without one renders as an empty svg;+ * chartSnapshotSvg already catches), because a half-pruned option is still an+ * attacker's shape, kept.+ */+const chartOption: Check = (v) => {+ if (!isPlainObject(v)) return DROP+ let nodes = LIMITS.optionNodes+ const pure = (node: unknown, depth: number): boolean => {+ if (--nodes < 0 || depth < 0) return false+ if (node === null) return true+ switch (typeof node) {+ case 'boolean': return true+ case 'number': return Number.isFinite(node)+ case 'string': return node.length <= LIMITS.html+ case 'object': break+ default: return false // functions and symbols never survive JSON anyway+ }+ if (Array.isArray(node)) return node.every((entry) => pure(entry, depth - 1))+ if (!isPlainObject(node)) return false+ return Object.keys(node).every(+ (key) => key !== PROTO && key.length <= LIMITS.scalar && pure(node[key], depth - 1),+ )+ }+ return pure(v, LIMITS.optionDepth) ? v : DROP+}++// `el` is required: a connector end with no element to anchor to is dangling,+// and editor.syncConnectors drops those anyway+const connectorEnd = shape(MODEL_KEYS.connectorEnd, {+ el: cssValue(), side: oneOf('auto', 'top', 'right', 'bottom', 'left'),+}, ['el'])++/**+ * One check per property the format defines on an element, keyed by property+ * name — the names do not collide across element types (`loop` is a media+ * boolean; the animation loop lives under `fx`, checked by its own table).+ *+ * Every name in MODEL_KEYS.element must appear here or it is dropped as if it+ * were unknown; scripts/test-clipboard.ts asserts the coverage, so adding a+ * field to model.ts fails the rig until it is taught here too.+ */+const ELEMENT_CHECKS: Record<string, Check> = {+ // identity + geometry+ id: cssValue(), morphId: cssValue(), role: cssValue(), group: cssValue(),+ groupId: cssValue(), showOnHover: cssValue(), link: cssValue(),+ x: num(-1e6, 1e6), y: num(-1e6, 1e6), w: num(0, 1e6), h: num(0, 1e6),+ rotation: num(-3600, 3600), opacity: num(0, 1),+ shadow: (v) => (Array.isArray(v) ? list(16, shadowSpec)(v) : shadowSpec(v)),+ blur: num(0, 1000), backdropFilter: num(0, 1000), blend: cssValue(64),+ fx,+ // text+ html: str(LIMITS.html), placeholder: str(LIMITS.prose),+ fontSize: num(0, 4000), fontFamily: fontStack, fontWeight: num(1, 1000),+ lineHeight: num(0, 100), letterSpacing: num(-1000, 1000),+ color: color(), colorGradient: gradient,+ align: oneOf('left', 'center', 'right'), valign: oneOf('top', 'middle', 'bottom'),+ textStroke: shape(['width', 'color', 'fill'], {+ width: num(0, 1e3), color: color(), fill: color(),+ }, ['width', 'color']),+ // shape+ shape: oneOf('rect', 'ellipse', 'triangle', 'arrow', 'line', 'path'),+ fill: paint, fillGradient: gradient, stroke: paint,+ strokeWidth: num(0, 1e4), strokeDash: num(0, 1e4),+ strokeStyle: oneOf('solid', 'dashed', 'dotted'),+ lineStart: oneOf('none', 'arrow', 'dot', 'bar'), lineEnd: oneOf('none', 'arrow', 'dot', 'bar'),+ radius: num(0, 1e5), d: pathData,+ pathBox: (v) => (Array.isArray(v) && v.length === 4 ? list(4, num(-1e6, 1e6))(v) : DROP),+ from: connectorEnd, to: connectorEnd,+ // image / svg / media+ src: mediaRef, poster: mediaRef, asset: cssValue(),+ fit: oneOf('contain', 'cover', 'fill'),+ markup: str(LIMITS.markup), css: str(LIMITS.css),+ kind: oneOf('video', 'audio'),+ autoplay: bool, loop: bool, muted: bool, controls: bool,+ // chart / table+ preset: cssValue(), option: chartOption,+ source: shape(['tableId'], { tableId: cssValue() }, ['tableId']),+ columns: list(LIMITS.cols, shape(['w'], { w: num(0, 1e6) }, ['w'])),+ rows: tableRows, header: bool, style: tableStyle,+ type: oneOf(...Object.keys(MODEL_KEYS.element)),+}++/**+ * The keys each element type cannot render WITHOUT. Hand-written because+ * modelkeys.generated.ts records names, not optionality; scripts/test-clipboard.ts+ * pins every entry to a measured failure and asserts each name is real.+ *+ * All six were reproduced against the pre-change validator, which emitted the+ * element anyway (`{type:'table',id:'t'}` came back as `{type:'table',id:'t'}`):+ *+ * table columns → renderTableHtml "…(reading 'reduce')" on el.columns+ * rows → same, "…(reading 'map')" once columns is supplied+ * text html → resolveFields (render.ts) "…(reading 'indexOf')"+ * image src → resolveAsset "…(reading 'startsWith')"+ * shape shape → shapeSvg's switch matches nothing, node stays undefined+ * fill → shapeSvg writes fill="undefined" and the shape paints+ * BLACK — the same corruption a rejected `url("#core-glow")`+ * used to cause, arriving by the other door+ * chart option → charts-lite has no series to read+ * media kind → the poster/icon still branches on it+ * src → nothing to play+ *+ * Not listed, deliberately: values that only DEGRADE. Geometry+ * (x/y/w/h/rotation/opacity) and strokeWidth stringify to "undefinedpx"/"NaN",+ * which CSS and SVG ignore, so the element lands at a default frame instead of+ * throwing — losing a whole pasted element over a defaultable number is the+ * worse trade. `svg` is absent for a different reason: its content comes from+ * `markup` OR `asset` (2 of the 4780 elements in a real deck use the asset+ * form), and svgMarkup already falls back to ''.+ */+const REQUIRED_ELEMENT_KEYS: Record<string, readonly string[]> = {+ text: ['html'],+ shape: ['shape', 'fill'],+ image: ['src'],+ chart: ['option'],+ table: ['columns', 'rows'],+ media: ['kind', 'src'],+}++/** Exported so the rig can prove each name is a real key of that element type. */+export const REQUIRED_KEYS: Readonly<Record<string, readonly string[]>> = REQUIRED_ELEMENT_KEYS++/**+ * Check ONE element property in isolation — the entry point for property-level+ * intake such as remote CRDT ops, where a whole element is never in hand.+ * Returns the value to store; `ok:false` means the op must be ignored.+ */+export function checkElementProp(+ type: string, key: string, value: unknown,+): { ok: boolean; value?: unknown } {+ const known = (MODEL_KEYS.element as Record<string, readonly string[]>)[type]+ if (!known || !known.includes(key) || key === PROTO) return { ok: false }+ const val = ELEMENT_CHECKS[key]?.(value)+ return val === DROP ? { ok: false } : { ok: true, value: val }+}++/** Rebuild a foreign element, or null if it is not one. */+export function sanitizeElement(value: unknown): SlideElement | null {+ if (!isPlainObject(value)) return null+ const type = value.type+ if (typeof type !== 'string') return null+ const known = (MODEL_KEYS.element as Record<string, readonly string[]>)[type]+ if (!known) return null+ // Identity is not optional: ids anchor selection, morph, comments and the+ // CRDT node key, and a slide paste keeps them (only slide ids are reminted).+ const id = ELEMENT_CHECKS.id(value.id)+ if (typeof id !== 'string' || !id) return null+ const out: Record<string, unknown> = { type, id }+ for (const key of Object.keys(value)) {+ if (key === 'type' || key === 'id' || key === PROTO || !known.includes(key)) continue+ const val = ELEMENT_CHECKS[key]?.(value[key])+ if (val !== DROP) out[key] = val+ }+ // An element missing what its type needs is not a degraded element, it is one+ // the format cannot express — and the renderer throws on it (see above), which+ // takes the whole slide down, not just the paste.+ if (!(REQUIRED_ELEMENT_KEYS[type] ?? []).every((key) => out[key] !== DROP)) return null+ return out as unknown as SlideElement+}++const SLIDE_CHECKS: Record<string, Check> = {+ id: cssValue(), name: str(LIMITS.prose), stateOf: cssValue(),+ // background is a CSS `background` shorthand, so it gets the colour rule at+ // the shorthand's length — wide enough for a multi-stop linear-gradient(),+ // still no url() reaching for the network from a pasted slide+ background: color(LIMITS.scalar), notes: str(LIMITS.html),+ hidden: bool,+ transition: oneOf('none', 'fade', 'slide', 'zoom', 'morph'),+ hover: shape(['type', 'dim', 'default'], {+ type: oneOf('focus-group', 'reveal'), dim: num(0, 1), default: cssValue(),+ }, ['type']),+ comments: list(LIMITS.comments, shape(MODEL_KEYS.comment, {+ id: cssValue(), elementId: cssValue(), x: num(-1e6, 1e6), y: num(-1e6, 1e6),+ author: str(LIMITS.prose), text: str(LIMITS.prose), at: str(LIMITS.scalar), resolved: bool,+ replies: list(LIMITS.comments, shape(['id', 'author', 'text', 'at'], {+ id: cssValue(), author: str(LIMITS.prose), text: str(LIMITS.prose), at: str(LIMITS.scalar),+ })),+ })),+ // elements are dropped INDIVIDUALLY: one hostile element must not cost the+ // author the rest of a legitimately copied slide+ elements: (v) => (Array.isArray(v) && v.length <= LIMITS.elements+ ? v.map(sanitizeElement).filter((el): el is SlideElement => el !== null)+ : DROP),+}++/**+ * The property names checked above. scripts/test-clipboard.ts asserts that+ * every name in MODEL_KEYS covers one — a field added to model.ts and not+ * taught here would be dropped from every paste, silently, which is exactly+ * the class of failure this file exists to stop.+ */+export const CHECKED_KEYS = {+ element: Object.keys(ELEMENT_CHECKS),+ slide: Object.keys(SLIDE_CHECKS),+}++/** Rebuild a foreign slide, or null if it is not one. */+export function sanitizeSlide(value: unknown): Slide | null {+ if (!isPlainObject(value)) return null+ const id = SLIDE_CHECKS.id(value.id)+ if (typeof id !== 'string' || !id) return null+ const out = shape(MODEL_KEYS.slide, SLIDE_CHECKS)(value) as Record<string, unknown>+ if (!Array.isArray(out.elements)) out.elements = []+ return out as unknown as Slide+}++/**+ * Rebuild a foreign asset table. Keys become `asset:` references and object+ * keys; values are opaque bytes (a data: URI) or raw svg markup, so they are+ * checked for type and size only — what the renderer does with markup is the+ * renderer's business.+ */+export function sanitizeAssets(value: unknown): Record<string, string> {+ const out: Record<string, string> = {}+ if (!isPlainObject(value)) return out+ let n = 0+ for (const key of Object.keys(value)) {+ if (key === PROTO || !key || key.length > LIMITS.scalar || CSS_BREAKOUT.test(key)) continue+ const v = value[key]+ if (typeof v !== 'string' || v.length > LIMITS.asset) continue+ if (++n > LIMITS.assets) break+ out[key] = v+ }+ return out+}++/**+ * Rebuild a foreign font table. `weight` and `style` are interpolated RAW into+ * an @font-face rule by fonts.ts, so they get the CSS-value treatment; family+ * and asset must both be present or the record cannot load anything.+ */+export function sanitizeFonts(value: unknown): Array<{ family: string; asset: string }> {+ if (!Array.isArray(value)) return []+ const out: Array<{ family: string; asset: string }> = []+ for (const entry of value.slice(0, LIMITS.assets)) {+ const font = shape(['family', 'asset', 'weight', 'style'], {+ family: fontStack, asset: cssValue(), weight: cssValue(64), style: cssValue(64),+ })(entry) as Record<string, unknown> | undefined+ if (typeof font?.family === 'string' && typeof font.asset === 'string' && font.asset) {+ out.push(font as unknown as { family: string; asset: string })+ }+ }+ return out+}diff --git a/tray/ios/EditorViewController.swift b/tray/ios/EditorViewController.swiftindex b071ead3..40646a99 100644--- a/tray/ios/EditorViewController.swift+++ b/tray/ios/EditorViewController.swift@@ -43,12 +43,12 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR/// a picker when it holds no handle — afterwards ⌘S, autosave write-back and/// in-place update all reuse it. So the FIRST request targets this document/// and needs no UI; any later one is a genuine Save-As or export and must- /// not overwrite it. Comparing filenames instead would fail: Bento derives- /// its suggested name from the deck TITLE, so it rarely matches.+ /// not overwrite it. Deciding that from the suggested name instead would+ /// fail: Bento derives it from the deck TITLE, so it rarely matches, and+ /// every save would wrongly prompt.private var openDocumentVended = falseprivate var isPresentingFullscreen = falseprivate var fullscreenObs: NSKeyValueObservation?- private var pendingExportName: String?/// Stable per-document host: a truncated SHA-256 of the file's path. Hex/// only, so it is always a valid host component.@@ -343,7 +343,13 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURsuggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {guard let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).firstelse { completionHandler(nil); return }- var dest = docs.appendingPathComponent(suggestedFilename)+ // suggestedFilename is page-influenced (`<a download>` carries it), and+ // WebKit's sanitisation of it is undocumented — so it goes through the+ // same filter as an export name rather than resting on that. SUBSTITUTED+ // rather than refused, unlike an export: refusing loses a save the user+ // asked for, and here the directory is fixed and the loop below can only+ // create a new file, so a bad name costs a name, never a file.+ var dest = docs.appendingPathComponent(safeFileName(suggestedFilename) ?? "download.html")// never clobber: downloads are new files by definitionvar n = 2let ext = dest.pathExtension@@ -388,8 +394,12 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR} else {// A copy/template/read-only export. Ask where it goes; it must// never land on the open document.- pendingExportName = (m["suggestedName"] as? String) ?? "deck.bento.html"- reply(id, ok: true, value: pendingExportName!)+ //+ // Normalised HERE as well as at the write, because this name is+ // handed back to the page and comes straight back as the write+ // target: sanitising only one end would leave the two disagreeing+ // about what file the handle refers to.+ reply(id, ok: true, value: exportName(m["suggestedName"] as? String))}case "read":@@ -397,7 +407,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR// currently on disk. Only the OPEN document is readable — an export// target is somewhere we were handed once and do not hold.let want = (m["name"] as? String) ?? ""- if want == document.fileURL.lastPathComponent {+ if targetsOpenDocument(want) {reply(id, ok: true, value: String(data: document.html, encoding: .utf8) ?? "")} else {reply(id, ok: true, value: nil)@@ -406,7 +416,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURcase "write":let text = (m["text"] as? String) ?? ""let name = (m["name"] as? String) ?? ""- if name == document.fileURL.lastPathComponent {+ if targetsOpenDocument(name) {document.html = Data(text.utf8)// updateChangeCount + autosave is the sanctioned path: it// coordinates with iCloud and file coordination rather than@@ -426,9 +436,92 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR}}+ /// The name to vend for an export handle: sanitised, and never the open+ /// document's.+ ///+ /// The vended name IS the handle as far as this bridge is concerned — read+ /// and write carry nothing else to tell two handles apart — so an export+ /// vended under the open document's filename would BE the open document's+ /// handle, and its close() would overwrite the original in place. That is+ /// the loss exportCopy exists to prevent (an export carries different+ /// credentials: a read-only copy has the owner keys stripped), and it is not+ /// exotic: Bento suggests an export name derived from the deck TITLE, so a+ /// deck saved under its own title — "Notes" as Notes.bento.html — makes+ /// "Duplicate as new deck…" suggest exactly the open file's name.+ ///+ /// Disambiguated rather than refused, because the export is a save the user+ /// asked for and the picker still shows them where it lands. Prefixed rather+ /// than numbered, because ".bento.html" is a DOUBLE extension that+ /// deletingPathExtension splits down the middle ("Notes.bento 2.html").+ private func exportName(_ suggested: String?) -> String {+ let name = safeFileName(suggested) ?? "deck.bento.html"+ return name == document.fileURL.lastPathComponent ? "copy of \(name)" : name+ }++ /// Does a read/write from the page address the OPEN document, or an export?+ ///+ /// Both halves are load-bearing. Comparing names is only sound because+ /// exportName() guarantees no export handle is ever vended under this name;+ /// requiring that the document was actually vended means a name the page+ /// produced on its own — no handle for it ever handed out — cannot address+ /// the file on disk. Routing on `openDocumentVended` alone could not work:+ /// the page can hold the document's handle AND an export's at once, so which+ /// handle a write came through is the question, not how many exist.+ private func targetsOpenDocument(_ name: String) -> Bool {+ openDocumentVended && name == document.fileURL.lastPathComponent+ }+private func reply(_ id: Int, ok: Bool, value: String?) {- let arg = value.map { "\"\($0.replacingOccurrences(of: "\"", with: "\\\""))\"" } ?? "null"- webView.evaluateJavaScript("window.__bentoNativeReply(\(id), \(ok), \(arg))")+ webView.evaluateJavaScript("window.__bentoNativeReply(\(id), \(ok), \(value.map(jsString) ?? "null"))")+ }++ /// Encode one string as a JavaScript literal for the reply call.+ ///+ /// Escaping just `"` by hand was not enough, and the `read` op is the proof:+ /// it returns the WHOLE document HTML, which carries newlines and+ /// backslashes. A raw newline inside a JS string literal is a syntax error,+ /// so the reply never runs, `__bentoNativeReply` never fires and the promise+ /// in bridge.js waits forever — getFile() and createWritable({keepExistingData})+ /// hang rather than fail. A backslash is quieter and worse: save.ts writes+ /// every `<` in the data block as a JSON unicode escape, and interpolated+ /// raw the JS parser CONSUMES that escape — the page gets back a document+ /// whose `#bento-doc` block now contains a literal `<`, which is the one+ /// thing the splice contract escapes it to prevent.+ ///+ /// JSON strings are JS strings, so a JSON encoder is the whole answer.+ ///+ /// The unreachable failure branch replies `null`, not `""`: for the `read`+ /// op an empty string is a CLAIM — that the file on disk is empty — and a+ /// page acting on it would save a document built on nothing. `null` is the+ /// same thing the nil path already sends, and bridge.js turns it into an+ /// empty File either way, so nothing is lost by declining to assert.+ private func jsString(_ s: String) -> String {+ guard let d = try? JSONSerialization.data(withJSONObject: s, options: [.fragmentsAllowed]),+ let out = String(data: d, encoding: .utf8) else { return "null" }+ // JSON leaves U+2028/2029 bare; ES2019 made them legal in a string+ // literal, but this costs nothing and does not bet on the engine vintage.+ return out.replacingOccurrences(of: "\u{2028}", with: "\\u2028")+ .replacingOccurrences(of: "\u{2029}", with: "\\u2029")+ }++ /// Reduce a page-supplied filename to ONE plain component, or refuse it.+ ///+ /// The name arrives from the document, and this host treats documents as+ /// mutually untrusted (that is why the origin is per-document). Passed+ /// straight to appendingPathComponent, `../Documents/Notes.bento.html`+ /// escapes the temp directory and overwrites a deck the user downloaded+ /// earlier and will later open and trust — and since the write lands BEFORE+ /// the export picker appears, the only thing they are shown is a picker for+ /// a different file. Refused rather than repaired: a legitimate export name+ /// is already a single filename, so anything else is not worth guessing at.+ private func safeFileName(_ raw: String?) -> String? {+ guard let raw else { return nil }+ // lastPathComponent drops any directory part; the remaining tests catch+ // what it leaves behind — "" from an empty name, "/" from bare root, and+ // a leading dot, which covers ".." and hidden files in one.+ let name = (raw as NSString).lastPathComponent+ guard !name.isEmpty, !name.contains("/"), !name.hasPrefix(".") else { return nil }+ return name}/// Write an exported copy to a temp file and let the user place it. Kept@@ -436,7 +529,17 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR/// different credentials (a read-only copy has the owner keys stripped), so/// overwriting the original with one would be a real data loss.private func exportCopy(named name: String, text: String, done: @escaping (Bool, String?) -> Void) {- let tmp = FileManager.default.temporaryDirectory.appendingPathComponent(name)+ guard let safe = safeFileName(name) else { done(false, "unsafe name"); return }+ let dir = FileManager.default.temporaryDirectory+ let tmp = dir.appendingPathComponent(safe)+ // Belt and braces over safeFileName. The write is the step that cannot be+ // taken back, so prove the resolved path is still inside the temp+ // directory instead of trusting that the name tests caught everything.+ // Both sides are standardized from the SAME base url, so this compares+ // like with like rather than /var against /private/var.+ guard tmp.standardizedFileURL.path.hasPrefix(dir.standardizedFileURL.path + "/") else {+ done(false, "unsafe name"); return+ }do { try Data(text.utf8).write(to: tmp) } catch { done(false, "\(error)"); return }let picker = UIDocumentPickerViewController(forExporting: [tmp], asCopy: true)present(picker, animated: true) { done(true, nil) }