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(project-limit): never memoize a fallback machine hash; refuse non-string tokens

reviewcb527132a7be
diff --git a/src/core/machine-id.test.ts b/src/core/machine-id.test.ts
index 5fbd41aa8..6d25e34f0 100644
--- a/src/core/machine-id.test.ts
+++ b/src/core/machine-id.test.ts
@@ -87,10 +87,18 @@ describe('machineHashOf', () => {
})
})
-/** A fake OS: records every call; any command or file not in the tables fails like a missing tool. */
+/**
+ * A fake OS: records every call (sleeps included); any command or file not in the tables fails like
+ * a missing tool. An `exec` entry given as a list is a script, one outcome per call (`null` = the
+ * call fails), so a test can make the first read fail and a later one succeed.
+ */
function fakeOs(
platform: NodeJS.Platform,
- opts: { exec?: Record<string, string>; files?: Record<string, string>; hostname?: string } = {}
+ opts: {
+ exec?: Record<string, string | (string | null)[]>
+ files?: Record<string, string>
+ hostname?: string
+ } = {}
) {
const calls: string[] = []
const deps: MachineIdDeps = {
@@ -98,8 +106,9 @@ function fakeOs(
exec: async (cmd, args) => {
const key = [cmd, ...args].join(' ')
calls.push(`exec ${key}`)
- const out = opts.exec?.[key]
- if (out === undefined) throw new Error(`spawn ${cmd} ENOENT`)
+ const entry = opts.exec?.[key]
+ const out = Array.isArray(entry) ? entry.shift() : entry
+ if (out === undefined || out === null) throw new Error(`spawn ${cmd} EAGAIN`)
return out
},
readFile: async (file) => {
@@ -108,18 +117,24 @@ function fakeOs(
if (out === undefined) throw Object.assign(new Error(`ENOENT: ${file}`), { code: 'ENOENT' })
return out
},
- hostname: () => opts.hostname ?? 'test-host'
+ hostname: () => opts.hostname ?? 'test-host',
+ sleep: async (ms) => {
+ calls.push(`sleep ${ms}`)
+ }
}
return { deps, calls }
}
+const IOREG = 'ioreg -rd1 -c IOPlatformExpertDevice'
+const IOREG_CALL = `exec ${IOREG}`
+const OS_HASH = machineHashOf('C0FFEE00-1234-4ABC-9DEF-0123456789AB')
+const FALLBACK_HASH = machineHashOf('host:Mac-Studio.local')
+
describe('readMachineHashWith', () => {
it('darwin: hashes the IOPlatformUUID from ioreg', async () => {
- const { deps, calls } = fakeOs('darwin', {
- exec: { 'ioreg -rd1 -c IOPlatformExpertDevice': IOREG_SAMPLE }
- })
- await expect(readMachineHashWith(deps)).resolves.toBe(machineHashOf('C0FFEE00-1234-4ABC-9DEF-0123456789AB'))
- expect(calls).toEqual(['exec ioreg -rd1 -c IOPlatformExpertDevice'])
+ const { deps, calls } = fakeOs('darwin', { exec: { [IOREG]: IOREG_SAMPLE } })
+ await expect(readMachineHashWith(deps)).resolves.toBe(OS_HASH)
+ expect(calls).toEqual([IOREG_CALL])
})
it('win32: hashes the MachineGuid from reg query', async () => {
@@ -154,29 +169,62 @@ describe('readMachineHashWith', () => {
await expect(readMachineHashWith(deps)).resolves.toBe(machineHashOf('fedcba9876543210fedcba9876543210'))
})
+ it('retries a failed OS read once, after a short delay', async () => {
+ const { deps, calls } = fakeOs('darwin', { exec: { [IOREG]: [null, IOREG_SAMPLE] } })
+ await expect(readMachineHashWith(deps)).resolves.toBe(OS_HASH)
+ expect(calls).toEqual([IOREG_CALL, 'sleep 250', IOREG_CALL])
+ })
+
it.each([
['darwin, ioreg missing', fakeOs('darwin', { hostname: 'Mac-Studio.local' })],
- ['darwin, ioreg without a UUID', fakeOs('darwin', { exec: { 'ioreg -rd1 -c IOPlatformExpertDevice': '' }, hostname: 'Mac-Studio.local' })],
+ ['darwin, ioreg without a UUID', fakeOs('darwin', { exec: { [IOREG]: '' }, hostname: 'Mac-Studio.local' })],
['win32, reg fails', fakeOs('win32', { hostname: 'Mac-Studio.local' })],
['linux, both files missing', fakeOs('linux', { hostname: 'Mac-Studio.local' })],
['an unknown platform', fakeOs('freebsd', { hostname: 'Mac-Studio.local' })]
])('%s: hashes host:<hostname>, never returns the raw fallback', async (_label, { deps }) => {
const hash = await readMachineHashWith(deps)
- expect(hash).toBe(machineHashOf('host:Mac-Studio.local'))
+ expect(hash).toBe(FALLBACK_HASH)
expect(hash).toMatch(HEX64)
})
+
+ it('falls back only after both attempts failed', async () => {
+ const { deps, calls } = fakeOs('darwin', { hostname: 'Mac-Studio.local' })
+ await expect(readMachineHashWith(deps)).resolves.toBe(FALLBACK_HASH)
+ expect(calls).toEqual([IOREG_CALL, 'sleep 250', IOREG_CALL])
+ })
})
describe('readMachineHash', () => {
afterEach(() => setMachineIdDepsForTests(null))
- it('reads the OS once and memoizes the promise', async () => {
- const { deps, calls } = fakeOs('linux', { files: { '/etc/machine-id': MACHINE_ID_FILE } })
+ it('memoizes a successful OS read: one exec across calls, concurrent callers share it', async () => {
+ const { deps, calls } = fakeOs('darwin', { exec: { [IOREG]: IOREG_SAMPLE } })
setMachineIdDepsForTests(deps)
const first = readMachineHash()
expect(readMachineHash()).toBe(first)
- await expect(first).resolves.toBe(machineHashOf('0123456789abcdef0123456789abcdef'))
- await readMachineHash()
- expect(calls).toEqual(['read /etc/machine-id'])
+ await expect(first).resolves.toBe(OS_HASH)
+ expect(readMachineHash()).toBe(first)
+ await expect(readMachineHash()).resolves.toBe(OS_HASH)
+ expect(calls).toEqual([IOREG_CALL])
+ })
+
+ it('a first read that fails then succeeds on retry returns the OS hash', async () => {
+ const { deps, calls } = fakeOs('darwin', { exec: { [IOREG]: [null, IOREG_SAMPLE] } })
+ setMachineIdDepsForTests(deps)
+ await expect(readMachineHash()).resolves.toBe(OS_HASH)
+ await expect(readMachineHash()).resolves.toBe(OS_HASH)
+ expect(calls).toEqual([IOREG_CALL, 'sleep 250', IOREG_CALL])
+ })
+
+ it('does not memoize the fallback: a later call that reads the OS returns and keeps the OS hash', async () => {
+ const { deps, calls } = fakeOs('darwin', {
+ exec: { [IOREG]: [null, null, IOREG_SAMPLE] },
+ hostname: 'Mac-Studio.local'
+ })
+ setMachineIdDepsForTests(deps)
+ await expect(readMachineHash()).resolves.toBe(FALLBACK_HASH)
+ await expect(readMachineHash()).resolves.toBe(OS_HASH)
+ await expect(readMachineHash()).resolves.toBe(OS_HASH)
+ expect(calls).toEqual([IOREG_CALL, 'sleep 250', IOREG_CALL, IOREG_CALL])
})
})
diff --git a/src/core/machine-id.ts b/src/core/machine-id.ts
index cd0127554..194d032d1 100644
--- a/src/core/machine-id.ts
+++ b/src/core/machine-id.ts
@@ -5,6 +5,14 @@
* claims an allowance — and why the raw id never leaves this module: not logged, not returned, not
* sent. Only the hash goes to the server, and the server refuses anything that is not 64 lowercase
* hex, so every path here — the fallback included — ends in `machineHashOf`.
+ *
+ * Only a hash that came from the OS is memoized. A failed read is retried once, and if that fails
+ * too the `host:<hostname>` fallback is returned but NOT kept: a timeout or a spawn hiccup is not
+ * evidence that this machine has no id, and memoizing it would give the process the wrong identity.
+ * The stored token would then stop verifying, and a claim made in that state would rebind the
+ * allowance to the hostname hash. The next normal launch would then mismatch it, and the server's
+ * once-per-30-days rebind limit could hold the user at FREE on their own machine. So the next call
+ * asks the OS again.
*/
import { execFile } from 'child_process'
import { promises as fs } from 'fs'
@@ -14,6 +22,8 @@ import crypto from 'node:crypto'
/** Part of the wire contract with nodeterm-server: changing it rebinds every claimed allowance. */
const MACHINE_HASH_SALT = 'nodeterm-project-allowance-v1:'
const EXEC_TIMEOUT_MS = 5000
+/** Wait before the one retry of a failed OS read. */
+const RETRY_DELAY_MS = 250
const UUID = '[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}'
const IOREG_UUID_RE = new RegExp(`"IOPlatformUUID"\\s*=\\s*"(${UUID})"`)
@@ -48,6 +58,7 @@ export interface MachineIdDeps {
exec(cmd: string, args: string[]): Promise<string>
readFile(file: string): Promise<string>
hostname(): string
+ sleep(ms: number): Promise<void>
}
const realDeps: MachineIdDeps = {
@@ -59,7 +70,8 @@ const realDeps: MachineIdDeps = {
)
}),
readFile: (file) => fs.readFile(file, 'utf8'),
- hostname: () => os.hostname()
+ hostname: () => os.hostname(),
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
}
async function readRawMachineId(deps: MachineIdDeps): Promise<string | null> {
@@ -88,10 +100,17 @@ async function readRawMachineId(deps: MachineIdDeps): Promise<string | null> {
return null
}
-/** The machine hash, read through `deps`. Never rejects: any failure hashes `host:<hostname>`. */
-export async function readMachineHashWith(deps: MachineIdDeps): Promise<string> {
- const raw = await readRawMachineId(deps)
- if (raw) return machineHashOf(raw)
+/** The hash of the OS machine id, retrying a failed read once; null when both attempts failed. */
+async function readOsMachineHash(deps: MachineIdDeps): Promise<string | null> {
+ let raw = await readRawMachineId(deps)
+ if (!raw) {
+ await deps.sleep(RETRY_DELAY_MS)
+ raw = await readRawMachineId(deps)
+ }
+ return raw ? machineHashOf(raw) : null
+}
+
+function fallbackHash(deps: MachineIdDeps): string {
let host = ''
try {
host = deps.hostname()
@@ -101,17 +120,40 @@ export async function readMachineHashWith(deps: MachineIdDeps): Promise<string>
return machineHashOf('host:' + host)
}
+/** The machine hash, read through `deps` (no memo). Never rejects: two failed reads hash
+ * `host:<hostname>`. */
+export async function readMachineHashWith(deps: MachineIdDeps): Promise<string> {
+ return (await readOsMachineHash(deps)) ?? fallbackHash(deps)
+}
+
let deps: MachineIdDeps = realDeps
+/** Settled to a hash that came from the OS — kept for the life of the process. */
let memo: Promise<string> | null = null
+/** The attempt in progress, shared by concurrent callers; cleared when it settles. */
+let inFlight: Promise<string> | null = null
-/** This machine's hash, read from the OS once per process (memoized). */
+/** This machine's hash. An OS-read hash is memoized; the fallback is returned but not kept. */
export function readMachineHash(): Promise<string> {
- memo ??= readMachineHashWith(deps)
- return memo
+ if (memo) return memo
+ if (inFlight) return inFlight
+ const d = deps
+ const attempt: Promise<string> = readOsMachineHash(d)
+ .catch(() => null)
+ .then((hash) => {
+ // A test reset while this was in flight leaves it un-memoized.
+ const current = inFlight === attempt
+ if (current) inFlight = null
+ if (hash === null) return fallbackHash(d)
+ if (current) memo = attempt
+ return hash
+ })
+ inFlight = attempt
+ return attempt
}
/** Test seam: swap the OS readers (null restores the real ones) and drop the memo. */
export function setMachineIdDepsForTests(next: MachineIdDeps | null): void {
deps = next ?? realDeps
memo = null
+ inFlight = null
}
diff --git a/src/core/project-allowance-token.test.ts b/src/core/project-allowance-token.test.ts
index b47665224..3b480a2fe 100644
--- a/src/core/project-allowance-token.test.ts
+++ b/src/core/project-allowance-token.test.ts
@@ -126,7 +126,11 @@ describe('verifyAllowanceToken', () => {
['empty signature', `${mint().split('.')[0]}.`],
['a signed non-object payload', signRaw(42)],
['a signed null payload', signRaw(null)],
- ['a signed non-JSON payload', signText('not json')]
+ ['a signed non-JSON payload', signText('not json')],
+ // A hand-edited or corrupted token file can hand over any JSON value, whatever the type says.
+ ['a number', 123 as unknown as string],
+ ['an object', {} as unknown as string],
+ ['null', null as unknown as string]
])('returns null (never throws) for %s', (_label, token) => {
expect(verifyAllowanceToken(token, EXPECT, PUB)).toBeNull()
})
diff --git a/src/core/project-allowance-token.ts b/src/core/project-allowance-token.ts
index 4d224616c..cc98fe01d 100644
--- a/src/core/project-allowance-token.ts
+++ b/src/core/project-allowance-token.ts
@@ -34,7 +34,8 @@ export function verifyAllowanceToken(
expect: { deviceId: string; machine: string; epoch?: number },
publicKeyPem: string = PROJECT_ALLOWANCE_PUBLIC_KEY
): VerifiedAllowance | null {
- if (!token || !publicKeyPem) return null
+ // A runtime guard, not a type one: the token comes off disk, where any JSON value can stand in.
+ if (typeof token !== 'string' || !token || !publicKeyPem) return null
const dot = token.indexOf('.')
if (dot < 1) return null
const p = token.slice(0, dot)