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(hook-server): refuse browser requests (Origin / non-loopback Host) before the bearer

reviewe182c0027552
diff --git a/src/core/agents/hook-browser-guard.test.ts b/src/core/agents/hook-browser-guard.test.ts
new file mode 100644
index 000000000..606c82a5c
--- /dev/null
+++ b/src/core/agents/hook-browser-guard.test.ts
@@ -0,0 +1,73 @@
+// The hook server's browser guard, as a pure decision. The real-transport proof that every client
+// we ship still passes it lives in hook-server.browser-guard.test.ts.
+import { describe, it, expect } from 'vitest'
+import { browserRequestRefusal, isLoopbackHostHeader } from './hook-browser-guard'
+
+describe('isLoopbackHostHeader', () => {
+ it('accepts every Host our clients send (measured: curl, node http, node fetch, Bun fetch)', () => {
+ for (const host of [
+ '127.0.0.1:41253', // curl / node http / fetch to the TCP listener
+ '127.0.0.1:52011', // the SSH loopback-TCP fallback: the HOST's port, not ours
+ 'localhost', // curl --unix-socket http://localhost/…, node http.request({socketPath})
+ 'localhost:0', // the codex launcher: http://localhost:${NODETERM_HOOK_PORT-0} over the socket
+ 'localhost:34357', // curl / fetch to http://localhost:<port>
+ 'LOCALHOST:80',
+ '127.0.0.1',
+ '[::1]',
+ '[::1]:8080'
+ ]) {
+ expect(isLoopbackHostHeader(host), host).toBe(true)
+ }
+ })
+
+ it('refuses every name a page could have the browser send (DNS rebinding) or a near miss', () => {
+ for (const host of [
+ 'evil.example',
+ 'evil.example:41253',
+ '127.0.0.1.evil.example',
+ '127.0.0.1.evil.example:41253',
+ 'localhost.evil.example',
+ 'localhost.',
+ 'evil-localhost',
+ 'localhost:abc',
+ 'localhost:',
+ 'localhost:123456',
+ '127.0.0.1:41253 ',
+ ' 127.0.0.1',
+ '127.0.0.2',
+ '0.0.0.0:41253',
+ '[::1]x',
+ '[::2]:80',
+ '::1',
+ '',
+ 'localhost\r\nX: y'
+ ]) {
+ expect(isLoopbackHostHeader(host), JSON.stringify(host)).toBe(false)
+ }
+ })
+})
+
+describe('browserRequestRefusal', () => {
+ it('passes the header sets our clients send', () => {
+ expect(browserRequestRefusal({ host: '127.0.0.1:41253' })).toBeNull()
+ expect(browserRequestRefusal({ host: 'localhost' })).toBeNull()
+ // Node's own fetch (undici) sends sec-fetch-mode, never an Origin: it must keep passing.
+ expect(browserRequestRefusal({ host: '127.0.0.1:1', 'sec-fetch-mode': 'cors' })).toBeNull()
+ })
+
+ it('a request with no Host header at all is not refused (no browser can send one)', () => {
+ expect(browserRequestRefusal({})).toBeNull()
+ })
+
+ it('refuses ANY Origin header, whatever its value, before the Host is even looked at', () => {
+ for (const origin of ['https://evil.example', 'null', 'http://127.0.0.1:41253', 'http://localhost', '']) {
+ expect(browserRequestRefusal({ host: '127.0.0.1:41253', origin }), origin).toMatch(/origin/i)
+ }
+ // Node joins a repeated Origin header with ', ' — still an Origin.
+ expect(browserRequestRefusal({ host: '127.0.0.1:41253', origin: 'https://a.example, https://b.example' })).toMatch(/origin/i)
+ })
+
+ it('refuses a non-loopback Host', () => {
+ expect(browserRequestRefusal({ host: 'evil.example:41253' })).toMatch(/host/i)
+ })
+})
diff --git a/src/core/agents/hook-browser-guard.ts b/src/core/agents/hook-browser-guard.ts
new file mode 100644
index 000000000..18e812ad0
--- /dev/null
+++ b/src/core/agents/hook-browser-guard.ts
@@ -0,0 +1,56 @@
+// The hook server's browser guard: belt-and-braces in front of the bearer.
+//
+// The hook server listens on 127.0.0.1 and on a 0600 unix socket, and every route sits behind the
+// `x-nodeterm-hook-token` bearer. That bearer is the real gate and stays the real gate. What this
+// adds is a second, independent refusal for the one caller class that can reach a loopback port
+// without being a process of ours: a web page in the user's browser.
+//
+// - A cross-origin page cannot read our replies, and a custom header forces a preflight we never
+// answer — but a page that has DNS-rebound its own name to 127.0.0.1 is same-origin with us, and
+// then only the unguessable bearer (and the ephemeral port) stood in its way.
+// - Every browser sends `Origin` on a POST (fetch, XHR, form, sendBeacon), and sends the PAGE's
+// host name in `Host`. None of our clients send `Origin`, and all of them send a loopback name.
+//
+// MEASURED (2026-10-23), every client that posts to this server, both transports:
+// curl --unix-socket … http://localhost/… Host: localhost (managed hook scripts,
+// nodeterm.sh, context.sh,
+// the failover probe, the
+// remote tunnel probe)
+// curl --unix-socket … http://localhost:0/… Host: localhost:0 (codex launcher)
+// curl http://127.0.0.1:<port>/… Host: 127.0.0.1:<port> (TCP, and the SSH
+// loopback-TCP fallback,
+// whose port is the HOST's)
+// node http.request({socketPath}) Host: localhost (codex relay daemon,
+// endpoint owner probe)
+// node http.request({hostname:'127.0.0.1',port}) Host: 127.0.0.1:<port>
+// node fetch (undici) Host: 127.0.0.1:<port>, sec-fetch-mode: cors,
+// no Origin (tests)
+// Bun 1.3.14 fetch (opencode's runtime), unix and TCP: Host localhost / 127.0.0.1:<port>, no Origin
+// No client sends Origin. The SSH reverse tunnel forwards bytes, so a host-side curl's Host header
+// arrives here unchanged.
+//
+// A request with NO Host header is not refused: Node already answers 400 to an HTTP/1.1 request
+// without one (`requireHostHeader`), so only an HTTP/1.0 client can get here without it, and no
+// browser sends a request without a Host.
+
+import type { IncomingHttpHeaders } from 'http'
+
+/** The Host names we answer to. A port, when present, may be any port: the SSH loopback-TCP
+ * fallback arrives with the HOST's listener port, and the codex launcher's socket URL uses 0. */
+const LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d{1,5})?$/i
+
+export function isLoopbackHostHeader(host: string): boolean {
+ return LOOPBACK_HOST.test(host)
+}
+
+/** Why this request is refused before the bearer is looked at, or null to let it through. */
+export function browserRequestRefusal(headers: IncomingHttpHeaders): string | null {
+ if (headers.origin !== undefined) {
+ return 'hook-endpoint-refused: requests carrying an Origin header (a browser) are not accepted.'
+ }
+ const host = headers.host
+ if (host !== undefined && !isLoopbackHostHeader(host)) {
+ return 'hook-endpoint-refused: the Host header is not a loopback name.'
+ }
+ return null
+}
diff --git a/src/core/agents/hook-server.browser-guard.test.ts b/src/core/agents/hook-server.browser-guard.test.ts
new file mode 100644
index 000000000..6c57721e5
--- /dev/null
+++ b/src/core/agents/hook-server.browser-guard.test.ts
@@ -0,0 +1,137 @@
+// The browser guard against the REAL server, driven by the REAL clients' transports: curl over the
+// unix socket and over loopback TCP (the generated sh clients and the SSH tunnel's host-side
+// curl), Node's http over the socket (the codex relay daemon, the endpoint owner probe) and Node's
+// fetch. A guard that refused any one of them would silently cost that client its hooks — the
+// pure decision lives in hook-browser-guard.test.ts; this file proves it is wired in front of the
+// bearer on BOTH listeners and that every shipped client shape still gets through.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFile } from 'node:child_process'
+import fs from 'node:fs'
+import net from 'node:net'
+import os from 'node:os'
+import path from 'node:path'
+import { request } from 'node:http'
+import { promisify } from 'node:util'
+import { hookServer } from './hook-server'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform } from '../platform-fake'
+
+const run = promisify(execFile)
+
+let dir = ''
+let reached = 0
+
+beforeAll(async () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-browser-guard-'))
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ await hookServer.start()
+ hookServer.setControlHandler(async (cmd) => {
+ reached++
+ return { ok: true, message: `did ${cmd.verb}` }
+ })
+})
+
+afterAll(() => {
+ hookServer.stop()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+const bearer = (): Record<string, string> => ({ 'X-Nodeterm-Hook-Token': hookServer.getToken() })
+
+/** The real curl. `url` decides the Host curl sends, exactly as in the generated scripts. */
+async function curl(
+ transport: 'sock' | 'tcp',
+ url: string,
+ headers: Record<string, string>
+): Promise<{ status: string; body: string }> {
+ const out = path.join(dir, `curl-out-${Math.random().toString(36).slice(2)}`)
+ const args = ['-sS', '-o', out, '-w', '%{http_code}', '-X', 'POST']
+ if (transport === 'sock') args.push('--unix-socket', hookServer.getSockPath())
+ args.push(url, '-H', 'Accept: text/plain')
+ for (const [k, v] of Object.entries(headers)) args.push('-H', `${k}: ${v}`)
+ args.push('--data-urlencode', 'nodeId=node-1')
+ const { stdout } = await run('curl', args)
+ const body = fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : ''
+ fs.rmSync(out, { force: true })
+ return { status: stdout.trim(), body }
+}
+
+const tcpUrl = (p: string, host = '127.0.0.1'): string => `http://${host}:${hookServer.getPort()}${p}`
+
+describe.skipIf(process.platform === 'win32')('the browser guard on the real hook server', () => {
+ it('every shipped client transport still reaches the handler', async () => {
+ reached = 0
+ // The managed hook scripts, nodeterm.sh, context.sh and the failover probe over the socket.
+ expect(await curl('sock', 'http://localhost/control/list', bearer())).toEqual({ status: '200', body: 'did list\n' })
+ // The codex launcher's socket URL carries a port of 0 (`localhost:${NODETERM_HOOK_PORT-0}`).
+ expect((await curl('sock', 'http://localhost:0/control/list', bearer())).status).toBe('200')
+ // The same scripts over loopback TCP.
+ expect((await curl('tcp', tcpUrl('/control/list'), bearer())).status).toBe('200')
+ expect((await curl('tcp', tcpUrl('/control/list', 'localhost'), bearer())).status).toBe('200')
+ // The SSH loopback-TCP fallback: the host-side curl names the HOST's listener port, which is
+ // not ours. The bytes are forwarded unchanged, so that Host arrives here.
+ expect((await curl('tcp', tcpUrl('/control/list'), { ...bearer(), Host: '127.0.0.1:52011' })).status).toBe('200')
+ // Node's http over the socket (codex relay daemon, endpoint owner probe): Host is `localhost`.
+ const viaNode = await new Promise<number>((resolve, reject) => {
+ const req = request(
+ { socketPath: hookServer.getSockPath(), path: '/verify', method: 'POST', headers: bearer() },
+ (res) => {
+ res.resume()
+ res.on('end', () => resolve(res.statusCode ?? 0))
+ }
+ )
+ req.on('error', reject)
+ req.end()
+ })
+ expect(viaNode).toBe(204)
+ // Node's fetch sends `sec-fetch-mode: cors` (measured) but no Origin.
+ const viaFetch = await fetch(tcpUrl('/verify'), { method: 'POST', headers: bearer() })
+ expect(viaFetch.status).toBe(204)
+ expect(reached).toBe(5)
+ })
+
+ it('refuses a request carrying an Origin, on both listeners, even with the right bearer', async () => {
+ reached = 0
+ const evil = { ...bearer(), Origin: 'https://evil.example' }
+ for (const r of [
+ await curl('sock', 'http://localhost/control/list', evil),
+ await curl('tcp', tcpUrl('/control/list'), evil),
+ // A page served from the loopback origin itself (or a sandboxed iframe's `null`) is still a page.
+ await curl('tcp', tcpUrl('/control/list'), { ...bearer(), Origin: `http://127.0.0.1:${hookServer.getPort()}` }),
+ await curl('tcp', tcpUrl('/control/list'), { ...bearer(), Origin: 'null' })
+ ]) {
+ expect(r.status).toBe('403')
+ expect(r.body).toMatch(/Origin/)
+ }
+ expect(reached).toBe(0)
+ })
+
+ it('refuses a DNS-rebound Host, even with the right bearer', async () => {
+ reached = 0
+ for (const host of [`evil.example:${hookServer.getPort()}`, `127.0.0.1.evil.example:${hookServer.getPort()}`]) {
+ const r = await curl('tcp', tcpUrl('/control/list'), { ...bearer(), Host: host })
+ expect(r.status, host).toBe('403')
+ expect(r.body).toMatch(/Host/)
+ }
+ expect(reached).toBe(0)
+ })
+
+ it('a refused browser request learns nothing about the bearer (no 421 wrong-owner answer)', async () => {
+ const r = await curl('tcp', tcpUrl('/control/list'), { 'X-Nodeterm-Hook-Token': 'guess', Origin: 'https://evil.example' })
+ expect(r.status).toBe('403')
+ })
+
+ it('an HTTP/1.0 request with no Host header still reaches the bearer check', async () => {
+ const status = await new Promise<string>((resolve, reject) => {
+ const s = net.connect(hookServer.getPort(), '127.0.0.1', () => {
+ s.write(`POST /verify HTTP/1.0\r\nX-Nodeterm-Hook-Token: ${hookServer.getToken()}\r\nContent-Length: 0\r\n\r\n`)
+ })
+ let buf = ''
+ s.on('data', (d) => (buf += d.toString()))
+ s.on('end', () => resolve(buf.split(' ')[1] ?? ''))
+ s.on('error', reject)
+ })
+ expect(status).toBe('204')
+ })
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 6d298cf7d..733e8a35d 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -12,6 +12,7 @@ import { platform } from '../platform'
import { writeFileAtomic } from '../fs-atomic'
import { parseEndpointEnv } from './hook-endpoint-parse'
import { hookSockPath } from './hook-sock-path'
+import { browserRequestRefusal } from './hook-browser-guard'
import { canControlCanvas, type AgentId } from '../../shared/agents/config'
import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'
import {
@@ -822,6 +823,16 @@ export class HookServer {
res.end()
return
}
+ // Belt-and-braces BEFORE the bearer: a browser page (DNS rebinding included) is refused
+ // on the Origin / Host it cannot help sending, and learns nothing about the bearer — not
+ // even the 403-vs-421 distinction below. The bearer stays the real gate; every client we
+ // ship passes this unchanged (measured list in hook-browser-guard.ts).
+ const browserRefusal = browserRequestRefusal(req.headers)
+ if (browserRefusal) {
+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' })
+ res.end(`${browserRefusal}\n`)
+ return
+ }
if (!this.tokenMatches(req.headers['x-nodeterm-hook-token'])) {
if (!req.headers['x-nodeterm-hook-token']) {
res.writeHead(403)