Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: a view-only copy carries no private key, whatever the source held (#613)

nyblnet882f4f4da0fb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a1424b83..a7dfdc87 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1809,6 +1809,13 @@ jobs:
# script rather than sanitising one.
run: node scripts/test-type-embed.ts
+ - name: Type share-copy rig
+ # A view-only copy carries the room it follows and NO private key —
+ # not the owner's, not a legacy writer key, not an invite — whatever the
+ # source document held; an editor copy writes only through its own
+ # fresh, revocable invite. Every copy is minted in type/src/share.ts.
+ run: node scripts/test-type-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.ts
index 9f6d2865..e3b54312 100644
--- a/scripts/test-export-secrets.ts
+++ b/scripts/test-export-secrets.ts
@@ -426,7 +426,12 @@ function exportedBody(src: string, name: string): string {
return src.slice(open, i + 1)
}
-const SHARE_APPS = ['spaces']
+// 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'])
for (const app of SHARE_APPS) {
const rel = `${app}/src/share.ts`
let src: string
@@ -452,6 +457,14 @@ 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
+ }
+
// 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`)
diff --git a/scripts/test-type-share.ts b/scripts/test-type-share.ts
new file mode 100644
index 00000000..b6f640f5
--- /dev/null
+++ b/scripts/test-type-share.ts
@@ -0,0 +1,103 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The copies bento/type writes for someone ELSE carry no private key.
+//
+// node scripts/test-type-share.ts
+//
+// WHAT THIS PROVES. "View-only copy…" and "Invite to edit…" (type/src/share.ts)
+// write a document for another person. A view-only copy must follow the live
+// session and NEVER write; an editor copy must write only through its own
+// revocable invite. So neither may carry a private key it was not given:
+// 1. a reader copy has NO writerPriv, ownerPriv or invite keypair — whatever
+// the source document held — while keeping the room it follows;
+// 2. an editor copy has no writerPriv or ownerPriv, and its invite is a FRESH
+// one, never the source's;
+// 3. the default strip removes the whole collab block;
+// 4. every copy builder lives in share.ts, and collab.ts builds none inline.
+//
+// THE FIXTURE IS THE CASE THAT WAS MISSED. bento/type never mints a writer
+// key (its rooms are v2, owner-keyed), so a copy of a document type created was
+// clean all along. The gap was a document that ARRIVED holding one — an older
+// file, a pasted JSON — because parseDoc carries `collab` through verbatim.
+// So the source here goes through parseDoc with a legacy writer key on it.
+
+import { register } from 'node:module'
+import { readFileSync } from 'node:fs'
+register('./lib/ts-resolve-hooks.mjs', import.meta.url)
+const { readerCopy, inviteCopy, stripCollabSecrets } = await import('../type/src/share.ts')
+const { emptyDoc, parseDoc } = await import('../type/src/model.ts')
+const { mintCollab } = await import('../kernel/src/sync/online.ts')
+import type { TypeDoc } from '../type/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}`) }
+const read = (p: string) => readFileSync(new URL('../' + p, import.meta.url), 'utf8')
+
+const SECRETS = ['WRITER-PRIVATE', 'OWNER-PRIVATE', 'INVITE-PRIVATE']
+const arrived = (): TypeDoc => {
+ const r = parseDoc(JSON.stringify({ ...emptyDoc(), body: [{ id: 'p1', kind: 'para', text: 'terms' }],
+ collab: { v: 2, on: true, room: 'w-room', key: 'ROOM-READ-KEY', owner: 'OWNER-PUB', ownerPriv: 'OWNER-PRIVATE',
+ writerPub: 'WRITER-PUB', writerPriv: 'WRITER-PRIVATE',
+ invite: { pub: 'INV-PUB', priv: 'INVITE-PRIVATE', role: 'writer', sig: 'SIG' } } }))
+ if (!r.ok) throw new Error('fixture did not parse')
+ return r.doc
+}
+
+console.log('\na view-only copy carries no private key\n')
+{
+ const src = arrived()
+ ok((src.collab as { writerPriv?: string }).writerPriv === 'WRITER-PRIVATE',
+ 'the source really holds a legacy writer key after parseDoc — the case that was missed')
+ const r = readerCopy(src)
+ const blob = JSON.stringify(r)
+ for (const s of SECRETS) ok(!blob.includes(s), `the reader copy does not contain ${s}`)
+ ok(!('writerPriv' in r.collab!) && !('ownerPriv' in r.collab!) && !('invite' in r.collab!),
+ 'writerPriv, ownerPriv and invite are absent as FIELDS, not merely emptied')
+ ok(r.collab?.role === 'reader' && r.collab?.on === true, 'it is a live reader')
+ ok(r.collab?.room === 'w-room' && r.collab?.key === 'ROOM-READ-KEY',
+ 'and keeps the room and read key it needs to follow the session')
+ ok(r.collab?.sync === undefined, 'with no sync state of the source\'s')
+ ok((src.collab as { writerPriv?: string }).writerPriv === 'WRITER-PRIVATE', 'and the OPEN document is untouched')
+
+ // the ordinary case, from a room type itself mints
+ const fresh = { ...emptyDoc(), collab: await mintCollab() } as TypeDoc
+ const r2 = readerCopy(fresh)
+ ok(!('ownerPriv' in r2.collab!) && !('writerPriv' in r2.collab!) && !('invite' in r2.collab!),
+ 'a copy of a document type minted itself is clean too')
+}
+
+console.log('\nan editor copy writes only through its own invite\n')
+{
+ const src = arrived()
+ const ownerPriv = (await mintCollab()).ownerPriv as string // a real key, so mintInvite can sign
+ const e = await inviteCopy(src, ownerPriv)
+ const blob = JSON.stringify(e)
+ ok(!blob.includes('WRITER-PRIVATE'), 'no legacy writer key — it would be a second way in no revocation reaches')
+ ok(!blob.includes('OWNER-PRIVATE'), 'no owner key')
+ ok(!blob.includes('INVITE-PRIVATE') && e.collab?.invite?.pub !== 'INV-PUB',
+ 'and the invite is a FRESH one, never the source\'s own')
+ ok(e.collab?.invite?.role === 'writer' && e.collab?.on === true, 'a live editor invite')
+}
+
+console.log('\nthe default strip removes the room too\n')
+{
+ const d = arrived(); stripCollabSecrets(d)
+ ok(!('collab' in d), 'with no keepRoom, the whole collab block goes — the room key is a capability')
+}
+
+console.log('\nevery copy is minted in share.ts\n')
+{
+ const collab = read('type/src/collab.ts')
+ ok(/inviteCopy\(/.test(collab) && /readerCopy\(/.test(collab), 'collab.ts builds its copies through share.ts')
+ ok(!/JSON\.parse\(JSON\.stringify\(store\.doc\)\)/.test(collab), 'and clones none inline')
+ // No other type module builds a reader or audience copy by hand.
+ const { readdirSync } = await import('node:fs')
+ const rogue = readdirSync(new URL('../type/src/', import.meta.url))
+ .filter(f => f.endsWith('.ts') && f !== 'share.ts' && f !== 'model.ts')
+ .filter(f => /role:\s*'(?:reader|audience)'/.test(read('type/src/' + f)))
+ 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(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/type/src/collab.ts b/type/src/collab.ts
index 4cf8a8c4..7e8add94 100644
--- a/type/src/collab.ts
+++ b/type/src/collab.ts
@@ -31,11 +31,12 @@
// sync/session.ts's SyncSession is for.
import './collab.css';
+import { inviteCopy, readerCopy } from './share.ts';
import { serializeAuto, writeUpdatedFileAs } from '../../kernel/src/save.ts';
import { lsGet, lsSet } from '../../kernel/src/storage.ts';
import { offlineEnabled } from '../../kernel/src/net.ts';
import {
- joinFromDoc, mintInvite, onlineTransport, rotateKeys,
+ joinFromDoc, onlineTransport, rotateKeys,
sharingOn, startSharing, stopSharing,
} from './sync/online.ts';
import { SyncSession, hostStore, type Peer, type SyncNotice } from './sync/session.ts';
@@ -81,14 +82,6 @@ function noticeText(n: SyncNotice): string {
}
}
-/** A copy sent for someone else to work on must not carry the owner's keys. */
-function stripCollabSecrets(doc: TypeDoc, opts: { keepRoom?: boolean } = {}) {
- if (!doc.collab) return;
- if (!opts.keepRoom) { delete doc.collab; return; }
- delete doc.collab.ownerPriv;
- delete doc.collab.invite;
-}
-
/** Where a peer is, in terms someone reading the sidebar understands. */
function blockLabel(doc: TypeDoc, blockId: string): string {
const i = doc.body.findIndex(b => b.id === blockId);
@@ -260,10 +253,9 @@ export function initCollab(store: Store, editor: Editor): void {
return;
}
session.stampInto(store.doc);
- const clone: TypeDoc = JSON.parse(JSON.stringify(store.doc));
- stripCollabSecrets(clone, { keepRoom: true });
- clone.collab!.invite = await mintInvite(c.ownerPriv, 'writer');
- clone.collab!.on = true;
+ // Built in share.ts, the one place share copies are minted (and the place
+ // test-export-secrets and test-type-share inspect).
+ const clone = await inviteCopy(store.doc, c.ownerPriv);
try {
const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'invite' });
if (ok) toast(t('Editor copy saved — recipients join live with edit access'));
@@ -276,9 +268,7 @@ export function initCollab(store: Store, editor: Editor): void {
await goLive();
const c = store.doc.collab;
if (!c?.room || !c.key) { toast(t('This document has no live session to follow')); return; }
- const clone: TypeDoc = JSON.parse(JSON.stringify(store.doc));
- clone.collab = { ...c, role: 'reader', on: true, sync: undefined };
- stripCollabSecrets(clone, { keepRoom: true });
+ const clone = readerCopy(store.doc);
try {
const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone, { suffix: 'viewonly' });
if (ok) toast(t('View-only copy saved — it follows the live session'));
diff --git a/type/src/model.ts b/type/src/model.ts
index ded462bb..adc7fbe8 100644
--- a/type/src/model.ts
+++ b/type/src/model.ts
@@ -363,6 +363,15 @@ export interface TypeDoc {
/** owner's signature over `inv.${pub}.${role}.${exp||0}` */
sig: string;
};
+ /**
+ * The LEGACY (pre-v2) shared writer keypair. bento/type never mints one —
+ * its rooms are owner-keyed — but a document can ARRIVE holding one, and
+ * parseDoc keeps `collab` verbatim. Declared so the code that must strip
+ * the private half can name it: undeclared, it was the one key the share
+ * stripper left in every view-only copy. Matches kernel sync/crdt.ts.
+ */
+ writerPub?: string;
+ writerPriv?: string;
};
/** unknown fields are PRESERVED — format additivity (PLATFORM §3) */
[extra: string]: unknown;
diff --git a/type/src/share.ts b/type/src/share.ts
new file mode 100644
index 00000000..d1a743fe
--- /dev/null
+++ b/type/src/share.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// SHARE COPIES — the documents bento/type writes for someone ELSE to open: an
+// editor invite ("Invite to edit…") and a view-only reader ("View-only
+// copy…"). Minted in one place, DOM-free, so the copy that ships is the copy
+// the rigs inspect.
+//
+// It used to be built inline in collab.ts, and its stripper dropped ownerPriv
+// and the invite but NOT writerPriv. bento/type never mints a writer key — its
+// rooms are v2, owner-keyed — but `parseDoc` carries `collab` through verbatim,
+// so a document that ARRIVED holding a legacy writer key (an older file, a
+// pasted JSON) handed that key to every view-only copy made from it: a "reader"
+// holding a private key that writes, which defeats the read-only tier at the
+// relay. Nothing caught it because scripts/test-export-secrets.ts's share-copy
+// checks ran against spaces alone; this file is shaped to that same contract
+// (stripCollabSecrets / inviteCopy / readerCopy) so they now cover type too.
+//
+// Still a HAND LIST of private fields. The kernel's shared allowlist of what a
+// copy may keep will replace it; until then, a new private field in `collab`
+// must be added to stripCollabSecrets.
+
+import { mintInvite } from './sync/online.ts';
+import type { TypeDoc } from './model.ts';
+
+const clone = (doc: TypeDoc): TypeDoc => JSON.parse(JSON.stringify(doc)) as TypeDoc;
+
+/**
+ * Remove every private key a copy for someone else must not carry.
+ *
+ * By default the WHOLE block goes — the room key is a capability too. With
+ * `keepRoom`, the room and its public keys stay (so the copy can follow the
+ * live session) and every private key goes: the owner's, any legacy writer
+ * key, and any invite keypair this document holds.
+ */
+export function stripCollabSecrets(doc: TypeDoc, opts: { keepRoom?: boolean } = {}): void {
+ if (!doc.collab) return;
+ if (!opts.keepRoom) { delete doc.collab; return; }
+ delete doc.collab.ownerPriv;
+ delete doc.collab.writerPriv;
+ delete doc.collab.invite;
+}
+
+/**
+ * An EDITOR copy: joins live with edit access through its own owner-signed
+ * invite, which the owner can revoke. It strips FIRST — a writer key left
+ * beside the invite would be a second way in that no revocation reaches.
+ */
+export async function inviteCopy(doc: TypeDoc, ownerPriv: string): Promise<TypeDoc> {
+ const out = clone(doc);
+ stripCollabSecrets(out, { keepRoom: true });
+ out.collab!.invite = await mintInvite(ownerPriv, 'writer');
+ out.collab!.on = true;
+ return out;
+}
+
+/**
+ * A VIEW-ONLY copy: follows the live session and never writes. It carries the
+ * room and the public keys, and no private key of any kind; the relay drops
+ * anything it tries to send.
+ */
+export function readerCopy(doc: TypeDoc): TypeDoc {
+ const out = clone(doc);
+ out.collab = { ...out.collab!, role: 'reader', on: true, sync: undefined };
+ stripCollabSecrets(out, { keepRoom: true });
+ return out;
+}