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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(hooks): hook server listens on a unix domain socket beside loopback TCP
Claude Codec70b611c9337
diff --git a/src/core/agents/codex-thread-id-route.test.ts b/src/core/agents/codex-thread-id-route.test.tsindex 576fa1852..92735c83e 100644--- a/src/core/agents/codex-thread-id-route.test.ts+++ b/src/core/agents/codex-thread-id-route.test.ts@@ -75,8 +75,10 @@ describe('/codex-thread/bind refuses a path-unsafe thread id', () => {}expect(bound).toEqual([])// Nothing anywhere: not in the store, and — the `..` row — not in the store's parent either.+ // (`sock/` is the hook server's own unix-socket listener dir, issue #367 — always present,+ // never a record.)expect(existsSync(codexThreadIdentityRoot())).toBe(false)- expect(readdirSync(dir)).toEqual(['hook-endpoint.env'])+ expect(readdirSync(dir).sort()).toEqual(['hook-endpoint.env', 'sock'])})it('still binds a thread id the app-server would actually mint', async () => {diff --git a/src/core/agents/hook-identity-enforcement.test.ts b/src/core/agents/hook-identity-enforcement.test.tsindex d5ba04f0a..87d0a9ba0 100644--- a/src/core/agents/hook-identity-enforcement.test.ts+++ b/src/core/agents/hook-identity-enforcement.test.ts@@ -361,7 +361,10 @@ describe('the latch is memory, not state', () => {const walk = (root: string): string[] =>readdirSync(root).flatMap((entry) => {const full = join(root, entry)- return statSync(full).isDirectory() ? walk(full) : [full]+ const st = statSync(full)+ // Regular files only: the hook server's own unix socket (issue #367) lives under the data+ // dir too, and a socket is not readable state — opening it is ENXIO, not evidence.+ return st.isDirectory() ? walk(full) : st.isFile() ? [full] : []})for (const file of walk(dir)) {// A persisted latch is a node that one filesystem accident can brick forever. Nothing ondiff --git a/src/core/agents/hook-server.sock.test.ts b/src/core/agents/hook-server.sock.test.tsnew file mode 100644index 000000000..6d5be30f5--- /dev/null+++ b/src/core/agents/hook-server.sock.test.ts@@ -0,0 +1,163 @@+// The hook server's unix-socket listener (issue #367), exercised with the REAL curl against the+// REAL server — the same discipline as canvas-control-shim.test.ts, because the consumers of this+// listener are generated sh clients whose transport is exactly `curl --unix-socket`.+//+// What must hold: the socket answers the SAME routes through the SAME handler under the SAME auth+// as loopback TCP (it is a second door to one room, never a side entrance around the bearer or the+// per-node verdict); it sits at 0600 inside a 0700 dir; a stale socket file from a crash never+// blocks the next boot; and it is advertised — posixQuoted in the endpoint file (#358) and as+// NODETERM_HOOK_SOCK in the session env — only when it actually bound.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFile } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'+import { hookServer } from './hook-server'+import { nodeAuthToken } from './node-auth-token'+import { parseEndpointEnv } from './hook-endpoint-parse'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'++const run = promisify(execFile)++let dir = ''+let received: { verb: string; nodeId: string; verified: boolean }[] = []++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-sockls-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setControlHandler(async (cmd) => {+ received.push({ verb: cmd.verb, nodeId: cmd.nodeId, verified: cmd.verified })+ return { ok: true, message: `did ${cmd.verb}` }+ })+})++afterAll(() => {+ hookServer.stop()+ fs.rmSync(dir, { recursive: true, force: true })+})++interface CurlReply {+ status: string+ body: string+}++/** POST a /control/ request with the real curl, over the socket or over loopback TCP. */+async function post(+ transport: { sock?: string; port?: number },+ verb: string,+ headers: Record<string, string>,+ nodeId = 'node-1'+): Promise<CurlReply> {+ 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', transport.sock, `http://localhost/control/${verb}`)+ else args.push(`http://127.0.0.1:${transport.port}/control/${verb}`)+ args.push('-H', 'Accept: text/plain')+ for (const [k, v] of Object.entries(headers)) args.push('-H', `${k}: ${v}`)+ args.push('--data-urlencode', `nodeId=${nodeId}`)+ 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 }+}++describe('hook server unix-socket listener', () => {+ it('binds hook.sock at 0600 inside a 0700 sock/ dir under the data dir', () => {+ const sock = hookServer.getSockPath()+ expect(sock).toBe(path.join(dir, 'sock', 'hook.sock'))+ expect(fs.statSync(sock).mode & 0o777).toBe(0o600)+ expect(fs.statSync(path.dirname(sock)).mode & 0o777).toBe(0o700)+ })++ it('advertises it quoted in the endpoint file (#358 parser reads it back) and in buildPtyEnv', () => {+ const sock = hookServer.getSockPath()+ const raw = fs.readFileSync(hookServer.endpointFilePath(), 'utf8')+ expect(raw).toContain(`NODETERM_HOOK_SOCK='${sock}'\n`)+ expect(parseEndpointEnv(raw).NODETERM_HOOK_SOCK).toBe(sock)+ // ...while the TCP coordinates STAY: sessions holding a pre-socket script still connect.+ expect(Number(parseEndpointEnv(raw).NODETERM_HOOK_PORT)).toBe(hookServer.getPort())+ expect(hookServer.buildPtyEnv('n1', 'claude').NODETERM_HOOK_SOCK).toBe(sock)+ })++ it('answers the same route, through the same handler, on both transports', async () => {+ received = []+ const auth = { 'X-Nodeterm-Hook-Token': hookServer.getToken() }+ const viaSock = await post({ sock: hookServer.getSockPath() }, 'list', auth)+ const viaTcp = await post({ port: hookServer.getPort() }, 'list', auth)+ expect(viaSock).toEqual({ status: '200', body: 'did list\n' })+ expect(viaTcp).toEqual(viaSock)+ expect(received).toEqual([+ { verb: 'list', nodeId: 'node-1', verified: false },+ { verb: 'list', nodeId: 'node-1', verified: false }+ ])+ })++ // THE MUTATION GUARD the socket must carry: it is a second transport, not an auth bypass. A+ // mutation that skips (or always-passes) the bearer check turns both cases red.+ it('refuses a missing or wrong bearer over the socket, without reaching the handler', async () => {+ received = []+ const sock = hookServer.getSockPath()+ expect((await post({ sock }, 'list', {})).status).toBe('403')+ expect((await post({ sock }, 'list', { 'X-Nodeterm-Hook-Token': 'wrong' })).status).toBe('403')+ expect(received).toEqual([])+ })++ it('rebinds cleanly over a stale socket file left by a crash', async () => {+ const sock = hookServer.getSockPath()+ hookServer.stop()+ expect(fs.existsSync(sock)).toBe(false) // stop() unlinked its own socket+ // A crash skips stop(): fake the leftover. Anything occupying the path blocks bind with+ // EADDRINUSE unless the server unlinks first — the StreamLocalBindUnlink lesson.+ fs.mkdirSync(path.dirname(sock), { recursive: true })+ fs.writeFileSync(sock, '')+ await hookServer.start()+ hookServer.setControlHandler(async (cmd) => {+ received.push({ verb: cmd.verb, nodeId: cmd.nodeId, verified: cmd.verified })+ return { ok: true, message: `did ${cmd.verb}` }+ })+ expect(hookServer.getSockPath()).toBe(sock)+ const reply = await post({ sock }, 'list', { 'X-Nodeterm-Hook-Token': hookServer.getToken() })+ expect(reply).toEqual({ status: '200', body: 'did list\n' })+ })+})++// The per-node identity machinery must be transport-agnostic: the verified-only verbs (sticky &+// co.) demand a token THIS instance minted for THAT node id, on the socket exactly as on TCP.+describe('unix-socket listener — verified-only verbs keep their gate', () => {+ const SECRET = Buffer.alloc(32, 9)++ beforeAll(() => {+ hookServer.setNodeAuthSecret(SECRET)+ })++ afterAll(() => {+ hookServer.clearNodeAuthSecretForTests()+ })++ it('sticky over the socket: refused without the per-node token, verified with it', async () => {+ const sock = hookServer.getSockPath()+ const bearer = { 'X-Nodeterm-Hook-Token': hookServer.getToken() }+ const refused = await post({ sock }, 'sticky', bearer)+ expect(refused.status).toBe('403')+ expect(refused.body).toContain('Sticky write refused.')+ received = []+ const ok = await post({ sock }, 'sticky', {+ ...bearer,+ 'X-Nodeterm-Node-Token': nodeAuthToken(SECRET, 'node-1')+ })+ expect(ok.status).toBe('200')+ expect(received).toEqual([{ verb: 'sticky', nodeId: 'node-1', verified: true }])+ })++ it("another node's token is refused over the socket too (forged, hard 403)", async () => {+ const reply = await post({ sock: hookServer.getSockPath() }, 'list', {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'X-Nodeterm-Node-Token': nodeAuthToken(SECRET, 'node-OTHER')+ })+ expect(reply.status).toBe('403')+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex fba6cae34..60955d4f5 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -1,8 +1,9 @@import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'import { randomUUID, timingSafeEqual } from 'crypto'-import { writeFileSync, mkdirSync } from 'fs'+import { writeFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'import path from 'path'import { platform } from '../platform'+import { hookSockPath } from './hook-sock-path'import { canControlCanvas, type AgentId } from '../../shared/agents/config'import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'import type { CodexIdentityEvent } from '../../shared/types'@@ -216,6 +217,19 @@ export function verifiedRefusalFor(verb: string): string {class HookServer {private server: Server | null = null+ /**+ * The unix-domain twin of the loopback TCP listener (issue #367). Same HTTP handler, same+ * bearer + per-node token auth — the whole identity machinery is transport-agnostic (nothing+ * in the handler reads `remoteAddress`), so the socket is never an auth bypass. Two reasons it+ * exists: it lets a sandboxed macOS Codex regain hook connectivity via codex's+ * `network.allow_unix_sockets` allowlist (the TCP loopback can never be allowlisted), and it+ * pays down #195's debt that ANY local user could reach the TCP port at all (the socket lives+ * in a 0700 dir at 0600). The TCP listener STAYS: existing tmux panes hold pre-socket env, and+ * the Linux codex sandbox blocks unix sockets anyway. Best-effort: if the socket cannot bind,+ * nothing advertises it and everything runs on TCP exactly as before.+ */+ private unixServer: Server | null = null+ private sockPath = ''private port = 0private token = ''private listener: ((e: NormalizedAgentEvent) => void) | null = null@@ -300,6 +314,10 @@ class HookServer {getPort(): number {return this.port}+ /** The unix listener's socket path, or '' when it is not live (bind failed, win32). */+ getSockPath(): string {+ return this.sockPath+ }getToken(): string {return this.token}@@ -475,7 +493,9 @@ class HookServer {async start(): Promise<void> {if (this.server) returnthis.token = randomUUID()- this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {+ // ONE handler, shared verbatim by the TCP and the unix-socket listeners: every gate (bearer,+ // per-node verdict, verified-only verbs) runs identically on both transports.+ const handler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {// Hooks fail open: any error path still ends 204 so a broken hook never blocks the agent.try {if (req.method !== 'POST') {@@ -705,7 +725,8 @@ class HookServer {res.writeHead(204)res.end()}- })+ }+ this.server = createServer(handler)await new Promise<void>((resolve, reject) => {const onErr = (e: Error): void => {this.server?.off('listening', onOk)@@ -716,12 +737,65 @@ class HookServer {this.server?.on('error', (e) => console.error('[agent-hooks] server error', e))const addr = this.server!.address()if (addr && typeof addr === 'object') this.port = addr.port- this.writeEndpointFile()resolve()}this.server!.once('error', onErr)this.server!.listen(0, '127.0.0.1', onOk)})+ // Second leg, then ONE endpoint write that advertises whatever actually came up. A failed+ // socket bind must not cost the TCP endpoint file (or the boot).+ await this.startUnixListener(handler)+ this.writeEndpointFile()+ }++ /** Bind the unix-socket twin (see `unixServer`). Never throws — a socket that cannot bind is+ * simply not advertised, and everything keeps running on loopback TCP. */+ private async startUnixListener(+ handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>+ ): Promise<void> {+ // Node's AF_UNIX support on Windows is not the discipline this path was built around, and no+ // generated sh client runs there anyway.+ if (process.platform === 'win32') return+ const p = hookSockPath(platform().userDataDir)+ try {+ const dir = path.dirname(p)+ mkdirSync(dir, { recursive: true, mode: 0o700 })+ // mkdir's mode is ignored when the dir already exists — enforce it, because the DIRECTORY+ // mode is what actually keeps other local users off the socket (the file chmod below only+ // lands after listen, and the socket is world-connectable for that instant otherwise).+ chmodSync(dir, 0o700)+ // A stale socket file BLOCKS bind with EADDRINUSE even when nothing is listening — the+ // StreamLocalBindUnlink lesson from the SSH reverse tunnels. Unlink-then-bind is safe here:+ // the path is ours alone (0700 dir, digest-keyed fallback), so anything at it is our own+ // leftover from a crash.+ try {+ unlinkSync(p)+ } catch {+ /* nothing stale to clear */+ }+ const srv = createServer(handler)+ await new Promise<void>((resolve, reject) => {+ const onErr = (e: Error): void => {+ srv.off('listening', onOk)+ reject(e)+ }+ const onOk = (): void => {+ srv.off('error', onErr)+ resolve()+ }+ srv.once('error', onErr)+ srv.once('listening', onOk)+ srv.listen(p)+ })+ chmodSync(p, 0o600)+ srv.on('error', (e) => console.error('[agent-hooks] unix listener error', e))+ this.unixServer = srv+ this.sockPath = p+ } catch (e) {+ console.warn('[agent-hooks] unix hook socket unavailable, staying TCP-only', e)+ this.unixServer = null+ this.sockPath = ''+ }}// Constant-time bearer-token check (avoids a timing side channel on the compare).@@ -941,7 +1015,13 @@ class HookServer {// Advertised (not compiled in) so a failover that sources ANOTHER instance's endpoint// file also picks up THAT instance's token dir: it then finds a token that instance can// verify, or none — never a mismatched one.- `NODETERM_NODE_TOKEN_DIR=${posixQuote(nodeTokenDir())}\n`,+ `NODETERM_NODE_TOKEN_DIR=${posixQuote(nodeTokenDir())}\n` ++ // The unix-socket twin, only when it actually bound. Every generated client (managed+ // hook script, both sh shims, opencode plugin, codex launcher) is already sock-first —+ // `[ -n "$NODETERM_HOOK_SOCK" ]` — so advertising it moves local hook traffic off the+ // TCP port; the PORT line stays above for sessions holding a pre-socket script. Quoted+ // like every other value (#351/#358): macOS data dirs carry a space.+ (this.sockPath ? `NODETERM_HOOK_SOCK=${posixQuote(this.sockPath)}\n` : ''),// 0o600: this file holds the bearer token — owner read/write only so another local user// can't read it and forge hook events.{ encoding: 'utf8', mode: 0o600 }@@ -969,6 +1049,13 @@ class HookServer {// means the data dir has vanished and the hook is meant to be inert anyway.NODETERM_HOOK_VERSION: NODETERM_HOOK_PROTOCOL_VERSION,NODETERM_HOOK_ENDPOINT: this.endpointFilePath(),+ // The socket PATH is fine on the tmux -e argv where the token/port were not: it is an+ // address, not a credential — connecting still takes the bearer from the 0600 endpoint+ // file, and the socket itself sits in a 0700 dir. Advertised in env (not only the endpoint+ // file) so the codex sandbox shim can name the exact path in its macOS+ // `network.allow_unix_sockets` remedy line (issue #367) even when the endpoint file is+ // what a sandboxed sh could not read.+ ...(this.sockPath ? { NODETERM_HOOK_SOCK: this.sockPath } : {}),NODETERM_NODE_ID: nodeId,NODETERM_AGENT_ID: agentId,...(permWaitSecs > 0 ? { NODETERM_PERM_WAIT_SECS: String(permWaitSecs) } : {}),@@ -987,6 +1074,18 @@ class HookServer {stop(): void {this.server?.close()this.server = null+ this.unixServer?.close()+ this.unixServer = null+ // Unlink so the NEXT bind is clean even if close() lost the race with process exit; the+ // startup unlink above is still the backstop for a crash that skipped this entirely.+ if (this.sockPath) {+ try {+ unlinkSync(this.sockPath)+ } catch {+ /* already gone */+ }+ this.sockPath = ''+ }this.port = 0this.token = ''}diff --git a/src/core/agents/hook-sock-path.test.ts b/src/core/agents/hook-sock-path.test.tsnew file mode 100644index 000000000..66b4a38c5--- /dev/null+++ b/src/core/agents/hook-sock-path.test.ts@@ -0,0 +1,30 @@+import { describe, it, expect } from 'vitest'+import path from 'node:path'+import { hookSockPath, SUN_PATH_BUDGET } from './hook-sock-path'++describe('hookSockPath — the SUN_LEN discipline', () => {+ const home = '/home/u'++ it('binds under the data dir with a deliberately short name when it fits', () => {+ expect(hookSockPath('/data/nodeterm', home)).toBe('/data/nodeterm/sock/hook.sock')+ })++ it('falls back to a digest-keyed homedir path when the data dir would blow sun_path', () => {+ const long = '/Users/a-very-long-username/Library/Application Support/' + 'x'.repeat(80)+ const p = hookSockPath(long, home)+ expect(p.startsWith(path.join(home, '.nodeterm', 'sock') + path.sep)).toBe(true)+ expect(p).toMatch(/hook-[0-9a-f]{16}\.sock$/)+ // The point of the fallback: the result itself must FIT.+ expect(Buffer.byteLength(p, 'utf8')).toBeLessThanOrEqual(SUN_PATH_BUDGET)+ })++ it('keys the fallback to the data dir, so two instances never fight over one socket', () => {+ const a = hookSockPath('/very/long/'.repeat(12) + 'instance-a', home)+ const b = hookSockPath('/very/long/'.repeat(12) + 'instance-b', home)+ expect(a).not.toBe(b)+ })++ it('the budget sits under the tightest real limit (macOS: 104 bytes including the NUL)', () => {+ expect(SUN_PATH_BUDGET).toBeLessThanOrEqual(103)+ })+})diff --git a/src/core/agents/hook-sock-path.ts b/src/core/agents/hook-sock-path.tsnew file mode 100644index 000000000..fa48a21c6--- /dev/null+++ b/src/core/agents/hook-sock-path.ts@@ -0,0 +1,30 @@+import { createHash } from 'crypto'+import os from 'os'+import path from 'path'++/**+ * Where the hook server's unix-domain listener binds (issue #367).+ *+ * The SUN_LEN limit is REAL and this repo has hit it twice: `sun_path` is 104 bytes on macOS+ * (108 on Linux) INCLUDING the trailing NUL, and both the SSH ControlMaster+ * (`core/remote-ssh/control-master.ts`) and the codex relay daemon learned that a socket under a+ * long data dir simply fails to bind/connect. So the same discipline applies here:+ *+ * - primary: `<userDataDir>/sock/hook.sock` — a deliberately SHORT filename inside a private+ * 0700 subdirectory (the directory's mode is what actually protects the socket from other+ * local users; the 0600 chmod on the socket file itself is belt and braces);+ * - fallback, when the primary would not fit sun_path (a deep macOS "Application Support" path,+ * a long username): `~/.nodeterm/sock/hook-<sha256(userDataDir)[:16]>.sock` — the exact shape+ * `controlSocketPath` uses for the SSH masters. Home, NOT os.tmpdir(): a world-writable /tmp+ * lets any local user pre-create ("squat") the predictable name, and the sticky bit then stops+ * us from unlinking it — the homedir path has neither problem. The digest keys the file to the+ * data dir so two instances (two data dirs) never fight over one socket.+ */+export const SUN_PATH_BUDGET = 103++export function hookSockPath(userDataDir: string, home: string = os.homedir()): string {+ const primary = path.join(userDataDir, 'sock', 'hook.sock')+ if (Buffer.byteLength(primary, 'utf8') <= SUN_PATH_BUDGET) return primary+ const id = createHash('sha256').update(userDataDir).digest('hex').slice(0, 16)+ return path.join(home, '.nodeterm', 'sock', `hook-${id}.sock`)+}