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): ProxyJump on the Windows in-process SSH transport

enesb2e9ea064988
diff --git a/src/core/remote-ssh/native/native-jump.test.ts b/src/core/remote-ssh/native/native-jump.test.ts
new file mode 100644
index 000000000..56107881c
--- /dev/null
+++ b/src/core/remote-ssh/native/native-jump.test.ts
@@ -0,0 +1,285 @@
+// ProxyJump over the native transport, against REAL SSH protocol peers: ssh2's own Server,
+// in-process, on loopback — a target and two jump hosts, each with its own host key and its own
+// accepted client key. The jumps answer direct-tcpip (what `ssh -W` asks a bastion for) by dialing
+// the destination, so the whole chain is the real protocol end to end, on every OS the CI runs.
+
+import { describe, it, expect, beforeAll, afterAll, afterEach, beforeEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import net, { type AddressInfo } from 'net'
+import { Server, utils, type Connection } from 'ssh2'
+import { NativeMux } from './native-mux'
+import { parseSshArgv } from './ssh-argv'
+import { childArgs } from '../control-master'
+import { parseProxyJump, sshGArgs, type HostQuery, type ResolvedHost } from './ssh-config'
+import type { SshConnection } from '../../../shared/ssh'
+
+const clientKey = utils.generateKeyPairSync('ed25519') // the target accepts only this
+const jumpKey = utils.generateKeyPairSync('ed25519') // the jumps accept only this
+const strangerKey = utils.generateKeyPairSync('ed25519')
+
+interface Peer {
+ name: string
+ server: Server
+ port: number
+ hostKey: { private: string; public: string }
+ logins: number
+ live: Connection[]
+ /** direct-tcpip destinations this peer was asked for (`host:port`). */
+ forwards: string[]
+ /** Sessions allowed per connection (MaxSessions); Infinity = no limit. */
+ limit: number
+}
+
+function pubMatches(offered: { algo: string; data: Buffer }, pub: string): boolean {
+ const k = utils.parseKey(pub)
+ const one = Array.isArray(k) ? k[0] : k
+ return !(one instanceof Error) && offered.algo === one.type && offered.data.equals(one.getPublicSSH())
+}
+
+function startPeer(name: string, acceptKey: string, isJump: boolean): Promise<Peer> {
+ const hostKey = utils.generateKeyPairSync('ed25519')
+ const peer: Peer = { name, server: null as unknown as Server, port: 0, hostKey, logins: 0, live: [], forwards: [], limit: Infinity }
+ peer.server = new Server({ hostKeys: [hostKey.private] }, (client) => {
+ peer.live.push(client)
+ let open = 0
+ client.on('authentication', (ctx) => {
+ if (ctx.method !== 'publickey' || !pubMatches(ctx.key, acceptKey)) return ctx.reject(['publickey'])
+ ctx.accept()
+ })
+ client.on('ready', () => {
+ peer.logins++
+ if (isJump) {
+ client.on('tcpip', (accept, reject, info) => {
+ peer.forwards.push(`${info.destIP}:${info.destPort}`)
+ const up = net.connect(info.destPort, info.destIP)
+ up.once('error', () => reject?.())
+ up.once('connect', () => {
+ const ch = accept()
+ ch.on('close', () => up.destroy())
+ up.on('close', () => ch.close())
+ ch.pipe(up).pipe(ch)
+ })
+ })
+ }
+ client.on('session', (accept, reject) => {
+ if (open >= peer.limit) return reject()
+ open++
+ const session = accept()
+ session.on('close', () => open--)
+ session.on('exec', (a, _r, info) => {
+ const ch = a()
+ if (info.command.startsWith('hang') || info.command.startsWith('hold')) return
+ ch.write(`${name} ran: ${info.command}\n`)
+ ch.exit(0)
+ ch.end()
+ })
+ })
+ })
+ client.on('error', () => {})
+ })
+ return new Promise((r) =>
+ peer.server.listen(0, '127.0.0.1', () => {
+ peer.port = (peer.server.address() as AddressInfo).port
+ r(peer)
+ })
+ )
+}
+
+let dir: string
+let target: Peer
+let jump1: Peer
+let jump2: Peer
+/** `ssh -G` per name — what each alias resolves to. Tests edit it. */
+let config: Record<string, Partial<ResolvedHost>>
+let asked: HostQuery[]
+
+const kh = (): string => path.join(dir, 'known_hosts')
+
+function base(port: number, user: string, id: string): ResolvedHost {
+ return {
+ hostname: '127.0.0.1',
+ port,
+ user,
+ identityFiles: [path.join(dir, id)],
+ identitiesOnly: true,
+ userKnownHostsFiles: [kh()],
+ globalKnownHostsFiles: [],
+ strictHostKeyChecking: 'ask'
+ }
+}
+
+function mux(): NativeMux {
+ const m = new NativeMux({
+ defaultAgent: () => undefined,
+ resolveHost: async (q) => {
+ asked.push(q)
+ const c = config[q.host]
+ if (!c) throw new Error(`no config for ${q.host}`)
+ return { ...(c as ResolvedHost), ...(q.user ? { user: q.user } : {}), ...(q.port ? { port: q.port } : {}) }
+ }
+ })
+ muxes.push(m)
+ return m
+}
+
+const conn = (): SshConnection => ({ user: 'dev', host: 'target.test', port: target.port, identityFile: path.join(dir, 'id') })
+const CP = (): string => path.join(dir, 'cm.sock')
+const exec = (cmd: string) => {
+ const p = parseSshArgv(childArgs(conn(), CP(), cmd))
+ if (p.kind !== 'exec') throw new Error('not exec')
+ return p
+}
+
+beforeAll(async () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-native-jump-'))
+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)
+ fs.writeFileSync(path.join(dir, 'jump_id'), jumpKey.private)
+ fs.writeFileSync(path.join(dir, 'stranger_id'), strangerKey.private)
+ target = await startPeer('target', clientKey.public, false)
+ jump1 = await startPeer('jump1', jumpKey.public, true)
+ jump2 = await startPeer('jump2', jumpKey.public, true)
+})
+afterAll(() => {
+ for (const p of [target, jump1, jump2]) p.server.close()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+const muxes: NativeMux[] = []
+beforeEach(() => {
+ fs.rmSync(kh(), { force: true })
+ asked = []
+ for (const p of [target, jump1, jump2]) {
+ p.logins = 0
+ p.forwards = []
+ p.limit = Infinity
+ }
+ config = {
+ 'target.test': { ...base(target.port, 'dev', 'id'), proxyJump: 'ops@jump1' },
+ jump1: base(jump1.port, 'ops', 'jump_id'),
+ jump2: base(jump2.port, 'ops', 'jump_id')
+ }
+})
+afterEach(() => {
+ for (const m of muxes.splice(0)) m.exitAll()
+ for (const p of [target, jump1, jump2]) for (const c of p.live.splice(0)) c.end()
+})
+
+describe('NativeMux over a ProxyJump chain', () => {
+ it('reaches the target through the jump, each hop with its own identity and host key', async () => {
+ const m = mux()
+ const r = await m.exec(exec('echo hi'))
+ expect(r.stderr.toString()).toBe('')
+ expect(r.stdout.toString()).toBe('target ran: echo hi\n')
+ expect(jump1.forwards).toEqual([`127.0.0.1:${target.port}`])
+ expect(jump1.logins).toBe(1)
+ // The hop was resolved by its own `ssh -G`, with only what the spec named — never the
+ // target's -i (OpenSSH does not pass it to its jump ssh either).
+ expect(asked.find((q) => q.host === 'jump1')).toEqual({ user: 'ops', host: 'jump1', port: undefined })
+ // Both host keys were recorded, each under its own port.
+ const known = fs.readFileSync(kh(), 'utf8')
+ expect(known).toContain(`[127.0.0.1]:${jump1.port} ssh-ed25519`)
+ expect(known).toContain(`[127.0.0.1]:${target.port} ssh-ed25519`)
+ // Shared, like any master: a second command neither logs in again nor re-crosses the jump.
+ await m.exec(exec('echo again'))
+ expect(jump1.logins).toBe(1)
+ expect(jump1.forwards).toHaveLength(1)
+ })
+
+ it('refuses a CHANGED host key on the jump, before the target is ever reached', async () => {
+ fs.writeFileSync(kh(), `[127.0.0.1]:${jump1.port} ${utils.generateKeyPairSync('ed25519').public}\n`)
+ const r = await mux().exec(exec('echo hi'))
+ expect(r.code).toBe(255)
+ expect(r.stderr.toString()).toMatch(/jump host jump1: .*REMOTE HOST IDENTIFICATION HAS CHANGED/)
+ expect(target.logins).toBe(0)
+ expect(jump1.forwards).toEqual([])
+ })
+
+ it('reports an auth failure on the jump as the jump\'s', async () => {
+ config.jump1 = base(jump1.port, 'ops', 'stranger_id')
+ const r = await mux().exec(exec('echo hi'))
+ expect(r.code).toBe(255)
+ expect(r.stderr.toString()).toMatch(/jump host jump1: ops@jump1: Permission denied \(publickey\)/)
+ expect(target.logins).toBe(0)
+ })
+
+ it('a jump that drops ends the target\'s channels with 255', async () => {
+ const m = mux()
+ const pending = m.exec(exec('hang'))
+ await new Promise((r) => setTimeout(r, 150))
+ expect(m.check(CP())).toBe(true)
+ for (const c of jump1.live) c.end()
+ const d = await pending
+ expect(d.code).toBe(255)
+ await new Promise((r) => setTimeout(r, 50))
+ expect(m.check(CP())).toBe(false)
+ })
+
+ it('crosses a 2-hop chain in order, and ignores a LATER hop\'s own ProxyJump (as OpenSSH -J does)', async () => {
+ config['target.test'].proxyJump = 'jump1,ops@[127.0.0.1]:' + jump2.port
+ config['127.0.0.1'] = { ...base(jump2.port, 'ops', 'jump_id'), proxyJump: 'jump2' } // would loop if followed
+ const r = await mux().exec(exec('echo two'))
+ expect(r.stdout.toString()).toBe('target ran: echo two\n')
+ expect(jump1.forwards).toEqual([`127.0.0.1:${jump2.port}`])
+ expect(jump2.forwards).toEqual([`127.0.0.1:${target.port}`])
+ expect(jump2.logins).toBe(1)
+ })
+
+ it('follows the FIRST hop\'s own ProxyJump, and refuses a loop', async () => {
+ config['target.test'].proxyJump = 'jump2'
+ config.jump2 = { ...base(jump2.port, 'ops', 'jump_id'), proxyJump: 'jump1' }
+ const r = await mux().exec(exec('echo nested'))
+ expect(r.stdout.toString()).toBe('target ran: echo nested\n')
+ expect(jump1.forwards).toEqual([`127.0.0.1:${jump2.port}`])
+ expect(jump2.forwards).toEqual([`127.0.0.1:${target.port}`])
+
+ config.jump1 = { ...base(jump1.port, 'ops', 'jump_id'), proxyJump: 'jump2' }
+ const loop = await mux().exec(exec('echo loop'))
+ expect(loop.code).toBe(255)
+ 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'))
+ expect(r.code).toBe(255)
+ expect(r.stderr.toString()).toMatch(/ProxyCommand is not supported .*jump host jump1/)
+ })
+
+ it('overflow connections (MaxSessions spill) reuse the primary\'s jump chain', async () => {
+ target.limit = 1
+ const m = mux()
+ const a = await m.channel(exec('hold a'))
+ const b = await m.channel(exec('hold b'))
+ expect(m.connectionCount(CP())).toBe(2)
+ expect(target.logins).toBe(2)
+ expect(jump1.logins).toBe(1) // one bastion login, two forwards over it
+ expect(jump1.forwards).toHaveLength(2)
+ a.close()
+ b.close()
+ })
+})
+
+describe('parseProxyJump', () => {
+ it('reads the forms OpenSSH accepts and `ssh -G` prints', () => {
+ expect(parseProxyJump('bastion')).toEqual([{ user: undefined, host: 'bastion', port: undefined }])
+ expect(parseProxyJump('ops@bastion:2222,[10.0.0.5]:22')).toEqual([
+ { user: 'ops', host: 'bastion', port: 2222 },
+ { user: undefined, host: '10.0.0.5', port: 22 }
+ ])
+ expect(parseProxyJump('ssh://me@[::1]:22')).toEqual([{ user: 'me', host: '::1', port: 22 }])
+ expect(parseProxyJump('a@b@host')).toEqual([{ user: 'a@b', host: 'host', port: undefined }])
+ })
+
+ it('refuses what it cannot read rather than guessing', () => {
+ for (const bad of ['', 'a,,b', 'host:0', 'host:99999', 'host:x', '::1', '[::1', '-oProxyCommand=x', 'ssh://h/path', '@host']) {
+ expect(() => parseProxyJump(bad), bad).toThrow(/invalid ProxyJump/)
+ }
+ })
+
+ it('a hop is asked of `ssh -G` with only what its spec named', () => {
+ expect(sshGArgs({ host: 'bastion' })).toEqual(['-G', 'bastion'])
+ expect(sshGArgs({ user: 'ops', host: 'bastion', port: 2222 })).toEqual(['-G', '-p', '2222', '-l', 'ops', 'bastion'])
+ expect(() => sshGArgs({ host: '-oProxyCommand=x' })).toThrow()
+ })
+})
diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.ts
index f377b7b46..80c9f6c95 100644
--- a/src/core/remote-ssh/native/native-mux.ts
+++ b/src/core/remote-ssh/native/native-mux.ts
@@ -22,13 +22,19 @@
// - ServerAliveInterval/CountMax → ssh2 keepalive; ConnectTimeout bounds the TCP connect only
// (a passphrase prompt is not cut off by it, as with OpenSSH);
// - a connection that drops ends every channel on it with exit 255, which is what a mux'd
-// OpenSSH client reports and what the renderer's SshReconnector already listens for.
+// OpenSSH client reports and what the renderer's SshReconnector already listens for;
+// - 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).
import net from 'net'
+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 { ParsedSsh, ReverseForward, SshOptions, SshTarget } from './ssh-argv'
-import type { ResolvedHost } from './ssh-config'
+import { parseProxyJump, type HostQuery, type JumpSpec, type ResolvedHost } from './ssh-config'
import { acceptNewHostKey } from './known-hosts'
/** Result of one remote command, in the shape execFile callers already handle. */
@@ -42,8 +48,9 @@ export interface ExecResult {
}
export interface NativeMuxDeps {
- /** Effective config for a destination (`ssh -G`; see ssh-config.ts). */
- resolveHost(target: SshTarget): Promise<ResolvedHost>
+ /** Effective config for a destination (`ssh -G`; see ssh-config.ts). A ProxyJump hop is asked
+ * with only what its spec names (user/port may be absent — the hop's own config answers). */
+ resolveHost(target: HostQuery): Promise<ResolvedHost>
/** Ask the user for a key's passphrase; null = cancelled (or nobody answered). Absent = never
* prompt. `retry`: the previous answer was wrong. `target`: `user@host`, for the dialog. */
askPassphrase?(identityFile: string, req: { retry: boolean; target: string }): Promise<string | null>
@@ -74,6 +81,19 @@ interface Conn {
channels: number
/** The server refused a channel here (its MaxSessions): skip it until one closes. */
full: boolean
+ /** The ProxyJump chain this connection runs over, first hop first ([] = direct). An overflow
+ * connection BORROWS its primary's chain, so only the primary owns (and ends) these. */
+ jumps: Client[]
+ ownsJumps: boolean
+}
+
+/** How deep a first hop's own ProxyJump may recurse before we call it a loop. */
+const MAX_JUMP_DEPTH = 8
+
+interface Hop {
+ /** How the hop was named (alias as written), for messages and the passphrase dialog. */
+ query: HostQuery & { user: string }
+ host: ResolvedHost
}
/**
@@ -196,7 +216,9 @@ export class NativeMux {
if (extra.length >= MAX_OVERFLOW_CONNECTIONS) {
throw new Error('ssh: channel open failed: the server refused more sessions (MaxSessions)')
}
- conn = this.open(`${controlPath}#${extra.length + 1}`, primary.target, primary.options, { interactive: false })
+ // Over the primary's own jump chain (see `connect`): one bastion login per project, and the
+ // group already lives and dies with the primary, which is what owns the chain.
+ conn = this.open(`${controlPath}#${extra.length + 1}`, primary.target, primary.options, { interactive: false }, primary)
const added = conn
extra.push(added)
this.overflow.set(controlPath, extra)
@@ -413,7 +435,13 @@ export class NativeMux {
})
}
- private open(controlPath: string, target: SshTarget, options: SshOptions, mode: { interactive: boolean }): Conn {
+ private open(
+ controlPath: string,
+ target: SshTarget,
+ options: SshOptions,
+ mode: { interactive: boolean },
+ via?: Conn
+ ): Conn {
const client = new Client()
let resolveClosed!: (why: string) => void
const closed = new Promise<string>((r) => (resolveClosed = r))
@@ -427,7 +455,9 @@ export class NativeMux {
target,
options,
channels: 0,
- full: false
+ full: false,
+ jumps: [],
+ ownsJumps: false
}
let lastError = ''
client.on('error', (e: Error & { level?: string }) => {
@@ -436,6 +466,8 @@ export class NativeMux {
})
client.on('close', () => {
conn.alive = false
+ // The jump connections belong to the target connection: they end with it.
+ if (conn.ownsJumps) for (const j of conn.jumps) j.end()
if (this.conns.get(controlPath) === conn) {
this.conns.delete(controlPath)
// The group dies with its primary, as mux clients die with their ControlMaster.
@@ -453,7 +485,7 @@ export class NativeMux {
ch.on('error', () => local.destroy())
ch.pipe(local).pipe(ch)
})
- conn.ready = this.connect(client, target, options, mode).catch((e: Error) => {
+ conn.ready = this.connect(conn, target, options, mode, via).catch((e: Error) => {
conn.alive = false
client.end()
throw e
@@ -464,17 +496,109 @@ export class NativeMux {
return conn
}
- private async connect(client: Client, target: SshTarget, options: SshOptions, mode: { interactive: boolean }): Promise<void> {
+ private async connect(
+ conn: Conn,
+ target: SshTarget,
+ options: SshOptions,
+ mode: { interactive: boolean },
+ 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 (host.proxyJump) {
- throw new Error(`ssh: ProxyJump is not supported by nodeterm's Windows SSH transport yet (host ${target.host})`)
- }
const timeoutMs = (options.connectTimeout ?? host.connectTimeout ?? DEFAULT_CONNECT_TIMEOUT_MS / 1000) * 1000
- const sock = await (this.deps.connectSocket ?? defaultConnectSocket)(host.hostname, host.port, timeoutMs)
- const knownAs = host.hostKeyAlias ?? target.host
+ const connectSocket = this.deps.connectSocket ?? defaultConnectSocket
+ let sock: Duplex
+ const borrowed = via?.jumps.length ? via.jumps[via.jumps.length - 1] : undefined
+ if (borrowed && via?.alive) {
+ conn.jumps = via.jumps
+ conn.ownsJumps = false
+ sock = await forwardTo(borrowed, host.hostname, host.port)
+ } else if (host.proxyJump) {
+ const hops = await this.jumpChain(host, target.host, 0, new Set())
+ const built: Client[] = []
+ 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
+ )
+ for (let i = 0; i < hops.length; i++) {
+ const hop = hops[i]
+ const jump = new Client()
+ built.push(jump)
+ // A jump client with no 'error' listener would throw from its emitter after the handshake.
+ jump.on('error', (e: Error) => this.deps.log?.(`[native-ssh] jump ${hop.query.host}: ${e.message}`))
+ await this.handshake(jump, next, hop.query, hop.host, jumpOptions(options), mode, `jump host ${hop.query.host}: `)
+ const to = i + 1 < hops.length ? hops[i + 1].host : host
+ next = await forwardTo(jump, to.hostname, to.port)
+ }
+ sock = next
+ } catch (e) {
+ for (const j of built) j.end()
+ throw e
+ }
+ } 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())
+ try {
+ await this.handshake(conn.client, sock, target, host, options, mode, '')
+ } catch (e) {
+ if (conn.ownsJumps) for (const j of conn.jumps) j.end()
+ throw e
+ }
+ }
+
+ /**
+ * The hops to cross for `host`, first hop first, with OpenSSH's meaning: `ssh -J a,b t` runs
+ * `ssh -J a -W t b`, whose own jump is `ssh -W b a`. So every hop is resolved by ITS OWN
+ * `ssh -G` (never the target's -i, IdentitiesOnly or IdentityAgent, which OpenSSH does not pass
+ * on either), a later hop's own ProxyJump is overridden by the chain before it, and only the
+ * FIRST hop's own ProxyJump is followed — recursively, which is what OpenSSH does too.
+ */
+ private async jumpChain(host: ResolvedHost, name: string, depth: number, seen: Set<string>): Promise<Hop[]> {
+ if (depth >= MAX_JUMP_DEPTH) {
+ throw new Error(`ssh: ProxyJump chain for ${name} is deeper than ${MAX_JUMP_DEPTH} hops (a loop in ~/.ssh/config?)`)
+ }
+ const specs: JumpSpec[] = parseProxyJump(host.proxyJump ?? '')
+ const hops: Hop[] = []
+ for (const spec of specs) {
+ const resolved = await this.deps.resolveHost({ user: spec.user, host: spec.host, port: spec.port })
+ 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}`)
+ seen.add(key)
+ return [...(await this.jumpChain(first.host, first.query.host, depth + 1, seen)), ...hops]
+ }
+ return hops
+ }
+
+ /** The SSH handshake over `sock`: host key (accept-new) and publickey auth, for one hop or the target. */
+ private async handshake(
+ client: Client,
+ sock: Duplex,
+ target: HostQuery & { user: string },
+ host: ResolvedHost,
+ options: SshOptions,
+ mode: { interactive: boolean },
+ prefix: string
+ ): Promise<void> {
+ // OpenSSH checks the key under the REAL host name (HostName) unless HostKeyAlias says otherwise.
+ const knownAs = host.hostKeyAlias ?? host.hostname
let hostKeyRefusal = ''
const cancelled = { value: false }
const auth = this.authPlan(target, host, options, mode, cancelled)
@@ -495,9 +619,10 @@ export class NativeMux {
)
if (!v.accept) {
hostKeyRefusal =
- v.verdict === 'revoked'
+ prefix +
+ (v.verdict === 'revoked'
? `@@@ WARNING: REVOKED HOST KEY DETECTED FOR ${knownAs} @@@`
- : `@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@ Host key verification failed for ${knownAs}.`
+ : `@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@ Host key verification failed for ${knownAs}.`)
}
return v.accept
},
@@ -508,21 +633,30 @@ export class NativeMux {
await new Promise<void>((resolve, reject) => {
const onReady = (): void => {
client.removeListener('error', onErr)
+ client.removeListener('close', onClose)
resolve()
}
const onErr = (e: Error & { level?: string }): void => {
client.removeListener('ready', onReady)
+ client.removeListener('close', onClose)
if (hostKeyRefusal) return reject(new Error(hostKeyRefusal))
if (e.level === 'client-authentication') {
// A passphrase the user declined is the reason, not a denial by the server; say so the
// way the POSIX path does (SshProjectManager's cancelled message).
if (cancelled.value) return reject(new Error('SSH connection cancelled: this key needs its passphrase.'))
- return reject(new Error(`${target.user}@${target.host}: Permission denied (publickey).`))
+ return reject(new Error(`${prefix}${target.user}@${target.host}: Permission denied (publickey).`))
}
- reject(new Error(`ssh: ${e.message}`))
+ reject(new Error(`ssh: ${prefix}${e.message}`))
+ }
+ // A stream socket (a jump's forwarded channel) can end before the handshake with no 'error'.
+ const onClose = (): void => {
+ client.removeListener('ready', onReady)
+ client.removeListener('error', onErr)
+ reject(new Error(hostKeyRefusal || `ssh: ${prefix}connection closed during the handshake`))
}
client.once('ready', onReady)
client.once('error', onErr)
+ client.once('close', onClose)
client.connect(cfg)
})
}
@@ -533,7 +667,7 @@ export class NativeMux {
* passphrase when one is encrypted and prompting is allowed.
*/
private authPlan(
- target: SshTarget,
+ target: HostQuery & { user: string },
host: ResolvedHost,
options: SshOptions,
mode: { interactive: boolean },
@@ -672,6 +806,25 @@ export function channelExit(ch: ClientChannel): { code: number | null; signal: s
return exits.get(ch) ?? { code: null, signal: null, closed: false }
}
+/** Options for a jump hop: interactivity and keepalive follow the connection being built; nothing
+ * that names an identity does (OpenSSH does not pass -i / IdentitiesOnly to its jump ssh). */
+function jumpOptions(o: SshOptions): SshOptions {
+ return {
+ batchMode: o.batchMode,
+ serverAliveInterval: o.serverAliveInterval,
+ serverAliveCountMax: o.serverAliveCountMax
+ }
+}
+
+/** A direct-tcpip channel from `client` to host:port (`ssh -W`), used as the next hop's socket. */
+function forwardTo(client: Client, host: string, port: number): Promise<Duplex> {
+ return new Promise((resolve, reject) =>
+ client.forwardOut('127.0.0.1', 0, host, port, (err, ch) =>
+ err ? reject(new Error(`ssh: channel open failed to ${host}:${port}: ${err.message}`)) : resolve(ch)
+ )
+ )
+}
+
function fail(e: unknown): ExecResult {
const msg = e instanceof Error ? e.message : String(e)
return { code: 255, signal: null, stdout: Buffer.alloc(0), stderr: Buffer.from(msg + '\n'), timedOut: false }
diff --git a/src/core/remote-ssh/native/native-runtime.ts b/src/core/remote-ssh/native/native-runtime.ts
index aae53645f..6ba5f1db9 100644
--- a/src/core/remote-ssh/native/native-runtime.ts
+++ b/src/core/remote-ssh/native/native-runtime.ts
@@ -10,8 +10,7 @@ import fs from 'fs'
import path from 'path'
import { findExecutableSync } from '../../exec-path'
import { NativeMux, WINDOWS_OPENSSH_AGENT_PIPE, type ExecResult } from './native-mux'
-import { parseSshG, sshGArgs } from './ssh-config'
-import type { SshTarget } from './ssh-argv'
+import { parseSshG, sshGArgs, type HostQuery } from './ssh-config'
import { runSshArgv, useNativeSsh } from './native-invoke'
export { useNativeSsh }
@@ -35,11 +34,17 @@ function sshForConfig(): string {
)
}
-function resolveHost(t: SshTarget) {
+function resolveHost(t: HostQuery) {
return new Promise<ReturnType<typeof parseSshG>>((resolve, reject) => {
- execFile(sshForConfig(), sshGArgs(t), { timeout: 5_000, windowsHide: true }, (err, stdout) => {
+ 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.host}: ${err.message}`))
+ return reject(new Error(`ssh -G failed for ${t.user ? `${t.user}@` : ''}${t.host}: ${err.message}`))
}
try {
resolve(parseSshG(stdout))
diff --git a/src/core/remote-ssh/native/ssh-config.ts b/src/core/remote-ssh/native/ssh-config.ts
index de0e060e8..965ef3268 100644
--- a/src/core/remote-ssh/native/ssh-config.ts
+++ b/src/core/remote-ssh/native/ssh-config.ts
@@ -99,10 +99,85 @@ export function parseSshG(out: string, home: string = os.homedir()): ResolvedHos
}
}
+/**
+ * A destination to evaluate: a project's target (every field the argv gave), or one ProxyJump hop,
+ * which names only what its spec wrote — an absent user or port is the hop's OWN config's answer,
+ * exactly as OpenSSH's jump ssh (`ssh [-l user] [-p port] -W … hop`) resolves it.
+ */
+export interface HostQuery {
+ user?: string
+ host: string
+ port?: number
+ identityFile?: string
+ identityAgent?: string
+}
+
/** `ssh -G` argv for a destination with the same command-line overrides the transport applies. */
-export function sshGArgs(t: { user: string; host: string; port?: number; identityFile?: string }): string[] {
- const args = ['-G', '-p', String(t.port ?? 22)]
+export function sshGArgs(t: HostQuery): string[] {
+ // A destination beginning with `-` would be read as an option by ssh.
+ if (t.host.startsWith('-') || t.user?.startsWith('-')) throw new Error(`ssh: invalid destination ${t.host}`)
+ const args = ['-G']
+ if (t.port !== undefined) args.push('-p', String(t.port))
if (t.identityFile) args.push('-o', 'IdentitiesOnly=yes', '-i', t.identityFile)
- args.push(`${t.user}@${t.host}`)
+ if (t.user) args.push('-l', t.user)
+ args.push(t.host)
return args
}
+
+/** One ProxyJump hop as written: `[user@]host[:port]` or `ssh://[user@]host[:port]`. */
+export interface JumpSpec {
+ user?: string
+ host: string
+ port?: number
+}
+
+/**
+ * Parse a ProxyJump value (a comma-separated chain, first hop first) the way OpenSSH's
+ * parse_jump does. `ssh -G` prints the last hop normalized (`user@[host]:port`, numeric hosts in
+ * brackets) and the earlier ones as written, so both forms are accepted. Throws on anything else —
+ * a hop we cannot read must not be guessed at.
+ */
+export function parseProxyJump(value: string): JumpSpec[] {
+ const hops = value.split(',').map((h) => h.trim())
+ if (!hops.length || hops.some((h) => !h)) throw new Error(`ssh: invalid ProxyJump "${value}"`)
+ return hops.map((raw) => {
+ const bad = (): Error => new Error(`ssh: invalid ProxyJump hop "${raw}"`)
+ let rest = raw
+ if (/^ssh:\/\//i.test(rest)) {
+ rest = rest.slice(6)
+ if (rest.endsWith('/')) rest = rest.slice(0, -1)
+ if (rest.includes('/')) throw bad()
+ }
+ let user: string | undefined
+ const at = rest.lastIndexOf('@')
+ if (at !== -1) {
+ user = rest.slice(0, at)
+ rest = rest.slice(at + 1)
+ if (!user) throw bad()
+ }
+ let host: string
+ let portText: string | undefined
+ if (rest.startsWith('[')) {
+ const close = rest.indexOf(']')
+ if (close === -1) throw bad()
+ host = rest.slice(1, close)
+ const after = rest.slice(close + 1)
+ if (after) {
+ if (!after.startsWith(':')) throw bad()
+ portText = after.slice(1)
+ }
+ } else {
+ const colon = rest.indexOf(':')
+ if (colon !== -1 && rest.indexOf(':', colon + 1) !== -1) throw bad() // bare IPv6: needs [ ]
+ host = colon === -1 ? rest : rest.slice(0, colon)
+ portText = colon === -1 ? undefined : rest.slice(colon + 1)
+ }
+ if (!host || host.startsWith('-') || /[\s,]/.test(host) || user?.startsWith('-')) throw bad()
+ let port: number | undefined
+ if (portText !== undefined) {
+ port = Number(portText)
+ if (!/^\d+$/.test(portText) || port <= 0 || port > 65535) throw bad()
+ }
+ return { user, host, port }
+ })
+}