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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(security): serve the daemon's loopback ports only to requests addressed to them (OH-4) (#349)
0xken15a6d89fd2cb20
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 663903944..fa90a4913 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -177,6 +177,7 @@ import type { CableAgent } from './cable/cableSession.js'import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'import { E2eeStore } from './lib/e2ee/store.js'+import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'import { b64e } from './lib/e2ee/core.js'import { MachinePeerStore } from './lib/e2ee/machinePeers.js'import { connectWithPassword } from './lib/e2ee/relayClient.js'@@ -7019,7 +7020,9 @@ const enterSafeMode = (err: unknown): void => {// itself was what failed, or we never got that far — take the port for the status alone, so the app// still reads not-ready rather than down. A port we cannot take at all leaves only a ticking clock.if (!daemonBoot.hookServer) {+ const hosts = loopbackHosts(env.PORT)const status = createServer((req, res) => {+ if (!isLoopbackRequest(req, hosts)) { res.writeHead(403).end(); return }const body = safeModeStatusBody({version: VERSION, pid: process.pid, startedAt: Date.now(),computerId: computerId(), error: disposition.reason,diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 17d205e6f..972dc3da6 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -1,4 +1,4 @@-import type { Server } from 'node:http'+import { request, type Server } from 'node:http'import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'@@ -328,3 +328,40 @@ describe('browser setup links are gone', () => {expect(await response.text()).not.toContain('setup=browser')})})++describe('requests must name this server', () => {+ // A page that re-points its hostname at 127.0.0.1 is same-origin to this port; only its Host gives it away.+ async function send(base: string, method: string, path: string, headers: Record<string, string>): Promise<number> {+ const url = new URL(path, base)+ return new Promise((resolve, reject) => {+ const r = request({ host: '127.0.0.1', port: url.port, path: url.pathname, method, headers }, (res) => { res.resume(); resolve(res.statusCode ?? 0) })+ r.on('error', reject)+ r.end()+ })+ }++ it('refuses every route, reads included, when Host is not a loopback name for this port', async () => {+ const onStatus = vi.fn(() => ({ ok: true }))+ const onLogs = vi.fn(() => 'secret log')+ const { base } = await start({ onStatus, onLogs })+ const evil = { host: 'rebind.evil.example:' + new URL(base).port }+ for (const [method, path, extra] of [+ ['GET', '/api/status', {}], ['GET', '/api/logs', {}], ['GET', '/', {}], ['GET', '/api/machines', {}],+ ['POST', '/api/remote-password/set', { 'x-adapter-local': '1' }], ['POST', '/api/stop', { 'x-adapter-local': '1' }],+ ] as const) {+ expect(await send(base, method, path, { ...evil, ...extra }), `${method} ${path}`).toBe(403)+ }+ expect(onStatus).not.toHaveBeenCalled()+ expect(onLogs).not.toHaveBeenCalled()+ })++ it('still serves loopback names, and the dashboard from its own origin', async () => {+ const { base } = await start({ onStatus: () => ({ ok: true }) })+ const port = new URL(base).port+ for (const host of [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]) {+ expect(await send(base, 'GET', '/api/status', { host }), host).toBe(200)+ }+ expect(await send(base, 'GET', '/api/status', { host: `localhost:${port}`, origin: `http://localhost:${port}` })).toBe(200)+ expect(await send(base, 'GET', '/api/status', { host: `127.0.0.1:${port}`, origin: 'http://evil.example' })).toBe(403)+ })+})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 6cc458872..893f30f9b 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -23,6 +23,7 @@ import type { HookTerminalHint } from './lib/terminalTypes.js'import { ENGINES, type AgentEngine } from './engines/types.js'import type { CommandBarService } from './lib/commandBar.js'import { handleCommandBarHttp } from './lib/commandBarHttp.js'+import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'/*** Which agent does a hook belong to, given the two grades of evidence?@@ -371,6 +372,9 @@ export function startHookServer(handlers: HookServerHandlers,): Promise<{ server: http.Server; port: number }> {const hookCredential = loadOrCreateHookCredential(env.ADAPTER_DATA_DIR)+ // Filled in once the port is bound: the Host a request must name is the port actually taken.+ let hosts: ReadonlySet<string> = new Set()+ let lastRefusalLogAt = 0const server = http.createServer((req, res) => {void (async () => {const url = (req.url ?? '').split('?')[0]@@ -378,6 +382,17 @@ export function startHookServer(res.writeHead(code, { 'Content-Type': 'application/json' })res.end(JSON.stringify(body))}+ // Before any route, reads included. See lib/loopbackRequest.ts.+ if (!isLoopbackRequest(req, hosts)) {+ // At most one line a minute: enough to explain a client that was refused, not a lever for a+ // page to flood the log. Host and Origin are the sender's, so they are escaped and bounded.+ if (Date.now() - lastRefusalLogAt > 60_000) {+ lastRefusalLogAt = Date.now()+ const shown = (v: unknown) => JSON.stringify(String(v ?? '').slice(0, 80))+ console.warn(`[hooks] refused ${req.method} ${url.slice(0, 80)} · host=${shown(req.headers.host)} origin=${shown(req.headers.origin)}`)+ }+ json(403, { error: 'FORBIDDEN_HOST' }); return+ }// A handler that throws must still answer: this whole function is a void-discarded async, so// a throw here is an unhandledRejection and a request that hangs until the caller gives up —// which, for the desktop app, is a 30s timeout that names Dio instead of the fault.@@ -734,6 +749,7 @@ export function startHookServer(})server.listen(port, '127.0.0.1', () => {const actual = (server.address() as AddressInfo).port+ hosts = loopbackHosts(actual)console.log(`[hooks] listening on 127.0.0.1:${actual} (SessionStart/SessionEnd callbacks)`)resolve({ server, port: actual })})diff --git a/cli/src/lib/loopbackRequest.spec.ts b/cli/src/lib/loopbackRequest.spec.tsnew file mode 100644index 000000000..5b6048641--- /dev/null+++ b/cli/src/lib/loopbackRequest.spec.ts@@ -0,0 +1,28 @@+import type { IncomingMessage } from 'http'+import { describe, expect, it } from 'vitest'+import { isLoopbackRequest, loopbackHosts } from './loopbackRequest.js'++const hosts = loopbackHosts(18473)+const req = (headers: Record<string, string>) => ({ headers } as unknown as IncomingMessage)++describe('isLoopbackRequest', () => {+ it('serves the names every native caller and the dashboard use, on the bound port only', () => {+ for (const host of ['127.0.0.1:18473', 'localhost:18473', '[::1]:18473', 'LOCALHOST:18473']) {+ expect(isLoopbackRequest(req({ host }), hosts)).toBe(true)+ }+ for (const host of ['127.0.0.1:18474', '127.0.0.1', 'evil.example:18473', 'evil.example', '']) {+ expect(isLoopbackRequest(req({ host }), hosts)).toBe(false)+ }+ expect(isLoopbackRequest(req({}), hosts)).toBe(false)+ })++ it('takes a browser request only from its own loopback origin', () => {+ expect(isLoopbackRequest(req({ host: '127.0.0.1:18473', origin: 'http://127.0.0.1:18473' }), hosts)).toBe(true)+ expect(isLoopbackRequest(req({ host: 'localhost:18473', origin: 'http://localhost:18473' }), hosts)).toBe(true)+ expect(isLoopbackRequest(req({ host: '127.0.0.1:18473', origin: 'http://evil.example' }), hosts)).toBe(false)+ expect(isLoopbackRequest(req({ host: '127.0.0.1:18473', origin: 'http://localhost:18473' }), hosts)).toBe(false)+ expect(isLoopbackRequest(req({ host: '127.0.0.1:18473', origin: 'null' }), hosts)).toBe(false)+ expect(isLoopbackRequest(req({ host: '127.0.0.1:18473', 'sec-fetch-site': 'cross-site' }), hosts)).toBe(false)+ expect(isLoopbackRequest(req({ host: '127.0.0.1:18473', 'sec-fetch-site': 'same-origin' }), hosts)).toBe(true)+ })+})diff --git a/cli/src/lib/loopbackRequest.ts b/cli/src/lib/loopbackRequest.tsnew file mode 100644index 000000000..51447b20b--- /dev/null+++ b/cli/src/lib/loopbackRequest.ts@@ -0,0 +1,28 @@+/**+ * Whether an HTTP request to one of the daemon's loopback servers was really addressed to it.+ *+ * Binding 127.0.0.1 keeps other machines out, not other ORIGINS: a web page that re-points its own+ * hostname at 127.0.0.1 reaches these ports as a same-origin page and reads whatever answers. What it+ * cannot do is change the Host its browser sends — that stays the page's own name — so a request is+ * served only when Host names this server, and a browser request only when its Origin is that name too.+ *+ * Every native caller (the desktop app, the CLI, engine hooks, store agents) sends a loopback Host and+ * no Origin; the dashboard sends its own loopback origin. Nothing legitimate is refused.+ */+import type { IncomingMessage } from 'http'++const LOOPBACK_NAMES = ['127.0.0.1', 'localhost', '[::1]']++/** The `host:port` values that name a loopback server on `port` — the port it actually bound. */+export function loopbackHosts(port: number): Set<string> {+ return new Set(LOOPBACK_NAMES.map((name) => `${name}:${port}`))+}++export function isLoopbackRequest(req: IncomingMessage, hosts: ReadonlySet<string>): boolean {+ const host = req.headers.host?.toLowerCase()+ if (!host || !hosts.has(host)) return false+ const origin = req.headers.origin+ if (origin !== undefined && origin !== `http://${host}`) return false+ // Defence in depth for browsers that omit Origin on a GET: they still say where the request began.+ return req.headers['sec-fetch-site'] !== 'cross-site'+}diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex a660f434e..a0c543468 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -71,6 +71,13 @@ describe('local CLI WebSocket', () => {return `ws://127.0.0.1:${port}/api/local-ws`}+ it('refuses an upgrade whose Host is not a loopback name for this port', async () => {+ const url = await start(new FakeBackend())+ const ws = new WebSocket(url, { headers: { host: 'rebind.evil.example:' + new URL(url).port } })+ const status = await new Promise<number>((resolve) => ws.once('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)))+ expect(status).toBe(403)+ })+it('consumes validated preparation UI acknowledgements locally', async () => {const backend = new FakeBackend(), opened = vi.fn()const ws = new WebSocket(await start(backend, { onDevicePrepareOpened: opened }))diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 617e2034e..b4c46fdcb 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -5,6 +5,7 @@ import type http from 'node:http'import type { Socket } from 'node:net'import { WebSocket, WebSocketServer, type RawData } from 'ws'import { watchSocketLiveness } from './lib/wsLiveness.js'+import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'import type { Frame, LocalClientSink } from './backendSocket.js'import {decodeTerminalLocal,@@ -242,7 +243,9 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOrejectUpgrade(socket, 403, 'Forbidden')return}- if (req.headers.origin) {+ // Also refuses any Origin: a browser always sends one on a WebSocket, and no browser is a client.+ const bound = server.address()+ if (req.headers.origin || !bound || typeof bound === 'string' || !isLoopbackRequest(req, loopbackHosts(bound.port))) {rejectUpgrade(socket, 403, 'Forbidden')return}