Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

sync: the session's broadcast surface (client-side show) (#454)

nyblnet2666e20d5341
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4eafc840..c57af6e5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -892,6 +892,15 @@ jobs:
--outfile="$RUNNER_TEMP/test-sync-vouch.mjs"
node "$RUNNER_TEMP/test-sync-vouch.mjs"
+ - name: session broadcast surface rig
+ # startShow/endShow, the verb channel, and the audience's reception.
+ # What breaks silently if it regresses: the audsnap under the show key
+ # is the LIVE sync state instead of a fresh adopt of the projected doc,
+ # which leaks `stash` (deleted slides' notes) and the whole per-keystroke
+ # text history past the projection; or a local op reaches the audience
+ # without the app's projection applied. Both are mutation-caught here.
+ run: node scripts/test-sync-show.ts
+
- name: dash validator rig
# 109 checks over the shapes that read as DATA rather than as damage —
# a column shorter than the sheet has rows, a dictionary index past the
diff --git a/kernel/src/sync/crdt.ts b/kernel/src/sync/crdt.ts
index 92742b87..7f6dff8f 100644
--- a/kernel/src/sync/crdt.ts
+++ b/kernel/src/sync/crdt.ts
@@ -181,11 +181,11 @@ export interface CollabCreds {
sync?: SyncStateJSON
writerPub?: string
writerPriv?: string
- role?: 'writer' | 'reader'
+ role?: 'writer' | 'reader' | 'audience'
v?: number
owner?: string
ownerPriv?: string
- invite?: { pub: string; priv: string; role: 'writer' | 'commenter'; exp?: number; sig: string }
+ invite?: { pub: string; priv: string; role: 'writer' | 'commenter' | 'audience'; exp?: number; sig: string }
}
/** A blob the document references but does not inline. */
diff --git a/kernel/src/sync/online.ts b/kernel/src/sync/online.ts
index 6dc642ff..f743d71a 100644
--- a/kernel/src/sync/online.ts
+++ b/kernel/src/sync/online.ts
@@ -77,14 +77,14 @@ async function mintKeypair(): Promise<{ pub: string; priv: string }> {
}
}
-export type CollabInvite = { pub: string; priv: string; role: 'writer' | 'commenter'; exp?: number; sig: string }
+export type CollabInvite = { pub: string; priv: string; role: 'writer' | 'commenter' | 'audience'; exp?: number; sig: string }
/** Owner-signed invite: a delegation keypair whose private half rides in the
* shared copy. Chain: owner signs `inv.${pub}.${role}.${exp||0}`; a joining
* device later signs its own pubkey with the invite key (`dlg.${memberPub}`).
* The relay verifies both signatures and never sees private material — so a
* blind relay still cannot certify its own key. */
-export async function mintInvite(ownerPrivB64: string, role: 'writer' | 'commenter' = 'writer', exp = 0): Promise<CollabInvite> {
+export async function mintInvite(ownerPrivB64: string, role: 'writer' | 'commenter' | 'audience' = 'writer', exp = 0): Promise<CollabInvite> {
const kp = await mintKeypair()
const sig = await signText(ownerPrivB64, `inv.${kp.pub}.${role}.${exp}`)
return { pub: kp.pub, priv: kp.priv, role, ...(exp ? { exp } : {}), sig }
@@ -242,11 +242,31 @@ export class OnlineTransport implements Transport {
/** the relay refused a frame; `ops` are the ones it will never accept
* (null when the refusal couldn't be pinned to a frame we sent) */
onRefused?: (code: RefusalCode, ops: Op[] | null) => void
+ // ——— broadcast reception (audience side, and the presenter's own
+ // checkpoint/count signals). All optional: a session with no show wires
+ // none of them and nothing below fires. ———
+ /** an aud op batch (audience): apply through the reader path */
+ onShowOps?: (ops: Op[]) => void
+ /** an aud snapshot (audience): the whole show document under Ke */
+ onShowSnap?: (doc: SyncDoc, state: SyncStateJSON) => void
+ /** a control verb (audience): nav/black/laser with its decrypted payload */
+ onShowVerb?: (kind: 'nav' | 'black' | 'laser', payload: unknown) => void
+ /** the relay asks the presenter to checkpoint (soft cap or show-full) */
+ onShowCheckpoint?: () => void
+ /** coarse audience count, to the presenter */
+ onShowCount?: (n: number) => void
+ /** an audience socket was closed by the relay (4001 end/grace, 4002
+ * not-live, 4003 show-full, 1008 revoked) */
+ onShowClosed?: (code: number) => void
},
private auth?: AuthSpec,
) {
this.docId = docId
this.writeReadyP = new Promise<void>((r) => { this.resolveWriteReady = r })
+ // Known before init's async work: an audience socket is a chain whose
+ // invite the owner signed with role 'audience'. Set here so startShow and
+ // the send guards see it immediately.
+ this.audienceMode = auth?.kind === 'chain' && auth.invite.role === 'audience'
this.init(room)
}
@@ -289,6 +309,14 @@ export class OnlineTransport implements Transport {
* something and unstamped content-bearing frames can be refused. Legacy
* `r` rooms sign nothing — gating there would drop every legitimate frame. */
private signedRoom = false
+ /** An audience socket: connects on the audience path (ivr=audience) and is
+ * RECEIVE-ONLY — it sends no protocol frame, only the transport keepalive.
+ * The relay drops anything else it sent, but a client that does not send it
+ * in the first place cannot leak presence or an op it should not have. */
+ private audienceMode = false
+ /** True when this transport is an audience socket — receive-only. The session
+ * refuses startShow on it, and every show sender below no-ops. */
+ get audience(): boolean { return this.audienceMode }
private async init(room: string) {
const raw = b64u.dec(this.keyB64)
@@ -327,7 +355,11 @@ export class OnlineTransport implements Transport {
this.myPub = id.pub
const iv = a.invite
const dg = await signText(iv.priv, `dlg.${id.pub}`)
- this.url = `${room}?tok=${tok}&bt=1&w=${id.pub}&o=${a.owner}` +
+ // An audience member connects on the audience path: ivr=audience (which
+ // the owner signed into the invite), no bt (it never proves, never gets a
+ // ticket), and receive-only. audienceMode was set in the constructor.
+ const bt = this.audienceMode ? '' : '&bt=1'
+ this.url = `${room}?tok=${tok}${bt}&w=${id.pub}&o=${a.owner}` +
`&ivp=${iv.pub}&ivr=${iv.role}&ive=${iv.exp ?? 0}&ivs=${iv.sig}&dg=${dg}`
} else {
this.url = `${room}?tok=${tok}`
@@ -377,15 +409,24 @@ export class OnlineTransport implements Transport {
if (data === 'pong') { this.awaitingPong = false; return } // keepalive reply
this.onEnvelope(data).catch(() => {})
}
- const drop = () => {
+ const drop = (ev?: { code?: number }) => {
if (this.ws !== ws) return
this.stopHeartbeat()
this.ws = null
this.setStatus('closed')
+ // Broadcast close codes carry meaning: the relay closed an audience
+ // socket deliberately. 4001 end/grace and 1008 revoked are TERMINAL —
+ // the show is over or access is gone, so do not reconnect into a wall;
+ // 4002 not-live and 4003 show-full are transient (the presenter has not
+ // gone live yet, or the show is momentarily full), so reconnect with
+ // backoff — that IS the "waiting for the presenter" state.
+ const code = ev?.code
+ if (code && code >= 4001 && code <= 4003 || code === 1008) this.hooks.onShowClosed?.(code!)
+ if (code === 4001 || code === 1008) { this.closed = true; return }
this.retry()
}
ws.onclose = drop
- ws.onerror = drop
+ ws.onerror = () => drop()
}
private startHeartbeat(ws: WebSocket) {
@@ -538,6 +579,9 @@ export class OnlineTransport implements Transport {
wt?: string
/** possession nonce on `ready`: sign it to prove the `?w=` key is ours */
c?: string
+ /** broadcast: the audience stream tag, the verb name, the count */
+ s?: string
+ n?: number
} & RefusedEnv
try {
env = JSON.parse(text)
@@ -573,6 +617,9 @@ export class OnlineTransport implements Transport {
this.handleRefusal(env)
return
}
+ // ——— broadcast control, no encrypted body ———
+ if (env.ctl === 'audckpt') { this.hooks.onShowCheckpoint?.(); return }
+ if (env.ctl === 'audcount') { if (typeof env.n === 'number') this.hooks.onShowCount?.(env.n); return }
if (env.ctl === 'ack' || env.ctl === 'ready') {
// one ack = the oldest un-acked persisted frame landed
if (env.ctl === 'ack') this.awaitingAck.shift()
@@ -580,6 +627,14 @@ export class OnlineTransport implements Transport {
this.saveSeq(env.q)
this.maybeSnapshot(env.q)
}
+ if (env.ctl === 'ready' && typeof env.q !== 'number') {
+ // An AUDIENCE ready: `bc`/`v`, no `q`. The audience is receive-only and
+ // has no op log to replay or snapshot — running the collab path below
+ // would make it try to upload one. It is simply live now.
+ this.inReplay = false
+ this.resolveWriteReady()
+ return
+ }
if (env.ctl === 'ready') {
// `c` is the relay's possession challenge, present only for a socket
// whose `?w=` hash-matched the room. Answer it and the ticket follows on
@@ -614,6 +669,25 @@ export class OnlineTransport implements Transport {
return // wrong key / corrupted — ignore
}
if (typeof env.q === 'number') this.saveSeq(env.q)
+ // ——— broadcast reception (audience side). These arrive pre-routed by the
+ // relay, which only fans them to audience sockets and verified every
+ // signed one; the payload is under Ke, which only show participants hold.
+ // So they do not go through vouched() — that is the ROOM's read-only
+ // guarantee, a different trust path from the relay-routed show stream. ———
+ if (env.s === 'aud' && !env.ctl) {
+ const f = payload as { ops?: Op[] }
+ if (f?.ops) this.hooks.onShowOps?.(f.ops)
+ return
+ }
+ if (env.ctl === 'audsnap') {
+ const sn = payload as { doc: SyncDoc; state: SyncStateJSON }
+ if (sn?.doc && sn.state) this.hooks.onShowSnap?.(sn.doc, sn.state)
+ return
+ }
+ if (env.ctl === 'nav' || env.ctl === 'black' || env.ctl === 'laser') {
+ this.hooks.onShowVerb?.(env.ctl, payload)
+ return
+ }
if (env.snap === 1) {
if (!this.vouched(env)) return
const s = payload as { doc: SyncDoc; state: SyncStateJSON }
@@ -691,19 +765,82 @@ export class OnlineTransport implements Transport {
}
}
- private async encrypt(plain: string): Promise<{ i: string; d: string } | null> {
- if (!this.key) return null
+ private async encrypt(plain: string, key: CryptoKey | null = this.key): Promise<{ i: string; d: string } | null> {
+ if (!key) return null
const iv = new Uint8Array(12)
crypto.getRandomValues(iv)
const ct = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: iv as BufferSource },
- this.key,
+ key,
new TextEncoder().encode(plain),
)
return { i: b64u.enc(iv), d: b64u.enc(new Uint8Array(ct)) }
}
+ // ——— BROADCAST: the presenter's audience stream ———
+ // The presenter's socket carries the room key (this.key). A show's audience
+ // holds a SEPARATE show key Ke; the presenter encrypts a second copy of each
+ // op batch and each control frame under Ke, tagged s:'aud', and the relay
+ // routes those to audience sockets only. Only the presenter side needs this:
+ // an audience copy's own this.key already IS Ke (its collab.key is the show
+ // key), so it decrypts s:'aud' frames on the ordinary path below.
+ private showKey: CryptoKey | null = null
+
+ /** Install (or clear) the show key. Raw AES-GCM key, base64url. */
+ async setShowKey(rawB64: string | null): Promise<void> {
+ if (this.audienceMode) return
+ this.showKey = rawB64
+ ? await crypto.subtle.importKey('raw', b64u.dec(rawB64) as BufferSource, 'AES-GCM', false, ['encrypt'])
+ : null
+ }
+
+ /** One op batch to the audience: sealed under Ke, tagged s:'aud'. NEVER
+ * persisted by the relay (it ignores p on this stream), so it does not join
+ * the resend log — a dropped aud batch is recovered by the next audsnap, not
+ * by replay. Silent no-op if there is no show key or the socket is gone. */
+ async sendAud(ops: Op[]): Promise<void> {
+ if (this.audienceMode) return
+ const enc = await this.encrypt(JSON.stringify({ t: 'ops', a: 'show', ops }), this.showKey)
+ if (!enc || !this.ws) return
+ try { this.ws.send(JSON.stringify({ s: 'aud', i: enc.i, d: enc.d })) } catch { /* gone */ }
+ }
+
+ /** The whole (already app-projected) document to the audience, under Ke. */
+ async sendAudSnap(doc: SyncDoc, state: SyncStateJSON): Promise<void> {
+ if (this.audienceMode) return
+ const enc = await this.encrypt(JSON.stringify({ doc, state }), this.showKey)
+ if (!enc || !this.ws) return
+ try { this.ws.send(JSON.stringify({ ctl: 'audsnap', i: enc.i, d: enc.d })) } catch { /* gone */ }
+ }
+
+ /** A control verb. live/end sign the literal; nav/black encrypt their payload
+ * under Ke and sign the ciphertext with the stream in the text (so a
+ * room-stream signature cannot be replayed as the audience's); laser is
+ * unsigned. The relay checks all of this against the socket's proven key. */
+ async sendVerb(kind: 'live' | 'end' | 'nav' | 'black' | 'laser', payload?: unknown): Promise<void> {
+ if (this.audienceMode || !this.ws) return
+ try {
+ if (kind === 'live' || kind === 'end') {
+ const g = this.signKey ? await signWith(this.signKey, kind) : undefined
+ this.ws.send(JSON.stringify({ ctl: kind, g }))
+ return
+ }
+ const enc = await this.encrypt(JSON.stringify(payload ?? null), this.showKey)
+ if (!enc) return
+ if (kind === 'laser') {
+ this.ws.send(JSON.stringify({ ctl: 'laser', s: 'aud', i: enc.i, d: enc.d }))
+ return
+ }
+ const g = this.signKey ? await signFrame(this.signKey, `${kind}.aud.${enc.i}`, enc.d) : undefined
+ this.ws.send(JSON.stringify({ ctl: kind, s: 'aud', i: enc.i, d: enc.d, g }))
+ } catch { /* gone */ }
+ }
+
send(frame: Frame) {
+ // An audience socket is receive-only: it never puts a protocol frame on the
+ // wire (the relay would drop it, but not sending it is the guarantee). The
+ // keepalive ping is not a protocol frame and is left alone.
+ if (this.audienceMode) return
void (async () => {
const enc = await this.encrypt(JSON.stringify(frame))
if (!enc) return
@@ -787,7 +924,15 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
// v2 owner → direct with ownerPriv; v2 member → invite chain (device key
// minted per-machine); legacy → the shared writer key pair.
let auth: AuthSpec | undefined
- if (collab.role !== 'reader') {
+ if (collab.role === 'audience') {
+ // An AUDIENCE copy: its collab.key is the show key Ke, its invite is the
+ // owner-signed `audience` ticket. It joins on the chain (ivr=audience,
+ // set from the invite role) and the transport makes it receive-only. No
+ // audience invite, no join — there is nothing to fall back to.
+ if (collab.owner && collab.invite) {
+ auth = { kind: 'chain', owner: collab.owner, invite: collab.invite, docId }
+ }
+ } else if (collab.role !== 'reader') {
if (collab.v === 2 && collab.owner && collab.ownerPriv) {
auth = { kind: 'direct', pub: collab.owner, priv: collab.ownerPriv }
} else if (collab.v === 2 && collab.owner && collab.invite) {
@@ -801,7 +946,18 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
getSnapshot: () => session.snapshot(),
onOpen: () => session.hello(),
onReady: (seen) => session.onRelayReady(seen),
- onRefused: (code, ops) => session.refused(code, ops),
+ onRefused: (code, ops) => {
+ // show-full is a broadcast refusal: it means "checkpoint now", handled
+ // by the show path, not the collab resend log.
+ if ((code as string) === 'show-full') { session.showCheckpoint(); return }
+ session.refused(code, ops)
+ },
+ onShowOps: (ops) => session.applyShowOps(ops),
+ onShowSnap: (doc, state) => session.applyShowSnap(doc, state),
+ onShowVerb: (kind, payload) => session.showVerb(kind, payload),
+ onShowCheckpoint: () => session.showCheckpoint(),
+ onShowCount: (n) => session.showCount(n),
+ onShowClosed: (code) => session.showClosed(code),
}, auth)
return active
})
diff --git a/kernel/src/sync/session.ts b/kernel/src/sync/session.ts
index b25f88bd..55ca48fe 100644
--- a/kernel/src/sync/session.ts
+++ b/kernel/src/sync/session.ts
@@ -201,6 +201,51 @@ export interface Transport {
readonly kind: string
send(frame: Frame): void
close(): void
+ // ——— broadcast (the online transport only; BroadcastChannel has no show) ———
+ /** resolves once the socket may write (proven, or an older/relay reader) */
+ writeReady?(): Promise<void>
+ /** true when this is a receive-only audience socket */
+ readonly audience?: boolean
+ /** import (or clear, with null) the per-show key Ke */
+ setShowKey?(rawB64: string | null): Promise<void>
+ /** an op batch to the audience, sealed under Ke */
+ sendAud?(ops: Op[]): void | Promise<void>
+ /** the whole projected document to the audience, under Ke */
+ sendAudSnap?(doc: SyncDoc, state: SyncStateJSON): void | Promise<void>
+ /** a control verb: live/end (signed literal) or nav/black/laser (under Ke) */
+ sendVerb?(kind: 'live' | 'end' | 'nav' | 'black' | 'laser', payload?: unknown): void | Promise<void>
+}
+
+/** What a broadcast surfaces to the app. The audience acts on `verb` and
+ * `closed`; the presenter on `checkpoint` (send a fresh audsnap — the session
+ * does that for you) and `count`. */
+export type ShowEvent =
+ | { t: 'verb'; kind: 'nav' | 'black' | 'laser'; payload: unknown }
+ | { t: 'closed'; code: number }
+ | { t: 'checkpoint' }
+ | { t: 'count'; n: number }
+
+/** The presenter's control surface, live only while a show is on. Every call
+ * is a no-op before the socket is proven — startShow awaits that first. */
+export interface ShowVerbs {
+ nav(payload: unknown): void
+ black(payload: unknown): void
+ laser(payload: unknown): void
+}
+
+/** What the app injects to run a show. The kernel never learns the app's field
+ * names: `projectOp` decides which ops an audience may see, `snapshot` returns
+ * the ALREADY-PROJECTED document. Both are the app's (slides/src/audience.ts). */
+export interface ShowConfig {
+ /** raw AES-GCM show key Ke, base64url */
+ showKey: string
+ /** null = this op is not for the audience (dropped from the aud stream) */
+ projectOp(op: Op): Op | null
+ /** the projected document ONLY. The session builds the sync state itself
+ * (freshAudState) — an adopt of this doc, so no stash or text history leaks
+ * past the projection. The app must NOT supply a state; there is nowhere it
+ * could get a safe one. */
+ snapshot(): { doc: SyncDoc }
}
/**
@@ -524,6 +569,7 @@ export class SyncSession {
if (!ops.length) return
this.log.push(...ops)
this.broadcast({ t: 'ops', a: this.actor, ops })
+ if (this.showCfg) this.projectToAudience(ops)
}
/**
@@ -619,6 +665,13 @@ export class SyncSession {
} finally {
this.applying = false
}
+ // While presenting, a CO-PRESENTER's edits arrive here, not through flush,
+ // so they must be projected onto the aud stream too — otherwise the
+ // audience sees another writer's changes only at the next checkpoint. Only
+ // the presenter has a show config, so this fires for it alone; the audience
+ // (which reaches applyRemote via applyShowOps) has none and re-projects
+ // nothing.
+ if (this.showCfg) this.projectToAudience(ops)
if (this.state.gappedActors.length) {
this.send({ t: 'need', a: this.actor, vv: this.state.vv })
}
@@ -727,6 +780,94 @@ export class SyncSession {
// --- relay refusals -------------------------------------------------------
+ // ——— broadcast: the presenter's show, and the audience's reception ———
+ private showCfg: ShowConfig | null = null
+ private showListeners = new Set<(e: ShowEvent) => void>()
+
+ /** The presenter's live-verb surface, or null when no show is running. */
+ show: ShowVerbs | null = null
+
+ /** Subscribe to show events (verbs, count, checkpoint, close). */
+ onShow(fn: (e: ShowEvent) => void): () => void {
+ this.showListeners.add(fn)
+ return () => this.showListeners.delete(fn)
+ }
+ private emitShow(e: ShowEvent) { this.showListeners.forEach((fn) => fn(e)) }
+
+ /** The online transport, if one is connected — the only one with a show. */
+ private showTransport(): Transport | undefined {
+ return this.transports.find((t) => typeof t.setShowKey === 'function')
+ }
+
+ /** A sync state built ONLY from the projected doc — adopt-shaped, so it
+ * carries no stash and no text history to leak past the projection. */
+ private freshAudState(doc: SyncDoc): SyncStateJSON {
+ const eng = new this.host.engine(this.actor)
+ eng.adopt(doc as never)
+ return JSON.parse(JSON.stringify(eng.toJSON())) as SyncStateJSON
+ }
+
+ /**
+ * Begin broadcasting. The caller is already sharing (a proven writer); this
+ * installs the show key, waits until the socket may write, sends the first
+ * audsnap, and opens the verb surface. Ops flow to the audience from the next
+ * flush on. Idempotent-ish: a second call replaces the config.
+ */
+ async startShow(cfg: ShowConfig): Promise<void> {
+ const tr = this.showTransport()
+ if (!tr?.setShowKey) throw new Error('startShow: no online transport to broadcast on')
+ if (tr.audience) throw new Error('startShow: an audience copy cannot present')
+ this.showCfg = cfg
+ await tr.setShowKey(cfg.showKey)
+ await tr.writeReady?.()
+ await tr.sendVerb?.('live')
+ const snap = cfg.snapshot()
+ await tr.sendAudSnap?.(snap.doc, this.freshAudState(snap.doc))
+ this.show = {
+ nav: (p) => { void this.showTransport()?.sendVerb?.('nav', p) },
+ black: (p) => { void this.showTransport()?.sendVerb?.('black', p) },
+ laser: (p) => { void this.showTransport()?.sendVerb?.('laser', p) },
+ }
+ }
+
+ /** End the show: a signed `end`, then the key is dropped. */
+ async endShow(): Promise<void> {
+ const tr = this.showTransport()
+ this.show = null
+ this.showCfg = null
+ await tr?.sendVerb?.('end')
+ await tr?.setShowKey?.(null)
+ }
+
+ /** Each local op batch, projected onto the aud stream. An op the app maps to
+ * null is not the audience's to see; a batch that projects to nothing sends
+ * no frame. */
+ private projectToAudience(ops: Op[]) {
+ if (!this.showCfg) return
+ const projected: Op[] = []
+ for (const op of ops) { const p = this.showCfg.projectOp(op); if (p) projected.push(p) }
+ if (projected.length) void this.showTransport()?.sendAud?.(projected)
+ }
+
+ /** The relay asked us to checkpoint (soft cap) or refused an aud op
+ * (show-full). Either way a fresh audsnap re-bases the audience and resets
+ * the relay's cap; the audsnap subsumes any refused batch, so nothing needs
+ * resending. The session does this itself (it holds snapshot()); the event
+ * is for the app's awareness. */
+ showCheckpoint(): void {
+ if (!this.showCfg) return
+ const snap = this.showCfg.snapshot()
+ void this.showTransport()?.sendAudSnap?.(snap.doc, this.freshAudState(snap.doc))
+ this.emitShow({ t: 'checkpoint' })
+ }
+ showCount(n: number): void { this.emitShow({ t: 'count', n }) }
+ showVerb(kind: 'nav' | 'black' | 'laser', payload: unknown): void { this.emitShow({ t: 'verb', kind, payload }) }
+ showClosed(code: number): void { this.emitShow({ t: 'closed', code }) }
+ /** An aud op batch arrived (audience): apply through the reader path. */
+ applyShowOps(ops: Op[]): void { this.applyRemote(ops) }
+ /** An aud snapshot arrived (audience). */
+ applyShowSnap(doc: SyncDoc, state: SyncStateJSON): void { this.applySnapshot(doc, state) }
+
/** the editor subscribes here to toast what the relay refused */
onNotice(fn: (n: SyncNotice) => void): () => void {
this.noticeListeners.add(fn)
diff --git a/scripts/test-sync-show.ts b/scripts/test-sync-show.ts
new file mode 100644
index 00000000..5c03b263
--- /dev/null
+++ b/scripts/test-sync-show.ts
@@ -0,0 +1,236 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The SESSION's broadcast surface — startShow/endShow, the verb channel, the
+// projection onto the aud stream, and the audience's reception.
+//
+// node scripts/test-sync-show.ts
+//
+// Drives the REAL SyncSession over a REAL slides Store, with a recording fake
+// online transport in place of the relay, so the assertions are about the
+// session's actual control flow. What it proves:
+//
+// 1. startShow installs the show key, waits until the socket may write, and
+// sends `live` then a first audsnap — in that order.
+// 2. THE AUDSNAP STATE IS FRESH-ADOPT, not the live state. Security's finding:
+// the live/stampInto state carries `stash` (dead-window values — deleted
+// slides' notes) and per-character `txt` history, neither of which the
+// projection removed. The audsnap state must be rebuilt from the projected
+// doc alone. Asserted three ways: byte-identical to an independent adopt,
+// empty stash, empty txt — while the LIVE state has both populated.
+// 3. THE PROJECTION IS APPLIED. An op the app maps to null never reaches the
+// aud stream; a batch that projects to nothing sends no frame.
+// 4. The verb surface (nav/black/laser) is null until a show is on, then
+// sends signed control frames; endShow sends `end` and drops the key.
+// 5. checkpoint (soft cap or show-full) re-bases the audience with a fresh
+// audsnap the session builds itself, and surfaces a `checkpoint` event.
+// 6. THE AUDIENCE applies aud ops through the reader path (no re-broadcast),
+// applies an audsnap, and surfaces verbs / count / close as show events.
+
+const listeners: Record<string, Array<() => void>> = {};
+(globalThis as unknown as { window: unknown }).window = {
+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),
+ clearTimeout: (h: number) => clearTimeout(h),
+ setInterval: (fn: () => void, ms: number) => setInterval(fn, ms),
+ clearInterval: (h: number) => clearInterval(h),
+ addEventListener: (ev: string, fn: () => void) => { (listeners[ev] ??= []).push(fn); },
+};
+
+const { register } = await import('node:module');
+register('./lib/ts-resolve-hooks.mjs', import.meta.url);
+
+const { Store } = await import('../slides/src/store.ts');
+const { SyncSession } = await import('../slides/src/sync/session.ts');
+const { newDoc, emptySlide } = await import('../slides/src/model.ts');
+// slides' engine is bound to its doc shape; the independent adopt below must
+// use the SAME bound engine the session uses, not the bare kernel one.
+const { SyncState } = await import('../slides/src/sync/crdt.ts');
+
+let failures = 0, checks = 0;
+function ok(cond: boolean, msg: string) {
+ checks++;
+ if (!cond) { failures++; console.log(` FAIL ${msg}`); } else console.log(` ok ${msg}`);
+}
+const H = (s: string) => console.log(`\n=== ${s} ===`);
+const settle = (ms = 260) => new Promise(r => setTimeout(r, ms));
+type Op = { a: string; l: number; op: string; sl?: string; el?: string; k?: string; v?: unknown };
+
+/** A recording stand-in for the online transport. The session finds it by its
+ * setShowKey method, exactly as it finds the real one. */
+function recorder() {
+ const rec = {
+ kind: 'online',
+ showKey: null as string | null,
+ aud: [] as Op[][],
+ snaps: [] as Array<{ doc: unknown; state: Record<string, unknown> }>,
+ verbs: [] as Array<{ kind: string; payload?: unknown }>,
+ send() {},
+ close() {},
+ writeReady: () => Promise.resolve(),
+ setShowKey(k: string | null) { rec.showKey = k; return Promise.resolve(); },
+ sendAud(ops: Op[]) { rec.aud.push(ops); },
+ sendAudSnap(doc: unknown, state: Record<string, unknown>) { rec.snaps.push({ doc, state }); },
+ sendVerb(kind: string, payload?: unknown) { rec.verbs.push({ kind, payload }); return Promise.resolve(); },
+ };
+ return rec;
+}
+
+function deckWithSecret() {
+ const doc = newDoc();
+ doc.docId = `show-${Math.random().toString(36).slice(2, 10)}`;
+ doc.slides = [
+ { ...emptySlide(), id: 's1', notes: 'public notes', elements: [
+ { id: 'e1', type: 'text', x: 100, y: 100, w: 600, h: 120, html: 'Title' },
+ { id: 'e2', type: 'text', x: 100, y: 300, w: 600, h: 120, html: 'Body' },
+ ] },
+ { ...emptySlide(), id: 'secret', notes: 'CONFIDENTIAL speaker notes', elements: [
+ { id: 'se1', type: 'text', x: 100, y: 100, w: 600, h: 120, html: 'Rehearsal only' },
+ ] },
+ ] as never;
+ return doc;
+}
+
+/** The projection slides would inject: drop the secret slide and its elements. */
+const projectDoc = (doc: { slides: Array<{ id: string }> }) => {
+ const c = JSON.parse(JSON.stringify(doc));
+ c.slides = c.slides.filter((s: { id: string }) => s.id !== 'secret');
+ return c;
+};
+const projectOp = (op: Op): Op | null => (op.sl === 'secret' || (op.el ?? '').includes('se1') ? null : op);
+
+console.log('bento-sync — the session broadcast surface\n');
+
+H('startShow: key, then live, then a fresh-adopt audsnap');
+{
+ const store = new Store(deckWithSecret());
+ const s = new SyncSession(store);
+ const tr = recorder();
+ s.addTransport(() => tr as never);
+ // give the LIVE session real text history + a dead-window value, so "the
+ // audsnap is not the live state" is a real contrast and not vacuous
+ store.commit(() => { store.doc.slides[0].elements[0].html = 'Title v2'; });
+ await settle();
+ store.commit(() => { store.doc.slides[0].elements[0].html = 'Title v3 typed'; });
+ await settle();
+ const liveState = s.snapshot().state as Record<string, unknown>;
+
+ await s.startShow({ showKey: 'c2hvd2tleTMyYnl0ZXNj2hvd2tleTMyYnl0ZQ', projectOp, snapshot: () => ({ doc: projectDoc(store.doc) }) });
+
+ ok(tr.showKey === 'c2hvd2tleTMyYnl0ZXNj2hvd2tleTMyYnl0ZQ', 'the show key was installed on the transport');
+ ok(tr.verbs.length === 1 && tr.verbs[0].kind === 'live', 'a `live` verb was sent');
+ ok(tr.snaps.length === 1, 'a first audsnap was sent');
+
+ const audState = tr.snaps[0].state;
+ // (2a) byte-identical to an independent adopt of the projected doc
+ const eng = new SyncState((s as unknown as { actor: string }).actor);
+ (eng as unknown as { adopt(d: unknown): void }).adopt(projectDoc(store.doc));
+ const independent = JSON.parse(JSON.stringify(eng.toJSON()));
+ ok(JSON.stringify(audState) === JSON.stringify(independent), 'the audsnap state is byte-identical to a fresh adopt of the projected doc');
+ // (2b) explicitly: no stash, no txt history — the two leak channels
+ ok(JSON.stringify(audState.stash ?? {}) === '{}', 'the audsnap state carries NO stash (no dead-window values)');
+ ok(JSON.stringify(audState.txt ?? {}) === '{}', 'the audsnap state carries NO per-character text history');
+ // and the LIVE state HAS them, so the contrast is real
+ ok(JSON.stringify(liveState.txt ?? {}) !== '{}', 'the LIVE state does carry text history (the thing not leaked)');
+ // (2c) the secret slide is not in the projected state
+ ok(!Object.keys(audState.pos as object).some(k => k.includes('secret')), 'the secret slide is absent from the audsnap state');
+ ok(!(tr.snaps[0].doc as { slides: Array<{id:string}> }).slides.some(sl => sl.id === 'secret'), 'and absent from the audsnap doc');
+
+ s.stop?.();
+}
+
+H('the projection filters the aud op stream');
+{
+ const store = new Store(deckWithSecret());
+ const s = new SyncSession(store);
+ const tr = recorder();
+ s.addTransport(() => tr as never);
+ await s.startShow({ showKey: 'c2hvd2tleTMyYnl0ZXNj2hvd2tleTMyYnl0ZQ', projectOp, snapshot: () => ({ doc: projectDoc(store.doc) }) });
+ tr.aud.length = 0;
+
+ // one commit touching a PUBLIC element and a SECRET one
+ store.commit(() => {
+ store.doc.slides[0].elements[1].html = 'Body edited';
+ store.doc.slides[1].elements[0].html = 'secret edited';
+ });
+ await settle();
+ ok(tr.aud.length >= 1, 'the public edit reached the aud stream');
+ const all = tr.aud.flat();
+ ok(all.length > 0 && all.every(op => op.el !== 'se1' && op.sl !== 'secret'), 'no secret op is on the aud stream');
+ ok(all.some(op => (op.el ?? '').includes('e2')), 'the public op is (composite elKey)');
+
+ // a commit touching ONLY the secret sends nothing
+ tr.aud.length = 0;
+ store.commit(() => { store.doc.slides[1].elements[0].html = 'secret again'; });
+ await settle();
+ ok(tr.aud.length === 0, 'a batch that projects to nothing sends no aud frame');
+ s.stop?.();
+}
+
+H('the verb surface, and endShow');
+{
+ const store = new Store(deckWithSecret());
+ const s = new SyncSession(store);
+ const tr = recorder();
+ s.addTransport(() => tr as never);
+ ok(s.show === null, 'no verb surface before a show');
+ await s.startShow({ showKey: 'c2hvd2tleTMyYnl0ZXNj2hvd2tleTMyYnl0ZQ', projectOp, snapshot: () => ({ doc: projectDoc(store.doc) }) });
+ ok(s.show !== null, 'the verb surface exists during a show');
+ tr.verbs.length = 0;
+ s.show!.nav({ id: 's1' });
+ s.show!.black({ on: true });
+ s.show!.laser({ x: 1, y: 2 });
+ await settle(20);
+ ok(tr.verbs.filter(v => v.kind === 'nav')[0]?.payload && (tr.verbs.find(v=>v.kind==='nav')!.payload as {id:string}).id === 's1', 'nav carries its payload');
+ ok(tr.verbs.some(v => v.kind === 'black') && tr.verbs.some(v => v.kind === 'laser'), 'black and laser are sent');
+ await s.endShow();
+ ok(s.show === null, 'endShow closes the verb surface');
+ ok(tr.verbs.some(v => v.kind === 'end'), 'endShow sends `end`');
+ ok(tr.showKey === null, 'and drops the show key');
+ s.stop?.();
+}
+
+H('checkpoint re-bases the audience with a fresh audsnap');
+{
+ const store = new Store(deckWithSecret());
+ const s = new SyncSession(store);
+ const tr = recorder();
+ s.addTransport(() => tr as never);
+ const events: Array<{ t: string }> = [];
+ s.onShow(e => events.push(e));
+ await s.startShow({ showKey: 'c2hvd2tleTMyYnl0ZXNj2hvd2tleTMyYnl0ZQ', projectOp, snapshot: () => ({ doc: projectDoc(store.doc) }) });
+ tr.snaps.length = 0;
+ s.showCheckpoint();
+ ok(tr.snaps.length === 1, 'checkpoint sends a fresh audsnap');
+ ok(JSON.stringify(tr.snaps[0].state.stash ?? {}) === '{}', 'and it too is stash-free');
+ ok(events.some(e => e.t === 'checkpoint'), 'checkpoint surfaces an event to the app');
+ s.stop?.();
+}
+
+H('the audience: reader-path apply, snapshot, and show events');
+{
+ const store = new Store(deckWithSecret());
+ const s = new SyncSession(store);
+ // an audience session never startShow's; it only receives.
+ const events: Array<Record<string, unknown>> = [];
+ s.onShow(e => events.push(e as never));
+
+ // an aud op applies through the reader path (state.apply + emit, not commit)
+ s.applyShowOps([{ a: 'pres', s: 1, l: 9, op: 'set', sl: 's1', el: 's1\u001fe1', k: 'x', v: 777 } as never]);
+ ok(store.doc.slides[0].elements[0].x === 777, 'an aud op applies to the document (reader path)');
+
+ // a verb surfaces
+ s.showVerb('nav', { id: 's2' });
+ s.showVerb('black', { on: true });
+ ok(events.some(e => e.t === 'verb' && e.kind === 'nav' && (e.payload as {id:string}).id === 's2'), 'a nav verb surfaces with its payload');
+ ok(events.some(e => e.t === 'verb' && e.kind === 'black'), 'a black verb surfaces');
+
+ // count and close surface
+ s.showCount(4);
+ s.showClosed(4001);
+ ok(events.some(e => e.t === 'count' && e.n === 4), 'the audience count surfaces');
+ ok(events.some(e => e.t === 'closed' && e.code === 4001), 'a close code surfaces');
+ s.stop?.();
+}
+
+console.log(failures ? `\n${failures} FAILED of ${checks}` : `\nALL PASS (${checks} checks)`);
+process.exit(failures ? 1 : 0);
diff --git a/scripts/test-sync-vouch.ts b/scripts/test-sync-vouch.ts
index acc0bf45..329562bc 100644
--- a/scripts/test-sync-vouch.ts
+++ b/scripts/test-sync-vouch.ts
@@ -35,6 +35,10 @@ import { webcrypto } from 'node:crypto'
type Listener = (ev: unknown) => void
class FakeSocket {
static last: FakeSocket | null = null
+ static readonly CONNECTING = 0
+ static readonly OPEN = 1
+ static readonly CLOSING = 2
+ static readonly CLOSED = 3
readyState = 0
sent: string[] = []
private ls = new Map<string, Listener[]>()
@@ -48,6 +52,7 @@ class FakeSocket {
removeEventListener(t: string, fn: Listener) { this.ls.set(t, (this.ls.get(t) ?? []).filter((f) => f !== fn)) }
send(s: string) { this.sent.push(s) }
close() { this.readyState = 3; this.fire('close', {}) }
+ serverClose(code: number) { this.readyState = 3; this.fire('close', { code }) }
fire(t: string, ev: Record<string, unknown>) {
const h = (this as unknown as Record<string, Listener | null>)[`on${t}`]
if (h) h(ev)
@@ -181,5 +186,106 @@ for (const [name, Transport] of [['kernel', KernelTransport], ['dash', DashTrans
ok(r.applied.includes('ops') && r.applied.includes('snap'), `${name}: an r-room applies unstamped ops and snapshots`)
}
+// ————— the audience transport: receive-only, and close codes mean things —————
+//
+// An audience socket connects on the chain with role 'audience'. It must put NO
+// protocol frame on the wire (the relay drops them, but not sending is the
+// guarantee), decrypt s:'aud' frames under its own key (which IS the show key),
+// and act on the relay's deliberate close codes: 4001/1008 are terminal (do not
+// reconnect into a wall), 4002/4003 are transient (reconnect — that is the
+// "waiting for the presenter" state).
+{
+ console.log('the audience transport is receive-only and reads close codes…')
+ const kp = (await webcrypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])) as CryptoKeyPair
+ const priv = b64u.enc(new Uint8Array(await webcrypto.subtle.exportKey('pkcs8', kp.privateKey)))
+ const pub = b64u.enc(new Uint8Array(await webcrypto.subtle.exportKey('raw', kp.publicKey)))
+
+ const showOps: unknown[][] = []
+ let closedCode: number | null = null
+ FakeSocket.last = null
+ const tr = new KernelTransport(
+ 'wss://relay.test/d/wAUDIENCEROOMwAUDIENCEROOMwAUDIENCEROOMwAUD', keyB64, 'doc-1',
+ () => {},
+ {
+ onSnap: () => {}, getSnapshot: () => ({ doc: { docId: 'doc-1' }, state: { v: 2 } as never }),
+ onOpen: () => {}, onReady: () => false,
+ onShowOps: (ops) => { showOps.push(ops) },
+ onShowClosed: (code) => { closedCode = code },
+ },
+ { kind: 'chain', owner: pub, invite: { pub, priv, role: 'audience', sig: 'x' }, docId: 'doc-1' },
+ )
+ for (let i = 0; i < 50 && !FakeSocket.last; i++) await new Promise((r) => setTimeout(r, 2))
+ const ws = FakeSocket.last!
+ ok(!!ws, 'the audience transport opened a socket')
+ ok(ws.url.includes('ivr=audience'), 'it connected on the audience path (ivr=audience)')
+ ok(!ws.url.includes('bt=1'), 'and did not ask for a write ticket (it never proves)')
+ ws.open()
+ ws.deliver({ ctl: 'ready', bc: 1, v: 2 })
+ await tick()
+
+ // receive-only, as a CONTRAST against a normal reader: the same send() on a
+ // non-audience transport reaches the wire, on the audience it does not — so
+ // the assertion isolates the gate, not write()'s buffering.
+ {
+ FakeSocket.last = null
+ const reader = new KernelTransport(
+ 'wss://relay.test/d/wREADERREADERREADERREADERREADERREADERREADE', keyB64, 'doc-1',
+ () => {}, { onSnap: () => {}, getSnapshot: () => ({ doc: { docId: 'doc-1' }, state: { v: 2 } as never }), onOpen: () => {}, onReady: () => false }, undefined,
+ )
+ for (let i = 0; i < 50 && !FakeSocket.last; i++) await new Promise((r) => setTimeout(r, 2))
+ const rws = FakeSocket.last!
+ rws.open()
+ const rBefore = rws.sent.length
+ reader.send({ t: 'p', a: 'x', p: { name: 'x' } } as never)
+ await tick()
+ ok(rws.sent.length > rBefore, 'a normal reader transport DOES put a sent frame on the wire (the gate is observable)')
+ reader.close()
+ }
+ const before = ws.sent.length
+ tr.send({ t: 'p', a: 'x', p: { name: 'x' } } as never)
+ tr.send({ t: 'ops', a: 'x', ops: [] } as never)
+ await tick()
+ ok(ws.sent.length === before, 'but nothing the session sends leaves an AUDIENCE socket')
+
+ // the SHOW senders are guarded too, not just send(). Security probed exactly
+ // this: on an audience transport, setShowKey + the three senders put five
+ // frames (live/nav/laser/aud/audsnap) on the wire. Unreachable from the
+ // shipped boot and the relay drops them, but "not sending is the guarantee"
+ // must hold for all four senders, not one of four.
+ ok(tr.audience === true, 'the transport reports itself as an audience socket')
+ await tr.setShowKey(keyB64)
+ const b2 = ws.sent.length
+ await tr.sendVerb('live')
+ await tr.sendVerb('nav', { id: 's1' })
+ await tr.sendVerb('laser', { x: 1, y: 2 })
+ await tr.sendAud([{ a: 'p', s: 1, l: 1, op: 'set', sl: 's1', el: 's1x', k: 'x', v: 1 } as never])
+ await tr.sendAudSnap({ docId: 'd' } as never, { v: 2 } as never)
+ await tick()
+ ok(ws.sent.length === b2, 'an audience transport puts NO show frame on the wire either (all four senders guarded)')
+
+ // an aud op frame (sealed under the show key = this.key) applies via onShowOps
+ ws.deliver({ s: 'aud', ...(await seal({ t: 'ops', a: 'pres', ops: [{ a: 'pres', s: 1, l: 1, op: 'set', sl: 's1', el: 's1x', k: 'x', v: 1 }] })) })
+ await tick()
+ ok(showOps.length === 1, 'an s:aud op frame is delivered to onShowOps')
+
+ // 4002 not-live: transient — surface the code AND reconnect
+ const sock1 = FakeSocket.last
+ ws.serverClose(4002)
+ ok(closedCode === 4002, 'a 4002 close surfaces its code')
+ await new Promise((r) => setTimeout(r, 950))
+ ok(FakeSocket.last !== sock1, '4002 reconnects (waiting for the presenter)')
+
+ // 4001 end: terminal — surface the code and do NOT reconnect
+ const ws2 = FakeSocket.last!
+ ws2.open()
+ closedCode = null
+ const sock2 = FakeSocket.last
+ ws2.serverClose(4001)
+ ok(closedCode === 4001, 'a 4001 close surfaces its code')
+ await new Promise((r) => setTimeout(r, 950))
+ ok(FakeSocket.last === sock2, '4001 does NOT reconnect (the show is over)')
+ tr.close()
+}
+
console.log(failures === 0 ? `\nALL PASS (${checks} checks)` : `\n${failures} FAILURES of ${checks} checks`)
process.exit(failures ? 1 : 0)
diff --git a/slides/src/model.ts b/slides/src/model.ts
index ceda1373..09b2b2bc 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -573,7 +573,7 @@ export interface BentoDoc {
invite?: {
pub: string
priv: string
- role: 'writer' | 'commenter'
+ role: 'writer' | 'commenter' | 'audience'
/** unix ms expiry; 0/absent = no expiry */
exp?: number
/** owner's signature over `inv.${pub}.${role}.${exp||0}` */
diff --git a/type/src/model.ts b/type/src/model.ts
index 7b10bce7..d73bcdc7 100644
--- a/type/src/model.ts
+++ b/type/src/model.ts
@@ -350,7 +350,7 @@ export interface TypeDoc {
invite?: {
pub: string;
priv: string;
- role: 'writer' | 'commenter';
+ role: 'writer' | 'commenter' | 'audience';
/** unix ms expiry; 0/absent = no expiry */
exp?: number;
/** owner's signature over `inv.${pub}.${role}.${exp||0}` */