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(security): four ways the identity gate stranded a node it meant to protect

Claude Code8cbe9f5d4de8
diff --git a/src/core/agents/codex-thread-id-route.test.ts b/src/core/agents/codex-thread-id-route.test.ts
index 65bedd247..576fa1852 100644
--- a/src/core/agents/codex-thread-id-route.test.ts
+++ b/src/core/agents/codex-thread-id-route.test.ts
@@ -17,6 +17,8 @@ import { fakePlatform } from '../platform-fake'
import { codexThreadIdentityRoot } from '../codex-identity-proxy'
const SECRET = Buffer.alloc(32, 3)
+// Another instance's secret ⇒ another instance's kid ⇒ the `legacy` failover verdict.
+const OTHER_SECRET = Buffer.alloc(32, 5)
const NODE = 'node-thread-route'
// The exact trap rows: `.` and `..` are path segments the charset accepts, `../x` and `a/b` carry a
@@ -25,6 +27,7 @@ const UNSAFE_THREAD_IDS = ['.', '..', '../x', 'a/b', '', 'x'.repeat(129)]
let dir = ''
let bound: { nodeId: string; threadId: string }[] = []
+let identityEvents: { nodeId: string; mode: string; reason?: string }[] = []
function bind(threadId: string): Promise<Response> {
return fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/bind`, {
@@ -47,6 +50,9 @@ beforeAll(async () => {
hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId }) => {
bound.push({ nodeId, threadId })
})
+ hookServer.setCodexIdentityListener((e) => {
+ identityEvents.push(e)
+ })
})
afterAll(() => {
@@ -58,6 +64,7 @@ afterAll(() => {
beforeEach(() => {
bound = []
+ identityEvents = []
})
describe('/codex-thread/bind refuses a path-unsafe thread id', () => {
@@ -78,3 +85,56 @@ describe('/codex-thread/bind refuses a path-unsafe thread id', () => {
expect(bound).toEqual([{ nodeId: NODE, threadId: '0199b4b7-8d4e-7a4e-9a2f-3c9d0f1a2b3c' }])
})
})
+
+/**
+ * `/codex-thread/fallback` is the launcher saying "I gave up, I am running plain codex". It grants
+ * nothing, and only `forged` is refused there — the same rule /hook/* follows, and the one
+ * docs/node-identity.md's per-route table states.
+ *
+ * The route shipped refusing anything that was not `verified`, which made it the one place in the
+ * series that 403s a CROSS-INSTANCE token. Invariant 3: a foreign kid is `legacy` and is never
+ * refused anywhere. The refusal also bought nothing — a hostile sibling wanting to flag another
+ * node as fallen back just omits the header, which was always accepted.
+ */
+describe('/codex-thread/fallback refuses only a forged token', () => {
+ const fallback = (token?: string): Promise<Response> => {
+ const headers: Record<string, string> = {
+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),
+ 'content-type': 'application/x-www-form-urlencoded'
+ }
+ if (token !== undefined) headers['X-Nodeterm-Node-Token'] = token
+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/fallback`, {
+ method: 'POST',
+ headers,
+ body: `nodeId=${encodeURIComponent(NODE)}&reason=node-token-unavailable`
+ })
+ }
+
+ it('accepts a tokenless report — the case it exists for', async () => {
+ expect((await fallback()).status).toBe(204)
+ expect(identityEvents).toEqual([{ nodeId: NODE, mode: 'plain', reason: 'node-token-unavailable' }])
+ })
+
+ it('accepts this instance’s own token', async () => {
+ expect((await fallback(nodeAuthToken(SECRET, NODE))).status).toBe(204)
+ expect(identityEvents).toHaveLength(1)
+ })
+
+ it('accepts ANOTHER instance’s token — a foreign kid is never refused, anywhere', async () => {
+ // The regression this test exists for. Two desktops sharing one remote host account is the
+ // documented failover; the loser's sessions present a foreign kid on every route, and its
+ // fallback reports were the one thing that went dark.
+ expect((await fallback(nodeAuthToken(OTHER_SECRET, NODE))).status).toBe(204)
+ expect(identityEvents).toEqual([{ nodeId: NODE, mode: 'plain', reason: 'node-token-unavailable' }])
+ })
+
+ it('accepts an invented kid too, for the same reason — it is unjudgeable, not hostile', async () => {
+ expect((await fallback('AAAAAAAA.BBBBBBBBBBBB')).status).toBe(204)
+ expect(identityEvents).toHaveLength(1)
+ })
+
+ it('403s OUR kid with a mac minted for another node — the one attack signal', async () => {
+ expect((await fallback(nodeAuthToken(SECRET, 'some-other-node'))).status).toBe(403)
+ expect(identityEvents).toEqual([])
+ })
+})
diff --git a/src/core/agents/hook-curl-config-sh.ts b/src/core/agents/hook-curl-config-sh.ts
index edc7d5d7e..48b5728dc 100644
--- a/src/core/agents/hook-curl-config-sh.ts
+++ b/src/core/agents/hook-curl-config-sh.ts
@@ -19,6 +19,27 @@
* copies of a quoting rule is how one of them stays wrong.
*/
+/**
+ * THE ESCAPING RULE, ONCE. A curl config file is LINE-based and its quoted values understand
+ * backslash escapes, so exactly four characters could end a header line and start a directive of
+ * their own: `"`, `\`, LF and CR. All four are STRIPPED from a value before it is written.
+ *
+ * Stripping (rather than escaping) is safe here because none can occur in a value we send — the
+ * per-node token is `kid.mac` over `[A-Za-z0-9._-]`, the bearer is a `randomUUID()` — so nothing
+ * legitimate is altered, and a value that somehow acquired one still cannot break out of its line.
+ *
+ * Two emitters read this list and no third may invent its own: `headerLine` (POSIX sh, for the
+ * generated clients) and `curlHeaderConfigLine` (Node, for a config file this process writes
+ * itself). A rule with two copies is a rule where one copy is wrong — which is how the SSH tunnel
+ * probe ended up ESCAPING two of the four and ignoring the line breaks entirely.
+ */
+const CURL_CONFIG_STRIP = ['\\', '"', '\n', '\r'] as const
+
+/** The same four characters as a `tr -d` set, single-quoted in sh (`tr` reads its own escapes). */
+const TR_STRIP_SET = CURL_CONFIG_STRIP.map((c) =>
+ c === '\\' ? '\\\\' : c === '\n' ? '\\n' : c === '\r' ? '\\r' : c
+).join('')
+
/**
* One `header = "<name>: <value>"` line for a curl config file, emitted by `printf` so the value
* is read from its sh variable AT CALL TIME (callers such as the managed script's failover re-read
@@ -28,7 +49,21 @@
* inside double quotes here, so it is never word-split or globbed.
*/
function headerLine(name: string, valueRef: string): string {
- return ` printf 'header = "${name}: %s"\\n' "$(printf %s "${valueRef}" | tr -d '\\\\"\\n\\r')"`
+ return ` printf 'header = "${name}: %s"\\n' "$(printf %s "${valueRef}" | tr -d '${TR_STRIP_SET}')"`
+}
+
+/**
+ * The same rule for a config file NODE writes and pipes to curl itself — today the SSH tunnel probe
+ * in `main/remote-ssh/remote-hooks.ts`, which is on the far side of a `ssh` child and so cannot use
+ * the sh emitter above.
+ *
+ * Newline-terminated, because a curl config file is line-based and an unterminated last line is a
+ * directive curl may or may not read depending on its version.
+ */
+export function curlHeaderConfigLine(name: string, value: string): string {
+ let v = value
+ for (const c of CURL_CONFIG_STRIP) v = v.split(c).join('')
+ return `header = "${name}: ${v}"\n`
}
/**
diff --git a/src/core/agents/hook-identity-enforcement.test.ts b/src/core/agents/hook-identity-enforcement.test.ts
index 827147e3a..5f37d9c90 100644
--- a/src/core/agents/hook-identity-enforcement.test.ts
+++ b/src/core/agents/hook-identity-enforcement.test.ts
@@ -23,6 +23,7 @@ import { initNodeTokens, refreshNodeTokens, sweepNodeToken } from './node-token-
import {
IDENTITY_REFUSED_NOTE,
IDENTITY_RESTART_NOTE,
+ IDENTITY_UNMINTABLE_NOTE,
NODE_IDENTITY_STRICT_AFTER,
TOLERANT_CONTROL_VERBS
} from './node-identity-policy'
@@ -489,6 +490,83 @@ describe('a swept token must also release the latch', () => {
})
})
+/**
+ * The refusal that told a node to restart to pick up an identity that cannot exist.
+ *
+ * Two populations can never hold a token, however many times they are restarted: a case-folding
+ * collision group (refused by design — on APFS they would share one file) and a node id outside
+ * `isSafeNodeId`, which reaches the canvas because `fileToProject` does not validate ids read out
+ * of `project.json`. Before the cutoff they get the warning window; after it every mutation is
+ * refused forever, and `IDENTITY_REFUSED_NOTE` sent them round a restart loop while the only real
+ * signal was a `console.warn` in the main-process log.
+ */
+describe('a node that can NEVER have an identity is told so, and not told to restart', () => {
+ beforeEach(() => {
+ hookServer.setIdentityClockForTests(() => PAST_CUTOFF)
+ })
+
+ it('names the cause for a case-folding collision group, on both dialects', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ initNodeTokens({ canvases: () => [{ nodes: [{ id: 'Dup-1' }, { id: 'dup-1' }] }] })
+ try {
+ const text = await control('open-terminal', 'Dup-1')
+ expect(text.status).toBe(403)
+ expect((await text.text()).trim()).toBe(IDENTITY_UNMINTABLE_NOTE)
+ // Both members of the set, not just the one that lost the race to the shared file.
+ const json = await control('open-terminal', 'dup-1', undefined, 'application/json')
+ expect(json.status).toBe(403)
+ expect(await json.json()).toEqual({ ok: false, error: IDENTITY_UNMINTABLE_NOTE })
+ expect(controlCalls).toEqual([])
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('names it for an id `isSafeNodeId` refuses, with nothing registered at all', async () => {
+ // No materialiser pass has ever seen this id — the server reads the impossibility off the id.
+ for (const nodeId of ['has space', 'a/b', '..', 'x'.repeat(129), '']) {
+ const res = await control('open-terminal', nodeId)
+ expect(res.status, nodeId).toBe(403)
+ expect((await res.text()).trim(), nodeId).toBe(IDENTITY_UNMINTABLE_NOTE)
+ }
+ expect(controlCalls).toEqual([])
+ })
+
+ it('does not say "Restart", because restarting is the thing that cannot work', () => {
+ expect(IDENTITY_UNMINTABLE_NOTE).not.toContain('Restart')
+ expect(IDENTITY_REFUSED_NOTE).toContain('Restart')
+ })
+
+ it('keeps the ordinary sentence for an ordinary node — the one a restart DOES fix', async () => {
+ const res = await control('open-terminal', 'n-ordinary-refusal')
+ expect(res.status).toBe(403)
+ expect((await res.text()).trim()).toBe(IDENTITY_REFUSED_NOTE)
+ })
+
+ it('goes back to the ordinary sentence once the twin leaves the canvas', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ let twinned = true
+ initNodeTokens({
+ canvases: () => [{ nodes: twinned ? [{ id: 'Gone-1' }, { id: 'gone-1' }] : [{ id: 'Gone-1' }] }]
+ })
+ try {
+ expect((await (await control('open-terminal', 'Gone-1')).text()).trim()).toBe(
+ IDENTITY_UNMINTABLE_NOTE
+ )
+ // The twin is removed from `project.json`; the next persist re-materialises the survivor.
+ twinned = false
+ refreshNodeTokens()
+ expect(existsSync(join(nodeTokenDir(), 'Gone-1'))).toBe(true)
+ // There IS an identity to pick up now, so the advice to restart is true again.
+ expect((await (await control('open-terminal', 'Gone-1')).text()).trim()).toBe(
+ IDENTITY_REFUSED_NOTE
+ )
+ } finally {
+ warn.mockRestore()
+ }
+ })
+})
+
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))
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 4a0ae12f8..ab9cc443a 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -15,6 +15,7 @@ import {
CONTEXT_LINK_POLICY_VERB,
IDENTITY_REFUSED_NOTE,
IDENTITY_RESTART_NOTE,
+ IDENTITY_UNMINTABLE_NOTE,
type IdentityDecision
} from './node-identity-policy'
@@ -152,6 +153,8 @@ class HookServer {
* and a restart must re-earn it. Bounded by the number of node ids that ever post here.
*/
private provenNodes = new Set<string>()
+ /** Node ids the materialiser refuses to mint for (see `markNodeIdentityUnmintable`). */
+ private unmintableNodes = new Set<string>()
private controlHandler:
| ((cmd: { verb: string; nodeId: string; args: Record<string, string> }) => Promise<{
ok: boolean
@@ -248,6 +251,39 @@ class HookServer {
this.provenNodes.delete(nodeId)
}
+ /**
+ * Node ids the materialiser has REFUSED to mint for, and will keep refusing until a file on disk
+ * changes — today, the members of a case-folding collision group (`node-token-service.ts`).
+ *
+ * It exists only to pick the right refusal SENTENCE. `IDENTITY_REFUSED_NOTE` tells the user to
+ * restart the node to pick up an identity; for these nodes there is nothing to pick up, so that
+ * advice sends them round a loop while the only other signal is a `console.warn` in a log they
+ * are not reading. The other unmintable population — an id outside `isSafeNodeId`, which reaches
+ * the canvas because `fileToProject` does not validate ids out of `project.json` — needs no
+ * registration: this server can see it in the id itself.
+ *
+ * Marked/cleared rather than recomputed because the collision is a property of the whole CANVAS,
+ * which the hook server has no view of.
+ */
+ markNodeIdentityUnmintable(nodeId: string): void {
+ this.unmintableNodes.add(nodeId)
+ }
+
+ /** The twin left the canvas (or the id was fixed): this node can be minted for again. */
+ clearNodeIdentityUnmintable(nodeId: string): void {
+ this.unmintableNodes.delete(nodeId)
+ }
+
+ /**
+ * Which refusal sentence this node should hear. `IDENTITY_UNMINTABLE_NOTE` names the real cause
+ * and deliberately does NOT advise a restart; see it for why that distinction is worth a Set.
+ */
+ private identityRefusalNote(nodeId: string): string {
+ return !isSafeNodeId(nodeId) || this.unmintableNodes.has(nodeId)
+ ? IDENTITY_UNMINTABLE_NOTE
+ : IDENTITY_REFUSED_NOTE
+ }
+
setControlHandler(cb: NonNullable<HookServer['controlHandler']>): void {
this.controlHandler = cb
}
@@ -381,12 +417,16 @@ class HookServer {
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.
+ // Which sentence: a node in a case-folding collision group, or with an id
+ // `isSafeNodeId` refuses, can NEVER pick up an identity, and telling it to restart is
+ // an instruction to loop forever. See `identityRefusalNote`.
+ const note = this.identityRefusalNote(nodeId)
if (wantsText) {
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
- res.end(`${IDENTITY_REFUSED_NOTE}\n`)
+ res.end(`${note}\n`)
} else {
res.writeHead(403, { 'content-type': 'application/json' })
- res.end(JSON.stringify({ ok: false, error: IDENTITY_REFUSED_NOTE }))
+ res.end(JSON.stringify({ ok: false, error: note }))
}
return
}
@@ -438,7 +478,7 @@ class HookServer {
// 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`)
+ res.end(`${this.identityRefusalNote(nodeId)}\n`)
return
}
// Always text: the caller is the sh shim, and the payload IS prose (a rendered
@@ -630,13 +670,15 @@ class HookServer {
if (verb === 'fallback') {
// This is the ONE route that may be called without the per-node capability, because the
// commonest thing it reports is "there was no capability to present" — requiring one would
- // silence it in exactly the case it exists for. That exemption is as narrow as it can be
- // made: a report that DOES carry a token must have the right one, so only a tokenless caller
- // is trusted on the nodeId it names. Without this a session holding the shared bearer could
- // flag a sibling node as fallen back. Cosmetic (the flag is transient and downgrade-only),
- // but a claim in a comment has to be true.
- const token = req.headers['x-nodeterm-node-token']
- if (token !== undefined && !this.nodeTokenVerified(nodeId, token)) {
+ // silence it in exactly the case it exists for. So only `forged` is refused here, the same
+ // rule /hook/* follows and the one the per-route table documents.
+ //
+ // It used to refuse anything that was not `verified`, which caught the CROSS-INSTANCE
+ // FAILOVER: another instance's token is `legacy`, and invariant 3 says a foreign kid is
+ // never refused anywhere. That check also bought nothing it was meant to buy — a hostile
+ // sibling wanting to flag another node as fallen back simply omits the header, which was
+ // always accepted — so it only ever silenced a legitimate report.
+ if (verifyNodeToken(this.nodeAuthSecretOrNull(), nodeId, req.headers['x-nodeterm-node-token']) === 'forged') {
res.writeHead(403)
res.end()
return
diff --git a/src/core/agents/node-identity-policy.ts b/src/core/agents/node-identity-policy.ts
index 052de0c15..03433fa41 100644
--- a/src/core/agents/node-identity-policy.ts
+++ b/src/core/agents/node-identity-policy.ts
@@ -118,6 +118,31 @@ export const IDENTITY_REFUSED_NOTE =
'not presenting its node identity. Restart this node (right-click it, "Restart agent") to pick ' +
'one up.'
+/**
+ * The refusal for a node that can NEVER have an identity, however many times it is restarted.
+ *
+ * Two populations land here, and both are permanent until a FILE is edited:
+ *
+ * - a node whose id case-folds onto another id on the same canvas. The materialiser refuses tokens
+ * for the whole colliding set on purpose (`node-token-service.ts`) — on APFS they would be one
+ * file, and that is the hijack.
+ * - a node whose id is outside `[A-Za-z0-9._-]`, or `.`/`..`/empty/over-length. `fileToProject`
+ * does not validate ids read out of `project.json`, so such an id reaches the canvas intact and
+ * `nodeAuthToken` returns '' for it forever.
+ *
+ * Giving those `IDENTITY_REFUSED_NOTE` is the worst kind of wrong answer: it names an action
+ * ("Restart this node… to pick one up") that is guaranteed not to work, so the user restarts in a
+ * loop while the only real signal — a `console.warn` in the main-process log — sits somewhere they
+ * will never look. This sentence names the cause instead, refuses to advise a restart, and points
+ * at both real ways out: fix the id, or use the escape hatch, which does release this.
+ */
+export const IDENTITY_UNMINTABLE_NOTE =
+ 'NodeTerm could not confirm which node sent this command, so it did not run — and this node can ' +
+ 'never present an identity, so restarting it will not help: its node id is invalid, or it ' +
+ "collides with another node id in this project's project.json when letter case is ignored. Fix " +
+ 'the duplicate or invalid id there, or turn off Settings → Agents → "Require verified node ' +
+ 'identity for canvas control".'
+
/**
* Control verbs that an unproven, unverified caller may still run after the cutoff.
*
diff --git a/src/core/agents/node-token-files.ts b/src/core/agents/node-token-files.ts
index 1d311aba8..70206ff12 100644
--- a/src/core/agents/node-token-files.ts
+++ b/src/core/agents/node-token-files.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, chmodSync, writeFileSync, renameSync, rmSync } from 'fs'
+import { mkdirSync, chmodSync, existsSync, writeFileSync, renameSync, rmSync } from 'fs'
import path from 'path'
import { platform } from '../platform'
import { isSafeNodeId } from './node-auth-token'
@@ -69,6 +69,28 @@ export function materialisedNodes(): ReadonlySet<string> {
return materialised
}
+/**
+ * Is this node's token file BOTH written by us this run AND still on disk?
+ *
+ * The Set alone is a "we wrote it" cache that is never re-checked, and that is a stranding bug the
+ * moment anything else touches the dir: remove `node-tokens/` while the app runs (a cleanup tool, a
+ * user tidying their data dir, a sync client) and every later `refreshNodeTokens()` short-circuits,
+ * writes nothing, and every live session presents an empty header — which for an already-PROVEN
+ * node is a hard 403 for the rest of the run, with no path back short of a restart.
+ *
+ * One `existsSync` per node per persist closes it and keeps the short-circuit's whole point (which
+ * was to stop a per-persist re-derive + tmp + rename + chmod storm, ~2000 syscalls on a 375-node
+ * workspace). A stat is not a write.
+ */
+export function nodeTokenFilePresent(nodeId: string): boolean {
+ if (!materialised.has(nodeId) || !isSafeNodeId(nodeId)) return false
+ try {
+ return existsSync(path.join(nodeTokenDir(), nodeId))
+ } catch {
+ return false // unreadable dir ⇒ re-assert, the fail-open direction everywhere else takes
+ }
+}
+
export function resetNodeTokenFilesForTests(): void {
materialised.clear()
}
diff --git a/src/core/agents/node-token-service.test.ts b/src/core/agents/node-token-service.test.ts
index 4d3f44398..90b845f8f 100644
--- a/src/core/agents/node-token-service.test.ts
+++ b/src/core/agents/node-token-service.test.ts
@@ -169,6 +169,30 @@ describe('node token service — writes once, not on every persist', () => {
expect(ino('node-1')).not.toBe(was)
})
+ /**
+ * The short-circuit is a "we wrote it" cache, and before this it was never re-checked against the
+ * filesystem. Anything that removes `node-tokens/` while the app runs — a cleanup tool, a user
+ * tidying their data dir, a sync client — therefore made every later refresh a no-op: live
+ * sessions present an empty header, and every already-PROVEN node takes a hard 403 for the rest
+ * of the run.
+ */
+ it('re-writes a token file deleted out of band, instead of trusting the cache forever', async () => {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => canvases })
+ fs.rmSync(nodeTokenDir(), { recursive: true, force: true })
+ refreshNodeTokens() // an ordinary persist, no `force`
+ expect(fs.readdirSync(nodeTokenDir()).sort()).toEqual(['node-1', 'node-2', 'node-3'])
+ })
+
+ it('still writes once, not twice, when the file IS there — the stat is not a rewrite', async () => {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => canvases })
+ const was = ino('node-1')
+ refreshNodeTokens()
+ refreshNodeTokens()
+ expect(ino('node-1')).toBe(was)
+ })
+
it('re-materialises a swept id, so a deleted-then-recreated node is not left on legacy', async () => {
hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
ensureNodeToken('node-1')
@@ -243,3 +267,55 @@ describe('node token service — the remote (SSH) minter', () => {
setRemoteNodeTokenWriter(null)
})
})
+
+/**
+ * A token file outlives its node whenever the node leaves the canvas by a path that does not go
+ * through `ptyManager.destroy(intent:'delete')` — a project removed, a canvas edited elsewhere, a
+ * hand-rewritten `project.json` — so the dir grows one 0600 file per dead id, forever.
+ *
+ * The sweep's authority is deliberately narrow: an id has to have been OBSERVED on a canvas earlier
+ * this run. `persistedCanvases()` is a view of what has been READ this run, so an id's absence from
+ * it is not evidence a node is gone — and sweeping a live node's token un-proves it and drops it to
+ * `legacy`, which after the cutoff is a node that cannot drive the canvas at all.
+ */
+describe('node token service — a node that leaves the canvas takes its token with it', () => {
+ it('sweeps the file and releases the latch for an id that was there and now is not', async () => {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ let live = [{ id: 'stays' }, { id: 'departs' }]
+ initNodeTokens({ canvases: () => [{ nodes: live }] })
+ expect(fs.readdirSync(nodeTokenDir()).sort()).toEqual(['departs', 'stays'])
+
+ // A departed node may have proved itself while it was still here, and a latch outliving the
+ // token it was earned with is a permanent 403 on that id if it ever comes back.
+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')
+
+ live = [{ id: 'stays' }]
+ refreshNodeTokens()
+ expect(fs.readdirSync(nodeTokenDir())).toEqual(['stays'])
+ expect(forget).toHaveBeenCalledWith('departs')
+ forget.mockRestore()
+ })
+
+ it('never sweeps an id it has not seen on a canvas this run', async () => {
+ // A file from a PREVIOUS run, for a node on a project this run has not read yet. Deleting it
+ // because it is missing from `canvasNodeIds()` would strand that node the moment its project
+ // loads — the exact bug the narrow authority exists to avoid.
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => [{ nodes: [{ id: 'known' }] }] })
+ fs.writeFileSync(path.join(nodeTokenDir(), 'from-a-project-not-loaded-yet'), 'tok\n', { mode: 0o600 })
+ refreshNodeTokens()
+ expect(fs.readdirSync(nodeTokenDir()).sort()).toEqual([
+ 'from-a-project-not-loaded-yet',
+ 'known'
+ ])
+ })
+
+ it('sweeps nothing on the BOOT pass, however empty the index still is', async () => {
+ // `initNodeTokens` runs before the desktop's workspace has necessarily been read. Starting the
+ // observed set empty is what stops a half-loaded index from costing every live node its token.
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => [{ nodes: [{ id: 'node-1' }] }] })
+ initNodeTokens({ canvases: () => [] })
+ expect(fs.readdirSync(nodeTokenDir())).toEqual(['node-1'])
+ })
+})
diff --git a/src/core/agents/node-token-service.ts b/src/core/agents/node-token-service.ts
index 1ec447c83..3242d9384 100644
--- a/src/core/agents/node-token-service.ts
+++ b/src/core/agents/node-token-service.ts
@@ -1,10 +1,32 @@
import { hookServer } from './hook-server'
import { nodeAuthToken, isSafeNodeId } from './node-auth-token'
-import { writeNodeTokenFile, sweepNodeTokenFile, materialisedNodes } from './node-token-files'
+import { writeNodeTokenFile, sweepNodeTokenFile, nodeTokenFilePresent } from './node-token-files'
type Canvases = () => Array<{ id?: string; nodes: Array<{ id: string }> }>
let canvases: Canvases = () => []
+/**
+ * Node ids this run has SEEN on a canvas. The orphan sweep's only source of authority.
+ *
+ * A token file outlives its node whenever the node leaves the canvas by any path that does not go
+ * through `ptyManager.destroy(intent:'delete')` — a project removed, a canvas edited elsewhere, a
+ * `project.json` rewritten by hand — so `node-tokens/` grows one 0600 file per dead id, forever.
+ *
+ * The tempting fix, "delete every file whose id is not in `canvasNodeIds()`", is WRONG here and it
+ * is worth writing down why: `workspaceStore.persistedCanvases()` is explicitly a view of what has
+ * been READ this run ("a project whose file has never been read this run is simply absent"). Its
+ * absence from that list is not evidence that a node is gone — and sweeping a live node's token
+ * un-proves it and drops it to `legacy`, which after the cutoff is a node that cannot drive the
+ * canvas at all.
+ *
+ * So the sweep only ever removes an id it has positively OBSERVED on a canvas earlier this run and
+ * that has since disappeared. Positive evidence in, positive evidence out. `initNodeTokens` starts
+ * it empty, so the BOOT pass — the one most likely to run against a half-loaded index — sweeps
+ * nothing and only records. What this cannot reclaim is a file orphaned by a PREVIOUS run; that
+ * needs an authoritative enumeration of every canvas, which this shell does not have.
+ */
+const seenNodeIds = new Set<string>()
+
/**
* The token FILENAME has to stay the bare node id: the client is `sh` + `curl`, it holds only
* `$NODETERM_NODE_ID`, and it cannot hash. That makes the filesystem's own name-equality part of
@@ -80,12 +102,22 @@ function sweepToken(nodeId: string): void {
hookServer.forgetProvenNode(nodeId)
}
-/** Loud on purpose: this is the only signal that a node is on `legacy` for a reason. */
-function warnCollision(group: readonly string[]): void {
+/**
+ * Announce a refusal, twice — once to whoever reads the main-process log, and once to the hook
+ * server, which is the only place a HUMAN can be told.
+ *
+ * The console.warn was the whole signal before, and it is the wrong one: the person who hits this
+ * is an agent's user watching a canvas-control call get refused, and the sentence they were shown
+ * (`IDENTITY_REFUSED_NOTE`) told them to restart the node to pick up an identity. These nodes can
+ * never pick one up — that is what a refusal MEANS here — so the advice is a loop. Marking the
+ * whole group unmintable is what lets the routes say the true thing instead.
+ */
+function refuseIdentityFor(group: readonly string[]): void {
console.warn(
'[node-identity] refusing per-node tokens: these node ids collide when case-folded and would ' +
`share one file on a case-insensitive filesystem — ${group.join(', ')}`
)
+ for (const id of group) hookServer.markNodeIdentityUnmintable(id)
}
function canvasNodeIds(): string[] {
@@ -95,15 +127,25 @@ function canvasNodeIds(): string[] {
}
/**
- * `materialisedNodes()` is exactly the right key for the short-circuit: it holds the ids this RUN
- * has written a readable file for, and the token is DERIVED from (secret, nodeId) — neither input
- * can change without a restart — so a second write produces byte-identical content. `force` is the
- * boot sweep's door past it, for a run that wants the files re-asserted regardless.
+ * The short-circuit: skip an id whose file this run already wrote AND that is still on disk. The
+ * token is DERIVED from (secret, nodeId) — neither input can change without a restart — so a second
+ * write produces byte-identical content, and re-deriving it on every persist cost a ~375-node
+ * workspace ~2000 synchronous syscalls per save.
+ *
+ * `nodeTokenFilePresent`, not the bare Set: a Set that is never re-checked against the filesystem
+ * turns an out-of-band `rm -rf node-tokens/` into a permanent 403 for every proven node (see it).
+ * `force` is the boot sweep's door past the whole check.
*
* `sweepNodeTokenFile` deletes from that Set, so a deleted-and-recreated node re-materialises.
*/
function materialiseOne(secret: Buffer, nodeId: string, force: boolean): void {
- if (!force && materialisedNodes().has(nodeId)) return
+ // Reaching here means this id is NOT in a colliding group on this pass, so whatever refused it
+ // before no longer holds — the twin left the canvas, or the id was fixed. Cleared before the
+ // short-circuit, because the short-circuit is the steady state and the mark must not outlive the
+ // condition that set it. An id `isSafeNodeId` refuses needs no clearing: the hook server reads
+ // that off the id itself.
+ hookServer.clearNodeIdentityUnmintable(nodeId)
+ if (!force && nodeTokenFilePresent(nodeId)) return
const token = nodeAuthToken(secret, nodeId)
if (token) writeNodeTokenFile(nodeId, token)
}
@@ -117,6 +159,10 @@ function materialiseOne(secret: Buffer, nodeId: string, force: boolean): void {
*/
export function initNodeTokens(deps: { canvases: Canvases }): void {
canvases = deps.canvases
+ // A new provider is a new world: nothing observed under the old one is evidence about this one.
+ // It also means the boot pass records without sweeping, which is what keeps a workspace index
+ // that is still loading from costing every live node its token.
+ seenNodeIds.clear()
refreshNodeTokens({ force: true })
}
@@ -128,7 +174,7 @@ export function ensureNodeToken(nodeId: string, opts?: { force?: boolean }): voi
// its canvas has been persisted.
const group = collidingGroups([...canvasNodeIds(), nodeId]).get(nodeId)
if (group) {
- warnCollision(group)
+ refuseIdentityFor(group)
for (const id of group) sweepToken(id)
return
}
@@ -164,7 +210,7 @@ export function remoteNodeTokenMinter(): ((nodeId: string) => string) | null {
return (nodeId: string): string => {
const group = collidingGroups([...canvasNodeIds(), nodeId]).get(nodeId)
if (group) {
- warnCollision(group)
+ refuseIdentityFor(group)
// The latch is keyed by node id and is instance-global — an SSH node proves itself over the
// same hook server — so a refusal here has to release it too, or the remote node is stranded
// exactly as a local one would be. The FILE lives on the host and the caller sweeps it there;
@@ -202,6 +248,23 @@ export function ensureRemoteNodeToken(controlPath: string, nodeId: string): void
}
}
+/**
+ * Delete the token of every node we WATCHED leave a canvas, and release its latch with it.
+ *
+ * Only ids in `seenNodeIds` are candidates — see there for why absence from `canvasNodeIds()` is
+ * not on its own evidence that a node is gone. `sweepToken`, not `sweepNodeTokenFile`: a departed
+ * node may have proved itself while it was still here, and a latch outliving the token it was
+ * earned with is a permanent 403 on the id if it ever comes back.
+ */
+function sweepDepartedNodes(live: ReadonlySet<string>): void {
+ for (const id of seenNodeIds) {
+ if (live.has(id)) continue
+ seenNodeIds.delete(id)
+ sweepToken(id)
+ }
+ for (const id of live) seenNodeIds.add(id)
+}
+
/**
* Wired to `onPersist`, which fires on every canvas LOAD and every canvas SAVE. Rewriting every
* token for every node in every project there cost a ~375-node workspace ~2000 synchronous syscalls
@@ -213,9 +276,10 @@ export function refreshNodeTokens(opts?: { force?: boolean }): void {
const secret = hookServer.nodeAuthSecretOrNull()
if (!secret) return
const ids = canvasNodeIds()
+ sweepDepartedNodes(new Set(ids))
const colliding = collidingGroups(ids)
for (const group of new Set(colliding.values())) {
- warnCollision(group)
+ refuseIdentityFor(group)
// Sweep, don't merely skip: an earlier pass may have written one of these before its twin
// appeared on the canvas, and that surviving file is the token the twin would read. `sweepToken`
// (not `sweepNodeTokenFile`) because that same earlier pass may already have let the node PROVE
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 7968e0bbd..afacf4fb8 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { RemoteHooks, isSafeRemoteHome } from './remote-hooks'
+import { hookServer } from '../../core/agents/hook-server'
const conn = { host: 'h', user: 'u' }
@@ -517,7 +518,10 @@ describe('RemoteHooks.writeNodeTokens', () => {
}
const writes = calls.filter((c) => c.cmd.includes('cat >'))
expect(writes).toHaveLength(2)
- expect(writes[0].cmd).toContain("cat > '/home/u/.nodeterm/node-tokens/node-1'")
+ // tmp + rename, the local writer's shape: `cat >` truncates, so writing straight at the file
+ // leaves an EMPTY token behind when the host is out of quota or disk.
+ expect(writes[0].cmd).toContain("cat > '/home/u/.nodeterm/node-tokens/.node-1.tmp'")
+ expect(writes[0].cmd).toContain("mv -f '/home/u/.nodeterm/node-tokens/.node-1.tmp' '/home/u/.nodeterm/node-tokens/node-1'")
// ...and the token is on stdin, newline-terminated (the client reads it with `head -n 1`).
expect(writes[0].stdin).toBe(`${mint('node-1')}\n`)
expect(writes.at(-1)?.stdin).toBe(`${mint('node-2')}\n`)
@@ -557,7 +561,7 @@ describe('RemoteHooks.writeNodeTokens', () => {
return { code: 0, stdout: '' }
})
await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)
- expect(calls.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ expect(calls.some((c) => c.includes("node-tokens/node-2'"))).toBe(true)
})
it('an unsafe node id reaches no path and no command AT ALL', async () => {
@@ -588,6 +592,48 @@ describe('RemoteHooks.writeNodeTokens', () => {
expect(calls).toHaveLength(0)
})
+ /**
+ * INVARIANT 7 — a sweep releases the latch. Every OTHER path that takes a token away calls
+ * `hookServer.forgetProvenNode` (`sweepToken` in node-token-service); this one did not, and the
+ * latch is instance-global and keyed by node id, so a remote node whose write did not land was
+ * refused permanently at the desktop — told to restart to pick up an identity that is not on the
+ * host to pick up.
+ *
+ * The failure is a `code`, not a throw: the runner RESOLVES on a non-zero exit, which is why
+ * reading only the `catch` left this invisible.
+ */
+ describe('a write that does not land releases the latch', () => {
+ it('un-proves the node when the host exits non-zero', async () => {
+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')
+ const run = vi.fn(async (args: string[]) => ({
+ code: args.join(' ').includes('cat >') ? 1 : 0,
+ stdout: ''
+ }))
+ await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ expect(forget).toHaveBeenCalledWith('node-1')
+ forget.mockRestore()
+ })
+
+ it('un-proves the node when the runner throws', async () => {
+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')
+ const run = vi.fn(async (args: string[]) => {
+ if (args.join(' ').includes('cat >')) throw new Error('EACCES')
+ return { code: 0, stdout: '' }
+ })
+ await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ expect(forget).toHaveBeenCalledWith('node-1')
+ forget.mockRestore()
+ })
+
+ it('leaves a node whose write DID land alone — the latch is what protects it', async () => {
+ const forget = vi.spyOn(hookServer, 'forgetProvenNode')
+ const { rh } = tokenHarness()
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ expect(forget).not.toHaveBeenCalled()
+ forget.mockRestore()
+ })
+ })
+
it('sweeps a token the minter REFUSES (case-fold collision) instead of leaving it on the host', async () => {
// The refusal is the local sweep's remote twin: a file an earlier connect wrote for a
// colliding id is exactly the token its twin would read.
@@ -595,8 +641,8 @@ describe('RemoteHooks.writeNodeTokens', () => {
const refusing = (id: string): string => (id === 'Node-1' ? '' : mint(id))
await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['Node-1', 'node-2'], refusing)
expect(calls.some((c) => c.cmd.includes("rm -f '/home/u/.nodeterm/node-tokens/Node-1'"))).toBe(true)
- expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/Node-1'"))).toBe(false)
- expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/.Node-1.tmp'"))).toBe(false)
+ expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/.node-2.tmp'"))).toBe(true)
})
})
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index cda51ef66..c99ca43db 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -9,6 +9,8 @@ import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileCo
import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@shared/agents/hook-events'
import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'
import { isSafeNodeId } from '../../core/agents/node-auth-token'
+import { hookServer } from '../../core/agents/hook-server'
+import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
/**
@@ -267,6 +269,11 @@ export class RemoteHooks {
* SWEEPS: an earlier connect's file for that id is precisely the token its colliding twin would
* read, so leaving it in place is the attack the local `node-token-service` sweeps for.
*
+ * Fail-open does NOT mean fail-silent: a node whose write did not land has no token to present,
+ * and the trust-on-first-proof latch lives at the DESKTOP and is keyed by node id, so leaving it
+ * armed over a token that is not there is a permanent 403 (invariant 7). Every failure path here
+ * therefore calls `hookServer.forgetProvenNode`.
+ *
* KNOWN LIMITATION — the dir is flat, i.e. per HOST ACCOUNT, not per nodeterm instance. Two
* instances driving the same host+user (two desktops sharing a deploy account, or a desktop
* whose SSH project points at a host that also runs a headless Server Edition under the same
@@ -319,16 +326,36 @@ export class RemoteHooks {
if (mk.code !== 0) return // no dir ⇒ no files; the nodes stay `legacy`
for (const { id, token } of writes) {
const file = posixQuote(`${dir}/${id}`)
+ // TMP + RENAME, the same shape the local writer uses, and for a reason that is not
+ // cosmetic: `cat > <file>` TRUNCATES before the write can fail, so a host that is out of
+ // quota or disk left the node holding an EMPTY token file. An empty header reads as
+ // `legacy`, and a node still latched at the desktop then takes a hard 403 on every
+ // canvas-control call for the rest of the session. Writing beside the file and renaming
+ // means a failure costs the node nothing it already had.
+ const tmp = posixQuote(`${dir}/.${id}.tmp`)
+ let wrote = false
try {
- await this.r.run(
- // `cat >` TRUNCATES an existing file and keeps its old mode, so the chmod is not
- // redundant with the umask: it is what re-narrows a file some earlier state left wide.
- childArgs(conn, controlPath, `umask 077; cat > ${file} && chmod 600 ${file}`),
+ // chmod on the TMP, so the mode is right before the name exists; `mv` within one dir is
+ // a rename, which carries the tmp's 0600 over whatever the destination's mode was.
+ const w = await this.r.run(
+ childArgs(
+ conn,
+ controlPath,
+ `umask 077; cat > ${tmp} && chmod 600 ${tmp} && mv -f ${tmp} ${file} || { rm -f ${tmp}; exit 1; }`
+ ),
`${token}\n` // newline-terminated: the client reads it with `head -n 1`
)
+ // The runner RESOLVES on a non-zero exit — a failed write is a `code`, not a throw, and
+ // reading only the throw is how this failure stayed invisible.
+ wrote = w.code === 0
} catch {
/* fail-open per node: one unwritable token must not cost the others theirs */
}
+ // INVARIANT 7 — a node with no token must not stay latched. Every other path that takes a
+ // token away releases the latch (`sweepToken` in node-token-service); this one silently did
+ // not, and the desktop's latch is instance-global, so a remote node whose write failed was
+ // refused permanently with advice to restart that could not help.
+ if (!wrote) hookServer.forgetProvenNode(id)
}
} catch {
/* fail-open: an identity file must never be able to fail a connect */
@@ -805,13 +832,14 @@ export class RemoteHooks {
// it there. `nodeId=verify` is kept in the body only so an OLDER desktop's script and this
// one send the same bytes; the route reads nothing.
`--config - http://localhost/verify --data nodeId=verify`
- // A curl config file's double-quoted value understands backslash escapes, so the token is
- // escaped for it. Today's bearer is a `randomUUID()` (hex + dashes) and cannot contain
- // either character — the escaping is here so that stays true if the mint ever changes.
- const header = token.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
+ // ONE COPY OF THE QUOTING RULE. This used to build its own `header = "…"` line, escaping `\`
+ // and `"` and ignoring the two line breaks — a second, weaker version of the rule that
+ // `hook-curl-config-sh.ts` states for the generated sh clients. `curlHeaderConfigLine` is
+ // that same rule for a config file WE write; a rule with two copies is a rule where one copy
+ // is wrong.
const r = await this.r.run(
childArgs(conn, controlPath, cmd),
- `header = "x-nodeterm-hook-token: ${header}"\n`
+ curlHeaderConfigLine('x-nodeterm-hook-token', token)
)
return r.code === 0 && r.stdout.trim() === '204'
} catch {
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 2dc0f6e04..19f958db5 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -2008,8 +2008,10 @@ describe('SshProjectManager — per-node tokens on the host', () => {
await mgr.connect('p1', conn)
await settle()
const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
- expect(cmds.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-1'"))).toBe(true)
- expect(cmds.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ // tmp + rename (`cat >` truncates, so writing straight at the file leaves an EMPTY token
+ // behind when the host is out of quota or disk — see RemoteHooks.writeNodeTokens).
+ expect(cmds.some((c) => c.includes("mv -f '/home/u/.nodeterm/node-tokens/.node-1.tmp' '/home/u/.nodeterm/node-tokens/node-1'"))).toBe(true)
+ expect(cmds.some((c) => c.includes("mv -f '/home/u/.nodeterm/node-tokens/.node-2.tmp' '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
// never on a command line — the host's process table is readable by its other users.
expect(cmds.some((c) => c.includes('mac-of-node-1'))).toBe(false)
const write = run.mock.calls.find(([a]) =>
@@ -2052,7 +2054,7 @@ describe('SshProjectManager — per-node tokens on the host', () => {
run.mockClear()
await mgr.writeNodeTokenForNode(controlPath, 'node-9')
const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
- expect(cmds.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-9'"))).toBe(true)
+ expect(cmds.some((c) => c.includes("mv -f '/home/u/.nodeterm/node-tokens/.node-9.tmp' '/home/u/.nodeterm/node-tokens/node-9'"))).toBe(true)
// an unknown control path is a no-op, not a throw
run.mockClear()
await expect(mgr.writeNodeTokenForNode('/nope.sock', 'node-9')).resolves.toBeUndefined()