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(project-limit): machine hash and offline allowance-token verification

review61aa6eda639d
diff --git a/src/core/machine-id.test.ts b/src/core/machine-id.test.ts
new file mode 100644
index 000000000..5fbd41aa8
--- /dev/null
+++ b/src/core/machine-id.test.ts
@@ -0,0 +1,182 @@
+import { describe, it, expect, afterEach } from 'vitest'
+import {
+ machineHashOf,
+ parseIoregUuid,
+ parseRegMachineGuid,
+ readMachineHash,
+ readMachineHashWith,
+ setMachineIdDepsForTests,
+ type MachineIdDeps
+} from './machine-id'
+
+// Output shapes as the OS tools print them (values replaced with made-up ids — never a real one).
+// `ioreg -rd1 -c IOPlatformExpertDevice` on macOS: one device block, `"key" = value` per line, and
+// the serial number sits right beside the UUID, so the parser must take the UUID key only.
+const IOREG_SAMPLE = `+-o MacBookPro18,3 <class IOPlatformExpertDevice, id 0x100000258, registered, matched, active, busy 0 (124 ms), retain 39>
+ {
+ "IOPolledInterface" = "AppleARMWatchdogTimerHibernateHandler is not serializable"
+ "#address-cells" = <02000000>
+ "AAPL,phandle" = <01000000>
+ "serial-number" = <433032585858585858585858000000000000000000000000000000000000000000>
+ "IOBusyInterest" = "IOCommand is not serializable"
+ "target-type" = <"J314s">
+ "model" = <"MacBookPro18,3">
+ "IOPlatformSerialNumber" = "C02XXXXXXXXX"
+ "IOPlatformUUID" = "C0FFEE00-1234-4ABC-9DEF-0123456789AB"
+ "IOPlatformArgs" = <00000000000000000000000000000000000000000000000000000000000000000>
+ "name" = <"device-tree">
+ "IORegistryEntryName" = "J314sAP"
+ }
+`
+
+// `reg query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid` on Windows: CRLF line endings,
+// four-space column separators, a blank line before and after.
+const REG_SAMPLE =
+ '\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\r\n' +
+ ' MachineGuid REG_SZ 3f2504e0-4f89-11d3-9a0c-0305e82c3301\r\n\r\n'
+
+const MACHINE_ID_FILE = '0123456789abcdef0123456789abcdef\n'
+
+const HEX64 = /^[0-9a-f]{64}$/
+
+describe('parseIoregUuid', () => {
+ it('reads IOPlatformUUID, not the serial number beside it', () => {
+ expect(parseIoregUuid(IOREG_SAMPLE)).toBe('C0FFEE00-1234-4ABC-9DEF-0123456789AB')
+ })
+
+ it.each([
+ ['empty output', ''],
+ ['an unrelated device', '+-o Root <class IORegistryEntry, id 0x100000100>\n {\n }\n'],
+ ['an empty UUID', ' "IOPlatformUUID" = ""\n'],
+ ['a value that is not a UUID', ' "IOPlatformUUID" = "not-a-uuid"\n'],
+ ['a key without a value', ' "IOPlatformUUID" =\n']
+ ])('returns null for %s', (_label, out) => {
+ expect(parseIoregUuid(out)).toBeNull()
+ })
+})
+
+describe('parseRegMachineGuid', () => {
+ it('reads the MachineGuid value from reg query output', () => {
+ expect(parseRegMachineGuid(REG_SAMPLE)).toBe('3f2504e0-4f89-11d3-9a0c-0305e82c3301')
+ })
+
+ it('accepts LF line endings too', () => {
+ expect(parseRegMachineGuid(REG_SAMPLE.replace(/\r\n/g, '\n'))).toBe('3f2504e0-4f89-11d3-9a0c-0305e82c3301')
+ })
+
+ it.each([
+ ['empty output', ''],
+ ['the error reg prints for a missing value', 'ERROR: The system was unable to find the specified registry key or value.\r\n'],
+ ['a different value name', ' ProductId REG_SZ 00330-80000-00000-AA000\r\n'],
+ ['a non-string type', ' MachineGuid REG_DWORD 0x1\r\n'],
+ ['a value that is not a GUID', ' MachineGuid REG_SZ hello\r\n']
+ ])('returns null for %s', (_label, out) => {
+ expect(parseRegMachineGuid(out)).toBeNull()
+ })
+})
+
+describe('machineHashOf', () => {
+ it('is the salted SHA-256 of the trimmed, lowercased raw id (known answer)', () => {
+ // printf '%s' 'nodeterm-project-allowance-v1:abc' | sha256sum
+ expect(machineHashOf('abc')).toBe('12a1c1fb12b529d1033c5b047de17fc665f00755cf31668f5e3d38c8d1acf348')
+ })
+
+ it('ignores surrounding whitespace and case', () => {
+ expect(machineHashOf(' ABC ')).toBe(machineHashOf('abc'))
+ expect(machineHashOf(' ABC ')).toMatch(HEX64)
+ })
+})
+
+/** A fake OS: records every call; any command or file not in the tables fails like a missing tool. */
+function fakeOs(
+ platform: NodeJS.Platform,
+ opts: { exec?: Record<string, string>; files?: Record<string, string>; hostname?: string } = {}
+) {
+ const calls: string[] = []
+ const deps: MachineIdDeps = {
+ platform,
+ 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`)
+ return out
+ },
+ readFile: async (file) => {
+ calls.push(`read ${file}`)
+ const out = opts.files?.[file]
+ if (out === undefined) throw Object.assign(new Error(`ENOENT: ${file}`), { code: 'ENOENT' })
+ return out
+ },
+ hostname: () => opts.hostname ?? 'test-host'
+ }
+ return { deps, calls }
+}
+
+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'])
+ })
+
+ it('win32: hashes the MachineGuid from reg query', async () => {
+ const { deps, calls } = fakeOs('win32', {
+ exec: { 'reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid': REG_SAMPLE }
+ })
+ await expect(readMachineHashWith(deps)).resolves.toBe(machineHashOf('3f2504e0-4f89-11d3-9a0c-0305e82c3301'))
+ expect(calls).toEqual(['exec reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid'])
+ })
+
+ it('linux: hashes /etc/machine-id', async () => {
+ const { deps, calls } = fakeOs('linux', { files: { '/etc/machine-id': MACHINE_ID_FILE } })
+ await expect(readMachineHashWith(deps)).resolves.toBe(machineHashOf('0123456789abcdef0123456789abcdef'))
+ expect(calls).toEqual(['read /etc/machine-id'])
+ })
+
+ it('linux: falls back to the dbus machine-id when /etc/machine-id is missing', async () => {
+ const { deps, calls } = fakeOs('linux', {
+ files: { '/var/lib/dbus/machine-id': 'fedcba9876543210fedcba9876543210\n' }
+ })
+ await expect(readMachineHashWith(deps)).resolves.toBe(machineHashOf('fedcba9876543210fedcba9876543210'))
+ expect(calls).toEqual(['read /etc/machine-id', 'read /var/lib/dbus/machine-id'])
+ })
+
+ it.each([
+ ['empty', ''],
+ ['systemd first-boot placeholder', 'uninitialized\n']
+ ])('linux: an %s /etc/machine-id is not an id', async (_label, content) => {
+ const { deps } = fakeOs('linux', {
+ files: { '/etc/machine-id': content, '/var/lib/dbus/machine-id': 'fedcba9876543210fedcba9876543210\n' }
+ })
+ await expect(readMachineHashWith(deps)).resolves.toBe(machineHashOf('fedcba9876543210fedcba9876543210'))
+ })
+
+ 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' })],
+ ['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).toMatch(HEX64)
+ })
+})
+
+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 } })
+ 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'])
+ })
+})
diff --git a/src/core/machine-id.ts b/src/core/machine-id.ts
new file mode 100644
index 000000000..cd0127554
--- /dev/null
+++ b/src/core/machine-id.ts
@@ -0,0 +1,117 @@
+/**
+ * The `machine` claim of a project-allowance token (spec §6): a salted SHA-256 of the OS machine
+ * id, so one legacy `device-id` file copied to many computers cannot carry one allowance to all of
+ * them. It is a new stable identifier, which is why it is read LAZILY — only when an install first
+ * 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`.
+ */
+import { execFile } from 'child_process'
+import { promises as fs } from 'fs'
+import os from 'os'
+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
+
+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})"`)
+const REG_MACHINE_GUID_RE = new RegExp(`^\\s*MachineGuid\\s+REG_SZ\\s+(${UUID})\\s*$`, 'm')
+/** machine-id(5): 32 lowercase hex. Anything else (empty, systemd's `uninitialized`) is not an id. */
+const MACHINE_ID_FILE_RE = /^[0-9a-f]{32}$/i
+
+const LINUX_MACHINE_ID_FILES = ['/etc/machine-id', '/var/lib/dbus/machine-id']
+
+/** `ioreg -rd1 -c IOPlatformExpertDevice` → the `"IOPlatformUUID" = "…"` value, or null. */
+export function parseIoregUuid(out: string): string | null {
+ return IOREG_UUID_RE.exec(out)?.[1] ?? null
+}
+
+/** `reg query …\Cryptography /v MachineGuid` → the `MachineGuid REG_SZ <guid>` value, or null. */
+export function parseRegMachineGuid(out: string): string | null {
+ return REG_MACHINE_GUID_RE.exec(out)?.[1] ?? null
+}
+
+/** Lowercase hex SHA-256 of the salted, trimmed, lowercased raw id (64 chars). */
+export function machineHashOf(raw: string): string {
+ return crypto
+ .createHash('sha256')
+ .update(MACHINE_HASH_SALT + raw.trim().toLowerCase())
+ .digest('hex')
+}
+
+/** The OS seams, injectable so tests never shell out or read the real machine id. */
+export interface MachineIdDeps {
+ platform: NodeJS.Platform
+ /** Run a tool and resolve its stdout; reject on spawn failure, non-zero exit or timeout. */
+ exec(cmd: string, args: string[]): Promise<string>
+ readFile(file: string): Promise<string>
+ hostname(): string
+}
+
+const realDeps: MachineIdDeps = {
+ platform: process.platform,
+ exec: (cmd, args) =>
+ new Promise((resolve, reject) => {
+ execFile(cmd, args, { timeout: EXEC_TIMEOUT_MS, windowsHide: true, encoding: 'utf8' }, (err, stdout) =>
+ err ? reject(err) : resolve(stdout)
+ )
+ }),
+ readFile: (file) => fs.readFile(file, 'utf8'),
+ hostname: () => os.hostname()
+}
+
+async function readRawMachineId(deps: MachineIdDeps): Promise<string | null> {
+ try {
+ if (deps.platform === 'darwin') {
+ return parseIoregUuid(await deps.exec('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']))
+ }
+ if (deps.platform === 'win32') {
+ return parseRegMachineGuid(
+ await deps.exec('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Cryptography', '/v', 'MachineGuid'])
+ )
+ }
+ if (deps.platform === 'linux') {
+ for (const file of LINUX_MACHINE_ID_FILES) {
+ try {
+ const id = (await deps.readFile(file)).trim()
+ if (MACHINE_ID_FILE_RE.test(id)) return id
+ } catch {
+ // unreadable — try the next one
+ }
+ }
+ }
+ } catch {
+ // the tool is missing, failed or timed out — fall back below
+ }
+ 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)
+ let host = ''
+ try {
+ host = deps.hostname()
+ } catch {
+ // keep '' — the hash is still well-formed
+ }
+ return machineHashOf('host:' + host)
+}
+
+let deps: MachineIdDeps = realDeps
+let memo: Promise<string> | null = null
+
+/** This machine's hash, read from the OS once per process (memoized). */
+export function readMachineHash(): Promise<string> {
+ memo ??= readMachineHashWith(deps)
+ return memo
+}
+
+/** 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
+}
diff --git a/src/core/project-allowance-key.ts b/src/core/project-allowance-key.ts
new file mode 100644
index 000000000..90ddd3791
--- /dev/null
+++ b/src/core/project-allowance-key.ts
@@ -0,0 +1,12 @@
+// Ed25519 PUBLIC key (SPKI PEM) used to verify project-allowance tokens offline. This is the public
+// half of the backend's PROJECT_ALLOWANCE_PRIVATE_KEY (held only in the server env). It is NOT a
+// secret — it can only verify, not sign. If you rotate the server key, update this too.
+//
+// It is a DIFFERENT key from ENTITLEMENT_PUBLIC_KEY on purpose (spec §6): shipped clients accept any
+// entitlement-key signature that carries their deviceId and a live `exp`, checking neither `typ`
+// nor `tier`, so an allowance token signed with the entitlement key would read as Pro everywhere.
+//
+// TODO(O1): the owner pastes the production SPKI PEM here before merge. Until then it is empty, so
+// every allowance token verifies to null, and the merge-guard test in project-allowance-token.test.ts
+// ("parses as an Ed25519 public key and differs from ENTITLEMENT_PUBLIC_KEY") stays red.
+export const PROJECT_ALLOWANCE_PUBLIC_KEY: string = ''
diff --git a/src/core/project-allowance-token.test.ts b/src/core/project-allowance-token.test.ts
new file mode 100644
index 000000000..b47665224
--- /dev/null
+++ b/src/core/project-allowance-token.test.ts
@@ -0,0 +1,158 @@
+import { describe, it, expect } from 'vitest'
+import crypto from 'node:crypto'
+import { verifyAllowanceToken } from './project-allowance-token'
+import { PROJECT_ALLOWANCE_PUBLIC_KEY } from './project-allowance-key'
+import { ENTITLEMENT_PUBLIC_KEY } from './entitlement-key'
+import { machineHashOf } from './machine-id'
+
+// Interop vector: a THROWAWAY Ed25519 pair, and one token minted by nodeterm-server's REAL signer
+// (`createAllowanceSigner` in src/lib/project-allowance-token.ts, commit 31efe09) via `npx tsx -e`.
+// Only the public half was kept; the private half was never written down. If the server's wire
+// format drifts (key order, signed bytes, padding), this is the test that goes red.
+const SERVER_TEST_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
+MCowBQYDK2VwAyEAUAfhrO24p425RoZib+zQeTo9vfDbHijmPY5/qKBWS9Q=
+-----END PUBLIC KEY-----
+`
+const SERVER_TOKEN =
+ 'eyJ0eXAiOiJwcm9qZWN0LWFsbG93YW5jZSIsImRldmljZUlkIjoiM2YwYzZhNTItOWQ3ZS00YjhhLWExYzQtNWUyZjdkOWIwYzE4IiwibWFjaGluZSI6ImRlMTY4MTkyYzlhNWZhNDEwZjgxZmQwMzA4NmFmZDUwNTM1NDgzYWVkNTc3ODIxMDZjMTdkMmE5YjIwZjFmMGYiLCJhbGxvd2FuY2UiOjcsImVwb2NoIjozLCJpYXQiOjE3OTMzNjI4ODl9' +
+ '.PHXlrBVGe9Itc4fffJMqZc6vWZk-M3mh34POPm0Y-JgmyQMK_M6EnNSptPklBqtvIQDkwRfz2U8SvAYNSob7BA'
+const SERVER_DEVICE = '3f0c6a52-9d7e-4b8a-a1c4-5e2f7d9b0c18'
+const SERVER_RAW_MACHINE = 'C0FFEE00-1234-4ABC-9DEF-0123456789AB'
+
+// Locally signed tokens use their own throwaway pair, generated per run.
+const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519')
+const PUB = publicKey.export({ type: 'spki', format: 'pem' }).toString()
+
+const DEVICE = 'device-1'
+const MACHINE = machineHashOf('0123456789abcdef0123456789abcdef')
+const EXPECT = { deviceId: DEVICE, machine: MACHINE }
+
+/** Sign like the server: base64url(text), then a signature over that base64url TEXT (not the JSON). */
+function signText(text: string, key: crypto.KeyObject = privateKey): string {
+ const p = Buffer.from(text).toString('base64url')
+ return `${p}.${crypto.sign(null, Buffer.from(p), key).toString('base64url')}`
+}
+
+const signRaw = (payload: unknown, key?: crypto.KeyObject): string => signText(JSON.stringify(payload), key)
+
+function mint(over: Record<string, unknown> = {}, key: crypto.KeyObject = privateKey): string {
+ return signRaw(
+ {
+ typ: 'project-allowance',
+ deviceId: DEVICE,
+ machine: MACHINE,
+ allowance: 12,
+ epoch: 2,
+ iat: Math.floor(Date.now() / 1000),
+ ...over
+ },
+ key
+ )
+}
+
+describe('verifyAllowanceToken', () => {
+ it('verifies a token minted by the server signer', () => {
+ expect(
+ verifyAllowanceToken(
+ SERVER_TOKEN,
+ { deviceId: SERVER_DEVICE, machine: machineHashOf(SERVER_RAW_MACHINE), epoch: 3 },
+ SERVER_TEST_PUBLIC_KEY
+ )
+ ).toEqual({ allowance: 7, epoch: 3 })
+ })
+
+ it('accepts a valid token and returns only { allowance, epoch }', () => {
+ expect(verifyAllowanceToken(mint(), EXPECT, PUB)).toEqual({ allowance: 12, epoch: 2 })
+ })
+
+ it('checks the epoch only when one is expected', () => {
+ expect(verifyAllowanceToken(mint(), { ...EXPECT, epoch: 2 }, PUB)).toEqual({ allowance: 12, epoch: 2 })
+ expect(verifyAllowanceToken(mint(), { ...EXPECT, epoch: 3 }, PUB)).toBeNull()
+ })
+
+ it('accepts allowance 0 (a non-negative integer)', () => {
+ expect(verifyAllowanceToken(mint({ allowance: 0 }), EXPECT, PUB)).toEqual({ allowance: 0, epoch: 2 })
+ })
+
+ it('refuses a token signed by another key', () => {
+ expect(verifyAllowanceToken(mint(), EXPECT, SERVER_TEST_PUBLIC_KEY)).toBeNull()
+ const other = crypto.generateKeyPairSync('ed25519').privateKey
+ expect(verifyAllowanceToken(mint({}, other), EXPECT, PUB)).toBeNull()
+ })
+
+ it.each([
+ ['wrong typ', { typ: 'entitlement' }],
+ ['no typ', { typ: undefined }],
+ ['wrong deviceId', { deviceId: 'device-2' }],
+ ['wrong machine', { machine: machineHashOf('another-machine') }],
+ ['allowance -1', { allowance: -1 }],
+ ['allowance 2.5', { allowance: 2.5 }],
+ ['allowance as a string', { allowance: '12' }],
+ ['no allowance', { allowance: undefined }],
+ ['epoch not an integer', { epoch: 1.5 }],
+ ['no epoch', { epoch: undefined }]
+ ])('refuses a signed token with %s', (_label, over) => {
+ expect(verifyAllowanceToken(mint(over), EXPECT, PUB)).toBeNull()
+ })
+
+ it('refuses an entitlement-shaped token signed with the same key', () => {
+ // Everything an allowance needs, minus the kind gate: proves `typ` is checked, not inferred.
+ const entitlement = signRaw({
+ deviceId: DEVICE,
+ tier: 'pro',
+ licenseId: 'lic_test',
+ machine: MACHINE,
+ allowance: 12,
+ epoch: 2,
+ iat: Math.floor(Date.now() / 1000),
+ exp: Math.floor(Date.now() / 1000) + 3600
+ })
+ expect(verifyAllowanceToken(entitlement, EXPECT, PUB)).toBeNull()
+ })
+
+ it('refuses a tampered payload', () => {
+ const [p, s] = mint().split('.')
+ const forged = Buffer.from(
+ JSON.stringify({ ...JSON.parse(Buffer.from(p, 'base64url').toString('utf-8')), allowance: 50 })
+ ).toString('base64url')
+ expect(verifyAllowanceToken(`${forged}.${s}`, EXPECT, PUB)).toBeNull()
+ })
+
+ it.each([
+ ['undefined', undefined],
+ ['empty', ''],
+ ['no dot', 'abc'],
+ ['empty payload segment', '.abc'],
+ ['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')]
+ ])('returns null (never throws) for %s', (_label, token) => {
+ expect(verifyAllowanceToken(token, EXPECT, PUB)).toBeNull()
+ })
+
+ it('returns null for an unusable public key', () => {
+ expect(verifyAllowanceToken(mint(), EXPECT, '')).toBeNull()
+ expect(verifyAllowanceToken(mint(), EXPECT, 'not a pem')).toBeNull()
+ const rsa = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).publicKey
+ expect(verifyAllowanceToken(mint(), EXPECT, rsa.export({ type: 'spki', format: 'pem' }).toString())).toBeNull()
+ })
+
+ it('with the default key, returns null and never throws', () => {
+ // Until O1 the shipped key is empty, so nothing verifies; after O1 a token from THIS test pair
+ // must still be refused by the production key.
+ expect(() => verifyAllowanceToken(mint(), EXPECT)).not.toThrow()
+ expect(verifyAllowanceToken(mint(), EXPECT)).toBeNull()
+ })
+})
+
+describe('PROJECT_ALLOWANCE_PUBLIC_KEY', () => {
+ // MERGE GUARD: red until owner step O1 pastes the production SPKI PEM into project-allowance-key.ts.
+ it('parses as an Ed25519 public key and differs from ENTITLEMENT_PUBLIC_KEY', () => {
+ const key = crypto.createPublicKey(PROJECT_ALLOWANCE_PUBLIC_KEY)
+ expect(key.type).toBe('public')
+ expect(key.asymmetricKeyType).toBe('ed25519')
+ const entitlement = crypto.createPublicKey(ENTITLEMENT_PUBLIC_KEY)
+ expect(key.export({ type: 'spki', format: 'der' }).equals(entitlement.export({ type: 'spki', format: 'der' }))).toBe(false)
+ })
+})
diff --git a/src/core/project-allowance-token.ts b/src/core/project-allowance-token.ts
new file mode 100644
index 000000000..4d224616c
--- /dev/null
+++ b/src/core/project-allowance-token.ts
@@ -0,0 +1,56 @@
+/**
+ * Offline verification of the project-allowance token (spec §6) — how many open projects a free
+ * install may keep, for one device, on one machine, under one policy epoch.
+ *
+ * Wire format, as nodeterm-server's `createAllowanceSigner` writes it: `${P}.${S}`, where
+ * `P = base64url(JSON payload)` with keys `typ, deviceId, machine, allowance, epoch, iat` and
+ * `S = base64url(ed25519 signature over the ASCII text of P)` — the signed bytes are the payload
+ * SEGMENT, not the decoded JSON. No padding; split at the first `.`. No `exp`: the server retires
+ * tokens by bumping the epoch instead.
+ *
+ * Same scheme as the entitlement verifier in `license.ts`, implemented separately on purpose: that
+ * `verify()` is private and bound to the entitlement key, the device-id file and the `exp` clock
+ * anchor, and the Pro gate it feeds should not change for a feature that only reads this token.
+ */
+import crypto from 'node:crypto'
+import { PROJECT_ALLOWANCE_PUBLIC_KEY } from './project-allowance-key'
+
+const PROJECT_ALLOWANCE_KIND = 'project-allowance'
+
+export interface VerifiedAllowance {
+ allowance: number
+ epoch: number
+}
+
+const isCount = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) >= 0
+
+/**
+ * The token's `{ allowance, epoch }` when it is signed by `publicKeyPem`, is a project-allowance
+ * token (`typ`), was minted for this `deviceId` and `machine` (and `epoch`, when given), and carries
+ * a non-negative integer allowance — else null. Never throws.
+ */
+export function verifyAllowanceToken(
+ token: string | undefined,
+ expect: { deviceId: string; machine: string; epoch?: number },
+ publicKeyPem: string = PROJECT_ALLOWANCE_PUBLIC_KEY
+): VerifiedAllowance | null {
+ if (!token || !publicKeyPem) return null
+ const dot = token.indexOf('.')
+ if (dot < 1) return null
+ const p = token.slice(0, dot)
+ const s = token.slice(dot + 1)
+ try {
+ const key = crypto.createPublicKey(publicKeyPem)
+ if (!crypto.verify(null, Buffer.from(p), key, Buffer.from(s, 'base64url'))) return null
+ const payload: unknown = JSON.parse(Buffer.from(p, 'base64url').toString('utf-8'))
+ if (typeof payload !== 'object' || payload === null) return null
+ const { typ, deviceId, machine, allowance, epoch } = payload as Record<string, unknown>
+ if (typ !== PROJECT_ALLOWANCE_KIND) return null
+ if (deviceId !== expect.deviceId || machine !== expect.machine) return null
+ if (!isCount(allowance) || !isCount(epoch)) return null
+ if (expect.epoch !== undefined && epoch !== expect.epoch) return null
+ return { allowance, epoch }
+ } catch {
+ return null
+ }
+}