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(security): per-route identity enforcement — trust on first proof, dated warning window
Claude Code6a3108e758f8
diff --git a/docs/node-identity.md b/docs/node-identity.mdnew file mode 100644index 000000000..107959275--- /dev/null+++ b/docs/node-identity.md@@ -0,0 +1,110 @@+# Per-node hook identity++Every agent session on a machine shares one hook bearer token. The bearer proves *"a session on+this machine"*; it cannot prove **which** session. Every hook route takes a caller-supplied+`nodeId`, so before per-node identity any session holding the bearer could post events as a+sibling node, read a sibling's linked transcript, or drive canvas control in its name.++Per-node identity closes that. Each node gets a capability derived from a restart-stable secret,+and each route decides what a missing or foreign one is worth.++## The credential++```+kid = base64url(HMAC-SHA256(secret, "nt-node-auth-kid-v1"))[0..8]+mac = base64url(HMAC-SHA256(secret, "nt-node-auth-v1|" + nodeId))+token = kid + "." + mac+```++Derived, not minted-and-stored: tmux sessions outlive the app, so a table built at spawn is empty+for every already-running session after a restart and cannot be rebuilt. A derivation lives exactly+as long as the secret.++It reaches a client as a 0600 file under `NODETERM_NODE_TOKEN_DIR/<nodeId>` (advertised in the+endpoint file), **never** as an environment variable — that channel put the credential on the tmux+`-e` argv, world-readable on a stock Linux.++| File | What it owns |+| --- | --- |+| `src/core/agents/node-auth-secret.ts` | The secret. safeStorage on the desktop, raw 0600 bytes on the Server Edition. |+| `src/core/agents/node-auth-token.ts` | The derivation, `verifyNodeToken`, `isSafeNodeId`. |+| `src/core/agents/node-token-files.ts` | The 0600 token files in their 0700 dir. |+| `src/core/agents/node-identity-policy.ts` | **What a token buys, per route.** |+| `src/core/agents/hook-server.ts` | The routes that apply it. |++## Three verdicts, not two++`verifyNodeToken` answers `verified`, `legacy` or `forged`.++- **`verified`** — the caller holds the token this instance derived for that node id.+- **`legacy`** — no token, an empty header, another instance's `kid`, or no secret at all. This is+ *"we cannot judge this"*, **not** a failure. Every client older than the token, the phone, and the+ documented cross-instance failover land here.+- **`forged`** — **our** `kid` with a mac that is not this node's. Nothing legitimate produces it.+ It is a 403 on every route, always, with no explanatory prose.++## Per-route policy++| Route | `legacy` |+| --- | --- |+| `/hook/*` | Always accepted, 204, listeners fired. The label is a label. |+| `/verify`, `/hook/verify` | Bearer alone, forever — no identity of any kind. |+| `/codex-thread/{start,bind}` | Refused. Strict from the day they existed; there is no upgrade population to protect. |+| `/codex-thread/fallback` | Accepted **when tokenless** (the commonest thing it reports is that there was no token); a report that carries one must carry the right one. |+| `/control/*`, `/context-link/*` | See below. |++### Trust on first proof++`hookServer` remembers, **in memory only**, every node that has presented a valid token for itself+(`provenNodes`). Once a node is in that set, an unverified request naming it is refused: the session+demonstrably *can* authenticate, so one that suddenly cannot is either a different process wearing+its node id or a forgery.++Two properties keep that from breaking anybody:++- **A foreign `kid` never proves a node and is never caught by the latch.** Another instance's token+ is the documented cross-instance failover, not an impostor.+- **The latch is never written to disk.** A restart re-earns it within one hook event, and a+ persisted latch is a node that one filesystem accident could brick forever.++### The dated window++Until **2026-10-13** (`NODE_IDENTITY_STRICT_AFTER`), an unverified *mutation* on `/control/*` still+**executes**, and the reply is prefixed with a sentence naming the fix and this date. On and after+that date the same situation is a refusal and the handler never runs.++The date is the owner's rule — *the second minor release or 60 days after the shipping release,+whichever is later* — resolved to a concrete instant. It lives in the source+(`node-identity-policy.ts`) as well as here, so "we'll tighten this later" is a commitment with a+date rather than a comment.++`list` sits in a **tolerant** bucket that stays open past the cutoff: it leaks the shape of the+canvas but changes nothing, and refusing it would leave a legacy client unable to orient itself at+all. Every `/context-link/*` verb is a read and sits in the same bucket.++`/context-link/*` refuses with **prose and a 200**, not a 403: the agent explicitly asked for a+read, and the shim turns any non-200 into "nodeterm unreachable" — a lie it can do nothing with.++`write` and `close` keep their **user confirmation** whatever the token says. A capability is not a+substitute for the human's answer, and neither verb is ever tolerant.++### The escape hatch++`settings.hookIdentityStrict` (absent by default):++| Value | Effect |+| --- | --- |+| absent | Follow `NODE_IDENTITY_STRICT_AFTER`. |+| `true` | Enforce now, before the date. |+| `false` | Keep the warning window open past the date **and** release the latch. |++`false` is for a user whose upgrade strands a live session: it gets the canvas back without+downgrading the app. Neither value ever admits a `forged` token.++## Ids are path segments++`isSafeNodeId` (node ids) and `isSafeThreadId` (codex thread ids) refuse `.`, `..`, empty and+over-length **on top of** the `[A-Za-z0-9._-]` charset, because both ids are used as path segments+— `<tokenDir>/<nodeId>`, `<codexThreadIdentityRoot>/<threadId>` — and `.` and `..` match that+charset. One predicate each, applied before the id reaches a path join or a hash. Do not add a+second copy of either rule; a rule with two copies is a rule where one copy is wrong.diff --git a/src/core/agents/hook-identity-enforcement.test.ts b/src/core/agents/hook-identity-enforcement.test.tsnew file mode 100644index 000000000..cbb796f11--- /dev/null+++ b/src/core/agents/hook-identity-enforcement.test.ts@@ -0,0 +1,353 @@+// A13 — per-route identity enforcement on `/control/*` and `/context-link/*`.+//+// Real hook server, real POSTs, spies for the handlers: "refused" here means the handler never ran,+// not that the reply looked unhappy. The properties this file exists to pin:+//+// - trust on first proof: a node that has never presented a token keeps the legacy path; one that+// HAS is latched, and an unverified request for it afterwards is refused.+// - a FOREIGN kid never proves a node and is never caught by the latch — that is what keeps the+// documented cross-instance failover alive.+// - the latch is in memory only. Persisting it would let one filesystem accident brick a node+// forever; a restart must re-earn it, which it does within one hook event.+// - the dated window: an unverified mutation EXECUTES and carries the restart line until+// 2026-10-13, and is refused with the same shape afterwards.+// - `write`/`close` keep their user confirmation whatever the token says.+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { mkdtempSync, rmSync, readdirSync, readFileSync, statSync } 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 {+ IDENTITY_REFUSED_NOTE,+ IDENTITY_RESTART_NOTE,+ NODE_IDENTITY_STRICT_AFTER,+ TOLERANT_CONTROL_VERBS+} from './node-identity-policy'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'++const SECRET = Buffer.alloc(32, 11)+// Another instance's secret ⇒ another instance's kid ⇒ the `legacy` failover verdict, NOT `forged`.+const OTHER_SECRET = Buffer.alloc(32, 13)++const IN_WINDOW = new Date('2026-09-01T00:00:00Z')+const PAST_CUTOFF = new Date('2026-11-01T00:00:00Z')++let dir = ''+let controlCalls: { verb: string; nodeId: string }[] = []+let contextCalls: { verb: string; nodeId: string }[] = []++function headers(token?: string): Record<string, string> {+ const h: Record<string, string> = {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'content-type': 'application/x-www-form-urlencoded',+ accept: 'text/plain'+ }+ if (token !== undefined) h['X-Nodeterm-Node-Token'] = token+ return h+}++function control(verb: string, nodeId: string, token?: string, accept = 'text/plain'): Promise<Response> {+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/control/${verb}`, {+ method: 'POST',+ headers: { ...headers(token), accept },+ body: `nodeId=${encodeURIComponent(nodeId)}`+ })+}++function contextLink(verb: string, nodeId: string, token?: string): Promise<Response> {+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/context-link/${verb}`, {+ method: 'POST',+ headers: headers(token),+ body: `nodeId=${encodeURIComponent(nodeId)}`+ })+}++/** A real hook event — the only thing that can put a node in `provenNodes`. */+function hookEvent(nodeId: string, token?: string): Promise<Response> {+ const payload = JSON.stringify({ hook_event_name: 'UserPromptSubmit', session_id: 's', prompt: 'hi' })+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/claude`, {+ method: 'POST',+ headers: headers(token),+ body: `nodeId=${encodeURIComponent(nodeId)}&payload=${encodeURIComponent(payload)}`+ })+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'hooksrv-identity-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setNodeAuthSecret(SECRET)+ hookServer.setControlHandler(async ({ verb, nodeId }) => {+ controlCalls.push({ verb, nodeId })+ return { ok: true, message: `did ${verb}` }+ })+ hookServer.setContextLinkHandler(async ({ verb, nodeId }) => {+ contextCalls.push({ verb, nodeId })+ return 'the linked transcript'+ })+})++afterAll(() => {+ hookServer.setIdentityClockForTests(() => new Date())+ hookServer.setIdentityStrictOverride(() => undefined)+ hookServer.clearNodeAuthSecretForTests()+ hookServer.stop()+ resetPlatformForTests()+ rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ controlCalls = []+ contextCalls = []+ hookServer.setIdentityClockForTests(() => IN_WINDOW)+ hookServer.setIdentityStrictOverride(() => undefined)+})++describe('/control/* during the warning window', () => {+ it('runs an unverified mutation and prefixes the reply with the restart note', async () => {+ const res = await control('open-terminal', 'n-window')+ expect(res.status).toBe(200)+ const body = await res.text()+ // It EXECUTED — that is the promise of the window.+ expect(controlCalls).toEqual([{ verb: 'open-terminal', nodeId: 'n-window' }])+ expect(body.startsWith(IDENTITY_RESTART_NOTE)).toBe(true)+ // …and the reply the agent came for is still there, under the note.+ expect(body).toContain('did open-terminal')+ })++ it('never warns a verified mutation', async () => {+ const res = await control('open-terminal', 'n-verified', nodeAuthToken(SECRET, 'n-verified'))+ expect(res.status).toBe(200)+ const body = await res.text()+ expect(body).not.toContain(IDENTITY_RESTART_NOTE)+ expect(body.trim()).toBe('did open-terminal')+ expect(controlCalls).toHaveLength(1)+ })++ it('lets a tolerant verb through silently — it leaks canvas shape but changes nothing', async () => {+ const res = await control('list', 'n-list')+ expect(res.status).toBe(200)+ expect(await res.text()).not.toContain(IDENTITY_RESTART_NOTE)+ expect(controlCalls).toEqual([{ verb: 'list', nodeId: 'n-list' }])+ })++ it('403s a forged token without a word of advice — nothing legitimate produces one', async () => {+ const forged = nodeAuthToken(SECRET, 'somebody-else')+ const res = await control('open-terminal', 'n-forged', forged)+ expect(res.status).toBe(403)+ expect(controlCalls).toEqual([])+ })+})++describe('/control/* after the cutoff', () => {+ beforeEach(() => {+ hookServer.setIdentityClockForTests(() => PAST_CUTOFF)+ })++ it('refuses an unverified mutation BEFORE the handler runs, with the same sentence', async () => {+ const res = await control('open-terminal', 'n-cutoff')+ expect(res.status).toBe(403)+ expect((await res.text()).trim()).toBe(IDENTITY_REFUSED_NOTE)+ // The point of the feature: nothing happened.+ expect(controlCalls).toEqual([])+ })++ it('answers a JSON caller in JSON, not in text', async () => {+ const res = await control('open-terminal', 'n-cutoff-json', undefined, 'application/json')+ expect(res.status).toBe(403)+ expect(await res.json()).toEqual({ ok: false, error: IDENTITY_REFUSED_NOTE })+ expect(controlCalls).toEqual([])+ })++ it('still lets a verified mutation through', async () => {+ const res = await control('open-terminal', 'n-strict-ok', nodeAuthToken(SECRET, 'n-strict-ok'))+ expect(res.status).toBe(200)+ expect(controlCalls).toHaveLength(1)+ })++ it('still lets an unproven node read the canvas shape', async () => {+ const res = await control('list', 'n-strict-list')+ expect(res.status).toBe(200)+ expect(controlCalls).toEqual([{ verb: 'list', nodeId: 'n-strict-list' }])+ })+})++describe('/context-link/* degrades to prose, never to silence', () => {+ it('takes the legacy path for a node that has never proven itself', async () => {+ const res = await contextLink('transcript', 'n-ctx-legacy')+ expect(res.status).toBe(200)+ expect(await res.text()).toContain('the linked transcript')+ expect(contextCalls).toEqual([{ verb: 'transcript', nodeId: 'n-ctx-legacy' }])+ })++ it('refuses a latched node with a SENTENCE and a 200 — the agent asked for a read', async () => {+ expect((await hookEvent('n-ctx-proven', nodeAuthToken(SECRET, 'n-ctx-proven'))).status).toBe(204)+ const res = await contextLink('transcript', 'n-ctx-proven')+ // Not a 403: the shim turns any non-200 into "nodeterm unreachable", which would be a lie and+ // tells the agent nothing it can act on.+ expect(res.status).toBe(200)+ expect((await res.text()).trim()).toBe(IDENTITY_REFUSED_NOTE)+ expect(contextCalls).toEqual([])+ })++ it('403s a forged token here too', async () => {+ const res = await contextLink('transcript', 'n-ctx-forged', nodeAuthToken(SECRET, 'other'))+ expect(res.status).toBe(403)+ expect(contextCalls).toEqual([])+ })+})++describe('trust on first proof', () => {+ it('is not proven before the first hook event, and is one event later', async () => {+ expect(hookServer.isNodeProven('n-latch')).toBe(false)+ // Before proof, unverified control mutations run (with the note) — the legacy path.+ expect((await control('open-terminal', 'n-latch')).status).toBe(200)+ expect(controlCalls).toHaveLength(1)++ // ONE hook event with this node's own token is the whole ceremony. That is why a restart+ // re-proves immediately and why the latch never needs to be written down.+ expect((await hookEvent('n-latch', nodeAuthToken(SECRET, 'n-latch'))).status).toBe(204)+ expect(hookServer.isNodeProven('n-latch')).toBe(true)++ // After proof, the same tokenless request is refused — the session demonstrably CAN+ // authenticate, so one that suddenly cannot is a different process or a forgery.+ const res = await control('open-terminal', 'n-latch')+ expect(res.status).toBe(403)+ expect((await res.text()).trim()).toBe(IDENTITY_REFUSED_NOTE)+ expect(controlCalls).toHaveLength(1)+ })++ it('latches `list` too — it is not a mutation, but it is still the wrong caller', async () => {+ expect((await hookEvent('n-latch-list', nodeAuthToken(SECRET, 'n-latch-list'))).status).toBe(204)+ expect((await control('list', 'n-latch-list')).status).toBe(403)+ expect(controlCalls).toEqual([])+ })++ it('is released by hookIdentityStrict = false, without downgrading the app', async () => {+ expect((await hookEvent('n-hatch', nodeAuthToken(SECRET, 'n-hatch'))).status).toBe(204)+ expect((await control('open-terminal', 'n-hatch')).status).toBe(403)+ controlCalls = []+ hookServer.setIdentityStrictOverride(() => false)+ const res = await control('open-terminal', 'n-hatch')+ expect(res.status).toBe(200)+ expect((await res.text()).startsWith(IDENTITY_RESTART_NOTE)).toBe(true)+ expect(controlCalls).toHaveLength(1)+ })++ it('is brought forward by hookIdentityStrict = true, before the cutoff', async () => {+ hookServer.setIdentityStrictOverride(() => true)+ const res = await control('open-terminal', 'n-early-strict')+ expect(res.status).toBe(403)+ expect(controlCalls).toEqual([])+ })+})++describe('a foreign kid', () => {+ const FOREIGN = () => nodeAuthToken(OTHER_SECRET, 'n-foreign')++ it('never proves a node', async () => {+ expect((await hookEvent('n-foreign', FOREIGN())).status).toBe(204)+ expect(hookServer.isNodeProven('n-foreign')).toBe(false)+ })++ it('is never caught by the latch — the cross-instance failover has to keep working', async () => {+ // Prove the node with THIS instance's token first, so the latch is armed…+ expect((await hookEvent('n-foreign2', nodeAuthToken(SECRET, 'n-foreign2'))).status).toBe(204)+ expect(hookServer.isNodeProven('n-foreign2')).toBe(true)+ // A TOKENLESS caller is now refused…+ expect((await control('open-terminal', 'n-foreign2')).status).toBe(403)+ // …but a caller holding ANOTHER instance's token is the documented failover, not an impostor,+ // so it gets the window's behaviour: it runs, and it is told to restart.+ const res = await control('open-terminal', 'n-foreign2', nodeAuthToken(OTHER_SECRET, 'n-foreign2'))+ expect(res.status).toBe(200)+ expect((await res.text()).startsWith(IDENTITY_RESTART_NOTE)).toBe(true)+ expect(controlCalls).toEqual([{ verb: 'open-terminal', nodeId: 'n-foreign2' }])+ })+})++describe('the latch is memory, not state', () => {+ it('leaves no trace of a proven node anywhere under the data dir', async () => {+ expect((await hookEvent('n-nopersist', nodeAuthToken(SECRET, 'n-nopersist'))).status).toBe(204)+ expect(hookServer.isNodeProven('n-nopersist')).toBe(true)+ const walk = (root: string): string[] =>+ readdirSync(root).flatMap((entry) => {+ const full = join(root, entry)+ return statSync(full).isDirectory() ? walk(full) : [full]+ })+ for (const file of walk(dir)) {+ // A persisted latch is a node that one filesystem accident can brick forever. Nothing on+ // disk may know which nodes have proven themselves.+ expect(readFileSync(file, 'utf8'), file).not.toContain('n-nopersist')+ }+ })+})++describe('write/close keep the human in the loop, token or no token', () => {+ it('sends a verified destructive verb to the handler that owns the confirmation', async () => {+ const res = await control('write', 'n-write-v', nodeAuthToken(SECRET, 'n-write-v'))+ expect(res.status).toBe(200)+ // Identity never short-circuits INTO the action: it can only refuse before the handler, never+ // stand in for the dialog the handler puts up.+ expect(controlCalls).toEqual([{ verb: 'write', nodeId: 'n-write-v' }])+ })++ it('sends an unverified destructive verb there too, during the window', async () => {+ const res = await control('close', 'n-close-l')+ expect(res.status).toBe(200)+ expect(controlCalls).toEqual([{ verb: 'close', nodeId: 'n-close-l' }])+ expect((await res.text()).startsWith(IDENTITY_RESTART_NOTE)).toBe(true)+ })++ it('never waves them through as tolerant', () => {+ // The confirm-gated pair (src/main/canvas-control-core.ts `isDestructiveVerb`) is untouched by+ // this feature. Tolerance would be the one way identity could weaken it, so it is pinned here;+ // the set itself is covered in canvas-control-core.test.ts.+ expect(TOLERANT_CONTROL_VERBS.has('write')).toBe(false)+ expect(TOLERANT_CONTROL_VERBS.has('close')).toBe(false)+ })+})++describe('an instance with no secret at all', () => {+ it('gates nobody — not even past the cutoff', async () => {+ // safeStorage unavailable on the desktop, an uncreatable key file on the Server Edition. This+ // instance cannot mint a token, so nothing can ever be verified here; warning or refusing+ // `legacy` would hit EVERY caller on the machine with advice that cannot work.+ hookServer.clearNodeAuthSecretForTests()+ hookServer.setIdentityClockForTests(() => PAST_CUTOFF)+ try {+ const res = await control('open-terminal', 'n-nosecret')+ expect(res.status).toBe(200)+ const body = await res.text()+ expect(body).not.toContain(IDENTITY_RESTART_NOTE)+ expect(body.trim()).toBe('did open-terminal')+ expect(controlCalls).toHaveLength(1)+ } finally {+ hookServer.setNodeAuthSecret(SECRET)+ }+ })+})++describe('both shells wire the escape hatch', () => {+ it('is set from settings.hookIdentityStrict in the desktop AND the Server Edition', () => {+ // This repo has shipped a hook-server change to one shell only three times. An unwired shell+ // has no hatch at all, which is the one thing a stranded user cannot work around.+ const root = resolve(__dirname, '../../..')+ for (const rel of ['src/main/index.ts', 'src/server/index.ts']) {+ const src = readFileSync(join(root, rel), 'utf8')+ expect(src, rel).toContain('setIdentityStrictOverride')+ expect(src, rel).toContain('hookIdentityStrict')+ }+ })+})++describe('the injected clock', () => {+ it('is what the cutoff is read against, so a suite crosses it without touching the machine', async () => {+ hookServer.setIdentityClockForTests(() => new Date(NODE_IDENTITY_STRICT_AFTER.getTime() - 1))+ expect((await control('open-terminal', 'n-edge')).status).toBe(200)+ hookServer.setIdentityClockForTests(() => new Date(NODE_IDENTITY_STRICT_AFTER.getTime()))+ expect((await control('open-terminal', 'n-edge2')).status).toBe(403)+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 0209045e6..7f49e3016 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -6,9 +6,17 @@ import { platform } from '../platform'import { canControlCanvas, type AgentId } from '../../shared/agents/config'import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'import type { CodexIdentityEvent } from '../../shared/types'+import type { NodeTokenVerdict } from './node-auth-token'import { nodeTokenDir } from './node-token-files'-import { isSafeNodeId, verifyNodeToken } from './node-auth-token'+import { isForeignKidToken, isSafeNodeId, verifyNodeToken } from './node-auth-token'import { isSafeThreadId } from '../codex-identity-proxy'+import {+ controlPolicy,+ CONTEXT_LINK_POLICY_VERB,+ IDENTITY_REFUSED_NOTE,+ IDENTITY_RESTART_NOTE,+ type IdentityDecision+} from './node-identity-policy'// 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@@ -171,6 +179,15 @@ class HookServer {private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = nullprivate endpointPath = ''private nodeAuthSecret: Buffer | null = null+ /**+ * `settings.hookIdentityStrict`, read LIVE (a getter, not a snapshot) so flipping it in Settings+ * takes effect on the next request rather than the next launch. `undefined` — the default, and+ * what an un-wired shell gets — means "follow NODE_IDENTITY_STRICT_AFTER".+ */+ private identityStrict: () => boolean | undefined = () => undefined+ /** The clock the cutoff is read against. A seam, so a suite can stand on either side of a DATE+ * without touching the machine's own. */+ private identityNow: () => Date = () => new Date()endpointFilePath(): string {if (!this.endpointPath) this.endpointPath = path.join(platform().userDataDir, 'hook-endpoint.env')@@ -260,6 +277,22 @@ class HookServer {this.nodeAuthSecret = null}+ /**+ * The escape hatch, injected by the shell from `settings.hookIdentityStrict`.+ *+ * `undefined` follows the dated constant. `true` opts in early. `false` keeps the warning window+ * open past the cutoff AND releases the trust-on-first-proof latch — so a user whose upgrade goes+ * wrong gets their canvas back without downgrading the app. Never releases `forged`.+ */+ setIdentityStrictOverride(read: () => boolean | undefined): void {+ this.identityStrict = read+ }++ /** Test seam only: see `identityNow`. */+ setIdentityClockForTests(now: () => Date): void {+ this.identityNow = now+ }+async start(): Promise<void> {if (this.server) returnthis.token = randomUUID()@@ -312,21 +345,50 @@ class HookServer {// dialog — the caller saw "endpoint unreachable" while the dialog was still up, and a// late confirm still delivered, so the agent was told nothing happened when it had.req.setTimeout(CONTROL_CEILING_MS, () => req.destroy())+ const wantsText = String(req.headers.accept ?? '').includes('text/plain')+ // IDENTITY, and it runs BEFORE the handler: the promise of a refusal is that nothing+ // happened, and a check after the handler is a check that happened too late.+ const { verdict, decision } = this.identityGate(+ nodeId,+ verb,+ req.headers['x-nodeterm-node-token']+ )+ if (verdict === 'forged') {+ res.writeHead(403)+ res.end()+ return+ }+ if (decision === 'refuse') {+ // The route's own refusal shape, so the sh shim (which prints any non-200 body to+ // stderr and exits 1) shows the sentence and nothing else.+ if (wantsText) {+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })+ res.end(`${IDENTITY_REFUSED_NOTE}\n`)+ } else {+ res.writeHead(403, { 'content-type': 'application/json' })+ res.end(JSON.stringify({ ok: false, error: IDENTITY_REFUSED_NOTE }))+ }+ return+ }const result = this.controlHandler? await this.controlHandler({ verb, nodeId, args }): { ok: false, error: 'control unavailable' }+ const warn = decision === 'allow-with-warning'// The POSIX-sh shim asks for text/plain: it has no JSON parser, so the server does the// rendering the Node CLI used to do client-side. Everything else keeps the JSON shape.- if (String(req.headers.accept ?? '').includes('text/plain')) {+ if (wantsText) {const text = result.ok? result.message ?? JSON.stringify(result.result ?? {}): result.error ?? 'control request failed'res.writeHead(result.ok ? 200 : 400, { 'content-type': 'text/plain; charset=utf-8' })- res.end(`${text}\n`)+ res.end(warn ? `${IDENTITY_RESTART_NOTE}\n${text}\n` : `${text}\n`)return}res.writeHead(result.ok ? 200 : 400, { 'content-type': 'application/json' })- res.end(JSON.stringify(result))+ // A field, not a prefix: the JSON dialect is a STRUCTURED reply a legacy client parses,+ // and folding the note into `message` would either hide `result` (text rendering falls+ // back to it only when `message` is absent) or corrupt a field somebody reads.+ res.end(JSON.stringify(warn ? { ...result, warning: IDENTITY_RESTART_NOTE } : result))return}if (reqUrl.pathname.startsWith('/context-link/')) {@@ -339,6 +401,26 @@ class HookServer {// handler ceiling rather than dropping it. The effective bound here is the race below;// the socket ceiling is only the backstop behind it.req.setTimeout(CONTROL_CEILING_MS, () => req.destroy())+ // Same latch as /control/, and every verb here is a READ, so it is presented to the+ // policy as the tolerant verb: an unproven legacy caller keeps its transcript.+ const gate = this.identityGate(+ nodeId,+ CONTEXT_LINK_POLICY_VERB,+ req.headers['x-nodeterm-node-token']+ )+ if (gate.verdict === 'forged') {+ res.writeHead(403)+ res.end()+ return+ }+ if (gate.decision === 'refuse') {+ // PROSE, not a 403. The agent explicitly asked for a read; the shim turns any non-200+ // into "Could not read linked context (nodeterm unreachable)", which would be a lie and+ // tells it nothing it can act on. A sentence it can act on is the better failure.+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })+ res.end(`${IDENTITY_REFUSED_NOTE}\n`)+ return+ }// Always text: the caller is the sh shim, and the payload IS prose (a rendered// transcript). The handler owns the authorization — see context-link.ts.const text = this.contextLinkHandler@@ -449,6 +531,47 @@ class HookServer {return verifyNodeToken(this.nodeAuthSecretOrNull(), nodeId, provided) === 'verified'}+ /**+ * The identity gate for `/control/*` and `/context-link/*` — one call site for the verdict, the+ * latch and the policy, so the two routes cannot drift into two different rules.+ *+ * Both halves of the answer come back: the routes agree on the POLICY but not on the SHAPE of a+ * refusal (a 403 on control, prose on context-link), and `forged` is a bare 403 on both — it is+ * an attack signal, and handing it "restart this node" would be advice to an attacker and a lie+ * to nobody else.+ */+ private identityGate(+ nodeId: string,+ verb: string,+ presented: string | string[] | undefined+ ): { verdict: NodeTokenVerdict; decision: IdentityDecision } {+ const secret = this.nodeAuthSecretOrNull()+ // NO SECRET ⇒ NO GATE, ever. This instance cannot mint a token, so nothing can be `verified`,+ // so a policy that warns or refuses `legacy` here would warn or refuse EVERY caller on the+ // machine — and the advice it would give ("restart this node to pick up an identity") is+ // advice that cannot work, because there is no identity to pick up. This is the state a+ // desktop lands in when safeStorage is unavailable and the state a Server Edition lands in+ // when the key file cannot be created; both must keep working exactly as they did.+ if (!secret) return { verdict: 'legacy', decision: 'allow' }+ const verdict = verifyNodeToken(secret, nodeId, presented)+ // Proof is earned on ANY route that can present a valid token, not just /hook/*: a session's+ // first act may well be a canvas-control call.+ if (verdict === 'verified') this.provenNodes.add(nodeId)+ return {+ verdict,+ decision: controlPolicy({+ verdict,+ // A FOREIGN kid is the documented cross-instance failover. It never proved this node (only+ // `verified` adds to the set) and it must never be caught by the latch either, or the+ // first day a second instance exists is the day failover stops working.+ proven: this.provenNodes.has(nodeId) && !isForeignKidToken(secret, presented),+ verb,+ now: this.identityNow(),+ override: this.identityStrict()+ })+ }+ }+/*** `/codex-thread/{start,bind,fallback}`.*diff --git a/src/core/agents/node-auth-token.ts b/src/core/agents/node-auth-token.tsindex 8c6a48e91..d1717a682 100644--- a/src/core/agents/node-auth-token.ts+++ b/src/core/agents/node-auth-token.ts@@ -53,6 +53,26 @@ export function nodeAuthToken(secret: Buffer, nodeId: string): string {export type NodeTokenVerdict = 'verified' | 'legacy' | 'forged'+/**+ * Does the presented token carry ANOTHER instance's kid?+ *+ * `verifyNodeToken` deliberately folds this into `legacy` — for a LABEL, "we cannot judge this" is+ * the whole answer. A policy that latches on proof needs the distinction back: a node this instance+ * has proven, contacted by a caller holding a second instance's token, is the documented+ * cross-instance failover, not an impostor, and must not trip the latch. Same cheap plain compare+ * `verifyNodeToken` uses for the kid: it is a routing decision over non-secret bytes.+ */+export function isForeignKidToken(+ secret: Buffer | null,+ presented: string | string[] | undefined+): boolean {+ if (!secret) return false+ if (typeof presented !== 'string' || presented === '') return false+ const dot = presented.indexOf('.')+ if (dot <= 0) return false+ return presented.slice(0, dot) !== nodeAuthKid(secret)+}+/*** Three-way, not two-way. `legacy` is NOT a failure — it is "we cannot judge this", and per-route* policy decides what that means (a missing token, or another instance's kid during the documenteddiff --git a/src/core/agents/node-identity-policy.test.ts b/src/core/agents/node-identity-policy.test.tsnew file mode 100644index 000000000..d57c41562--- /dev/null+++ b/src/core/agents/node-identity-policy.test.ts@@ -0,0 +1,175 @@+// The decision table, exhaustively. `controlPolicy` is pure on purpose: the routes it governs are+// the two an agent drives with a shell command, and a rule that can only be exercised through a+// socket is a rule nobody can read off a test.+import { describe, it, expect } from 'vitest'+import {+ controlPolicy,+ CONTEXT_LINK_POLICY_VERB,+ IDENTITY_REFUSED_NOTE,+ IDENTITY_RESTART_NOTE,+ NODE_IDENTITY_STRICT_AFTER,+ TOLERANT_CONTROL_VERBS+} from './node-identity-policy'++const BEFORE = new Date('2026-09-01T00:00:00Z')+const AFTER = new Date('2026-11-01T00:00:00Z')+const TOLERANT = 'list'+const MUTATION = 'open-terminal'++describe('the cutoff is a dated commitment, not a "later"', () => {+ it('is 2026-10-13, in the source', () => {+ expect(NODE_IDENTITY_STRICT_AFTER.toISOString()).toBe('2026-10-13T00:00:00.000Z')+ })++ it('puts that date in the sentence the user reads', () => {+ expect(IDENTITY_RESTART_NOTE).toContain('2026-10-13')+ })++ it('names the action in both sentences, so the user is told what to do', () => {+ for (const note of [IDENTITY_RESTART_NOTE, IDENTITY_REFUSED_NOTE]) {+ expect(note).toContain('Restart agent')+ // One line: both are PREFIXED onto a reply, and a multi-line prefix buries the reply.+ expect(note).not.toContain('\n')+ }+ })++ it('says, in the refusal, that the command did not run', () => {+ expect(IDENTITY_REFUSED_NOTE).toContain('did not run')+ })+})++describe('the tolerant bucket', () => {+ it('holds `list` and nothing that changes the canvas', () => {+ expect([...TOLERANT_CONTROL_VERBS]).toEqual(['list'])+ // The token is never a substitute for the human's answer, so the confirm-gated verbs are not+ // in here — they must reach the handler (and its dialog), not be waved through by tolerance.+ expect(TOLERANT_CONTROL_VERBS.has('write')).toBe(false)+ expect(TOLERANT_CONTROL_VERBS.has('close')).toBe(false)+ })++ it('is what /context-link/* presents, because every context-link verb is a read', () => {+ expect(TOLERANT_CONTROL_VERBS.has(CONTEXT_LINK_POLICY_VERB)).toBe(true)+ })+})++describe('controlPolicy', () => {+ it('refuses a forged token in every combination — it is the one unambiguous attack signal', () => {+ for (const proven of [false, true]) {+ for (const verb of [TOLERANT, MUTATION]) {+ for (const now of [BEFORE, AFTER]) {+ for (const override of [undefined, true, false]) {+ expect(+ controlPolicy({ verdict: 'forged', proven, verb, now, override }),+ `${proven}/${verb}/${now.toISOString()}/${override}`+ ).toBe('refuse')+ }+ }+ }+ }+ })++ it('allows a verified token in every combination, and never warns it', () => {+ for (const proven of [false, true]) {+ for (const verb of [TOLERANT, MUTATION]) {+ for (const now of [BEFORE, AFTER]) {+ for (const override of [undefined, true, false]) {+ expect(+ controlPolicy({ verdict: 'verified', proven, verb, now, override }),+ `${proven}/${verb}/${now.toISOString()}/${override}`+ ).toBe('allow')+ }+ }+ }+ }+ })++ describe('legacy, before the node has ever proven itself', () => {+ it('takes the legacy path for a tolerant verb, on both sides of the cutoff', () => {+ for (const now of [BEFORE, AFTER]) {+ expect(controlPolicy({ verdict: 'legacy', proven: false, verb: TOLERANT, now })).toBe('allow')+ }+ })++ it('runs a mutation with a warning during the window', () => {+ expect(controlPolicy({ verdict: 'legacy', proven: false, verb: MUTATION, now: BEFORE })).toBe(+ 'allow-with-warning'+ )+ })++ it('refuses a mutation after the cutoff', () => {+ expect(controlPolicy({ verdict: 'legacy', proven: false, verb: MUTATION, now: AFTER })).toBe(+ 'refuse'+ )+ })++ it('treats the cutoff instant itself as strict', () => {+ expect(+ controlPolicy({+ verdict: 'legacy',+ proven: false,+ verb: MUTATION,+ now: new Date(NODE_IDENTITY_STRICT_AFTER.getTime())+ })+ ).toBe('refuse')+ expect(+ controlPolicy({+ verdict: 'legacy',+ proven: false,+ verb: MUTATION,+ now: new Date(NODE_IDENTITY_STRICT_AFTER.getTime() - 1)+ })+ ).toBe('allow-with-warning')+ })+ })++ describe('legacy, after the node HAS proven itself — the latch', () => {+ it('refuses, for every verb and on both sides of the cutoff', () => {+ // A session that demonstrably CAN authenticate and suddenly does not is either a different+ // process wearing its node id or a forgery this instance cannot name. Even `list` leaks the+ // canvas shape, so the latch does not exempt it.+ for (const verb of [TOLERANT, MUTATION]) {+ for (const now of [BEFORE, AFTER]) {+ expect(controlPolicy({ verdict: 'legacy', proven: true, verb, now })).toBe('refuse')+ }+ }+ })+ })++ describe('the hookIdentityStrict escape hatch', () => {+ it('undefined follows the constant', () => {+ expect(+ controlPolicy({ verdict: 'legacy', proven: false, verb: MUTATION, now: AFTER, override: undefined })+ ).toBe('refuse')+ expect(+ controlPolicy({ verdict: 'legacy', proven: false, verb: MUTATION, now: BEFORE, override: undefined })+ ).toBe('allow-with-warning')+ })++ it('true is strict before the cutoff (opt in early)', () => {+ expect(+ controlPolicy({ verdict: 'legacy', proven: false, verb: MUTATION, now: BEFORE, override: true })+ ).toBe('refuse')+ })++ it('false keeps the warning window open past the cutoff, latch included', () => {+ // This is the whole point of the hatch: a user whose upgrade goes wrong gets their canvas+ // back without downgrading the app. It must therefore also release the latch — the latch is+ // the likelier thing to have stranded them.+ expect(+ controlPolicy({ verdict: 'legacy', proven: false, verb: MUTATION, now: AFTER, override: false })+ ).toBe('allow-with-warning')+ expect(+ controlPolicy({ verdict: 'legacy', proven: true, verb: MUTATION, now: AFTER, override: false })+ ).toBe('allow-with-warning')+ expect(+ controlPolicy({ verdict: 'legacy', proven: true, verb: TOLERANT, now: AFTER, override: false })+ ).toBe('allow')+ })++ it('never lets a forged token through, whatever it is set to', () => {+ expect(+ controlPolicy({ verdict: 'forged', proven: false, verb: TOLERANT, now: BEFORE, override: false })+ ).toBe('refuse')+ })+ })+})diff --git a/src/core/agents/node-identity-policy.ts b/src/core/agents/node-identity-policy.tsnew file mode 100644index 000000000..ba8983221--- /dev/null+++ b/src/core/agents/node-identity-policy.ts@@ -0,0 +1,139 @@+/**+ * What a per-node token BUYS, per route: the policy that turns the three-way verdict from+ * `verifyNodeToken` into allow / allow-with-warning / refuse.+ *+ * The whole identity series up to here is measurement — it can say `verified`, `legacy`, `forged`+ * and it labels events with the answer, but nothing has ever DEPENDED on it. This file is where it+ * starts to. That is the dangerous half, because the population it governs is already running:+ * tmux sessions outlive the app, so on the day this ships there are live agent sessions holding a+ * launcher, a skill shim and an environment from before the token existed. Enforce on day one and+ * their next `manage-nodeterm-canvas` call stops working with no way for them to know why.+ *+ * So enforcement arrives in two moves, and both are here rather than scattered through the routes:+ *+ * 1. TRUST ON FIRST PROOF. A node that has never presented a token this instance minted keeps the+ * legacy path. A node that HAS is latched: an unverified request naming it afterwards is+ * refused, because that session demonstrably CAN authenticate and one that suddenly cannot is+ * either a different process wearing its node id or a forgery this instance cannot name. The+ * latch costs the legacy population nothing — they never prove anything, so they never latch.+ *+ * 2. A DATED WINDOW. Until `NODE_IDENTITY_STRICT_AFTER` an unverified MUTATION still executes and+ * the reply carries `IDENTITY_RESTART_NOTE`, which names the fix and the date. After it, the+ * same situation is a refusal. The date is in the source, not in a comment saying "later":+ * a tightening with no date is a tightening that never happens.+ */+import type { NodeTokenVerdict } from './node-auth-token'++/**+ * When an unverified mutation stops executing and starts being refused.+ *+ * The owner's rule was "the second minor release OR 60 days after the shipping release, whichever+ * is LATER", resolved here to the concrete instant that rule lands on. Resolved, not computed: a+ * date the code can print is a date a user can plan around, and a rule that has to be re-derived+ * from a release calendar is a rule that quietly never fires. Also in docs/node-identity.md.+ */+export const NODE_IDENTITY_STRICT_AFTER = new Date('2026-10-13T00:00:00Z')++/** The date as the user reads it. Derived, so the sentence and the constant cannot drift apart. */+const STRICT_DATE = NODE_IDENTITY_STRICT_AFTER.toISOString().slice(0, 10)++/**+ * Prefixed onto the reply of an unverified mutation that STILL RAN.+ *+ * It says what could not be established, that the command ran anyway, the exact action that fixes+ * it, and the date after which it stops being a note and starts being a refusal. One line, because+ * it is a prefix and a multi-line prefix buries the reply the agent actually asked for.+ */+export const IDENTITY_RESTART_NOTE =+ 'NodeTerm could not confirm which node sent this command: this session is not presenting its ' ++ 'node identity, so it ran unverified. Restart this node (right-click it, "Restart agent") to ' ++ `pick one up — from ${STRICT_DATE} commands from a session without one are refused.`++/**+ * The same situation once it is refused — after the cutoff, or once the node has proven itself and+ * an unverified caller turns up anyway.+ *+ * Deliberately carries NO date: it fires on both sides of the cutoff (the latch does not wait for+ * it), and a sentence that says "since <date>" would be false for half of the cases it answers.+ */+export const IDENTITY_REFUSED_NOTE =+ 'NodeTerm could not confirm which node sent this command, so it did not run: this session is ' ++ 'not presenting its node identity. Restart this node (right-click it, "Restart agent") to pick ' ++ 'one up.'++/**+ * Control verbs that an unproven, unverified caller may still run after the cutoff.+ *+ * `list` is the whole bucket: it leaks the shape of the canvas — node ids, titles, which agent is+ * where — and it changes nothing. Refusing it would break every legacy client's ability to even+ * ORIENT itself, permanently, for a leak that a caller already holding the shared bearer could get+ * from a dozen other places. Nothing that acts on the canvas belongs in here, and in particular not+ * the confirm-gated pair (`write`, `close`): tolerance would be the one way this feature could+ * weaken the human confirmation, which it must never do.+ */+export const TOLERANT_CONTROL_VERBS = new Set(['list'])++/**+ * The verb `/context-link/*` presents to `controlPolicy`.+ *+ * Every context-link verb is a READ — the route hands back a rendered transcript, summary or+ * terminal capture and changes nothing — so the whole route belongs in the same bucket as `list`.+ * Saying that with a named constant keeps it ONE bucket rather than two lists that drift.+ */+export const CONTEXT_LINK_POLICY_VERB = 'list'++export type IdentityDecision = 'allow' | 'allow-with-warning' | 'refuse'++export interface ControlPolicyInput {+ /** What `verifyNodeToken` made of the presented header. */+ verdict: NodeTokenVerdict+ /**+ * Has THIS node ever presented a token this instance minted for it?+ *+ * The caller is responsible for one subtlety: a FOREIGN kid (another instance's token — the+ * documented cross-instance failover) must arrive here as `proven: false`, even for a node that+ * has latched. It is `legacy` for the same reason it is `legacy` in `verifyNodeToken`: this+ * instance has no standing to judge another instance's credential, and latching against one+ * would break failover on the day a second instance appears.+ */+ proven: boolean+ /** The control verb; `CONTEXT_LINK_POLICY_VERB` for a context-link read. */+ verb: string+ /** Injected, never `Date.now()` inside: a suite has to be able to stand on both sides of the+ * cutoff without touching the machine clock. */+ now: Date+ /** `settings.hookIdentityStrict`. `undefined` ⇒ follow the constant. */+ override?: boolean+}++/**+ * Pure. Every route decision in this feature comes from this one table:+ *+ * forged → refuse (the one unambiguous attack signal)+ * verified → allow+ * legacy + latched → refuse (trust on first proof)+ * legacy + tolerant verb → allow (the legacy population's read path)+ * legacy + mutation, inside the window → allow-with-warning+ * legacy + mutation, past the cutoff → refuse+ *+ * `override === false` is the escape hatch: it releases the LATCH as well as the cutoff, because+ * the latch is the likelier of the two to have stranded a user whose upgrade went wrong, and a+ * hatch that does not rescue them is not a hatch. It never releases `forged`.+ */+export function controlPolicy({+ verdict,+ proven,+ verb,+ now,+ override+}: ControlPolicyInput): IdentityDecision {+ if (verdict === 'forged') return 'refuse'+ if (verdict === 'verified') return 'allow'+ if (override === false) {+ return TOLERANT_CONTROL_VERBS.has(verb) ? 'allow' : 'allow-with-warning'+ }+ if (proven) return 'refuse'+ if (TOLERANT_CONTROL_VERBS.has(verb)) return 'allow'+ const strict = override ?? now.getTime() >= NODE_IDENTITY_STRICT_AFTER.getTime()+ return strict ? 'refuse' : 'allow-with-warning'+}diff --git a/src/main/index.ts b/src/main/index.tsindex efdf5635e..443de37ac 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -918,6 +918,10 @@ app.whenReady().then(async () => {// unavailable the load rejects and we FAIL OPEN — identity stays unavailable (legacy mode),// `codexIdentityCaps()` answers `shared: false`, every launch line stays the bare `codex`, and// nothing is half-armed. Never throws up the boot path.+ // The escape hatch for per-route enforcement, read LIVE so flipping it in Settings takes effect+ // on the next request. Wired OUTSIDE the try: it is not part of arming the secret, and a machine+ // running in legacy mode is precisely one whose owner may need it.+ hookServer.setIdentityStrictOverride(() => settingsStore.get().hookIdentityStrict)try {const nodeAuthSecret = await loadOrCreateNodeAuthSecret()hookServer.setNodeAuthSecret(nodeAuthSecret)diff --git a/src/server/index.ts b/src/server/index.tsindex 8fcbd671c..e93387c41 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -424,6 +424,9 @@ export async function startServer(// secret is stored as raw 0600 bytes (node-auth-key.bin); the loader handles the at-rest format.// FAIL OPEN and LOUD: if the secret can't be created/read, identity stays unavailable (legacy// mode) and the hook server keeps serving — a throw here must never block boot or the hooks.+ // Same escape hatch as the desktop, wired OUTSIDE the try for the same reason: it is not part of+ // arming the secret, and a headless host in legacy mode is where it is most likely to be needed.+ hookServer.setIdentityStrictOverride(() => settingsStore.get().hookIdentityStrict)try {hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())// Materialise a token file for every persisted node so an already-running session becomesdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 80add576b..f63271d99 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1040,6 +1040,16 @@ export interface Settings {notchHoverExpand: boolean/** Dictation (desktop/server). Written as a whole object by the renderer. */speech: SpeechSettings+ /** Per-node hook identity enforcement (src/core/agents/node-identity-policy.ts).+ *+ * The ONLY optional key in this interface, and deliberately so: it is a TRI-state, and the two+ * non-default states are opposite escape hatches. Absent (the default — it is not in+ * DEFAULT_SETTINGS) follows `NODE_IDENTITY_STRICT_AFTER`, so the rollout has one schedule for+ * everybody. `true` opts in to strict enforcement before that date. `false` keeps the warning+ * window open past it and releases the trust-on-first-proof latch, so a user whose upgrade+ * strands a live session gets their canvas back without downgrading the app. Neither value ever+ * admits a forged token. */+ hookIdentityStrict?: boolean}export const DEFAULT_SETTINGS: Settings = {