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.

refactor(codex): one derivation, one secret — retrofit #167 onto kid.mac + the file channel

Claude Code00df63fb09e9
diff --git a/docs/codex-shared-identity.md b/docs/codex-shared-identity.md
index 9f2e36292..5642763ea 100644
--- a/docs/codex-shared-identity.md
+++ b/docs/codex-shared-identity.md
@@ -58,7 +58,9 @@ other install runs plain `codex`. §3 is what makes that a quiet degrade instead
| `src/core/codex-session-name.ts` | The app-server protocol client: mint a thread, check one exists, read its name. |
| `src/core/codex-identity-caps.ts` | "Can a node on this machine get a managed identity?" — the construction-time gate. |
| `src/core/agents/hook-server.ts` | The `/codex-thread/{start,bind,fallback}` routes and the per-node capability. |
-| `src/main/codex-node-auth-secret.ts` | The keychain-backed secret both of the above are keyed on. |
+| `src/core/agents/node-auth-secret.ts` | The one restart-stable secret both of the above are keyed on (sealed via `safeStorage` on the desktop, raw 0600 bytes on the Server Edition). |
+| `src/core/agents/node-auth-token.ts` | The one derivation — `kid.mac` — and the three-way verifier every route judges a presented token with. |
+| `src/core/agents/node-token-files.ts` | How a token reaches the client: one 0600 file per node under `node-tokens/`, never the tmux argv. |
| `src/renderer/state/codexIdentity.ts` | The renderer's gate + the transient per-node mode the UI shows. |
### The records
diff --git a/src/core/agents/hook-server.env.test.ts b/src/core/agents/hook-server.env.test.ts
index 668742173..f4736e93a 100644
--- a/src/core/agents/hook-server.env.test.ts
+++ b/src/core/agents/hook-server.env.test.ts
@@ -9,6 +9,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { hookServer } from './hook-server'
+import { nodeAuthToken } from './node-auth-token'
import { initPlatform, resetPlatformForTests } from '../platform'
import { fakePlatform } from '../platform-fake'
@@ -86,7 +87,7 @@ describe('hookServer.buildPtyEnv — no credential in the tmux -e argv (the §2.
*/
it('emits no PER-NODE capability either, for a shared-identity agent with identity armed', () => {
expect(hookServer.identityAvailable()).toBe(true)
- const minted = hookServer.codexNodeAuthToken('n1')
+ const minted = nodeAuthToken(hookServer.nodeAuthSecretOrNull()!, 'n1')
expect(minted).toBeTruthy() // the value that must NOT be reachable via /proc/<pid>/cmdline
const env = hookServer.buildPtyEnv('n1', 'codex')
expect(Object.keys(env).filter((k) => /token/i.test(k))).toEqual([])
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 284215558..b7b4b6698 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -1,5 +1,5 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
-import { createHmac, randomUUID, timingSafeEqual } from 'crypto'
+import { randomUUID, timingSafeEqual } from 'crypto'
import { writeFileSync, mkdirSync } from 'fs'
import path from 'path'
import { platform } from '../platform'
@@ -7,7 +7,7 @@ import { canControlCanvas, type AgentId } from '../../shared/agents/config'
import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'
import type { CodexIdentityEvent } from '../../shared/types'
import { nodeTokenDir } from './node-token-files'
-import { verifyNodeToken } from './node-auth-token'
+import { isSafeNodeId, verifyNodeToken } from './node-auth-token'
// v2 advertises NODETERM_NODE_TOKEN_DIR so clients read their per-node capability from a file
// rather than receiving it in argv. Nothing consumes the posted version server-side, so the bump
@@ -159,7 +159,7 @@ class HookServer {
/**
* The shared-identity spine's handlers (see core/codex-identity-proxy.ts). Both are injected by
* the shell, and BOTH routes below additionally require a per-node capability — see
- * `codexNodeAuthToken`.
+ * `nodeTokenVerified`.
*/
private codexThreadStartHandler:
| ((req: { nodeId: string; cwd: string; hookEndpoint: string }) => Promise<string>)
@@ -169,7 +169,7 @@ class HookServer {
| null = null
private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = null
private endpointPath = ''
- private codexNodeAuthSecret: Buffer | null = null
+ private nodeAuthSecret: Buffer | null = null
endpointFilePath(): string {
if (!this.endpointPath) this.endpointPath = path.join(platform().userDataDir, 'hook-endpoint.env')
@@ -231,25 +231,6 @@ class HookServer {
this.codexIdentityListener = cb
}
- /**
- * Mint the capability a Codex process must present for node-scoped identity operations.
- *
- * THIS IS THE SECURITY FIX. The global hook bearer proves only "this request came from some
- * NodeTerm-spawned session"; it cannot prove WHICH session. Every identity route takes a
- * caller-supplied `nodeId`, so with the shared bearer alone any agent session could bind ITS
- * OWN codex thread to a SIBLING node — reparenting another node's status, and (through the hook
- * prelude, which re-exports the recorded node id and endpoint) aiming that node's hook traffic.
- * This token is HMAC(secret, nodeId): stable across app restarts, scoped to one node, injected
- * only into that node's session env, and never written to the shared endpoint file that every
- * session can read.
- */
- codexNodeAuthToken(nodeId: string): string {
- if (!/^[A-Za-z0-9._-]+$/.test(nodeId)) return ''
- if (!this.codexNodeAuthSecret)
- throw new Error('NodeTerm Codex node authentication is unavailable')
- return createHmac('sha256', this.codexNodeAuthSecret).update(nodeId).digest('base64url')
- }
-
/**
* The shell injects a restart-stable node-auth secret before any identity-scoped PTY is created —
* sealed via safeStorage on the desktop, raw 0600 bytes on the Server Edition (see
@@ -258,36 +239,24 @@ class HookServer {
*/
setNodeAuthSecret(secret: Uint8Array): void {
if (secret.byteLength < 32) throw new Error('Invalid NodeTerm node-auth secret')
- this.codexNodeAuthSecret = Buffer.from(secret)
- }
-
- /**
- * Thin alias kept for one release so anything still calling the #167-era name keeps working while
- * both shells migrate to setNodeAuthSecret. A later task removes it.
- */
- setCodexNodeAuthSecret(secret: Uint8Array): void {
- this.setNodeAuthSecret(secret)
+ this.nodeAuthSecret = Buffer.from(secret)
}
/** True once a valid secret is set; false before, and after a failed load (nothing was set). The
* later routing tasks gate every identity-scoped decision on this. */
identityAvailable(): boolean {
- return !!this.codexNodeAuthSecret
+ return !!this.nodeAuthSecret
}
/** The raw secret for the routing tasks that must derive/verify per-node capabilities themselves,
* or null when identity is unavailable (legacy mode). Callers must handle null — never throw. */
nodeAuthSecretOrNull(): Buffer | null {
- return this.codexNodeAuthSecret
- }
-
- hasCodexNodeAuth(): boolean {
- return !!this.codexNodeAuthSecret
+ return this.nodeAuthSecret
}
/** Test seam only: this server is a module singleton, so its secret otherwise leaks across tests. */
clearNodeAuthSecretForTests(): void {
- this.codexNodeAuthSecret = null
+ this.nodeAuthSecret = null
}
async start(): Promise<void> {
@@ -463,18 +432,20 @@ class HookServer {
return a.length === b.length && timingSafeEqual(a, b)
}
- private codexNodeTokenMatches(nodeId: string, provided: string | string[] | undefined): boolean {
- if (typeof provided !== 'string') return false
- let expected = ''
- try {
- expected = this.codexNodeAuthToken(nodeId)
- } catch {
- return false
- }
- if (!expected) return false
- const a = Buffer.from(provided)
- const b = Buffer.from(expected)
- return a.length === b.length && timingSafeEqual(a, b)
+ /**
+ * The identity routes' gate: ONE derivation, the same `verifyNodeToken` /hook/* is labelled by.
+ *
+ * These routes are STRICT — only `verified` proceeds. `legacy` (no token, an empty header,
+ * another instance's kid, no secret at all) is refused here, deliberately and unlike /hook/*:
+ * they were strict from the day they existed, so there is no upgrade population to protect. A
+ * session that predates the per-node capability has no launcher that calls `/codex-thread/*` at
+ * all; failing it open would buy nothing and hand back the authorization hole the capability
+ * exists to close (any session holding the shared bearer binding its own codex thread to a
+ * SIBLING node — reparenting that node's status and, through the hook prelude which re-exports
+ * the recorded node id and endpoint, aiming that node's hook traffic).
+ */
+ private nodeTokenVerified(nodeId: string, provided: string | string[] | undefined): boolean {
+ return verifyNodeToken(this.nodeAuthSecretOrNull(), nodeId, provided) === 'verified'
}
/**
@@ -505,7 +476,9 @@ class HookServer {
// that gives up first and can clean up after itself.
req.setTimeout(CONTROL_CEILING_MS, () => req.destroy())
const nodeId = form.nodeId ?? ''
- if (!/^[A-Za-z0-9._-]+$/.test(nodeId)) {
+ // `isSafeNodeId`, not a local regex: the same predicate the token derivation and the token
+ // FILE path use, so an id one of them would refuse can never reach the other two.
+ if (!isSafeNodeId(nodeId)) {
res.writeHead(400)
res.end()
return
@@ -519,7 +492,7 @@ class HookServer {
// 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.codexNodeTokenMatches(nodeId, token)) {
+ if (token !== undefined && !this.nodeTokenVerified(nodeId, token)) {
res.writeHead(403)
res.end()
return
@@ -536,7 +509,7 @@ class HookServer {
res.end()
return
}
- if (!this.codexNodeTokenMatches(nodeId, req.headers['x-nodeterm-node-token'])) {
+ if (!this.nodeTokenVerified(nodeId, req.headers['x-nodeterm-node-token'])) {
res.writeHead(403)
res.end()
return
@@ -638,13 +611,9 @@ class HookServer {
// proves WHICH node is calling, so a sibling uid reading it off /proc/<pid>/cmdline could
// bind its own codex thread to that node — the exact reparenting this capability exists to
// prevent. It reaches the client through the 0600 token file instead (nodeTokenDir(), keyed
- // by $NODETERM_NODE_ID and advertised in the endpoint file).
- //
- // The launcher (core/codex-identity-proxy.ts) still reads the ENV var and is not yet wired to
- // the file — that retrofit is its own task. Until then a codex node finds no capability, its
- // preflight reports `node-token-unavailable`, and it execs plain codex: shared identity is
- // INERT, not broken. That is the fallback this launcher was built around, and an inert
- // feature is a straight trade against a live cross-uid credential leak.
+ // by $NODETERM_NODE_ID and advertised in the endpoint file) — where the launcher
+ // (core/codex-identity-proxy.ts) reads it, exactly as the managed script and both sh shims
+ // do, so shared identity is LIVE with no credential in anyone's argv.
}
}
diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.ts
index b9a58d8c6..d775d10dd 100644
--- a/src/core/codex-identity-proxy.ts
+++ b/src/core/codex-identity-proxy.ts
@@ -14,8 +14,9 @@
* re-exports both into the agent's environment. An attacker who could write one of these files
* could aim a session's hook traffic at a node (or an endpoint) of their choosing. Every record
* therefore carries an HMAC over (threadId, nodeId, endpoint) keyed by the same restart-stable
- * secret the hook server uses to mint per-node capabilities (`src/main/codex-node-auth-secret.ts`).
- * Unsigned/mis-signed records are ignored, not repaired.
+ * secret the hook server uses to mint per-node capabilities
+ * (`src/core/agents/node-auth-secret.ts` — sealed via safeStorage on the desktop, raw 0600 bytes on
+ * the Server Edition). Unsigned/mis-signed records are ignored, not repaired.
*
* ACCOUNT SCOPING is deliberately absent here: managed Codex accounts are a later slice. The
* storage shape is one file per thread id; scoping adds a directory level above it without
@@ -282,6 +283,7 @@ export function buildCodexLauncherScript(
# identity must still be a working node.
nt_reason=''
+nt_node_token=''
nt_fail() { nt_reason=$1; return 1; }
nt_hook_curl() { curl "$@"; }
@@ -311,9 +313,22 @@ nt_preflight() {
. "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || { nt_fail broker-unreachable; return; }
case "\${NODETERM_HOOK_PORT-}" in ''|*[!0-9]*) nt_fail broker-unreachable; return ;; esac
case "\${NODETERM_HOOK_TOKEN-}" in ''|*[!A-Za-z0-9-]*) nt_fail broker-unreachable; return ;; esac
- # The per-node capability. Absent => this build/shell has no managed identity to give.
- case "\${NODETERM_CODEX_NODE_TOKEN-}" in
- ''|*[!A-Za-z0-9_-]*) nt_fail node-token-unavailable; return ;;
+ # The PER-NODE capability, read the way every other client reads it: the endpoint file (v2,
+ # sourced just above) advertises the directory, and the token is one 0600 file in it named for
+ # THIS node id — a lookup by name, never a scan, so a session can only ever present its own. It
+ # is deliberately NOT an env var any more: that channel put the credential on the tmux \`-e\`
+ # argv, world-readable on a stock Linux, and the credential's whole job is to prove WHICH node
+ # is calling. \$NODETERM_CODEX_NODE_TOKEN survives only as a one-release fallback for a session
+ # spawned by the previous build, which carries the var and has no file yet.
+ if [ -n "\${NODETERM_NODE_TOKEN_DIR-}" ]; then
+ nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null) || nt_node_token=''
+ fi
+ [ -n "$nt_node_token" ] || nt_node_token="\${NODETERM_CODEX_NODE_TOKEN-}"
+ # The '.' IS the token: the wire shape is kid.mac (one derivation shared with /hook/*). A gate
+ # without the dot rejects every token this app mints and degrades every codex node to plain
+ # codex — silently, because falling back is what this script is built to do.
+ case "$nt_node_token" in
+ ''|*[!A-Za-z0-9._-]*) nt_fail node-token-unavailable; return ;;
esac
if [ "\${1-}" = resume ]; then
case "\${2-}" in ''|*[!A-Za-z0-9._-]*) nt_fail thread-id-unavailable; return ;; esac
@@ -368,7 +383,7 @@ nt_post() {
nt_budget=$1
shift
printf 'header = "X-NodeTerm-Hook-Token: %s"\\nheader = "X-NodeTerm-Node-Token: %s"\\n' \\
- "$NODETERM_HOOK_TOKEN" "$NODETERM_CODEX_NODE_TOKEN" |
+ "$NODETERM_HOOK_TOKEN" "$nt_node_token" |
nt_hook_curl --silent --show-error --fail --max-time "$nt_budget" --config - --request POST "$@"
}
diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.ts
index ea3c2bede..0cda48311 100644
--- a/src/core/codex-launcher-sh.test.ts
+++ b/src/core/codex-launcher-sh.test.ts
@@ -15,11 +15,22 @@ import { promisify } from 'node:util'
import { randomBytes } from 'node:crypto'
import { buildCodexLauncherScript } from './codex-identity-proxy'
import { hookServer } from './agents/hook-server'
+import { nodeAuthKid, nodeAuthToken } from './agents/node-auth-token'
+import {
+ nodeTokenDir,
+ resetNodeTokenFilesForTests,
+ sweepNodeTokenFile,
+ writeNodeTokenFile
+} from './agents/node-token-files'
import { initPlatform, resetPlatformForTests } from './platform'
import { fakePlatform } from './platform-fake'
const run = promisify(execFile)
+/** The one secret. Every token in this file is derived from it by `nodeAuthToken` — the same
+ * function the server verifies with, so a second derivation cannot hide here. */
+const SECRET = randomBytes(32)
+
let dir = ''
let launcher = ''
let binDir = ''
@@ -52,7 +63,7 @@ beforeAll(async () => {
// `true` stands in for `codex app-server daemon start`; the "no app-server" case overrides it.
fs.writeFileSync(launcher, buildCodexLauncherScript('true'), { mode: 0o755 })
await hookServer.start()
- hookServer.setCodexNodeAuthSecret(randomBytes(32))
+ hookServer.setNodeAuthSecret(SECRET)
hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd }) => {
started.push({ nodeId, cwd })
if (startDelayMs) await new Promise((r) => setTimeout(r, startDelayMs))
@@ -71,6 +82,8 @@ beforeAll(async () => {
afterAll(() => {
hookServer.stop()
+ hookServer.clearNodeAuthSecretForTests()
+ resetNodeTokenFilesForTests()
resetPlatformForTests()
fs.rmSync(dir, { recursive: true, force: true })
})
@@ -83,8 +96,19 @@ beforeEach(() => {
startDelayMs = 0
bindAnswer = () => {}
fs.writeFileSync(argvLog, '')
+ // The capability arrives through the FILE channel now (0600 under nodeTokenDir(), advertised as
+ // NODETERM_NODE_TOKEN_DIR in the endpoint file) — never through the tmux argv. Re-materialised
+ // per test because several cases below deliberately poison or remove it.
+ fs.rmSync(nodeTokenDir(), { recursive: true, force: true })
+ writeNodeTokenFile('node-1', nodeAuthToken(SECRET, 'node-1'))
})
+/**
+ * NOTE what is NOT here: `NODETERM_CODEX_NODE_TOKEN`. `buildPtyEnv` stopped emitting it (it rode
+ * the world-readable tmux `-e` argv), so the launcher's real environment has no per-node credential
+ * in it at all — it reads the token file. A test that kept injecting the var would prove the file
+ * channel works only by accident.
+ */
function baseEnv(): Record<string, string> {
return {
PATH: `${binDir}:${process.env.PATH ?? ''}`,
@@ -95,8 +119,7 @@ function baseEnv(): Record<string, string> {
// live coordinates after an app restart), but their presence is why a node whose endpoint file
// vanished can still report that it fell back.
NODETERM_HOOK_PORT: String(hookServer.getPort()),
- NODETERM_HOOK_TOKEN: hookServer.getToken(),
- NODETERM_CODEX_NODE_TOKEN: hookServer.codexNodeAuthToken('node-1')
+ NODETERM_HOOK_TOKEN: hookServer.getToken()
}
}
@@ -157,11 +180,6 @@ describe('falls back to plain codex', () => {
'hook endpoint points at nothing (app restarted, tmux session outlived it)',
{ NODETERM_HOOK_ENDPOINT: '/nonexistent/hook-endpoint.env' },
'hook-endpoint-unavailable'
- ],
- [
- 'no per-node capability token (secure storage unavailable)',
- { NODETERM_CODEX_NODE_TOKEN: '' },
- 'node-token-unavailable'
]
]
@@ -254,40 +272,142 @@ describe('a start handler that takes real time', () => {
}, 20_000)
})
+// The channel and the derivation both changed under this launcher: the token is `kid.mac` (one
+// shared derivation with /hook/*) and it arrives in a 0600 FILE, not in the tmux argv. Between the
+// two changes the feature was INERT — the launcher read an env var nothing set any more, reported
+// `node-token-unavailable` and ran plain codex. These are the tests that say it is not.
+describe('the per-node capability, over the file channel', () => {
+ it('accepts the kid.mac wire shape — the dot is part of the token, not a charset violation', async () => {
+ // THE TRAP. The old gate was `*[!A-Za-z0-9_-]*`, minted from HMAC(secret, nodeId) with no
+ // separator in it. The shared derivation puts a `.` between kid and mac, so that gate rejects
+ // EVERY current token and degrades every codex node silently.
+ const token = nodeAuthToken(SECRET, 'node-1')
+ expect(token).toContain('.')
+ expect(fs.readFileSync(path.join(nodeTokenDir(), 'node-1'), 'utf8').trim()).toBe(token)
+ await callLauncher([])
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])
+ expect(fallbacks).toEqual([])
+ expect(codexArgv()).toEqual(['--remote unix:// resume thread-abc'])
+ })
+
+ it('reads the token from the FILE with the env channel gone entirely', async () => {
+ expect(baseEnv().NODETERM_CODEX_NODE_TOKEN).toBeUndefined()
+ await callLauncher(['resume', 'thread-xyz'])
+ expect(bound).toEqual([{ nodeId: 'node-1', threadId: 'thread-xyz' }])
+ expect(fallbacks).toEqual([])
+ })
+
+ it('prefers the FILE over a stale env var left over from a pre-upgrade session', async () => {
+ // Charset-valid but wrong. If the env var won, the route would 403 and the node would degrade.
+ await callLauncher([], { NODETERM_CODEX_NODE_TOKEN: nodeAuthToken(SECRET, 'node-2') })
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])
+ expect(fallbacks).toEqual([])
+ })
+
+ it('still honors the env var for one release, when no file was materialised', async () => {
+ // A session spawned by the previous build carries the var and has no token file yet.
+ sweepNodeTokenFile('node-1')
+ fs.rmSync(path.join(nodeTokenDir(), 'node-1'), { force: true })
+ await callLauncher([], { NODETERM_CODEX_NODE_TOKEN: nodeAuthToken(SECRET, 'node-1') })
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir) }])
+ expect(fallbacks).toEqual([])
+ })
+
+ it('a missing token file and no env var → node-token-unavailable → plain codex', async () => {
+ fs.rmSync(path.join(nodeTokenDir(), 'node-1'), { force: true })
+ await callLauncher(['--ask-for-approval', 'never', 'do the thing'])
+ expect(codexArgv()).toEqual(['--ask-for-approval never do the thing'])
+ expect(started).toEqual([])
+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'node-token-unavailable' }])
+ })
+
+ it('a token path that cannot be read as a file → the same degrade, never a crash', async () => {
+ // A directory where the token should be: `head` fails, and the launcher must treat that the
+ // way it treats every other unavailable identity — plain codex with the arguments intact.
+ const file = path.join(nodeTokenDir(), 'node-1')
+ fs.rmSync(file, { force: true })
+ fs.mkdirSync(file)
+ try {
+ await callLauncher(['hello'])
+ expect(codexArgv()).toEqual(['hello'])
+ expect(started).toEqual([])
+ expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'node-token-unavailable' }])
+ } finally {
+ fs.rmSync(file, { recursive: true, force: true })
+ }
+ })
+})
+
describe('per-node capability (the authorization the shared bearer cannot give)', () => {
+ const post = (verb: string, body: string, headers: Record<string, string>) =>
+ fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/${verb}`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'x-nodeterm-hook-token': hookServer.getToken(),
+ ...headers
+ },
+ body
+ })
+
+ it('binding node-1 with node-2\'s token is 403 — judged by the SHARED verifier', async () => {
+ const res = await post('bind', 'nodeId=node-1&threadId=thread-xyz', {
+ 'x-nodeterm-node-token': nodeAuthToken(SECRET, 'node-2')
+ })
+ expect(res.status).toBe(403)
+ expect(bound).toEqual([])
+ })
+
+ it('our own kid with a mutated mac is 403 on start as well as bind', async () => {
+ const good = nodeAuthToken(SECRET, 'node-1')
+ const mac = good.slice(good.indexOf('.') + 1)
+ const mutated = `${nodeAuthKid(SECRET)}.${mac.slice(0, -1)}${mac.endsWith('A') ? 'B' : 'A'}`
+ expect(mutated).not.toBe(good)
+ expect((await post('bind', 'nodeId=node-1&threadId=thread-xyz', {
+ 'x-nodeterm-node-token': mutated
+ })).status).toBe(403)
+ expect((await post('start', `nodeId=node-1&cwd=${encodeURIComponent(dir)}`, {
+ 'x-nodeterm-node-token': mutated
+ })).status).toBe(403)
+ expect(bound).toEqual([])
+ expect(started).toEqual([])
+ })
+
+ it('start and bind stay STRICT: a tokenless caller is refused, unlike /hook/*', async () => {
+ // These routes were strict from day one and have no upgrade population to protect — a
+ // pre-#167 session has no launcher that calls them at all — so `legacy` is a 403 here.
+ expect((await post('start', `nodeId=node-1&cwd=${encodeURIComponent(dir)}`, {})).status).toBe(403)
+ expect((await post('bind', 'nodeId=node-1&threadId=thread-xyz', {})).status).toBe(403)
+ expect(started).toEqual([])
+ expect(bound).toEqual([])
+ })
+
it('the fallback report is trusted only when it presents no token at all', async () => {
// The one route the capability is not required on — because the commonest thing it reports is
// that there was no capability to present. The exemption is exactly that narrow: a report that
// DOES carry a token must carry the right one, or a session holding only the shared bearer
// could flag a sibling node as fallen back.
- const post = (nodeId: string, headers: Record<string, string>) =>
- fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/fallback`, {
- method: 'POST',
- headers: {
- 'content-type': 'application/x-www-form-urlencoded',
- 'x-nodeterm-hook-token': hookServer.getToken(),
- ...headers
- },
- body: `nodeId=${nodeId}&reason=broker-unreachable`
- })
- expect((await post('node-1', {})).status).toBe(204)
+ const report = (nodeId: string, headers: Record<string, string>) =>
+ post('fallback', `nodeId=${nodeId}&reason=broker-unreachable`, headers)
+ expect((await report('node-1', {})).status).toBe(204)
expect(fallbacks).toEqual([{ nodeId: 'node-1', reason: 'broker-unreachable' }])
- const wrong = await post('node-1', {
- 'x-nodeterm-node-token': hookServer.codexNodeAuthToken('node-2')
+ const wrong = await report('node-1', {
+ 'x-nodeterm-node-token': nodeAuthToken(SECRET, 'node-2')
})
expect(wrong.status).toBe(403)
expect(fallbacks).toHaveLength(1)
- const right = await post('node-1', {
- 'x-nodeterm-node-token': hookServer.codexNodeAuthToken('node-1')
+ const right = await report('node-1', {
+ 'x-nodeterm-node-token': nodeAuthToken(SECRET, 'node-1')
})
expect(right.status).toBe(204)
expect(fallbacks).toHaveLength(2)
})
it("refuses a token minted for a SIBLING node, and falls back rather than binding it", async () => {
- await callLauncher(['resume', 'thread-xyz'], {
- NODETERM_CODEX_NODE_TOKEN: hookServer.codexNodeAuthToken('node-2')
- })
+ // The hijack shape the file channel has to survive: node-1's own token FILE holding a token
+ // minted for node-2 (a case-folding collision on APFS, a hand-edited file).
+ writeNodeTokenFile('node-1', nodeAuthToken(SECRET, 'node-2'))
+ await callLauncher(['resume', 'thread-xyz'])
// The route rejected it before the handler ran: no binding was recorded for node-1.
expect(bound).toEqual([])
expect(codexArgv()).toEqual(['resume thread-xyz'])
diff --git a/src/main/codex-node-auth-secret.test.ts b/src/main/codex-node-auth-secret.test.ts
deleted file mode 100644
index de3a28cf4..000000000
--- a/src/main/codex-node-auth-secret.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { promises as fs } from 'fs'
-import os from 'os'
-import path from 'path'
-
-let userData = ''
-let encryptionAvailable = true
-const flip = (value: Buffer) => Buffer.from(value.map((byte) => byte ^ 0xff))
-
-vi.mock('electron', () => ({
- app: { getPath: () => userData },
- safeStorage: {
- isEncryptionAvailable: () => encryptionAvailable,
- encryptString: (value: string) => flip(Buffer.from(value, 'utf8')),
- decryptString: (value: Buffer) => flip(value).toString('utf8')
- }
-}))
-
-import { loadOrCreateCodexNodeAuthSecret, resetCodexNodeAuthSecretForTests } from './codex-node-auth-secret'
-
-const file = () => path.join(userData, 'codex-node-auth-key.json')
-
-describe('Codex node-auth secret', () => {
- beforeEach(async () => {
- userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-codex-node-auth-'))
- encryptionAvailable = true
- resetCodexNodeAuthSecretForTests()
- })
-
- afterEach(async () => {
- await fs.rm(userData, { recursive: true, force: true })
- })
-
- it('persists only keychain ciphertext and restores the same secret after restart', async () => {
- const first = await loadOrCreateCodexNodeAuthSecret()
- const stored = JSON.parse(await fs.readFile(file(), 'utf8')) as Record<string, unknown>
- expect(first).toHaveLength(32)
- expect(stored).toEqual({ version: 1, secretKeyEnc: expect.any(String) })
- expect(JSON.stringify(stored)).not.toContain(first.toString('base64'))
- expect((await fs.stat(file())).mode & 0o777).toBe(0o600)
- resetCodexNodeAuthSecretForTests()
- expect(await loadOrCreateCodexNodeAuthSecret()).toEqual(first)
- })
-
- it('fails closed without an OS keychain and writes no plaintext fallback', async () => {
- encryptionAvailable = false
- await expect(loadOrCreateCodexNodeAuthSecret()).rejects.toThrow('OS keychain is unavailable')
- await expect(fs.access(file())).rejects.toThrow()
- })
-
- it('fails closed on malformed persisted state instead of rotating ownership', async () => {
- await fs.writeFile(file(), '{"version":1,"secretKeyEnc":"broken"}\n', {
- mode: 0o600
- })
- await expect(loadOrCreateCodexNodeAuthSecret()).rejects.toThrow()
- expect(await fs.readFile(file(), 'utf8')).toBe('{"version":1,"secretKeyEnc":"broken"}\n')
- })
-})
diff --git a/src/main/codex-node-auth-secret.ts b/src/main/codex-node-auth-secret.ts
deleted file mode 100644
index 62639854b..000000000
--- a/src/main/codex-node-auth-secret.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { randomBytes } from 'crypto'
-import { promises as fs } from 'fs'
-import path from 'path'
-import { app, safeStorage } from 'electron'
-
-type StoredSecret = { version: 1; secretKeyEnc: string }
-
-let cached: Promise<Buffer> | null = null
-let cachedFile = ''
-
-function secretFile(): string {
- return path.join(app.getPath('userData'), 'codex-node-auth-key.json')
-}
-
-function decode(raw: string): Buffer {
- if (!safeStorage.isEncryptionAvailable()) {
- throw new Error('OS keychain is unavailable')
- }
- let stored: StoredSecret
- try {
- stored = JSON.parse(raw) as StoredSecret
- } catch {
- throw new Error('Codex node-auth key is malformed')
- }
- if (stored?.version !== 1 || typeof stored.secretKeyEnc !== 'string') {
- throw new Error('Codex node-auth key is malformed')
- }
- const secret = Buffer.from(safeStorage.decryptString(Buffer.from(stored.secretKeyEnc, 'base64')), 'base64')
- if (secret.byteLength !== 32) throw new Error('Codex node-auth key is invalid')
- return secret
-}
-
-async function persist(file: string, secret: Buffer): Promise<void> {
- if (!safeStorage.isEncryptionAvailable()) throw new Error('OS keychain is unavailable')
- const body: StoredSecret = {
- version: 1,
- secretKeyEnc: safeStorage.encryptString(secret.toString('base64')).toString('base64')
- }
- const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
- await fs.mkdir(path.dirname(file), { recursive: true })
- try {
- await fs.writeFile(tmp, `${JSON.stringify(body)}\n`, {
- encoding: 'utf8',
- mode: 0o600,
- flag: 'wx'
- })
- await fs.rename(tmp, file)
- await fs.chmod(file, 0o600)
- } finally {
- await fs.unlink(tmp).catch(() => {})
- }
-}
-
-async function load(file: string): Promise<Buffer> {
- try {
- return decode(await fs.readFile(file, 'utf8'))
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
- }
- const secret = randomBytes(32)
- await persist(file, secret)
- return secret
-}
-
-/** Restart-stable node-capability key. Ciphertext only at rest; no plaintext fallback. */
-export function loadOrCreateCodexNodeAuthSecret(): Promise<Buffer> {
- const file = secretFile()
- if (cached && cachedFile === file) return cached
- const pending = load(file)
- cached = pending
- cachedFile = file
- pending.catch(() => {
- if (cached === pending) {
- cached = null
- cachedFile = ''
- }
- })
- return pending
-}
-
-export function resetCodexNodeAuthSecretForTests(): void {
- cached = null
- cachedFile = ''
-}
diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.ts
index 8e3051f1a..625670022 100644
--- a/src/server/handlers/index.ts
+++ b/src/server/handlers/index.ts
@@ -74,16 +74,15 @@ export function registerCoreHandlers(
// The Server Edition answers "no shared identity", so every Codex node here launches the bare
// `codex` it always did — a working node with its own app-server, just without the shared one.
//
- // The blocker is the secret, not the plumbing: the per-node capability that closes the identity
- // routes' authorization hole is keychain-backed on the desktop (Electron `safeStorage`, see
- // src/main/codex-node-auth-secret.ts) and there is no equivalent on a headless Linux host. The
- // only way to arm this here is a secret at rest in the data dir, which is a security decision
- // this slice is not entitled to make quietly. Wiring it up is exactly three calls at this spot —
- // `hookServer.setCodexNodeAuthSecret(secret)`, `setCodexThreadIdentityAuthSecret(secret)`,
- // `refreshCodexIdentityCaps()` — plus the same two `setCodexThread*Handler` registrations
- // src/main/index.ts makes; everything they call already lives in src/core and boots from
- // CorePlatform. Until that secret question is answered, saying "no" here is what keeps the
- // browser's Codex nodes identical to what they are today rather than half-armed.
+ // The secret question that used to block this is ANSWERED: src/server/index.ts arms
+ // `hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())` at boot, which on a headless
+ // host is raw 0600 bytes in the data dir — a decision taken explicitly, not quietly (see
+ // src/core/agents/node-auth-secret.ts). What is still missing is only the codex-specific
+ // plumbing: `setCodexThreadIdentityAuthSecret(secret)`, `refreshCodexIdentityCaps()`, and the two
+ // `setCodexThread*Handler` registrations src/main/index.ts makes. Everything they call already
+ // lives in src/core and boots from CorePlatform, so this stays a scope line, not a blocker —
+ // until it is drawn differently, saying "no" here keeps the browser's Codex nodes identical to
+ // what they are today rather than half-armed.
registerCodexIdentityIpc(() => UNKNOWN_CODEX_IDENTITY_CAPS)
// Claude subscription usage. Previously desktop-only — the browser bridge answered `null`, so