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): label /hook/* events verified, on both raw listeners
Claude Code6147deb78994
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 93cf5b607..e8a22c168 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -7,6 +7,7 @@ import { canControlCanvas, hasSharedIdentity, type AgentId } from '../../shared/import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'import type { CodexIdentityEvent } from '../../shared/types'import { nodeTokenDir } from './node-token-files'+import { verifyNodeToken } from './node-auth-token'// v2 advertises NODETERM_NODE_TOKEN_DIR so clients read their per-node capability from a file// rather than receiving it in argv. Nothing consumes the posted version server-side, so the bump@@ -111,12 +112,37 @@ export function parseControlBody(}}+/**+ * What the hook server knows about the POST an event arrived on, beyond the event itself.+ *+ * `verified` = the caller presented a per-node token THIS instance minted for THAT node id. It is+ * a LABEL, nothing more: `false` is the overwhelmingly common, entirely legitimate case (any client+ * that predates the token, the phone, a cross-instance failover), so nothing may gate behaviour on+ * it. A later task makes the label useful; until then, false must cost a caller nothing.+ */+export interface HookEventMeta {+ verified: boolean+}+class HookServer {private server: Server | null = nullprivate port = 0private token = ''private listener: ((e: NormalizedAgentEvent) => void) | null = null- private rawListener: ((agentId: string, nodeId: string, payload: Record<string, unknown>) => void) | null = null+ private rawListener:+ | ((+ agentId: string,+ nodeId: string,+ payload: Record<string, unknown>,+ meta: HookEventMeta+ ) => void)+ | null = null+ /**+ * Nodes that have presented a token this instance minted for THAT node id. In memory only and+ * deliberately so: it is a record of what happened on this process's socket, not a durable claim,+ * and a restart must re-earn it. Bounded by the number of node ids that ever post here.+ */+ private provenNodes = new Set<string>()private controlHandler:| ((cmd: { verb: string; nodeId: string; args: Record<string, string> }) => Promise<{ok: boolean@@ -166,10 +192,24 @@ class HookServer {// Raw payload listener: receives the parsed (un-normalized) hook JSON. Drives the// contextTail/subagentTail features, which need transcript_path (not in NormalizedAgentEvent).- setRawListener(cb: (agentId: string, nodeId: string, payload: Record<string, unknown>) => void): void {+ // `meta` carries what the transport knows about the caller (see HookEventMeta).+ setRawListener(+ cb: (+ agentId: string,+ nodeId: string,+ payload: Record<string, unknown>,+ meta: HookEventMeta+ ) => void+ ): void {this.rawListener = cb}+ /** Has this node ever posted with a token this instance minted for it? Read by the routing task+ * that consumes the label; never a gate on /hook/* itself. */+ isNodeProven(nodeId: string): boolean {+ return this.provenNodes.has(nodeId)+ }+setControlHandler(cb: NonNullable<HookServer['controlHandler']>): void {this.controlHandler = cb}@@ -327,6 +367,28 @@ class HookServer {const agentId = decodeURIComponent(reqUrl.pathname.replace(/^\/hook\//, ''))const form = parseForm(await readBody(req))const nodeId = form.nodeId ?? ''+ // Identity is a LABEL here, not a gate. The three-way verdict maps to:+ // forged — our own kid with a mac that is not this node's ⇒ 403. Nothing legitimate can+ // produce it (only a holder of a token for ANOTHER node, or a mutation of one),+ // so it is the single case this route refuses.+ // legacy — no token, or another instance's kid. THE COMMON CASE, and it must keep+ // behaving exactly as it did before this label existed: 204, listeners fired.+ // Every client that predates the token, the phone, and the documented+ // cross-instance failover land here. Do not gate this on identityAvailable(),+ // on the agent, or on anything else — the fail-open is the contract.+ // verified — the caller holds this node's token; remember the node and pass the flag on.+ const verdict = verifyNodeToken(+ this.nodeAuthSecretOrNull(),+ nodeId,+ req.headers['x-nodeterm-node-token']+ )+ if (verdict === 'forged') {+ res.writeHead(403)+ res.end()+ return+ }+ const verified = verdict === 'verified'+ if (verified) this.provenNodes.add(nodeId)if (agentId && nodeId && form.payload) {let payload: Record<string, unknown> = {}try {@@ -346,9 +408,9 @@ class HookServer {if (form.nodeterm_answered) payload.nodeterm_answered = form.nodeterm_answered// Raw listener first: it drives the transcript-tailing features (which need// transcript_path). Inside the try so a throwing raw listener still ends 204.- this.rawListener?.(agentId, nodeId, payload)+ this.rawListener?.(agentId, nodeId, payload, { verified })const normalized = normalizeFor(agentId, { nodeId, agentId, payload })- if (normalized && this.listener) this.listener(normalized)+ if (normalized && this.listener) this.listener({ ...normalized, verified })}res.writeHead(204)res.end()diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.tsnew file mode 100644index 000000000..1978c6953--- /dev/null+++ b/src/core/agents/hook-verified-parity.test.ts@@ -0,0 +1,152 @@+// `/hook/*` learns to LABEL an event with the identity of the node that posted it.+//+// Two properties are pinned here, and the second one is the load-bearing one:+//+// 1. A valid per-node token makes the event `verified` — the flag reaches BOTH the normalized+// listener and the raw listener.+// 2. NO token is `legacy`, and legacy must behave EXACTLY as it does today: 204, listeners fired,+// never a 403. The phone, a cross-instance failover and any future spawner legitimately have no+// token to present. This route fails OPEN by contract; only `forged` (our own kid with a bad+// mac — a thing nothing legitimate can produce) is refused.+//+// Plus a source-level parity assertion: BOTH shells must register a 4-arg raw listener. This repo+// has shipped a hook-server signature change to one shell only three times; the guard is cheap.+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { mkdtempSync, rmSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { hookServer } from './hook-server'+import { nodeAuthToken } from './node-auth-token'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'++// Fixed so the tokens below are derivable in the test; length is what setNodeAuthSecret demands.+const SECRET = Buffer.alloc(32, 7)+const OTHER_SECRET = Buffer.alloc(32, 9)+const NODE = 'node-verified-1'++let dir = ''+let events: NormalizedAgentEvent[] = []+let raws: { agentId: string; nodeId: string; meta: { verified: boolean } | undefined }[] = []++function post(nodeId: string, token?: string): Promise<Response> {+ const headers: Record<string, string> = {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'content-type': 'application/x-www-form-urlencoded'+ }+ // A10 teaches the CLIENTS to send this; until then the test is the only caller that does.+ if (token !== undefined) headers['X-Nodeterm-Node-Token'] = token+ const payload = JSON.stringify({ hook_event_name: 'UserPromptSubmit', session_id: 's1', prompt: 'hi' })+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/claude`, {+ method: 'POST',+ headers,+ body: `nodeId=${encodeURIComponent(nodeId)}&payload=${encodeURIComponent(payload)}`+ })+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'hooksrv-verified-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setNodeAuthSecret(SECRET)+ hookServer.setListener((e) => {+ events.push(e)+ })+ hookServer.setRawListener((agentId, nodeId, _payload, meta) => {+ raws.push({ agentId, nodeId, meta })+ })+})++afterAll(() => {+ hookServer.clearNodeAuthSecretForTests()+ hookServer.stop()+ rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ events = []+ raws = []+})++describe('hook server: the verified label on /hook/*', () => {+ it('labels an event verified when the node presents its own token', async () => {+ const res = await post(NODE, nodeAuthToken(SECRET, NODE))+ expect(res.status).toBe(204)+ expect(events).toHaveLength(1)+ expect(events[0].verified).toBe(true)+ expect(raws).toEqual([{ agentId: 'claude', nodeId: NODE, meta: { verified: true } }])+ })++ it('remembers a node that has proven itself', async () => {+ await post(NODE, nodeAuthToken(SECRET, NODE))+ expect(hookServer.isNodeProven(NODE)).toBe(true)+ expect(hookServer.isNodeProven('some-other-node')).toBe(false)+ })++ // THE FAIL-OPEN CONTRACT. Do not "tighten" this into a 403.+ it('accepts a tokenless post exactly as before and labels it unverified — NEVER 403', async () => {+ const res = await post(NODE)+ expect(res.status).toBe(204)+ expect(events).toHaveLength(1)+ expect(events[0].verified).toBe(false)+ expect(events[0].nodeId).toBe(NODE)+ expect(raws).toEqual([{ agentId: 'claude', nodeId: NODE, meta: { verified: false } }])+ expect(hookServer.isNodeProven('untokened-node')).toBe(false)+ })++ it('refuses a forged token — our kid, a mutated mac — with 403 and no listener call', async () => {+ const good = nodeAuthToken(SECRET, NODE)+ const forged = good.slice(0, -1) + (good.endsWith('A') ? 'B' : 'A')+ const res = await post(NODE, forged)+ expect(res.status).toBe(403)+ expect(events).toEqual([])+ expect(raws).toEqual([])+ })++ it('refuses a token minted for a DIFFERENT node by this instance (same kid, wrong mac)', async () => {+ const res = await post(NODE, nodeAuthToken(SECRET, 'some-other-node'))+ expect(res.status).toBe(403)+ expect(events).toEqual([])+ })++ // The documented cross-instance failover: another instance's token is unjudgeable, not hostile.+ it('treats a foreign kid as legacy — succeeds, unverified, never 403', async () => {+ const res = await post(NODE, nodeAuthToken(OTHER_SECRET, NODE))+ expect(res.status).toBe(204)+ expect(events).toHaveLength(1)+ expect(events[0].verified).toBe(false)+ expect(raws[0].meta).toEqual({ verified: false })+ })++ it('is legacy — not forged — for every node when the server has no secret at all', async () => {+ hookServer.clearNodeAuthSecretForTests()+ try {+ const res = await post(NODE, nodeAuthToken(SECRET, NODE))+ expect(res.status).toBe(204)+ expect(events[0].verified).toBe(false)+ } finally {+ hookServer.setNodeAuthSecret(SECRET)+ }+ })+})++describe('both shells register a 4-arg raw listener', () => {+ const root = resolve(__dirname, '../../..')+ const shells = ['src/main/index.ts', 'src/server/agent-status.ts']++ for (const rel of shells) {+ it(`${rel} takes the meta argument`, () => {+ const src = readFileSync(join(root, rel), 'utf8')+ const m = /setRawListener\(\s*(?:async\s*)?\(([^)]*)\)/.exec(src)+ expect(m, `${rel} registers no raw listener at all`).toBeTruthy()+ const params = m![1]+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ expect(params).toHaveLength(4)+ expect(params[3]).toMatch(/meta/)+ })+ }+})diff --git a/src/main/index.ts b/src/main/index.tsindex 7b57ed837..efdf5635e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1783,7 +1783,12 @@ app.whenReady().then(async () => {return isSafeRemoteTranscriptPath(abs, remoteHome) ? abs : undefined}const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])- hookServer.setRawListener((agentId, nodeId, payload) => {+ // nodeId → did its LAST hook POST carry a token this instance minted for it. Recorded only;+ // nothing reads it yet, and nothing here may branch on it (a `false` is the ordinary case for any+ // client that predates the token — see HookEventMeta). The Server Edition keeps the same map.+ const nodeVerified = new Map<string, boolean>()+ hookServer.setRawListener((agentId, nodeId, payload, meta) => {+ if (nodeId) nodeVerified.set(nodeId, meta.verified)if (agentId === 'grok') {// This branch records two associations, neither of which grok's envelope states outright.// Everything the claude path does below hangs off `transcript_path`, and grok has none.diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.tsindex 158a19fdd..23ca97adc 100644--- a/src/server/agent-status.test.ts+++ b/src/server/agent-status.test.ts@@ -13,7 +13,14 @@ import { decodePtyData } from '../shared/rpc'// fire raw + normalized events without binding a real port.function fakeHooks() {let listener: ((e: unknown) => void) | undefined- let raw: ((agentId: string, nodeId: string, payload: Record<string, unknown>) => void) | undefined+ let raw:+ | ((+ agentId: string,+ nodeId: string,+ payload: Record<string, unknown>,+ meta: { verified: boolean }+ ) => void)+ | undefinedreturn {hooks: {setListener: (cb: (e: unknown) => void) => {@@ -24,8 +31,14 @@ function fakeHooks() {}},fireNormalized: (e: unknown) => listener?.(e),- fireRaw: (agentId: string, nodeId: string, payload: Record<string, unknown>) =>- raw?.(agentId, nodeId, payload)+ // `verified` defaults to false — the unlabelled/legacy POST, which is the ordinary case and the+ // one every existing expectation in this file was written against.+ fireRaw: (+ agentId: string,+ nodeId: string,+ payload: Record<string, unknown>,+ verified = false+ ) => raw?.(agentId, nodeId, payload, { verified })}}diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex f9361b261..748f0776c 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -29,7 +29,14 @@ import type { ServerPlatform } from './platform-server'/** The narrow surface of the hook server this module needs — injectable for tests. */export interface HookLike {setListener(cb: (e: NormalizedAgentEvent) => void): void- setRawListener(cb: (agentId: string, nodeId: string, payload: Record<string, unknown>) => void): void+ setRawListener(+ cb: (+ agentId: string,+ nodeId: string,+ payload: Record<string, unknown>,+ meta: { verified: boolean }+ ) => void+ ): void}export interface WireAgentStatusOptions {@@ -158,7 +165,12 @@ export function wireAgentStatus(}const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])- hooks.setRawListener((agentId, nodeId, payload) => {+ // nodeId → did its LAST hook POST carry a token this instance minted for it. Recorded only;+ // nothing reads it yet, and nothing here may branch on it (a `false` is the ordinary case for any+ // client that predates the token — see HookEventMeta). The desktop shell keeps the same map.+ const nodeVerified = new Map<string, boolean>()+ hooks.setRawListener((agentId, nodeId, payload, meta) => {+ if (nodeId) nodeVerified.set(nodeId, meta.verified)if (agentId === 'grok') {// This branch records two associations, neither of which grok's envelope states outright.// Everything the claude path does below hangs off `transcript_path`, and grok has none.diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex cf9dd3d03..579edf379 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -53,6 +53,14 @@ export interface NormalizedAgentEvent {tokens?: numbertoolUses?: numberresult?: string+ /**+ * The POST that produced this event presented a per-node token the running instance had minted+ * for THIS node id. Set by the hook server, never by a normalizer.+ *+ * It is a LABEL, not a permission: `false` covers every client that predates the token, the+ * phone, and the documented cross-instance failover, so no consumer may treat it as "reject".+ */+ verified?: boolean// recurringrecurringKind?: 'loop' | 'schedule' | 'cron'/** The recurring job was REMOVED (e.g. CronDelete) — take the card down. */