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): the machine-scoped account model, path builders, and fail-closed scope

Claude Codeb05f03607ffb
diff --git a/src/core/codex-accounts-core.test.ts b/src/core/codex-accounts-core.test.ts
new file mode 100644
index 000000000..15c701d26
--- /dev/null
+++ b/src/core/codex-accounts-core.test.ts
@@ -0,0 +1,286 @@
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { describe, expect, it } from 'vitest'
+import {
+ ACCOUNT_ID_RE,
+ assertCodexAccountId,
+ isSafeAccountId,
+ codexAccountHome,
+ codexHomeForAccount,
+ codexSessionEnv,
+ codexSocketForAccount,
+ codexTmuxEnvArgs,
+ codexUsageAccounts,
+ legacyCodexAccountHome,
+ migrateLegacyCodexAccountHome,
+ migrateLegacyCodexAccountHomes,
+ needsCodexAccountScope,
+ remoteCodexHome,
+ remoteCodexSocket,
+ remoteCodexTmuxEnvArgs,
+ systemCodexHome,
+ AUTH_ENV_STRIP,
+ stripCodexAuthEnv
+} from './codex-accounts-core'
+
+describe('Codex account id validation (supply-chain guard)', () => {
+ it.each(['a', 'A0', 'account-a', 'be28d3d4-c18c-430c-a257-ae550d3dd7ed', 'a.b_c-1'])(
+ 'accepts safe id %s',
+ (id) => {
+ expect(isSafeAccountId(id)).toBe(true)
+ expect(() => assertCodexAccountId(id)).not.toThrow()
+ }
+ )
+
+ it.each(['', '.', '..', 'a/b', '/absolute', '../escape', '.hidden', '-lead', 'space name', 'a\nb'])(
+ 'refuses traversal / unsafe id %j',
+ (id) => {
+ expect(isSafeAccountId(id)).toBe(false)
+ expect(() => assertCodexAccountId(id)).toThrow('Invalid Codex account id')
+ }
+ )
+
+ it('exposes the same regex the renderer validates against (one definition)', () => {
+ expect(ACCOUNT_ID_RE.source).toBe('^[A-Za-z0-9][A-Za-z0-9._-]*$')
+ })
+})
+
+describe('managed Codex account paths', () => {
+ it('isolates two accounts under distinct homes and shared-server sockets', () => {
+ const userData = '/isolated/nodeterm'
+ expect(codexAccountHome(userData, 'account-a')).not.toBe(
+ legacyCodexAccountHome(userData, 'account-a')
+ )
+ expect(codexHomeForAccount(userData, 'account-a')).not.toBe(
+ codexHomeForAccount(userData, 'account-b')
+ )
+ expect(codexSocketForAccount(userData, 'account-a')).not.toBe(
+ codexSocketForAccount(userData, 'account-b')
+ )
+ })
+
+ it('folds userDataDir into the digest so separate profiles never collide', () => {
+ expect(codexAccountHome('/profile-one', 'account-a')).not.toBe(
+ codexAccountHome('/profile-two', 'account-a')
+ )
+ })
+
+ it.each(['', '../escape', 'space name', '/absolute'])(
+ 'rejects unsafe account id %j at the home builder',
+ (id) => {
+ expect(() => codexAccountHome('/isolated/nodeterm', id)).toThrow('Invalid Codex account id')
+ }
+ )
+
+ // A NON-EMPTY unsafe id reaches the socket builder through `codexAccountHome` and throws; an
+ // empty id is the system account (falsy ⇒ `~/.codex`), which is the intended semantics.
+ it.each(['../escape', 'space name', '/absolute'])(
+ 'rejects a non-empty unsafe account id %j at the socket builder',
+ (id) => {
+ expect(() => codexSocketForAccount('/isolated/nodeterm', id)).toThrow(
+ 'Invalid Codex account id'
+ )
+ }
+ )
+
+ it('treats an empty id as the system account, not a traversal', () => {
+ expect(codexHomeForAccount('/isolated/nodeterm', '')).toBe(systemCodexHome())
+ expect(codexSocketForAccount('/isolated/nodeterm', '')).toBe(
+ path.join(systemCodexHome(), 'app-server-control', 'app-server-control.sock')
+ )
+ })
+
+ it('system account resolves to $CODEX_HOME (absolute) or ~/.codex', () => {
+ const prev = process.env.CODEX_HOME
+ try {
+ delete process.env.CODEX_HOME
+ expect(systemCodexHome()).toBe(path.join(os.homedir(), '.codex'))
+ expect(codexHomeForAccount('/isolated/nodeterm')).toBe(systemCodexHome())
+ process.env.CODEX_HOME = 'relative-ignored'
+ expect(systemCodexHome()).toBe(path.join(os.homedir(), '.codex'))
+ process.env.CODEX_HOME = '/custom/codex'
+ expect(systemCodexHome()).toBe('/custom/codex')
+ } finally {
+ if (prev === undefined) delete process.env.CODEX_HOME
+ else process.env.CODEX_HOME = prev
+ }
+ })
+
+ it('keeps the managed daemon socket below macOS SUN_LEN', () => {
+ const userData = '/Users/example/Library/Application Support/node-terminal'
+ const accountId = 'be28d3d4-c18c-430c-a257-ae550d3dd7ed'
+ expect(Buffer.byteLength(codexSocketForAccount(userData, accountId))).toBeLessThan(104)
+ })
+})
+
+describe('per-session Codex env', () => {
+ it('overwrites inherited account scope for system and managed sessions', () => {
+ const accountHome = codexAccountHome('/isolated/nodeterm', 'account-a')
+ expect(codexSessionEnv('/isolated/nodeterm')).toMatchObject({ NODETERM_CODEX_ACCOUNT_ID: '' })
+ expect(codexSessionEnv('/isolated/nodeterm', 'account-a')).toEqual({
+ CODEX_HOME: accountHome,
+ NODETERM_CODEX_ACCOUNT_ID: 'account-a'
+ })
+ expect(codexTmuxEnvArgs('/isolated/nodeterm', 'account-a')).toEqual([
+ '-e',
+ `CODEX_HOME=${accountHome}`,
+ '-e',
+ 'NODETERM_CODEX_ACCOUNT_ID=account-a'
+ ])
+ })
+
+ it('scopes Codex agents and managed-id login terminals, nothing else', () => {
+ expect(needsCodexAccountScope('codex')).toBe(true)
+ expect(needsCodexAccountScope(undefined, 'account-a')).toBe(true)
+ expect(needsCodexAccountScope(undefined, undefined)).toBe(false)
+ expect(needsCodexAccountScope('bash')).toBe(false)
+ })
+})
+
+describe('remote managed Codex homes', () => {
+ it('isolates remote accounts under short host-local homes (digest over id only)', () => {
+ const remoteHome = '/home/corvin'
+ const first = remoteCodexHome(remoteHome, 'account-a')
+ const second = remoteCodexHome(remoteHome, 'account-b')
+ expect(first).not.toBe(second)
+ expect(remoteCodexHome(remoteHome)).toBe('/home/corvin/.codex')
+ expect(remoteCodexSocket(remoteHome, 'account-a')).toBe(
+ `${first}/app-server-control/app-server-control.sock`
+ )
+ expect(remoteCodexTmuxEnvArgs(remoteHome, 'account-a')).toEqual([
+ '-e',
+ `CODEX_HOME=${first}`,
+ '-e',
+ 'NODETERM_CODEX_ACCOUNT_ID=account-a'
+ ])
+ })
+
+ it('rejects a relative remote home and unsafe account id', () => {
+ expect(() => remoteCodexHome('relative', 'account-a')).toThrow('Remote home must be absolute')
+ expect(() => remoteCodexHome('/home/corvin', '../escape')).toThrow('Invalid Codex account id')
+ })
+})
+
+describe('legacy home migration (real fs, fail closed)', () => {
+ it('moves an existing long managed home to its deterministic short home', () => {
+ const fixture = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-home-'))
+ try {
+ const userData = path.join(fixture, 'Library', 'Application Support', 'node-terminal')
+ const shortRoot = path.join(fixture, 'cx')
+ const legacy = legacyCodexAccountHome(userData, 'account-a')
+ mkdirSync(legacy, { recursive: true })
+ writeFileSync(path.join(legacy, 'auth.json'), 'fixture')
+
+ const target = migrateLegacyCodexAccountHome(userData, 'account-a', shortRoot)
+
+ expect(target).toBe(codexAccountHome(userData, 'account-a', shortRoot))
+ expect(readFileSync(path.join(target, 'auth.json'), 'utf8')).toBe('fixture')
+ expect(existsSync(legacy)).toBe(false)
+ } finally {
+ rmSync(fixture, { recursive: true, force: true })
+ }
+ })
+
+ it('never overwrites an existing short home', () => {
+ const fixture = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-home-keep-'))
+ try {
+ const userData = path.join(fixture, 'ud')
+ const shortRoot = path.join(fixture, 'cx')
+ const legacy = legacyCodexAccountHome(userData, 'account-a')
+ const target = codexAccountHome(userData, 'account-a', shortRoot)
+ mkdirSync(legacy, { recursive: true })
+ writeFileSync(path.join(legacy, 'auth.json'), 'legacy')
+ mkdirSync(target, { recursive: true })
+ writeFileSync(path.join(target, 'auth.json'), 'already-here')
+
+ migrateLegacyCodexAccountHome(userData, 'account-a', shortRoot)
+
+ expect(readFileSync(path.join(target, 'auth.json'), 'utf8')).toBe('already-here')
+ expect(existsSync(legacy)).toBe(true)
+ } finally {
+ rmSync(fixture, { recursive: true, force: true })
+ }
+ })
+
+ it('sweeps valid entries and leaves an invalid entry untouched (fail closed)', () => {
+ const fixture = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-sweep-'))
+ try {
+ const userData = path.join(fixture, 'ud')
+ const shortRoot = path.join(fixture, 'cx')
+ const legacyRoot = path.join(userData, 'codex-accounts')
+ const good = path.join(legacyRoot, 'account-a')
+ const bad = path.join(legacyRoot, '.hidden') // fails ACCOUNT_ID_RE -> untouched
+ mkdirSync(good, { recursive: true })
+ mkdirSync(bad, { recursive: true })
+ writeFileSync(path.join(good, 'auth.json'), 'good')
+ writeFileSync(path.join(bad, 'auth.json'), 'bad')
+
+ migrateLegacyCodexAccountHomes(userData, shortRoot)
+
+ expect(existsSync(good)).toBe(false)
+ expect(
+ readFileSync(path.join(codexAccountHome(userData, 'account-a', shortRoot), 'auth.json'), 'utf8')
+ ).toBe('good')
+ // The invalid id never resolves to a short home and is left exactly where it was.
+ expect(readFileSync(path.join(bad, 'auth.json'), 'utf8')).toBe('bad')
+ } finally {
+ rmSync(fixture, { recursive: true, force: true })
+ }
+ })
+
+ it('is a no-op when there is no legacy root', () => {
+ const fixture = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-noop-'))
+ try {
+ expect(() =>
+ migrateLegacyCodexAccountHomes(path.join(fixture, 'ud'), path.join(fixture, 'cx'))
+ ).not.toThrow()
+ } finally {
+ rmSync(fixture, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('auth-env strip (no credential shadows the account login)', () => {
+ it('lists the OpenAI/Codex key vars', () => {
+ expect([...AUTH_ENV_STRIP]).toEqual(['OPENAI_API_KEY', 'CODEX_API_KEY'])
+ })
+
+ it('removes exactly those vars and preserves the rest', () => {
+ const stripped = stripCodexAuthEnv({
+ OPENAI_API_KEY: 'sk-leak',
+ CODEX_API_KEY: 'ck-leak',
+ CODEX_HOME: '/home/.codex',
+ PATH: '/usr/bin'
+ })
+ expect(stripped).toEqual({ CODEX_HOME: '/home/.codex', PATH: '/usr/bin' })
+ expect('OPENAI_API_KEY' in stripped).toBe(false)
+ expect('CODEX_API_KEY' in stripped).toBe(false)
+ })
+})
+
+describe('usage discovery follows real homes, not the pending marker', () => {
+ it('maps records to id/home/label/email regardless of pending', () => {
+ expect(
+ codexUsageAccounts(
+ [{ id: 'account-a', label: 'Pending row', pending: true }],
+ (id) => codexAccountHome('/isolated/nodeterm', id)
+ )
+ ).toEqual([
+ {
+ id: 'account-a',
+ home: codexAccountHome('/isolated/nodeterm', 'account-a'),
+ label: 'Pending row',
+ email: undefined
+ }
+ ])
+ })
+})
+
+describe('shared id predicate stays renderer-safe', () => {
+ it('src/shared/codex-account imports nothing from src/core', () => {
+ const src = readFileSync(path.join(__dirname, '..', 'shared', 'codex-account.ts'), 'utf8')
+ expect(/from ['"](\.\.\/)*core\//.test(src)).toBe(false)
+ expect(/from ['"]\.\/codex-accounts-core['"]/.test(src)).toBe(false)
+ })
+})
diff --git a/src/core/codex-accounts-core.ts b/src/core/codex-accounts-core.ts
new file mode 100644
index 000000000..5290bc528
--- /dev/null
+++ b/src/core/codex-accounts-core.ts
@@ -0,0 +1,253 @@
+// Pure model + on-disk layout for machine-scoped managed Codex accounts. Mirrors
+// `claude-accounts-core.ts` (multiple managed logins), with `CODEX_HOME` in place of
+// `CLAUDE_CONFIG_DIR` and OpenAI/Codex key vars in the auth-env strip. Only `crypto`/`fs`/`os`/
+// `path` — no electron, no `../main/*` — so it arms on headless Server Edition too. The impure
+// account LIST + login lifecycle land in a later PR's `src/main/codex-accounts.ts`; the
+// `platform()` seam for `userDataDir` lives in `codex-config-dir.ts`.
+//
+// Ships INERT (nothing spawns against it yet) but fully tested. Based on @Corvin's
+// `codex-accounts-core.ts` in PR #112, re-sliced to the S6 PR-1 model layer.
+import { createHash } from 'crypto'
+import { existsSync, mkdirSync, readdirSync, renameSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { ACCOUNT_ID_RE, isSafeAccountId } from '../shared/codex-account'
+
+export { ACCOUNT_ID_RE, isSafeAccountId } from '../shared/codex-account'
+
+/**
+ * Throw on any id that could escape the accounts root — locally OR on a remote host over ssh.
+ * Account ids reach the filesystem as directory / socket / scope / mapping-file components and
+ * come from attacker-controlled `settings.json` / `project.json`, so this is the supply-chain
+ * guard: `''`, `.`, `..`, `a/b`, `/absolute`, and whitespace ids are all refused at the door.
+ */
+export function assertCodexAccountId(id: string): void {
+ if (!isSafeAccountId(id)) throw new Error('Invalid Codex account id')
+}
+
+/** The pre-migration long home, `<userData>/codex-accounts/<id>`, moved to the short home at boot. */
+export function legacyCodexAccountHome(userDataDir: string, accountId: string): string {
+ assertCodexAccountId(accountId)
+ return path.join(userDataDir, 'codex-accounts', accountId)
+}
+
+/**
+ * A managed account's local home, `~/.nodeterm/cx/<sha256(userDataDir\0accountId)[0..16]>`, mode
+ * `0o700`. The digest is deliberately SHORT: the app-server control socket lives two levels below
+ * it (`<home>/app-server-control/app-server-control.sock`) and must stay under macOS `SUN_LEN` —
+ * the normal Electron userData path plus a UUID already overshoots. `userDataDir` is folded into
+ * the digest so separate NodeTerm profiles never collide, without a global static account root.
+ */
+export function codexAccountHome(
+ userDataDir: string,
+ accountId: string,
+ shortRoot = path.join(os.homedir(), '.nodeterm', 'cx')
+): string {
+ assertCodexAccountId(accountId)
+ const digest = createHash('sha256')
+ .update(userDataDir)
+ .update('\0')
+ .update(accountId)
+ .digest('hex')
+ .slice(0, 16)
+ return path.join(shortRoot, digest)
+}
+
+/**
+ * Move one legacy long home to its deterministic short home, fail-closed: no-op if the legacy dir
+ * is absent, the target already exists, or the paths coincide. An id that fails the regex throws
+ * (via `legacyCodexAccountHome`) and is therefore left untouched by the boot sweep below.
+ */
+export function migrateLegacyCodexAccountHome(
+ userDataDir: string,
+ accountId: string,
+ shortRoot?: string
+): string {
+ const legacy = legacyCodexAccountHome(userDataDir, accountId)
+ const target = codexAccountHome(userDataDir, accountId, shortRoot)
+ if (legacy === target || !existsSync(legacy) || existsSync(target)) return target
+ mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 })
+ renameSync(legacy, target)
+ return target
+}
+
+/** Boot sweep: migrate every legacy managed home. Invalid / unmovable entries are left in place. */
+export function migrateLegacyCodexAccountHomes(userDataDir: string, shortRoot?: string): void {
+ const legacyRoot = path.join(userDataDir, 'codex-accounts')
+ let entries: Array<{ name: string; isDirectory(): boolean }>
+ try {
+ entries = readdirSync(legacyRoot, { withFileTypes: true })
+ } catch {
+ return
+ }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue
+ try {
+ migrateLegacyCodexAccountHome(userDataDir, entry.name, shortRoot)
+ } catch {
+ // Invalid/unmovable entries remain untouched and therefore fail closed.
+ }
+ }
+}
+
+/** The SYSTEM Codex home: `$CODEX_HOME` when set to an absolute path, else `~/.codex`. */
+export function systemCodexHome(): string {
+ const configured = process.env.CODEX_HOME?.trim()
+ return configured && path.isAbsolute(configured) ? configured : path.join(os.homedir(), '.codex')
+}
+
+/** System vs managed is presence/absence of an id: no id ⇒ `~/.codex`; a valid id ⇒ its short home. */
+export function codexHomeForAccount(userDataDir: string, accountId?: string): string {
+ return accountId ? codexAccountHome(userDataDir, accountId) : systemCodexHome()
+}
+
+/** The one persistent app-server's control socket for an account (system or managed). */
+export function codexSocketForAccount(userDataDir: string, accountId?: string): string {
+ return path.join(
+ codexHomeForAccount(userDataDir, accountId),
+ 'app-server-control',
+ 'app-server-control.sock'
+ )
+}
+
+/** Short, deterministic remote homes keep the app-server Unix socket below SUN_LEN. A remote host
+ * has ONE home root, so the digest is over `accountId` only. */
+export function remoteCodexHome(remoteHome: string, accountId?: string): string {
+ if (!path.posix.isAbsolute(remoteHome)) throw new Error('Remote home must be absolute')
+ if (!accountId) return path.posix.join(remoteHome, '.codex')
+ assertCodexAccountId(accountId)
+ const digest = createHash('sha256').update(accountId).digest('hex').slice(0, 16)
+ return path.posix.join(remoteHome, '.nodeterm', 'cx', digest)
+}
+
+export function remoteCodexSocket(remoteHome: string, accountId?: string): string {
+ return path.posix.join(
+ remoteCodexHome(remoteHome, accountId),
+ 'app-server-control',
+ 'app-server-control.sock'
+ )
+}
+
+export function remoteCodexSessionEnv(
+ remoteHome: string,
+ accountId?: string
+): { CODEX_HOME: string; NODETERM_CODEX_ACCOUNT_ID: string } {
+ return {
+ CODEX_HOME: remoteCodexHome(remoteHome, accountId),
+ NODETERM_CODEX_ACCOUNT_ID: accountId ?? ''
+ }
+}
+
+export function remoteCodexTmuxEnvArgs(remoteHome: string, accountId?: string): string[] {
+ return Object.entries(remoteCodexSessionEnv(remoteHome, accountId)).flatMap(([key, value]) => [
+ '-e',
+ `${key}=${value}`
+ ])
+}
+
+/**
+ * Explicit per-session env. An EMPTY account id means the system account and is written
+ * explicitly, so it OVERWRITES any managed `NODETERM_CODEX_ACCOUNT_ID` inherited from a parent
+ * (tmux shares one server env) rather than silently acting as the wrong login.
+ */
+export function codexSessionEnv(
+ userDataDir: string,
+ accountId?: string
+): { CODEX_HOME: string; NODETERM_CODEX_ACCOUNT_ID: string } {
+ return {
+ CODEX_HOME: codexHomeForAccount(userDataDir, accountId),
+ NODETERM_CODEX_ACCOUNT_ID: accountId ?? ''
+ }
+}
+
+/** A refusal carrying the same `unavailable` code the spawn layer surfaces to the renderer. */
+export interface CodexScopeRefusal {
+ unavailable: 'codex-account'
+}
+export type CodexSessionScope =
+ | { CODEX_HOME: string; NODETERM_CODEX_ACCOUNT_ID: string }
+ | CodexScopeRefusal
+
+export function isCodexScopeRefusal(scope: CodexSessionScope): scope is CodexScopeRefusal {
+ return (scope as CodexScopeRefusal).unavailable === 'codex-account'
+}
+
+/**
+ * Resolve the session scope for a Codex spawn, fail-closed (S6 Decision 2 / §5 property 4).
+ *
+ * An EXPLICITLY selected managed account whose home is missing REFUSES (`{ unavailable:
+ * 'codex-account' }`) — it never falls back to the system home. This is deliberately STRICTER than
+ * the Claude sibling's `pty-manager` fallback: silently acting as the wrong login is a worse
+ * failure for an explicit switch than for a first spawn. The system account (no id) always
+ * resolves and, per `codexSessionEnv`, explicitly clears any inherited managed scope.
+ *
+ * `homeExists` is injected so the spawn layer passes real `existsSync` and this stays testable
+ * against a real temp filesystem. The later `pty-manager` PR maps `unavailable` straight through.
+ */
+export function resolveCodexSessionScope(
+ userDataDir: string,
+ accountId: string | undefined,
+ homeExists: (home: string) => boolean = existsSync
+): CodexSessionScope {
+ if (!accountId) return codexSessionEnv(userDataDir)
+ assertCodexAccountId(accountId)
+ const home = codexAccountHome(userDataDir, accountId)
+ if (!homeExists(home)) return { unavailable: 'codex-account' }
+ return { CODEX_HOME: home, NODETERM_CODEX_ACCOUNT_ID: accountId }
+}
+
+/**
+ * Codex agents need an explicit system-or-managed scope; a plain login terminal needs it when it
+ * carries a managed account id. Sharing this predicate keeps tmux and plain PTYs aligned.
+ */
+export function needsCodexAccountScope(agentId?: string, accountId?: string): boolean {
+ return agentId === 'codex' || !!accountId
+}
+
+/**
+ * Usage discovery follows actual account HOMES, not the renderer's eventually-consistent `pending`
+ * marker: a completed auth file can exist after a restart before settings reconciles, and the
+ * provider itself safely reports `unavailable` when a home is not logged in yet. Consumed by the
+ * usage PR.
+ */
+export function codexUsageAccounts(
+ accounts: ReadonlyArray<{
+ id: string
+ label: string
+ email?: string | null
+ pending?: boolean
+ }>,
+ homeFor: (accountId: string) => string
+): Array<{ id: string; home: string; label: string; email?: string | null }> {
+ return accounts.map((account) => ({
+ id: account.id,
+ home: homeFor(account.id),
+ label: account.label,
+ email: account.email
+ }))
+}
+
+/** tmux has a shared server env, so both values must be set explicitly per new Codex session. */
+export function codexTmuxEnvArgs(userDataDir: string, accountId?: string): string[] {
+ return Object.entries(codexSessionEnv(userDataDir, accountId)).flatMap(([key, value]) => [
+ '-e',
+ `${key}=${value}`
+ ])
+}
+
+/**
+ * Env vars that would silently SHADOW the selected account's OAuth login (`auth.json`) by forcing
+ * API-key auth instead — the Codex analogue of Claude's `ANTHROPIC_API_KEY`/`CLAUDE_CODE_OAUTH_TOKEN`
+ * strip. Removed from the session env at spawn so a managed account always acts as its own login.
+ * A credential is never placed on argv (the hook-token-argv lesson); this only touches the env.
+ */
+export const AUTH_ENV_STRIP = ['OPENAI_API_KEY', 'CODEX_API_KEY'] as const
+
+/** Return a copy of `env` with every `AUTH_ENV_STRIP` var removed. Applied at spawn by the pty PR. */
+export function stripCodexAuthEnv(
+ env: Record<string, string | undefined>
+): Record<string, string | undefined> {
+ const out = { ...env }
+ for (const key of AUTH_ENV_STRIP) delete out[key]
+ return out
+}
diff --git a/src/core/codex-config-dir.ts b/src/core/codex-config-dir.ts
new file mode 100644
index 000000000..5f69dbc92
--- /dev/null
+++ b/src/core/codex-config-dir.ts
@@ -0,0 +1,16 @@
+// Resolve a managed Codex account's home under this app's persistent state root. The account LIST
+// + login lifecycle live in a later PR's main/codex-accounts.ts; this is just the impure path
+// resolution (it needs the platform seam for userDataDir) split out so core modules can use it
+// without importing electron. Sibling of `claude-config-dir.ts`.
+import { platform } from './platform'
+import { codexHomeForAccount, codexSocketForAccount } from './codex-accounts-core'
+
+/** The Codex home for an account id (or the system `~/.codex` when omitted), via the platform seam. */
+export function codexHomeFor(accountId?: string): string {
+ return codexHomeForAccount(platform().userDataDir, accountId)
+}
+
+/** The account's app-server control socket, via the platform seam. */
+export function codexSocketFor(accountId?: string): string {
+ return codexSocketForAccount(platform().userDataDir, accountId)
+}
diff --git a/src/core/pty-codex-account.test.ts b/src/core/pty-codex-account.test.ts
new file mode 100644
index 000000000..3f918e902
--- /dev/null
+++ b/src/core/pty-codex-account.test.ts
@@ -0,0 +1,57 @@
+// Property 4 (S6 §5) / Decision 2: an EXPLICITLY selected managed Codex account whose home is
+// missing REFUSES — it never falls back to the system home. This pins the fail-closed spawn scope
+// at the model layer (`resolveCodexSessionScope`), where the later pty-manager PR consumes it. The
+// PR-1 model ships inert, so this tests the resolver against a REAL temp filesystem rather than a
+// full PtyManager spawn (nothing spawns against the model yet).
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import {
+ codexAccountHome,
+ isCodexScopeRefusal,
+ resolveCodexSessionScope
+} from './codex-accounts-core'
+
+describe('Codex spawn scope resolves fail-closed', () => {
+ let userDataDir: string
+
+ beforeEach(() => {
+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-codex-scope-'))
+ })
+ afterEach(() => {
+ rmSync(userDataDir, { recursive: true, force: true })
+ })
+
+ it('fails closed without spawning when an explicitly selected account home is missing', () => {
+ // The short home is deliberately NOT created.
+ const scope = resolveCodexSessionScope(userDataDir, 'account-a', existsSync)
+ expect(isCodexScopeRefusal(scope)).toBe(true)
+ expect(scope).toEqual({ unavailable: 'codex-account' })
+ // Decision 2: the refusal must NOT be the system home under any key.
+ expect((scope as { CODEX_HOME?: string }).CODEX_HOME).toBeUndefined()
+ })
+
+ it('spawns against only the selected managed home once it exists', () => {
+ const home = codexAccountHome(userDataDir, 'account-a')
+ mkdirSync(home, { recursive: true })
+ const scope = resolveCodexSessionScope(userDataDir, 'account-a', existsSync)
+ expect(isCodexScopeRefusal(scope)).toBe(false)
+ expect(scope).toEqual({ CODEX_HOME: home, NODETERM_CODEX_ACCOUNT_ID: 'account-a' })
+ })
+
+ it('uses explicit system scope instead of an inherited managed scope', () => {
+ // No account id ⇒ system scope, and it ALWAYS resolves (never refuses), explicitly clearing
+ // any managed NODETERM_CODEX_ACCOUNT_ID a parent process leaked in.
+ const scope = resolveCodexSessionScope(userDataDir, undefined, existsSync)
+ expect(isCodexScopeRefusal(scope)).toBe(false)
+ expect(scope).toMatchObject({ NODETERM_CODEX_ACCOUNT_ID: '' })
+ expect(path.isAbsolute((scope as { CODEX_HOME: string }).CODEX_HOME)).toBe(true)
+ })
+
+ it('refuses an unsafe explicit account id before touching the filesystem', () => {
+ expect(() => resolveCodexSessionScope(userDataDir, '../escape', existsSync)).toThrow(
+ 'Invalid Codex account id'
+ )
+ })
+})
diff --git a/src/shared/codex-account.ts b/src/shared/codex-account.ts
new file mode 100644
index 000000000..c2cdf0529
--- /dev/null
+++ b/src/shared/codex-account.ts
@@ -0,0 +1,41 @@
+// The shared Codex account record + the id predicate the RENDERER validates against before a
+// settings id becomes a filesystem path. This module is import-safe from both `src/core` (path
+// builders) and `src/renderer` (settings UI) — it pulls in NOTHING from `src/core`, so validating
+// an account id in the renderer never drags the impure core path machinery into the bundle.
+//
+// The regex lives here (not in `codex-accounts-core.ts`) precisely so there is ONE definition of a
+// safe account id shared across the seam. `codex-accounts-core` imports it back; a second copy of
+// the alphabet would drift out of step with the path builders it exists to protect.
+
+/**
+ * A managed OR system Codex account, threaded structurally through IPC and settings — there is no
+ * class. `id` empty/undefined at a call site means the SYSTEM account (`~/.codex`); any non-empty
+ * `id` here is a managed account. `host` absent ⇒ this machine; set ⇒ that SSH host.
+ */
+export interface CodexAccount {
+ id: string
+ /** Display label; defaults to the captured email. */
+ label: string
+ email?: string | null
+ /** True until `codex login` completes in the account home and the email is captured. */
+ pending?: boolean
+ /** Set only for remote (SSH) accounts: the ssh host this account's home lives on. */
+ host?: string
+}
+
+/**
+ * Shape of a valid Codex account id. MUST start alphanumeric — that single anchor blocks `.`,
+ * `..`, and any leading separator at the door, so a hostile id from a git-shared `settings.json` /
+ * `project.json` can never traverse out of the accounts root when it becomes a directory, socket,
+ * scope, or mapping-file component. Shared by every path builder in `codex-accounts-core.ts`.
+ */
+export const ACCOUNT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
+
+/**
+ * The regex as a predicate, for callers that must REFUSE a bad id rather than throw on it — the
+ * renderer validates a settings/relay id with this before it is ever handed to the path builders.
+ * One definition, re-exported for `src/core`'s `assertCodexAccountId`.
+ */
+export function isSafeAccountId(id: string): boolean {
+ return typeof id === 'string' && ACCOUNT_ID_RE.test(id)
+}