Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
slides: adopt the kernel doc-fields allowlist for share copies (last adoption) (#632)
nyblnet3d0987c015f9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 00128c00..5a3b859c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1914,6 +1914,13 @@ jobs:# fresh, revocable invite. Every copy is minted in type/src/share.ts.run: node scripts/test-type-share.ts+ - name: Slides share-copy rig+ # The view-only and editor copies (slides/src/share.ts) carry only the+ # kernel allowlist — no private key, a fresh invite, no sync on a reader —+ # and strip any EMBEDDED document's envelope. Runs the real builders with+ # real keys through the ts hook, like the type rig above.+ run: node scripts/test-slides-share.ts+- name: Type chrome rig# Where controls live: nothing in two menus, no inserts in the# overflow, and every element the chrome reaches for actually exists —diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.tsindex 1e688cd4..c007b0b7 100644--- a/scripts/test-export-secrets.ts+++ b/scripts/test-export-secrets.ts@@ -229,7 +229,10 @@ console.log('\nexports')// Everything that hands the document to somebody else. Named rather than// discovered so that a DELETED strip and a deleted export do not look alike.-const EXPORTS = ['savePresentationPackage', 'saveReaderCopy', 'saveEditorCopy', 'saveAsTemplate', 'copyDocJson']+// The DROP-THE-WHOLE-BLOCK exports still strip. saveReaderCopy/saveEditorCopy+// moved to the kernel allowlist (slides/src/share.ts) — they delegate now and are+// guarded below, not here.+const EXPORTS = ['savePresentationPackage', 'saveAsTemplate', 'copyDocJson']for (const name of EXPORTS) {ok(/stripCollabSecrets\(/.test(body(name)),`${name}() strips the session before the copy leaves`)@@ -238,19 +241,20 @@ for (const name of EXPORTS) {ok(!/writeText\(JSON\.stringify\(this\.store\.doc\)/.test(body('copyDocJson')),'copyDocJson() copies a stripped CLONE, never the live document')-// The invite copy (slides' "Invite to edit…", saveEditorCopy) keeps the room and-// adds a scoped invite. Calling the stripper is not enough — it must run FIRST:-// stripped after the invite is minted, nothing is lost, but stripped never (or-// re-attached after) and the deck's own writerPriv/ownerPriv travel beside the-// invite — a second way in that the People list cannot revoke. The same order-// SHARE_APPS pins for spaces' share.ts below; slides mints its copies from-// editor.ts methods rather than a share module, so it is pinned here.+// slides' reader/invite copies now come from the kernel allowlist via+// slides/src/share.ts (readerCopy/inviteCopy) — behaviour is run in+// scripts/test-slides-share.ts. The editor METHODS must DELEGATE to them and build+// no collab of their own: a re/introduced inline `clone.collab = { ...c }` or a+// keepRoom strip would be the bypass.{+ const reader = mask(body('saveReaderCopy'))const inv = mask(body('saveEditorCopy'))- const strip = inv.search(/stripCollabSecrets\(\s*clone\s*,\s*\{\s*keepRoom:\s*true\s*\}\s*\)/)- const mint = inv.indexOf('mintInvite(')- ok(strip >= 0 && mint >= 0 && strip < mint,- 'saveEditorCopy() strips the clone (keepRoom) BEFORE it mints the scoped invite')+ ok(/\breaderCopy\(/.test(reader), 'saveReaderCopy() delegates to share.ts readerCopy()')+ ok(/\binviteCopy\(/.test(inv), 'saveEditorCopy() delegates to share.ts inviteCopy()')+ ok(!/\.collab\s*=\s*\{/.test(reader) && !/\.collab\s*=\s*\{/.test(inv),+ 'neither editor method rebuilds collab inline — it comes only from the share helper')+ ok(!/stripCollabSecrets\(/.test(reader) && !/stripCollabSecrets\(/.test(inv),+ 'neither uses the keepRoom stripper any more (the allowlist replaced it)')}// The audience copy (live broadcast) is the one export that does NOT go@@ -473,15 +477,16 @@ function exportedBody(src: string, name: string): string {return src.slice(open, i + 1)}-// spaces and type both mint copies through the kernel ALLOWLIST-// (collabForReader / collabForInvite) now. Their builders are proven BEHAVIOURALLY-// in scripts/test-spaces-invite.ts and scripts/test-type-share.ts (bundled via-// esbuild, running the real functions); this rig runs under strip-only node and-// cannot import a file with a parameter property, so for each it keeps a SOURCE-// guard: the builders route through the kernel helpers and reintroduce neither the-// delete-stripper nor a spread-the-source bypass. The cross-app "no builder-// bypasses" row lands with the slides adoption (the last one).-for (const app of ['spaces', 'type']) {+// spaces, type and slides mint copies through the kernel ALLOWLIST+// (collabForReader / collabForInvite) from a share.ts. Their builders are proven+// BEHAVIOURALLY in scripts/test-{spaces-invite,type-share,slides-share}.ts (bundled+// via esbuild / the ts hook, running the real functions); this rig runs under+// strip-only node and cannot import a file with a parameter property, so for each+// it keeps a SOURCE guard: the builders route through the kernel helpers and+// reintroduce neither the delete-stripper nor a spread-the-source bypass. (dash's+// builders live in sync/online.ts — its own guard is below. The cross-app sweep+// that no builder in ANY app bypasses the allowlist follows it.)+for (const app of ['spaces', 'type', 'slides']) {const rel = `${app}/src/share.ts`const src = read(rel)ok(!/stripCollabSecrets/.test(src), `${rel}: the delete-based stripper is gone — the kernel allowlist replaces it`)@@ -537,10 +542,65 @@ for (const app of ['spaces', 'type']) {`${rel}: neither builder rebuilds collab by spreading the source — only a collabFor* projection`)ok(!/\.\.\.rest\b/.test(readerFn) && !/\.\.\.rest\b/.test(inviteFn),`${rel}: neither builder uses a destructure-rest denylist`)- // a non-owner early-return must NOT hand back the un-projected source block- // (`return collab`) — that leaks everything; refuse with `return null` instead.- ok(!/\breturn collab\b/.test(inviteFn),- `${rel}: inviteCopy never returns the source block unchanged (null for a non-owner)`)+ // Judge the RETURNS structurally (as the spread check judges spreads): every+ // return must be a collabFor* projection or null — so a non-owner early return+ // of the source block reds the guard EVEN WHEN ALIASED (`const c2 = collab;+ // return c2`), which a literal `return collab` match would miss.+ const badReturn = /\breturn\s+(?!null\b)(?![^\n;]*collabFor)[^\n;]/+ ok(!badReturn.test(readerFn) && !badReturn.test(inviteFn),+ `${rel}: every return is a collabFor* projection or null — never the source block, even aliased`)+}++// Cross-app sweep: every app now mints its share copies through the kernel+// allowlist, so assert as ONE family that NO builder in ANY app bypasses it — a+// new or regressed builder cannot quietly carry the room. Each must route through a+// collabFor* helper and spread no source. (The share.ts apps RETURN the doc clone+// `out`; dash returns the collab, so its early-return-of-source judge is in the+// dash block above.)+{+ const BUILDERS: ReadonlyArray<readonly [string, readonly string[]]> = [+ ['spaces/src/share.ts', ['readerCopy', 'inviteCopy']],+ ['type/src/share.ts', ['readerCopy', 'inviteCopy']],+ ['slides/src/share.ts', ['readerCopy', 'inviteCopy']],+ ['dash/src/sync/online.ts', ['readerCopy', 'inviteCopy']],+ ]+ let bypasses = 0+ for (const [rel, fns] of BUILDERS) {+ const src = read(rel)+ for (const fn of fns) {+ const b = mask(exportedBody(src, fn))+ const routed = /collabFor(Reader|Invite)\(/.test(b)+ const spread = /\{\s*\.\.\.(?!collabFor)/.test(b)+ if (!b || !routed || spread) { bypasses++; console.log(` (bypass: ${rel} ${fn})`) }+ }+ }+ ok(bypasses === 0,+ 'no copy builder in any app bypasses the kernel allowlist — all route through collabFor* and spread no source')+}++// Embedded documents: a doc can EMBED another bento document inside it, and that+// inner document carries its own room keys. A reader/invite copy must strip the+// inner document's envelope or the copy leaks the inner room. This is the strip+// the slides extraction briefly lost; pin it by source so it can't be dropped+// again, across every app that embeds. (Reader + invite builders only.)+{+ // slides embeds (el.doc) and its builders clone through the embedded-document+ // strip — the behaviour is run in scripts/test-slides-share.ts.+ const s = read('slides/src/share.ts')+ const slidesStrips = /stripEmbeddedEnvelopes\(/.test(mask(s))+ && /\bcloneForShare\(/.test(mask(exportedBody(s, 'readerCopy')))+ && /\bcloneForShare\(/.test(mask(exportedBody(s, 'inviteCopy')))+ ok(slidesStrips, 'slides: reader and invite copies strip the embedded document (via cloneForShare)')++ // type ALSO embeds (type/src/embed.ts); #633 makes every share copy embed-safe by+ // cloning through withoutEmbeddedCaps, so a source embed (older file, pasted JSON)+ // is scrubbed, not only embed.ts's intake path. (Behaviour is run in+ // scripts/test-type-share.ts.)+ const ty = read('type/src/share.ts')+ ok(/withoutEmbeddedCaps\(/.test(mask(ty))+ && /\bclone\(/.test(mask(exportedBody(ty, 'readerCopy')))+ && /\bclone\(/.test(mask(exportedBody(ty, 'inviteCopy'))),+ 'type: reader and invite copies scrub embedded documents (clone through withoutEmbeddedCaps, #633)')}// --- the OTHER half of the round trip: pasting one back in -------------------diff --git a/scripts/test-slides-share.ts b/scripts/test-slides-share.tsnew file mode 100644index 00000000..9e604f0c--- /dev/null+++ b/scripts/test-slides-share.ts@@ -0,0 +1,105 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/slides share-copy rig — what a view-only / editor copy carries, run+// against the REAL builders (slides/src/share.ts) with real WebCrypto keys.+//+// node scripts/test-slides-share.ts+//+// slides is SHIPPED, so reader/invite are held to the same behavioural bar as+// spaces/type/dash: build every copy from ONE source carrying every known secret,+// an unknown field and a JSON own __proto__ key, and prove only the kernel+// allowlist survives. The builders were extracted out of editor.ts so this rig can+// import and run them (editor.ts has DOM at module scope and cannot load in node);+// scripts/test-export-secrets.ts still source-guards the editor call sites.++import { register } from 'node:module'+register('./lib/ts-resolve-hooks.mjs', import.meta.url)+const { readerCopy, inviteCopy } = await import('../slides/src/share.ts')+const { newDoc } = await import('../slides/src/model.ts')+const { mintCollab } = await import('../kernel/src/sync/online.ts')+import type { BentoDoc } from '../slides/src/model.ts'++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }++console.log('every builder, from one poisoned source\n')+{+ const base = await mintCollab() as Record<string, unknown> // real room/owner keys, so inviteCopy can sign+ const poisoned = newDoc()+ const pc = JSON.parse('{"__proto__":{"polluted":true}}') as Record<string, unknown>+ Object.assign(pc, base, {+ writerPriv: 'WPRIV',+ invite: { pub: 'SRC', priv: 'SRCPRIV', role: 'writer', sig: 's' },+ audience: { invite: { priv: 'APRIV' } },+ sync: { v: 2, tag: 'stamp' }, links: [{ url: 'https://pub' }], futureSecret: 'LEAK',+ })+ ;(poisoned as unknown as { collab: unknown }).collab = pc++ const READER_KEYS = ['room', 'key', 'owner', 'writerPub', 'on', 'v', 'role']+ const INVITE_KEYS = ['room', 'key', 'owner', 'writerPub', 'on', 'v', 'sync', 'invite', 'role']+ const POISON = ['writerPriv', 'ownerPriv', 'audience', 'futureSecret', 'links']++ const rc = readerCopy(poisoned).collab as unknown as Record<string, unknown>+ const ic = (await inviteCopy(poisoned, base.ownerPriv as string)).collab as unknown as Record<string, unknown>++ ok(Object.keys(rc).every((k) => READER_KEYS.includes(k)),+ `reader copy: ONLY reader-allowlist keys survive (${Object.keys(rc).sort().join(',')})`)+ ok(rc.role === 'reader', 'reader copy: role forced to reader (opens locked)')+ ok(rc.sync === undefined, 'reader copy: the CRDT sync stamp is dropped')+ ok(Object.keys(ic).every((k) => INVITE_KEYS.includes(k)),+ `invite copy: ONLY invite-allowlist keys survive (${Object.keys(ic).sort().join(',')})`)+ ok(ic.sync !== undefined, 'invite copy: keeps the sync stamp (it contributes)')+ ok((ic.invite as { pub: string }).pub !== 'SRC', 'invite copy: the delegation is FRESH, never the source invite')+ ok(ic.role === 'writer', 'invite copy: top-level role from the fresh writer invite (opens editable)')+ for (const f of POISON) { ok(!(f in rc), `reader drops ${f}`); ok(!(f in ic), `invite drops ${f}`) }+ ok(!Object.hasOwn(rc, '__proto__') && !Object.hasOwn(ic, '__proto__'), 'neither copy carries a __proto__ own key')+ ok(({} as Record<string, unknown>).polluted === undefined, 'and the __proto__ source key polluted nothing (Object.hasOwn)')++ // the planted bypass: rebuilding collab by SPREADING the source keeps every+ // secret; the exact-key-set check above is what turns that red.+ const bypass = { ...pc, role: 'reader' } as Record<string, unknown>+ ok('writerPriv' in bypass && !Object.keys(bypass).every((k) => READER_KEYS.includes(k)),+ 'a spread-the-source bypass FAILS the reader key-set check (not vacuous)')++ // the open document is untouched (the builders clone)+ ok((poisoned as unknown as { collab: Record<string, unknown> }).collab.ownerPriv !== undefined,+ 'the open document is untouched — the builders clone, never mutate it')+}++// A slides deck can EMBED another bento document inside an element (el.doc). That+// inner document carries its own collab, so a copy must strip it — the extracted+// builders keep the embedded-document strip the old inline path ran.+console.log('\nembedded documents are stripped from every copy\n')+{+ const base = await mintCollab() as Record<string, unknown>+ const SECRET = { ownerPriv: 'OWNER-PRIV', writerPriv: 'WRITER-PRIV', key: 'ROOM-KEY', room: 'ROOM-ID',+ invite: { pub: 'i', priv: 'INVITE-PRIV', role: 'writer', sig: 's' } }+ const inner = () => ({ title: 'inner', slides: [{ id: 'x' }], docId: 'INNER-DOCID', collab: JSON.parse(JSON.stringify(SECRET)) })+ const NEEDLES = ['OWNER-PRIV', 'WRITER-PRIV', 'INVITE-PRIV', 'ROOM-KEY', 'ROOM-ID', 'INNER-DOCID']+ const leaks = (o: unknown) => NEEDLES.filter((n) => JSON.stringify(o).includes(n))+ const withEmbed = () => {+ const d = newDoc()+ ;(d as unknown as { collab: unknown }).collab = JSON.parse(JSON.stringify(base))+ d.slides[0].elements = [{ id: 'e1', type: 'embed', x: 0, y: 0, w: 1, h: 1, app: 'web', doc: inner() } as never]+ return d+ }+ const r = readerCopy(withEmbed())+ ok(leaks(r).length === 0, `view-only copy strips the embedded document's secrets (${leaks(r).join(',') || 'clean'})`)+ const iv = await inviteCopy(withEmbed(), base.ownerPriv as string)+ ok(leaks(iv).length === 0, `editor copy strips the embedded document's secrets (${leaks(iv).join(',') || 'clean'})`)+ const keptDoc = (r.slides[0].elements[0] as unknown as { doc: { title?: string } }).doc+ ok(keptDoc.title === 'inner', 'and the embedded content itself survives (only its envelope goes)')+}++// FROM_LIVE now imports the kernel superset, which carries `template`. That is a+// no-op for slides: template is written only on the Save-as-template clone, never+// on a live editing doc — so there is never a live value to keep. Pin the invariant.+console.log('\nthe FROM_LIVE superset is a no-op for a live slides doc\n')+{+ ok((newDoc() as unknown as { template?: unknown }).template === undefined,+ 'a fresh/live slides doc carries no template, so keeping it live changes nothing')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex e7f8f626..e97d4b54 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -38,6 +38,7 @@ import { availablePacks, fetchPack, markFileSaved, packCoverage, packsInFile, stimport { injectFonts } from '../fonts'import { appConfig } from '../../../kernel/src/app.ts'import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, mintRoomKey, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'+import { readerCopy, inviteCopy } from '../share'import { projectDoc, projectOp, type AudienceTicket } from '../audience'import { stripEmbeddedEnvelopes } from '../envelope'import { compactJson } from '../compact'@@ -1145,9 +1146,7 @@ export class Editor {this.toast(t('This deck has no live session to follow'))return}- const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc- clone.collab = { ...c, role: 'reader', on: true, sync: undefined }- stripCollabSecrets(clone, { keepRoom: true })+ const clone = readerCopy(this.store.doc)try {const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'viewonly' })if (ok) this.toast(t('Read-only copy saved — it follows the live session, view only'))@@ -1170,14 +1169,11 @@ export class Editor {}this.canvas.commitTextEdit()this.session?.stampInto(this.store.doc) // copies rejoin as true forks- const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc- // Strip FIRST, then delegate: the invite is the only private material an- // editor copy is allowed to carry. A v2 room is verified through the- // owner→invite→member chain, so a stray `writerPriv` (room-wide write key- // from a pre-v2 mint) would be a second, UNREVOKABLE way in.- stripCollabSecrets(clone, { keepRoom: true })- clone.collab!.invite = await mintInvite(c.ownerPriv, 'writer')- clone.collab!.on = true+ // The invite is the only private material an editor copy may carry: the kernel+ // allowlist (share.ts inviteCopy) drops every private half AND a legacy+ // writerPriv, then attaches a FRESH owner-signed invite and takes the role from+ // it — a v2 room is verified through the owner→invite→member chain.+ const clone = await inviteCopy(this.store.doc, c.ownerPriv)try {const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'invite' })if (ok) this.toast(t('Editor copy saved — recipients join live with edit access'))diff --git a/slides/src/restoregate.ts b/slides/src/restoregate.tsindex f132029c..d0356b7e 100644--- a/slides/src/restoregate.ts+++ b/slides/src/restoregate.ts@@ -26,13 +26,17 @@import { MODEL_KEYS } from './modelkeys.generated'import { FORMAT, parseDoc, type BentoDoc, type Slide } from './model'import { LIMITS, SLIDE_CHECKS, sanitizeAssets, sanitizeFonts, sanitizeSlide, withDropReport, withPathSegment, type Dropped } from './untrusted'+import { FROM_LIVE } from '../../kernel/src/docfields.ts'const DOC_KEYS = new Set<string>(MODEL_KEYS.doc)-/** identity and capability: always the open file's, never the snapshot's. Shared+/** Identity and capability: always the open file's, never the snapshot's. Shared* with the Store's undo/redo (store.ts restore()), which keeps the same set live* so Cmd-Z never resurrects an old docId, a stale sharing flag, or a dropped- * read-only mode. */-export const FROM_LIVE = ['docId', 'collab', 'readonly'] as const+ * read-only mode. Now the kernel list, re-exported here. Its extra `template` is a+ * no-op for slides: template is written only on the Save-as-template clone, never+ * on a live editing doc, so there is never a live value to keep — the snapshot's+ * template is dropped exactly as before (pinned by a rig). */+export { FROM_LIVE }const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)diff --git a/slides/src/share.ts b/slides/src/share.tsnew file mode 100644index 00000000..fdeb55eb--- /dev/null+++ b/slides/src/share.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// SHARE COPIES — the documents bento/slides writes for someone ELSE to open: a+// view-only reader ("Read-only copy…") and an editor invite ("Editor copy…").+// Extracted from the Editor so they are DOM-free and the copy that ships is the+// copy the rig inspects (scripts/test-slides-share.ts runs these with real keys).+//+// Both go through the kernel ALLOWLIST (kernel/src/docfields.ts): a copy keeps+// only what is on the list, so a new field in `collab` — private or not — fails+// CLOSED. The reader forces role:'reader' and drops every private half AND the+// sync stamp; the invite keeps the stamp, carries a FRESH owner-signed invite and+// takes its top-level role FROM that invite. Neither rebuilds collab by spreading+// the source. The audience projection (audience.ts) is a separate tier and is NOT+// built here; the drop-the-whole-block exports (template, package, Copy JSON) drop+// the collab block entirely in editor.ts.++import { mintInvite } from './sync/online'+import { stripEmbeddedEnvelopes } from './envelope'+import { collabForReader, collabForInvite } from '../../kernel/src/docfields.ts'+import type { BentoDoc } from './model'++/** A deep clone with the EMBEDDED-document strip applied, so neither a copy's own+ * collab (handled below by the allowlist) nor any document embedded inside it can+ * carry a capability or secret out. A deep clone first, so nothing done to the+ * copy reaches the open document. */+const cloneForShare = (doc: BentoDoc): BentoDoc => {+ const out = JSON.parse(JSON.stringify(doc)) as BentoDoc+ stripEmbeddedEnvelopes(out)+ return out+}++/**+ * A VIEW-ONLY copy: follows the live session and never writes. Keeps the room,+ * the read key and the public keys; forced to role:'reader'; loses every private+ * half, the sync stamp and anything unknown — the relay drops whatever it sends.+ */+export function readerCopy(doc: BentoDoc): BentoDoc {+ const out = cloneForShare(doc)+ out.collab = { ...collabForReader(out.collab!), on: true } as BentoDoc['collab']+ return out+}++/**+ * An EDITOR copy: joins live with edit access through its own owner-signed invite,+ * which the owner can revoke. The allowlist keeps room/read-key/public keys + the+ * sync stamp and drops every private half; the fresh invite and the top-level role+ * come from mintInvite, never from the source — so a legacy writer key or a source+ * invite can never ride along.+ */+export async function inviteCopy(doc: BentoDoc, ownerPriv: string): Promise<BentoDoc> {+ const out = cloneForShare(doc)+ const invite = await mintInvite(ownerPriv, 'writer')+ out.collab = { ...collabForInvite(out.collab!, invite), on: true } as BentoDoc['collab']+ return out+}