Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

spaces: adopt the kernel doc-fields allowlist for share copies (#627)

nyblnetda2cb308500b
diff --git a/kernel/src/docfields.ts b/kernel/src/docfields.ts
index fb638e3f..c7ab6327 100644
--- a/kernel/src/docfields.ts
+++ b/kernel/src/docfields.ts
@@ -67,9 +67,10 @@ export const COLLAB_READER_KEEP =
/** 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 {
+export function collabForReader(collab: object): Obj {
+ const src = collab as Obj
const out: Obj = {}
- for (const k of COLLAB_READER_KEEP) if (Object.hasOwn(collab, k) && collab[k] !== undefined) out[k] = collab[k]
+ for (const k of COLLAB_READER_KEEP) if (Object.hasOwn(src, k) && src[k] !== undefined) out[k] = src[k]
out.role = 'reader'
return out
}
@@ -80,13 +81,20 @@ export function collabForReader(collab: Obj): Obj {
* 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
+export const COLLAB_INVITE_KEEP = [...COLLAB_READER_KEEP, 'sync'] 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 {
+/** Project a collab block to what an invite copy may hold, then attach the
+ * FRESHLY-MINTED `invite` and set the top-level role FROM it. The source's own
+ * invite, links and role are never carried (they are not in the allowlist, and
+ * invite + role come only from the parameter), so a commenter invite opens
+ * locked (role:'commenter') and a writer invite editable — never the source's
+ * chrome. */
+export function collabForInvite(collab: object, invite: { role: string }): Obj {
+ const src = collab as Obj
const out: Obj = {}
- for (const k of COLLAB_INVITE_KEEP) if (Object.hasOwn(collab, k) && collab[k] !== undefined) out[k] = collab[k]
+ for (const k of COLLAB_INVITE_KEEP) if (Object.hasOwn(src, k) && src[k] !== undefined) out[k] = src[k]
+ out.invite = invite
+ out.role = invite.role
return out
}
diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.ts
index 14a295af..ef66d371 100644
--- a/scripts/test-export-secrets.ts
+++ b/scripts/test-export-secrets.ts
@@ -448,12 +448,13 @@ function exportedBody(src: string, name: string): string {
return src.slice(open, i + 1)
}
-// The BUILDER checks hold for every app that mints share copies in a share.ts.
-// They covered spaces alone until 2026-10-04 — and type, which built its copies
-// inline in collab.ts with a stripper that kept writerPriv, went unchecked.
-// The CALL-SITE checks below are spaces' editor architecture and stay spaces'.
-const SHARE_APPS = ['spaces', 'type']
-const SHARE_CALLSITE_APPS = new Set(['spaces'])
+// The delete-based stripper TEXT checks hold only for an app that still mints
+// copies that way. type does (inline in collab.ts, through share.ts's stripper).
+// spaces moved to the kernel ALLOWLIST (collabForReader / collabForInvite) on
+// 2026-10-04; its builders are proven BEHAVIOURALLY in scripts/test-spaces-invite.ts
+// — this rig runs under strip-only node and cannot import a file with a parameter
+// property, so it keeps spaces' SOURCE guard here and the behaviour lives there.
+const SHARE_APPS = ['type']
for (const app of SHARE_APPS) {
const rel = `${app}/src/share.ts`
let src: string
@@ -479,32 +480,40 @@ for (const app of SHARE_APPS) {
ok(!/ownerPriv\s*[,}]/.test(mask(exportedBody(src, 'readerCopy'))),
`${rel}: readerCopy never re-attaches a private key`)
- if (!SHARE_CALLSITE_APPS.has(app)) {
- // type's call site: collab.ts must build every copy through share.ts.
- const collab = read(`${app}/src/collab.ts`)
- ok(/inviteCopy\(/.test(collab) && /readerCopy\(/.test(collab) && !/stripCollabSecrets/.test(collab),
- `${app}/src/collab.ts mints share copies only through share.ts`)
- continue
- }
+ // type's call site: collab.ts must build every copy through share.ts.
+ const collab = read(`${app}/src/collab.ts`)
+ ok(/inviteCopy\(/.test(collab) && /readerCopy\(/.test(collab) && !/stripCollabSecrets/.test(collab),
+ `${app}/src/collab.ts mints share copies only through share.ts`)
+}
- // The call site. A share copy must reach the file through a writer that takes
- // a DOCUMENT — the ordinary save path serializes the open one.
- const ed = read(`${app}/src/editor.ts`)
+// spaces: minted through the kernel allowlist now. SOURCE guard (behaviour is in
+// scripts/test-spaces-invite.ts): both builders route through the kernel helper,
+// the delete-based stripper is gone, and neither rebuilds collab by SPREADING the
+// source (`{ ...c }`) — the denylist bypass that would carry every secret back.
+{
+ const rel = 'spaces/src/share.ts'
+ const src = read(rel)
+ ok(!/stripCollabSecrets/.test(src), `${rel}: the delete-based stripper is gone — the kernel allowlist replaces it`)
+ const inviteFn = mask(exportedBody(src, 'inviteCopy'))
+ const readerFn = mask(exportedBody(src, 'readerCopy'))
+ ok(/collabForInvite\(/.test(inviteFn), `${rel}: inviteCopy routes through collabForInvite`)
+ ok(/collabForReader\(/.test(readerFn), `${rel}: readerCopy routes through collabForReader`)
+ ok(/mintInvite\(/.test(inviteFn), `${rel}: inviteCopy still mints a SCOPED invite`)
+ ok(!/\{\s*\.\.\.c\b/.test(inviteFn) && !/\{\s*\.\.\.c\b/.test(readerFn),
+ `${rel}: neither builder rebuilds collab by spreading the source — that bypass carries every secret`)
+
+ // the call site (unchanged by the migration): the share button derives its
+ // document and writes through the encrypt-aware hook, never the ordinary save.
+ const ed = read('spaces/src/editor.ts')
const share = bodies(ed).get('shareCopy') ?? ''
- ok(!!share, `${app}/src/editor.ts has a shareCopy()`)
- ok(/inviteCopy\(|readerCopy\(/.test(share),
- `${app}: the share button derives its document (inviteCopy/readerCopy)`)
- ok(!/saveAs\(/.test(mask(share)),
- `${app}: the share button does NOT reach the ordinary copy path — that path writes store.doc, credentials and all`)
- ok(/onShareCopy\?\.\(/.test(share), `${app}: it writes through the share-copy hook`)
-
- // …and that hook must encrypt, and must not become the ⌘S target.
- const main = read(`${app}/src/main.ts`)
+ ok(!!share, 'spaces/src/editor.ts has a shareCopy()')
+ ok(/inviteCopy\(|readerCopy\(/.test(share), 'spaces: the share button derives its document (inviteCopy/readerCopy)')
+ ok(!/saveAs\(/.test(mask(share)), 'spaces: the share button does NOT reach the ordinary copy path')
+ ok(/onShareCopy\?\.\(/.test(share), 'spaces: it writes through the share-copy hook')
+ const main = read('spaces/src/main.ts')
const hook = main.slice(main.indexOf('editor.onShareCopy'), main.indexOf('editor.onShareCopy') + 400)
- ok(/serializeAuto\(/.test(hook),
- `${app}: onShareCopy writes through serializeAuto — an active password reaches the shared copy`)
- ok(!/keepHandle:\s*true/.test(hook),
- `${app}: onShareCopy does not retain the file handle — the next ⌘S must not overwrite the copy with the full document`)
+ ok(/serializeAuto\(/.test(hook), 'spaces: onShareCopy writes through serializeAuto — a password reaches the copy')
+ ok(!/keepHandle:\s*true/.test(hook), 'spaces: onShareCopy does not retain the file handle')
}
// --- the OTHER half of the round trip: pasting one back in -------------------
diff --git a/scripts/test-spaces-invite.ts b/scripts/test-spaces-invite.ts
index 6008a59b..84649a1d 100644
--- a/scripts/test-spaces-invite.ts
+++ b/scripts/test-spaces-invite.ts
@@ -51,7 +51,7 @@ const g = globalThis as unknown as Record<string, unknown>
g.localStorage = shim
g.window = g.window ?? { localStorage: shim, addEventListener() {}, setTimeout, clearTimeout }
-const { inviteCopy, readerCopy, stripCollabSecrets, isOwner, canWrite } = await import('../spaces/src/share.ts')
+const { inviteCopy, readerCopy, isOwner, canWrite } = await import('../spaces/src/share.ts')
const { mintCollab } = await import('../kernel/src/sync/online.ts')
import type { SpacesDoc } from '../spaces/src/model.ts'
@@ -157,12 +157,59 @@ ok(vc.sync === undefined, 'the stamped CRDT state is dropped — a viewer must n
ok(!canWrite(viewer!), 'canWrite() reports false for it')
// ---------------------------------------------------------------------------
-console.log('\nthe stripper')
+// The allowlist bar (security, 2026-10-04): build every copy builder from ONE
+// source carrying every known secret, an unknown future field and a JSON own
+// __proto__ key, and prove only the allowlist survives — nothing by name, and
+// nothing new by accident. (The whole-block default drop is docForExport's job,
+// pinned in scripts/test-export-secrets.ts.)
+console.log('\nevery builder, from one poisoned source')
-const dropped = JSON.parse(JSON.stringify(doc)) as SpacesDoc
-stripCollabSecrets(dropped)
-ok(dropped.collab === undefined,
- 'by default the whole block goes — room + key together ARE the read capability')
+// a real own __proto__ key: JSON.parse makes it an OWN property, not the chain.
+const poisoned = JSON.parse(JSON.stringify(doc)) as SpacesDoc
+const pc = JSON.parse(
+ '{"__proto__":{"polluted":true}}',
+) as Record<string, unknown>
+// keep the REAL ownerPriv (inviteCopy mints against it); poison everything else
+Object.assign(pc, poisoned.collab, {
+ 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.collab = pc as SpacesDoc['collab']
+
+const READER_KEYS = ['room', 'key', 'owner', 'writerPub', 'on', 'v', 'role']
+const INVITE_KEYS = ['room', 'key', 'owner', 'writerPub', 'on', 'v', 'sync', 'invite', 'role']
+const SECRETS = ['writerPriv', 'ownerPriv', 'audience', 'futureSecret', 'links']
+
+const rc = readerCopy(poisoned)!.collab as Record<string, unknown>
+const vic = (await inviteCopy(poisoned))!.collab 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 is forced to reader')
+ok(rc.sync === undefined, 'reader copy: the CRDT sync stamp is dropped')
+ok(Object.keys(vic).every((k) => INVITE_KEYS.includes(k)),
+ `invite copy: ONLY invite-allowlist keys survive (${Object.keys(vic).sort().join(',')})`)
+ok(vic.sync !== undefined, 'invite copy: keeps the sync stamp (it contributes)')
+ok((vic.invite as { pub: string }).pub !== 'SRC', 'invite copy: the delegation is FRESH, never the source invite')
+ok(vic.role === 'writer', 'invite copy: top-level role comes from the fresh writer invite (editor chrome)')
+for (const f of SECRETS) {
+ ok(!(f in rc), `reader copy drops ${f}`)
+ ok(!(f in vic), `invite copy drops ${f}`)
+}
+ok(!Object.hasOwn(rc, '__proto__') && !Object.hasOwn(vic, '__proto__'),
+ 'neither copy carries a __proto__ own key')
+ok(({} as Record<string, unknown>).polluted === undefined,
+ 'and the __proto__ source key polluted nothing (Object.hasOwn, not `in`)')
+
+// The planted bypass: a builder that rebuilds collab by SPREADING the source
+// keeps every secret. The exact-key-set check above is what turns that red —
+// proving it is not a vacuous check.
+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 (the check is not vacuous)')
// Derived from the KERNEL type, not typed out here: a new private field added
// to CollabCreds fails this until inviteCopy stops carrying it.
diff --git a/scripts/test-sync-session.ts b/scripts/test-sync-session.ts
index f51d7fdf..2de7cb88 100644
--- a/scripts/test-sync-session.ts
+++ b/scripts/test-sync-session.ts
@@ -604,20 +604,23 @@ H('docfields: collabForReader is an allowlist — unknown + known secrets fail c
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');
+H('docfields: collabForInvite keeps sync, attaches a FRESH invite, role from it');
{
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' },
+ sync: { v: SYNC_V }, invite: { pub: 'SOURCE', priv: 'sourceSecret', 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');
+ const fresh = { pub: 'FRESH', priv: 'freshSecret', role: 'commenter', sig: 'f' };
+ const inv = collabForInvite(dirty, fresh);
+ ok('sync' in inv, 'an invite copy keeps sync (it contributes, so it forks from the stamp)');
+ ok(inv.invite === fresh, 'the invite is the FRESH one passed in');
+ ok((inv.invite as { pub: string }).pub === 'FRESH', 'never the source invite — that delegation can’t ride along');
+ ok(inv.role === 'commenter', 'the top-level role is taken FROM the fresh invite (a commenter invite opens locked)');
+ ok(!('ownerPriv' in inv) && !('writerPriv' in inv) && !('audience' in inv), 'owner/writer secrets are 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');
+ ok([...COLLAB_INVITE_KEEP].slice(-1)[0] === 'sync' && ![...COLLAB_INVITE_KEEP].includes('invite' as never), 'COLLAB_INVITE_KEEP is the reader list plus sync (invite comes from the param, not the allowlist)');
}
H('docfields: a reader copy with NO sync stamp joins a live room and converges');
diff --git a/spaces/src/share.ts b/spaces/src/share.ts
index 8e0a0864..d2f586d1 100644
--- a/spaces/src/share.ts
+++ b/spaces/src/share.ts
@@ -33,40 +33,12 @@
// client and the deployed worker drift apart.
import { mintInvite } from '../../kernel/src/sync/online.ts'
+import { collabForReader, collabForInvite } from '../../kernel/src/docfields.ts'
import type { SpacesDoc } from './model.ts'
/** A share export's filename suffix — also what the UI calls the copy. */
export type ShareKind = 'invite' | 'viewonly'
-/**
- * Take the live session out of a copy that is about to leave this machine.
- *
- * ONE list, in one place, and DERIVED BY DELETING rather than by rebuilding
- * the block from an allow-list: a private field added to `CollabCreds` later
- * is covered here without anyone remembering to act. Divergent per-export
- * copies of this list are how one export path ends up leaking what the other
- * three strip — slides wrote that sentence after it happened.
- *
- * The default is to drop `collab` outright: a template, a page extract or the
- * JSON on the clipboard must not join anything, and `room` + `key` together
- * ARE the read capability. `keepRoom` is for the copies that are MEANT to
- * follow the session — they keep the room, the symmetric read key and the
- * PUBLIC keys, and lose only the private halves.
- *
- * Note what `keepRoom` does NOT do: it never adds a capability. An invite is
- * added afterwards, deliberately and visibly, by `inviteCopy()`.
- */
-export function stripCollabSecrets(doc: SpacesDoc, opts: { keepRoom?: boolean } = {}): void {
- if (!doc.collab) return
- if (!opts.keepRoom) {
- delete doc.collab
- return
- }
- delete doc.collab.writerPriv // the muzzle — no room-wide write capability travels
- delete doc.collab.ownerPriv // …nor the owner key, which can also revoke…
- delete doc.collab.invite // …nor any invite (delegation) material we hold
-}
-
/** A deep clone, so nothing done to a copy can reach the open document. */
const clone = (doc: SpacesDoc): SpacesDoc => JSON.parse(JSON.stringify(doc)) as SpacesDoc
@@ -124,9 +96,11 @@ export async function inviteCopy(doc: SpacesDoc): Promise<SpacesDoc | null> {
const c = doc.collab
if (!c?.room || !c.key || !isOwner(doc)) return null
const out = clone(doc)
- stripCollabSecrets(out, { keepRoom: true })
- out.collab!.invite = await mintInvite(c.ownerPriv!, 'writer')
- out.collab!.on = true
+ // allowlist (kernel docfields): keeps room/read-key/public keys + sync, drops
+ // every private half AND anything unknown; the fresh invite and the top-level
+ // role come from mintInvite, never from the source.
+ const invite = await mintInvite(c.ownerPriv!, 'writer')
+ out.collab = { ...collabForInvite(c, invite), on: true } as SpacesDoc['collab']
return out
}
@@ -148,8 +122,9 @@ export function readerCopy(doc: SpacesDoc): SpacesDoc | null {
const c = doc.collab
if (!c?.room || !c.key) return null
const out = clone(doc)
- out.collab = { ...c, role: 'reader', on: true, sync: undefined }
- stripCollabSecrets(out, { keepRoom: true })
+ // allowlist (kernel docfields): keeps room/read-key/public keys, forces
+ // role:'reader', drops every private half, the sync stamp AND anything unknown.
+ out.collab = { ...collabForReader(c), on: true } as SpacesDoc['collab']
return out
}
diff --git a/spaces/src/store.ts b/spaces/src/store.ts
index 5064ae2e..3375a022 100644
--- a/spaces/src/store.ts
+++ b/spaces/src/store.ts
@@ -14,6 +14,7 @@
type Scope = 'doc' | 'page'
import { type SpacesDoc, type Page, type Block, buildIndex, type SpaceIndex, homePage } from './model'
+import { FROM_LIVE } from '../../kernel/src/docfields.ts'
type Listener = () => void
type Event = 'doc' | 'page' | 'tree' | 'selection' | 'dirty'
@@ -46,10 +47,10 @@ const UNDO_BUDGET = 24 * 1024 * 1024
* is encoded and travel with it; `assets` is kept by undo/redo for a different
* reason — snapshots omit it for size — and a replaceDoc brings its own.
*
- * Same name and shape as slides' FROM_LIVE (slides/src/restoregate.ts) so the
- * kernel can lift one shared list; spaces adds `template`, which slides lacks.
+ * The shared list now lives in the kernel (kernel/src/docfields.ts) and is
+ * re-exported here, so restoregate.ts keeps importing it from `./store.ts`.
*/
-export const FROM_LIVE = ['docId', 'collab', 'readonly', 'template'] as const
+export { FROM_LIVE }
/** Overwrite `next`'s FROM_LIVE keys with `live`'s — including deleting one the
* live document does not have. Mutates and returns `next`. */