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): add a passphrase-unlocked key to the Windows ssh-agent on opt-in

enes2b3b7351737e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 074a7a97f..78b5c16fc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -70,5 +70,15 @@ jobs:
- name: Build session host
run: npm run host:build
+ # agent-add.test.ts measures the REAL Windows OpenSSH agent service (a constrained add is
+ # refused, an unconstrained one is stored). The runner ships it Disabled; the test removes
+ # every key it adds.
+ - name: Start the OpenSSH agent service
+ shell: pwsh
+ run: |
+ Set-Service ssh-agent -StartupType Manual
+ Start-Service ssh-agent
+ Get-Service ssh-agent
+
- name: Windows-relevant tests
run: npx vitest run src/core/windows-delivery-safety.test.ts src/core/settled-text.test.ts src/core/native-windows-pane.test.ts src/core/phone-approval.test.ts src/main/remote/standing-host.test.ts src/main/remote/approved-devices.test.ts src/renderer/lib/phone-approval.test.ts src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/codex-cli.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/core/remote-ssh/native/ src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsx scripts/windows-update-preflight.test.ts
diff --git a/src/core/remote-ssh/native/agent-add.test.ts b/src/core/remote-ssh/native/agent-add.test.ts
new file mode 100644
index 000000000..96e893bcd
--- /dev/null
+++ b/src/core/remote-ssh/native/agent-add.test.ts
@@ -0,0 +1,362 @@
+// The add-identity encoder against a fake agent that DECODES the message and rebuilds the private
+// key from it (a sign/verify round trip, so a field in the wrong order or an mpint with a lost sign
+// byte fails), plus the reply handling, and — where the platform has one — a real OpenSSH agent.
+
+import { describe, it, expect, afterEach } from 'vitest'
+import net from 'net'
+import os from 'os'
+import path from 'path'
+import fs from 'fs'
+import crypto from 'crypto'
+import { spawn, type ChildProcess } from 'child_process'
+import { utils, createAgent, type ParsedKey } from 'ssh2'
+import {
+ addKeyToAgent,
+ addIdentityRequest,
+ removeIdentityRequest,
+ sendAgentRequest,
+ sshMpint,
+ parseAddKeysToAgent,
+ decideAgentAdd,
+ SSH2_AGENTC_ADD_IDENTITY,
+ SSH2_AGENTC_ADD_ID_CONSTRAINED,
+ SSH_AGENT_CONSTRAIN_LIFETIME,
+ SSH_AGENT_FAILURE,
+ SSH_AGENT_SUCCESS
+} from './agent-add'
+import { findExecutableSync } from '../../exec-path'
+
+function parsed(k: string, pass?: string): ParsedKey {
+ const p = utils.parseKey(k, pass)
+ const one = Array.isArray(p) ? p[0] : p
+ if (one instanceof Error) throw one
+ return one
+}
+
+const PASS = 'pw'
+const KEYS: Record<string, ParsedKey> = {
+ ed25519: parsed(utils.generateKeyPairSync('ed25519', { passphrase: PASS, cipher: 'aes256-ctr', rounds: 4 }).private, PASS),
+ ecdsa256: parsed(utils.generateKeyPairSync('ecdsa', { bits: 256, passphrase: PASS, cipher: 'aes256-ctr', rounds: 4 }).private, PASS),
+ ecdsa384: parsed(utils.generateKeyPairSync('ecdsa', { bits: 384 }).private),
+ ecdsa521: parsed(utils.generateKeyPairSync('ecdsa', { bits: 521 }).private),
+ rsa: parsed(utils.generateKeyPairSync('rsa', { bits: 2048, passphrase: PASS, cipher: 'aes256-ctr', rounds: 4 }).private, PASS)
+}
+
+/** A cursor over an SSH-encoded buffer. */
+function reader(b: Buffer) {
+ let o = 0
+ return {
+ byte: () => b[o++],
+ u32: () => {
+ const v = b.readUInt32BE(o)
+ o += 4
+ return v
+ },
+ str(): Buffer {
+ const n = this.u32()
+ const s = b.subarray(o, o + n)
+ o += n
+ return s
+ },
+ rest: () => b.subarray(o)
+ }
+}
+
+/** mpint → unsigned magnitude, asserting the encoding is canonical (minimal, non-negative). */
+function mp(s: Buffer): Buffer {
+ if (s.length === 0) return s
+ expect(s[0] & 0x80).toBe(0)
+ if (s[0] === 0) expect(s[1] & 0x80).not.toBe(0)
+ return s[0] === 0 ? s.subarray(1) : s
+}
+
+const u = (b: Buffer): string => b.toString('base64url')
+
+/** Rebuild a node private key from a decoded add-identity body and prove it signs as `key`. */
+function decodeAndCheck(body: Buffer, key: ParsedKey): { type: number; comment: string; constraints: Buffer } {
+ const r = reader(body)
+ const type = r.byte()
+ const keyType = r.str().toString()
+ expect(keyType).toBe(key.type)
+ let jwk: crypto.webcrypto.JsonWebKey
+ if (keyType === 'ssh-ed25519') {
+ const a = r.str()
+ const ka = r.str()
+ expect(a.length).toBe(32)
+ expect(ka.length).toBe(64)
+ expect(ka.subarray(32).equals(a)).toBe(true)
+ jwk = { kty: 'OKP', crv: 'Ed25519', x: u(a), d: u(ka.subarray(0, 32)) }
+ } else if (keyType.startsWith('ecdsa-')) {
+ const curve = r.str().toString()
+ expect(keyType).toBe(`ecdsa-sha2-${curve}`)
+ const q = r.str()
+ expect(q[0]).toBe(4)
+ const w = (q.length - 1) / 2
+ const d = mp(r.str())
+ const crv = { nistp256: 'P-256', nistp384: 'P-384', nistp521: 'P-521' }[curve] as string
+ jwk = { kty: 'EC', crv, x: u(q.subarray(1, 1 + w)), y: u(q.subarray(1 + w)), d: u(Buffer.concat([Buffer.alloc(w - d.length), d])) }
+ } else {
+ const [n, e, d, iqmp, p, q] = [r.str(), r.str(), r.str(), r.str(), r.str(), r.str()].map(mp)
+ const bn = (b: Buffer): bigint => BigInt('0x' + (b.toString('hex') || '0'))
+ const hex = (v: bigint): Buffer => {
+ const h = v.toString(16)
+ return Buffer.from(h.length % 2 ? '0' + h : h, 'hex')
+ }
+ // iqmp must be q^-1 mod p (OpenSSH's definition), i.e. q * iqmp ≡ 1 (mod p).
+ expect((bn(q) * bn(iqmp)) % bn(p)).toBe(1n)
+ jwk = {
+ kty: 'RSA', n: u(n), e: u(e), d: u(d), p: u(p), q: u(q), qi: u(iqmp),
+ dp: u(hex(bn(d) % (bn(p) - 1n))), dq: u(hex(bn(d) % (bn(q) - 1n)))
+ }
+ }
+ const priv = crypto.createPrivateKey({ key: jwk, format: 'jwk' })
+ const data = Buffer.from('nodeterm agent add round trip')
+ const algo = keyType === 'ssh-ed25519' ? null : 'sha256'
+ const sig = crypto.sign(algo, data, priv)
+ expect(crypto.verify(algo, data, crypto.createPublicKey(key.getPublicPEM()), sig)).toBe(true)
+ const comment = r.str().toString()
+ return { type, comment, constraints: r.rest() }
+}
+
+function unframe(req: Buffer): Buffer {
+ const len = req.readUInt32BE(0)
+ expect(req.length).toBe(4 + len)
+ return req.subarray(4)
+}
+
+describe('sshMpint', () => {
+ it('encodes minimally and keeps the value non-negative', () => {
+ expect(sshMpint(Buffer.from([])).equals(Buffer.from([0, 0, 0, 0]))).toBe(true)
+ expect(sshMpint(Buffer.from([0, 0])).equals(Buffer.from([0, 0, 0, 0]))).toBe(true)
+ expect(sshMpint(Buffer.from([0x7f])).equals(Buffer.from([0, 0, 0, 1, 0x7f]))).toBe(true)
+ expect(sshMpint(Buffer.from([0x80])).equals(Buffer.from([0, 0, 0, 2, 0, 0x80]))).toBe(true)
+ expect(sshMpint(Buffer.from([0, 0, 0x81, 1])).equals(Buffer.from([0, 0, 0, 3, 0, 0x81, 1]))).toBe(true)
+ })
+})
+
+describe('parseAddKeysToAgent (ssh -G spellings, measured on Windows 9.5p2 and macOS 10.3p1)', () => {
+ it('reads true, a lifetime in seconds, and treats everything else as no', () => {
+ expect(parseAddKeysToAgent('true')).toEqual({ add: true })
+ expect(parseAddKeysToAgent('yes')).toEqual({ add: true })
+ expect(parseAddKeysToAgent('3600')).toEqual({ add: true, lifetimeSec: 3600 })
+ for (const v of ['false', 'no', 'ask', 'confirm', 'confirm 1800', '0', '-5', '1h', '', undefined, 'TRUEISH']) {
+ expect(parseAddKeysToAgent(v)).toEqual({ add: false })
+ }
+ })
+})
+
+describe('decideAgentAdd', () => {
+ const WIN = '\\\\.\\pipe\\openssh-ssh-agent'
+ it('adds nothing by default — the Windows agent keeps keys until removed', () => {
+ expect(decideAgentAdd({ agentPath: WIN, addKeysToAgent: 'false', windowsAgentOptIn: false })).toBeNull()
+ expect(decideAgentAdd({ agentPath: WIN, addKeysToAgent: undefined, windowsAgentOptIn: false })).toBeNull()
+ })
+ it('the machine opt-in applies to the Windows agent pipe only', () => {
+ expect(decideAgentAdd({ agentPath: WIN, addKeysToAgent: 'false', windowsAgentOptIn: true })).toEqual({})
+ expect(decideAgentAdd({ agentPath: WIN.toUpperCase(), addKeysToAgent: 'false', windowsAgentOptIn: true })).toEqual({})
+ expect(decideAgentAdd({ agentPath: '\\\\.\\pipe\\pageant.x', addKeysToAgent: 'false', windowsAgentOptIn: true })).toBeNull()
+ expect(decideAgentAdd({ agentPath: '/tmp/agent.sock', addKeysToAgent: 'false', windowsAgentOptIn: true })).toBeNull()
+ })
+ it("the host's own AddKeysToAgent is honoured on any agent, a lifetime kept as a constraint", () => {
+ expect(decideAgentAdd({ agentPath: WIN, addKeysToAgent: 'true', windowsAgentOptIn: false })).toEqual({})
+ expect(decideAgentAdd({ agentPath: '/tmp/agent.sock', addKeysToAgent: 'true', windowsAgentOptIn: false })).toEqual({})
+ // A lifetime wins over the opt-in's unconstrained add: Windows refuses it and stores NOTHING.
+ expect(decideAgentAdd({ agentPath: WIN, addKeysToAgent: '600', windowsAgentOptIn: true })).toEqual({ lifetimeSec: 600 })
+ })
+})
+
+describe('addIdentityRequest', () => {
+ for (const [name, key] of Object.entries(KEYS)) {
+ it(`${name}: an unconstrained add carries a key that signs as the original`, () => {
+ const req = addIdentityRequest(key, `C:\\Users\\me\\.ssh\\id_${name}`)
+ expect(req).not.toBeNull()
+ const m = decodeAndCheck(unframe(req as Buffer), key)
+ expect(m.type).toBe(SSH2_AGENTC_ADD_IDENTITY)
+ expect(m.comment).toBe(`C:\\Users\\me\\.ssh\\id_${name}`)
+ expect(m.constraints.length).toBe(0)
+ })
+ }
+
+ it('a lifetime makes it ADD_ID_CONSTRAINED with one lifetime constraint', () => {
+ const m = decodeAndCheck(unframe(addIdentityRequest(KEYS.ed25519, 'k', { lifetimeSec: 3600 }) as Buffer), KEYS.ed25519)
+ expect(m.type).toBe(SSH2_AGENTC_ADD_ID_CONSTRAINED)
+ expect(m.constraints.equals(Buffer.from([SSH_AGENT_CONSTRAIN_LIFETIME, 0, 0, 0x0e, 0x10]))).toBe(true)
+ })
+
+ it('refuses a nonsense lifetime instead of sending an unbounded add', () => {
+ for (const lifetimeSec of [0, -1, 1.5, NaN]) expect(addIdentityRequest(KEYS.ed25519, 'k', { lifetimeSec })).toBeNull()
+ })
+
+ it('refuses a key type it does not encode', () => {
+ const odd = { ...KEYS.rsa, type: 'ssh-dss', getPrivatePEM: () => KEYS.rsa.getPrivatePEM() } as unknown as ParsedKey
+ expect(addIdentityRequest(odd, 'k')).toBeNull()
+ const broken = { type: 'ssh-ed25519', getPrivatePEM: () => 'not a pem' } as unknown as ParsedKey
+ expect(addIdentityRequest(broken, 'k')).toBeNull()
+ })
+})
+
+describe('addKeyToAgent against a fake agent', () => {
+ let server: net.Server | null = null
+ let sockPath = ''
+ const tmps: string[] = []
+ afterEach(async () => {
+ await new Promise<void>((r) => (server ? server.close(() => r()) : r()))
+ server = null
+ for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true })
+ })
+
+ async function fakeAgent(reply: (req: Buffer, sock: net.Socket) => void): Promise<string> {
+ if (process.platform === 'win32') {
+ sockPath = `\\\\.\\pipe\\nodeterm-agent-add-test-${crypto.randomUUID()}`
+ } else {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-aa-'))
+ tmps.push(tmp)
+ sockPath = path.join(tmp, 's')
+ }
+ server = net.createServer((sock) => {
+ let buf = Buffer.alloc(0)
+ sock.on('data', (d: Buffer) => {
+ buf = Buffer.concat([buf, d])
+ if (buf.length >= 4 && buf.length >= 4 + buf.readUInt32BE(0)) reply(buf, sock)
+ })
+ sock.on('error', () => {})
+ })
+ await new Promise<void>((r) => server?.listen(sockPath, () => r()))
+ return sockPath
+ }
+
+ const answer = (type: number) => (_req: Buffer, sock: net.Socket) => sock.write(Buffer.from([0, 0, 0, 1, type]))
+
+ it('reports SUCCESS as added, and the agent received the whole key', async () => {
+ let got: Buffer | null = null
+ const p = await fakeAgent((req, sock) => {
+ got = req
+ answer(SSH_AGENT_SUCCESS)(req, sock)
+ })
+ expect(await addKeyToAgent(p, KEYS.rsa, 'id_rsa')).toBe('added')
+ expect(decodeAndCheck(unframe(got as unknown as Buffer), KEYS.rsa).comment).toBe('id_rsa')
+ })
+
+ it('reports FAILURE as refused', async () => {
+ const p = await fakeAgent(answer(SSH_AGENT_FAILURE))
+ expect(await addKeyToAgent(p, KEYS.ed25519, 'k', { lifetimeSec: 60 })).toBe('refused')
+ })
+
+ it('an agent that hangs up, stays silent or answers garbage is an error, never a throw', async () => {
+ let p = await fakeAgent((_r, sock) => sock.destroy())
+ expect(await addKeyToAgent(p, KEYS.ed25519, 'k')).toBe('error')
+ await new Promise<void>((r) => server?.close(() => r()))
+ p = await fakeAgent(() => {})
+ expect(await addKeyToAgent(p, KEYS.ed25519, 'k', { timeoutMs: 150 })).toBe('error')
+ await new Promise<void>((r) => server?.close(() => r()))
+ p = await fakeAgent((_r, sock) => sock.write(Buffer.from([0xff, 0xff, 0xff, 0xff, 6])))
+ expect(await addKeyToAgent(p, KEYS.ed25519, 'k')).toBe('error')
+ })
+
+ it('no agent at the path is an error', async () => {
+ const missing = process.platform === 'win32' ? `\\\\.\\pipe\\nodeterm-missing-${crypto.randomUUID()}` : path.join(os.tmpdir(), `nt-missing-${crypto.randomUUID()}`)
+ expect(await addKeyToAgent(missing, KEYS.ed25519, 'k')).toBe('error')
+ })
+
+ it('an unsupported key never touches the agent', async () => {
+ let calls = 0
+ const p = await fakeAgent((req, sock) => {
+ calls++
+ answer(SSH_AGENT_SUCCESS)(req, sock)
+ })
+ const odd = { type: 'ssh-dss', getPrivatePEM: () => '' } as unknown as ParsedKey
+ expect(await addKeyToAgent(p, odd, 'k')).toBe('unsupported-key')
+ expect(calls).toBe(0)
+ })
+})
+
+// A REAL agent: OpenSSH's own ssh-agent where the platform ships one (macOS, Linux). Proves the
+// agent accepts every encoded type, honours the lifetime, and can SIGN with what it received.
+const sshAgentBin = process.platform === 'win32' ? null : findExecutableSync('ssh-agent', ['/usr/bin/ssh-agent'])
+
+describe.skipIf(!sshAgentBin)('addKeyToAgent against OpenSSH ssh-agent', () => {
+ let child: ChildProcess | null = null
+ let tmp = ''
+ afterEach(() => {
+ child?.kill()
+ child = null
+ if (tmp) fs.rmSync(tmp, { recursive: true, force: true })
+ })
+
+ async function startAgent(): Promise<string | null> {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-ag-'))
+ const sock = path.join(tmp, 'a')
+ if (Buffer.byteLength(sock) > 100) return null // sun_path; the sandbox dir may be deep
+ child = spawn(sshAgentBin as string, ['-D', '-a', sock], { stdio: 'ignore' })
+ for (let i = 0; i < 50 && !fs.existsSync(sock); i++) await new Promise((r) => setTimeout(r, 50))
+ return fs.existsSync(sock) ? sock : null
+ }
+
+ const identities = (sock: string): Promise<string[]> =>
+ new Promise((res, rej) =>
+ createAgent(sock).getIdentities((e, ks) => (e ? rej(e) : res((ks ?? []).map((k) => (k as ParsedKey).comment))))
+ )
+
+ it('adds every key type, signs with it, and drops a constrained key at its lifetime', async (ctx) => {
+ const sock = await startAgent()
+ if (!sock) return ctx.skip()
+ for (const [name, key] of Object.entries(KEYS)) expect(await addKeyToAgent(sock, key, name)).toBe('added')
+ expect((await identities(sock)).sort()).toEqual(Object.keys(KEYS).sort())
+ // Sign through the agent with a key it only knows from our message.
+ const sig = await new Promise<Buffer>((res, rej) =>
+ createAgent(sock).sign(KEYS.ed25519, Buffer.from('x'), {}, (e, s) => (e ? rej(e) : res(s as Buffer)))
+ )
+ expect(KEYS.ed25519.verify(Buffer.from('x'), sig)).toBe(true)
+ const rsaSig = await new Promise<Buffer>((res, rej) =>
+ createAgent(sock).sign(KEYS.rsa, Buffer.from('x'), { hash: 'sha256' }, (e, s) => (e ? rej(e) : res(s as Buffer)))
+ )
+ expect(KEYS.rsa.verify(Buffer.from('x'), rsaSig, 'sha256')).toBe(true)
+ for (const key of Object.values(KEYS)) expect(await sendAgentRequest(sock, removeIdentityRequest(key))).toBe('added')
+ expect(await identities(sock)).toEqual([])
+ expect(await addKeyToAgent(sock, KEYS.rsa, 'short', { lifetimeSec: 1 })).toBe('added')
+ expect(await identities(sock)).toEqual(['short'])
+ await new Promise((r) => setTimeout(r, 2200))
+ expect(await identities(sock)).toEqual([])
+ }, 15_000)
+})
+
+// The REAL Windows OpenSSH agent service. Runs on the windows-latest CI leg, which starts the
+// service first (ci.yml); skipped where the pipe does not exist. Pins the measurement the policy
+// rests on: a constrained add is REFUSED, an unconstrained one is stored and signs.
+const WINDOWS_PIPE = '\\\\.\\pipe\\openssh-ssh-agent'
+const windowsAgentUp = process.platform === 'win32' && (() => {
+ try {
+ return fs.existsSync(WINDOWS_PIPE)
+ } catch {
+ return false
+ }
+})()
+
+describe.skipIf(!windowsAgentUp)('addKeyToAgent against the Windows OpenSSH agent service', () => {
+ afterEach(async () => {
+ for (const key of Object.values(KEYS)) await sendAgentRequest(WINDOWS_PIPE, removeIdentityRequest(key))
+ })
+
+ const comments = (): Promise<string[]> =>
+ new Promise((res, rej) =>
+ createAgent(WINDOWS_PIPE).getIdentities((e, ks) => (e ? rej(e) : res((ks ?? []).map((k) => (k as ParsedKey).comment))))
+ )
+
+ it('refuses a lifetime constraint for every key type, and stores nothing', async () => {
+ for (const [name, key] of Object.entries(KEYS)) {
+ expect(await addKeyToAgent(WINDOWS_PIPE, key, `nt-test-${name}`, { lifetimeSec: 60 })).toBe('refused')
+ }
+ expect((await comments()).filter((c) => c.startsWith('nt-test-'))).toEqual([])
+ })
+
+ it('stores an unconstrained key of every type, signs with it, and removes it', async () => {
+ for (const [name, key] of Object.entries(KEYS)) expect(await addKeyToAgent(WINDOWS_PIPE, key, `nt-test-${name}`)).toBe('added')
+ expect((await comments()).filter((c) => c.startsWith('nt-test-')).sort()).toEqual(Object.keys(KEYS).map((n) => `nt-test-${n}`).sort())
+ const sig = await new Promise<Buffer>((res, rej) =>
+ createAgent(WINDOWS_PIPE).sign(KEYS.rsa, Buffer.from('x'), { hash: 'sha256' }, (e, s) => (e ? rej(e) : res(s as Buffer)))
+ )
+ expect(KEYS.rsa.verify(Buffer.from('x'), sig, 'sha256')).toBe(true)
+ for (const key of Object.values(KEYS)) expect(await sendAgentRequest(WINDOWS_PIPE, removeIdentityRequest(key))).toBe('added')
+ expect((await comments()).filter((c) => c.startsWith('nt-test-'))).toEqual([])
+ }, 20_000)
+})
diff --git a/src/core/remote-ssh/native/agent-add.ts b/src/core/remote-ssh/native/agent-add.ts
new file mode 100644
index 000000000..6a9f259dd
--- /dev/null
+++ b/src/core/remote-ssh/native/agent-add.ts
@@ -0,0 +1,253 @@
+// Load a passphrase-unlocked key into an ssh-agent — the native transport's `AddKeysToAgent`.
+//
+// ssh2's AgentProtocol only lists and signs; adding a key is SSH2_AGENTC_ADD_IDENTITY (17) or
+// SSH2_AGENTC_ADD_ID_CONSTRAINED (25) from the agent protocol (draft-miller-ssh-agent), with the
+// PRIVATE key in OpenSSH wire format. We write that one message ourselves.
+//
+// Wire format of the key (draft-miller-ssh-agent §3.2.x), each field an SSH `string`/`mpint`:
+// ssh-ed25519 string type, string ENC(A) (32 B), string k || ENC(A) (64 B)
+// ecdsa-sha2-nistpNNN string type, string curve ("nistpNNN"), string Q (0x04||x||y), mpint d
+// ssh-rsa string type, mpint n, mpint e, mpint d, mpint iqmp, mpint p, mpint q
+// then `string comment`, then (message 25 only) constraints: byte 1 + uint32 seconds = lifetime.
+// The components come from node's own JWK export of the key ssh2 already parsed — JWK `qi` is
+// q^-1 mod p, which is exactly OpenSSH's iqmp.
+//
+// FAIL-OPEN by construction: `addKeyToAgent` never throws and never waits longer than its timeout.
+// The connection that unlocked the key is already authenticated; the agent is a convenience for the
+// NEXT one, so nothing it answers (or fails to answer) may reach the connection.
+
+import net from 'net'
+import crypto from 'crypto'
+import type { ParsedKey } from 'ssh2'
+
+export const SSH2_AGENTC_ADD_IDENTITY = 17
+export const SSH2_AGENTC_ADD_ID_CONSTRAINED = 25
+export const SSH2_AGENTC_REMOVE_IDENTITY = 18
+export const SSH_AGENT_CONSTRAIN_LIFETIME = 1
+export const SSH_AGENT_SUCCESS = 6
+export const SSH_AGENT_FAILURE = 5
+
+/** An agent reply we cannot wait for longer than this; the connection never waits on it anyway. */
+export const AGENT_ADD_TIMEOUT_MS = 3_000
+
+function u32(n: number): Buffer {
+ const b = Buffer.alloc(4)
+ b.writeUInt32BE(n >>> 0)
+ return b
+}
+
+function sshString(b: Buffer | string): Buffer {
+ const buf = typeof b === 'string' ? Buffer.from(b, 'utf8') : b
+ return Buffer.concat([u32(buf.length), buf])
+}
+
+/** SSH mpint of a non-negative big-endian magnitude: leading zeros stripped, 0x00 prefixed when
+ * the high bit is set (it would otherwise read as negative), zero as the empty string. */
+export function sshMpint(magnitude: Buffer): Buffer {
+ let i = 0
+ while (i < magnitude.length && magnitude[i] === 0) i++
+ let m = magnitude.subarray(i)
+ if (m.length && m[0] & 0x80) m = Buffer.concat([Buffer.from([0]), m])
+ return sshString(m)
+}
+
+const b64u = (s: string | undefined): Buffer => {
+ if (!s) throw new Error('key component missing')
+ return Buffer.from(s, 'base64url')
+}
+
+const CURVES: Record<string, { name: string; jwk: string }> = {
+ 'ecdsa-sha2-nistp256': { name: 'nistp256', jwk: 'P-256' },
+ 'ecdsa-sha2-nistp384': { name: 'nistp384', jwk: 'P-384' },
+ 'ecdsa-sha2-nistp521': { name: 'nistp521', jwk: 'P-521' }
+}
+
+/** Coordinate/scalar to the curve's full byte width (JWK already pads, but be exact). */
+function pad(b: Buffer, len: number): Buffer {
+ return b.length >= len ? b : Buffer.concat([Buffer.alloc(len - b.length), b])
+}
+
+/**
+ * The private-key body of an add-identity message (type through the last key field, no comment),
+ * or null for a key type we do not encode (DSA, security keys, certificates).
+ */
+export function agentKeyBlob(key: ParsedKey): Buffer | null {
+ let jwk: crypto.webcrypto.JsonWebKey
+ try {
+ jwk = crypto.createPrivateKey(key.getPrivatePEM()).export({ format: 'jwk' })
+ } catch {
+ return null
+ }
+ try {
+ if (key.type === 'ssh-ed25519') {
+ if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') return null
+ const a = b64u(jwk.x)
+ const k = b64u(jwk.d)
+ if (a.length !== 32 || k.length !== 32) return null
+ return Buffer.concat([sshString('ssh-ed25519'), sshString(a), sshString(Buffer.concat([k, a]))])
+ }
+ const curve = CURVES[key.type]
+ if (curve) {
+ if (jwk.kty !== 'EC' || jwk.crv !== curve.jwk) return null
+ const width = curve.jwk === 'P-521' ? 66 : curve.jwk === 'P-384' ? 48 : 32
+ const q = Buffer.concat([Buffer.from([4]), pad(b64u(jwk.x), width), pad(b64u(jwk.y), width)])
+ return Buffer.concat([sshString(key.type), sshString(curve.name), sshString(q), sshMpint(b64u(jwk.d))])
+ }
+ if (key.type === 'ssh-rsa') {
+ if (jwk.kty !== 'RSA') return null
+ return Buffer.concat([
+ sshString('ssh-rsa'),
+ sshMpint(b64u(jwk.n)),
+ sshMpint(b64u(jwk.e)),
+ sshMpint(b64u(jwk.d)),
+ sshMpint(b64u(jwk.qi)),
+ sshMpint(b64u(jwk.p)),
+ sshMpint(b64u(jwk.q))
+ ])
+ }
+ } catch {
+ return null
+ }
+ return null
+}
+
+/** One framed add-identity request (uint32 length + body), constrained when `lifetimeSec` is set. */
+export function addIdentityRequest(key: ParsedKey, comment: string, opts: { lifetimeSec?: number } = {}): Buffer | null {
+ const blob = agentKeyBlob(key)
+ if (!blob) return null
+ const constrained = opts.lifetimeSec !== undefined
+ if (constrained && !(Number.isInteger(opts.lifetimeSec) && (opts.lifetimeSec as number) > 0)) return null
+ const body = Buffer.concat([
+ Buffer.from([constrained ? SSH2_AGENTC_ADD_ID_CONSTRAINED : SSH2_AGENTC_ADD_IDENTITY]),
+ blob,
+ sshString(comment),
+ constrained ? Buffer.concat([Buffer.from([SSH_AGENT_CONSTRAIN_LIFETIME]), u32(opts.lifetimeSec as number)]) : Buffer.alloc(0)
+ ])
+ return Buffer.concat([u32(body.length), body])
+}
+
+/** A framed remove-identity request for the key's public blob (used by the tests to clean up). */
+export function removeIdentityRequest(key: ParsedKey): Buffer {
+ const body = Buffer.concat([Buffer.from([SSH2_AGENTC_REMOVE_IDENTITY]), sshString(key.getPublicSSH())])
+ return Buffer.concat([u32(body.length), body])
+}
+
+export type AgentAddResult = 'added' | 'refused' | 'unsupported-key' | 'error'
+
+/**
+ * Send one request to the agent at `agentPath` (a unix socket or a Windows named pipe) and read
+ * its one-byte verdict. Never throws: every failure is 'error', a FAILURE reply is 'refused'.
+ */
+export function sendAgentRequest(
+ agentPath: string,
+ request: Buffer,
+ opts: { timeoutMs?: number; connect?: (p: string) => net.Socket } = {}
+): Promise<Exclude<AgentAddResult, 'unsupported-key'>> {
+ return new Promise((resolve) => {
+ let done = false
+ let sock: net.Socket | null = null
+ const finish = (r: Exclude<AgentAddResult, 'unsupported-key'>): void => {
+ if (done) return
+ done = true
+ clearTimeout(timer)
+ try {
+ sock?.destroy()
+ } catch {
+ /* ignore */
+ }
+ resolve(r)
+ }
+ const timer = setTimeout(() => finish('error'), opts.timeoutMs ?? AGENT_ADD_TIMEOUT_MS)
+ try {
+ sock = (opts.connect ?? ((p: string) => net.connect(p)))(agentPath)
+ } catch {
+ return finish('error')
+ }
+ let buf = Buffer.alloc(0)
+ sock.on('error', () => finish('error'))
+ sock.on('close', () => finish('error'))
+ sock.on('data', (d: Buffer) => {
+ buf = Buffer.concat([buf, d])
+ if (buf.length < 5) return
+ const len = buf.readUInt32BE(0)
+ if (len < 1 || len > 256 * 1024) return finish('error')
+ if (buf.length < 4 + len) return
+ const type = buf[4]
+ finish(type === SSH_AGENT_SUCCESS ? 'added' : type === SSH_AGENT_FAILURE ? 'refused' : 'error')
+ })
+ sock.on('connect', () => {
+ try {
+ sock?.write(request)
+ } catch {
+ finish('error')
+ }
+ })
+ })
+}
+
+/** Add `key` to the agent at `agentPath`. Never throws. */
+export async function addKeyToAgent(
+ agentPath: string,
+ key: ParsedKey,
+ comment: string,
+ opts: { lifetimeSec?: number; timeoutMs?: number; connect?: (p: string) => net.Socket } = {}
+): Promise<AgentAddResult> {
+ let req: Buffer | null
+ try {
+ req = addIdentityRequest(key, comment, { lifetimeSec: opts.lifetimeSec })
+ } catch {
+ req = null
+ }
+ if (!req) return 'unsupported-key'
+ return sendAgentRequest(agentPath, req, opts)
+}
+
+/** What the user's own config asks for: `AddKeysToAgent` as `ssh -G` prints it. */
+export type AddKeysRequest = { add: false } | { add: true; lifetimeSec?: number }
+
+/**
+ * `ssh -G`'s `addkeystoagent` value → what to do. `true`/`yes` add, a positive number of seconds
+ * adds with that lifetime. `ask` and `confirm` are NOT honoured (ask needs a second prompt, confirm
+ * a per-use confirmation this app cannot show) and read as "no"; so does anything unrecognised —
+ * a spelling we do not know must never widen what lands in an agent.
+ */
+export function parseAddKeysToAgent(v: string | undefined): AddKeysRequest {
+ const s = (v ?? '').trim().toLowerCase()
+ if (s === 'true' || s === 'yes') return { add: true }
+ if (/^\d+$/.test(s)) {
+ const n = Number(s)
+ return n > 0 && Number.isSafeInteger(n) ? { add: true, lifetimeSec: n } : { add: false }
+ }
+ return { add: false }
+}
+
+/** The Windows OpenSSH agent service's pipe (duplicated from native-mux to keep this a leaf). */
+const WINDOWS_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent'
+
+/**
+ * Whether to load a freshly unlocked key into `agentPath`, and with what lifetime. null = do not.
+ *
+ * MEASURED on windows-latest (OpenSSH_for_Windows_9.5p2, 2026-09-30): the Windows agent service
+ * REFUSES every constrained add (`ssh-add -t 5` and `ssh-add -c` both "agent refused operation",
+ * and our own ADD_ID_CONSTRAINED gets SSH_AGENT_FAILURE), and an unconstrained add is STORED —
+ * DPAPI-encrypted under HKCU\Software\OpenSSH\Agent\Keys — and is still listed after
+ * `Restart-Service ssh-agent` and a stop/start. So on that agent an add means "until the user
+ * removes it", and the app does that only when the user asked:
+ * - their own ssh config says `AddKeysToAgent yes` for the host (what Windows' ssh.exe would do
+ * for them), or a lifetime (sent constrained; Windows refuses it and nothing is stored — never
+ * retried without the constraint);
+ * - or the machine-wide opt-in (`settings.windowsSshAgentAddKeys`), for the Windows pipe only,
+ * whose Settings copy says the key is kept until removed.
+ * Any OTHER agent (a configured IdentityAgent, or POSIX under NODETERM_NATIVE_SSH=1) follows the
+ * host config alone, exactly as OpenSSH's AddKeysToAgent would.
+ */
+export function decideAgentAdd(req: {
+ agentPath: string
+ addKeysToAgent: string | undefined
+ windowsAgentOptIn: boolean
+}): { lifetimeSec?: number } | null {
+ const cfg = parseAddKeysToAgent(req.addKeysToAgent)
+ if (cfg.add) return cfg.lifetimeSec !== undefined ? { lifetimeSec: cfg.lifetimeSec } : {}
+ if (req.windowsAgentOptIn && req.agentPath.toLowerCase() === WINDOWS_AGENT_PIPE) return {}
+ return null
+}
diff --git a/src/core/remote-ssh/native/native-mux.test.ts b/src/core/remote-ssh/native/native-mux.test.ts
index 6505c191b..f9c3e306c 100644
--- a/src/core/remote-ssh/native/native-mux.test.ts
+++ b/src/core/remote-ssh/native/native-mux.test.ts
@@ -230,6 +230,92 @@ describe('NativeMux over a real SSH protocol peer', () => {
}
})
+ it('offers a freshly unlocked key to the agent AFTER it authenticated — once, fail-open', async () => {
+ fs.rmSync(path.join(dir, 'known_hosts'), { force: true })
+ fs.writeFileSync(path.join(dir, 'id'), lockedKey.private)
+ try {
+ const asked: { agentPath: string; identityFile: string }[] = []
+ const added: { agentPath: string; type: string; comment: string; lifetimeSec?: number }[] = []
+ // IdentitiesOnly with no id.pub: the agent step is skipped (nothing to filter to), so the
+ // key file is what authenticates — the case the add exists for.
+ const m = track(
+ mux({
+ defaultAgent: () => '/fake/agent.sock',
+ askPassphrase: async () => 'open sesame',
+ agentAdd: (req) => {
+ asked.push({ agentPath: req.agentPath, identityFile: req.identityFile })
+ return { lifetimeSec: 600 }
+ },
+ addKeyToAgent: async (agentPath, key, comment, opts) => {
+ added.push({ agentPath, type: key.type, comment, lifetimeSec: opts?.lifetimeSec })
+ return 'added'
+ }
+ })
+ )
+ expect((await m.exec(exec('echo one'))).code).toBe(0)
+ expect((await m.exec(exec('echo two'))).code).toBe(0)
+ await new Promise((r) => setTimeout(r, 20))
+ expect(asked).toEqual([{ agentPath: '/fake/agent.sock', identityFile: path.join(dir, 'id') }])
+ expect(added).toEqual([{ agentPath: '/fake/agent.sock', type: 'ssh-ed25519', comment: path.join(dir, 'id'), lifetimeSec: 600 }])
+
+ // A policy that says no adds nothing; an agent that throws costs the connection nothing.
+ const noAdd = track(
+ mux({
+ defaultAgent: () => '/fake/agent.sock',
+ askPassphrase: async () => 'open sesame',
+ agentAdd: () => null,
+ addKeyToAgent: async () => {
+ throw new Error('must not be called')
+ }
+ })
+ )
+ expect((await noAdd.exec(exec('echo three'))).code).toBe(0)
+ const logs: string[] = []
+ const broken = track(
+ mux({
+ defaultAgent: () => '/fake/agent.sock',
+ askPassphrase: async () => 'open sesame',
+ log: (l) => logs.push(l),
+ agentAdd: () => {
+ throw new Error('policy exploded')
+ }
+ })
+ )
+ expect((await broken.exec(exec('echo four'))).code).toBe(0)
+ const failing = track(
+ mux({
+ defaultAgent: () => '/fake/agent.sock',
+ askPassphrase: async () => 'open sesame',
+ log: (l) => logs.push(l),
+ agentAdd: () => ({}),
+ addKeyToAgent: async () => {
+ throw new Error('agent exploded')
+ }
+ })
+ )
+ expect((await failing.exec(exec('echo five'))).code).toBe(0)
+ await new Promise((r) => setTimeout(r, 20))
+ expect(logs.some((l) => /could not add .* to the ssh agent \(error\)/.test(l))).toBe(true)
+ } finally {
+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)
+ }
+ })
+
+ it('never offers a key that needed no passphrase', async () => {
+ let consulted = 0
+ const m = track(
+ mux({
+ defaultAgent: () => '/fake/agent.sock',
+ agentAdd: () => {
+ consulted++
+ return {}
+ }
+ })
+ )
+ expect((await m.exec(exec('echo plain'))).code).toBe(0)
+ expect(consulted).toBe(0)
+ })
+
it('forward on a path with no connection fails the way ssh does', async () => {
const m = track(mux())
await expect(
diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.ts
index f377b7b46..da44745be 100644
--- a/src/core/remote-ssh/native/native-mux.ts
+++ b/src/core/remote-ssh/native/native-mux.ts
@@ -30,6 +30,7 @@ import { Client, createAgent, utils, type Channel, type ClientChannel, type Conn
import type { ParsedSsh, ReverseForward, SshOptions, SshTarget } from './ssh-argv'
import type { ResolvedHost } from './ssh-config'
import { acceptNewHostKey } from './known-hosts'
+import { addKeyToAgent, type AgentAddResult } from './agent-add'
/** Result of one remote command, in the shape execFile callers already handle. */
export interface ExecResult {
@@ -50,6 +51,14 @@ export interface NativeMuxDeps {
/** Default agent when the config names none (`SSH_AUTH_SOCK` / Windows' openssh-ssh-agent pipe). */
defaultAgent?(): string | undefined
readFile?(p: string): Buffer | null
+ /**
+ * Whether (and how) to load a key the user just unlocked with a passphrase into `agentPath` —
+ * the native transport's `AddKeysToAgent`. null = do not. Absent = never. Asked only after the
+ * connection authenticated WITH that key; the add itself is fire-and-forget and fail-open.
+ */
+ agentAdd?(req: { agentPath: string; host: ResolvedHost; identityFile: string }): { lifetimeSec?: number } | null
+ /** Test seam: the agent add (agent-add.ts's addKeyToAgent). */
+ addKeyToAgent?: typeof addKeyToAgent
/** Test seam: the TCP (or proxy) socket to run the protocol over. */
connectSocket?(host: string, port: number, timeoutMs: number): Promise<net.Socket>
log?(line: string): void
@@ -127,7 +136,8 @@ export class NativeMux {
* Keys unlocked with a passphrase during this process, so an overflow connection (never
* interactive) can authenticate without asking again. Held only while some connection is alive —
* the "decrypted key in memory for the connection's life" tradeoff of this transport on Windows,
- * where there is no app-private ssh-agent to hold it instead.
+ * where there is no app-private ssh-agent to hold it instead. (The Windows OpenSSH agent service
+ * would PERSIST it, so the key reaches that agent only on an explicit opt-in — agent-add.ts.)
*/
private unlocked = new Map<string, ParsedKey>()
@@ -509,6 +519,7 @@ export class NativeMux {
const onReady = (): void => {
client.removeListener('error', onErr)
resolve()
+ this.maybeAddToAgent(host, auth.succeeded())
}
const onErr = (e: Error & { level?: string }): void => {
client.removeListener('ready', onReady)
@@ -527,6 +538,30 @@ export class NativeMux {
})
}
+ /**
+ * After a connection authenticated with a key the user just typed the passphrase for, load it
+ * into the host's agent when the policy says so (the POSIX path gets the same from OpenSSH's
+ * `AddKeysToAgent`). Never awaited and never throws: the connection is already up, and the agent
+ * only saves the NEXT connection a prompt.
+ */
+ private maybeAddToAgent(host: ResolvedHost, offer: UnlockedOffer | null): void {
+ if (!offer?.agentPath || !this.deps.agentAdd) return
+ let decision: { lifetimeSec?: number } | null = null
+ try {
+ decision = this.deps.agentAdd({ agentPath: offer.agentPath, host, identityFile: offer.file })
+ } catch {
+ decision = null
+ }
+ if (!decision) return
+ const add = this.deps.addKeyToAgent ?? addKeyToAgent
+ void Promise.resolve()
+ .then(() => add(offer.agentPath as string, offer.key, offer.file, { lifetimeSec: decision?.lifetimeSec }))
+ .catch((): AgentAddResult => 'error')
+ .then((r) => {
+ if (r !== 'added') this.deps.log?.(`[native-ssh] could not add ${offer.file} to the ssh agent (${r}); it will ask for the passphrase again next time`)
+ })
+ }
+
/**
* The publickey sequence: the agent first (filtered to the pinned key under IdentitiesOnly, so a
* big agent cannot burn the server's MaxAuthTries), then each identity file, asking for a
@@ -538,7 +573,7 @@ export class NativeMux {
options: SshOptions,
mode: { interactive: boolean },
cancelled: { value: boolean }
- ): { next(): Promise<unknown> } {
+ ): { next(): Promise<unknown>; succeeded(): UnlockedOffer | null } {
const username = host.user
const identitiesOnly = options.identitiesOnly ?? host.identitiesOnly
const files = target.identityFile ? [target.identityFile] : host.identityFiles
@@ -551,6 +586,8 @@ export class NativeMux {
})
const agentPath = resolveAgentPath(target.identityAgent ?? host.identityAgent, this.deps.defaultAgent?.())
const steps: (() => Promise<unknown | null>)[] = []
+ // The key file behind the LAST method handed to ssh2 — on 'ready' that is the one that worked.
+ let last: UnlockedOffer | null = null
if (agentPath) {
steps.push(async () => {
if (!identitiesOnly) return { type: 'agent', username, agent: agentPath }
@@ -562,6 +599,7 @@ export class NativeMux {
for (const file of files) {
steps.push(async () => {
const cachedKey = this.unlocked.get(file)
+ // Unlocked earlier this run: its agent add (if any) was decided then.
if (cachedKey) return { type: 'publickey', username, key: cachedKey }
const data = read(file)
if (!data) return null
@@ -583,7 +621,7 @@ export class NativeMux {
if (key instanceof Error) return null
const parsed = Array.isArray(key) ? key[0] : key
if (prompted) this.unlocked.set(file, parsed)
- return { type: 'publickey', username, key: parsed }
+ return { type: 'publickey', username, key: parsed, [UNLOCKED]: prompted ? { file, key: parsed, agentPath } : undefined }
})
}
let i = 0
@@ -591,15 +629,30 @@ export class NativeMux {
async next() {
while (i < steps.length) {
const step = steps[i++]
- const auth = await step()
- if (auth) return auth
+ const auth = (await step()) as ({ [UNLOCKED]?: UnlockedOffer } & Record<string, unknown>) | null
+ if (auth) {
+ last = auth[UNLOCKED] ?? null
+ delete auth[UNLOCKED]
+ return auth
+ }
}
+ last = null
return false
- }
+ },
+ succeeded: () => last
}
}
}
+const UNLOCKED = Symbol('unlocked-offer')
+
+/** A key the user unlocked with a passphrase during this connect, and the agent the host uses. */
+interface UnlockedOffer {
+ file: string
+ key: ParsedKey
+ agentPath: string | undefined
+}
+
/** Which agent to use: an explicit config value wins; `SSH_AUTH_SOCK`-style references and an
* absent value fall to the default; `none` disables it. */
export function resolveAgentPath(configured: string | undefined, fallback: string | undefined): string | undefined {
diff --git a/src/core/remote-ssh/native/native-runtime.ts b/src/core/remote-ssh/native/native-runtime.ts
index aae53645f..54b339aa9 100644
--- a/src/core/remote-ssh/native/native-runtime.ts
+++ b/src/core/remote-ssh/native/native-runtime.ts
@@ -13,6 +13,7 @@ import { NativeMux, WINDOWS_OPENSSH_AGENT_PIPE, type ExecResult } from './native
import { parseSshG, sshGArgs } from './ssh-config'
import type { SshTarget } from './ssh-argv'
import { runSshArgv, useNativeSsh } from './native-invoke'
+import { decideAgentAdd } from './agent-add'
export { useNativeSsh }
@@ -25,6 +26,13 @@ export function setNativePassphrasePrompt(fn: PassphrasePrompt | null): void {
passphrasePrompt = fn
}
+let windowsAgentOptIn: () => boolean = () => false
+
+/** Main installs the `settings.windowsSshAgentAddKeys` reader here (read at each unlock). */
+export function setNativeWindowsAgentOptIn(fn: () => boolean): void {
+ windowsAgentOptIn = fn
+}
+
/** The ssh binary, used only for `ssh -G` (config evaluation), never as a transport here. */
function sshForConfig(): string {
return (
@@ -68,6 +76,15 @@ export function nativeMux(): NativeMux {
resolveHost,
defaultAgent,
askPassphrase: (f, req) => (passphrasePrompt ? passphrasePrompt(f, req) : Promise.resolve(null)),
+ agentAdd: ({ agentPath, host }) => {
+ let optIn = false
+ try {
+ optIn = windowsAgentOptIn() === true
+ } catch {
+ optIn = false
+ }
+ return decideAgentAdd({ agentPath, addKeysToAgent: host.addKeysToAgent, windowsAgentOptIn: optIn })
+ },
log: (line) => console.warn(line)
})
}
diff --git a/src/core/remote-ssh/native/ssh-config.ts b/src/core/remote-ssh/native/ssh-config.ts
index de0e060e8..4b11332c7 100644
--- a/src/core/remote-ssh/native/ssh-config.ts
+++ b/src/core/remote-ssh/native/ssh-config.ts
@@ -39,6 +39,12 @@ export interface ResolvedHost {
strictHostKeyChecking: string
/** Seconds, or undefined for none. */
connectTimeout?: number
+ /**
+ * The config's `AddKeysToAgent`, as `ssh -G` prints it: `false` / `true` / `ask` / `confirm`, a
+ * lifetime in seconds, or `confirm <seconds>`. Parsed by `parseAddKeysToAgent` (agent-add.ts);
+ * kept raw here so an unknown spelling reads as "not asked for", never as yes.
+ */
+ addKeysToAgent?: string
}
/** `~` / `%d` expansion for path-valued options. `ssh -G` leaves `~` unexpanded. */
@@ -95,7 +101,8 @@ export function parseSshG(out: string, home: string = os.homedir()): ResolvedHos
userKnownHostsFiles: words('userknownhostsfile'),
globalKnownHostsFiles: words('globalknownhostsfile'),
strictHostKeyChecking: single.get('stricthostkeychecking') ?? 'ask',
- connectTimeout: Number.isFinite(timeout) && timeout > 0 ? timeout : undefined
+ connectTimeout: Number.isFinite(timeout) && timeout > 0 ? timeout : undefined,
+ addKeysToAgent: single.get('addkeystoagent')
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 0897489bc..8fd0903e0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -19,7 +19,7 @@ import { IPC } from '../shared/ipc'
// in-memory and redacted at its push boundary; the panel/IPC side is gated on the setting.
const logBuffer = new LogBuffer()
installLogSink(logBuffer)
-import { nativeMux, useNativeSsh } from '../core/remote-ssh/native/native-runtime'
+import { nativeMux, setNativeWindowsAgentOptIn, useNativeSsh } from '../core/remote-ssh/native/native-runtime'
import { writeFilesToClipboard } from './clipboard-files'
import { pickProjectIcon } from './project-icon-upload'
import { allowGuestNavigation } from './webview-nav'
@@ -4658,6 +4658,9 @@ app.whenReady().then(async () => {
// Forgetting a team also forgets the device token this app run holds for it in memory.
ipcMain.handle(IPC.relayHostedBookmarkRemove, async (_e, hostId: string) => removeHostedBookmark(String(hostId), bookmarks))
}
+ // Windows SSH projects: the opt-in to keep passphrase-unlocked keys in the Windows OpenSSH agent
+ // (core/remote-ssh/native/agent-add.ts). Read at each unlock, so a toggle applies to the next one.
+ setNativeWindowsAgentOptIn(() => settingsStore.get().windowsSshAgentAddKeys === true)
sshProjectManager = initSshProject(
(projectId) => {
// On (re)connect, reconcile the server's .nodeterm/project.json with our offline cache by rev.
diff --git a/src/renderer/components/settings/sections/SshSection.tsx b/src/renderer/components/settings/sections/SshSection.tsx
index d4117c437..b50e7fe5f 100644
--- a/src/renderer/components/settings/sections/SshSection.tsx
+++ b/src/renderer/components/settings/sections/SshSection.tsx
@@ -7,6 +7,10 @@ import { FieldRow } from '../FieldRow'
import { Button } from '@renderer/ui/Button'
import { Input } from '@renderer/ui/Input'
import { uuid } from '@renderer/lib/uuid'
+import { Switch } from '@renderer/ui/Switch'
+import { useSettings } from '../../../state/settings'
+import { isWindowsPlatform } from '@shared/platform-utils'
+import { isBrowserRuntime } from '../../../bridge/runtime'
const ROWS = {
servers: {
@@ -15,12 +19,23 @@ const ROWS = {
'ssh', 'remote', 'server', 'host', 'connect', 'identity', 'key',
'test', 'folder', 'directory', 'cwd', 'working directory'
]
+ },
+ windowsAgent: {
+ title: 'Keep unlocked keys in the Windows ssh-agent',
+ keywords: ['ssh-agent', 'agent', 'passphrase', 'key', 'windows', 'AddKeysToAgent', 'ssh-add', 'prompt']
}
}
-const ENTRIES = Object.values(ROWS)
+/** The native SSH transport (and with it this switch) is the Windows desktop's; a browser tab's
+ * SSH is the server's business, whatever OS the viewer runs. */
+function showsWindowsAgentRow(): boolean {
+ return typeof navigator !== 'undefined' && !isBrowserRuntime() && isWindowsPlatform()
+}
+const ENTRIES = showsWindowsAgentRow() ? Object.values(ROWS) : [ROWS.servers]
export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Element {
const sshServers = useSshServers((s) => s.servers)
+ const agentAddKeys = useSettings((s) => s.settings.windowsSshAgentAddKeys)
+ const updateSettings = useSettings((s) => s.update)
const [sshDraft, setSshDraft] = useState<SshServer | null>(null)
const [importMsg, setImportMsg] = useState<string | null>(null)
const [testMsg, setTestMsg] = useState<string | null>(null)
@@ -291,6 +306,22 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
)}
</div>
</SearchableRow>
+
+ {showsWindowsAgentRow() ? (
+ <SearchableRow {...ROWS.windowsAgent}>
+ <FieldRow
+ label="Keep unlocked keys in the Windows ssh-agent"
+ description="Off by default. On, a key you unlock with its passphrase for an SSH project is also added to the Windows OpenSSH Authentication Agent service (when it is running), so later connections — and your own ssh — stop asking. Windows stores the key, encrypted for your account, until you remove it (ssh-add -d, or ssh-add -D for all); it stays after nodeterm quits and after a restart. Hosts whose ~/.ssh/config says AddKeysToAgent yes get this without the switch."
+ control={
+ <Switch
+ checked={agentAddKeys === true}
+ onChange={(v) => void updateSettings({ windowsSshAgentAddKeys: v })}
+ ariaLabel="Keep unlocked keys in the Windows ssh-agent"
+ />
+ }
+ />
+ </SearchableRow>
+ ) : null}
</SettingsSection>
)
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e27de074e..1399ab006 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1874,6 +1874,17 @@ export interface Settings {
* terminal. Logic: `renderer/terminal/copy-on-select.ts`.
*/
copyOnSelect: boolean
+ /**
+ * Windows SSH projects: after a key is unlocked with its passphrase, also load it into the
+ * Windows OpenSSH agent service, so later connections (and the user's own `ssh`) do not prompt
+ * again. OFF by default because that agent STORES the key — DPAPI-encrypted in
+ * `HKCU\Software\OpenSSH\Agent\Keys`, surviving service restarts — until it is removed
+ * (`ssh-add -d` / `-D`), and it refuses a lifetime constraint (measured on windows-latest,
+ * OpenSSH_for_Windows_9.5p2), so there is no "for this session only". A host whose own
+ * `~/.ssh/config` says `AddKeysToAgent yes` gets the add without this switch: that user already
+ * asked OpenSSH for exactly this. Logic: `core/remote-ssh/native/agent-add.ts`.
+ */
+ windowsSshAgentAddKeys: boolean
/** Plain mouse wheel zooms the canvas (no Cmd/Ctrl needed). On macOS a two-finger trackpad
* scroll keeps panning independently (see canvas/wheel-gesture.ts), so mouse and trackpad
* coexist; elsewhere this still trades away scroll-to-pan, so it stays opt-in. */
@@ -2245,6 +2256,7 @@ export const DEFAULT_SETTINGS: Settings = {
openMarkdownPreviewMigrated: true,
terminalMiddleClickPaste: false,
copyOnSelect: false,
+ windowsSshAgentAddKeys: false,
wheelZoom: false,
wheelZoomSpeed: 1,
trackpadPan: true,