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
feat(hooks): every client presents its per-node token, empty header = legacy
Claude Codead6cf5386b08
diff --git a/.superpowers/sdd/node-identity/task-A10-report.md b/.superpowers/sdd/node-identity/task-A10-report.mdnew file mode 100644index 000000000..157780ef9--- /dev/null+++ b/.superpowers/sdd/node-identity/task-A10-report.md@@ -0,0 +1,84 @@+# Task A10 report — every client presents its per-node token++**Status:** COMPLETE++## What shipped++All four clients now read `<$NODETERM_NODE_TOKEN_DIR>/<$NODETERM_NODE_ID>` — a lookup by name,+never a scan — and put its first line on `X-Nodeterm-Node-Token` for every request. Missing file,+missing dir, pre-v2 endpoint ⇒ empty ⇒ the server's `legacy` path, unchanged.++- `src/core/agents/hooks/managed-script.ts` (claude/gemini/codex/grok, local + remote)+ - new `nt_read_node_token()` helper + a call right after the endpoint file is sourced;+ - the header on ALL FOUR curls (request POST socket + port, "answered" POST socket + port);+ - `nt_pick_fallback` now also clears `NODETERM_NODE_TOKEN_DIR` before sourcing;+ - `nt_send_request` calls `nt_read_node_token` AFTER a successful fallback, before the re-POST.+- `src/main/canvas-control-core.ts` — `CONTROL_SHIM_SCRIPT`, both curl branches.+- `src/core/context-link-core.ts` — `CONTEXT_SHIM_SCRIPT`, both curl branches.+- `src/core/agents/hooks/opencode.ts` — `live()` seeds `tokenDir` from+ `NODETERM_NODE_TOKEN_DIR` and a second regex picks the v2 line out of the endpoint file+ (its prefix differs from `NODETERM_HOOK_*`, so widening the existing group was not an option);+ a `nodeToken(dir)` reader feeds the `x-nodeterm-node-token` header in the shared `headers`+ object, which all three transports (Bun unix `fetch`, TCP `fetch`, `node:http` socketPath) use.++`codex-identity-proxy.ts` untouched (task A12).++## Tests — real execution, written RED first++17 new assertions failed before the change, all pass after.++- `managed-script.test.ts` (+1 file-local suite, +7 tests → 38 in the file):+ a REAL hook server with a REAL secret, the REAL generated script under `/bin/sh` with the REAL+ curl, asserting the SERVER's own verdict (`meta.verified`):+ - token file present ⇒ `verified: true`;+ - dir advertised only by the ENDPOINT FILE ⇒ `verified: true` (pins "after the source");+ - no token file / no dir at all ⇒ one event, `verified: false`, exit 0;+ - dir holding only ANOTHER node's token ⇒ one event, `verified: false` (presenting it would be+ `forged` ⇒ 403 ⇒ NO listener call, so "exactly one unverified event" is the assertion);+ - **failover, real server:** dead unix-socket primary whose dir holds a FOREIGN-secret token,+ live fallback endpoint advertising its own dir with the real token ⇒ `verified: true`.+ - plus two fake-curl fixtures for the header text itself: the retry carries the FALLBACK dir's+ token and never the primary's, and a pre-v2 fallback (no dir line) leaves the header empty.+- `canvas-control-shim.test.ts` (+5): the real shim, real curl, against header-capturing servers+ on BOTH transports — present / from the endpoint file / absent / another node's id.+- `context-link.cli.test.ts` (+5): same shape for `context.sh`.+- `opencode.test.ts` (+8): the generated plugin body imported and executed — TCP `fetch`, Bun+ unix `fetch`, and `node:http` against a real unix server; present / absent / no dir / other+ node / dir learned from the endpoint file.++**Mutation-checked** (both failover subtleties are proven by tests, not by inspection):+- delete `nt_read_node_token` from the fallback branch ⇒ 3 tests fail (incl. the real-server one);+- delete `NODETERM_NODE_TOKEN_DIR=""` from `nt_pick_fallback` ⇒ 1 test fails.++## Gates++- `npx vitest run src/core/agents src/main/canvas-control-shim.test.ts src/core/context-link.cli.test.ts src/core/no-electron.test.ts src/server/no-electron.test.ts`+ → **21 files, 240 tests, all passing.**+- `npm run typecheck` → clean.+- Wider regression run (`src/core src/main src/server src/shared test/server`): 247 files,+ 3153 tests — only `src/main/node-pty-patch.test.ts` (3) fails, and it fails identically at HEAD+ with all my changes stashed: the clone's `node_modules` is a symlink to an unpatched tree.++## Concerns++1. **curl drops an empty header.** `-H "X: ${empty}"` sends NOTHING — curl removes a header with+ no content after the colon (measured). So the sh clients send "absent", not "present but+ empty". The server reads both as `legacy`, so the contract holds exactly, but any later task+ that wants to DISTINGUISH "client is A10-aware but has no token" from "client predates A10"+ cannot do it from this header. The opencode plugin does send a literal empty value.+2. **`/control/*` and `/context-link/*` do not verify the header yet** (A7 only armed `/hook/*`).+ Those two shims are therefore proven only up to "the header is on the wire with the right+ value" — asserted against real capturing servers, but not against a real verdict. The managed+ hook script IS proven against a real verdict.+3. **Every client path is covered by a real-execution test.** No path was left to string matching+ alone. The one thing not exercised end-to-end is the token file being written by the REMOTE+ host writer (control-master's `remoteEndpointFileContents` advertises the remote dir) — that is+ the remote-materialisation task's ground, not A10's.+4. **`spawnSync` cannot be used for these tests.** It blocks node's event loop, so an in-process+ hook server never accepts the connection and every POST silently "fails" into the failover+ path. The new suites spawn asynchronously; the pre-existing fake-curl fixtures still use+ `spawnSync` because nothing in-process has to answer them.+5. **This clone is shared with a parallel session.** Three commits (`f502f413`, `bce88091`,+ `94e835ac`) landed on `feat/node-identity` while A10 was in progress, and that session has+ uncommitted work in `node-token-service.ts` / `pty-manager.ts`. The A10 commit lists its eight+ paths explicitly and touches nothing of theirs.diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex c87dc0858..d8b428507 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -1,9 +1,13 @@-import { spawnSync } from 'node:child_process'-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs'+import { spawn, spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync, utimesSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterAll, describe, expect, it } from 'vitest'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'import { buildManagedScript } from './managed-script'+import { hookServer } from '../hook-server'+import { nodeAuthToken } from '../node-auth-token'+import { initPlatform, resetPlatformForTests } from '../../platform'+import { fakePlatform } from '../../platform-fake'describe('buildManagedScript', () => {const s = buildManagedScript('claude')@@ -198,15 +202,24 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {// A remote session left pointing at a DEAD project id's endpoint (the tunnel that socket// named is long gone) — exactly the "active but idle forever" state.const dead = join(home, '.nodeterm', 'hook-endpoint-oldproject.env')+ // Each endpoint advertises its OWN node-token dir (the v2 line), and each dir holds a+ // DIFFERENT token for the same node id — that is what makes "whose token went out?"+ // observable on the retry.+ const deadTokens = join(home, 'dead-tokens')+ const liveTokens = join(home, 'live-tokens')+ mkdirSync(deadTokens, { recursive: true })+ mkdirSync(liveTokens, { recursive: true })+ writeFileSync(join(deadTokens, 'node-1'), 'PRIMARY-NODE-TOKEN\n', 'utf8')+ writeFileSync(join(liveTokens, 'node-1'), 'FALLBACK-NODE-TOKEN\n', 'utf8')writeFileSync(dead,- `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'hook-oldproject.sock')}\nNODETERM_HOOK_TOKEN=dead-token\nNODETERM_HOOK_VERSION=1\n`,+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'hook-oldproject.sock')}\nNODETERM_HOOK_TOKEN=dead-token\nNODETERM_HOOK_VERSION=1\nNODETERM_NODE_TOKEN_DIR=${deadTokens}\n`,'utf8')// The live project's endpoint, rewritten by the most recent connect.writeFileSync(join(home, '.nodeterm', 'hook-endpoint-liveproject.env'),- 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=live-token\nNODETERM_HOOK_VERSION=1\n',+ `NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=live-token\nNODETERM_HOOK_VERSION=1\nNODETERM_NODE_TOKEN_DIR=${liveTokens}\n`,'utf8')// Fake curl: log every invocation, fail the unix-socket transport (dead tunnel), succeed on TCP.@@ -241,8 +254,236 @@ describe('buildManagedScript endpoint failover, executed under /bin/sh', () => {expect(calls[1]).toContain('nodeId=node-1')// The dead transport must not survive into the retry (SOCK/PORT are cleared before sourcing).expect(calls[1]).not.toContain('--unix-socket')+ // The per-node token follows the ENDPOINT, not the process: the primary POST carries the+ // primary dir's token, and the retry carries the FALLBACK dir's — a stale token dir would+ // send our kid to an instance that cannot judge it.+ expect(calls[0]).toContain('X-Nodeterm-Node-Token: PRIMARY-NODE-TOKEN')+ expect(calls[1]).toContain('X-Nodeterm-Node-Token: FALLBACK-NODE-TOKEN')+ expect(calls[1]).not.toContain('PRIMARY-NODE-TOKEN')})++ // The other half of the same subtlety: an OLDER instance's endpoint file carries no+ // NODETERM_NODE_TOKEN_DIR line at all. Sourcing it must leave the dir EMPTY (nt_pick_fallback+ // clears it first), not silently keep ours — otherwise the retry reads OUR token dir and hands+ // our kid to a server that never minted it.+ it.skipIf(!shAvailable)('drops our token dir when the adopted endpoint advertises none', () => {+ const home = join(dir, 'home2')+ const bin = join(dir, 'bin2')+ const log = join(dir, 'curl2.log')+ mkdirSync(join(home, '.nodeterm'), { recursive: true })+ mkdirSync(bin, { recursive: true })+ const tokens = join(home, 'tokens')+ mkdirSync(tokens, { recursive: true })+ writeFileSync(join(tokens, 'node-1'), 'PRIMARY-ONLY-TOKEN\n', 'utf8')+ const dead = join(home, '.nodeterm', 'hook-endpoint-oldproject.env')+ writeFileSync(+ dead,+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'dead.sock')}\nNODETERM_HOOK_TOKEN=dead-token\nNODETERM_HOOK_VERSION=1\nNODETERM_NODE_TOKEN_DIR=${tokens}\n`,+ 'utf8'+ )+ // A pre-v2 endpoint file: port + token + version, and no token dir.+ writeFileSync(+ join(home, '.nodeterm', 'hook-endpoint-liveproject.env'),+ 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=live-token\nNODETERM_HOOK_VERSION=1\n',+ 'utf8'+ )+ writeFileSync(+ join(bin, 'curl'),+ `#!/bin/sh\nprintf '%s\\n' "$*" >> ${JSON.stringify(log)}\ncase "$*" in *--unix-socket*) exit 7 ;; esac\nexit 0\n`,+ { encoding: 'utf8', mode: 0o755 }+ )+ const script = join(dir, 'claude2.sh')+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })+ const res = spawnSync('sh', [script], {+ encoding: 'utf8',+ input: '{"hook_event_name":"PermissionRequest"}',+ env: {+ PATH: `${bin}:${process.env.PATH ?? ''}`,+ HOME: home,+ NODETERM_NODE_ID: 'node-1',+ NODETERM_HOOK_ENDPOINT: dead,+ NODETERM_PERM_WAIT_SECS: '1'+ }+ })+ expect(res.status).toBe(0)+ const calls = readFileSync(log, 'utf8').trim().split('\n')+ expect(calls).toHaveLength(2)+ expect(calls[0]).toContain('X-Nodeterm-Node-Token: PRIMARY-ONLY-TOKEN')+ expect(calls[1]).toContain('live-token')+ expect(calls[1]).not.toContain('PRIMARY-ONLY-TOKEN')+ })+})++// The per-node token (task A10). Everything here runs the REAL generated script under /bin/sh+// with the REAL curl against the REAL hook server, and asserts the server's own verdict — the+// only thing that proves the header is on the wire in the shape verifyNodeToken accepts.+//+// One environment fact worth stating once: curl DROPS a header whose value is empty+// (`-H "X: ${empty}"` sends nothing at all). That is exactly the contract we want — the server+// treats an absent header and an empty one identically as `legacy` — so "empty header" below+// means "absent or empty", read as `headers[...] ?? ''`.+describe('managed script presents the per-node token', () => {+ const SECRET = Buffer.alloc(32, 7)+ const FOREIGN_SECRET = Buffer.alloc(32, 9)+ const NODE = 'node-1'+ const sh = spawnSync('sh', ['-c', 'exit 0'])+ const shAvailable = sh.status === 0 && !sh.error++ let dir = ''+ let script = ''+ let raws: { nodeId: string; verified: boolean }[] = []++ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'nt-hook-node-token-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: join(dir, 'userData') }))+ await hookServer.start()+ hookServer.setNodeAuthSecret(SECRET)+ hookServer.setRawListener((_agentId, nodeId, _payload, meta) => {+ raws.push({ nodeId, verified: meta.verified })+ })+ script = join(dir, 'claude.sh')+ writeFileSync(script, buildManagedScript('claude'), { encoding: 'utf8', mode: 0o755 })+ })++ afterAll(() => {+ hookServer.clearNodeAuthSecretForTests()+ hookServer.stop()+ if (dir) rmSync(dir, { recursive: true, force: true })+ })++ beforeEach(() => {+ raws = []+ })++ /** A fresh $HOME per case: the failover scan globs ~/.nodeterm/hook-endpoint-*.env. */+ function newHome(name: string): string {+ const home = join(dir, name)+ mkdirSync(join(home, '.nodeterm'), { recursive: true })+ return home+ }++ function tokenDirWith(name: string, files: Record<string, string>): string {+ const d = join(dir, name)+ mkdirSync(d, { recursive: true })+ for (const [nodeId, token] of Object.entries(files)) {+ writeFileSync(join(d, nodeId), `${token}\n`, { encoding: 'utf8', mode: 0o600 })+ }+ return d+ }++ /**+ * Runs the hook the way claude does. NODETERM_PERM_WAIT_SECS arms the perm-wait branch, whose+ * request POST is in the FOREGROUND — so by the time sh exits the server has already seen it and+ * the assertions are deterministic (the normal branch backgrounds the POST and would race).+ *+ * ASYNC on purpose: `spawnSync` blocks node's event loop, so the hook server in this very+ * process never accepts the connection and every POST "fails" into the failover path.+ */+ function runHook(home: string, env: Record<string, string>): Promise<number> {+ return new Promise((resolve) => {+ const child = spawn('sh', [script], {+ env: {+ PATH: process.env.PATH ?? '',+ HOME: home,+ NODETERM_NODE_ID: NODE,+ NODETERM_HOOK_PORT: String(hookServer.getPort()),+ NODETERM_HOOK_TOKEN: hookServer.getToken(),+ NODETERM_PERM_WAIT_SECS: '1',+ ...env+ },+ stdio: ['pipe', 'ignore', 'ignore']+ })+ child.stdin.end('{"hook_event_name":"PermissionRequest"}')+ child.on('close', (code) => resolve(code ?? -1))+ })+ }++ it.skipIf(!shAvailable)('makes the event verified when this node has a token file', async () => {+ const tokens = tokenDirWith('tokens-good', { [NODE]: nodeAuthToken(SECRET, NODE) })+ expect(await runHook(newHome('home-good'), { NODETERM_NODE_TOKEN_DIR: tokens })).toBe(0)+ expect(raws).toEqual([{ nodeId: NODE, verified: true }])+ })++ it.skipIf(!shAvailable)('reads the dir the ENDPOINT FILE advertises, not just the env', async () => {+ // The v2 endpoint file is how a remote session (and a session that outlived a restart) learns+ // where its token lives — so the read has to happen AFTER the file is sourced.+ const home = newHome('home-endpoint')+ const tokens = tokenDirWith('tokens-endpoint', { [NODE]: nodeAuthToken(SECRET, NODE) })+ const endpoint = join(home, '.nodeterm', 'hook-endpoint-live.env')+ writeFileSync(+ endpoint,+ `NODETERM_HOOK_PORT=${hookServer.getPort()}\nNODETERM_HOOK_TOKEN=${hookServer.getToken()}\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokens}\n`,+ 'utf8'+ )+ expect(+ await runHook(home, {+ NODETERM_HOOK_PORT: '',+ NODETERM_HOOK_TOKEN: '',+ NODETERM_HOOK_ENDPOINT: endpoint+ })+ ).toBe(0)+ expect(raws).toEqual([{ nodeId: NODE, verified: true }])+ })++ it.skipIf(!shAvailable)('still posts — unverified, nothing fails — when there is no token file', async () => {+ const empty = tokenDirWith('tokens-empty', {})+ expect(await runHook(newHome('home-none'), { NODETERM_NODE_TOKEN_DIR: empty })).toBe(0)+ expect(raws).toEqual([{ nodeId: NODE, verified: false }])+ })++ it.skipIf(!shAvailable)('still posts when no token dir is advertised at all (pre-v2 endpoint)', async () => {+ expect(await runHook(newHome('home-nodir'), {})).toBe(0)+ expect(raws).toEqual([{ nodeId: NODE, verified: false }])+ })++ it.skipIf(!shAvailable)('is keyed by $NODETERM_NODE_ID — another node\'s token file is never presented', async () => {+ // The dir holds a token this instance minted for a DIFFERENT node. Presenting it would be+ // `forged` (our kid, wrong mac) and the server would answer 403 with NO listener call — so+ // "exactly one event, unverified" is the assertion that the client looked up by node id+ // rather than picking whatever file was lying there.+ const tokens = tokenDirWith('tokens-other', { 'node-other': nodeAuthToken(SECRET, 'node-other') })+ expect(await runHook(newHome('home-other'), { NODETERM_NODE_TOKEN_DIR: tokens })).toBe(0)+ expect(raws).toEqual([{ nodeId: NODE, verified: false }])+ })++ // THE failover subtlety: after adopting another instance's endpoint file, the token must be+ // RE-READ from that instance's dir. The primary's dir here holds a FOREIGN token (minted from a+ // different secret): if it survived the fallback — because the dir was not cleared, or because+ // the read happened once at the top — the server would see a foreign kid and label the event+ // `legacy`, i.e. verified:false. Only a genuine re-read produces verified:true.+ it.skipIf(!shAvailable)('re-reads the token from the endpoint it FELL BACK to', async () => {+ const home = newHome('home-failover')+ const primaryTokens = tokenDirWith('tokens-primary', {+ [NODE]: nodeAuthToken(FOREIGN_SECRET, NODE)+ })+ const fallbackTokens = tokenDirWith('tokens-fallback', { [NODE]: nodeAuthToken(SECRET, NODE) })+ const dead = join(home, '.nodeterm', 'hook-endpoint-dead.env')+ writeFileSync(+ dead,+ `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'nothing-listens-here.sock')}\nNODETERM_HOOK_TOKEN=dead\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${primaryTokens}\n`,+ 'utf8'+ )+ const live = join(home, '.nodeterm', 'hook-endpoint-live.env')+ writeFileSync(+ live,+ `NODETERM_HOOK_PORT=${hookServer.getPort()}\nNODETERM_HOOK_TOKEN=${hookServer.getToken()}\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${fallbackTokens}\n`,+ 'utf8'+ )+ // `ls -t` picks the freshest candidate — make the dead one unambiguously older.+ const old = Date.now() / 1000 - 600+ utimesSync(dead, old, old)++ expect(+ await runHook(home, {+ NODETERM_HOOK_PORT: '',+ NODETERM_HOOK_TOKEN: '',+ NODETERM_HOOK_ENDPOINT: dead+ })+ ).toBe(0)+ expect(raws).toEqual([{ nodeId: NODE, verified: true }])+ })})describe('buildManagedScript generated shell is syntactically valid', () => {diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex fd3b4cab4..397209b8e 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -77,6 +77,19 @@ export function buildManagedScript('if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then',' . "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :','fi',+ '# The PER-NODE capability. The endpoint file (v2) advertises the directory; the token itself is',+ '# one file in it named for THIS node id — a lookup by name, never a scan, so a session can only',+ '# ever present its own. Absent (pre-v2 endpoint, pre-upgrade session, remote write that failed)',+ '# leaves it EMPTY, and an empty header is exactly what the server reads as `legacy`: the POST',+ '# still happens and nothing about it fails. Kept in a function because the failover below has to',+ '# RE-read it against the dir of the endpoint it adopted.',+ 'nt_read_node_token() {',+ ' nt_node_token=""',+ ' if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then',+ ' nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)',+ ' fi',+ '}',+ 'nt_read_node_token','# Gate on the NODE ID only — it is what marks a nodeterm-spawned session (a user\'s own','# terminal has neither var and exits here, bit-for-bit legacy no-op). The token is NOT','# required at this point: a phone-spawned session whose endpoint was empty/dead at spawn',@@ -111,9 +124,14 @@ export function buildManagedScript('fi','# --- Endpoint failover helpers --------------------------------------------------','# Source the freshest EXISTING candidate endpoint file, skipping the already-tried path',- '# ($1), into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION}. Returns 0 if one was sourced, else 1.',+ '# ($1), into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION} + NODETERM_NODE_TOKEN_DIR. Returns 0 if one',+ '# was sourced, else 1.','# SOCK/PORT are cleared first so a primary-vs-fallback transport switch (e.g. dead SOCK →',- '# live PORT) never leaves the stale transport winning in the re-POST below.',+ '# live PORT) never leaves the stale transport winning in the re-POST below. NODE_TOKEN_DIR is',+ '# cleared for the same reason and one more: our token belongs to the instance that MINTED it, so',+ '# carrying our dir into someone else\'s endpoint would point the read at a directory that server',+ '# cannot verify. Cleared, the newly sourced file sets its own — we then present THAT instance\'s',+ '# token for this node, or (if it has none) nothing at all, which is honest `legacy`.','nt_pick_fallback() {',' nt_tried="$1"',' set --',@@ -133,6 +151,7 @@ export function buildManagedScript(' [ -n "$nt_fresh" ] && [ -r "$nt_fresh" ] || return 1',' NODETERM_HOOK_SOCK=""',' NODETERM_HOOK_PORT=""',+ ' NODETERM_NODE_TOKEN_DIR=""',' . "$nt_fresh" 2>/dev/null || return 1',' return 0','}',@@ -145,6 +164,7 @@ export function buildManagedScript(' --connect-timeout 0.5 --max-time 1.5 \\',' -H "Content-Type: application/x-www-form-urlencoded" \\',' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',+ ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',@@ -154,6 +174,7 @@ export function buildManagedScript(' --connect-timeout 0.5 --max-time 1.5 \\',' -H "Content-Type: application/x-www-form-urlencoded" \\',' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',+ ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',@@ -170,6 +191,10 @@ export function buildManagedScript('nt_send_request() {',' nt_request_post && return 0',' if nt_pick_fallback "$NODETERM_HOOK_ENDPOINT"; then',+ ' # The token is re-read HERE, not once at the top: it must come from the dir the endpoint we',+ ' # just adopted advertises. Reusing the primary\'s would send our kid to a server that cannot',+ ' # judge it — harmless, but also pointless, and it would hide a real identity behind a legacy.',+ ' nt_read_node_token',' nt_request_post',' fi','}',@@ -203,6 +228,7 @@ export function buildManagedScript(' --connect-timeout 0.5 --max-time 1 \\',' -H "Content-Type: application/x-www-form-urlencoded" \\',' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',+ ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',@@ -213,6 +239,7 @@ export function buildManagedScript(' --connect-timeout 0.5 --max-time 1 \\',' -H "Content-Type: application/x-www-form-urlencoded" \\',' -H "X-Nodeterm-Hook-Token: ${NODETERM_HOOK_TOKEN}" \\',+ ' -H "X-Nodeterm-Node-Token: ${nt_node_token}" \\',' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',diff --git a/src/core/agents/hooks/opencode.test.ts b/src/core/agents/hooks/opencode.test.tsindex a016b0285..7bc8e6267 100644--- a/src/core/agents/hooks/opencode.test.ts+++ b/src/core/agents/hooks/opencode.test.ts@@ -282,6 +282,161 @@ describe('generated plugin unix-socket transport', () => {})})+// The per-node token (task A10). The plugin is the one client that is not sh: it must learn the+// token dir from the SAME endpoint file (a new KEY=VALUE line the file's regex has to accept),+// read `<dir>/<nodeId>`, and put the header on BOTH transports — the Bun `fetch` (TCP and unix)+// and the node:http socketPath fallback.+describe('generated plugin presents the per-node token', () => {+ let tokenDir: string+ let sockDir: string++ beforeEach(() => {+ tokenDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-oc-tok-'))+ sockDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-oc-tsock-'))+ fs.writeFileSync(path.join(tokenDir, 'node-1'), 'OPENCODE-NODE-TOKEN\n', { mode: 0o600 })+ })+ afterEach(() => {+ vi.unstubAllEnvs()+ vi.unstubAllGlobals()+ fs.rmSync(tokenDir, { recursive: true, force: true })+ fs.rmSync(sockDir, { recursive: true, force: true })+ })++ async function importPlugin(): Promise<Record<string, (input: unknown) => Promise<void>>> {+ const file = path.join(tmp, `plugin-token-${Math.random().toString(36).slice(2)}.mjs`)+ fs.writeFileSync(file, buildOpencodePlugin())+ const mod = await import(/* @vite-ignore */ `file://${file}`)+ return mod.NodetermStatus()+ }++ /** Fires one event over the plain TCP `fetch` path and returns the headers it sent. */+ async function tcpHeaders(env: Record<string, string>): Promise<Record<string, string>> {+ const calls: Array<Record<string, string>> = []+ vi.stubGlobal('fetch', (_url: string, init: { headers: Record<string, string> }) => {+ calls.push(init.headers)+ return Promise.resolve(new Response())+ })+ vi.stubEnv('NODETERM_NODE_ID', 'node-1')+ vi.stubEnv('NODETERM_HOOK_PORT', '43210')+ vi.stubEnv('NODETERM_HOOK_TOKEN', 'tok')+ vi.stubEnv('NODETERM_HOOK_ENDPOINT', '')+ vi.stubEnv('NODETERM_HOOK_SOCK', '')+ for (const [k, v] of Object.entries(env)) vi.stubEnv(k, v)+ const hooks = await importPlugin()+ await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'ses_1' } } })+ expect(calls.length).toBe(1)+ return calls[0]+ }++ it('sends the token on the fetch path when the file exists', async () => {+ const headers = await tcpHeaders({ NODETERM_NODE_TOKEN_DIR: tokenDir })+ expect(headers['x-nodeterm-node-token']).toBe('OPENCODE-NODE-TOKEN')+ })++ it('sends an EMPTY token — and still posts — when there is no token file', async () => {+ const headers = await tcpHeaders({ NODETERM_NODE_TOKEN_DIR: path.join(tokenDir, 'nope') })+ expect(headers['x-nodeterm-node-token']).toBe('')+ })++ it('sends an empty token when no dir is advertised at all (pre-v2 endpoint)', async () => {+ const headers = await tcpHeaders({})+ expect(headers['x-nodeterm-node-token']).toBe('')+ })++ it('never presents ANOTHER node\'s token file — the path is keyed by the node id', async () => {+ const headers = await tcpHeaders({ NODETERM_NODE_TOKEN_DIR: tokenDir, NODETERM_NODE_ID: 'node-9' })+ expect(headers['x-nodeterm-node-token']).toBe('')+ })++ it('learns the dir from the ENDPOINT FILE (the v2 line), not only the env', async () => {+ const envFile = path.join(sockDir, 'hook-endpoint.env')+ fs.writeFileSync(+ envFile,+ `NODETERM_HOOK_PORT=43210\nNODETERM_HOOK_TOKEN=filetok\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokenDir}\n`+ )+ const headers = await tcpHeaders({ NODETERM_HOOK_ENDPOINT: envFile, NODETERM_HOOK_PORT: '' })+ expect(headers['x-nodeterm-node-token']).toBe('OPENCODE-NODE-TOKEN')+ expect(headers['x-nodeterm-hook-token']).toBe('filetok')+ })++ it('sends it on the Bun unix-fetch path too', async () => {+ const calls: Array<{ init: Record<string, unknown> }> = []+ vi.stubGlobal('Bun', {})+ vi.stubGlobal('fetch', (_url: string, init: Record<string, unknown>) => {+ calls.push({ init })+ return Promise.resolve(new Response())+ })+ vi.stubEnv('NODETERM_NODE_ID', 'node-1')+ vi.stubEnv('NODETERM_HOOK_SOCK', '/tmp/some.sock')+ vi.stubEnv('NODETERM_HOOK_TOKEN', 'tok')+ vi.stubEnv('NODETERM_HOOK_PORT', '')+ vi.stubEnv('NODETERM_HOOK_ENDPOINT', '')+ vi.stubEnv('NODETERM_NODE_TOKEN_DIR', tokenDir)+ const hooks = await importPlugin()+ await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'ses_1' } } })+ expect(calls.length).toBe(1)+ expect((calls[0].init.headers as Record<string, string>)['x-nodeterm-node-token']).toBe(+ 'OPENCODE-NODE-TOKEN'+ )+ })++ it('sends it on the node:http socketPath path too (real unix server)', async () => {+ const { createServer } = await import('node:http')+ const sock = path.join(sockDir, 'hook.sock')+ const received: Array<string> = []+ const server = createServer((req, res) => {+ req.resume()+ req.on('end', () => {+ received.push(String(req.headers['x-nodeterm-node-token'] ?? ''))+ res.end('ok')+ })+ })+ await new Promise<void>((r) => server.listen(sock, r))+ try {+ vi.stubEnv('NODETERM_NODE_ID', 'node-1')+ vi.stubEnv('NODETERM_HOOK_SOCK', sock)+ vi.stubEnv('NODETERM_HOOK_TOKEN', 'socktok')+ vi.stubEnv('NODETERM_HOOK_PORT', '')+ vi.stubEnv('NODETERM_HOOK_ENDPOINT', '')+ vi.stubEnv('NODETERM_NODE_TOKEN_DIR', tokenDir)+ const hooks = await importPlugin()+ await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'ses_1' } } })+ await vi.waitFor(() => expect(received.length).toBe(1))+ expect(received[0]).toBe('OPENCODE-NODE-TOKEN')+ } finally {+ server.close()+ }+ })++ it('posts over node:http with an EMPTY token when the file is missing', async () => {+ const { createServer } = await import('node:http')+ const sock = path.join(sockDir, 'hook-empty.sock')+ const received: Array<string> = []+ const server = createServer((req, res) => {+ req.resume()+ req.on('end', () => {+ received.push(String(req.headers['x-nodeterm-node-token'] ?? ''))+ res.end('ok')+ })+ })+ await new Promise<void>((r) => server.listen(sock, r))+ try {+ vi.stubEnv('NODETERM_NODE_ID', 'node-1')+ vi.stubEnv('NODETERM_HOOK_SOCK', sock)+ vi.stubEnv('NODETERM_HOOK_TOKEN', 'socktok')+ vi.stubEnv('NODETERM_HOOK_PORT', '')+ vi.stubEnv('NODETERM_HOOK_ENDPOINT', '')+ vi.stubEnv('NODETERM_NODE_TOKEN_DIR', path.join(tokenDir, 'nope'))+ const hooks = await importPlugin()+ await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'ses_1' } } })+ await vi.waitFor(() => expect(received.length).toBe(1))+ expect(received[0]).toBe('')+ } finally {+ server.close()+ }+ })+})+describe('opencodeConfigDir honors XDG_CONFIG_HOME', () => {it('lands the plugin under $XDG_CONFIG_HOME/opencode when the (absolute) env var is set', () => {const xdg = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-xdg-'))diff --git a/src/core/agents/hooks/opencode.ts b/src/core/agents/hooks/opencode.tsindex 28681424e..cdcefb791 100644--- a/src/core/agents/hooks/opencode.ts+++ b/src/core/agents/hooks/opencode.ts@@ -60,7 +60,8 @@ export const NodetermStatus = async () => {port: process.env.NODETERM_HOOK_PORT,sock: process.env.NODETERM_HOOK_SOCK,token: process.env.NODETERM_HOOK_TOKEN,- version: process.env.NODETERM_HOOK_VERSION+ version: process.env.NODETERM_HOOK_VERSION,+ tokenDir: process.env.NODETERM_NODE_TOKEN_DIR}try {const file = process.env.NODETERM_HOOK_ENDPOINT@@ -68,19 +69,36 @@ export const NodetermStatus = async () => {for (const line of fs.readFileSync(file, 'utf8').split('\\n')) {const m = line.match(/^NODETERM_HOOK_(PORT|SOCK|TOKEN|VERSION)=(.*)$/)if (m) conf[m[1].toLowerCase()] = m[2]+ // The v2 endpoint line: where this instance keeps per-node tokens. It has its own+ // prefix, so it needs its own match rather than a widened NODETERM_HOOK_ group.+ const d = line.match(/^NODETERM_NODE_TOKEN_DIR=(.*)$/)+ if (d) conf.tokenDir = d[1]}}} catch {}return conf}+ // The PER-NODE capability, read fresh per POST from <dir>/<nodeId> — a lookup by name, never a+ // scan, so this session can only ever present its own. Missing (pre-v2 endpoint, a node whose+ // token was never materialised) is an ordinary state: the header goes out EMPTY and the server+ // reads that as legacy, exactly like every client that predates this.+ const nodeToken = (dir) => {+ try {+ if (!dir) return ''+ return fs.readFileSync(dir + '/' + nodeId, 'utf8').split('\\n')[0].trim()+ } catch {+ return ''+ }+ }const post = (event, extra) => {try {- const { port, sock, token, version } = live()+ const { port, sock, token, version, tokenDir } = live()if (!token || (!sock && !port)) returnconst payload = JSON.stringify({ event, ...extra })const headers = {'content-type': 'application/x-www-form-urlencoded',- 'x-nodeterm-hook-token': token+ 'x-nodeterm-hook-token': token,+ 'x-nodeterm-node-token': nodeToken(tokenDir)}const body ='nodeId=' + encodeURIComponent(nodeId) +diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex c71d313ef..476687026 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -156,6 +156,15 @@ if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then. "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :fi+# The PER-NODE capability: the endpoint file (v2) advertises the directory, the token is one file+# in it named for THIS node id — a lookup by name, never a scan, so a session can only ever present+# its own. Missing (pre-v2 endpoint, a node whose token was never materialised) leaves it empty,+# which the server reads as legacy — the request still goes, exactly as before.+nt_node_token=""+if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then+ nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)+fi+nt_verb="list"if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi@@ -183,12 +192,14 @@ if [ -n "$NODETERM_HOOK_SOCK" ]; then--unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/context-link/$nt_verb" \\-H "Accept: text/plain" \\-H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\+ -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)elif [ -n "$NODETERM_HOOK_PORT" ]; thennt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\"http://127.0.0.1:\${NODETERM_HOOK_PORT}/context-link/$nt_verb" \\-H "Accept: text/plain" \\-H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\+ -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)elserm -f "$nt_out"diff --git a/src/core/context-link.cli.test.ts b/src/core/context-link.cli.test.tsindex 2516dd432..c902b0985 100644--- a/src/core/context-link.cli.test.ts+++ b/src/core/context-link.cli.test.ts@@ -4,7 +4,7 @@// for the behavior it inherited, plus the remote (SSH) case the old shape could not express.import { describe, it, expect, beforeAll, afterAll } from 'vitest'import { execFile } from 'node:child_process'-import { mkdtempSync, writeFileSync, rmSync, chmodSync } from 'node:fs'+import { mkdirSync, mkdtempSync, writeFileSync, rmSync, chmodSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { promisify } from 'node:util'@@ -252,3 +252,85 @@ describe('context-link CLI', () => {expect(out).not.toContain('deploy the app')})})++// The per-node token (task A10). Same shape as every other client: read the file the endpoint+// advertises, keyed by this node's id, present it on BOTH transports.+//+// curl DROPS a header whose value is empty (`-H "X: ${empty}"` sends nothing at all) — which is+// the contract we want, since the server reads absent and empty identically as `legacy`. So+// "empty token" below is read as `headers[...] ?? ''`.+describe('context-link shim presents the per-node token', () => {+ const seen: { path: string; nodeToken: string }[] = []+ let tcp: import('node:http').Server+ let unix: import('node:http').Server+ let tcpPort = 0+ let sock = ''+ let tokenDir = ''++ beforeAll(async () => {+ const http = await import('node:http')+ const handler = (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse): void => {+ req.resume()+ req.on('end', () => {+ seen.push({ path: req.url ?? '', nodeToken: String(req.headers['x-nodeterm-node-token'] ?? '') })+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })+ res.end('ok\n')+ })+ }+ tcp = http.createServer(handler)+ unix = http.createServer(handler)+ await new Promise<void>((r) => tcp.listen(0, '127.0.0.1', r))+ tcpPort = (tcp.address() as { port: number }).port+ sock = join(dir, 'ctx-token-probe.sock')+ await new Promise<void>((r) => unix.listen(sock, r))+ tokenDir = join(dir, 'node-tokens')+ mkdirSync(tokenDir, { recursive: true })+ writeFileSync(join(tokenDir, 'node-A'), 'CONTEXT-NODE-TOKEN\n', { mode: 0o600 })+ })++ afterAll(() => {+ tcp.close()+ unix.close()+ })++ function probe(nodeId: string, env: Record<string, string>): Promise<unknown> {+ return run('/bin/sh', [shim, 'list'], {+ env: { PATH: process.env.PATH ?? '', NODETERM_NODE_ID: nodeId, NODETERM_HOOK_TOKEN: 'x', ...env }+ })+ }++ it('sends it over the TCP branch when the file exists', async () => {+ seen.length = 0+ await probe('node-A', { NODETERM_HOOK_PORT: String(tcpPort), NODETERM_NODE_TOKEN_DIR: tokenDir })+ expect(seen).toEqual([{ path: '/context-link/list', nodeToken: 'CONTEXT-NODE-TOKEN' }])+ })++ it('sends it over the unix-socket branch too (the SSH path)', async () => {+ seen.length = 0+ await probe('node-A', { NODETERM_HOOK_SOCK: sock, NODETERM_NODE_TOKEN_DIR: tokenDir })+ expect(seen).toEqual([{ path: '/context-link/list', nodeToken: 'CONTEXT-NODE-TOKEN' }])+ })++ it('reads the dir out of the endpoint file, not only the env', async () => {+ seen.length = 0+ const endpoint = join(dir, 'ctx-token-endpoint.env')+ writeFileSync(+ endpoint,+ `NODETERM_HOOK_PORT=${tcpPort}\nNODETERM_HOOK_TOKEN=whatever\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokenDir}\n`+ )+ await probe('node-A', { NODETERM_HOOK_ENDPOINT: endpoint })+ expect(seen).toEqual([{ path: '/context-link/list', nodeToken: 'CONTEXT-NODE-TOKEN' }])+ })++ it('still reads, with an empty token, when no token file exists', async () => {+ seen.length = 0+ await probe('node-A', { NODETERM_HOOK_PORT: String(tcpPort), NODETERM_NODE_TOKEN_DIR: join(dir, 'nope') })+ expect(seen).toEqual([{ path: '/context-link/list', nodeToken: '' }])+ })++ it('never presents ANOTHER node\'s token file — the path is keyed by $NODETERM_NODE_ID', async () => {+ seen.length = 0+ await probe('node-Z', { NODETERM_HOOK_PORT: String(tcpPort), NODETERM_NODE_TOKEN_DIR: tokenDir })+ expect(seen).toEqual([{ path: '/context-link/list', nodeToken: '' }])+ })+})diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.tsindex 8cfb32cc5..45ea2b1ae 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -229,6 +229,15 @@ if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then. "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :fi+# The PER-NODE capability: the endpoint file (v2) advertises the directory, the token is one file+# in it named for THIS node id — a lookup by name, never a scan, so a session can only ever present+# its own. Missing (pre-v2 endpoint, a node whose token was never materialised) leaves it empty,+# which the server reads as legacy — the request still goes, exactly as before.+nt_node_token=""+if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then+ nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)+fi+nt_verb="list"if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi@@ -266,12 +275,14 @@ if [ -n "$NODETERM_HOOK_SOCK" ]; then--unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/control/$nt_verb" \\-H "Accept: text/plain" \\-H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\+ -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)elif [ -n "$NODETERM_HOOK_PORT" ]; thennt_code=$(curl -sS -o "$nt_out" -w '%{http_code}' -X POST \\"http://127.0.0.1:\${NODETERM_HOOK_PORT}/control/$nt_verb" \\-H "Accept: text/plain" \\-H "X-Nodeterm-Hook-Token: \${NODETERM_HOOK_TOKEN}" \\+ -H "X-Nodeterm-Node-Token: \${nt_node_token}" \\--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)elserm -f "$nt_out"diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.tsindex e421535b9..86458d903 100644--- a/src/main/canvas-control-shim.test.ts+++ b/src/main/canvas-control-shim.test.ts@@ -242,6 +242,99 @@ describe('canvas-control shim over a unix socket', () => {})})+// The per-node token (task A10). The shim's job is only to PRESENT it: read the file the endpoint+// advertises, keyed by this node's id, and put it on every request — on BOTH transports.+//+// One environment fact, stated once: curl DROPS a header whose value is empty (`-H "X: ${empty}"`+// sends nothing at all). That is the contract we want — absent and empty are the same `legacy` to+// the server — so "empty header" below is read as `headers[...] ?? ''`.+describe('canvas-control shim presents the per-node token', () => {+ const seen: { path: string; nodeToken: string }[] = []+ let tcp: import('node:http').Server+ let unix: import('node:http').Server+ let tcpPort = 0+ let sock = ''+ let tokenDir = ''++ beforeAll(async () => {+ const http = await import('node:http')+ const handler = (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse): void => {+ req.resume()+ req.on('end', () => {+ seen.push({+ path: req.url ?? '',+ nodeToken: String(req.headers['x-nodeterm-node-token'] ?? '')+ })+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })+ res.end('ok\n')+ })+ }+ tcp = http.createServer(handler)+ unix = http.createServer(handler)+ await new Promise<void>((r) => tcp.listen(0, '127.0.0.1', r))+ tcpPort = (tcp.address() as { port: number }).port+ sock = path.join(dir, 'token-probe.sock')+ await new Promise<void>((r) => unix.listen(sock, r))+ tokenDir = path.join(dir, 'node-tokens')+ fs.mkdirSync(tokenDir, { recursive: true })+ fs.writeFileSync(path.join(tokenDir, 'node-1'), 'CANVAS-NODE-TOKEN\n', { mode: 0o600 })+ })++ afterAll(() => {+ tcp.close()+ unix.close()+ })++ it('sends it over the TCP branch when the file exists', async () => {+ seen.length = 0+ await callShim(['list'], { NODETERM_HOOK_PORT: String(tcpPort), NODETERM_NODE_TOKEN_DIR: tokenDir })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: 'CANVAS-NODE-TOKEN' }])+ })++ it('sends it over the unix-socket branch too (the SSH path)', async () => {+ seen.length = 0+ await callShim(['list'], {+ NODETERM_HOOK_PORT: '',+ NODETERM_HOOK_SOCK: sock,+ NODETERM_NODE_TOKEN_DIR: tokenDir+ })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: 'CANVAS-NODE-TOKEN' }])+ })++ it('reads the dir out of the endpoint file, not only the env', async () => {+ seen.length = 0+ const endpoint = path.join(dir, 'token-endpoint.env')+ fs.writeFileSync(+ endpoint,+ `NODETERM_HOOK_PORT=${tcpPort}\nNODETERM_HOOK_TOKEN=whatever\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokenDir}\n`+ )+ await callShim(['list'], {+ NODETERM_HOOK_PORT: '',+ NODETERM_HOOK_TOKEN: '',+ NODETERM_HOOK_ENDPOINT: endpoint+ })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: 'CANVAS-NODE-TOKEN' }])+ })++ it('still calls, with an empty token, when no token file exists', async () => {+ seen.length = 0+ const empty = path.join(dir, 'no-tokens')+ fs.mkdirSync(empty, { recursive: true })+ await callShim(['list'], { NODETERM_HOOK_PORT: String(tcpPort), NODETERM_NODE_TOKEN_DIR: empty })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: '' }])+ })++ it('never presents ANOTHER node\'s token file — the path is keyed by $NODETERM_NODE_ID', async () => {+ seen.length = 0+ await callShim(['list'], {+ NODETERM_HOOK_PORT: String(tcpPort),+ NODETERM_NODE_TOKEN_DIR: tokenDir,+ NODETERM_NODE_ID: 'node-9'+ })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: '' }])+ })+})+describe('parseControlBody', () => {it('reads the shim dialect: nodeId plus arg.<name> fields', () => {expect(