Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(relay): hosted team store with roles and a closed start on corruption

reviewe960329d4183
diff --git a/src/core/relay/team-store.test.ts b/src/core/relay/team-store.test.ts
new file mode 100644
index 000000000..9f6f4ddb3
--- /dev/null
+++ b/src/core/relay/team-store.test.ts
@@ -0,0 +1,111 @@
+// src/core/relay/team-store.test.ts
+import { describe, it, expect, afterEach } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { TeamStore, parseTeam, emptyTeam, upsertPeer, removePeer, setShared, peerFor } from './team-store'
+
+const made: string[] = []
+const tmp = () => {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'team-'))
+ made.push(d)
+ return d
+}
+afterEach(() => {
+ for (const d of made.splice(0)) fs.rmSync(d, { recursive: true, force: true })
+})
+const owner = { pubkeyB64: 'O', label: 'Enes', role: 'owner' as const, addedAt: '2026-09-28T00:00:00Z', addedBy: 'cli' }
+const writeDoc = (dir: string, doc: unknown) =>
+ fs.writeFileSync(path.join(dir, 'team.json'), JSON.stringify(doc))
+
+describe('team doc', () => {
+ it('rejects a forged role and unknown shapes', () => {
+ expect(parseTeam({ v: 1, peers: [{ ...owner, role: 'root' }], sharedProjects: [] })).toBeNull()
+ expect(parseTeam({ v: 2, peers: [], sharedProjects: [] })).toBeNull()
+ expect(parseTeam(null)).toBeNull()
+ expect(parseTeam({ v: 1, peers: [owner], sharedProjects: ['p1'] })).toEqual({ v: 1, peers: [owner], sharedProjects: ['p1'] })
+ })
+ it('upsert replaces by key; remove refuses the last owner without force', () => {
+ let d = upsertPeer(emptyTeam(), owner)
+ d = upsertPeer(d, { ...owner, label: 'E2' })
+ expect(d.peers).toHaveLength(1)
+ expect(peerFor(d, 'O')?.label).toBe('E2')
+ expect(removePeer(d, 'O', false)).toBe('last-owner')
+ expect(removePeer(d, 'O', true)).toEqual({ ...d, peers: [] })
+ })
+ it('remove refuses when a key listed twice as owner is the only owner key', () => {
+ // A hand-edited file can list one key twice. Counting ENTRIES would see two owners and let
+ // the removal (which drops every entry for that key) leave the team with none.
+ const doubled = { ...emptyTeam(), peers: [owner, { ...owner, label: 'dup' }] }
+ expect(removePeer(doubled, 'O', false)).toBe('last-owner')
+ // A non-owner leaving a team that has no owner at all is not a last-owner removal.
+ const noOwner = upsertPeer(emptyTeam(), { ...owner, pubkeyB64: 'V', role: 'viewer' })
+ expect(removePeer(noOwner, 'V', false)).toEqual(emptyTeam())
+ })
+ it('setShared is idempotent', () => {
+ const d = setShared(setShared(emptyTeam(), 'p', true), 'p', true)
+ expect(d.sharedProjects).toEqual(['p'])
+ expect(setShared(d, 'p', false).sharedProjects).toEqual([])
+ })
+})
+
+describe('TeamStore', () => {
+ it('persists 0600 and reloads', async () => {
+ const dir = tmp()
+ const s = new TeamStore(dir)
+ await s.load()
+ await s.update((d) => upsertPeer(d, owner))
+ expect((fs.statSync(path.join(dir, 'team.json')).mode & 0o777).toString(8)).toBe('600')
+ const again = new TeamStore(dir)
+ expect(peerFor(await again.load(), 'O')?.role).toBe('owner')
+ })
+ it('a corrupt file is set aside and the store starts CLOSED (no pins)', async () => {
+ const dir = tmp()
+ fs.writeFileSync(path.join(dir, 'team.json'), '{not json')
+ const s = new TeamStore(dir)
+ expect((await s.load()).peers).toEqual([])
+ expect(fs.readdirSync(dir).some((f) => f.startsWith('team.json.corrupt-'))).toBe(true)
+ })
+ it('concurrent updates never lose a write', async () => {
+ const s = new TeamStore(tmp())
+ await s.load()
+ await Promise.all(['a', 'b', 'c'].map((k) => s.update((d) => upsertPeer(d, { ...owner, pubkeyB64: k }))))
+ expect(s.current().peers.map((p) => p.pubkeyB64).sort()).toEqual(['a', 'b', 'c'])
+ })
+ it('an update on a never-loaded store loads the file first instead of replacing it', async () => {
+ // The admin `add-owner` path can run while start() never loaded (e.g. the host key was
+ // unreadable). Writing from the in-memory empty doc would wipe every existing member.
+ const dir = tmp()
+ writeDoc(dir, { v: 1, peers: [owner, { ...owner, pubkeyB64: 'E', role: 'editor' }], sharedProjects: ['p1'] })
+ const s = new TeamStore(dir)
+ await s.update((d) => upsertPeer(d, { ...owner, pubkeyB64: 'V', role: 'viewer' }))
+ const onDisk = await new TeamStore(dir).load()
+ expect(onDisk.peers.map((p) => p.pubkeyB64).sort()).toEqual(['E', 'O', 'V'])
+ expect(onDisk.sharedProjects).toEqual(['p1'])
+ })
+ it('an unreadable file is never overwritten, and the next update retries the load', async () => {
+ const dir = tmp()
+ const file = path.join(dir, 'team.json')
+ fs.mkdirSync(file) // readFile → EISDIR: unreadable, which is not the same as absent
+ const s = new TeamStore(dir)
+ await expect(s.update((d) => upsertPeer(d, owner))).rejects.toThrow()
+ expect(fs.statSync(file).isDirectory()).toBe(true)
+ fs.rmdirSync(file)
+ writeDoc(dir, { v: 1, peers: [{ ...owner, pubkeyB64: 'E', role: 'editor' }], sharedProjects: [] })
+ await s.update((d) => upsertPeer(d, owner))
+ expect(s.current().peers.map((p) => p.pubkeyB64).sort()).toEqual(['E', 'O'])
+ })
+ it('a load() called after an update() sees that update (loads are serialized with writes)', async () => {
+ // An unserialized read issued while a write is queued returns the pre-write file and resets
+ // the in-memory doc to it — the next update then computes from stale state and drops a write.
+ const dir = tmp()
+ writeDoc(dir, { v: 1, peers: [owner], sharedProjects: [] })
+ const s = new TeamStore(dir)
+ await s.load()
+ const u = s.update((d) => upsertPeer(d, { ...owner, pubkeyB64: 'B', role: 'editor' }))
+ const l = s.load()
+ await u
+ expect(peerFor(await l, 'B')?.role).toBe('editor')
+ expect(peerFor(s.current(), 'B')?.role).toBe('editor')
+ })
+})
diff --git a/src/core/relay/team-store.ts b/src/core/relay/team-store.ts
new file mode 100644
index 000000000..32bd59a94
--- /dev/null
+++ b/src/core/relay/team-store.ts
@@ -0,0 +1,129 @@
+// The hosted team's membership: which device keys may auto-reconnect, with what role, and which
+// projects non-editors may see. Pure transforms + a single-writer store.
+//
+// SEPARATE from the phone's remote-approved-devices.json on purpose: push's `hasPairedPhone` counts
+// that file's entries, so a teammate's pin there would read as a paired phone.
+//
+// Corrupt ⇒ CLOSED: the file is set aside and the store starts with no peers, so nobody
+// auto-reconnects. The owner recovers with `team add-owner` over SSH, which is also the
+// root of trust.
+import { promises as fs, existsSync, mkdirSync } from 'node:fs'
+import path from 'node:path'
+import { writeFileAtomic, renameAtomic } from '../fs-atomic'
+
+export type TeamRole = 'owner' | 'editor' | 'commenter' | 'viewer'
+export const TEAM_ROLES: readonly TeamRole[] = ['owner', 'editor', 'commenter', 'viewer']
+export interface TeamPeer { pubkeyB64: string; label: string; role: TeamRole; addedAt: string; addedBy: string }
+export interface TeamDoc { v: 1; peers: TeamPeer[]; sharedProjects: string[] }
+
+const LABEL_MAX = 60
+const isStr = (v: unknown, max = 512): v is string => typeof v === 'string' && v.length > 0 && v.length <= max
+
+export function emptyTeam(): TeamDoc {
+ return { v: 1, peers: [], sharedProjects: [] }
+}
+
+export function parseTeam(raw: unknown): TeamDoc | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
+ const o = raw as Record<string, unknown>
+ if (o.v !== 1 || !Array.isArray(o.peers) || !Array.isArray(o.sharedProjects)) return null
+ const peers: TeamPeer[] = []
+ for (const p of o.peers) {
+ if (!p || typeof p !== 'object') return null
+ const q = p as Record<string, unknown>
+ if (!isStr(q.pubkeyB64, 64) || typeof q.label !== 'string' || q.label.length > LABEL_MAX) return null
+ if (!(TEAM_ROLES as readonly unknown[]).includes(q.role)) return null
+ if (!isStr(q.addedAt, 40) || !isStr(q.addedBy, 64)) return null
+ peers.push({ pubkeyB64: q.pubkeyB64, label: q.label, role: q.role as TeamRole, addedAt: q.addedAt, addedBy: q.addedBy })
+ }
+ if (!o.sharedProjects.every((s) => isStr(s, 128))) return null
+ return { v: 1, peers, sharedProjects: [...new Set(o.sharedProjects as string[])] }
+}
+
+export function peerFor(doc: TeamDoc, pubkeyB64: string): TeamPeer | undefined {
+ return doc.peers.find((p) => p.pubkeyB64 === pubkeyB64)
+}
+
+export function upsertPeer(doc: TeamDoc, p: TeamPeer): TeamDoc {
+ const label = p.label.slice(0, LABEL_MAX)
+ return { ...doc, peers: [...doc.peers.filter((x) => x.pubkeyB64 !== p.pubkeyB64), { ...p, label }] }
+}
+
+export function removePeer(doc: TeamDoc, pubkeyB64: string, force: boolean): TeamDoc | 'last-owner' {
+ if (!peerFor(doc, pubkeyB64)) return doc
+ const rest = doc.peers.filter((p) => p.pubkeyB64 !== pubkeyB64)
+ // "Would an owner remain?", not "is this the only owner ENTRY?": a hand-edited file can list one
+ // key twice, and counting entries would let this removal (which drops every entry for the key)
+ // leave a team that had an owner with none.
+ const hadOwner = doc.peers.some((p) => p.role === 'owner')
+ if (hadOwner && !rest.some((p) => p.role === 'owner') && !force) return 'last-owner'
+ return { ...doc, peers: rest }
+}
+
+export function setShared(doc: TeamDoc, projectId: string, on: boolean): TeamDoc {
+ const rest = doc.sharedProjects.filter((p) => p !== projectId)
+ return { ...doc, sharedProjects: on ? [...rest, projectId] : rest }
+}
+
+export class TeamStore {
+ private doc: TeamDoc = emptyTeam()
+ /** Whether `doc` reflects the file. Until it does, a write would publish the in-memory empty
+ * doc OVER the real team (an admin `add-owner` while `start()` never loaded is the case). */
+ private loaded = false
+ private tail: Promise<unknown> = Promise.resolve()
+ constructor(private readonly dir: string) {}
+ private file(): string { return path.join(this.dir, 'team.json') }
+ exists(): boolean { return existsSync(this.file()) }
+ current(): TeamDoc { return this.doc }
+
+ /** Queued behind every earlier update, so it never hands back (or resets `current()` to) a file
+ * a queued write is about to replace — the next update would compute from that stale doc. */
+ load(): Promise<TeamDoc> {
+ return this.serialize(() => this.read())
+ }
+
+ update(fn: (d: TeamDoc) => TeamDoc | 'last-owner'): Promise<TeamDoc | 'last-owner'> {
+ return this.serialize(async () => {
+ // Lazily, INSIDE the chain: a failed read rejects this update and leaves `loaded` false, so
+ // nothing is written over a file we could not read and the next update tries again.
+ if (!this.loaded) await this.read()
+ const next = fn(this.doc)
+ if (next === 'last-owner') return next
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 })
+ await writeFileAtomic(this.file(), JSON.stringify(next, null, 2) + '\n', { mode: 0o600 })
+ this.doc = next
+ return next
+ })
+ }
+
+ private serialize<T>(op: () => Promise<T>): Promise<T> {
+ const run = this.tail.then(op)
+ this.tail = run.catch(() => {})
+ return run
+ }
+
+ /** The unqueued read. Only ever called from inside `serialize`. */
+ private async read(): Promise<TeamDoc> {
+ let raw: string
+ try {
+ raw = await fs.readFile(this.file(), 'utf-8')
+ } catch (err) {
+ // Unreadable is not absent (#385): refuse rather than start empty over it.
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
+ return this.adopt(emptyTeam())
+ }
+ let parsed: TeamDoc | null = null
+ try { parsed = parseTeam(JSON.parse(raw)) } catch { parsed = null }
+ if (!parsed) {
+ await renameAtomic(this.file(), `${this.file()}.corrupt-${Date.now()}`)
+ return this.adopt(emptyTeam())
+ }
+ return this.adopt(parsed)
+ }
+
+ private adopt(doc: TeamDoc): TeamDoc {
+ this.doc = doc
+ this.loaded = true
+ return doc
+ }
+}