Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: an embed keeps the source document, never its capabilities (#633)
nyblnet10195a8f206f
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 32ca1910..b67751c6 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -8030,3 +8030,24 @@ does the work — with legitimate `.pptx`/`.xlsx` imports unaffected. Rule: asize limit must be enforced DURING decompression, never after; the declaredsize in a container header is an attacker input, and the primitive, not thecaller's preflight, must hold the ceiling.++## 2026-10-05 — An embed keeps the source document, never its capabilities (type)++**An embedded document's `collab` block — that document's sharing keys — does+not travel with it, in or out of bento/type.** An `embed` block carries a copy+of another Bento document so a reader can open the original; that copy keeps+its content and `docId` and loses the kernel's capability fields+(`CAP_FIELDS` / `withoutCaps`, kernel/src/docfields.ts), at every depth of+bento/type's own embed blocks (the kernel helper is shallow, and an embedded+bento/type document can hold embeds of its own).++Applied where a document comes in and wherever it goes out:+- **in** — `readArtifact` (embedding a file) and `parseDoc` (opening a file,+ Replace from JSON, `loadDoc`, a restored snapshot);+- **out** — the view-only and editor share copies, "Copy document JSON"+ (`docForExport`), Save, and the browser's recovery and version snapshots.++Both ends, because an embed can reach the live document by a path neither end+sees alone (a peer's sync op, a document stored before intake was scrubbed).+A document's OWN `collab` is untouched by any of this; that is the file's.+`test-type-embed.ts`, `test-type-share.ts` and `test-export-secrets.ts` pin it.diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.tsindex 067bf2a6..1e688cd4 100644--- a/scripts/test-export-secrets.ts+++ b/scripts/test-export-secrets.ts@@ -388,8 +388,33 @@ for (const app of CLIP_APPS) {try { src = read(`${app}/src/model.ts`) } catch { continue }if (!/docForExport/.test(src)) continueconst body = src.slice(src.indexOf('export function docForExport'))- ok(/\.\.\.rest|delete .*collab|const \{ collab/.test(body.slice(0, 400)),+ // A docForExport that delegates to the kernel's shared scrubber is checked+ // THROUGH it: the rule is how capabilities leave, not which file spells it.+ const delegated = /withoutCaps\(/.test(body.slice(0, 160)) && /from '\.\.\/\.\.\/kernel\/src\/docfields\.ts'/.test(src)+ const stripper = delegated ? read('kernel/src/docfields.ts').slice(read('kernel/src/docfields.ts').indexOf('export function withoutCaps')) : body+ ok(/\.\.\.rest|delete .*collab|const \{ collab|delete out\[k\]/.test(stripper.slice(0, 400)),`${app}/src/model.ts: docForExport strips by REMOVING collab, not by listing fields to keep`)+ if (delegated) {+ ok(/CAP_FIELDS\s*=\s*\[[^\]]*'collab'/.test(read('kernel/src/docfields.ts')),+ `${app}: the kernel's CAP_FIELDS — the one shared list — names collab`)+ }+}++// EMBEDDED documents. bento/type's embed block carries a copy of another+// document; its sharing keys must neither come in (intake) nor go out (every+// path a document leaves by). Read from source, like the checks above.+{+ let model = '', embed = '', share = ''+ try { model = read('type/src/model.ts'); embed = read('type/src/embed.ts'); share = read('type/src/share.ts') } catch { /* no type */ }+ if (embed) {+ const fn = embed.slice(embed.indexOf('export function readArtifact'))+ ok(/return \{[^}]*doc:\s*embedSafe\(/.test(fn.slice(0, fn.indexOf('\n}') + 2)),+ 'type/src/embed.ts: readArtifact keeps the source document only through embedSafe — embedded documents don\'t carry sharing keys in')+ ok(/return withoutEmbeddedCaps\(withoutCaps\(doc\)\)/.test(model),+ 'type/src/model.ts: docForExport also strips embedded documents\' keys')+ ok(/const clone = \(doc: TypeDoc\): TypeDoc => withoutEmbeddedCaps\(/.test(share),+ 'type/src/share.ts: every share copy is built from an embed-safe clone')+ }}// ---------------------------------------------------------------------------diff --git a/scripts/test-type-embed.ts b/scripts/test-type-embed.tsindex 233d936a..e14233fc 100644--- a/scripts/test-type-embed.ts+++ b/scripts/test-type-embed.ts@@ -91,5 +91,34 @@ console.log('\n— a file with no preview still embeds —');ok(e!.view.includes('Bento Slides'), 'and says which app it came from');}+console.log('\n— embedded documents don\'t carry sharing keys —');+{+ // The source document's collab block is that document's sharing keys: the+ // room's read key and, in a writer's or owner's copy, private keys and an+ // invite. Embedding copies the source document into ours; it must arrive+ // without them.+ const ENVELOPE = { on: true, room: 'w123', key: 'READ-KEY', owner: 'OWNER-PUB', ownerPriv: 'OWNER-KEY',+ writerPub: 'WRITER-PUB', writerPriv: 'WRITER-KEY', invite: { pub: 'IP', priv: 'INVITE-KEY', role: 'writer', sig: 'S' } };+ const SECRETS = ['READ-KEY', 'OWNER-KEY', 'WRITER-KEY', 'INVITE-KEY'];+ const shell = (doc: object) => '<script id="bento-doc">' + JSON.stringify(doc) + '</script>';++ const e = readArtifact(shell({ format: 'bento/slides', docId: 's9', title: 'Roadmap', collab: ENVELOPE }));+ const blob = JSON.stringify(e!.doc);+ for (const secret of SECRETS) ok(!blob.includes(secret), `the ${secret} does not survive intake`);+ ok(!('collab' in (e!.doc as object)), 'the whole collab block is gone, not just its keys');+ ok((e!.doc as { title?: string }).title === 'Roadmap', 'while the document itself is intact');+ ok((e!.doc as { docId?: string }).docId === 's9', 'and docId is KEPT — it names the source, and is not a capability');++ // NESTED: an embedded bento/type document can carry embeds of its own. The+ // kernel's withoutCaps is shallow, so this is the case it alone would miss.+ const inner = { format: 'bento/slides', docId: 'deck-1', collab: ENVELOPE };+ const middle = { format: 'bento/type', docId: 'type-2', collab: ENVELOPE,+ body: [{ id: 'e', kind: 'embed', text: '', embed: { app: 'bento/slides', view: '<svg/>', doc: inner } }] };+ const n = readArtifact(shell(middle));+ const nblob = JSON.stringify(n!.doc);+ ok(SECRETS.every(x => !nblob.includes(x)), 'an embed INSIDE an embedded document arrives without its keys too');+ ok(nblob.includes('deck-1'), 'and the inner document is still there to open');+}+console.log(`\n${checks - bad}/${checks} checks passed`);if (bad) process.exit(1);diff --git a/scripts/test-type-share.ts b/scripts/test-type-share.tsindex 7d334f30..e0c0aa5f 100644--- a/scripts/test-type-share.ts+++ b/scripts/test-type-share.ts@@ -26,7 +26,7 @@ import { register } from 'node:module'import { readFileSync } from 'node:fs'register('./lib/ts-resolve-hooks.mjs', import.meta.url)const { readerCopy, inviteCopy } = await import('../type/src/share.ts')-const { emptyDoc, parseDoc } = await import('../type/src/model.ts')+const { emptyDoc, parseDoc, docForExport } = await import('../type/src/model.ts')const { mintCollab } = await import('../kernel/src/sync/online.ts')import type { TypeDoc } from '../type/src/model.ts'@@ -135,5 +135,57 @@ console.log('\nevery copy is minted in share.ts\n')ok(rogue.length === 0, `no copy builder outside share.ts sets a reader/audience role (${rogue.join(', ') || 'none'}) — type builds no audience copies at all`)}+console.log('\nembedded documents don\'t carry sharing keys out\n')+{+ // An embed's copy of its source document, carrying that document's FULL+ // sharing envelope plus its docId. It is put onto the live body DIRECTLY —+ // not through parseDoc, which now cleans embeds on entry — because the point+ // is a document that reached the live file by another path (a peer's sync op,+ // anything pre-dating the intake scrub). Built through parseDoc, the rows+ // below would pass whether or not the outbound strip existed.+ const ENV = { v: 2, on: true, room: 'w-src', key: 'SRC-READ-KEY', owner: 'SRC-OWNER-PUB', ownerPriv: 'SRC-OWNER-KEY',+ writerPub: 'SRC-WRITER-PUB', writerPriv: 'SRC-WRITER-KEY', invite: { pub: 'SRC-INV-PUB', priv: 'SRC-INVITE-KEY', role: 'writer', sig: 'S' } }+ const SECRETS = ['SRC-READ-KEY', 'SRC-OWNER-KEY', 'SRC-WRITER-KEY', 'SRC-INVITE-KEY']+ const withDirtyEmbed = async (): Promise<TypeDoc> => {+ const r = parseDoc(JSON.stringify({ ...emptyDoc(), body: [{ id: 'p1', kind: 'para', text: 'see the deck' }],+ collab: await mintCollab() }))+ if (!r.ok) throw new Error('fixture did not parse')+ r.doc.body.push({ id: 'e1', kind: 'embed', text: '',+ embed: { app: 'bento/slides', view: '<svg/>', doc: { format: 'bento/slides', docId: 'deck-SRC', title: 'Q3', collab: ENV } } } as never)+ return r.doc+ }+ const embedded = (d: TypeDoc) => (d.body.find(b => b.kind === 'embed') as { embed: { doc: Record<string, unknown> } }).embed.doc+ const clean = (d: TypeDoc) => { const b = JSON.stringify(d.body); return SECRETS.every(x => !b.includes(x)) }++ const src = await withDirtyEmbed()+ ok(!clean(src), 'the fixture really holds an embed carrying a full sharing envelope')++ const r = readerCopy(src)+ ok(clean(r) && !('collab' in embedded(r)), 'a VIEW-ONLY copy carries none of the embedded document\'s keys')+ ok(embedded(r).docId === 'deck-SRC' && embedded(r).title === 'Q3', 'while the embedded document and its docId are kept')++ const own = (await mintCollab()).ownerPriv as string+ const i = await inviteCopy(src, own)+ ok(clean(i) && !('collab' in embedded(i)), 'an EDITOR copy carries none of them either')++ const x = docForExport(src)+ ok(clean(x) && !('collab' in embedded(x)), '"Copy document JSON" (docForExport) carries none of them')+ ok(!('collab' in x), 'and still drops the document\'s own room, as it always has')++ ok(!clean(src) && 'collab' in embedded(src), 'none of the three mutated the OPEN document')++ // Entry: a document arriving through parseDoc (open, Replace from JSON,+ // loadDoc, restore) comes in with its embeds already clean.+ const entering = parseDoc(JSON.stringify({ ...emptyDoc(), body: [{ id: 'e1', kind: 'embed', text: '',+ embed: { app: 'bento/slides', view: '<svg/>', doc: { format: 'bento/slides', docId: 'deck-SRC', collab: ENV } } }] }))+ ok(entering.ok && clean(entering.doc), 'a document ENTERING bento/type has its embeds cleaned on the way in')++ // Leaving to disk: Save and the browser snapshots go through the same strip.+ const main = read('type/src/main.ts'), auto = read('type/src/autosave.ts')+ ok(/saveFile\(withoutEmbeddedCaps\(store\.doc\)/.test(main), 'Save writes the document with its embeds cleaned')+ ok(/putRecovery\(safe\)/.test(auto) && /addVersion\(safe\)/.test(auto) && /const safe = withoutEmbeddedCaps\(doc\)/.test(auto),+ 'and so do the recovery snapshot and the version history, which any local page can read')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/type/src/autosave.ts b/type/src/autosave.tsindex 9f707779..6aac1bcb 100644--- a/type/src/autosave.ts+++ b/type/src/autosave.ts@@ -35,7 +35,7 @@ import {} from '../../kernel/src/autosave.ts';import { canonicalize } from './canon.ts';import { registerReady, type FeatureContext } from './features.ts';-import type { TypeDoc } from './model.ts';+import { withoutEmbeddedCaps, type TypeDoc } from './model.ts';import { gateRestored } from './restoregate.ts';import { t } from './i18n.ts';@@ -90,11 +90,14 @@ async function runAutosave(ctx: FeatureContext): Promise<void> {// put a legible copy on disk beside a file whose whole purpose is that it// is not legible. See canSnapshot() above.if (!canSnapshot()) return;- const stored = await putRecovery(doc);+ // A snapshot lands in IndexedDB, which on file:// any local page can read —+ // so embeds go in without another document's sharing keys.+ const safe = withoutEmbeddedCaps(doc);+ const stored = await putRecovery(safe);if (!stored) return; // no usable IndexedDB here (private browsing, some file:// contexts)if (Date.now() - lastVersionAt > VERSION_THROTTLE_MS) {lastVersionAt = Date.now();- await addVersion(doc);+ await addVersion(safe);}}diff --git a/type/src/embed.ts b/type/src/embed.tsindex 4ec683b7..dc271b56 100644--- a/type/src/embed.ts+++ b/type/src/embed.ts@@ -26,7 +26,7 @@// every renderer in every file to cover the matrix, and version skew between// the embedded copy and the real app.-import { uid, type Block } from './model.ts';+import { uid, embedSafe, type Block } from './model.ts';import { t } from './i18n.ts';import { registerTool, type FeatureContext } from './features.ts';@@ -227,7 +227,13 @@ export function readArtifact(html: string): EmbedData | null {// to show without running anything.const still = PREVIEW.exec(html);const view = still && safeView(still[1]) ? still[1] : fallbackView(app);- return { app, view, doc: parsed };+ // The source document rides along so a reader can open the original — but+ // never its capabilities. embedSafe (model.ts) removes the CAP_FIELDS of the+ // shared kernel list (kernel/src/docfields.ts) — today `collab`: the source+ // room's read key and any private keys a writer's or owner's copy holds —+ // and does the same inside any embeds that document carries. docId is kept:+ // it names the source so a reader can open it, and is not a capability.+ return { app, view, doc: embedSafe(parsed) };}/** When a file carries no preview, the embed still says what it is. */diff --git a/type/src/main.ts b/type/src/main.tsindex 7a8f2d4b..725134d9 100644--- a/type/src/main.ts+++ b/type/src/main.ts@@ -17,7 +17,7 @@ import './registry.ts'; // side-effect: every feature module registers itselfimport { i18nApi } from '../../kernel/src/i18n.ts';import { openAbout } from './about.ts';import { startTheme, setTheme, themeChoice, type ThemeChoice } from '../../kernel/src/theme.ts';-import { parseDoc, emptyDoc, uid, wordCount, type TypeDoc } from './model.ts';+import { parseDoc, emptyDoc, uid, wordCount, withoutEmbeddedCaps, type TypeDoc } from './model.ts';import { gateRestored } from './restoregate.ts';import { Store } from './store.ts';import { Editor } from './editor.ts';@@ -933,7 +933,10 @@ function paintTitle() {}async function save(forcePicker = false) {- const result = await saveFile(store.doc, forcePicker);+ // Embeds leave this file without their sharing keys even if one reached the+ // live document by a path parseDoc never saw (a peer's sync op). The+ // document's OWN collab is kept — it is this file's.+ const result = await saveFile(withoutEmbeddedCaps(store.doc), forcePicker);if (result === 'cancelled') return;dirty = false;paintTitle();diff --git a/type/src/model.ts b/type/src/model.tsindex adc7fbe8..19d8fbdd 100644--- a/type/src/model.ts+++ b/type/src/model.ts@@ -12,6 +12,7 @@// the container.import { normalize, shift as shiftMarks, type Mark } from './inline.ts';+import { withoutCaps } from '../../kernel/src/docfields.ts';// value import is safe: xref.ts imports only TYPES from this module, precisely// so the core can call into it without a cycleimport { shiftRefs } from './xref.ts';@@ -424,9 +425,55 @@ export function copyIsReceiveOnly(collab: TypeDoc['collab'] | undefined): boolea* asserts that shape across every app that has a clipboard export.*/export function docForExport(doc: TypeDoc): TypeDoc {- const { collab, ...rest } = doc as TypeDoc & { collab?: unknown };- void collab;- return rest as TypeDoc;+ return withoutEmbeddedCaps(withoutCaps(doc));+}++/**+ * An embedded document keeps its content, never its capabilities — at any depth.+ *+ * An `embed` block carries a copy of another Bento document (embed.ts), so that+ * a reader can open the original. Its `collab` block is that document's sharing+ * keys, and has no business inside ours. `withoutCaps` (kernel docfields.ts,+ * the one shared list of capability fields) removes them from the document+ * itself; this ALSO walks into bento/type's own embed blocks, because an+ * embedded bento/type document can hold embeds of its own and the kernel helper+ * is shallow. The walk follows bento/type's own nesting: the `body` of each+ * embedded document, and the `embed` blocks within it.+ *+ * Pure — returns a new document where anything changed, never mutating the+ * input, because one caller (docForExport) is handed the LIVE document.+ */+export function embedSafe<T>(doc: T, depth = 0): T {+ if (!doc || typeof doc !== 'object') return doc;+ return scrubEmbeds(withoutCaps(doc as object) as Record<string, unknown>, depth) as T;+}++/** The same walk for a document whose OWN collab is somebody else's business+ * (a share-copy builder decides that) — only its embeds are made safe. */+export function withoutEmbeddedCaps<T>(doc: T): T {+ if (!doc || typeof doc !== 'object') return doc;+ return scrubEmbeds(doc as Record<string, unknown>, 0) as T;+}++/** Nesting deeper than this is not a real document. Past it an embed loses its+ * copy of the source rather than keeping one unscrubbed: fail closed. */+const EMBED_DEPTH = 16;++function scrubEmbeds(doc: Record<string, unknown>, depth: number): Record<string, unknown> {+ const body = doc.body;+ if (!Array.isArray(body)) return doc;+ let changed = false;+ const next = body.map((b: unknown) => {+ const blk = b as { kind?: unknown; embed?: { doc?: unknown } } | null;+ if (!blk || blk.kind !== 'embed' || !blk.embed || !blk.embed.doc || typeof blk.embed.doc !== 'object') return b;+ changed = true;+ if (depth >= EMBED_DEPTH) {+ const { doc: _drop, ...embed } = blk.embed;+ return { ...blk, embed };+ }+ return { ...blk, embed: { ...blk.embed, doc: embedSafe(blk.embed.doc, depth + 1) } };+ });+ return changed ? { ...doc, body: next } : doc;}export const uid = (p = 'b'): string => {@@ -709,7 +756,12 @@ export function parseDoc(raw: string): ParseResult {if (threads.length) doc.comments = Object.fromEntries(threads.map(t => [t.id, t]));else delete doc.comments;- return { ok: true, doc, repaired };+ // Every document entering bento/type — a file opened, Replace from JSON,+ // loadDoc, a restored snapshot — comes in with its EMBEDS made safe: an embed+ // stored before intake was scrubbed, or pasted in by hand, does not carry+ // another document's sharing keys into the live document. The document's own+ // collab is untouched; that is this file's.+ return { ok: true, doc: withoutEmbeddedCaps(doc), repaired };}/** The document's text, in order — what gets measured, searched and diffed. */diff --git a/type/src/share.ts b/type/src/share.tsindex 54f8e9b6..e425bb42 100644--- a/type/src/share.ts+++ b/type/src/share.ts@@ -23,9 +23,12 @@import { mintInvite } from './sync/online.ts';import { collabForReader, collabForInvite } from '../../kernel/src/docfields.ts';-import type { TypeDoc } from './model.ts';+import { withoutEmbeddedCaps, type TypeDoc } from './model.ts';-const clone = (doc: TypeDoc): TypeDoc => JSON.parse(JSON.stringify(doc)) as TypeDoc;+// Every share copy starts here, so every one is embed-safe: an embedded+// document never carries its own sharing keys out of this file, however it got+// in (an older file, a pasted JSON — not only through embed.ts's intake).+const clone = (doc: TypeDoc): TypeDoc => withoutEmbeddedCaps(JSON.parse(JSON.stringify(doc)) as TypeDoc);/*** An EDITOR copy: joins live with edit access through its own owner-signed