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(codex): remove stat-then-read fs races the relay daemon CodeQL flagged

Claude Code68112546591f
diff --git a/src/main/codex-relay-daemon.test.ts b/src/main/codex-relay-daemon.test.ts
index d143aefd2..51d930e98 100644
--- a/src/main/codex-relay-daemon.test.ts
+++ b/src/main/codex-relay-daemon.test.ts
@@ -2,10 +2,13 @@ import { describe, expect, it } from 'vitest'
import { createServer } from 'http'
import { spawnSync } from 'child_process'
import {
+ closeSync,
existsSync,
+ fstatSync,
linkSync,
mkdirSync,
mkdtempSync,
+ openSync,
readFileSync,
rmSync,
statSync,
@@ -709,8 +712,15 @@ describe('exposeForeignThread — PR 3 primitive + verify-then-recycle (§4.2a,
exposeForeignThread(targetSocket, threadId, [targetSocket, sourceSocket])
).rejects.toThrow('different rollout')
// The pre-existing target is byte- and inode-preserved: never overwritten, never rolled back.
- expect(statSync(targetRollout).ino).toBe(differentIno)
- expect(readFileSync(targetRollout, 'utf8')).toBe('a different conversation')
+ // One descriptor proves the inode AND the contents belong to the same file — no stat-then-read
+ // race on the target path.
+ const fd = openSync(targetRollout, 'r')
+ try {
+ expect(fstatSync(fd).ino).toBe(differentIno)
+ expect(readFileSync(fd, 'utf8')).toBe('a different conversation')
+ } finally {
+ closeSync(fd)
+ }
} finally {
await Promise.all([stopSource(), stopTarget()])
rmSync(root, { recursive: true, force: true })
@@ -826,12 +836,23 @@ describe('relay self-spawn + token transport (probe U6, GC 6 argv-spy)', () => {
// The node token is not echoed back into the relay's stdout.
expect(ok.stdout).not.toContain(token)
- // The control token lives only in the 0600 state file, and it is not the node token.
+ // The control token lives only in the 0600 state file, and it is not the node token. One
+ // descriptor proves the mode AND the contents belong to the same inode — no stat-then-read
+ // race on the state path.
const statePath = path.join(home, '.nodeterm', 'codex-relay-v6.json')
- const state = JSON.parse(readFileSync(statePath, 'utf8')) as { token: string; pid: number }
- expect((statSync(statePath).mode & 0o777).toString(8)).toBe('600')
+ const stateFd = openSync(statePath, 'r')
+ let raw: string
+ let mode: number
+ try {
+ mode = fstatSync(stateFd).mode & 0o777
+ raw = readFileSync(stateFd, 'utf8')
+ } finally {
+ closeSync(stateFd)
+ }
+ const state = JSON.parse(raw) as { token: string; pid: number }
+ expect(mode.toString(8)).toBe('600')
expect(state.token).not.toBe(token)
- expect(readFileSync(statePath, 'utf8')).not.toContain(token)
+ expect(raw).not.toContain(token)
// Tear down the detached serve child the round-trip spawned.
try {
diff --git a/src/main/codex-relay-daemon.ts b/src/main/codex-relay-daemon.ts
index 1b24aeecc..6b7aa0784 100644
--- a/src/main/codex-relay-daemon.ts
+++ b/src/main/codex-relay-daemon.ts
@@ -40,9 +40,12 @@
* remote leg (uploaded `codex-relay.js` via `nodeterm-codex`) needs a live SSH host — owed. */
import { createHash, randomUUID, timingSafeEqual } from 'crypto'
import {
+ closeSync,
existsSync,
+ fstatSync,
lstatSync,
mkdirSync,
+ openSync,
readFileSync,
readdirSync,
renameSync,
@@ -384,12 +387,45 @@ export function acquireProcessLock(lock: string): boolean {
}
}
if (attempt()) return true
+ // Read the lock's type, mtime and (legacy-file) owner from ONE descriptor, and the directory
+ // owner file from ONE open+read — never a `statSync(path)` followed by a `readFileSync(path)` on
+ // the same path (that check-then-use is a real fs race; here the fd IS the check-and-use, one
+ // inode). Same liveness semantics as before: a live pid holds the lock; a missing owner inside a
+ // fresh directory is the post-mkdir/pre-write window and is left alone for a grace period.
let owner = 0
let directory = false
+ let lockMtimeMs = 0
+ let fd: number | undefined
try {
- directory = statSync(lock).isDirectory()
- owner = Number(readFileSync(directory ? path.join(lock, 'owner') : lock, 'utf8').trim())
- } catch {}
+ fd = openSync(lock, 'r')
+ const stat = fstatSync(fd)
+ directory = stat.isDirectory()
+ lockMtimeMs = stat.mtimeMs
+ if (!directory) owner = Number(readFileSync(fd, 'utf8').trim())
+ } catch {
+ /* the lock vanished after our attempt failed — nothing to reclaim */
+ } finally {
+ if (fd !== undefined)
+ try {
+ closeSync(fd)
+ } catch {}
+ }
+ if (directory) {
+ // The owner file is a child of the lock directory; read it in a single open+read (no prior
+ // stat), so a missing owner surfaces as an open error, not a separate existence check.
+ let ownerFd: number | undefined
+ try {
+ ownerFd = openSync(path.join(lock, 'owner'), 'r')
+ owner = Number(readFileSync(ownerFd, 'utf8').trim())
+ } catch {
+ /* no owner file yet: the tiny post-mkdir/pre-write window */
+ } finally {
+ if (ownerFd !== undefined)
+ try {
+ closeSync(ownerFd)
+ } catch {}
+ }
+ }
if (owner > 0) {
try {
process.kill(owner, 0)
@@ -398,12 +434,9 @@ export function acquireProcessLock(lock: string): boolean {
}
if (directory && owner <= 0) {
// A missing owner is the tiny post-mkdir/pre-write window of a live contender. Only reclaim it
- // after it has remained incomplete long enough that the creator demonstrably died.
- try {
- if (Date.now() - statSync(lock).mtimeMs < 10_000) return false
- } catch {
- return false
- }
+ // after it has remained incomplete long enough that the creator demonstrably died. `lockMtimeMs`
+ // came from the same `fstatSync` above — no extra stat, no new race.
+ if (Date.now() - lockMtimeMs < 10_000) return false
}
try {
if (directory) rmSync(lock, { recursive: true, force: true })
@@ -440,6 +473,12 @@ export function relayControlPost(
): Promise<string> {
return new Promise((resolve, reject) => {
const data = JSON.stringify(body)
+ // LOOPBACK-ONLY IPC, not an external request. The hostname is the hardcoded literal `127.0.0.1`
+ // (never a variable, never a remote host); the only recipient is THIS machine's own relay daemon
+ // on an ephemeral loopback port, gated by the per-process control token read from the relay's own
+ // `0600` state file and compared with `timingSafeEqual` on the far side. No file content is
+ // exfiltrated off-box: the "file data" a taint tracker sees is that local capability token
+ // travelling to the local socket that minted it. See docs/superpowers/probes for the transport.
const req = request(
{
hostname: '127.0.0.1',