Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: implement authenticated local WebSocket server for secure loopback transport of JSON frames and HTRL binary streams

0xken15faf77af0acf8
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 3f1d28d2b..d340b4a21 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -3,6 +3,7 @@ import { readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem, grokHistoryPage } from './backendSocket.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
+import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'
import { registry, type RegisteredSession } from './lib/registry.js'
const wsMock = vi.hoisted(() => {
@@ -295,6 +296,80 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('serves authenticated local RPCs in cleartext without weakening cloud E2EE', async () => {
+ const socket = new BackendSocket('token')
+ socket.runtimeModelsProvider = async () => [
+ { id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'Sol / High' },
+ ]
+ const frames: Array<Record<string, unknown>> = []
+ expect(socket.registerLocalClient('local:test', {
+ sendFrame: (frame) => { frames.push(frame); return true },
+ sendBinary: () => true,
+ })).toBe(true)
+
+ socket.handleLocalFrame('local:test', {
+ type: 'models_list', payload: { requestId: 'local-models' },
+ })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'models_list_result',
+ payload: {
+ requestId: 'local-models',
+ models: [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'Sol / High' }],
+ },
+ }))
+
+ await socket.unregisterLocalClient('local:test')
+ await socket.stop()
+ })
+
+ it('routes local terminal binary directly and preserves local streams when cloud disconnects', async () => {
+ vi.useFakeTimers()
+ const socket = new BackendSocket('token')
+ const handleBinary = vi.fn(async () => undefined)
+ const closeConnection = vi.fn(async () => undefined)
+ const closeConnectionsWhere = vi.fn(async (
+ _predicate: (connId: string) => boolean,
+ _reason: string,
+ _notify?: boolean,
+ ) => undefined)
+ const stop = vi.fn(async () => undefined)
+ socket.setTerminalStreamManager({
+ handleBinary,
+ closeConnection,
+ closeConnectionsWhere,
+ stop,
+ } as unknown as TerminalStreamManager)
+ const binary: Uint8Array[] = []
+ socket.registerLocalClient('local:terminal', {
+ sendFrame: () => true,
+ sendBinary: (frame) => { binary.push(frame); return true },
+ })
+ const clear = {
+ kind: TerminalBinaryKind.input,
+ streamId: '00112233-4455-6677-8899-aabbccddeeff',
+ seq: 1,
+ bytes: Uint8Array.of(1, 2),
+ compressed: false,
+ }
+ await socket.handleLocalBinary('local:terminal', clear)
+ expect(handleBinary).toHaveBeenCalledWith('local:terminal', clear)
+ expect(socket.sendTerminalBinaryTo('local:terminal', clear)).toBe(true)
+ expect(decodeTerminalLocal(binary[0])).toEqual(clear)
+
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ ws.close()
+ expect(closeConnectionsWhere).toHaveBeenCalledOnce()
+ const predicate = closeConnectionsWhere.mock.calls[0][0] as (connId: string) => boolean
+ expect(predicate('web-1')).toBe(true)
+ expect(predicate('local:terminal')).toBe(false)
+
+ await socket.unregisterLocalClient('local:terminal')
+ expect(closeConnection).toHaveBeenCalledWith('local:terminal', 'local client disconnected', false)
+ await socket.stop()
+ })
+
it('reports commander presence only when it crosses zero', async () => {
const socket = new BackendSocket('token')
const changes: boolean[] = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 68e9eeec2..8916ac775 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -49,6 +49,7 @@ import { E2eeManager, type PairResult } from './lib/e2ee/manager.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
import {
decodeTerminalHop,
+ encodeTerminalLocal,
encodeTerminalHop,
TerminalHopDirection,
type TerminalBinaryClear,
@@ -82,9 +83,18 @@ const DEVICE_AGENT_NAME_MAX_CODEPOINTS = 15
const DEVICE_AGENT_NAME_MAX_BYTES = 39 // device project_t.name[40], including trailing NUL on-device.
const DEVICE_ELLIPSIS = '…'
-type Frame = Record<string, unknown>
+export type Frame = Record<string, unknown>
type OutboundEnvelope = Record<string, unknown>
+export interface LocalClientSink {
+ sendFrame: (frame: Frame) => boolean
+ sendBinary: (frame: Uint8Array) => boolean
+}
+
+function isLocalClientId(connId: string): boolean {
+ return connId.startsWith('local:')
+}
+
interface QueueItem {
id: number
data: string
@@ -257,6 +267,7 @@ export class BackendSocket {
private heartbeat: NodeJS.Timeout | null = null
private appPing: NodeJS.Timeout | null = null
private readonly downChains = new Map<string, Promise<void>>()
+ private readonly localClients = new Map<string, LocalClientSink>()
private terminalStreams: TerminalStreamManager | null = null
private isAlive = true
private onStatus: (connected: boolean) => void
@@ -451,7 +462,11 @@ export class BackendSocket {
// completing during the gap burns a `claude -p` recap that goes nowhere. attachAdapter always
// re-pushes the true count via recomputeAndSendClients on reconnect (and 0→N re-fires the replay).
this.setCommanderCount(0, null) // active count is unknown until the next __clients snapshot
- void this.terminalStreams?.closeAll('backend disconnected')
+ void this.terminalStreams?.closeConnectionsWhere(
+ (connId) => !isLocalClientId(connId),
+ 'backend disconnected',
+ false,
+ )
this.replayCommanderOnNextSnapshot = true
this.onStatus(false)
if (this.closed) return
@@ -493,16 +508,26 @@ export class BackendSocket {
* User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */
send(frame: Frame): void {
if (env.LOG_FRAMES) logFrame('→', 'web', frame)
+ for (const [connId, sink] of this.localClients) {
+ if (!sink.sendFrame(frame)) void this.unregisterLocalClient(connId)
+ }
this.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })
}
/** Send an up-frame to exactly ONE web connection (E2EE pairing/welcome + targeted RPC replies). */
sendTo(connId: string, frame: Frame): void {
+ const local = this.localClients.get(connId)
+ if (local) {
+ if (!local.sendFrame(frame)) void this.unregisterLocalClient(connId)
+ return
+ }
this.enqueue({ t: 'up', targetConnId: connId, frame })
}
/** Pairwise terminal output is never queued across reconnect: the stream/lease is closed on link loss. */
sendTerminalTo(connId: string, type: string, payload: Record<string, unknown>): boolean {
+ const local = this.localClients.get(connId)
+ if (local) return local.sendFrame({ type, payload })
const frame = this.e2ee.wrapTarget(connId, type, payload)
if (!frame) return false
return this.sendBestEffort({
@@ -517,6 +542,11 @@ export class BackendSocket {
/** Pairwise-encrypted binary terminal output/keyframe. The hop prefix exposes
* only connId and direction to the opaque backend relay. */
sendTerminalBinaryTo(connId: string, clear: TerminalBinaryClear): boolean {
+ const local = this.localClients.get(connId)
+ if (local) {
+ const frame = encodeTerminalLocal(clear)
+ return frame ? local.sendBinary(frame) : false
+ }
const clientFrame = this.e2ee.wrapTerminalBinary(connId, clear)
if (!clientFrame) return false
const packet = encodeTerminalHop(TerminalHopDirection.up, connId, clientFrame)
@@ -536,6 +566,32 @@ export class BackendSocket {
this.enqueue({ t: 'up', webEligible: false, commanderEligible: true, frame: this.e2ee.wrapCommander(frame) })
}
+ /** Attach one authenticated loopback desktop client to the same RPC and event plane as cloud web. */
+ registerLocalClient(connId: string, sink: LocalClientSink): boolean {
+ if (!isLocalClientId(connId) || this.localClients.has(connId)) return false
+ this.localClients.set(connId, sink)
+ return true
+ }
+
+ /** Release all connection-scoped state when the loopback WebSocket closes. */
+ async unregisterLocalClient(connId: string): Promise<void> {
+ if (!this.localClients.delete(connId)) return
+ this.downChains.delete(connId)
+ await this.terminalStreams?.closeConnection(connId, 'local client disconnected', false)
+ }
+
+ /** Route an authenticated local JSON frame through the existing per-client FIFO. */
+ handleLocalFrame(connId: string, frame: Frame): void {
+ if (!this.localClients.has(connId)) return
+ this.enqueueDown(frame, connId)
+ }
+
+ /** Route an authenticated local terminal frame without applying cloud E2EE. */
+ async handleLocalBinary(connId: string, frame: TerminalBinaryClear): Promise<void> {
+ if (!this.localClients.has(connId)) return
+ await this.terminalStreams?.handleBinary(connId, frame)
+ }
+
private enqueue(msg: OutboundEnvelope): void {
const item: QueueItem = { id: this.nextQueueId++, data: JSON.stringify(msg), msg, attempts: 0 }
if (this.queue.length >= QUEUE_MAX) this.dropOneQueued()
@@ -641,6 +697,10 @@ export class BackendSocket {
const resultType = `${type}_result`
// Before the E2EE wrap: an RPC reply is only readable here.
if (env.LOG_FRAMES) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
+ if (this.localClients.has(connId)) {
+ this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
+ return
+ }
if (connId && this.e2ee.hasSession(connId) && ENCRYPTED_RPC_RESULT_TYPES.has(resultType)) {
let replyPayload = payload
if (resultType === 'agent_recent_result') {
@@ -676,11 +736,19 @@ export class BackendSocket {
private async dispatchDown(frame: Frame, connId: string): Promise<void> {
const type = frame.type as string | undefined
if (!type) return
+ const local = this.localClients.has(connId)
// E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.
- if (type.startsWith('e2e_')) { this.e2ee.handleFrame(connId, frame); return }
+ if (type.startsWith('e2e_')) {
+ if (local) {
+ this.sendTo(connId, { type: 'local_protocol_error', payload: { error: 'LOCAL_E2EE_UNSUPPORTED' } })
+ return
+ }
+ this.e2ee.handleFrame(connId, frame)
+ return
+ }
// Client→adapter encrypted frames: chat messages plus trusted web control actions. Plaintext
// passes through for legacy/device transition paths; undecryptable ciphertext is dropped.
- if (isEncryptedDownType(type)) {
+ if (!local && isEncryptedDownType(type)) {
if (type !== 'message' && type !== 'question_response' && !isWrapped(frame.payload)) {
const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId
if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 32ebab82e..5f73f24d0 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -56,6 +56,8 @@ import { readTerminalConfigSnapshot, writeTerminalConfigSnapshot } from './lib/t
import { Watcher, type LineEvent } from './watcher/watcher.js'
import { chooseHookAgent, startHookServer } from './hookServer.js'
import { BackendSocket } from './backendSocket.js'
+import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from './localWsServer.js'
+import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'
import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, type LiveEvent, type TurnState } from './lib/normalize.js'
import { AnalyticsCollector } from './lib/analytics/collector.js'
import { runAnalyticsCommand } from './lib/analytics/command.js'
@@ -2103,6 +2105,12 @@ async function runForeground(token: string): Promise<void> {
onStatus: () => ({
machineId: backend.machineId,
version: VERSION,
+ localWs: {
+ path: LOCAL_WS_PATH,
+ protocolVersion: LOCAL_WS_PROTOCOL_VERSION,
+ terminalProtocolVersion: TERMINAL_BINARY_VERSION,
+ e2ee: false,
+ },
backendUrl: env.BACKEND_WS_URL,
webUrl: env.WEB_URL,
connected: backend.isConnected(),
@@ -2148,6 +2156,11 @@ async function runForeground(token: string): Promise<void> {
},
onStop: () => { setTimeout(() => process.kill(process.pid, 'SIGTERM'), 50) }, // let the 200 flush first
})
+ const localWsServer = attachLocalWsServer(hookServer, {
+ token,
+ machineId: backend.machineId,
+ backend,
+ })
// Install both CLI hooks with the port the local server actually bound.
if (!env.DISABLE_HOOK_INSTALL) {
installSessionHooks(hookPort)
@@ -2528,6 +2541,7 @@ async function runForeground(token: string): Promise<void> {
;(hookServer as unknown as { closeAllConnections?: () => void }).closeAllConnections?.()
// Release the fixed hook port before the child binds. Process-owned agents stay in the persisted
// registry and are revalidated by the new daemon's first discovery passes.
+ await localWsServer.close()
hookServer.close()
shutdownSummaryPool()
shutdownVoiceRouter()
@@ -2618,6 +2632,7 @@ async function runForeground(token: string): Promise<void> {
for (const r of devinReaders.values()) r.stop()
await cursorDiscovery.stop()
await watcher.stop()
+ await localWsServer.close()
hookServer.close()
shutdownSummaryPool()
shutdownVoiceRouter()
diff --git a/cli/src/lib/terminalBinary.spec.ts b/cli/src/lib/terminalBinary.spec.ts
index ea2225401..d619948db 100644
--- a/cli/src/lib/terminalBinary.spec.ts
+++ b/cli/src/lib/terminalBinary.spec.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest'
import {
deriveTerminalBinaryKey,
+ decodeTerminalLocal,
+ encodeTerminalLocal,
openTerminalBinary,
parseTerminalBinaryEnvelope,
sealTerminalBinary,
@@ -97,3 +99,43 @@ describe('terminal binary protocol v3', () => {
expect(openTerminalBinary(key, badFlags)).toBeNull()
})
})
+
+describe('authenticated loopback terminal framing v1', () => {
+ it('matches the cross-language HTRL golden frame', () => {
+ const encoded = encodeTerminalLocal({
+ kind: TerminalBinaryKind.input,
+ streamId,
+ seq: 3,
+ bytes: new TextEncoder().encode('xin chào\r'),
+ compressed: false,
+ })!
+ expect(Buffer.from(encoded).toString('hex')).toBe(
+ '4854524c0101000000000022' +
+ '00112233445566778899aabbccddeeff' +
+ '0000000000000003' +
+ '78696e206368c3a06f0d',
+ )
+ expect(decodeTerminalLocal(encoded)).toEqual({
+ kind: TerminalBinaryKind.input,
+ streamId,
+ seq: 3,
+ bytes: new TextEncoder().encode('xin chào\r'),
+ compressed: false,
+ })
+ })
+
+ it('rejects malformed local frames', () => {
+ const encoded = encodeTerminalLocal({
+ kind: TerminalBinaryKind.sync,
+ streamId,
+ seq: 4,
+ bytes: new Uint8Array(),
+ compressed: false,
+ })!
+ expect(decodeTerminalLocal(encoded.subarray(0, encoded.length - 1))).toBeNull()
+ const badReserved = encoded.slice(); badReserved[7] = 1
+ expect(decodeTerminalLocal(badReserved)).toBeNull()
+ const badMagic = encoded.slice(); badMagic[0] = 0
+ expect(decodeTerminalLocal(badMagic)).toBeNull()
+ })
+})
diff --git a/cli/src/lib/terminalBinary.ts b/cli/src/lib/terminalBinary.ts
index 5e6becf23..92bc8137a 100644
--- a/cli/src/lib/terminalBinary.ts
+++ b/cli/src/lib/terminalBinary.ts
@@ -6,6 +6,9 @@ export const TERMINAL_BINARY_VERSION = 3
export const TERMINAL_BINARY_HEADER_BYTES = 20
export const TERMINAL_BINARY_MAX_CIPHERTEXT_BYTES = 512 * 1024
export const TERMINAL_HOP_HEADER_BYTES = 24
+export const TERMINAL_LOCAL_VERSION = 1
+export const TERMINAL_LOCAL_HEADER_BYTES = 12
+export const TERMINAL_LOCAL_MAX_PAYLOAD_BYTES = 512 * 1024
export const enum TerminalBinaryKind {
input = 1,
@@ -34,6 +37,7 @@ export interface TerminalBinaryEnvelope {
const MAGIC = Uint8Array.of(0x48, 0x54, 0x52, 0x4d) // HTRM
const HOP_MAGIC = Uint8Array.of(0x48, 0x54, 0x52, 0x48) // HTRH
+const LOCAL_MAGIC = Uint8Array.of(0x48, 0x54, 0x52, 0x4c) // HTRL
const FLAG_ZLIB = 1
const TERMINAL_KEY_INFO = utf8('harness-terminal-binary-v3')
@@ -159,6 +163,38 @@ export function openTerminalBinary(key: Uint8Array, raw: Uint8Array): { counter:
return frame ? { counter: envelope.counter, frame } : null
}
+/** Plain terminal framing for the authenticated loopback desktop transport. */
+export function encodeTerminalLocal(frame: TerminalBinaryClear): Uint8Array | null {
+ const payload = encodeTerminalPlain(frame)
+ if (!payload || payload.length > TERMINAL_LOCAL_MAX_PAYLOAD_BYTES) return null
+ const flags = frame.compressed ? FLAG_ZLIB : 0
+ const header = new Uint8Array(TERMINAL_LOCAL_HEADER_BYTES)
+ header.set(LOCAL_MAGIC, 0)
+ header[4] = TERMINAL_LOCAL_VERSION
+ header[5] = frame.kind
+ header[6] = flags
+ const view = new DataView(header.buffer)
+ view.setUint32(8, payload.length, false)
+ const out = new Uint8Array(header.length + payload.length)
+ out.set(header)
+ out.set(payload, header.length)
+ return out
+}
+
+/** Decode a terminal frame only after the WebSocket peer passed loopback API-key authentication. */
+export function decodeTerminalLocal(raw: Uint8Array): TerminalBinaryClear | null {
+ const bytes = Uint8Array.from(raw)
+ if (bytes.length < TERMINAL_LOCAL_HEADER_BYTES) return null
+ for (let index = 0; index < LOCAL_MAGIC.length; index++) if (bytes[index] !== LOCAL_MAGIC[index]) return null
+ const kind = bytes[5]
+ const flags = bytes[6]
+ if (bytes[4] !== TERMINAL_LOCAL_VERSION || !validKind(kind) || bytes[7] !== 0) return null
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
+ const length = view.getUint32(8, false)
+ if (length > TERMINAL_LOCAL_MAX_PAYLOAD_BYTES || bytes.length !== TERMINAL_LOCAL_HEADER_BYTES + length) return null
+ return decodeTerminalPlain(kind, flags, bytes.slice(TERMINAL_LOCAL_HEADER_BYTES))
+}
+
export const enum TerminalHopDirection {
down = 1,
up = 2,
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 84fcbba1d..4218f14c0 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -685,6 +685,16 @@ export class TerminalStreamManager {
await Promise.all(states.map((state) => this.closeStream(state, reason, notify)))
}
+ /** Close one transport class without disturbing streams owned by another transport. */
+ async closeConnectionsWhere(
+ predicate: (connId: string) => boolean,
+ reason: string,
+ notify = false,
+ ): Promise<void> {
+ const states = [...this.streams.values()].filter((state) => predicate(state.connId))
+ await Promise.all(states.map((state) => this.closeStream(state, reason, notify)))
+ }
+
async closeAll(reason = 'backend disconnected'): Promise<void> {
await Promise.all([...this.streams.values()].map((state) => this.closeStream(state, reason, false)))
}
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
new file mode 100644
index 000000000..13426c902
--- /dev/null
+++ b/cli/src/localWsServer.spec.ts
@@ -0,0 +1,131 @@
+import http from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { afterEach, describe, expect, it } from 'vitest'
+import { WebSocket } from 'ws'
+import type { Frame, LocalClientSink } from './backendSocket.js'
+import { attachLocalWsServer, type LocalWsBackend, type LocalWsServer } from './localWsServer.js'
+import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './lib/terminalBinary.js'
+
+const token = 'machine-api-key'
+const machineId = 'machine-123'
+const streamId = '00112233-4455-6677-8899-aabbccddeeff'
+
+class FakeBackend implements LocalWsBackend {
+ sink: LocalClientSink | null = null
+ connId: string | null = null
+ frames: Frame[] = []
+ binaries: TerminalBinaryClear[] = []
+ unregisters: string[] = []
+
+ registerLocalClient(connId: string, sink: LocalClientSink): boolean {
+ this.connId = connId
+ this.sink = sink
+ return true
+ }
+ async unregisterLocalClient(connId: string): Promise<void> {
+ this.unregisters.push(connId)
+ }
+ handleLocalFrame(_connId: string, frame: Frame): void {
+ this.frames.push(frame)
+ }
+ async handleLocalBinary(_connId: string, frame: TerminalBinaryClear): Promise<void> {
+ this.binaries.push(frame)
+ }
+}
+
+function onceOpen(ws: WebSocket): Promise<void> {
+ return new Promise((resolve, reject) => {
+ ws.once('open', () => resolve())
+ ws.once('error', reject)
+ })
+}
+
+function onceMessage(ws: WebSocket): Promise<Frame> {
+ return new Promise((resolve, reject) => {
+ ws.once('message', (raw) => {
+ try { resolve(JSON.parse(raw.toString()) as Frame) } catch (error) { reject(error) }
+ })
+ ws.once('error', reject)
+ })
+}
+
+describe('local CLI WebSocket', () => {
+ let server: http.Server | null = null
+ let local: LocalWsServer | null = null
+
+ afterEach(async () => {
+ await local?.close()
+ await new Promise<void>((resolve) => server?.close(() => resolve()) ?? resolve())
+ local = null
+ server = null
+ })
+
+ async function start(backend: FakeBackend): Promise<string> {
+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
+ local = attachLocalWsServer(server, { token, machineId, backend })
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
+ const port = (server.address() as AddressInfo).port
+ return `ws://127.0.0.1:${port}/api/local-ws`
+ }
+
+ it('authenticates, selects the exact machine, and routes JSON plus HTRL binary', async () => {
+ const backend = new FakeBackend()
+ const url = await start(backend)
+ const ws = new WebSocket(url, [token])
+ await onceOpen(ws)
+ const connected = onceMessage(ws)
+ ws.send(JSON.stringify({
+ type: 'machine_select',
+ payload: { machineId, localProtocolVersion: 1 },
+ }))
+ await expect(connected).resolves.toMatchObject({
+ type: 'connected',
+ payload: { machineId, transport: 'local', e2ee: false },
+ })
+
+ ws.send(JSON.stringify({ type: 'agents_list', payload: { requestId: 'r1' } }))
+ const binary = encodeTerminalLocal({
+ kind: TerminalBinaryKind.input,
+ streamId,
+ seq: 1,
+ bytes: new TextEncoder().encode('hello'),
+ compressed: false,
+ })!
+ ws.send(binary)
+ await new Promise((resolve) => setTimeout(resolve, 20))
+ expect(backend.frames).toEqual([{ type: 'agents_list', payload: { requestId: 'r1' } }])
+ expect(backend.binaries[0]).toMatchObject({
+ kind: TerminalBinaryKind.input,
+ streamId,
+ seq: 1,
+ })
+
+ const reply = onceMessage(ws)
+ expect(backend.sink?.sendFrame({ type: 'agents_list_result', payload: { requestId: 'r1', agents: [] } })).toBe(true)
+ await expect(reply).resolves.toMatchObject({ type: 'agents_list_result' })
+ ws.close()
+ })
+
+ it('rejects the wrong API key before WebSocket upgrade', async () => {
+ const url = await start(new FakeBackend())
+ const ws = new WebSocket(url, ['wrong-key'])
+ const error = await new Promise<Error>((resolve) => ws.once('error', resolve))
+ expect(error.message).toContain('401')
+ })
+
+ it('rejects browser origins and machine-id mismatches', async () => {
+ const url = await start(new FakeBackend())
+ const browser = new WebSocket(url, [token], { origin: 'https://example.com' })
+ const error = await new Promise<Error>((resolve) => browser.once('error', resolve))
+ expect(error.message).toContain('403')
+
+ const ws = new WebSocket(url, [token])
+ await onceOpen(ws)
+ const closed = new Promise<number>((resolve) => ws.once('close', resolve))
+ ws.send(JSON.stringify({
+ type: 'machine_select',
+ payload: { machineId: 'other-machine', localProtocolVersion: 1 },
+ }))
+ await expect(closed).resolves.toBe(4403)
+ })
+})
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
new file mode 100644
index 000000000..a37f81d3c
--- /dev/null
+++ b/cli/src/localWsServer.ts
@@ -0,0 +1,201 @@
+import { randomUUID, timingSafeEqual } from 'node:crypto'
+import type http from 'node:http'
+import type { Socket } from 'node:net'
+import { WebSocket, WebSocketServer, type RawData } from 'ws'
+import type { Frame, LocalClientSink } from './backendSocket.js'
+import { decodeTerminalLocal, TERMINAL_BINARY_VERSION, type TerminalBinaryClear } from './lib/terminalBinary.js'
+
+export const LOCAL_WS_PATH = '/api/local-ws'
+export const LOCAL_WS_PROTOCOL_VERSION = 1
+
+const MAX_JSON_BYTES = 512 * 1024
+const HEARTBEAT_MS = 20_000
+
+export interface LocalWsBackend {
+ registerLocalClient: (connId: string, sink: LocalClientSink) => boolean
+ unregisterLocalClient: (connId: string) => Promise<void>
+ handleLocalFrame: (connId: string, frame: Frame) => void
+ handleLocalBinary: (connId: string, frame: TerminalBinaryClear) => Promise<void>
+}
+
+export interface LocalWsServerOptions {
+ token: string
+ machineId: string
+ backend: LocalWsBackend
+}
+
+export interface LocalWsServer {
+ close: () => Promise<void>
+}
+
+function isLoopback(address: string | undefined): boolean {
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
+}
+
+function secureEqual(left: string, right: string): boolean {
+ const a = Buffer.from(left)
+ const b = Buffer.from(right)
+ return a.length === b.length && timingSafeEqual(a, b)
+}
+
+function offeredProtocols(value: string | string[] | undefined): string[] {
+ const raw = Array.isArray(value) ? value.join(',') : value ?? ''
+ return raw.split(',').map((part) => part.trim()).filter(Boolean)
+}
+
+function rejectUpgrade(socket: Socket, status: number, reason: string): void {
+ if (socket.destroyed) return
+ socket.end(
+ `HTTP/1.1 ${status} ${reason}\r\n` +
+ 'Connection: close\r\n' +
+ 'Content-Length: 0\r\n' +
+ '\r\n',
+ )
+}
+
+function jsonFrame(raw: RawData): Frame | null {
+ const bytes = Buffer.isBuffer(raw)
+ ? raw
+ : raw instanceof ArrayBuffer
+ ? Buffer.from(raw)
+ : Array.isArray(raw)
+ ? Buffer.concat(raw)
+ : Buffer.alloc(0)
+ if (!bytes.length || bytes.length > MAX_JSON_BYTES) return null
+ try {
+ const value = JSON.parse(bytes.toString('utf8')) as unknown
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null
+ const frame = value as Frame
+ return typeof frame.type === 'string' && frame.type.length <= 100 ? frame : null
+ } catch {
+ return null
+ }
+}
+
+function binaryBytes(raw: RawData): Uint8Array {
+ if (Buffer.isBuffer(raw)) return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength)
+ if (raw instanceof ArrayBuffer) return new Uint8Array(raw)
+ if (Array.isArray(raw)) return new Uint8Array(Buffer.concat(raw))
+ return new Uint8Array()
+}
+
+/**
+ * Add an authenticated loopback WebSocket endpoint to the CLI's existing HTTP server.
+ * The machine API key is accepted only as a WebSocket subprotocol and is never returned by /api/status.
+ */
+export function attachLocalWsServer(server: http.Server, options: LocalWsServerOptions): LocalWsServer {
+ const wss = new WebSocketServer({
+ noServer: true,
+ maxPayload: MAX_JSON_BYTES,
+ handleProtocols: (protocols) =>
+ [...protocols].find((protocol) => secureEqual(protocol, options.token)) ?? false,
+ })
+
+ const onUpgrade = (req: http.IncomingMessage, socket: Socket, head: Buffer): void => {
+ const path = (req.url ?? '').split('?')[0]
+ if (path !== LOCAL_WS_PATH) return
+ if (!isLoopback(req.socket.remoteAddress)) {
+ rejectUpgrade(socket, 403, 'Forbidden')
+ return
+ }
+ if (req.headers.origin) {
+ rejectUpgrade(socket, 403, 'Forbidden')
+ return
+ }
+ const protocols = offeredProtocols(req.headers['sec-websocket-protocol'])
+ if (!protocols.some((protocol) => secureEqual(protocol, options.token))) {
+ rejectUpgrade(socket, 401, 'Unauthorized')
+ return
+ }
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))
+ }
+ server.on('upgrade', onUpgrade)
+
+ wss.on('connection', (ws) => {
+ const connId = `local:${randomUUID()}`
+ let selected = false
+ let alive = true
+ let chain = Promise.resolve()
+
+ const sink: LocalClientSink = {
+ sendFrame: (frame) => {
+ if (ws.readyState !== WebSocket.OPEN) return false
+ try { ws.send(JSON.stringify(frame)); return true } catch { return false }
+ },
+ sendBinary: (frame) => {
+ if (ws.readyState !== WebSocket.OPEN) return false
+ try { ws.send(frame, { binary: true }); return true } catch { return false }
+ },
+ }
+
+ const close = (code: number, reason: string): void => {
+ try { ws.close(code, reason) } catch { ws.terminate() }
+ }
+
+ ws.on('pong', () => { alive = true })
+ ws.on('message', (raw, isBinary) => {
+ chain = chain.then(async () => {
+ if (!selected) {
+ if (isBinary) { close(4400, 'machine_select required'); return }
+ const frame = jsonFrame(raw)
+ const payload = frame?.payload as Record<string, unknown> | undefined
+ if (frame?.type !== 'machine_select'
+ || payload?.machineId !== options.machineId
+ || payload?.localProtocolVersion !== LOCAL_WS_PROTOCOL_VERSION) {
+ close(4403, 'machine mismatch')
+ return
+ }
+ if (!options.backend.registerLocalClient(connId, sink)) {
+ close(1011, 'local registration failed')
+ return
+ }
+ selected = true
+ sink.sendFrame({
+ type: 'connected',
+ payload: {
+ machineId: options.machineId,
+ transport: 'local',
+ localProtocolVersion: LOCAL_WS_PROTOCOL_VERSION,
+ terminalProtocolVersion: TERMINAL_BINARY_VERSION,
+ e2ee: false,
+ },
+ })
+ return
+ }
+
+ if (isBinary) {
+ const frame = decodeTerminalLocal(binaryBytes(raw))
+ if (!frame) { close(4400, 'invalid terminal frame'); return }
+ await options.backend.handleLocalBinary(connId, frame)
+ return
+ }
+ const frame = jsonFrame(raw)
+ if (!frame) { close(4400, 'invalid json frame'); return }
+ options.backend.handleLocalFrame(connId, frame)
+ }).catch(() => close(1011, 'local dispatch failed'))
+ })
+
+ const heartbeat = setInterval(() => {
+ if (!alive) { ws.terminate(); return }
+ alive = false
+ try { ws.ping() } catch { ws.terminate() }
+ }, HEARTBEAT_MS)
+ heartbeat.unref?.()
+
+ const cleanup = (): void => {
+ clearInterval(heartbeat)
+ if (selected) void options.backend.unregisterLocalClient(connId)
+ selected = false
+ }
+ ws.once('close', cleanup)
+ ws.once('error', () => { /* close performs cleanup */ })
+ })
+
+ return {
+ close: async () => {
+ server.off('upgrade', onUpgrade)
+ for (const client of wss.clients) client.close(1001, 'server shutting down')
+ await new Promise<void>((resolve) => wss.close(() => resolve()))
+ },
+ }
+}