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(security): arm node identity on both shells — safeStorage on desktop, raw 0600 on the server

Claude Codedc52cc9d8e70
diff --git a/src/core/agents/hook-server.env.test.ts b/src/core/agents/hook-server.env.test.ts
index 2e7875aa3..863552e9f 100644
--- a/src/core/agents/hook-server.env.test.ts
+++ b/src/core/agents/hook-server.env.test.ts
@@ -47,3 +47,9 @@ describe('hookServer.buildPtyEnv — canvas control gate', () => {
expect(hookServer.buildPtyEnv('n1', 'grok').NODETERM_NODE_ID).toBe('n1')
})
})
+
+describe('hookServer.setNodeAuthSecret — length guard', () => {
+ it('rejects a secret shorter than 32 bytes rather than arming a weak identity', () => {
+ expect(() => hookServer.setNodeAuthSecret(new Uint8Array(31))).toThrow(/invalid|secret/i)
+ })
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index cf5d018ec..200f013d3 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -206,12 +206,37 @@ class HookServer {
return createHmac('sha256', this.codexNodeAuthSecret).update(nodeId).digest('base64url')
}
- /** The shell injects a keychain-backed, restart-stable secret before any Codex PTY is created. */
- setCodexNodeAuthSecret(secret: Uint8Array): void {
- if (secret.byteLength < 32) throw new Error('Invalid NodeTerm Codex node-auth secret')
+ /**
+ * 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
+ * core/agents/node-auth-secret.ts). Called on BOTH shells at boot. Rejects a secret under 32
+ * bytes so a truncated/garbage load can never arm a weak identity.
+ */
+ 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)
+ }
+
+ /** 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
+ }
+
+ /** 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
}
diff --git a/src/core/agents/node-auth-secret.test.ts b/src/core/agents/node-auth-secret.test.ts
index 06b600e9b..4585c65c8 100644
--- a/src/core/agents/node-auth-secret.test.ts
+++ b/src/core/agents/node-auth-secret.test.ts
@@ -106,4 +106,20 @@ describe('node-auth secret behind CorePlatform', () => {
initPlatform(fakePlatform({ userDataDir: dir }))
await expect(loadOrCreateNodeAuthSecret()).rejects.toThrow(/invalid|malformed/i)
})
+
+ it('reject-then-retry: a rejected load clears the single-flight cache so a later healthy call succeeds', async () => {
+ // The whole fail-open series leans on this: if a rejection LEFT the rejected promise cached, the
+ // shell's catch would swallow it once and every subsequent boot-path retry would re-await the same
+ // dead promise — identity would stay wedged off for the life of the process. Prove the cache clears.
+ const file = path.join(dir, 'node-auth-key.bin')
+ fs.writeFileSync(file, Buffer.alloc(10), { mode: 0o600 })
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ await expect(loadOrCreateNodeAuthSecret()).rejects.toThrow(/invalid|malformed/i)
+
+ // Heal the platform (remove the poisoned file) and retry — a fresh mint must now succeed.
+ fs.rmSync(file)
+ const secret = await loadOrCreateNodeAuthSecret()
+ expect(secret.byteLength).toBe(32)
+ expect(fs.existsSync(file)).toBe(true)
+ })
})
diff --git a/src/main/index.ts b/src/main/index.ts
index dc716796e..5b15493a7 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -131,7 +131,7 @@ import {
writeCodexThreadIdentity
} from '../core/codex-identity-proxy'
import { codexThreadExists, startCodexThread } from '../core/codex-session-name'
-import { loadOrCreateCodexNodeAuthSecret } from './codex-node-auth-secret'
+import { loadOrCreateNodeAuthSecret } from '../core/agents/node-auth-secret'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import {
isSafeLocalTranscriptPath,
@@ -907,18 +907,20 @@ app.whenReady().then(async () => {
// listeners (setListener/setRawListener/setControlHandler) attach later, which the server
// tolerates — early hook POSTs are simply dropped, never mis-routed.
await hookServer.start()
- // ---- Codex shared identity (src/core/codex-identity-proxy.ts) -------------------------------
- // One keychain-backed secret does two jobs: it mints the per-node capability the identity routes
- // require (closing the "shared bearer can name any sibling node" hole) and it signs the thread →
- // node records the hook prelude reads back. If secure storage is unavailable the whole feature
- // stays OFF — `codexIdentityCaps()` then answers `shared: false`, every launch line stays the
- // bare `codex`, and nothing is half-armed.
+ // ---- Node identity (src/core/agents/node-auth-secret.ts) ------------------------------------
+ // One secret does two jobs: it arms the hook server's per-node capability (closing the "shared
+ // bearer can name any sibling node" hole) and it signs the codex thread → node records the hook
+ // prelude reads back. On the desktop it is sealed via safeStorage; if secure storage is
+ // unavailable the load rejects and we FAIL OPEN — identity stays unavailable (legacy mode),
+ // `codexIdentityCaps()` answers `shared: false`, every launch line stays the bare `codex`, and
+ // nothing is half-armed. Never throws up the boot path.
try {
- const codexNodeAuthSecret = await loadOrCreateCodexNodeAuthSecret()
- hookServer.setCodexNodeAuthSecret(codexNodeAuthSecret)
- setCodexThreadIdentityAuthSecret(codexNodeAuthSecret)
+ const nodeAuthSecret = await loadOrCreateNodeAuthSecret()
+ hookServer.setNodeAuthSecret(nodeAuthSecret)
+ // Keep signing bound codex thread records with the same secret so they keep verifying.
+ setCodexThreadIdentityAuthSecret(nodeAuthSecret)
} catch (error) {
- console.error('[codex-identity] unavailable; Codex nodes run plain codex:', error)
+ console.warn('[node-identity] no secret — hook identity unavailable, running legacy', error)
}
// Probes the CLI for `--remote`, installs the launcher, and publishes the construction-time
// answer. MUST stay after the secret above and before the window: it is what unblocks
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index 38aca57e7..116b18a80 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -1,4 +1,4 @@
-import { app, ipcMain, shell, webContents } from 'electron'
+import { app, ipcMain, safeStorage, shell, webContents } from 'electron'
import type { CorePlatform } from '../core/platform'
import { mainWindowClientIds, sendToMain } from './main-window'
import { peerRegistry } from './peer-registry'
@@ -171,5 +171,12 @@ export function electronPlatform(): ElectronPlatform {
},
clientIds: () => [...mainWindowClientIds(), ...peerRegistry().ids()],
openExternal: (url) => shell.openExternal(url),
+ // Seal / unseal node secrets at rest with the OS keychain. Byte-in byte-out, mirroring #167's
+ // codex-node-auth-key.json shape: encrypt the UTF-8 content of the passed buffer, decrypt back to
+ // the same bytes. Both are supplied together (a shell must supply BOTH hooks or NEITHER — see
+ // CorePlatform). If the keychain is unavailable safeStorage throws, which node-auth-secret.ts
+ // surfaces as a rejected load; both shells catch that and run legacy (fail-open), never crash.
+ sealSecret: (b) => safeStorage.encryptString(b.toString('utf8')),
+ unsealSecret: (b) => Buffer.from(safeStorage.decryptString(b), 'utf8'),
}
}
diff --git a/src/server/index.ts b/src/server/index.ts
index 77ddabdf3..2da957e8b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -23,6 +23,7 @@ import { DownloadTickets } from '../core/download-tickets'
import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'
import os from 'os'
import { hookServer } from '../core/agents/hook-server'
+import { loadOrCreateNodeAuthSecret } from '../core/agents/node-auth-secret'
import {
writePendingAnswerLocal,
startPendingSweep,
@@ -417,6 +418,17 @@ export async function startServer(
}
await hookServer.start()
+ // ---- Node identity (src/core/agents/node-auth-secret.ts) ------------------------------------
+ // First time the Server Edition arms node identity. Headless Linux has no OS keychain, so the
+ // secret is stored as raw 0600 bytes (node-auth-key.bin); the loader handles the at-rest format.
+ // FAIL OPEN and LOUD: if the secret can't be created/read, identity stays unavailable (legacy
+ // mode) and the hook server keeps serving — a throw here must never block boot or the hooks.
+ try {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ } catch (error) {
+ console.warn('[node-identity] no secret — hook identity unavailable, running legacy', error)
+ }
+
// Context Link: core owns the whole feature (read handler, shim, skill, instruction blocks) and
// writes everything under `dataDir`; what it needs from a shell is the link map. The desktop's
// renderer pushes it from the live canvas — headless there may be no browser attached at all, so
diff --git a/src/server/node-identity-boot.test.ts b/src/server/node-identity-boot.test.ts
new file mode 100644
index 000000000..2b32882e2
--- /dev/null
+++ b/src/server/node-identity-boot.test.ts
@@ -0,0 +1,50 @@
+/**
+ * Server Edition boot arming: the headless shell has no OS keychain, so it loads the RAW 0600
+ * secret and hands it to the hook server. This is the FIRST time the Server Edition arms node
+ * identity — before this task it never called any setter and `identityAvailable()` stayed false
+ * for the whole process, silently disabling every identity-scoped route. The invariant proven
+ * here is the headline of Task A2: false before the secret is set, true after.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { fakePlatform } from '../core/platform-fake'
+import { hookServer } from '../core/agents/hook-server'
+import { loadOrCreateNodeAuthSecret, resetNodeAuthSecretForTests } from '../core/agents/node-auth-secret'
+
+let dir = ''
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-server-ident-'))
+ resetPlatformForTests()
+ resetNodeAuthSecretForTests()
+ // Server-Edition shape: no seal hooks, so the secret is stored raw (node-auth-key.bin).
+ initPlatform(fakePlatform({ userDataDir: dir }))
+})
+
+afterEach(() => {
+ hookServer.stop()
+ resetPlatformForTests()
+ resetNodeAuthSecretForTests()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+describe('Server Edition arms node identity on boot', () => {
+ it('identity is unavailable before the secret is set and available after', async () => {
+ await hookServer.start()
+ expect(hookServer.identityAvailable()).toBe(false)
+
+ // The exact boot sequence src/server/index.ts runs after hookServer.start().
+ const secret = await loadOrCreateNodeAuthSecret()
+ hookServer.setNodeAuthSecret(secret)
+
+ expect(hookServer.identityAvailable()).toBe(true)
+ // Later routing tasks read the secret through this accessor.
+ expect(hookServer.nodeAuthSecretOrNull()?.byteLength).toBe(32)
+ // Server Edition stores raw bytes at rest, never the sealed json.
+ expect(fs.existsSync(path.join(dir, 'node-auth-key.bin'))).toBe(true)
+ expect(fs.existsSync(path.join(dir, 'node-auth-key.json'))).toBe(false)
+ })
+})