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): fail closed on malformed access, log dropped casts, no late open after a drop

review322c63929c51
diff --git a/src/core/relay/relay-host.core.test.ts b/src/core/relay/relay-host.core.test.ts
index c81b40bfc..33ba304c3 100644
--- a/src/core/relay/relay-host.core.test.ts
+++ b/src/core/relay/relay-host.core.test.ts
@@ -430,3 +430,105 @@ describe('core relay host — a throwing hook or dispatch never wedges the sessi
expect(s.clientId()).toBeNull()
})
})
+
+describe('core relay host — review round 2 (cast logging, R12 malformed decisions, R13 late open)', () => {
+ it('a throwing access hook on a cast is LOGGED, never swallowed silently', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const t = open({
+ autoApprove: () => true,
+ hooks: { access: (_s, kind) => { if (kind === 'cast') throw new Error('nope'); return { allow: true } } }
+ }, true)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(JSON.stringify({ t: 'cast', method: 'pty:write', args: ['s1', 'x'] }))
+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith('[relay-host] access threw on cast pty:write:', 'nope'))
+ expect(t.fa.casts).toEqual([])
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('R12: a malformed access decision DENIES — E_ROLE for a req, dropped for a cast; only an absent hook allows all', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const returns: Record<string, unknown> = {
+ undef: undefined, nul: null, empty: {}, badArgs: { allow: true, args: 'x' }, noMsg: { allow: false }
+ }
+ const t = open({
+ autoApprove: () => true,
+ hooks: {
+ access: (_s, _k, method) =>
+ (method in returns ? returns[method] : { allow: true }) as ReturnType<NonNullable<import('./relay-host').RelayHostHooks['access']>>
+ }
+ }, true)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ const names = Object.keys(returns)
+ names.forEach((m, i) => t.client.send(JSON.stringify({ t: 'req', id: 100 + i, method: m, args: [] })))
+ for (const m of names) t.client.send(JSON.stringify({ t: 'cast', method: m, args: [] }))
+ // Positive controls, sent AFTER: once they arrive, every malformed frame had its turn.
+ t.client.send(JSON.stringify({ t: 'cast', method: 'fine', args: [] }))
+ t.client.send(JSON.stringify({ t: 'req', id: 200, method: 'fine', args: [] }))
+ await vi.waitFor(() => expect(t.frames.some((f) => JSON.parse(f).id === 200)).toBe(true))
+ const res = t.frames.map((f) => JSON.parse(f))
+ for (let i = 0; i < names.length; i++) {
+ expect(res.find((r) => r.id === 100 + i)).toMatchObject({
+ ok: false, error: { code: 'E_ROLE', message: 'Access check failed.' }
+ })
+ }
+ expect(t.fa.dispatched.map((r) => r.method)).toEqual(['fine'])
+ expect(t.fa.casts).toEqual([{ method: 'fine', args: [] }])
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ /** A host whose pin write the test finishes by hand, so the peer can drop while it is in flight. */
+ function openWithDeferredPin(hooks?: Parameters<typeof connectRelayHost>[0]['hooks']) {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const fa = fakeAttach()
+ const counts = { hostOpened: 0, hostClosed: 0, records: 0 }
+ let finishPin!: () => void
+ const host = connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,
+ autoApprove: () => true, hooks,
+ pins: { record: () => { counts.records++; return new Promise<void>((r) => { finishPin = r }) } },
+ onPeerPending: () => {}, onOpen: () => counts.hostOpened++, 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: () => {}
+ })
+ return { host, client, fa, counts, finishPin: () => finishPin() }
+ }
+ const settle = () => new Promise((r) => setTimeout(r, 20))
+
+ it('R13(a): a peer that drops during the pin write fires onClose ONCE, even when wrapSink then throws', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const t = openWithDeferredPin({ wrapSink: () => { throw new Error('filter exploded') } })
+ await vi.waitFor(() => expect(t.counts.records).toBe(1)) // both confirmed; the pin write is in flight
+ t.client.close() // the peer drops
+ expect(t.counts.hostClosed).toBe(1)
+ t.finishPin() // the pin write lands AFTER the drop
+ await settle()
+ expect(t.counts.hostClosed).toBe(1) // no late second fire from the wrapSink fail-closed path
+ expect(t.counts.hostOpened).toBe(0)
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('R13(b): a peer that drops during the pin write is never attached to the dead socket', async () => {
+ const t = openWithDeferredPin()
+ await vi.waitFor(() => expect(t.counts.records).toBe(1))
+ t.client.close()
+ t.finishPin()
+ await settle()
+ expect(t.fa.sinks.size).toBe(0) // nothing attached (and so nothing leaks: detach already ran)
+ expect(t.counts.hostOpened).toBe(0)
+ expect(t.host.clientId()).toBeNull()
+ expect(t.counts.hostClosed).toBe(1)
+ })
+})
diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.ts
index 62d5989e0..8b0078b82 100644
--- a/src/core/relay/relay-host.ts
+++ b/src/core/relay/relay-host.ts
@@ -65,6 +65,9 @@ export interface PeerAttach {
/** Answer the peer's request. May REJECT (or throw): the host answers that request `E_HANDLER`
* and the session keeps serving — a failed dispatch never goes unanswered or unhandled. */
dispatch(id: number, req: RpcRequest): Promise<RpcOk | RpcErr>
+ /** Deliver the peer's cast. Must NOT throw: the tunnel cast path and the teardown's board-log
+ * unsubscribe replay call it unguarded (a cast has no reply channel — isolate and log inside,
+ * as both platforms' `cast` already do). */
cast(id: number, method: string, args: unknown[]): void
}
@@ -77,8 +80,12 @@ export type AccessDecision = { allow: true; args?: unknown[] } | { allow: false;
* A hook that THROWS never reaches the socket (a throw there escapes into the WebSocket's own
* synchronous message emit, which then delivers nothing more and never closes: the peer hangs and
* stays attached). Instead: `interceptReq` / `access` on a req → the request is answered
- * `E_HANDLER`; `access` on a cast → the cast is dropped; `narrowResponse` → `E_HANDLER`, never the
- * un-narrowed result; `wrapSink` → the session FAILS CLOSED (see `open`).
+ * `E_HANDLER`; `access` on a cast → the cast is dropped and logged; `narrowResponse` → `E_HANDLER`,
+ * never the un-narrowed result; `wrapSink` → the session FAILS CLOSED (see `open`).
+ *
+ * `access` FAILS CLOSED on a malformed answer too: anything but a well-formed `AccessDecision`
+ * (`undefined`, `null`, `{}`, non-array `args`, a refusal without a `message`) DENIES — `E_ROLE`
+ * 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. */
@@ -135,12 +142,34 @@ export interface ConnectRelayHostOptions {
onPeerPending(session: RelayHostSession): void
/** Mutually approved: the peer is a CorePlatform client of this core now. */
onOpen(session: RelayHostSession): void
- /** The relay socket dropped (the peer is already torn down when this fires). */
+ /**
+ * 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.
+ */
onClose(): void
}
const errorMessage = (err: unknown): string => (err instanceof Error ? err.message : String(err))
+/** A well-formed `AccessDecision` — anything else from an `access` hook is a DENIAL (R12). */
+function isAccessDecision(d: unknown): d is AccessDecision {
+ if (typeof d !== 'object' || d === null) return false
+ const o = d as { allow?: unknown; args?: unknown; message?: unknown }
+ if (o.allow === true) return o.args === undefined || Array.isArray(o.args)
+ if (o.allow === false) return typeof o.message === 'string'
+ return false
+}
+
+/** The access hook's verdict: decided, threw, or answered something that is not a decision. */
+type AccessVerdict =
+ | { kind: 'decided'; decision: AccessDecision }
+ | { kind: 'threw'; err: unknown }
+ | { kind: 'malformed' }
+
+/** The refusal a req gets when the access hook's answer is not a decision (never its raw value). */
+const ACCESS_CHECK_FAILED = 'Access check failed.'
+
/** Live bridged peers, for revocation: unpinning a key refuses the NEXT handshake, but the OPEN
* socket keeps full shell access until it is cut (see revocation.ts). */
const live = new Set<RelayHostSession>()
@@ -286,6 +315,19 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
const handlerError = (id: number, err: unknown): string =>
JSON.stringify({ t: 'res', id, ok: false, error: { code: 'E_HANDLER', message: errorMessage(err) } })
+ /** Ask the access hook, and never let it throw or mis-answer its way into the socket: a throw is
+ * `threw`, a malformed answer is `malformed` (both deny). Only an ABSENT hook allows all. */
+ const checkAccess = (kind: 'req' | 'cast', method: string, args: unknown[]): AccessVerdict => {
+ if (!opts.hooks?.access) return { kind: 'decided', decision: { allow: true } }
+ let answer: unknown
+ try {
+ answer = opts.hooks.access(session, kind, method, args)
+ } catch (err) {
+ return { kind: 'threw', err }
+ }
+ return isAccessDecision(answer) ? { kind: 'decided', decision: answer } : { kind: 'malformed' }
+ }
+
/** Send the response `build` produces. If building or serialising it throws (a narrowResponse hook,
* an unserialisable result), answer `E_HANDLER` instead. Never throws: it runs inside a `.then`,
* where a throw would be an unhandled rejection and a request nobody ever answers. */
@@ -427,13 +469,17 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
)
return
}
- let decision: AccessDecision
- try {
- decision = opts.hooks?.access?.(session, 'req', m.method, m.args) ?? { allow: true as const }
- } catch (err) {
- socket.sendTunnelText(handlerError(m.id, err))
+ const verdict = checkAccess('req', m.method, m.args)
+ if (verdict.kind === 'threw') {
+ socket.sendTunnelText(handlerError(m.id, verdict.err))
+ return
+ }
+ if (verdict.kind === 'malformed') {
+ console.warn(`[relay-host] access returned a malformed decision on req ${m.method}; refused`)
+ socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: false, error: { code: 'E_ROLE', message: ACCESS_CHECK_FAILED } }))
return
}
+ const decision = verdict.decision
if (!decision.allow) {
socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: false, error: { code: 'E_ROLE', message: decision.message } }))
return
@@ -466,12 +512,19 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
(err) => socket.sendTunnelText(handlerError(m.id, err))
)
} else if (m.t === 'cast') {
- let d: AccessDecision
- try {
- d = opts.hooks?.access?.(session, 'cast', m.method, m.args) ?? { allow: true as const }
- } catch {
- return // a cast has no reply channel: a policy that cannot decide drops it
+ // A cast has no reply channel: a policy that throws or cannot decide DROPS it — and says so,
+ // because a silently dropped pty:write swallows keystrokes with nothing in any log (the same
+ // reason both platforms log a throwing cast listener).
+ const verdict = checkAccess('cast', m.method, m.args)
+ if (verdict.kind === 'threw') {
+ console.warn(`[relay-host] access threw on cast ${m.method}:`, errorMessage(verdict.err))
+ return
}
+ if (verdict.kind === 'malformed') {
+ console.warn(`[relay-host] access returned a malformed decision on cast ${m.method}; dropped`)
+ return
+ }
+ const d = verdict.decision
if (!d.allow) return
const args = d.args ?? m.args
if (projectOutOfScope(m.method, args)) return
@@ -494,7 +547,11 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
// res/ev from a peer are ignored (mirrors src/server/ws.ts).
},
onClose: () => {
- // The peer is GONE — the same state a closed browser tab leaves the core in.
+ // The peer is GONE — the same state a closed browser tab leaves the core in. Mark the session
+ // closed FIRST: a gate whose pin write is still in flight will call open() later, and open()
+ // must then bail — never attach the peer to this dead socket, and never reach the wrapSink
+ // fail-closed path that would fire onClose a second time (R13).
+ closed = true
live.delete(session)
detach()
opts.onClose()