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(ssh): app-private ssh-agent so an unlocked key lasts one app run
parsa2223f7ce4e10df1
diff --git a/src/main/remote-ssh/ssh-agent.test.ts b/src/main/remote-ssh/ssh-agent.test.tsnew file mode 100644index 000000000..479a7b422--- /dev/null+++ b/src/main/remote-ssh/ssh-agent.test.ts@@ -0,0 +1,213 @@+// The app-private ssh-agent (ssh-agent.ts). No real `ssh-agent` is spawned: the spawner is+// injected and the "socket" is a file the fake creates, which is exactly what start() waits on.+// What matters here is not the process management but the two properties the feature rests on:+// env() never falls back to the ambient agent (a fallback would silently load the key into the+// user's login agent forever), and start() never hands a caller an agent that is not listening yet.+import { promises as fs, existsSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { AppSshAgent, agentSockPath } from './ssh-agent'++let tmp: string | undefined++async function sock(): Promise<string> {+ tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-agent-test-'))+ return path.join(tmp, 'agent.sock')+}++afterEach(async () => {+ if (tmp) await fs.rm(tmp, { recursive: true, force: true }).catch(() => {})+ tmp = undefined+})++/** A stand-in for the spawned agent: binds (creates) the socket file, immediately by default or+ * after `bindDelayMs` to model the real exec→bind gap. Immediate binding is synchronous on+ * purpose, so the fake needs no timer and the fake-timer test below can still start an agent.+ * Handlers registered via on() are REAL (kept and firable): the production 'exit'/'error'+ * handlers are what let a dead agent be restarted, and a fake that discards them would leave+ * that whole path unexercised - deleting those handlers kept an earlier version of this suite+ * green. */+function fakeAgent(sockPath: string, bindDelayMs = 0) {+ const calls: string[][] = []+ const kills: number[] = []+ const handlers = new Map<string, ((...a: unknown[]) => void)[]>()+ const emit = (ev: string): void => {+ for (const cb of handlers.get(ev) ?? []) cb()+ }+ const spawnAgent = vi.fn((args: string[]) => {+ calls.push(args)+ let timer: ReturnType<typeof setTimeout> | undefined+ if (bindDelayMs === 0) writeFileSync(sockPath, '')+ else timer = setTimeout(() => writeFileSync(sockPath, ''), bindDelayMs)+ return {+ pid: 1234,+ kill: () => {+ if (timer) clearTimeout(timer)+ kills.push(1)+ },+ on: (ev: string, cb: (...a: unknown[]) => void) => {+ handlers.set(ev, [...(handlers.get(ev) ?? []), cb])+ }+ }+ })+ return { spawnAgent, calls, kills, emit }+}++describe('agentSockPath', () => {+ it('is short, under the home dir, and differs per app instance', () => {+ const a = agentSockPath('/Users/u/Library/Application Support/node-terminal')+ const b = agentSockPath('/Users/u/dev/nodeterm-testdata')+ expect(a).not.toBe(b) // NT_MULTI: a second instance must not unlink the first one's socket+ expect(a.startsWith(path.join(os.homedir(), '.nodeterm'))).toBe(true)+ // A unix socket path is capped near 104 bytes; userData paths blow that, which is the whole+ // reason this lives in ~/.nodeterm rather than next to the app's data.+ expect(a.length).toBeLessThan(104)+ })+})++describe('AppSshAgent', () => {+ it('spawns a foreground agent with a key lifetime, on its own socket', async () => {+ const p = await sock()+ const { spawnAgent, calls } = fakeAgent(p)+ const agent = new AppSshAgent(spawnAgent, p)+ await agent.start()+ // -D keeps it a direct child (the default double-forks and would survive a kill); -t bounds an+ // agent orphaned by a crash, which is the only path where stop() never runs.+ expect(calls[0]).toEqual(['-D', '-t', '12h', '-a', p])+ expect(agent.isRunning()).toBe(true)+ agent.stop()+ })++ it('starts once for concurrent callers, and nobody is released before the socket is listening', async () => {+ const p = await sock()+ const { spawnAgent } = fakeAgent(p, 40) // binds late, like a real agent's exec+ const agent = new AppSshAgent(spawnAgent, p)+ // Two projects connecting at once: without a memoized start, the second returns immediately on+ // `if (this.child)` while the socket is still binding, ssh finds no agent, and its unlocked key+ // goes nowhere — every later connect in that run prompts again.+ const bound: boolean[] = []+ await Promise.all([+ agent.start().then(() => bound.push(existsSync(p))),+ agent.start().then(() => bound.push(existsSync(p)))+ ])+ expect(spawnAgent).toHaveBeenCalledTimes(1)+ expect(bound).toEqual([true, true])+ agent.stop()+ })++ it('points at its OWN socket even when the spawn fails (fail closed, never at the login agent)', async () => {+ const p = await sock()+ // spawn() reports a missing binary as an ASYNC 'error' event on the child, never a sync throw+ // - the earlier sync-throwing fake tested a failure mode child_process cannot produce.+ const handlers = new Map<string, (...a: unknown[]) => void>()+ const agent = new AppSshAgent((args) => {+ void args+ const child = {+ kill: vi.fn(),+ on: (ev: string, cb: (...a: unknown[]) => void) => handlers.set(ev, cb)+ }+ setImmediate(() => handlers.get('error')?.(new Error('spawn ssh-agent ENOENT')))+ return child+ }, p)+ await expect(agent.start()).resolves.toBeUndefined() // never fatal, and no unhandled 'error'+ expect(agent.isRunning()).toBe(false)+ // The load-bearing assertion of this whole file: returning {} here would let ssh inherit the+ // user's SSH_AUTH_SOCK, and AddKeysToAgent=yes would load the key into their login agent+ // permanently — the exact leak this feature exists to close, reached by a silent path.+ expect(agent.env()).toEqual({ SSH_AUTH_SOCK: p })+ })++ it('publishes the core-spawner env var even when the start throws synchronously (fail closed there too)', async () => {+ const p = await sock()+ const prev = process.env.NODETERM_APP_AGENT_SOCK+ delete process.env.NODETERM_APP_AGENT_SOCK+ const agent = new AppSshAgent(() => {+ throw new Error('EACCES') // e.g. mkdir/rm on ~/.nodeterm denied, or spawn itself throwing+ }, p)+ await expect(agent.start()).resolves.toBeUndefined()+ // env() is unconditional, but the CORE spawners (remote PTYs, remote git) read this env var+ // instead — left unset on the sync-throw path they silently fell back to the ambient agent,+ // the one asymmetry in an otherwise fail-closed design.+ expect(process.env.NODETERM_APP_AGENT_SOCK).toBe(p)+ agent.stop() // also unpublishes+ expect(process.env.NODETERM_APP_AGENT_SOCK).toBeUndefined()+ if (prev !== undefined) process.env.NODETERM_APP_AGENT_SOCK = prev+ })++ it('an agent that DIES mid-run is restarted by the next start(), not joined as a memoized ghost', async () => {+ const p = await sock()+ const { spawnAgent, emit } = fakeAgent(p)+ const agent = new AppSshAgent(spawnAgent, p)+ await agent.start()+ expect(agent.isRunning()).toBe(true)+ emit('exit') // the agent process died (crash, external kill)+ expect(agent.isRunning()).toBe(false)+ // Without the exit handler clearing the memoized `starting`, this start() would return the+ // stale resolved promise forever: no agent for the rest of the run, a prompt on every connect.+ await agent.start()+ expect(spawnAgent).toHaveBeenCalledTimes(2)+ expect(agent.isRunning()).toBe(true)+ agent.stop()+ })++ it('publishes the socket for core spawners while up, and unpublishes it on stop', async () => {+ // Remote PTYs (pty-manager) and remote git (remote-git) shell out to ssh from src/core, which+ // cannot import this main-process module - they find the agent through this env var. Losing+ // the publish reopens the pane-prompt / login-agent leak; losing the DELETE leaves core+ // pointing at a socket that no longer exists after quit-in-place (macOS window close).+ const p = await sock()+ const { spawnAgent } = fakeAgent(p)+ const agent = new AppSshAgent(spawnAgent, p)+ delete process.env.NODETERM_APP_AGENT_SOCK+ try {+ await agent.start()+ expect(process.env.NODETERM_APP_AGENT_SOCK).toBe(p)+ agent.stop()+ expect(process.env.NODETERM_APP_AGENT_SOCK).toBeUndefined()+ } finally {+ delete process.env.NODETERM_APP_AGENT_SOCK+ }+ })++ it('stop() kills the agent, removes the socket, and a later start brings a fresh one up', async () => {+ const p = await sock()+ const { spawnAgent, kills } = fakeAgent(p)+ const agent = new AppSshAgent(spawnAgent, p)+ await agent.start()+ agent.stop()+ expect(kills).toHaveLength(1)+ expect(existsSync(p)).toBe(false) // no socket left for the next run to trip over+ expect(agent.isRunning()).toBe(false)+ await agent.start()+ expect(spawnAgent).toHaveBeenCalledTimes(2)+ agent.stop()+ })++ it('scheduleStop forgets the key after its grace, and a connect inside the window cancels it', async () => {+ const p = await sock()+ const { spawnAgent, kills } = fakeAgent(p)+ const agent = new AppSshAgent(spawnAgent, p)+ await agent.start() // real timers: the fake binds synchronously, so this settles at once+ vi.useFakeTimers()+ try {++ // The browse-master case: the connect dialog disconnects its throwaway master a moment+ // before the real project connects. Forgetting in that gap would charge a second prompt.+ agent.scheduleStop(10_000)+ vi.advanceTimersByTime(5_000)+ void agent.start()+ vi.advanceTimersByTime(10_000)+ expect(agent.isRunning()).toBe(true)++ // Nothing came back: the key is forgotten when the grace expires. `kills` is the assertion+ // that matters - isRunning() alone stayed green when stop() forgot to kill() the process.+ agent.scheduleStop(10_000)+ vi.advanceTimersByTime(10_001)+ expect(agent.isRunning()).toBe(false)+ expect(kills).toHaveLength(1)+ } finally {+ vi.useRealTimers()+ }+ })+})diff --git a/src/main/remote-ssh/ssh-agent.ts b/src/main/remote-ssh/ssh-agent.tsnew file mode 100644index 000000000..5e3ee80f5--- /dev/null+++ b/src/main/remote-ssh/ssh-agent.ts@@ -0,0 +1,193 @@+// An ssh-agent owned by THIS app run, so an unlocked key is forgotten when nodeterm quits.+//+// `AddKeysToAgent=yes` (control-master.ts) makes the first successful unlock load the key into+// whatever `SSH_AUTH_SOCK` names, and every later master then authenticates with no prompt at all.+// Pointed at the user's LOGIN agent that unlock outlives the app entirely: the key stays usable by+// every process on the machine until logout or reboot, which makes the passphrase on the key file+// nearly decorative once it has been typed. Pointing the masters at an agent this app spawns and+// kills scopes the unlock to the app's lifetime instead: quit nodeterm and the next launch asks+// again, while a single run keeps its single prompt (reconnects, watchdog respawns, closing and+// reopening a project all reuse it).+//+// What this does and does not buy, precisely: it scopes the key's LIFETIME, not its reachability.+// The socket is 0600, but any process running as this user can still point `SSH_AUTH_SOCK` at it+// and use the key while the app is up, exactly as with the login agent.+//+// Deliberate tradeoffs:+// - A key ALREADY loaded in the user's login agent no longer authenticates a nodeterm master, so+// those users now see one prompt per app run where they previously saw none. That is the price+// of "forgotten on quit"; `SSH_AUTH_SOCK` names exactly one socket, so there is no both.+// - Nothing is ever added to the user's own agent, and their shell/git never see ours.+// - A credential that lives ONLY in an agent (1Password, Secretive, a smartcard) has no key file+// to unlock, so overriding the socket would lock those users out. Most are unaffected because+// `IdentityAgent` in ~/.ssh/config overrides `SSH_AUTH_SOCK` and is the documented setup for+// them; ssh-project.ts covers the rest with a one-shot retry on the ambient agent.+//+// The agent runs in the FOREGROUND (`-D`) as a direct child, so `kill()` really ends it (the+// default double-forks away and would survive us), and with a default identity lifetime (`-t`)+// because `stop()` is not guaranteed to run: `app.exit()`, a SIGKILL or a crash leaves the agent+// reparented to init, holding the key, with its socket unlinked by the next run's `start()` — an+// unreachable process that lives until reboot. The lifetime is what bounds that case.+import { spawn } from 'child_process'+import { createHash } from 'crypto'+import { existsSync, mkdirSync, rmSync } from 'fs'+import os from 'os'+import path from 'path'++/** How core's own ssh spawners (remote PTYs in pty-manager, remote git) find this agent: core+ * cannot import a main-process module, so the socket path is published in process.env under this+ * name while the agent is up. NOT `SSH_AUTH_SOCK` itself - that would leak into every LOCAL+ * terminal the app spawns and quietly repoint the user's own shell at our agent. */+export const APP_AGENT_ENV = 'NODETERM_APP_AGENT_SOCK'++/** Absolute ssh-agent binary. A GUI Electron app does not inherit the shell PATH (the exact+ * reason sshBin()/findSsh() exist), and a bare `spawn('ssh-agent')` miss is only a console.error+ * whose visible symptom is "a passphrase prompt on every connect this run" with no diagnostic. */+function findSshAgent(): string {+ for (const p of ['/usr/bin/ssh-agent', '/opt/homebrew/bin/ssh-agent', '/usr/local/bin/ssh-agent']) {+ if (existsSync(p)) return p+ }+ return 'ssh-agent' // PATH as a last resort; a miss fails into env()'s fail-closed posture+}++/** Backstop for an agent orphaned by a crash (a clean quit kills it outright), and the ceiling on+ * how long one app run can stay unlocked — hence generous rather than tight. */+const KEY_LIFETIME = '12h'+/** How long the agent survives the last SSH connection going away. A grace, not a policy: the+ * connect dialog tears down its throwaway `ssh-browse-*` master a few hundred ms BEFORE the real+ * project connects, and killing the agent in that gap would charge the user a second passphrase+ * prompt to add one server. */+export const IDLE_GRACE_MS = 10_000++interface AgentChild {+ pid?: number+ kill(): void+ on(event: string, cb: (...args: unknown[]) => void): void+}++/** The socket lives in the same short, space-free home dir as the ControlMaster sockets: a unix+ * socket path is capped near 104 bytes, which userData (~/Library/Application Support/…) eats.+ * Keyed by data dir like `controlPathFor` is keyed by project id, so a second instance+ * (`NT_MULTI=1`, ./dev-test.sh) binds its own socket instead of unlinking the first one's and+ * silently leaving that app agentless when it quits. */+export function agentSockPath(dataDirKey = process.env.NT_USER_DATA ?? 'default'): string {+ const id = createHash('sha256').update(dataDirKey).digest('hex').slice(0, 8)+ return path.join(os.homedir(), '.nodeterm', `agent-${id}.sock`)+}++export class AppSshAgent {+ private child: AgentChild | null = null+ /** In-flight `start()`, so concurrent connects share one spawn AND one wait. Returning early on+ * `if (this.child)` while the socket is still binding would hand the second connect an agent+ * that cannot answer yet, and its key would go nowhere. */+ private starting: Promise<void> | null = null+ private idleTimer: ReturnType<typeof setTimeout> | null = null++ constructor(+ private spawnAgent: (args: string[]) => AgentChild = (args) =>+ spawn(findSshAgent(), args, { stdio: 'ignore' }),+ private sockPath: string = agentSockPath()+ ) {}++ /**+ * Start the agent if it is not already running, resolving once its socket is listening. Called+ * before a master is spawned rather than at boot, so an app run that never opens an SSH project+ * never pays for an agent process. Never rejects: a failed start costs a passphrase prompt per+ * connect (the pre-agent behavior), which is the safe direction — see `env()`.+ */+ start(): Promise<void> {+ this.cancelScheduledStop()+ return (this.starting ??= this.spawnAndWait())+ }++ private async spawnAndWait(): Promise<void> {+ try {+ mkdirSync(path.dirname(this.sockPath), { recursive: true, mode: 0o700 })+ // `ssh-agent -a` refuses to bind over an existing file, and a crash leaves one behind.+ rmSync(this.sockPath, { force: true })+ const child = this.spawnAgent(['-D', '-t', KEY_LIFETIME, '-a', this.sockPath])+ const forget = (): void => {+ if (this.child === child) {+ this.child = null+ this.starting = null // a later connect restarts the agent instead of joining a dead one+ }+ }+ child.on('exit', forget)+ // Without this an ENOENT (no ssh-agent on PATH) is an unhandled 'error' event on the child.+ child.on('error', forget)+ this.child = child+ } catch (e) {+ console.error('[ssh-agent] could not start an app-private agent', e)+ this.child = null+ return+ }+ // Publish the socket for the CORE ssh spawners that cannot import this file: remote PTYs+ // (pty-manager) and remote git (remote-git) shell out to ssh themselves, and `childArgs` uses+ // `ControlMaster=auto`, so with the master down one of them authenticates for real. Left+ // inheriting the ambient socket, a remote PTY (which HAS a tty) prompts for the passphrase in+ // the pane and, for anyone with `AddKeysToAgent yes` in their own ~/.ssh/config, loads the key+ // into their login agent permanently. Set even when the spawn failed, for the same fail-closed+ // reason as `env()`.+ process.env[APP_AGENT_ENV] = this.sockPath+ // The socket appears a few ms after exec. Bounded: past this we simply proceed, and ssh prompts.+ const deadline = Date.now() + 1_000+ while (this.child && !existsSync(this.sockPath) && Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 20))+ }+ }++ /**+ * Env for anything that may AUTHENTICATE (the ControlMaster spawn, and the child ssh/scp that+ * re-auth when the master is down).+ *+ * Deliberately unconditional, even before the agent is up or after a failed start: falling back+ * to `{}` would let ssh inherit the ambient `SSH_AUTH_SOCK`, and `AddKeysToAgent=yes` would then+ * quietly load the key into the user's login agent forever — the exact leak this exists to close,+ * reached by the silent path. Pointing at a socket that is not listening costs one prompt; ssh+ * warns and carries on. Fail closed.+ */+ env(): Record<string, string> {+ return { SSH_AUTH_SOCK: this.sockPath }+ }++ /** Kill the agent after `delayMs` unless something starts it again first (see IDLE_GRACE_MS).+ * Unref'd: a pending forget must never hold the process open. */+ scheduleStop(delayMs: number = IDLE_GRACE_MS): void {+ this.cancelScheduledStop()+ this.idleTimer = setTimeout(() => {+ this.idleTimer = null+ this.stop()+ }, delayMs)+ this.idleTimer.unref?.()+ }++ private cancelScheduledStop(): void {+ if (this.idleTimer) clearTimeout(this.idleTimer)+ this.idleTimer = null+ }++ /**+ * Kill the agent and drop its socket. MUST stay synchronous for the same reason as+ * `disconnectAll()`: it runs from Electron's sync `before-quit`, and anything awaited there can+ * lose the race with process exit — precisely the case where the key must not survive.+ */+ stop(): void {+ this.cancelScheduledStop()+ this.child?.kill()+ this.child = null+ this.starting = null+ delete process.env[APP_AGENT_ENV]+ try {+ rmSync(this.sockPath, { force: true })+ } catch {+ // best effort: a leftover socket file is unlinked by the next start()+ }+ }++ /** Is an agent process live right now? Only for tests and diagnostics. */+ isRunning(): boolean {+ return this.child !== null+ }+}++export const appSshAgent = new AppSshAgent()