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(ssh): materialise per-node tokens on the host over stdin, never argv

Claude Code63f93a6b904e
diff --git a/src/core/agents/node-token-service.test.ts b/src/core/agents/node-token-service.test.ts
index 280aa6849..4d3f44398 100644
--- a/src/core/agents/node-token-service.test.ts
+++ b/src/core/agents/node-token-service.test.ts
@@ -12,7 +12,11 @@ import {
ensureNodeToken,
sweepNodeToken,
refreshNodeTokens,
- nodeIdFoldKey
+ nodeIdFoldKey,
+ nodeIdsForCanvas,
+ remoteNodeTokenMinter,
+ setRemoteNodeTokenWriter,
+ ensureRemoteNodeToken
} from './node-token-service'
let dir = ''
@@ -174,3 +178,68 @@ describe('node token service — writes once, not on every persist', () => {
expect(fs.existsSync(path.join(nodeTokenDir(), 'node-1'))).toBe(true)
})
})
+
+/**
+ * The REMOTE (SSH) materialiser's half. The host is a different filesystem with a different
+ * writer, but it must be judged by the SAME rules — otherwise a hostile `project.json` bypasses
+ * the local guards simply by living on an SSH project.
+ */
+describe('node token service — the remote (SSH) minter', () => {
+ it('returns null when there is no secret, so a connect spends no round-trips at all', () => {
+ hookServer.clearNodeAuthSecretForTests()
+ initNodeTokens({ canvases: () => canvases })
+ expect(remoteNodeTokenMinter()).toBeNull()
+ })
+
+ it('mints the same token the local writer would file, without touching the local disk', async () => {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => canvases })
+ const before = fs.readFileSync(path.join(nodeTokenDir(), 'node-1'), 'utf8')
+ const mint = remoteNodeTokenMinter()!
+ expect(`${mint('node-1')}\n`).toBe(before)
+ })
+
+ it('refuses a case-folding collision on the remote path too (empty ⇒ the caller sweeps)', async () => {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => [{ id: 'p1', nodes: [{ id: 'Node-1' }, { id: 'node-1' }] }] })
+ const mint = remoteNodeTokenMinter()!
+ expect(mint('Node-1')).toBe('')
+ expect(mint('node-1')).toBe('')
+ expect(mint('node-7')).not.toBe('')
+ })
+
+ it('refuses an unsafe id', async () => {
+ hookServer.setNodeAuthSecret(await loadOrCreateNodeAuthSecret())
+ initNodeTokens({ canvases: () => canvases })
+ const mint = remoteNodeTokenMinter()!
+ expect(mint('..')).toBe('')
+ expect(mint('../x')).toBe('')
+ })
+
+ it('nodeIdsForCanvas returns one project’s node ids, de-duplicated, and nothing for a stranger', () => {
+ initNodeTokens({
+ canvases: () => [
+ { id: 'p1', nodes: [{ id: 'node-1' }, { id: 'node-1' }, { id: 'node-2' }] },
+ { id: 'p2', nodes: [{ id: 'node-3' }] }
+ ]
+ })
+ expect(nodeIdsForCanvas('p1')).toEqual(['node-1', 'node-2'])
+ expect(nodeIdsForCanvas('p2')).toEqual(['node-3'])
+ expect(nodeIdsForCanvas('nope')).toEqual([])
+ })
+
+ it('the spawn-path writer is a no-op until one is registered, and never throws', () => {
+ setRemoteNodeTokenWriter(null)
+ expect(() => ensureRemoteNodeToken('/cm.sock', 'node-1')).not.toThrow()
+ const seen: string[][] = []
+ setRemoteNodeTokenWriter((cp, id) => seen.push([cp, id]))
+ ensureRemoteNodeToken('/cm.sock', 'node-1')
+ expect(seen).toEqual([['/cm.sock', 'node-1']])
+ // a writer that throws must not reach the pty spawn that called it
+ setRemoteNodeTokenWriter(() => {
+ throw new Error('ssh gone')
+ })
+ expect(() => ensureRemoteNodeToken('/cm.sock', 'node-1')).not.toThrow()
+ setRemoteNodeTokenWriter(null)
+ })
+})
diff --git a/src/core/agents/node-token-service.ts b/src/core/agents/node-token-service.ts
index d6409bd8b..cc72a8336 100644
--- a/src/core/agents/node-token-service.ts
+++ b/src/core/agents/node-token-service.ts
@@ -2,7 +2,7 @@ import { hookServer } from './hook-server'
import { nodeAuthToken, isSafeNodeId } from './node-auth-token'
import { writeNodeTokenFile, sweepNodeTokenFile, materialisedNodes } from './node-token-files'
-type Canvases = () => Array<{ nodes: Array<{ id: string }> }>
+type Canvases = () => Array<{ id?: string; nodes: Array<{ id: string }> }>
let canvases: Canvases = () => []
/**
@@ -120,6 +120,64 @@ export function sweepNodeToken(nodeId: string): void {
sweepNodeTokenFile(nodeId)
}
+/** The node ids of ONE persisted canvas. The remote materialiser is per SSH project, not global:
+ * a host only ever needs tokens for the nodes that actually run there. */
+export function nodeIdsForCanvas(projectId: string): string[] {
+ const ids: string[] = []
+ for (const c of canvases()) if (c.id === projectId) for (const n of c.nodes ?? []) ids.push(n.id)
+ return [...new Set(ids)]
+}
+
+/**
+ * A minting function for the REMOTE materialiser (`RemoteHooks.writeNodeTokens`), or null when this
+ * instance has no secret at all — which is the whole "legacy everywhere" mode, and the caller then
+ * spends no ssh round-trips discovering it one node at a time.
+ *
+ * The secret is captured ONCE and the closure reused for the whole pass, so every token in one
+ * connect comes from one secret (a rotation mid-pass would otherwise write a mixed dir, half of it
+ * unverifiable). '' is a refusal the caller sweeps for — and the case-fold refusal is applied HERE,
+ * not left to the remote side: an APFS host would otherwise let a hostile `project.json` bypass the
+ * local guard simply by putting the colliding pair on an SSH project.
+ */
+export function remoteNodeTokenMinter(): ((nodeId: string) => string) | null {
+ const secret = hookServer.nodeAuthSecretOrNull()
+ if (!secret) return null
+ return (nodeId: string): string => {
+ const group = collidingGroups([...canvasNodeIds(), nodeId]).get(nodeId)
+ if (group) {
+ warnCollision(group)
+ return ''
+ }
+ return nodeAuthToken(secret, nodeId)
+ }
+}
+
+/**
+ * The SPAWN-time leg of the remote materialiser: a node created AFTER its project connected has no
+ * token on the host until the next reconnect, which for a long-lived SSH project is "never".
+ *
+ * It is a registered writer rather than a direct call because the mechanism lives in main
+ * (`SshProjectManager` owns the ControlMaster runner) while the spawn happens in core, and core
+ * must keep building without electron. Unregistered — the Server Edition, every test — it is a
+ * no-op, which is the correct behavior there too.
+ */
+type RemoteNodeTokenWriter = (controlPath: string, nodeId: string) => void
+let remoteWriter: RemoteNodeTokenWriter | null = null
+
+export function setRemoteNodeTokenWriter(writer: RemoteNodeTokenWriter | null): void {
+ remoteWriter = writer
+}
+
+/** Fire-and-forget, fail-open: a token that cannot be written costs the node `legacy`, never its
+ * terminal. Nothing here may throw into a pty spawn. */
+export function ensureRemoteNodeToken(controlPath: string, nodeId: string): void {
+ try {
+ remoteWriter?.(controlPath, nodeId)
+ } catch {
+ /* fail-open */
+ }
+}
+
/**
* Wired to `onPersist`, which fires on every canvas LOAD and every canvas SAVE. Rewriting every
* token for every node in every project there cost a ~375-node workspace ~2000 synchronous syscalls
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 32158c741..26a387409 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -58,7 +58,7 @@ import {
forgetCodexThreadIdentitiesForNode,
installCodexLauncher
} from './codex-identity-proxy'
-import { ensureNodeToken, sweepNodeToken } from './agents/node-token-service'
+import { ensureNodeToken, ensureRemoteNodeToken, sweepNodeToken } from './agents/node-token-service'
import { hasSharedIdentity, type AgentId } from '../shared/agents/config'
// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which
@@ -1959,6 +1959,14 @@ export class PtyManager {
const remoteSsh = options.sshRemote && options.persistKey ? findSsh() : null
if (options.sshRemote && options.persistKey && remoteSsh) {
file = remoteSsh
+ // The remote twin of the local `ensureNodeToken` above: materialise THIS node's token on the
+ // host before the attach. The connect path writes one for every node the canvas had AT
+ // CONNECT; a node created afterwards would otherwise wait for the next reconnect — for a
+ // long-lived SSH project, forever — and spend that whole time on `legacy`.
+ // Fire-and-forget and fail-open by construction (see ensureRemoteNodeToken): the hook script
+ // re-reads the file at every event, so a token that lands a moment after the attach is in
+ // time for everything that matters, and one that never lands costs only the verified label.
+ ensureRemoteNodeToken(options.sshRemote.controlPath, options.persistKey)
// Route this ssh child's agent lookups at the APP-PRIVATE ssh-agent when main is running one
// (published via env because core cannot import main's ssh-agent.ts). Matters when the
// ControlMaster is down: `childArgs` uses `ControlMaster=auto`, so this child authenticates
diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.ts
index 6e9446741..3492ba241 100644
--- a/src/core/pty-shadow.test.ts
+++ b/src/core/pty-shadow.test.ts
@@ -10,6 +10,7 @@ import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { REAP_IDLE_MS, REAP_SWEEP_MS } from './pty-reap'
import type { ControlSpawn } from './tmux-control-client'
import type { PtyDevices } from './pty-devices'
+import { setRemoteNodeTokenWriter } from './agents/node-token-service'
/**
* SHADOW CLIENTS: a tmux control-mode (`-C`) client over plain pipes, attached to the tmux session
@@ -512,6 +513,30 @@ describe('control-mode shadow clients for released sessions', () => {
expect(control.calls).toHaveLength(0)
})
+ it('materialises the spawning node token ON THE HOST (a node created after connect)', async () => {
+ // The connect writes a token for every node the canvas had THEN. Without this leg a node
+ // created afterwards has no token file on the host until the next reconnect — which for a
+ // long-lived SSH project is never — and spends that whole time on `legacy`.
+ const seen: string[][] = []
+ setRemoteNodeTokenWriter((controlPath, nodeId) => seen.push([controlPath, nodeId]))
+ try {
+ await tmuxManager()
+ await fake.handlers[IPC.ptyCreate](ALICE, {
+ cols: 80,
+ rows: 24,
+ persistKey: 'node-r2',
+ sshRemote: { conn: { host: 'h1', user: 'u' }, controlPath: '/tmp/cm', remoteCwd: '/srv/app' }
+ })
+ expect(seen).toEqual([['/tmp/cm', 'node-r2']])
+ // ...and a LOCAL node never asks a host for anything.
+ seen.length = 0
+ await fake.handlers[IPC.ptyCreate](ALICE, { cols: 80, rows: 24, persistKey: 'node-local' })
+ expect(seen).toEqual([])
+ } finally {
+ setRemoteNodeTokenWriter(null)
+ }
+ })
+
it('returns null (never rejects) when the control client cannot even be spawned', async () => {
const m = await tmuxManager()
const { sessionId } = await create(ALICE)
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 01aae924a..9053fed12 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -466,3 +466,128 @@ describe('RemoteHooks.installContextLink', () => {
await expect(new RemoteHooks({ run }).installContextLink(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()
})
})
+
+/**
+ * The per-node token files ON THE HOST. Until this existed, `control-master.ts` advertised
+ * `$HOME/.nodeterm/node-tokens` in the endpoint file and NOTHING ever wrote it, so every remote
+ * node was permanently `legacy`.
+ */
+describe('RemoteHooks.writeNodeTokens', () => {
+ /** A stand-in for `nodeAuthToken(secret, id)` — the shape matters (kid.mac), not the bytes. */
+ const mint = (id: string): string => `kid12345.mac-of-${id}`
+
+ function tokenHarness(opts: { code?: number; throws?: boolean } = {}) {
+ const calls: { args: string[]; stdin?: string; cmd: string }[] = []
+ const run = vi.fn(async (args: string[], stdin?: string) => {
+ const cmd = args.join(' ')
+ calls.push({ args, stdin, cmd })
+ if (opts.throws) throw new Error('ssh died')
+ return { code: opts.code ?? 0, stdout: '' }
+ })
+ return { rh: new RemoteHooks({ run }), calls, run }
+ }
+
+ it('writes every token through STDIN — a credential never rides an ssh command line', async () => {
+ const { rh, calls } = tokenHarness()
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)
+ // THE INVARIANT: the host's process table is readable by its other users, so not one arg of
+ // not one child ssh may contain a token — not the write, not the mkdir, not anything.
+ for (const c of calls)
+ for (const a of c.args) {
+ expect(a).not.toContain('mac-of-node-1')
+ expect(a).not.toContain('mac-of-node-2')
+ }
+ const writes = calls.filter((c) => c.cmd.includes('cat >'))
+ expect(writes).toHaveLength(2)
+ expect(writes[0].cmd).toContain("cat > '/home/u/.nodeterm/node-tokens/node-1'")
+ // ...and the token is on stdin, newline-terminated (the client reads it with `head -n 1`).
+ expect(writes[0].stdin).toBe(`${mint('node-1')}\n`)
+ expect(writes.at(-1)?.stdin).toBe(`${mint('node-2')}\n`)
+ })
+
+ it('creates the dir and each file under umask 077 (0700 dir, 0600 files)', async () => {
+ const { rh, calls } = tokenHarness()
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ const mkdir = calls.find((c) => c.cmd.includes('mkdir -p'))
+ expect(mkdir?.cmd).toContain('umask 077')
+ expect(mkdir?.cmd).toContain("'/home/u/.nodeterm/node-tokens'")
+ for (const w of calls.filter((c) => c.cmd.includes('cat >'))) expect(w.cmd).toContain('umask 077')
+ })
+
+ it('fails open when the host refuses (exit 1) — the connect is never at risk', async () => {
+ const { rh, calls } = tokenHarness({ code: 1 })
+ await expect(
+ rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ ).resolves.toBeUndefined()
+ // A dir we could not create is not a dir we write tokens into.
+ expect(calls.some((c) => c.cmd.includes('cat >'))).toBe(false)
+ })
+
+ it('fails open when the runner throws', async () => {
+ const { rh } = tokenHarness({ throws: true })
+ await expect(
+ rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)
+ ).resolves.toBeUndefined()
+ })
+
+ it('fails open per node: one unwritable token does not cost the others theirs', async () => {
+ const calls: string[] = []
+ const run = vi.fn(async (args: string[]) => {
+ const cmd = args.join(' ')
+ calls.push(cmd)
+ if (cmd.includes('node-1')) throw new Error('EACCES')
+ return { code: 0, stdout: '' }
+ })
+ await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)
+ expect(calls.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ })
+
+ it('an unsafe node id reaches no path and no command AT ALL', async () => {
+ // A hostile project.json supplies these; `..` under the token dir resolves to its PARENT.
+ const { rh, calls } = tokenHarness()
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['../x', '..', '.', 'a b', ''], mint)
+ expect(calls).toHaveLength(0)
+ })
+
+ it('still serves the safe ids when a hostile one rides along', async () => {
+ const { rh, calls } = tokenHarness()
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['../x', 'node-1'], mint)
+ const writes = calls.filter((c) => c.cmd.includes('cat >'))
+ expect(writes).toHaveLength(1)
+ expect(writes[0].cmd).toContain("node-tokens/node-1'")
+ expect(calls.every((c) => !c.cmd.includes('../x'))).toBe(true)
+ })
+
+ it('refuses a host $HOME that is not a plain path — no interpolation, fail open', async () => {
+ // `printf %s "$HOME"` is the host's answer, i.e. DATA. A newline in it is a command separator
+ // in every `mkdir -p ${remoteDir}` this file builds.
+ const { rh, calls } = tokenHarness()
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u\ntouch /tmp/pwn', ['node-1'], mint)
+ expect(calls).toHaveLength(0)
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/$(id)', ['node-1'], mint)
+ expect(calls).toHaveLength(0)
+ await rh.writeNodeTokens(conn, '/s.sock', '', ['node-1'], mint)
+ expect(calls).toHaveLength(0)
+ })
+
+ it('sweeps a token the minter REFUSES (case-fold collision) instead of leaving it on the host', async () => {
+ // The refusal is the local sweep's remote twin: a file an earlier connect wrote for a
+ // colliding id is exactly the token its twin would read.
+ const { rh, calls } = tokenHarness()
+ const refusing = (id: string): string => (id === 'Node-1' ? '' : mint(id))
+ await rh.writeNodeTokens(conn, '/s.sock', '/home/u', ['Node-1', 'node-2'], refusing)
+ expect(calls.some((c) => c.cmd.includes("rm -f '/home/u/.nodeterm/node-tokens/Node-1'"))).toBe(true)
+ expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/Node-1'"))).toBe(false)
+ expect(calls.some((c) => c.cmd.includes("cat > '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ })
+})
+
+describe('RemoteHooks.setup — the host $HOME is data, not truth', () => {
+ it('refuses a $HOME carrying shell syntax and installs nothing', async () => {
+ const { rh, calls } = harness({ responses: { 'printf %s "$HOME"': '/home/u\ntouch /tmp/pwn' } })
+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
+ expect(res).toBeNull()
+ // Only the $HOME probe itself ran — nothing interpolated the answer.
+ expect(calls).toHaveLength(1)
+ })
+})
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index 93f081b2b..c6e44d895 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -8,6 +8,7 @@
import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'
import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@shared/agents/hook-events'
import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'
+import { isSafeNodeId } from '../../core/agents/node-auth-token'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
/**
@@ -53,6 +54,36 @@ export interface RemoteRunner {
run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>
}
+/** Generous ceiling on a host-reported `$HOME` — longer than any real path, short enough to bound. */
+const REMOTE_HOME_MAX = 4096
+
+/**
+ * Is a host-reported `$HOME` safe to build remote commands from?
+ *
+ * `printf %s "$HOME"` returns DATA, not truth, and this file interpolates the answer into remote
+ * command lines — several of them still UNQUOTED (`mkdir -p ${remoteDir}`). A `$HOME` holding a
+ * newline is therefore a command separator, and one holding `$(…)`/backticks is a substitution, on
+ * a host we are running as the user. A host can set `$HOME` to whatever it likes.
+ *
+ * Deliberately far narrower than "what a filesystem allows": ordinary path characters only. The
+ * cost of a false rejection is fail-open (no per-node token → `legacy`, the designed state; or, in
+ * `setup`, no hooks at all — which is why the rejection is LOUD there), and the cost of a false
+ * acceptance is remote code execution. A host whose home directory contains a non-ASCII character
+ * is refused by that trade, which is the known and accepted price.
+ *
+ * It judges the EXACT string the caller holds — leading/trailing whitespace is a rejection, not
+ * something quietly stripped (same rule as `isSafeRemoteGrokHome`): trimming here would return
+ * `true` about a value whose embedded newline is still on the command line the caller then builds.
+ */
+export function isSafeRemoteHome(home: string): boolean {
+ return (
+ typeof home === 'string' &&
+ home.length > 0 &&
+ home.length <= REMOTE_HOME_MAX &&
+ /^[\w./ -]+$/.test(home)
+ )
+}
+
// Per-agent remote install targets (JSON-settings agents merged via mergeManagedHook). Codex
// is installed separately (installCodexRemote) because it needs a hooks.json merge PLUS a
// config.toml trust write — see that method. Grok is separate too (installGrokRemote): its config
@@ -93,6 +124,17 @@ export class RemoteHooks {
const { code, stdout } = await this.r.run(childArgs(conn, controlPath, 'printf %s "$HOME"'))
const home = stdout.trim()
if (code !== 0 || !home) return null // fail-open: nothing else would work
+ // The host's answer is interpolated into every remote path below, several of them still
+ // unquoted — so a `$HOME` that is not a plain path is refused OUTRIGHT rather than escaped
+ // case by case. LOUD, because unlike the rest of this file's fail-open steps the user loses
+ // hooks entirely and there would otherwise be nothing anywhere saying why.
+ if (!isSafeRemoteHome(home)) {
+ console.warn(
+ '[remote-hooks] the host reported a $HOME that is not a plain path — refusing to build ' +
+ 'remote commands from it; this host runs without status hooks'
+ )
+ return null
+ }
const remoteDir = `${home}/.nodeterm`
const sock = `${remoteDir}/hook-${projectId}.sock`
// PER-PROJECT endpoint file. The sock is already per-project, but the endpoint file used to
@@ -166,6 +208,93 @@ export class RemoteHooks {
}
}
+ /**
+ * Materialise this instance's per-node tokens ON THE HOST — `<home>/.nodeterm/node-tokens/<id>`,
+ * 0600 in a 0700 dir, exactly the layout the endpoint file already advertises as
+ * `NODETERM_NODE_TOKEN_DIR` and the managed script already reads (`head -n 1 "$DIR/$NODE_ID"`).
+ * Nothing wrote it before this, which is why every remote node was permanently `legacy`.
+ *
+ * THE INVARIANT — a credential NEVER rides an ssh command line. The host's process table is
+ * readable by its OTHER users (`ps` shows full argv), and a remote command line is argv on both
+ * ends. So the token goes on STDIN, as the endpoint-file write above already does, and only the
+ * (non-secret) path is interpolated. Do not "simplify" this into `printf %s <token> > file`.
+ *
+ * Fail-open per node AND overall. A connect that died over an identity file would be a far worse
+ * regression than an unverified remote node: a node with no token file presents an empty header,
+ * which the server reads as `legacy` — the designed state, not an outage.
+ *
+ * `mint` returning '' is a REFUSAL (no secret, or the case-fold collision guard), and a refusal
+ * SWEEPS: an earlier connect's file for that id is precisely the token its colliding twin would
+ * read, so leaving it in place is the attack the local `node-token-service` sweeps for.
+ *
+ * KNOWN LIMITATION — the dir is flat, i.e. per HOST ACCOUNT, not per nodeterm instance. Two
+ * instances driving the same host+user (two desktops sharing a deploy account, or a desktop
+ * whose SSH project points at a host that also runs a headless Server Edition under the same
+ * $HOME) mint with DIFFERENT secrets and overwrite each other's files. The loser's sessions then
+ * present a token carrying the winner's kid, which `verifyNodeToken` reads as `legacy` — never as
+ * another node, and never as `forged`. So the cost is a silent drop to the fail-open state, not a
+ * mis-verification. Scoping the dir as `node-tokens/<kid>/<id>` would close it and needs NO client
+ * change (the client uses whatever dir the endpoint file names) — it is left out here only to keep
+ * the remote layout identical to the local one; see the task A11 report.
+ */
+ async writeNodeTokens(
+ conn: SshConnection,
+ controlPath: string,
+ home: string,
+ nodeIds: readonly string[],
+ mint: (nodeId: string) => string
+ ): Promise<void> {
+ try {
+ if (!isSafeRemoteHome(home)) return
+ const dir = `${home}/.nodeterm/node-tokens`
+ // Gate BEFORE any path join: the ids come from `project.json`, which travels in shared and
+ // cloned repos, and `..` under the token dir resolves to its PARENT. De-duplicated so a
+ // canvas listing one node twice is one write, not two.
+ const ids = [...new Set(nodeIds)].filter((id) => isSafeNodeId(id))
+ // Mint FIRST, so a set with nothing to do costs no round-trip at all (and an all-unsafe
+ // list costs not one remote command).
+ const writes: { id: string; token: string }[] = []
+ const sweeps: string[] = []
+ for (const id of ids) {
+ let token = ''
+ try {
+ token = mint(id)
+ } catch {
+ token = '' // a minter that throws is a refusal, not a crashed connect
+ }
+ if (token) writes.push({ id, token })
+ else sweeps.push(id)
+ }
+ for (const id of sweeps) {
+ await this.r
+ .run(childArgs(conn, controlPath, `rm -f ${posixQuote(`${dir}/${id}`)}`))
+ .catch(() => {})
+ }
+ if (!writes.length) return
+ // `umask 077` so the dir is 0700 the moment it exists; `chmod 700` because an EXISTING dir
+ // keeps its old mode (the same belt-and-braces the local writer applies).
+ const mk = await this.r.run(
+ childArgs(conn, controlPath, `umask 077; mkdir -p ${posixQuote(dir)} && chmod 700 ${posixQuote(dir)}`)
+ )
+ if (mk.code !== 0) return // no dir ⇒ no files; the nodes stay `legacy`
+ for (const { id, token } of writes) {
+ const file = posixQuote(`${dir}/${id}`)
+ try {
+ await this.r.run(
+ // `cat >` TRUNCATES an existing file and keeps its old mode, so the chmod is not
+ // redundant with the umask: it is what re-narrows a file some earlier state left wide.
+ childArgs(conn, controlPath, `umask 077; cat > ${file} && chmod 600 ${file}`),
+ `${token}\n` // newline-terminated: the client reads it with `head -n 1`
+ )
+ } catch {
+ /* fail-open per node: one unwritable token must not cost the others theirs */
+ }
+ }
+ } catch {
+ /* fail-open: an identity file must never be able to fail a connect */
+ }
+ }
+
/**
* Install the managed codex status hook on the REMOTE host: write `codex.sh`, merge our handler
* into `~/.codex/hooks.json`, and — the part that makes codex different from claude/gemini — write
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 989c5d9ed..2dc0f6e04 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -1970,3 +1970,92 @@ describe('lastSshErrorLine', () => {
expect(out.length).toBeLessThanOrEqual(201)
})
})
+
+/**
+ * Remote nodes were permanently `legacy`: the endpoint file advertised
+ * `$HOME/.nodeterm/node-tokens` and nothing ever wrote it. The connect is where that dir gets
+ * filled, on exactly the terms the canvas-control install already uses.
+ */
+describe('SshProjectManager — per-node tokens on the host', () => {
+ /** A runner for a connect whose reverse hook tunnel VERIFIES (curl answers 204), which is what
+ * sets `hookEndpointPath` — the gate the token write shares with the canvas-control install. */
+ function verifiedRun() {
+ return vi.fn(async (args: string[], _stdin?: string) => {
+ const j = args.join(' ')
+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (j.includes('%{http_code}')) return { code: 0, stdout: '204' }
+ return { code: 0, stdout: '' }
+ })
+ }
+ /** The connect fires the write without awaiting it (best-effort setup must not delay a
+ * terminal), so the assertions run after the microtask queue drains. */
+ const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 0))
+
+ afterEach(() => vi.restoreAllMocks())
+
+ it('materialises every canvas node id on the host, tokens on STDIN', async () => {
+ const run = verifiedRun()
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ nodeIdsForProject: (id) => (id === 'p1' ? ['node-1', 'node-2'] : []),
+ nodeTokenMinter: () => (nodeId) => `kid12345.mac-of-${nodeId}`
+ })
+ await mgr.connect('p1', conn)
+ await settle()
+ const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
+ expect(cmds.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-1'"))).toBe(true)
+ expect(cmds.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-2'"))).toBe(true)
+ // never on a command line — the host's process table is readable by its other users.
+ expect(cmds.some((c) => c.includes('mac-of-node-1'))).toBe(false)
+ const write = run.mock.calls.find(([a]) =>
+ (a as string[]).join(' ').includes("node-tokens/node-1'")
+ )
+ expect(write?.[1]).toBe('kid12345.mac-of-node-1\n')
+ })
+
+ it('writes nothing when this instance has no node-auth secret (legacy everywhere)', async () => {
+ const run = verifiedRun()
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ nodeIdsForProject: () => ['node-1'],
+ nodeTokenMinter: () => null
+ })
+ await mgr.connect('p1', conn)
+ await settle()
+ expect(run.mock.calls.some(([a]) => (a as string[]).join(' ').includes('node-tokens'))).toBe(false)
+ })
+
+ it('writeNodeTokenForNode covers a node created AFTER the connect', async () => {
+ const run = verifiedRun()
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ nodeIdsForProject: () => [],
+ nodeTokenMinter: () => (nodeId) => `kid12345.mac-of-${nodeId}`
+ })
+ const { controlPath } = await mgr.connect('p1', conn)
+ await settle()
+ run.mockClear()
+ await mgr.writeNodeTokenForNode(controlPath, 'node-9')
+ const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
+ expect(cmds.some((c) => c.includes("cat > '/home/u/.nodeterm/node-tokens/node-9'"))).toBe(true)
+ // an unknown control path is a no-op, not a throw
+ run.mockClear()
+ await expect(mgr.writeNodeTokenForNode('/nope.sock', 'node-9')).resolves.toBeUndefined()
+ expect(run.mock.calls).toHaveLength(0)
+ })
+})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index ef11f1560..da0be4f89 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -31,6 +31,11 @@ import {
import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'
import { RemoteHooks } from './remote-hooks'
import { hookServer } from '../../core/agents/hook-server'
+import {
+ nodeIdsForCanvas,
+ remoteNodeTokenMinter,
+ setRemoteNodeTokenWriter
+} from '../../core/agents/node-token-service'
import { askpassServer } from './ssh-askpass'
import { appSshAgent } from './ssh-agent'
import { sessionName } from '../../core/tmux-naming'
@@ -105,6 +110,14 @@ interface Runners {
* FILE was in play, which is the signature of a credential held only in the user's own agent,
* and selects the hint that names the fix (see connectOnce's failure tail). */
askpassAsked?: (masterPid?: number) => boolean
+ /** The node ids of this project's persisted canvas — the nodes whose per-node tokens have to
+ * exist ON THE HOST for a remote session to be anything but `legacy`. Injected (rather than
+ * read from the workspace store here) so the manager stays a pure unit under test. Absent ⇒ no
+ * tokens are materialised, which is the pre-identity behavior. */
+ nodeIdsForProject?: (projectId: string) => string[]
+ /** Mints this instance's per-node token, or null when there is no node-auth secret at all
+ * (legacy everywhere). Resolved per pass so one connect's tokens all come from one secret. */
+ nodeTokenMinter?: () => ((nodeId: string) => string) | null
}
/** Backoff after a FAILED remote claude probe (no markers = claude not found on that attempt).
@@ -572,6 +585,11 @@ export class SshProjectManager {
if (remoteHome && hookEndpointPath) {
void this.remoteHooks.installCanvasControl(conn, controlPath, remoteHome)
void this.remoteHooks.installContextLink(conn, controlPath, remoteHome)
+ // Per-node tokens for every node of this project (the endpoint file written just above
+ // is what tells the host's hook script where to find them, which is also why this is
+ // gated on `hookEndpointPath`: a token nothing can be pointed at is a wasted round-trip).
+ // Same not-awaited best-effort terms as the two installs.
+ void this.materialiseNodeTokens(projectId, conn, controlPath, remoteHome)
}
// Same ownership check the failure path makes below, and for the same reason: the setup
// above is several remote round-trips, and a disconnect + reconnect inside that window
@@ -960,6 +978,53 @@ export class SshProjectManager {
return this.conns.get(projectId)?.remoteHome
}
+ /**
+ * Write this project's per-node tokens onto its host (connect path). Everything about it is
+ * best-effort: no minter (no secret ⇒ legacy everywhere) or no node ids ⇒ not a single remote
+ * command, and `RemoteHooks.writeNodeTokens` never throws.
+ */
+ private async materialiseNodeTokens(
+ projectId: string,
+ conn: SshConnection,
+ controlPath: string,
+ remoteHome: string
+ ): Promise<void> {
+ try {
+ const mint = this.r.nodeTokenMinter?.()
+ if (!mint) return
+ const ids = this.r.nodeIdsForProject?.(projectId) ?? []
+ if (!ids.length) return
+ await this.remoteHooks.writeNodeTokens(conn, controlPath, remoteHome, ids, mint)
+ } catch {
+ /* fail-open: an identity file must never be able to fail a connect */
+ }
+ }
+
+ /**
+ * Materialise ONE node's token on the host that serves `controlPath` — the SPAWN path (see
+ * `ensureRemoteNodeToken`). A node created after the project connected would otherwise have no
+ * token on the host until the next reconnect, i.e. for a long-lived project, never.
+ *
+ * Keyed by control path rather than project id because that is what a pty session carries.
+ * Gated on the same two facts the connect path is: a resolved `$HOME` (every remote path must be
+ * absolute) and a verified tunnel (`hookEndpointPath` ⇒ the endpoint file that names the token
+ * dir actually exists on the host).
+ */
+ async writeNodeTokenForNode(controlPath: string, nodeId: string): Promise<void> {
+ try {
+ for (const c of this.conns.values()) {
+ if (c.controlPath !== controlPath) continue
+ if (!c.remoteHome || !c.hookEndpointPath) return
+ const mint = this.r.nodeTokenMinter?.()
+ if (!mint) return
+ await this.remoteHooks.writeNodeTokens(c.conn, c.controlPath, c.remoteHome, [nodeId], mint)
+ return
+ }
+ } catch {
+ /* fail-open: never let a token write reach a pty spawn */
+ }
+ }
+
/**
* Proactively re-validate every cached master (powerMonitor 'resume'). Sleep kills the TCP
* under the masters, but ServerAlive only notices ~60s AFTER wake, until then every terminal
@@ -1573,6 +1638,10 @@ export function initSshProject(
)
}),
getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),
+ // Per-node identity for REMOTE nodes. Both come from the same module the local materialiser
+ // uses, so one canvas cannot be judged by two different rules depending on where it runs.
+ nodeIdsForProject: (projectId) => nodeIdsForCanvas(projectId),
+ nodeTokenMinter: () => remoteNodeTokenMinter(),
onStatus: (e) => {
// sendToMain resolves the window AT SEND TIME (see main-window.ts): the `win` captured here
// is destroyed and recreated by a macOS close/reopen, and sending to the stale reference is
@@ -1588,6 +1657,11 @@ export function initSshProject(
}
}
})
+ // The spawn-path leg of the remote materialiser: `pty-manager` (core) reaches the ControlMaster
+ // through this registration, because the runner that owns it lives here, in main.
+ setRemoteNodeTokenWriter((controlPath, nodeId) => {
+ void mgr.writeNodeTokenForNode(controlPath, nodeId)
+ })
// Registered after `mgr` exists so the dialog can name the server: the askpass request carries
// the asking master's pid, and only the manager can map it back to a connection.
askpassServer.setPromptHandler((req) =>