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(windows): ForwardAgent, ProxyCommand and Pageant on the native SSH transport

review15f670caa937
diff --git a/src/core/remote-ssh/native/agent-add.test.ts b/src/core/remote-ssh/native/agent-add.test.ts
index cbd7e24c3..d2c8a5168 100644
--- a/src/core/remote-ssh/native/agent-add.test.ts
+++ b/src/core/remote-ssh/native/agent-add.test.ts
@@ -26,6 +26,7 @@ import {
} from './agent-add'
import { findExecutableSync } from '../../exec-path'
import { ed25519KeyPair } from './test-keys'
+import { pickWindowsAgent } from './windows-agent-discovery'
function parsed(k: string, pass?: string): ParsedKey {
const p = utils.parseKey(k, pass)
@@ -156,6 +157,10 @@ describe('decideAgentAdd', () => {
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()
+ // The Pageant pipe windows-agent-discovery.ts picks as a default agent is never written to by the opt-in.
+ const discovered = pickWindowsAgent({ pipes: ['pageant.dev.3f9a1c0b2e'], user: 'dev' }) as string
+ expect(discovered).toBe('\\\\.\\pipe\\pageant.dev.3f9a1c0b2e')
+ expect(decideAgentAdd({ agentPath: discovered, 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", () => {
diff --git a/src/core/remote-ssh/native/native-jump.test.ts b/src/core/remote-ssh/native/native-jump.test.ts
index 26d48026c..83ba12b3d 100644
--- a/src/core/remote-ssh/native/native-jump.test.ts
+++ b/src/core/remote-ssh/native/native-jump.test.ts
@@ -15,6 +15,22 @@ import { childArgs } from '../control-master'
import { parseProxyJump, sshGArgs, type HostQuery, type ResolvedHost } from './ssh-config'
import type { SshConnection } from '../../../shared/ssh'
import { ed25519KeyPair } from './test-keys'
+import { spawn } from 'child_process'
+import type { ProxySpawn } from './proxy-command'
+
+/**
+ * A ProxySpawn that reads the EXPANDED `pipe <host> <port>` the mux handed the shell and runs a
+ * node stdio↔TCP pipe to it instead — the shell is not the subject here, the token expansion and
+ * the stdio transport are (proxy-command.test.ts covers the real /bin/sh form).
+ */
+const proxyLines: string[] = []
+const pipeSpawn: ProxySpawn = (_file, args) => {
+ const line = args[args.length - 1].replace(/^exec /, '').replace(/^"|"$/g, '')
+ proxyLines.push(line)
+ const [, host, port] = line.split(' ')
+ const script = `const s=require('net').connect(${Number(port)},${JSON.stringify(host)});process.stdin.pipe(s).pipe(process.stdout)`
+ return spawn(process.execPath, ['-e', script], { stdio: ['pipe', 'pipe', 'pipe'] })
+}
const clientKey = ed25519KeyPair() // the target accepts only this
const jumpKey = ed25519KeyPair() // the jumps accept only this
@@ -114,6 +130,7 @@ function base(port: number, user: string, id: string): ResolvedHost {
function mux(): NativeMux {
const m = new NativeMux({
defaultAgent: () => undefined,
+ spawnProxy: pipeSpawn,
resolveHost: async (q) => {
asked.push(q)
const c = config[q.host]
@@ -240,11 +257,43 @@ describe('NativeMux over a ProxyJump chain', () => {
expect(loop.stderr.toString()).toMatch(/ProxyJump loop/)
})
- it('refuses a ProxyCommand on a jump by name', async () => {
- config.jump1 = { ...base(jump1.port, 'ops', 'jump_id'), proxyCommand: 'nc %h %p' }
- const r = await mux().exec(exec('echo hi'))
+ it('starts the chain from the FIRST hop\'s ProxyCommand (tokens expanded for that hop)', async () => {
+ proxyLines.length = 0
+ config.jump1 = { ...base(jump1.port, 'ops', 'jump_id'), proxyCommand: 'pipe %h %p' }
+ const r = await mux().exec(exec('echo via-proxy'))
+ expect(r.stderr.toString()).toBe('')
+ expect(r.stdout.toString()).toBe('target ran: echo via-proxy\n')
+ expect(proxyLines).toEqual([`pipe 127.0.0.1 ${jump1.port}`])
+ expect(jump1.forwards).toEqual([`127.0.0.1:${target.port}`])
+ })
+
+ it('a direct ProxyCommand on the target; ProxyUseFdpass is refused by name', async () => {
+ proxyLines.length = 0
+ config['target.test'] = { ...base(target.port, 'dev', 'id'), proxyCommand: 'pipe %h %p' }
+ const r = await mux().exec(exec('echo direct'))
+ expect(r.stdout.toString()).toBe('target ran: echo direct\n')
+ expect(proxyLines).toEqual([`pipe 127.0.0.1 ${target.port}`])
+ expect(jump1.logins).toBe(0)
+
+ config['target.test'] = { ...base(target.port, 'dev', 'id'), proxyCommand: 'pipe %h %p', proxyUseFdpass: true }
+ const f = await mux().exec(exec('echo fd'))
+ expect(f.code).toBe(255)
+ expect(f.stderr.toString()).toMatch(/ProxyUseFdpass is not supported/)
+ })
+
+ it('a ProxyCommand that fails before the handshake reports its stderr', async () => {
+ const failing = new NativeMux({
+ defaultAgent: () => undefined,
+ spawnProxy: () =>
+ spawn(process.execPath, ['-e', `process.stderr.write('kex_exchange: Connection refused\\n');process.exit(255)`], {
+ stdio: ['pipe', 'pipe', 'pipe']
+ }),
+ resolveHost: async () => ({ ...base(target.port, 'dev', 'id'), proxyCommand: 'whatever' })
+ })
+ muxes.push(failing)
+ const r = await failing.exec(exec('echo x'))
expect(r.code).toBe(255)
- expect(r.stderr.toString()).toMatch(/ProxyCommand is not supported .*jump host jump1/)
+ expect(r.stderr.toString()).toMatch(/ProxyCommand exited \(code 255\).*kex_exchange: Connection refused/)
})
it('overflow connections (MaxSessions spill) reuse the primary\'s jump chain', async () => {
diff --git a/src/core/remote-ssh/native/native-mux.test.ts b/src/core/remote-ssh/native/native-mux.test.ts
index fa9d82e43..5f68d9f57 100644
--- a/src/core/remote-ssh/native/native-mux.test.ts
+++ b/src/core/remote-ssh/native/native-mux.test.ts
@@ -7,7 +7,7 @@ import fs from 'fs'
import os from 'os'
import path from 'path'
import { AddressInfo } from 'net'
-import { Server, utils, type Connection } from 'ssh2'
+import { Client, Server, utils, type Connection, type ConnectConfig } from 'ssh2'
import { NativeMux, noMasterMessage } from './native-mux'
import { parseSshArgv } from './ssh-argv'
import { childArgs, masterRoundTripArgs, remoteTmuxPtyArgs } from '../control-master'
@@ -26,6 +26,10 @@ let port: number
let connections = 0
let live: Connection[] = []
let serverHostKey = hostKey.private
+/** Per session: the requests seen before its exec ('auth-agent', 'pty'), with the command. */
+let sessions: { requests: string[]; cmd: string }[] = []
+/** Whether the server grants agent forwarding (AllowAgentForwarding). */
+let allowAgentFwd = true
function pubMatches(offered: { algo: string; data: Buffer }, pub: string): boolean {
const k = utils.parseKey(pub)
@@ -47,14 +51,22 @@ function startServer(): Promise<void> {
client.on('ready', () => {
client.on('session', (accept) => {
const session = accept()
+ const requests: string[] = []
let ptyInfo: { cols: number; rows: number } | undefined
+ session.on('auth-agent', (acceptFwd, rejectFwd) => {
+ requests.push('auth-agent')
+ if (allowAgentFwd) acceptFwd?.()
+ else rejectFwd?.()
+ })
session.on('pty', (acceptPty, _reject, info) => {
+ requests.push('pty')
ptyInfo = { cols: info.cols, rows: info.rows }
acceptPty?.()
})
session.on('exec', (acceptExec, _reject, info) => {
const ch = acceptExec()
const cmd = info.command
+ sessions.push({ requests: [...requests], cmd })
if (cmd === 'cat') {
const chunks: Buffer[] = []
ch.on('data', (d: Buffer) => chunks.push(d))
@@ -126,6 +138,8 @@ const muxes: NativeMux[] = []
afterEach(() => {
for (const m of muxes.splice(0)) m.exitAll()
for (const c of live.splice(0)) c.end()
+ sessions = []
+ allowAgentFwd = true
})
const track = (m: NativeMux): NativeMux => (muxes.push(m), m)
@@ -324,3 +338,136 @@ describe('NativeMux over a real SSH protocol peer', () => {
).rejects.toThrow(noMasterMessage(CP()))
})
})
+
+describe('ForwardAgent (target PTY channels only)', () => {
+ const pty = () => {
+ const p = parseSshArgv(remoteTmuxPtyArgs(conn(), CP(), 'nt-fwd', '~'))
+ if (p.kind !== 'exec') throw new Error()
+ return p
+ }
+ const drain = (ch: NodeJS.ReadableStream & NodeJS.EventEmitter): Promise<void> =>
+ new Promise((r) => {
+ ch.on('close', () => r())
+ ch.resume()
+ })
+ const fwdMux = (forwardAgent: string | undefined, extra: Partial<ConstructorParameters<typeof NativeMux>[0]> = {}) =>
+ track(
+ mux({
+ resolveHost: async () => ({ ...host(), forwardAgent }),
+ defaultAgent: () => '/fake/agent.sock',
+ ...extra
+ })
+ )
+
+ it('`yes`: the pty channel asks for forwarding; background execs never do', async () => {
+ const m = fwdMux('yes')
+ expect((await m.exec(exec('echo bg'))).code).toBe(0)
+ await drain(await m.shell(pty(), { cols: 80, rows: 24 }))
+ expect((await m.exec(exec('echo bg2'))).code).toBe(0)
+ const bg = sessions.filter((x) => x.cmd.startsWith('echo'))
+ expect(bg.every((x) => !x.requests.includes('auth-agent'))).toBe(true)
+ const term = sessions.find((x) => x.cmd.includes('new-session'))
+ expect(term?.requests).toEqual(['auth-agent', 'pty'])
+ })
+
+ it('`no` / absent: nothing is requested', async () => {
+ for (const v of ['no', undefined]) {
+ const m = fwdMux(v)
+ await drain(await m.shell(pty(), { cols: 80, rows: 24 }))
+ m.exitAll()
+ }
+ expect(sessions.some((x) => x.requests.includes('auth-agent'))).toBe(false)
+ })
+
+ it('a server that refuses forwarding still gets its terminal, and is not asked again', async () => {
+ allowAgentFwd = false
+ const logs: string[] = []
+ const m = fwdMux('yes', { log: (l) => logs.push(l) })
+ const out = await new Promise<string>((resolve, reject) => {
+ m.shell(pty(), { cols: 80, rows: 24 }).then((ch) => {
+ let text = ''
+ ch.on('data', (d: Buffer) => (text += d.toString()))
+ ch.on('close', () => resolve(text))
+ }, reject)
+ })
+ expect(out).toContain('pty 80x24')
+ await drain(await m.shell(pty(), { cols: 80, rows: 24 }))
+ const terms = sessions.filter((x) => x.cmd.includes('new-session'))
+ expect(terms.map((x) => x.requests.includes('auth-agent'))).toEqual([false, false])
+ expect(logs.filter((l) => /refused agent forwarding/.test(l))).toHaveLength(1)
+ })
+})
+
+describe('agent selection on Windows (Pageant pipe)', () => {
+ const me = os.userInfo().username
+ const capture = (): { agents: unknown[]; restore(): void } => {
+ const agents: unknown[] = []
+ const real = Client.prototype.connect
+ Client.prototype.connect = function (this: Client, cfg: ConnectConfig) {
+ agents.push(cfg.agent)
+ return real.call(this, cfg)
+ }
+ return { agents, restore: () => void (Client.prototype.connect = real) }
+ }
+
+ it('`IdentityAgent pageant` is the discovered pipe — never the string ssh2 turns into pagent.exe', async () => {
+ const cap = capture()
+ try {
+ const m = track(
+ mux({
+ platform: 'win32',
+ listWindowsPipes: () => ['openssh-ssh-agent', `pageant.${me}.abc123`],
+ resolveHost: async () => ({ ...host(), identityAgent: 'pageant', forwardAgent: 'yes' })
+ })
+ )
+ expect((await m.exec(exec('echo pg'))).code).toBe(0)
+ expect(cap.agents).toEqual([`\\\\.\\pipe\\pageant.${me}.abc123`])
+ } finally {
+ cap.restore()
+ }
+ })
+
+ it('no Pageant pipe: no agent at all, and one warning saying why', async () => {
+ const cap = capture()
+ const logs: string[] = []
+ try {
+ const m = track(
+ mux({
+ platform: 'win32',
+ listWindowsPipes: () => ['openssh-ssh-agent'],
+ log: (l) => logs.push(l),
+ resolveHost: async () => ({ ...host(), identityAgent: 'PAGEANT', forwardAgent: 'yes' })
+ })
+ )
+ expect((await m.exec(exec('echo nopg'))).code).toBe(0)
+ expect(cap.agents).toEqual([undefined])
+ expect(logs.filter((l) => /IdentityAgent pageant: no Pageant pipe/.test(l))).toHaveLength(1)
+ } finally {
+ cap.restore()
+ }
+ })
+
+ it('POSIX keeps the value as written', async () => {
+ const cap = capture()
+ try {
+ const m = track(mux({ platform: 'linux', resolveHost: async () => ({ ...host(), identityAgent: '/tmp/a.sock', forwardAgent: 'yes' }) }))
+ expect((await m.exec(exec('echo posix'))).code).toBe(0)
+ expect(cap.agents).toEqual(['/tmp/a.sock'])
+ } finally {
+ cap.restore()
+ }
+ })
+})
+
+describe('unsupported ~/.ssh/config options', () => {
+ it('are named in ONE warning, and the connection still comes up', async () => {
+ const logs: string[] = []
+ const m = track(
+ mux({ log: (l) => logs.push(l), resolveHost: async () => ({ ...host(), unsupported: ['certificatefile', 'localforward'] }) })
+ )
+ expect((await m.exec(exec('echo a'))).code).toBe(0)
+ await m.exit(CP())
+ expect((await m.exec(exec('echo b'))).code).toBe(0)
+ expect(logs.filter((l) => /does not support are ignored: certificatefile, localforward/.test(l))).toHaveLength(1)
+ })
+})
diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.ts
index 5459da84e..0877bb515 100644
--- a/src/core/remote-ssh/native/native-mux.ts
+++ b/src/core/remote-ssh/native/native-mux.ts
@@ -26,15 +26,21 @@
// - ProxyJump: each hop is its own SSH connection with its OWN `ssh -G` config (user, port,
// identity files, known hosts, agent), and the next hop — finally the target — runs over a
// direct-tcpip channel of the previous one, which is what OpenSSH's `ssh -W` jump process does.
-// See `jumpChain` for how a chain and a hop's own ProxyJump are resolved. ProxyCommand is
-// refused by name (it runs an arbitrary local program as the transport).
+// See `jumpChain` for how a chain and a hop's own ProxyJump are resolved;
+// - ProxyCommand: the target's (or the first jump hop's) socket is the command's stdio, as with
+// OpenSSH (proxy-command.ts). ProxyUseFdpass is refused by name;
+// - ForwardAgent: requested on PTY channels of the target connection only — never on a jump hop
+// and never on the background exec/sftp channels, as OpenSSH's own mux helpers do not either.
import net from 'net'
+import os from 'os'
import type { Duplex } from 'stream'
import fs from 'fs'
import { Client, createAgent, utils, type Channel, type ClientChannel, type ConnectConfig, type UNIXConnectionDetails, type ParsedKey, type SFTPWrapper } from 'ssh2'
import type { LocalForward, ParsedSsh, ReverseForward, SshOptions, SshTarget } from './ssh-argv'
-import { parseProxyJump, type HostQuery, type JumpSpec, type ResolvedHost } from './ssh-config'
+import { parseProxyJump, resolveForwardAgent, type HostQuery, type JumpSpec, type ResolvedHost } from './ssh-config'
+import { WINDOWS_OPENSSH_AGENT_PIPE, resolveWindowsIdentityAgent } from './windows-agent-discovery'
+import { expandProxyTokens, proxyCommandSocket, type ProxySpawn } from './proxy-command'
import { acceptNewHostKey } from './known-hosts'
import { addKeyToAgent, type AgentAddResult } from './agent-add'
@@ -68,6 +74,12 @@ export interface NativeMuxDeps {
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>
+ /** Test seam: how a ProxyCommand is spawned (proxy-command.ts). */
+ spawnProxy?: ProxySpawn
+ /** Windows: the names under `\\.\pipe\`, for `IdentityAgent pageant` (windows-agent-discovery.ts). */
+ listWindowsPipes?(): string[]
+ /** Platform the agent rules follow; defaults to process.platform (a test seam). */
+ platform?: NodeJS.Platform
log?(line: string): void
}
@@ -75,7 +87,7 @@ export interface NativeMuxDeps {
const AUTH_WAIT_MS = 5 * 60_000 + 30_000
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
-export const WINDOWS_OPENSSH_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent'
+export { WINDOWS_OPENSSH_AGENT_PIPE }
interface Conn {
key: string
@@ -97,6 +109,10 @@ interface Conn {
* connection BORROWS its primary's chain, so only the primary owns (and ends) these. */
jumps: Client[]
ownsJumps: boolean
+ /** ProxyCommand streams this connection spawned; destroyed (the process killed) when it closes. */
+ proxies: Duplex[]
+ /** ForwardAgent resolved to an agent: PTY channels on this connection request forwarding. */
+ agentForward: boolean
}
interface LocalListener {
@@ -187,6 +203,8 @@ export class NativeMux {
* would PERSIST it, so the key reaches that agent only on an explicit opt-in — agent-add.ts.)
*/
private unlocked = new Map<string, ParsedKey>()
+ /** Warnings already logged (one per distinct line), so a reconnect loop does not flood the log. */
+ private warned = new Set<string>()
constructor(private deps: NativeMuxDeps) {}
@@ -388,12 +406,69 @@ export class NativeMux {
if (!err) recordExit(ch)
cb(err, ch)
}
- if (!ptyOpts) client.exec(p.command ?? '', done)
- else if (p.command) client.exec(p.command, { pty: ptyOpts }, done)
- else client.shell(ptyOpts, done)
+ if (!ptyOpts) return client.exec(p.command ?? '', done)
+ const owner = this.connOf(cp, client)
+ const open = (fwd: boolean): void => {
+ const cb = (err: Error | undefined, ch: ClientChannel): void => {
+ // ssh2 closes the channel when the server refuses agent forwarding (AllowAgentForwarding
+ // no). That must not cost the terminal: retry without it, and stop asking this connection.
+ if (err && fwd && /agent forwarding/i.test(err.message)) {
+ if (owner) owner.agentForward = false
+ this.warnOnce(`[native-ssh] ${p.target.user}@${p.target.host}: the server refused agent forwarding (ForwardAgent)`)
+ return open(false)
+ }
+ done(err, ch)
+ }
+ // ssh2 honors `agentForward` per channel; @types/ssh2 does not declare it.
+ const agentOpt = { agentForward: true } as Record<string, unknown>
+ if (p.command) client.exec(p.command, fwd ? { pty: ptyOpts, ...agentOpt } : { pty: ptyOpts }, cb)
+ else if (fwd) client.shell(ptyOpts, agentOpt, cb)
+ else client.shell(ptyOpts, cb)
+ }
+ open(owner?.agentForward === true)
})
}
+ /** The connection (primary or overflow) of `controlPath` that owns `client`. */
+ private connOf(controlPath: string, client: Client): Conn | undefined {
+ return [this.conns.get(controlPath), ...(this.overflow.get(controlPath) ?? [])].find((c) => c?.client === client)
+ }
+
+ private warnOnce(line: string): void {
+ if (this.warned.has(line)) return
+ this.warned.add(line)
+ this.deps.log?.(line)
+ }
+
+ /**
+ * The agent a hop authenticates with: an explicit config value wins, `none` disables it, else
+ * the platform default. On Windows `IdentityAgent pageant` becomes the discovered Pageant pipe —
+ * never the bare string, which ssh2 would turn into a pagent.exe spawn.
+ */
+ private agentPathFor(configured: string | undefined): string | undefined {
+ if ((this.deps.platform ?? process.platform) === 'win32' && configured?.toLowerCase() === 'pageant') {
+ let pipes: string[] = []
+ try {
+ pipes = this.deps.listWindowsPipes?.() ?? []
+ } catch {
+ pipes = []
+ }
+ let user: string | undefined
+ try {
+ user = os.userInfo().username
+ } catch {
+ user = undefined
+ }
+ const r = resolveWindowsIdentityAgent(configured, pipes, user)
+ if (r.missing) {
+ this.warnOnce('[native-ssh] IdentityAgent pageant: no Pageant pipe found (Pageant 0.75+ or KeeAgent must be running)')
+ return undefined
+ }
+ return r.agent
+ }
+ return resolveAgentPath(configured, this.deps.defaultAgent?.())
+ }
+
/**
* An SFTP session for scp's argv. The shared connection when there is one; otherwise a one-off
* connection (scp's builders say ControlMaster=no, i.e. never become the master) that closes
@@ -561,7 +636,9 @@ export class NativeMux {
channels: 0,
full: false,
jumps: [],
- ownsJumps: false
+ ownsJumps: false,
+ proxies: [],
+ agentForward: false
}
let lastError = ''
client.on('error', (e: Error & { level?: string }) => {
@@ -573,6 +650,7 @@ export class NativeMux {
closeLocalForwards(conn)
// The jump connections belong to the target connection: they end with it.
if (conn.ownsJumps) for (const j of conn.jumps) j.end()
+ for (const px of conn.proxies) px.destroy()
if (this.conns.get(controlPath) === conn) {
this.conns.delete(controlPath)
// The group dies with its primary, as mux clients die with their ControlMaster.
@@ -609,8 +687,10 @@ export class NativeMux {
via?: Conn
): Promise<void> {
const host = await this.deps.resolveHost(target)
- if (host.proxyCommand) {
- throw new Error(`ssh: ProxyCommand is not supported by nodeterm's Windows SSH transport (host ${target.host})`)
+ if (!via && host.unsupported?.length) {
+ this.warnOnce(
+ `[native-ssh] ${target.host}: ~/.ssh/config options nodeterm's SSH transport does not support are ignored: ${host.unsupported.join(', ')}`
+ )
}
const timeoutMs = (options.connectTimeout ?? host.connectTimeout ?? DEFAULT_CONNECT_TIMEOUT_MS / 1000) * 1000
const connectSocket = this.deps.connectSocket ?? defaultConnectSocket
@@ -626,11 +706,11 @@ export class NativeMux {
conn.jumps = built
conn.ownsJumps = true
try {
- let next: Duplex = await connectSocket(
- hops[0].host.hostname,
- hops[0].host.port,
- (options.connectTimeout ?? hops[0].host.connectTimeout ?? DEFAULT_CONNECT_TIMEOUT_MS / 1000) * 1000
- )
+ const firstTimeoutMs = (options.connectTimeout ?? hops[0].host.connectTimeout ?? DEFAULT_CONNECT_TIMEOUT_MS / 1000) * 1000
+ // The first hop's own ProxyCommand starts the chain, as `ssh -W` on that hop would run it.
+ let next: Duplex = hops[0].host.proxyCommand
+ ? this.proxySocket(conn, hops[0].query, hops[0].host, firstTimeoutMs)
+ : await connectSocket(hops[0].host.hostname, hops[0].host.port, firstTimeoutMs)
for (let i = 0; i < hops.length; i++) {
const hop = hops[i]
const jump = new Client()
@@ -646,14 +726,20 @@ export class NativeMux {
for (const j of built) j.end()
throw e
}
+ } else if (host.proxyCommand) {
+ sock = this.proxySocket(conn, target, host, timeoutMs)
} else {
sock = await connectSocket(host.hostname, host.port, timeoutMs)
}
// A jump that drops takes the target with it: every channel then ends with 255 (the forwarded
// stream closing already does this; ending explicitly does not depend on ssh2 noticing it).
for (const j of conn.jumps) j.once('close', () => conn.client.end())
+ // ForwardAgent: the TARGET hop only (jump hops above never forward), with the UNFILTERED agent
+ // — OpenSSH forwards the whole agent even under IdentitiesOnly.
+ const forwardAgent = resolveForwardAgent(host.forwardAgent, this.agentPathFor(target.identityAgent ?? host.identityAgent))
+ conn.agentForward = forwardAgent !== undefined
try {
- await this.handshake(conn.client, sock, target, host, options, mode, '')
+ await this.handshake(conn.client, sock, target, host, options, mode, '', forwardAgent)
} catch (e) {
if (conn.ownsJumps) for (const j of conn.jumps) j.end()
throw e
@@ -678,11 +764,6 @@ export class NativeMux {
hops.push({ query: { user: resolved.user, host: spec.host, port: resolved.port }, host: resolved })
}
const first = hops[0]
- if (first.host.proxyCommand) {
- throw new Error(
- `ssh: ProxyCommand is not supported by nodeterm's Windows SSH transport (jump host ${first.query.host})`
- )
- }
if (first.host.proxyJump) {
const key = `${first.host.user}@${first.host.hostname}:${first.host.port}`
if (seen.has(key)) throw new Error(`ssh: ProxyJump loop at ${first.query.host}`)
@@ -692,6 +773,24 @@ export class NativeMux {
return hops
}
+ /** The ProxyCommand stream for `host` (tokens expanded), owned by `conn`. */
+ private proxySocket(conn: Conn, query: HostQuery & { user?: string }, host: ResolvedHost, timeoutMs: number): Duplex {
+ if (host.proxyUseFdpass) {
+ throw new Error(`ssh: ProxyUseFdpass is not supported by nodeterm's SSH transport (host ${query.host})`)
+ }
+ const cmd = expandProxyTokens(host.proxyCommand ?? '', {
+ hostname: host.hostname,
+ port: host.port,
+ user: host.user,
+ originalHost: query.host,
+ hostKeyAlias: host.hostKeyAlias
+ })
+ const sock = proxyCommandSocket(cmd, { timeoutMs, spawn: this.deps.spawnProxy })
+ conn.proxies.push(sock)
+ sock.on('error', (e) => this.deps.log?.(`[native-ssh] ${query.host}: ${e.message}`))
+ return sock
+ }
+
/** The SSH handshake over `sock`: host key (accept-new) and publickey auth, for one hop or the target. */
private async handshake(
client: Client,
@@ -700,7 +799,9 @@ export class NativeMux {
host: ResolvedHost,
options: SshOptions,
mode: { interactive: boolean },
- prefix: string
+ prefix: string,
+ /** ForwardAgent's agent (target hop only): set as ssh2's `agent`, which agent channels use. */
+ forwardAgent?: string
): Promise<void> {
// OpenSSH checks the key under the REAL host name (HostName) unless HostKeyAlias says otherwise.
const knownAs = host.hostKeyAlias ?? host.hostname
@@ -733,7 +834,10 @@ export class NativeMux {
},
authHandler: (_methods: unknown, _partial: unknown, next: (a: unknown) => void) => {
auth.next().then(next, () => next(false))
- }
+ },
+ // Not `agentForward: true`: that would request forwarding on every background exec and SFTP
+ // channel too. Only `channel()`'s PTY channels ask (see there).
+ ...(forwardAgent ? { agent: forwardAgent } : {})
} as ConnectConfig
await new Promise<void>((resolve, reject) => {
const onReady = (): void => {
@@ -813,7 +917,7 @@ export class NativeMux {
return null
}
})
- const agentPath = resolveAgentPath(target.identityAgent ?? host.identityAgent, this.deps.defaultAgent?.())
+ const agentPath = this.agentPathFor(target.identityAgent ?? host.identityAgent)
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
diff --git a/src/core/remote-ssh/native/native-runtime.test.ts b/src/core/remote-ssh/native/native-runtime.test.ts
new file mode 100644
index 000000000..5f5f34ff9
--- /dev/null
+++ b/src/core/remote-ssh/native/native-runtime.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect } from 'vitest'
+import { makeResolveHost, resolveSshProgram, sshFallbacks } from './native-runtime'
+
+describe('resolveSshProgram', () => {
+ it('the binary when there is one, on every platform', () => {
+ expect(resolveSshProgram('linux', {}, () => '/usr/bin/ssh')).toBe('/usr/bin/ssh')
+ expect(resolveSshProgram('win32', {}, () => 'C:\\Windows\\System32\\OpenSSH\\ssh.exe')).toBe(
+ 'C:\\Windows\\System32\\OpenSSH\\ssh.exe'
+ )
+ })
+ it('no binary on Windows: the `ssh` sentinel the native transport serves', () => {
+ expect(resolveSshProgram('win32', {}, () => null)).toBe('ssh')
+ })
+ it('no binary on POSIX (or native opted out): null, as before', () => {
+ expect(resolveSshProgram('linux', {}, () => null)).toBeNull()
+ expect(resolveSshProgram('darwin', {}, () => null)).toBeNull()
+ expect(resolveSshProgram('win32', { NODETERM_NATIVE_SSH: '0' }, () => null)).toBeNull()
+ expect(resolveSshProgram('linux', { NODETERM_NATIVE_SSH: '1' }, () => null)).toBe('ssh')
+ })
+ it('the fallbacks: POSIX locations unchanged; Windows adds the OpenSSH Client directory', () => {
+ expect(sshFallbacks('darwin')).toEqual(['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'])
+ expect(sshFallbacks('win32', { SystemRoot: 'C:\\Windows' })).toEqual(['C:\\Windows\\System32\\OpenSSH\\ssh.exe'])
+ })
+})
+
+describe('makeResolveHost', () => {
+ const enoent = Object.assign(new Error('spawn ssh ENOENT'), { code: 'ENOENT' })
+ it('evaluates the config with ssh -G', async () => {
+ const calls: string[][] = []
+ const resolve = makeResolveHost({
+ ssh: () => 'ssh',
+ execFile: (_f, args, _o, cb) => {
+ calls.push(args)
+ cb(null, 'hostname 10.0.0.9\nuser dev\nport 2200\n')
+ }
+ })
+ expect(await resolve({ host: 'box', user: 'dev' })).toMatchObject({ hostname: '10.0.0.9', port: 2200 })
+ expect(calls).toEqual([['-G', '-l', 'dev', 'box']])
+ })
+
+ it('no ssh binary at all: OpenSSH defaults, and ONE log line per host', async () => {
+ const logs: string[] = []
+ const resolve = makeResolveHost({
+ ssh: () => 'ssh',
+ execFile: (_f, _a, _o, cb) => cb(enoent, ''),
+ log: (l) => logs.push(l),
+ home: '/home/me',
+ user: () => 'me'
+ })
+ expect(await resolve({ host: 'box', port: 2222 })).toMatchObject({ hostname: 'box', port: 2222, user: 'me' })
+ await resolve({ host: 'box' })
+ expect(logs).toEqual(['[native-ssh] ssh.exe not found; ~/.ssh/config was not evaluated for box'])
+ })
+
+ it('any other failure still rejects', async () => {
+ const resolve = makeResolveHost({
+ ssh: () => 'ssh',
+ execFile: (_f, _a, _o, cb) => cb(Object.assign(new Error('bad config line 3'), { code: 255 }), '')
+ })
+ await expect(resolve({ host: 'box' })).rejects.toThrow(/ssh -G failed for box: bad config line 3/)
+ })
+})
diff --git a/src/core/remote-ssh/native/native-runtime.ts b/src/core/remote-ssh/native/native-runtime.ts
index d26fe8b2c..639fc8d5b 100644
--- a/src/core/remote-ssh/native/native-runtime.ts
+++ b/src/core/remote-ssh/native/native-runtime.ts
@@ -7,10 +7,12 @@
import { execFile } from 'child_process'
import fs from 'fs'
+import os from 'os'
import path from 'path'
-import { findExecutableSync } from '../../exec-path'
-import { NativeMux, WINDOWS_OPENSSH_AGENT_PIPE, type ExecResult } from './native-mux'
-import { parseSshG, sshGArgs, type HostQuery } from './ssh-config'
+import { findExecutableSync, shellPathNow } from '../../exec-path'
+import { NativeMux, type ExecResult } from './native-mux'
+import { defaultHostFromQuery, parseSshG, sshGArgs, type HostQuery, type ResolvedHost } from './ssh-config'
+import { WINDOWS_OPENSSH_AGENT_PIPE, pickWindowsAgent } from './windows-agent-discovery'
import { runSshArgv, useNativeSsh } from './native-invoke'
import { decideAgentAdd } from './agent-add'
@@ -32,42 +34,132 @@ export function setNativeWindowsAgentOptIn(fn: () => boolean): void {
windowsAgentOptIn = fn
}
+const POSIX_SSH_FALLBACKS = ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh']
+
+/** Where an ssh binary may live off PATH: the usual POSIX locations, and on Windows the OpenSSH
+ * Client feature's own directory (GUI apps there can start with a PATH that lacks it). */
+export function sshFallbacks(platform: NodeJS.Platform = process.platform, env: NodeJS.ProcessEnv = process.env): string[] {
+ if (platform !== 'win32') return POSIX_SSH_FALLBACKS
+ return [path.win32.join(env.SystemRoot || env.WINDIR || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')]
+}
+
+let cachedSshBinary: string | null | undefined
+
+/**
+ * The ssh BINARY, or null. The one lookup every module used to keep a private copy of. GUI apps do
+ * not inherit the shell PATH, so this walks the cached login-shell PATH (exec-path.ts) then the
+ * fallbacks; a MISS is only memoized once that async PATH probe has settled, so an early call
+ * cannot cache a custom-location ssh away forever.
+ */
+export function findSshBinary(): string | null {
+ if (cachedSshBinary !== undefined) return cachedSshBinary
+ const found = findExecutableSync('ssh', sshFallbacks())
+ if (found || shellPathNow() !== undefined) cachedSshBinary = found
+ return found
+}
+
+/**
+ * The ssh PROGRAM a runner should name: the binary when there is one, else — only where the native
+ * transport carries every ssh call (Windows, or NODETERM_NATIVE_SSH=1) — the bare sentinel `ssh`.
+ * `isSshProgram('ssh')` is true, so every runner that checks `isSshProgram && useNativeSsh` routes
+ * it to NativeMux and never spawns it: a Windows machine without the OpenSSH Client feature can
+ * still open SSH projects. Never memoized itself (`useNativeSsh` is read at call time).
+ */
+export function resolveSshProgram(
+ platform: NodeJS.Platform = process.platform,
+ env: NodeJS.ProcessEnv = process.env,
+ binary: () => string | null = findSshBinary
+): string | null {
+ return binary() ?? (useNativeSsh(platform, env) ? 'ssh' : null)
+}
+
/** The ssh binary, used only for `ssh -G` (config evaluation), never as a transport here. */
function sshForConfig(): string {
- return (
- findExecutableSync('ssh', ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh']) ??
- (process.platform === 'win32'
- ? path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')
- : 'ssh')
- )
+ return findSshBinary() ?? (process.platform === 'win32' ? sshFallbacks()[0] : 'ssh')
}
-function resolveHost(t: HostQuery) {
- return new Promise<ReturnType<typeof parseSshG>>((resolve, reject) => {
- let args: string[]
- try {
- args = sshGArgs(t)
- } catch (e) {
- return reject(e)
- }
- execFile(sshForConfig(), args, { timeout: 5_000, windowsHide: true }, (err, stdout) => {
- if (err && !stdout) {
- return reject(new Error(`ssh -G failed for ${t.user ? `${t.user}@` : ''}${t.host}: ${err.message}`))
- }
+type ExecFileLike = (
+ file: string,
+ args: string[],
+ opts: { timeout: number; windowsHide: boolean },
+ cb: (err: (Error & { code?: unknown }) | null, stdout: string) => void
+) => void
+
+/**
+ * `ssh -G` for a destination. With NO ssh binary at all (ENOENT — Windows without the OpenSSH
+ * Client feature) the host resolves to OpenSSH's no-config defaults instead of failing the connect,
+ * and the log says once per host that ~/.ssh/config was not evaluated. Any other failure rejects.
+ */
+export function makeResolveHost(deps: {
+ execFile?: ExecFileLike
+ ssh?: () => string
+ log?: (line: string) => void
+ home?: string
+ user?: () => string
+} = {}): (t: HostQuery) => Promise<ResolvedHost> {
+ const run: ExecFileLike = deps.execFile ?? ((f, a, o, cb) => void execFile(f, a, o, (e, out) => cb(e, String(out ?? ''))))
+ const warned = new Set<string>()
+ return (t) =>
+ new Promise<ResolvedHost>((resolve, reject) => {
+ let args: string[]
try {
- resolve(parseSshG(stdout))
+ args = sshGArgs(t)
} catch (e) {
- reject(e)
+ return reject(e)
}
+ run((deps.ssh ?? sshForConfig)(), args, { timeout: 5_000, windowsHide: true }, (err, stdout) => {
+ if (err && !stdout) {
+ if (err.code === 'ENOENT') {
+ if (!warned.has(t.host)) {
+ warned.add(t.host)
+ ;(deps.log ?? console.warn)(`[native-ssh] ssh.exe not found; ~/.ssh/config was not evaluated for ${t.host}`)
+ }
+ let user: string
+ try {
+ user = deps.user ? deps.user() : os.userInfo().username
+ } catch {
+ return reject(new Error(`ssh: no user for ${t.host} (and no ssh binary to read ~/.ssh/config with)`))
+ }
+ return resolve(defaultHostFromQuery(t, deps.home ?? os.homedir(), user))
+ }
+ return reject(new Error(`ssh -G failed for ${t.user ? `${t.user}@` : ''}${t.host}: ${err.message}`))
+ }
+ try {
+ resolve(parseSshG(stdout))
+ } catch (e) {
+ reject(e)
+ }
+ })
})
- })
}
-/** Windows: the OpenSSH agent service's pipe when it exists. POSIX: the app agent, else the ambient one. */
+/** Windows: the names under `\\.\pipe\` (empty when the directory cannot be listed). */
+function listWindowsPipes(): string[] {
+ try {
+ return fs.readdirSync('\\\\.\\pipe\\')
+ } catch {
+ return []
+ }
+}
+
+/**
+ * Windows: the OpenSSH agent service's pipe, else the user's Pageant / KeeAgent pipe
+ * (windows-agent-discovery.ts). POSIX: the app agent, else the ambient one.
+ */
function defaultAgent(): string | undefined {
if (process.platform === 'win32') {
+ const pipes = listWindowsPipes()
+ let user: string | undefined
+ try {
+ user = os.userInfo().username
+ } catch {
+ user = undefined
+ }
+ const picked = pickWindowsAgent({ pipes, user })
+ if (picked) return picked
try {
- return fs.existsSync(WINDOWS_OPENSSH_AGENT_PIPE) ? WINDOWS_OPENSSH_AGENT_PIPE : undefined
+ // A pipe directory we could not list: the service pipe may still be there.
+ return !pipes.length && fs.existsSync(WINDOWS_OPENSSH_AGENT_PIPE) ? WINDOWS_OPENSSH_AGENT_PIPE : undefined
} catch {
return undefined
}
@@ -78,8 +170,9 @@ function defaultAgent(): string | undefined {
export function nativeMux(): NativeMux {
if (!instance) {
instance = new NativeMux({
- resolveHost,
+ resolveHost: makeResolveHost(),
defaultAgent,
+ listWindowsPipes,
askPassphrase: (f, req) => (passphrasePrompt ? passphrasePrompt(f, req) : Promise.resolve(null)),
agentAdd: ({ agentPath, host }) => {
let optIn = false
diff --git a/src/core/remote-ssh/native/proxy-command.test.ts b/src/core/remote-ssh/native/proxy-command.test.ts
new file mode 100644
index 000000000..f7aa8c352
--- /dev/null
+++ b/src/core/remote-ssh/native/proxy-command.test.ts
@@ -0,0 +1,132 @@
+import { describe, it, expect } from 'vitest'
+import net, { type AddressInfo } from 'net'
+import { spawn } from 'child_process'
+import { expandProxyTokens, proxyCommandArgv, proxyCommandSocket, type ProxySpawn } from './proxy-command'
+
+const T = { hostname: '10.0.0.5', port: 2222, user: 'dev', originalHost: 'box', hostKeyAlias: undefined }
+
+describe('expandProxyTokens', () => {
+ it.each([
+ ['nc %h %p', 'nc 10.0.0.5 2222'],
+ ['ssh -W %h:%p %r@bastion', 'ssh -W 10.0.0.5:2222 dev@bastion'],
+ ['connect %n', 'connect box'],
+ ['echo %k', 'echo box'],
+ ['printf 100%%', 'printf 100%']
+ ])('%s', (cmd, want) => {
+ expect(expandProxyTokens(cmd, T)).toBe(want)
+ })
+ it('%k is HostKeyAlias when one is set', () => {
+ expect(expandProxyTokens('x %k', { ...T, hostKeyAlias: 'alias' })).toBe('x alias')
+ })
+ it('an unknown token is an error by name, never passed through', () => {
+ expect(() => expandProxyTokens('nc %h %C', T)).toThrow(/unknown token %C/)
+ expect(() => expandProxyTokens('trailing %', T)).toThrow(/unknown token %/)
+ })
+})
+
+describe('proxyCommandArgv', () => {
+ it('POSIX: sh -c exec, as OpenSSH runs it', () => {
+ expect(proxyCommandArgv('nc a 22', 'linux')).toEqual({ file: '/bin/sh', args: ['-c', 'exec nc a 22'], verbatim: false })
+ })
+ it('Windows: cmd.exe /d /s /c with the line quoted verbatim', () => {
+ expect(proxyCommandArgv('ncat a 22', 'win32', { ComSpec: 'C:\\Windows\\system32\\cmd.exe' })).toEqual({
+ file: 'C:\\Windows\\system32\\cmd.exe',
+ args: ['/d', '/s', '/c', '"ncat a 22"'],
+ verbatim: true
+ })
+ })
+})
+
+/** A ProxySpawn that ignores the shell and runs `node -e <script>` instead (portable on every leg). */
+const nodeSpawn = (script: string, seen?: { file: string; args: string[] }[]): ProxySpawn => (file, args) => {
+ seen?.push({ file, args })
+ return spawn(process.execPath, ['-e', script], { stdio: ['pipe', 'pipe', 'pipe'] })
+}
+
+describe('proxyCommandSocket', () => {
+ it('speaks over the proxy\'s stdio (a node stdio↔TCP pipe), both ways', async () => {
+ const echo = net.createServer((s) => s.pipe(s))
+ await new Promise<void>((r) => echo.listen(0, '127.0.0.1', () => r()))
+ const port = (echo.address() as AddressInfo).port
+ const pipe = `const s=require('net').connect(${port},'127.0.0.1');process.stdin.pipe(s).pipe(process.stdout)`
+ const seen: { file: string; args: string[] }[] = []
+ const sock = proxyCommandSocket('ignored %h', { timeoutMs: 5000, spawn: nodeSpawn(pipe, seen), platform: 'linux' })
+ try {
+ const got = await new Promise<string>((resolve, reject) => {
+ sock.on('error', reject)
+ sock.on('data', (d: Buffer) => resolve(d.toString()))
+ sock.write('ping')
+ })
+ expect(got).toBe('ping')
+ expect(seen[0]).toEqual({ file: '/bin/sh', args: ['-c', 'exec ignored %h'] })
+ } finally {
+ sock.destroy()
+ echo.close()
+ }
+ })
+
+ it('an early exit is an error carrying the proxy\'s stderr', async () => {
+ const sock = proxyCommandSocket('x', {
+ timeoutMs: 5000,
+ spawn: nodeSpawn(`process.stderr.write('ncat: Connection refused.\\n');process.exit(1)`)
+ })
+ const err = await new Promise<Error>((r) => sock.on('error', r))
+ expect(err.message).toMatch(/ProxyCommand exited \(code 1\) before the connection was up: ncat: Connection refused\./)
+ })
+
+ it('a proxy that never answers times out (ConnectTimeout) and is killed', async () => {
+ const children: import('child_process').ChildProcess[] = []
+ const sock = proxyCommandSocket('x', {
+ timeoutMs: 200,
+ spawn: (f, a, o) => {
+ const c = nodeSpawn('setInterval(()=>{},1000)')(f, a, o)
+ children.push(c)
+ return c
+ }
+ })
+ const err = await new Promise<Error>((r) => sock.on('error', r))
+ expect(err.message).toMatch(/timed out/)
+ await new Promise<void>((r) => (children[0].exitCode !== null || children[0].signalCode !== null ? r() : children[0].once('exit', () => r())))
+ expect(children[0].signalCode ?? children[0].exitCode).not.toBeNull()
+ })
+
+ it('destroying the stream kills the proxy', async () => {
+ const children: import('child_process').ChildProcess[] = []
+ const sock = proxyCommandSocket('x', {
+ timeoutMs: 5000,
+ spawn: (f, a, o) => {
+ const c = nodeSpawn(`process.stdout.write('SSH-2.0-x\\r\\n');setInterval(()=>{},1000)`)(f, a, o)
+ children.push(c)
+ return c
+ }
+ })
+ await new Promise((r) => sock.once('data', r))
+ const exited = new Promise((r) => children[0].once('exit', r))
+ sock.destroy()
+ await exited
+ })
+
+ it('a spawn that fails is an error, not a hang', async () => {
+ const sock = proxyCommandSocket('x', {
+ timeoutMs: 5000,
+ spawn: () => {
+ throw new Error('spawn ENOENT')
+ }
+ })
+ const err = await new Promise<Error>((r) => sock.on('error', r))
+ expect(err.message).toMatch(/could not be started \(spawn ENOENT\)/)
+ })
+
+ it.skipIf(process.platform === 'win32')('the real /bin/sh form runs the expanded command', async () => {
+ // POSIX-only: the default spawn runs `/bin/sh -c 'exec …'`.
+ const sock = proxyCommandSocket(`printf 'hello'`, { timeoutMs: 5000 })
+ const got = await new Promise<string>((resolve, reject) => {
+ let s = ''
+ sock.on('data', (d: Buffer) => (s += d.toString()))
+ sock.on('end', () => resolve(s))
+ sock.on('error', reject)
+ sock.resume()
+ })
+ expect(got).toBe('hello')
+ })
+})
diff --git a/src/core/remote-ssh/native/proxy-command.ts b/src/core/remote-ssh/native/proxy-command.ts
new file mode 100644
index 000000000..dd25d6d60
--- /dev/null
+++ b/src/core/remote-ssh/native/proxy-command.ts
@@ -0,0 +1,148 @@
+// `ProxyCommand` for the in-process transport: run the user's command and speak SSH over its
+// stdin/stdout, exactly what OpenSSH does (sshconnect.c `ssh_proxy_connect`).
+//
+// Trust: the command comes from the user's own ~/.ssh/config (via `ssh -G`), the same trust level
+// it has for OpenSSH on a Mac. Nothing nodeterm controls is interpolated into it except the token
+// VALUES OpenSSH itself substitutes (%h %p %r %n %k), and those come from the same validated
+// destination `sshGArgs` refuses a leading `-` in. An unknown `%x` is an error by name, as it is
+// for OpenSSH (percent_expand is fatal on an unknown key) — never passed through as a guess.
+//
+// `ProxyUseFdpass yes` (the proxy hands back a connected fd over a unix socket) cannot be served
+// from Node and is refused by name by the caller.
+
+import { spawn as nodeSpawn, type ChildProcess } from 'child_process'
+import { Duplex } from 'stream'
+
+/** The values OpenSSH substitutes into a ProxyCommand (sshconnect.c `expand_proxy_command`). */
+export interface ProxyTokens {
+ /** %h — the real host name (HostName, after alias resolution). */
+ hostname: string
+ /** %p */
+ port: number
+ /** %r — the remote user. */
+ user: string
+ /** %n — the host as the user named it (alias). */
+ originalHost: string
+ /** %k — HostKeyAlias when set, else the host as named. */
+ hostKeyAlias?: string
+}
+
+/** Expand `%h %p %r %n %k %%`; throws on any other `%x`, naming it. */
+export function expandProxyTokens(cmd: string, t: ProxyTokens): string {
+ return cmd.replace(/%(.?)/g, (_m, k: string) => {
+ switch (k) {
+ case '%':
+ return '%'
+ case 'h':
+ return t.hostname
+ case 'p':
+ return String(t.port)
+ case 'r':
+ return t.user
+ case 'n':
+ return t.originalHost
+ case 'k':
+ return t.hostKeyAlias ?? t.originalHost
+ default:
+ throw new Error(`ssh: ProxyCommand: unknown token %${k} in "${cmd}"`)
+ }
+ })
+}
+
+/** argv for a ProxyCommand on this platform: POSIX `sh -c 'exec …'` (OpenSSH's own form);
+ * Windows `cmd.exe /d /s /c "…"`, which is how a command line is run there without a POSIX shell. */
+export function proxyCommandArgv(
+ cmd: string,
+ platform: NodeJS.Platform = process.platform,
+ env: NodeJS.ProcessEnv = process.env
+): { file: string; args: string[]; verbatim: boolean } {
+ if (platform === 'win32') {
+ return { file: env.ComSpec || env.COMSPEC || 'cmd.exe', args: ['/d', '/s', '/c', `"${cmd}"`], verbatim: true }
+ }
+ return { file: '/bin/sh', args: ['-c', `exec ${cmd}`], verbatim: false }
+}
+
+/** What the transport needs of a spawned proxy (a ChildProcess with piped stdio). */
+export type ProxySpawn = (file: string, args: string[], opts: { verbatim: boolean }) => ChildProcess
+
+const defaultSpawn: ProxySpawn = (file, args, opts) =>
+ nodeSpawn(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, windowsVerbatimArguments: opts.verbatim })
+
+/** How much of the proxy's stderr is kept for an error message. */
+const STDERR_KEEP = 4096
+
+/**
+ * Spawn the proxy and return a Duplex over its stdio (stdout readable, stdin writable). The child
+ * is killed when the stream is destroyed. If it exits — or nothing arrives from it within
+ * `timeoutMs` (OpenSSH's ConnectTimeout, which for a proxy covers the wait for the server's banner)
+ * — the stream errors with the reason and the proxy's last stderr, which the handshake reports.
+ */
+export function proxyCommandSocket(
+ cmd: string,
+ opts: { timeoutMs: number; platform?: NodeJS.Platform; spawn?: ProxySpawn; env?: NodeJS.ProcessEnv }
+): Duplex {
+ const { file, args, verbatim } = proxyCommandArgv(cmd, opts.platform, opts.env)
+ let stderr = ''
+ let gotData = false
+ let child: ChildProcess | null = null
+ const kill = (): void => {
+ if (child && child.exitCode === null && child.signalCode === null) child.kill()
+ }
+ const why = (msg: string): Error => {
+ const tail = stderr.trim().split(/\r?\n/).pop()
+ return new Error(`ProxyCommand ${msg}${tail ? `: ${tail}` : ''}`)
+ }
+ const stream = new Duplex({
+ read() {
+ child?.stdout?.resume()
+ },
+ write(chunk: Buffer, _enc, cb) {
+ if (!child?.stdin || child.stdin.destroyed) return cb(why('is not running'))
+ child.stdin.write(chunk, (e) => cb(e ?? null))
+ },
+ final(cb) {
+ child?.stdin?.end()
+ cb()
+ },
+ destroy(err, cb) {
+ clearTimeout(timer)
+ kill()
+ cb(err)
+ }
+ })
+ const timer = setTimeout(() => {
+ if (!gotData) stream.destroy(why(`timed out after ${Math.round(opts.timeoutMs / 1000)}s`))
+ }, opts.timeoutMs)
+ try {
+ child = (opts.spawn ?? defaultSpawn)(file, args, { verbatim })
+ } catch (e) {
+ queueMicrotask(() => stream.destroy(why(`could not be started (${(e as Error).message})`)))
+ return stream
+ }
+ const c = child
+ c.on('error', (e) => stream.destroy(why(`could not be started (${e.message})`)))
+ c.stderr?.on('data', (d: Buffer) => {
+ stderr = (stderr + d.toString('utf8')).slice(-STDERR_KEEP)
+ })
+ c.stdin?.on('error', () => {})
+ c.stdout?.on('data', (d: Buffer) => {
+ if (!gotData) {
+ gotData = true
+ clearTimeout(timer)
+ }
+ if (!stream.push(d)) c.stdout?.pause()
+ })
+ // An EOF before any byte waits for the process's own exit: that is where the reason is (an EOF
+ // handed on now would surface as ssh2's bare "Connection lost before handshake").
+ c.stdout?.on('end', () => {
+ if (gotData) stream.push(null)
+ })
+ // 'close', not 'exit': stdout may still hold the banner when the process has already exited.
+ c.on('close', (code, signal) => {
+ clearTimeout(timer)
+ if (stream.destroyed) return
+ // Before any byte: the proxy never reached the server. After: the connection simply ended.
+ if (!gotData) stream.destroy(why(`exited (${signal ?? `code ${code}`}) before the connection was up`))
+ })
+ return stream
+}
diff --git a/src/core/remote-ssh/native/ssh-config.test.ts b/src/core/remote-ssh/native/ssh-config.test.ts
new file mode 100644
index 000000000..f2a2f5bd3
--- /dev/null
+++ b/src/core/remote-ssh/native/ssh-config.test.ts
@@ -0,0 +1,80 @@
+import { describe, it, expect } from 'vitest'
+import { defaultHostFromQuery, parseSshG, resolveForwardAgent } from './ssh-config'
+
+const BASE = ['hostname h.example', 'user dev', 'port 22', 'identityfile ~/.ssh/id_ed25519'].join('\n')
+
+describe('parseSshG — options the native transport acts on or warns about', () => {
+ it('ForwardAgent is kept raw; `no` and absent both read as no forwarding', () => {
+ expect(parseSshG(`${BASE}\nforwardagent yes`, '/home/dev').forwardAgent).toBe('yes')
+ expect(parseSshG(`${BASE}\nforwardagent /tmp/a.sock`, '/home/dev').forwardAgent).toBe('/tmp/a.sock')
+ expect(parseSshG(`${BASE}\nforwardagent no`, '/home/dev').forwardAgent).toBe('no')
+ expect(parseSshG(BASE, '/home/dev').forwardAgent).toBeUndefined()
+ })
+
+ it('ProxyCommand and ProxyUseFdpass', () => {
+ const h = parseSshG(`${BASE}\nproxycommand nc %h %p\nproxyusefdpass yes`, '/home/dev')
+ expect(h.proxyCommand).toBe('nc %h %p')
+ expect(h.proxyUseFdpass).toBe(true)
+ expect(parseSshG(`${BASE}\nproxycommand none\nproxyusefdpass no`, '/home/dev')).toMatchObject({
+ proxyCommand: undefined,
+ proxyUseFdpass: false
+ })
+ })
+
+ it('names every set option it ignores, and nothing when none is set', () => {
+ const h = parseSshG(
+ `${BASE}\ncertificatefile ~/.ssh/id-cert.pub\nlocalforward [127.0.0.1]:8080 [db]:5432\ndynamicforward 1080`,
+ '/home/dev'
+ )
+ expect(h.unsupported).toEqual(['certificatefile', 'localforward', 'dynamicforward'])
+ expect(parseSshG(BASE, '/home/dev').unsupported).toBeUndefined()
+ })
+})
+
+describe('resolveForwardAgent', () => {
+ const env = { MY_AGENT: '/run/agent.sock' }
+ it.each([
+ [undefined, undefined],
+ ['no', undefined],
+ ['yes', '/auth/agent'],
+ ['/tmp/x.sock', '/tmp/x.sock'],
+ ['~/agent.sock', '/home/dev/agent.sock'],
+ ['$MY_AGENT', '/run/agent.sock'],
+ ['${MY_AGENT}', '/run/agent.sock'],
+ ['$UNSET_VAR', undefined],
+ // The default agent's own variable, unset (Windows): the agent this connection uses.
+ ['$SSH_AUTH_SOCK', '/auth/agent'],
+ ['\\\\.\\pipe\\openssh-ssh-agent', '\\\\.\\pipe\\openssh-ssh-agent']
+ ])('%s → %s', (value, want) => {
+ expect(resolveForwardAgent(value, '/auth/agent', env, '/home/dev')).toBe(want)
+ })
+
+ it('`yes` with no agent at all forwards nothing', () => {
+ expect(resolveForwardAgent('yes', undefined, {}, '/home/dev')).toBeUndefined()
+ })
+})
+
+describe('defaultHostFromQuery (no ssh binary to evaluate ~/.ssh/config)', () => {
+ it('uses the query, then OpenSSH defaults', () => {
+ const h = defaultHostFromQuery({ host: 'box' }, '/home/me', 'me', 'linux')
+ expect(h).toMatchObject({ hostname: 'box', port: 22, user: 'me', identitiesOnly: false, strictHostKeyChecking: 'ask' })
+ expect(h.identityFiles).toEqual(
+ ['id_rsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', 'id_ed25519_sk'].map((f) => `/home/me/.ssh/${f}`)
+ )
+ expect(h.userKnownHostsFiles).toEqual(['/home/me/.ssh/known_hosts', '/home/me/.ssh/known_hosts2'])
+ expect(h.globalKnownHostsFiles).toEqual(['/etc/ssh/ssh_known_hosts', '/etc/ssh/ssh_known_hosts2'])
+ })
+
+ it('an explicit user, port and key win; Windows paths are Windows paths', () => {
+ const h = defaultHostFromQuery(
+ { host: 'box', user: 'root', port: 2222, identityFile: 'C:\\k\\id', identityAgent: 'none' },
+ 'C:\\Users\\me',
+ 'me',
+ 'win32',
+ { ProgramData: 'D:\\PD' }
+ )
+ expect(h).toMatchObject({ user: 'root', port: 2222, identityFiles: ['C:\\k\\id'], identitiesOnly: true, identityAgent: 'none' })
+ expect(h.userKnownHostsFiles[0]).toBe('C:\\Users\\me\\.ssh\\known_hosts')
+ expect(h.globalKnownHostsFiles).toEqual(['D:\\PD\\ssh\\ssh_known_hosts'])
+ })
+})
diff --git a/src/core/remote-ssh/native/ssh-config.ts b/src/core/remote-ssh/native/ssh-config.ts
index d36af2498..2d2b128c0 100644
--- a/src/core/remote-ssh/native/ssh-config.ts
+++ b/src/core/remote-ssh/native/ssh-config.ts
@@ -29,8 +29,20 @@ export interface ResolvedHost {
identityAgent?: string
/** `ProxyJump` chain as written (`[user@]host[:port],…`), or undefined. */
proxyJump?: string
- /** `ProxyCommand`, present so the caller can REFUSE it by name (not supported natively). */
+ /** `ProxyCommand` as written (tokens unexpanded — proxy-command.ts expands them). */
proxyCommand?: string
+ /** `ProxyUseFdpass yes`: the proxy hands back a socket fd, which this transport cannot take. */
+ proxyUseFdpass?: boolean
+ /**
+ * `ForwardAgent` as `ssh -G` prints it: `yes`, `no`, a socket/pipe path, or `$VAR`. Resolved by
+ * `resolveForwardAgent`; kept raw so an unknown spelling is decided in one place.
+ */
+ forwardAgent?: string
+ /**
+ * Options the config sets that the native transport does NOT honor (e.g. `certificatefile`,
+ * `localforward`), by `ssh -G` name — warned about once per connection, never silently dropped.
+ */
+ unsupported?: string[]
/** Name the host key is recorded under in known_hosts (`HostKeyAlias`), else the host. */
hostKeyAlias?: string
userKnownHostsFiles: string[]
@@ -88,6 +100,7 @@ export function parseSshG(out: string, home: string = os.homedir()): ResolvedHos
return v && v !== 'none' ? v : undefined
}
const timeout = Number(single.get('connecttimeout'))
+ const unsupported = UNSUPPORTED_OPTIONS.filter((k) => opt(k) !== undefined)
return {
hostname,
port,
@@ -97,12 +110,77 @@ export function parseSshG(out: string, home: string = os.homedir()): ResolvedHos
identityAgent: opt('identityagent'),
proxyJump: opt('proxyjump'),
proxyCommand: opt('proxycommand'),
+ proxyUseFdpass: single.get('proxyusefdpass') === 'yes',
+ forwardAgent: opt('forwardagent'),
hostKeyAlias: opt('hostkeyalias'),
userKnownHostsFiles: words('userknownhostsfile'),
globalKnownHostsFiles: words('globalknownhostsfile'),
strictHostKeyChecking: single.get('stricthostkeychecking') ?? 'ask',
connectTimeout: Number.isFinite(timeout) && timeout > 0 ? timeout : undefined,
- addKeysToAgent: single.get('addkeystoagent')
+ addKeysToAgent: single.get('addkeystoagent'),
+ ...(unsupported.length ? { unsupported } : {})
+ }
+}
+
+/**
+ * Config options `ssh -G` prints only when the user's config sets them, and that this transport
+ * does not act on: user certificates and config-declared forwards (nodeterm never relied on the
+ * latter, and opening them would hide their bind failures). Named in a warning, never guessed at.
+ */
+export const UNSUPPORTED_OPTIONS = ['certificatefile', 'localforward', 'remoteforward', 'dynamicforward'] as const
+
+/**
+ * The agent to forward to the host for `ForwardAgent`, or undefined for none. `yes` forwards the
+ * agent this connection authenticates with (`agentPath`); a path or `$VAR` names another one, as
+ * OpenSSH >= 8.2 allows. A Windows named pipe (`\\.\pipe\…`) is a path like any other.
+ */
+export function resolveForwardAgent(
+ value: string | undefined,
+ agentPath: string | undefined,
+ env: NodeJS.ProcessEnv = process.env,
+ home: string = os.homedir()
+): string | undefined {
+ if (!value || value === 'no') return undefined
+ if (value === 'yes') return agentPath
+ if (value.startsWith('$')) {
+ const name = value.replace(/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/, '$1')
+ if (name === value) return undefined
+ return env[name] || (name === 'SSH_AUTH_SOCK' ? agentPath : undefined)
+ }
+ return expandHomePath(value, home)
+}
+
+/**
+ * The host as OpenSSH would resolve it with NO config file — what the native transport falls back
+ * to when there is no ssh binary to run `ssh -G` with (Windows without the OpenSSH Client feature).
+ * Aliases, per-host keys and ProxyJump in ~/.ssh/config are then not evaluated; the caller says so.
+ */
+export function defaultHostFromQuery(
+ t: HostQuery,
+ home: string = os.homedir(),
+ localUser: string = os.userInfo().username,
+ platform: NodeJS.Platform = process.platform,
+ env: NodeJS.ProcessEnv = process.env
+): ResolvedHost {
+ const p = platform === 'win32' ? path.win32 : path.posix
+ const ssh = (f: string): string => p.join(home, '.ssh', f)
+ const global =
+ platform === 'win32'
+ ? [p.join(env.ProgramData || env.PROGRAMDATA || 'C:\\ProgramData', 'ssh', 'ssh_known_hosts')]
+ : ['/etc/ssh/ssh_known_hosts', '/etc/ssh/ssh_known_hosts2']
+ return {
+ hostname: t.host,
+ port: t.port ?? 22,
+ user: t.user ?? localUser,
+ // OpenSSH's built-in default order; a file that does not exist is simply skipped.
+ identityFiles: t.identityFile
+ ? [t.identityFile]
+ : ['id_rsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', 'id_ed25519_sk'].map(ssh),
+ identitiesOnly: !!t.identityFile,
+ identityAgent: t.identityAgent,
+ userKnownHostsFiles: [ssh('known_hosts'), ssh('known_hosts2')],
+ globalKnownHostsFiles: global,
+ strictHostKeyChecking: 'ask'
}
}
diff --git a/src/core/remote-ssh/native/windows-agent-discovery.test.ts b/src/core/remote-ssh/native/windows-agent-discovery.test.ts
new file mode 100644
index 000000000..ebefa0672
--- /dev/null
+++ b/src/core/remote-ssh/native/windows-agent-discovery.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest'
+import {
+ WINDOWS_OPENSSH_AGENT_PIPE,
+ findPageantPipe,
+ pickWindowsAgent,
+ resolveWindowsIdentityAgent
+} from './windows-agent-discovery'
+
+const PAGEANT = 'pageant.Dev.3f9a1c0b2e'
+
+describe('pickWindowsAgent', () => {
+ it('prefers the OpenSSH agent service', () => {
+ expect(pickWindowsAgent({ pipes: [PAGEANT, 'openssh-ssh-agent'], user: 'dev' })).toBe(WINDOWS_OPENSSH_AGENT_PIPE)
+ })
+ it('falls back to the user\'s Pageant pipe (user matched case-insensitively)', () => {
+ expect(pickWindowsAgent({ pipes: ['pageant.other.aa', PAGEANT], user: 'dev' })).toBe(`\\\\.\\pipe\\${PAGEANT}`)
+ })
+ it('another user\'s Pageant is not ours; no agent pipe at all is undefined', () => {
+ expect(pickWindowsAgent({ pipes: ['pageant.other.aa'], user: 'dev' })).toBeUndefined()
+ expect(pickWindowsAgent({ pipes: ['some-other-pipe'], user: 'dev' })).toBeUndefined()
+ expect(pickWindowsAgent({ pipes: [] })).toBeUndefined()
+ })
+ it('a user name with dots still matches', () => {
+ expect(findPageantPipe(['pageant.first.last.abc123'], 'First.Last')).toBe('\\\\.\\pipe\\pageant.first.last.abc123')
+ })
+})
+
+describe('resolveWindowsIdentityAgent', () => {
+ it('maps `IdentityAgent pageant` (any case) to the discovered pipe', () => {
+ expect(resolveWindowsIdentityAgent('pageant', [PAGEANT], 'dev')).toEqual({ agent: `\\\\.\\pipe\\${PAGEANT}` })
+ expect(resolveWindowsIdentityAgent('PAGEANT', [PAGEANT], 'dev')).toEqual({ agent: `\\\\.\\pipe\\${PAGEANT}` })
+ })
+ it('never hands back the bare string when there is no pipe (ssh2 would spawn pagent.exe)', () => {
+ expect(resolveWindowsIdentityAgent('pageant', ['openssh-ssh-agent'], 'dev')).toEqual({ agent: undefined, missing: true })
+ })
+ it('passes every other value through', () => {
+ expect(resolveWindowsIdentityAgent('none', [PAGEANT], 'dev')).toEqual({ agent: 'none' })
+ expect(resolveWindowsIdentityAgent(undefined, [PAGEANT], 'dev')).toEqual({ agent: undefined })
+ expect(resolveWindowsIdentityAgent('\\\\.\\pipe\\x', [], 'dev')).toEqual({ agent: '\\\\.\\pipe\\x' })
+ })
+})
diff --git a/src/core/remote-ssh/native/windows-agent-discovery.ts b/src/core/remote-ssh/native/windows-agent-discovery.ts
new file mode 100644
index 000000000..dcad1ff99
--- /dev/null
+++ b/src/core/remote-ssh/native/windows-agent-discovery.ts
@@ -0,0 +1,54 @@
+// Which ssh agent a Windows machine offers, decided from the named pipes it has. Pure: the caller
+// lists `\\.\pipe\` (native-runtime.ts) and passes the names in, so every rule runs on any CI leg.
+//
+// Two agents matter on Windows. The OpenSSH agent service listens on `openssh-ssh-agent`. Pageant
+// (PuTTY >= 0.75) and KeeAgent ALSO listen on an OpenSSH-protocol pipe, named
+// `pageant.<user>.<hash>` — which is the pipe we use. We deliberately do NOT hand ssh2 its own
+// `'pageant'` agent string: that spawns a bundled 32-bit `pagent.exe` helper we would have to ship
+// unpacked and sign, and it speaks the old WM_COPYDATA protocol the pipe replaced. A Pageant older
+// than 0.75 (no pipe) is therefore not supported.
+
+const PIPE_PREFIX = '\\\\.\\pipe\\'
+
+/** The Windows OpenSSH agent service's pipe. */
+export const WINDOWS_OPENSSH_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent'
+const OPENSSH_PIPE_NAME = 'openssh-ssh-agent'
+
+/** `\\.\pipe\<name>` for a bare pipe name. */
+export function pipePath(name: string): string {
+ return `${PIPE_PREFIX}${name}`
+}
+
+/** The first `pageant.<user>.<hash>` pipe belonging to `user` (case-insensitive), as a full path. */
+export function findPageantPipe(pipes: readonly string[], user: string | undefined): string | undefined {
+ const want = user?.toLowerCase()
+ const hit = pipes.find((p) => {
+ const m = /^pageant\.(.+)\.[^.]+$/i.exec(p)
+ return !!m && (!want || m[1].toLowerCase() === want)
+ })
+ return hit ? pipePath(hit) : undefined
+}
+
+/**
+ * The default agent from the pipes this machine has: the OpenSSH agent service first (it is what
+ * Windows' own ssh uses), else the user's Pageant / KeeAgent pipe. Undefined when neither exists.
+ */
+export function pickWindowsAgent(req: { pipes: readonly string[]; user?: string }): string | undefined {
+ if (req.pipes.some((p) => p.toLowerCase() === OPENSSH_PIPE_NAME)) return WINDOWS_OPENSSH_AGENT_PIPE
+ return findPageantPipe(req.pipes, req.user)
+}
+
+/**
+ * `IdentityAgent pageant` (any case) → the discovered Pageant pipe, or `{ missing: true }` when
+ * there is none — never the bare string, which ssh2 would turn into a pagent.exe spawn. Every
+ * other value passes through unchanged.
+ */
+export function resolveWindowsIdentityAgent(
+ configured: string | undefined,
+ pipes: readonly string[],
+ user: string | undefined
+): { agent: string | undefined; missing?: true } {
+ if (!configured || configured.toLowerCase() !== 'pageant') return { agent: configured }
+ const pipe = findPageantPipe(pipes, user)
+ return pipe ? { agent: pipe } : { agent: undefined, missing: true }
+}