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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
docs(identity): a phone-spawned session is verified — measured, and pinned
enes3618c4c62469
diff --git a/docs/node-identity.md b/docs/node-identity.mdindex fd26e61f8..a75269ee7 100644--- a/docs/node-identity.md+++ b/docs/node-identity.md@@ -169,8 +169,20 @@ including nodes on other projects, or on other people's canvases. Minting happensecret is. The case-fold collision refusal is applied on the *minting* side for the same reason: anAPFS host must not be a way around the local guard.-**The phone needs nothing.** It posts hook events with no node token (`legacy`, accepted) and drives-canvas control over the relay → IPC, not over `/control/*` at all.+**The phone needs nothing, and holds nothing — but the sessions it spawns are `verified`.** The+phone *device* posts no hook events at all: it drives canvas control over the relay → IPC, not over+`/control/*` at all. The sessions it SPAWNS run **on the host**, source the host's 0600 endpoint+file, and therefore read and present the host's per-node token exactly as a desktop-spawned session+does — a phone-spawned session is `verified`.++The chain is worth stating, because it has been mis-derived twice: the phone injects only+`NODETERM_HOOK_ENDPOINT` and `NODETERM_NODE_ID` (it types `tmux new-session -A` over its own SSH+transport, so no `ptyManager` and no `ensureNodeToken` is involved anywhere); the endpoint file+advertises `NODETERM_NODE_TOKEN_DIR`; the managed script reads `$DIR/$NODETERM_NODE_ID` and sends it+on stdin. The token file is there because `refreshNodeTokens` runs on **every canvas persist**, not+because the spawn path minted it. Narrowing that materialisation to the spawn path would silently+drop every phone-spawned session to `legacy` — `src/core/agents/phone-spawned-identity.test.ts`+exists to make that a red build.## Per-route policy@@ -187,8 +199,10 @@ The bearer is required everywhere; this table is about the *node* token on top o| `/codex-thread/fallback` | **Always accepted** | 403 | It reports a DEGRADE and grants nothing; refusing it would silence it in exactly the tokenless case it exists for. |**Why `/hook/*` never 403s a missing token.** It is the fail-open contract, and it is load-bearing-rather than timid. The legitimate tokenless callers are real and permanent: the **phone** (it injects-its own env and cannot mint), the **cross-instance failover** (a second instance's token is+rather than timid. The legitimate tokenless callers are real and permanent: a **phone-spawned session+whose host had no endpoint file yet** (its `NODETERM_HOOK_ENDPOINT` resolved empty, so there was no+token dir to read — note that a phone-spawned session on a host that *does* have one is `verified`,+see above), the **cross-instance failover** (a second instance's token isunjudgeable, not hostile), every session that predates the feature, and any future spawner. A 403there does not degrade a feature — it silently stops an agent's status, context meter and approvals,and the managed script's `curl -sS` has no `--fail`, so a 403 exits 0 and the node goes dark with nodiff --git a/src/core/agents/phone-spawned-identity.test.ts b/src/core/agents/phone-spawned-identity.test.tsnew file mode 100644index 000000000..7d2b4ea2d--- /dev/null+++ b/src/core/agents/phone-spawned-identity.test.ts@@ -0,0 +1,211 @@+/**+ * A PHONE-SPAWNED session is `verified`, and this test is why nobody has to re-derive that.+ *+ * The phone injects exactly two vars (nodeterm-ios TerminalTransport.swift:188):+ * NODETERM_HOOK_ENDPOINT and NODETERM_NODE_ID. No bearer, no port, no token. It does NOT go through+ * ptyManager.create — it types `tmux new-session -A` over its own SSH transport — so the token file+ * it reads was materialised by the PERSIST-time sweep (node-token-service.refreshNodeTokens, wired+ * to onPersist on both shells), not by the spawn path.+ *+ * That distinction is the whole reason this test exists: narrowing materialisation to the spawn path+ * would silently drop every phone-spawned session to `legacy`, and rev.3 of the messaging design+ * would become right by accident, after the fact, with no error anywhere.+ *+ * WHICH HARNESS (the plan offered two): this drives the REAL generated script END-TO-END against a+ * real `node:http` listener on 127.0.0.1 with the real `curl`, and asserts the headers that actually+ * arrived — the same shape as the 2026-08-15 measurement, and the stronger of the two options.+ * Sourcing the script to call `nt_hook_headers` in isolation would prove the emitter and nothing+ * about whether the POST carries it.+ *+ * The env handed to `sh` is EXACTLY the phone's — HOME + PATH (so `curl` and `head` resolve) plus+ * the two vars HookEnv.flags sets. In particular NODETERM_PERM_WAIT_SECS is deliberately absent, so+ * the script takes its normal backgrounded-POST branch; the assertions wait on the listener rather+ * than on the child, because that is what the phone's sessions really do.+ */+import { spawn, spawnSync } from 'node:child_process'+import { createServer, type IncomingMessage, type Server } from 'node:http'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import { buildManagedScript } from './hooks/managed-script'+import { nodeAuthToken, verifyNodeToken } from './node-auth-token'++const SECRET = Buffer.alloc(32, 7)++interface Received {+ url: string+ headers: Record<string, string>+ body: string+}++describe('a phone-spawned session presents its per-node token', () => {+ const sh = spawnSync('sh', ['-c', 'exit 0'])+ const curl = spawnSync('sh', ['-c', 'command -v curl'], { encoding: 'utf8' })+ const available = sh.status === 0 && !sh.error && curl.status === 0++ let dir = ''+ let server: Server | null = null+ let port = 0+ let received: Received[] = []+ let waiters: (() => void)[] = []++ beforeAll(async () => {+ if (!available) return+ dir = mkdtempSync(join(tmpdir(), 'phoneid-'))+ server = createServer((req: IncomingMessage, res) => {+ const chunks: Buffer[] = []+ req.on('data', (c: Buffer) => chunks.push(c))+ req.on('end', () => {+ const headers: Record<string, string> = {}+ for (const [k, v] of Object.entries(req.headers)) {+ if (typeof v === 'string') headers[k] = v+ }+ received.push({ url: req.url ?? '', headers, body: Buffer.concat(chunks).toString('utf8') })+ res.writeHead(204)+ res.end()+ for (const w of waiters.splice(0)) w()+ })+ })+ await new Promise<void>((resolve) => {+ server!.listen(0, '127.0.0.1', () => {+ const addr = server!.address()+ if (addr && typeof addr === 'object') port = addr.port+ resolve()+ })+ })+ })++ afterAll(() => {+ server?.close()+ if (dir) rmSync(dir, { recursive: true, force: true })+ })++ beforeEach(() => {+ received = []+ waiters = []+ })++ /** Resolve when one more POST has landed (or reject after `ms` — a silent script is a failure). */+ function nextPost(ms = 5000): Promise<Received> {+ if (received.length > 0) return Promise.resolve(received[received.length - 1])+ return new Promise<Received>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('no POST arrived')), ms)+ waiters.push(() => {+ clearTimeout(timer)+ resolve(received[received.length - 1])+ })+ })+ }++ /**+ * The phone's own spawn, minus tmux: `sh <script>` with EXACTLY HookEnv.flags' two vars. `body`+ * is what claude pipes in on stdin.+ */+ function runPhoneHook(script: string, home: string, nodeId: string, endpoint: string): Promise<number> {+ return new Promise((resolve) => {+ const child = spawn('sh', [script], {+ env: {+ HOME: home,+ PATH: process.env.PATH ?? '',+ NODETERM_HOOK_ENDPOINT: endpoint,+ NODETERM_NODE_ID: nodeId+ },+ stdio: ['pipe', 'ignore', 'ignore']+ })+ child.stdin.end('{"hook_event_name":"Stop","session_id":"s1"}')+ child.on('close', (code) => resolve(code ?? -1))+ })+ }++ /** A fresh $HOME so the failover glob (~/.nodeterm/hook-endpoint-*.env) finds nothing of its own. */+ function newHome(name: string): string {+ const home = join(dir, name)+ mkdirSync(join(home, '.nodeterm'), { recursive: true })+ return home+ }++ /** The 0600 endpoint file the host wrote; `tokenDir` absent reproduces a pre-v2 (v1) file. */+ function endpointFile(name: string, tokenDir: string | null, version = 2): string {+ const p = join(dir, name)+ writeFileSync(+ p,+ `NODETERM_HOOK_PORT=${port}\nNODETERM_HOOK_TOKEN=bearer-xyz\n` ++ `NODETERM_HOOK_VERSION=${version}\n` ++ (tokenDir ? `NODETERM_NODE_TOKEN_DIR=${tokenDir}\n` : ''),+ { encoding: 'utf8', mode: 0o600 }+ )+ return p+ }++ function tokenDirWith(name: string, files: Record<string, string>): string {+ const d = join(dir, name)+ mkdirSync(d, { recursive: true, mode: 0o700 })+ for (const [nodeId, token] of Object.entries(files)) {+ writeFileSync(join(d, nodeId), `${token}\n`, { encoding: 'utf8', mode: 0o600 })+ }+ return d+ }++ function writeScript(name: string, source: string): string {+ const p = join(dir, name)+ writeFileSync(p, source, { encoding: 'utf8', mode: 0o755 })+ return p+ }++ it.skipIf(!available)(+ 'reads the token dir out of the endpoint file it was handed, and sends the header',+ async () => {+ const token = nodeAuthToken(SECRET, 'phone-1')+ const tokens = tokenDirWith('tokens-1', { 'phone-1': token })+ const ep = endpointFile('hook-endpoint-1.env', tokens)+ const script = writeScript('hook-1.sh', buildManagedScript('claude', null))++ expect(await runPhoneHook(script, newHome('home-1'), 'phone-1', ep)).toBe(0)+ const post = await nextPost()++ expect(post.url).toBe('/hook/claude')+ expect(post.headers['x-nodeterm-node-token']).toBe(token)+ // The bearer rides the same stdin config, and the body names the node.+ expect(post.headers['x-nodeterm-hook-token']).toBe('bearer-xyz')+ expect(post.body).toContain('nodeId=phone-1')+ // The REAL verifier's verdict on what really arrived — not a re-derivation of it here.+ expect(verifyNodeToken(SECRET, 'phone-1', post.headers['x-nodeterm-node-token'])).toBe(+ 'verified'+ )+ }+ )++ it.skipIf(!available)(+ 'degrades to no header at all (legacy, never an error) when no token file exists',+ async () => {+ // NEGATIVE CONTROL 1 of the 2026-08-15 measurement: a node id the sweep never materialised.+ // curl drops a header whose value is empty, so "absent" and "empty" are the same wire state,+ // and the server reads both as `legacy`.+ const tokens = tokenDirWith('tokens-2', { 'phone-1': nodeAuthToken(SECRET, 'phone-1') })+ const ep = endpointFile('hook-endpoint-2.env', tokens)+ const script = writeScript('hook-2.sh', buildManagedScript('claude', null))++ expect(await runPhoneHook(script, newHome('home-2'), 'phone-2', ep)).toBe(0)+ const post = await nextPost()++ expect(post.body).toContain('nodeId=phone-2')+ expect(post.headers['x-nodeterm-node-token'] ?? '').toBe('')+ expect(verifyNodeToken(SECRET, 'phone-2', post.headers['x-nodeterm-node-token'])).toBe('legacy')+ }+ )++ it.skipIf(!available)('degrades the same way on a pre-v2 endpoint file', async () => {+ // NEGATIVE CONTROL 2: the endpoint file advertises no NODETERM_NODE_TOKEN_DIR, so there is+ // nowhere to look. Still a POST, still 204, still `legacy`.+ const ep = endpointFile('hook-endpoint-3.env', null, 1)+ const script = writeScript('hook-3.sh', buildManagedScript('claude', null))++ expect(await runPhoneHook(script, newHome('home-3'), 'phone-1', ep)).toBe(0)+ const post = await nextPost()++ expect(post.body).toContain('nodeId=phone-1')+ expect(post.headers['x-nodeterm-node-token'] ?? '').toBe('')+ })++})