Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: shared doc-fields module (identity + capability/secret lists) (#622)
nyblnet68a363ea0f10
diff --git a/kernel/src/docfields.ts b/kernel/src/docfields.tsnew file mode 100644index 00000000..519c3e60--- /dev/null+++ b/kernel/src/docfields.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Fields a COPY of a document treats specially — the two sides of "not ordinary+// content." Every Bento app shares these lists, so a field added in one place is+// handled everywhere and a new secret fails CLOSED instead of leaking.+//+// 1. Identity/capability kept LIVE across undo/redo and every whole-document+// restore (FROM_LIVE) — never resurrected from a snapshot.+// 2. Capabilities/secrets STRIPPED when a copy is exported or shared+// (CAP_FIELDS at the top level; COLLAB_READER_KEEP — an ALLOWLIST — within+// a kept collab block).+//+// The helpers operate on plain objects: each app's doc/collab shape is a+// superset of the kernel's, so this module stays app-agnostic and imports+// nothing.++type Obj = Record<string, unknown>++// --- identity (kept live on undo/redo + whole-doc restore) ------------------++/** Top-level fields that are identity or capability, never undoable content.+ * undo/redo and every whole-document restore keep the LIVE value, not the+ * snapshot's — so nothing can resurrect an old docId, a stale sharing flag, a+ * dropped read-only mode or a cleared template flag. SUPERSET across apps: a+ * field absent from a given app's doc makes keeping it live a no-op. */+export const FROM_LIVE = ['docId', 'collab', 'readonly', 'template'] as const++/** After a restore has replaced `doc` with a snapshot, put identity back from+ * the LIVE doc — or delete it where live lacks it, so the snapshot's value can+ * never leak through. Mutates `restored` in place. */+export function keepLiveIdentity(restored: Obj, live: Obj): void {+ for (const k of FROM_LIVE) {+ if (Object.hasOwn(live, k) && live[k] !== undefined) restored[k] = live[k]+ else delete restored[k]+ }+}++// --- capabilities / secrets (stripped on export) ----------------------------++/** Top-level fields that carry a write/owner capability or secret. A copy that+ * does NOT keep the live room drops these entirely. A new top-level secret is+ * closed by adding it here, beside where capabilities are minted. (Top level is+ * a denylist: most top-level fields are content and cannot be allowlisted.) */+export const CAP_FIELDS = ['collab'] as const++/** A shallow copy of `doc` with every capability field removed. */+export function withoutCaps<T extends object>(doc: T): T {+ const out = { ...(doc as Obj) }+ for (const k of CAP_FIELDS) delete out[k]+ return out as T+}++/** Within a KEPT collab block, the fields a reader/viewer copy may carry. This+ * is an ALLOWLIST: anything not listed — writerPriv, ownerPriv, invite,+ * audience, the CRDT `sync` stamp, any link records, and any field added later —+ * is dropped, so a new secret fails CLOSED. `sync` is deliberately excluded: a+ * reader does not contribute, so it adopts fresh and converges from the room,+ * and carrying no stamp removes stale-stamp risk (writer/invite copies keep sync+ * through their own builders). `key` (the symmetric READ cap) and `room` stay —+ * a reader needs them to decrypt and join. `role` is NOT copied from the source+ * (a writer's collab must never project as a writer — the #588 class);+ * collabForReader sets it to 'reader' itself. */+export const COLLAB_READER_KEEP =+ ['room', 'key', 'owner', 'writerPub', 'on', 'v'] as const++/** Project a collab block down to what a reader/viewer copy may hold: a new+ * object with only the allowlisted fields that are present, and role forced to+ * 'reader' — never the source's role. */+export function collabForReader(collab: Obj): Obj {+ const out: Obj = {}+ for (const k of COLLAB_READER_KEEP) if (Object.hasOwn(collab, k) && collab[k] !== undefined) out[k] = collab[k]+ out.role = 'reader'+ return out+}++/** Within a kept collab, the fields an INVITE (edit/comment) copy may carry: the+ * reader allowlist PLUS the CRDT `sync` stamp (an invite copy contributes, so it+ * forks from the stamp) and the owner-signed `invite` delegation. Still an+ * ALLOWLIST — ownerPriv, writerPriv, audience, any link records, and any field+ * added later are dropped. The role rides inside `invite` (invite.role), not the+ * top level, so collabForInvite sets no top-level role. */+export const COLLAB_INVITE_KEEP = [...COLLAB_READER_KEEP, 'sync', 'invite'] as const++/** Project a collab block down to what an invite copy may hold: a new object with+ * only the allowlisted fields that are present. */+export function collabForInvite(collab: Obj): Obj {+ const out: Obj = {}+ for (const k of COLLAB_INVITE_KEEP) if (Object.hasOwn(collab, k) && collab[k] !== undefined) out[k] = collab[k]+ return out+}diff --git a/scripts/test-sync-session.ts b/scripts/test-sync-session.tsindex 280ff7e1..cf06ecf4 100644--- a/scripts/test-sync-session.ts+++ b/scripts/test-sync-session.ts@@ -57,6 +57,7 @@ const { Store } = await import('../slides/src/store.ts');const { SyncSession, assetsToOffload } = await import('../slides/src/sync/session.ts');const { newDoc, emptySlide } = await import('../slides/src/model.ts');const { SYNC_V } = await import('../kernel/src/sync/crdt.ts');+const { FROM_LIVE, keepLiveIdentity, CAP_FIELDS, withoutCaps, COLLAB_READER_KEEP, collabForReader, COLLAB_INVITE_KEEP, collabForInvite } = await import('../kernel/src/docfields.ts');let failures = 0, checks = 0;function ok(cond: boolean, msg: string) {@@ -559,6 +560,93 @@ H('a read-only live viewer still materialises a relay-offloaded image (not via csess.stop?.();}+// The shared doc-fields lists (kernel/src/docfields.ts) that every app imports:+// identity kept live on restore, and the capability/secret projections — proven+// here so the one module the apps depend on has the behaviour pinned centrally.+H('docfields: identity is taken from the live doc on restore, never the snapshot');+{+ const live = { docId: 'new', collab: { on: false }, readonly: true, title: 'live' } as Record<string, unknown>;+ const restored = { docId: 'old', collab: { on: true }, template: true, title: 'snap' } as Record<string, unknown>;+ keepLiveIdentity(restored, live);+ ok(restored.docId === 'new', 'docId comes from live');+ ok((restored.collab as { on: boolean }).on === false, 'collab comes from live (sharing stays off)');+ ok(restored.readonly === true, 'readonly comes from live');+ ok(!('template' in restored), 'a field live lacks is DELETED from the restored doc (no snapshot leak)');+ ok(restored.title === 'snap', 'non-identity content is left as the snapshot had it');+ ok([...FROM_LIVE].join() === 'docId,collab,readonly,template', 'FROM_LIVE is the agreed superset');+}++H('docfields: withoutCaps drops top-level capabilities, keeps content');+{+ const doc = { docId: 'x', slides: [], title: 't', collab: { ownerPriv: 'SECRET' } } as Record<string, unknown>;+ const stripped = withoutCaps(doc) as Record<string, unknown>;+ ok(!('collab' in stripped), 'withoutCaps removes collab');+ ok(stripped.docId === 'x' && 'slides' in stripped && stripped.title === 't', 'content is kept');+ ok((doc as { collab?: unknown }).collab !== undefined, 'the source doc is untouched (shallow copy)');+ ok([...CAP_FIELDS].join() === 'collab', 'CAP_FIELDS is the top-level capability denylist');+}++H('docfields: collabForReader is an allowlist — unknown + known secrets fail closed');+{+ const dirty = {+ room: 'r', key: 'k', owner: 'o', writerPub: 'wp', on: true, v: 2, role: 'writer',+ ownerPriv: 'X', writerPriv: 'Y', invite: { priv: 'Z' }, audience: {}, sync: { v: SYNC_V },+ links: [{ url: 'https://leak' }], futureSecret: 'LEAK',+ } as Record<string, unknown>;+ const clean = collabForReader(dirty);+ ok(!('ownerPriv' in clean) && !('writerPriv' in clean) && !('invite' in clean) && !('audience' in clean),+ 'the write/owner secrets are dropped');+ ok(!('sync' in clean), 'the CRDT sync stamp is dropped (readers carry no stamp)');+ ok(!('links' in clean) && !('futureSecret' in clean), 'link records and any UNKNOWN field are dropped — the allowlist fails closed');+ ok(clean.role === 'reader', 'role is FORCED to reader — a writer source never projects as a writer (#588 class)');+ ok(Object.keys(clean).sort().join() === 'key,on,owner,role,room,v,writerPub', 'exactly the allowlisted fields + the forced role survive');+ ok(clean.room === 'r' && clean.key === 'k', 'room + the symmetric read key are kept (a reader must decrypt + join)');+ ok([...COLLAB_READER_KEEP].length === 6, 'COLLAB_READER_KEEP is the 6-field public allowlist (role is forced, not copied)');+}++H('docfields: collabForInvite keeps sync + invite, still drops secrets and unknowns');+{+ const dirty = {+ room: 'r', key: 'k', owner: 'o', writerPub: 'wp', on: true, v: 2, role: 'writer',+ sync: { v: SYNC_V }, invite: { pub: 'ip', priv: 'isecret', role: 'writer', sig: 's' },+ ownerPriv: 'X', writerPriv: 'Y', audience: {},+ links: [{ url: 'https://leak' }], ownerSecret: 'LEAK',+ } as Record<string, unknown>;+ const inv = collabForInvite(dirty);+ ok('sync' in inv && 'invite' in inv, 'an invite copy keeps sync (it contributes) and its invite delegation');+ ok(!('ownerPriv' in inv) && !('writerPriv' in inv) && !('audience' in inv), 'owner/writer secrets are still dropped');+ ok(!('links' in inv) && !('ownerSecret' in inv), 'an invite copy carries NO unknown field (links / ownerSecret dropped)');+ ok(!('role' in inv), 'no top-level role on an invite copy — the role rides in invite.role');+ ok([...COLLAB_INVITE_KEEP].slice(-2).join() === 'sync,invite', 'COLLAB_INVITE_KEEP is the reader list plus sync + invite');+}++H('docfields: a reader copy with NO sync stamp joins a live room and converges');+{+ const docId = `ro-conv-${Math.random().toString(36).slice(2, 10)}`;+ // W: the live room — a writer with secrets + (conceptually) a sync stamp.+ const wdoc = newDoc(); wdoc.docId = docId;+ (wdoc as unknown as { collab: Record<string, unknown> }).collab = {+ room: 'r', key: 'k', on: true, v: 2, owner: 'o', ownerPriv: 'SECRET',+ writerPub: 'wp', writerPriv: 'WSECRET', role: 'writer', invite: { priv: 'INV' }, sync: { v: SYNC_V },+ };+ const W = new Store(JSON.parse(JSON.stringify(wdoc)));+ const sW = new SyncSession(W);+ W.commit(() => { W.doc.title = 'room content'; });+ await settle();+ // The reader copy carries only collabForReader(W.collab): no sync, no secrets.+ const rcollab = collabForReader((W.doc as unknown as { collab: Record<string, unknown> }).collab);+ ok(!('sync' in rcollab) && !('writerPriv' in rcollab) && !('ownerPriv' in rcollab),+ 'the reader copy is built with no sync stamp and no write/owner secrets');+ const rdoc = newDoc(); rdoc.docId = docId; rdoc.title = 'stale';+ (rdoc as unknown as { collab: Record<string, unknown> }).collab = rcollab;+ const R = new Store(JSON.parse(JSON.stringify(rdoc)));+ const sR = new SyncSession(R);+ await settle();+ ok(R.doc.title === 'room content',+ `the no-stamp reader converged to the room content (got ${JSON.stringify(R.doc.title)})`);+ sW.stop?.(); sR.stop?.();+}+console.log(`\n${checks - failures}/${checks} checks passed`);// BroadcastChannel and the heartbeat keep node's event loop aliveprocess.exit(failures ? 1 : 0);