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 service — owner approval, roles, removal

review535cf8bf03c0
diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.ts
new file mode 100644
index 000000000..85bc1acf2
--- /dev/null
+++ b/src/core/relay/hosted-service.test.ts
@@ -0,0 +1,629 @@
+// src/core/relay/hosted-service.test.ts
+// Real relay-socket E2EE + real trust gates over an in-process transport; fake mint + fake attach.
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { createHostedService, PENDING_TTL_MS, type HostedService, type HostedServiceDeps } from './hosted-service'
+import { transportPair } from './transport-pair'
+import { connectRelayClient } from './relay-client'
+import { killRelayHostsByPeerKey, type PeerAttach } from './relay-host'
+import { connectRelay } from './relay-socket'
+import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
+import { decodeJoinCode } from './join-code'
+import { IPC } from '../../shared/ipc'
+import type { RelayTransport } from './relay-socket'
+
+const pub = (k: KeyPair) => publicKeyToB64(k.publicKey)
+
+interface Armed { ms: number; h: unknown; cleared: boolean }
+
+const live: Array<{ svc: HostedService; dataDir: string }> = []
+afterEach(() => {
+ for (const w of live.splice(0)) {
+ w.svc.stop()
+ fs.rmSync(w.dataDir, { recursive: true, force: true })
+ }
+})
+
+function world(opts: Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectOfNode'>> & { recordTimers?: boolean } = {}) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-'))
+ const sinks = new Map<number, { sendText(j: string): void }>()
+ const dispatched: string[] = []
+ const casts: string[] = []
+ let next = 1
+ const attach: PeerAttach = {
+ attach: (s) => { const id = next++; sinks.set(id, s); return id },
+ detach: (id) => { sinks.delete(id) },
+ dispatch: async (_id, req) => {
+ dispatched.push(req.method)
+ if (req.method === IPC.agentSubagentSnapshot) {
+ return { t: 'res', id: req.id, ok: true, result: [{ nodeId: 'n-shared', task: 'shared task' }, { nodeId: 'n-other', task: 'SECRET other task' }] }
+ }
+ return { t: 'res', id: req.id, ok: true, result: { projects: [{ id: 'P' }, { id: 'Q' }], activeProjectId: 'P' } }
+ },
+ cast: (_id, method) => { casts.push(method) }
+ }
+ const peersT: RelayTransport[] = []
+ let mints = 0
+ const armed: Armed[] = []
+ const timerDeps: Pick<HostedServiceDeps, 'setTimeout' | 'clearTimeout'> = opts.recordTimers
+ ? {
+ setTimeout: (fn, ms) => { const h = setTimeout(fn, ms); armed.push({ ms, h, cleared: false }); return h },
+ clearTimeout: (h) => {
+ for (const a of armed) if (a.h === h) a.cleared = true
+ clearTimeout(h as ReturnType<typeof setTimeout>)
+ }
+ }
+ : {}
+ const svc = createHostedService({
+ dataDir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',
+ attach,
+ projectOfNode: opts.projectOfNode ?? ((id) => (id === 'n-other' ? 'Q' : 'P')),
+ projectCwd: () => '/srv/app',
+ fetch: (async () => { mints++; return new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 }) }) as typeof fetch,
+ transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT },
+ ...(opts.now ? { now: opts.now } : {}),
+ ...(opts.monotonicNow ? { monotonicNow: opts.monotonicNow } : {}),
+ ...timerDeps
+ })
+ live.push({ svc, dataDir })
+ const join = (keys = genKeyPair(), auto = false, humanConfirms = true) => {
+ const frames: string[] = []
+ const denied: string[] = []
+ let approved = false
+ let closed = 0
+ const peerT = peersT.shift()!
+ const c = connectRelayClient({
+ url: 'ws://127.0.0.1/r', token: 'T', hostKeyB64: svc.info()!.hostPublicKeyB64, ourKeys: keys, transport: peerT,
+ // The guest's human confirms on a LATER turn, as a human does. Over this in-process transport
+ // onSas runs inside connectRelay, before the client holds its socket, so a confirm sent there
+ // would be dropped (a real WebSocket never delivers inside connectRelay).
+ autoApprove: auto, onSas: (s) => { if (humanConfirms) queueMicrotask(() => s.confirm()) }, onApproved: () => { approved = true }, onFrame: (j) => frames.push(j),
+ onPtyData: () => {}, onClose: () => { closed++ }, onDenied: (r) => denied.push(r)
+ })
+ const res = (id: number) => {
+ const f = frames.find((x) => { const m = JSON.parse(x); return m.t === 'res' && m.id === id })
+ return f ? JSON.parse(f) : undefined
+ }
+ const events = (channel: string) => frames.map((x) => JSON.parse(x)).filter((m) => m.t === 'ev' && m.channel === channel).map((m) => m.args[0])
+ return {
+ c, frames, denied, keys, res, events,
+ isApproved: () => approved,
+ closedCount: () => closed,
+ req: (id: number, method: string, args: unknown[] = []) => c.send(JSON.stringify({ t: 'req', id, method, args })),
+ cast: (method: string, args: unknown[] = []) => c.send(JSON.stringify({ t: 'cast', method, args }))
+ }
+ }
+ /** A peer below the relay client: it finishes the handshake but never confirms, and can send
+ * tunnel frames the real client refuses to send before approval. */
+ const rawPeer = (keys = genKeyPair()) => {
+ const frames: string[] = []
+ const socket = connectRelay({
+ url: 'ws://127.0.0.1/r', token: 'T', role: 'client', ourKeys: keys, theirPubB64: svc.info()!.hostPublicKeyB64,
+ transport: peersT.shift()!, onReady: () => {}, onRpc: () => {}, onFrame: () => {}, onClose: () => {},
+ onTunnel: (kind, payload) => { if (kind === 'text') frames.push(new TextDecoder().decode(payload)) }
+ })
+ const res = (id: number) => {
+ const f = frames.find((x) => { const m = JSON.parse(x); return m.t === 'res' && m.id === id })
+ return f ? JSON.parse(f) : undefined
+ }
+ return { frames, res, req: (id: number, method: string, args: unknown[] = []) => socket.sendTunnelText(JSON.stringify({ t: 'req', id, method, args })) }
+ }
+ return { svc, join, rawPeer, sinks, dispatched, casts, dataDir, armed, mints: () => mints }
+}
+
+/** The HOST opened the session. The client's own open can come first: the host pins an
+ * owner-approved teammate into the team store before it opens. */
+async function hostOpened(w: ReturnType<typeof world>, keys: KeyPair) {
+ // An approved request leaves `pending` in the host's onOpen (the tests here never deny these).
+ await vi.waitFor(() => expect(w.svc.status().pending.some((p) => p.peerKeyB64 === pub(keys))).toBe(false))
+}
+
+async function ownerOnline(w: ReturnType<typeof world>, ownerKeys = genKeyPair()) {
+ await w.svc.init()
+ await w.svc.addOwner(pub(ownerKeys), 'Enes')
+ await w.svc.share('P', true)
+ expect(await w.svc.start()).toBe('started')
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const owner = w.join(ownerKeys, true)
+ await vi.waitFor(() => expect(owner.isApproved()).toBe(true))
+ return owner
+}
+
+/** A guest whose first connect is waiting for an owner. */
+async function pendingGuest(w: ReturnType<typeof world>, keys = genKeyPair()) {
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const before = w.svc.status().pending.length
+ const g = w.join(keys)
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(before + 1))
+ const pendingId = w.svc.status().pending.find((p) => p.peerKeyB64 === pub(keys))!.pendingId
+ return { g, pendingId }
+}
+
+async function approvedGuest(w: ReturnType<typeof world>, owner: Awaited<ReturnType<typeof ownerOnline>>, role: string, id: number, keys = genKeyPair()) {
+ const { g, pendingId } = await pendingGuest(w, keys)
+ owner.req(id, IPC.relayHostedApprove, [pendingId, role])
+ await vi.waitFor(() => expect(g.isApproved()).toBe(true))
+ await vi.waitFor(() => expect(w.svc.status().pending.some((p) => p.pendingId === pendingId)).toBe(false))
+ return g
+}
+
+describe('hosted service', () => {
+ it('an unknown device waits; only owners are told; nothing is served before approval', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const guest = w.join()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ await vi.waitFor(() => expect(owner.frames.some((f) => f.includes(IPC.relayHostedPeerPending))).toBe(true))
+ // The relay client itself refuses to send before approval…
+ expect(guest.req(1, IPC.workspaceLoad)).toBe(false)
+ // …and the host refuses a peer that sends anyway, hosted verbs included.
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const raw = w.rawPeer()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(2))
+ raw.req(1, IPC.workspaceLoad)
+ raw.req(2, IPC.relayHostedApprove, [w.svc.status().pending[0].pendingId, 'owner'])
+ raw.req(3, IPC.relayHostedSelf)
+ await vi.waitFor(() => expect(raw.res(3)).toBeDefined())
+ for (const id of [1, 2, 3]) expect(raw.res(id)).toMatchObject({ ok: false, error: { code: 'E_UNAUTHORIZED' } })
+ expect(w.dispatched).toEqual([])
+ expect(w.svc.status().pending).toHaveLength(2)
+ })
+
+ it('owner approves as viewer; the guest opens with viewer rights and a narrowed workspace', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const guest = w.join()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ owner.req(5, IPC.relayHostedApprove, [w.svc.status().pending[0].pendingId, 'viewer'])
+ await vi.waitFor(() => expect(guest.isApproved()).toBe(true))
+ await hostOpened(w, guest.keys)
+ guest.req(2, IPC.fsWrite, ['/srv/app/x', 'y'])
+ await vi.waitFor(() => expect(guest.frames.some((f) => f.includes('"id":2') && f.includes('E_ROLE'))).toBe(true))
+ guest.req(3, IPC.workspaceLoad)
+ await vi.waitFor(() => expect(guest.frames.some((f) => f.includes('"id":3'))).toBe(true))
+ const res = JSON.parse(guest.frames.find((f) => f.includes('"id":3'))!)
+ expect(res.result.projects.map((p: { id: string }) => p.id)).toEqual(['P'])
+ expect(w.svc.status().peers.find((p) => p.role === 'viewer')).toBeTruthy()
+ })
+
+ it('a non-owner cannot approve', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const g1 = w.join()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ owner.req(5, IPC.relayHostedApprove, [w.svc.status().pending[0].pendingId, 'editor'])
+ await vi.waitFor(() => expect(g1.isApproved()).toBe(true))
+ await hostOpened(w, g1.keys)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const g2 = w.join()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ g1.req(9, IPC.relayHostedApprove, [w.svc.status().pending[0].pendingId, 'owner'])
+ await vi.waitFor(() => expect(g1.frames.some((f) => f.includes('"id":9') && f.includes('Only an owner'))).toBe(true))
+ expect(g2.isApproved()).toBe(false)
+ })
+
+ it('pinned reconnect needs no human; removal cuts the live session with a reason', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const keys = genKeyPair()
+ const g = w.join(keys)
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ owner.req(5, IPC.relayHostedApprove, [w.svc.status().pending[0].pendingId, 'editor'])
+ await vi.waitFor(() => expect(g.isApproved()).toBe(true))
+ await hostOpened(w, keys)
+ g.c.close()
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const again = w.join(keys, true)
+ await vi.waitFor(() => expect(again.isApproved()).toBe(true))
+ expect(await w.svc.remove(publicKeyToB64(keys.publicKey), false)).toBe('removed')
+ await vi.waitFor(() => expect(again.denied).toEqual(['removed']))
+ })
+
+ it('an unanswered request expires after 10 minutes and is denied', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+ try {
+ const w = world()
+ const owner = await ownerOnline(w)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const g = w.join()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ const pendingId = w.svc.status().pending[0].pendingId
+ expect(w.svc.status().scheduler?.bridged).toBe(2)
+ await vi.advanceTimersByTimeAsync(600_000)
+ await vi.waitFor(() => expect(g.denied).toEqual(['expired']))
+ expect(w.svc.status().pending).toHaveLength(0)
+ // R20: the scheduler heard the end it did not see on the wire.
+ expect(w.svc.status().scheduler?.bridged).toBe(1)
+ expect(owner.events(IPC.relayHostedPendingClosed)).toContainEqual({ pendingId, reason: 'expired' })
+ w.svc.stop()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('the pending TTL is ten minutes', () => {
+ expect(PENDING_TTL_MS).toBe(600_000)
+ })
+})
+
+describe('hosted service — owner routing', () => {
+ it('pending events go to connected OWNERS only; an owner who connects later is told what is still open', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const editor = await approvedGuest(w, owner, 'editor', 5)
+ const { pendingId } = await pendingGuest(w)
+ await vi.waitFor(() => expect(owner.events(IPC.relayHostedPeerPending).map((p) => p.pendingId)).toContain(pendingId))
+ expect(editor.frames.some((f) => f.includes('relay:hosted:'))).toBe(false)
+
+ // A second owner, offline until now: the open request reaches them on connect.
+ const secondKeys = genKeyPair()
+ await w.svc.addOwner(pub(secondKeys), 'Ada')
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const second = w.join(secondKeys, true)
+ await vi.waitFor(() => expect(second.isApproved()).toBe(true))
+ await vi.waitFor(() => expect(second.events(IPC.relayHostedPeerPending).map((p) => p.pendingId)).toEqual([pendingId]))
+ // The one already answered (the editor's) is not replayed.
+ expect(second.events(IPC.relayHostedPeerPending)).toHaveLength(1)
+
+ // The request ends: both owners hear it, the editor still hears nothing.
+ owner.req(8, IPC.relayHostedDeny, [pendingId])
+ await vi.waitFor(() => expect(second.events(IPC.relayHostedPendingClosed)).toContainEqual({ pendingId, reason: 'denied' }))
+ expect(owner.events(IPC.relayHostedPendingClosed)).toContainEqual({ pendingId, reason: 'denied' })
+ expect(editor.frames.some((f) => f.includes('relay:hosted:'))).toBe(false)
+ })
+
+ it('a pinned peer that never confirms does not hold the room’s only idle listener', async () => {
+ const w = world()
+ await ownerOnline(w)
+ const keys = genKeyPair()
+ await w.svc.addOwner(pub(keys), 'Stuck')
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ // Pinned (the host latches its own confirm), but this client's human never answers its dialog.
+ const stuck = w.join(keys, false, false)
+ // The handshake alone takes the listener out of the pool: a fresh idle one replaces it.
+ await vi.waitFor(() => expect(w.svc.status().scheduler).toMatchObject({ idle: 1, bridged: 2 }))
+ expect(stuck.isApproved()).toBe(false)
+ // …so the next teammate can still get in.
+ const { pendingId } = await pendingGuest(w)
+ expect(typeof pendingId).toBe('string')
+ })
+
+ it('the pending event carries the SAS the guest sees and the guest’s key', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ const g = w.join(keys)
+ await vi.waitFor(() => expect(owner.events(IPC.relayHostedPeerPending)).toHaveLength(1))
+ const ev = owner.events(IPC.relayHostedPeerPending)[0]
+ expect(ev.peerKeyB64).toBe(pub(keys))
+ expect(ev.sas).toBe(g.c.sas())
+ expect(typeof ev.pendingId).toBe('string')
+ })
+})
+
+describe('hosted service — approve and deny', () => {
+ it('deny tells the guest why, and the scheduler stops counting it as bridged (R20)', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const { g, pendingId } = await pendingGuest(w)
+ expect(w.svc.status().scheduler?.bridged).toBe(2)
+ owner.req(7, IPC.relayHostedDeny, [pendingId])
+ await vi.waitFor(() => expect(g.denied).toEqual(['denied']))
+ await vi.waitFor(() => expect(owner.res(7)).toMatchObject({ ok: true, result: true }))
+ expect(w.svc.status().pending).toHaveLength(0)
+ expect(w.svc.status().scheduler?.bridged).toBe(1)
+ expect(g.isApproved()).toBe(false)
+ })
+
+ it('a second approve of the same request answers false', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const { g, pendingId } = await pendingGuest(w)
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'viewer'])
+ owner.req(6, IPC.relayHostedApprove, [pendingId, 'owner'])
+ await vi.waitFor(() => expect(owner.res(6)).toBeDefined())
+ expect(owner.res(5)).toMatchObject({ ok: true, result: true })
+ expect(owner.res(6)).toMatchObject({ ok: true, result: false })
+ await vi.waitFor(() => expect(g.isApproved()).toBe(true))
+ await hostOpened(w, g.keys)
+ // The first decision stands.
+ expect(w.svc.status().peers.find((p) => p.role === 'viewer')).toBeTruthy()
+ expect(w.svc.status().peers.filter((p) => p.role === 'owner')).toHaveLength(1)
+ // And an approve after the request closed is false too.
+ owner.req(9, IPC.relayHostedApprove, [pendingId, 'editor'])
+ await vi.waitFor(() => expect(owner.res(9)).toMatchObject({ ok: true, result: false }))
+ })
+
+ it('an approve naming an unknown role or request is refused, and nothing opens', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const { g, pendingId } = await pendingGuest(w)
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'superuser'])
+ owner.req(6, IPC.relayHostedApprove, ['no-such-request', 'viewer'])
+ await vi.waitFor(() => expect(owner.res(6)).toBeDefined())
+ expect(owner.res(5)).toMatchObject({ ok: false })
+ expect(owner.res(6)).toMatchObject({ ok: true, result: false })
+ expect(g.isApproved()).toBe(false)
+ expect(w.svc.status().pending).toHaveLength(1)
+ })
+
+ it('the approval is pinned with the approver as addedBy, and the pin is what reconnects', async () => {
+ const fixed = 1_700_000_000_000
+ const w = world({ now: () => fixed })
+ const ownerKeys = genKeyPair()
+ const owner = await ownerOnline(w, ownerKeys)
+ const keys = genKeyPair()
+ const { pendingId } = await pendingGuest(w, keys)
+ expect(w.svc.status().pending[0].since).toBe(fixed)
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'commenter'])
+ await vi.waitFor(() => expect(w.svc.status().peers.some((p) => p.role === 'commenter')).toBe(true))
+ const doc = JSON.parse(fs.readFileSync(path.join(w.dataDir, 'relay', 'team.json'), 'utf-8'))
+ expect(doc.peers.find((p: { pubkeyB64: string }) => p.pubkeyB64 === pub(keys))).toEqual({
+ pubkeyB64: pub(keys), label: '', role: 'commenter', addedAt: new Date(fixed).toISOString(), addedBy: pub(ownerKeys)
+ })
+ })
+
+ it('hosted verbs cannot be CAST around the interceptor, and an unknown hosted verb is refused', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const { g, pendingId } = await pendingGuest(w)
+ owner.cast(IPC.relayHostedApprove, [pendingId, 'owner'])
+ owner.req(11, 'relay:hosted:bogus')
+ await vi.waitFor(() => expect(owner.res(11)).toMatchObject({ ok: false, error: { code: 'E_ROLE' } }))
+ expect(g.isApproved()).toBe(false)
+ expect(w.svc.status().pending).toHaveLength(1)
+ expect(w.casts).toEqual([])
+ expect(w.dispatched).toEqual([])
+ })
+})
+
+describe('hosted service — roles', () => {
+ it('relay:hosted:self answers the caller’s own role; invite-code is owner-only', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const viewer = await approvedGuest(w, owner, 'viewer', 5)
+ viewer.req(1, IPC.relayHostedSelf)
+ owner.req(2, IPC.relayHostedSelf)
+ viewer.req(3, IPC.relayHostedInviteCode)
+ owner.req(4, IPC.relayHostedInviteCode)
+ viewer.req(6, IPC.relayHostedDeny, ['whatever'])
+ await vi.waitFor(() => expect(viewer.res(6)).toBeDefined())
+ await vi.waitFor(() => expect(owner.res(4)).toBeDefined())
+ expect(viewer.res(1)).toMatchObject({ ok: true, result: { role: 'viewer', label: '', hostLabel: 'box' } })
+ expect(owner.res(2)).toMatchObject({ ok: true, result: { role: 'owner', label: 'Enes', hostLabel: 'box' } })
+ expect(viewer.res(3)).toMatchObject({ ok: false, error: { message: expect.stringMatching(/Only an owner/) } })
+ expect(viewer.res(6)).toMatchObject({ ok: false, error: { message: expect.stringMatching(/Only an owner/) } })
+ const code = decodeJoinCode(owner.res(4).result)
+ expect(code).toMatchObject({ v: 1, relayEndpoint: 'ws://127.0.0.1/r', hostPublicKeyB64: w.svc.info()!.hostPublicKeyB64, hostDeviceId: 'host-dev', label: 'box' })
+ })
+
+ it('the role is read on EVERY decision: a promotion applies to the next request', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const g = await approvedGuest(w, owner, 'viewer', 5, keys)
+ g.req(1, IPC.fsWrite, ['/srv/app/x', 'y'])
+ await vi.waitFor(() => expect(g.res(1)).toMatchObject({ ok: false, error: { code: 'E_ROLE' } }))
+ expect(w.dispatched).toEqual([])
+ await w.svc.addOwner(pub(keys), 'Promoted')
+ g.req(2, IPC.fsWrite, ['/srv/app/x', 'y'])
+ await vi.waitFor(() => expect(g.res(2)).toMatchObject({ ok: true }))
+ expect(w.dispatched).toEqual([IPC.fsWrite])
+ })
+
+ it('R19: a viewer’s subagent snapshot omits nodes outside the shared projects; an editor’s does not', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const viewer = await approvedGuest(w, owner, 'viewer', 5)
+ const editor = await approvedGuest(w, owner, 'editor', 6)
+ viewer.req(1, IPC.agentSubagentSnapshot)
+ editor.req(2, IPC.agentSubagentSnapshot)
+ await vi.waitFor(() => expect(viewer.res(1)).toBeDefined())
+ await vi.waitFor(() => expect(editor.res(2)).toBeDefined())
+ expect(viewer.res(1).result).toEqual([{ nodeId: 'n-shared', task: 'shared task' }])
+ expect(JSON.stringify(viewer.frames)).not.toContain('SECRET')
+ expect(editor.res(2).result.map((e: { nodeId: string }) => e.nodeId)).toEqual(['n-shared', 'n-other'])
+ })
+
+ it('workspace:load is narrowed for owners too', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ owner.req(1, IPC.workspaceLoad)
+ await vi.waitFor(() => expect(owner.res(1)).toBeDefined())
+ expect(owner.res(1).result).toEqual({ projects: [{ id: 'P' }], activeProjectId: 'P' })
+ })
+
+ it('status reports members and who is connected', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const g = await approvedGuest(w, owner, 'editor', 5)
+ expect(w.svc.status().peers).toEqual([
+ { label: 'Enes', role: 'owner', connected: true },
+ { label: '', role: 'editor', connected: true }
+ ])
+ g.c.close()
+ await vi.waitFor(() => expect(w.svc.status().peers[1].connected).toBe(false))
+ expect(w.svc.status().enabled).toBe(true)
+ })
+})
+
+describe('hosted service — removal', () => {
+ it('removal returns the scheduler’s bridged count (R20) and refuses the last owner', async () => {
+ const w = world()
+ const ownerKeys = genKeyPair()
+ const owner = await ownerOnline(w, ownerKeys)
+ const keys = genKeyPair()
+ const g = await approvedGuest(w, owner, 'editor', 5, keys)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.bridged).toBe(2))
+ expect(await w.svc.remove(pub(keys), false)).toBe('removed')
+ await vi.waitFor(() => expect(g.denied).toEqual(['removed']))
+ expect(w.svc.status().scheduler?.bridged).toBe(1)
+ expect(w.svc.status().peers).toEqual([{ label: 'Enes', role: 'owner', connected: true }])
+
+ expect(await w.svc.remove(pub(genKeyPair()), false)).toBe('unknown')
+ expect(await w.svc.remove(pub(ownerKeys), false)).toBe('last-owner')
+ expect(owner.denied).toEqual([])
+ expect(owner.c.isOpen()).toBe(true)
+ expect(await w.svc.remove(pub(ownerKeys), true)).toBe('removed')
+ await vi.waitFor(() => expect(owner.denied).toEqual(['removed']))
+ })
+
+ it('remove reads the team from disk even before start (never a false "unknown")', async () => {
+ const w = world()
+ const keys = genKeyPair()
+ await w.svc.init()
+ await w.svc.addOwner(pub(genKeyPair()), 'A')
+ await w.svc.addOwner(pub(keys), 'B')
+ // A fresh service over the same directory has loaded nothing yet.
+ const again = createHostedService({
+ dataDir: w.dataDir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'd', hostLabel: 'x',
+ attach: { attach: () => 1, detach: () => {}, dispatch: async (_i, r) => ({ t: 'res', id: r.id, ok: true, result: null }), cast: () => {} },
+ projectOfNode: () => undefined, projectCwd: () => undefined
+ })
+ expect(await again.remove(pub(keys), false)).toBe('removed')
+ })
+})
+
+describe('hosted service — a request whose session already ended', () => {
+ it('a guest that drops while pending is cleaned up at once: owners told, timer cleared, count returned', async () => {
+ const w = world({ recordTimers: true })
+ const owner = await ownerOnline(w)
+ const { g, pendingId } = await pendingGuest(w)
+ expect(w.svc.status().scheduler?.bridged).toBe(2)
+ g.c.close()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(0))
+ expect(w.svc.status().scheduler?.bridged).toBe(1)
+ await vi.waitFor(() => expect(owner.events(IPC.relayHostedPendingClosed)).toContainEqual({ pendingId, reason: 'gone' }))
+ const expiry = w.armed.filter((a) => a.ms === PENDING_TTL_MS)
+ expect(expiry).toHaveLength(1)
+ expect(expiry[0].cleared).toBe(true)
+ })
+
+ it('expiry tolerates a session closed behind the service’s back: no throw, no second end, entry removed', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+ try {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const { g, pendingId } = await pendingGuest(w, keys)
+ // Closed WITHOUT a reason and without the service: the core fires no onClose for this.
+ killRelayHostsByPeerKey(pub(keys))
+ expect(g.closedCount()).toBe(1)
+ expect(w.svc.status().pending).toHaveLength(1)
+ expect(w.svc.status().scheduler?.bridged).toBe(2)
+ await vi.advanceTimersByTimeAsync(PENDING_TTL_MS)
+ expect(w.svc.status().pending).toHaveLength(0)
+ expect(w.svc.status().scheduler?.bridged).toBe(1)
+ expect(g.denied).toEqual([]) // it was already gone: nothing more was sent
+ expect(g.closedCount()).toBe(1)
+ await vi.waitFor(() => expect(owner.events(IPC.relayHostedPendingClosed)).toContainEqual({ pendingId, reason: 'expired' }))
+ w.svc.stop()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
+
+describe('hosted service — lifecycle', () => {
+ it('start before init is no-team; init creates once and reports a second init as not created', async () => {
+ const w = world()
+ expect(await w.svc.start()).toBe('no-team')
+ expect(w.svc.info()).toBeNull()
+ expect(await w.svc.init()).toEqual({ created: true })
+ expect(await w.svc.init()).toEqual({ created: false })
+ expect(fs.existsSync(path.join(w.dataDir, 'relay', 'team.json'))).toBe(true)
+ })
+
+ it('two inits racing: one creates the key, the other is told it was not created (E_HOST_KEY_EXISTS)', async () => {
+ const w = world()
+ const results = await Promise.all([w.svc.init(), w.svc.init(), w.svc.init()])
+ expect(results.filter((r) => r.created)).toHaveLength(1)
+ expect(results.filter((r) => !r.created)).toHaveLength(2)
+ })
+
+ it('an unreadable host key is reported and never replaced; init refuses it too', async () => {
+ const w = world()
+ await w.svc.init()
+ const file = path.join(w.dataDir, 'relay', 'host-key.json')
+ fs.writeFileSync(file, 'not json')
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ expect(await w.svc.start()).toBe('host-key-unreadable')
+ await expect(w.svc.init()).rejects.toMatchObject({ code: 'E_HOST_KEY_UNREADABLE' })
+ } finally {
+ err.mockRestore()
+ }
+ expect(fs.readFileSync(file, 'utf-8')).toBe('not json')
+ expect(w.svc.status().enabled).toBe(false)
+ })
+
+ it('R2: start is idempotent — a running or concurrently starting service never gets a second scheduler', async () => {
+ const w = world()
+ await w.svc.init()
+ const [a, b] = await Promise.all([w.svc.start(), w.svc.start()])
+ expect([a, b]).toEqual(['started', 'started'])
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ expect(await w.svc.start()).toBe('started')
+ await new Promise((r) => setTimeout(r, 30))
+ expect(w.mints()).toBe(1)
+ expect(w.svc.status().scheduler?.idle).toBe(1)
+ })
+
+ it('stop cuts every session and pending request; start brings hosting back', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const { g } = await pendingGuest(w)
+ w.svc.stop()
+ expect(w.svc.status()).toMatchObject({ enabled: false, scheduler: null, pending: [] })
+ await vi.waitFor(() => expect(owner.closedCount()).toBe(1))
+ await vi.waitFor(() => expect(g.closedCount()).toBe(1))
+ expect(w.svc.status().peers.every((p) => !p.connected)).toBe(true)
+ expect(await w.svc.start()).toBe('started')
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ })
+
+ it('a stop that lands while start is still loading wins', async () => {
+ const w = world()
+ await w.svc.init()
+ const starting = w.svc.start()
+ w.svc.stop()
+ expect(await starting).toBe('stopped')
+ expect(w.svc.status().enabled).toBe(false)
+ expect(w.mints()).toBe(0)
+ })
+
+ it('rotateKey replaces the host address and keeps hosting', async () => {
+ const w = world()
+ await ownerOnline(w)
+ const before = w.svc.info()!.hostPublicKeyB64
+ await w.svc.rotateKey()
+ expect(w.svc.info()!.hostPublicKeyB64).not.toBe(before)
+ expect(w.svc.status().enabled).toBe(true)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ expect(decodeJoinCode(w.svc.joinCode()!)!.hostPublicKeyB64).toBe(w.svc.info()!.hostPublicKeyB64)
+ })
+
+ it('R22: the scheduler runs on the monotonic clock, not the wall clock', async () => {
+ const mono = vi.fn(() => performance.now())
+ const w = world({ monotonicNow: mono, now: () => 42 })
+ await w.svc.init()
+ expect(await w.svc.start()).toBe('started')
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ // Only the scheduler reads the monotonic clock; the wall clock (42) is for display and the mint.
+ expect(mono).toHaveBeenCalled()
+ expect(w.svc.status().scheduler?.mintsLastHour).toBe(1)
+ })
+
+ it('every hosted channel lives under the one prefix the access hook refuses outside the interceptor', () => {
+ const hosted = Object.entries(IPC).filter(([k]) => k.startsWith('relayHosted')).map(([, v]) => v)
+ expect(hosted).toHaveLength(6)
+ for (const ch of hosted) expect(ch).toMatch(/^relay:hosted:/)
+ })
+})
diff --git a/src/core/relay/hosted-service.ts b/src/core/relay/hosted-service.ts
new file mode 100644
index 000000000..86cf3bfb2
--- /dev/null
+++ b/src/core/relay/hosted-service.ts
@@ -0,0 +1,502 @@
+// Hosted team relay: the Server Edition side of docs/hosted-team-relay.md.
+// Composes the host key, team store, standing-listener scheduler and access policy around the core
+// relay host. All relay-peer traffic crosses relay-host.ts's hooks; hosted RPCs (relay:hosted:*)
+// are INTERCEPTED there and never registered on the platform, so a Server Edition browser client
+// (whose gate is the server password, not a team role) cannot call them.
+//
+// Four rules the file rests on:
+// - The ROLE is read from the team store on every decision (access, sink filter, narrowing,
+// interceptors) and never cached on a session, so a removal or a promotion applies to the very
+// next message. Removal also cuts the live session (`killRelayHostsByPeerKey`).
+// - An interceptor bypasses `access` and the scope jails, so each one checks the CALLER's own
+// session key against the team store: `relay:hosted:self` is open to any approved peer, approve /
+// deny / invite-code to owners only.
+// - Pending requests are told to connected OWNERS only (never a broadcast: a viewer must not learn
+// who is knocking), and an owner who connects later is told the ones still open.
+// - The scheduler hears about EVERY session end. The core fires `onClose` only for ends the shell
+// did not ask for; every end this service causes (deny, expiry, removal, a listener the
+// scheduler closes) runs the same `ended` bookkeeping, at most once per session.
+import { realpathSync } from 'node:fs'
+import path from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { IPC } from '../../shared/ipc'
+import { connectRelayHost, killRelayHostsByPeerKey, type PeerAttach, type RelayHostSession } from './relay-host'
+import type { RelayTransport } from './relay-socket'
+import type { TrustDeniedReason } from './relay-trust'
+import { createHostKey, loadHostKey, rotateHostKey, hostAddress, HostKeyUnreadableError } from './host-key'
+import { TeamStore, peerFor, upsertPeer, removePeer, setShared, TEAM_ROLES, type TeamRole } from './team-store'
+import { decideAccess, wrapSinkForRole, narrowResponseForRole, type AccessContext } from './access-policy'
+import { mintHostToken } from './host-token'
+import { createHostedScheduler, type Listener, type SchedulerStatus } from './hosted-scheduler'
+import { encodeJoinCode } from './join-code'
+import type { KeyPair } from './e2ee'
+import type { UiSink } from '../ui-sink-registry'
+
+/** An unanswered join request is refused after ten minutes. */
+export const PENDING_TTL_MS = 600_000
+
+/** Every hosted channel starts with this. Anything under it that the interceptor does not answer
+ * (a CAST of a hosted verb, an unknown hosted verb) is refused by the access hook. */
+const HOSTED_PREFIX = 'relay:hosted:'
+
+/** The join code's own label cap (join-code.ts): a longer host name would make an undecodable code. */
+const JOIN_LABEL_MAX = 60
+
+export interface HostedPending { pendingId: string; sas: string; peerKeyB64: string; since: number }
+/** Why a pending request stopped being pending, as told to owners on `relay:hosted:pending-closed`. */
+export type PendingClosedReason = 'approved' | 'denied' | 'expired' | 'gone'
+/** `stopped`: a `stop()` landed after this `start()` was called and before it finished; it wins. */
+export type HostedStartResult = 'started' | 'no-team' | 'host-key-unreadable' | 'stopped'
+
+export interface HostedServiceDeps {
+ dataDir: string
+ apiBase: string
+ relayUrl: string
+ deviceId: string
+ hostLabel: string
+ attach: PeerAttach
+ projectOfNode(nodeId: string): string | undefined
+ projectCwd(projectId: string): string | undefined
+ /** TEST ONLY: an in-process transport per listener. Production opens a real WebSocket. */
+ transport?: () => RelayTransport
+ /** TEST ONLY: the host-token mint's fetch. */
+ fetch?: typeof fetch
+ /** Wall clock (ms): display only (`since`, `addedAt`) and the mint's clock-skew fallback. */
+ now?: () => number
+ /** MONOTONIC clock (ms) for the scheduler, whose hourly mint budget must not stretch or empty when
+ * the wall clock steps. Defaults to `performance.now`. */
+ monotonicNow?: () => number
+ setTimeout?(fn: () => void, ms: number): unknown
+ clearTimeout?(handle: unknown): void
+}
+
+export interface HostedInfo { relayEndpoint: string; hostId: string; hostPublicKeyB64: string; hostDeviceId: string; label: string }
+
+export interface HostedStatus {
+ enabled: boolean
+ scheduler: SchedulerStatus | null
+ peers: Array<{ label: string; role: TeamRole; connected: boolean }>
+ pending: HostedPending[]
+}
+
+export interface HostedService {
+ /** Create the host key (once) and the team file. `created` is false when a key already existed —
+ * including when a concurrent init won the race. An unreadable key throws; it is never replaced. */
+ init(): Promise<{ created: boolean }>
+ /** Idempotent: a running (or concurrently starting) service answers 'started' with no second scheduler. */
+ start(): Promise<HostedStartResult>
+ /** Stop hosting: every listener, session and pending request ends. A start still loading loses. */
+ stop(): void
+ addOwner(pubkeyB64: string, label: string): Promise<void>
+ remove(pubkeyB64: string, force: boolean): Promise<'removed' | 'last-owner' | 'unknown'>
+ share(projectId: string, on: boolean): Promise<void>
+ info(): HostedInfo | null
+ joinCode(): string | null
+ status(): HostedStatus
+ /** Replace the host key and keep hosting. Every teammate needs a new join code. */
+ rotateKey(): Promise<void>
+}
+
+/** One relay listener and, once a peer bridges, its session. */
+interface Conn {
+ session: RelayHostSession | null
+ /** The scheduler's events for this listener. */
+ ev: { onBridged(): void; onClose(): void }
+ /** The peer's role-filtered sink, set when the core opens the session. */
+ sink: UiSink | null
+ /** Set while this session is a pending join request. */
+ pendingId: string | null
+ /** The owner decision awaiting the peer's own confirm; what `pins.record` writes. */
+ approval: { role: TeamRole; by: string } | null
+ open: boolean
+ ended: boolean
+}
+
+interface PendingEntry { info: HostedPending; conn: Conn; timer: unknown }
+
+const OWNER_ONLY: Readonly<Record<string, string>> = Object.freeze({
+ [IPC.relayHostedApprove]: 'Only an owner can approve.',
+ [IPC.relayHostedDeny]: 'Only an owner can deny.',
+ [IPC.relayHostedInviteCode]: 'Only an owner can invite.'
+})
+
+const errorMessage = (err: unknown): string => (err instanceof Error ? err.message : String(err))
+
+const realpath = (p: string): string | null => {
+ try {
+ return realpathSync(p)
+ } catch {
+ return null
+ }
+}
+
+const idOf = (p: unknown): unknown =>
+ p !== null && typeof p === 'object' ? (p as Record<string, unknown>).id : undefined
+
+/** `workspace:load` holds every project on this core; a hosted peer sees the shared ones only. Fails
+ * closed: a result that does not look like a workspace keeps no projects. */
+function narrowWorkspace(result: unknown, shared: ReadonlySet<string>): unknown {
+ if (result === null || typeof result !== 'object' || Array.isArray(result)) return result
+ const ws = result as Record<string, unknown>
+ const projects = Array.isArray(ws.projects)
+ ? ws.projects.filter((p) => { const id = idOf(p); return typeof id === 'string' && shared.has(id) })
+ : []
+ const active = projects.some((p) => idOf(p) === ws.activeProjectId) ? ws.activeProjectId : (idOf(projects[0]) ?? '')
+ return { ...ws, projects, activeProjectId: active }
+}
+
+export function createHostedService(deps: HostedServiceDeps): HostedService {
+ const dir = path.join(deps.dataDir, 'relay')
+ const team = new TeamStore(dir)
+ // Looked up at call time (not captured), so a test's fake timers and fake Date apply.
+ const wallNow = (): number => (deps.now ? deps.now() : Date.now())
+ const monoNow = (): number => (deps.monotonicNow ? deps.monotonicNow() : performance.now())
+ const setT = (fn: () => void, ms: number): unknown => (deps.setTimeout ? deps.setTimeout(fn, ms) : setTimeout(fn, ms))
+ const clearT = (h: unknown): void => {
+ if (h === null || h === undefined) return
+ if (deps.clearTimeout) deps.clearTimeout(h)
+ else clearTimeout(h as ReturnType<typeof setTimeout>)
+ }
+
+ let keys: KeyPair | null = null
+ let scheduler: ReturnType<typeof createHostedScheduler> | null = null
+ /** Bumped by every stop. A start that began in an older epoch never creates a scheduler. */
+ let epoch = 0
+ /** start / rotateKey run one at a time, so two admin commands can never race a scheduler into
+ * existence (R2) or start one with the key a rotation is replacing. */
+ let lifecycle: Promise<unknown> = Promise.resolve()
+ const conns = new Set<Conn>() // every listener whose session has not ended
+ const pending = new Map<string, PendingEntry>()
+
+ const onLifecycle = <T>(op: () => Promise<T>): Promise<T> => {
+ const run = lifecycle.then(op)
+ lifecycle = run.catch(() => {})
+ return run
+ }
+
+ const keyOf = (c: Conn): string | null => c.session?.peerKeyB64() ?? null
+ /** The team's word on this session's key, NOW. Never cached (see the header). */
+ const roleOf = (c: Conn): TeamRole | undefined => {
+ const k = keyOf(c)
+ return k ? peerFor(team.current(), k)?.role : undefined
+ }
+ const ctxFor = (c: Conn): AccessContext => {
+ const shared = new Set(team.current().sharedProjects)
+ return {
+ // An open session with no team entry can only be one whose pin write failed (or one a removal
+ // is about to cut): it gets the lowest role, never a guess upward.
+ role: roleOf(c) ?? 'viewer',
+ sharedProjects: shared,
+ projectOfNode: (nodeId) => deps.projectOfNode(nodeId),
+ projectCwds: () =>
+ [...shared].map((p) => deps.projectCwd(p)).filter((cwd): cwd is string => typeof cwd === 'string' && cwd.length > 0),
+ realpath
+ }
+ }
+
+ const send = (c: Conn, channel: string, payload: unknown): void => {
+ if (!c.sink) return
+ try {
+ c.sink.sendText(JSON.stringify({ t: 'ev', channel, args: [payload] }))
+ } catch {
+ // Its socket is gone; the session's own close is already on its way.
+ }
+ }
+ /** Connected owners ONLY, judged per send. Never a broadcast. */
+ const tellOwners = (channel: string, payload: unknown): void => {
+ for (const c of conns) if (c.open && roleOf(c) === 'owner') send(c, channel, payload)
+ }
+
+ const closePending = (id: string, reason: PendingClosedReason): void => {
+ const p = pending.get(id)
+ if (!p) return
+ pending.delete(id)
+ clearT(p.timer)
+ if (p.conn.pendingId === id) p.conn.pendingId = null
+ tellOwners(IPC.relayHostedPendingClosed, { pendingId: id, reason })
+ }
+
+ /** Everything owed to a session that ended, however it ended: drop it, close its request, and tell
+ * the scheduler (which no longer counts it as bridged). At most once per session. */
+ const ended = (c: Conn, reason: PendingClosedReason): void => {
+ if (c.ended) return
+ c.ended = true
+ c.open = false
+ conns.delete(c)
+ if (c.pendingId) closePending(c.pendingId, reason)
+ try {
+ c.ev.onClose()
+ } catch {
+ // The scheduler never throws here; a throw must not undo the bookkeeping above.
+ }
+ }
+
+ /** End a session on this service's own decision. `deny` is a no-op on a session that already
+ * closed (a drop, a key swap, a kill from elsewhere), so this tolerates every such state. */
+ const endSession = (c: Conn, why: TrustDeniedReason, reason: PendingClosedReason): void => {
+ c.session?.deny(why)
+ ended(c, reason)
+ }
+
+ const expire = (c: Conn, pendingId: string): void => {
+ // Answered or gone already: its timer was cleared, but a clear can lose a race with the fire.
+ if (c.pendingId !== pendingId) return
+ endSession(c, 'expired', 'expired')
+ }
+
+ /** Pin an OWNER-approved peer into the team. The trust gate calls this only after both ends
+ * confirmed, with the key bound into the gate. An auto-approved peer is already a member. */
+ const recordApproval = async (c: Conn, peerKeyB64: string): Promise<void> => {
+ const a = c.approval
+ if (!a) return
+ try {
+ await team.update((d) =>
+ upsertPeer(d, { pubkeyB64: peerKeyB64, label: '', role: a.role, addedAt: new Date(wallNow()).toISOString(), addedBy: a.by })
+ )
+ } catch (err) {
+ // The gate still opens (consent for THIS session is mutual); the next connect asks again.
+ console.warn(`[hosted-team] could not record an approved teammate: ${errorMessage(err)}`)
+ }
+ }
+
+ const self = (c: Conn): { role: TeamRole; label: string; hostLabel: string } => {
+ const k = keyOf(c)
+ const p = k ? peerFor(team.current(), k) : undefined
+ return { role: p?.role ?? 'viewer', label: p?.label ?? '', hostLabel: deps.hostLabel }
+ }
+
+ /** approve / deny / invite-code. Owner-only, judged from the CALLER's session key. Synchronous on
+ * purpose: two approves of one request are decided in arrival order, and the second answers false. */
+ const ownerVerb = (c: Conn, method: string, args: unknown[]): unknown => {
+ if (roleOf(c) !== 'owner') throw new Error(OWNER_ONLY[method])
+ if (method === IPC.relayHostedInviteCode) return api.joinCode()
+ const [pendingId, role] = args
+ const p = typeof pendingId === 'string' ? pending.get(pendingId) : undefined
+ if (method === IPC.relayHostedDeny) {
+ if (!p) return false
+ endSession(p.conn, 'denied', 'denied')
+ return true
+ }
+ if (typeof role !== 'string' || !(TEAM_ROLES as readonly string[]).includes(role)) throw new Error('Unknown role.')
+ if (!p || p.conn.approval) return false // gone, or another owner got there first
+ const by = keyOf(c)
+ if (!by) throw new Error('Only an owner can approve.')
+ p.conn.approval = { role: role as TeamRole, by }
+ // This end's confirm. The request stays pending until the peer's own confirm opens it.
+ p.conn.session?.confirm()
+ return true
+ }
+
+ function openListener(hostKeys: KeyPair, token: string, ev: Conn['ev']): Listener {
+ const c: Conn = { session: null, ev, sink: null, pendingId: null, approval: null, open: false, ended: false }
+ const bridged = (): void => {
+ try {
+ ev.onBridged()
+ } catch {
+ // Never let the scheduler's bookkeeping break a handshake.
+ }
+ }
+ conns.add(c)
+ try {
+ c.session = connectRelayHost({
+ url: deps.relayUrl,
+ token,
+ ourKeys: hostKeys,
+ attach: deps.attach,
+ transport: deps.transport ? deps.transport() : undefined,
+ // Asked once, at the end of the handshake, on BOTH paths (pinned or not) — which makes it the
+ // moment this listener stops being available to anyone else: a pinned peer that never
+ // confirms must not hold the room's only idle listener until its refresh.
+ autoApprove: (peerKeyB64) => {
+ bridged()
+ return peerFor(team.current(), peerKeyB64) !== undefined
+ },
+ pins: { record: (state) => recordApproval(c, state.peerKeyB64) },
+ hooks: {
+ interceptReq: (_s, method, args) => {
+ if (method === IPC.relayHostedSelf) return Promise.resolve(self(c))
+ if (!Object.hasOwn(OWNER_ONLY, method)) return null
+ try {
+ return Promise.resolve(ownerVerb(c, method, args))
+ } catch (err) {
+ return Promise.reject(err)
+ }
+ },
+ access: (_s, kind, method, args) => {
+ // Intercepted requests never get here, so a hosted verb that did is a cast or unknown.
+ if (typeof method === 'string' && method.startsWith(HOSTED_PREFIX)) {
+ return { allow: false, message: 'That is answered by the hosted team service only.' }
+ }
+ return decideAccess(kind, method, args, ctxFor(c))
+ },
+ wrapSink: (_s, sink) => {
+ const wrapped = wrapSinkForRole(sink, () => ctxFor(c))
+ c.sink = wrapped
+ return wrapped
+ },
+ // RPC responses bypass the outbound sink filter, so the role narrowing runs here too — after
+ // the shared-project narrowing of the workspace (the subagent snapshot is the case today).
+ narrowResponse: (_s, method, result) => {
+ const ctx = ctxFor(c)
+ const scoped = method === IPC.workspaceLoad ? narrowWorkspace(result, ctx.sharedProjects) : result
+ return narrowResponseForRole(method, scoped, ctx)
+ }
+ },
+ onPeerPending: (s) => {
+ bridged()
+ if (c.ended) return
+ const info: HostedPending = { pendingId: randomUUID(), sas: s.sas() ?? '', peerKeyB64: s.peerKeyB64() ?? '', since: wallNow() }
+ const timer = setT(() => expire(c, info.pendingId), PENDING_TTL_MS)
+ pending.set(info.pendingId, { info, conn: c, timer })
+ c.pendingId = info.pendingId
+ tellOwners(IPC.relayHostedPeerPending, info)
+ },
+ onOpen: () => {
+ bridged()
+ if (c.ended) return
+ c.open = true
+ if (c.pendingId) closePending(c.pendingId, 'approved')
+ if (roleOf(c) === undefined) {
+ console.warn('[hosted-team] a session opened with no team entry (its pin was not recorded); it is served as a viewer')
+ }
+ // An owner who was offline when a request arrived is told the ones still open.
+ if (roleOf(c) === 'owner') for (const p of pending.values()) send(c, IPC.relayHostedPeerPending, p.info)
+ },
+ onClose: () => ended(c, 'gone')
+ })
+ } catch (err) {
+ conns.delete(c)
+ throw err
+ }
+ return {
+ bridged: false,
+ close: () => {
+ c.session?.close()
+ ended(c, 'gone')
+ }
+ }
+ }
+
+ const stopNow = (): void => {
+ epoch++
+ const s = scheduler
+ scheduler = null
+ s?.stop() // closes every listener it holds, bridged ones included
+ for (const c of [...conns]) {
+ c.session?.close()
+ ended(c, 'gone')
+ }
+ for (const id of [...pending.keys()]) closePending(id, 'gone')
+ }
+
+ async function startNow(my: number): Promise<HostedStartResult> {
+ if (my !== epoch) return 'stopped'
+ if (scheduler) return 'started'
+ if (!team.exists()) return 'no-team'
+ let k: KeyPair | null
+ try {
+ k = await loadHostKey(dir)
+ } catch (err) {
+ if (err instanceof HostKeyUnreadableError) {
+ console.error('[hosted-team]', err.message)
+ return 'host-key-unreadable'
+ }
+ throw err
+ }
+ if (!k) return 'no-team'
+ await team.load()
+ if (my !== epoch) return 'stopped'
+ keys = k
+ const hostKeys = k
+ const addr = hostAddress(k)
+ const s = createHostedScheduler(
+ {
+ mint: () =>
+ mintHostToken({ apiBase: deps.apiBase, deviceId: deps.deviceId, hostPublicKeyB64: addr.hostPublicKeyB64, fetch: deps.fetch, now: wallNow }),
+ open: (token, ev) => openListener(hostKeys, token, ev),
+ setTimeout: (fn, ms) => setT(fn, ms),
+ clearTimeout: (h) => clearT(h)
+ },
+ monoNow
+ )
+ scheduler = s
+ s.start()
+ return 'started'
+ }
+
+ const api: HostedService = {
+ async init() {
+ let created = false
+ try {
+ await createHostKey(dir)
+ created = true
+ } catch (err) {
+ // A key already there (a second init, or one that won a concurrent race) is not an error.
+ if ((err as { code?: unknown } | null)?.code !== 'E_HOST_KEY_EXISTS') throw err
+ }
+ if (!team.exists()) await team.update((d) => d)
+ return { created }
+ },
+ start() {
+ const my = epoch
+ return onLifecycle(() => startNow(my))
+ },
+ stop() {
+ stopNow()
+ },
+ async addOwner(pubkeyB64, label) {
+ await team.update((d) =>
+ upsertPeer(d, { pubkeyB64, label, role: 'owner', addedAt: new Date(wallNow()).toISOString(), addedBy: 'cli' })
+ )
+ },
+ async remove(pubkeyB64, force) {
+ let known = false
+ // Decided inside the store's chain, so it reads the file even before start() loaded it.
+ const r = await team.update((d) => {
+ known = peerFor(d, pubkeyB64) !== undefined
+ // Nothing to remove: 'last-owner' is the store's "write nothing"; `known` says which it was.
+ return known ? removePeer(d, pubkeyB64, force) : 'last-owner'
+ })
+ if (!known) return 'unknown'
+ if (r === 'last-owner') return 'last-owner'
+ killRelayHostsByPeerKey(pubkeyB64, 'removed')
+ // The kill ends them without the core's onClose; the bookkeeping is ours.
+ for (const c of [...conns]) if (keyOf(c) === pubkeyB64) ended(c, 'gone')
+ return 'removed'
+ },
+ async share(projectId, on) {
+ await team.update((d) => setShared(d, projectId, on))
+ },
+ info() {
+ if (!keys) return null
+ const a = hostAddress(keys)
+ return { relayEndpoint: deps.relayUrl, hostId: a.hostId, hostPublicKeyB64: a.hostPublicKeyB64, hostDeviceId: deps.deviceId, label: deps.hostLabel }
+ },
+ joinCode() {
+ const i = api.info()
+ return i ? encodeJoinCode({ v: 1, ...i, label: i.label.slice(0, JOIN_LABEL_MAX) }) : null
+ },
+ status() {
+ const connected = new Set<string>()
+ for (const c of conns) {
+ const k = c.open ? keyOf(c) : null
+ if (k) connected.add(k)
+ }
+ return {
+ enabled: scheduler !== null,
+ scheduler: scheduler?.status() ?? null,
+ peers: team.current().peers.map((p) => ({ label: p.label, role: p.role, connected: connected.has(p.pubkeyB64) })),
+ pending: [...pending.values()].map((p) => ({ ...p.info }))
+ }
+ },
+ rotateKey() {
+ return onLifecycle(async () => {
+ stopNow()
+ const my = epoch
+ keys = await rotateHostKey(dir)
+ await startNow(my)
+ })
+ }
+ }
+ return api
+}
diff --git a/src/core/relay/join-code.test.ts b/src/core/relay/join-code.test.ts
new file mode 100644
index 000000000..362704d4a
--- /dev/null
+++ b/src/core/relay/join-code.test.ts
@@ -0,0 +1,29 @@
+// src/core/relay/join-code.test.ts
+import { describe, it, expect } from 'vitest'
+import { encodeJoinCode, decodeJoinCode, isJoinCode } from './join-code'
+import { genKeyPair, publicKeyToB64 } from './e2ee'
+import { hostIdFromPublicKeyB64 } from './relay-id'
+
+const pub = publicKeyToB64(genKeyPair().publicKey)
+const good = { v: 1 as const, relayEndpoint: 'wss://relay.nodeterm.dev', hostId: hostIdFromPublicKeyB64(pub), hostPublicKeyB64: pub, hostDeviceId: 'd', label: 'box' }
+
+describe('join code', () => {
+ it('round-trips and is recognized', () => {
+ const s = encodeJoinCode(good)
+ expect(s.startsWith('nodeterm://join?code=')).toBe(true)
+ expect(isJoinCode(s)).toBe(true)
+ expect(isJoinCode('nodeterm://pair?code=abc')).toBe(false)
+ expect(decodeJoinCode(s)).toEqual(good)
+ })
+ it('refuses a hostId that does not match the key (a tampered code)', () => {
+ expect(decodeJoinCode(encodeJoinCode({ ...good, hostId: 'x'.repeat(22) }))).toBeNull()
+ })
+ it('refuses plaintext relays except loopback', () => {
+ expect(decodeJoinCode(encodeJoinCode({ ...good, relayEndpoint: 'ws://evil.example' }))).toBeNull()
+ expect(decodeJoinCode(encodeJoinCode({ ...good, relayEndpoint: 'ws://127.0.0.1:8080' }))).not.toBeNull()
+ })
+ it('never throws on junk', () => {
+ expect(decodeJoinCode('nodeterm://join?code=%%%')).toBeNull()
+ expect(decodeJoinCode('')).toBeNull()
+ })
+})
diff --git a/src/core/relay/join-code.ts b/src/core/relay/join-code.ts
new file mode 100644
index 000000000..72eaa57ea
--- /dev/null
+++ b/src/core/relay/join-code.ts
@@ -0,0 +1,40 @@
+// `nodeterm://join?code=<base64url(JSON)>` — the address of a hosted team. PUBLIC material only:
+// a leaked code lets someone ASK to join, never get in (an owner must approve the first connect).
+// The host key inside is what authenticates the host to the joiner, and the hostId must derive
+// from it, so a code cannot point a teammate at a different room than the key it carries.
+import { hostIdFromPublicKeyB64 } from './relay-id'
+
+export interface JoinCode { v: 1; relayEndpoint: string; hostId: string; hostPublicKeyB64: string; hostDeviceId: string; label: string }
+const PREFIX = 'nodeterm://join?code='
+
+function allowedEndpoint(endpoint: string): boolean {
+ let u: URL
+ try { u = new URL(endpoint) } catch { return false }
+ if (u.protocol === 'wss:') return true
+ return u.protocol === 'ws:' && ['127.0.0.1', 'localhost', '::1', '[::1]'].includes(u.hostname)
+}
+
+export function encodeJoinCode(c: JoinCode): string {
+ return PREFIX + Buffer.from(JSON.stringify(c), 'utf-8').toString('base64url')
+}
+
+export function isJoinCode(s: string): boolean {
+ return s.trim().startsWith(PREFIX)
+}
+
+export function decodeJoinCode(s: string): JoinCode | null {
+ const t = s.trim()
+ if (!t.startsWith(PREFIX)) return null
+ try {
+ const o = JSON.parse(Buffer.from(t.slice(PREFIX.length), 'base64url').toString('utf-8')) as Record<string, unknown>
+ const str = (k: string, max: number) => typeof o[k] === 'string' && (o[k] as string).length > 0 && (o[k] as string).length <= max
+ if (o.v !== 1 || !str('relayEndpoint', 512) || !str('hostId', 64) || !str('hostPublicKeyB64', 64) || !str('hostDeviceId', 128)) return null
+ if (typeof o.label !== 'string' || o.label.length > 60) return null
+ if (!allowedEndpoint(o.relayEndpoint as string)) return null
+ // May throw on a malformed key; inside the try, so junk decodes to null.
+ if (hostIdFromPublicKeyB64(o.hostPublicKeyB64 as string) !== o.hostId) return null
+ return { v: 1, relayEndpoint: o.relayEndpoint as string, hostId: o.hostId as string, hostPublicKeyB64: o.hostPublicKeyB64 as string, hostDeviceId: o.hostDeviceId as string, label: o.label }
+ } catch {
+ return null
+ }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 636c5d2be..6a3617f6a 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -594,6 +594,19 @@ export const IPC = {
relayClientApproved: (connectionId: string) => `relay:client:approved:${connectionId}`,
relayClientFrame: (connectionId: string) => `relay:client:frame:${connectionId}`,
relayClientClosed: (connectionId: string) => `relay:client:closed:${connectionId}`,
+ // HOSTED team relay (Server Edition, src/core/relay/hosted-service.ts). These ride the relay
+ // tunnel only: the core relay host INTERCEPTS them per session and they are never registered on
+ // the platform, so a browser client (gated by the server password, not a team role) cannot reach
+ // them. `relayHostedPeerPending` / `relayHostedPendingClosed` are events sent to connected OWNERS
+ // only; `relayHostedApprove` (pendingId, role), `relayHostedDeny` (pendingId) and
+ // `relayHostedInviteCode` () are owner-only requests; `relayHostedSelf` () is open to any approved
+ // peer and answers its own role.
+ relayHostedPeerPending: 'relay:hosted:peer-pending',
+ relayHostedPendingClosed: 'relay:hosted:pending-closed',
+ relayHostedApprove: 'relay:hosted:approve',
+ relayHostedDeny: 'relay:hosted:deny',
+ relayHostedInviteCode: 'relay:hosted:invite-code',
+ relayHostedSelf: 'relay:hosted:self',
handoffBuild: 'handoff:build',
// Phone pairing (nodeterm iOS "scan a QR" flow): renderer starts/stops the one-shot LAN
// listener; main pushes the completion result back over `pairing:done`. The per-device