Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Release 1.2.7 (#682)
nyblnet29ca06550a78
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4c817206..3b959906 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1097,6 +1097,18 @@ jobs:# auth or calls itself an Editor — an allowlist, failing closed.run: node scripts/test-dash-share-dirty.ts+ - name: bento/dash sync inbound+ # A peer cannot set this copy's room, docId, readonly, template,+ # format, version or policy — by relay op, by snapshot, or by a frame+ # injected on the same-origin BroadcastChannel.+ run: node scripts/test-dash-sync-inbound.ts++ - name: bento/dash room snapshot and inbound fields+ # A dash room snapshot carries no never-synced field (collab first); a+ # remote op or snapshot can't adopt one; no prototype-shaped name off the+ # wire reaches any object, and a prototype-named actor can't throw.+ run: node scripts/test-dash-snapshot-collab.ts+- name: bento/dash save race (kernel SaveQueue)# The unsaved dot goes out only for the revision that was written; a# dropped file's handle swap waits for the write in flight; an in-place@@ -1875,6 +1887,15 @@ jobs:echo 'negative control passed with the boundary removed'; exit 1; finode scripts/test-audience-projection.ts+ - name: Audience embed rig+ # An embed's document can carry another deck's envelope (collab ++ # docId); the handout, the live snapshot and every live op the real+ # engine emits must arrive without it. Negative control first.+ run: |+ if node scripts/test-audience-embed.ts --mutate > /dev/null 2>&1; then+ echo 'negative control passed with the envelope rule emptied'; exit 1; fi+ node scripts/test-audience-embed.ts+- name: Broadcast follow-mode rig# The audience side's decisions (slides/src/follow.ts): nav by slide# ID with the index only as fallback — an insert mid-talk moves nobody;@@ -2245,6 +2266,16 @@ jobs:# dirty flag — so a surviving slides assumption shows up there.run: node --no-warnings scripts/test-sync-session.ts+ - name: Room snapshot carries no capability fields+ # Every snapshot path (relay upload, fork broadcast, re-snap, flush-time+ # fork snap) builds from one helper that strips the never-synced fields.+ run: node --no-warnings scripts/test-sync-snapshot-collab.ts++ - name: Remote ops and snapshots can't rewrite identity, capability or modes+ # The never-synced set is also the receive filter (applySet and+ # mergeSnapshot), and no prototype-shaped name reaches any object.+ run: node --no-warnings scripts/test-sync-inbound-docfields.ts+- name: the spaces binding of the sync session# Only what bento/spaces answers DIFFERENTLY, because three of the five# host answers are not slides' answers and each one is invisible untildiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a02d807b..c50fa8ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,18 +11,8 @@ pre-1.0.## [Unreleased]-- **Ghost Cut: move elements with ⇧⌘X (Ctrl+Shift+X).** The selection fades- where it stands instead of disappearing; paste moves it to the pointer — on- this slide or another — keeping it the same element, in one undoable step.- Escape puts it back. It is also copied, so pasting in another deck works as- after ⌘C. Plain ⌘X is unchanged. Thanks to senthan-07 (#679).-- **An edit made while the deck is saving is no longer marked saved.** Saving- takes a moment, and an edit made in that moment — by you, or by someone in a- live session — used to be shown as saved while the file on disk was still- missing it. The unsaved-changes dot now goes out only when the file holds- exactly what is on screen; otherwise it stays on and the next save (or- auto-save) writes the edit. ⌘S, auto-save and "Update this file" also wait- for each other instead of writing the file at the same time.+## [1.2.7] — 2026-10-11+- **One page for PowerPoint, in and out: bento.page/convert.** Drop a`.pptx` to open it as a bento/slides deck, or drop a bento/slides deck (orits document JSON) to save it as PowerPoint. The page detects what you@@ -33,7 +23,6 @@ pre-1.0.slides, the Save menu has both ways in: "Import PowerPoint…" opens the pageready for a .pptx, and "Export for PowerPoint…" opens it for this deck'ssaved file.-- **Saving as PowerPoint keeps more of your deck.** Speaker notes, links,tables, charts, pictures and hidden slides come across, and now codeblocks too (as editable text in Consolas, indentation kept) and embedded@@ -50,7 +39,34 @@ pre-1.0.`--report r.json`). Export is a page, a library and a command-line toolrather than a button in the app, so every shared file stays small and theapp stays focused.-+- **Security: update this file. This release closes further issues found in+ our own review.** None needs anything from you beyond updating, except one+ step if you share decks live: **open each shared deck after updating and use+ Reset access once.** What each issue was is described here once people have+ had time to update.+- **An edit made while the deck is saving is no longer marked saved.** Saving+ takes a moment, and an edit made in that moment — by you, or by someone in a+ live session — used to be shown as saved while the file on disk was still+ missing it. The unsaved-changes dot now goes out only when the file holds+ exactly what is on screen; otherwise it stays on and the next save (or+ auto-save) writes the edit. ⌘S, auto-save and "Update this file" also wait+ for each other instead of writing the file at the same time.+- **Turn text into code without leaving the text box.** Type a fenced block+ — a line of three backticks (optionally with a language, like ```` ```js ````+ or ```` ```python ````), your code, and a closing line of three backticks —+ and when you finish editing it becomes a real Code element: highlighted,+ with its language set, and able to morph between slides. If the box held+ only the fence it turns into the Code element in place; text above or below+ stays as text boxes stacked around it. Pasting fenced text works the same,+ into a text box or straight onto the slide. Backticks inside the code are+ kept as typed, and an unclosed fence stays plain text. You can also select+ one or more lines and press `` ` `` to set them in code style; press it+ again to undo that.+- **Ghost Cut: move elements with ⇧⌘X (Ctrl+Shift+X).** The selection fades+ where it stands instead of disappearing; paste moves it to the pointer — on+ this slide or another — keeping it the same element, in one undoable step.+ Escape puts it back. It is also copied, so pasting in another deck works as+ after ⌘C. Plain ⌘X is unchanged. Thanks to senthan-07 (#679).- **Long speaker notes scroll in presenter view.** Notes that are taller thanthe space beside the current and next slides now get their own verticalscrollbar instead of being cut off.@@ -66,17 +82,6 @@ pre-1.0.slide. Interactive states stay behind for now, since a pasted state wouldarrive as an ordinary slide cut off from its parent. Thanks to tikurahul(#615).-- **Turn text into code without leaving the text box.** Type a fenced block- — a line of three backticks (optionally with a language, like ```` ```js ````- or ```` ```python ````), your code, and a closing line of three backticks —- and when you finish editing it becomes a real Code element: highlighted,- with its language set, and able to morph between slides. If the box held- only the fence it turns into the Code element in place; text above or below- stays as text boxes stacked around it. Pasting fenced text works the same,- into a text box or straight onto the slide. Backticks inside the code are- kept as typed, and an unclosed fence stays plain text. You can also select- one or more lines and press `` ` `` to set them in code style; press it- again to undo that.- **Screen readers announce what each Save-as and Share command does.** Themenus keep one-line rows with the description on hover, and the same textis now read out as the command's description; the Save-as list scrolls when@@ -87,7 +92,6 @@ pre-1.0.draws a clear amber ring. Also fixed: the Save caret's ▾ vanished atmedium window widths, rows in the phone ⋯ menu were centred, and menus inthe dark theme cast a navy shadow that did not show.-- **Save is the top bar's primary button; the bar's other buttons line up.**Save and its save-as caret are now filled with the text colour, like theprimary buttons in dialogs, in light and dark themes. The amberdiff --git a/dash/src/sync/crdt.ts b/dash/src/sync/crdt.tsindex e1aedee2..a9aea0db 100644--- a/dash/src/sync/crdt.ts+++ b/dash/src/sync/crdt.ts@@ -166,6 +166,82 @@ export const SYNC_V = 2export const DOC_NODE = '@doc'+/**+ * Top-level document keys that belong to THIS COPY and never to the room.+ *+ * `collab` is the room, its keys and this copy's role; `docId` is identity;+ * `readonly`/`template` are what this copy may do and how it opens; `format`,+ * `version` and `policy` are what this build agreed to read. None of them is+ * shared content, and every one of them is something a sender could use+ * against a receiver: a `set` op or a snapshot register for `collab` made+ * every receiver adopt the SENDER'S room, and the next save wrote it into+ * their file. Senders include any writer through the relay and — with no+ * signature at all — any page on the same origin through the BroadcastChannel,+ * which on file:// is every local document.+ *+ * Refused on the way in (`applySet`, `mergeSnapshot`) and never emitted on the+ * way out (`localOne`). A key is matched on its top-level field, so+ * `collab.sync` is as local as `collab`.+ */+/**+ * Names that must never be used as an object key from remote data.+ *+ * `target[k] = v` with k `__proto__` REPLACES the target's prototype, so a+ * remote `set` named `__proto__` could make `doc.readonly` read true and+ * `doc.collab` read the sender's room through inheritance, with nothing on+ * the document itself to show for it. And this engine looks up per-node and+ * per-actor maps with `??=` (`this.stash[node] ??= {}`, `this.gap[a] ??= []`):+ * a node or actor named `constructor` or `__proto__` resolves to an INHERITED+ * object there, and the write lands on `Object` or `Object.prototype` for the+ * whole page. So all three are refused wherever a remote string becomes a+ * key, as the whole key or as any segment of a composite one (`names.x`,+ * a node id, `col:rid`). Values are never inspected — a cell may say+ * "constructor".+ */+const UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])+export const isUnsafeKey = (s: unknown): boolean =>+ typeof s === 'string' && s.split(/[^A-Za-z0-9_$]+/).some((seg) => UNSAFE_KEYS.has(seg))++/** Any own object KEY at any depth that is unsafe, or any `id` that is (ids become keys later). */+function hasUnsafeKeys(v: unknown): boolean {+ if (!v || typeof v !== 'object') return false+ // An array's keys are its indices — a 100k-row column must not run the+ // pattern 100k times. Only its elements can carry keys.+ if (Array.isArray(v)) {+ for (const x of v) if (x && typeof x === 'object' && hasUnsafeKeys(x)) return true+ return false+ }+ for (const k of Object.keys(v)) {+ if (isUnsafeKey(k)) return true+ const x = (v as Record<string, unknown>)[k]+ if (k === 'id' && isUnsafeKey(x)) return true+ if (hasUnsafeKeys(x)) return true+ }+ return false+}++/** An op whose identifiers, or whose payload's keys, could reach a prototype. */+export function isUnsafeOp(op: Op): boolean {+ const o = op as unknown as Record<string, unknown>+ for (const f of ['a', 'n', 'k', 'sh', 'col']) if (isUnsafeKey(o[f])) return true+ if (Array.isArray(o.keys) && o.keys.some(isUnsafeKey)) return true+ // payload objects: their keys are written onto nodes and maps+ for (const f of ['v', 'node', 'vals']) if (hasUnsafeKeys(o[f])) return true+ return false+}++export const LOCAL_ONLY_DOC_KEYS: ReadonlySet<string> = new Set([+ 'collab', 'docId', 'readonly', 'template', 'format', 'version', 'policy',+ // Volatile and history fields: never content, and the kernel engine's own+ // skipDoc. Dash has no `revisions`/`trail` today; the shared history engine+ // would bring them, and this set must already be right when it does.+ 'modified', 'revisions', 'trail',+])+export const isLocalOnlyDocKey = (k: string): boolean => {+ const dot = k.indexOf('.')+ return LOCAL_ONLY_DOC_KEYS.has(dot > 0 ? k.slice(0, dot) : k)+}+/** node-id separator. U+001F cannot appear in a sheet/column id: import mints* them by slugging (import.ts) and the parser repairs anything else. */const NS = '\u001f'@@ -806,7 +882,12 @@ export class DashSync {}private localOne(doc: DashDoc, p: Patch, ops: Op[]): void {- const push = <T extends Op>(o: T): T => { ops.push(o); return o }+ const push = <T extends Op>(o: T): T => {+ // Never put this copy's own keys on the wire (LOCAL_ONLY_DOC_KEYS).+ if (o.op === 'set' && ((o as unknown as SetOp).n ?? DOC_NODE) === DOC_NODE && isLocalOnlyDocKey((o as unknown as SetOp).k)) return o+ ops.push(o)+ return o+ }switch (p.op) {case 'setCells': {// dictLen is a local undo artefact (it truncates a dictionary this edit@@ -1153,6 +1234,10 @@ export class DashSync {private applyOne(doc: DashDoc, op: Op, res: ApplyResult): void {if (op.a === this.actor) return // our own ops are pre-applied at mint time+ // The actor names keys below (`this.vv[op.a]`, `this.gap[op.a] ??= []`)+ // before anything else looks at the op, so it is checked first, and such+ // an op is not even delivered: no honest replica has that actor id.+ if (isUnsafeKey(op.a)) returnconst seen = this.vv[op.a] ?? 0if (op.s <= seen) return // duplicateif (op.s > seen + 1) {@@ -1173,6 +1258,9 @@ export class DashSync {}private applyEffect(doc: DashDoc, op: Op, res: ApplyResult): void {+ // Delivered (the sequence advanced, so no gap and no `need` storm) but+ // without effect. Gap-buffered and parked ops replay through here too.+ if (isUnsafeOp(op)) returnswitch (op.op) {case 'set': this.applySet(doc, op, res); breakcase 'cell': this.applyCell(doc, op, res); break@@ -1278,6 +1366,11 @@ export class DashSync {private applySet(doc: DashDoc, op: SetOp, res: ApplyResult): void {const node = op.n ?? DOC_NODE+ // A peer cannot set this copy's room, identity or permissions — see+ // LOCAL_ONLY_DOC_KEYS. Checked before the register moves only to keep the+ // state free of registers nothing may ever write; mergeSnapshot refuses+ // the same keys, so a stray register would be inert either way.+ if (node === DOC_NODE && isLocalOnlyDocKey(op.k)) returnif (older(op.l, op.a, this.reg(node, op.k))) returnif (node === DOC_NODE) {this.setReg(node, op.k, [op.l, op.a])@@ -2329,6 +2422,11 @@ export class DashSync {mergeSnapshot(doc: DashDoc, rdoc: DashDoc, rstate: SyncStateJSON): ApplyResult {const res: ApplyResult = { changed: false, structure: false }if (!rstate || rstate.v !== SYNC_V) return res+ // Every map in the state is keyed by a remote node id, actor or register+ // name, and the document's sheets and columns are inserted by their ids —+ // one unsafe key anywhere and the WHOLE snapshot is refused. A snapshot is+ // an optimisation; ops still converge without it.+ if (hasUnsafeKeys(rstate) || hasUnsafeKeys(rdoc)) return resthis.lamport = Math.max(this.lamport, rstate.lamport ?? 0)for (const [a, s] of Object.entries(rstate.vv ?? {})) {if ((this.vv[a] ?? 0) < s) {@@ -2409,6 +2507,8 @@ export class DashSync {// --- property registers: the winning side's value lives in its documentfor (const [node, keys] of Object.entries(rstate.regs ?? {})) {for (const [key, rr] of Object.entries(keys)) {+ // the sender's room, identity and permissions are not content+ if (node === DOC_NODE && isLocalOnlyDocKey(key)) continueif (!regNewer(rr, this.reg(node, key))) continuethis.setReg(node, key, clone(rr))if (node !== DOC_NODE) {diff --git a/dash/src/sync/session.ts b/dash/src/sync/session.tsindex 7ce445b4..2b712e82 100644--- a/dash/src/sync/session.ts+++ b/dash/src/sync/session.ts@@ -22,7 +22,7 @@import type { Store, Patch } from '../store.ts'import type { DashDoc } from '../model.ts'-import { DashSync, SYNC_V, committable, type Op, type SyncStateJSON } from './crdt.ts'+import { DashSync, SYNC_V, DOC_NODE, LOCAL_ONLY_DOC_KEYS, committable, type Op, type SyncStateJSON } from './crdt.ts'import { collabOf, copyCanWrite, mintCollab, type CollabBlock } from './online.ts'import { lsGet, lsJson } from '../../../kernel/src/storage.ts'@@ -481,11 +481,28 @@ export class SyncSession {// --- snapshots (online catch-up + file-fork merge) ------------------------+ /**+ * THE snapshot builder: the relay upload (online.ts getSnapshot) and the fork+ * snap frame (shipSnapshot) both take theirs from here and nowhere else.+ *+ * A snapshot is readable by EVERY room-key holder, readers included, but the+ * live doc carries this device's whole collab block (owner / writer private+ * keys, invite material). So every never-synced top-level field leaves the+ * snapshot, unconditionally. mergeSnapshot reads only `sheets`, sheet/row+ * nodes and the doc keys that have a register (title and the measures /+ * names / assets / blobs maps), so a receiver loses nothing. Their doc-level+ * registers are dropped too, so a stripped value can never read as a delete.+ */snapshot(): { doc: DashDoc; state: SyncStateJSON } {- return {- doc: JSON.parse(JSON.stringify(this.store.doc)) as DashDoc,- state: JSON.parse(JSON.stringify(this.state.toJSON())) as SyncStateJSON,- }+ // LOCAL_ONLY_DOC_KEYS is also the receive filter (crdt.ts), so send and receive match+ const doc = JSON.parse(JSON.stringify(this.store.doc)) as Record<string, unknown>+ for (const k of LOCAL_ONLY_DOC_KEYS) delete doc[k]+ const state = JSON.parse(JSON.stringify(this.state.toJSON())) as SyncStateJSON+ const docRegs = (state.regs as Record<string, Record<string, unknown>> | undefined)?.[DOC_NODE]+ if (docRegs)+ for (const key of Object.keys(docRegs))+ if (LOCAL_ONLY_DOC_KEYS.has(key.split('.')[0])) delete docRegs[key]+ return { doc: doc as unknown as DashDoc, state }}applySnapshot(rdoc: DashDoc, rstate: SyncStateJSON) {diff --git a/kernel/src/sync/crdt.ts b/kernel/src/sync/crdt.tsindex 01076a71..1723c245 100644--- a/kernel/src/sync/crdt.ts+++ b/kernel/src/sync/crdt.ts@@ -135,7 +135,13 @@ export const shape = (// 'revisions'/'trail' are in-file version history (docfields.ts class 'history'):// file-local, never synced — each replica keeps its own timeline. (PR2 turns// skipDoc into a content-class allowlist so unknown fields don't sync either.)- const skipDoc = new Set([parents, 'modified', 'collab', 'format', 'version', 'revisions', 'trail'])+ // docId / readonly / template are identity and file modes: never synced, and —+ // because skipDoc is ALSO the receive filter (applySet, mergeSnapshot) — never+ // adopted from a peer either. A remote op can't rewrite a deck's identity,+ // lock or unlock it, or turn it into a template. `policy` is an encoding tag+ // like format/version: a loader that meets an unknown one FREEZES the document+ // read-only on open, so a peer must never be able to set it.+ const skipDoc = new Set([parents, 'modified', 'collab', 'format', 'version', 'policy', 'revisions', 'trail', 'docId', 'readonly', 'template'])// `assets` and `blobs` are per-key for every app and always have been —// unioned rather than defaulted so an app naming its own map cannot drop them.return { parents, children, text, skipDoc, maps: new Set(['assets', 'blobs', ...maps]) }@@ -235,6 +241,55 @@ export const BLOB_INLINE_MAX = 64 * 1024/** composite element node key: slide id + separator + element id. U+001F* never appears in model ids (uid() emits [a-z0-9-]; generators use ASCII). */const SEP = '\u001f'++/**+ * Names that address an object's PROTOTYPE when used as a property key.+ * `obj['__proto__'] = v` doesn't add a field, it swaps the prototype, so a+ * remote op naming it made doc.readonly / doc.collab READ a peer's values+ * through inheritance until reload, past any name-based refusal list. Every+ * name off the wire is checked whole and per segment: dotted map keys, composite+ * element keys (SEP), and register keys (`node key`, space-separated).+ */+const PROTO_NAMES = new Set(['__proto__', 'constructor', 'prototype'])+const protoName = (s: unknown): boolean =>+ typeof s === 'string' && s.split(/[.\u001f ]/).some((p) => PROTO_NAMES.has(p))++/** Does any own KEY, at any depth of a wire value, carry a prototype name?+ * Fails CLOSED: an object nested past the cap counts as unsafe rather than+ * passing uninspected (no real op payload comes close to 64 levels). */+function hasProtoKey(x: unknown, depth = 0): boolean {+ if (x === null || typeof x !== 'object') return false+ if (depth > 64) return true+ if (Array.isArray(x)) {+ // Walk ELEMENTS, not index keys: an index is never a prototype name, and+ // running protoName per index cost ~85ms on a 100k-row snapshot.+ for (const el of x) if (hasProtoKey(el, depth + 1)) return true+ // NAMED own keys on an array (structured clone over BroadcastChannel keeps+ // them) are walked too, values included — but only when the array has any,+ // so a plain array stays a single pass.+ const keys = Object.keys(x)+ if (keys.length !== x.length)+ for (const k of keys) {+ if (/^(0|[1-9]\d*)$/.test(k)) continue+ if (protoName(k) || hasProtoKey((x as unknown as Record<string, unknown>)[k], depth + 1)) return true+ }+ return false+ }+ for (const k of Object.keys(x)) {+ if (protoName(k)) return true+ if (hasProtoKey((x as Record<string, unknown>)[k], depth + 1)) return true+ }+ return false+}++/** A remote op that names a prototype anywhere — in an identifier it addresses+ * (k, el, sl, id, a cascade key) or as a key inside its payload. */+function protoOp(op: Op): boolean {+ const o = op as unknown as Partial<Record<'k' | 'el' | 'sl' | 'id', unknown>> & { cas?: unknown }+ if ([o.k, o.el, o.sl, o.id].some(protoName)) return true+ if (Array.isArray(o.cas) && o.cas.some(protoName)) return true+ return hasProtoKey(op)+}export const elKey = (sl: string, el: string): string => sl + SEP + elexport const keySlide = (key: string): string => key.slice(0, key.indexOf(SEP))export const keyEl = (key: string): string => key.slice(key.indexOf(SEP) + 1)@@ -479,10 +534,14 @@ export class SyncEngine {stash: Record<string, Record<string, { v?: unknown; r: Reg }>> = {}/** live nodes whose winning parent is dead/absent — data parked here */limbo: Record<string, SlideElement> = {}+ // Both are keyed by REMOTE strings (node ids, actor ids) and never serialized,+ // so they are null-prototype: `??=` on a key like "constructor" must find+ // nothing, not Object.prototype.constructor. Defence in depth behind the+ // intake guards (applyOne / applyEffect)./** ops targeting nodes we haven't seen yet, keyed by node id */- private pending: Record<string, Op[]> = {}+ private pending: Record<string, Op[]> = Object.create(null)/** out-of-order ops per actor awaiting their gap to fill */- private gap: Record<string, Op[]> = {}+ private gap: Record<string, Op[]> = Object.create(null)/** The document shape. NO DEFAULT, deliberately: a default is how a spaces* call site silently gets slides' shape and corrupts a room that then has@@ -922,6 +981,9 @@ export class SyncEngine {private applyOne(doc: BentoDoc, op: Op, res: ApplyResult) {if (op.a === this.actor) return // own ops are pre-applied at diff time+ // An actor id is used as a key in vv / gap; a prototype-shaped one is no real+ // peer, so it is dropped before it can touch either table.+ if (protoName(op.a)) returnconst seen = this.vv[op.a] ?? 0if (op.s <= seen) return // duplicateif (op.s > seen + 1) {@@ -946,6 +1008,13 @@ export class SyncEngine {}private applyEffect(doc: BentoDoc, op: Op, res: ApplyResult) {+ // A prototype-shaped name anywhere in the op: CONSUMED, never applied. The+ // version vector already advanced in applyOne, so the sender's later ops+ // still deliver — dropping it from the sequence would stall them.+ if (protoOp(op)) {+ dbg(String((op as { el?: string }).el ?? '?'), `${op.op} DROP prototype-shaped name`)+ return+ }// A FLAT document has no element layer, so an element-scoped op has// nowhere to land. It should never arrive — peers in a room share a shape// — but the frame came off the wire, and materializing it would either@@ -1016,8 +1085,19 @@ export class SyncEngine {| undefined}+ /** A doc-level key this peer must never ADOPT from a remote op or snapshot:+ * the never-synced set (skipDoc) — capability, identity, file modes, history,+ * volatile/encoding fields. Whatever a peer sends for these is refused, so a+ * remote peer or a local page on the channel can't replace the room keys,+ * rewrite docId, or flip readonly/template in a victim's open deck (which the+ * next save would write to the file). `assets.x` → field `assets`. */+ private refusesDocKey(k: string): boolean {+ return this.S.skipDoc.has(this.mapKey(k)?.[0] ?? k)+ }+private applySet(doc: BentoDoc, op: SetOp, res: ApplyResult) {const nodeId = op.el ?? op.sl ?? DOC_NODE+ if (nodeId === DOC_NODE && this.refusesDocKey(op.k)) return // never adopted, whatever the sender claimsconst rk = `${nodeId} ${op.k}`if (!newer(op.l, op.a, this.regs[rk])) return// birth gate: an ins is a whole-node assignment — sets older than the@@ -1438,6 +1518,10 @@ export class SyncEngine {mergeSnapshot(doc: BentoDoc, rdoc: BentoDoc, rstate: SyncStateJSON): ApplyResult {const res: ApplyResult = { changed: false, structure: false }if (rstate.v !== SYNC_V) return res // pre-v2 snapshot: bare-id keys, unusable+ // A snapshot whose state or doc carries a prototype-shaped key anywhere is+ // refused whole: its ids/keys feed pos, births, regs, stash and doc writes,+ // and no honest peer ever produces one. Catch-up still arrives via ops.+ if (hasProtoKey(rstate) || hasProtoKey(rdoc)) return resthis.lamport = Math.max(this.lamport, rstate.lamport)for (const [a, s] of Object.entries(rstate.vv ?? {})) {if ((this.vv[a] ?? 0) < s) {@@ -1568,6 +1652,8 @@ export class SyncEngine {const sp = rk.indexOf(' ')const nodeId = rk.slice(0, sp)const key = rk.slice(sp + 1)+ // the snapshot path writes doc fields too: same refusal as applySet+ if (nodeId === DOC_NODE && this.refusesDocKey(key)) continueif (!regNewer(rr, this.regs[rk])) continuethis.regs[rk] = clone(rr) // registers advance even for dead nodesif (nodeId !== DOC_NODE) {diff --git a/kernel/src/sync/session.ts b/kernel/src/sync/session.tsindex eaf630a3..f2f696ab 100644--- a/kernel/src/sync/session.ts+++ b/kernel/src/sync/session.ts@@ -21,6 +21,7 @@ import {SyncEngine,SYNC_V,BLOB_INLINE_MAX,+ DOC_NODE,type BlobRef,type CollabCreds,type Op,@@ -685,14 +686,9 @@ export class SyncSession {this.forkPending = truethis.carriesForkState = truetry {- // inlined rather than this.snapshot() — that calls flush(), and flush()- // is our caller- this.broadcast({- t: 'snap',- a: this.actor,- doc: this.snapshotDoc(),- state: JSON.parse(JSON.stringify(this.state.toJSON())),- })+ // snapshotPair() rather than this.snapshot() — that calls flush(), and+ // flush() is our caller+ this.broadcast({ t: 'snap', a: this.actor, ...this.snapshotPair() })} catch (e2) {// snapshot itself failed (state unserializable) — the shadow is still// advanced, so editing continues and the next reconnect retries@@ -1023,6 +1019,15 @@ export class SyncSession {*/private snapshotDoc(): SyncDoc {const doc = JSON.parse(JSON.stringify(this.store.doc)) as SyncDoc+ // A snapshot is readable by EVERY room-key holder, readers included, but the+ // live doc carries this device's whole collab block (owner / writer private+ // keys, invite material). So every never-synced field leaves the snapshot:+ // the engine's skipDoc set, unconditionally and map-independently, apart+ // from the structural container. Receivers lose nothing — mergeSnapshot only+ // copies keys that have a register, and skipDoc keys never get one.+ const skip = this.state.S.skipDoc+ const rec = doc as unknown as Record<string, unknown>+ for (const k of Object.keys(rec)) if (skip.has(k) && k !== this.state.S.parents) delete rec[k]const assets = doc.assetsif (assets)for (const [k, v] of Object.entries(assets))@@ -1030,13 +1035,32 @@ export class SyncSession {return doc}+ /** The sync state as a snapshot may carry it: the doc-level registers of every+ * key snapshotDoc() strips are dropped too — a register whose value is missing+ * from the snapshot doc would read to a receiver's mergeSnapshot as a DELETE. */+ private snapshotState(): SyncStateJSON {+ const j = JSON.parse(JSON.stringify(this.state.toJSON())) as SyncStateJSON+ const skip = this.state.S.skipDoc+ const regs: SyncStateJSON['regs'] = {}+ for (const [rk, r] of Object.entries(j.regs ?? {})) {+ if (rk.startsWith(`${DOC_NODE} `) && skip.has(rk.slice(DOC_NODE.length + 1))) continue+ regs[rk] = r+ }+ j.regs = regs+ return j+ }++ /** THE snapshot builder. Every path that sends a snapshot off this peer — the+ * relay upload (snapshot()), the hello re-snap, the fork broadcast, and the+ * flush-time fork snap — builds from this and from nothing else. */+ private snapshotPair(): { doc: SyncDoc; state: SyncStateJSON } {+ return { doc: this.snapshotDoc(), state: this.snapshotState() }+ }+/** current (doc, sync-state) pair for an encrypted relay snapshot */snapshot(): { doc: SyncDoc; state: SyncStateJSON } {this.flush()- return {- doc: this.snapshotDoc(),- state: JSON.parse(JSON.stringify(this.state.toJSON())),- }+ return this.snapshotPair()}/** How many inline assets are still awaiting blob offload — overdiff --git a/schema/slides-1.2.7.json b/schema/slides-1.2.7.jsonnew file mode 100644index 00000000..561050cc--- /dev/null+++ b/schema/slides-1.2.7.json@@ -0,0 +1,2379 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://bento.page/schema/slides.json",+ "title": "bento/slides document",+ "description": "The #bento-doc JSON of a Bento Slides file, generated from the app's validation tables. Guide: https://bento.page/agents.md",+ "x-bento-version": "1.2.7",+ "$ref": "#/$defs/doc",+ "$defs": {+ "prop-fx": {+ "type": "object",+ "properties": {+ "ambient": {+ "type": "string",+ "enum": [+ "kenburns"+ ]+ },+ "countUp": {+ "type": "boolean"+ },+ "enter": {+ "type": "string",+ "enum": [+ "fade-up",+ "fade",+ "fade-down",+ "slide-left",+ "slide-right",+ "slide-up",+ "slide-down"+ ]+ },+ "enterDur": {+ "type": "number",+ "minimum": 0,+ "maximum": 600+ },+ "ken": {+ "type": "object",+ "properties": {+ "dir": {+ "type": "string",+ "enum": [+ "drift",+ "out",+ "in"+ ]+ },+ "duration": {+ "type": "number",+ "minimum": 0,+ "maximum": 3600+ },+ "scale": {+ "type": "number",+ "minimum": 0,+ "maximum": 100+ }+ },+ "additionalProperties": false+ },+ "loop": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "number",+ "minimum": 0,+ "maximum": 3600+ },+ "distance": {+ "type": "number",+ "minimum": -100000,+ "maximum": 100000+ },+ "duration": {+ "type": "number",+ "minimum": 0,+ "maximum": 3600+ },+ "ease": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "path": {+ "type": "string",+ "maxLength": 65536,+ "description": "SVG path data"+ },+ "speeds": {+ "type": "array",+ "maxItems": 2000,+ "items": {+ "type": "number",+ "minimum": 0.001,+ "maximum": 1000+ }+ },+ "type": {+ "type": "string",+ "enum": [+ "dash-march",+ "motion-path"+ ]+ }+ },+ "additionalProperties": false,+ "required": [+ "type"+ ]+ },+ "order": {+ "type": "number",+ "minimum": -10000,+ "maximum": 10000+ },+ "step": {+ "type": "number",+ "minimum": 0,+ "maximum": 10000+ }+ },+ "additionalProperties": false+ },+ "prop-shadow": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 10000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "x": {+ "type": "number",+ "minimum": -10000,+ "maximum": 10000+ },+ "y": {+ "type": "number",+ "minimum": -10000,+ "maximum": 10000+ }+ },+ "additionalProperties": false,+ "required": [+ "blur",+ "color"+ ]+ },+ {+ "type": "array",+ "maxItems": 16,+ "items": {+ "type": "object",+ "properties": {+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 10000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "x": {+ "type": "number",+ "minimum": -10000,+ "maximum": 10000+ },+ "y": {+ "type": "number",+ "minimum": -10000,+ "maximum": 10000+ }+ },+ "additionalProperties": false,+ "required": [+ "blur",+ "color"+ ]+ }+ }+ ]+ },+ "prop-colorGradient": {+ "type": "object",+ "properties": {+ "angle": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "stops": {+ "type": "array",+ "maxItems": 64,+ "items": {+ "type": "object",+ "properties": {+ "at": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ }+ },+ "additionalProperties": false,+ "required": [+ "at",+ "color"+ ]+ }+ }+ },+ "additionalProperties": false,+ "required": [+ "stops"+ ]+ },+ "prop-themeRefs": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ },+ "maxProperties": 64,+ "description": "property path → palette token"+ },+ "prop-textStroke": {+ "type": "object",+ "properties": {+ "width": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "fill": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ }+ },+ "additionalProperties": false,+ "required": [+ "width",+ "color"+ ]+ },+ "prop-link": {+ "type": "string",+ "maxLength": 4000,+ "description": "slide id or http(s) URL"+ },+ "text": {+ "type": "object",+ "properties": {+ "align": {+ "type": "string",+ "enum": [+ "left",+ "center",+ "right"+ ]+ },+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "colorGradient": {+ "$ref": "#/$defs/prop-colorGradient"+ },+ "fontFamily": {+ "type": "string",+ "maxLength": 300+ },+ "fontSize": {+ "type": "number",+ "minimum": 0,+ "maximum": 4000+ },+ "fontWeight": {+ "type": "number",+ "minimum": 1,+ "maximum": 1000+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "html": {+ "type": "string",+ "maxLength": 65536+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "letterSpacing": {+ "type": "number",+ "minimum": -1000,+ "maximum": 1000+ },+ "lineHeight": {+ "type": "number",+ "minimum": 0,+ "maximum": 100+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "placeholder": {+ "type": "string",+ "maxLength": 4000+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "textStroke": {+ "$ref": "#/$defs/prop-textStroke"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "text"+ },+ "valign": {+ "type": "string",+ "enum": [+ "top",+ "middle",+ "bottom"+ ]+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id",+ "html"+ ],+ "description": "text element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "prop-fillGradient": {+ "type": "object",+ "properties": {+ "angle": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "stops": {+ "type": "array",+ "maxItems": 64,+ "items": {+ "type": "object",+ "properties": {+ "at": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ }+ },+ "additionalProperties": false,+ "required": [+ "at",+ "color"+ ]+ }+ }+ },+ "additionalProperties": false,+ "required": [+ "stops"+ ]+ },+ "prop-from": {+ "type": "object",+ "properties": {+ "el": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "side": {+ "type": "string",+ "enum": [+ "auto",+ "top",+ "right",+ "bottom",+ "left"+ ]+ }+ },+ "additionalProperties": false,+ "required": [+ "el"+ ]+ },+ "prop-to": {+ "type": "object",+ "properties": {+ "el": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "side": {+ "type": "string",+ "enum": [+ "auto",+ "top",+ "right",+ "bottom",+ "left"+ ]+ }+ },+ "additionalProperties": false,+ "required": [+ "el"+ ]+ },+ "shape": {+ "type": "object",+ "properties": {+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "d": {+ "type": "string",+ "maxLength": 65536,+ "description": "SVG path data"+ },+ "fill": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour or url(#local-id)"+ },+ "fillGradient": {+ "$ref": "#/$defs/prop-fillGradient"+ },+ "from": {+ "$ref": "#/$defs/prop-from"+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "heads": {+ "type": "number",+ "minimum": 2,+ "maximum": 2+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "lineEnd": {+ "type": "string",+ "enum": [+ "none",+ "arrow",+ "dot",+ "bar",+ "arrow-open",+ "triangle",+ "triangle-open",+ "diamond",+ "diamond-open",+ "square",+ "circle-open"+ ]+ },+ "lineStart": {+ "type": "string",+ "enum": [+ "none",+ "arrow",+ "dot",+ "bar",+ "arrow-open",+ "triangle",+ "triangle-open",+ "diamond",+ "diamond-open",+ "square",+ "circle-open"+ ]+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "pathBox": {+ "type": "array",+ "minItems": 4,+ "maxItems": 4,+ "items": {+ "type": "number"+ }+ },+ "radius": {+ "type": "number",+ "minimum": 0,+ "maximum": 100000+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "shape": {+ "type": "string",+ "enum": [+ "rect",+ "ellipse",+ "triangle",+ "arrow",+ "line",+ "path"+ ]+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "stroke": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour or url(#local-id)"+ },+ "strokeDash": {+ "type": "number",+ "minimum": 0,+ "maximum": 10000+ },+ "strokeStyle": {+ "type": "string",+ "enum": [+ "solid",+ "dashed",+ "dotted"+ ]+ },+ "strokeWidth": {+ "type": "number",+ "minimum": 0,+ "maximum": 10000+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "to": {+ "$ref": "#/$defs/prop-to"+ },+ "type": {+ "const": "shape"+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id",+ "shape",+ "fill"+ ],+ "description": "shape element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "prop-crop": {+ "type": "object",+ "properties": {+ "scale": {+ "type": "number",+ "minimum": 1,+ "maximum": 64+ },+ "x": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "y": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ },+ "additionalProperties": false,+ "required": [+ "x",+ "y",+ "scale"+ ]+ },+ "image": {+ "type": "object",+ "properties": {+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "crop": {+ "$ref": "#/$defs/prop-crop"+ },+ "fit": {+ "type": "string",+ "enum": [+ "contain",+ "cover",+ "fill"+ ]+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "keepAspectRatio": {+ "type": "boolean"+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "radius": {+ "type": "number",+ "minimum": 0,+ "maximum": 100000+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "src": {+ "type": "string",+ "maxLength": 33554432,+ "description": "data: URI, asset:<key> or URL"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "image"+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id",+ "src"+ ],+ "description": "image element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "svg": {+ "type": "object",+ "properties": {+ "asset": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "css": {+ "type": "string",+ "maxLength": 131072+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "markup": {+ "type": "string",+ "maxLength": 4194304+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "svg"+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id"+ ],+ "description": "svg element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "prop-source": {+ "type": "object",+ "properties": {+ "tableId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ }+ },+ "additionalProperties": false,+ "required": [+ "tableId"+ ]+ },+ "prop-option": {+ "type": "object",+ "description": "ECharts-shaped option, plain JSON"+ },+ "chart": {+ "type": "object",+ "properties": {+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "option": {+ "$ref": "#/$defs/prop-option"+ },+ "preset": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "source": {+ "$ref": "#/$defs/prop-source"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "chart"+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id",+ "option"+ ],+ "description": "chart element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "prop-style": {+ "type": "object",+ "properties": {+ "borderColor": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "borderWidth": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "cellPadX": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "cellPadY": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "fontFamily": {+ "type": "string",+ "maxLength": 300+ },+ "fontSize": {+ "type": "number",+ "minimum": 0,+ "maximum": 4000+ },+ "headerBg": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "headerColor": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "radius": {+ "type": "number",+ "minimum": 0,+ "maximum": 100000+ },+ "zebra": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ }+ },+ "additionalProperties": false+ },+ "prop-rows": {+ "type": "array",+ "maxItems": 2000,+ "items": {+ "type": "object",+ "properties": {+ "cells": {+ "type": "array",+ "maxItems": 200,+ "items": {+ "type": "object",+ "properties": {+ "align": {+ "type": "string",+ "enum": [+ "left",+ "center",+ "right"+ ]+ },+ "bg": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "bold": {+ "type": "boolean"+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "html": {+ "type": "string",+ "maxLength": 65536+ }+ },+ "additionalProperties": false+ }+ }+ },+ "additionalProperties": false,+ "required": [+ "cells"+ ]+ }+ },+ "prop-columns": {+ "type": "array",+ "maxItems": 200,+ "items": {+ "type": "object",+ "properties": {+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "w"+ ]+ }+ },+ "table": {+ "type": "object",+ "properties": {+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "columns": {+ "$ref": "#/$defs/prop-columns"+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "header": {+ "type": "boolean"+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "rows": {+ "$ref": "#/$defs/prop-rows"+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "style": {+ "$ref": "#/$defs/prop-style"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "table"+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id",+ "columns",+ "rows"+ ],+ "description": "table element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "media": {+ "type": "object",+ "properties": {+ "autoplay": {+ "type": "boolean"+ },+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "controls": {+ "type": "boolean"+ },+ "fit": {+ "type": "string",+ "enum": [+ "contain",+ "cover",+ "fill"+ ]+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "kind": {+ "type": "string",+ "enum": [+ "video",+ "audio"+ ]+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "loop": {+ "type": "boolean"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "muted": {+ "type": "boolean"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "poster": {+ "type": "string",+ "maxLength": 33554432,+ "description": "data: URI, asset:<key> or URL"+ },+ "radius": {+ "type": "number",+ "minimum": 0,+ "maximum": 100000+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "src": {+ "type": "string",+ "maxLength": 33554432,+ "description": "data: URI, asset:<key> or URL"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "media"+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id",+ "kind",+ "src"+ ],+ "description": "media element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "prop-doc": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 200+ },+ {+ "type": "object"+ }+ ]+ },+ "embed": {+ "type": "object",+ "properties": {+ "app": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "doc": {+ "$ref": "#/$defs/prop-doc"+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "live": {+ "type": "boolean"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "embed"+ },+ "url": {+ "type": "string",+ "maxLength": 4000,+ "pattern": "^https?://"+ },+ "view": {+ "type": "string",+ "maxLength": 4194304+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id"+ ],+ "description": "embed element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "code": {+ "type": "object",+ "properties": {+ "align": {+ "type": "string",+ "enum": [+ "left",+ "center",+ "right"+ ]+ },+ "backdropFilter": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "blend": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "blur": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "content": {+ "type": "string",+ "maxLength": 65536+ },+ "fontFamily": {+ "type": "string",+ "maxLength": 300+ },+ "fontSize": {+ "type": "number",+ "minimum": 0,+ "maximum": 4000+ },+ "fx": {+ "$ref": "#/$defs/prop-fx"+ },+ "grammarAssetId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "grammarName": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "group": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "groupId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "h": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "lineHeight": {+ "type": "number",+ "minimum": 0,+ "maximum": 100+ },+ "link": {+ "$ref": "#/$defs/prop-link"+ },+ "morphId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "opacity": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "role": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "rotation": {+ "type": "number",+ "minimum": -3600,+ "maximum": 3600+ },+ "shadow": {+ "$ref": "#/$defs/prop-shadow"+ },+ "showOnHover": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "themeAssetId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "themeName": {+ "type": "string",+ "maxLength": 64,+ "pattern": "^[^\"'<>{};]*$"+ },+ "themeRefs": {+ "$ref": "#/$defs/prop-themeRefs"+ },+ "type": {+ "const": "code"+ },+ "valign": {+ "type": "string",+ "enum": [+ "top",+ "middle",+ "bottom"+ ]+ },+ "w": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false,+ "required": [+ "type",+ "id"+ ],+ "description": "code element; x/y/w/h in slide px (1280×720 default); a stable id pairs morphs"+ },+ "element": {+ "oneOf": [+ {+ "$ref": "#/$defs/text"+ },+ {+ "$ref": "#/$defs/shape"+ },+ {+ "$ref": "#/$defs/image"+ },+ {+ "$ref": "#/$defs/svg"+ },+ {+ "$ref": "#/$defs/chart"+ },+ {+ "$ref": "#/$defs/table"+ },+ {+ "$ref": "#/$defs/media"+ },+ {+ "$ref": "#/$defs/embed"+ },+ {+ "$ref": "#/$defs/code"+ }+ ]+ },+ "slide": {+ "type": "object",+ "properties": {+ "background": {+ "type": "string",+ "maxLength": 200,+ "description": "CSS colour; no url()"+ },+ "comments": {+ "type": "array",+ "maxItems": 500,+ "items": {+ "type": "object",+ "properties": {+ "at": {+ "type": "string",+ "maxLength": 200+ },+ "author": {+ "type": "string",+ "maxLength": 4000+ },+ "elementId": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "replies": {+ "type": "array",+ "maxItems": 500,+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "author": {+ "type": "string",+ "maxLength": 4000+ },+ "text": {+ "type": "string",+ "maxLength": 4000+ },+ "at": {+ "type": "string",+ "maxLength": 200+ }+ },+ "additionalProperties": false+ }+ },+ "resolved": {+ "type": "boolean"+ },+ "text": {+ "type": "string",+ "maxLength": 4000+ },+ "x": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ },+ "y": {+ "type": "number",+ "minimum": -1000000,+ "maximum": 1000000+ }+ },+ "additionalProperties": false+ }+ },+ "elements": {+ "type": "array",+ "maxItems": 5000,+ "items": {+ "$ref": "#/$defs/element"+ }+ },+ "hidden": {+ "type": "boolean"+ },+ "hover": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "focus-group",+ "reveal"+ ]+ },+ "dim": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ },+ "default": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ }+ },+ "additionalProperties": false,+ "required": [+ "type"+ ]+ },+ "id": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "name": {+ "type": "string",+ "maxLength": 4000+ },+ "notes": {+ "type": "string",+ "maxLength": 65536+ },+ "stateOf": {+ "type": "string",+ "maxLength": 200,+ "pattern": "^[^\"'<>{};]*$"+ },+ "themeRefs": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ },+ "maxProperties": 64,+ "description": "property path → palette token"+ },+ "transition": {+ "type": "string",+ "enum": [+ "none",+ "fade",+ "slide",+ "zoom",+ "morph"+ ]+ },+ "unnumbered": {+ "type": "boolean"+ }+ },+ "additionalProperties": false,+ "required": [+ "id"+ ],+ "description": "stateOf = hidden variant reached by a link; transition morph pairs same-id elements"+ },+ "tableStyle": {+ "type": "object",+ "properties": {+ "borderColor": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "borderWidth": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "cellPadX": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "cellPadY": {+ "type": "number",+ "minimum": 0,+ "maximum": 1000+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "fontFamily": {+ "type": "string",+ "maxLength": 300+ },+ "fontSize": {+ "type": "number",+ "minimum": 0,+ "maximum": 4000+ },+ "headerBg": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "headerColor": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ },+ "radius": {+ "type": "number",+ "minimum": 0,+ "maximum": 100000+ },+ "zebra": {+ "type": "string",+ "maxLength": 64,+ "description": "CSS colour; no url()"+ }+ },+ "additionalProperties": false+ },+ "theme": {+ "type": "object",+ "properties": {+ "accent": {+ "type": "string",+ "maxLength": 64,+ "description": "accent colour"+ },+ "background": {+ "type": "string",+ "maxLength": 64,+ "description": "slide background"+ },+ "chartPalette": {+ "type": "array",+ "maxItems": 64,+ "items": {+ "type": "string",+ "maxLength": 64,+ "description": "series colour"+ }+ },+ "codePalette": {+ "type": "object",+ "properties": {+ "a": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "c": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "d": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "f": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "k": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "n": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "p": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ },+ "s": {+ "type": "string",+ "maxLength": 64,+ "description": "token colour"+ }+ },+ "additionalProperties": false+ },+ "color": {+ "type": "string",+ "maxLength": 64,+ "description": "body text colour"+ },+ "fontFamily": {+ "type": "string",+ "maxLength": 300,+ "description": "CSS font-family stack for body text"+ },+ "headingFamily": {+ "type": "string",+ "maxLength": 300,+ "description": "display face for headings; absent = fontFamily"+ },+ "palette": {+ "type": "object",+ "properties": {+ "accent2": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot accent2"+ },+ "accent3": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot accent3"+ },+ "accent4": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot accent4"+ },+ "accent5": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot accent5"+ },+ "accent6": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot accent6"+ },+ "bg2": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot bg2"+ },+ "folHlink": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot folHlink"+ },+ "hlink": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot hlink"+ },+ "tx2": {+ "type": "string",+ "maxLength": 64,+ "description": "brand slot tx2"+ }+ },+ "additionalProperties": false+ },+ "table": {+ "$ref": "#/$defs/tableStyle"+ }+ },+ "additionalProperties": false,+ "required": [+ "background",+ "color",+ "accent",+ "fontFamily"+ ]+ },+ "doc": {+ "type": "object",+ "properties": {+ "assets": {+ "type": "object",+ "maxProperties": 2000,+ "additionalProperties": {+ "type": "string",+ "maxLength": 33554432+ },+ "description": "key → data: URI or svg, used as asset:<key>"+ },+ "blobs": {+ "type": "object",+ "description": "runtime-written"+ },+ "collab": {+ "type": "object",+ "description": "runtime-written credentials; never author"+ },+ "docId": {+ "type": "string",+ "maxLength": 200,+ "description": "runtime-minted uuid; omit"+ },+ "fonts": {+ "type": "array",+ "maxItems": 2000,+ "items": {+ "type": "object",+ "properties": {+ "asset": {+ "type": "string",+ "maxLength": 200,+ "description": "asset:<key> or builtin:<name>"+ },+ "family": {+ "type": "string",+ "maxLength": 300+ },+ "style": {+ "type": "string",+ "maxLength": 64+ },+ "weight": {+ "type": "string",+ "maxLength": 64+ }+ },+ "additionalProperties": false,+ "required": [+ "family",+ "asset"+ ]+ }+ },+ "format": {+ "const": "bento/slides"+ },+ "layouts": {+ "type": "array",+ "maxItems": 500,+ "items": {+ "$ref": "#/$defs/slide"+ },+ "description": "slide templates"+ },+ "meta": {+ "type": "object",+ "properties": {+ "author": {+ "type": "string",+ "maxLength": 4000+ },+ "company": {+ "type": "string",+ "maxLength": 4000+ },+ "event": {+ "type": "string",+ "maxLength": 4000+ },+ "keywords": {+ "type": "string",+ "maxLength": 4000+ },+ "subject": {+ "type": "string",+ "maxLength": 4000+ }+ },+ "additionalProperties": false+ },+ "modified": {+ "type": "string",+ "maxLength": 200,+ "description": "runtime-written"+ },+ "present": {+ "type": "object",+ "properties": {+ "controls": {+ "type": "boolean"+ },+ "morphSeconds": {+ "type": "number",+ "minimum": 0,+ "maximum": 60+ },+ "numberHidden": {+ "type": "boolean"+ },+ "progress": {+ "type": "boolean"+ },+ "slideNumber": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ },+ "readonly": {+ "type": "boolean",+ "description": "presentation package"+ },+ "size": {+ "type": "object",+ "properties": {+ "height": {+ "type": "number",+ "minimum": 1,+ "maximum": 100000+ },+ "width": {+ "type": "number",+ "minimum": 1,+ "maximum": 100000+ }+ },+ "additionalProperties": false,+ "required": [+ "width",+ "height"+ ]+ },+ "slides": {+ "type": "array",+ "minItems": 1,+ "maxItems": 500,+ "items": {+ "$ref": "#/$defs/slide"+ }+ },+ "template": {+ "type": "boolean"+ },+ "theme": {+ "$ref": "#/$defs/theme"+ },+ "title": {+ "type": "string",+ "maxLength": 4000+ },+ "version": {+ "type": "integer",+ "minimum": 1,+ "description": "format version; this shell writes 1"+ },+ "$schema": {+ "type": "string"+ },+ "compact": {+ "const": true,+ "description": "input only: omitted fields take editor defaults (AGENTS.md)"+ }+ },+ "additionalProperties": false,+ "required": [+ "format",+ "slides"+ ]+ }+ }+}diff --git a/schema/slides.json b/schema/slides.jsonindex 185e89ff..561050cc 100644--- a/schema/slides.json+++ b/schema/slides.json@@ -3,7 +3,7 @@"$id": "https://bento.page/schema/slides.json","title": "bento/slides document","description": "The #bento-doc JSON of a Bento Slides file, generated from the app's validation tables. Guide: https://bento.page/agents.md",- "x-bento-version": "1.2.6",+ "x-bento-version": "1.2.7","$ref": "#/$defs/doc","$defs": {"prop-fx": {diff --git a/scripts/test-audience-embed.ts b/scripts/test-audience-embed.tsnew file mode 100644index 00000000..40073d7e--- /dev/null+++ b/scripts/test-audience-embed.ts@@ -0,0 +1,185 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// An audience never receives an embedded deck's envelope (slides/src/audience.ts).+//+// node scripts/test-audience-embed.ts+// node scripts/test-audience-embed.ts --mutate (must FAIL: the negative control)+//+// WHAT THIS PROVES. An `embed` element's `doc` is another deck's JSON and can+// carry that deck's ENVELOPE — `collab` (room, read key, writer/owner private+// keys, an invite's private half) and `docId`. Every copy for someone else must+// drop it (envelope.ts). The audience gets content by three routes, and each is+// RUN here on a presenter deck whose embeds carry a full envelope — on a slide,+// an interactive state and a custom layout:+// 1. the handout, `projectDoc` ("Save audience copy…");+// 2. the live snapshot (`audsnap`), which the editor builds with the same+// `projectDoc` — pinned by name, since the editor needs a DOM;+// 3. live edits, `projectOp`, on ops the REAL engine emits mid-show: an embed+// inserted, an embed's document replaced, a slide carrying one inserted,+// and "Save slide as layout" (one whole-value `layouts` register).+// Controls: the embedded CONTENT still arrives; the presenter's deck and the+// ops sent to the real room are not modified (projection is copy-on-write);+// a plain embed with no envelope passes through as the same object.+// --mutate swaps the module's envelope rule for a no-op and every leak row+// must go red.++import { readFileSync } from 'node:fs'+import { projectDoc, projectOp } from '../slides/src/audience.ts'+import { SyncState } from '../slides/src/sync/crdt.ts'+import type { BentoDoc, Slide } from '../slides/src/model.ts'+import type { Op } from '../kernel/src/sync/crdt.ts'++const MUTATE = process.argv.includes('--mutate')+let failures = 0, checks = 0+const ok = (cond: boolean, msg: string) => { checks++; if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`) }++// the embedded deck's envelope: every value must stay out of what the audience gets+const INNER = {+ docId: 'INNER-DOCID-0001',+ collab: { room: 'wINNER-ROOM', key: 'INNER-ROOM-KEY', on: true, v: 2, owner: 'INNER-OWNER-PUB',+ ownerPriv: 'INNER-OWNER-PRIV', writerPub: 'INNER-WRITER-PUB', writerPriv: 'INNER-WRITER-PRIV',+ invite: { pub: 'INNER-INV-PUB', priv: 'INNER-INV-PRIV', role: 'writer', sig: 'INNER-SIG' }, sync: { v: 2, marker: 'INNER-SYNC' } },+}+const NEEDLES = ['INNER-DOCID-0001', 'wINNER-ROOM', 'INNER-ROOM-KEY', 'INNER-OWNER-PRIV', 'INNER-WRITER-PRIV', 'INNER-INV-PRIV', 'INNER-SYNC']+const leaks = (o: unknown) => NEEDLES.filter((n) => JSON.stringify(o).includes(n))+const innerDoc = (title: string) => ({ format: 'bento/slides', version: 1, title, slides: [{ id: 'inner-s1', elements: [] }], ...JSON.parse(JSON.stringify(INNER)) })+const embed = (id: string, title: string) => ({ id, type: 'embed', x: 0, y: 0, w: 400, h: 300, rotation: 0, opacity: 1, app: 'slides', doc: innerDoc(title) })+const slide = (o: Partial<Slide> & { id: string }): Slide => ({ background: '#fff', transition: 'fade', elements: [], notes: '', ...o } as Slide)++const presenter = (): BentoDoc => ({+ format: 'bento/slides', version: 1, docId: 'PRESENTER-DOCID', title: 'talk', size: { w: 1280, h: 720 },+ theme: {}, assets: {},+ collab: { room: 'wPRESENTER-ROOM', key: 'PRESENTER-ROOM-KEY', on: true, v: 2, owner: 'OWNERPUB', ownerPriv: 'PRESENTER-OWNER-PRIV' },+ slides: [+ slide({ id: 's1', elements: [embed('e1', 'on a slide') as never] }),+ slide({ id: 's1-state', stateOf: 's1', elements: [embed('e2', 'on a state') as never] } as never),+ slide({ id: 's2', elements: [{ id: 't1', type: 'text', x: 0, y: 0, w: 10, h: 10, rotation: 0, opacity: 1, html: 'hi' } as never] }),+ ],+ layouts: [slide({ id: 'L1', elements: [embed('e3', 'on a layout') as never] })],+} as unknown as BentoDoc)+const ticket = { invite: { pub: 'AUDPUB', priv: 'AUDPRIV', role: 'audience' as const, sig: 'SIG' }, key: 'SHOW-KEY' }++// the negative control: make the module's envelope rule a no-op, keep everything else+if (MUTATE) {+ const env = await import('../slides/src/envelope.ts') as { EMBED_ENVELOPE: string[] }+ ;(env.EMBED_ENVELOPE as unknown as string[]).length = 0+}++console.log('\n1 · the handout (projectDoc)\n')+const src = presenter()+const before = JSON.stringify(src)+const { doc: aud } = projectDoc(src, ticket)+ok(leaks(aud).length === 0, `no embedded envelope value survives (${leaks(aud).join(', ') || 'none'})`)+const titles = JSON.stringify(aud)+ok(['on a slide', 'on a state', 'on a layout'].every((t) => titles.includes(t)), 'the embedded content still arrives — slide, state and layout')+ok(JSON.stringify(src) === before, "the presenter's deck is untouched (copy-on-write)")+ok(!JSON.stringify(aud).includes('PRESENTER-OWNER-PRIV') && !JSON.stringify(aud).includes('PRESENTER-ROOM-KEY'), "control: the presenter's own secrets were already absent")++console.log('\n2 · the live snapshot (audsnap)\n')+const editor = readFileSync('slides/src/editor/editor.ts', 'utf8').replace(/^\s*\/\/.*$/gm, '')+ok(/snapshot:\s*\(\)\s*=>\s*\(\{\s*doc:\s*projectDoc\(this\.store\.doc,\s*ticket\)\.doc\s*\}\)/.test(editor),+ "the editor's audience snapshot is projectDoc's output — the handout rows above cover it")+const { doc: snap } = projectDoc(presenter(), ticket)+ok(leaks(snap).length === 0, 'the snapshot built that way carries no embedded envelope value')++console.log('\n3 · live edits (projectOp on real engine ops)\n')+const engineOps = (edit: (d: BentoDoc) => void) => {+ const a = presenter()+ const engine = new SyncState('presenter')+ engine.adopt(a as never)+ const b = JSON.parse(JSON.stringify(a)) as BentoDoc+ edit(b)+ return engine.diff(a as never, b as never, { text: true }) as Op[]+}+const cases: [string, (d: BentoDoc) => void][] = [+ ['an embed inserted mid-show', (d) => { (d.slides[2].elements as unknown[]).push(embed('e9', 'inserted')) }],+ ["an embed's document replaced", (d) => { (d.slides[2].elements as unknown[]).push(embed('e8', 'x')); (d.slides[0].elements[0] as { doc: unknown }).doc = innerDoc('replaced') }],+ ['a slide carrying an embed inserted', (d) => { d.slides.push(slide({ id: 's3', elements: [embed('e7', 'new slide') as never] })) }],+ ['Save slide as layout (the layouts register)', (d) => { d.layouts = [...(d.layouts ?? []), slide({ id: 'L2', elements: [embed('e6', 'new layout') as never] })] }],+]+for (const [name, edit] of cases) {+ const ops = engineOps(edit)+ const carrying = ops.filter((o) => leaks(o).length)+ const sent = JSON.stringify(ops)+ const out = ops.map(projectOp).filter((o): o is Op => o !== null)+ ok(carrying.length > 0, `${name}: the engine's ops DO carry the envelope (${carrying.map((o) => `${o.op}${(o as { kind?: string }).kind ? ':' + (o as { kind?: string }).kind : ''}${(o as { k?: string }).k ? ':' + (o as { k?: string }).k : ''}`).join(', ')}) — the row is not vacuous`)+ ok(leaks(out).length === 0, `${name}: none of it reaches the audience (${leaks(out).join(', ') || 'none'})`)+ ok(out.length === ops.length, `${name}: every op still streams (${out.length}/${ops.length})`)+ ok(JSON.stringify(ops) === sent, `${name}: the ops sent to the real room are not modified`)+}++console.log('\ncontrols\n')+const plain: Op = { op: 'set', sl: 's1', el: 'e1', k: 'doc', v: { title: 'no envelope' } } as unknown as Op+ok(projectOp(plain) === plain, 'an embed doc with no envelope passes through as the same op')+const asset: Op = { op: 'set', sl: 's1', el: 'e1', k: 'doc', v: 'asset:abc' } as unknown as Op+ok(projectOp(asset) === asset, 'an asset-ref embed source passes through')++// ---- 4 · DEEP: documents nested inside the embedded document ---------------+// The envelope rule is deep (envelope.ts stripEnvelope): every document nested+// inside an embed — of any Bento app, at any depth up to ENVELOPE_MAX_DEPTH —+// loses its envelope; deeper ones are dropped. Run through all three routes the+// rule serves here: the handout, a live op, and the export strip every other+// copy uses (stripEmbeddedEnvelopes).+console.log('\n4 · deep — documents nested inside the embed\n')+const { stripEnvelope, stripEmbeddedEnvelopes, ENVELOPE_MAX_DEPTH } = await import('../slides/src/envelope.ts') as {+ stripEnvelope: <T>(v: T) => T; stripEmbeddedEnvelopes: (d: BentoDoc) => number; ENVELOPE_MAX_DEPTH: number }+const env = (tag: string) => ({ docId: `${tag}-DOCID`, collab: { room: `w${tag}-ROOM`, key: `${tag}-ROOM-KEY`, v: 2,+ ownerPriv: `${tag}-OWNER-PRIV`, writerPriv: `${tag}-WRITER-PRIV`, invite: { pub: 'p', priv: `${tag}-INV-PRIV`, role: 'writer', sig: 's' } } })+const envNeedles = (tag: string) => [`${tag}-DOCID`, `w${tag}-ROOM`, `${tag}-ROOM-KEY`, `${tag}-OWNER-PRIV`, `${tag}-WRITER-PRIV`, `${tag}-INV-PRIV`]+const has = (o: unknown, needles: string[]) => needles.filter((n) => JSON.stringify(o).includes(n))+/** a slides deck carrying `inner` (if any) in an embed, with its own envelope tagged `tag` */+const slidesDeck = (tag: string, inner?: unknown) => ({ format: 'bento/slides', version: 1, title: `deck ${tag}`, ...env(tag),+ slides: [{ id: `${tag}-s`, elements: inner === undefined ? [] : [{ id: `${tag}-e`, type: 'embed', app: 'slides', doc: inner }] }] })+const carrying = (inner: unknown): BentoDoc => {+ const d = presenter(); (d.slides[2].elements as unknown[]).push({ id: 'deep', type: 'embed', x: 0, y: 0, w: 1, h: 1, rotation: 0, opacity: 1, app: 'slides', doc: inner }); return d+}+const routes = (inner: unknown) => {+ const hand = projectDoc(carrying(inner), ticket).doc+ const op = projectOp({ op: 'set', sl: 's2', el: 'deep', k: 'doc', v: inner } as unknown as Op)+ const exp = JSON.parse(JSON.stringify(carrying(inner))) as BentoDoc; stripEmbeddedEnvelopes(exp)+ return { hand, op, exp }+}+const deepCase = (name: string, inner: unknown, tags: string[], content: string[]) => {+ const needles = tags.flatMap(envNeedles)+ ok(has(inner, needles).length === needles.length, `${name}: the fixture carries every level's envelope (${tags.join(', ')})`)+ const r = routes(inner)+ for (const [route, out] of [['handout', r.hand], ['live op', r.op], ['export strip', r.exp]] as const)+ ok(has(out, needles).length === 0, `${name} — ${route}: no level's envelope survives (${has(out, needles).join(', ') || 'none'})`)+ ok(content.every((c) => JSON.stringify(r.hand).includes(c)), `${name}: every level's content still arrives`)+}+deepCase('doubly nested slides-in-slides', slidesDeck('L1', slidesDeck('L2')), ['L1', 'L2'], ['deck L1', 'deck L2'])+deepCase('triply nested slides-in-slides', slidesDeck('L1', slidesDeck('L2', slidesDeck('L3'))), ['L1', 'L2', 'L3'], ['deck L1', 'deck L2', 'deck L3'])+// a bento/type document nested in a slides embed, found by its FORMAT: it sits+// under an ordinary key (not `doc`), in an array+const typeDoc = { format: 'bento/type', version: 1, title: 'a type report', ...env('TY'), body: [{ p: 'text' }] }+const slidesWithType = { ...slidesDeck('L1'), attachments: [{ label: 'report', file: typeDoc }] }+deepCase('a type doc nested in a slides embed', slidesWithType, ['L1', 'TY'], ['deck L1', 'a type report'])++// the depth bound: a chain of 20 nested decks — documents past ENVELOPE_MAX_DEPTH are dropped+{+ let chain: unknown = slidesDeck('D20')+ for (let i = 19; i >= 1; i--) chain = slidesDeck(`D${i}`, chain)+ const out = stripEnvelope(chain)+ const s = JSON.stringify(out)+ ok(ENVELOPE_MAX_DEPTH === 16, `the bound is 16 documents deep (${ENVELOPE_MAX_DEPTH})`)+ ok(s.includes('"deck D16"') && !s.includes('"deck D17"'), 'depth bound: the 16th nested document is kept, the 17th and below are DROPPED')+ const all = Array.from({ length: 20 }, (_, i) => `D${i + 1}`).flatMap(envNeedles)+ ok(has(out, all).length === 0, `depth bound: no envelope from any level survives, kept or dropped (${has(out, all).length} found)`)+ ok(JSON.stringify(chain).includes('"deck D20"'), 'depth bound: the input chain itself is untouched')+}++// identity: a clean nested deck (no envelope anywhere) comes back as the SAME object,+// so projectElement/projectOp report "nothing changed" and stream the original+{+ const clean = { format: 'bento/slides', version: 1, title: 'clean', slides: [{ id: 'c', elements: [{ id: 'ce', type: 'embed', doc: { format: 'bento/type', title: 'clean inner', body: [] } }] }] }+ ok(stripEnvelope(clean) === clean, 'a clean nested deck is returned by identity')+ const op = { op: 'set', sl: 's2', el: 'deep', k: 'doc', v: clean } as unknown as Op+ ok(projectOp(op) === op, 'and its live op passes through as the same op')+ const inner = slidesDeck('ID', slidesDeck('ID2'))+ const out = stripEnvelope(inner) as { slides: { elements: unknown[] }[] }+ ok(out !== inner && JSON.stringify(inner).includes('ID2-ROOM-KEY'), 'a dirty one is copied, and the input is not modified')+}++console.log(`\n${checks - failures}/${checks} checks passed${MUTATE ? ' (mutated: failures expected)' : ''}`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-clipboard.ts b/scripts/test-clipboard.tsindex 40427184..0fdec33b 100644--- a/scripts/test-clipboard.ts+++ b/scripts/test-clipboard.ts@@ -365,5 +365,31 @@ console.log('\nkey coverage')ok(slideMissing.length === 0, `every slide property in the format has a check (missing: ${slideMissing.join(', ') || 'none'})`)}+// --- copying never puts an embedded deck's envelope on the system clipboard --+// The clipboard is readable by any app: a copied embed whose document (or a+// document nested inside it) carries another deck's envelope — collab, docId —+// must leave that behind. Read from the RAW serialized text, before any paste+// gate, because that text is what lands on the clipboard.+{+ console.log('\nclipboard: embedded envelopes stay behind\n')+ const env = (tag: string) => ({ docId: `${tag}-DOCID`, collab: { room: `w${tag}-ROOM`, key: `${tag}-ROOM-KEY`, v: 2,+ ownerPriv: `${tag}-OWNER-PRIV`, writerPriv: `${tag}-WRITER-PRIV`, invite: { pub: 'p', priv: `${tag}-INV-PRIV`, role: 'writer', sig: 's' } } })+ const needles = ['C1', 'C2'].flatMap((t) => [`${t}-DOCID`, `w${t}-ROOM`, `${t}-ROOM-KEY`, `${t}-OWNER-PRIV`, `${t}-WRITER-PRIV`, `${t}-INV-PRIV`])+ const deck = (tag: string, inner?: unknown) => ({ format: 'bento/slides', version: 1, title: `clip deck ${tag}`, ...env(tag),+ slides: [{ id: `${tag}-s`, elements: inner === undefined ? [] : [{ id: `${tag}-e`, type: 'embed', app: 'slides', doc: inner }] }] })+ const doc = newDoc() as any+ doc.slides[0].elements = [{ id: 'clip-embed', type: 'embed', x: 0, y: 0, w: 400, h: 300, rotation: 0, opacity: 1, app: 'slides', doc: deck('C1', deck('C2')) }]+ const before = JSON.stringify(doc)+ const found = (s: string) => needles.filter((n) => s.includes(n))+ ok(found(before).length === needles.length, `the deck carries both levels' envelopes (${found(before).length}/${needles.length}) — the rows below are not vacuous`)+ const elText = serializeElements(doc.slides[0].elements, doc)+ ok(found(elText).length === 0, `copying ELEMENTS puts none of it on the clipboard (${found(elText).join(', ') || 'none'})`)+ ok(elText.includes('clip deck C1') && elText.includes('clip deck C2'), '…and the embedded content still copies, both levels')+ const slText = serializeSlides(doc.slides, doc)+ ok(found(slText).length === 0, `copying SLIDES puts none of it on the clipboard (${found(slText).join(', ') || 'none'})`)+ ok(slText.includes('clip deck C1') && slText.includes('clip deck C2'), '…and the embedded content still copies, both levels')+ ok(JSON.stringify(doc) === before, 'the open deck is not modified by copying')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/scripts/test-dash-snapshot-collab.ts b/scripts/test-dash-snapshot-collab.tsnew file mode 100644index 00000000..f841048f--- /dev/null+++ b/scripts/test-dash-snapshot-collab.ts@@ -0,0 +1,222 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/dash room-snapshot + inbound rig.+//+// node scripts/test-dash-snapshot-collab.ts+//+// dash runs its OWN sync engine (dash/src/sync), so the kernel's fixes don't+// reach it. Three properties, mirroring the kernel's:+// 1. A room snapshot (relay upload + fork snap frame) never carries the+// never-synced fields — the collab block first. A reader decrypts the+// snapshot with its own key and finds no private-key material.+// 2. A remote op or snapshot can't ADOPT those fields (identity, modes,+// capability, history) into an open workbook.+// 3. No prototype-shaped name off the wire reaches any object, and a+// prototype-named actor can't throw in the frame handler.+//+// Mutations (verified by editing dash/src/sync and re-running; each fails by+// EXIT CODE): restore the whole-doc clone in snapshot(); drop the NEVER_SYNCED+// refusal in applySet; drop the prototype guards.++(globalThis as { window?: unknown }).window = {+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),+ clearTimeout: (h: number) => clearTimeout(h),+ setInterval: (fn: () => void, ms: number) => setInterval(fn, ms),+ clearInterval: (h: number) => clearInterval(h),+ addEventListener: () => {},+}+;(globalThis as { document?: unknown }).document = { hidden: false, addEventListener() {} }++import { registerHooks } from 'node:module'+registerHooks({+ load(url, context, next) {+ if (url.endsWith('.css')) return { format: 'module', source: 'export {}', shortCircuit: true }+ return next(url, context)+ },+})++const { parseDoc } = await import('../dash/src/model.ts')+const { Store } = await import('../dash/src/store.ts')+const { SyncSession } = await import('../dash/src/sync/session.ts')+const { SYNC_V } = await import('../dash/src/sync/crdt.ts')+const { collabForReader } = await import('../kernel/src/docfields.ts')+type DashDoc = import('../dash/src/model.ts').DashDoc+type Rec = Record<string, unknown>++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }+const H = (s: string) => console.log(`\n=== ${s} ===`)+const settle = (ms = 120) => new Promise((r) => setTimeout(r, ms))+const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x))++const thrown: string[] = []+process.on('uncaughtException', (e) => { thrown.push(String((e as Error)?.message ?? e)) })++const roomKey = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')+const SECRETS = ['OWNER-PRIV-SECRET', 'INVITE-PRIV-SECRET']+const leaks = (x: unknown) => SECRETS.filter((s) => JSON.stringify(x).includes(s))++function book(id: string): DashDoc {+ const r = parseDoc(JSON.stringify({+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: id, title: 'Book',+ collab: {+ room: 'wOWNER', key: roomKey, owner: 'OWNER-PUB', writerPub: 'WP', on: true, v: 2,+ ownerPriv: { d: 'OWNER-PRIV-SECRET' }, invite: { role: 'writer', priv: { d: 'INVITE-PRIV-SECRET' } },+ },+ sheets: [{+ id: 'sh', kind: 'table', name: 'Data', rids: [[1, 1]], nextRid: 2,+ columns: [{ id: 'v', name: 'Value', type: 'number' }],+ data: { v: { enc: 'raw', v: [1] } }, steps: [],+ }],+ }))+ if (!r.ok) throw new Error('fixture')+ return r.doc+}++async function throughRoom(plain: unknown, readKey: string): Promise<unknown> {+ const k = (s: string) => crypto.subtle.importKey('raw', new Uint8Array(Buffer.from(s, 'base64url')), 'AES-GCM', false, ['encrypt', 'decrypt'])+ const iv = crypto.getRandomValues(new Uint8Array(12))+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await k(roomKey), new TextEncoder().encode(JSON.stringify(plain)))+ return JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, await k(readKey), ct)))+}++const session = (s: unknown) => s as {+ snapshot: () => { doc: Rec; state: { v: number; regs: Record<string, Record<string, unknown>> } }+ applySnapshot: (d: unknown, st: unknown) => void+ onFrame: (f: unknown) => void+ shipSnapshot: () => void+ addTransport: (mk: (docId: string, onFrame: (f: unknown) => void) => unknown) => unknown+ state: { vv: Rec }+ stop?: () => void+}+// A throw out of a frame handler is recorded and fails the rig by exit code; it+// must not abort the script (open channels would then keep the process alive).+const frame = (s: ReturnType<typeof session>, f: Rec) => {+ try { s.onFrame(f) } catch (e) { thrown.push(String((e as Error)?.message ?? e)) }+}+const snapApply = (s: ReturnType<typeof session>, d: unknown, st: unknown) => {+ try { s.applySnapshot(d, st) } catch (e) { thrown.push(String((e as Error)?.message ?? e)) }+}+process.on('unhandledRejection', (e) => { thrown.push(String((e as Error)?.message ?? e)) })++H('relay upload: the snapshot a READER decrypts carries no collab')+{+ const store = new Store(book(`d-${Math.random()}`))+ const s = session(new SyncSession(store))+ await settle(40)+ ok(leaks(store.doc).length > 0, 'control — the live workbook DOES hold its secrets')+ const snap = s.snapshot()+ const readerKey = (collabForReader(store.doc.collab as unknown as Rec) as { key: string }).key+ const seen = await throughRoom(snap, readerKey) as { doc: Rec }+ ok(!('collab' in seen.doc) && leaks(seen).length === 0, `decrypted with the reader key: no collab, no private keys (${leaks(seen).join(',') || 'none'})`)+ ok(!('docId' in seen.doc) && !('format' in seen.doc), 'identity / encoding fields are not in the snapshot either')+ ok(Array.isArray(seen.doc.sheets) && seen.doc.title === 'Book', 'content still rides the snapshot')+ s.stop?.()+}++H('fork snap frame: carries no collab')+{+ const store = new Store(book(`d-${Math.random()}`))+ const s = session(new SyncSession(store))+ const sent: Rec[] = []+ s.addTransport(() => ({ send: (f: Rec) => sent.push(f), close() {} }))+ await settle(40)+ s.shipSnapshot()+ const snaps = sent.filter((f) => f.t === 'snap')+ ok(snaps.length >= 1, `the fork snap was sent (${snaps.length})`)+ ok(snaps.every((f) => !('collab' in (f.doc as Rec)) && leaks(f).length === 0), 'no snap frame carries collab or private keys')+ s.stop?.()+}++H('a joiner converges from the stripped snapshot and keeps its own collab')+{+ const base = book(`d-${Math.random()}`)+ const A = new Store(clone(base)), sA = session(new SyncSession(A))+ const B = new Store(clone(base)), sB = session(new SyncSession(B))+ await settle(40)+ A.commit({ op: 'setTitle', title: 'retitled on A' } as never)+ await settle(40)+ const bCollab = JSON.stringify(B.doc.collab)+ const snap = sA.snapshot()+ sB.applySnapshot(snap.doc, snap.state)+ ok(B.doc.title === 'retitled on A', 'the joiner merged the content')+ ok(JSON.stringify(B.doc.collab) === bCollab, 'its own collab is untouched (a stripped key is not a delete)')+ sA.stop?.(); sB.stop?.()+}++H('a remote op or snapshot adopts no never-synced field')+{+ const HOSTILE: Rec = {+ collab: { room: 'wEVIL', key: 'EVIL' }, docId: 'EVIL-ID', readonly: true, template: true,+ revisions: [{ id: 'forged' }], trail: [1], format: 'evil', version: 999,+ }+ const F = Object.keys(HOSTILE)+ const store = new Store(book(`d-${Math.random()}`))+ const s = session(new SyncSession(store))+ await settle(40)+ const before = clone(Object.fromEntries(F.map((f) => [f, (store.doc as unknown as Rec)[f]])))+ const ops = F.map((k, i) => ({ a: 'evil', s: i + 1, l: 900000 + i, op: 'set', k, v: HOSTILE[k] }))+ ops.push({ a: 'evil', s: F.length + 1, l: 900000 + F.length, op: 'set', k: 'title', v: 'retitled by peer' })+ frame(s, { t: 'ops', a: 'evil', ops, pv: SYNC_V })+ await settle(40)+ const d = store.doc as unknown as Rec+ for (const f of F) ok(JSON.stringify(d[f]) === JSON.stringify(before[f]), `${f}: unchanged by a remote set`)+ ok(d.title === 'retitled by peer', 'a content set in the same frame still applies')++ // a snapshot with a VALID state and winning forged registers+ const peer = new Store(clone(store.doc)), sp = session(new SyncSession(peer))+ await settle(40)+ const snap = sp.snapshot()+ ok(snap.state.v === SYNC_V, 'the hostile snapshot carries a valid state')+ const rstate = clone(snap.state)+ rstate.regs['@doc'] ??= {}+ for (const [i, f] of [...F, 'title'].entries()) rstate.regs['@doc'][f] = [950000 + i, 'evil']+ const rdoc = { ...clone(snap.doc), ...clone(HOSTILE), title: 'retitled by snapshot' }+ snapApply(s, rdoc, rstate)+ for (const f of F) ok(JSON.stringify(d[f]) === JSON.stringify(before[f]), `${f}: unchanged by a remote snapshot`)+ ok(d.title === 'retitled by snapshot', 'a content register in the same snapshot still applies')+ s.stop?.(); sp.stop?.()+}++H('no prototype-shaped name reaches any object; prototype-named actors cannot throw')+{+ const objProtoBefore = Object.getOwnPropertyNames(Object.prototype).sort().join(',')+ const store = new Store(book(`d-${Math.random()}`))+ const s = session(new SyncSession(store))+ await settle(40)+ const EVIL = { readonly: true, collab: { room: 'rEVIL' } }+ let n = 0+ const op = (f: Rec) => ({ a: 'proto', s: ++n, l: 990000 + n, op: 'set', ...f })+ frame(s, { t: 'ops', a: 'proto', pv: SYNC_V, ops: [+ op({ k: '__proto__', v: EVIL }), op({ k: 'constructor', v: EVIL }), op({ k: 'measures.__proto__', v: EVIL }),+ op({ k: 'subtitle', v: JSON.parse('{"__proto__":{"readonly":true}}') }),+ ] })+ frame(s, { t: 'ops', a: 'proto', pv: SYNC_V, ops: [op({ k: 'title', v: 'after the hostile ops' })] })+ // actor ids, in and out of order (s=2 first reaches the gap buffer)+ for (const name of ['constructor', '__proto__', 'prototype']) {+ frame(s, { t: 'ops', a: name, pv: SYNC_V, ops: [+ { a: name, s: 2, l: 1, op: 'set', k: 'title', v: `gap ${name}` }, { a: name, s: 1, l: 1, op: 'set', k: 'title', v: name },+ ] })+ }+ // a poisoned snapshot is refused whole+ const peer = new Store(clone(store.doc)), sp = session(new SyncSession(peer))+ await settle(40)+ const snap = sp.snapshot()+ const rstate = clone(snap.state)+ ;(rstate.regs['@doc'] ??= {})['__proto__'] = [999999, 'evil']+ snapApply(s, { ...clone(snap.doc), title: 'poisoned' }, rstate)+ await settle(40)+ const d = store.doc as unknown as Rec+ ok(thrown.length === 0, `no throw from any frame (${thrown.join(' | ') || 'none'})`)+ ok(Object.getOwnPropertyNames(Object.prototype).sort().join(',') === objProtoBefore, 'Object.prototype gained nothing')+ ok(Object.getPrototypeOf(d) === Object.prototype && d.readonly !== true, 'the doc keeps its prototype; readonly does not appear')+ ok(!Object.hasOwn(d, 'constructor') && d.subtitle === undefined, 'no constructor field; a payload carrying a __proto__ key is refused')+ ok(!d.measures || Object.getPrototypeOf(d.measures) === Object.prototype, 'the measures map keeps its prototype')+ ok(!['constructor', '__proto__', 'prototype'].some((x) => Object.hasOwn(s.state.vv, x)), 'no prototype-named actor in the version vector')+ ok(d.title === 'after the hostile ops', 'the sender’s next op still delivered; the poisoned snapshot changed nothing')+ s.stop?.(); sp.stop?.()+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-dash-sync-inbound.ts b/scripts/test-dash-sync-inbound.tsnew file mode 100644index 00000000..97371ada--- /dev/null+++ b/scripts/test-dash-sync-inbound.ts@@ -0,0 +1,276 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/dash SYNC INBOUND rig — a peer cannot set this copy's room, identity+// or permissions.+//+// node scripts/test-dash-sync-inbound.ts+//+// WHY THIS EXISTS. The sync engine wrote ANY document-level key a remote+// `set` op named, and adopted any document-level register a snapshot carried.+// So a sender could make every receiver take on THE SENDER'S `collab` — room,+// keys and role — or its docId, or lock it read-only, and the receiver's next+// save wrote that into their own file. Senders: any writer through the relay,+// and, with no signature at all, any page on the same origin through the+// BroadcastChannel — which on file:// is every local document. Three routes,+// one row each: a relay op (the engine), a snapshot (the engine), and a frame+// injected on the BroadcastChannel into a real SyncSession.++import { registerHooks } from 'node:module'+registerHooks({+ load(url, context, next) {+ if (url.endsWith('.css')) return { format: 'module', source: 'export {}', shortCircuit: true }+ return next(url, context)+ },+})++// One in-process bus standing in for the browser's BroadcastChannel: any+// "page" that opens the same name receives what the others post.+const bus = new Map<string, Set<FakeChannel>>()+class FakeChannel {+ name: string+ onmessage: ((ev: { data: unknown }) => void) | null = null+ constructor(name: string) { this.name = name; (bus.get(name) ?? bus.set(name, new Set()).get(name)!).add(this) }+ postMessage(data: unknown) {+ for (const c of bus.get(this.name) ?? []) if (c !== this) c.onmessage?.({ data: JSON.parse(JSON.stringify(data)) })+ }+ close() { bus.get(this.name)?.delete(this) }+}+;(globalThis as { BroadcastChannel: unknown }).BroadcastChannel = FakeChannel++const { parseDoc } = await import('../dash/src/model.ts')+const { Store } = await import('../dash/src/store.ts')+const { DashSync, SYNC_V, DOC_NODE, LOCAL_ONLY_DOC_KEYS, isUnsafeKey, colNode, shNode } = await import('../dash/src/sync/crdt.ts')+const { SyncSession } = await import('../dash/src/sync/session.ts')+type DashDoc = import('../dash/src/model.ts').DashDoc++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }++const MINE = { room: 'w-MINE', key: 'k-mine', on: true, owner: 'o-mine', ownerPriv: 'p-mine', v: 2 }+const EVIL = { room: 'w-EVIL', key: 'k-evil', on: true, owner: 'o-evil', ownerPriv: 'p-evil', v: 2 }+const fresh = (): DashDoc => {+ const r = parseDoc(JSON.stringify({+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'doc-mine', title: 'Mine', collab: MINE,+ sheets: [{+ id: 'sh', kind: 'table', name: 'Data', rids: [[1, 1]], nextRid: 2,+ columns: [{ id: 'v', name: 'Value', type: 'number' }],+ data: { v: { enc: 'raw', v: [1] } }, steps: [],+ }],+ }))+ if (!r.ok) throw new Error('fixture')+ return r.doc+}+/** What the attacker tries to plant, one op per key, plus a legitimate title. */+const HOSTILE: Array<[string, unknown]> = [+ ['collab', EVIL], ['collab.room', 'w-EVIL'], ['docId', 'doc-EVIL'], ['readonly', true],+ ['template', true], ['format', 'bento/slides'], ['version', 99], ['policy', 'evil'],+ ['modified', '1999-01-01T00:00:00Z'], ['revisions', [{ evil: true }]], ['trail', [{ evil: true }]],+]+const intact = (d: DashDoc, where: string) => {+ const c = (d as { collab?: { room?: string; key?: string; ownerPriv?: string } }).collab+ ok(c?.room === 'w-MINE' && c?.key === 'k-mine' && c?.ownerPriv === 'p-mine', `${where}: my room and keys are still mine — got ${c?.room}`)+ ok(d.docId === 'doc-mine', `${where}: my docId — got ${d.docId}`)+ ok(!(d as { readonly?: boolean }).readonly && !(d as { template?: boolean }).template, `${where}: not locked, not turned into a template`)+ ok(d.format === 'bento/dash' && d.version === 1 && (d as { policy?: string }).policy === 'bento-dash-1', `${where}: format, version and policy untouched`)+ ok((d as { modified?: string }).modified !== '1999-01-01T00:00:00Z' && !('revisions' in d) && !('trail' in d),+ `${where}: modified, revisions and trail not written by the sender`)+ // A dotted key does not reach INTO collab (writeKey treats it as a literal+ // top-level name), but it would leave a junk "collab.room" key in the+ // document that the next save writes into the file.+ const stray = Object.keys(d).filter((k) => k.includes('.'))+ ok(stray.length === 0, `${where}: no stray dotted top-level keys — got ${stray.join(',') || 'none'}`)+}+const evilOps = (from = 1) => [+ ...HOSTILE.map(([k, v], i) => ({ op: 'set' as const, a: 'evil', s: from + i, l: 10_000 + i, k, v })),+ // control: an ordinary doc-level edit in the SAME batch still lands+ { op: 'set' as const, a: 'evil', s: from + HOSTILE.length, l: 20_000, k: 'title', v: 'Retitled by a peer' },+]++ok([...LOCAL_ONLY_DOC_KEYS].sort().join() === 'collab,docId,format,modified,policy,readonly,revisions,template,trail,version',+ 'ten keys belong to the copy, not the room; adding or removing one is a decision')++console.log('\n1. a relay op (any writer) — the engine')+{+ const doc = fresh()+ const st = new DashSync('victim')+ st.adopt(doc)+ st.apply(doc, evilOps())+ intact(doc, 'relay op')+ ok(doc.title === 'Retitled by a peer', 'the ordinary title edit in the same batch still applied — the refusal is per key, not per batch')+ ok(st.vv.evil === HOSTILE.length + 1, `delivery still advanced past the refused ops (vv ${st.vv.evil}) — no gap, no "need" storm`)+}++console.log('\n2. a snapshot carrying registers for them — the engine')+{+ const doc = fresh()+ const st = new DashSync('victim')+ st.adopt(doc)+ const rdoc = { ...fresh(), collab: EVIL, docId: 'doc-EVIL', readonly: true, template: true, title: 'Retitled by a snapshot' } as DashDoc+ const regs: Record<string, [number, string]> = { title: [30_000, 'evil'] }+ for (const [k] of HOSTILE) regs[k] = [30_000, 'evil']+ st.mergeSnapshot(doc, rdoc, { v: SYNC_V, lamport: 30_000, vv: { evil: 1 }, regs: { [DOC_NODE]: regs } } as never)+ intact(doc, 'snapshot')+ ok(doc.title === 'Retitled by a snapshot', 'the snapshot\'s ordinary title register still merged')+}++console.log('\n3. BroadcastChannel injection — another local page, no signature, into a real session')+{+ const store = new Store(fresh())+ new SyncSession(store)+ const evilPage = new FakeChannel('bento-sync-doc-mine')+ // `pv` is the protocol version every frame carries; a hostile page sets it too+ evilPage.postMessage({ pv: SYNC_V, t: 'ops', a: 'evil', ops: evilOps() })+ await new Promise((r) => setTimeout(r, 150))+ intact(store.doc, 'BroadcastChannel ops')+ ok(store.doc.title === 'Retitled by a peer', 'and the channel really delivered: the title in the same frame landed')+ const rdoc = { ...fresh(), collab: EVIL, docId: 'doc-EVIL', readonly: true, title: 'Snap title' } as DashDoc+ const regs: Record<string, [number, string]> = { title: [40_000, 'evil2'] }+ for (const [k] of HOSTILE) regs[k] = [40_000, 'evil2']+ evilPage.postMessage({ pv: SYNC_V, t: 'snap', a: 'evil2', doc: rdoc, state: { v: SYNC_V, lamport: 40_000, vv: { evil2: 1 }, regs: { [DOC_NODE]: regs } } })+ await new Promise((r) => setTimeout(r, 150))+ intact(store.doc, 'BroadcastChannel snapshot')+ ok(store.doc.title === 'Snap title', 'and the snapshot frame really merged: its title landed')+}++console.log('\n5. PROTOTYPE KEYS: __proto__, constructor and prototype are never keys')+// `target[k] = v` with k "__proto__" REPLACES the prototype: doc.readonly would+// read true and doc.collab the sender's room through inheritance, with nothing+// on the document to show it. And `map[node] ??= {}` with node "constructor"+// resolves to the inherited Object function, so the write lands on Object for+// the whole page. JSON.parse is how a frame arrives, and it makes "__proto__"+// an OWN key, which is exactly the shape a real attacker sends.+{+ const clean = () => {+ ok(Object.getPrototypeOf({}) === Object.prototype && !('readonly' in Object.prototype) && !('collab' in Object.prototype)+ && !('room' in Object.prototype) && (Object as unknown as { pwned?: unknown }).pwned === undefined,+ 'nothing on Object or Object.prototype was touched')+ }+ const protoIntact = (d: DashDoc, where: string) => {+ ok(Object.getPrototypeOf(d) === Object.prototype, `${where}: the document's prototype is still Object.prototype`)+ ok((d as { readonly?: unknown }).readonly === undefined, `${where}: doc.readonly does not read true through inheritance`)+ const c = (d as { collab?: { room?: string } }).collab+ ok(c?.room === 'w-MINE', `${where}: doc.collab is still mine — got ${c?.room}`)+ }+ const evilPayload = { readonly: true, collab: EVIL, pwned: true }+ const hostile = JSON.parse(JSON.stringify([+ { op: 'set', a: 'evil', s: 1, l: 50_000, k: '__proto__', v: evilPayload },+ { op: 'set', a: 'evil', s: 2, l: 50_001, k: 'names.__proto__', v: evilPayload },+ { op: 'set', a: 'evil', s: 3, l: 50_002, n: 'constructor', k: 'pwned', v: true },+ { op: 'set', a: 'evil', s: 4, l: 50_003, n: shNode('sh'), k: 'prototype', v: evilPayload },+ { op: 'cell', a: 'evil', s: 5, l: 50_004, sh: 'sh', col: '__proto__', rids: [1], v: [1] },+ { op: 'ovr', a: 'evil', s: 6, l: 50_005, sh: 'sh', keys: ['__proto__:1'], v: [evilPayload], m: [0] },+ { op: 'title-control' },+ ]).replace('{"op":"title-control"}', JSON.stringify({ op: 'set', a: 'evil', s: 7, l: 50_006, k: 'title', v: 'After the bad ops' })))+ // an op from an actor CALLED __proto__ — keys `vv` and `gap` before anything else+ const badActor = JSON.parse('[{"op":"set","a":"__proto__","s":1,"l":1,"k":"title","v":"x"},{"op":"set","a":"constructor","s":1,"l":1,"k":"title","v":"x"}]')+ // a node payload with an OWN "__proto__" key, as JSON.parse delivers it+ const badIns = JSON.parse(JSON.stringify({ op: 'ins', a: 'evil', s: 8, l: 50_007, n: colNode('sh', 'z'), ord: 'V', node: { id: 'z', name: 'Z', type: 'number' } })+ .replace('"type":"number"', '"type":"number","__proto__":{"readonly":true}'))+ ok(Object.prototype.hasOwnProperty.call(badIns.node, '__proto__'), 'the fixture really carries an OWN __proto__ key, as a parsed frame would')++ {+ // CONTROL for the ins row: the same op without the __proto__ key inserts+ const d0 = fresh(); const s0 = new DashSync('victim'); s0.adopt(d0)+ s0.apply(d0, [{ op: 'ins', a: 'ok', s: 1, l: 1, n: colNode('sh', 'z'), ord: 'V', node: { id: 'z', name: 'Z', type: 'number' } } as never])+ ok((d0.sheets[0] as { columns: Array<{ id: string }> }).columns.some((c) => c.id === 'z'),+ 'CONTROL — a clean column insert through the same path does land (so the refusal below is not vacuous)')+ }+ const doc = fresh()+ const st = new DashSync('victim')+ st.adopt(doc)+ st.apply(doc, [...hostile, badIns])+ let actorThrew: unknown = null+ try { st.apply(doc, badActor) } catch (e) { actorThrew = e }+ ok(actorThrew === null, `ops from actors named __proto__/constructor do not crash apply${actorThrew ? ' — threw ' + (actorThrew as Error).message : ''}`)+ // an OUT-OF-ORDER op from an actor called "constructor": the gap buffer is+ // `this.gap[a] ??= []`, which for that name resolves to the inherited Object+ // function — and `.some` on it throws, taking the whole apply down+ let threw: unknown = null+ try { st.apply(doc, JSON.parse('[{"op":"set","a":"constructor","s":5,"l":2,"k":"title","v":"x"}]')) } catch (e) { threw = e }+ ok(threw === null, `an out-of-order op from actor "constructor" does not crash apply${threw ? ' — threw ' + (threw as Error).message : ''}`)+ ok(!Object.prototype.hasOwnProperty.call(st.vv, 'constructor') && !Object.prototype.hasOwnProperty.call(st.vv, '__proto__'),+ `and neither name became a version-vector entry, which is saved into the file and sent to every peer — vv keys: ${Object.keys(st.vv).join(',')}`)+ protoIntact(doc, 'relay ops')+ ok(doc.title === 'After the bad ops', 'the ordinary op after them still landed — refused ops still count as delivered')+ ok(st.vv.evil === 8, `delivery advanced through all eight (vv ${st.vv.evil}), so no gap and no "need" storm`)+ ok(!('__proto__' in st.vv && Object.prototype.hasOwnProperty.call(st.vv, '__proto__')) && st.vv.constructor === Object,+ 'an actor named __proto__ or constructor never became a version-vector entry')+ const sheet = doc.sheets[0] as { columns: Array<{ id: string }>; data: Record<string, unknown> }+ ok(Object.getPrototypeOf(sheet.data) === Object.prototype && !sheet.columns.some((c) => c.id === 'z'),+ 'the column with an own __proto__ key was not inserted, and the sheet\'s data map keeps its prototype')+ clean()++ // snapshots: a register named __proto__, a doc with an own __proto__ key,+ // a node id "constructor" in the state — each refuses the whole snapshot+ for (const [what, rdocJson, regs] of [+ ['a __proto__ register', JSON.stringify({ ...fresh(), title: 'Snap' }).replace('"title"', '"title"'), JSON.parse('{"@doc":{"__proto__":[60000,"evil"],"title":[60000,"evil"]}}')],+ ['a document with an own __proto__ key', JSON.stringify({ ...fresh(), title: 'Snap' }).replace('{', '{"__proto__":{"readonly":true,"collab":{"room":"w-EVIL"}},'), { [DOC_NODE]: { title: [60_000, 'evil'] } }],+ ['a node id "constructor"', JSON.stringify({ ...fresh(), title: 'Snap' }), { constructor: { pwned: [60_000, 'evil'] }, [DOC_NODE]: { title: [60_000, 'evil'] } }],+ ] as const) {+ const d = fresh()+ const s2 = new DashSync('victim')+ s2.adopt(d)+ const state = JSON.parse(JSON.stringify({ v: SYNC_V, lamport: 60_000, vv: { evil: 1 }, regs }))+ s2.mergeSnapshot(d, JSON.parse(rdocJson), state)+ protoIntact(d, `snapshot with ${what}`)+ ok(d.title === 'Mine', `snapshot with ${what}: refused whole — not even its title merged`)+ }+ clean()++ // and through the BroadcastChannel into a real session+ const store = new Store(fresh())+ new SyncSession(store)+ const page = new FakeChannel('bento-sync-doc-mine')+ page.postMessage({ pv: SYNC_V, t: 'ops', a: 'evil3', ops: hostile.map((o: { a: string }) => ({ ...o, a: 'evil3' })) })+ await new Promise((r) => setTimeout(r, 150))+ protoIntact(store.doc, 'BroadcastChannel')+ ok(store.doc.title === 'After the bad ops', 'and the channel delivered: the ordinary op landed')+ clean()++ ok(isUnsafeKey('a.__proto__') && isUnsafeKey('c\u001fconstructor') && !isUnsafeKey('Constructor') && !isUnsafeKey('my_prototype_x'),+ 'segments are matched exactly — "Constructor" and "my_prototype_x" are ordinary names')+}++console.log('\n6. OUTBOUND: the snapshot every reader receives carries none of them')+// session.snapshot() is the one builder for the relay upload and the fork+// `snap` frame. A reader holds the room key and can decrypt it, so the owner's+// collab block (ownerPriv) must not be in it. The doc REGISTERS go too: a+// register with no value beside it reads as a DELETE to an older client that+// lacks the inbound refusal, which would strip that client's own room.+{+ const store = new Store(fresh())+ const sess = new SyncSession(store) as unknown as { snapshot(): { doc: Record<string, unknown>; state: { regs?: Record<string, Record<string, unknown>> } }; state: { regs: Record<string, Record<string, unknown>> } }+ // plant registers for local-only keys the way a tampered or future state could hold them+ ;(sess.state.regs[DOC_NODE] ??= {}).collab = [1, 'x']+ sess.state.regs[DOC_NODE].docId = [1, 'x']+ sess.state.regs[DOC_NODE].title = [1, 'x']+ const snap = sess.snapshot()+ const leaked = [...LOCAL_ONLY_DOC_KEYS].filter((k) => k in snap.doc)+ ok(leaked.length === 0, `the snapshot document carries none of the local-only fields — leaked: ${leaked.join(',') || 'none'}`)+ ok(!JSON.stringify(snap).includes('p-mine'), 'the owner\'s private key appears nowhere in the snapshot, at any depth')+ const regs = snap.state.regs?.[DOC_NODE] ?? {}+ ok(!('collab' in regs) && !('docId' in regs), 'nor do their registers, which an older client would read as a delete')+ ok('title' in regs && Array.isArray((snap.doc as { sheets?: unknown[] }).sheets), 'content and ordinary registers are still there')+ ok((store.doc as { collab?: { ownerPriv?: string } }).collab?.ownerPriv === 'p-mine', 'and the LIVE workbook keeps its own keys — only the outbound copy is stripped')+}++console.log('\n4. the outbound guard does not block ordinary doc-level edits')+// The emitter's guard (`localOne`'s push) has NO reachable trigger today: the+// only doc-level ops dash emits are `title` and `measures.*`. It is defence for+// a future patch kind, so this row checks only that it costs nothing — it is+// deliberately not counted as coverage of the guard.+{+ const doc = fresh()+ const st = new DashSync('me')+ st.adopt(doc)+ const ops = [+ ...st.local(doc, [{ op: 'setMeasure', name: 'm', measure: { expr: '1' } }] as never),+ ...st.local(doc, [{ op: 'setTitle', title: 'x' }] as never),+ ]+ ok(ops.map((o) => (o as { k?: string }).k).join() === 'measures.m,title', 'measures and title still go out')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+// a SyncSession keeps heartbeat timers; exit explicitly so a clean run is not a hang+process.exit(failures ? 1 : 0)diff --git a/scripts/test-sync-inbound-docfields.ts b/scripts/test-sync-inbound-docfields.tsnew file mode 100644index 00000000..a2087582--- /dev/null+++ b/scripts/test-sync-inbound-docfields.ts@@ -0,0 +1,319 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Inbound doc-field rig: a remote op or snapshot can't rewrite identity,+// capability, modes or history in an open deck.+//+// node scripts/test-sync-inbound-docfields.ts+//+// The engine's doc-level apply used to write ANY key a remote op named. A+// writer over the relay, or any page on the unsigned same-machine channel,+// could replace the room keys, rewrite docId, or flip readonly / template in a+// victim's open deck, and the next save would write it to the file. The never-+// synced set (crdt.ts skipDoc) is now also the RECEIVE filter: applySet and+// mergeSnapshot refuse it. This rig sends a hostile frame per field over the+// real BroadcastChannel and straight into the session, then a hostile snapshot+// with a VALID state, against both the slides and spaces bindings; content+// still applies on every path.+//+// Mutations (verified by editing kernel/src/sync/crdt.ts and re-running):+// remove the applySet refusal → the ops rows red; remove the mergeSnapshot+// refusal → the snapshot rows red.++(globalThis as unknown as { window: unknown }).window = {+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),+ clearTimeout: (h: number) => clearTimeout(h),+ setInterval: (fn: () => void, ms: number) => setInterval(fn, ms),+ clearInterval: (h: number) => clearInterval(h),+ addEventListener: () => {},+};+(globalThis as unknown as { document: unknown }).document = { hidden: false, addEventListener() {} };++const { register } = await import('node:module');+register('./lib/ts-resolve-hooks.mjs', import.meta.url);++const { Store } = await import('../slides/src/store.ts');+const { SyncSession } = await import('../slides/src/sync/session.ts');+const { newDoc } = await import('../slides/src/model.ts');+const { SYNC_V } = await import('../kernel/src/sync/crdt.ts');++let failures = 0, checks = 0;+function ok(cond: boolean, msg: string) {+ checks++;+ if (!cond) { failures++; console.log(` FAIL ${msg}`); } else console.log(` ok ${msg}`);+}+const H = (s: string) => console.log(`\n=== ${s} ===`);+const settle = (ms = 200) => new Promise(r => setTimeout(r, ms));+const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x));++// what a hostile peer would like to put into the victim's open deck+const HOSTILE: Record<string, unknown> = {+ collab: { room: 'wEVIL', key: 'EVIL-KEY', ownerPriv: { d: 'EVIL' }, on: true, v: 2 },+ docId: 'EVIL-DOC-ID',+ readonly: true,+ template: true,+ revisions: [{ id: 'forged', at: 't', body: {} }],+ trail: [{ forged: true }],+ modified: '1999-01-01',+ format: 'evil/format',+ version: 999,+ // an unknown policy freezes the document read-only on its next open+ policy: 'evil-policy-freezes-on-open',+};+const FIELDS = Object.keys(HOSTILE);++function victimDoc() {+ const d = newDoc();+ d.docId = `victim-${Math.random().toString(36).slice(2, 8)}`;+ d.title = 'mine';+ (d as unknown as { collab: unknown }).collab = { room: 'wMINE', key: 'MY-KEY', ownerPriv: { d: 'MINE' }, on: true, v: 2 };+ return d;+}+type Rec = Record<string, unknown>;+const pick = (d: Rec) => Object.fromEntries(FIELDS.map((f) => [f, d[f]]));+/** Did field `f` resist the peer? `modified` is re-stamped with the RECEIVER's+ * own clock on every remote change (session afterRemoteChange, by design), so+ * for it the test is that the peer's value never lands; every other field must+ * be exactly what it was. */+const held = (f: string, before: Rec, after: Rec) =>+ f === 'modified' ? after[f] !== HOSTILE.modified : JSON.stringify(after[f]) === JSON.stringify(before[f]);++/** ops a hostile actor `a` sends: one set per never-synced field, then a content set */+function hostileOps(a: string) {+ const ops = FIELDS.map((k, i) => ({ a, s: i + 1, l: 100000 + i, op: 'set', k, v: clone(HOSTILE[k]) }));+ ops.push({ a, s: FIELDS.length + 1, l: 100000 + FIELDS.length, op: 'set', k: 'title', v: 'retitled by peer' });+ return ops;+}++H('a hostile ops frame, straight into the session, adopts nothing never-synced');+{+ const store = new Store(victimDoc());+ const s = new SyncSession(store);+ await settle(40);+ const before = clone(pick(store.doc as unknown as Rec));+ (s as unknown as { onFrame: (f: unknown) => void }).onFrame({ t: 'ops', a: 'evil', ops: hostileOps('evil'), pv: SYNC_V });+ await settle(40);+ const after = pick(store.doc as unknown as Rec);+ for (const f of FIELDS) ok(held(f, before, after), `${f}: unchanged by a remote set`);+ ok(store.doc.title === 'retitled by peer', 'a CONTENT set in the same frame still applies');+ s.stop?.();+}++H('the same frame over the real BroadcastChannel (a page on this machine)');+{+ const store = new Store(victimDoc());+ const s = new SyncSession(store);+ await settle(80);+ const before = clone(pick(store.doc as unknown as Rec));+ const ch = new BroadcastChannel(`bento-sync-${store.doc.docId}`);+ ch.postMessage({ t: 'ops', a: 'evil-tab', ops: hostileOps('evil-tab'), pv: SYNC_V });+ await settle(200);+ const after = pick(store.doc as unknown as Rec);+ ok(FIELDS.every((f) => held(f, before, after)),+ `no never-synced field changed (${FIELDS.filter((f) => !held(f, before, after)).join(',') || 'none'})`);+ ok(store.doc.title === 'retitled by peer', 'the content set still applies over the channel');+ ch.close(); s.stop?.();+}++H('a prototype-shaped name cannot reach any object, at any level');+{+ const doc = victimDoc();+ const sl = (doc as unknown as { slides: Array<{ id: string; elements: Rec[] }> }).slides[0];+ sl.elements.push({ id: 'e1', type: 'text', x: 0, y: 0, w: 10, h: 10, html: 'hi' });+ doc.assets = { logo: 'data:,x' } as never;+ const store = new Store(doc);+ const s = new SyncSession(store);+ await settle(40);+ const send = (a: string, ops: Rec[]) => (s as unknown as { onFrame: (f: unknown) => void }).onFrame({ t: 'ops', a, ops, pv: SYNC_V });+ const EVIL = { readonly: true, template: true, collab: { room: 'rEVIL' } };+ let n = 0;+ const op = (fields: Rec) => ({ a: 'proto', s: ++n, l: 200000 + n, op: 'set', ...fields });+ send('proto', [+ op({ k: '__proto__', v: EVIL }), // doc level+ op({ k: 'constructor', v: EVIL }),+ op({ k: 'prototype', v: EVIL }),+ op({ k: 'assets.__proto__', v: EVIL }), // dotted map sub-key+ op({ sl: sl.id, k: '__proto__', v: EVIL }), // slide level+ op({ el: `${sl.id}\u001fe1`, k: '__proto__', v: EVIL }), // element level+ op({ k: 'subtitle', v: JSON.parse('{"__proto__":{"readonly":true}}') }), // a payload KEY+ op({ k: 'subtitle2', v: (() => { // a NAMED key on an array+ const a: unknown[] = [1, 2, 3]; // (structured clone keeps one)+ Object.defineProperty(a, '__proto__', { value: { readonly: true }, enumerable: true, configurable: true, writable: true });+ return a;+ })() }),+ op({ k: 'subtitle3', v: (() => { // a named NON-proto array key+ const a = [1, 2, 3] as unknown[] & { x?: unknown }; // whose VALUE carries one+ a.x = JSON.parse('{"__proto__":{"readonly":true}}');+ return a;+ })() }),+ op({ k: 'deep', v: (() => { // __proto__ 70 levels down —+ let o: unknown = JSON.parse('{"__proto__":{"readonly":true}}'); // past the scan's depth cap,+ for (let i = 0; i < 70; i++) o = { n: o }; // which must REFUSE, not pass+ return o;+ })() }),+ ]);+ // the same sender's next op must still deliver — the guard consumes, never stalls+ send('proto', [op({ k: 'title', v: 'after the hostile ops' })]);+ // and an actor id that is itself a prototype name is ignored without throwing+ let threw = false;+ try { send('__proto__', [{ a: '__proto__', s: 1, l: 1, op: 'set', k: 'title', v: 'from __proto__' }]); } catch { threw = true; }+ await settle(40);+ const d = store.doc as unknown as Rec;+ const slide = (d.slides as Array<Rec>)[0];+ const el = (slide.elements as Rec[]).find((e) => e.id === 'e1')!;+ ok(Object.getPrototypeOf(d) === Object.prototype, 'the doc keeps its plain prototype');+ ok(d.readonly !== true && d.template !== true && (d.collab as Rec)?.room !== 'rEVIL', 'readonly/template/collab do not appear through inheritance');+ ok(!Object.hasOwn(d, 'constructor') && !Object.hasOwn(d, 'prototype'), 'no own constructor/prototype field was written');+ ok(Object.getPrototypeOf(d.assets) === Object.prototype, 'the assets map keeps its prototype (dotted sub-key refused)');+ ok(Object.getPrototypeOf(slide) === Object.prototype, 'the slide keeps its prototype');+ ok(Object.getPrototypeOf(el) === Object.prototype, 'the element keeps its prototype');+ ok(d.subtitle === undefined, 'an op whose payload carries a __proto__ KEY is refused');+ ok(d.subtitle2 === undefined, 'an array payload with a NAMED __proto__ key is refused (arrays are walked by element)');+ ok(d.subtitle3 === undefined, 'an array whose named NON-proto key holds a __proto__ key is refused (named keys are walked)');+ ok(d.deep === undefined, 'a __proto__ key nested past the depth cap is refused (the cap fails closed)');+ ok(d.title === 'after the hostile ops', 'the sender’s next op still delivered (consumed, not stalled)');+ ok(!threw && d.title !== 'from __proto__', 'a prototype-named actor is ignored, without throwing');+ s.stop?.();+}++H('prototype-named actor and node ids: no throw, no pollution, vv clean');+{+ // An uncaught throw inside a frame handler (BroadcastChannel delivers async)+ // must FAIL this rig by exit code, not slip past as a log line.+ const thrown: string[] = [];+ const onUncaught = (e: unknown) => { thrown.push(String((e as Error)?.message ?? e)); };+ process.on('uncaughtException', onUncaught);+ const objProtoBefore = Object.getOwnPropertyNames(Object.prototype).sort().join(',');++ const doc = victimDoc();+ const sl = (doc as unknown as { slides: Array<{ id: string; elements: Rec[] }> }).slides[0];+ const store = new Store(doc);+ const s = new SyncSession(store);+ await settle(80);+ const direct = (f: Rec) => { try { (s as unknown as { onFrame: (f: unknown) => void }).onFrame({ pv: SYNC_V, ...f }); } catch (e) { thrown.push(String((e as Error).message)); } };+ const ch = new BroadcastChannel(`bento-sync-${store.doc.docId}`);+ for (const name of ['constructor', '__proto__', 'prototype']) {+ // actor id: in order AND out of order (s=2 first reaches the gap buffer)+ const actorOps = [{ a: name, s: 2, l: 500002, op: 'set', k: 'title', v: `gap from ${name}` },+ { a: name, s: 1, l: 500001, op: 'set', k: 'title', v: `from ${name}` }];+ direct({ t: 'ops', a: name, ops: actorOps });+ ch.postMessage({ t: 'ops', a: name, ops: actorOps, pv: SYNC_V });+ // node ids, from a clean actor, out of order so `pending` is reached+ const clean = `clean-${name.replace(/_/g, '')}`;+ direct({ t: 'ops', a: clean, ops: [+ { a: clean, s: 1, l: 510001, op: 'set', sl: name, k: 'title', v: 'x' },+ { a: clean, s: 2, l: 510002, op: 'set', el: `${sl.id}\u001f${name}`, k: 'x', v: 1 },+ { a: clean, s: 3, l: 510003, op: 'set', el: `${name}\u001fe9`, k: 'x', v: 1 },+ { a: clean, s: 4, l: 510004, op: 'del', kind: 'slide', id: name },+ ] });+ }+ // the clean control still applies+ direct({ t: 'ops', a: 'control', ops: [{ a: 'control', s: 1, l: 600000, op: 'set', k: 'title', v: 'control applied' }] });+ await settle(250);+ process.off('uncaughtException', onUncaught);+ ch.close();++ const d = store.doc as unknown as Rec;+ const vv = (s as unknown as { state: { vv: Rec } }).state.vv;+ ok(thrown.length === 0, `no throw from any frame (${thrown.join(' | ') || 'none'})`);+ ok(Object.getOwnPropertyNames(Object.prototype).sort().join(',') === objProtoBefore, 'Object.prototype gained nothing');+ ok(Object.getPrototypeOf(d) === Object.prototype, 'the doc keeps its prototype');+ ok(!['constructor', '__proto__', 'prototype'].some((n) => Object.hasOwn(vv, n)), 'no prototype-named actor entered the version vector');+ ok(d.title === 'control applied', 'a clean control op still applies afterwards');+ s.stop?.();+}++H('the named-array-key and depth edges also hold over the real BroadcastChannel');+{+ // structured clone is what can deliver a NAMED array key, so prove that path+ const store = new Store(victimDoc());+ const s = new SyncSession(store);+ await settle(80);+ const arr = [1, 2, 3] as unknown[] & { x?: unknown };+ arr.x = JSON.parse('{"__proto__":{"readonly":true}}');+ let deep: unknown = JSON.parse('{"__proto__":{"readonly":true}}');+ for (let i = 0; i < 70; i++) deep = { n: deep };+ const ch = new BroadcastChannel(`bento-sync-${store.doc.docId}`);+ ch.postMessage({ t: 'ops', a: 'bc-edge', pv: SYNC_V, ops: [+ { a: 'bc-edge', s: 1, l: 700001, op: 'set', k: 'namedArr', v: arr },+ { a: 'bc-edge', s: 2, l: 700002, op: 'set', k: 'deepBC', v: deep },+ { a: 'bc-edge', s: 3, l: 700003, op: 'set', k: 'title', v: 'bc control' },+ ] });+ await settle(200);+ const d = store.doc as unknown as Rec;+ ok(d.namedArr === undefined && d.deepBC === undefined, 'over the channel: both edge payloads refused');+ ok(d.title === 'bc control' && Object.getPrototypeOf(d) === Object.prototype, 'the control applied; the doc keeps its prototype');+ ch.close(); s.stop?.();+}++H('a snapshot carrying a prototype-shaped key is refused whole');+{+ const store = new Store(victimDoc());+ const s = new SyncSession(store);+ await settle(40);+ const peer = new Store(clone(store.doc));+ const sp = new SyncSession(peer);+ await settle(40);+ const snap = (sp as unknown as { snapshot: () => { doc: Rec; state: { regs: Rec } } }).snapshot();+ const rstate = clone(snap.state);+ rstate.regs['@doc __proto__'] = [400000, 'evil'];+ rstate.regs['@doc title'] = [400001, 'evil'];+ const rdoc: Rec = { ...clone(snap.doc), title: 'retitled by a poisoned snapshot' };+ Object.defineProperty(rdoc, '__proto__', { value: { readonly: true }, enumerable: true, configurable: true, writable: true });+ (s as unknown as { applySnapshot: (d: unknown, st: unknown) => void }).applySnapshot(rdoc, rstate);+ const d = store.doc as unknown as Rec;+ ok(Object.getPrototypeOf(d) === Object.prototype && d.readonly !== true, 'the doc keeps its prototype; readonly does not appear');+ ok(d.title === 'mine', 'nothing from the poisoned snapshot landed — not even its content register');+ s.stop?.(); sp.stop?.();+}++H('a hostile SNAPSHOT with a valid state adopts nothing never-synced');+{+ const store = new Store(victimDoc());+ const s = new SyncSession(store);+ await settle(40);+ const before = clone(pick(store.doc as unknown as Rec));+ // a real, valid state from a real session on the same document, then winning+ // registers forged for every never-synced field (and for title, as a control)+ const peer = new Store(clone(store.doc));+ const sp = new SyncSession(peer);+ await settle(40);+ const snap = (sp as unknown as { snapshot: () => { doc: Rec; state: { v: number; regs: Rec } } }).snapshot();+ ok(snap.state.v === SYNC_V, 'the hostile snapshot carries a VALID state (current SYNC_V), not a stub');+ const rdoc: Rec = { ...clone(snap.doc), ...clone(HOSTILE), title: 'retitled by snapshot' };+ const rstate = clone(snap.state);+ for (const [i, f] of [...FIELDS, 'title'].entries()) rstate.regs[`@doc ${f}`] = [300000 + i, 'evil'];+ (s as unknown as { applySnapshot: (d: unknown, st: unknown) => void }).applySnapshot(rdoc, rstate);+ const after = pick(store.doc as unknown as Rec);+ for (const f of FIELDS) ok(held(f, before, after), `${f}: unchanged by a remote snapshot`);+ ok(store.doc.title === 'retitled by snapshot', 'a content register in the same snapshot still applies');+ s.stop?.(); sp.stop?.();+}++H('the spaces binding shares the engine, and the filter');+{+ const { Store: SStore } = await import('../spaces/src/store.ts');+ const { SyncSession: SSession } = await import('../spaces/src/sync/session.ts');+ const { FORMAT, FORMAT_VERSION, defaultTheme } = await import('../spaces/src/model.ts');+ const d: Rec = {+ format: FORMAT, version: FORMAT_VERSION,+ docId: `victim-sp-${Math.random().toString(36).slice(2, 8)}`,+ title: 'mine', theme: defaultTheme(), home: 'home',+ collab: { room: 'wMINE', key: 'MY-KEY', ownerPriv: { d: 'MINE' }, on: true, v: 2 },+ pages: [{ id: 'home', title: 'Home', blocks: [{ id: 'b1', type: 'p', html: 'hello' }] }],+ };+ const store = new SStore(d as never);+ const s = new SSession(store as never);+ await settle(40);+ const live = (store as unknown as { doc: Rec }).doc;+ const before = clone(pick(live));+ (s as unknown as { onFrame: (f: unknown) => void }).onFrame({ t: 'ops', a: 'evil', ops: hostileOps('evil'), pv: SYNC_V });+ await settle(40);+ const after = pick((store as unknown as { doc: Rec }).doc);+ ok(FIELDS.every((f) => held(f, before, after)),+ `spaces: no never-synced field changed (${FIELDS.filter((f) => !held(f, before, after)).join(',') || 'none'})`);+ s.stop?.();+}++console.log(`\n${checks - failures}/${checks} checks passed`);+process.exit(failures ? 1 : 0);diff --git a/scripts/test-sync-shape.ts b/scripts/test-sync-shape.tsindex a080d411..9258db6e 100644--- a/scripts/test-sync-shape.ts+++ b/scripts/test-sync-shape.ts@@ -118,9 +118,11 @@ const spacesDoc = (blocks: unknown[]) => ({// EXACT pin — any change to the skip set must be deliberate and land here.// `revisions` and `trail` joined it with the field-classification ruling// (kernel/src/docfields.ts, class 'history'): in-file version history is- // file-local and never synced. Everything else is the shipped engine's set.- ok([...SLIDES_SHAPE.skipDoc].sort().join(',') === 'collab,format,modified,revisions,slides,trail,version',- 'and its skip set is exactly the shipped engine set plus the history class (revisions, trail)')+ // file-local and never synced. `docId`, `readonly` and `template` joined it+ // because skipDoc is also the RECEIVE filter: identity and file modes are+ // never adopted from a peer. Everything else is the shipped engine's set.+ ok([...SLIDES_SHAPE.skipDoc].sort().join(',') === 'collab,docId,format,modified,policy,readonly,revisions,slides,template,trail,version',+ 'and its skip set is exactly the shipped engine set plus history, identity and modes')}// ---- stamping WITHOUT the token history ------------------------------------diff --git a/scripts/test-sync-snapshot-collab.ts b/scripts/test-sync-snapshot-collab.tsnew file mode 100644index 00000000..e66e4ed2--- /dev/null+++ b/scripts/test-sync-snapshot-collab.ts@@ -0,0 +1,183 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Room-snapshot rig: a snapshot never carries the uploader's collab block.+//+// node scripts/test-sync-snapshot-collab.ts+//+// A room snapshot is encrypted under the ROOM key and readable by every holder+// of it — readers included (their copy keeps collab.key). The live doc carries+// this device's whole collab block: ownerPriv on the owner, writerPriv on a v1+// writer, invite material. So every path that sends a snapshot must strip it:+// the relay upload (snapshot()), the fork broadcast (hello()), the re-snap a+// fork sends a new peer, and the flush-time fork snap. This rig decrypts a real+// snapshot with the READER's key and asserts no secret is in it, drives the two+// frame paths through a capturing transport, checks a joiner still converges+// from the stripped snapshot without losing its own collab, and pins that every+// snap frame in session.ts is built by the one helper.+//+// Mutations (verified by editing kernel/src/sync/session.ts and re-running):+// restore the whole-doc clone in snapshotDoc() → the decrypt + frame rows red;+// drop snapshotState()'s register filter → the "no stale register" row reds.++const listeners: Record<string, Array<() => void>> = {};+(globalThis as unknown as { window: unknown }).window = {+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),+ clearTimeout: (h: number) => clearTimeout(h),+ setInterval: (fn: () => void, ms: number) => setInterval(fn, ms),+ clearInterval: (h: number) => clearInterval(h),+ addEventListener: (ev: string, fn: () => void) => { (listeners[ev] ??= []).push(fn); },+};+(globalThis as unknown as { document: unknown }).document = { hidden: false, addEventListener() {} };++const { register } = await import('node:module');+register('./lib/ts-resolve-hooks.mjs', import.meta.url);+const { readFileSync } = await import('node:fs');++const { Store } = await import('../slides/src/store.ts');+const { SyncSession } = await import('../slides/src/sync/session.ts');+const { newDoc } = await import('../slides/src/model.ts');+const { SYNC_V } = await import('../kernel/src/sync/crdt.ts');+const { collabForReader } = await import('../kernel/src/docfields.ts');++let failures = 0, checks = 0;+function ok(cond: boolean, msg: string) {+ checks++;+ if (!cond) { failures++; console.log(` FAIL ${msg}`); } else console.log(` ok ${msg}`);+}+const H = (s: string) => console.log(`\n=== ${s} ===`);+const settle = (ms = 260) => new Promise(r => setTimeout(r, ms));+const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x));++const SECRETS = ['OWNER-PRIV-SECRET', 'INVITE-PRIV-SECRET', 'WRITER-PRIV-SECRET'];+const leaks = (x: unknown) => SECRETS.filter((s) => JSON.stringify(x).includes(s));++// a real 32-byte room key, base64url — the reader's copy keeps it verbatim+const b64u = (b: Uint8Array) => Buffer.from(b).toString('base64url');+const unb64u = (s: string) => new Uint8Array(Buffer.from(s, 'base64url'));+const roomKey = b64u(crypto.getRandomValues(new Uint8Array(32)));++/** AES-GCM under the room key, as the relay upload does; decrypt with `readKey`. */+async function throughRoom(plain: unknown, readKey: string): Promise<unknown> {+ const k = (s: string) => crypto.subtle.importKey('raw', unb64u(s), 'AES-GCM', false, ['encrypt', 'decrypt']);+ const iv = crypto.getRandomValues(new Uint8Array(12));+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await k(roomKey), new TextEncoder().encode(JSON.stringify(plain)));+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, await k(readKey), ct);+ return JSON.parse(new TextDecoder().decode(pt));+}++// The collab blocks a live doc holds on three kinds of device.+const COLLABS: Record<string, Record<string, unknown>> = {+ 'v2 owner': {+ room: 'wOWNERROOM', key: roomKey, owner: 'OWNER-PUB', writerPub: 'WP', on: true, v: 2,+ ownerPriv: { kty: 'EC', d: 'OWNER-PRIV-SECRET' },+ invite: { role: 'writer', priv: { d: 'INVITE-PRIV-SECRET' } },+ },+ 'v2 writer (invitee)': {+ room: 'wOWNERROOM', key: roomKey, owner: 'OWNER-PUB', writerPub: 'WP', on: true, v: 2, role: 'writer',+ invite: { role: 'writer', priv: { d: 'INVITE-PRIV-SECRET' } },+ },+ 'v1 writer (legacy room)': {+ room: 'rLEGACY', key: roomKey, writerPub: 'WP', on: true,+ writerPriv: { kty: 'EC', d: 'WRITER-PRIV-SECRET' },+ },+};++function docWith(collab: Record<string, unknown>) {+ const d = newDoc();+ d.docId = `snap-${Math.random().toString(36).slice(2, 8)}`;+ d.title = 'shared deck';+ (d as unknown as { collab: unknown }).collab = clone(collab);+ return d;+}++H('relay upload: the snapshot a READER decrypts carries no collab');+for (const [label, collab] of Object.entries(COLLABS)) {+ const store = new Store(docWith(collab));+ const s = new SyncSession(store);+ await settle(40);+ ok(leaks(store.doc).length > 0, `${label}: control — the live doc DOES hold its secrets`);+ const snap = (s as unknown as { snapshot: () => { doc: Record<string, unknown>; state: unknown } }).snapshot();+ const readerKey = (collabForReader(store.doc.collab as unknown as Record<string, unknown>) as { key: string }).key;+ const seen = await throughRoom(snap, readerKey) as { doc: Record<string, unknown> };+ ok(!('collab' in seen.doc), `${label}: decrypted with the reader key, the snapshot doc has NO collab block`);+ ok(leaks(seen).length === 0, `${label}: and no ownerPriv / writerPriv / invite anywhere in doc or state (${leaks(seen).join(',') || 'none'})`);+ ok(seen.doc.title === 'shared deck', `${label}: content still rides the snapshot`);+ s.stop?.();+}++H('frame paths: the fork broadcast and the re-snap carry no collab');+{+ // a saved fork file (offline edits + stamped state), on the owner's device+ const base = docWith(COLLABS['v2 owner']);+ const seed = new Store(clone(base));+ const sseed = new SyncSession(seed);+ seed.commit(() => { seed.doc.title = 'forked offline'; });+ await settle();+ (sseed as unknown as { stampInto: (d: unknown) => void }).stampInto(seed.doc);+ sseed.stop?.();+ const forkFile = clone(seed.doc);++ const A = new Store(clone(forkFile));+ const sA = new SyncSession(A);+ const sent: Array<{ t: string; doc?: Record<string, unknown> }> = [];+ sA.addTransport(() => ({ send: (f: { t: string }) => sent.push(f as never), close() {} }) as never);+ // fork broadcast (hello() with forkPending) and a new peer's hello (re-snap)+ (sA as unknown as { hello: () => void }).hello();+ (sA as unknown as { onFrame: (f: unknown) => void }).onFrame({ t: 'hello', a: 'late-tab', vv: {}, p: {}, pv: SYNC_V });+ const snaps = sent.filter((f) => f.t === 'snap');+ ok(snaps.length >= 1, `the fork sent snapshot frames (${snaps.length})`);+ ok(snaps.every((f) => f.doc && !('collab' in f.doc)), 'no snap frame carries a collab block');+ ok(snaps.every((f) => leaks(f).length === 0), 'no snap frame carries ownerPriv / invite material');+ ok(snaps.some((f) => f.doc?.title === 'forked offline'), 'the frames still carry the fork’s content');+ sA.stop?.();++ H('a joiner converges from the stripped snapshot and keeps its own collab');+ const B = new Store(clone(base));+ const sB = new SyncSession(B);+ await settle(40);+ const bCollabBefore = JSON.stringify(B.doc.collab);+ const snap = snaps[snaps.length - 1] as unknown as { doc: unknown; state: unknown };+ (sB as unknown as { applySnapshot: (d: unknown, s: unknown) => void }).applySnapshot(snap.doc, snap.state);+ ok(B.doc.title === 'forked offline', 'the joiner merged the fork’s content');+ ok(JSON.stringify(B.doc.collab) === bCollabBefore, 'the joiner’s own collab is untouched (a stripped key is not a delete)');+ sB.stop?.();+}++H('no stale register: a stripped key never reaches a receiver as a delete');+{+ // A pre-allowlist state may hold a doc-level register for a never-synced+ // field (revisions, emitted by an older client). snapshotDoc() strips the+ // value; the register must go too, or mergeSnapshot reads it as a delete.+ const store = new Store(docWith(COLLABS['v2 owner']));+ (store.doc as unknown as { revisions: unknown }).revisions = [{ id: 'r1', at: 't', body: {} }];+ const s = new SyncSession(store);+ await settle(40);+ const eng = (s as unknown as { state: { regs: Record<string, [number, string]> } }).state;+ eng.regs['@doc revisions'] = [999, 'old-client'];+ const snap = (s as unknown as { snapshot: () => { doc: Record<string, unknown>; state: { regs: Record<string, unknown> } } }).snapshot();+ ok(!('revisions' in snap.doc), 'the snapshot doc drops revisions (a skipDoc field)');+ ok(!('@doc revisions' in (snap.state.regs ?? {})), 'and the snapshot state drops its register');+ const R = new Store(docWith(COLLABS['v2 writer (invitee)']));+ (R.doc as unknown as { revisions: unknown }).revisions = [{ id: 'mine', at: 't', body: {} }];+ const sR = new SyncSession(R);+ await settle(40);+ (sR as unknown as { applySnapshot: (d: unknown, s: unknown) => void }).applySnapshot(snap.doc, snap.state);+ const rRev = (R.doc as unknown as { revisions?: Array<{ id: string }> }).revisions;+ ok(!!rRev && rRev[0]?.id === 'mine', 'the receiver keeps its own revisions (not deleted by a dangling register)');+ s.stop?.(); sR.stop?.();+}++H('every snap frame in session.ts is built by the one helper');+{+ const src = readFileSync(new URL('../kernel/src/sync/session.ts', import.meta.url), 'utf8');+ // every object literal that opens a snap frame+ const frameSites = src.split('\n').filter((l) => /\{ t: 'snap'/.test(l));+ ok(frameSites.length >= 3, `found the snap frame sites (${frameSites.length})`);+ ok(frameSites.every((l) => /snapshotPair\(\)|doc: s\.doc, state: s\.state/.test(l)),+ 'each builds from snapshotPair() or from snapshot() (which returns snapshotPair())');+ ok(/this\.flush\(\)\s*\n\s*return this\.snapshotPair\(\)/.test(src), 'snapshot() returns snapshotPair()');+}++console.log(`\n${checks - failures}/${checks} checks passed`);+process.exit(failures ? 1 : 0);diff --git a/slides/package.json b/slides/package.jsonindex 299b29a6..52b1556a 100644--- a/slides/package.json+++ b/slides/package.json@@ -1,7 +1,7 @@{"name": "bento-slides","private": true,- "version": "1.2.6",+ "version": "1.2.7","license": "MIT","type": "module","scripts": {diff --git a/slides/src/audience.ts b/slides/src/audience.tsindex a72a8985..b47b094c 100644--- a/slides/src/audience.ts+++ b/slides/src/audience.ts@@ -34,6 +34,7 @@* the field names — the boundary is slides' and lives here only.*/import type { BentoDoc, Slide } from './model'+import { stripEnvelope } from './envelope.ts' // .ts: this module stays node-importable for the rigsimport type { Op } from '../../kernel/src/sync/crdt'/** Slide-level fields an audience never receives. Comments are slide-level@@ -69,14 +70,29 @@ function projectSlide(slide: Slide): Slide {if (k === 'notes') out.notes = ''else delete out[k]}+ if (Array.isArray(slide.elements)) out.elements = slide.elements.map(projectElement)return out as unknown as Slide}+/**+ * An embed's `doc` is another deck's JSON, and that deck's ENVELOPE (`collab` —+ * room, read key, private halves — and `docId`) must never reach an audience+ * (envelope.ts: the same rule every other copy applies via stripCollabSecrets).+ * Copy-on-write: the element and its doc are replaced, never edited, because+ * the op this runs on is the same object the presenter sends to the real room.+ */+function projectElement<T>(el: T): T {+ const src = (el as { doc?: unknown } | null)?.doc+ const doc = stripEnvelope(src)+ return doc === src ? el : { ...el, doc }+}+/*** The audience document. Deep-copies; the presenter's doc is untouched.** - every slide (interactive states included) and every custom layout goes- * through `projectSlide`+ * through `projectSlide`, which also strips every embedded document's+ * envelope (`collab` + `docId`)* - `collab` becomes the ticket: same room, `key` = the SHOW key, the* audience invite, role 'reader' (the client's read-only boot path), and no* private halves — `ownerPriv`, `writerPriv` and any writer invite are gone@@ -128,9 +144,12 @@ export function projectDoc(doc: BentoDoc, ticket: AudienceTicket): { doc: BentoD* - a doc-level `set` of a slide-shaped list (`layouts`) → the same op with* every entry projected* - an `ins` of a slide → the same op with the inserted node projected (the- * slide must still arrive — minus its notes and comments)- * - everything else → unchanged. Element ops carry no hidden field; slide- * deletes/orders reveal nothing; doc-level sets have no hidden keys.+ * slide must still arrive — minus its notes and comments, and minus any+ * embedded document's envelope)+ * - an `ins` of an element, or a `set` of an element's `doc` → the embed's+ * document without its envelope (the element still arrives)+ * - everything else → unchanged. Other element ops carry no hidden field;+ * slide deletes/orders reveal nothing; doc-level sets have no hidden keys.*/export function projectOp(op: Op): Op | null {if (op.op === 'set' && op.sl !== undefined && op.el === undefined@@ -141,6 +160,16 @@ export function projectOp(op: Op): Op | null {return { ...op, v: (op.v as Slide[]).map(projectSlide) }}if (op.op === 'ins' && op.kind === 'slide') return { ...op, node: projectSlide(op.node as Slide) }+ // an element inserted mid-show, or an embed's document replaced: the same+ // embedded-envelope rule projectDoc applies through projectSlide+ if (op.op === 'ins' && op.kind === 'element') {+ const node = projectElement(op.node)+ return node === op.node ? op : { ...op, node }+ }+ if (op.op === 'set' && op.el !== undefined && op.k === 'doc') {+ const v = stripEnvelope(op.v)+ return v === op.v ? op : { ...op, v }+ }return op}diff --git a/slides/src/editor/clipboard.ts b/slides/src/editor/clipboard.tsindex 18bac45f..8a68239b 100644--- a/slides/src/editor/clipboard.ts+++ b/slides/src/editor/clipboard.ts@@ -17,6 +17,7 @@import type { BentoDoc, Slide, SlideElement, TextElement } from '../model'import { uid } from '../model'import { firstFamily } from '../fonts'+import { stripEmbeddedEnvelopes } from '../envelope'import { LIMITS, sanitizeAssets, sanitizeElement, sanitizeFonts, sanitizeSlide } from '../untrusted'export interface ClipPayload {@@ -59,11 +60,23 @@ function collectAssets(els: SlideElement[], fonts: NonNullable<BentoDoc['fonts']return out}+/**+ * A deep clone with every embedded document's envelope removed (envelope.ts —+ * the rule every other copy applies). The system clipboard is readable by any+ * app, and a payload pasted into a chat must not carry another deck's room key.+ * The paste side gates the same rule on the way back in.+ */+function cloneForClipboard<T extends { elements: SlideElement[] }>(slides: T[]): T[] {+ const out = JSON.parse(JSON.stringify(slides)) as T[]+ stripEmbeddedEnvelopes({ slides: out } as unknown as BentoDoc)+ return out+}+export function serializeElements(els: SlideElement[], doc: BentoDoc): string {const fonts = fontsFor(els, doc)const payload: ClipPayload = {__bento: 'clip', kind: 'elements',- elements: JSON.parse(JSON.stringify(els)),+ elements: cloneForClipboard([{ elements: els }])[0].elements,assets: collectAssets(els, fonts, doc),fonts,}@@ -75,7 +88,7 @@ export function serializeSlides(slides: Slide[], doc: BentoDoc): string {const fonts = fontsFor(els, doc)const payload: ClipPayload = {__bento: 'clip', kind: 'slides',- slides: JSON.parse(JSON.stringify(slides)),+ slides: cloneForClipboard(slides),assets: collectAssets(els, fonts, doc),fonts,}diff --git a/slides/src/envelope.ts b/slides/src/envelope.tsindex 5649bf89..1a1b3fb5 100644--- a/slides/src/envelope.ts+++ b/slides/src/envelope.ts@@ -20,13 +20,67 @@ export const EMBED_ENVELOPE = ['collab', 'docId'] as constconst isObj = (v: unknown): v is Record<string, unknown> =>typeof v === 'object' && v !== null && !Array.isArray(v)-/** The same object without its envelope — a copy when there is something to- * drop, the input itself when there is not (callers may compare by identity). */+/**+ * How many documents deep an embedded document may nest (the embed's own+ * document is depth 1). A document nested deeper is DROPPED, never kept: past+ * the bound nothing is inspected, so nothing past it may travel.+ */+export const ENVELOPE_MAX_DEPTH = 16++/** Is this object a document of ANY Bento app? (`bento/slides`, `bento/type`, …) */+const isBentoDoc = (v: Record<string, unknown>): boolean =>+ typeof v.format === 'string' && v.format.startsWith('bento/')++const DROP: unique symbol = Symbol('drop')++/**+ * `v` at document depth `depth`; `isDoc` when the caller knows it is a+ * document (the embed's own `doc`, or any object under a `doc` key) whether or+ * not it declares a format. Copy-on-write: returns `v` itself when nothing+ * beneath it changed, a copy along the changed path otherwise, or DROP.+ */+function walk(v: unknown, depth: number, isDoc: boolean): unknown {+ if (Array.isArray(v)) {+ let out: unknown[] | null = null+ for (let i = 0; i < v.length; i++) {+ const w = walk(v[i], depth, false)+ if (w !== v[i] && !out) out = v.slice(0, i)+ if (out && w !== DROP) out.push(w)+ }+ return out ?? v+ }+ if (!isObj(v)) return v+ const doc = isDoc || isBentoDoc(v)+ const here = doc ? depth + 1 : depth+ if (here > ENVELOPE_MAX_DEPTH) return DROP+ let out: Record<string, unknown> | null = null+ if (doc && EMBED_ENVELOPE.some((k) => k in v)) {+ out = { ...v }+ for (const k of EMBED_ENVELOPE) delete out[k]+ }+ for (const k of Object.keys(v)) {+ if (doc && (EMBED_ENVELOPE as readonly string[]).includes(k)) continue+ const w = walk(v[k], here, k === 'doc')+ if (w === v[k]) continue+ out ??= { ...v }+ if (w === DROP) delete out[k]+ else out[k] = w+ }+ return out ?? v+}++/**+ * The embedded document without its envelope — and without the envelope of+ * every document nested inside it, at any depth, of any Bento app: an object is+ * a document when it declares a `bento/…` format or sits under a `doc` key (the+ * embed convention). Documents nested more than ENVELOPE_MAX_DEPTH deep are+ * dropped. Returns the input ITSELF when nothing was removed — callers+ * (audience.ts) detect a change by identity — and a copy along the changed path+ * otherwise; the input is never modified.+ */export function stripEnvelope<T>(v: T): T {- if (!isObj(v) || !EMBED_ENVELOPE.some((k) => k in v)) return v- const copy = { ...v }- for (const k of EMBED_ENVELOPE) delete copy[k]- return copy as T+ const out = walk(v, 0, true)+ return (out === DROP ? undefined : out) as T}/**