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): prompt for passphrase-protected keys via an SSH_ASKPASS relay

parsa22280121bb609bc
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 6d0e865db..1d5b914bd 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1180,6 +1180,14 @@ export class PtyManager {
const remoteSsh = options.sshRemote && options.persistKey ? findSsh() : null
if (options.sshRemote && options.persistKey && remoteSsh) {
file = remoteSsh
+ // 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
+ // for real, and inheriting the ambient SSH_AUTH_SOCK would prompt in the pane and - for a
+ // user with `AddKeysToAgent yes` in their own ~/.ssh/config - load the key into their LOGIN
+ // agent permanently, the leak the app agent exists to close. Scoped to the remote branch:
+ // local terminals keep the user's own agent.
+ if (process.env.NODETERM_APP_AGENT_SOCK) env.SSH_AUTH_SOCK = process.env.NODETERM_APP_AGENT_SOCK
// When the project's reverse tunnel + remote endpoint file are set up (Task 2), inject the
// remote hook env into the remote tmux session so the installed hook script POSTs state back
// over the unix-socket tunnel. Fail-open: no hookEndpointPath → no hook env (Phase-1 status).
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 73a1ac09c..a612f9d22 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -26,7 +26,8 @@ const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile:
/** The option prefix every child ssh shares: self-healing mux (auto + persist, so the first
* child after a cleanly-gone master rebuilds it), keepalives for when the child owns the
- * transport, and the identity key (auth matters exactly when mux is unavailable). */
+ * transport, and the identity key (auth matters exactly when mux is unavailable), pinned with
+ * IdentitiesOnly so a fallback connect can't burn MaxAuthTries on unrelated agent keys. */
const childPrefix = [
'-o', 'ControlMaster=auto',
'-o', 'ControlPath=/s.sock',
@@ -35,6 +36,7 @@ const childPrefix = [
'-o', 'ServerAliveInterval=15',
'-o', 'ServerAliveCountMax=4',
'-p', '2222',
+ '-o', 'IdentitiesOnly=yes',
'-i', '/k/id'
]
@@ -72,21 +74,48 @@ describe('masterArgs', () => {
'-o', 'StrictHostKeyChecking=accept-new',
'-o', 'ServerAliveInterval=15',
'-o', 'ServerAliveCountMax=4',
+ '-o', 'ConnectTimeout=15',
+ '-o', 'PasswordAuthentication=no',
+ '-o', 'KbdInteractiveAuthentication=no',
+ '-o', 'AddKeysToAgent=yes',
'-p', '2222',
+ '-o', 'IdentitiesOnly=yes',
'-i', '/k/id',
])
})
+ it('loads unlocked keys into the agent: the agent, not the app, is the passphrase cache', () => {
+ // Measured against a real sshd: with this option the second connect (fresh master, fresh
+ // pid) authenticates through the agent with ZERO askpass invocations; without it every
+ // single connect re-prompted. Deleting ssh-passphrase-cache.ts rides on this line.
+ expect(masterArgs(conn, '/s.sock')).toContain('AddKeysToAgent=yes')
+ })
+ it('pins the offer to the configured key (IdentitiesOnly) so agent keys cannot burn MaxAuthTries', () => {
+ // Measured: 8 junk agent keys + `-i` ended the connection with "Too many authentication
+ // failures" (server default MaxAuthTries=6) before the configured key was ever offered.
+ // The agent still SIGNS the pinned key, so prompt-free reconnects are unaffected.
+ const args = masterArgs(conn, '/s.sock').join(' ')
+ expect(args).toContain('-o IdentitiesOnly=yes -i /k/id')
+ })
+ it('omits IdentitiesOnly (not just -i) when no identityFile is configured: agent keys must stay usable', () => {
+ // IdentitiesOnly with NO -i would stop ssh from offering agent keys at all, which would
+ // break the very reconnect path AddKeysToAgent provides. It must ride with -i or not at all.
+ const bare = { host: 'h.example.com', user: 'deploy', port: 2222 }
+ const args = masterArgs(bare, '/s.sock')
+ expect(args).not.toContain('-i')
+ expect(args.join(' ')).not.toContain('IdentitiesOnly')
+ })
})
describe('childArgs', () => {
it('muxes over the master socket, self-healing (auto + persist), and appends a remote command', () => {
expect(childArgs(conn, '/s.sock', 'tmux ls')).toEqual([...childPrefix, '[email protected]', 'tmux ls'])
})
- it('omits -i when the connection has no identityFile', () => {
+ it('omits -i AND IdentitiesOnly when the connection has no identityFile', () => {
const bare = { host: 'h.example.com', user: 'deploy', port: 2222 }
const args = childArgs(bare, '/s.sock', 'tmux ls')
expect(args).not.toContain('-i')
+ expect(args.join(' ')).not.toContain('IdentitiesOnly') // would disable agent keys outright
expect(args.at(-2)).toBe('[email protected]')
})
it('regression: never ControlMaster=no — a dead master made every child a silent fresh direct connection', () => {
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index dd695f98a..b0990613c 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -33,6 +33,23 @@ function portArgs(conn: SshConnection): string[] {
return ['-p', String(conn.port ?? 22)]
}
+/**
+ * `IdentitiesOnly=yes` + `-i` when the connection names a key, nothing otherwise. The pairing
+ * exists because of `AddKeysToAgent` (masterArgs): an agent accumulates keys, and without
+ * IdentitiesOnly ssh offers EVERY agent key before the configured one. Each rejected offer spends
+ * one of the server's `MaxAuthTries` (default 6), so a well-stocked agent ended the connection
+ * with "Too many authentication failures" before the configured key was ever offered (measured
+ * against a real sshd: 8 junk agent keys plus `-i` = disconnected; the same with IdentitiesOnly
+ * connects). IdentitiesOnly does NOT bypass the agent for the named key: ssh still has the agent
+ * sign it, so the no-reprompt behavior survives (measured: askpass removed entirely, agent
+ * holding the key, zero prompts). With NO configured key this must stay empty, because
+ * IdentitiesOnly would then disable agent keys outright and break the very reconnect path
+ * AddKeysToAgent provides.
+ */
+function identityArgs(conn: SshConnection): string[] {
+ return conn.identityFile ? ['-o', 'IdentitiesOnly=yes', '-i', conn.identityFile] : []
+}
+
/** Args for the backgrounded multiplexing master (the one auth happens here). */
export function masterArgs(conn: SshConnection, controlPath: string): string[] {
const args = [
@@ -61,9 +78,50 @@ export function masterArgs(conn: SshConnection, controlPath: string): string[] {
'ServerAliveInterval=15',
'-o',
'ServerAliveCountMax=4',
- ...portArgs(conn)
+ // Bound the TCP-connect phase. connect() waits on the master PROCESS for keyed connections
+ // (a passphrase prompt can take minutes), so a black-holed TCP connect must fail through ssh
+ // itself rather than ride that long window for the kernel's ~75s of SYN retries. Auth,
+ // including the passphrase prompt, is not covered by ConnectTimeout, so no slow human is
+ // ever cut off by this.
+ '-o',
+ 'ConnectTimeout=15',
+ // The master has no tty, so it can never complete password or keyboard-interactive auth: the
+ // best it can do is submit an EMPTY credential, which OpenSSH does silently, once per allowed
+ // prompt. Every connect against a password-auth host therefore produced several FAILED logins,
+ // and because the app retries on its own timers (reconnector backoff, 45s watchdog, resume,
+ // tab switches) a single evening was enough to trip the host's own fail2ban and lock the user
+ // out with "Connection closed by <host>". Refusing both methods up front means the master
+ // fails honestly on publickey alone and never spends a login attempt it cannot win.
+ //
+ // Do NOT express this as `NumberOfPasswordPrompts=0`: that counter also bounds the KEY
+ // PASSPHRASE retry loop in OpenSSH's load_identity_file, so zero means an encrypted key is
+ // tried once with an empty passphrase and then abandoned WITHOUT ever invoking SSH_ASKPASS.
+ // It silently disables passphrase prompting altogether, which an end-to-end test against a
+ // real sshd caught and no unit test could.
+ '-o',
+ 'PasswordAuthentication=no',
+ '-o',
+ 'KbdInteractiveAuthentication=no',
+ // Load a successfully unlocked key into the agent named by SSH_AUTH_SOCK. An AGENT, not this
+ // app, is the passphrase cache: the next master (reconnect, watchdog respawn) authenticates
+ // through it and never re-prompts (measured against a real sshd: second connect, fresh master,
+ // zero askpass invocations, even with SSH_ASKPASS removed), and the decrypted key sits in a
+ // purpose-built process instead of a plaintext string in Electron main memory — which is why
+ // the old in-app passphrase cache was deleted in its favor.
+ //
+ // WHICH agent is the app's choice, and it is not the user's: main points SSH_AUTH_SOCK at an
+ // app-private agent it spawns and kills (src/main/remote-ssh/ssh-agent.ts), so the unlock is
+ // scoped to one app run instead of living in the login agent until logout. Read that file
+ // before assuming a key unlocked here survives a quit.
+ //
+ // Harmless when no agent is reachable at all: ssh skips the add silently (measured: not one
+ // stderr line, so nothing for lastSshErrorLine to mistake for a failure cause) and simply
+ // prompts again next time.
+ '-o',
+ 'AddKeysToAgent=yes',
+ ...portArgs(conn),
+ ...identityArgs(conn)
]
- if (conn.identityFile) args.push('-i', conn.identityFile)
args.push(target(conn))
return args
}
@@ -106,7 +164,10 @@ export function childArgs(conn: SshConnection, controlPath: string, remote?: str
]
// The key matters exactly when mux is NOT available (fallback / becoming master) — the case
// the old childArgs ignored: with a non-default identityFile every fallback exec failed auth.
- if (conn.identityFile) args.push('-i', conn.identityFile)
+ // identityArgs also pins the offer (IdentitiesOnly) so that same fallback cannot burn the
+ // server's MaxAuthTries on unrelated agent keys; the agent still signs the pinned key, which
+ // is the only way a tty-less child can use an ENCRYPTED key at all (it has no askpass wiring).
+ args.push(...identityArgs(conn))
args.push(target(conn))
if (remote !== undefined) args.push(remote)
return args
@@ -209,7 +270,7 @@ export function mkDirArgs(conn: SshConnection, controlPath: string, path: string
* basenamed by the caller, and the path is absolute). scp uses `-P` (uppercase) for the port. */
export function scpArgs(conn: SshConnection, controlPath: string, localPath: string, remotePath: string): string[] {
const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, '-o', 'BatchMode=yes', '-P', String(conn.port ?? 22)]
- if (conn.identityFile) args.push('-i', conn.identityFile)
+ args.push(...identityArgs(conn))
args.push(localPath, `${conn.user}@${conn.host}:${remotePath}`)
return args
}
@@ -242,7 +303,7 @@ export function scpDownArgs(
recursive = false
): string[] {
const args = ['-o', 'ControlMaster=no', '-o', `ControlPath=${controlPath}`, '-o', 'BatchMode=yes', '-P', String(conn.port ?? 22)]
- if (conn.identityFile) args.push('-i', conn.identityFile)
+ args.push(...identityArgs(conn))
if (recursive) args.push('-r')
args.push(`${conn.user}@${conn.host}:${remoteScpPath(remotePath)}`, localPath)
return args
diff --git a/src/core/remote-ssh/remote-git.ts b/src/core/remote-ssh/remote-git.ts
index 0be570470..07080be56 100644
--- a/src/core/remote-ssh/remote-git.ts
+++ b/src/core/remote-ssh/remote-git.ts
@@ -61,7 +61,13 @@ export async function runRemoteGit(
const ssh = findSsh()
if (!ssh) return { ok: false, out: '', err: 'ssh not found' }
try {
- const { stdout } = await run(ssh, remoteGitArgs(ref.conn, ref.controlPath, cwd, args), { maxBuffer })
+ // With the master down, `ControlMaster=auto` makes this child authenticate for real; point it
+ // at the app-private ssh-agent (published via env by main's ssh-agent.ts, which core cannot
+ // import) so the unlocked key is found there and never sought in the user's login agent.
+ const env = process.env.NODETERM_APP_AGENT_SOCK
+ ? { ...process.env, SSH_AUTH_SOCK: process.env.NODETERM_APP_AGENT_SOCK }
+ : process.env
+ const { stdout } = await run(ssh, remoteGitArgs(ref.conn, ref.controlPath, cwd, args), { maxBuffer, env })
return { ok: true, out: stdout.replace(/\n$/, ''), err: '' }
} catch (e) {
const err = e as { stdout?: string; stderr?: string; message?: string }
diff --git a/src/main/index.ts b/src/main/index.ts
index 4fe1912aa..e09dd6253 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -22,6 +22,8 @@ import { generateCommitMessage, generateGroupName, generateTerminalName } from '
import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
import { hookServer } from '../core/agents/hook-server'
+import { askpassServer, ensureAskpassScript } from './remote-ssh/ssh-askpass'
+import { appSshAgent } from './remote-ssh/ssh-agent'
import {
writePendingAnswerLocal,
startPendingSweep,
@@ -339,7 +341,9 @@ function createWindow(): BrowserWindow {
height: 900,
show: false,
backgroundColor: '#1e1e1e',
- title: 'node-terminal',
+ // NT_MULTI instances are throwaway dev sandboxes: label the window so a second instance is
+ // never mistaken for the real one (the dock already shows the Electron icon in dev).
+ title: NT_MULTI ? 'node-terminal (test instance)' : 'node-terminal',
icon: linuxIcon,
// Integrate the macOS traffic lights into our top bar (modern Mac app look).
titleBarStyle: 'hiddenInset',
@@ -785,6 +789,10 @@ app.whenReady().then(async () => {
// listeners (setListener/setRawListener/setControlHandler) attach later, which the server
// tolerates — early hook POSTs are simply dropped, never mis-routed.
await hookServer.start()
+ // Loopback SSH_ASKPASS relay (ssh-project.ts): lets the ControlMaster, which has no tty, route a
+ // passphrase-protected identity file's prompt back through the app instead of failing auth.
+ await askpassServer.start()
+ const askpassScriptPath = await ensureAskpassScript(app.getPath('userData'))
const win = createWindow()
// NT_MULTI instances are throwaway dev sandboxes. The dock badge is the one marker that is
// always visible on macOS (the window title is hidden by titleBarStyle: 'hiddenInset', and the
@@ -1717,14 +1725,24 @@ app.whenReady().then(async () => {
relayClients.delete(id)
})
}
- sshProjectManager = initSshProject(win, (projectId) => {
- // On (re)connect, reconcile the server's .nodeterm/project.json with our offline cache by rev.
- // A non-null result means the remote won → adopt it in the renderer (Task 7's listener does the
- // silent replace / conflict bar). null means our cache was pushed up instead — nothing to send.
- void workspaceStore.refreshSshProject(projectId).then((adopted) => {
- if (adopted) sendToMain(IPC.workspaceExternalChange, adopted)
- })
- })
+ sshProjectManager = initSshProject(
+ (projectId) => {
+ // On (re)connect, reconcile the server's .nodeterm/project.json with our offline cache by rev.
+ // A non-null result means the remote won → adopt it in the renderer (Task 7's listener does the
+ // silent replace / conflict bar). null means our cache was pushed up instead, so nothing to send.
+ // The .catch is load-bearing: this fires on every successful SSH connect, sendToMain THROWS
+ // when the render frame is disposed (reload, crash, quit, see ssh-project.ts), and an
+ // unhandled rejection is a hard main-process crash, not a log line. Right after the user
+ // answers a passphrase prompt is exactly when the renderer can be mid-churn.
+ void workspaceStore
+ .refreshSshProject(projectId)
+ .then((adopted) => {
+ if (adopted) sendToMain(IPC.workspaceExternalChange, adopted)
+ })
+ .catch(() => {})
+ },
+ askpassScriptPath
+ )
// Wake-from-sleep: re-validate every SSH master NOW instead of letting ServerAlive discover the
// dead TCP ~60s later — until it does, every remote terminal looks alive and is dead (no echo,
// no scroll). The small delay lets the network interface come back up first; connect() is
@@ -1791,7 +1809,13 @@ app.on('window-all-closed', () => {
void ptyManager.killAll()
// Land any pending throttled .nodeterm mirror write BEFORE the masters die — killing a
// master mid-write used to leave a truncated project.json on the server.
- void remoteWorkspaceIO.flush().finally(() => sshProjectManager?.disconnectAll())
+ void remoteWorkspaceIO.flush().finally(() => {
+ sshProjectManager?.disconnectAll()
+ // Every master is gone, so nothing can use the unlocked key; scheduled (not stop()) so a
+ // quick window-reopen + reconnect inside the grace re-uses the agent instead of re-prompting.
+ // Without this, a destroyed window left the key alive for the agent's full 12h backstop.
+ appSshAgent.scheduleStop()
+ })
}
})
@@ -1805,6 +1829,11 @@ app.on('before-quit', (e) => {
if (quitFlushed) {
// Second pass (the deferred app.quit() below): the flush had its chance — drop the masters.
sshProjectManager?.disconnectAll()
+ // Then the app-private ssh-agent, which is the whole point of it existing: quitting nodeterm
+ // forgets the unlocked key. AFTER disconnectAll so a throw here can never skip the master
+ // teardown, and in this pass rather than the first, where the flush is still writing over
+ // those masters. `.finally(app.quit())` above guarantees this pass runs.
+ appSshAgent.stop()
return
}
quitFlushed = true
diff --git a/src/main/remote-ssh/ssh-askpass.test.ts b/src/main/remote-ssh/ssh-askpass.test.ts
new file mode 100644
index 000000000..c42da1fb7
--- /dev/null
+++ b/src/main/remote-ssh/ssh-askpass.test.ts
@@ -0,0 +1,350 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { AskpassServer, buildAskpassScript, classifyPrompt, type AskpassPromptRequest } from './ssh-askpass'
+
+/** ssh's real passphrase prompt (sshconnect2.c), byte-identical on every retry. */
+const passphrasePrompt = (key: string) => `Enter passphrase for key '${key}': `
+
+describe('classifyPrompt', () => {
+ it('recognizes the key-passphrase prompt and extracts the key ssh actually wants', () => {
+ expect(classifyPrompt(passphrasePrompt('/home/u/.ssh/id_ed25519'))).toEqual({
+ passphrase: true,
+ keyPath: '/home/u/.ssh/id_ed25519'
+ })
+ })
+
+ it('does NOT claim the server password or keyboard-interactive prompts', () => {
+ // SSH_ASKPASS_REQUIRE=force routes these here too; answering them would send a server
+ // password where a key passphrase belongs and mislabel the dialog.
+ expect(classifyPrompt("[email protected]'s password: ").passphrase).toBe(false)
+ expect(classifyPrompt('Verification code: ').passphrase).toBe(false)
+ expect(classifyPrompt('Duo two-factor login for alice\n\nPasscode or option (1-3): ').passphrase).toBe(false)
+ expect(classifyPrompt('').passphrase).toBe(false)
+ })
+
+ it('still treats an unrecognized passphrase-shaped prompt as a passphrase ask', () => {
+ expect(classifyPrompt('Enter passphrase: ')).toEqual({ passphrase: true })
+ })
+})
+
+describe('buildAskpassScript', () => {
+ it('is a POSIX-sh script that curls the loopback server with the expected fields', () => {
+ const script = buildAskpassScript()
+ expect(script.startsWith('#!/bin/sh')).toBe(true)
+ expect(script).toContain('curl')
+ expect(script).toContain('/prompt')
+ expect(script).toContain('NODETERM_ASKPASS_PORT')
+ expect(script).toContain('NODETERM_ASKPASS_TOKEN')
+ expect(script).toContain('NODETERM_ASKPASS_IDENTITY')
+ // The invoking ssh pid: a SECOND ask from the same pid selects the "didn't work" dialog copy
+ // (ssh reuses the byte-identical prompt on retries, so wording can never carry it), and it is
+ // what cancel attribution (wasCancelledBy) scopes by.
+ expect(script).toContain('caller=$PPID')
+ })
+})
+
+describe('AskpassServer', () => {
+ let server: AskpassServer | undefined
+
+ afterEach(() => {
+ server?.stop()
+ server = undefined
+ })
+
+ async function makeServer(handler?: (req: AskpassPromptRequest) => Promise<string | null>) {
+ const s = new AskpassServer()
+ if (handler) s.setPromptHandler(handler)
+ await s.start()
+ server = s
+ return s
+ }
+
+ async function post(
+ s: AskpassServer,
+ identity: string,
+ caller: string,
+ prompt = passphrasePrompt(identity)
+ ): Promise<{ status: number; body: string }> {
+ const res = await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'x-nodeterm-askpass-token': s.getToken()
+ },
+ body: new URLSearchParams({ identity, caller, prompt }).toString()
+ })
+ return { status: res.status, body: await res.text() }
+ }
+
+ it('answers a throwing prompt handler with an empty 200, and a wrong route with a clean 404', async () => {
+ // The catch is the SSH_ASKPASS contract's backstop: empty stdout = "no passphrase", never a
+ // hang. It must also never re-head a response that was already answered (the 404/403 bails
+ // above it), which would throw ERR_HTTP_HEADERS_SENT out of this un-awaited async callback
+ // and take the main process down with it.
+ const s = await makeServer(async () => {
+ throw new Error('handler blew up')
+ })
+ const res = await post(s, '/home/u/.ssh/id_ed25519', '111')
+ expect(res.status).toBe(200)
+ expect(res.body).toBe('')
+ const wrongRoute = await fetch(`http://127.0.0.1:${s.getPort()}/nope`, { method: 'GET' })
+ expect(wrongRoute.status).toBe(404)
+ expect(await wrongRoute.text()).toBe('')
+ })
+
+ it('rejects a bad token with 403', async () => {
+ const s = await makeServer()
+ const res = await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
+ method: 'POST',
+ headers: { 'x-nodeterm-askpass-token': 'wrong' }
+ })
+ expect(res.status).toBe(403)
+ })
+
+ it('holds no passphrase state: every NEW ssh process prompts (prompt-free reconnects are the agent, not us)', async () => {
+ // The old in-app cache served a second master from memory. AddKeysToAgent=yes replaced it:
+ // once the agent holds the key, ssh never invokes askpass at all, so any ask that DOES reach
+ // this server is one the agent could not answer and must go to the user.
+ const prompts: { identityFile: string; retry: boolean; caller: string }[] = []
+ const s = await makeServer(async (req) => {
+ prompts.push(req)
+ return 'hunter2'
+ })
+ const identity = '/home/u/.ssh/id_test_a'
+
+ const first = await post(s, identity, '111')
+ expect(first.body).toBe('hunter2')
+ const second = await post(s, identity, '222')
+ expect(second.body).toBe('hunter2')
+ expect(prompts).toEqual([
+ // `caller` is the asking master's pid, which is how main names the server on the dialog.
+ { identityFile: identity, retry: false, caller: '111' },
+ { identityFile: identity, retry: false, caller: '222' } // a new pid is a fresh connection, never a retry
+ ])
+ })
+
+ it('flags a second ask from the SAME ssh process as retry (the "didn\'t work" dialog copy)', async () => {
+ let calls = 0
+ const s = await makeServer(async (req) => {
+ calls++
+ expect(req.retry).toBe(calls > 1)
+ return calls === 1 ? 'wrong-guess' : 'right-guess'
+ })
+ const identity = '/home/u/.ssh/id_test_b'
+
+ const first = await post(s, identity, '333')
+ expect(first.body).toBe('wrong-guess')
+
+ // ssh re-invokes askpass with the SAME prompt text when the passphrase failed to decrypt.
+ const retry = await post(s, identity, '333')
+ expect(retry.body).toBe('right-guess')
+ expect(calls).toBe(2)
+ })
+
+ it('dedupes concurrent asks for the same identity into one prompt whose answer feeds both', async () => {
+ let calls = 0
+ const s = await makeServer(async () => {
+ calls++
+ await new Promise((r) => setTimeout(r, 50))
+ return 'shared-pw'
+ })
+ const identity = '/home/u/.ssh/id_test_c'
+ const [a, b] = await Promise.all([post(s, identity, '444'), post(s, identity, '555')])
+ expect(a.body).toBe('shared-pw')
+ expect(b.body).toBe('shared-pw')
+ expect(calls).toBe(1)
+ })
+
+ it('declining a SHARED dialog attributes the cancel to EVERY master that joined it', async () => {
+ // Two projects share one key: the second master joins the first master's in-flight dialog
+ // rather than opening its own. Recording only the first asker's pid on decline left the
+ // joiner's connect with wasCancelledBy(itsPid) === false, so one project showed "needs its
+ // passphrase" while the other showed the generic connection error for the same Cancel click.
+ let release: ((v: string | null) => void) | undefined
+ const s = await makeServer(() => new Promise((r) => (release = r)))
+ const identity = '/home/u/.ssh/id_test_joint'
+ const first = post(s, identity, '9001')
+ // Wait until the first ask's dialog is actually outstanding before the second joins it.
+ await new Promise<void>((resolve) => {
+ const tick = () => (s.isPromptingAny() ? resolve() : setTimeout(tick, 5))
+ tick()
+ })
+ const second = post(s, identity, '9002')
+ // Give the joiner's POST time to reach the in-flight dialog, then decline it once.
+ await new Promise((r) => setTimeout(r, 50))
+ release!(null)
+ const [a, b] = await Promise.all([first, second])
+ expect(a.body).toBe('')
+ expect(b.body).toBe('')
+ expect(s.wasCancelledBy(9001)).toBe(true)
+ expect(s.wasCancelledBy(9002)).toBe(true)
+ expect(s.wasCancelledBy(9003)).toBe(false) // a master that never asked stays unaffected
+ })
+
+ it('serializes prompts for different identities: one dialog at a time, both answered', async () => {
+ let active = 0
+ let maxActive = 0
+ const s = await makeServer(async (req) => {
+ active++
+ maxActive = Math.max(maxActive, active)
+ await new Promise((r) => setTimeout(r, 30))
+ active--
+ return `pw-for-${req.identityFile}`
+ })
+ const [a, b] = await Promise.all([
+ post(s, '/home/u/.ssh/id_d1', '666'),
+ post(s, '/home/u/.ssh/id_d2', '777')
+ ])
+ expect(maxActive).toBe(1)
+ expect(a.body).toBe('pw-for-/home/u/.ssh/id_d1')
+ expect(b.body).toBe('pw-for-/home/u/.ssh/id_d2')
+ })
+
+ it('a cancel answers empty, records the pid, and keeps NO suppression latch', async () => {
+ let calls = 0
+ const s = await makeServer(async () => {
+ calls++
+ return null
+ })
+ const identity = '/home/u/.ssh/id_test_e'
+
+ expect(s.cancelledRecently()).toBe(false)
+ const first = await post(s, identity, '888')
+ expect(first.body).toBe('')
+ expect(s.cancelledRecently()).toBe(true)
+ expect(s.wasCancelledBy(888)).toBe(true)
+
+ // There is deliberately no per-(key, pid) latch suppressing a repeat ask. ssh ABANDONS a key
+ // the moment it gets an empty answer, so the process that was declined never asks for that
+ // key again: a latch could only ever fire on a RECYCLED pid, where it would silently swallow
+ // a brand-new master's legitimate prompt and leave the user staring at a failed connect with
+ // no dialog. Prompting again is the safe direction for a case that cannot occur anyway.
+ const second = await post(s, identity, '888')
+ expect(second.body).toBe('')
+ expect(calls).toBe(2)
+ })
+
+ it('a LATER connect (new ssh pid) prompts again after a cancel, with no explicit reset', async () => {
+ let calls = 0
+ const s = await makeServer(async () => {
+ calls++
+ return calls === 1 ? null : 'second-time-pw'
+ })
+ const identity = '/home/u/.ssh/id_test_f'
+
+ await post(s, identity, '101') // cancelled
+ // A fresh master (fresh pid) must always get its own dialog; nothing lingers from a decline.
+ const second = await post(s, identity, '102')
+ expect(second.body).toBe('second-time-pw')
+ expect(calls).toBe(2)
+ })
+
+ it("a sibling connect does not wipe a concurrent master's retry counter (pid-scoped counting)", async () => {
+ // Two projects share one key: master B's fresh ask must read as a first ask, while master
+ // A's re-ask right after must STILL read as A's retry, or the dialog would drop its "that
+ // passphrase didn't work" wording exactly when the user needs it.
+ const flags: boolean[] = []
+ let calls = 0
+ const s = await makeServer(async (req) => {
+ flags.push(req.retry)
+ calls++
+ return calls === 1 ? 'wrong-guess' : 'right-guess'
+ })
+ const identity = '/home/u/.ssh/id_test_shared'
+
+ await post(s, identity, '501') // master A, first ask
+ await post(s, identity, '502') // sibling master B: its own first ask
+ await post(s, identity, '501') // master A asking AGAIN: a retry despite B in between
+ expect(flags).toEqual([false, false, true])
+ })
+
+ it('sets SSH_ASKPASS even when the server has NO configured identity file', () => {
+ // The regression this guards: saved servers usually have identityFile null (ssh then offers
+ // the default identities, which are exactly the ones likely to be encrypted). Returning {}
+ // here meant the tty-less master had no way to prompt and the whole feature was dead code.
+ const s = new AskpassServer()
+ const env = s.envFor(undefined, '/ud/ssh-askpass.sh')
+ expect(env.SSH_ASKPASS).toBe('/ud/ssh-askpass.sh')
+ expect(env.SSH_ASKPASS_REQUIRE).toBe('force')
+ expect(env.NODETERM_ASKPASS_IDENTITY).toBe('')
+ })
+
+ it('declines a server password prompt instead of answering it', async () => {
+ let calls = 0
+ const s = await makeServer(async () => {
+ calls++
+ return 'should-never-be-sent'
+ })
+ const identity = '/home/u/.ssh/id_test_pw'
+ const res = await post(s, identity, '601', "[email protected]'s password: ")
+ expect(res.body).toBe('')
+ expect(calls).toBe(0) // no dialog shown
+ })
+
+ it('a password prompt after a passphrase ask is not counted as a passphrase retry', async () => {
+ // Key decrypts fine but the server rejects publickey and falls back to password auth: the
+ // declined password prompt must not open a dialog, and must not pollute the retry counter
+ // (a later passphrase ask from this same pid would then wrongly say "that didn't work").
+ let calls = 0
+ const s = await makeServer(async (req) => {
+ calls++
+ expect(req.retry).toBe(false)
+ return 'correct-passphrase'
+ })
+ const identity = '/home/u/.ssh/id_test_fallback'
+
+ await post(s, identity, '701')
+ const fallback = await post(s, identity, '701', "[email protected]'s password: ")
+ expect(fallback.body).toBe('')
+ expect(calls).toBe(1)
+ })
+
+ it('keys the ask under the key the PROMPT names, not the configured -i identity', async () => {
+ // Without IdentitiesOnly (no configured identityFile), ssh also offers default identities:
+ // the prompt names the real key, and that is what the dialog, the retry counter and the
+ // in-flight coalescing must be keyed by.
+ const s = await makeServer(async (req) => `pw-for-${req.identityFile}`)
+ const configured = '/home/u/.ssh/id_configured'
+ const actual = '/home/u/.ssh/id_default'
+ const res = await post(s, configured, '801', passphrasePrompt(actual))
+ expect(res.body).toBe(`pw-for-${actual}`)
+ })
+
+ it('drops an oversized body without wedging the server', async () => {
+ const s = await makeServer(async () => 'never-asked')
+ const big = 'x'.repeat(80_000)
+ await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'x-nodeterm-askpass-token': s.getToken()
+ },
+ body: `identity=${big}`
+ }).catch(() => undefined) // the server destroys the connection; a reset here is expected
+ // The server must still answer the next, well-formed request.
+ const after = await post(s, '/home/u/.ssh/id_test_i', '401')
+ expect(after.status).toBe(200)
+ })
+
+ it('attributes a decline to the ssh process that was asked, not to a global clock', async () => {
+ // The failure message used to come from a process-wide timestamp, so a Cancel on one project
+ // relabelled an unrelated project's genuine auth failure as "needs its passphrase" for the
+ // next 60s. The askpass helper's $PPID is the master pid (verified against a real sshd), so
+ // the answer can be exact.
+ const s = await makeServer(async () => null)
+ const identity = '/home/u/.ssh/id_test_pid'
+ await post(s, identity, '4242') // master 4242's prompt was declined
+
+ expect(s.wasCancelledBy(4242)).toBe(true)
+ expect(s.wasCancelledBy(9999)).toBe(false) // a different project's master: unaffected
+ // Only a caller that cannot name its master (adopted orphan, test fake) falls back to time.
+ expect(s.wasCancelledBy(undefined)).toBe(true)
+ })
+
+ it('envFor passes the configured identity file through as a hint', async () => {
+ const s = new AskpassServer()
+ const env = s.envFor('/home/u/.ssh/id_ed25519', '/ud/ssh-askpass.sh')
+ expect(env.SSH_ASKPASS).toBe('/ud/ssh-askpass.sh')
+ expect(env.SSH_ASKPASS_REQUIRE).toBe('force')
+ expect(env.NODETERM_ASKPASS_IDENTITY).toBe('/home/u/.ssh/id_ed25519')
+ })
+})
diff --git a/src/main/remote-ssh/ssh-askpass.ts b/src/main/remote-ssh/ssh-askpass.ts
new file mode 100644
index 000000000..f6b4a3b36
--- /dev/null
+++ b/src/main/remote-ssh/ssh-askpass.ts
@@ -0,0 +1,393 @@
+// SSH_ASKPASS support for the project ControlMaster (ssh-project.ts), which spawns ssh with no
+// tty (stdio ignored), so OpenSSH has nowhere to prompt for an encrypted identity file's
+// passphrase. This gives it somewhere: a generated askpass script that curls a loopback server
+// here, which in turn asks the renderer (via an injected prompt handler). No electron import,
+// unit-testable like hook-server.ts's HookServer, against a real ephemeral port.
+//
+// This server deliberately holds NO passphrase state. masterArgs sets `AddKeysToAgent=yes`, so a
+// successful unlock loads the key into an ssh-agent and every later connect (reconnect, watchdog
+// respawn) authenticates through it without askpass ever being invoked (measured against a real
+// sshd: second connect on a fresh master, zero prompts, even with SSH_ASKPASS removed). The agent
+// supersedes the in-app passphrase cache that used to live in ssh-passphrase-cache.ts: it holds
+// the decrypted key in a purpose-built process instead of a plaintext string in Electron main
+// memory. That agent is nodeterm's OWN (ssh-agent.ts), spawned and killed with the app, so the
+// unlock lasts one app run rather than until the user's next logout. When no agent is reachable
+// ssh skips the add silently and this prompt simply fires once per connect, the pre-cache behavior.
+//
+// Two OpenSSH behaviors (verified against sshconnect2.c / readpass.c) shape what remains:
+//
+// - ssh re-invokes askpass with the BYTE-IDENTICAL "Enter passphrase for key ..." prompt when
+// the previous answer failed to decrypt the key (the "Bad passphrase, try again" wording
+// belongs to ssh-add, not ssh). Prompt text can therefore never signal a retry. Instead the
+// script reports its $PPID (the invoking ssh process), and a SECOND passphrase ask from the
+// same (key, ssh pid) pair means the last answer did not work: see `asked`, which exists
+// solely to put the "that passphrase didn't work" wording on the dialog.
+// - An EMPTY answer makes ssh abandon that key immediately rather than retrying, which is what
+// makes Cancel clean, and what makes declining a non-passphrase prompt safe (see below). It is
+// also why there is NO per-(key, pid) cancel latch here: a declined ssh process never asks for
+// that key again, so a latch could only ever fire on a RECYCLED pid, silently suppressing a
+// brand-new master's legitimate prompt.
+//
+// SSH_ASKPASS_REQUIRE=force routes EVERY interactive prompt through this helper, including the
+// server's password / keyboard-interactive prompts when publickey auth is rejected. Those are
+// not ours to answer: this feature unlocks local key files. Answering them would send a server
+// password where a key passphrase belongs and mislabel the dialog, so a non-passphrase prompt is
+// declined with an empty answer, which is exactly the behavior of the tty-less master before
+// askpass existed.
+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
+import { randomUUID, timingSafeEqual } from 'crypto'
+import { promises as fs } from 'fs'
+import path from 'path'
+
+const ASKPASS_SCRIPT_NAME = 'ssh-askpass.sh'
+/** A passphrase prompt body is a few bytes; cap generously against a misbehaving caller. */
+const MAX_BODY_BYTES = 65_536
+/** Ask-counter ceiling. Entries are keyed by (key path, ssh pid) and a finished ssh process
+ * never asks again, so they are dead weight once its connect ends; there is no exit signal to
+ * prune them by, so the whole map is dropped when it grows past this. Worst case after a drop:
+ * one retry prompt reads as a first ask and loses its "didn't work" wording. Cosmetic. */
+const MAX_ASK_ENTRIES = 500
+
+function readBody(req: IncomingMessage): Promise<string> {
+ return new Promise((resolve) => {
+ const chunks: Buffer[] = []
+ let bytes = 0
+ req.on('data', (c: Buffer) => {
+ chunks.push(c)
+ bytes += c.length
+ if (bytes > MAX_BODY_BYTES) req.destroy()
+ })
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))
+ req.on('error', () => resolve(''))
+ // req.destroy() (the oversize path above) emits neither 'end' nor 'error', only 'close'.
+ // Resolving on close keeps the handler from waiting forever on a dropped request. A double
+ // resolve on the normal path is harmless, promises settle once.
+ req.on('close', () => resolve(''))
+ })
+}
+
+/** ssh's key-passphrase prompt: `Enter passphrase for key '/home/u/.ssh/id_ed25519': `. The
+ * wording is a hardcoded English literal in OpenSSH (no i18n upstream, none in distro patches),
+ * and the quoted path is the key ssh actually wants unlocked, which is NOT always the `-i`
+ * identity: without IdentitiesOnly, ssh also offers the default identities. */
+const PASSPHRASE_PROMPT = /enter passphrase for key\s*'([^']*)'/i
+
+/**
+ * Classify what ssh is asking for. `keyPath` is the key named by the prompt when it carries one,
+ * and it is what the retry counting and dialog coalescing key by: the configured `-i` identity is
+ * not always the key ssh is unlocking (with no `-i` at all, ssh offers the default identities).
+ */
+export function classifyPrompt(prompt: string): { passphrase: boolean; keyPath?: string } {
+ const m = PASSPHRASE_PROMPT.exec(prompt)
+ if (m) return { passphrase: true, keyPath: m[1] || undefined }
+ // Defensive: a passphrase ask whose shape we do not recognize still must not be mistaken for
+ // a server password prompt ("...@host's password:" never contains the word "passphrase").
+ if (/passphrase/i.test(prompt)) return { passphrase: true }
+ return { passphrase: false }
+}
+
+/**
+ * The SSH_ASKPASS helper ssh invokes when it needs a passphrase and has no tty to prompt into.
+ * One curl POST to our loopback server, printing whatever it returns (the passphrase, or nothing
+ * on cancel) to stdout, which is exactly SSH_ASKPASS's contract. Generated at runtime into
+ * userData rather than bundled via electron-builder, so packaging needs no changes (mirrors how
+ * hook-server.ts writes hook-endpoint.env there); curl is already a hard runtime dependency of
+ * this app's agent hooks, so this introduces nothing new. Values are env-expanded by sh and the
+ * results are never re-parsed, so hostile characters in a path cannot inject.
+ */
+export function buildAskpassScript(): string {
+ return [
+ '#!/bin/sh',
+ 'answer=$(curl -sS --max-time 300 -X POST "http://127.0.0.1:${NODETERM_ASKPASS_PORT}/prompt" \\',
+ ' -H "X-Nodeterm-Askpass-Token: ${NODETERM_ASKPASS_TOKEN}" \\',
+ ' --data-urlencode "identity=${NODETERM_ASKPASS_IDENTITY}" \\',
+ ' --data-urlencode "caller=$PPID" \\',
+ ' --data-urlencode "prompt=$1")',
+ // A failure here is otherwise INVISIBLE: ssh reads empty stdout as "no passphrase", abandons
+ // the key, and the connect dies with a bare "Permission denied (publickey)" that says nothing
+ // about the helper. (Exactly how a container with no curl looked.) The breadcrumb goes to
+ // stderr, which is the master's captured stderr, so it reaches the app's log.
+ '[ $? -eq 0 ] || { echo "nodeterm-askpass: no answer from the app on 127.0.0.1:${NODETERM_ASKPASS_PORT} (curl missing or the app is gone)" >&2; exit 1; }',
+ "printf '%s' \"$answer\"",
+ ''
+ ].join('\n')
+}
+
+/** Write the askpass script into userData (idempotent overwrite each launch) and return its path. */
+export async function ensureAskpassScript(userDataDir: string): Promise<string> {
+ const p = path.join(userDataDir, ASKPASS_SCRIPT_NAME)
+ await fs.mkdir(userDataDir, { recursive: true })
+ // 0o700: invoked by ssh with the user's own env, owner-only like the ControlMaster socket dir.
+ await fs.writeFile(p, buildAskpassScript(), { encoding: 'utf8', mode: 0o700 })
+ return p
+}
+
+export interface AskpassPromptRequest {
+ identityFile: string
+ /** True when the SAME ssh process already asked for this key, i.e. the previous answer failed
+ * to decrypt it. Drives the "that passphrase didn't work" dialog copy. */
+ retry: boolean
+ /** The asking ssh master's pid (the helper's $PPID), when it reported one. The handler maps it
+ * back to the connection being unlocked so the dialog can name the server. Empty for a caller
+ * that cannot report a pid. */
+ caller: string
+}
+
+/** `null` = the user actively declined. `undefined` = nobody answered (prompt expired, or there
+ * was no UI to ask). Both send ssh an empty answer, but only a decline is reported as a
+ * cancellation, so someone who simply walked away is not told they cancelled. */
+type PromptHandler = (req: AskpassPromptRequest) => Promise<string | null | undefined>
+
+export class AskpassServer {
+ private server: Server | null = null
+ private port = 0
+ private token = ''
+ private promptHandler: PromptHandler | null = null
+ /** Caller pids (the ssh process the askpass helper reported as its $PPID) whose prompt the user
+ * DECLINED. Verified against a real sshd: the helper's $PPID is exactly the master process the
+ * app spawned, so connect() can ask "was MY master's prompt cancelled" and get an exact answer
+ * instead of the time-scoped guess below. Capped like `asked` (no exit signal to prune by).
+ * Known residual: an entry outlives its process, so on a pid-wrapping host a much later master
+ * that happens to reuse a recorded pid AND fails without ever prompting gets its failure
+ * phrased as "cancelled". Cosmetic (the connect failed either way), bounded by the cap. */
+ private cancelledCallers = new Set<string>()
+ /** When the last cancel happened. Fallback ONLY for callers that cannot report a master pid
+ * (an adopted orphan master, test fakes). Being process-global, it can attribute one project's
+ * cancel to another project's unrelated failure inside the window, which is exactly why the
+ * pid-keyed set above is preferred whenever a pid is available. */
+ private lastCancelAt = 0
+ /** Passphrase-ask counts keyed by key path + NUL + caller pid (NUL cannot occur in a path, so
+ * keys never collide). Kept for ONE purpose now that the agent replaced the passphrase cache:
+ * a count above zero means the same ssh process is asking again, i.e. the previous answer
+ * failed to decrypt the key, and that is what selects the "that passphrase didn't work"
+ * dialog copy (ssh's retry prompt is byte-identical to the first, so the text cannot carry
+ * it). Deliberately NOT cleared per attempt: a fresh master always has a fresh pid, so
+ * clearing would only wipe a CONCURRENT attempt's counters (two projects can share one key)
+ * and mislabel that attempt's retry as a first ask. */
+ private asked = new Map<string, number>()
+ /** Serializes dialogs across keys: the renderer shows one passphrase prompt at a time. */
+ private queue: Promise<unknown> = Promise.resolve()
+ /** In-flight prompt per key, so concurrent asks (two projects sharing a key) collapse into one
+ * dialog whose answer feeds every waiter. `callers` collects EVERY master pid that joined the
+ * dialog, not just the first asker's: a decline must be recorded for each of them, or the
+ * second project's connect would miss the cancel (`wasCancelledBy` its own pid = false) and
+ * report the generic connection error instead of the "needs its passphrase" one. */
+ private inflight = new Map<string, { done: Promise<string | null>; callers: Set<string> }>()
+
+ getPort(): number {
+ return this.port
+ }
+ getToken(): string {
+ return this.token
+ }
+
+ setPromptHandler(cb: PromptHandler): void {
+ this.promptHandler = cb
+ }
+
+ async start(): Promise<void> {
+ if (this.server) return
+ this.token = randomUUID()
+ this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
+ try {
+ if (req.method !== 'POST' || !(req.url ?? '').startsWith('/prompt')) {
+ res.writeHead(404)
+ res.end()
+ return
+ }
+ if (!this.tokenMatches(req.headers['x-nodeterm-askpass-token'])) {
+ res.writeHead(403)
+ res.end()
+ return
+ }
+ const body = new URLSearchParams(await readBody(req))
+ const answer = await this.resolvePassphrase(
+ body.get('identity') ?? '',
+ body.get('caller') ?? '',
+ body.get('prompt') ?? ''
+ )
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
+ res.end(answer ?? '')
+ } catch {
+ // SSH_ASKPASS contract: empty stdout means "no passphrase" to ssh, never a hang. ssh
+ // abandons the key on an empty answer, so a failure here degrades to a clean auth error.
+ // headersSent guard: this callback is async and nothing awaits it, so a throw AFTER a
+ // response was already headed (the 404/403 bails, or res.end on a dead socket) would make
+ // this second writeHead throw ERR_HTTP_HEADERS_SENT into an unhandled rejection, i.e. a
+ // main-process crash for a request that had already been answered.
+ if (!res.headersSent) res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
+ res.end('')
+ }
+ })
+ await new Promise<void>((resolve, reject) => {
+ const onErr = (e: Error): void => {
+ this.server?.off('listening', onOk)
+ reject(e)
+ }
+ const onOk = (): void => {
+ this.server?.off('error', onErr)
+ this.server?.on('error', (e) => console.error('[ssh-askpass] server error', e))
+ const addr = this.server!.address()
+ if (addr && typeof addr === 'object') this.port = addr.port
+ resolve()
+ }
+ this.server!.once('error', onErr)
+ this.server!.listen(0, '127.0.0.1', onOk)
+ })
+ }
+
+ stop(): void {
+ this.server?.close()
+ this.server = null
+ this.port = 0
+ this.token = ''
+ }
+
+ private async resolvePassphrase(
+ identityEnv: string,
+ caller: string,
+ prompt: string
+ ): Promise<string | null> {
+ const kind = classifyPrompt(prompt)
+ // Not a key passphrase (server password, keyboard-interactive/2FA): decline. ssh treats the
+ // empty answer as "no answer" and moves on, exactly as it did before askpass was wired up.
+ if (!kind.passphrase) return null
+ // Prefer the key named by the prompt: ssh may be unlocking a default identity rather than
+ // the configured `-i` one, and latching/counting under the configured path would be wrong.
+ const identityFile = kind.keyPath || identityEnv
+ if (!identityFile) return null
+
+ const askKey = `${identityFile}\u0000${caller}`
+ const seen = this.asked.get(askKey) ?? 0
+ if (this.asked.size >= MAX_ASK_ENTRIES) this.asked.clear()
+ this.asked.set(askKey, seen + 1)
+
+ if (!this.promptHandler) return null
+ // seen > 0: the SAME ssh process asking again, so the previous answer failed to decrypt.
+ // No cancel latch guards this path: a declined ssh process abandons the key immediately on
+ // the empty answer (see the header), so it never asks for the same key again.
+ return this.askUser(identityFile, caller, seen > 0)
+ }
+
+ private askUser(identityFile: string, caller: string, retry: boolean): Promise<string | null> {
+ const existing = this.inflight.get(identityFile)
+ if (existing) {
+ // A second master joining the dialog must be attributable too: record its pid alongside
+ // the first asker's, so a decline marks BOTH connects as cancelled (see `inflight`).
+ if (caller) existing.callers.add(caller)
+ return existing.done
+ }
+ const callers = new Set<string>(caller ? [caller] : [])
+ const turn = this.queue.then(async () => {
+ // The FIRST asker's pid is what the dialog is labelled from: joiners share this one dialog
+ // (see `inflight`), so a key serving two servers names whichever asked first.
+ const answer = await this.promptHandler!({ identityFile, retry, caller })
+ if (answer == null) {
+ // A decline is recorded per joined master pid so each waiter's connect can attribute it.
+ // An expiry records nothing: the user declined nothing, and reporting "you cancelled"
+ // for a prompt that merely timed out would be a lie.
+ if (answer === null) {
+ for (const c of callers) {
+ if (this.cancelledCallers.size >= MAX_ASK_ENTRIES) this.cancelledCallers.clear()
+ this.cancelledCallers.add(c)
+ }
+ this.lastCancelAt = Date.now()
+ }
+ return null
+ }
+ return answer
+ })
+ this.queue = turn.then(
+ () => undefined,
+ () => undefined
+ )
+ const done = turn.finally(() => {
+ this.inflight.delete(identityFile)
+ })
+ this.inflight.set(identityFile, { done, callers })
+ return done
+ }
+
+ /**
+ * Did the user cancel a passphrase prompt in the last `withinMs`? Used only to phrase the
+ * connect failure ("needs its passphrase" vs a generic error). Time-scoped rather than keyed by
+ * identity because a connection with no configured identity file cannot know which key ssh will
+ * ask about until the prompt arrives, and by then the attempt has already failed.
+ */
+ cancelledRecently(withinMs = 60_000): boolean {
+ return this.lastCancelAt > 0 && Date.now() - this.lastCancelAt <= withinMs
+ }
+
+ /**
+ * Did THIS master ever ask for a passphrase? A connect that failed without ever asking had no
+ * key FILE in play at all, which is what separates "wrong/declined passphrase" from "the only
+ * credential lives in an agent we are not pointing at" (see ssh-project's ambient-agent retry).
+ */
+ askedBy(masterPid?: number): boolean {
+ if (masterPid === undefined) return false
+ // `asked` is keyed `<key path>\u0000<caller pid>` (see resolvePassphrase); NUL cannot occur
+ // in a path, so a suffix match is exact. Scanning beats a second index: the map is capped.
+ const suffix = `\u0000${masterPid}`
+ for (const k of this.asked.keys()) if (k.endsWith(suffix)) return true
+ return false
+ }
+
+ /**
+ * Did the user decline the prompt raised by THIS master? Exact when the caller can name its
+ * master's pid, because the askpass helper's $PPID is that same process. Without a pid (adopted
+ * orphan, test fake) it degrades to the time-scoped answer, which can misattribute another
+ * project's cancel and is therefore only a last resort.
+ */
+ wasCancelledBy(masterPid?: number): boolean {
+ if (masterPid !== undefined) return this.cancelledCallers.has(String(masterPid))
+ return this.cancelledRecently()
+ }
+
+ /**
+ * Env vars for the ControlMaster spawn so ssh routes its passphrase prompt through us.
+ *
+ * Set for EVERY connection, including ones with no configured identity file. That is the whole
+ * point: a saved server usually has `identityFile: null` (the app only fills it in when
+ * `~/.ssh/config` named an `IdentityFile`), and ssh then offers the DEFAULT identities
+ * (`~/.ssh/id_ed25519`, `id_rsa`, …). Those are exactly the keys most likely to be encrypted.
+ * Gating this on a configured identity file made the whole feature dead code for the common
+ * case: the tty-less master had no way to prompt and simply failed auth.
+ *
+ * Harmless when nothing needs unlocking: ssh only executes the helper if it actually has to ask
+ * (agent auth and unencrypted keys never invoke it, which is also why a key already loaded by
+ * `AddKeysToAgent` produces no prompt at all). `identityFile` is passed only as a hint; the
+ * authoritative key is the one named by the prompt (see `classifyPrompt`).
+ */
+ envFor(identityFile: string | undefined, scriptPath: string): Record<string, string> {
+ return {
+ SSH_ASKPASS: scriptPath,
+ // Modern OpenSSH (8.4+) forces askpass with this even though the master has no tty. Older
+ // OpenSSH instead gates askpass on DISPLAY being set (with no tty); set both for portability.
+ SSH_ASKPASS_REQUIRE: 'force',
+ DISPLAY: process.env.DISPLAY || ':0',
+ NODETERM_ASKPASS_PORT: String(this.port),
+ NODETERM_ASKPASS_TOKEN: this.token,
+ // Only a hint, and often absent: a saved server usually has no configured identity file.
+ // The prompt names the key ssh actually wants, and that is what the latch/counting key by.
+ NODETERM_ASKPASS_IDENTITY: identityFile ?? ''
+ }
+ }
+
+ /** Is ANY passphrase prompt outstanding (shown, or queued behind another dialog)? A connect
+ * whose server has no configured identity file does not know which key ssh will ask about, so
+ * it can only ask the unkeyed question. Used purely to keep waiting, and only by spawners
+ * that cannot report process exit. */
+ isPromptingAny(): boolean {
+ return this.inflight.size > 0
+ }
+
+ // Constant-time bearer-token check (avoids a timing side channel on the compare).
+ private tokenMatches(provided: string | string[] | undefined): boolean {
+ if (typeof provided !== 'string' || !this.token) return false
+ const a = Buffer.from(provided)
+ const b = Buffer.from(this.token)
+ return a.length === b.length && timingSafeEqual(a, b)
+ }
+}
+
+export const askpassServer = new AskpassServer()
diff --git a/src/main/remote-ssh/ssh-passphrase-prompt.test.ts b/src/main/remote-ssh/ssh-passphrase-prompt.test.ts
new file mode 100644
index 000000000..ea8827b59
--- /dev/null
+++ b/src/main/remote-ssh/ssh-passphrase-prompt.test.ts
@@ -0,0 +1,119 @@
+// The main→renderer half of the passphrase prompt (ssh-project.ts): deliver the request, wait
+// for the renderer's submit, expire abandoned prompts, and fail fast when no UI can hear it.
+// None of this needs Electron: main-window.ts takes any MainWindowLike via setMainWindow, and
+// resolvePassphrasePrompt is exactly what the ipcMain.handle(sshPassphraseSubmit) delegates to.
+// Before these tests, a swapped (requestId, value) argument or a renamed channel was green
+// everywhere except a live app.
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { promptForPassphrase, resolvePassphrasePrompt } from './ssh-project'
+import { setMainWindow, type MainWindowLike } from '../main-window'
+import { IPC } from '../../shared/ipc'
+import type { SshPassphraseRequest } from '../../shared/types'
+
+/** Everything promptForPassphrase pushed at the (fake) renderer, in order. */
+type Sent = { channel: string; payload: Record<string, unknown> }
+
+function installWindow(opts?: { destroyed?: boolean; sendThrows?: boolean }): Sent[] {
+ const sent: Sent[] = []
+ const win: MainWindowLike = {
+ isDestroyed: () => opts?.destroyed ?? false,
+ isFocused: () => true,
+ isMinimized: () => false,
+ restore: () => {},
+ show: () => {},
+ focus: () => {},
+ on: () => {},
+ webContents: {
+ send: (channel: string, ...args: unknown[]) => {
+ // Mirrors the real failure mode: webContents.send throws "Render frame was disposed"
+ // while the window object itself still looks alive.
+ if (opts?.sendThrows) throw new Error('Render frame was disposed')
+ sent.push({ channel, payload: args[0] as Record<string, unknown> })
+ }
+ }
+ }
+ setMainWindow(win)
+ return sent
+}
+
+afterEach(() => {
+ vi.useRealTimers()
+ // Leave no live fake window behind for other tests in this file.
+ installWindow({ destroyed: true })
+})
+
+describe('promptForPassphrase / resolvePassphrasePrompt', () => {
+ it('delivers the request on the right channel and resolves with the submitted value', async () => {
+ const sent = installWindow()
+ const p = promptForPassphrase({ identityFile: '/home/u/.ssh/id_ed25519', retry: true, target: 'u@h1' })
+ expect(sent).toHaveLength(1)
+ expect(sent[0].channel).toBe(IPC.sshPassphraseRequest)
+ const req = sent[0].payload as unknown as SshPassphraseRequest
+ expect(req.identityFile).toBe('/home/u/.ssh/id_ed25519')
+ expect(req.retry).toBe(true)
+ expect(req.requestId).toBeTruthy()
+ // One key can serve several servers and this prompt can fire from the watchdog, so the dialog
+ // has to be able to name the destination it is unlocking for.
+ expect(req.target).toBe('u@h1')
+ // The (requestId, value) order is the load-bearing contract with the renderer's submit.
+ resolvePassphrasePrompt(req.requestId, 'hunter2')
+ await expect(p).resolves.toBe('hunter2')
+ })
+
+ it('a null submit (the Cancel button) resolves null, i.e. an ACTIVE decline', async () => {
+ const sent = installWindow()
+ const p = promptForPassphrase({ identityFile: '/k', retry: false })
+ const req = sent[0].payload as unknown as SshPassphraseRequest
+ resolvePassphrasePrompt(req.requestId, null)
+ await expect(p).resolves.toBeNull()
+ })
+
+ it('expires an abandoned prompt as undefined (never "cancelled") and dismisses the dialog', async () => {
+ vi.useFakeTimers()
+ const sent = installWindow()
+ const p = promptForPassphrase({ identityFile: '/k', retry: false })
+ const req = sent[0].payload as unknown as SshPassphraseRequest
+ await vi.advanceTimersByTimeAsync(301_000) // just past the 5-minute prompt expiry
+ // undefined = nobody answered; only an explicit null may be reported as a cancellation.
+ await expect(p).resolves.toBeUndefined()
+ // The renderer's (possibly still open) dialog is closed so a late answer has nowhere to land.
+ const dismiss = sent.find((s) => s.channel === IPC.sshPassphraseDismiss)
+ expect(dismiss?.payload).toEqual({ requestId: req.requestId })
+ // A late submit against the expired request is a silent no-op, not a crash.
+ expect(() => resolvePassphrasePrompt(req.requestId, 'too-late')).not.toThrow()
+ })
+
+ it('resolves undefined immediately when no window exists (nobody could ever answer)', async () => {
+ installWindow({ destroyed: true })
+ // Must not ride the 5-minute expiry: with the window closed (macOS close-to-dock) the
+ // watchdog would otherwise hold every reconnect's master for the full window, repeatedly.
+ await expect(promptForPassphrase({ identityFile: '/k', retry: false })).resolves.toBeUndefined()
+ })
+
+ it('resolves undefined immediately when the send throws (frame disposed mid-reload)', async () => {
+ installWindow({ sendThrows: true })
+ await expect(promptForPassphrase({ identityFile: '/k', retry: false })).resolves.toBeUndefined()
+ })
+
+ it('a double submit resolves once and the second is a no-op', async () => {
+ const sent = installWindow()
+ const p = promptForPassphrase({ identityFile: '/k', retry: false })
+ const req = sent[0].payload as unknown as SshPassphraseRequest
+ resolvePassphrasePrompt(req.requestId, 'first')
+ resolvePassphrasePrompt(req.requestId, 'second')
+ await expect(p).resolves.toBe('first')
+ })
+
+ it('concurrent prompts resolve independently by requestId', async () => {
+ const sent = installWindow()
+ const a = promptForPassphrase({ identityFile: '/ka', retry: false })
+ const b = promptForPassphrase({ identityFile: '/kb', retry: false })
+ const [reqA, reqB] = sent.map((s) => s.payload as unknown as SshPassphraseRequest)
+ expect(reqA.requestId).not.toBe(reqB.requestId)
+ // Answer them out of order: each answer must land on ITS request, not the newest one.
+ resolvePassphrasePrompt(reqB.requestId, 'for-b')
+ resolvePassphrasePrompt(reqA.requestId, 'for-a')
+ await expect(a).resolves.toBe('for-a')
+ await expect(b).resolves.toBe('for-b')
+ })
+})
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index bcd9c4b8d..b5cfc62cd 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -3,6 +3,7 @@ import os from 'os'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SshProjectManager, lastSshErrorLine } from './ssh-project'
+import { AskpassServer } from './ssh-askpass'
import { controlPathFor } from '../../core/remote-ssh/control-master'
const conn = { host: 'h', user: 'u' }
@@ -29,11 +30,11 @@ describe('SshProjectManager', () => {
const { mgr, statuses } = makeMgr()
const { controlPath } = await mgr.connect('p1', conn)
expect(controlPath).toBe(controlPathFor('p1'))
- // (A later `connected` event can carry the async claude-CLI probe's answer — see below.)
+ // (A later `connected` event can carry the async claude-CLI probe's answer, see below.)
expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])
})
- it('connect is idempotent — second call reuses the live master', async () => {
+ it('connect is idempotent, second call reuses the live master', async () => {
const { mgr, spawnMaster } = makeMgr()
await mgr.connect('p1', conn)
await mgr.connect('p1', conn)
@@ -85,7 +86,7 @@ describe('SshProjectManager', () => {
await mgr.connect('p1', conn)
const before = run.mock.calls.length
expect(await mgr.writePendingAnswer('p1', '../evil', 'allow')).toBe(false)
- // @ts-expect-error — runtime guard against a bad decision value
+ // @ts-expect-error, runtime guard against a bad decision value
expect(await mgr.writePendingAnswer('p1', 'ok-id', 'always')).toBe(false)
expect(run.mock.calls.length).toBe(before) // neither refusal touched ssh
})
@@ -166,7 +167,7 @@ describe('SshProjectManager', () => {
it('connect leaves tmuxConfPath undefined when the remote conf write fails (no -f to a missing conf)', async () => {
// The runner resolves (does not throw) on a non-zero remote exit. Fail the `cat >`/mkdir write
- // with code 1 while letting the $HOME probe succeed so remoteHome resolves — this isolates the
+ // with code 1 while letting the $HOME probe succeed so remoteHome resolves, this isolates the
// write-failure path. tmuxConfPath must stay undefined (so no `-f <missing-conf>`), yet connect
// still succeeds and returns the control path.
const run = vi.fn(async (args: string[]) => {
@@ -191,10 +192,10 @@ describe('SshProjectManager', () => {
// --- remote `claude --version` probe ------------------------------------------------------
//
// The probe runs through a LOGIN shell, so the user's profile can print banners to stdout. The
- // value is marker-delimited and only what sits between the markers is parsed — a banner version
+ // value is marker-delimited and only what sits between the markers is parsed, a banner version
// (`Ubuntu 22.04.3`) must NEVER be read as claude's version, or every Claude node in the project
// would launch `--permission-mode auto` on a CLI that exits 1 on it.
- const BANNER = 'Welcome — Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-89-generic)\nkernel 6.8.0-106\n'
+ const BANNER = 'Welcome, Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-89-generic)\nkernel 6.8.0-106\n'
/** A manager whose remote claude probe answers with `banner + <markers>version</markers>`.
* Pass an array to script successive probe attempts (retry coverage); the last entry repeats. */
@@ -270,7 +271,7 @@ describe('SshProjectManager', () => {
})
it('a FAILED probe reports version null (distinguishable from "old CLI") and retries', async () => {
- // First attempt: markers absent (claude not found — e.g. a transient PATH/login-shell hiccup);
+ // First attempt: markers absent (claude not found, e.g. a transient PATH/login-shell hiccup);
// second attempt: a modern CLI. The first answer must land immediately (fail-open `false`,
// version null) so launch paths never wait on retries, and the retry must upgrade it to `true`.
const { mgr, events } = mgrWithClaude(
@@ -415,7 +416,7 @@ describe('SshProjectManager', () => {
expect(await fs.readdir(dir)).toEqual(['notes.md'])
})
- it('never overwrites an existing file — it takes the next (n) name', async () => {
+ it('never overwrites an existing file, it takes the next (n) name', async () => {
const { mgr } = makeDlMgr()
await mgr.connect('p1', conn, '/srv/repo')
const dir = await destDir()
@@ -434,7 +435,7 @@ describe('SshProjectManager', () => {
expect(scpCalls[0]).toContain('-r')
})
- it('a failed transfer leaves nothing behind — no target, no .part', async () => {
+ it('a failed transfer leaves nothing behind, no target, no .part', async () => {
const { mgr } = makeDlMgr(false, 1)
await mgr.connect('p1', conn, '/srv/repo')
const dir = await destDir()
@@ -485,12 +486,15 @@ describe('SshProjectManager', () => {
//
// A master socket FILE can outlive its process (app crash, `kill -9`, host sleep). ssh's
// ControlMaster=auto refuses to bind over an existing socket file, so a stale one makes every
- // `-O check` fail and connect() time out with a generic error — the field-reported "SSH
+ // `-O check` fail and connect() time out with a generic error, the field-reported "SSH
// connection error" with no cause. A fresh connect must clear a dead leftover before spawning.
describe('leftover master socket', () => {
const isCheck = (args: string[]) => args[0] === '-O' && args[1] === 'check'
- afterEach(() => vi.restoreAllMocks())
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
it('unlinks a DEAD leftover socket before spawning a fresh master', async () => {
const statuses: string[] = []
@@ -523,7 +527,7 @@ describe('SshProjectManager', () => {
it('adopts a LIVE orphan master (whose hook tunnel verifies) instead of spawning a second one', async () => {
const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
// Live master answers `-O check`; its reverse hook tunnel VERIFIES (the curl returns 204), so
- // `remoteHooks.setup` succeeds and the orphan is kept — no fresh master is built.
+ // `remoteHooks.setup` succeeds and the orphan is kept, no fresh master is built.
const run = vi.fn(async (args: string[]) => {
const j = args.join(' ')
if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
@@ -550,12 +554,14 @@ describe('SshProjectManager', () => {
it('rebuilds a FRESH master when the adopted orphan cannot re-establish the hook tunnel', async () => {
// Fresh-launch-straight-to-SSH field bug: the adopted live-orphan master still serves the
// PREVIOUS run's reverse-hook forward (dead port), so `setup()`'s tunnel never verifies over it.
- // The reverse tunnel — and with it every remote agent's status hooks — must come back WITHOUT
+ // The reverse tunnel, and with it every remote agent's status hooks, must come back WITHOUT
// any local activity, so connect() drops the orphan and rebuilds a fresh master, over which the
// tunnel verifies. The `%{http_code}` curl answers 000 (dead) until a fresh master is spawned.
let respawned = false
+ const seq: string[] = []
const spawnMaster = vi.fn(() => {
respawned = true
+ seq.push('spawn')
return { kill: vi.fn(), on: vi.fn() }
})
const run = vi.fn(async (args: string[]) => {
@@ -573,18 +579,159 @@ describe('SshProjectManager', () => {
run,
runScp: vi.fn(async () => ({ code: 0 })),
getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
- onStatus: (e) => statuses.push(e.status)
+ onStatus: (e) => statuses.push(e.status),
+ // The rebuild is the SECOND spawn site: it too must have the app agent listening before
+ // ssh authenticates, or the rebuilt master's unlocked key goes nowhere. The fresh-spawn
+ // ordering test cannot catch this site; asserting it here does.
+ ensureAgent: vi.fn(async () => {
+ await new Promise((r) => setImmediate(r))
+ seq.push('agent')
+ })
})
const info = await mgr.connect('p1', conn)
// The orphan was dropped (its `-O exit` ran + socket unlinked) and a fresh master spawned once.
expect(run.mock.calls.some(([a]) => a[0] === '-O' && a[1] === 'exit')).toBe(true)
expect(rmSpy).toHaveBeenCalledWith(controlPathFor('p1'), { force: true })
expect(spawnMaster).toHaveBeenCalledTimes(1)
+ expect(seq).toEqual(['agent', 'spawn']) // agent up BEFORE the rebuilt master, on this site too
// The retried setup over the fresh master verified → the remote endpoint file is advertised.
expect(info.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
expect(statuses.slice(0, 2)).toEqual(['connecting', 'connected'])
})
+ it('the orphan-rebuild wait runs on connect-loop terms, not a fixed 5s inner loop', async () => {
+ // F6 regression: the rebuilt master can need an askpass passphrase (agent cold), which takes
+ // longer than any fixed few-second loop. The old inner `for (j < 50)` wait expired while the
+ // dialog was still open and then FELL THROUGH into the success block: status said connected,
+ // no socket was bound, and hookEndpointPath was lost (the very field bug the rebuild cures).
+ // Here the rebuilt master stays alive (prompting) for ~7s before binding, which is past the
+ // 5s base budget and far past what the old inner loop allowed. The connect must wait it out
+ // and only then report connected WITH the verified endpoint path.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)
+ vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
+ vi.useFakeTimers()
+ let respawned = false
+ let checksAfterRespawn = 0
+ const BIND_AT = 70 // 100ms cadence ⇒ ~7s: past BASE_WAIT_MS and past the old 50-check loop
+ const spawnMaster = vi.fn(() => {
+ respawned = true
+ return { kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => false }
+ })
+ const run = vi.fn(async (args: string[]) => {
+ const j = args.join(' ')
+ if (args[0] === '-O' && args[1] === 'check') {
+ if (!respawned) return { code: 0, stdout: '' } // the live orphan answers
+ checksAfterRespawn++
+ return { code: checksAfterRespawn >= BIND_AT ? 0 : 1, stdout: '' }
+ }
+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (j.includes('%{http_code}')) return { code: 0, stdout: respawned ? '204' : '000' }
+ return { code: 0, stdout: '' }
+ })
+ const statuses: string[] = []
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
+ onStatus: (e) => statuses.push(e.status)
+ })
+ const connectPromise = mgr.connect('p1', conn)
+ await vi.advanceTimersByTimeAsync(15_000)
+ const info = await connectPromise
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ expect(checksAfterRespawn).toBeGreaterThanOrEqual(BIND_AT)
+ // The retried setup over the (slow) fresh master verified, so the endpoint is not dropped.
+ expect(info.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(statuses).toContain('connected')
+ })
+
+ it('a rebuilt master that never comes up FAILS the connect instead of reporting connected', async () => {
+ // The other half of F6: the old fall-through declared success unconditionally, so a rebuilt
+ // master that died (cancelled prompt, auth failure) still produced status 'connected' with
+ // no socket behind it. It must fail, with the REBUILT master's stderr as the cause.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)
+ vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
+ vi.useFakeTimers()
+ let respawned = false
+ const spawnMaster = vi.fn(() => {
+ respawned = true
+ return {
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'root@h: Permission denied (publickey).',
+ exited: () => true
+ }
+ })
+ const run = vi.fn(async (args: string[]) => {
+ const j = args.join(' ')
+ if (args[0] === '-O' && args[1] === 'check') return { code: respawned ? 1 : 0, stdout: '' }
+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (j.includes('%{http_code}')) return { code: 0, stdout: '000' } // tunnel never verifies
+ return { code: 0, stdout: '' }
+ })
+ const statuses: string[] = []
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
+ onStatus: (e) => statuses.push(e.status)
+ })
+ const assertion = expect(mgr.connect('p1', conn)).rejects.toThrow('Permission denied (publickey)')
+ await vi.advanceTimersByTimeAsync(3000)
+ await assertion
+ expect(statuses).not.toContain('connected')
+ expect(statuses).toContain('error')
+ })
+
+ it('a dead adopted orphan fails on the base budget with a generic error, even while ANOTHER prompt is up', async () => {
+ // F3+F9: the adopted-orphan handle has no exited()/pid()/stderr(). It also positively
+ // cannot prompt (it authenticated in a previous run), so (a) an outstanding prompt that
+ // necessarily belongs to a DIFFERENT project must not stretch this failure from 5s to the
+ // 300s prompt ceiling, and (b) the 60s global cancel clock must not relabel the failure
+ // as "cancelled". Here the orphan answers the adoption probe then dies: both fallbacks
+ // scream true, and the connect must ignore them.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)
+ vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
+ vi.useFakeTimers()
+ let probed = false
+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check') {
+ if (!probed) {
+ probed = true
+ return { code: 0, stdout: '' } // adoption probe: the orphan still answered…
+ }
+ return { code: 1, stdout: '' } // …and died before the wait loop's first check
+ }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ askpassIsPrompting: () => true, // another project's dialog is open the whole time
+ askpassWasCancelled: (pid) => pid === undefined // the global-clock fallback would say yes
+ })
+ // Generic failure, not the passphrase-cancel message, and within ~5s, not 300s: if either
+ // guess leaked through, this either times out (extended wait) or throws the wrong message.
+ const assertion = expect(mgr.connect('p1', conn)).rejects.toThrow(
+ 'Could not establish the SSH connection.'
+ )
+ await vi.advanceTimersByTimeAsync(6000)
+ await assertion
+ expect(spawnMaster).not.toHaveBeenCalled() // adopted, never respawned
+ })
+
it('skips the probe entirely when no socket file exists (the normal path)', async () => {
const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
const checks: string[][] = []
@@ -605,10 +752,933 @@ describe('SshProjectManager', () => {
await mgr.connect('p1', conn)
expect(spawnMaster).toHaveBeenCalledTimes(1)
expect(rmSpy).not.toHaveBeenCalled() // nothing to clean
- // Only the connect loop's `-O check` runs — no extra leftover-probe round-trip.
+ // Only the connect loop's `-O check` runs, no extra leftover-probe round-trip.
expect(checks.length).toBeGreaterThanOrEqual(1)
})
})
+
+ // --- concurrent connect for one project ---------------------------------------------------
+ //
+ // Four callers can fire at once (watchdog revalidateAll, powerMonitor resume, the renderer's
+ // SshReconnector backoff, a tab switch). They used to race through the `existing` branch and
+ // kill each other's in-flight master, which surfaced as an empty-stderr generic failure while
+ // the surviving master was torn down underneath the winner.
+ describe('concurrent connect', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('coalesces simultaneous connects into ONE master', async () => {
+ const { mgr, spawnMaster } = makeMgr()
+ const [a, b, c] = await Promise.all([
+ mgr.connect('p1', conn),
+ mgr.connect('p1', conn),
+ mgr.connect('p1', conn)
+ ])
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ expect(a.controlPath).toBe(controlPathFor('p1'))
+ expect(b).toEqual(a)
+ expect(c).toEqual(a)
+ })
+
+ it('a watchdog revalidate during an in-flight connect does not kill its master', async () => {
+ const { mgr, spawnMaster } = makeMgr()
+ const first = mgr.connect('p1', conn)
+ const viaWatchdog = mgr.revalidateAll() // hits connect() for the same project
+ await Promise.all([first, viaWatchdog])
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ const killed = spawnMaster.mock.results[0].value as { kill: ReturnType<typeof vi.fn> }
+ expect(killed.kill).not.toHaveBeenCalled()
+ expect(mgr.refForProject('p1')).toBeTruthy()
+ })
+
+ it('a disconnected project starts a FRESH connect instead of coalescing onto the stale attempt', async () => {
+ // Without disconnect clearing `inFlight`, a connect() issued after a disconnect coalesces
+ // onto the doomed attempt (its master was killed) and returns that result instead of
+ // establishing a live master. Clearing inFlight on disconnect makes the reconnect spawn a
+ // new master rather than recycling the dead attempt.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ let releaseCheck: (() => void) | undefined
+ let gate: Promise<void> | null = new Promise((r) => (releaseCheck = r))
+ const spawnMaster = vi.fn((_args: string[]) => ({ kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => false }))
+ const run = vi.fn(async (args: string[]) => {
+ // Hold the connect's first `-O check` so it is genuinely in flight when we disconnect.
+ if (args[0] === '-O' && args[1] === 'check' && gate) {
+ const g = gate
+ gate = null
+ await g
+ }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const first = mgr.connect('p1', conn) // blocked mid-connect
+ // Let the first attempt pass its (microtask-ish) setup so it spawns + registers conns before
+ // we tear it down; otherwise disconnect() runs before the attempt has registered and finds
+ // nothing to disconnect (a false pass that wouldn't exercise the inFlight fix).
+ await new Promise((resolve) => setImmediate(resolve))
+ await mgr.disconnect('p1') // tears the master down and (the fix) clears inFlight
+ const second = mgr.connect('p1', conn) // reconnect while the old attempt is still queued
+ releaseCheck!()
+ await Promise.all([first, second])
+ expect(spawnMaster).toHaveBeenCalledTimes(2) // the second connect spawned a fresh master
+ expect(mgr.refForProject('p1')).toBeTruthy()
+ })
+
+ it('a coalesced join still applies its remoteCwd once the shared attempt lands', async () => {
+ // The `existing` reuse branch updates remoteCwd on every call; the coalescing join used to
+ // drop it, leaving refForRemoteCwd unable to route remote git ops for the joiner's folder.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ let releaseCheck: (() => void) | undefined
+ let gate: Promise<void> | null = new Promise((r) => (releaseCheck = r))
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check' && gate) {
+ const g = gate
+ gate = null
+ await g // hold the first attempt so the second call really joins it
+ }
+ return { code: 0, stdout: '' }
+ })
+ 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()
+ })
+ const first = mgr.connect('p1', conn) // e.g. the watchdog: no remoteCwd
+ const second = mgr.connect('p1', conn, '/srv/repo') // the tab switch names the folder
+ releaseCheck!()
+ await Promise.all([first, second])
+ expect(mgr.refForRemoteCwd('/srv/repo')).toEqual({ conn, controlPath: controlPathFor('p1') })
+ })
+
+ it('an edited endpoint unlinks the old socket so the leftover probe cannot re-adopt it', async () => {
+ // disconnect() FIRES `-O exit` without awaiting it, and kill() does nothing to a master that
+ // already daemonized, so the old master is typically still answering when the leftover-socket
+ // probe runs a few lines later. The probe would adopt it as a live orphan and leave the
+ // project on the OLD endpoint. The fs mock is STATEFUL on purpose: a stat that keeps
+ // reporting a socket after rm() cannot tell the two behaviors apart, and an earlier version
+ // of this test passed against the bug for exactly that reason.
+ let socketOnDisk = true
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockImplementation(async () => {
+ if (socketOnDisk) return { isSocket: () => true } as never
+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
+ })
+ vi.spyOn(fs, 'rm').mockImplementation(async () => {
+ socketOnDisk = false
+ })
+ const spawnMaster = vi.fn(() => {
+ socketOnDisk = true // a fresh master binds its own socket
+ return { kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => false }
+ })
+ // Everything answers, INCLUDING the remote hook setup, so an adopted orphan would be kept
+ // rather than rescued by the orphan-rebuild path (which would spawn and mask the bug).
+ const run = vi.fn(async (args: 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: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', { host: 'old.example.com', user: 'u' })
+ spawnMaster.mockClear()
+ run.mockClear()
+ await mgr.connect('p1', { host: 'new.example.com', user: 'u' })
+ // A FRESH master was built for the new host. Without the unlink the probe finds the old
+ // socket still answering and adopts it, and spawnMaster is never called at all.
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ // and the teardown was aimed at the OLD endpoint before the socket went away.
+ expect(run.mock.calls.some(([a]) => a.includes('exit') && a.includes('[email protected]'))).toBe(true)
+ })
+
+ it('revalidateAll re-reads each project rather than trusting a stale snapshot', async () => {
+ // The race needs a pass that is ALREADY RUNNING when the user repoints a server: the loop
+ // snapshots every entry up front, so a later iteration would reconnect its project using the
+ // conn as it was before the edit, tearing down the master just built for the new endpoint.
+ // A single-project test cannot express this, because the snapshot and its use are adjacent.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
+ let releaseSlow: (() => void) | undefined
+ const slowGate = new Promise<void>((r) => (releaseSlow = r))
+ let gateArmed = false
+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => false }))
+ const run = vi.fn(async (args: string[]) => {
+ // Hold the FIRST project's revalidate open so the edit below lands mid-pass.
+ if (gateArmed && args.includes('[email protected]')) await slowGate
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('slow', { host: 'slow.example.com', user: 'u' })
+ await mgr.connect('p2', { host: 'old.example.com', user: 'u' })
+
+ gateArmed = true
+ const pass = mgr.revalidateAll() // snapshots BOTH projects, then blocks on 'slow'
+ await new Promise((r) => setTimeout(r, 0))
+ await mgr.connect('p2', { host: 'new.example.com', user: 'u' }) // the user repoints p2
+ const spawnsAfterEdit = spawnMaster.mock.calls.length
+ releaseSlow?.()
+ await pass
+
+ // The pass must reuse p2's NEW master, not re-establish the endpoint its snapshot recorded.
+ expect(mgr.refForProject('p2')?.conn.host).toBe('new.example.com')
+ expect(spawnMaster.mock.calls.length).toBe(spawnsAfterEdit)
+ expect(run.mock.calls.some(([a]) => a.includes('exit') && a.includes('[email protected]'))).toBe(false)
+ })
+
+ it('a connect naming an EDITED endpoint never shares the in-flight attempt to the old one', async () => {
+ // Joining across different endpoints handed the caller a connection to the WRONG server
+ // (the old attempt's result). The joiner must wait the old attempt out and then establish
+ // a master to ITS endpoint, tearing the old-endpoint master down on the way.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ let releaseCheck: (() => void) | undefined
+ let gate: Promise<void> | null = new Promise((r) => (releaseCheck = r))
+ const targets: string[] = []
+ const spawnMaster = vi.fn((args: string[]) => {
+ targets.push(args[args.length - 1]) // masterArgs puts user@host last
+ return { kill: vi.fn(), on: vi.fn() }
+ })
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check' && gate) {
+ const g = gate
+ gate = null
+ await g
+ }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const first = mgr.connect('p1', { host: 'h1', user: 'u' })
+ const second = mgr.connect('p1', { host: 'h2', user: 'u' })
+ releaseCheck!()
+ await first
+ await second
+ expect(spawnMaster).toHaveBeenCalledTimes(2)
+ expect(targets).toEqual(['u@h1', 'u@h2'])
+ // The map now owns the NEW endpoint, and the old-endpoint master was truly exited
+ // (`-O exit` over its socket, so a daemonized ControlPersist master dies too).
+ expect(mgr.refForProject('p1')?.conn).toEqual({ host: 'h2', user: 'u' })
+ expect(run.mock.calls.some(([a]) => (a as string[])[0] === '-O' && (a as string[])[1] === 'exit')).toBe(true)
+ })
+
+ it('maps an asking master pid back to its user@host so the passphrase dialog can name the server', async () => {
+ // The askpass request carries only the asking ssh pid (the helper's $PPID). Without this
+ // lookup the dialog can only name a key file, which is ambiguous when one key serves several
+ // servers and the prompt came from the watchdog rather than the connect dialog.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), pid: () => 4242 })),
+ run: vi.fn(async () => ({ code: 0, stdout: '' })),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', { host: 'h1', user: 'u' })
+ expect(mgr.targetForMasterPid('4242')).toBe('u@h1')
+ expect(mgr.targetForMasterPid('9999')).toBeUndefined() // an adopted orphan names nothing
+ expect(mgr.targetForMasterPid('')).toBeUndefined()
+ })
+
+ it('an endpoint-edit connect stays coalesce-able while it waits (a second connect must not kill the waiting master)', async () => {
+ // The endpoint-change branch tears the old master down through disconnect(), which drops the
+ // project's `inFlight` entry. That entry belongs to the attempt that is STILL RUNNING, and
+ // the attempt then parks in the master wait loop for as long as the passphrase prompt takes.
+ // With it gone, a concurrent connect for the same project no longer coalesces: it takes the
+ // reuse branch, its `-O check` fails against the not-yet-bound socket, and it KILLS the
+ // master that is sitting on the prompt and spawns a second one for the same control path.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const h1 = { host: 'h1', user: 'u' }
+ const h2 = { host: 'h2', user: 'u' }
+ const targets: string[] = []
+ const kills: string[] = []
+ const spawnMaster = vi.fn((args: string[]) => {
+ const t = args[args.length - 1]
+ targets.push(t)
+ return { kill: vi.fn(() => kills.push(t)), on: vi.fn() }
+ })
+ // h2's socket does not answer until `bound` flips: exactly the window in which ssh is
+ // waiting on the askpass prompt.
+ let bound = false
+ let sawH2Check: (() => void) | undefined
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check' && args[args.length - 1] === 'u@h2') {
+ sawH2Check?.()
+ return { code: bound ? 0 : 1, stdout: '' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const nextH2Check = (): Promise<void> => new Promise<void>((r) => (sawH2Check = r))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', h1)
+ const edited = mgr.connect('p1', h2) // endpoint edit: tears h1 down, then waits on h2
+ await nextH2Check() // it is now parked in the wait loop, master alive, socket silent
+ const concurrent = mgr.connect('p1', h2) // watchdog / second tab / reconnect dialog
+ // Coalesced onto the SAME attempt, so nothing re-enters connectOnce to kill the waiter.
+ expect(concurrent).toBe(edited)
+ bound = true
+ await Promise.all([edited, concurrent])
+ expect(targets).toEqual(['u@h1', 'u@h2']) // one master per endpoint, no double spawn
+ expect(kills).not.toContain('u@h2') // the waiting master survived
+ expect(mgr.refForProject('p1')?.conn).toEqual(h2)
+ })
+
+ it('a reconnect after a server EDIT re-establishes on the new endpoint instead of reusing the old master', async () => {
+ // Sequential flavor of the same defect: with a LIVE cached master, `-O check` answers for
+ // the OLD server, and the reuse branch would return it for the edited conn.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const targets: string[] = []
+ const spawnMaster = vi.fn((args: string[]) => {
+ targets.push(args[args.length - 1])
+ return { kill: vi.fn(), on: vi.fn() }
+ })
+ const run = vi.fn(async (_args: string[]) => ({ code: 0, stdout: '' }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ await mgr.connect('p1', { host: 'h1', user: 'u' })
+ await mgr.connect('p1', { host: 'h1', user: 'u', label: 'renamed' }) // display-only change
+ expect(spawnMaster).toHaveBeenCalledTimes(1) // a rename never tears down a healthy master
+ await mgr.connect('p1', { host: 'h2', user: 'u' })
+ expect(spawnMaster).toHaveBeenCalledTimes(2)
+ expect(targets).toEqual(['u@h1', 'u@h2'])
+ expect(mgr.refForProject('p1')?.conn).toEqual({ host: 'h2', user: 'u' })
+ })
+
+ it('a failed attempt never tears down a replacement master it does not own', async () => {
+ // The loser of a race must kill its OWN master, not whatever sits in the map by then.
+ // connect() awaits real fs promises, which fake timers cannot flush; stub them first.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ vi.useFakeTimers()
+ let spawns = 0
+ const spawnMaster = vi.fn(() => {
+ spawns++
+ return { kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => spawns === 1 }
+ })
+ const run = vi.fn(async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ )
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const assertion = expect(mgr.connect('p1', conn)).rejects.toThrow()
+ await vi.advanceTimersByTimeAsync(2000)
+ await assertion
+ // Its own master was killed exactly once, and nothing else was touched.
+ const own = spawnMaster.mock.results[0].value as { kill: ReturnType<typeof vi.fn> }
+ expect(own.kill).toHaveBeenCalled()
+ })
+ })
+
+ it('bounds the wait by WALL CLOCK, not attempt count, when each check is slow', async () => {
+ // Regression: the loop counted attempts, but every attempt is a real `ssh -O check` process
+ // whose cost is not fixed (up to run()'s 15s execFile timeout against a bound-but-unresponsive
+ // master). A 3000-attempt ceiling therefore meant up to ~12 hours of "connecting", not the 5
+ // minutes intended. Here each check takes 3s and the master is dead, so the 5s budget must end
+ // it in a couple of checks rather than tens.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ vi.useFakeTimers()
+ let checks = 0
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check') {
+ checks++
+ await new Promise((r) => setTimeout(r, 3000)) // a slow, blocking check
+ return { code: 1, stdout: '' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), stderr: () => '' })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const assertion = expect(mgr.connect('p1', conn)).rejects.toThrow()
+ await vi.advanceTimersByTimeAsync(60_000)
+ await assertion
+ // 5s budget at 3s per check: a small handful, nowhere near an attempt-count ceiling.
+ expect(checks).toBeLessThanOrEqual(4)
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('still connects when the socket binds only AFTER the master exits (ControlPersist handoff)', async () => {
+ // What MASTER_EXIT_GRACE_CHECKS exists for: with ControlPersist the foreground ssh binds the
+ // socket and then daemonizes and EXITS on success, so our poll can observe "exited" before it
+ // observes the socket answering. Zero grace would declare that successful connect a failure.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ vi.useFakeTimers()
+ let checks = 0
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check') {
+ checks++
+ return { code: checks >= 3 ? 0 : 1, stdout: '' } // answers on a check AFTER the exit
+ }
+ return { code: 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ // exited() is true from the very first poll: the daemonize already happened.
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => true })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const connectPromise = mgr.connect('p1', conn)
+ await vi.advanceTimersByTimeAsync(2000)
+ const { controlPath } = await connectPromise
+ expect(controlPath).toBe(controlPathFor('p1'))
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it('the prompt-extended wait actually ENDS at its ceiling instead of waiting forever', async () => {
+ // A master that stays alive without ever binding (hung askpass curl, wedged handshake) gets
+ // the 300s prompt ceiling, and that ceiling must terminate: an accidental infinite wait
+ // would leave the project on "connecting" forever with nothing to report it.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ vi.useFakeTimers()
+ let checks = 0
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check') checks++
+ return { code: args[0] === '-O' && args[1] === 'check' ? 1 : 0, stdout: '' }
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), stderr: () => '', exited: () => false })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const assertion = expect(mgr.connect('p1', conn)).rejects.toThrow(
+ 'Could not establish the SSH connection.'
+ )
+ await vi.advanceTimersByTimeAsync(310_000) // just past the 300s prompt ceiling
+ await assertion
+ // It really rode the EXTENDED window (not the 5s base) and then stopped.
+ expect(checks).toBeGreaterThan(1000)
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ }, 20_000)
+
+ // --- SSH_ASKPASS wiring (passphrase-protected identity files) ----------------------------
+ describe('askpass wiring', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ // Same guard the 'master watchdog' tests use below: connect() awaits real fs promises
+ // (mkdir/stat), which fake timers can't flush deterministically, see that block's comment.
+ function stubFsForFakeTimers() {
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ }
+
+ it('spawnMaster receives the env masterEnvFor(identityFile) returns', async () => {
+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
+ const run = vi.fn(async (_args: string[]) => ({ code: 0, stdout: '' }))
+ const masterEnvFor = vi.fn(
+ (identityFile?: string): Record<string, string> =>
+ identityFile ? { SSH_ASKPASS: '/ud/ssh-askpass.sh', NODETERM_ASKPASS_IDENTITY: identityFile } : {}
+ )
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ masterEnvFor
+ })
+ const withKey = { host: 'h', user: 'u', identityFile: '/home/u/.ssh/id_ed25519' }
+ await mgr.connect('p1', withKey)
+ expect(masterEnvFor).toHaveBeenCalledWith(withKey.identityFile)
+ expect(spawnMaster).toHaveBeenCalledWith(expect.any(Array), {
+ SSH_ASKPASS: '/ud/ssh-askpass.sh',
+ NODETERM_ASKPASS_IDENTITY: withKey.identityFile
+ })
+ })
+
+ it('brings the app-private ssh-agent up BEFORE the master is spawned', async () => {
+ // Order is the whole point: ssh reads SSH_AUTH_SOCK at auth time, so an agent that is not
+ // listening yet means `AddKeysToAgent=yes` stores the unlocked key nowhere and every connect
+ // in this app run prompts again.
+ const seq: string[] = []
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => {
+ seq.push('spawn')
+ return { kill: vi.fn(), on: vi.fn() }
+ }),
+ run: vi.fn(async () => ({ code: 0, stdout: '' })),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ ensureAgent: vi.fn(async () => {
+ await new Promise((r) => setImmediate(r)) // a real start awaits the socket binding
+ seq.push('agent')
+ })
+ })
+ await mgr.connect('p1', { host: 'h', user: 'u' })
+ expect(seq).toEqual(['agent', 'spawn'])
+ })
+
+ it('a failing ensureAgent never fails the connect (a missing agent costs a prompt, not a session)', async () => {
+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run: vi.fn(async () => ({ code: 0, stdout: '' })),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ ensureAgent: vi.fn(async () => {
+ throw new Error('no ssh-agent on PATH')
+ })
+ })
+ await expect(mgr.connect('p1', { host: 'h', user: 'u' })).resolves.toBeTruthy()
+ expect(spawnMaster).toHaveBeenCalledTimes(1)
+ })
+
+ it('reports idle ONLY on a user-facing disconnect that leaves nothing connected', async () => {
+ // `onIdle` is what forgets the unlocked key. Internal teardowns empty `conns` routinely (an
+ // endpoint edit, a failed connect, the watchdog dropping a stale master), and treating those
+ // as "the user is done with SSH" would drop the key mid-reconnect.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const onIdle = vi.fn()
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run: vi.fn(async () => ({ code: 0, stdout: '' })),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ onIdle
+ })
+ await mgr.connect('p1', { host: 'h1', user: 'u' })
+ await mgr.connect('p2', { host: 'h2', user: 'u' })
+
+ await mgr.disconnect('p1', { final: true }) // p2 still holds a master: not idle
+ expect(onIdle).not.toHaveBeenCalled()
+
+ // The load-bearing case: an INTERNAL teardown that leaves nothing connected. An endpoint
+ // edit, a failed connect and the watchdog's stale-master drop all look exactly like this,
+ // and forgetting the key here would re-prompt in the middle of a reconnect.
+ await mgr.disconnect('p2')
+ expect(onIdle).not.toHaveBeenCalled()
+
+ await mgr.connect('p2', { host: 'h2', user: 'u' })
+ await mgr.disconnect('p2', { final: true })
+ expect(onIdle).toHaveBeenCalledTimes(1)
+ })
+
+ it('quit exits the daemonized masters, not just the child we spawned', async () => {
+ // ControlPersist=300 outlives kill(): without a synchronous `-O exit` a relaunch inside five
+ // minutes adopts the still-authenticated master and connects with no passphrase, even though
+ // the app-private agent (and the unlocked key) died at quit.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const runSync = vi.fn()
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run: vi.fn(async () => ({ code: 0, stdout: '' })),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ runSync
+ })
+ await mgr.connect('p1', { host: 'h1', user: 'u' })
+ mgr.disconnectAll()
+ expect(runSync).toHaveBeenCalledTimes(1)
+ const args = runSync.mock.calls[0][0] as string[]
+ expect(args.slice(0, 2)).toEqual(['-O', 'exit'])
+ expect(args[args.length - 1]).toBe('u@h1')
+ })
+
+ it('a stale attempt that outlived a disconnect+reconnect does not clobber the live entry', async () => {
+ // The success tail runs AFTER remoteHooks.setup (several round-trips). A disconnect and a
+ // fresh reconnect inside that window leave a DIFFERENT attempt's master in the map; the
+ // stale attempt writing its results onto it clobbered the live hookEndpointPath with
+ // undefined (dead RUNNING badges) and emitted a second 'connected'. The guard: only the
+ // attempt that still OWNS the map entry may write or report.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ let released = false
+ let releaseFirstSetup: (() => void) | undefined
+ const firstSetupGate = new Promise<void>((r) => (releaseFirstSetup = r))
+ let hookProbes = 0
+ const run = vi.fn(async (args: string[]) => {
+ const j = args.join(' ')
+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (j.includes('%{http_code}')) {
+ // Attempt 1's tunnel verification parks here; the live attempt (probing while attempt 1
+ // is still parked) verifies immediately. Everything AFTER the release belongs to
+ // attempt 1's bounded retry, and stays dead so its setup conclusively returns null -
+ // the case whose `hookEndpointPath = undefined` used to clobber the live entry.
+ if (++hookProbes === 1) {
+ await firstSetupGate
+ return { code: 0, stdout: '000' }
+ }
+ return { code: 0, stdout: released ? '000' : '204' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const statuses: string[] = []
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 51234, token: 'tok', version: '1' }),
+ onStatus: (e) => statuses.push(e.status)
+ })
+ const conn = { host: 'h', user: 'u' }
+ const stale = mgr.connect('p1', conn) // parks inside setup's tunnel verification
+ await new Promise((r) => setImmediate(r))
+ await new Promise((r) => setImmediate(r))
+ await mgr.disconnect('p1') // user tears the project down mid-setup
+ const live = await mgr.connect('p1', conn) // fresh attempt, completes fully
+ expect(live.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ released = true
+ releaseFirstSetup!()
+ await stale // settles without owning the entry
+ // The live entry survived the stale attempt: the endpoint is intact (a reuse connect
+ // returns the cached entry - under the unguarded code the stale write set it to undefined,
+ // which is the dead-RUNNING-badges failure). Status counts are not asserted: the live
+ // attempt's claude probe legitimately re-pushes 'connected' on its own schedule.
+ const reused = await mgr.connect('p1', conn)
+ expect(reused.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ })
+
+ it('a publickey denial with NO passphrase ask gets the agent-only hint, ONE attempt, no retry', async () => {
+ // The agent-only credential case (smartcard, 1Password/Secretive with no IdentityAgent line):
+ // no key FILE exists, so no prompt can rescue it, and our private agent hides the user's own.
+ // The answer is a HINT naming the documented fix (IdentityAgent), never a second attempt: an
+ // automatic ambient-agent retry fired on every ordinary auth failure (launchd exports
+ // SSH_AUTH_SOCK on every Mac) and carried AddKeysToAgent=yes into the login agent - the leak
+ // this design exists to close.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const spawnMaster = vi.fn(() => ({
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'u@h: Permission denied (publickey).',
+ exited: () => true,
+ pid: () => 4242
+ }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run: vi.fn(async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ ),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ askpassAsked: () => false // askpass never fired for this master: no key file was in play
+ })
+ await expect(mgr.connect('p1', { host: 'h', user: 'u' })).rejects.toThrow(/IdentityAgent/)
+ expect(spawnMaster).toHaveBeenCalledTimes(1) // exactly one attempt - never a blind retry
+ })
+
+ it('the same denial WITH a passphrase ask keeps the plain error (a key file was in play)', async () => {
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'u@h: Permission denied (publickey).',
+ exited: () => true,
+ pid: () => 77
+ })),
+ run: vi.fn(async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ ),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ askpassAsked: () => true
+ })
+ await expect(mgr.connect('p1', { host: 'h', user: 'u' })).rejects.toThrow(
+ /Permission denied \(publickey\)\.$/
+ )
+ })
+
+ it('a cancelled passphrase prompt surfaces a dedicated message instead of the generic one', async () => {
+ stubFsForFakeTimers()
+ vi.useFakeTimers()
+ const spawnMaster = vi.fn(() => ({
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'root@h: Permission denied (publickey).'
+ }))
+ // `-O check` never succeeds, the connect retry loop exhausts and hits the failure branch.
+ const run = vi.fn(async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ )
+ const withKey = { host: 'h', user: 'u', identityFile: '/home/u/.ssh/id_ed25519' }
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ masterEnvFor: () => ({}),
+ askpassWasCancelled: () => true
+ })
+ // Attach the rejection assertion BEFORE advancing timers: advancing drives the rejection
+ // synchronously inside this call, and attaching afterwards races Node's unhandled-rejection
+ // detector against `expect().rejects`, attaching first closes that window.
+ const assertion = expect(mgr.connect('p1', withKey)).rejects.toThrow(
+ 'SSH connection cancelled: this key needs its passphrase.'
+ )
+ await vi.advanceTimersByTimeAsync(6000) // flush the base wall-clock wait
+ await assertion
+ })
+
+ it('attributes a cancel to the exact master pid through the real AskpassServer wiring', async () => {
+ // Pins the production wiring `askpassWasCancelled: (pid) => askpassServer.wasCancelledBy(pid)`
+ // together with a spawner handle that reports its child's pid, i.e. that connect() actually
+ // threads master.pid() through. The different-pid case is the load-bearing half: had connect()
+ // passed undefined, wasCancelledBy falls back to the 60s global-clock answer, BOTH connects
+ // below would read as cancelled, and one project's Cancel would relabel another project's
+ // genuine auth failure as "needs its passphrase" (the bug the pid keying exists to prevent).
+ // Real timers: the exit-grace loop is only ~5 checks x 100ms per connect.
+ const s = new AskpassServer()
+ s.setPromptHandler(async () => null) // the user hits Cancel
+ await s.start()
+ try {
+ // Drive the decline the way the real helper does: a POST whose caller field is the $PPID
+ // the askpass script reports, which is the pid of the master the app spawned.
+ await fetch(`http://127.0.0.1:${s.getPort()}/prompt`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ 'x-nodeterm-askpass-token': s.getToken()
+ },
+ body: new URLSearchParams({
+ identity: '/home/u/.ssh/id_ed25519',
+ caller: '4242',
+ prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': "
+ }).toString()
+ })
+ const mgrWithMasterPid = (pid: number) =>
+ new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'root@h: Permission denied (publickey).',
+ exited: () => true,
+ pid: () => pid
+ })),
+ run: async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' },
+ runScp: async () => ({ code: 0 }),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ masterEnvFor: () => ({}),
+ askpassWasCancelled: (masterPid) => s.wasCancelledBy(masterPid)
+ })
+ // The master whose prompt was declined gets the passphrase-specific message.
+ await expect(mgrWithMasterPid(4242).connect('p-cancel-mine', conn)).rejects.toThrow(
+ 'SSH connection cancelled: this key needs its passphrase.'
+ )
+ // A DIFFERENT master pid, same stderr, still inside the fallback's 60s window: it must
+ // keep its real error. Pid attribution, not the clock, decides the message.
+ await expect(mgrWithMasterPid(9999).connect('p-cancel-other', conn)).rejects.toThrow(
+ 'Could not establish the SSH connection: root@h: Permission denied (publickey).'
+ )
+ } finally {
+ s.stop()
+ }
+ }, 15_000)
+
+ it('fails fast with the master stderr when the master process exits (no blind 5s wait)', async () => {
+ stubFsForFakeTimers()
+ vi.useFakeTimers()
+ const spawnMaster = vi.fn(() => ({
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'root@h: Permission denied (publickey).',
+ exited: () => true
+ }))
+ const run = vi.fn(async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ )
+ const checkCount = () => run.mock.calls.filter((c) => (c[0] as string[])[1] === 'check').length
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn()
+ })
+ const assertion = expect(mgr.connect('p1', conn)).rejects.toThrow('Permission denied (publickey)')
+ await vi.advanceTimersByTimeAsync(2000)
+ await assertion
+ // Exit grace is a handful of checks, far fewer than the base 50-attempt window.
+ expect(checkCount()).toBeLessThan(10)
+ })
+
+ it('keeps waiting while a keyed master process is still alive (slow handshake or prompt)', async () => {
+ stubFsForFakeTimers()
+ vi.useFakeTimers()
+ let checkCalls = 0
+ const SUCCEED_AT = 80 // past the base wall-clock budget (BASE_WAIT_MS): proves the alive-master extension
+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn(), exited: () => false }))
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check') {
+ checkCalls++
+ return { code: checkCalls >= SUCCEED_AT ? 0 : 1, stdout: '' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const withKey = { host: 'h', user: 'u', identityFile: '/home/u/.ssh/id_ed25519' }
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ masterEnvFor: () => ({})
+ })
+ const connectPromise = mgr.connect('p1', withKey)
+ await vi.advanceTimersByTimeAsync(12000)
+ const { controlPath } = await connectPromise
+ expect(controlPath).toBe(controlPathFor('p1'))
+ expect(checkCalls).toBeGreaterThanOrEqual(SUCCEED_AT)
+ })
+
+ it('requests the askpass env for a server with no configured identity file', async () => {
+ stubFsForFakeTimers()
+ vi.useFakeTimers()
+ const masterEnvFor = vi.fn((): Record<string, string> => ({}))
+ const withKey = { host: 'h', user: 'u' } // no identityFile, the common real-world case
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => ({
+ kill: vi.fn(),
+ on: vi.fn(),
+ stderr: () => 'root@h: Permission denied (publickey).',
+ exited: () => true
+ })),
+ run: vi.fn(async (args: string[]) =>
+ args[0] === '-O' && args[1] === 'check' ? { code: 1, stdout: '' } : { code: 0, stdout: '' }
+ ),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ masterEnvFor
+ })
+ const assertion = expect(mgr.connect('p1', withKey)).rejects.toThrow()
+ await vi.advanceTimersByTimeAsync(2000)
+ await assertion
+ // The askpass env is requested for EVERY connect, including servers with no configured
+ // identity file: ssh offers the default identities, which are the ones likely encrypted.
+ expect(masterEnvFor).toHaveBeenCalled()
+ })
+
+ it('extends the wait past the base ~5s while a passphrase prompt is still outstanding', async () => {
+ stubFsForFakeTimers()
+ vi.useFakeTimers()
+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))
+ let checkCalls = 0
+ const SUCCEED_AT = 80 // past the base wall-clock budget (BASE_WAIT_MS), proves the wait actually extended
+ const run = vi.fn(async (args: string[]) => {
+ if (args[0] === '-O' && args[1] === 'check') {
+ checkCalls++
+ return { code: checkCalls >= SUCCEED_AT ? 0 : 1, stdout: '' }
+ }
+ return { code: 0, stdout: '' }
+ })
+ const withKey = { host: 'h', user: 'u', identityFile: '/home/u/.ssh/id_ed25519' }
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster,
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus: vi.fn(),
+ masterEnvFor: () => ({}),
+ askpassIsPrompting: () => true
+ })
+ const connectPromise = mgr.connect('p1', withKey)
+ await vi.advanceTimersByTimeAsync(9000) // well past the base 5s ceiling
+ const { controlPath } = await connectPromise
+ expect(controlPath).toBe(controlPathFor('p1'))
+ expect(checkCalls).toBeGreaterThanOrEqual(SUCCEED_AT)
+ })
+ })
})
describe('master watchdog', () => {
@@ -617,13 +1687,13 @@ describe('master watchdog', () => {
afterEach(() => vi.restoreAllMocks())
function makeWatchedMgr() {
- // Keep the re-establish path off the real fs — controlPathFor hashes into the REAL
+ // Keep the re-establish path off the real fs, controlPathFor hashes into the REAL
// ~/.nodeterm/ssh-cm, and an unmocked stat+rm could unlink a genuinely live socket there.
vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
vi.spyOn(fs, 'rm').mockResolvedValue(undefined)
const statuses: string[] = []
- // `-O check` fails while checkFails is true; spawning a fresh master heals it — models a
+ // `-O check` fails while checkFails is true; spawning a fresh master heals it, models a
// master that died behind our back and comes back only when the watchdog respawns it.
let checkFails = false
const spawnMaster = vi.fn(() => {
@@ -644,7 +1714,7 @@ describe('master watchdog', () => {
return { mgr, statuses, spawnMaster, setMasterDead: () => (checkFails = true) }
}
- it('a healthy master is only checked — never respawned, no reconnecting status', async () => {
+ it('a healthy master is only checked, never respawned, no reconnecting status', async () => {
const { mgr, statuses, spawnMaster } = makeWatchedMgr()
await mgr.connect('p1', conn)
mgr.startWatchdog(5)
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 52ba25758..1312959b0 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -1,10 +1,11 @@
import { promises as fs } from 'fs'
import path from 'path'
import { spawn, execFile, execFileSync } from 'child_process'
-import { app, ipcMain, type BrowserWindow } from 'electron'
+import { app, ipcMain } from 'electron'
import { IPC } from '../../shared/ipc'
+import { getMainWindow, sendToMain } from '../main-window'
import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, type SshConnection } from '../../shared/ssh'
-import type { DownloadResult, SshProjectStatusEvent } from '../../shared/types'
+import type { DownloadResult, SshPassphraseRequest, SshProjectStatusEvent } from '../../shared/types'
import { candidateName, safeDownloadBasename } from '../../core/download-name'
import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
import { allowMediaPath } from '../media-protocol'
@@ -26,17 +27,30 @@ import {
import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'
import { RemoteHooks } from './remote-hooks'
import { hookServer } from '../../core/agents/hook-server'
+import { askpassServer } from './ssh-askpass'
+import { appSshAgent } from './ssh-agent'
import { sessionName } from '../../core/tmux-naming'
interface Runners {
userDataDir: string
/** Spawn the long-lived master; returns a handle we can kill. `stderr()` (when the spawner wires
* it) returns the master's captured stderr so a failed connect can surface the REAL ssh error
- * (auth denied, host unreachable, host-key mismatch) instead of a generic timeout. */
- spawnMaster: (args: string[]) => {
+ * (auth denied, host unreachable, host-key mismatch) instead of a generic timeout. `env` (when
+ * given) carries the SSH_ASKPASS wiring for a passphrase-protected identity file. `exited()`
+ * (when wired) reports whether the spawned process has ended; connect() uses it to fail fast
+ * on a definitive auth error and to keep waiting while a passphrase prompt is up. */
+ spawnMaster: (
+ args: string[],
+ env?: Record<string, string>
+ ) => {
kill: () => void
on: (ev: string, cb: (...a: unknown[]) => void) => void
stderr?: () => string
+ exited?: () => boolean
+ /** The spawned ssh's pid. The askpass helper reports this same value as its `$PPID`
+ * (verified against a real sshd), so a cancelled prompt can be attributed to this exact
+ * master rather than guessed from a global timestamp. */
+ pid?: () => number | undefined
}
/** Run a one-shot ssh, resolving its stdout + exit code; optional stdin written to the child. */
run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>
@@ -48,29 +62,81 @@ interface Runners {
/** Delays between claude-probe retries after a FAILED attempt (claude not found). Injected so
* tests don't wait on real backoff; production uses PROBE_RETRY_DELAYS_MS. */
probeRetryDelaysMs?: number[]
+ /** Env for anything that may AUTHENTICATE: the askpass wiring that routes a passphrase-protected
+ * identity file's prompt to the UI, plus `SSH_AUTH_SOCK` for the app-private ssh-agent that
+ * holds the unlocked key for this app run (ssh-agent.ts). Applied to the master spawn and to
+ * `run`/`runScp` in production, because `childArgs` uses `ControlMaster=auto`: with the master
+ * down, a child ssh re-authenticates for real and would otherwise miss the key entirely. All of
+ * these hooks are optional (benign defaults) so test fakes need no updating. */
+ masterEnvFor?: (identityFile?: string) => Record<string, string>
+ /** Bring the app-private ssh-agent up before a master is spawned. Awaited (and never allowed to
+ * reject) at each spawn site rather than at the top of `connect()`, which must stay synchronous
+ * through `inFlight.set` or concurrent connects stop coalescing. */
+ ensureAgent?: () => Promise<void>
+ /** The last SSH connection just went away through a user-facing disconnect. Production schedules
+ * the app-private agent's shutdown, which is what "forget the key" actually means. */
+ onIdle?: () => void
+ /** Synchronous one-shot ssh, for `disconnectAll()` only: `before-quit` is sync, so an awaited
+ * `-O exit` never lands and the daemonized ControlPersist master survives the app. */
+ runSync?: (args: string[]) => void
+ /** Did the user decline the passphrase prompt raised by THIS master? Distinguishes "needs its
+ * passphrase" from a genuine auth failure in the error message. Takes the master's pid because
+ * the identity file is not a usable key here: a server with none only learns which key ssh
+ * wanted from the prompt itself, by which time the attempt has already failed. */
+ askpassWasCancelled?: (masterPid?: number) => boolean
+ /** Is any passphrase prompt shown or queued right now? Fallback wait signal ONLY for spawners
+ * that cannot report process exit AND could be prompting (test fakes). Adopted orphans also
+ * lack an exit signal but positively cannot prompt (already authenticated), so connect()
+ * never consults this for them. */
+ askpassIsPrompting?: () => boolean
+ /** Did THIS master ever raise a passphrase prompt? A publickey denial with no ask means no key
+ * 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
}
/** Backoff after a FAILED remote claude probe (no markers = claude not found on that attempt).
* A transient login-shell hiccup (nvm cache warm-up, NFS home, corp wrapper) shouldn't disable
- * `--permission-mode auto` for the whole connection. A DEFINITE version answer never retries —
+ * `--permission-mode auto` for the whole connection. A DEFINITE version answer never retries ,
* a CLI doesn't change under a live connection; the next connect re-probes anyway. */
const PROBE_RETRY_DELAYS_MS = [5_000, 15_000, 30_000]
/** How many `name (n)` variants a download tries before falling back to a stamped name. */
const DOWNLOAD_NAME_ATTEMPTS = 50
-/** Cap on how much master stderr we retain (a misconfigured host can spew) — enough for the error. */
+/** Cap on how much master stderr we retain (a misconfigured host can spew), enough for the error. */
const MASTER_STDERR_CAP = 8 * 1024
/** Master watchdog cadence (see `startWatchdog`). Healthy cost per tick: ONE mux'd `-O check`
- * per connected project — no new TCP/auth — so this can afford to be brisk; 45s bounds how
+ * per connected project, no new TCP/auth, so this can afford to be brisk; 45s bounds how
* long exec polls can churn direct-fallback connections after an unnoticed master death. */
const MASTER_WATCHDOG_MS = 45_000
+/** How long connect() waits for `-O check` to answer when nothing is blocking on a human.
+ *
+ * These are WALL-CLOCK budgets, not attempt counts, and that distinction is load bearing: each
+ * check is a real `ssh -O check` process whose cost is not fixed. Normally it fails instantly
+ * (the control socket is not bound until after auth, so the connect is an immediate ENOENT), but
+ * against a bound-yet-unresponsive master it blocks until `run`'s own 15s execFile timeout. A
+ * 3000-attempt ceiling therefore meant anywhere from 5 minutes to 12 hours depending on how the
+ * checks happened to behave, with the user watching "connecting" the whole time. A deadline
+ * bounds the wait regardless of per-check cost. */
+const BASE_WAIT_MS = 5_000
+/** Budget while the master process is still alive: mid-handshake, or waiting on the askpass
+ * passphrase prompt a human can take minutes to answer. Mirrors the askpass script's own curl
+ * --max-time 300 and the main-side prompt expiry, so all three give up around the same point.
+ * A dead master short-circuits this long before the deadline (see the connect loop). */
+const PROMPT_WAIT_MS = 300_000
+/** Extra checks granted after the master process exits before declaring failure. With
+ * ControlPersist the foreground ssh daemonizes and EXITS on success; OpenSSH binds the control
+ * socket before that fork, so the first post-exit check normally succeeds. The grace only
+ * papers over scheduling between our poll and that exit. */
+const MASTER_EXIT_GRACE_CHECKS = 5
+
/**
* Pick the most informative line from an ssh master's stderr for the error banner. `-v` isn't
* passed, so ordinary stderr has no `debug` noise, but we still skip `debug*`/`Warning:` lines and
- * take the LAST real line — ssh prints the actionable cause last ("Permission denied (publickey).",
+ * take the LAST real line, ssh prints the actionable cause last ("Permission denied (publickey).",
* "ssh: Could not resolve hostname …", "Host key verification failed."). Falls back to the last
* non-empty line. Truncated so a runaway banner can't blow up the UI.
*/
@@ -85,6 +151,31 @@ export function lastSshErrorLine(stderr: string): string | undefined {
return pick.length > 200 ? `${pick.slice(0, 200)}…` : pick
}
+/**
+ * Do two conns name the same master? Compares exactly the fields `masterArgs` binds with (host,
+ * user, port, identity file); `label` and the rest are display/child-level concerns, and flagging
+ * them would tear down a healthy master over a rename. Used both by the reuse branch and the
+ * in-flight coalescing: without it, editing a server's endpoint while an attempt (or a live
+ * master) for the OLD endpoint existed handed the caller a connection to the wrong host.
+ */
+function sameEndpoint(a: SshConnection, b: SshConnection): boolean {
+ return (
+ a.host === b.host &&
+ a.user === b.user &&
+ (a.port ?? 22) === (b.port ?? 22) &&
+ (a.identityFile ?? '') === (b.identityFile ?? '')
+ )
+}
+
+export interface ConnectResult {
+ controlPath: string
+ hookEndpointPath?: string
+ tmuxConfPath?: string
+ remoteHome?: string
+ claudeAutoPermissionMode?: boolean
+ remoteClaudeVersion?: string | null
+}
+
interface Conn {
conn: SshConnection
controlPath: string
@@ -103,7 +194,7 @@ interface Conn {
/** Does the REMOTE host's claude CLI accept `--permission-mode auto` (>= 2.1.71)? Probed at
* connect (with bounded retries when claude wasn't found): the remote CLI can be older than the
* local one, and the local answer must never be applied to a remote launch. Undefined/false ⇒
- * the renderer omits the flag for this project's Claude nodes (bare command — today's
+ * the renderer omits the flag for this project's Claude nodes (bare command, today's
* behavior), never a failed launch. */
claudeAutoPermissionMode?: boolean
/** The probed remote `claude --version` output. `null` = the probe ran and found no claude
@@ -172,12 +263,14 @@ export class SshProjectManager {
private remoteHooks: RemoteHooks
/** Per-manager counter mixed into each upload token so concurrent drops never collide. */
private uploadSeq = 0
- /** Projects whose agent-status mirror was actually pushed — gates the disconnect cleanup so a
+ /** Projects whose agent-status mirror was actually pushed, gates the disconnect cleanup so a
* transient folder-picker browse (never pushed) doesn't pay an extra rm round-trip. */
private statusPushed = new Set<string>()
+ /** One in-flight connect attempt per project, so concurrent callers share it (see connect).
+ * The conn the attempt was started with rides along so a joiner with an EDITED endpoint can
+ * be detected instead of silently receiving a connection to the old server. */
+ private inFlight = new Map<string, { conn: SshConnection; attempt: Promise<ConnectResult> }>()
private watchdog?: ReturnType<typeof setInterval>
- /** Re-entrancy guard: a tick mid-reconnect (slow host) must not stack a second revalidation. */
- private revalidating = false
constructor(private r: Runners) {
this.remoteHooks = new RemoteHooks({ run: r.run })
}
@@ -186,12 +279,12 @@ export class SshProjectManager {
* Master watchdog. Nothing subscribes to the master process's death, and it can't: with
* `ControlPersist` the real master daemonizes away from the child we spawned, and a network
* change (no sleep event, so no powerMonitor 'resume' → `revalidateAll`) kills it with no
- * signal to us. Every child ssh then silently falls back to a direct connection — sessions
+ * signal to us. Every child ssh then silently falls back to a direct connection, sessions
* keep "working", so the dead master goes unnoticed while each 5s poll opens a fresh
* TCP+auth connection (the ~72k-logins/day field report). The mux'd pty clients' exit-255
* does fire the renderer's SshReconnector, but ptys respawned before the master is back up
* land on direct fallback connections and never migrate. So: periodically re-run the
- * idempotent `connect()` per cached entry (via `revalidateAll`) — a live master costs one
+ * idempotent `connect()` per cached entry (via `revalidateAll`), a live master costs one
* mux'd `-O check`; a dead one gets the full re-establish (stale socket unlinked, master
* respawned, 'reconnecting' status so the renderer flow engages). Interval is unref'd so it
* never holds the process open; an empty conns map makes a tick a no-op.
@@ -199,11 +292,14 @@ export class SshProjectManager {
startWatchdog(intervalMs = MASTER_WATCHDOG_MS): void {
if (this.watchdog) return
this.watchdog = setInterval(() => {
- if (this.revalidating || this.conns.size === 0) return
- this.revalidating = true
- void this.revalidateAll().finally(() => {
- this.revalidating = false
- })
+ if (this.conns.size === 0) return
+ // No global re-entrancy latch here anymore: it held for the WHOLE pass, and one project
+ // parked on a passphrase prompt (PROMPT_WAIT_MS, minutes) froze every other project's
+ // revalidation for that window - the direct-fallback churn this watchdog exists to stop.
+ // Re-entrancy is instead handled where it belongs: connect() coalesces per project, so a
+ // tick that overlaps a still-running pass joins the in-flight attempts instead of stacking
+ // new masters, and healthy projects keep getting their cheap `-O check` every tick.
+ void this.revalidateAll()
}, intervalMs)
this.watchdog.unref?.()
}
@@ -213,21 +309,83 @@ export class SshProjectManager {
this.watchdog = undefined
}
- async connect(
+ /**
+ * Open (or reuse) the project's ControlMaster.
+ *
+ * Concurrent callers for the SAME project share one attempt. Four independent callers can fire
+ * at once (the 45s watchdog's revalidateAll, powerMonitor resume, the renderer's SshReconnector
+ * backoff, and a tab switch or the connect dialog), and without this they raced through the
+ * `existing` branch below and killed each other's in-flight master. The loser then reported an
+ * empty-stderr "Could not establish the SSH connection." while the winner's master was torn
+ * down under it. Waiting on a passphrase prompt widens that window to minutes, which turns the
+ * race from unlikely into routine, so the coalescing has to live here rather than in callers.
+ */
+ connect(projectId: string, conn: SshConnection, remoteCwd?: string): Promise<ConnectResult> {
+ const inFlight = this.inFlight.get(projectId)
+ if (inFlight) {
+ if (sameEndpoint(inFlight.conn, conn)) {
+ // Adopt the joiner's remoteCwd once the shared attempt lands, mirroring the `existing`
+ // reuse branch in connectOnce: dropping it left refForRemoteCwd unable to route remote
+ // git ops for the joiner's folder until the next reconnect.
+ if (remoteCwd) {
+ void inFlight.attempt.then(
+ () => {
+ const e = this.conns.get(projectId)
+ if (e) e.remoteCwd = remoteCwd
+ },
+ () => {}
+ )
+ }
+ return inFlight.attempt
+ }
+ // The endpoint was EDITED while an attempt to the old one is still in flight (connect
+ // dialog racing the watchdog). Sharing would hand this caller a connection to the WRONG
+ // server, and killing the in-flight master mid-attempt is the exact race coalescing
+ // exists to prevent. So wait the old attempt out (its outcome does not matter), then
+ // connect on the new endpoint; connectOnce tears down whatever old-endpoint master the
+ // settled attempt left behind.
+ const after = (): Promise<ConnectResult> => this.connect(projectId, conn, remoteCwd)
+ return inFlight.attempt.then(after, after)
+ }
+ const attempt = this.connectOnce(projectId, conn, remoteCwd).finally(() => {
+ if (this.inFlight.get(projectId)?.attempt === attempt) this.inFlight.delete(projectId)
+ })
+ this.inFlight.set(projectId, { conn, attempt })
+ return attempt
+ }
+
+ private async connectOnce(
projectId: string,
conn: SshConnection,
remoteCwd?: string
- ): Promise<{
- controlPath: string
- hookEndpointPath?: string
- tmuxConfPath?: string
- remoteHome?: string
- claudeAutoPermissionMode?: boolean
- remoteClaudeVersion?: string | null
- }> {
+ ): Promise<ConnectResult> {
const existing = this.conns.get(projectId)
- if (existing) {
- // Verify the cached master is still alive before reusing it — a dropped/timed-out master
+ if (existing && !sameEndpoint(existing.conn, conn)) {
+ // The project now points at a DIFFERENT endpoint/identity. `-O check` below would happily
+ // confirm the OLD master alive and the reuse branch would leave the project silently
+ // connected to the previous server. A bare kill() is not enough either: the daemonized
+ // ControlPersist master outlives our child, and the leftover-socket probe further down
+ // would re-adopt it as a live orphan (the control path is keyed by projectId alone). Only
+ // disconnect()'s `-O exit` over the socket tears the daemonized master and its socket
+ // down for real; the transient 'disconnected' status it emits is immediately followed by
+ // 'connecting' below, and the renderer treats both as "connection gone" anyway.
+ // `keepInFlight`: this teardown is INTERNAL to a connect that is still running, and its own
+ // `inFlight` entry is what makes the rest of this attempt (which can park for minutes on a
+ // passphrase prompt) coalesce concurrent connects. Letting the public disconnect drop it
+ // sent the next same-project connect down the reuse branch instead, where a `-O check`
+ // against the not-yet-bound socket fails and it KILLS the prompting master and spawns a
+ // second one for the same control path.
+ await this.disconnect(projectId, { keepInFlight: true })
+ // `disconnect()` FIRES its `-O exit` but does not await it (`void this.r.run(...)`), and
+ // `kill()` is a no-op for a master that already daemonized. So the old master is usually
+ // still alive right here, and the leftover-socket probe below would `-O check` it, find it
+ // answering, and adopt it as a live orphan: the project ends up back on the OLD endpoint,
+ // which is the exact failure this branch exists to prevent. Await an exit of our own (a
+ // no-op if the first one already landed) and unlink the socket so the probe cannot see it.
+ await this.r.run(exitMasterArgs(existing.conn, existing.controlPath)).catch(() => {})
+ await fs.rm(existing.controlPath, { force: true }).catch(() => {})
+ } else if (existing) {
+ // Verify the cached master is still alive before reusing it, a dropped/timed-out master
// would otherwise leave us reusing a dead socket. If `-O check` fails, surface
// `reconnecting`, drop the stale entry, and fall through to re-establish.
const { code } = await this.r.run(checkMasterArgs(existing.conn, existing.controlPath))
@@ -245,6 +403,12 @@ export class SshProjectManager {
}
}
this.r.onStatus({ projectId, status: 'reconnecting' })
+ // `-O exit` first, kill() second: kill() is a no-op against a master that already daemonized
+ // (ControlPersist), and the leftover-socket unlink below would otherwise pull the socket out
+ // from under a still-live daemon that keeps its TCP session and remote reverse forward for
+ // up to 300s - the "two fds on one sshd" condition the orphan-rebuild path exists to cure.
+ // Best-effort: a genuinely dead master makes this a fast failed round-trip.
+ await this.r.run(exitMasterArgs(existing.conn, existing.controlPath)).catch(() => {})
existing.master.kill()
this.conns.delete(projectId)
}
@@ -254,16 +418,16 @@ export class SshProjectManager {
try {
await fs.mkdir(path.dirname(controlPath), { recursive: true, mode: 0o700 })
} catch {
- // ignore — keeps the manager unit-testable
+ // ignore, keeps the manager unit-testable
}
this.r.onStatus({ projectId, status: 'connecting' })
- // A master socket FILE can outlive its process (app crash, `kill -9`, host sleep/resume — a
+ // A master socket FILE can outlive its process (app crash, `kill -9`, host sleep/resume, a
// plain `kill()` on quit doesn't always let ssh unlink it). ssh's `ControlMaster=auto` REFUSES
// to bind over an existing socket file ("ControlSocket … already exists, disabling
// multiplexing"), so a leftover DEAD socket makes every `-O check` below fail and connect()
- // time out with a generic error — the "SSH connection error" a user sees with no cause. Only a
+ // time out with a generic error, the "SSH connection error" a user sees with no cause. Only a
// FRESH connect reaches here (an existing entry returned above), so any socket on disk is a
- // leftover: probe it once — a still-answering master is a live orphan (its `ControlPersist`
+ // leftover: probe it once, a still-answering master is a live orphan (its `ControlPersist`
// outlived us) → adopt it; a dead one gets unlinked so the fresh master can bind. The common
// case (no leftover) skips straight to spawn with no extra round-trip.
let master: Conn['master']
@@ -290,16 +454,32 @@ export class SshProjectManager {
}
} else {
if (leftover) await fs.rm(controlPath, { force: true }).catch(() => {})
- master = this.r.spawnMaster(masterArgs(conn, controlPath))
+ // The app-private agent has to be listening BEFORE ssh authenticates, or `AddKeysToAgent`
+ // stores the unlocked key nowhere and every connect this run prompts again. Never fatal.
+ await this.r.ensureAgent?.().catch(() => {})
+ master = this.r.spawnMaster(masterArgs(conn, controlPath), this.r.masterEnvFor?.(conn.identityFile) ?? {})
}
this.conns.set(projectId, { conn, controlPath, master, remoteCwd })
- // Wait until the master answers `-O check`, retrying briefly.
- for (let i = 0; i < 50; i++) {
+ // Wait until the master answers `-O check`. The bound is the master PROCESS, not a fixed
+ // attempt count: while the spawned ssh is alive it is connecting, authenticating, or waiting
+ // on the askpass passphrase prompt, which a human can take minutes to answer, so it gets the
+ // long ceiling. The moment it exits without the socket answering, a few grace checks run (the
+ // ControlPersist daemonize handoff) and then the loop fails WITH the master's stderr, so a
+ // definitive auth error surfaces in about a second instead of after a blind timeout.
+ // `ConnectTimeout` in masterArgs keeps a black-holed TCP connect from riding the long ceiling.
+ // This deliberately does NOT depend on `conn.identityFile`: a saved server usually has none
+ // (ssh then offers the default identities, which are just as likely to be encrypted), and
+ // gating the wait on it meant the very connections that need a prompt got the 5s budget.
+ // Spawners with no exit signal fall back to the prompting signal, EXCEPT adopted orphans,
+ // which cannot prompt at all (see the loop body).
+ let exitGrace = MASTER_EXIT_GRACE_CHECKS
+ let waitStartedAt = Date.now()
+ for (;;) {
const { code } = await this.r.run(checkMasterArgs(conn, controlPath))
if (code === 0) {
// Master is up. Best-effort remote hook setup (reverse tunnel + endpoint + install);
- // fail-open — a null result just means the remote agents run without hooks.
- let res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
+ // fail-open, a null result just means the remote agents run without hooks.
+ const res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
// Fresh-launch-straight-to-SSH failure mode (field report: no RUNNING badges from remote
// sessions until a reconnect): an ADOPTED live-orphan master carries the previous app run's
// `-R <sock>:127.0.0.1:<oldPort>` reverse-hook forward. Its target port died with that run,
@@ -308,20 +488,29 @@ export class SshProjectManager {
// remote endpoint file is never written → every remote hook POST vanishes → dead status for
// the whole session. A client-side forward-cancel can't reliably displace the leaked listener;
// the certain cure is a FRESH master, whose predecessor's forwards sshd tears down on `-O exit`.
- // Rebuild once and retry — ONLY on the orphan+failure path, so a clean connect is untouched.
- if (!res && reusedOrphan) {
+ // Rebuild once and retry, ONLY on the orphan+failure path, so a clean connect is untouched.
+ // Ownership check first: `setup()` is several round-trips, and if a disconnect + reconnect
+ // landed inside that window this attempt no longer owns the control path. Rebuilding then
+ // `-O exit`s and UNLINKS the live attempt's master and socket, and overwrites its map entry
+ // with a third master, while the renderer has already been handed the second one.
+ if (!res && reusedOrphan && this.conns.get(projectId)?.master === master) {
await this.r.run(exitMasterArgs(conn, controlPath)).catch(() => {}) // drop the orphan + its forwards
await fs.rm(controlPath, { force: true }).catch(() => {})
reusedOrphan = false
- master = this.r.spawnMaster(masterArgs(conn, controlPath))
+ await this.r.ensureAgent?.().catch(() => {}) // as on the fresh-spawn path
+ master = this.r.spawnMaster(masterArgs(conn, controlPath), this.r.masterEnvFor?.(conn.identityFile) ?? {})
this.conns.set(projectId, { conn, controlPath, master, remoteCwd })
- for (let j = 0; j < 50 && !res; j++) {
- if ((await this.r.run(checkMasterArgs(conn, controlPath))).code === 0) {
- res = await this.remoteHooks.setup(projectId, conn, controlPath, this.r.getHook())
- break
- }
- await new Promise((r) => setTimeout(r, 100))
- }
+ // Re-enter the wait loop on the SAME terms as a fresh spawn: the exit-aware,
+ // wall-clock-bounded wait above, with the budget restarted (the orphan adopt + failed
+ // setup already burned real time). A fixed few-second inner loop here reported
+ // `connected` while the rebuilt master was still waiting on its askpass passphrase
+ // prompt (agent cold): no socket was bound, every later child ssh hit a nonexistent
+ // socket, and the just-recovered hookEndpointPath was lost again. Falling through to
+ // the loop also means a rebuilt master that never comes up fails properly, with ITS
+ // stderr and pid-attributed cancel, instead of being declared connected.
+ exitGrace = MASTER_EXIT_GRACE_CHECKS
+ waitStartedAt = Date.now()
+ continue
}
const hookEndpointPath = res?.endpointPath
// Resolve the remote $HOME once and retain it (the hook setup above also learns it but
@@ -361,7 +550,7 @@ export class SshProjectManager {
}
// Canvas control for remote agent nodes. Gated on BOTH the resolved home (every remote
// path must be absolute) and a verified tunnel (`hookEndpointPath` is only set once
- // setup() proved the reverse forward reaches this app run) — installing a skill whose
+ // setup() proved the reverse forward reaches this app run), installing a skill whose
// endpoint answers nothing would have the agent retry a dead socket instead of reporting
// canvas control as unavailable. Not awaited: it is several remote round-trips of pure
// best-effort setup, and holding the connect on them would delay every terminal.
@@ -369,14 +558,21 @@ export class SshProjectManager {
void this.remoteHooks.installCanvasControl(conn, controlPath, remoteHome)
void this.remoteHooks.installContextLink(conn, controlPath, remoteHome)
}
- const entry = this.conns.get(projectId)
+ // 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
+ // leaves a DIFFERENT attempt's master in the map. Writing this attempt's results onto it
+ // clobbered the live connection's `hookEndpointPath` with `undefined` (the "no RUNNING
+ // badges from remote sessions" failure), emitted a second `connected`, and started a
+ // second claude probe against the same entry. A stale attempt reports its own result and
+ // touches nothing.
+ const entry = this.conns.get(projectId)?.master === master ? this.conns.get(projectId) : undefined
if (entry) {
entry.hookEndpointPath = hookEndpointPath
entry.remoteHome = remoteHome
entry.tmuxConfPath = tmuxConfPath
+ this.r.onStatus({ projectId, status: 'connected' })
}
- this.r.onStatus({ projectId, status: 'connected' })
- // Probe the REMOTE claude CLI once per connect — `--permission-mode auto` only exists in
+ // Probe the REMOTE claude CLI once per connect, `--permission-mode auto` only exists in
// >= 2.1.71 and the host's CLI may be older than the local one. NOT awaited: the answer is
// only ever an optional flag, and the probe's login shell must not delay the connect (and
// with it every terminal in the project). It pushes itself into the conn + renderer when
@@ -384,7 +580,7 @@ export class SshProjectManager {
// Swallow any rejection: this is a best-effort optional probe, and an unhandled rejection
// in the main process is a hard crash (Node's default --unhandled-rejections=throw), not a
// log line. Internals are already try/catch-guarded, but `this.r.onStatus` (IPC send) can
- // still throw if the window is torn down mid-probe — that must never surface here.
+ // still throw if the window is torn down mid-probe, that must never surface here.
if (entry) void this.probeClaudeAutoPermissionMode(projectId, entry).catch(() => {})
return {
controlPath,
@@ -395,17 +591,59 @@ export class SshProjectManager {
remoteClaudeVersion: entry?.remoteClaudeVersion
}
}
+ const alive = master.exited ? !master.exited() : undefined
+ if (alive === false) {
+ // Master ended and the socket still is not answering: either a real failure, or the
+ // daemonize handoff raced our poll. A few more checks settle which, then give up.
+ if (--exitGrace <= 0) break
+ } else {
+ // An adopted orphan positively CANNOT be prompting: it authenticated in a previous app
+ // run and is never re-authed by reuse. Consulting the global prompting signal for it
+ // could only pick up a DIFFERENT project's dialog and stretch this dead orphan's
+ // failure from 5s to the 300s prompt ceiling. The prompting fallback is thus only for
+ // spawners that truly cannot report exit (test fakes).
+ const extended = alive ?? (reusedOrphan ? false : (this.r.askpassIsPrompting?.() ?? false))
+ if (Date.now() - waitStartedAt >= (extended ? PROMPT_WAIT_MS : BASE_WAIT_MS)) break
+ }
await new Promise((res) => setTimeout(res, 100))
}
- // Capture the master's real ssh error BEFORE disconnect tears it down — that stderr
+ // Capture the master's real ssh error BEFORE disconnect tears it down, that stderr
// ("Permission denied (publickey)", "Could not resolve hostname", "Host key verification
// failed", …) is the actual cause, and is otherwise thrown away by the master's ignored stdio.
const stderr = master.stderr?.().trim()
- await this.disconnect(projectId)
+ // Same "cannot have prompted" fact as above: an adopted orphan has no pid to attribute by,
+ // and letting wasCancelledBy(undefined) fall back to the 60s global clock relabelled an
+ // orphan's genuine failure as "cancelled" whenever any unrelated prompt was declined in
+ // that window. No prompt ever existed for it, so the answer is a hard false.
+ const cancelled = reusedOrphan ? false : (this.r.askpassWasCancelled?.(master.pid?.()) ?? false)
+ // Tear down OUR master, not whatever happens to be in the map. A concurrent attempt may have
+ // replaced the entry while we were waiting, and calling disconnect() blindly would kill the
+ // healthy replacement and delete its entry, leaving a project that reports connected while
+ // owning nothing.
+ if (this.conns.get(projectId)?.master === master) await this.disconnect(projectId)
+ else master.kill()
const detail = stderr ? lastSshErrorLine(stderr) : undefined
- const message = detail
- ? `Could not establish the SSH connection: ${detail}`
- : 'Could not establish the SSH connection.'
+ // A publickey denial where askpass was NEVER invoked means ssh had no key file to unlock at
+ // all, which is what a credential held only in an agent looks like (a smartcard, 1Password or
+ // Secretive without an `IdentityAgent` line). Masters authenticate against the app-private
+ // agent (ssh-agent.ts), so the user's own agent is not consulted and no prompt can rescue it.
+ // This is a HINT, not a retry: retrying on the ambient agent would spend a second failed login
+ // on every ordinary auth failure (launchd exports SSH_AUTH_SOCK on every Mac, empty or not),
+ // and it would carry `AddKeysToAgent=yes` into the user's agent, which is the exact leak this
+ // design closes. `IdentityAgent` in ~/.ssh/config overrides SSH_AUTH_SOCK and is the documented
+ // setup for those tools, so the fix belongs in the user's config, not in a blind second attempt.
+ const agentOnlyHint =
+ !reusedOrphan &&
+ !cancelled &&
+ /permission denied/i.test(stderr ?? '') &&
+ !(this.r.askpassAsked?.(master.pid?.()) ?? false)
+ ? ' nodeterm authenticates through its own ssh-agent, so a key held only in your system agent is not offered — set IdentityAgent in ~/.ssh/config, or give this server an identity file.'
+ : ''
+ const message = cancelled
+ ? 'SSH connection cancelled: this key needs its passphrase.'
+ : detail
+ ? `Could not establish the SSH connection: ${detail}${agentOnlyHint}`
+ : `Could not establish the SSH connection.${agentOnlyHint}`
this.r.onStatus({ projectId, status: 'error', error: message })
throw new Error(message)
}
@@ -431,7 +669,7 @@ export class SshProjectManager {
if (!c) return null
// `localPath` is a renderer string passed straight to scp as a positional arg. A value starting
// with `-` (e.g. `-oProxyCommand=…`) would be parsed by scp as an OPTION (argv flag smuggling →
- // RCE), not a file. A real OS file drop is always an absolute path, so require one here — this
+ // RCE), not a file. A real OS file drop is always an absolute path, so require one here, this
// rejects `-`-prefixed, relative, and empty paths and fully closes the flag-smuggling vector.
if (!localPath.startsWith('/')) return null
try {
@@ -447,7 +685,7 @@ export class SshProjectManager {
if (mk.code !== 0) return null
// `fileName` is a renderer string: posixQuote blocks shell injection but NOT filesystem
// traversal (e.g. `../../../.bashrc` would escape the token dir and overwrite a remote file).
- // Basename it in main before building the write path — never trust it for a write target.
+ // Basename it in main before building the write path, never trust it for a write target.
const safe = path.posix.basename(fileName)
if (!safe || safe === '.' || safe === '..') return null
const remotePath = `${dir}/${safe}`
@@ -459,7 +697,7 @@ export class SshProjectManager {
}
/**
- * Pull a remote file (or directory tree) down to `destDir` over the project's ControlMaster —
+ * Pull a remote file (or directory tree) down to `destDir` over the project's ControlMaster ,
* the mirror of `uploadFile`, and what the Explorer's Download action runs on an SSH project.
*
* Three things carry the safety here:
@@ -469,7 +707,7 @@ export class SshProjectManager {
* renderer string can steer the write, and `..` can never appear as a component.
* - **Nothing existing is overwritten.** A collision takes the next `name (n)` candidate.
* - **A failed transfer leaves no half-file under the real name.** scp writes to `<name>.part`
- * (a `.part` DIRECTORY for `-r`) and it is renamed into place only on exit 0 — the same
+ * (a `.part` DIRECTORY for `-r`) and it is renamed into place only on exit 0, the same
* write-then-rename discipline `sshWriteArgs` uses remotely. A failure unlinks the remains.
*/
async downloadFile(projectId: string, remotePath: string, destDir: string): Promise<DownloadResult> {
@@ -479,7 +717,7 @@ export class SshProjectManager {
if (!name) return { ok: false, error: 'That path cannot be downloaded.' }
try {
// Ask the REMOTE whether this is a directory rather than trusting the renderer's tree state:
- // it decides `-r`, and the tree can be stale. A failed probe is not evidence of "file" —
+ // it decides `-r`, and the tree can be stale. A failed probe is not evidence of "file" ,
// but `test -d` failing on a live master overwhelmingly means "not a directory", and the
// worst case of guessing wrong is a plain scp error, so this stays fail-open.
const probe = await this.r.run(childArgs(c.conn, c.controlPath, `test -d ${quoteRemotePath(remotePath)}`))
@@ -516,10 +754,10 @@ export class SshProjectManager {
/**
* Pull a remote FILE into the local media cache (for nt-media:// playback) and resolve its
- * cached absolute path. The entry is keyed by (host, remote path) — see remoteMediaCacheName —
+ * cached absolute path. The entry is keyed by (host, remote path), see remoteMediaCacheName ,
* so re-opening an unchanged file reuses the cached copy: reuse is gated on the remote size
* still matching (`wc -c` is portable where `stat -c/-f` is not). A FAILED size probe is not
- * evidence of anything (a hiccup ≠ a changed file) — it falls through to a fresh transfer,
+ * evidence of anything (a hiccup ≠ a changed file), it falls through to a fresh transfer,
* whose own failure is the real error. Directories are refused: a player node plays one file.
*/
async cacheMediaFile(
@@ -550,7 +788,7 @@ export class SshProjectManager {
}
await fs.mkdir(cacheDir, { recursive: true })
// Same write-then-rename discipline as downloadFile: never leave a half-copied file
- // under the final name — nt-media would happily serve a truncated video.
+ // under the final name, nt-media would happily serve a truncated video.
const partPath = `${dest}.part`
await fs.rm(partPath, { force: true }).catch(() => {})
const res = await this.r.runScp(scpDownArgs(c.conn, c.controlPath, remotePath, partPath, false))
@@ -567,7 +805,7 @@ export class SshProjectManager {
}
/** Best-effort, bounded cache: keep the newest MEDIA_CACHE_KEEP entries. An evicted entry that
- * is still playing in an open node stops being seekable — acceptable for a 20-deep cache of a
+ * is still playing in an open node stops being seekable, acceptable for a 20-deep cache of a
* convenience copy; the node re-fetches on next open. */
private async pruneMediaCache(cacheDir: string, except: string): Promise<void> {
try {
@@ -579,7 +817,7 @@ export class SshProjectManager {
await fs.rm(path.join(cacheDir, n), { force: true }).catch(() => {})
}
} catch {
- // pruning is best-effort — a fat cache is a nuisance, not a fault
+ // pruning is best-effort, a fat cache is a nuisance, not a fault
}
}
@@ -588,7 +826,7 @@ export class SshProjectManager {
* Called on project delete BEFORE disconnect, so the remote `nt-<id>` sessions are killed
* regardless of whether the nodes were mounted (only the active project's nodes are). `nodeIds`
* are raw node ids; we map each to its `nt-<id>` session name (the same name `spawnSession` /
- * `remoteTmuxHasSessionArgs` use). Best-effort per id — a missing session is ignored.
+ * `remoteTmuxHasSessionArgs` use). Best-effort per id, a missing session is ignored.
*/
async killSessions(projectId: string, nodeIds: string[]): Promise<void> {
const c = this.conns.get(projectId)
@@ -636,6 +874,23 @@ export class SshProjectManager {
return undefined
}
+ /**
+ * `user@host` of the connection whose ControlMaster has this pid, for the passphrase dialog.
+ * The askpass helper reports the asking ssh process as its `$PPID` (see ssh-askpass.ts), which
+ * is exactly the master this manager spawned, so a prompt can be attributed to a server without
+ * threading a project id through the askpass protocol. Undefined when nothing matches: an
+ * adopted orphan master has no pid, and orphans never prompt anyway. The dialog just falls back
+ * to naming the key alone.
+ */
+ targetForMasterPid(pid: string): string | undefined {
+ if (!pid) return undefined
+ for (const c of this.conns.values()) {
+ const p = c.master.pid?.()
+ if (p !== undefined && String(p) === pid) return `${c.conn.user}@${c.conn.host}`
+ }
+ return undefined
+ }
+
/** The resolved remote `$HOME` for a connected project, if known. */
remoteHomeFor(projectId: string): string | undefined {
return this.conns.get(projectId)?.remoteHome
@@ -643,22 +898,36 @@ export class SshProjectManager {
/**
* 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
+ * under the masters, but ServerAlive only notices ~60s AFTER wake, until then every terminal
* looks alive and is dead (keys echo nothing, scroll does nothing). `connect()` is idempotent:
- * a live master returns immediately; a dead one is killed — which tears down its mux'd
+ * a live master returns immediately; a dead one is killed, which tears down its mux'd
* per-terminal ssh clients too, so their exit-255 drops fire the renderer's SshReconnector
- * NOW instead of a minute later — and re-established, after which the reconnector's
+ * NOW instead of a minute later, and re-established, after which the reconnector's
* 'connected' flush respawns the dead nodes. Failures just leave the normal status-event
* error path in charge (connect reports it before throwing).
*/
async revalidateAll(): Promise<void> {
- for (const [projectId, e] of [...this.conns]) {
- try {
- await this.connect(projectId, e.conn, e.remoteCwd)
- } catch {
- // connect() already reported an error status for this project; keep checking the rest.
- }
- }
+ // Per project CONCURRENTLY, not serially: a re-establish can park on the askpass passphrase
+ // prompt for up to PROMPT_WAIT_MS (5 min), and a serial pass wedged EVERY other project's
+ // check behind it for that whole window - the direct-fallback churn the watchdog exists to
+ // stop, reintroduced by the watchdog itself. connect() coalesces per project, so concurrent
+ // passes cannot double-spawn; a live master's check is one mux'd `-O check`, so the fan-out
+ // costs nothing in the healthy case.
+ await Promise.all(
+ [...this.conns.keys()].map(async (projectId) => {
+ // Re-read the entry at fire time instead of using a snapshot of it: the user may repoint
+ // a server while other projects are still checking. Passing a stale `conn` would send
+ // connect() down the endpoint-mismatch branch and tear down the master that was just
+ // established for the NEW endpoint, silently reverting the project to the old host.
+ const e = this.conns.get(projectId)
+ if (!e) return // disconnected while the pass was being set up
+ try {
+ await this.connect(projectId, e.conn, e.remoteCwd)
+ } catch {
+ // connect() already reported an error status for this project; the rest still ran.
+ }
+ })
+ )
}
/** The connection's cached remote `--permission-mode auto` capability (undefined = not
@@ -671,7 +940,7 @@ export class SshProjectManager {
* Every LIVE connection as `{ projectId, hostKey }`. Feeds the remote-usage target list, which
* needs both halves: the host key to match accounts against, and a project whose ControlMaster
* can carry the read. Hosts shared by several projects are deduped by the caller
- * (`remoteUsageTargets`), not here — this is the raw map.
+ * (`remoteUsageTargets`), not here, this is the raw map.
*/
connectedHosts(): { projectId: string; hostKey: string }[] {
return [...this.conns.entries()].map(([projectId, c]) => ({
@@ -687,7 +956,7 @@ export class SshProjectManager {
}
/** Remote path of this project's pushed agent-status mirror (`~`-relative when the remote
- * home never resolved — the shell expands it in the commands below). */
+ * home never resolved, the shell expands it in the commands below). */
private statusFilePath(projectId: string, c: Conn): string {
const dir = c.remoteHome ? `${c.remoteHome}/.nodeterm` : '~/.nodeterm'
return `${dir}/agent-status-${projectId}.json`
@@ -696,8 +965,8 @@ export class SshProjectManager {
/**
* Mirror this project's slice of the agent-status doc onto its host as
* `~/.nodeterm/agent-status-<projectId>.json` (atomic tmp+mv, 0600 via umask). This is the
- * ONLY status source that exists on an SSH host — hook events tunnel from the host to the
- * desktop's loopback hook server — so it's what the mobile companion reads when it browses
+ * ONLY status source that exists on an SSH host, hook events tunnel from the host to the
+ * desktop's loopback hook server, so it's what the mobile companion reads when it browses
* the host directly. No-ops when the project isn't connected; best-effort otherwise (a failed
* write only means stale/absent badges on the phone).
*/
@@ -723,10 +992,10 @@ export class SshProjectManager {
/**
* Sweep phone read-acks on the connected hosts (spec: cross-surface read sync). The phone drops
* `~/.nodeterm/acks/<nodeId>.seen` on the host it can reach; for a Mac→SSH node that host is the
- * REMOTE one, so the desktop must consume them over the ControlMaster — the local-fs sweep never
+ * REMOTE one, so the desktop must consume them over the ControlMaster, the local-fs sweep never
* sees them. One command per connected HOST (deduped by host key, since projects sharing a host
* share `$HOME/.nodeterm/acks`) atomically lists + deletes each `.seen` and prints its nodeId; the
- * returned ids are fed the SAME `ackDone` + unread-clear path a local ack takes. Best-effort — a
+ * returned ids are fed the SAME `ackDone` + unread-clear path a local ack takes. Best-effort, a
* disconnected/failed project simply contributes nothing. The command is fully literal (no
* interpolation), and the returned nodeIds are used only as in-memory map keys (never a path), so
* a compromised host can at worst clear an unread badge / resolve a done card it can guess.
@@ -754,7 +1023,7 @@ export class SshProjectManager {
}
}
} catch {
- // best-effort per host — a failed sweep just leaves the acks for the next tick
+ // best-effort per host, a failed sweep just leaves the acks for the next tick
}
}
return out
@@ -866,11 +1135,11 @@ export class SshProjectManager {
* Best-effort `claude --version` ON THE REMOTE HOST. Null when it can't be determined.
*
* An ssh EXEC channel gets a non-interactive, non-login shell, whose rc file usually bails out
- * early — so a claude installed via nvm/asdf/homebrew-on-PATH may be invisible to a plain
+ * early, so a claude installed via nvm/asdf/homebrew-on-PATH may be invisible to a plain
* `claude --version`. The remote tmux session that actually RUNS the node uses a login shell, so
* the probe tries that first and only then the bare command. A login shell also sources the
* user's profile, whose STDOUT noise (banners, neofetch, …) would otherwise be parsed as the
- * version — hence the marker-delimited value (see `claude-version-probe.ts`).
+ * version, hence the marker-delimited value (see `claude-version-probe.ts`).
*/
private async remoteClaudeVersion(conn: SshConnection, controlPath: string): Promise<string | null> {
try {
@@ -887,21 +1156,21 @@ export class SshProjectManager {
* the answer into the live conn + the renderer (a `connected` status event carrying it).
*
* Deliberately OFF the connect critical path: it runs `$SHELL -lc`, which sources nvm/conda/rbenv
- * inits — routinely hundreds of ms, sometimes seconds — and every remote terminal in the project
+ * inits, routinely hundreds of ms, sometimes seconds, and every remote terminal in the project
* waits on connect. A node launched in the gap just omits the flag (the designed fail-open
* fallback); the next launch, once the answer lands, gets `auto`.
*
- * A FAILED attempt (no claude found) retries on a bounded backoff — a transient hiccup must not
+ * A FAILED attempt (no claude found) retries on a bounded backoff, a transient hiccup must not
* disable `auto` until the next reconnect. EVERY attempt pushes its answer immediately (the
* fail-open `false` first, a later success upgrading it): launch paths that wait on the first
* answer (`ensureActivePermissionMode`) must never be held hostage by the retry tail. A definite
- * version — old or new — stops the retries: a CLI doesn't change under a live connection.
+ * version, old or new, stops the retries: a CLI doesn't change under a live connection.
*/
private async probeClaudeAutoPermissionMode(projectId: string, entry: Conn): Promise<void> {
const delays = this.r.probeRetryDelaysMs ?? PROBE_RETRY_DELAYS_MS
for (let attempt = 0; ; attempt++) {
// One remote `claude --version` feeds BOTH version gates (permission-mode auto >= 2.1.71 and
- // fullscreen tui >= 2.1.89) — no second probe.
+ // fullscreen tui >= 2.1.89), no second probe.
const version = await this.remoteClaudeVersion(entry.conn, entry.controlPath)
// Disconnected / reconnected (new Conn) while we probed → the answer belongs to a dead
// connection; drop it rather than write it onto the new one.
@@ -930,7 +1199,14 @@ export class SshProjectManager {
}
}
- async disconnect(projectId: string): Promise<void> {
+ /**
+ * Tear a project's master down. `keepInFlight` marks an INTERNAL teardown inside a live connect
+ * (see connectOnce's endpoint-change branch); `final` marks a USER-facing disconnect (the IPC
+ * handler, i.e. a deleted project), which is the only kind allowed to report the manager idle —
+ * internal teardowns, the watchdog's stale-master drop and a failed connect all empty `conns`
+ * routinely and must not be read as "the user is done with SSH".
+ */
+ async disconnect(projectId: string, opts?: { keepInFlight?: boolean; final?: boolean }): Promise<void> {
const c = this.conns.get(projectId)
if (!c) return
// Remove the pushed agent-status mirror while the master is still alive: a file left behind
@@ -947,7 +1223,20 @@ export class SshProjectManager {
void this.r.run(exitMasterArgs(c.conn, c.controlPath))
c.master.kill()
this.conns.delete(projectId)
+ // Drop any in-flight connect attempt for this project. Without this, a connect() issued after
+ // a disconnect coalesces onto the stale attempt (see connect): the user tears a project down,
+ // re-opens it, and the fresh connect returns the DOOMED attempt's promise instead of
+ // establishing a master for the live server. The running attempt is not awaited/cancelled
+ // here (it may be blocked on a passphrase prompt), but once settled its .finally sees no
+ // matching inFlight entry and does not resurrect anything. `keepInFlight` is the internal
+ // caller's opt-out: a teardown INSIDE a live attempt must not discard that attempt's own
+ // coalescing entry (see connectOnce's endpoint-change branch).
+ if (!opts?.keepInFlight) this.inFlight.delete(projectId)
this.r.onStatus({ projectId, status: 'disconnected' })
+ // Nothing left to keep an unlocked key alive for. Production schedules (not performs) the
+ // agent shutdown: the connect dialog's throwaway browse master disconnects a few hundred ms
+ // before the real project connects, and forgetting in that gap costs a second prompt.
+ if (opts?.final && this.conns.size === 0) this.r.onIdle?.()
}
/**
@@ -957,53 +1246,211 @@ export class SshProjectManager {
* master, so on a hard quit `c.master.kill()` would never run → orphaned `-N` master (~5 min
* ControlPersist). Here we kill the master immediately and skip the graceful `-O cancel`: the
* reverse hook forward dies with the master, so cancelling it is unnecessary on quit.
+ *
+ * `kill()` alone is not enough to make quit mean quit, though: a successful master DAEMONIZES
+ * (ControlPersist=300), so the child we kill has usually already exited and the real master
+ * lives on for five minutes — long enough for a relaunch to adopt it through the leftover-socket
+ * probe and connect with no passphrase, even though the app-private agent (and with it the
+ * unlocked key) died at quit. The synchronous `-O exit` below is what closes that: it tears the
+ * daemon down over its own socket. Bounded per connection by the runner, since this blocks quit.
+ * Remote tmux sessions are server-side and unaffected; only the transport goes.
*/
disconnectAll(): void {
this.stopWatchdog()
for (const projectId of [...this.conns.keys()]) {
const c = this.conns.get(projectId)
if (!c) continue
+ this.r.runSync?.(exitMasterArgs(c.conn, c.controlPath))
c.master.kill()
this.conns.delete(projectId)
this.r.onStatus({ projectId, status: 'disconnected' })
}
+ // Drop every in-flight connect attempt (see disconnect: a stale attempt must not coalesce a
+ // later connect onto a master that was just killed for a now-orphaned attempt).
+ this.inFlight.clear()
+ }
+}
+
+/**
+ * Pending renderer answers to sshPassphraseRequest, keyed by requestId. One `ipcMain.handle` for
+ * sshPassphraseSubmit resolves whichever entry the user answered.
+ */
+const pendingPassphrasePrompts = new Map<string, (value: string | null) => void>()
+
+/**
+ * Push to the renderer without ever letting the UI's health become load-bearing. `isDestroyed()`
+ * on the window is NOT enough: `webContents.send` throws "Render frame was disposed" when the
+ * frame is gone but the window object is not (a renderer crash, Cmd+R, navigation, quit). Left
+ * unguarded that throw either abandoned an in-flight passphrase prompt (answered as empty, so ssh
+ * dropped the key and the connect died with a bare Permission denied) or, from the expiry timer
+ * below, escaped as an UNCAUGHT exception in the main process. Returns false when nothing could
+ * be delivered.
+ *
+ * The explicit getMainWindow() probe is the other half: sendToMain's optional chain silently
+ * NO-OPS when there is no window at all (macOS close-to-dock, or before the first window exists),
+ * so without the probe this returned true for a send nobody received. That false "delivered" kept
+ * promptForPassphrase's no-UI branch dead exactly when it was needed: with the window closed and
+ * the watchdog respawning a master after a network drop, the prompt was "sent" to nothing and the
+ * askpass curl held the ssh master for the full 5-minute expiry, repeating every watchdog cycle
+ * until the window was reopened.
+ *
+ * ACCEPTED gap: `true` still only means "the webContents took the send". During a Cmd+R reload
+ * the frame is alive before React has re-attached onPassphraseRequest, so a prompt raised in
+ * that window is dropped and its connect rides the prompt expiry, after which the watchdog's
+ * next reconnect prompts again into the now-attached listener. Closing it needs a renderer ack
+ * handshake per prompt; a one-in-a-reload race that self-heals within one expiry does not buy
+ * that machinery.
+ */
+function pushToRenderer(channel: string, payload: unknown): boolean {
+ if (!getMainWindow()) return false
+ try {
+ sendToMain(channel, payload)
+ return true
+ } catch {
+ return false
}
}
+/** `null` means the user actively declined; `undefined` means nobody ever answered (the prompt
+ * expired or there was no UI to ask). Only a real decline should be reported as a cancellation. */
+type PromptOutcome = string | null | undefined
+
+/** Exported for tests: the whole main-side prompt path (deliver, expire, dismiss, no-UI) runs
+ * without Electron, with the window faked through main-window's setMainWindow. */
+export function promptForPassphrase(req: {
+ identityFile: string
+ retry: boolean
+ /** `user@host` this unlock is for, when the asking master could be identified. One key can
+ * serve several servers and this prompt can fire from the watchdog long after any connect
+ * dialog closed, so without it the dialog names a key and no destination. */
+ target?: string
+}): Promise<PromptOutcome> {
+ return new Promise((resolve) => {
+ const requestId = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
+ // Auto-resolve an abandoned prompt (user walked away, never answered or hit Cancel) instead
+ // of leaking the map entry and the askpass curl's HTTP request forever. Same bound as
+ // PROMPT_WAIT_MS, so the connect() wait loop, this timeout, and the askpass script's own
+ // curl --max-time all give up around the same point. The dismiss event closes the
+ // renderer's dialog too, so a late answer cannot land in a request that no longer exists.
+ const timer = setTimeout(() => {
+ pendingPassphrasePrompts.delete(requestId)
+ pushToRenderer(IPC.sshPassphraseDismiss, { requestId })
+ resolve(undefined) // expired, not declined
+ }, PROMPT_WAIT_MS)
+ pendingPassphrasePrompts.set(requestId, (value) => {
+ clearTimeout(timer)
+ resolve(value)
+ })
+ const payload: SshPassphraseRequest = {
+ requestId,
+ identityFile: req.identityFile,
+ retry: req.retry,
+ target: req.target
+ }
+ if (!pushToRenderer(IPC.sshPassphraseRequest, payload)) {
+ // No UI could receive it, so no answer is ever coming. Fail now rather than hold ssh (and
+ // the connect) for the full expiry window.
+ clearTimeout(timer)
+ pendingPassphrasePrompts.delete(requestId)
+ resolve(undefined)
+ }
+ })
+}
+
+/** The main-side half of the sshPassphraseSubmit IPC: resolve the pending prompt for
+ * `requestId` with the user's answer (null = declined). A stale/unknown requestId (already
+ * expired, double submit) is a silent no-op. Exported so the (requestId, value) contract is
+ * unit-testable; initSshProject's ipcMain.handle is a one-line delegate to this. */
+export function resolvePassphrasePrompt(requestId: string, value: string | null): void {
+ pendingPassphrasePrompts.get(requestId)?.(value)
+ pendingPassphrasePrompts.delete(requestId)
+}
+
export function initSshProject(
- win: BrowserWindow,
- onConnected?: (projectId: string) => void
+ onConnected?: (projectId: string) => void,
+ askpassScriptPath?: string
): SshProjectManager {
const ssh = sshBin()
const scp = scpBin()
+ // No window reference is threaded through here on purpose: every renderer push resolves the
+ // live window AT SEND TIME (getMainWindow/sendToMain), because a captured BrowserWindow goes
+ // stale across a macOS close/reopen cycle (see main-window.ts).
+ ipcMain.handle(IPC.sshPassphraseSubmit, (_e, requestId: string, value: string | null) =>
+ resolvePassphrasePrompt(requestId, value)
+ )
const mgr = new SshProjectManager({
userDataDir: app.getPath('userData'),
- spawnMaster: (args) => {
+ spawnMaster: (args, env) => {
// Capture the master's stderr (stdin/stdout stay ignored) so a failed connect can report the
// real ssh error instead of a generic timeout. Buffer is capped so a chatty host can't grow it
// unbounded; the master is long-lived and mostly silent, so this holds only the connect-time
// diagnostics we actually want.
- const child = spawn(ssh, args, { stdio: ['ignore', 'ignore', 'pipe'] })
+ const child = spawn(ssh, args, {
+ stdio: ['ignore', 'ignore', 'pipe'],
+ env: env && Object.keys(env).length ? { ...process.env, ...env } : process.env
+ })
let stderr = ''
+ let exited = false
child.stderr?.on('data', (chunk: Buffer) => {
if (stderr.length < MASTER_STDERR_CAP) stderr += chunk.toString('utf-8')
})
- // A spawn failure (ssh binary missing/unexecutable) surfaces on 'error' — fold it into the
+ // A spawn failure (ssh binary missing/unexecutable) surfaces on 'error', fold it into the
// same stderr channel so the connect error still has a cause. Prevents an unhandled 'error'.
child.on('error', (e: Error) => {
+ exited = true
if (stderr.length < MASTER_STDERR_CAP) stderr += `${e.message}\n`
})
- return { kill: () => child.kill(), on: (ev, cb) => child.on(ev, cb), stderr: () => stderr }
+ // Exit is a meaningful signal both ways: with ControlPersist a SUCCESSFUL master
+ // daemonizes and exits (socket already bound), and a failed one exits with the cause on
+ // stderr. connect()'s wait loop reads it through the exited() probe.
+ child.on('exit', () => {
+ exited = true
+ })
+ return {
+ kill: () => child.kill(),
+ on: (ev, cb) => child.on(ev, cb),
+ stderr: () => stderr,
+ exited: () => exited,
+ pid: () => child.pid
+ }
+ },
+ masterEnvFor: (identityFile) => ({
+ ...(askpassScriptPath ? askpassServer.envFor(identityFile, askpassScriptPath) : {}),
+ ...appSshAgent.env()
+ }),
+ ensureAgent: () => appSshAgent.start(),
+ // The last SSH project was disconnected by the user: forget the unlocked key (after a grace,
+ // see scheduleStop — the connect dialog's throwaway browse master disconnects right before the
+ // real project connects).
+ onIdle: () => appSshAgent.scheduleStop(),
+ askpassWasCancelled: (masterPid) => askpassServer.wasCancelledBy(masterPid),
+ askpassIsPrompting: () => askpassServer.isPromptingAny(),
+ askpassAsked: (masterPid) => askpassServer.askedBy(masterPid),
+ runSync: (args) => {
+ // Quit path only (disconnectAll). Bounded hard: `before-quit` is blocked while this runs, and
+ // an unreachable host must not add seconds to every quit.
+ try {
+ execFileSync(ssh, args, { timeout: 400, stdio: 'ignore' })
+ } catch {
+ // The master may already be gone, the host unreachable, or the timeout hit. Best effort.
+ }
},
run: (args, stdin) =>
new Promise((resolve) => {
// 16 MB ceiling: remote transcript reads pull up to REMOTE_TRANSCRIPT_CAP (5 MB) via
// RemoteFile; the default 1 MB maxBuffer would kill the child and silently break the
// remote context meter / subagent transcript / content search for large transcripts.
- // (cf. pty-manager tmux capture 50 MB, git-service 20–50 MB.) Just a ceiling — safe for
+ // (cf. pty-manager tmux capture 50 MB, git-service 20–50 MB.) Just a ceiling, safe for
// the small Phase-1/2a control commands too.
- const child = execFile(ssh, args, { timeout: 15000, maxBuffer: 16 * 1024 * 1024 }, (err, stdout) =>
- resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: stdout ?? '' })
+ // The agent env rides along here too: `childArgs` uses `ControlMaster=auto`, so with the
+ // master down the first child ssh authenticates for real, and the only place the unlocked
+ // key lives is the app-private agent.
+ const child = execFile(
+ ssh,
+ args,
+ { timeout: 15000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ...appSshAgent.env() } },
+ (err, stdout) =>
+ resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: stdout ?? '' })
)
if (stdin !== undefined) {
child.stdin?.end(stdin)
@@ -1011,13 +1458,32 @@ export function initSshProject(
}),
runScp: (args) =>
new Promise((resolve) => {
- execFile(scp, args, { maxBuffer: 1024 * 1024 }, (err) => resolve({ code: err ? 1 : 0 }))
+ // Same reason as `run`: scp re-authenticates when the master socket is gone.
+ execFile(scp, args, { maxBuffer: 1024 * 1024, env: { ...process.env, ...appSshAgent.env() } }, (err) =>
+ resolve({ code: err ? 1 : 0 })
+ )
}),
getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),
onStatus: (e) => {
- if (!win.isDestroyed()) win.webContents.send(IPC.sshProjectStatus, 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
+ // silently dropped. The try/catch is the other half: webContents.send THROWS when the render
+ // frame is disposed even though isDestroyed() is false (renderer crash, reload, quit), and a
+ // status push must never be load-bearing. It used to abort connect() mid-flight, which left
+ // a dead entry in the map, discarded the real ssh error, and on the disconnectAll path
+ // orphaned every remaining master.
+ try {
+ sendToMain(IPC.sshProjectStatus, e)
+ } catch {
+ // a UI that cannot hear us changes nothing about the connection itself
+ }
}
})
+ // 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) =>
+ promptForPassphrase({ ...req, target: mgr.targetForMasterPid(req.caller) })
+ )
mgr.startWatchdog()
ipcMain.handle(IPC.sshConnectProject, async (_e, projectId: string, conn: SshConnection, remoteCwd?: string) => {
const res = await mgr.connect(projectId, conn, remoteCwd)
@@ -1026,7 +1492,12 @@ export function initSshProject(
onConnected?.(projectId)
return res
})
- ipcMain.handle(IPC.sshDisconnectProject, (_e, projectId: string) => mgr.disconnect(projectId))
+ // `final`: the only USER-facing disconnect there is (a deleted project, or the connect dialog
+ // dropping its browse master). Internal teardowns never reach here, which is what makes "no
+ // connections left" a trustworthy signal to forget the key.
+ ipcMain.handle(IPC.sshDisconnectProject, (_e, projectId: string) =>
+ mgr.disconnect(projectId, { final: true })
+ )
ipcMain.handle(IPC.sshKillSessions, (_e, projectId: string, nodeIds: string[]) =>
mgr.killSessions(projectId, nodeIds)
)
diff --git a/src/preload/index.test.ts b/src/preload/index.test.ts
new file mode 100644
index 000000000..fcd9e12b6
--- /dev/null
+++ b/src/preload/index.test.ts
@@ -0,0 +1,71 @@
+// The preload bridge's passphrase surface. This is the ONLY place the renderer-facing
+// (requestId, value) argument order and the channel names are glued to ipcRenderer, and a swap
+// or a renamed channel here was green under every other test while breaking the live dialog.
+// electron is mocked (a preload script cannot run outside Electron); the assertion target is
+// the exact invoke/on wiring the real contextBridge would expose.
+import { describe, expect, it, vi } from 'vitest'
+import { IPC } from '../shared/ipc'
+import type { NodeTerminalApi, SshPassphraseRequest } from '../shared/types'
+
+const h = vi.hoisted(() => ({
+ invoke: vi.fn(async () => undefined),
+ send: vi.fn(),
+ on: vi.fn(),
+ removeListener: vi.fn(),
+ exposed: {} as Record<string, unknown>
+}))
+
+vi.mock('electron', () => ({
+ contextBridge: {
+ exposeInMainWorld: (key: string, value: unknown) => {
+ h.exposed[key] = value
+ }
+ },
+ ipcRenderer: {
+ invoke: h.invoke,
+ send: h.send,
+ on: h.on,
+ removeListener: h.removeListener
+ },
+ webUtils: { getPathForFile: vi.fn() }
+}))
+
+// Side-effect import: runs the preload script, which exposes the api through the mock above.
+import './index'
+
+const api = h.exposed.nodeTerminal as NodeTerminalApi
+
+describe('preload sshProject passphrase wiring', () => {
+ it('submitPassphrase invokes the submit channel with (requestId, value) in that order', async () => {
+ await api.sshProject.submitPassphrase('req-1', 'hunter2')
+ expect(h.invoke).toHaveBeenCalledWith(IPC.sshPassphraseSubmit, 'req-1', 'hunter2')
+ // Cancel path: null must travel as null (main reads null as an ACTIVE decline).
+ await api.sshProject.submitPassphrase('req-2', null)
+ expect(h.invoke).toHaveBeenCalledWith(IPC.sshPassphraseSubmit, 'req-2', null)
+ })
+
+ it('onPassphraseRequest subscribes the request channel and forwards the payload', () => {
+ const got: SshPassphraseRequest[] = []
+ const off = api.sshProject.onPassphraseRequest((e) => got.push(e))
+ const call = h.on.mock.calls.find((c) => c[0] === IPC.sshPassphraseRequest)
+ expect(call).toBeTruthy()
+ const handler = call![1] as (e: unknown, payload: unknown) => void
+ const payload = { requestId: 'r9', identityFile: '/k', retry: true }
+ handler({}, payload)
+ expect(got).toEqual([payload])
+ off()
+ expect(h.removeListener).toHaveBeenCalledWith(IPC.sshPassphraseRequest, handler)
+ })
+
+ it('onPassphraseDismiss subscribes the dismiss channel and forwards the requestId', () => {
+ const got: { requestId: string }[] = []
+ const off = api.sshProject.onPassphraseDismiss((e) => got.push(e))
+ const call = h.on.mock.calls.find((c) => c[0] === IPC.sshPassphraseDismiss)
+ expect(call).toBeTruthy()
+ const handler = call![1] as (e: unknown, payload: unknown) => void
+ handler({}, { requestId: 'r7' })
+ expect(got).toEqual([{ requestId: 'r7' }])
+ off()
+ expect(h.removeListener).toHaveBeenCalledWith(IPC.sshPassphraseDismiss, handler)
+ })
+})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 831461c4e..88f44d6e7 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -177,6 +177,18 @@ const api: NodeTerminalApi = {
const h = (_e: unknown, e: unknown) => cb(e as never)
ipcRenderer.on(IPC.sshProjectStatus, h)
return () => ipcRenderer.removeListener(IPC.sshProjectStatus, h)
+ },
+ submitPassphrase: (requestId, value) =>
+ ipcRenderer.invoke(IPC.sshPassphraseSubmit, requestId, value),
+ onPassphraseRequest: (cb) => {
+ const h = (_e: unknown, e: unknown) => cb(e as never)
+ ipcRenderer.on(IPC.sshPassphraseRequest, h)
+ return () => ipcRenderer.removeListener(IPC.sshPassphraseRequest, h)
+ },
+ onPassphraseDismiss: (cb) => {
+ const h = (_e: unknown, e: unknown) => cb(e as never)
+ ipcRenderer.on(IPC.sshPassphraseDismiss, h)
+ return () => ipcRenderer.removeListener(IPC.sshPassphraseDismiss, h)
}
},
sshFs: {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index a8afa6842..5edede686 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -139,7 +139,10 @@ export function buildStubApi(): Omit<
mkdir: U('sshProject.mkdir'),
uploadFile: U('sshProject.uploadFile'),
downloadFile: U('sshProject.downloadFile'),
- onStatus: noopUnsub
+ onStatus: noopUnsub,
+ submitPassphrase: U('sshProject.submitPassphrase'),
+ onPassphraseRequest: noopUnsub,
+ onPassphraseDismiss: noopUnsub
},
sshFs: {
list: U('sshFs.list'),
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index c706b9469..5d92b3e92 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -202,6 +202,17 @@ export const IPC = {
sshFsMkdir: 'sshFs:mkdir',
sshFsExists: 'sshFs:exists',
sshProjectStatus: 'ssh-project:status',
+ /** main → renderer: an SSH project's identity file is passphrase-protected and the ssh-agent
+ * does not hold the key (or the last answer was wrong), so show a prompt.
+ * Payload: SshPassphraseRequest. */
+ sshPassphraseRequest: 'ssh-project:passphrase-request',
+ /** renderer → main: the user's answer to an sshPassphraseRequest. Args: (requestId, value),
+ * value null on cancel. */
+ sshPassphraseSubmit: 'ssh-project:passphrase-submit',
+ /** main → renderer: a passphrase request expired main-side (abandoned prompt timeout). The
+ * renderer closes the matching dialog so a late answer cannot land in a dead request.
+ * Payload: { requestId }. */
+ sshPassphraseDismiss: 'ssh-project:passphrase-dismiss',
gitStatus: 'git:status',
gitInit: 'git:init',
gitClone: 'git:clone',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index cad344e20..966f941cc 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -928,6 +928,19 @@ export interface SshProjectStatusEvent {
remoteClaudeVersion?: string | null
}
+/** main → renderer: this SSH identity file needs its passphrase (the ssh-agent doesn't hold the
+ * key, or the last answer was wrong). `retry` distinguishes "that passphrase didn't work" from
+ * a first ask. */
+export interface SshPassphraseRequest {
+ requestId: string
+ identityFile: string
+ retry: boolean
+ /** `user@host` the unlock is for, when main could attribute the prompt to a connection. One key
+ * can serve several servers, and the prompt can fire from the watchdog long after any connect
+ * dialog closed. Absent when the asking master could not be identified (adopted orphan). */
+ target?: string
+}
+
export interface SshProjectApi {
/** Open (or reuse) the ControlMaster for an SSH project; resolves once connected. */
connect(
@@ -972,6 +985,11 @@ export interface SshProjectApi {
*/
downloadFile(projectId: string, remotePath: string, destDir?: string): Promise<DownloadResult>
onStatus(cb: (e: SshProjectStatusEvent) => void): () => void
+ /** The user's answer to a passphrase prompt (null on cancel). */
+ submitPassphrase(requestId: string, value: string | null): Promise<void>
+ onPassphraseRequest(cb: (e: SshPassphraseRequest) => void): () => void
+ /** Main expired a pending passphrase request; close its dialog if it is still showing. */
+ onPassphraseDismiss(cb: (e: { requestId: string }) => void): () => void
}
/** Outcome of a file download (SSH pull). `localPath` is the absolute path actually written —