Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(relay): client-side connector connectRelayClient (Stage 4 Task 3)

enes084bd041300e
diff --git a/src/main/index.ts b/src/main/index.ts
index 7e55cc09f..5567554fe 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -68,6 +68,9 @@ import { initRelayHost } from './remote/relay-host-service'
import { createRevoker } from './remote/revocation'
import { loadApprovedDevices, saveApprovedDevices } from './remote/approved-devices'
import { initRemoteClient } from './remote/client-service'
+import { connectRelayClient, type RelayClientSession } from './remote/relay-client'
+import { decodeOffer } from './remote/pairing'
+import { loadOrCreatePeerKeyPair } from './remote/peer-identity'
import { initSshProject } from './remote-ssh/ssh-project'
import { setGitRemoteResolver, type GitRemoteRef } from '../core/remote-ssh/remote-git'
import { SshFs } from './ssh-fs'
@@ -1028,6 +1031,66 @@ app.whenReady().then(async () => {
// Reconcile from persisted settings on launch (starts hosting if enabled + Pro).
standingHost.syncFromSettings()
initRemoteClient(win, { isPackaged: app.isPackaged })
+ // NEW interactive relay CLIENT (Stage 4): connect OUT to another desktop's host. `connectRelayClient`
+ // runs the client half of mutual SAS approval and, once BOTH humans confirm, exposes the raw rpc.ts
+ // frame pipe (`relay:client:send`/`relay:client:frame`) that Task 4's RpcClient drives. Runs BESIDE
+ // the legacy client (initRemoteClient). Inert until `relay:client:connect` — a solo user pays nothing.
+ {
+ const relayClients = new Map<string, RelayClientSession>()
+ const sendTo = (channel: string, ...args: unknown[]): void => {
+ if (!win.isDestroyed()) win.webContents.send(channel, ...args)
+ }
+ ipcMain.handle(IPC.relayClientConnect, async (_e, offerCode: string): Promise<string> => {
+ // No Pro gate on the client: the paywall is the HOST minting the pairing token, so a valid offer
+ // is the credential (mirrors initRemoteClient). The dev/relay gate still applies.
+ if (!relayAllowed()) {
+ throw new Error('Remote access is unavailable in development builds (set NODETERM_RELAY_URL).')
+ }
+ const offer = decodeOffer(String(offerCode ?? ''))
+ if (!offer) {
+ throw new Error('That pairing code is invalid or incomplete.')
+ }
+ // Our persistent peer identity (4d: pinned on both ends). A locked keyring rejects here as
+ // PeerKeyLockedError (E_PEER_KEY_LOCKED) — the identity on disk is intact and must NOT be rotated;
+ // the renderer tells the human to unlock and reconnect.
+ const keys = await loadOrCreatePeerKeyPair()
+ const connectionId = randomUUID()
+ const session = connectRelayClient({
+ url: offer.relayEndpoint,
+ token: offer.pairingToken,
+ hostKeyB64: offer.hostPublicKeyB64,
+ ourKeys: keys,
+ // The SAS is known — push it so this human can compare it before the host approves.
+ onSas: (s) => sendTo(IPC.relayClientSas(connectionId), s.sas()),
+ // Mutually approved — the frame pipe is live.
+ onApproved: () => sendTo(IPC.relayClientApproved(connectionId)),
+ // An inbound rpc frame from the host (res/ev) → the renderer's RpcClient.
+ onFrame: (json) => sendTo(IPC.relayClientFrame(connectionId), json),
+ // pty output arrives on the SAME per-session channel a local pty uses (ws-bridge binary path).
+ onPtyData: (sessionId, data) => sendTo(IPC.ptyData(sessionId), data),
+ onClose: () => {
+ relayClients.delete(connectionId)
+ sendTo(IPC.relayClientClosed(connectionId))
+ }
+ })
+ relayClients.set(connectionId, session)
+ return connectionId
+ })
+ // This human compared the SAS and pressed Confirm → advance the trust gate (confirm rides the
+ // ENCRYPTED tunnel). An unknown id (stale event) is a no-op.
+ ipcMain.on(IPC.relayClientConfirm, (_e, connectionId: string) => {
+ relayClients.get(String(connectionId))?.confirm()
+ })
+ // The renderer casts an outbound rpc frame at the host (refused inside the session before approval).
+ ipcMain.on(IPC.relayClientSend, (_e, connectionId: string, json: string) => {
+ relayClients.get(String(connectionId))?.send(String(json))
+ })
+ ipcMain.handle(IPC.relayClientDisconnect, (_e, connectionId: string) => {
+ const id = String(connectionId)
+ relayClients.get(id)?.close()
+ relayClients.delete(id)
+ })
+ }
sshProjectManager = initSshProject(win, (projectId) => {
// On (re)connect, reconcile the server's .nodeterm/project.json with our offline cache by rev.
// A non-null result means the remote won → adopt it in the renderer (Task 7's listener does the
diff --git a/src/main/remote/relay-client.test.ts b/src/main/remote/relay-client.test.ts
new file mode 100644
index 000000000..0af438aac
--- /dev/null
+++ b/src/main/remote/relay-client.test.ts
@@ -0,0 +1,316 @@
+// Task 3 (docs/remote-sessions.md 4c): the CLIENT half of the mutual-approval handshake and the
+// tunnel↔renderer frame pipe. This pairs the REAL `connectRelayHost` (Task 2) with the new
+// `connectRelayClient` over an in-process RelayTransport pair — the same fake wire relay-host.test.ts
+// and relay-trust.test.ts drive. Nothing crypto/tunnel/trust is faked: the E2EE handshake, the
+// session key, both trust gates, electronPlatform, the peer registry and presence are the real,
+// wired objects. Only the electron shell boundary and the relay WIRE are stand-ins.
+//
+// SECURITY the client MUST prove here (a mistake is a shell-access hole on the OTHER desktop, but
+// the client's own obligations are symmetric):
+// - obligation (a): the "I confirmed" that opens the session rides the ENCRYPTED tunnel. A forged
+// PLAINTEXT confirm injected by the relay MUST NOT advance approval or open the client.
+// - the confirm binds to THIS session's host key (the pinned key that keyed the ECDH shared secret
+// the SAS is derived from): both ends compute the SAME SAS, and mutual confirm opens the client.
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const h: {
+ handlers: Record<string, (...a: any[]) => unknown>
+ sent: Array<{ id?: number; channel: string; args: any[] }>
+ clientIds: number[]
+} = { handlers: {}, sent: [], clientIds: [] }
+
+vi.mock('electron', () => ({
+ app: { getPath: () => '/tmp/ud', getVersion: () => '9.9.9', isPackaged: false },
+ ipcMain: {
+ handle: (ch: string, fn: (...a: any[]) => unknown) => {
+ h.handlers[ch] = fn
+ },
+ on: (ch: string, fn: (...a: any[]) => void) => {
+ h.handlers[ch] = fn
+ }
+ },
+ webContents: {
+ fromId: (id: number) =>
+ id === 1
+ ? {
+ isDestroyed: () => false,
+ send: (ch: string, ...args: any[]) => h.sent.push({ id, channel: ch, args })
+ }
+ : undefined
+ },
+ shell: { openExternal: vi.fn(async () => {}) }
+}))
+
+vi.mock('../main-window', () => ({
+ sendToMain: (ch: string, ...args: any[]) => h.sent.push({ channel: ch, args }),
+ mainWindowClientIds: () => h.clientIds
+}))
+
+// The on-disk pin store, in memory (the trust gate's default load/save path). Each side pins the
+// OTHER end's key here.
+import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'
+let disk: ApprovedDevices = emptyApprovedDevices()
+vi.mock('./approved-devices', () => ({
+ loadApprovedDevices: async () => disk,
+ saveApprovedDevices: async (s: ApprovedDevices) => {
+ disk = s
+ }
+}))
+
+import { connectRelayHost, type RelayHostSession } from './relay-host'
+import { connectRelayClient, type RelayClientSession } from './relay-client'
+import { type RelayTransport } from './relay-socket'
+import { genKeyPair, publicKeyToB64 } from './e2ee'
+import { TRUST_CONFIRM } from './relay-trust'
+import { electronPlatform, type ElectronPlatform } from '../platform-electron'
+import { peerRegistry, unregisterPeerSink, wirePeerRegistry } from '../peer-registry'
+import { presenceHub } from '../../core/presence/hub'
+import { initCanvasSync } from '../../core/canvas-sync'
+import { initPlatform, resetPlatformForTests } from '../../core/platform'
+
+let platform: ElectronPlatform
+let gone: number[] = []
+
+/**
+ * A REAL host session (connectRelayHost against the real platform) bridged to a REAL
+ * connectRelayClient over an in-process transport pair. Exposes both trust surfaces plus a hook to
+ * inject a forged PLAINTEXT frame straight at the client (what a relay MITM can do).
+ */
+function pairHostAndClient(): {
+ host: RelayHostSession
+ client: RelayClientSession
+ clientSas: () => string | null
+ approved: RelayClientSession[]
+ frames: string[]
+ ptyData: Array<{ sessionId: string; data: string }>
+ clientClosed: () => number
+ /** Inject an arbitrary PLAINTEXT string (or bytes) at the client, as the relay could. */
+ injectToClient: (raw: string | Uint8Array) => void
+ /** BOTH humans press Confirm (each confirm rides its own encrypted tunnel). */
+ openMutually: () => Promise<void>
+} {
+ const hostKeys = genKeyPair()
+ const clientKeys = genKeyPair()
+
+ let hostOnMsg: ((d: unknown) => void) | null = null
+ let clientOnMsg: ((d: unknown) => void) | null = null
+ let hostOnClose: (() => void) | null = null
+ let clientOnClose: (() => void) | null = null
+
+ const hostT: RelayTransport = {
+ bufferedAmount: 0,
+ send: (d) => clientOnMsg?.(d),
+ close: () => clientOnClose?.(),
+ onMessage: (cb) => {
+ hostOnMsg = cb
+ },
+ onClose: (cb) => {
+ hostOnClose = cb
+ }
+ }
+ const clientT: RelayTransport = {
+ bufferedAmount: 0,
+ send: (d) => hostOnMsg?.(d),
+ close: () => hostOnClose?.(),
+ onMessage: (cb) => {
+ clientOnMsg = cb
+ },
+ onClose: (cb) => {
+ clientOnClose = cb
+ }
+ }
+
+ // The host FIRST: it waits passively for the client's e2ee_hello.
+ const host = connectRelayHost({
+ url: 'wss://relay.example',
+ token: 'tok',
+ ourKeys: hostKeys,
+ platform,
+ transport: hostT,
+ onPeerPending: () => {},
+ onOpen: () => {},
+ onClose: () => {}
+ })
+
+ const approved: RelayClientSession[] = []
+ const frames: string[] = []
+ const ptyData: Array<{ sessionId: string; data: string }> = []
+ let clientClosed = 0
+
+ // The client: constructing it drives the whole handshake synchronously over the in-process pair.
+ const client = connectRelayClient({
+ url: 'wss://relay.example',
+ token: 'tok',
+ hostKeyB64: publicKeyToB64(hostKeys.publicKey),
+ ourKeys: clientKeys,
+ transport: clientT,
+ onSas: () => {},
+ onApproved: (s) => approved.push(s),
+ onFrame: (json) => frames.push(json),
+ onPtyData: (sessionId, data) => ptyData.push({ sessionId, data }),
+ onClose: () => {
+ clientClosed++
+ }
+ })
+
+ return {
+ host,
+ client,
+ clientSas: () => client.sas(),
+ approved,
+ frames,
+ ptyData,
+ clientClosed: () => clientClosed,
+ injectToClient: (raw) => clientOnMsg?.(raw),
+ openMutually: async () => {
+ client.confirm() // this human, over the ENCRYPTED tunnel → the host's confirmRemote
+ host.confirm() // the other human, over its ENCRYPTED tunnel → the client's confirmRemote
+ await vi.waitFor(() => expect(client.isOpen()).toBe(true))
+ await vi.waitFor(() => expect(host.clientId()).not.toBeNull())
+ }
+ }
+}
+
+beforeEach(() => {
+ h.handlers = {}
+ h.sent = []
+ h.clientIds = [1]
+ disk = emptyApprovedDevices()
+ gone = []
+ platform = electronPlatform()
+ initPlatform(platform)
+ wirePeerRegistry({
+ setFlow: () => {},
+ captureForResync: async () => 'SCREEN',
+ onPeerGone: (id) => gone.push(id)
+ })
+ presenceHub.registerIpc()
+ initCanvasSync()
+})
+
+afterEach(() => {
+ for (const id of peerRegistry().ids()) unregisterPeerSink(id)
+ for (const pe of presenceHub.peers()) presenceHub.leave(pe.clientId)
+ resetPlatformForTests()
+})
+
+describe('relay client — SAS + mutual approval', () => {
+ it('both ends derive the SAME 6-digit SAS from this session', () => {
+ const p = pairHostAndClient()
+ expect(p.clientSas()).toMatch(/^\d{3} \d{3}$/)
+ expect(p.clientSas()).toBe(p.host.sas())
+ })
+
+ it('mutual confirm opens the client (onApproved fires) and the host (a live CorePlatform client)', async () => {
+ const p = pairHostAndClient()
+ expect(p.client.isOpen()).toBe(false)
+ expect(p.approved).toEqual([])
+
+ await p.openMutually()
+
+ expect(p.client.isOpen()).toBe(true)
+ expect(p.approved).toEqual([p.client]) // onApproved fired exactly once, with the session
+ expect(p.host.clientId()).not.toBeNull()
+ })
+
+ it('ONE side confirming is not enough — the client stays closed', async () => {
+ const p = pairHostAndClient()
+ p.client.confirm() // only this human
+ await new Promise((r) => setTimeout(r, 20))
+ expect(p.client.isOpen()).toBe(false)
+ expect(p.approved).toEqual([])
+ })
+})
+
+describe('relay client — obligation (a): the confirm MUST ride the encrypted tunnel', () => {
+ it('a forged PLAINTEXT confirm never advances approval nor opens the client', async () => {
+ const p = pairHostAndClient()
+ p.client.confirm() // the local human confirms — one-way approval must NOT be enough
+
+ // A relay MITM injects plaintext frames that *look* like the host's confirm, in every dialect
+ // the code knows. None is sealed under the session key, so none can reach the trust gate.
+ p.injectToClient(JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] }))
+ p.injectToClient(JSON.stringify({ type: TRUST_CONFIRM }))
+ p.injectToClient(JSON.stringify({ kind: 'notify', method: TRUST_CONFIRM, params: {} }))
+ p.injectToClient(JSON.stringify({ kind: 'req', id: '1', method: TRUST_CONFIRM, params: {} }))
+ // ...and raw bytes, which cannot decrypt.
+ p.injectToClient(new TextEncoder().encode(JSON.stringify({ t: 'cast', method: TRUST_CONFIRM })))
+ await new Promise((r) => setTimeout(r, 20))
+
+ expect(p.client.isOpen()).toBe(false) // approval did NOT advance
+ expect(p.approved).toEqual([]) // the session never opened
+ expect(disk.pubkeys).toEqual([]) // nothing pinned
+ })
+})
+
+describe('relay client — the frame pipe (tunnel ↔ renderer)', () => {
+ it('refuses to send a req BEFORE mutual approval, so the host dispatches nothing', async () => {
+ let created = 0
+ platform.handle('pty:create', async () => {
+ created++
+ return { id: 'x' }
+ })
+ const p = pairHostAndClient()
+
+ const sent = p.client.send(
+ JSON.stringify({ t: 'req', id: 1, method: 'pty:create', args: [{ cols: 80, rows: 24 }] })
+ )
+ await new Promise((r) => setTimeout(r, 20))
+
+ expect(sent).toBe(false) // refused locally — nothing left this machine
+ expect(created).toBe(0) // and the host handler never ran
+ expect(p.frames).toEqual([]) // no response frame either
+ })
+
+ it('after open, a req round-trips through platform.dispatch and its res reaches the client', async () => {
+ platform.handle('fs:list', async (dir: string) => [`${dir}/a.ts`])
+ const p = pairHostAndClient()
+ await p.openMutually()
+
+ const sent = p.client.send(JSON.stringify({ t: 'req', id: 7, method: 'fs:list', args: ['/w'] }))
+ expect(sent).toBe(true)
+
+ await vi.waitFor(() =>
+ expect(p.frames.map((j) => JSON.parse(j))).toContainEqual(
+ expect.objectContaining({ t: 'res', id: 7, ok: true, result: ['/w/a.ts'] })
+ )
+ )
+ })
+
+ it('forwards a host pty:data BINARY frame to onPtyData (decoded), not to onFrame', async () => {
+ const p = pairHostAndClient()
+ await p.openMutually()
+ const id = p.host.clientId()!
+
+ // The host streams pty output to this client; the peer sink turns it into a BINARY tunnel frame.
+ platform.sendTo(id, 'pty:data:s1', 'hello world')
+
+ await vi.waitFor(() => expect(p.ptyData).toEqual([{ sessionId: 's1', data: 'hello world' }]))
+ // pty:data must not leak onto the JSON frame pipe.
+ expect(p.frames.some((j) => j.includes('hello world'))).toBe(false)
+ })
+})
+
+describe('relay client — teardown', () => {
+ it('disconnect() closes the socket and is idempotent; the host peer is torn down', async () => {
+ const p = pairHostAndClient()
+ await p.openMutually()
+ const id = p.host.clientId()!
+ expect(peerRegistry().ids()).toContain(id)
+
+ p.client.close()
+ p.client.close()
+
+ // The socket close propagates to the host, which runs its ONE teardown (dropClient + prune).
+ await vi.waitFor(() => expect(gone).toEqual([id]))
+ expect(peerRegistry().ids()).not.toContain(id)
+ })
+
+ it('a relay-side socket drop fires the client onClose once', async () => {
+ const p = pairHostAndClient()
+ await p.openMutually()
+ // Close from the host end: the pair forwards the close to the client transport.
+ p.host.close()
+ await vi.waitFor(() => expect(p.clientClosed()).toBe(1))
+ })
+})
diff --git a/src/main/remote/relay-client.ts b/src/main/remote/relay-client.ts
new file mode 100644
index 000000000..eb5dfc8e2
--- /dev/null
+++ b/src/main/remote/relay-client.ts
@@ -0,0 +1,170 @@
+// The interactive-client CONNECTOR (docs/remote-sessions.md 4c): the CLIENT half of the mutual-
+// approval handshake, and the tunnel↔renderer frame pipe. It is the MIRROR IMAGE of
+// `connectRelayHost` (relay-host.ts) — connect OUT to a host's pairing offer, run the same
+// `createTrustGate` from the client side (compute + surface the SAS, confirm over the ENCRYPTED
+// tunnel, receive the host's confirm the same way), and once BOTH humans have approved, expose the
+// raw rpc.ts frame pipe so a later RpcClient (Task 4/5's FrameTransport + buildRelayApi) can drive
+// the host's core over `relay:client:send` / `relay:client:frame`.
+//
+// SECURITY — the client's obligations are the symmetric image of the host's (see relay-host.ts and
+// mutual-approval-core.ts). A mistake here forges the LOCAL human's consent or lets the relay open
+// the session without the REMOTE human, either of which grants shell access on a machine:
+// - obligation (a): the ONLY thing that can advance approval is a trust frame that came out of the
+// E2EE box (`connectRelay`'s `onTunnel`). Our own confirm rides the SAME sealed channel via
+// `socket.sendTunnelText` inside the gate's `sendConfirm` — never a plaintext path. A plaintext
+// frame the relay injects dies in relay-socket's `handleControl` and never reaches the gate.
+// - obligation (b): EXACTLY ONE `MutualApproval`, bound to THIS session's host key. For a client
+// the pinned host key from the offer (`opts.hostKeyB64`) IS the socket's peer key
+// (`socket.peerPublicKeyB64()`) — it seeded the ECDH shared secret the SAS is derived from, and
+// the client role never re-derives it. `peerKeyIntact()` re-asserts it against the live socket on
+// every tunnel frame, so a mid-session re-key (which relay-socket already refuses) can never
+// advance approval, forward a frame, or open the pipe under a swapped key.
+//
+// This file BUILDS NO api: it produces the SAS/approval events and the raw frame pipe only. It never
+// modifies the reviewed transport/trust/host machinery — it USES it.
+import { connectRelay, type RelayTransport, type RelaySocket } from './relay-socket'
+import { createTrustGate, type TrustGate } from './relay-trust'
+import type { KeyPair } from './e2ee'
+import { decodePtyData } from '../../shared/rpc'
+
+export interface RelayClientSession {
+ /** The 6-digit SAS both humans compare, or null before the key is derived. */
+ sas(): string | null
+ /** The host's stable box public key (base64) this session is bound to, or null before ready. */
+ peerKeyB64(): string | null
+ /** This human compared the SAS and pressed Confirm — sends our confirm over the ENCRYPTED tunnel. */
+ confirm(): void
+ /** Cast an outbound rpc.ts frame (JSON) at the host. Refused (returns false) before mutual approval:
+ * the host answers pre-approval reqs with E_UNAUTHORIZED anyway, so nothing is gained by sending. */
+ send(json: string): boolean
+ /** Both humans confirmed → the frame pipe is live. */
+ isOpen(): boolean
+ /** Tear down: close the relay socket. Idempotent. */
+ close(): void
+}
+
+export interface ConnectRelayClientOptions {
+ /** The relay wss URL from the decoded pairing offer. */
+ url: string
+ /** The single-use pairing token from the offer. */
+ token: string
+ /** The host's pinned box public key (base64) from the offer — the ECDH peer key for this session. */
+ hostKeyB64: string
+ /** Our long-lived peer identity (4d: pinned on both ends). Load via `loadOrCreatePeerKeyPair`. */
+ ourKeys: KeyPair
+ /** TEST ONLY: an in-process RelayTransport. Production opens a real ws (relay-socket.ts). */
+ transport?: RelayTransport
+ /** The SAS is known (the handshake completed) — ask this human to compare it. NOTHING is open yet. */
+ onSas(session: RelayClientSession): void
+ /** Mutually approved: the frame pipe is live (Task 4 builds the RpcClient on top). */
+ onApproved(session: RelayClientSession): void
+ /** An inbound rpc.ts TEXT frame from the host (a `res`/`ev`) → forward to the renderer. Trust frames
+ * are consumed by the gate BEFORE this and never delivered here. */
+ onFrame(json: string): void
+ /** An inbound pty:data BINARY frame → forward as pty output (mirrors the ws-bridge binary path). */
+ onPtyData(sessionId: string, data: string): void
+ /** The relay socket dropped (host/relay gone). */
+ onClose(): void
+}
+
+export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClientSession {
+ // `socket` is assigned AFTER `connectRelay` returns, but over an in-process transport the client's
+ // handshake (and thus `onReady`) completes SYNCHRONOUSLY during that call — so `onReady` must not
+ // reach for `socket` (it uses `opts.hostKeyB64`, which IS the socket's peer key for a client), and
+ // the deferred gate/session closures below guard with `socket?.`.
+ let socket: RelaySocket | null = null
+ let gate: TrustGate | null = null
+ let opened = false
+ let closed = false
+ // OBLIGATION (b) — defence in depth. The host key this session is bound to (== socket peer key for a
+ // client). If the socket's live peer key ever diverges from it, the session key was swapped under us;
+ // we then refuse to advance approval, forward a frame, or open. relay-socket's layer-1 guard already
+ // refuses the swap — this is the second, independent check.
+ let sessionPeerKey: string | null = null
+ let keySwapped = false
+
+ const session: RelayClientSession = {
+ sas: () => gate?.sas() ?? null,
+ peerKeyB64: () => gate?.peerKeyB64() ?? null,
+ confirm: () => gate?.confirmHere(),
+ send: (json) => {
+ if (!opened || closed || !socket) return false
+ return socket.sendTunnelText(json)
+ },
+ isOpen: () => opened,
+ close() {
+ if (closed) return
+ closed = true
+ socket?.close()
+ }
+ }
+
+ /** The socket's live peer key still matches the one bound into the gate. 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
+ session.close()
+ return false
+ }
+
+ /** Both humans confirmed: the frame pipe is live. */
+ const open = (): void => {
+ if (closed || opened) return
+ if (!peerKeyIntact()) return
+ opened = true
+ opts.onApproved(session)
+ }
+
+ socket = connectRelay({
+ url: opts.url,
+ token: opts.token,
+ role: 'client',
+ ourKeys: opts.ourKeys,
+ theirPubB64: opts.hostKeyB64,
+ transport: opts.transport,
+ onReady: () => {
+ // E2EE is up. This proves only that the host holds the pairing token — NOT that the human at the
+ // other end is who we think. Build the trust gate and ask this human to compare the SAS; nothing
+ // opens until BOTH confirm. Bind to the pinned host key (this session's ECDH peer key).
+ if (gate) return
+ sessionPeerKey = opts.hostKeyB64
+ gate = createTrustGate({
+ peerKeyB64: opts.hostKeyB64,
+ sessionId: `${opts.hostKeyB64}:${Date.now()}`, // obligation (b): ONE state per pairing attempt
+ sas: () => socket?.sas() ?? null,
+ // The ONLY confirm we ever send — over the ENCRYPTED, session-keyed tunnel (obligation (a)).
+ sendConfirm: (json) => {
+ socket?.sendTunnelText(json)
+ },
+ onOpen: open
+ })
+ opts.onSas(session)
+ },
+ // The legacy phone dialect is not spoken here.
+ onRpc: () => {},
+ onFrame: () => {},
+ onTunnel: (kind, payload) => {
+ // OBLIGATION (b) — before advancing approval or forwarding a frame: the session key must still
+ // belong to the ORIGINAL host. A frame that decrypted under a swapped key must not reach the gate
+ // or the renderer.
+ if (!peerKeyIntact()) return
+ if (kind === 'binary') {
+ // Binary is pty output only (mirrors the ws-bridge binary path). Anything undecodable is dropped.
+ const decoded = decodePtyData(payload)
+ if (decoded) opts.onPtyData(decoded.sessionId, decoded.data)
+ return
+ }
+ const json = new TextDecoder().decode(payload)
+ // Trust frames are consumed here and NEVER forwarded to the renderer's RPC client.
+ if (gate?.onTunnelText(json)) return
+ opts.onFrame(json)
+ },
+ onClose: () => {
+ opts.onClose()
+ }
+ })
+
+ return session
+}