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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): the key-swap self-close tells the shell; an existing host key is a typed error
reviewaf2ca94a1180
diff --git a/src/core/relay/host-key.test.ts b/src/core/relay/host-key.test.tsindex 1293db02f..5343f55f5 100644--- a/src/core/relay/host-key.test.ts+++ b/src/core/relay/host-key.test.ts@@ -3,7 +3,7 @@ import { describe, it, expect, afterEach } from 'vitest'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'-import { createHostKey, loadHostKey, rotateHostKey, hostAddress, HostKeyUnreadableError } from './host-key'+import { createHostKey, loadHostKey, rotateHostKey, hostAddress, HostKeyUnreadableError, HostKeyExistsError } from './host-key'import { genKeyPair, publicKeyToB64 } from './e2ee'import { hostIdFromPublicKeyB64 } from './relay-id'@@ -89,6 +89,9 @@ describe('server host key', () => {const dir = tmp()const a = await createHostKey(dir)await expect(createHostKey(dir)).rejects.toThrow(/already exists/)+ // A typed code, so a caller that lost an init race recognises it without matching message text.+ await expect(createHostKey(dir)).rejects.toMatchObject({ code: 'E_HOST_KEY_EXISTS' })+ await expect(createHostKey(dir)).rejects.toBeInstanceOf(HostKeyExistsError)expect(publicKeyToB64((await loadHostKey(dir))!.publicKey)).toBe(publicKeyToB64(a.publicKey))const b = await rotateHostKey(dir)expect(publicKeyToB64(b.publicKey)).not.toBe(publicKeyToB64(a.publicKey))diff --git a/src/core/relay/host-key.ts b/src/core/relay/host-key.tsindex 1a6bdf9dc..235be8284 100644--- a/src/core/relay/host-key.ts+++ b/src/core/relay/host-key.ts@@ -27,6 +27,16 @@ export class HostKeyUnreadableError extends Error {}}+/** `createHostKey` found a key already there. Typed, so a caller that lost an init race (two+ * `team init`s at once) can recognise it by `code` rather than by matching message text. */+export class HostKeyExistsError extends Error {+ readonly code = 'E_HOST_KEY_EXISTS'+ constructor() {+ super('A team host key already exists.')+ this.name = 'HostKeyExistsError'+ }+}+const file = (dir: string): string => path.join(dir, 'host-key.json')async function persist(dir: string, keys: KeyPair): Promise<void> {@@ -70,11 +80,11 @@ export async function loadHostKey(dir: string): Promise<KeyPair | null> {return decoded.keys}-/** Mint the first key. Refuses when one exists, and throws `HostKeyUnreadableError` (without- * writing) when one exists but cannot be read. */+/** Mint the first key. Refuses with `HostKeyExistsError` when one exists, and throws+ * `HostKeyUnreadableError` (without writing) when one exists but cannot be read. */export function createHostKey(dir: string): Promise<KeyPair> {return serializeWrite(dir, async () => {- if ((await loadHostKey(dir)) !== null) throw new Error('A team host key already exists.')+ if ((await loadHostKey(dir)) !== null) throw new HostKeyExistsError()const keys = genKeyPair()await persist(dir, keys)return keysdiff --git a/src/core/relay/relay-host.key-swap.test.ts b/src/core/relay/relay-host.key-swap.test.tsnew file mode 100644index 000000000..0434565a7--- /dev/null+++ b/src/core/relay/relay-host.key-swap.test.ts@@ -0,0 +1,106 @@+// src/core/relay/relay-host.key-swap.test.ts+// The key-swap self-close must tell the shell, like every other close the shell did not ask for.+// relay-socket's layer-1 guard makes a mid-session re-key unreachable over a real handshake, so the+// host's socket is wrapped here to report a different peer key on demand: that is the only way to+// reach relay-host's second, independent check (peerKeyIntact). Kept in its own file so the module+// mock cannot touch any other suite.+import { describe, it, expect, vi, afterEach } from 'vitest'+import { connectRelayHost, type PeerAttach } from './relay-host'+import { connectRelayClient } from './relay-client'+import { transportPair } from './transport-pair'+import { genKeyPair, publicKeyToB64 } from './e2ee'++const swap = vi.hoisted(() => ({ hostSeesPeerKey: null as string | null }))++vi.mock('./relay-socket', async (importOriginal) => {+ const real = await importOriginal<typeof import('./relay-socket')>()+ return {+ ...real,+ connectRelay: (o: Parameters<typeof real.connectRelay>[0]) => {+ const s = real.connectRelay(o)+ if (o.role !== 'host') return s+ // The socket's methods are closures (no `this`), so a spread copy behaves exactly like it.+ return { ...s, peerPublicKeyB64: () => swap.hostSeesPeerKey ?? s.peerPublicKeyB64() }+ }+ }+})++afterEach(() => {+ swap.hostSeesPeerKey = null+})++function fakeAttach() {+ const sinks = new Map<number, unknown>()+ let next = 1+ const attach: PeerAttach = {+ attach: (sink) => { const id = next++; sinks.set(id, sink); return id },+ detach: (id) => { sinks.delete(id) },+ dispatch: async (_id, req) => ({ t: 'res', id: req.id, ok: true, result: 'ok' }),+ cast: () => {}+ }+ return { attach, sinks }+}++const settle = () => new Promise((r) => setTimeout(r, 20))++describe('core relay host — the key-swap self-close', () => {+ it('fires onClose exactly once when an OPEN session’s key is found swapped, and detaches the peer', async () => {+ const hostKeys = genKeyPair()+ const { hostT, peerT } = transportPair()+ const fa = fakeAttach()+ const counts = { opened: 0, hostClosed: 0, clientClosed: 0 }+ const host = connectRelayHost({+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,+ autoApprove: () => true,+ onPeerPending: () => {}, onOpen: () => counts.opened++, onClose: () => counts.hostClosed+++ })+ const client = connectRelayClient({+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => {}, onFrame: () => {},+ onPtyData: () => {}, onClose: () => counts.clientClosed+++ })+ await vi.waitFor(() => expect(counts.opened).toBe(1))+ expect(fa.sinks.size).toBe(1)++ swap.hostSeesPeerKey = publicKeyToB64(genKeyPair().publicKey)+ client.send(JSON.stringify({ t: 'req', id: 1, method: 'anything', args: [] }))+ await settle()++ expect(counts.hostClosed).toBe(1)+ expect(counts.clientClosed).toBe(1)+ expect(fa.sinks.size).toBe(0)+ expect(host.clientId()).toBeNull()+ // Nothing the shell does afterwards fires it again.+ host.close()+ host.deny('denied')+ await settle()+ expect(counts.hostClosed).toBe(1)+ })++ it('fires onClose exactly once when the swap is found at open (the pin write was in flight), and never opens', async () => {+ const hostKeys = genKeyPair()+ const { hostT, peerT } = transportPair()+ const fa = fakeAttach()+ const counts = { opened: 0, hostClosed: 0, records: 0 }+ let finishPin!: () => void+ connectRelayHost({+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,+ autoApprove: () => true,+ pins: { record: () => { counts.records++; return new Promise<void>((r) => { finishPin = r }) } },+ onPeerPending: () => {}, onOpen: () => counts.opened++, onClose: () => counts.hostClosed+++ })+ connectRelayClient({+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => {}, onFrame: () => {},+ onPtyData: () => {}, onClose: () => {}+ })+ await vi.waitFor(() => expect(counts.records).toBe(1))+ swap.hostSeesPeerKey = publicKeyToB64(genKeyPair().publicKey)+ finishPin()+ await settle()++ expect(counts.opened).toBe(0)+ expect(fa.sinks.size).toBe(0)+ expect(counts.hostClosed).toBe(1)+ })+})diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.tsindex 8b0078b82..dad33d223 100644--- a/src/core/relay/relay-host.ts+++ b/src/core/relay/relay-host.ts@@ -88,7 +88,15 @@ export type AccessDecision = { allow: true; args?: unknown[] } | { allow: false;* for a req, dropped and logged for a cast. Only an ABSENT `access` hook means allow-all.*/export interface RelayHostHooks {- /** Answer a request here instead of dispatching it. `null` = not intercepted. */+ /**+ * Answer a request here instead of dispatching it. `null` = not intercepted.+ *+ * An intercepted request BYPASSES `access` and every project-scope jail below: nothing else looks+ * at it. An interceptor therefore enforces its own role and scope checks. The hosted team's do+ * (src/core/relay/hosted-service.ts): only `relay:hosted:self` is open to any approved peer;+ * approve, deny and invite-code are owner-only, judged from the CALLER's own session key in the+ * team store — never from anything the request carries.+ */interceptReq?(s: RelayHostSession, method: string, args: unknown[]): Promise<unknown> | null/** Allow (optionally rewriting args) or refuse a request/cast before any scope check or dispatch. */access?(s: RelayHostSession, kind: 'req' | 'cast', method: string, args: unknown[]): AccessDecision@@ -143,9 +151,11 @@ export interface ConnectRelayHostOptions {/** Mutually approved: the peer is a CorePlatform client of this core now. */onOpen(session: RelayHostSession): void/**- * The session ended without this shell asking: fires AT MOST ONCE, when the relay socket drops or- * when a throwing `wrapSink` fails the session closed. The peer is already torn down when it fires.- * `close()`, `deny()` and `killRelayHostsByPeerKey` NEVER fire it — their caller already knows.+ * The session ended without this shell asking: fires AT MOST ONCE, when the relay socket drops,+ * when a throwing `wrapSink` fails the session closed, or when the session key is found swapped+ * (the key-swap self-close). The peer is already torn down when it fires. `close()`, `deny()` and+ * `killRelayHostsByPeerKey` NEVER fire it — their caller already knows, and owes its own+ * bookkeeping for that end.*/onClose(): void}@@ -248,7 +258,12 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioif (keySwapped) return falseif (sessionPeerKey !== null && socket.peerPublicKeyB64() === sessionPeerKey) return truekeySwapped = true+ const wasLive = !closedsession.close()+ // A self-initiated close() never reaches the socket's onClose, and the shell did not ask for this+ // one: tell it, at most once (the wrapSink fail-closed rule). Its bookkeeping (a seat, a pending+ // request, a standing listener counted as bridged) must hear every end.+ if (wasLive) opts.onClose()return false}