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): hold a peer's frames between approval and open; defer a pre-socket client confirm

reviewc738a4ec2b19
diff --git a/src/core/relay/relay-client.ts b/src/core/relay/relay-client.ts
index 46619799e..ca966484b 100644
--- a/src/core/relay/relay-client.ts
+++ b/src/core/relay/relay-client.ts
@@ -90,8 +90,8 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient
let socket: RelaySocket | null = null
// Everything that can happen in that window and needs the socket is settled right after
// `connectRelay` returns (see the end of this function):
- // - our auto-approve confirm: sent inside onReady it would ride `socket?.` into nothing, the host
- // would never hear it, and a pinned reconnect would never open;
+ // - our confirm, auto-approved or a human's made inside `onSas`: sent inside onReady it would
+ // ride `socket?.` into nothing, the host would never hear it, and nothing would open there;
// - tunnel frames and the close: the host may answer inside its own onReady (a denial, its own
// confirm) and even close. Such a frame cannot pass peerKeyIntact() without a socket to read the
// live key from, so it is HELD here, in arrival order, and replayed through the same path.
@@ -111,7 +111,16 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient
const session: RelayClientSession = {
sas: () => gate?.sas() ?? null,
peerKeyB64: () => gate?.peerKeyB64() ?? null,
- confirm: () => gate?.confirmHere(),
+ confirm: () => {
+ // A confirm made before we hold our socket (in-process, `onSas` runs inside connectRelay)
+ // would latch OUR half while its frame went nowhere: this side then opens on the host's
+ // confirm and the host never does. Defer it exactly like the auto-approve one.
+ if (!socket) {
+ if (gate) confirmOwed = true
+ return
+ }
+ gate?.confirmHere()
+ },
send: (json) => {
if (!opened || closed || !socket) return false
return socket.sendTunnelText(json)
@@ -142,7 +151,8 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient
opts.onApproved(session)
}
- /** Our auto-approve confirm (never a human's): sent only once `socket` exists, see `confirmOwed`. */
+ /** Our owed confirm (the auto-approve one, or a human's made before the socket existed): sent
+ * only once `socket` exists, see `confirmOwed`. */
const autoConfirm = (): void => {
if (!closed) gate?.confirmHere()
}
diff --git a/src/core/relay/relay-host.core.test.ts b/src/core/relay/relay-host.core.test.ts
index 33ba304c3..aabade1c3 100644
--- a/src/core/relay/relay-host.core.test.ts
+++ b/src/core/relay/relay-host.core.test.ts
@@ -1,6 +1,6 @@
// src/core/relay/relay-host.core.test.ts
import { describe, it, expect, vi } from 'vitest'
-import { connectRelayHost, killRelayHostsByPeerKey, type PeerAttach, type RelayHostSession } from './relay-host'
+import { connectRelayHost, killRelayHostsByPeerKey, HELD_FRAMES_MAX, type PeerAttach, type RelayHostSession } from './relay-host'
import { connectRelayClient } from './relay-client'
import { transportPair } from './transport-pair'
import { genKeyPair, publicKeyToB64 } from './e2ee'
@@ -532,3 +532,187 @@ describe('core relay host — review round 2 (cast logging, R12 malformed decisi
expect(t.counts.hostClosed).toBe(1)
})
})
+
+describe('core relay host — frames between approval and open are held, not refused (R24)', () => {
+ /** Both ends auto-approve; the host's pin write is finished by hand. `onApproved` runs on the
+ * CLIENT, which opens before the host while the host's pin write is in flight. */
+ function openWithSlowPin(onApproved: (c: ReturnType<typeof connectRelayClient>) => void = () => {}) {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const fa = fakeAttach()
+ const frames: string[] = []
+ const counts = { hostOpened: 0, hostClosed: 0, clientClosed: 0, records: 0, clientApproved: 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,
+ pins: { record: () => { counts.records++; return new Promise<void>((r) => { finishPin = r }) } },
+ onPeerPending: () => {}, onOpen: () => counts.hostOpened++, onClose: () => counts.hostClosed++
+ })
+ const client: ReturnType<typeof connectRelayClient> = connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: true, onSas: () => {},
+ onApproved: (s) => { counts.clientApproved++; onApproved(s as ReturnType<typeof connectRelayClient>) },
+ onFrame: (j) => frames.push(j), onPtyData: () => {}, onClose: () => counts.clientClosed++
+ })
+ const res = (id: number) => frames.map((f) => JSON.parse(f)).find((m) => m.t === 'res' && m.id === id)
+ return { host, client, fa, frames, res, counts, finishPin: () => finishPin() }
+ }
+ const settle = () => new Promise((r) => setTimeout(r, 20))
+
+ it('a request sent at the client’s onApproved, during a slow pin, is answered after open — not refused', async () => {
+ const t = openWithSlowPin((c) => {
+ c.send(JSON.stringify({ t: 'req', id: 1, method: 'first', args: [] }))
+ })
+ await vi.waitFor(() => expect(t.counts.clientApproved).toBe(1))
+ expect(t.counts.records).toBe(1) // the host's pin write is in flight
+ await settle()
+ expect(t.res(1)).toBeUndefined() // held: neither refused nor served before open
+ expect(t.fa.dispatched).toEqual([])
+ t.finishPin()
+ await vi.waitFor(() => expect(t.res(1)).toMatchObject({ ok: true, result: 'ok' }))
+ expect(t.counts.hostOpened).toBe(1)
+ })
+
+ it('held frames run in arrival order, through the same access path as live ones', async () => {
+ const seen: string[] = []
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const fa = fakeAttach()
+ const frames: string[] = []
+ let finishPin!: () => void
+ let approved = false
+ let opened = false
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,
+ autoApprove: () => true,
+ pins: { record: () => new Promise<void>((r) => { finishPin = r }) },
+ hooks: {
+ access: (_s, kind, method) => {
+ seen.push(`${kind}:${method}`)
+ return method === 'refused' ? { allow: false, message: 'no' } : { allow: true }
+ }
+ },
+ onPeerPending: () => {}, onOpen: () => { opened = true }, onClose: () => {}
+ })
+ const client = connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => { approved = true },
+ onFrame: (j) => frames.push(j), onPtyData: () => {}, onClose: () => {}
+ })
+ await vi.waitFor(() => expect(approved).toBe(true))
+ client.send(JSON.stringify({ t: 'req', id: 1, method: 'a', args: [] }))
+ client.send(JSON.stringify({ t: 'cast', method: 'b', args: [] }))
+ client.send(JSON.stringify({ t: 'req', id: 2, method: 'refused', args: [] }))
+ client.send(JSON.stringify({ t: 'req', id: 3, method: 'c', args: [] }))
+ await settle()
+ expect(seen).toEqual([]) // nothing is judged, let alone served, before open
+ finishPin()
+ await vi.waitFor(() => expect(frames.some((f) => JSON.parse(f).id === 3)).toBe(true))
+ expect(opened).toBe(true)
+ expect(seen).toEqual(['req:a', 'cast:b', 'req:refused', 'req:c'])
+ expect(fa.dispatched.map((r) => r.method)).toEqual(['a', 'c'])
+ expect(fa.casts).toEqual([{ method: 'b', args: [] }])
+ expect(frames.map((f) => JSON.parse(f)).find((m) => m.id === 2)).toMatchObject({ ok: false, error: { code: 'E_ROLE' } })
+ })
+
+ it('the held queue is dropped when the peer drops before open', async () => {
+ const t = openWithSlowPin((c) => {
+ c.send(JSON.stringify({ t: 'req', id: 1, method: 'x', args: [] }))
+ c.send(JSON.stringify({ t: 'cast', method: 'y', args: [] }))
+ })
+ await vi.waitFor(() => expect(t.counts.clientApproved).toBe(1))
+ t.client.close()
+ t.finishPin()
+ await settle()
+ expect(t.fa.dispatched).toEqual([])
+ expect(t.fa.casts).toEqual([])
+ expect(t.fa.sinks.size).toBe(0)
+ expect(t.counts.hostOpened).toBe(0)
+ })
+
+ it('the held queue is dropped when the shell closes the session before open', async () => {
+ const t = openWithSlowPin((c) => {
+ c.send(JSON.stringify({ t: 'req', id: 1, method: 'x', args: [] }))
+ })
+ await vi.waitFor(() => expect(t.counts.clientApproved).toBe(1))
+ t.host.close()
+ t.finishPin()
+ await settle()
+ expect(t.fa.dispatched).toEqual([])
+ expect(t.counts.hostOpened).toBe(0)
+ expect(t.counts.hostClosed).toBe(0) // the shell asked for this close
+ })
+
+ it('an overflowing queue closes the session (and tells the shell once); nothing is served', async () => {
+ const t = openWithSlowPin((c) => {
+ for (let i = 0; i <= HELD_FRAMES_MAX; i++) c.send(JSON.stringify({ t: 'cast', method: 'flood', args: [i] }))
+ })
+ await vi.waitFor(() => expect(t.counts.clientApproved).toBe(1))
+ await vi.waitFor(() => expect(t.counts.hostClosed).toBe(1))
+ expect(t.counts.clientClosed).toBe(1)
+ t.finishPin()
+ await settle()
+ expect(t.fa.casts).toEqual([])
+ expect(t.fa.sinks.size).toBe(0)
+ expect(t.counts.hostOpened).toBe(0)
+ expect(t.counts.hostClosed).toBe(1)
+ })
+
+ it('exactly HELD_FRAMES_MAX held frames is not an overflow', async () => {
+ const t = openWithSlowPin((c) => {
+ for (let i = 0; i < HELD_FRAMES_MAX; i++) c.send(JSON.stringify({ t: 'cast', method: 'burst', args: [i] }))
+ })
+ await vi.waitFor(() => expect(t.counts.clientApproved).toBe(1))
+ t.finishPin()
+ await vi.waitFor(() => expect(t.fa.casts).toHaveLength(HELD_FRAMES_MAX))
+ expect(t.fa.casts.map((c) => c.args[0])).toEqual([...Array(HELD_FRAMES_MAX).keys()])
+ expect(t.counts.hostClosed).toBe(0)
+ })
+
+ it('a request before approval is still refused E_UNAUTHORIZED, never held', async () => {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const fa = fakeAttach()
+ let opened = false
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,
+ onPeerPending: () => {}, onOpen: () => { opened = true }, onClose: () => {}
+ })
+ const frames: string[] = []
+ const peer = connectRelay({
+ url: 'ws://127.0.0.1/x', token: 't', role: 'client', ourKeys: genKeyPair(),
+ theirPubB64: publicKeyToB64(hostKeys.publicKey), transport: peerT,
+ onReady: () => {}, onRpc: () => {}, onFrame: () => {}, onClose: () => {},
+ onTunnel: (kind, payload) => { if (kind === 'text') frames.push(new TextDecoder().decode(payload)) }
+ })
+ peer.sendTunnelText(JSON.stringify({ t: 'req', id: 1, method: 'x', args: [] }))
+ await vi.waitFor(() => expect(frames.length).toBe(1))
+ expect(JSON.parse(frames[0])).toMatchObject({ id: 1, ok: false, error: { code: 'E_UNAUTHORIZED' } })
+ expect(fa.dispatched).toEqual([])
+ expect(opened).toBe(false)
+ })
+})
+
+describe('core relay client — a confirm made before the client holds its socket (R29)', () => {
+ it('a human confirm inside onSas (in-process: before the socket exists) still reaches the host', async () => {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const opened: string[] = []
+ let hostSession!: RelayHostSession
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fakeAttach().attach, transport: hostT,
+ onPeerPending: (s) => { hostSession = s }, onOpen: () => opened.push('host'), onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: false,
+ onSas: (s) => s.confirm(), // synchronous: over this transport, connectRelay has not returned yet
+ onApproved: () => opened.push('peer'), onFrame: () => {}, onPtyData: () => {}, onClose: () => {}
+ })
+ await new Promise((r) => setTimeout(r, 20))
+ expect(opened).toEqual([]) // the host's human has not answered
+ hostSession.confirm()
+ await vi.waitFor(() => expect(opened.sort()).toEqual(['host', 'peer']))
+ })
+})
diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.ts
index dad33d223..b579616ed 100644
--- a/src/core/relay/relay-host.ts
+++ b/src/core/relay/relay-host.ts
@@ -23,8 +23,10 @@
// reach any channel the shell registered on the platform) only from the trust gate's `onOpen`, i.e.
// after BOTH humans compared the same SAS and pressed Confirm. The E2EE handshake completing
// (`onReady`) proves only that SOMEONE holds the pairing token — a pre-approval request is answered
-// with E_UNAUTHORIZED and never touches a handler. A pairing grants shell access; the SAS is the
-// only thing between a relay MITM and that shell.
+// with E_UNAUTHORIZED and never touches a handler. Between mutual approval and `onOpen` (the pin
+// write is in flight) the peer's frames are HELD, not refused, and served at open through the same
+// checks as live ones — still nothing before it (see HELD_FRAMES_MAX). A pairing grants shell
+// access; the SAS is the only thing between a relay MITM and that shell.
//
// SCOPE: this is the DESKTOP-peer vocabulary (the invited peer is fully trusted, as the invite copy
// states). The standing PHONE host keeps its existing legacy vocabulary in `host-service.ts` — with
@@ -43,6 +45,7 @@ import type { UiSink } from '../ui-sink-registry'
import {
E_UNAUTHORIZED,
parseRpcMessage,
+ type RpcCast,
type RpcErr,
type RpcOk,
type RpcRequest
@@ -152,8 +155,9 @@ export interface ConnectRelayHostOptions {
onOpen(session: RelayHostSession): void
/**
* 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
+ * when a throwing `wrapSink` fails the session closed, when the session key is found swapped (the
+ * key-swap self-close), or when the peer overflows the frames held between approval and open
+ * (`HELD_FRAMES_MAX`). 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.
*/
@@ -180,6 +184,15 @@ type AccessVerdict =
/** 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.'
+/**
+ * How many req/cast frames a peer may send between mutual approval and `open` (while the pin write
+ * is in flight) before the session is closed. Those frames are HELD, not refused: a client opens as
+ * soon as it has the host's confirm, so the first thing a new teammate sends (`workspace:load` at
+ * `onApproved`) routinely lands inside the host's pin write. Bounded, because nothing reads them
+ * until the pin settles.
+ */
+export const HELD_FRAMES_MAX = 256
+
/** 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>()
@@ -216,6 +229,10 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
// below this connection's own contribution (an unbalanced guest unsubscribe is ignored).
const boardLogSubs = new Map<string, number>()
+ // Frames the peer sent after BOTH humans approved but before `open` (the pin write is in flight).
+ // Served in arrival order at `open`, through the same path as live frames; dropped with the session.
+ const held: Array<RpcRequest | RpcCast> = []
+
/** The ONE teardown, mirroring src/server/ws.ts's close path exactly: `attach.detach` IS the three
* steps (presence leave → onPeerGone → PtyManager.dropClient → registry prune). Do NOT
* re-implement them here. */
@@ -246,24 +263,31 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
close() {
if (closed) return
closed = true
+ held.length = 0
live.delete(session)
detach()
socket.close()
}
}
+ /** End the session on the core's own initiative (a swapped key, a throwing wrapSink, a flooded
+ * hold queue). A self-initiated close() never reaches the socket's onClose, and the shell did not
+ * ask for this one: tell it, at most once, and never for a session that was already closed. Its
+ * bookkeeping (a seat, a pending request, a standing listener counted as bridged) must hear every
+ * end. */
+ const closeUnasked = (): void => {
+ const wasLive = !closed
+ session.close()
+ if (wasLive) opts.onClose()
+ }
+
/** The socket's live peer key still matches the one bound into the gate/approval state. A false
* return means the session key was swapped under us — refuse everything and cut the session. */
const peerKeyIntact = (): boolean => {
if (keySwapped) return false
if (sessionPeerKey !== null && socket.peerPublicKeyB64() === sessionPeerKey) return true
keySwapped = true
- const wasLive = !closed
- session.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()
+ closeUnasked()
return false
}
@@ -297,17 +321,21 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
} catch (err) {
// FAIL CLOSED. A wrapSink is a FILTER (a viewer's view of the host); falling back to the bare
// base sink would hand the peer everything the filter exists to withhold. Attach nothing and
- // end the session. A self-initiated close() never reaches the socket's onClose, so tell the
- // shell here — it did not ask for this, and its bookkeeping (a seat, a dialog) must hear it.
+ // end the session, and tell the shell (closeUnasked).
console.warn(`[relay-host] wrapSink threw; closing the session: ${errorMessage(err)}`)
- session.close()
- opts.onClose()
+ closeUnasked()
return
}
}
const id = opts.attach.attach(sink)
clientId = id
opts.onOpen(session)
+ // What the peer sent while the pin was being written, in arrival order, exactly as if it had
+ // arrived now. A frame that ends the session stops the rest.
+ for (const m of held.splice(0)) {
+ if (closed || clientId === null) break
+ serve(m)
+ }
}
/** UX scope, NOT a trust boundary: for the ONE `workspace:load` method, when this hosting session
@@ -390,6 +418,105 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
}
})
+ /** Serve one req/cast of an OPEN session: interceptor, access, scope jails, then dispatch/cast.
+ * Live frames and held ones (see `held`) both come through here, so they meet the same checks. */
+ const serve = (m: RpcRequest | RpcCast): void => {
+ if (clientId === null) return
+ if (m.t === 'req') {
+ // A hook may answer the request itself — it then never reaches a scope check or the core.
+ // Every hook call below is guarded: a throw is ANSWERED (E_HANDLER), never let into the
+ // socket's message emit (see RelayHostHooks).
+ let intercepted: Promise<unknown> | null
+ try {
+ intercepted = opts.hooks?.interceptReq?.(session, m.method, m.args) ?? null
+ } catch (err) {
+ socket.sendTunnelText(handlerError(m.id, err))
+ return
+ }
+ if (intercepted) {
+ void intercepted.then(
+ (result) => respond(m.id, () => ({ t: 'res', id: m.id, ok: true, result: result ?? null })),
+ (err) => socket.sendTunnelText(handlerError(m.id, err))
+ )
+ return
+ }
+ 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
+ }
+ const args = decision.args ?? m.args
+ // Board-log read/append naming a project outside this session's scope: refuse WITHOUT
+ // dispatching (the host router never resolves it), degrading exactly as an unknown project.
+ // Checked before the generic jail so these two keep their established degraded shape.
+ if (
+ (m.method === IPC.boardLogAppend || m.method === IPC.boardLogRead) &&
+ boardLogOutOfScope(args[0])
+ ) {
+ socket.sendTunnelText(JSON.stringify(boardLogRefusal(m.method, m.id)))
+ return
+ }
+ if (projectOutOfScope(m.method, args)) {
+ socket.sendTunnelText(JSON.stringify(projectScopeRefusal(m.method, m.id)))
+ return
+ }
+ const id = clientId
+ let pending: Promise<RpcOk | RpcErr>
+ try {
+ pending = opts.attach.dispatch(id, { ...m, args })
+ } catch (err) {
+ socket.sendTunnelText(handlerError(m.id, err))
+ return
+ }
+ void pending.then(
+ (res) => respond(m.id, () => narrowResponse(m.method, scopeResponse(m.method, res))),
+ (err) => socket.sendTunnelText(handlerError(m.id, err))
+ )
+ } else if (m.t === 'cast') {
+ // 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
+ // Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this
+ // connection's net per-project count so a dropped guest's watch is released in detach().
+ if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {
+ const projectId = args[0]
+ if (typeof projectId !== 'string' || boardLogOutOfScope(projectId)) return
+ if (m.method === IPC.boardLogSubscribe) {
+ boardLogSubs.set(projectId, (boardLogSubs.get(projectId) ?? 0) + 1)
+ } else {
+ const cur = boardLogSubs.get(projectId) ?? 0
+ if (cur <= 0) return // this connection holds no such watch — never decrement the shared count
+ if (cur === 1) boardLogSubs.delete(projectId)
+ else boardLogSubs.set(projectId, cur - 1)
+ }
+ }
+ opts.attach.cast(clientId, m.method, args)
+ }
+ }
+
const socket = connectRelay({
url: opts.url,
token: opts.token,
@@ -453,6 +580,18 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
const m = parseRpcMessage(json)
if (!m) return
if (clientId === null) {
+ // Mutually approved, not yet open (the pin write is in flight): HOLD, never refuse — the
+ // client is already open and its first request would otherwise fail. Nothing is judged or
+ // served before `open`; a peer that floods the hold is cut.
+ if (gate?.isApproved() && (m.t === 'req' || m.t === 'cast')) {
+ if (held.length >= HELD_FRAMES_MAX) {
+ console.warn(`[relay-host] a peer sent more than ${HELD_FRAMES_MAX} frames before its session opened; closing it`)
+ closeUnasked()
+ return
+ }
+ held.push(m)
+ return
+ }
// Not mutually approved: refuse — but ANSWER, or the peer's `await` would hang forever.
if (m.t === 'req') {
socket.sendTunnelText(
@@ -466,100 +605,8 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
}
return
}
- if (m.t === 'req') {
- // A hook may answer the request itself — it then never reaches a scope check or the core.
- // Every hook call below is guarded: a throw is ANSWERED (E_HANDLER), never let into the
- // socket's message emit (see RelayHostHooks).
- let intercepted: Promise<unknown> | null
- try {
- intercepted = opts.hooks?.interceptReq?.(session, m.method, m.args) ?? null
- } catch (err) {
- socket.sendTunnelText(handlerError(m.id, err))
- return
- }
- if (intercepted) {
- void intercepted.then(
- (result) => respond(m.id, () => ({ t: 'res', id: m.id, ok: true, result: result ?? null })),
- (err) => socket.sendTunnelText(handlerError(m.id, err))
- )
- return
- }
- 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
- }
- const args = decision.args ?? m.args
- // Board-log read/append naming a project outside this session's scope: refuse WITHOUT
- // dispatching (the host router never resolves it), degrading exactly as an unknown project.
- // Checked before the generic jail so these two keep their established degraded shape.
- if (
- (m.method === IPC.boardLogAppend || m.method === IPC.boardLogRead) &&
- boardLogOutOfScope(args[0])
- ) {
- socket.sendTunnelText(JSON.stringify(boardLogRefusal(m.method, m.id)))
- return
- }
- if (projectOutOfScope(m.method, args)) {
- socket.sendTunnelText(JSON.stringify(projectScopeRefusal(m.method, m.id)))
- return
- }
- const id = clientId
- let pending: Promise<RpcOk | RpcErr>
- try {
- pending = opts.attach.dispatch(id, { ...m, args })
- } catch (err) {
- socket.sendTunnelText(handlerError(m.id, err))
- return
- }
- void pending.then(
- (res) => respond(m.id, () => narrowResponse(m.method, scopeResponse(m.method, res))),
- (err) => socket.sendTunnelText(handlerError(m.id, err))
- )
- } else if (m.t === 'cast') {
- // 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
- // Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this
- // connection's net per-project count so a dropped guest's watch is released in detach().
- if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {
- const projectId = args[0]
- if (typeof projectId !== 'string' || boardLogOutOfScope(projectId)) return
- if (m.method === IPC.boardLogSubscribe) {
- boardLogSubs.set(projectId, (boardLogSubs.get(projectId) ?? 0) + 1)
- } else {
- const cur = boardLogSubs.get(projectId) ?? 0
- if (cur <= 0) return // this connection holds no such watch — never decrement the shared count
- if (cur === 1) boardLogSubs.delete(projectId)
- else boardLogSubs.set(projectId, cur - 1)
- }
- }
- opts.attach.cast(clientId, m.method, args)
- }
// res/ev from a peer are ignored (mirrors src/server/ws.ts).
+ if (m.t === 'req' || m.t === 'cast') serve(m)
},
onClose: () => {
// The peer is GONE — the same state a closed browser tab leaves the core in. Mark the session
@@ -567,6 +614,7 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
// 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
+ held.length = 0
live.delete(session)
detach()
opts.onClose()
diff --git a/src/core/relay/relay-trust.ts b/src/core/relay/relay-trust.ts
index 0191d2e3f..d44ba902a 100644
--- a/src/core/relay/relay-trust.ts
+++ b/src/core/relay/relay-trust.ts
@@ -74,6 +74,12 @@ export interface TrustGate {
* Call this ONLY from `connectRelay`'s `onTunnel`. See the SECURITY block above.
*/
onTunnelText(json: string): boolean
+ /**
+ * Both humans confirmed. Latched the moment the second confirm arrives, BEFORE the pin write and
+ * `onOpen`: true while the pin is still in flight, and it never goes back to false. A host uses it
+ * to tell "approved, opening" (hold the peer's frames) from "not approved" (refuse them).
+ */
+ isApproved(): boolean
/**
* Both humans confirmed → the pin attempt has settled and `onOpen` has fired. True exactly when
* `onOpen` has run: never while the pin write is still in flight.
@@ -168,6 +174,7 @@ export function createTrustGate(opts: TrustGateOptions): TrustGate {
settle()
return true // consumed: a trust frame is NEVER forwarded to the RPC dispatcher
},
+ isApproved: () => approved,
isOpen: () => opened,
peerKeyB64: () => opts.peerKeyB64
}