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(core): node-auth secret behind CorePlatform — sealed on desktop, raw 0600 on the server

Claude Code29e2901efe5b
diff --git a/src/core/agents/node-auth-secret.test.ts b/src/core/agents/node-auth-secret.test.ts
new file mode 100644
index 000000000..06b600e9b
--- /dev/null
+++ b/src/core/agents/node-auth-secret.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { randomBytes } from 'crypto'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform } from '../platform-fake'
+import { loadOrCreateNodeAuthSecret, resetNodeAuthSecretForTests } from './node-auth-secret'
+
+// A trivial reversible seal for the desktop-shaped tests: byte-wise xor. It is
+// enough to prove the at-rest bytes are ciphertext (never the raw base64) and
+// that unseal(seal(x)) === x, without dragging in Electron's safeStorage.
+const KEY = 0x5a
+const xor = (b: Buffer): Buffer => Buffer.from(b.map((x) => x ^ KEY))
+
+// Build a #167-shaped sealed file body ({version:1, secretKeyEnc: base64(seal(base64(secret)))}),
+// using the same xor the sealed platform is configured with.
+function sealedBody(secret: Buffer): string {
+ const secretKeyEnc = xor(Buffer.from(secret.toString('base64'), 'utf8')).toString('base64')
+ return JSON.stringify({ version: 1, secretKeyEnc }) + '\n'
+}
+
+let dir = ''
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-secret-'))
+ resetPlatformForTests()
+ resetNodeAuthSecretForTests()
+})
+
+afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+ resetPlatformForTests()
+ resetNodeAuthSecretForTests()
+})
+
+function mode(file: string): number {
+ return fs.statSync(file).mode & 0o777
+}
+
+describe('node-auth secret behind CorePlatform', () => {
+ it('Server Edition: mints 32 raw bytes at node-auth-key.bin mode 0600 and reloads identically', async () => {
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ const first = await loadOrCreateNodeAuthSecret()
+ expect(first.byteLength).toBe(32)
+
+ const file = path.join(dir, 'node-auth-key.bin')
+ expect(fs.existsSync(file)).toBe(true)
+ expect(fs.readFileSync(file).byteLength).toBe(32)
+ expect(mode(file)).toBe(0o600)
+ expect(fs.existsSync(path.join(dir, 'node-auth-key.json'))).toBe(false)
+
+ resetNodeAuthSecretForTests()
+ const second = await loadOrCreateNodeAuthSecret()
+ expect(second.equals(first)).toBe(true)
+ })
+
+ it('Desktop: seals to node-auth-key.json (ciphertext only, no raw base64) mode 0600, reloads identically', async () => {
+ initPlatform(fakePlatform({ userDataDir: dir, sealSecret: xor, unsealSecret: xor }))
+ const first = await loadOrCreateNodeAuthSecret()
+ expect(first.byteLength).toBe(32)
+
+ const file = path.join(dir, 'node-auth-key.json')
+ expect(fs.existsSync(file)).toBe(true)
+ expect(mode(file)).toBe(0o600)
+ expect(fs.existsSync(path.join(dir, 'node-auth-key.bin'))).toBe(false)
+
+ const atRest = fs.readFileSync(file, 'utf8')
+ // The raw secret's base64 must not appear on disk — only the sealed form.
+ expect(atRest.includes(first.toString('base64'))).toBe(false)
+ const parsed = JSON.parse(atRest)
+ expect(parsed.version).toBe(1)
+ expect(typeof parsed.secretKeyEnc).toBe('string')
+
+ resetNodeAuthSecretForTests()
+ const second = await loadOrCreateNodeAuthSecret()
+ expect(second.equals(first)).toBe(true)
+ })
+
+ it('single-flights a concurrent double-load: equal buffers, one file, no tmp left', async () => {
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ const [a, b] = await Promise.all([loadOrCreateNodeAuthSecret(), loadOrCreateNodeAuthSecret()])
+ expect(a.equals(b)).toBe(true)
+ const entries = fs.readdirSync(dir)
+ expect(entries).toEqual(['node-auth-key.bin'])
+ })
+
+ it('Desktop: adopts #167 codex-node-auth-key.json when present rather than minting fresh', async () => {
+ const legacyPlain = randomBytes(32)
+ fs.writeFileSync(path.join(dir, 'codex-node-auth-key.json'), sealedBody(legacyPlain), { mode: 0o600 })
+
+ initPlatform(fakePlatform({ userDataDir: dir, sealSecret: xor, unsealSecret: xor }))
+ const secret = await loadOrCreateNodeAuthSecret()
+ expect(secret.equals(legacyPlain)).toBe(true)
+ // And it is re-persisted under the new name so later loads are stable.
+ expect(fs.existsSync(path.join(dir, 'node-auth-key.json'))).toBe(true)
+ })
+
+ it('rejects when the platform supplies exactly one of sealSecret / unsealSecret', () => {
+ initPlatform(fakePlatform({ userDataDir: dir, sealSecret: xor }))
+ expect(() => loadOrCreateNodeAuthSecret()).toThrow(/both|neither/i)
+ })
+
+ it('rejects a malformed key file whose byte length is not 32', async () => {
+ fs.writeFileSync(path.join(dir, 'node-auth-key.bin'), Buffer.alloc(10), { mode: 0o600 })
+ initPlatform(fakePlatform({ userDataDir: dir }))
+ await expect(loadOrCreateNodeAuthSecret()).rejects.toThrow(/invalid|malformed/i)
+ })
+})
diff --git a/src/core/agents/node-auth-secret.ts b/src/core/agents/node-auth-secret.ts
new file mode 100644
index 000000000..55118f80d
--- /dev/null
+++ b/src/core/agents/node-auth-secret.ts
@@ -0,0 +1,138 @@
+import { randomBytes } from 'crypto'
+import { promises as fs } from 'fs'
+import path from 'path'
+import { platform } from '../platform'
+
+/**
+ * The single 32-byte secret every per-node capability derives from. It is the root
+ * of all node identity, so it is minted from crypto.randomBytes, written 0600 via
+ * tmp+rename (a reader never sees a partial file), and stored in ONE of two at-rest
+ * formats under two DISTINCT file names, so a data dir moved between shells can never
+ * be misread as the other format:
+ *
+ * - Desktop shell (can seal): node-auth-key.json — {version:1, secretKeyEnc:<base64
+ * of the sealed base64 secret>}, mirroring #167's codex-node-auth-key.json shape.
+ * - Server Edition (no keychain): node-auth-key.bin — exactly 32 raw bytes, mode 0600.
+ *
+ * The same secret signs the codex thread→node records #167 wrote, so on the sealed
+ * path we ADOPT a pre-existing codex-node-auth-key.json before minting fresh — minting
+ * anew would orphan every bound codex thread on the machine.
+ */
+
+type StoredSecret = { version: 1; secretKeyEnc: string }
+
+let cached: Promise<Buffer> | null = null
+let cachedDir = ''
+
+/** Whether the platform can seal secrets at rest. Throws if it supplies exactly one
+ * of the two hooks — a shell must supply BOTH or NEITHER (programming error). */
+function seals(): boolean {
+ const p = platform()
+ const hasSeal = typeof p.sealSecret === 'function'
+ const hasUnseal = typeof p.unsealSecret === 'function'
+ if (hasSeal !== hasUnseal) {
+ throw new Error('CorePlatform must supply both sealSecret and unsealSecret, or neither')
+ }
+ return hasSeal
+}
+
+const sealedFile = (dir: string): string => path.join(dir, 'node-auth-key.json')
+const rawFile = (dir: string): string => path.join(dir, 'node-auth-key.bin')
+const legacyFile = (dir: string): string => path.join(dir, 'codex-node-auth-key.json')
+
+/** Decode a #167-shaped sealed body via the platform's unseal hook. Identical shape to
+ * the codex key so adoption reuses this exact path. */
+function decodeSealed(raw: string): Buffer {
+ const p = platform()
+ let stored: StoredSecret
+ try {
+ stored = JSON.parse(raw) as StoredSecret
+ } catch {
+ throw new Error('node-auth key is malformed')
+ }
+ if (stored?.version !== 1 || typeof stored.secretKeyEnc !== 'string') {
+ throw new Error('node-auth key is malformed')
+ }
+ const unsealed = p.unsealSecret!(Buffer.from(stored.secretKeyEnc, 'base64'))
+ const secret = Buffer.from(unsealed.toString('utf8'), 'base64')
+ if (secret.byteLength !== 32) throw new Error('node-auth key is invalid')
+ return secret
+}
+
+/** Write bytes atomically: unique tmp with flag 'wx', chmod 0600, rename into place,
+ * unlink the tmp in finally. A reader never observes a partial file. */
+async function persistFile(file: string, data: string | Buffer): Promise<void> {
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ try {
+ await fs.writeFile(tmp, data, { mode: 0o600, flag: 'wx' })
+ await fs.rename(tmp, file)
+ await fs.chmod(file, 0o600)
+ } finally {
+ await fs.unlink(tmp).catch(() => {})
+ }
+}
+
+async function persistSealed(dir: string, secret: Buffer): Promise<void> {
+ const p = platform()
+ const secretKeyEnc = p.sealSecret!(Buffer.from(secret.toString('base64'), 'utf8')).toString('base64')
+ const body: StoredSecret = { version: 1, secretKeyEnc }
+ await persistFile(sealedFile(dir), `${JSON.stringify(body)}\n`)
+}
+
+/** Try to adopt #167's codex-node-auth-key.json (same secret signs codex thread→node
+ * records). Absent or unreadable → null, so the caller mints fresh rather than crashing. */
+async function adoptLegacy(dir: string): Promise<Buffer | null> {
+ try {
+ return decodeSealed(await fs.readFile(legacyFile(dir), 'utf8'))
+ } catch {
+ return null
+ }
+}
+
+async function loadSealed(dir: string): Promise<Buffer> {
+ try {
+ return decodeSealed(await fs.readFile(sealedFile(dir), 'utf8'))
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ const secret = (await adoptLegacy(dir)) ?? randomBytes(32)
+ await persistSealed(dir, secret)
+ return secret
+}
+
+async function loadRaw(dir: string): Promise<Buffer> {
+ const file = rawFile(dir)
+ try {
+ const buf = await fs.readFile(file)
+ if (buf.byteLength !== 32) throw new Error('node-auth key is invalid')
+ return buf
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ const secret = randomBytes(32)
+ await persistFile(file, secret)
+ return secret
+}
+
+/** Restart-stable 32-byte node-auth secret. Single-flight cached per userDataDir; a
+ * rejection clears the cache so a later call retries. */
+export function loadOrCreateNodeAuthSecret(): Promise<Buffer> {
+ const dir = platform().userDataDir
+ if (cached && cachedDir === dir) return cached
+ const pending = seals() ? loadSealed(dir) : loadRaw(dir)
+ cached = pending
+ cachedDir = dir
+ pending.catch(() => {
+ if (cached === pending) {
+ cached = null
+ cachedDir = ''
+ }
+ })
+ return pending
+}
+
+export function resetNodeAuthSecretForTests(): void {
+ cached = null
+ cachedDir = ''
+}
diff --git a/src/core/platform.ts b/src/core/platform.ts
index 1268d5ac9..df63cb516 100644
--- a/src/core/platform.ts
+++ b/src/core/platform.ts
@@ -13,6 +13,13 @@ export interface CorePlatform {
* because it is an Electron notion: the Server Edition has no such directory and simply omits
* it, which is also how src/core stays Electron-free (no-electron.test.ts). */
readonly resourcesPath?: string
+ /** Seal / unseal a secret at rest, byte-in byte-out. Present together on a shell that can
+ * encrypt (Desktop: Electron safeStorage). Their ABSENCE is a supported configuration, not a
+ * degradation: the Server Edition runs headless with no OS keychain and deliberately stores
+ * node secrets as raw 0600 bytes instead. A shell supplies BOTH hooks or NEITHER — supplying
+ * exactly one is a programming error that node-auth-secret.ts rejects. */
+ sealSecret?(b: Buffer): Buffer
+ unsealSecret?(b: Buffer): Buffer
/** Register a request/response RPC handler (Electron: ipcMain.handle, event stripped). */
handle(channel: string, fn: (...args: any[]) => unknown): void
/** Register a fire-and-forget handler (Electron: ipcMain.on, event stripped). */