Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(security): refuse path-unsafe codex thread ids before they reach a path
Claude Code37235fc7da92
diff --git a/src/core/agents/codex-thread-id-route.test.ts b/src/core/agents/codex-thread-id-route.test.tsnew file mode 100644index 000000000..65bedd247--- /dev/null+++ b/src/core/agents/codex-thread-id-route.test.ts@@ -0,0 +1,80 @@+// `/codex-thread/bind` takes a caller-supplied thread id and that id becomes a PATH SEGMENT under+// the record store (and a field inside the record signature). The route used to gate it with its+// own inline `/^[A-Za-z0-9._-]+$/` — a rule that accepts `.` and `..`, which is exactly the hole+// `isSafeNodeId` was written to close for node ids.+//+// The route now shares ONE predicate with the store (`isSafeThreadId`), so an id the store would+// refuse can never reach it through the route, and vice versa. These tests spin the real hook+// server and post real bodies; the handler is a spy, so "refused" means the handler never ran.+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { mkdtempSync, rmSync, existsSync, readdirSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { hookServer } from './hook-server'+import { nodeAuthToken } from './node-auth-token'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { codexThreadIdentityRoot } from '../codex-identity-proxy'++const SECRET = Buffer.alloc(32, 3)+const NODE = 'node-thread-route'++// The exact trap rows: `.` and `..` are path segments the charset accepts, `../x` and `a/b` carry a+// separator, empty is no segment at all, and 129 chars is over the bound.+const UNSAFE_THREAD_IDS = ['.', '..', '../x', 'a/b', '', 'x'.repeat(129)]++let dir = ''+let bound: { nodeId: string; threadId: string }[] = []++function bind(threadId: string): Promise<Response> {+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/codex-thread/bind`, {+ method: 'POST',+ headers: {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'X-Nodeterm-Node-Token': nodeAuthToken(SECRET, NODE),+ 'content-type': 'application/x-www-form-urlencoded'+ },+ body: `nodeId=${encodeURIComponent(NODE)}&threadId=${encodeURIComponent(threadId)}`+ })+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'codex-thread-route-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setNodeAuthSecret(SECRET)+ hookServer.setCodexThreadBindHandler(async ({ nodeId, threadId }) => {+ bound.push({ nodeId, threadId })+ })+})++afterAll(() => {+ hookServer.clearNodeAuthSecretForTests()+ hookServer.stop()+ resetPlatformForTests()+ rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ bound = []+})++describe('/codex-thread/bind refuses a path-unsafe thread id', () => {+ it('400s every trap row, never calls the handler, and writes no record', async () => {+ for (const threadId of UNSAFE_THREAD_IDS) {+ const res = await bind(threadId)+ expect(res.status, JSON.stringify(threadId)).toBe(400)+ }+ expect(bound).toEqual([])+ // Nothing anywhere: not in the store, and — the `..` row — not in the store's parent either.+ expect(existsSync(codexThreadIdentityRoot())).toBe(false)+ expect(readdirSync(dir)).toEqual(['hook-endpoint.env'])+ })++ it('still binds a thread id the app-server would actually mint', async () => {+ const res = await bind('0199b4b7-8d4e-7a4e-9a2f-3c9d0f1a2b3c')+ expect(res.status).toBe(204)+ expect(bound).toEqual([{ nodeId: NODE, threadId: '0199b4b7-8d4e-7a4e-9a2f-3c9d0f1a2b3c' }])+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex b7b4b6698..0209045e6 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -8,6 +8,7 @@ import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/norimport type { CodexIdentityEvent } from '../../shared/types'import { nodeTokenDir } from './node-token-files'import { isSafeNodeId, verifyNodeToken } from './node-auth-token'+import { isSafeThreadId } from '../codex-identity-proxy'// 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@@ -528,7 +529,9 @@ class HookServer {cwd,hookEndpoint: this.endpointFilePath()})- if (!/^[A-Za-z0-9._-]+$/.test(threadId)) throw new Error('invalid thread id')+ // 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.+ if (!isSafeThreadId(threadId)) throw new Error('invalid thread id')this.codexIdentityListener?.({ nodeId, mode: 'shared' })res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })res.end(`${threadId}\n`)@@ -539,7 +542,10 @@ class HookServer {return}const threadId = form.threadId ?? ''- if (!/^[A-Za-z0-9._-]+$/.test(threadId)) {+ // `isSafeThreadId`, not a local regex — the twin of the `isSafeNodeId` gate above and for the+ // same reason. This id is caller-supplied and becomes a PATH SEGMENT under the record store;+ // the bare charset the route used to carry accepts `.` and `..`.+ if (!isSafeThreadId(threadId)) {res.writeHead(400)res.end()returndiff --git a/src/core/codex-identity-proxy.test.ts b/src/core/codex-identity-proxy.test.tsindex 87e72dba4..b653b2fb4 100644--- a/src/core/codex-identity-proxy.test.ts+++ b/src/core/codex-identity-proxy.test.ts@@ -9,6 +9,7 @@ import {forgetCodexThreadIdentitiesForNode,codexThreadIdentityRoot,installCodexLauncher,+ isSafeThreadId,readCodexThreadIdentity,resetCodexThreadIdentityAuthSecret,resolveCodexThreadNodeIdentity,@@ -44,6 +45,54 @@ afterEach(() => {fs.rmSync(dir, { recursive: true, force: true })})+// A thread id is a PATH SEGMENT under `codexThreadIdentityRoot()` and a field inside the record+// signature. The charset alone never made it safe: `.` and `..` both match `[A-Za-z0-9._-]+`, and+// `..` as a path segment resolves to the record dir's PARENT. This is the same hole `isSafeNodeId`+// closed for node ids; these rows are the trap.+const UNSAFE_THREAD_IDS = ['.', '..', '../x', 'a/b', '', 'x'.repeat(129)]++describe('isSafeThreadId', () => {+ it('refuses every id that could leave the record directory, be empty, or be unbounded', () => {+ for (const id of UNSAFE_THREAD_IDS) expect(isSafeThreadId(id), JSON.stringify(id)).toBe(false)+ })++ it('accepts the ids the app-server actually mints', () => {+ for (const id of ['thread-1', '0199b4b7-8d4e-7a4e-9a2f-3c9d0f1a2b3c', 'x'.repeat(128)]) {+ expect(isSafeThreadId(id), id).toBe(true)+ }+ })+})++describe('path-unsafe thread ids never reach a path or a hash', () => {+ it('refuses to write a record under one, and creates nothing', () => {+ for (const id of UNSAFE_THREAD_IDS) {+ expect(() =>+ writeCodexThreadIdentity(id, 'node-1', '/data/e', recordsRoot)+ ).toThrow()+ }+ // Not one stray file, and — the row that matters — no record dropped in the PARENT of the+ // store by a `..` segment.+ expect(fs.existsSync(recordsRoot)).toBe(false)+ expect(fs.readdirSync(dir)).toEqual([])+ })++ it('refuses to bind one, and creates nothing', () => {+ for (const id of UNSAFE_THREAD_IDS) {+ expect(() =>+ bindCodexThreadIdentity(id, 'node-1', '/data/e', live([]), recordsRoot)+ ).toThrow()+ }+ expect(fs.readdirSync(dir)).toEqual([])+ })++ it('reads nothing back for one', () => {+ for (const id of UNSAFE_THREAD_IDS) {+ expect(readCodexThreadIdentity(id, recordsRoot), JSON.stringify(id)).toBeUndefined()+ expect(resolveCodexThreadNodeIdentity(id, recordsRoot), JSON.stringify(id)).toBeUndefined()+ }+ })+})+describe('codex thread identity store', () => {it('lives under the platform data dir, not $HOME', () => {// The wrong seam is why the Server Edition had no story at all: `homedir()` is not where adiff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.tsindex d775d10dd..34ef36022 100644--- a/src/core/codex-identity-proxy.ts+++ b/src/core/codex-identity-proxy.ts@@ -49,7 +49,33 @@ const CODEX_THREAD_START_CLIENT_MAX_S = CODEX_THREAD_START_TIMEOUT_MS / 1000 + 1const SAFE_NODE_ID = /^[A-Za-z0-9._-]+$/const SAFE_ENDPOINT = /^\/[A-Za-z0-9._/ -]+$/-const SAFE_THREAD_ID = /^[A-Za-z0-9._-]+$/+const THREAD_ID_CHARSET = /^[A-Za-z0-9._-]+$/+const MAX_THREAD_ID = 128++/**+ * The one predicate for a thread id — the twin of `isSafeNodeId` (core/agents/node-auth-token.ts),+ * for the same reason and against the same trap.+ *+ * The charset alone is NOT enough: `.` and `..` both MATCH `THREAD_ID_CHARSET`, and a thread id is+ * a PATH SEGMENT under `codexThreadIdentityRoot()` (`<root>/<threadId>`, plus the `.<threadId>.…`+ * tmp file beside it) as well as a signed field in the record. A `..` there resolves to the record+ * dir's PARENT. The id is caller-supplied — it arrives on `/codex-thread/bind` as a form field and+ * from a node's persisted state — so refuse `.` and `..` by name, refuse empty, refuse+ * over-length, BEFORE the id ever reaches a path join or a hash.+ *+ * Exported and shared deliberately: the hook routes and `codex-session-name.ts` used to carry+ * their own copies of the bare charset, and two copies of a rule is how one of them stays wrong.+ */+export function isSafeThreadId(id: string): boolean {+ return (+ typeof id === 'string' &&+ id.length > 0 &&+ id.length <= MAX_THREAD_ID &&+ id !== '.' &&+ id !== '..' &&+ THREAD_ID_CHARSET.test(id)+ )+}let identityAuthSecret: Buffer | null = null@@ -108,7 +134,7 @@ export function validCodexIdentity(nodeId: string, hookEndpoint: string): boolea}function identityFile(threadId: string, root = codexThreadIdentityRoot()): string {- if (!SAFE_THREAD_ID.test(threadId)) throw new Error('Invalid NodeTerm Codex thread identity')+ if (!isSafeThreadId(threadId)) throw new Error('Invalid NodeTerm Codex thread identity')return path.join(root, threadId)}@@ -131,7 +157,7 @@ export function readCodexThreadIdentity(threadId: string,root = codexThreadIdentityRoot()): CodexThreadIdentity | undefined {- if (!SAFE_THREAD_ID.test(threadId)) return undefined+ if (!isSafeThreadId(threadId)) return undefinedlet raw: stringtry {raw = readFileSync(path.join(root, threadId), 'utf8')@@ -163,7 +189,7 @@ export function writeCodexThreadIdentity(hookEndpoint: string,root = codexThreadIdentityRoot()): void {- if (!SAFE_THREAD_ID.test(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {+ if (!isSafeThreadId(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {throw new Error('Invalid NodeTerm Codex thread identity')}const signature = identitySignature(threadId, nodeId, hookEndpoint)@@ -202,7 +228,7 @@ export function bindCodexThreadIdentity(isNodeLive: (nodeId: string) => boolean,root = codexThreadIdentityRoot()): void {- if (!SAFE_THREAD_ID.test(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {+ if (!isSafeThreadId(threadId) || !validCodexIdentity(nodeId, hookEndpoint)) {throw new Error('Invalid NodeTerm Codex thread identity')}const existing = readCodexThreadIdentity(threadId, root)@@ -236,7 +262,7 @@ export function forgetCodexThreadIdentitiesForNode(return}for (const threadId of entries) {- if (!SAFE_THREAD_ID.test(threadId)) continue+ if (!isSafeThreadId(threadId)) continue// Reads through the signature check, so a record we do not trust is also one we do not delete.if (readCodexThreadIdentity(threadId, root)?.nodeId !== nodeId) continuetry {diff --git a/src/core/codex-session-name.ts b/src/core/codex-session-name.tsindex 236a00c2c..de65584f8 100644--- a/src/core/codex-session-name.ts+++ b/src/core/codex-session-name.ts@@ -19,9 +19,12 @@ import { WebSocket } from 'ws'// Minting a thread is a multi-step conversation with a typically COLD server, so it needs a real// budget — and the hook route serving it must raise its socket guard to match (handleCodexThread).// Shared with the launcher's client budget so the two cannot drift apart.-import { CODEX_THREAD_START_TIMEOUT_MS } from './codex-identity-proxy'+// `isSafeThreadId` comes from the same module, and deliberately: this file used to keep its own+// copy of the bare charset, which accepted `.` and `..` — harmless over the RPC wire here, but the+// ids it validates (a thread the app-server just minted, one a node persisted) are handed straight+// to the record store, where they ARE path segments. One rule, so the two cannot drift apart.+import { CODEX_THREAD_START_TIMEOUT_MS, isSafeThreadId } from './codex-identity-proxy'-const SAFE_THREAD_ID = /^[A-Za-z0-9._-]+$//*** `codex app-server daemon start` exiting 0 does NOT mean its control socket is accepting* connections yet — the daemon binds a beat later. Everything here runs immediately after that@@ -110,7 +113,7 @@ export function readCodexSessionNameAt(threadId: string,timeoutMs = REQUEST_TIMEOUT_MS): Promise<string | null> {- if (!SAFE_THREAD_ID.test(threadId)) return Promise.resolve(null)+ if (!isSafeThreadId(threadId)) return Promise.resolve(null)return new Promise((resolve) => {let settled = falselet ws: WebSocket@@ -271,7 +274,7 @@ export async function codexThreadExistsAt(attempts = SOCKET_WAIT_ATTEMPTS,gapMs = SOCKET_WAIT_MS): Promise<boolean> {- if (!SAFE_THREAD_ID.test(threadId)) return false+ if (!isSafeThreadId(threadId)) return falsefor (let i = 0; i < attempts; i++) {const result = await probeCodexThread(socketPath, threadId, timeoutMs)if (result !== 'unreachable') return result === 'yes'@@ -403,7 +406,7 @@ function startCodexThreadOnce(if (message.error ||typeof startedThreadId !== 'string' ||- !SAFE_THREAD_ID.test(startedThreadId)+ !isSafeThreadId(startedThreadId)) {finish(new Error('Codex app-server returned no valid thread identity'))return@@ -412,7 +415,7 @@ function startCodexThreadOnce(ws.send(JSON.stringify({ id: 3, method: 'turn/start', params: { threadId, input: [] } }))} else if (message.id === 3) {const turnId = message.result?.turn?.id- if (message.error || typeof turnId !== 'string' || !SAFE_THREAD_ID.test(turnId)) {+ if (message.error || typeof turnId !== 'string' || !isSafeThreadId(turnId)) {finish(new Error('Codex app-server could not materialize the new thread'))return}@@ -451,7 +454,7 @@ function startCodexThreadOnce(if (message.error ||typeof readyThreadId !== 'string' ||- !SAFE_THREAD_ID.test(readyThreadId)+ !isSafeThreadId(readyThreadId)) {finish(new Error('Codex app-server could not clean up thread materialization'))return@@ -484,7 +487,7 @@ export function readCodexSessionName(threadId: string,socketPath = defaultCodexAppServerSocket()): Promise<string | null> {- if (!SAFE_THREAD_ID.test(threadId)) return Promise.resolve(null)+ if (!isSafeThreadId(threadId)) return Promise.resolve(null)const key = `${socketPath}\0${threadId}`const cached = names.get(key)if (cached && Date.now() - cached.at < CACHE_MS) return Promise.resolve(cached.name)diff --git a/src/core/codex-thread-identity-sh.ts b/src/core/codex-thread-identity-sh.tsindex ad3984ce6..a5e7d6f81 100644--- a/src/core/codex-thread-identity-sh.ts+++ b/src/core/codex-thread-identity-sh.ts@@ -31,7 +31,9 @@ export function codexThreadIdentityResolverSh(identityRoot: string): string {# NODETERM_* env. Recover this thread's exact node binding, or change nothing at all.if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; thencase "$CODEX_THREAD_ID" in- ''|*[!A-Za-z0-9._-]*) ;;+ # '.' and '..' MATCH the charset and are path segments: "$identityRoot"/.. is the record dir's+ # PARENT. Refused by name here for the same reason isSafeThreadId refuses them in TypeScript.+ ''|.|..|*[!A-Za-z0-9._-]*) ;;*)nt_codex_map=${posixQuote(identityRoot)}/"$CODEX_THREAD_ID"if [ -r "$nt_codex_map" ]; then