// The runtime's collaboration manager: owns the identity, the E2EE transport, // and every live document session. MLS runs here, host-side — the UI sees // plaintext + membership events over the authenticated window sockets, tiles // see only the tp-sync frames the UI forwards down. Tiles never touch keys, // invitations, or membership (the runtime chrome is the only writer of those). // // Identity is a generated dev DID until AT sign-in lands (ZIRAN_DID / // ZIRAN_HANDLE override; swapping in atproto OAuth + service-auth changes // only this file's identity block and the relay's Verifier). import { dirname, join } from '@std/path'; import type { CollabProvider, ProviderSummary } from '../sync/provider.ts'; import type { Invitation, Member, Session, SyncManifest } from '../sync/protocol.ts'; import { fromB64, toB64 } from '../sync/protocol.ts'; import { RelaySyncTransport } from '../sync/relay-client.ts'; import { type KeyPackageDirectory, MlsSyncTransport, RelayKeyPackageDirectory } from '../sync/mls-transport.ts'; import { DevVerifier } from '../../relay/auth.ts'; import { resolveIdentity } from '../sync/atproto.ts'; import { type AtSession, fetchPdsKeyPackage } from './atsession.ts'; import { documentsDir, groupsDir, identityFile, mlsIdentityFile, syncRegistryFile } from './paths.ts'; import type { ZiranStore } from './store.ts'; /** Runtime-enforced defaults when a tile's manifest declares no sync roles. */ const DEFAULT_MANIFEST: SyncManifest = { owner: 'author', roles: { author: { write: true, admin: true }, editor: { write: true }, watcher: { write: false }, }, }; interface SharedDoc { /** Path-derived local doc id (changes on move; path is re-derived). */ localId: string; /** Stable cross-member channel id. */ syncId: string; path: string; role: string; manifest: SyncManifest; /** Seq the tile's persisted state is known to reflect (snapshot point). */ ackedSeq: number; } interface BufferedFrame { seq: number; author: string; role: string; b64: string; } interface LiveDoc { rec: SharedDoc; session: Session; /** Decrypted messages past ackedSeq, waiting for (re)attached tiles. */ buffer: BufferedFrame[]; lastForwardedSeq: number; roster: Member[]; } export type SyncSummary = ProviderSummary; export class RelayProvider implements CollabProvider { did = ''; handle = ''; relayUrl = ''; relayOk = false; #store: ZiranStore; #at?: AtSession; #relayFor: () => string = () => this.relayUrl; #devDid = ''; #devHandle = ''; #base?: RelaySyncTransport; #transport?: MlsSyncTransport; #registry: SharedDoc[] = []; #live = new Map(); // by localId #invitations = new Map(); // pending, token → invitation #dismissed = new Set(); #retryTimer: number | undefined; #retryDelay = 5_000; #connecting = false; /** A (re)connect was requested while one was in flight; run another pass. */ #connectAgain = false; #relayError: string | undefined; constructor(store: ZiranStore) { this.#store = store; } /* ——— boot ——— */ /** relayFor is consulted on every (re)connect: signing in moves you to the hosted relay, signing out back to the local one — a shareable invite link can only come from a relay the invitee can also reach. */ async init(relayFor: () => string, at?: AtSession): Promise { this.#relayFor = relayFor; this.#at = at; if (at) at.onChange = () => this.#reconnect(); await this.#loadDevIdentity(); try { this.#registry = JSON.parse(await Deno.readTextFile(syncRegistryFile())); } catch { this.#registry = []; } await this.#connect(); } /** Signed in → the real AT identity; otherwise the local dev identity. */ #applyIdentity(): void { if (this.#at?.signedIn) { this.did = this.#at.did!; this.handle = this.#at.handle ?? this.#at.did!; } else { this.did = this.#devDid; this.handle = this.#devHandle; } } async #connect(): Promise { // A connect requested mid-connect (say, signing in while the first // attempt is still dialing) must not be dropped: queue one more pass so // the freshest identity/relay choice always gets its turn. if (this.#connecting) { this.#connectAgain = true; return; } this.#connecting = true; try { do { this.#connectAgain = false; await this.#connectOnce(); } while (this.#connectAgain); } finally { this.#connecting = false; } } /** Live sessions run on real identities. Signed out — and outside ZIRAN_DID developer mode — there is no one to be on a relay AS: no connection, no rejoin, no sharing. This is the enforcement behind the panel's sign-in gate; without it, registered docs quietly rejoined the LOCAL relay under the machine's throwaway dev identity and showed up "live" while signed out — technically running, meaningfully nonsense. */ #canGoLive(): boolean { return this.#at?.signedIn === true || Boolean(Deno.env.get('ZIRAN_DID')); } async #connectOnce(): Promise { // Replace whatever transport exists. Swap before closing so the old // socket's close event reads as "replaced by us", not a drop to retry. const old = this.#base; this.#base = undefined; old?.close(); this.#live.clear(); this.#applyIdentity(); if (!this.#canGoLive()) { // Parked, not failing: no retries — signing in reconnects (at.onChange). this.#transport = undefined; this.relayOk = false; this.#relayError = undefined; this.#store.broadcast(); return; } this.relayUrl = this.#relayFor(); const relayDid = Deno.env.get('ZIRAN_RELAY_DID') ?? 'did:web:relay.ziran.space'; const base = new RelaySyncTransport({ url: this.relayUrl, did: this.did, handle: this.handle, // Signed in: a service-auth JWT minted by the user's own PDS. Dev // identity: an HMAC token under the relay's shared dev secret. token: () => this.#at?.signedIn ? this.#at.relayToken(relayDid) : new DevVerifier(Deno.env.get('ZIRAN_RELAY_SECRET') ?? 'dev-secret').mint(this.did), manifestFor: (syncId) => this.#registry.find((r) => r.syncId === syncId)?.manifest, // The connection dying is a state change, not an event to shrug off: // flag it and keep trying to get back. onClose: () => { if (this.#base !== base) return; // an old socket we replaced ourselves const wasConnected = this.relayOk; this.relayOk = false; if (wasConnected) { this.#relayError = 'the connection dropped'; // A drop after a working session usually means the relay is // restarting: come back quickly, then back off if it stays gone. this.#retryDelay = 2_000; } this.#store.broadcast(); this.#scheduleRetry(); }, }); this.#base = base; const relayDir = new RelayKeyPackageDirectory(base); // KeyPackage discovery prefers the invitee's own PDS record (works // across relays, survives relay resets); the relay directory is the // fallback and the home of dev identities. const directory: KeyPackageDirectory = { publish: async (did, kp) => { await relayDir.publish(did, kp); if (this.#at?.signedIn) { await this.#at.publishKeyPackage(toB64(kp)).catch((err) => console.warn('sync: could not publish KeyPackage to PDS:', (err as Error).message) ); } }, fetch: async (did) => { const pds = await fetchPdsKeyPackage(did); if (pds) return fromB64(pds); return relayDir.fetch(did); }, }; // The MLS identity must survive restarts AND transport rebuilds: its // KeyPackage is out in the world (PDS record, relay directory), and any // invitation encrypted to it dies the moment the private keys rotate. const idFile = mlsIdentityFile(this.did); this.#transport = new MlsSyncTransport({ base, did: this.did, directory, identityStore: { load: async () => { try { return await Deno.readFile(idFile); } catch { return null; } }, save: async (bytes) => { await Deno.mkdir(dirname(idFile), { recursive: true }); await Deno.writeFile(idFile, bytes, { mode: 0o600 }); }, }, groupStore: { load: async (syncId) => { try { return await Deno.readFile(join(groupsDir(), `${syncId}.bin`)); } catch { return null; } }, save: async (syncId, state) => { const tmp = join(groupsDir(), `.${syncId}.tmp`); await Deno.writeFile(tmp, state); await Deno.rename(tmp, join(groupsDir(), `${syncId}.bin`)); }, }, }); try { await this.#transport.register(); this.relayOk = true; this.#relayError = undefined; this.#retryDelay = 5_000; // healthy again: future retries start small this.#watchInbox(); this.#watchPendingInvites(); // Rejoin every registered shared doc so offline edits flow both ways // even before its window opens. Docs shared under a different identity // than the current one fail membership and are skipped with a warning. for (const rec of this.#registry) { await this.#rejoin(rec).catch((err) => console.warn(`sync: could not rejoin ${rec.path}:`, (err as Error).message) ); } console.log(`sync: connected to ${this.relayUrl}`); } catch (err) { this.relayOk = false; this.#relayError = (err as Error).message; console.warn('sync: relay unreachable, retrying:', (err as Error).message); this.#scheduleRetry(); } this.#store.broadcast(); } /** Keep trying while the relay is unreachable: 5s doubling to a minute, resetting whenever a connection succeeds. One timer, ever. */ #scheduleRetry(): void { if (this.#retryTimer !== undefined) return; const delay = this.#retryDelay; this.#retryDelay = Math.min(this.#retryDelay * 2, 60_000); this.#retryTimer = setTimeout(() => { this.#retryTimer = undefined; if (this.relayOk) return; // recovered by other means (e.g. sign-in) this.#reconnect().catch(() => {}); }, delay) as unknown as number; } /** Tear down and rebuild the transport under the (new) current identity. #connectOnce replaces the socket itself; this clears identity-scoped state on top (another person's invitations must not linger). */ async #reconnect(): Promise { this.#invitations.clear(); this.relayOk = false; await this.#connect(); } /** A person asked to try now (panel button): skip the backoff timer. */ retryNow(): void { if (this.#retryTimer !== undefined) { clearTimeout(this.#retryTimer); this.#retryTimer = undefined; } this.#retryDelay = 5_000; this.#reconnect().catch(() => {}); } async #loadDevIdentity(): Promise { const envDid = Deno.env.get('ZIRAN_DID'); const envHandle = Deno.env.get('ZIRAN_HANDLE'); try { const saved = JSON.parse(await Deno.readTextFile(identityFile())); this.#devDid = envDid ?? saved.did; this.#devHandle = envHandle ?? saved.handle; } catch { this.#devDid = envDid ?? `did:ziran:${[...crypto.getRandomValues(new Uint8Array(6))].map((b) => b.toString(16).padStart(2, '0')).join('')}`; this.#devHandle = envHandle ?? `${Deno.env.get('USER') ?? 'someone'}.ziran.local`; } await Deno.writeTextFile(identityFile(), JSON.stringify({ did: this.#devDid, handle: this.#devHandle })); } async #persistRegistry(): Promise { await Deno.writeTextFile(syncRegistryFile(), JSON.stringify(this.#registry, null, 2)); } /* ——— inbox ——— */ #watchInbox(): void { const transport = this.#transport!; (async () => { for await (const inv of transport.inbox()) { if (this.#transport !== transport) break; // identity switched; stale loop if (this.#dismissed.has(inv.token)) continue; // Already a member (or our own doc)? Then this invite is stale. if (this.#registry.some((r) => r.syncId === inv.docId)) continue; this.#invitations.set(inv.token, inv); this.#store.broadcast(); } })().catch(() => {}); } /** Invitations we issued to people who had never run Ziran complete themselves here: the relay says the invitee has published keys, so we add them to the group and hand over the Welcome. Needs the document in a live session, which rejoin gives us at startup. */ #watchPendingInvites(): void { const transport = this.#transport!; transport.onInviteReady(async (token, syncId, inviteeDid) => { if (this.#transport !== transport) return; // identity switched const rec = this.#registry.find((r) => r.syncId === syncId); if (!rec) return; try { await transport.completePending(token, syncId, inviteeDid); // The newcomer joins at the epoch this add created, so they need a // snapshot encrypted for it. await this.uploadSnapshot(rec); this.#store.broadcast(); console.log(`sync: completed the invitation for ${inviteeDid}`); } catch (err) { console.warn(`sync: could not complete an invitation:`, (err as Error).message); } }); } /* ——— doc lookup ——— */ byLocal(localId: string): SharedDoc | undefined { return this.#registry.find((r) => r.localId === localId); } /** Doc ids are path-derived, so a file move re-keys the registry entry (called via the store's move hook). */ moved(oldId: string, newId: string, newPath: string): void { const rec = this.#registry.find((r) => r.localId === oldId); if (!rec) return; const live = this.#live.get(oldId); rec.localId = newId; rec.path = newPath; if (live) { this.#live.delete(oldId); this.#live.set(newId, live); } this.#persistRegistry().catch(() => {}); } /* ——— sharing ——— */ /** Start sharing an open document: create the sync channel, join it, and upload the initial snapshot (the tile file itself). */ async share(localId: string): Promise { this.#requireRelay(); const doc = this.#store.doc(localId); if (!doc) throw new Error('document is not open'); const byPath = this.#registry.find((r) => r.path === doc.info.path); if (byPath && byPath.localId !== localId) this.moved(byPath.localId, localId, doc.info.path); const existing = this.byLocal(localId); if (existing) return existing; const manifest = (doc.tile.manifest as { sync?: { roles?: SyncManifest['roles']; owner?: string } }).sync; const rec: SharedDoc = { localId, syncId: crypto.randomUUID().replace(/-/g, ''), path: doc.info.path, role: '', manifest: manifest?.roles ? { owner: manifest.owner ?? Object.keys(manifest.roles)[0]!, roles: manifest.roles } : DEFAULT_MANIFEST, ackedSeq: 0, }; rec.role = rec.manifest.owner; this.#registry.push(rec); await this.#persistRegistry(); await this.#join(rec, 0); // Initial snapshot so the very first invitee downloads-then-syncs. await this.uploadSnapshot(rec); this.#store.broadcast(); return rec; } async #rejoin(rec: SharedDoc): Promise { const restored = await this.#transport!.restoreGroup(rec.syncId); if (!restored) throw new Error('no persisted group state'); await this.#join(rec, rec.ackedSeq); } async #join(rec: SharedDoc, sinceSeq: number): Promise { const session = await this.#transport!.join(rec.syncId, { sinceSeq }); const live: LiveDoc = { rec, session, buffer: [], lastForwardedSeq: sinceSeq, roster: session.roster() }; this.#live.set(rec.localId, live); session.onMessage((m) => { live.lastForwardedSeq = Math.max(live.lastForwardedSeq, m.seq); const frame = { seq: m.seq, author: m.author, role: m.role, b64: toB64(m.bytes) }; live.buffer.push(frame); this.#store.broadcastEvent({ type: 'sync-msg', docId: rec.localId, ...frame }); }); session.onEphemeral((m) => { this.#store.broadcastEvent({ type: 'sync-eph', docId: rec.localId, author: m.author, role: m.role, b64: toB64(m.bytes), }); }); session.onRoster((roster) => { live.roster = roster; this.#store.broadcastEvent({ type: 'sync-roster', docId: rec.localId, roster }); this.#store.broadcast(); // membership shows in panel + banner state }); // A tile already open when its doc goes live must hear 'ready' without // re-announcing itself. this.#store.broadcastEvent({ type: 'sync-ready', docId: rec.localId, me: session.me, roster: live.roster }); } /* ——— invitations out ——— */ async invite(localId: string, identifier: string, role: string): Promise<{ invitation: Invitation; link: string }> { this.#requireRelay(); const rec = this.byLocal(localId) ?? (await this.share(localId)); const spec = rec.manifest.roles[role]; if (!spec) throw new Error(`this document has no “${role}” role`); // Check the cap before touching the MLS group: the add-commit and the // relay-side invitation must move together, so refuse what the relay // would refuse before the group has advanced. if (typeof spec.max === 'number') { const holding = (this.#live.get(localId)?.roster ?? []).filter((m) => m.role === role).length; if (holding >= spec.max) { throw new Error(`every “${spec.label ?? role}” seat is taken`); } } // Handles resolve to DIDs (with backlink verification); dev DIDs and // real DIDs pass through as-is. let inviteeDid = identifier.trim(); if (!inviteeDid.startsWith('did:')) { inviteeDid = (await resolveIdentity(inviteeDid)).did; } if (inviteeDid === this.did) throw new Error('that is your own identity'); const doc = this.#store.doc(localId); const invitation = await this.#transport!.invite(rec.syncId, inviteeDid, role, doc?.info.name); // Snapshot AFTER the add-commit: the invitee joins at the post-add epoch // and can only decrypt a snapshot encrypted at (or after) that epoch. // (A pending invitation adds nobody yet; its snapshot comes on completion.) if (!invitation.pending) await this.uploadSnapshot(rec); this.#store.broadcast(); return { invitation, link: this.inviteLink(invitation.token) }; } inviteLink(token: string): string { // ws://host:port/ws → http://host:port/i/ return this.relayUrl.replace(/^ws/, 'http').replace(/\/ws$/, '') + `/i/${token}`; } /* ——— invitations in ——— */ async accept(token: string): Promise<{ path: string }> { this.#requireRelay(); let inv = this.#invitations.get(token) ?? (await this.#base!.getInvite(token)) ?? undefined; if (inv?.pending) { // Our copy may be stale — the inviter can have completed it since we // cached it (or before we reconnected). Ask the relay for the truth. const fresh = await this.#base!.getInvite(token); if (fresh) { inv = fresh; this.#invitations.set(token, fresh); this.#store.broadcast(); } } if (!inv) throw new Error('invitation not found — it may have been withdrawn'); if (inv.pending) { throw new Error( `${inv.inviterHandle ?? 'The person who invited you'} still has to finish this invitation; it will arrive on its own`, ); } // Download-then-sync: the snapshot IS the tile file; verify + open happens // through the normal engine path once we write it into documents/. const result = await this.#transport!.accept(token); if (!result.snapshot) throw new Error('the document snapshot is missing — ask for a fresh invitation'); const stem = (inv.title || 'shared').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'shared'; let path = join(documentsDir(), `${stem}.tile`); try { await Deno.stat(path); path = join(documentsDir(), `${stem}-${token.slice(0, 6)}.tile`); } catch { // free name } await Deno.writeFile(path, result.snapshot); const rec: SharedDoc = { localId: '', // set after openPath derives it syncId: result.docId, path, role: result.role, manifest: DEFAULT_MANIFEST, // relay enforces; local copy is advisory ackedSeq: result.atSeq, }; this.#invitations.delete(token); this.#dismissed.add(token); // openPath verifies CIDs and registers recents; its id keys our registry. const info = await this.#store.openPath(path); rec.localId = info.id; this.#registry.push(rec); await this.#persistRegistry(); await this.#join(rec, result.atSeq); this.#store.broadcast(); return { path }; } dismiss(token: string): void { this.#invitations.delete(token); this.#dismissed.add(token); this.#store.broadcast(); } /* ——— tile traffic (called from the API on behalf of the UI bridge) ——— */ /** Tile (re)announced itself: flush everything past its persisted state. */ attach(localId: string): { me: Member; roster: Member[]; buffered: BufferedFrame[] } | null { const live = this.#live.get(localId); if (!live) return null; return { me: live.session.me, roster: live.roster, buffered: live.buffer.filter((m) => m.seq > live.rec.ackedSeq), }; } async send(localId: string, b64: string): Promise { const live = this.#live.get(localId); if (!live) throw new Error('document is not in a live session'); return await live.session.append(fromB64(b64)); } ephemeral(localId: string, b64: string): void { // Fire-and-forget by contract; a rejection (socket died mid-send) must // not surface as an unhandled rejection and take the process down. Promise.resolve(this.#live.get(localId)?.session.ephemeral(fromB64(b64))).catch(() => {}); } /** The tile persisted its state (putData): everything forwarded so far is now reflected in the tile file. Advance the snapshot point, trim the buffer, and upload the fresh snapshot. */ async onLocalDataWrite(localId: string): Promise { const live = this.#live.get(localId); if (!live) return; live.rec.ackedSeq = live.lastForwardedSeq; live.buffer = live.buffer.filter((m) => m.seq > live.rec.ackedSeq); await this.#persistRegistry(); await this.uploadSnapshot(live.rec).catch(() => {}); } async uploadSnapshot(rec: SharedDoc): Promise { const live = this.#live.get(rec.localId); if (!live) return; const bytes = await Deno.readFile(rec.path); await live.session.snapshot(bytes, rec.ackedSeq); } /* ——— state for the UI ——— */ summary(): SyncSummary { const docs: SyncSummary['docs'] = {}; // Every *registered* shared doc appears — live or not. A relay outage // must read as "sharing is paused", never as "this was never shared". for (const rec of this.#registry) { const live = this.#live.get(rec.localId); const roster = live?.roster ?? []; const manifest = rec.manifest; docs[rec.localId] = { syncId: rec.syncId, role: rec.role, // A session is only as live as the socket under it: after a drop the // map still holds the old session until the next connect attempt. live: this.relayOk && Boolean(live), members: roster, inviteBase: this.relayUrl.replace(/^ws/, 'http').replace(/\/ws$/, ''), // The document defines its own roles; the chrome offers exactly // those, minus the owner's (that seat is taken) and any at capacity. roles: Object.entries(manifest.roles).map(([name, spec]) => ({ name, label: spec.label ?? name.charAt(0).toUpperCase() + name.slice(1), invitable: name !== manifest.owner, full: typeof spec.max === 'number' && roster.filter((m) => m.role === name).length >= spec.max, })), }; } return { provider: 'relay', identity: { did: this.did, handle: this.handle }, // An explicit ZIRAN_DID is developer mode: local dev identities may // invite each other without AT sign-in. Without it, inviting requires // signing in (the UI gates on this). devIdentity: Boolean(Deno.env.get('ZIRAN_DID')), at: this.#at?.signedIn ? { signedIn: true, handle: this.#at.handle ?? undefined, did: this.#at.did ?? undefined, displayName: this.#at.displayName ?? undefined, hasAvatar: Boolean(this.#at.avatar), } : { signedIn: false }, relayOk: this.relayOk, relay: this.relayUrl, relayError: this.relayOk ? undefined : this.#relayError, invitations: [...this.#invitations.values()].map(({ payload: _p, ...rest }) => rest), docs, }; } #requireRelay(): void { if (!this.#canGoLive()) { throw new Error('going live needs your AT identity — sign in first'); } if (!this.relayOk || !this.#transport) { throw new Error( this.#relayError ? `the relay is unreachable (${this.#relayError}) — collaboration is paused` : 'the relay is unreachable — collaboration is paused', ); } } }