Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

collab v2: per-person keys — owner-anchored invite delegation chain

nyblnet7ec37a2eb1d0
diff --git a/server/sync-worker/src/worker.js b/server/sync-worker/src/worker.js
index f762d864..27bc6dec 100644
--- a/server/sync-worker/src/worker.js
+++ b/server/sync-worker/src/worker.js
@@ -92,22 +92,35 @@ export class Room {
}
/** Valid writer signature over `${i}.${d}` for a signed room? */
- async verifySig(f) {
- if (typeof f.g !== 'string') return false
- if (!this.verifyKey) {
- const w = await this.state.storage.get('w')
- if (!w) return false
- try {
- this.verifyKey = await crypto.subtle.importKey('raw', b64uDec(w), EC_VERIFY, false, ['verify'])
- } catch { return false }
+ /** Import-and-cache a raw P-256 pubkey (b64url) for this wake. */
+ async pubKey(pubB64) {
+ this.keyCache ??= new Map()
+ let k = this.keyCache.get(pubB64)
+ if (!k) {
+ k = await crypto.subtle.importKey('raw', b64uDec(pubB64), EC_VERIFY, false, ['verify'])
+ this.keyCache.set(pubB64, k)
}
+ return k
+ }
+
+ async verifyWith(pubB64, sigB64, text) {
try {
return await crypto.subtle.verify(
- SIG_ALG, this.verifyKey, b64uDec(f.g), new TextEncoder().encode(`${f.i}.${f.d}`),
+ SIG_ALG, await this.pubKey(pubB64), b64uDec(sigB64), new TextEncoder().encode(text),
)
} catch { return false }
}
+ /** Frame signature against THIS SOCKET's certified key (v1.0.3: the verify
+ * key is per-socket — owner, legacy shared writer, or a chain-certified
+ * member all pin their own key at connect). */
+ async verifySig(f, ws) {
+ if (typeof f.g !== 'string') return false
+ const meta = ws.deserializeAttachment() || {}
+ if (!meta.w) return false
+ return this.verifyWith(meta.w, f.g, `${f.i}.${f.d}`)
+ }
+
async fetch(req) {
if (req.headers.get('Upgrade') !== 'websocket') {
return new Response('expected websocket', { status: 426 })
@@ -119,20 +132,43 @@ export class Room {
if (saved === undefined) await this.state.storage.put('tok', tok)
else if (saved !== tok) return new Response('forbidden', { status: 403 })
- // Signed rooms: the room name commits to the writer pubkey. Verify the
- // presented ?w= against the commitment before pinning it, so the pinned
- // key can't be substituted by a viewer.
+ // Signed rooms: the room name commits to a pubkey (v1.0.2: the shared
+ // writer key; v1.0.3: the OWNER key). A writer socket presents ?w= (the key
+ // it will sign frames with) and proves it either DIRECTLY (hash matches the
+ // commitment — owner / legacy shared writer) or via a CHAIN (member: the
+ // owner-signed invite + the invite-signed delegation of the member key).
+ // The verified key is pinned PER SOCKET; no ?w= at all = read-only socket.
const name = url.pathname.match(/^\/d\/([A-Za-z0-9._-]{1,80})$/)?.[1] || ''
+ if ((await this.state.storage.get('name')) === undefined) await this.state.storage.put('name', name)
const signed = name[0] === 'w'
+ let sockW = null
if (signed) {
const w = url.searchParams.get('w') || ''
- if (!/^[A-Za-z0-9_-]{80,200}$/.test(w)) return new Response('bad writer key', { status: 400 })
- if ('w' + (await sha256b64u(b64uDec(w))) !== name) {
- return new Response('writer key does not match room', { status: 403 })
+ if (w) {
+ if (!/^[A-Za-z0-9_-]{80,200}$/.test(w)) return new Response('bad writer key', { status: 400 })
+ const rev = (await this.state.storage.get('rev')) || []
+ let ok = 'w' + (await sha256b64u(b64uDec(w))) === name
+ if (!ok) {
+ // chain: o (owner pub) must match the commitment; ivs = owner's sig
+ // over the invite; dg = invite's sig over this member key. Expired or
+ // revoked links (member key OR invite key) are refused.
+ const o = url.searchParams.get('o') || ''
+ const ivp = url.searchParams.get('ivp') || ''
+ const ivr = url.searchParams.get('ivr') || ''
+ const ive = parseInt(url.searchParams.get('ive') || '0', 10) || 0
+ const ivs = url.searchParams.get('ivs') || ''
+ const dg = url.searchParams.get('dg') || ''
+ ok = !!(o && ivp && ivs && dg)
+ && ivr === 'writer'
+ && (!ive || Date.now() < ive)
+ && !rev.includes(ivp)
+ && 'w' + (await sha256b64u(b64uDec(o))) === name
+ && (await this.verifyWith(o, ivs, `inv.${ivp}.${ivr}.${ive}`))
+ && (await this.verifyWith(ivp, dg, `dlg.${w}`))
+ }
+ if (!ok || rev.includes(w)) return new Response('forbidden', { status: 403 })
+ sockW = w
}
- const savedW = await this.state.storage.get('w')
- if (savedW === undefined) await this.state.storage.put('w', w)
- else if (savedW !== w) return new Response('forbidden', { status: 403 })
}
const since = Math.max(0, parseInt(url.searchParams.get('since') || '0', 10) || 0)
@@ -146,7 +182,7 @@ export class Room {
// Per-socket rate-limit state rides on the socket's serialized attachment
// (in-memory Maps don't survive hibernation).
this.state.acceptWebSocket(server)
- server.serializeAttachment({ count: 0, windowStart: Date.now(), signed })
+ server.serializeAttachment({ count: 0, windowStart: Date.now(), signed, w: sockW })
await this.replay(server, since)
await this.state.storage.setAlarm(Date.now() + IDLE_TTL_MS)
@@ -207,13 +243,36 @@ export class Room {
} catch {
return
}
+ // owner-signed revocation: cut off ONE member key (or a whole invite
+ // lineage) without re-keying the room. Plaintext control frame — it names
+ // only pubkeys, never content. Live sockets on the revoked key are closed.
+ if (f.ctl === 'revoke' && typeof f.p === 'string' && typeof f.o === 'string' && typeof f.g === 'string') {
+ const name = (await this.state.storage.get('name')) || ''
+ if ('w' + (await sha256b64u(b64uDec(f.o))) !== name) return
+ if (!(await this.verifyWith(f.o, f.g, `rev.${f.p}`))) return
+ const rev = (await this.state.storage.get('rev')) || []
+ if (!rev.includes(f.p)) await this.state.storage.put('rev', [...rev, f.p])
+ const note = JSON.stringify({ ctl: 'revoked', p: f.p })
+ for (const peer of this.state.getWebSockets()) {
+ const m = peer.deserializeAttachment() || {}
+ try { peer.send(note) } catch { /* gone */ }
+ if (m.w === f.p) { try { peer.close(1008, 'revoked') } catch { /* gone */ } }
+ }
+ return
+ }
if (typeof f.i !== 'string' || typeof f.d !== 'string') return
+ // defense in depth: a revoked key's socket may outlive the close (or the
+ // revocation may land on another wake) — its writes must still die here.
+ if (meta.w && (f.p === 1 || f.snap === 1)) {
+ const rev = (await this.state.storage.get('rev')) || []
+ if (rev.includes(meta.w)) return
+ }
// Signed rooms: a persisted frame (op batch / snapshot) must carry a valid
// writer signature, else DROP it — this is what enforces read-only. A
// reader (no private key) can still send ephemeral frames (presence).
if (meta.signed && (f.p === 1 || f.snap === 1)) {
- if (!(await this.verifySig(f))) return
+ if (!(await this.verifySig(f, ws))) return
}
const out = { i: f.i, d: f.d }
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 9da24105..0ab2228c 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -24,7 +24,7 @@ import { openSpeakerWindow, speakerIdleBody } from '../screens'
import { borderPoint, boxCenter, lineEndpoints, setLineEndpoints, sideMidpoint } from './lineedit'
import { ICONS } from '../icons'
import { t, setLocale, locale, LOCALE_CHOICES } from '../i18n'
-import { disconnectOnline, joinFromDoc, mintCollab, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'
+import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'
const i18nT = t
@@ -458,6 +458,14 @@ export class Editor {
item(t('Save as presentation package…'),
t('A sealed hand-out: it opens straight into the show — viewing and presenting only, no editor, no live session.'),
() => void this.savePresentationPackage())
+ // v2 (fine-grained) owner: sharing edit access mints an INVITE — the
+ // copy carries a delegation key, never the owner's private key, so the
+ // owner can later revoke this copy's lineage without re-keying the room.
+ if (this.store.doc.collab?.v === 2 && this.store.doc.collab.ownerPriv) {
+ item(t('Share editor copy…'),
+ t('A copy others edit live with you. It carries an owner-signed invite — you stay the owner and can revoke it later without cutting anyone else off.'),
+ () => void this.saveEditorCopy())
+ }
if (sharingOn(this.store)) {
item(t('Save read-only copy…'),
t('A live viewer: it follows this shared session and shows edits as they happen, but can never change the deck (the relay enforces it — read-only is not just honour-system).'),
@@ -512,6 +520,8 @@ export class Editor {
const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc
clone.collab = { ...c, role: 'reader', on: true, sync: undefined }
delete clone.collab.writerPriv // the muzzle — no write capability travels
+ delete clone.collab.ownerPriv // v2: neither the owner key…
+ delete clone.collab.invite // …nor any invite (delegation) material
try {
const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone)
if (ok) this.toast(t('Read-only copy saved — it follows the live session, view only'))
@@ -520,6 +530,31 @@ export class Editor {
}
}
+ /** v2 share-with-edit-access: the copy carries an owner-signed INVITE (a
+ * delegation keypair) instead of the owner's private key. Every device that
+ * opens it mints its OWN member key and joins via the owner→invite→member
+ * chain — so the owner can later revoke this invite (cutting off every copy
+ * descended from it) or a single member key, without re-keying the room. */
+ private async saveEditorCopy() {
+ const c = this.store.doc.collab
+ if (!(c?.room && c.key && c.v === 2 && c.ownerPriv)) {
+ this.toast(t('Only the deck owner can mint editor invites'))
+ return
+ }
+ this.canvas.commitTextEdit()
+ this.session?.stampInto(this.store.doc) // copies rejoin as true forks
+ const clone = JSON.parse(JSON.stringify(this.store.doc)) as import('../model').BentoDoc
+ clone.collab!.invite = await mintInvite(c.ownerPriv, 'writer')
+ delete clone.collab!.ownerPriv
+ clone.collab!.on = true
+ try {
+ const ok = await writeUpdatedFileAs(await serializeAuto(clone), clone)
+ if (ok) this.toast(t('Editor copy saved — recipients join live with edit access'))
+ } catch {
+ this.toast(t('Saving failed'))
+ }
+ }
+
/** Set or change the encryption password (double-entry dialog). */
private async setFilePassword() {
const pass = await this.promptPassword()
diff --git a/slides/src/model.ts b/slides/src/model.ts
index daeb0c82..c5e4c372 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -407,6 +407,26 @@ export interface BentoDoc {
writerPriv?: string
/** 'reader' = this copy is a live viewer: receives updates, never sends. */
role?: 'writer' | 'reader'
+ /**
+ * Fine-grained access (v1.0.3+, `v: 2`): per-person keys. The room id
+ * commits to the OWNER's pubkey. A member copy carries an INVITE — an
+ * owner-signed delegation keypair — and each device mints its own identity
+ * key (kept in localStorage, never in the file); the chain
+ * owner → invite → member is what the blind relay verifies. `ownerPriv`
+ * travels ONLY in the owner's own copy. See docs/collab-design.md roadmap.
+ */
+ v?: number
+ owner?: string
+ ownerPriv?: string
+ invite?: {
+ pub: string
+ priv: string
+ role: 'writer' | 'commenter'
+ /** unix ms expiry; 0/absent = no expiry */
+ exp?: number
+ /** owner's signature over `inv.${pub}.${role}.${exp||0}` */
+ sig: string
+ }
}
/**
* Template file (.dotx-style): every OPEN instantiates a fresh document —
diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.ts
index 40d40746..0057f725 100644
--- a/slides/src/sync/online.ts
+++ b/slides/src/sync/online.ts
@@ -53,12 +53,60 @@ export async function signFrame(key: CryptoKey, i: string, d: string): Promise<s
return b64u.enc(new Uint8Array(sig))
}
+/** Sign an arbitrary string with a b64url PKCS#8 private key (cert chains). */
+export async function signText(privB64: string, text: string): Promise<string> {
+ const key = await importSignKey(privB64)
+ const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(text))
+ return b64u.enc(new Uint8Array(sig))
+}
+
+async function mintKeypair(): Promise<{ pub: string; priv: string }> {
+ const kp = (await crypto.subtle.generateKey(EC, true, ['sign', 'verify'])) as CryptoKeyPair
+ return {
+ pub: b64u.enc(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))),
+ priv: b64u.enc(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))),
+ }
+}
+
+export type CollabInvite = { pub: string; priv: string; role: 'writer' | 'commenter'; 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> {
+ 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 }
+}
+
+/** This device's member identity for a doc — minted once, kept in localStorage,
+ * NEVER in the file (the file travels; a device key must not). */
+export async function deviceIdentity(docId: string): Promise<{ pub: string; priv: string }> {
+ const k = `bento-member-${docId}`
+ try {
+ const saved = localStorage.getItem(k)
+ if (saved) return JSON.parse(saved)
+ } catch { /* storage unavailable → ephemeral identity */ }
+ const id = await mintKeypair()
+ try { localStorage.setItem(k, JSON.stringify(id)) } catch { /* ephemeral */ }
+ return id
+}
+
+/** Auth material for the relay connection. Exactly one shape applies:
+ * direct (owner or legacy shared-writer key) or chain (member via invite). */
+export type AuthSpec =
+ | { kind: 'direct'; pub: string; priv?: string }
+ | { kind: 'chain'; owner: string; invite: CollabInvite; docId: string }
+
export type CollabCreds = {
room: string
key: string
on: boolean
- writerPub: string
- writerPriv: string
+ v: number
+ owner: string
+ ownerPriv: string
role: 'writer'
}
@@ -75,16 +123,18 @@ export type CollabCreds = {
* Async because keypair generation is. See docs/collab-design.md.
*/
export async function mintCollab(): Promise<CollabCreds> {
- const kp = (await crypto.subtle.generateKey(EC, true, ['sign', 'verify'])) as CryptoKeyPair
- const pubRaw = new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))
- const privPk = new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))
- const commit = new Uint8Array(await crypto.subtle.digest('SHA-256', pubRaw as BufferSource))
+ // v2 (fine-grained): the room id commits to the OWNER's pubkey. The creator's
+ // copy holds ownerPriv; shared copies carry owner-signed INVITES instead, and
+ // each joining device mints its own member key (see mintInvite/deviceIdentity).
+ const kp = await mintKeypair()
+ const commit = new Uint8Array(await crypto.subtle.digest('SHA-256', b64u.dec(kp.pub) as BufferSource))
return {
room: `${syncHost()}/d/w${b64u.enc(commit)}`,
key: mintRoomKey(),
on: true,
- writerPub: b64u.enc(pubRaw),
- writerPriv: b64u.enc(privPk),
+ v: 2,
+ owner: kp.pub,
+ ownerPriv: kp.priv,
role: 'writer',
}
}
@@ -119,6 +169,9 @@ export class OnlineTransport implements Transport {
private pingTimer: ReturnType<typeof setInterval> | null = null
private awaitingPong = false
private static readonly PING_MS = 25_000
+ /** the key THIS socket signs with (owner / legacy writer / device) — used to
+ * recognise our own revocation and to attribute presence */
+ myPub: string | null = null
/**
* Replay bookmark — MEMORY ONLY, deliberately: it is valid only alongside
* the in-memory CRDT state it was earned with. A fresh join replays from
@@ -138,13 +191,14 @@ export class OnlineTransport implements Transport {
/** replay done: (actor,seq) pairs the room holds; return true to upload a snapshot */
onReady: (seen: Set<string>, seq: number) => boolean
},
- private writerPub?: string,
- private writerPriv?: string,
+ private auth?: AuthSpec,
) {
- void docId
+ this.docId = docId
this.init(room)
}
+ private docId = ''
+
/** (actor,seq) pairs seen in the current connection's replay */
private replaySeen = new Set<string>()
@@ -156,12 +210,27 @@ export class OnlineTransport implements Transport {
])
const tokDigest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw as BufferSource))
const tok = b64u.enc(tokDigest.slice(0, 18))
- // writers sign op frames; readers omit the key and the relay drops their
- // writes. The pubkey (`w`) rides on the URL so the relay can pin+verify.
- if (this.writerPriv) {
- try { this.signKey = await importSignKey(this.writerPriv) } catch { this.signKey = null }
+ // Writers sign op frames; readers omit auth and the relay drops their
+ // writes. Two writer shapes: DIRECT (the presented `w` key hash-matches the
+ // room commitment — the owner, or a legacy shared-writer copy) and CHAIN
+ // (a member: `w` = this device's key, plus the owner-signed invite and the
+ // invite-signed delegation of the device key — verified by the relay).
+ const a = this.auth
+ if (a?.kind === 'direct') {
+ if (a.priv) { try { this.signKey = await importSignKey(a.priv) } catch { this.signKey = null } }
+ this.myPub = a.pub
+ this.url = `${room}?tok=${tok}&w=${a.pub}`
+ } else if (a?.kind === 'chain') {
+ const id = await deviceIdentity(this.docId)
+ try { this.signKey = await importSignKey(id.priv) } catch { this.signKey = null }
+ this.myPub = id.pub
+ const iv = a.invite
+ const dg = await signText(iv.priv, `dlg.${id.pub}`)
+ this.url = `${room}?tok=${tok}&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}`
}
- this.url = `${room}?tok=${tok}` + (this.writerPub ? `&w=${this.writerPub}` : '')
this.connect()
}
@@ -242,12 +311,21 @@ export class OnlineTransport implements Transport {
}
private async onEnvelope(text: string) {
- let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string }
+ let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string; p?: string }
try {
env = JSON.parse(text)
} catch {
return
}
+ // the owner revoked a key; if it's OURS, stand down for good (the relay
+ // refuses our reconnects anyway — don't retry into a wall of 403s)
+ if (env.ctl === 'revoked') {
+ if (env.p && env.p === this.myPub) {
+ console.info('[bento-sync] this copy’s access was revoked by the owner')
+ this.close()
+ }
+ return
+ }
if (env.ctl === 'ack' || env.ctl === 'ready') {
if (typeof env.q === 'number') {
this.saveSeq(env.q)
@@ -353,6 +431,16 @@ export class OnlineTransport implements Transport {
this.ws = null
this.setStatus('closed')
}
+
+ /** OWNER action: revoke one member key (or an invite key — cutting off every
+ * copy descended from that invite). Signed `rev.${pub}`; the relay stores it,
+ * drops that key's future writes/joins, and fans out a `revoked` note. */
+ async revokeKey(pub: string, ownerPub: string, ownerPriv: string): Promise<boolean> {
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return false
+ const g = await signText(ownerPriv, `rev.${pub}`)
+ this.ws.send(JSON.stringify({ ctl: 'revoke', p: pub, o: ownerPub, g }))
+ return true
+ }
}
// --- share/join glue --------------------------------------------------------
@@ -391,15 +479,25 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
return new NullTransport()
}
active?.close()
- // readers carry writerPub (to name the room's writer key) but never the
- // private half — so their op frames go unsigned and the relay drops them.
- const priv = collab.role === 'reader' ? undefined : collab.writerPriv
+ // Auth shape per copy: reader → none (unsigned, relay drops writes);
+ // 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.v === 2 && collab.owner && collab.ownerPriv) {
+ auth = { kind: 'direct', pub: collab.owner, priv: collab.ownerPriv }
+ } else if (collab.v === 2 && collab.owner && collab.invite) {
+ auth = { kind: 'chain', owner: collab.owner, invite: collab.invite, docId }
+ } else if (collab.writerPub) {
+ auth = { kind: 'direct', pub: collab.writerPub, priv: collab.writerPriv }
+ }
+ }
active = new OnlineTransport(collab.room, collab.key, docId, onFrame, {
onSnap: (doc, state) => session.applySnapshot(doc, state),
getSnapshot: () => session.snapshot(),
onOpen: () => session.hello(),
onReady: (seen) => session.onRelayReady(seen),
- }, collab.writerPub, priv)
+ }, auth)
return active
})
return active