Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

34.2 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
// bento-sync online transport for dash — E2EE WebSocket to the blind relay
// (server/sync-worker). Every frame is AES-GCM encrypted with the room key
// from doc.collab.key; the relay sees ciphertext, fan-out routing, and nothing
// else. Auth is possession-proof: ?tok= is a hash of the key.
//
// THIS IS A PORT of slides/src/sync/online.ts, deliberately close to the
// original, and the differences are only the types it names (DashDoc, dash's
// Store, dash's Op/SyncStateJSON). Everything load-bearing — the room-id
// commitment, the owner→invite→member signature chain, the 25s keepalive, the
// refusal handling, the replay bookmark being memory-only — is unchanged,
// because every one of those lines was paid for by a bug in production and
// none of them are slides-shaped.
//
// Why a port and not an import: slides' module reaches into slides' store,
// model and update modules, so importing it would pull the whole slides app
// into dash's bundle. PLATFORM §9 already names this — the collab engine and
// relay are "shared but NOT yet in kernel/", and genericizing them is its own
// project. When that project happens, this file and its slides twin are the
// two callers to reconcile. The protocol they speak is IDENTICAL, which is the
// property that matters: one relay, one wire format, two apps.
//
// Relay contract: docs/relay-design.md. Threat model: docs/collab-design.md.

import type { Store } from '../store.ts'
import type { DashDoc } from '../model.ts'
import type { Op, SyncStateJSON } from './crdt.ts'
import type { Frame, RefusalCode, SyncSession, Transport } from './session.ts'
import { offlineEnabled } from '../../../kernel/src/update.ts'
import { netWebSocket } from '../../../kernel/src/net.ts'
import { lsGet, lsSet } from '../../../kernel/src/storage.ts'
import { carryThroughRotation, collabForReader, collabForInvite } from '../../../kernel/src/docfields.ts'

export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'
const SNAP_EVERY = 200 // ops between encrypted snapshot uploads

const b64u = {
  enc(bytes: Uint8Array): string {
    let s = ''
    for (const b of bytes) s += String.fromCharCode(b)
    return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
  },
  dec(s: string): Uint8Array {
    const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))
    const out = new Uint8Array(b.length)
    for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)
    return out
  },
}

export function mintRoomKey(): string {
  const bytes = new Uint8Array(32)
  crypto.getRandomValues(bytes)
  return b64u.enc(bytes)
}

const EC = { name: 'ECDSA', namedCurve: 'P-256' } as const
const SIGN_ALG = { name: 'ECDSA', hash: 'SHA-256' } as const

/** Import a signing private key (PKCS#8, base64url) for op frames. */
export async function importSignKey(privB64: string): Promise<CryptoKey> {
  return crypto.subtle.importKey('pkcs8', b64u.dec(privB64) as BufferSource, EC, false, ['sign'])
}

/** ECDSA-P256/SHA-256 signature over `${i}.${d}`, base64url. */
export async function signFrame(key: CryptoKey, i: string, d: string): Promise<string> {
  const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(`${i}.${d}`))
  return b64u.enc(new Uint8Array(sig))
}

/** Sign an arbitrary string with an already-imported signing key. */
export async function signWith(key: CryptoKey, text: string): Promise<string> {
  const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(text))
  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> {
  return signWith(await importSignKey(privB64), text)
}

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 }

/**
 * The `collab` block as this app writes it. dash's model.ts types the field as
 * `unknown` on purpose (it is credentials, not document content), so the shape
 * lives here — where the code that reads it lives.
 */
export interface CollabBlock {
  room: string
  key: string
  on?: boolean
  v?: number
  owner?: string
  ownerPriv?: string
  invite?: CollabInvite
  /** legacy 1.0.2-era shared writer key */
  writerPub?: string
  writerPriv?: string
  /**
   * What this COPY may do. Absent or 'writer' = it writes; 'reader' = a live
   * viewer; 'audience' = a live-SHOW member (kernel sync, #454) whose transport
   * is receive-only. Typed to the kernel's own union — it was narrower here,
   * which is how a role the kernel can hand us came to be read as a writer.
   * See `copyCanWrite`.
   */
  role?: 'writer' | 'reader' | 'audience'
  sync?: SyncStateJSON
}

/**
 * May THIS COPY write to its room?
 *
 * An ALLOWLIST, failing closed. Both gates used to ask `role !== 'reader'`,
 * which says yes to every role invented after it — so an 'audience' copy
 * offered its owner-signed show ticket as WRITE auth and called itself an
 * Editor in presence. A future role that can write will show as view-only
 * until this learns about it: visible and harmless. The old shape's failure
 * was invisible and wrong. Absent means writer because every file older than
 * the role field is one. Same rule as type's `copyCanWrite` (#588).
 */
export function copyCanWrite(collab: CollabBlock | undefined): boolean {
  if (!collab) return false
  return collab.role === undefined || collab.role === 'writer'
}

export const collabOf = (doc: DashDoc): CollabBlock | undefined =>
  (doc.collab as CollabBlock | undefined) ?? undefined

/** 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 = lsGet(k)
    if (saved) return JSON.parse(saved) as { pub: string; priv: string }
  } catch { /* storage unavailable → ephemeral identity */ }
  const id = await mintKeypair()
  lsSet(k, JSON.stringify(id))
  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
  v: number
  owner: string
  ownerPriv: string
  role: 'writer'
}

/**
 * Fresh collaboration credentials, minted at DOCUMENT CREATION and live by
 * default: the moment identity and keys exist, any copy of the file joins the
 * same room. Dormancy is enforced elsewhere (SyncSession.shareEligible) so a
 * workbook nobody has saved or shared never phones home.
 *
 * The room id COMMITS to the owner's public key — `w` + b64url(SHA-256(pub)) —
 * so the relay pins the writer key trustlessly: a viewer holds the room id but
 * cannot substitute a key of their own. `key` is the separate symmetric READ
 * capability. Async because keypair generation is.
 */
export async function mintCollab(): Promise<CollabCreds> {
  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,
    v: 2,
    owner: kp.pub,
    ownerPriv: kp.priv,
    role: 'writer',
  }
}

/** dev override for the relay host (e.g. ws://localhost:8787) */
export function syncHost(): string {
  try {
    return lsGet('bento-sync-url') || DEFAULT_SYNC_HOST
  } catch {
    return DEFAULT_SYNC_HOST
  }
}

export type OnlineStatus = 'connecting' | 'open' | 'closed'

/** A frame written to (or parked for) the relay. `ops` is set for persisted op
 *  batches — the only frames the relay acks, and the only ones whose refusal
 *  has to reach the session (an unsendable op must leave the resend log). */
type Outbound = { id: string; text: string; ops: Op[] | null; bytes: number; tries: number }

let frameSeq = 0
/** Short opaque per-frame id, emitted FIRST in the envelope so the relay can
 *  recover it with a bounded regex from an OVERSIZE frame — one it refuses
 *  before parsing, since parsing an attacker-sized string is a CPU abuse
 *  vector. */
const nextFrameId = (): string => `f${(++frameSeq).toString(36)}${Math.random().toString(36).slice(2, 6)}`

type RefusedEnv = {
  code?: string
  /** our frame id, echoed back — authoritative when present */
  k?: string
  max?: number
  got?: number
  bytes?: number
  retryInMs?: number
}

export class OnlineTransport implements Transport {
  readonly kind = 'online'
  status: OnlineStatus = 'connecting'
  onStatus: ((s: OnlineStatus) => void) | null = null
  private ws: WebSocket | null = null
  private key: CryptoKey | null = null
  /** writer signing key — null for readers (they decrypt but cannot author) */
  private signKey: CryptoKey | null = null
  private queue: Outbound[] = []
  private awaitingAck: Outbound[] = []
  private paused = false
  private pauseTimer: ReturnType<typeof setTimeout> | null = null
  private lastLimitNotice = 0
  private static readonly ACK_WINDOW = 64
  private static readonly MAX_RETRIES = 4
  private closed = false
  private backoff = 800
  private url = ''
  // Heartbeat: ping the relay (which auto-responds "pong" without waking the
  // Durable Object) so idle connections stay alive; if a pong does not come
  // back before the next tick the socket is treated as dead and reconnected,
  // rather than waiting out a TCP timeout that can take minutes.
  private pingTimer: ReturnType<typeof setInterval> | null = null
  private awaitingPong = false
  private static readonly PING_MS = 25_000
  /** the key THIS socket signs with — used to recognise our own revocation */
  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 the
   * room's snapshot (or 0); reconnects of THIS session resume from here.
   */
  private seq = 0
  private docId = ''
  private inReplay = true
  private snapInFlight = false
  private replaySeen = new Set<string>()
  private onFrame: (f: Frame) => void
  private hooks: {
    onSnap: (doc: DashDoc, state: SyncStateJSON) => void
    getSnapshot: () => { doc: DashDoc; state: SyncStateJSON }
    onOpen: () => void
    onReady: (seen: Set<string>, seq: number) => boolean
    onRefused?: (code: RefusalCode, ops: Op[] | null) => void
  }
  private auth?: AuthSpec
  private keyB64: string

  // NB: fields are declared and assigned explicitly rather than through
  // constructor parameter properties — the node type-stripping loader that
  // runs scripts/test-dash-sync.ts rejects that syntax outright.
  constructor(
    room: string,
    keyB64: string,
    docId: string,
    onFrame: (f: Frame) => void,
    hooks: OnlineTransport['hooks'],
    auth?: AuthSpec,
  ) {
    this.keyB64 = keyB64
    this.docId = docId
    this.onFrame = onFrame
    this.hooks = hooks
    this.auth = auth
    this.writeReadyP = new Promise<void>((r) => { this.resolveWriteReady = r })
    void this.init(room)
  }

  /** Credentials a blob layer would need: the relay origin, room name, the
   *  possession-proof token, and the raw room key. dash does not offload
   *  assets yet; the accessor exists so that layer needs no transport change.
   *  `tok` is the write ticket when this socket proved its key, else the read
   *  token — the same rule as the kernel transport, so the day dash offloads
   *  assets it inherits the ticketed path without a wire change. */
  blobCreds(): { base: string; room: string; tok: string; rawKey: Uint8Array } | null {
    if (!this.roomName || !this.tokValue) return null
    return {
      base: this.originValue,
      room: this.roomName,
      tok: this.writeTicket || this.tokValue,
      rawKey: b64u.dec(this.keyB64),
    }
  }
  /** Resolves once uploads may proceed: the ticket arrived, or `ready` came
   *  without a challenge (older relay, or we are a reader). Mirrors the kernel. */
  writeReady(): Promise<void> {
    return this.writeReadyP
  }
  private writeReadyP: Promise<void>
  private resolveWriteReady: () => void = () => {}
  private roomName = ''
  private tokValue = ''
  private originValue = ''
  /** relay-issued blob write ticket; null until a PROVEN socket is handed one */
  private writeTicket: string | null = null
  /** `w`-room: the relay's stamps mean something; unstamped content frames are
   *  refused. Legacy `r` rooms sign nothing and stay on the older trust model. */
  private signedRoom = false

  private async init(room: string) {
    const raw = b64u.dec(this.keyB64)
    this.key = await crypto.subtle.importKey('raw', raw as BufferSource, 'AES-GCM', false, ['encrypt', 'decrypt'])
    const tokDigest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw as BufferSource))
    const tok = b64u.enc(tokDigest.slice(0, 18))
    try {
      const u = new URL(room.replace(/^ws/, 'http'))
      this.originValue = u.origin
      this.roomName = u.pathname.replace(/^\/d\//, '')
      this.tokValue = tok
      this.signedRoom = this.roomName[0] === 'w'
    } catch { /* malformed room url — blobs simply stay unavailable */ }
    // Writers sign op frames; readers omit auth and the relay drops their
    // writes. Two writer shapes: DIRECT (the presented key hash-matches the
    // room commitment — the owner, or a legacy shared-writer copy) and CHAIN
    // (a member: 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
      // bt=1: we understand the blob write ticket. The relay only starts
      // REQUIRING it for uploads once a PROVEN writer has said so — the kernel
      // transport sends it too; the two clients must spell the wire the same
      // (scripts/test-relay-protocol.ts).
      this.url = `${room}?tok=${tok}&bt=1&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}&bt=1&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.connect()
  }

  private setStatus(s: OnlineStatus) {
    this.status = s
    this.onStatus?.(s)
  }

  private connect() {
    if (this.closed) return
    this.setStatus('connecting')
    let ws: WebSocket
    try {
      ws = netWebSocket(`${this.url}&since=${this.seq}`)
    } catch {
      // Offline is a decision, not an outage: retrying would spin until the
      // switch flips, and net.ts has closed anything already open anyway.
      if (!offlineEnabled()) this.retry()
      return
    }
    this.ws = ws
    ws.onopen = () => {
      this.backoff = 800
      this.inReplay = true
      this.replaySeen = new Set()
      // Acks do not survive the socket: whatever was un-acked is unknowable
      // now, and a stale entry would mis-name a later refusal. Delivery of
      // those ops is the log's job anyway (session.onRelayReady re-sends).
      this.awaitingAck = []
      this.setStatus('open')
      for (const out of this.queue.splice(0)) this.write(out)
      this.startHeartbeat(ws)
      this.hooks.onOpen()
    }
    ws.onmessage = (ev) => {
      const data = String(ev.data)
      if (data === 'pong') { this.awaitingPong = false; return }
      void this.onEnvelope(data).catch(() => {})
    }
    const drop = () => {
      if (this.ws !== ws) return
      this.stopHeartbeat()
      this.ws = null
      this.setStatus('closed')
      this.retry()
    }
    ws.onclose = drop
    ws.onerror = drop
  }

  private startHeartbeat(ws: WebSocket) {
    this.stopHeartbeat()
    this.awaitingPong = false
    this.pingTimer = setInterval(() => {
      if (this.ws !== ws || ws.readyState !== WebSocket.OPEN) return
      if (this.awaitingPong) {
        // no pong since the last ping → the socket is half-open; force a close
        // so onclose fires and we reconnect, rather than hanging silently
        try { ws.close() } catch { /* already gone */ }
        return
      }
      this.awaitingPong = true
      try { ws.send('ping') } catch { /* send failed → onclose handles it */ }
    }, OnlineTransport.PING_MS)
  }

  private stopHeartbeat() {
    if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null }
    this.awaitingPong = false
  }

  private retry() {
    if (this.closed) return
    setTimeout(() => this.connect(), this.backoff)
    this.backoff = Math.min(this.backoff * 1.8, 30000)
  }

  /**
   * The relay refused a frame. Handling this is not optional politeness: when
   * the relay dropped oversize/over-quota frames SILENTLY, the sender got no
   * ack, the peer stayed behind, its catch-up asked for the very same op, and
   * the sender re-sent the identical doomed frame forever.
   */
  private handleRefusal(env: RefusedEnv) {
    if ((env.code as string) === 'snap-ahead') {
      // the relay refused a snapshot claiming a seq it has not reached — nothing
      // lost, the log is intact; loud because this copy's counter drifted
      console.warn('[bento-sync] relay refused a snapshot ahead of the room’s seq — nothing lost', env)
      return
    }
    if (env.code === 'rate-limited') {
      this.throttle(typeof env.retryInMs === 'number' ? env.retryInMs : 10_000)
      return
    }
    if (env.code !== 'too-large' && env.code !== 'storage-failed' && env.code !== 'room-full') {
      // a code from a newer relay: no recovery we can invent is better than
      // leaving the op in the log, where the next catch-up retries it honestly
      console.warn('[bento-sync] relay refused a frame:', env.code)
      return
    }
    const culprit = this.matchRefused(env)
    if (culprit) this.awaitingAck = this.awaitingAck.filter((o) => o !== culprit)
    console.warn(`[bento-sync] relay refused a frame (${env.code})`, env)
    this.hooks.onRefused?.(env.code, culprit?.ops ?? null)
  }

  /**
   * Which frame does this refusal name? Exact when the relay echoed our id;
   * otherwise the head of the ack queue CONFIRMED against the size it
   * reported. Ambiguity → null → the ops stay in the log, because a wrong drop
   * is silent permanent divergence.
   */
  private matchRefused(env: RefusedEnv): Outbound | null {
    if (env.k) return this.awaitingAck.find((o) => o.id === env.k) ?? null
    const byText = typeof env.got === 'number'
    const want = byText ? env.got! : typeof env.bytes === 'number' ? env.bytes : null
    const size = (o: Outbound) => (byText ? o.text.length : o.bytes)
    const head = this.awaitingAck[0] ?? null
    if (want === null) return head // room-full carries no size — order is all we have
    if (head && size(head) === want) return head
    return this.awaitingAck.find((o) => size(o) === want) ?? null
  }

  /** Rate limited: hold everything for the window, then replay what we sent
   *  into it. Re-sending is safe (the CRDT dedups by actor:seq); losing them
   *  silently is not. */
  private throttle(ms: number) {
    const wait = Math.min(Math.max(ms, 1000), 60_000)
    const retryable = this.awaitingAck.filter((o) => ++o.tries <= OnlineTransport.MAX_RETRIES)
    this.awaitingAck = []
    this.queue = [...retryable, ...this.queue]
    if (this.pauseTimer) clearTimeout(this.pauseTimer)
    this.paused = true
    this.pauseTimer = setTimeout(() => {
      this.pauseTimer = null
      this.paused = false
      for (const out of this.queue.splice(0)) this.write(out)
    }, wait)
    const now = Date.now()
    if (now - this.lastLimitNotice > 60_000) {
      this.lastLimitNotice = now
      this.hooks.onRefused?.('rate-limited', null)
    }
  }

  /** write now, or park it (disconnected, or inside a rate-limit backoff) */
  private write(out: Outbound) {
    if (!this.paused && this.ws && this.ws.readyState === WebSocket.OPEN) {
      try {
        this.ws.send(out.text)
      } catch {
        this.park(out) // send threw → onclose will reconnect and flush
        return
      }
      if (out.ops) {
        this.awaitingAck.push(out)
        if (this.awaitingAck.length > OnlineTransport.ACK_WINDOW) this.awaitingAck.shift()
      }
      return
    }
    this.park(out)
  }

  private park(out: Outbound) {
    this.queue.push(out)
    if (this.queue.length > 500) this.queue.shift()
  }

  private async onEnvelope(text: string) {
    let env: {
      i?: string; d?: string; q?: number; snap?: number; ctl?: string; p?: string
      /** the writer signature the relay VERIFIED before fanning this out */
      g?: string
      /** blob write ticket — only ever sent to a socket that proved its key */
      wt?: string
      /** possession nonce on `ready`: sign it to prove the `?w=` key is ours */
      c?: string
    } & RefusedEnv
    try {
      env = JSON.parse(text)
    } catch {
      return
    }
    // the owner revoked a key; if it is 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
      }
      // a removal re-mints the room's blob ticket; the relay sends the
      // replacement to PROVEN sockets only
      if (typeof env.wt === 'string') this.writeTicket = env.wt
      return
    }
    // The ticket arrives on its own frame, after `prove` — never on `ready`.
    // See the kernel transport for why a hash-match on ?w= is not possession.
    if (env.ctl === 'wt') {
      if (typeof env.wt === 'string') this.writeTicket = env.wt
      this.resolveWriteReady()
      return
    }
    if (env.ctl === 'refused') {
      this.handleRefusal(env)
      return
    }
    if (env.ctl === 'ack' || env.ctl === 'ready') {
      if (env.ctl === 'ack') this.awaitingAck.shift()
      if (typeof env.q === 'number') {
        if (env.q > this.seq) this.seq = env.q
        this.maybeSnapshot(env.q)
      }
      if (env.ctl === 'ready') {
        // `c` is the relay's possession challenge. Answer it and the ticket
        // follows on its own `wt` frame; no `c` = older relay or a reader, and
        // uploads take the room token, so writes are released now.
        if (typeof env.c === 'string' && this.signKey && this.roomName) {
          void this.prove(env.c)
        } else {
          this.resolveWriteReady()
        }
        this.inReplay = false
        const wantSnap = this.hooks.onReady(this.replaySeen, env.q ?? 0)
        this.replaySeen = new Set()
        // fresh rooms and just-merged forks get a snapshot immediately so late
        // joiners converge without needing the full op log
        if (wantSnap || env.q === 0) void this.uploadSnapshot(env.q ?? 0)
      }
      return
    }
    if (!env.i || !env.d || !this.key) return
    let payload: unknown
    try {
      const pt = await crypto.subtle.decrypt(
        { name: 'AES-GCM', iv: b64u.dec(env.i) as BufferSource },
        this.key,
        b64u.dec(env.d) as BufferSource,
      )
      payload = JSON.parse(new TextDecoder().decode(pt))
    } catch {
      return // wrong key / corrupted — ignore
    }
    if (typeof env.q === 'number' && env.q > this.seq) this.seq = env.q
    if (env.snap === 1) {
      if (!this.vouched(env)) return
      const s = payload as { doc: DashDoc; state: SyncStateJSON }
      if (s && s.doc && s.state) this.hooks.onSnap(s.doc, s.state)
      return
    }
    const frame = payload as Frame
    // Decrypting proves the sender holds the READ key, which every copy does.
    // Authorship is the relay's to vouch for; refuse content frames without
    // its stamp. Same rule and same reasons as the kernel transport.
    if ((frame.t === 'ops' || frame.t === 'snap') && !this.vouched(env)) return
    if (this.inReplay && frame.t === 'ops') {
      for (const op of frame.ops) this.replaySeen.add(`${op.a}:${op.s}`)
    }
    this.onFrame(frame)
  }

  /** In a signed room the relay stamps exactly what it checked: `q` on a
   *  persisted frame, an echoed `g` on a verified ephemeral one. Unstamped
   *  content-bearing frames came from someone with the room key and nothing
   *  more. Legacy `r` rooms have no signatures to check. */
  private vouched(env: { q?: number; g?: string }): boolean {
    return !this.signedRoom || typeof env.q === 'number' || typeof env.g === 'string'
  }

  /** Answer the relay's possession challenge: `prove.<nonce>.<room>` signed
   *  with the key presented as `?w=`. Room name in the text → no cross-room
   *  replay; nonce single-use → no same-room replay. */
  private async prove(nonce: string) {
    if (!this.signKey || !this.ws) return
    try {
      const g = await signWith(this.signKey, `prove.${nonce}.${this.roomName}`)
      this.ws.send(JSON.stringify({ ctl: 'prove', g }))
    } catch {
      this.resolveWriteReady()
    }
  }

  /** every SNAP_EVERY persisted ops, upload a fresh encrypted snapshot */
  private maybeSnapshot(q: number) {
    if (q === 0 || q % SNAP_EVERY !== 0) return
    void this.uploadSnapshot(q)
  }

  /** encrypt + store the current (doc, state) as the room's snapshot */
  async uploadSnapshot(q: number) {
    if (this.snapInFlight) return
    this.snapInFlight = true
    try {
      const snap = this.hooks.getSnapshot()
      const text = await this.encrypt(JSON.stringify(snap))
      if (text && this.ws && this.ws.readyState === WebSocket.OPEN) {
        const env: Record<string, unknown> = { snap: 1, q, i: text.i, d: text.d }
        if (this.signKey) env.g = await signFrame(this.signKey, text.i, text.d)
        this.ws.send(JSON.stringify(env))
      }
    } finally {
      this.snapInFlight = false
    }
  }

  private async encrypt(plain: string): Promise<{ i: string; d: string } | null> {
    if (!this.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,
      new TextEncoder().encode(plain),
    )
    return { i: b64u.enc(iv), d: b64u.enc(new Uint8Array(ct)) }
  }

  send(frame: Frame) {
    void (async () => {
      const enc = await this.encrypt(JSON.stringify(frame))
      if (!enc) return
      let env: Record<string, unknown> = enc
      let ops: Op[] | null = null
      const id = nextFrameId()
      if (frame.t === 'ops') {
        env = { k: id, p: 1, ...enc }
        // sign the CIPHERTEXT so the relay verifies authorship while blind
        if (this.signKey) env.g = await signFrame(this.signKey, enc.i, enc.d)
        ops = frame.ops
      } else if (frame.t === 'snap' && this.signKey) {
        // the fork snapshot is ephemeral but replaces what every peer holds;
        // sign it so the relay can vouch for it (peers refuse an unstamped one)
        env = { ...enc, g: await signFrame(this.signKey, enc.i, enc.d) }
      }
      this.write({ id, text: JSON.stringify(env), ops, bytes: enc.i.length + enc.d.length, tries: 0 })
    })()
  }

  close() {
    this.closed = true
    if (this.pauseTimer) { clearTimeout(this.pauseTimer); this.pauseTimer = null }
    this.stopHeartbeat()
    this.ws?.close()
    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 --------------------------------------------------------

let active: OnlineTransport | null = null

export function onlineTransport(): OnlineTransport | null {
  return active
}

/** inert stand-in when a re-keyed document has no collab config */
class NullTransport implements Transport {
  readonly kind = 'off'
  send() {}
  close() {}
}

/** does this document want its relay connected? (absent `on` = true) */
export function sharingOn(store: Store): boolean {
  const c = collabOf(store.doc)
  return !!c?.room && !!c.key && c.on !== false
}

/** connect the session to the relay in doc.collab (no-op unless sharing is on) */
export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport | null {
  if (offlineEnabled()) return null // the hard no-network switch wins over everything
  if (active) return active
  if (!sharingOn(store)) return null
  session.addTransport((docId, onFrame) => {
    // re-invoked whenever the session re-keys (doc replaced): consult the
    // CURRENT document — its collab config may differ or be off
    const collab = collabOf(store.doc)
    if (!collab?.room || !collab.key || collab.on === false || store.doc.docId !== docId) {
      active = null
      return new NullTransport()
    }
    active?.close()
    let auth: AuthSpec | undefined
    if (copyCanWrite(collab)) {
      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),
      onRefused: (code, ops) => session.refused(code, ops),
    }, auth)
    return active
  })
  return active
}

/** flip sharing on and connect — the "Start live session" action. Credentials
 *  already exist (minted at creation); this only arms them. */
export async function startSharing(session: SyncSession, store: Store): Promise<OnlineTransport | null> {
  if (offlineEnabled()) return null
  if (active) return active
  const doc = store.doc as DashDoc & { collab?: CollabBlock }
  if (!doc.collab) doc.collab = await mintCollab()
  const was = doc.collab.on
  doc.collab.on = true
  // the file has to learn it is shared, or a copy saved from it never joins
  if (was !== true) store.markUnsaved()
  session.enableSharing()
  return joinFromDoc(session, store)
}

/**
 * Offline-mode disconnect: drop the relay WITHOUT touching doc.collab.on — the
 * document's sharing intent is unchanged; this viewer just will not network.
 */
export function disconnectOnline(session: SyncSession) {
  if (active) {
    session.removeTransport(active)
    active = null
  }
}

/** flip sharing off and disconnect. Credentials stay — copies saved during the
 *  session can rejoin if sharing is turned back on. */
export function stopSharing(session: SyncSession, store: Store) {
  if (active) {
    session.removeTransport(active)
    active = null
  }
  const c = collabOf(store.doc)
  if (c && c.on !== false) { c.on = false; store.markUnsaved() }
}

/** revocation: mint a fresh room + key. Every previously sent copy loses
 *  access; only copies saved AFTER this can join future sessions. */
export async function rotateKeys(session: SyncSession, store: Store) {
  stopSharing(session, store)
  const fresh = await mintCollab()
  const doc = store.doc as DashDoc & { collab?: CollabBlock }
  // fresh keys = the revocation; carry the rotate-survivors (sync, links) from
  // the old block (kernel/src/docfields.ts COLLAB_ROTATE_KEEP)
  doc.collab = carryThroughRotation(fresh, doc.collab)
  // revocation is only real once the FILE holds the new keys
  store.markUnsaved()
}

/** Save-a-copy helpers, via the kernel ALLOWLIST (kernel/src/docfields.ts): a copy
 *  keeps only what is on the list, so a new field — private or not — fails CLOSED.
 *  A reader keeps the READ key and loses every private half AND the sync stamp
 *  (a reader does not contribute), so the relay drops its writes. */
export function readerCopy(collab: CollabBlock): CollabBlock {
  return collabForReader(collab) as unknown as CollabBlock
}

/** An invite copy: the owner's private half stays home; a FRESH owner-signed
 *  invite travels and the top-level role comes from it. Each device that opens it
 *  mints its own member key. The allowlist drops any legacy writer key too. */
export async function inviteCopy(collab: CollabBlock): Promise<CollabBlock | null> {
  // A non-owner holds no key to root the chain in — and returning the SOURCE
  // block would leak writerPriv, sync, an old invite and any other field. Refuse,
  // as spaces does, rather than hand back an un-projected copy.
  if (!collab.ownerPriv) return null
  const invite = await mintInvite(collab.ownerPriv)
  return collabForInvite(collab, invite) as unknown as CollabBlock
}