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.

feat(codex): thread the account scope through the launcher and hook routes, fail-closed

Claude Codeb84628f03ae3
diff --git a/docs/shared-codex-node-identity.md b/docs/shared-codex-node-identity.md
new file mode 100644
index 000000000..a793da318
--- /dev/null
+++ b/docs/shared-codex-node-identity.md
@@ -0,0 +1,102 @@
+# Shared Codex node identity — the account-scoped ownership spine
+
+A Codex canvas node talks to **one shared `codex app-server`** and owns **one thread** inside it.
+The node↔thread mapping is what survives resumes, in-pane restarts, and app restarts. S6 adds the
+**account** dimension: the same machine can hold the system login (`~/.codex`) alongside several
+managed logins, and a thread's ownership record must name **which account** it belongs to, not just
+which node — so one account can never be made to speak for another's threads.
+
+This document covers the ownership spine shipped in S6 PR 2. The account **model** and on-disk home
+layout are PR 1 (`codex-accounts-core.ts`); the spawn wiring, relay, and switch/transfer protocol
+are later PRs. This slice **ships inert** — nothing sets `NODETERM_CODEX_ACCOUNT_ID` on a pane yet —
+but it is fully tested against real primitives (real `/bin/sh`, real fs, real HMAC).
+
+## The signing secret (both shells — Decision 1)
+
+Every ownership record is HMAC-signed by the **one** restart-stable 32-byte node-auth secret
+(`src/core/agents/node-auth-secret.ts`, `loadOrCreateNodeAuthSecret`). That secret already arms on
+**both** shells and this proxy reuses it as-is:
+
+- **Desktop:** sealed at rest via `safeStorage` → `node-auth-key.json` (ciphertext only, mode
+ `0600`; no raw-secret fallback ever written).
+- **Server Edition (no keychain):** 32 raw bytes at `node-auth-key.bin`, mode `0600`.
+
+It is **confidential and fail-closed**: a malformed/wrong-length persisted state **throws** rather
+than minting a fresh secret — rotating the key would orphan every bound thread on the machine — and
+the single-flight cache clears on rejection so a healed machine retries. It is wired at boot in both
+`src/main/index.ts` and `src/server/index.ts` via `setCodexThreadIdentityAuthSecret(...)`.
+
+> No `safeStorage`-only secret module is introduced. @Corvin's `codex-node-auth-secret.ts` in
+> PR #112 is `safeStorage`-ciphertext-only and throws on a headless server; the merged both-shells
+> channel above is the correct mirror, and duplicating it as a keychain-only file would regress the
+> Server Edition. This is the ratified Decision 1.
+
+## The ownership records
+
+`~/.nodeterm/codex-thread-nodes/` (under `CorePlatform.userDataDir`, **not** `~`):
+
+- **System account** → the bare-root file `<root>/<threadId>` — the exact S4 layout, so a machine
+ with no managed accounts is byte-for-byte unchanged and its legacy records keep resolving.
+- **Managed account** → `<root>/<accountId>/<threadId>`.
+
+Each record is a flat `key=value` text file, mode `0600`, **parsed as data, never sourced**:
+
+```
+accountId=<id or empty for system>
+nodeId=<owning canvas node>
+endpoint=<hook endpoint file path>
+signature=<base64url HMAC>
+```
+
+### The signature binds the full 4-tuple
+
+```
+signature = base64url( HMAC-SHA256( key, threadId ␀ accountScope ␀ nodeId ␀ hookEndpoint ) )
+```
+
+`accountScope` is the account id, or the literal `system` for the system account (empty id
+normalised). Because the scope is inside the preimage, a record signed for account **A** verifies
+only under scope **A** — copying it byte-for-byte into account **B**'s directory fails the MAC.
+Verification is `timingSafeEqual`. Records written before this slice carry **no** `accountId=` line
+and are verified with the original 3-tuple preimage **at the system scope only** — the one
+back-compat door, and it is a system-scope door (a scope-less signature is never honoured under a
+managed account).
+
+## Fail-closed ambiguity (the house rule, reused)
+
+Ownership resolution reuses the merged fail-closed posture (`pane-ownership.ts`,
+`node-identity-policy.ts`): **an owner that cannot be proven is denied.**
+
+- `resolveCodexThreadNodeIdentity(threadId)` with no account hint (the shared tool shell that knows
+ only a bare thread id) scans **every** scope and returns an owner **only when `owners.size === 1`**.
+ The same thread id owned by two different accounts resolves to **nothing**.
+- `resolveCodexThreadNodeIdentity(threadId, root, accountId)` with an explicit account resolves
+ within that one scope.
+- `codexThreadIdentityHasLiveConflict(...)` reports a conflict only when **two different live
+ nodes** own the thread across scopes.
+
+## The POSIX-sh resolver
+
+`codexThreadIdentityResolverSh(root)` is prepended to every managed hook script. A shared-app-server
+tool shell inherits `CODEX_THREAD_ID` but not the pane's `NODETERM_*` (see probe U5,
+`docs/superpowers/probes/2026-08-codex-tool-shell-env.md`), so this prelude recovers the binding:
+
+- reads `NODETERM_CODEX_ACCOUNT_ID` from the daemon env to pick the scope;
+- a known safe account id ⇒ reads **only** that account's record, and requires the record's
+ `accountId=` line to **agree with the daemon scope**;
+- an **empty** account id ⇒ scans every scope (bare-root system + each managed subdir) and binds
+ **only when exactly one candidate matches** (`nt_codex_matches -eq 1`) — two accounts holding the
+ same thread id change nothing;
+- it cannot verify the HMAC (no key in an agent's shell), so it re-validates every recovered field's
+ charset and the account-line/scope agreement before exporting. Its behaviour is proven under real
+ `/bin/sh` against a real on-disk scope tree in `codex-thread-identity-sh.test.ts`.
+
+## Supply-chain guard
+
+Account ids arrive from hand-editable `settings.json` / `project.json`. Every id passes
+`ACCOUNT_ID_RE` (`^[A-Za-z0-9][A-Za-z0-9._-]*$`, must start alphanumeric) — via `accountScope()` in
+the proxy, the launcher's own sh check, and the hook-server route — **before** it becomes a
+directory scope, so `.`/`..`/leading-separator/`a/b`/absolute ids are refused at the door. The
+launcher threads the account id through the `/codex-thread/{start,bind}` POST **body**, never on
+argv (Constraint 6); a bad id falls back to plain `codex` rather than binding under a hostile scope,
+and the server refuses it at `400` before the start handler can create an orphan thread.
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 373c04a62..8212ae958 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -10,6 +10,7 @@ import type { NodeTokenVerdict } from './node-auth-token'
import { nodeTokenDir } from './node-token-files'
import { isForeignKidToken, isSafeNodeId, verifyNodeToken } from './node-auth-token'
import { isSafeThreadId } from '../codex-identity-proxy'
+import { isSafeAccountId } from '../../shared/codex-account'
import {
controlPolicy,
CONTEXT_LINK_POLICY_VERB,
@@ -245,10 +246,20 @@ class HookServer {
* `nodeTokenVerified`.
*/
private codexThreadStartHandler:
- | ((req: { nodeId: string; cwd: string; hookEndpoint: string }) => Promise<string>)
+ | ((req: {
+ nodeId: string
+ cwd: string
+ hookEndpoint: string
+ accountId?: string
+ }) => Promise<string>)
| null = null
private codexThreadBindHandler:
- | ((req: { nodeId: string; threadId: string; hookEndpoint: string }) => Promise<void>)
+ | ((req: {
+ nodeId: string
+ threadId: string
+ hookEndpoint: string
+ accountId?: string
+ }) => Promise<void>)
| null = null
private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = null
private endpointPath = ''
@@ -828,6 +839,17 @@ class HookServer {
res.end()
return
}
+ // The account scope for this thread's ownership record (S6). Absent ⇒ system account. A
+ // non-empty id that is not a safe account id is refused BEFORE it reaches the record store,
+ // where it would become a directory component (Supply-chain guard, Constraint 7). Both routes
+ // share the same normalisation so a managed thread is never mis-filed under `system`.
+ const rawAccountId = form.accountId ?? ''
+ if (rawAccountId !== '' && !isSafeAccountId(rawAccountId)) {
+ res.writeHead(400)
+ res.end()
+ return
+ }
+ const accountId = rawAccountId || undefined
if (verb === 'start') {
const cwd = form.cwd ?? ''
if (!path.isAbsolute(cwd)) {
@@ -840,7 +862,8 @@ class HookServer {
const threadId = await this.codexThreadStartHandler({
nodeId,
cwd,
- hookEndpoint: this.endpointFilePath()
+ hookEndpoint: this.endpointFilePath(),
+ accountId
})
// Same predicate the record store gates on, so a thread id the store would refuse can
// never be handed back to a launcher that will then `resume` it.
@@ -868,7 +891,8 @@ class HookServer {
await this.codexThreadBindHandler({
nodeId,
threadId,
- hookEndpoint: this.endpointFilePath()
+ hookEndpoint: this.endpointFilePath(),
+ accountId
})
this.codexIdentityListener?.({ nodeId, mode: 'shared' })
res.writeHead(204)
diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.ts
index 684c6870e..11a17c3da 100644
--- a/src/core/codex-launcher-sh.test.ts
+++ b/src/core/codex-launcher-sh.test.ts
@@ -8,6 +8,7 @@
// remote-claude-usage.test.ts.
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'
import { execFile } from 'node:child_process'
+import { request as httpRequest } from 'node:http'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
@@ -35,8 +36,8 @@ let dir = ''
let launcher = ''
let binDir = ''
let argvLog = ''
-let started: Array<{ nodeId: string; cwd: string }> = []
-let bound: Array<{ nodeId: string; threadId: string }> = []
+let started: Array<{ nodeId: string; cwd: string; accountId?: string }> = []
+let bound: Array<{ nodeId: string; threadId: string; accountId?: string }> = []
let fallbacks: Array<{ nodeId: string; reason?: string }> = []
let startAnswer: (() => string) | null = null
let startDelayMs = 0
@@ -64,14 +65,14 @@ beforeAll(async () => {
fs.writeFileSync(launcher, buildCodexLauncherScript('true'), { mode: 0o755 })
await hookServer.start()
hookServer.setNodeAuthSecret(SECRET)
- hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd }) => {
- started.push({ nodeId, cwd })
+ hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, accountId }) => {
+ started.push({ nodeId, cwd, accountId })
if (startDelayMs) await new Promise((r) => setTimeout(r, startDelayMs))
if (!startAnswer) throw new Error('start refused')
return startAnswer()
})
- hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId }) => {
- bound.push({ nodeId, threadId })
+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, accountId }) => {
+ bound.push({ nodeId, threadId, accountId })
if (!bindAnswer) throw new Error('bind refused')
bindAnswer()
})
@@ -138,6 +139,40 @@ function codexArgv(): string[] {
return fs.readFileSync(argvLog, 'utf8').split('\n').slice(0, -1)
}
+/**
+ * POST a codex-thread request DIRECTLY, bypassing the launcher's own account-id validation, to
+ * exercise the SERVER's gate. Both bearer headers are presented so the request is authenticated and
+ * only the account-id check can reject it.
+ */
+function postCodexThread(
+ verb: 'start' | 'bind',
+ fields: Record<string, string>
+): Promise<number> {
+ const body = new URLSearchParams(fields).toString()
+ return new Promise((resolve, reject) => {
+ const req = httpRequest(
+ {
+ host: '127.0.0.1',
+ port: hookServer.getPort(),
+ method: 'POST',
+ path: `/codex-thread/${verb}`,
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'content-length': Buffer.byteLength(body),
+ 'x-nodeterm-hook-token': hookServer.getToken(),
+ 'x-nodeterm-node-token': nodeAuthToken(SECRET, 'node-1')
+ }
+ },
+ (res) => {
+ res.resume()
+ res.on('end', () => resolve(res.statusCode ?? 0))
+ }
+ )
+ req.on('error', reject)
+ req.end(body)
+ })
+}
+
describe('generated Codex launcher', () => {
it('is valid POSIX sh', async () => {
await expect(run('/bin/sh', ['-n', launcher])).resolves.toBeTruthy()
@@ -163,6 +198,53 @@ describe('generated Codex launcher', () => {
expect(started).toEqual([])
expect(codexArgv()).toEqual(['--remote unix:// resume thread-xyz'])
})
+
+ // S6: the account scope travels in the POST body, never on argv (Constraint 6), so the record is
+ // filed under the right account. An empty id (the system account) reaches the handler as undefined.
+ it('threads the managed account id through start (in the body, not on argv)', async () => {
+ await callLauncher([], { NODETERM_CODEX_ACCOUNT_ID: 'acct-A' })
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir), accountId: 'acct-A' }])
+ // The account id is NOT on the codex command line.
+ expect(codexArgv().join(' ')).not.toContain('acct-A')
+ })
+
+ it('threads the managed account id through a resume bind too', async () => {
+ await callLauncher(['resume', 'thread-xyz'], { NODETERM_CODEX_ACCOUNT_ID: 'acct-A' })
+ expect(bound).toEqual([{ nodeId: 'node-1', threadId: 'thread-xyz', accountId: 'acct-A' }])
+ expect(codexArgv().join(' ')).not.toContain('acct-A')
+ })
+
+ it('an account id that could escape the mapping directory → plain codex, never an unbound bind', async () => {
+ await callLauncher(['do', 'work'], { NODETERM_CODEX_ACCOUNT_ID: '../evil' })
+ // No thread was started or bound under the hostile scope; codex ran plain with the args intact.
+ expect(started).toEqual([])
+ expect(bound).toEqual([])
+ expect(codexArgv()).toEqual(['do work'])
+ expect(fallbacks.map((f) => f.reason)).toContain('codex-account-invalid')
+ })
+
+ // The SERVER's own gate, independent of the launcher: a hostile account id posted directly is
+ // refused at 400 BEFORE the start handler runs — so `startCodexThread` never creates a thread the
+ // record write would then orphan. (Mutation: drop the isSafeAccountId gate ⇒ 200 + a started row.)
+ it('the server refuses a hostile account id at 400 before starting a thread', async () => {
+ const status = await postCodexThread('start', {
+ nodeId: 'node-1',
+ cwd: fs.realpathSync(dir),
+ accountId: '../evil'
+ })
+ expect(status).toBe(400)
+ expect(started).toEqual([]) // the handler never ran ⇒ no orphaned thread
+ })
+
+ it('the server accepts a safe managed account id on a direct post', async () => {
+ const status = await postCodexThread('start', {
+ nodeId: 'node-1',
+ cwd: fs.realpathSync(dir),
+ accountId: 'acct-A'
+ })
+ expect(status).toBe(200)
+ expect(started).toEqual([{ nodeId: 'node-1', cwd: fs.realpathSync(dir), accountId: 'acct-A' }])
+ })
})
// Each case below is a way the managed identity can be unavailable on a real machine. The
diff --git a/src/main/index.ts b/src/main/index.ts
index 8694d9251..816a98e1f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1307,12 +1307,12 @@ app.whenReady().then(async () => {
// workspace that no longer holds it) is free to be re-claimed; one whose owner is still there is
// not, and the launcher then falls back rather than putting two clients on one conversation.
const codexNodeIsLive = (nodeId: string): boolean => !!workspaceStore.getNode(nodeId)
- hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, hookEndpoint }) => {
+ hookServer.setCodexThreadStartHandler(async ({ nodeId, cwd, hookEndpoint, accountId }) => {
const threadId = await startCodexThread(cwd)
- writeCodexThreadIdentity(threadId, nodeId, hookEndpoint)
+ writeCodexThreadIdentity(threadId, nodeId, hookEndpoint, undefined, accountId)
return threadId
})
- hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, hookEndpoint }) => {
+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId, hookEndpoint, accountId }) => {
// Ask the app-server whether this conversation exists BEFORE recording that a node owns it.
// The id reaching us is whatever the node persisted — it can be stale, or from a session that
// ran under plain codex and the shared server has never heard of. Binding it anyway writes a
@@ -1321,7 +1321,7 @@ app.whenReady().then(async () => {
if (!(await codexThreadExists(threadId))) {
throw new Error('Codex thread is unknown to the shared app-server')
}
- bindCodexThreadIdentity(threadId, nodeId, hookEndpoint, codexNodeIsLive)
+ bindCodexThreadIdentity(threadId, nodeId, hookEndpoint, codexNodeIsLive, undefined, accountId)
})
// SSH_ASKPASS relay (ssh-project.ts): lets the ControlMaster, which has no tty, route a
// passphrase-protected identity file's prompt back through the app instead of failing auth.