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.

fix(relay): hosted service — pending pull, refusal beats a pin in flight, no-entry sessions served nothing

review7625542c36ef
diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.ts
index 85bc1acf2..39414f3b8 100644
--- a/src/core/relay/hosted-service.test.ts
+++ b/src/core/relay/hosted-service.test.ts
@@ -4,31 +4,67 @@ 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 { createHostedService, PENDING_TTL_MS, PENDING_MAX, type HostedService, type HostedServiceDeps } from './hosted-service'
import { transportPair } from './transport-pair'
-import { connectRelayClient } from './relay-client'
+import { connectRelayClient, type RelayClientSession } from './relay-client'
import { killRelayHostsByPeerKey, type PeerAttach } from './relay-host'
import { connectRelay } from './relay-socket'
+import { loadHostKey } from './host-key'
import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
import { decodeJoinCode } from './join-code'
import { IPC } from '../../shared/ipc'
import type { RelayTransport } from './relay-socket'
+import type { UiSink } from '../ui-sink-registry'
+
+// The team store's disk write, holdable and failable per test: a pin write that is still in flight,
+// or one that fails, is what several of the rules below are about. Pass-through unless armed.
+const disk = vi.hoisted(() => ({ holdTeamWrite: false, failTeamWrite: false, held: [] as Array<() => void>, done: 0 }))
+vi.mock('../fs-atomic', async (importOriginal) => {
+ const real = await importOriginal<typeof import('../fs-atomic')>()
+ return {
+ ...real,
+ writeFileAtomic: async (file: string, data: string, opts?: { mode?: number }) => {
+ if (String(file).endsWith('team.json')) {
+ if (disk.failTeamWrite) {
+ disk.failTeamWrite = false
+ throw new Error('disk full')
+ }
+ if (disk.holdTeamWrite) {
+ disk.holdTeamWrite = false
+ await new Promise<void>((r) => disk.held.push(r))
+ }
+ }
+ await real.writeFileAtomic(file, data, opts)
+ if (String(file).endsWith('team.json')) disk.done++
+ }
+ }
+})
+const releaseHeldWrites = () => { for (const r of disk.held.splice(0)) r() }
const pub = (k: KeyPair) => publicKeyToB64(k.publicKey)
+const settle = () => new Promise((r) => setTimeout(r, 25))
-interface Armed { ms: number; h: unknown; cleared: boolean }
+interface Armed { ms: number; h: unknown; fn: () => void; cleared: boolean }
const live: Array<{ svc: HostedService; dataDir: string }> = []
afterEach(() => {
+ releaseHeldWrites()
+ disk.holdTeamWrite = false
+ disk.failTeamWrite = false
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 }>()
+type WorldOpts = Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'projectOfNode' | 'killPeer'>> & {
+ recordTimers?: boolean
+ dataDir?: string
+}
+
+function world(opts: WorldOpts = {}) {
+ const dataDir = opts.dataDir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-'))
+ const sinks = new Map<number, UiSink>()
const dispatched: string[] = []
const casts: string[] = []
let next = 1
@@ -49,7 +85,7 @@ function world(opts: Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'p
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 },
+ setTimeout: (fn, ms) => { const h = setTimeout(fn, ms); armed.push({ ms, h, fn, cleared: false }); return h },
clearTimeout: (h) => {
for (const a of armed) if (a.h === h) a.cleared = true
clearTimeout(h as ReturnType<typeof setTimeout>)
@@ -65,10 +101,11 @@ function world(opts: Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'p
transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT },
...(opts.now ? { now: opts.now } : {}),
...(opts.monotonicNow ? { monotonicNow: opts.monotonicNow } : {}),
+ ...(opts.killPeer ? { killPeer: opts.killPeer } : {}),
...timerDeps
})
live.push({ svc, dataDir })
- const join = (keys = genKeyPair(), auto = false, humanConfirms = true) => {
+ const join = (keys = genKeyPair(), auto = false, humanConfirms = true, onApproved?: (c: RelayClientSession) => void) => {
const frames: string[] = []
const denied: string[] = []
let approved = false
@@ -76,10 +113,10 @@ function world(opts: Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'p
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),
+ // A human who confirms at once — synchronously inside onSas, which over this in-process
+ // transport runs before the client holds its socket (the client defers that confirm).
+ autoApprove: auto, onSas: (s) => { if (humanConfirms) s.confirm() },
+ onApproved: (s) => { approved = true; onApproved?.(s) }, onFrame: (j) => frames.push(j),
onPtyData: () => {}, onClose: () => { closed++ }, onDenied: (r) => denied.push(r)
})
const res = (id: number) => {
@@ -110,14 +147,9 @@ function world(opts: Partial<Pick<HostedServiceDeps, 'now' | 'monotonicNow' | 'p
}
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))
+ const teamOnDisk = (): Array<{ pubkeyB64: string; role: string; addedBy: string; addedAt: string; label: string }> =>
+ JSON.parse(fs.readFileSync(path.join(dataDir, 'relay', 'team.json'), 'utf-8')).peers
+ return { svc, join, rawPeer, sinks, dispatched, casts, dataDir, armed, teamOnDisk, mints: () => mints }
}
async function ownerOnline(w: ReturnType<typeof world>, ownerKeys = genKeyPair()) {
@@ -132,20 +164,26 @@ async function ownerOnline(w: ReturnType<typeof world>, ownerKeys = genKeyPair()
}
/** A guest whose first connect is waiting for an owner. */
-async function pendingGuest(w: ReturnType<typeof world>, keys = genKeyPair()) {
+async function pendingGuest(w: ReturnType<typeof world>, keys = genKeyPair(), humanConfirms = true) {
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 g = w.join(keys, false, humanConfirms)
+ await vi.waitFor(() => expect(w.svc.status().pending.some((p) => p.peerKeyB64 === pub(keys))).toBe(true))
const pendingId = w.svc.status().pending.find((p) => p.peerKeyB64 === pub(keys))!.pendingId
return { g, pendingId }
}
+/** 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 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))
+ await hostOpened(w, keys)
return g
}
@@ -180,7 +218,6 @@ describe('hosted service', () => {
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)
@@ -198,7 +235,6 @@ describe('hosted service', () => {
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))
@@ -216,7 +252,8 @@ describe('hosted service', () => {
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)
+ // The reconnect below auto-approves only once the approval is pinned.
+ await vi.waitFor(() => expect(w.svc.status().peers.some((p) => p.role === 'editor')).toBe(true))
g.c.close()
await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
const again = w.join(keys, true)
@@ -247,8 +284,33 @@ describe('hosted service', () => {
}
})
- it('the pending TTL is ten minutes', () => {
+ it('the pending TTL is ten minutes and at most sixteen requests wait at once', () => {
expect(PENDING_TTL_MS).toBe(600_000)
+ expect(PENDING_MAX).toBe(16)
+ })
+})
+
+describe('hosted service — the first request of a new teammate (R24)', () => {
+ it('a request sent the moment the guest is approved, during the host’s pin write, is answered — not refused', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))
+ let sent = false
+ const g = w.join(genKeyPair(), false, true, (c) => {
+ sent = c.send(JSON.stringify({ t: 'req', id: 1, method: IPC.workspaceLoad, args: [] }))
+ })
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(1))
+ disk.holdTeamWrite = true // the pin write is in flight until we say so
+ owner.req(5, IPC.relayHostedApprove, [w.svc.status().pending[0].pendingId, 'viewer'])
+ await vi.waitFor(() => expect(g.isApproved()).toBe(true))
+ expect(sent).toBe(true)
+ await vi.waitFor(() => expect(disk.held).toHaveLength(1))
+ await settle()
+ expect(g.res(1)).toBeUndefined() // held, not refused
+ expect(w.dispatched).toEqual([])
+ releaseHeldWrites()
+ await vi.waitFor(() => expect(g.res(1)).toMatchObject({ ok: true, result: { projects: [{ id: 'P' }], activeProjectId: 'P' } }))
+ expect(g.frames.some((f) => f.includes('E_UNAUTHORIZED'))).toBe(false)
})
})
@@ -278,6 +340,34 @@ describe('hosted service — owner routing', () => {
expect(editor.frames.some((f) => f.includes('relay:hosted:'))).toBe(false)
})
+ it('R25: an owner can PULL the open requests; anyone else is refused', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const viewer = await approvedGuest(w, owner, 'viewer', 5)
+ const keys = genKeyPair()
+ const { pendingId } = await pendingGuest(w, keys)
+ owner.req(1, IPC.relayHostedPending)
+ viewer.req(2, IPC.relayHostedPending)
+ await vi.waitFor(() => expect(owner.res(1)).toBeDefined())
+ await vi.waitFor(() => expect(viewer.res(2)).toBeDefined())
+ expect(owner.res(1).result).toEqual(w.svc.status().pending)
+ expect(owner.res(1).result).toEqual([expect.objectContaining({ pendingId, peerKeyB64: pub(keys) })])
+ expect(viewer.res(2)).toMatchObject({ ok: false, error: { message: expect.stringMatching(/Only an owner/) } })
+ })
+
+ 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')
+ })
+
it('a pinned peer that never confirms does not hold the room’s only idle listener', async () => {
const w = world()
await ownerOnline(w)
@@ -293,18 +383,36 @@ describe('hosted service — owner routing', () => {
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 () => {
+describe('hosted service — at most one request per device, and a bounded queue (R28)', () => {
+ it('a second connection from the same key replaces the first request, which is denied', async () => {
const w = world()
const owner = await ownerOnline(w)
const keys = genKeyPair()
+ const first = await pendingGuest(w, keys)
+ const second = await pendingGuest(w, keys)
+ await vi.waitFor(() => expect(first.g.denied).toEqual(['denied']))
+ expect(second.pendingId).not.toBe(first.pendingId)
+ expect(w.svc.status().pending.map((p) => p.pendingId)).toEqual([second.pendingId])
+ await vi.waitFor(() => expect(owner.events(IPC.relayHostedPendingClosed)).toContainEqual({ pendingId: first.pendingId, reason: 'replaced' }))
+ expect(second.g.denied).toEqual([])
+ })
+
+ it(`over ${16} waiting requests, the next is denied at once and no owner is told`, async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ for (let i = 0; i < PENDING_MAX; i++) await pendingGuest(w)
+ expect(w.svc.status().pending).toHaveLength(PENDING_MAX)
+ await vi.waitFor(() => expect(owner.events(IPC.relayHostedPeerPending)).toHaveLength(PENDING_MAX))
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')
+ const bridgedBefore = w.svc.status().scheduler!.bridged
+ const over = w.join()
+ await vi.waitFor(() => expect(over.denied).toEqual(['denied']))
+ expect(w.svc.status().pending).toHaveLength(PENDING_MAX)
+ await settle()
+ expect(owner.events(IPC.relayHostedPeerPending)).toHaveLength(PENDING_MAX)
+ await vi.waitFor(() => expect(w.svc.status().scheduler?.bridged).toBe(bridgedBefore))
})
})
@@ -364,8 +472,7 @@ describe('hosted service — approve and deny', () => {
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({
+ expect(w.teamOnDisk().find((p) => p.pubkeyB64 === pub(keys))).toEqual({
pubkeyB64: pub(keys), label: '', role: 'commenter', addedAt: new Date(fixed).toISOString(), addedBy: pub(ownerKeys)
})
})
@@ -384,6 +491,79 @@ describe('hosted service — approve and deny', () => {
})
})
+describe('hosted service — a refusal while the approval’s pin is being written (R26)', () => {
+ it('a deny that lands while the pin write waits its turn pins nothing', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const { g, pendingId } = await pendingGuest(w, keys)
+ disk.holdTeamWrite = true
+ const sharing = w.svc.share('Z', true) // holds the team store's chain
+ await vi.waitFor(() => expect(disk.held).toHaveLength(1))
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'editor'])
+ await vi.waitFor(() => expect(g.isApproved()).toBe(true)) // both confirmed: the pin is queued
+ owner.req(6, IPC.relayHostedDeny, [pendingId])
+ await vi.waitFor(() => expect(g.denied).toEqual(['denied']))
+ const writes = disk.done
+ releaseHeldWrites()
+ await sharing
+ await settle() // the queued pin runs right behind the share; a skipped one writes nothing
+ expect(disk.done).toBe(writes + 1)
+ expect(w.teamOnDisk().some((p) => p.pubkeyB64 === pub(keys))).toBe(false)
+ expect(w.svc.status().peers.map((p) => p.role)).toEqual(['owner'])
+ })
+
+ it('a deny that lands while the pin write itself is in flight takes the pin back', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const { g, pendingId } = await pendingGuest(w, keys)
+ disk.holdTeamWrite = true
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'editor'])
+ await vi.waitFor(() => expect(disk.held).toHaveLength(1)) // the pin's own write is on disk's doorstep
+ owner.req(6, IPC.relayHostedDeny, [pendingId])
+ await vi.waitFor(() => expect(g.denied).toEqual(['denied']))
+ const writes = disk.done
+ releaseHeldWrites()
+ // The pin write lands, then the write that takes it back: only then is the file settled.
+ await vi.waitFor(() => expect(disk.done).toBe(writes + 2))
+ expect(w.teamOnDisk().some((p) => p.pubkeyB64 === pub(keys))).toBe(false)
+ expect(w.svc.status().peers.map((p) => p.role)).toEqual(['owner'])
+ })
+
+ it('an expiry that lands while the pin write is in flight takes the pin back too', async () => {
+ const w = world({ recordTimers: true })
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const { g, pendingId } = await pendingGuest(w, keys)
+ const expiry = w.armed.find((a) => a.ms === PENDING_TTL_MS)!
+ disk.holdTeamWrite = true
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'editor'])
+ await vi.waitFor(() => expect(disk.held).toHaveLength(1))
+ expiry.fn() // the ten minutes are up, mid-write
+ await vi.waitFor(() => expect(g.denied).toEqual(['expired']))
+ const writes = disk.done
+ releaseHeldWrites()
+ await vi.waitFor(() => expect(disk.done).toBe(writes + 2))
+ expect(w.teamOnDisk().some((p) => p.pubkeyB64 === pub(keys))).toBe(false)
+ expect(w.svc.status().peers.map((p) => p.role)).toEqual(['owner'])
+ })
+
+ it('a guest that merely DROPS during the pin write stays pinned: both humans did approve', async () => {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const { g, pendingId } = await pendingGuest(w, keys)
+ disk.holdTeamWrite = true
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'editor'])
+ await vi.waitFor(() => expect(disk.held).toHaveLength(1))
+ g.c.close()
+ await vi.waitFor(() => expect(w.svc.status().pending).toHaveLength(0))
+ releaseHeldWrites()
+ await vi.waitFor(() => expect(w.teamOnDisk().some((p) => p.pubkeyB64 === pub(keys) && p.role === 'editor')).toBe(true))
+ })
+})
+
describe('hosted service — roles', () => {
it('relay:hosted:self answers the caller’s own role; invite-code is owner-only', async () => {
const w = world()
@@ -429,6 +609,8 @@ describe('hosted service — roles', () => {
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')
+ // By design: an editor sees other projects' subagent tasks too. Editor is shell access on this
+ // host (D8), so withholding a task text an editor could read from disk would be theatre.
expect(editor.res(2).result.map((e: { nodeId: string }) => e.nodeId)).toEqual(['n-shared', 'n-other'])
})
@@ -454,6 +636,58 @@ describe('hosted service — roles', () => {
})
})
+describe('hosted service — a session with no team entry (R27)', () => {
+ it('in the window between a removal’s team write and its kill, the removed peer is served NOTHING', async () => {
+ const kills: Array<[string, string]> = []
+ const w = world({ killPeer: (key, reason) => { kills.push([key, reason]) } }) // the kill is held back
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const g = await approvedGuest(w, owner, 'editor', 5, keys)
+ const sink = [...w.sinks.values()].at(-1)!
+ const event = (n: number) => JSON.stringify({ t: 'ev', channel: IPC.agentStatus, args: [{ nodeId: 'n-shared', n }] })
+ sink.sendText(event(1)) // positive control: an editor receives it
+ await vi.waitFor(() => expect(g.frames.some((f) => f.includes('"n":1'))).toBe(true))
+
+ expect(await w.svc.remove(pub(keys), false)).toBe('removed')
+ expect(kills).toEqual([[pub(keys), 'removed']])
+ g.req(1, IPC.workspaceLoad)
+ g.req(2, IPC.fsWrite, ['/srv/app/x', 'y'])
+ g.req(3, IPC.relayHostedSelf)
+ sink.sendText(event(2))
+ await vi.waitFor(() => expect(g.res(3)).toBeDefined())
+ expect(g.res(1)).toMatchObject({ ok: false, error: { code: 'E_ROLE', message: expect.stringMatching(/not a member/) } })
+ expect(g.res(2)).toMatchObject({ ok: false, error: { code: 'E_ROLE', message: expect.stringMatching(/not a member/) } })
+ expect(g.res(3)).toMatchObject({ ok: false, error: { message: expect.stringMatching(/not a member/) } })
+ expect(g.frames.some((f) => f.includes('"n":2'))).toBe(false)
+ expect(w.dispatched).toEqual([])
+ killRelayHostsByPeerKey(pub(keys), 'removed') // the kill finally lands
+ await vi.waitFor(() => expect(g.denied).toEqual(['removed']))
+ })
+
+ it('a session whose OWN pin write failed keeps the documented viewer fallback', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const w = world()
+ const owner = await ownerOnline(w)
+ const keys = genKeyPair()
+ const { g, pendingId } = await pendingGuest(w, keys)
+ disk.failTeamWrite = true
+ owner.req(5, IPC.relayHostedApprove, [pendingId, 'editor'])
+ await vi.waitFor(() => expect(g.isApproved()).toBe(true))
+ await hostOpened(w, keys)
+ g.req(1, IPC.workspaceLoad)
+ g.req(2, IPC.fsWrite, ['/srv/app/x', 'y'])
+ await vi.waitFor(() => expect(g.res(2)).toBeDefined())
+ expect(g.res(1)).toMatchObject({ ok: true, result: { projects: [{ id: 'P' }] } })
+ expect(g.res(2)).toMatchObject({ ok: false, error: { code: 'E_ROLE', message: expect.stringMatching(/Viewers/) } })
+ expect(w.svc.status().peers.map((p) => p.role)).toEqual(['owner'])
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/could not record an approved teammate/))
+ } finally {
+ warn.mockRestore()
+ }
+ })
+})
+
describe('hosted service — removal', () => {
it('removal returns the scheduler’s bridged count (R20) and refuses the last owner', async () => {
const w = world()
@@ -564,6 +798,22 @@ describe('hosted service — lifecycle', () => {
expect(w.svc.status().enabled).toBe(false)
})
+ it('R30: the team is loaded before the host key, so status shows members even when the key is unreadable', async () => {
+ const w = world()
+ await w.svc.init()
+ await w.svc.addOwner(pub(genKeyPair()), 'Enes')
+ fs.writeFileSync(path.join(w.dataDir, 'relay', 'host-key.json'), 'not json')
+ const fresh = world({ dataDir: w.dataDir }) // nothing loaded yet
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ expect(fresh.svc.status().peers).toEqual([])
+ expect(await fresh.svc.start()).toBe('host-key-unreadable')
+ } finally {
+ err.mockRestore()
+ }
+ expect(fresh.svc.status().peers).toEqual([{ label: 'Enes', role: 'owner', connected: 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()
@@ -599,17 +849,36 @@ describe('hosted service — lifecycle', () => {
expect(w.mints()).toBe(0)
})
- it('rotateKey replaces the host address and keeps hosting', async () => {
+ it('R31: rotateKey on a running service replaces the address and restarts, returning the start result', async () => {
const w = world()
await ownerOnline(w)
const before = w.svc.info()!.hostPublicKeyB64
- await w.svc.rotateKey()
+ expect(await w.svc.rotateKey()).toBe('started')
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('R31: rotateKey on a never-started or stopped service rotates WITHOUT starting hosting', async () => {
+ const w = world()
+ await w.svc.init()
+ const onDisk = async () => publicKeyToB64((await loadHostKey(path.join(w.dataDir, 'relay')))!.publicKey)
+ const first = await onDisk()
+ expect(await w.svc.rotateKey()).toBe('not-running')
+ expect(w.svc.status().enabled).toBe(false)
+ expect(w.mints()).toBe(0)
+ const second = await onDisk()
+ expect(second).not.toBe(first)
+ expect(w.svc.info()!.hostPublicKeyB64).toBe(second)
+
+ expect(await w.svc.start()).toBe('started')
+ w.svc.stop()
+ expect(await w.svc.rotateKey()).toBe('not-running')
+ expect(w.svc.status().enabled).toBe(false)
+ expect(await onDisk()).not.toBe(second)
+ })
+
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 })
@@ -623,7 +892,7 @@ describe('hosted service — lifecycle', () => {
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)
+ expect(hosted).toHaveLength(7)
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
index 86cf3bfb2..03f8cf204 100644
--- a/src/core/relay/hosted-service.ts
+++ b/src/core/relay/hosted-service.ts
@@ -4,15 +4,23 @@
// 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 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`).
+// next message. A session whose key has NO team entry is served nothing at all — that is the
+// window between a removal's team write and its kill — except one whose own approval could not
+// be written (`pinFailed`), which keeps the lowest role. Removal also cuts the live session.
+// - Every hook derives the peer key from the SESSION it is handed, never from this file's own
+// record of it (which is only filled in once `connectRelayHost` returns).
// - 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.
+// session key against the team store: `relay:hosted:self` is open to any member, approve / deny /
+// invite-code / pending 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.
+// who is knocking), and an owner who connects later is told the ones still open. At most one
+// request per device key, and at most PENDING_MAX at once.
+// - An approval is pinned only once both humans confirmed. A deny or an expiry that lands while
+// that pin is still being written wins: the write is skipped, or taken back. A peer that merely
+// drops meanwhile keeps its pin — both humans did approve.
// - 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.
@@ -24,7 +32,7 @@ import { connectRelayHost, killRelayHostsByPeerKey, type PeerAttach, type RelayH
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 { TeamStore, peerFor, upsertPeer, removePeer, setShared, TEAM_ROLES, type TeamPeer, 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'
@@ -35,6 +43,10 @@ import type { UiSink } from '../ui-sink-registry'
/** An unanswered join request is refused after ten minutes. */
export const PENDING_TTL_MS = 600_000
+/** At most this many join requests wait at once; the next is denied without telling any owner. A
+ * bound on what anyone holding a join code (public material) can make an owner's dialog show. */
+export const PENDING_MAX = 16
+
/** 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:'
@@ -42,11 +54,16 @@ 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
+const NOT_A_MEMBER = 'You are not a member of this team.'
+
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'
+/** Why a pending request stopped being pending, as told to owners on `relay:hosted:pending-closed`.
+ * `replaced`: the same device connected again, and its newer request took this one's place. */
+export type PendingClosedReason = 'approved' | 'denied' | 'expired' | 'replaced' | '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'
+/** `not-running`: the key was rotated on a service that was not hosting, and hosting stays off. */
+export type HostedRotateResult = HostedStartResult | 'not-running'
export interface HostedServiceDeps {
dataDir: string
@@ -61,6 +78,9 @@ export interface HostedServiceDeps {
transport?: () => RelayTransport
/** TEST ONLY: the host-token mint's fetch. */
fetch?: typeof fetch
+ /** TEST ONLY: how a removal cuts the key's live sessions (default `killRelayHostsByPeerKey`). A
+ * test holds it back to observe the window between the team write and the kill. */
+ killPeer?(pubkeyB64: string, reason: TrustDeniedReason): void
/** 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
@@ -93,8 +113,9 @@ export interface HostedService {
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>
+ /** Replace the host key. Every teammate needs a new join code. A hosting service restarts on the
+ * new key and answers the start result; one that was not hosting stays off ('not-running'). */
+ rotateKey(): Promise<HostedRotateResult>
}
/** One relay listener and, once a peer bridges, its session. */
@@ -108,6 +129,10 @@ interface Conn {
pendingId: string | null
/** The owner decision awaiting the peer's own confirm; what `pins.record` writes. */
approval: { role: TeamRole; by: string } | null
+ /** This session's own approval was confirmed by both humans but could not be written. */
+ pinFailed: boolean
+ /** Set when THIS service refused the session (deny, expiry, removal) — never for a drop. */
+ refused: TrustDeniedReason | null
open: boolean
ended: boolean
}
@@ -117,7 +142,8 @@ 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.'
+ [IPC.relayHostedInviteCode]: 'Only an owner can invite.',
+ [IPC.relayHostedPending]: 'Only an owner can see join requests.'
})
const errorMessage = (err: unknown): string => (err instanceof Error ? err.message : String(err))
@@ -157,10 +183,12 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
if (deps.clearTimeout) deps.clearTimeout(h)
else clearTimeout(h as ReturnType<typeof setTimeout>)
}
+ const killPeer = (pubkeyB64: string, reason: TrustDeniedReason): void =>
+ deps.killPeer ? deps.killPeer(pubkeyB64, reason) : killRelayHostsByPeerKey(pubkeyB64, reason)
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. */
+ /** 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. */
@@ -174,18 +202,16 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
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 => {
+ /** The team's word on this key, NOW. Never cached (see the header). */
+ const memberRole = (key: string | null): TeamRole | undefined =>
+ key ? peerFor(team.current(), key)?.role : undefined
+ /** The role a session is served with, or null = serve it nothing. */
+ const standing = (c: Conn, s: RelayHostSession): TeamRole | null =>
+ memberRole(s.peerKeyB64()) ?? (c.pinFailed ? 'viewer' : null)
+ const ctxWith = (role: TeamRole): 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',
+ role,
sharedProjects: shared,
projectOfNode: (nodeId) => deps.projectOfNode(nodeId),
projectCwds: () =>
@@ -194,6 +220,7 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
}
}
+ const keyOf = (c: Conn): string | null => c.session?.peerKeyB64() ?? null
const send = (c: Conn, channel: string, payload: unknown): void => {
if (!c.sink) return
try {
@@ -204,8 +231,9 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
}
/** 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)
+ for (const c of conns) if (c.open && memberRole(keyOf(c)) === 'owner') send(c, channel, payload)
}
+ const pendingList = (): HostedPending[] => [...pending.values()].map((p) => ({ ...p.info }))
const closePending = (id: string, reason: PendingClosedReason): void => {
const p = pending.get(id)
@@ -234,42 +262,81 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
/** 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.refused ??= why
c.session?.deny(why)
ended(c, reason)
}
+ /** Cut every live session holding this key, and do the bookkeeping the kill itself does not
+ * (a kill never fires the core's onClose). */
+ const cutKey = (key: string, why: TrustDeniedReason): void => {
+ killPeer(key, why)
+ for (const c of [...conns]) {
+ if (keyOf(c) !== key) continue
+ c.refused ??= why
+ ended(c, 'gone')
+ }
+ }
+
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')
}
+ /** Take back a pin this service wrote for a session it then refused — only if the entry is still
+ * exactly what it wrote (a later `add-owner` of the same key is someone's deliberate act). */
+ const unpin = async (entry: TeamPeer): Promise<void> => {
+ let took = false
+ try {
+ await team.update((d) => {
+ const cur = peerFor(d, entry.pubkeyB64)
+ const ours = cur && cur.role === entry.role && cur.addedAt === entry.addedAt && cur.addedBy === entry.addedBy
+ if (!ours) return 'last-owner' // the store's "write nothing"
+ took = true
+ return removePeer(d, entry.pubkeyB64, true)
+ })
+ } catch (err) {
+ console.warn(`[hosted-team] could not take back a refused teammate's pin: ${errorMessage(err)}`)
+ return
+ }
+ // A reconnect from that key could have auto-approved while the pin stood.
+ if (took) cutKey(entry.pubkeyB64, 'denied')
+ }
+
/** 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
+ const entry: TeamPeer = { pubkeyB64: peerKeyB64, label: '', role: a.role, addedAt: new Date(wallNow()).toISOString(), addedBy: a.by }
+ let wrote = false
try {
- await team.update((d) =>
- upsertPeer(d, { pubkeyB64: peerKeyB64, label: '', role: a.role, addedAt: new Date(wallNow()).toISOString(), addedBy: a.by })
- )
+ await team.update((d) => {
+ // Denied or expired while this write waited its turn: pin nothing ('last-owner' = write nothing).
+ if (c.refused) return 'last-owner'
+ wrote = true
+ return upsertPeer(d, entry)
+ })
} catch (err) {
- // The gate still opens (consent for THIS session is mutual); the next connect asks again.
+ // The gate still opens (consent for THIS session is mutual) and serves it with the lowest role;
+ // the next connect asks again.
+ c.pinFailed = true
console.warn(`[hosted-team] could not record an approved teammate: ${errorMessage(err)}`)
+ return
}
+ // Denied or expired while the write itself was in flight: the refusal wins.
+ if (wrote && c.refused) await unpin(entry)
}
- 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])
+ /** approve / deny / invite-code / pending. 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 = (s: RelayHostSession, method: string, args: unknown[]): unknown => {
+ const caller = s.peerKeyB64()
+ if (memberRole(caller) !== 'owner' || !caller) throw new Error(OWNER_ONLY[method])
if (method === IPC.relayHostedInviteCode) return api.joinCode()
+ if (method === IPC.relayHostedPending) return pendingList()
const [pendingId, role] = args
const p = typeof pendingId === 'string' ? pending.get(pendingId) : undefined
if (method === IPC.relayHostedDeny) {
@@ -279,16 +346,41 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
}
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 }
+ p.conn.approval = { role: role as TeamRole, by: caller }
// This end's confirm. The request stays pending until the peer's own confirm opens it.
p.conn.session?.confirm()
return true
}
+ const onPending = (c: Conn, s: RelayHostSession): void => {
+ if (c.ended) return
+ const key = s.peerKeyB64() ?? ''
+ // One request per device: a newer connection from the same key takes the older one's place.
+ for (const p of [...pending.values()]) if (p.info.peerKeyB64 === key && p.conn !== c) endSession(p.conn, 'denied', 'replaced')
+ if (pending.size >= PENDING_MAX) {
+ console.warn(`[hosted-team] ${PENDING_MAX} join requests are already waiting; refused another`)
+ endSession(c, 'denied', 'gone') // no request was ever opened, so no owner hears of it
+ return
+ }
+ const info: HostedPending = { pendingId: randomUUID(), sas: s.sas() ?? '', peerKeyB64: key, 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)
+ }
+
+ const onOpen = (c: Conn, s: RelayHostSession): void => {
+ if (c.ended) return
+ c.open = true
+ if (c.pendingId) closePending(c.pendingId, 'approved')
+ const role = standing(c, s)
+ if (role === null) console.warn('[hosted-team] a session opened with no team entry; it is served nothing')
+ // An owner who was offline when a request arrived is told the ones still open.
+ if (memberRole(s.peerKeyB64()) === 'owner') for (const p of pending.values()) send(c, IPC.relayHostedPeerPending, p.info)
+ }
+
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 c: Conn = { session: null, ev, sink: null, pendingId: null, approval: null, pinFailed: false, refused: null, open: false, ended: false }
const bridged = (): void => {
try {
ev.onBridged()
@@ -309,58 +401,64 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
// confirms must not hold the room's only idle listener until its refresh.
autoApprove: (peerKeyB64) => {
bridged()
- return peerFor(team.current(), peerKeyB64) !== undefined
+ return memberRole(peerKeyB64) !== undefined
},
pins: { record: (state) => recordApproval(c, state.peerKeyB64) },
hooks: {
- interceptReq: (_s, method, args) => {
- if (method === IPC.relayHostedSelf) return Promise.resolve(self(c))
+ interceptReq: (s, method, args) => {
+ if (method === IPC.relayHostedSelf) {
+ const role = standing(c, s)
+ if (role === null) return Promise.reject(new Error(NOT_A_MEMBER))
+ const p = peerFor(team.current(), s.peerKeyB64() ?? '')
+ return Promise.resolve({ role, label: p?.label ?? '', hostLabel: deps.hostLabel })
+ }
if (!Object.hasOwn(OWNER_ONLY, method)) return null
try {
- return Promise.resolve(ownerVerb(c, method, args))
+ return Promise.resolve(ownerVerb(s, method, args))
} catch (err) {
return Promise.reject(err)
}
},
- access: (_s, kind, method, args) => {
+ 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))
+ const role = standing(c, s)
+ if (role === null) return { allow: false, message: NOT_A_MEMBER }
+ return decideAccess(kind, method, args, ctxWith(role))
},
- wrapSink: (_s, sink) => {
- const wrapped = wrapSinkForRole(sink, () => ctxFor(c))
+ wrapSink: (s, sink) => {
+ const filtered = wrapSinkForRole(sink, () => ctxWith(standing(c, s) ?? 'viewer'))
+ // A session with no standing receives nothing, terminal bytes included.
+ const wrapped: UiSink = {
+ sendText: (json) => { if (standing(c, s) !== null) filtered.sendText(json) },
+ sendBinary: (buf) => { if (standing(c, s) !== null) filtered.sendBinary(buf) },
+ bufferedAmount: () => filtered.bufferedAmount?.() ?? 0
+ }
+ c.session ??= s
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)
+ narrowResponse: (s, method, result) => {
+ const role = standing(c, s)
+ if (role === null) throw new Error(NOT_A_MEMBER)
+ const ctx = ctxWith(role)
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)
+ c.session ??= s
+ onPending(c, s)
},
- onOpen: () => {
+ onOpen: (s) => {
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)
+ c.session ??= s
+ onOpen(c, s)
},
onClose: () => ended(c, 'gone')
})
@@ -377,8 +475,8 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
}
}
- const stopNow = (): void => {
- epoch++
+ /** End hosting now: every listener, session and pending request. Leaves the epoch alone. */
+ const teardown = (): void => {
const s = scheduler
scheduler = null
s?.stop() // closes every listener it holds, bridged ones included
@@ -390,9 +488,11 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
}
async function startNow(my: number): Promise<HostedStartResult> {
- if (my !== epoch) return 'stopped'
if (scheduler) return 'started'
+ if (my !== epoch) return 'stopped'
if (!team.exists()) return 'no-team'
+ // The team BEFORE the key: status() then shows the members even when the key is unreadable.
+ await team.load()
let k: KeyPair | null
try {
k = await loadHostKey(dir)
@@ -404,7 +504,6 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
throw err
}
if (!k) return 'no-team'
- await team.load()
if (my !== epoch) return 'stopped'
keys = k
const hostKeys = k
@@ -442,7 +541,8 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
return onLifecycle(() => startNow(my))
},
stop() {
- stopNow()
+ epoch++
+ teardown()
},
async addOwner(pubkeyB64, label) {
await team.update((d) =>
@@ -459,9 +559,8 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
})
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')
+ // Until the kill lands, the session holds no team entry — and is served nothing (R27).
+ cutKey(pubkeyB64, 'removed')
return 'removed'
},
async share(projectId, on) {
@@ -486,15 +585,18 @@ export function createHostedService(deps: HostedServiceDeps): HostedService {
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 }))
+ pending: pendingList()
}
},
rotateKey() {
- return onLifecycle(async () => {
- stopNow()
+ return onLifecycle(async (): Promise<HostedRotateResult> => {
+ const wasHosting = scheduler !== null
+ teardown()
const my = epoch
keys = await rotateHostKey(dir)
- await startNow(my)
+ // A service that was not hosting stays off: rotating a key is not consent to start hosting.
+ if (!wasHosting) return 'not-running'
+ return startNow(my)
})
}
}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 6a3617f6a..e7d57e22a 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -598,11 +598,12 @@ export const IPC = {
// 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.
+ // only; `relayHostedApprove` (pendingId, role), `relayHostedDeny` (pendingId),
+ // `relayHostedInviteCode` () and `relayHostedPending` () (the open requests, pulled) 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',
+ relayHostedPending: 'relay:hosted:pending',
relayHostedApprove: 'relay:hosted:approve',
relayHostedDeny: 'relay:hosted:deny',
relayHostedInviteCode: 'relay:hosted:invite-code',