Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

type: receive-only copies are Viewers, and cannot be edited however they arrive (#588)

nyblnetb59a9105c3ef
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 3928d153..968019bd 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -7417,3 +7417,46 @@ assistive tech. The arrows Chrome does stretch stay font glyphs. The tree
rigs treat a drawn arrow as a deliberate difference: named in
`test-maths-lite.ts`, counted with the identical ones in the coverage floor.
Cost: +966 B of shell.
+
+## 2026-10-04 — Whether a copy may write is an allowlist of roles (type)
+
+**A copy's write capability is decided by the roles that can write, never by
+the roles that cannot.** bento/type's share popover and People label asked
+`collab.role !== 'reader'`. When #454 added `'audience'` — a live-show member
+whose transport is receive-only (kernel/src/sync/online.ts) — that test
+answered "yes": an audience copy opened in type was labelled **Editor** and
+offered "Invite to edit…" and "View-only copy…", contradicting the transport
+beneath it. Measured: an audience-shaped `collab` survives `parseDoc` with
+`role: 'audience'` intact, and the old test returns true for it. The relay
+still refused its writes, so the defect was a misleading UI, not a capability.
+
+`copyCanWrite` (type/src/model.ts) now returns true only for an absent role
+(every file older than the role field writes) or `'writer'`, and both gates in
+type/src/collab.ts use it. It fails CLOSED: a role nobody has taught it about
+gets view-only chrome, which is a visible, harmless bug, where the denylist's
+failure was invisible and misleading. Type's `collab.role` type is also widened
+to the kernel's own union (sync/crdt.ts) — it was narrower, which is why
+nothing flagged the gap.
+
+The same `!== 'reader'` shape stands in slides (editor.ts), spaces (share.ts)
+and dash (sync/online.ts); filed for those zones rather than changed here.
+`test-type-model.ts` pins the shape, including a role nobody has invented yet.
+
+**And a receive-only copy is locked, by a lock DERIVED from the document.**
+The mislabel had a worse twin: type mints view-only copies ("View-only copy…")
+yet its editor was unconditionally `contentEditable` and `Store.commit` never
+checked — so a reader could type freely while the popover said the copy
+"can't change the document". The relay dropped those edits, so they lived only
+locally and autosave could write them back, drifting the file from the room it
+follows. Measured in headless Chrome on the built shell: with no lock, a reader
+copy loaded via `loadDoc` stayed editable and typed text landed; with the lock,
+it is not editable and the text holds. `Store.locked` is recomputed on every
+change — never decided once at boot — because bento/slides found the
+build-time version, which a reader copy loaded into a running editor walked
+straight past. User commits are refused while locked; the sync session's own
+commits carry `system: true` and pass, because kernel session.ts writes a
+peer's published images into the document through `commit`, and a reader
+needs those more than anyone. Remote edits arrive through `touch()`, not
+`commit`, so a locked copy still follows the room. `copyIsReceiveOnly` is the
+lock's question (a document with no `collab` is local and editable — unlike
+`copyCanWrite`, which says no only because there is no room to write to).
diff --git a/scripts/test-type-model.ts b/scripts/test-type-model.ts
index 0f968e74..002167a3 100644
--- a/scripts/test-type-model.ts
+++ b/scripts/test-type-model.ts
@@ -18,7 +18,7 @@
// footnote marker in the middle of a word during the spike, so there is
// one function that moves both and this pins it.
-import { parseDoc, spliceText, emptyDoc, FORMAT, plainText, wordCount, type Block } from '../type/src/model.ts';
+import { parseDoc, spliceText, emptyDoc, FORMAT, plainText, wordCount, copyCanWrite, type Block } 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}`); };
@@ -128,5 +128,35 @@ H('odds and ends');
ok(r.ok && plainText(r.doc) === 'Heading\ntwo words', 'plain text joins blocks with newlines');
}
+console.log('\n— which copies may write —');
+{
+ // The copy shapes the kernel actually mints (kernel/src/sync/online.ts
+ // mintCollab / mintInvite, and #454's show ticket), run through parseDoc the
+ // way a real file reaches collab.ts — not hand-built collab objects, because
+ // what matters is what survives intake.
+ const via = (collab: object) => {
+ const r = parseDoc(JSON.stringify({ ...emptyDoc(), collab }));
+ return r.ok ? r.doc.collab : undefined;
+ };
+ const owner = via({ v: 2, on: true, room: 'w1', key: 'K', owner: 'OP', ownerPriv: 'OK' });
+ const editor = via({ v: 2, on: true, room: 'w1', key: 'K', owner: 'OP',
+ invite: { pub: 'IP', priv: 'IK', role: 'writer', sig: 'S' } });
+ const legacy = via({ on: true, room: 'r1', key: 'K', writerPub: 'WP', writerPriv: 'WK' });
+ const reader = via({ v: 2, on: true, room: 'w1', key: 'K', owner: 'OP', role: 'reader' });
+ const audience = via({ v: 2, on: true, room: 'w1', key: 'KE', owner: 'OP', role: 'audience',
+ invite: { pub: 'IP', priv: 'IK', role: 'audience', sig: 'S' } });
+
+ ok(audience?.role === 'audience', "an audience copy's role SURVIVES parseDoc — so collab.ts really is handed it");
+ ok(copyCanWrite(owner), 'an owner copy writes');
+ ok(copyCanWrite(editor), 'an invited editor writes');
+ ok(copyCanWrite(legacy), 'a legacy copy with no role field writes — every pre-role file is one');
+ ok(!copyCanWrite(reader), 'a view-only reader does not');
+ ok(!copyCanWrite(audience),
+ 'an AUDIENCE copy does not — though it carries an invite, which is what made it read as an Editor');
+ ok(!copyCanWrite(via({ v: 2, on: true, room: 'w1', key: 'K', role: 'presenter-of-tomorrow' })),
+ 'a role nobody has taught this about fails CLOSED, not open — the shape that would have caught this');
+ ok(!copyCanWrite(undefined), 'and a document with no collab at all has nothing to write to');
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`);
if (failures) process.exit(1);
diff --git a/scripts/test-type-store.ts b/scripts/test-type-store.ts
index 276ff25f..5b79621f 100644
--- a/scripts/test-type-store.ts
+++ b/scripts/test-type-store.ts
@@ -10,8 +10,15 @@
// · undo/redo round-trips exactly, including interleaved
// · a block snapshot restores the block it names even after the body moved
-import { Store } from '../type/src/store.ts';
-import { emptyDoc, uid, type TypeDoc } from '../type/src/model.ts';
+import { register } from 'node:module';
+// The sync adapter (hostStore) pulls the kernel transport in, which uses
+// TypeScript node's strip-only loader cannot run — so this rig loads through
+// the repo's transpiling hooks, like the other rigs that reach the sync stack.
+register('./lib/ts-resolve-hooks.mjs', import.meta.url);
+const { Store } = await import('../type/src/store.ts');
+import type { TypeDoc } from '../type/src/model.ts';
+const { emptyDoc, uid, parseDoc } = await import('../type/src/model.ts');
+const { hostStore } = await import('../type/src/sync/session.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}`); };
@@ -130,5 +137,78 @@ H('listeners fire once per commit');
ok(n === 3, 'and unsubscribing stops them');
}
+console.log('\n— a receive-only copy takes no edits, and still receives —');
+{
+ // Through parseDoc, the way a real file arrives — the lock is decided from
+ // what survives intake, not from a hand-built object.
+ const docOf = (collab?: object): TypeDoc => {
+ const d: TypeDoc = { ...emptyDoc(), body: [{ id: 'p1', kind: 'para', text: 'agreed' }] };
+ const r = parseDoc(JSON.stringify(collab ? { ...d, collab } : d));
+ if (!r.ok) throw new Error('fixture did not parse');
+ return r.doc;
+ };
+ const room = { v: 2, on: true, room: 'w1', key: 'K', owner: 'OP' };
+ // FACTORIES, not shared objects: a Store holds the document it is given, so
+ // a case that writes through one (the remote-edit case below does) would
+ // otherwise leak into every later case that reuses the fixture — which is
+ // exactly how the first version of this section failed.
+ const writer = () => docOf({ ...room, ownerPriv: 'OK' });
+ const reader = () => docOf({ ...room, role: 'reader' });
+ const audience = () => docOf({ ...room, role: 'audience', invite: { pub: 'IP', priv: 'IK', role: 'audience', sig: 'S' } });
+ const local = () => docOf();
+ const edit = (st: Store) => st.commit(d => { d.body[0].text = 'CHANGED'; });
+ const text = (st: Store) => st.doc.body[0].text;
+
+ let st = new Store(writer()); edit(st);
+ ok(!st.locked && text(st) === 'CHANGED', 'a writer copy edits');
+ st = new Store(local()); edit(st);
+ ok(!st.locked && text(st) === 'CHANGED', 'a LOCAL document (no collab) edits — no room is not read-only');
+
+ st = new Store(reader()); edit(st);
+ ok(st.locked, 'a view-only reader copy is locked');
+ ok(text(st) === 'agreed', 'and a user edit is REFUSED — it would live only here and drift from the room');
+ ok(!st.canUndo, 'leaving nothing on the undo stack either');
+ st = new Store(audience()); edit(st);
+ ok(st.locked && text(st) === 'agreed', 'an audience copy is locked the same way');
+
+ // The sync session's own commits must still land — a reader needs a peer's
+ // published images more than anyone (kernel session.ts resolveBlobs).
+ st = new Store(reader());
+ hostStore(st).commit(() => { (st.doc.assets ??= {}).img = 'data:image/png;base64,AA=='; });
+ ok(st.doc.assets?.img !== undefined, "a SYSTEM commit through the session adapter gets through the lock — readers still get images");
+
+ // The copy's own CONNECTION state goes through the same adapter (collab.ts
+ // wraps the store with hostStore for kernel online.ts's sharing helpers),
+ // and `window.bento.sync.unshare()` reaches stopSharing on ANY copy. A viewer
+ // disconnecting must stick — not drop the socket while the file still says
+ // on:true and quietly rejoins next open. This is why `system: true` stays on
+ // the adapter even once no blob path needs it.
+ {
+ const { stopSharing } = await import('../kernel/src/sync/online.ts');
+ st = new Store(reader());
+ stopSharing({ removeTransport() {} } as never, hostStore(st));
+ ok(st.doc.collab?.on === false,
+ 'a READER can turn its own sharing off (bento.sync.unshare) — connection state is not a content edit');
+ }
+
+ // A remote edit is applied surgically and announced with touch(), never commit.
+ st = new Store(reader()); let heard = 0; st.on(() => heard++);
+ st.doc.body[0].text = 'from the room'; st.touch();
+ ok(heard === 1 && text(st) === 'from the room', 'a REMOTE edit still lands on a locked copy — it follows the room');
+
+ // THE ARRIVAL PATH bento/slides found: a receive-only copy loaded into an
+ // editor that is already running.
+ st = new Store(writer());
+ ok(!st.locked, 'an editor that boots on a writer copy starts unlocked');
+ st.replace(reader());
+ ok(st.locked, 'and LOCKS when a reader copy is loaded into it later (loadDoc, Replace from JSON, recovery)');
+ edit(st);
+ ok(text(st) === 'agreed', 'so the newly-arrived copy refuses edits too');
+ st.undo();
+ ok(!st.locked, 'undoing that replace restores the writer copy — and unlocks with it');
+ edit(st);
+ ok(text(st) === 'CHANGED', 'which edits again');
+}
+
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 91889cc9..4cf8a8c4 100644
--- a/type/src/collab.ts
+++ b/type/src/collab.ts
@@ -42,6 +42,7 @@ import { SyncSession, hostStore, type Peer, type SyncNotice } from './sync/sessi
import type { Store } from './store.ts';
import type { Editor } from './editor.ts';
import type { TypeDoc } from './model.ts';
+import { copyCanWrite } from './model.ts';
import { t } from './i18n.ts';
// ─────────────────────────────────────────────────────────────── small DOM
@@ -309,7 +310,10 @@ export function initCollab(store: Store, editor: Editor): void {
if (cme) {
let myRole: 'owner' | 'editor' | 'viewer' | undefined;
- if (cme.role === 'reader') myRole = 'viewer';
+ // A copy that cannot write is a Viewer whatever else it carries — an
+ // audience copy holds an owner-signed INVITE (its show ticket), and the
+ // line below would otherwise have called it an Editor.
+ if (!copyCanWrite(cme)) myRole = 'viewer';
else if (cme.v === 2 && cme.ownerPriv) myRole = 'owner';
else if (cme.v === 2 && cme.invite) myRole = 'editor';
if (myRole) {
@@ -366,7 +370,7 @@ export function initCollab(store: Store, editor: Editor): void {
status.textContent = t('○ Not live — turns on when you share');
}
- const canWrite = !!cme && cme.role !== 'reader';
+ const canWrite = copyCanWrite(cme);
if (canWrite) {
const label = el('div', 'tc-label');
label.textContent = t('Share a copy');
diff --git a/type/src/editor.ts b/type/src/editor.ts
index 6e5a7398..ca7a2ed3 100644
--- a/type/src/editor.ts
+++ b/type/src/editor.ts
@@ -39,7 +39,11 @@ export class Editor {
constructor(host: HTMLElement, store: Store) {
this.host = host;
this.store = store;
- host.contentEditable = 'true';
+ // Editable only while the copy may write — and kept in step with the store,
+ // because a receive-only copy can arrive AFTER boot (see Store.locked).
+ const follow = () => { host.contentEditable = store.locked ? 'false' : 'true'; };
+ follow();
+ store.on(follow);
host.spellcheck = true;
this.render();
host.addEventListener('beforeinput', this.#beforeInput);
diff --git a/type/src/model.ts b/type/src/model.ts
index d73bcdc7..ded462bb 100644
--- a/type/src/model.ts
+++ b/type/src/model.ts
@@ -345,8 +345,15 @@ export interface TypeDoc {
v?: number;
owner?: string;
ownerPriv?: string;
- /** 'reader' = this copy is a live viewer: receives updates, never sends. */
- role?: 'writer' | 'reader';
+ /**
+ * What this COPY may do. Absent or 'writer' = it writes. 'reader' = a live
+ * viewer: receives updates, never sends. 'audience' = a live-SHOW member
+ * (kernel sync, #454): its key is the show key and its transport is
+ * receive-only. Typed to match the kernel's own union (sync/crdt.ts) — it
+ * was narrower here, which is how a role the kernel can hand us came to be
+ * read as a writer by collab.ts. See `copyCanWrite`.
+ */
+ role?: 'writer' | 'reader' | 'audience';
invite?: {
pub: string;
priv: string;
@@ -361,6 +368,37 @@ export interface TypeDoc {
[extra: string]: unknown;
}
+/**
+ * May THIS COPY write to its room?
+ *
+ * An ALLOWLIST, and the shape is the point. collab.ts used to ask
+ * `role !== 'reader'`, which answers "yes" for every role invented after it —
+ * so when the kernel added 'audience' (a live-show member whose transport is
+ * receive-only), type labelled that copy an Editor and offered it "Invite to
+ * edit…", contradicting the transport underneath. Failing CLOSED is the safe
+ * direction: a future role that can write would show view-only chrome until
+ * someone teaches this function about it, which is a visible, harmless bug;
+ * the old shape's failure was an invisible, misleading one.
+ *
+ * Absent means writer because every file older than the role field is one.
+ */
+export function copyCanWrite(collab: TypeDoc['collab'] | undefined): boolean {
+ if (!collab) return false;
+ return collab.role === undefined || collab.role === 'writer';
+}
+
+/**
+ * Is this a RECEIVE-ONLY copy — one that follows a room and must not edit it?
+ *
+ * Not simply `!copyCanWrite`: a document with no `collab` at all is a local
+ * document and is perfectly editable; `copyCanWrite` answers "no" for it only
+ * because there is no room to write TO. This is the question the edit lock
+ * asks, and it is the same one bento/slides' `canWriteDeck` answers.
+ */
+export function copyIsReceiveOnly(collab: TypeDoc['collab'] | undefined): boolean {
+ return !!collab && !copyCanWrite(collab);
+}
+
/**
* The document as it should leave this app — WITHOUT its collaboration
* credentials.
diff --git a/type/src/store.ts b/type/src/store.ts
index b3c24816..ed9bb4df 100644
--- a/type/src/store.ts
+++ b/type/src/store.ts
@@ -19,6 +19,7 @@
// presses, not five plus however many times the page re-laid-out.
import type { Block, TypeDoc } from './model.ts';
+import { copyIsReceiveOnly } from './model.ts';
type Snap =
| { kind: 'doc'; doc: TypeDoc }
@@ -38,7 +39,22 @@ export class Store {
/** the open coalescing run, so a burst of typing is ONE undo step */
#run: string | null = null;
- constructor(doc: TypeDoc) { this.#doc = doc; }
+ constructor(doc: TypeDoc) { this.#doc = doc; this.#relock(); }
+
+ /**
+ * True while the document is a RECEIVE-ONLY copy (a view-only reader, or a
+ * live-show audience member). User edits are refused; see `commit`.
+ *
+ * DERIVED from the document and recomputed on every change, never set once
+ * at boot. A copy can arrive in a running editor by load, by `loadDoc`, by
+ * restoring a recovery snapshot, or by undoing a replace — and bento/slides
+ * found the version of this lock that was decided only at build time, which
+ * a dropped-in reader copy simply walked past. Deriving it means there is no
+ * path to forget.
+ */
+ #locked = false;
+ get locked(): boolean { return this.#locked; }
+ #relock(): void { this.#locked = copyIsReceiveOnly(this.#doc.collab); }
get doc(): TypeDoc { return this.#doc; }
get canUndo(): boolean { return this.#undo.length > 0; }
@@ -47,7 +63,7 @@ export class Store {
get undoDepth(): number { return this.#undo.length; }
on(fn: Listener): () => void { this.#listeners.add(fn); return () => this.#listeners.delete(fn); }
- #emit() { for (const fn of this.#listeners) fn(this.#doc); }
+ #emit() { this.#relock(); for (const fn of this.#listeners) fn(this.#doc); }
#snap(scope: Scope): Snap {
if (scope === 'doc') return { kind: 'doc', doc: clone(this.#doc) };
@@ -69,7 +85,14 @@ export class Store {
* one undo step, which is how a typed word is one press of ⌘Z rather than
* five. Any commit without a run, or with a different one, closes the group.
*/
- commit(fn: (doc: TypeDoc) => void, opts: { scope?: Scope; run?: string } = {}): void {
+ commit(fn: (doc: TypeDoc) => void, opts: { scope?: Scope; run?: string; system?: boolean } = {}): void {
+ // A receive-only copy takes no USER edits — the relay would drop them, so
+ // they would live only here and quietly diverge this file from the room it
+ // claims to follow. `system` is for the sync session's own bookkeeping
+ // (materialising a peer's published images, kernel session.ts
+ // resolveBlobs), which a reader needs more than anyone: blocking it would
+ // leave every reader looking at empty pictures.
+ if (this.#locked && !opts.system) return;
const scope = opts.scope ?? 'doc';
const run = opts.run ?? null;
if (run === null || run !== this.#run) this.#push(this.#snap(scope));
diff --git a/type/src/sync/session.ts b/type/src/sync/session.ts
index 4370c409..d0ea99f5 100644
--- a/type/src/sync/session.ts
+++ b/type/src/sync/session.ts
@@ -64,7 +64,18 @@ export function hostStore(store: Store, onRemoteApplied?: () => void): HostStore
store.touch();
onRemoteApplied?.();
},
- commit(fn: () => void) { store.commit(() => fn()); },
+ // SYSTEM commits, never content edits — so they must get through a
+ // receive-only copy's lock (see Store.commit). Two kinds reach here:
+ // · the session's blob bookkeeping (kernel session.ts offloadAssets /
+ // resolveBlobs — though kernel #604 moves resolveBlobs off commit);
+ // · the copy's own CONNECTION state, through collab.ts's use of this same
+ // wrapper: kernel online.ts startSharing / stopSharing / rotateKeys
+ // commit `doc.collab`. The share UI only offers those to writers, but
+ // `window.bento.sync.unshare()` is ungated — and a viewer choosing to
+ // disconnect is their preference, not an edit to the room. Without this
+ // flag it half-works: the transport drops, `collab.on` stays true, and
+ // the copy rejoins on its next open. test-type-store.ts pins that.
+ commit(fn: () => void) { store.commit(() => fn(), { system: true }); },
// type has no dirty flag: the document is saved from the editor's own
// state, and a remote edit does not change whether THIS person has
// unsaved work. Accepting and ignoring beats inventing a flag nothing reads.