Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(ssh): in-process SSH transport for Windows (foundation, not wired yet)
enes126c78e3fa20
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ec026fab7..074a7a97f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,4 +71,4 @@ jobs:run: npm run host:build- 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/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+ 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.tsdiff --git a/package-lock.json b/package-lock.jsonindex 9c948ec6d..445f92369 100644--- a/package-lock.json+++ b/package-lock.json@@ -24,6 +24,7 @@"qrcode": "^1.5.4","sharp": "^0.35.4","smart-whisper": "^0.8.1",+ "ssh2": "^1.17.0","tweetnacl": "^1.0.3","ws": "^8.21.3","zustand": "^4.5.7"@@ -35,6 +36,7 @@"@types/qrcode": "^1.5.6","@types/react": "^18.3.31","@types/react-dom": "^18.3.7",+ "@types/ssh2": "^1.15.6","@types/ws": "^8.18.1","@vitejs/plugin-react": "^4.3.1","@xterm/addon-fit": "^0.11.0",@@ -1974,21 +1976,6 @@"node": ">=10"}},- "node_modules/@noble/hashes": {- "version": "2.2.0",- "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz",- "integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==",- "dev": true,- "license": "MIT",- "optional": true,- "peer": true,- "engines": {- "node": ">= 20.19.0"- },- "funding": {- "url": "https://paulmillr.com/funding/"- }- },"node_modules/@peculiar/asn1-schema": {"version": "2.9.5","resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.5.tgz",@@ -3012,6 +2999,33 @@"@types/node": "*"}},+ "node_modules/@types/ssh2": {+ "version": "1.15.6",+ "resolved": "https://registry.npmjs.org/@types/ssh2/-/ssh2-1.15.6.tgz",+ "integrity": "sha512-oGdxhBqcRTwSTKFm+9EiKzkNVYRLEFkcW44lhguvBalGJbWfGnDt/ezwSUZc+SF9m9bMc3VyklNAtp7zICjS5w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "^18.11.18"+ }+ },+ "node_modules/@types/ssh2/node_modules/@types/node": {+ "version": "18.19.130",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz",+ "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~5.26.4"+ }+ },+ "node_modules/@types/ssh2/node_modules/undici-types": {+ "version": "5.26.5",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/trusted-types": {"version": "2.0.7","resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",@@ -3886,6 +3900,15 @@"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==","license": "Python-2.0"},+ "node_modules/asn1": {+ "version": "0.2.6",+ "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",+ "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": "~2.1.0"+ }+ },"node_modules/asn1js": {"version": "3.0.10","resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",@@ -3996,6 +4019,21 @@"node": ">=6.0.0"}},+ "node_modules/bcrypt-pbkdf": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",+ "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "tweetnacl": "^0.14.3"+ }+ },+ "node_modules/bcrypt-pbkdf/node_modules/tweetnacl": {+ "version": "0.14.5",+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",+ "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",+ "license": "Unlicense"+ },"node_modules/bidi-js": {"version": "1.0.3","resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",@@ -4076,6 +4114,15 @@"dev": true,"license": "MIT"},+ "node_modules/buildcheck": {+ "version": "0.0.7",+ "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",+ "integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",+ "optional": true,+ "engines": {+ "node": ">=10.0.0"+ }+ },"node_modules/builder-util": {"version": "26.16.0","resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.16.0.tgz",@@ -4375,6 +4422,20 @@"dev": true,"license": "MIT"},+ "node_modules/cpu-features": {+ "version": "0.0.10",+ "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",+ "integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",+ "hasInstallScript": true,+ "optional": true,+ "dependencies": {+ "buildcheck": "~0.0.6",+ "nan": "^2.19.0"+ },+ "engines": {+ "node": ">=10.0.0"+ }+ },"node_modules/cross-dirname": {"version": "0.1.0","resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",@@ -7084,6 +7145,13 @@"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/nan": {+ "version": "2.29.0",+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.29.0.tgz",+ "integrity": "sha512-GlGk3HIvitbvs+LT3g6XUP1kpirKNvmDFwF/bmo6XNWSb/eYEs/O4bfgIEIXCZ+lIOTS5xNwDvSGMw6FJdAhtA==",+ "license": "MIT",+ "optional": true+ },"node_modules/nanoid": {"version": "3.3.18","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",@@ -7971,6 +8039,12 @@"dev": true,"license": "MIT"},+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },"node_modules/sanitize-filename": {"version": "1.6.4","resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz",@@ -8210,6 +8284,23 @@"license": "BSD-3-Clause","optional": true},+ "node_modules/ssh2": {+ "version": "1.17.0",+ "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",+ "integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",+ "hasInstallScript": true,+ "dependencies": {+ "asn1": "^0.2.6",+ "bcrypt-pbkdf": "^1.0.2"+ },+ "engines": {+ "node": ">=10.16.0"+ },+ "optionalDependencies": {+ "cpu-features": "~0.0.10",+ "nan": "^2.23.0"+ }+ },"node_modules/stackback": {"version": "0.0.2","resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",diff --git a/package.json b/package.jsonindex a10fdc6b0..1a94efb40 100644--- a/package.json+++ b/package.json@@ -186,6 +186,7 @@"qrcode": "^1.5.4","sharp": "^0.35.4","smart-whisper": "^0.8.1",+ "ssh2": "^1.17.0","tweetnacl": "^1.0.3","ws": "^8.21.3","zustand": "^4.5.7"@@ -197,6 +198,7 @@"@types/qrcode": "^1.5.6","@types/react": "^18.3.31","@types/react-dom": "^18.3.7",+ "@types/ssh2": "^1.15.6","@types/ws": "^8.18.1","@vitejs/plugin-react": "^4.3.1","@xterm/addon-fit": "^0.11.0",diff --git a/src/core/remote-ssh/native/known-hosts.test.ts b/src/core/remote-ssh/native/known-hosts.test.tsnew file mode 100644index 000000000..aede590d0--- /dev/null+++ b/src/core/remote-ssh/native/known-hosts.test.ts@@ -0,0 +1,136 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { createHmac, randomBytes } from 'crypto'+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ acceptNewHostKey,+ hostPatternsMatch,+ keyTypeOfBlob,+ knownHostsName,+ verifyHostKey+} from './known-hosts'+import { parseSshG, expandHomePath } from './ssh-config'++/** A wire-format public key blob: string keytype, then opaque key material. */+function blob(type: string, fill: number): Buffer {+ const t = Buffer.from(type)+ const len = Buffer.alloc(4)+ len.writeUInt32BE(t.length)+ return Buffer.concat([len, t, Buffer.alloc(32, fill)])+}+const ED_A = blob('ssh-ed25519', 1)+const ED_B = blob('ssh-ed25519', 2)+const RSA = blob('ssh-rsa', 3)+const line = (hosts: string, b: Buffer, marker = ''): string =>+ `${marker ? marker + ' ' : ''}${hosts} ${keyTypeOfBlob(b)} ${b.toString('base64')}`+const hashed = (name: string): string => {+ const salt = randomBytes(20)+ return `|1|${salt.toString('base64')}|${createHmac('sha1', salt).update(name).digest('base64')}`+}++describe('known_hosts matching (OpenSSH semantics)', () => {+ it('names a non-22 port the way ssh records it', () => {+ expect(knownHostsName('h', 22)).toBe('h')+ expect(knownHostsName('h', 2222)).toBe('[h]:2222')+ })++ it('matches plain, wildcard, negated and hashed patterns', () => {+ expect(hostPatternsMatch('a.example,b.example', 'b.example')).toBe(true)+ expect(hostPatternsMatch('*.example', 'x.example')).toBe(true)+ expect(hostPatternsMatch('*.example,!bad.example', 'bad.example')).toBe(false)+ expect(hostPatternsMatch(hashed('[h]:2222'), '[h]:2222')).toBe(true)+ expect(hostPatternsMatch(hashed('[h]:2222'), 'h')).toBe(false)+ })++ it('match / mismatch / unknown / revoked', () => {+ const file = [line('h', ED_A), line(hashed('[k]:22022'), RSA)].join('\n')+ expect(verifyHostKey([file], 'h', ED_A)).toBe('match')+ expect(verifyHostKey([file], 'h', ED_B)).toBe('mismatch')+ // A different key TYPE for a known host is not a mismatch (hosts serve several types).+ expect(verifyHostKey([file], 'h', RSA)).toBe('unknown')+ expect(verifyHostKey([file], 'other', ED_A)).toBe('unknown')+ expect(verifyHostKey([file], '[k]:22022', RSA)).toBe('match')+ const revoked = [file, line('*', ED_A, '@revoked')].join('\n')+ expect(verifyHostKey([revoked], 'h', ED_A)).toBe('revoked')+ })++ it('ignores @cert-authority lines — they can only leave a host unknown', () => {+ expect(verifyHostKey([line('*', ED_A, '@cert-authority')], 'h', ED_A)).toBe('unknown')+ })+})++describe('acceptNewHostKey (StrictHostKeyChecking=accept-new)', () => {+ let dir: string+ let user: string+ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-kh-'))+ user = path.join(dir, 'sub', 'known_hosts')+ })+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }))++ it('records a first-seen host and accepts it; a changed key is then refused', () => {+ const policy = { userFiles: [user], globalFiles: [] }+ expect(acceptNewHostKey(policy, 'h', 2222, ED_A)).toEqual({ accept: true, verdict: 'unknown' })+ expect(fs.readFileSync(user, 'utf8')).toBe(`[h]:2222 ssh-ed25519 ${ED_A.toString('base64')}\n`)+ expect(acceptNewHostKey(policy, 'h', 2222, ED_A)).toEqual({ accept: true, verdict: 'match' })+ expect(acceptNewHostKey(policy, 'h', 2222, ED_B)).toEqual({ accept: false, verdict: 'mismatch' })+ })++ it('appends without rewriting what another ssh wrote', () => {+ fs.mkdirSync(path.dirname(user), { recursive: true })+ fs.writeFileSync(user, 'x ssh-ed25519 AAAA') // no trailing newline+ acceptNewHostKey({ userFiles: [user], globalFiles: [] }, 'h', 22, ED_A)+ expect(fs.readFileSync(user, 'utf8').split('\n')).toEqual([+ 'x ssh-ed25519 AAAA',+ `h ssh-ed25519 ${ED_A.toString('base64')}`,+ ''+ ])+ })++ it('a global file counts as known', () => {+ const global = path.join(dir, 'global')+ fs.writeFileSync(global, line('h', ED_A) + '\n')+ expect(acceptNewHostKey({ userFiles: [user], globalFiles: [global] }, 'h', 22, ED_B).verdict).toBe('mismatch')+ })+})++describe('parseSshG', () => {+ it('reads the fields the transport needs, expanding ~', () => {+ const out = [+ 'user root',+ 'hostname 95.217.38.239',+ 'port 22',+ 'identitiesonly no',+ 'stricthostkeychecking ask',+ 'identityfile ~/.ssh/id_rsa',+ 'identityfile ~/.ssh/id_ed25519',+ 'userknownhostsfile ~/.ssh/known_hosts ~/.ssh/known_hosts2',+ 'globalknownhostsfile /etc/ssh/ssh_known_hosts',+ 'proxyjump none',+ 'connecttimeout none',+ 'identityagent SSH_AUTH_SOCK'+ ].join('\n')+ const r = parseSshG(out, '/home/me')+ expect(r).toMatchObject({+ hostname: '95.217.38.239',+ user: 'root',+ port: 22,+ identitiesOnly: false,+ identityFiles: [path.join('/home/me', '.ssh/id_rsa'), path.join('/home/me', '.ssh/id_ed25519')],+ userKnownHostsFiles: [path.join('/home/me', '.ssh/known_hosts'), path.join('/home/me', '.ssh/known_hosts2')],+ globalKnownHostsFiles: ['/etc/ssh/ssh_known_hosts'],+ identityAgent: 'SSH_AUTH_SOCK'+ })+ expect(r.proxyJump).toBeUndefined()+ expect(r.connectTimeout).toBeUndefined()+ })++ it('refuses output with no host/user', () => {+ expect(() => parseSshG('port 22')).toThrow()+ })++ it('expands a Windows-style home prefix too', () => {+ expect(expandHomePath('~\\.ssh\\id', 'C:\\Users\\me')).toBe(path.join('C:\\Users\\me', '.ssh\\id'))+ })+})diff --git a/src/core/remote-ssh/native/known-hosts.ts b/src/core/remote-ssh/native/known-hosts.tsnew file mode 100644index 000000000..2d61c7d67--- /dev/null+++ b/src/core/remote-ssh/native/known-hosts.ts@@ -0,0 +1,185 @@+// known_hosts for the in-process transport, with the semantics the argv builders ask OpenSSH for:+// `StrictHostKeyChecking=accept-new` — a host never seen before is recorded and accepted; a host+// whose recorded key CHANGED is refused (the MITM case), and so is a key marked @revoked.+//+// The file format is OpenSSH's (sshd(8) "SSH_KNOWN_HOSTS FILE FORMAT"), read from the same files+// `ssh -G` reports (userknownhostsfile + globalknownhostsfile), so a host the user already trusts+// with their own ssh is trusted here, and one we record is trusted by their ssh too:+// [@marker] host-patterns keytype base64-key [comment]+// Host patterns are comma-separated; `[host]:port` for a non-22 port; `*`/`?` wildcards; `!`+// negation; `|1|salt|hmac` for HashKnownHosts entries (HMAC-SHA1 of the name, keyed by the salt).+// @cert-authority lines are ignored (the native transport does not do host certificates), which+// can only make a host look UNKNOWN, never trusted.++import { createHmac } from 'crypto'+import fs from 'fs'+import path from 'path'++export type HostKeyVerdict = 'match' | 'mismatch' | 'revoked' | 'unknown'++/** The key type out of an ssh wire-format public key blob (`string keytype` comes first). */+export function keyTypeOfBlob(blob: Buffer): string | null {+ if (blob.length < 4) return null+ const n = blob.readUInt32BE(0)+ if (n <= 0 || 4 + n > blob.length || n > 64) return null+ return blob.subarray(4, 4 + n).toString('latin1')+}++/** The name a host is looked up under: bare for port 22, `[host]:port` otherwise. */+export function knownHostsName(host: string, port: number): string {+ return port === 22 ? host : `[${host}]:${port}`+}++function globMatch(pattern: string, name: string): boolean {+ let re = '^'+ for (const ch of pattern) {+ if (ch === '*') re += '.*'+ else if (ch === '?') re += '.'+ else re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&')+ }+ return new RegExp(re + '$', 'i').test(name)+}++function hashedMatch(entry: string, name: string): boolean {+ // |1|base64(salt)|base64(hmac-sha1(salt, name))+ const parts = entry.split('|')+ if (parts.length !== 4 || parts[1] !== '1') return false+ try {+ const salt = Buffer.from(parts[2], 'base64')+ const want = Buffer.from(parts[3], 'base64')+ const got = createHmac('sha1', salt).update(name).digest()+ return got.length === want.length && got.equals(want)+ } catch {+ return false+ }+}++/** Whether a host-patterns field matches `name` (a negated match anywhere wins, as in OpenSSH). */+export function hostPatternsMatch(field: string, name: string): boolean {+ if (field.startsWith('|')) return hashedMatch(field, name)+ let hit = false+ for (const raw of field.split(',')) {+ if (!raw) continue+ const neg = raw.startsWith('!')+ const pat = neg ? raw.slice(1) : raw+ if (globMatch(pat, name)) {+ if (neg) return false+ hit = true+ }+ }+ return hit+}++interface Entry {+ marker?: string+ hosts: string+ keyType: string+ key: Buffer+}++export function parseKnownHosts(text: string): Entry[] {+ const out: Entry[] = []+ for (const raw of text.split(/\r?\n/)) {+ const line = raw.trim()+ if (!line || line.startsWith('#')) continue+ const f = line.split(/\s+/)+ let i = 0+ let marker: string | undefined+ if (f[0].startsWith('@')) marker = f[i++]+ const hosts = f[i++]+ const keyType = f[i++]+ const b64 = f[i++]+ if (!hosts || !keyType || !b64) continue+ let key: Buffer+ try {+ key = Buffer.from(b64, 'base64')+ } catch {+ continue+ }+ if (key.length === 0) continue+ out.push({ marker, hosts, keyType, key })+ }+ return out+}++/**+ * The verdict for `blob` presented by `name` (already in knownHostsName form), across all files.+ * Order of precedence follows OpenSSH: a matching @revoked key refuses; a matching key accepts;+ * a recorded key of the SAME type that differs is a mismatch; otherwise the host is unknown.+ * A different key TYPE for a known host is "unknown", not a mismatch — OpenSSH offers the types it+ * has on record first, and a host that genuinely serves several types records each separately.+ */+export function verifyHostKey(texts: string[], name: string, blob: Buffer): HostKeyVerdict {+ const type = keyTypeOfBlob(blob)+ let sawSameTypeDifferent = false+ let matched = false+ for (const text of texts) {+ for (const e of parseKnownHosts(text)) {+ if (e.marker === '@cert-authority') continue+ if (!hostPatternsMatch(e.hosts, name)) continue+ if (e.marker === '@revoked') {+ if (e.key.equals(blob)) return 'revoked'+ continue+ }+ if (e.key.equals(blob)) matched = true+ else if (e.keyType === type) sawSameTypeDifferent = true+ }+ }+ if (matched) return 'match'+ return sawSameTypeDifferent ? 'mismatch' : 'unknown'+}++function readIfPresent(p: string): string {+ try {+ return fs.readFileSync(p, 'utf8')+ } catch {+ return ''+ }+}++/** The line `accept-new` appends for a first-seen host. */+export function knownHostsLine(name: string, blob: Buffer): string | null {+ const type = keyTypeOfBlob(blob)+ if (!type) return null+ return `${name} ${type} ${blob.toString('base64')}`+}++export interface HostKeyPolicy {+ userFiles: string[]+ globalFiles: string[]+}++/**+ * The accept-new decision, with the file side effects: an unknown key is appended to the FIRST+ * user known_hosts file (created with its directory, 0600/0700 — ssh's own modes) and accepted;+ * a match accepts; mismatch / revoked refuse. Returns the verdict that decided it so the caller+ * can name the reason in the connection error.+ */+export function acceptNewHostKey(+ policy: HostKeyPolicy,+ host: string,+ port: number,+ blob: Buffer+): { accept: boolean; verdict: HostKeyVerdict } {+ const name = knownHostsName(host, port)+ const texts = [...policy.userFiles, ...policy.globalFiles].map(readIfPresent)+ const verdict = verifyHostKey(texts, name, blob)+ if (verdict === 'match') return { accept: true, verdict }+ if (verdict !== 'unknown') return { accept: false, verdict }+ const line = knownHostsLine(name, blob)+ const file = policy.userFiles[0]+ if (!line || !file) return { accept: false, verdict }+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })+ const existing = readIfPresent(file)+ const sep = existing && !existing.endsWith('\n') ? '\n' : ''+ // An append, not a rewrite: other ssh processes read and append to this file concurrently,+ // and replacing it would lose a line one of them wrote in between.+ fs.appendFileSync(file, `${sep}${line}\n`, { mode: 0o600 })+ } catch {+ // Could not record it. OpenSSH's accept-new warns ("Failed to add the host to the list of+ // known hosts") and connects anyway; the transport must mean the same thing, so it does too —+ // the next connection simply asks again.+ }+ return { accept: true, verdict }+}diff --git a/src/core/remote-ssh/native/native-invoke.test.ts b/src/core/remote-ssh/native/native-invoke.test.tsnew file mode 100644index 000000000..eff48f5e1--- /dev/null+++ b/src/core/remote-ssh/native/native-invoke.test.ts@@ -0,0 +1,161 @@+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import net, { type AddressInfo } from 'net'+import path from 'path'+import { Server, utils, type Connection } from 'ssh2'+import { NativeMux } from './native-mux'+import { runSshArgv, startNativeMaster, useNativeSsh } from './native-invoke'+import {+ checkMasterArgs,+ childArgs,+ exitMasterArgs,+ hookForwardArgs,+ hookForwardCancelArgs,+ masterArgs+} from '../control-master'+import type { SshConnection } from '../../../shared/ssh'++const hostKey = utils.generateKeyPairSync('ed25519')+const clientKey = utils.generateKeyPairSync('ed25519')++let dir: string+let server: Server+let port: number+let clients: Connection[] = []+/** Remote socket path → the server-side client that asked for it (to push a connection back). */+const streamForwards = new Map<string, Connection>()++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-native-inv-'))+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)+ server = new Server({ hostKeys: [hostKey.private] }, (client) => {+ clients.push(client)+ client.on('authentication', (ctx) => (ctx.method === 'publickey' ? ctx.accept() : ctx.reject(['publickey'])))+ client.on('ready', () => {+ // @types/ssh2 only types the tcpip names, but the server does emit the OpenSSH streamlocal ones.+ client.on('request', (accept, reject, rawName, info) => {+ const name = rawName as string+ const socketPath = (info as unknown as { socketPath?: string }).socketPath+ if (name === '[email protected]' && socketPath) {+ streamForwards.set(socketPath, client)+ return accept?.()+ }+ if (name === '[email protected]' && socketPath) {+ streamForwards.delete(socketPath)+ return accept?.()+ }+ reject?.()+ })+ client.on('session', (accept) => {+ accept().on('exec', (a, _r, info) => {+ const ch = a()+ ch.write(`ran: ${info.command}\n`)+ ch.exit(0)+ ch.end()+ })+ })+ })+ client.on('error', () => {})+ })+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()))+ port = (server.address() as AddressInfo).port+})+afterAll(() => {+ server.close()+ fs.rmSync(dir, { recursive: true, force: true })+})+const muxes: NativeMux[] = []+afterEach(() => {+ for (const m of muxes.splice(0)) m.exitAll()+ for (const c of clients.splice(0)) c.end()+})++function mux(): NativeMux {+ const m = new NativeMux({+ defaultAgent: () => undefined,+ resolveHost: async () => ({+ hostname: '127.0.0.1',+ port,+ user: 'dev',+ identityFiles: [path.join(dir, 'id')],+ identitiesOnly: true,+ userKnownHostsFiles: [path.join(dir, 'known_hosts')],+ globalKnownHostsFiles: [],+ strictHostKeyChecking: 'ask'+ })+ })+ muxes.push(m)+ return m+}+const conn = (): SshConnection => ({ user: 'dev', host: '127.0.0.1', port, identityFile: path.join(dir, 'id') })+const CP = (): string => path.join(dir, 'cm.sock')++describe('native-invoke', () => {+ it('useNativeSsh: always on win32, opt-in elsewhere, opt-out anywhere', () => {+ expect(useNativeSsh('win32', {})).toBe(true)+ expect(useNativeSsh('darwin', {})).toBe(false)+ expect(useNativeSsh('linux', { NODETERM_NATIVE_SSH: '1' })).toBe(true)+ expect(useNativeSsh('win32', { NODETERM_NATIVE_SSH: '0' })).toBe(false)+ })++ it('a master pseudo-process: -O check answers once it is up, -O exit ends it and it "exits"', async () => {+ const m = mux()+ expect((await runSshArgv(m, checkMasterArgs(conn(), CP()))).code).toBe(255)+ const master = startNativeMaster(m, masterArgs(conn(), CP()))+ const exitCode = new Promise<number | null>((r) => master.on('exit', r))+ for (let i = 0; i < 100 && (await runSshArgv(m, checkMasterArgs(conn(), CP()))).code !== 0; i++) {+ await new Promise((r) => setTimeout(r, 20))+ }+ const check = await runSshArgv(m, checkMasterArgs(conn(), CP()))+ expect(check.code).toBe(0)+ expect(check.stderr.toString()).toMatch(/Master running/)+ const r = await runSshArgv(m, childArgs(conn(), CP(), 'uname'))+ expect(r.stdout.toString()).toBe('ran: uname\n')+ expect((await runSshArgv(m, exitMasterArgs(conn(), CP()))).code).toBe(0)+ expect(await exitCode).toBe(255)+ expect(master.exited()).toBe(true)+ })++ it('a master that cannot authenticate exits with the reason on stderr', async () => {+ const m = mux()+ const bad: SshConnection = { ...conn(), identityFile: path.join(dir, 'missing') }+ const master = startNativeMaster(m, masterArgs(bad, CP()))+ await new Promise<void>((r) => master.on('exit', () => r()))+ expect(master.stderr()).toMatch(/Permission denied/)+ })++ it('-O forward carries a remote unix-socket connection to the local TCP port; -O cancel removes it', async () => {+ const got: string[] = []+ const local = net.createServer((s) => s.on('data', (d) => got.push(d.toString())))+ await new Promise<void>((r) => local.listen(0, '127.0.0.1', () => r()))+ const localPort = (local.address() as AddressInfo).port+ try {+ const m = mux()+ await runSshArgv(m, childArgs(conn(), CP(), 'true')) // bring the shared connection up+ const remoteSock = '/home/dev/.nodeterm/hook-test.sock'+ expect((await runSshArgv(m, hookForwardArgs(conn(), CP(), remoteSock, localPort))).code).toBe(0)+ const srv = streamForwards.get(remoteSock)+ expect(srv).toBeDefined()+ await new Promise<void>((resolve, reject) =>+ srv!.openssh_forwardOutStreamLocal(remoteSock, (err, ch) => {+ if (err) return reject(err)+ ch.end('POST /hook')+ resolve()+ })+ )+ for (let i = 0; i < 50 && got.join('') !== 'POST /hook'; i++) await new Promise((r) => setTimeout(r, 20))+ expect(got.join('')).toBe('POST /hook')+ expect((await runSshArgv(m, hookForwardCancelArgs(conn(), CP(), remoteSock, localPort))).code).toBe(0)+ expect(streamForwards.has(remoteSock)).toBe(false)+ } finally {+ local.close()+ }+ })++ it('an argv the parser refuses is a named exit 255, not a guess', async () => {+ const r = await runSshArgv(mux(), ['-L', '1:h:2', '[email protected]'])+ expect(r.code).toBe(255)+ expect(r.stderr.toString()).toMatch(/unsupported ssh argument -L/)+ })+})diff --git a/src/core/remote-ssh/native/native-invoke.ts b/src/core/remote-ssh/native/native-invoke.tsnew file mode 100644index 000000000..820301b63--- /dev/null+++ b/src/core/remote-ssh/native/native-invoke.ts@@ -0,0 +1,175 @@+// The seam between "an ssh/scp argv this app built" and the in-process transport. Every runner+// that used to hand an argv to the ssh binary can hand it here instead and get the answer in the+// shape it already handles: `-O` ops answer like OpenSSH's control client, a command answers like+// execFile, a master looks like the spawned master process the manager watches.+//+// WHEN it is used is one decision, `useNativeSsh()`: always on Windows (where OpenSSH cannot+// multiplex — see native-mux.ts), and on POSIX only when NODETERM_NATIVE_SSH=1 asks for it, which+// exists so the transport can be exercised end to end against a real host from a Mac or Linux+// desktop. It is read at call time, never cached, so a test can flip it.++import { EventEmitter } from 'events'+import fs from 'fs'+import path from 'path'+import type { SFTPWrapper } from 'ssh2'+import { NativeMux, noMasterMessage, type ExecResult } from './native-mux'+import { parseScpArgv, parseSshArgv, type ParsedSsh } from './ssh-argv'++export function useNativeSsh(+ platform: NodeJS.Platform = process.platform,+ env: NodeJS.ProcessEnv = process.env+): boolean {+ if (env.NODETERM_NATIVE_SSH === '0') return false+ return platform === 'win32' || env.NODETERM_NATIVE_SSH === '1'+}++/**+ * Run any non-master ssh argv: `-O check|exit|forward|cancel` or a command. Never throws; an+ * argv the parser refuses is exit 255 with the reason on stderr, so a new flag in a builder shows+ * up as a named failure rather than as a command run with a different meaning.+ */+export async function runSshArgv(+ mux: NativeMux,+ argv: string[],+ io: { stdin?: string | Buffer; timeoutMs?: number } = {}+): Promise<ExecResult> {+ let p: ParsedSsh+ try {+ p = parseSshArgv(argv)+ } catch (e) {+ return result(255, '', `${(e as Error).message}\n`)+ }+ if (p.kind === 'master') {+ return result(255, '', 'native ssh transport: a master is started with startNativeMaster, not run\n')+ }+ if (p.kind === 'exec') return mux.exec(p, io)+ const cp = p.options.controlPath+ if (!cp) return result(255, '', 'native ssh transport: -O without a ControlPath\n')+ switch (p.op) {+ case 'check':+ return mux.check(cp) ? result(0, '', 'Master running (pid=0)\n') : result(255, '', `${noMasterMessage(cp)}\n`)+ case 'exit':+ return (await mux.exit(cp)) ? result(0, '', 'Exit request sent.\n') : result(255, '', `${noMasterMessage(cp)}\n`)+ case 'forward':+ try {+ await mux.forward(cp, p.forward)+ return result(0, '', '')+ } catch (e) {+ return result(255, '', `${(e as Error).message}\n`)+ }+ case 'cancel':+ await mux.cancel(cp, p.forward)+ return result(0, '', '')+ }+}++/** What SshProjectManager watches for a spawned master process (Runners.spawnMaster). */+export interface NativeMasterHandle {+ kill(): void+ on(event: 'exit', cb: (code: number | null) => void): void+ stderr(): string+ exited(): boolean+ pid(): number | undefined+}++/**+ * `ssh -M -N …` as a pseudo-process: "exits" when the connection fails to come up or later drops,+ * with the reason on stderr (the manager reads its last line as the user-facing error, exactly as+ * it reads a real master's). `-O check` answers true from the moment it is authenticated.+ */+export function startNativeMaster(mux: NativeMux, argv: string[]): NativeMasterHandle {+ const events = new EventEmitter()+ let stderr = ''+ let exited = false+ const finish = (code: number | null, why: string): void => {+ if (exited) return+ exited = true+ if (why) stderr += why.endsWith('\n') ? why : `${why}\n`+ events.emit('exit', code)+ }+ let controlPath: string | undefined+ try {+ const p = parseSshArgv(argv)+ if (p.kind !== 'master' || !p.options.controlPath) throw new Error('native ssh transport: not a master argv')+ controlPath = p.options.controlPath+ mux.master(controlPath, p.target, p.options).then(+ ({ closed }) => void closed.then((why) => finish(255, why)),+ (e: Error) => finish(255, e.message)+ )+ } catch (e) {+ // Report on the next tick, as a failed spawn does, so the caller's listeners are attached.+ queueMicrotask(() => finish(255, (e as Error).message))+ }+ return {+ kill: () => {+ if (controlPath) void mux.exit(controlPath)+ },+ on: (_ev, cb) => void events.on('exit', cb),+ stderr: () => stderr,+ exited: () => exited,+ // No OS process. The manager only uses the pid to correlate askpass prompts, which the native+ // transport raises itself.+ pid: () => undefined+ }+}++/**+ * The scp argv scpArgs / scpDownArgs build, over SFTP on the shared connection. Files and (for a+ * download) directory trees; a recursive UPLOAD is not something any builder produces.+ */+export async function runScpArgv(mux: NativeMux, argv: string[]): Promise<{ code: number; stderr: string }> {+ let p: ReturnType<typeof parseScpArgv>+ try {+ p = parseScpArgv(argv)+ } catch (e) {+ return { code: 1, stderr: (e as Error).message }+ }+ const cp = p.options.controlPath+ try {+ const sftp = await mux.sftp(cp, p.target, p.options)+ try {+ const remote = await realRemotePath(sftp, p.remotePath)+ if (p.direction === 'up') {+ if (p.recursive) throw new Error('scp: recursive upload is not supported')+ await promisify<void>((cb) => sftp.fastPut(p.localPath, remote, cb))+ } else {+ await download(sftp, remote, p.localPath, p.recursive)+ }+ return { code: 0, stderr: '' }+ } finally {+ sftp.end()+ }+ } catch (e) {+ return { code: 1, stderr: (e as Error).message }+ }+}++/** scp's remote path semantics: relative to the login directory (remoteScpPath already turned `~/x` into `x`). */+async function realRemotePath(sftp: SFTPWrapper, p: string): Promise<string> {+ if (p.startsWith('/')) return p+ const home = await promisify<string>((cb) => sftp.realpath('.', cb))+ return p === '' || p === '.' ? home : `${home.replace(/\/$/, '')}/${p}`+}++async function download(sftp: SFTPWrapper, remote: string, local: string, recursive: boolean): Promise<void> {+ const st = await promisify<{ isDirectory(): boolean }>((cb) => sftp.stat(remote, cb))+ if (!st.isDirectory()) {+ await promisify<void>((cb) => sftp.fastGet(remote, local, cb))+ return+ }+ if (!recursive) throw new Error(`scp: ${remote}: not a regular file`)+ fs.mkdirSync(local, { recursive: true })+ const entries = await promisify<{ filename: string }[]>((cb) => sftp.readdir(remote, cb))+ for (const e of entries) {+ if (e.filename === '.' || e.filename === '..') continue+ await download(sftp, `${remote}/${e.filename}`, path.join(local, e.filename), true)+ }+}++function promisify<T>(fn: (cb: (err: Error | null | undefined, v: T) => void) => void): Promise<T> {+ return new Promise((resolve, reject) => fn((err, v) => (err ? reject(err) : resolve(v))))+}++function result(code: number, stdout: string, stderr: string): ExecResult {+ return { code, signal: null, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr), timedOut: false }+}diff --git a/src/core/remote-ssh/native/native-mux.test.ts b/src/core/remote-ssh/native/native-mux.test.tsnew file mode 100644index 000000000..6505c191b--- /dev/null+++ b/src/core/remote-ssh/native/native-mux.test.ts@@ -0,0 +1,239 @@+// The native transport against a REAL SSH protocol peer: ssh2's own Server, in-process, on+// loopback. No sshd, no Docker, so it runs identically on the macOS, Linux and windows-latest CI+// legs — which is the point: this transport exists for Windows.++import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { AddressInfo } from 'net'+import { Server, utils, type Connection } from 'ssh2'+import { NativeMux, noMasterMessage } from './native-mux'+import { parseSshArgv } from './ssh-argv'+import { childArgs, masterRoundTripArgs, remoteTmuxPtyArgs } from '../control-master'+import type { ResolvedHost } from './ssh-config'+import type { SshConnection } from '../../../shared/ssh'++const hostKey = utils.generateKeyPairSync('ed25519')+const otherHostKey = utils.generateKeyPairSync('ed25519')+const clientKey = utils.generateKeyPairSync('ed25519')+const lockedKey = utils.generateKeyPairSync('ed25519', { passphrase: 'open sesame', cipher: 'aes256-cbc', rounds: 4 })++let dir: string+let server: Server+let port: number+let connections = 0+let live: Connection[] = []+let serverHostKey = hostKey.private++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 startServer(): Promise<void> {+ server = new Server({ hostKeys: [serverHostKey] }, (client) => {+ connections+++ live.push(client)+ client.on('authentication', (ctx) => {+ if (ctx.method !== 'publickey') return ctx.reject(['publickey'])+ const ok = pubMatches(ctx.key, clientKey.public) || pubMatches(ctx.key, lockedKey.public)+ if (!ok) return ctx.reject(['publickey'])+ if (!ctx.signature) return ctx.accept() // key-ok probe+ ctx.accept()+ })+ client.on('ready', () => {+ client.on('session', (accept) => {+ const session = accept()+ let ptyInfo: { cols: number; rows: number } | undefined+ session.on('pty', (acceptPty, _reject, info) => {+ ptyInfo = { cols: info.cols, rows: info.rows }+ acceptPty?.()+ })+ session.on('exec', (acceptExec, _reject, info) => {+ const ch = acceptExec()+ const cmd = info.command+ if (cmd === 'cat') {+ const chunks: Buffer[] = []+ ch.on('data', (d: Buffer) => chunks.push(d))+ ch.on('end', () => {+ ch.write(Buffer.concat(chunks))+ ch.exit(0)+ ch.end()+ })+ return+ }+ if (cmd === 'hang') return // never answers+ if (cmd.startsWith('fail ')) {+ ch.stderr.write('boom\n')+ ch.exit(Number(cmd.slice(5)))+ return ch.end()+ }+ if (ptyInfo) ch.write(`pty ${ptyInfo.cols}x${ptyInfo.rows}\r\n`)+ ch.write(`ran: ${cmd}\n`)+ ch.exit(0)+ ch.end()+ })+ })+ })+ client.on('error', () => {})+ })+ return new Promise((r) =>+ server.listen(0, '127.0.0.1', () => {+ port = (server.address() as AddressInfo).port+ r()+ })+ )+}++function host(): ResolvedHost {+ return {+ hostname: '127.0.0.1',+ port,+ user: 'dev',+ identityFiles: [path.join(dir, 'id')],+ identitiesOnly: true,+ userKnownHostsFiles: [path.join(dir, 'known_hosts')],+ globalKnownHostsFiles: [],+ strictHostKeyChecking: 'ask'+ }+}++function mux(extra: Partial<ConstructorParameters<typeof NativeMux>[0]> = {}): NativeMux {+ return new NativeMux({ resolveHost: async () => host(), defaultAgent: () => undefined, ...extra })+}++const conn = (): SshConnection => ({ user: 'dev', host: '127.0.0.1', 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-'))+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)+ await startServer()+})+afterAll(() => {+ server.close()+ fs.rmSync(dir, { recursive: true, force: true })+})+const muxes: NativeMux[] = []+afterEach(() => {+ for (const m of muxes.splice(0)) m.exitAll()+ for (const c of live.splice(0)) c.end()+})+const track = (m: NativeMux): NativeMux => (muxes.push(m), m)++describe('NativeMux over a real SSH protocol peer', () => {+ it('shares ONE connection across many commands (ControlMaster=auto)', async () => {+ const m = track(mux())+ const before = connections+ const results = await Promise.all([1, 2, 3, 4, 5].map((i) => m.exec(exec(`echo ${i}`))))+ expect(results.map((r) => r.stdout.toString())).toEqual([1, 2, 3, 4, 5].map((i) => `ran: echo ${i}\n`))+ expect(results.every((r) => r.code === 0)).toBe(true)+ expect(connections - before).toBe(1)+ expect(m.check(CP())).toBe(true)+ })++ it('pipes stdin, and reports exit code and stderr', async () => {+ const m = track(mux())+ const r = await m.exec(exec('cat'), { stdin: 'hello\nworld' })+ expect(r.stdout.toString()).toBe('hello\nworld')+ const f = await m.exec(exec('fail 3'))+ expect(f.code).toBe(3)+ expect(f.stderr.toString()).toBe('boom\n')+ })++ it('-O exit closes it; ControlMaster=no then never re-creates the shared one', async () => {+ const m = track(mux())+ await m.exec(exec('echo up'))+ expect(await m.exit(CP())).toBe(true)+ expect(m.check(CP())).toBe(false)+ const rt = parseSshArgv(masterRoundTripArgs(conn(), CP()))+ if (rt.kind !== 'exec') throw new Error()+ const r = await m.exec(rt)+ // One-off connection, like OpenSSH's direct fallback — and still no shared master afterwards.+ expect(r.code).toBe(0)+ expect(m.check(CP())).toBe(false)+ })++ it('times a command out like execFile, and a dropped connection ends channels with 255', async () => {+ const m = track(mux())+ const t = await m.exec(exec('hang'), { timeoutMs: 300 })+ expect(t.timedOut).toBe(true)+ const pending = m.exec(exec('hang'))+ await new Promise((r) => setTimeout(r, 100))+ for (const c of live) c.end()+ const d = await pending+ expect(d.code).toBe(255)+ expect(m.check(CP())).toBe(false)+ })++ it('opens a pty channel with the requested size', async () => {+ const m = track(mux())+ const p = parseSshArgv(remoteTmuxPtyArgs(conn(), CP(), 'nt-x', '~'))+ if (p.kind !== 'exec') throw new Error()+ const ch = await m.shell(p, { cols: 132, rows: 43 })+ const out = await new Promise<string>((resolve) => {+ let s = ''+ ch.on('data', (d: Buffer) => (s += d.toString()))+ ch.on('close', () => resolve(s))+ })+ expect(out).toContain('pty 132x43')+ })++ it('records a first-seen host key, then refuses a CHANGED one', async () => {+ const m = track(mux())+ await m.exec(exec('echo a'))+ expect(fs.readFileSync(path.join(dir, 'known_hosts'), 'utf8')).toContain(`[127.0.0.1]:${port} ssh-ed25519`)+ m.exitAll()+ server.close()+ serverHostKey = otherHostKey.private+ await startServer() // new port → rewrite the known_hosts entry under the new port name+ const kh = path.join(dir, 'known_hosts')+ const text = fs.readFileSync(kh, 'utf8').replace(/\[127\.0\.0\.1\]:\d+/, `[127.0.0.1]:${port}`)+ fs.writeFileSync(kh, text)+ const r = await track(mux()).exec(exec('echo b'))+ expect(r.code).toBe(255)+ expect(r.stderr.toString()).toMatch(/REMOTE HOST IDENTIFICATION HAS CHANGED/)+ })++ it('asks for a passphrase for an encrypted key — but never in BatchMode', async () => {+ fs.rmSync(path.join(dir, 'known_hosts'), { force: true })+ fs.writeFileSync(path.join(dir, 'id'), lockedKey.private)+ try {+ const asked: string[] = []+ const m = track(+ mux({+ askPassphrase: async (f) => {+ asked.push(f)+ return asked.length === 1 ? 'wrong' : 'open sesame'+ }+ })+ )+ const r = await m.exec(exec('echo locked'))+ expect(r.stdout.toString()).toBe('ran: echo locked\n')+ expect(asked).toHaveLength(2)++ const batch = track(mux({ askPassphrase: async () => 'open sesame' }))+ const rt = parseSshArgv(masterRoundTripArgs(conn(), path.join(dir, 'other.sock')))+ if (rt.kind !== 'exec') throw new Error()+ const b = await batch.exec(rt)+ expect(b.code).toBe(255)+ expect(b.stderr.toString()).toMatch(/Permission denied/)+ } finally {+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)+ }+ })++ it('forward on a path with no connection fails the way ssh does', async () => {+ const m = track(mux())+ await expect(+ m.forward(CP(), { remoteSocket: '/r.sock', localHost: '127.0.0.1', localPort: 1 })+ ).rejects.toThrow(noMasterMessage(CP()))+ })+})diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.tsnew file mode 100644index 000000000..6a0b33f9c--- /dev/null+++ b/src/core/remote-ssh/native/native-mux.ts@@ -0,0 +1,497 @@+// The in-process SSH transport: one ssh2 connection per ControlPath, multiplexing every exec,+// pty and forward the app runs for an SSH project — the job OpenSSH's ControlMaster does on POSIX.+//+// WHY it exists (measured on windows-latest, 2026-09-30, OpenSSH_for_Windows_9.5p2): Windows'+// own ssh cannot multiplex at all. `ssh -M` fails with `getsockname failed: Not a socket`, and a+// child carrying `ControlPath` does not even fall back to a direct connection — it FAILS, so on a+// stock Windows machine an SSH project opened no terminal and ran no remote command. Git for+// Windows' ssh (10.5p1) brings a master up but every session request over it dies with+// `mux_client_request_session: read from master failed: Connection reset by peer` and falls back+// to a full login per command. Neither is a transport. POSIX keeps OpenSSH untouched; this module+// is what `native-invoke.ts` routes to on win32.+//+// Semantics are the ones the argv builders ask OpenSSH for, so a call site cannot tell which+// transport ran it:+// - ControlMaster=auto: a command on a path with no live connection ESTABLISHES one (the first+// child becomes the master), and it is shared from then on;+// - ControlMaster=no: never create the shared connection — a missing one runs the command on a+// one-off connection, as OpenSSH's direct fallback does (BatchMode: no prompts on it);+// - -O check/exit/forward/cancel answer from the shared connection;+// - StrictHostKeyChecking=accept-new (known-hosts.ts), PasswordAuthentication=no and+// KbdInteractiveAuthentication=no: publickey only, via agent then key files;+// - 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.++import net from 'net'+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 { acceptNewHostKey } from './known-hosts'++/** Result of one remote command, in the shape execFile callers already handle. */+export interface ExecResult {+ code: number | null+ signal: string | null+ stdout: Buffer+ stderr: Buffer+ /** True when the timeout ended it (execFile's `killed`). */+ timedOut: boolean+}++export interface NativeMuxDeps {+ /** Effective config for a destination (`ssh -G`; see ssh-config.ts). */+ resolveHost(target: SshTarget): Promise<ResolvedHost>+ /** Ask the user for a key's passphrase; null = cancelled. Absent = never prompt. */+ askPassphrase?(identityFile: string): Promise<string | null>+ /** Default agent when the config names none (`SSH_AUTH_SOCK` / Windows' openssh-ssh-agent pipe). */+ defaultAgent?(): string | undefined+ readFile?(p: string): Buffer | null+ /** 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+}++/** How long a passphrase prompt may hold the handshake open (matches the askpass PROMPT_WAIT_MS). */+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'++interface Conn {+ key: string+ client: Client+ ready: Promise<void>+ alive: boolean+ closed: Promise<string>+ forwards: Map<string, ReverseForward>+}++function targetKey(t: SshTarget): string {+ return `${t.user}@${t.host}:${t.port}|${t.identityFile ?? ''}`+}++/** The error text OpenSSH prints for a control socket nobody is listening on. */+export function noMasterMessage(controlPath: string): string {+ return `Control socket connect(${controlPath}): No such file or directory`+}++function defaultConnectSocket(host: string, port: number, timeoutMs: number): Promise<net.Socket> {+ return new Promise((resolve, reject) => {+ const sock = net.connect({ host, port })+ const timer = setTimeout(() => {+ sock.destroy()+ reject(new Error(`ssh: connect to host ${host} port ${port}: Operation timed out`))+ }, timeoutMs)+ sock.once('connect', () => {+ clearTimeout(timer)+ resolve(sock)+ })+ sock.once('error', (e) => {+ clearTimeout(timer)+ reject(new Error(`ssh: connect to host ${host} port ${port}: ${e.message}`))+ })+ })+}++export class NativeMux {+ private conns = new Map<string, Conn>()++ constructor(private deps: NativeMuxDeps) {}++ /** Is there a live shared connection on this path (`-O check`)? */+ check(controlPath: string): boolean {+ return this.conns.get(controlPath)?.alive === true+ }++ /** End the shared connection (`-O exit`). Resolves once it is closed. */+ async exit(controlPath: string): Promise<boolean> {+ const c = this.conns.get(controlPath)+ if (!c) return false+ this.conns.delete(controlPath)+ c.alive = false+ c.client.end()+ await Promise.race([c.closed, new Promise((r) => setTimeout(r, 2000))])+ return true+ }++ /** End every connection (app quit). */+ exitAll(): void {+ for (const [cp, c] of this.conns) {+ this.conns.delete(cp)+ c.alive = false+ c.client.end()+ }+ }++ /**+ * Bring up (or reuse) the shared connection — `ssh -M -N`, or the implicit master of a+ * ControlMaster=auto child. Resolves when authenticated; rejects with an OpenSSH-shaped message.+ * `closed` resolves (never rejects) with the reason once the connection is gone, which is what a+ * master PROCESS's exit is to the manager.+ */+ async master(controlPath: string, target: SshTarget, options: SshOptions): Promise<{ closed: Promise<string> }> {+ const existing = this.conns.get(controlPath)+ if (existing?.alive) {+ await existing.ready+ return { closed: existing.closed }+ }+ const conn = this.open(controlPath, target, options, { interactive: options.batchMode !== true })+ this.conns.set(controlPath, conn)+ try {+ await conn.ready+ } catch (e) {+ if (this.conns.get(controlPath) === conn) this.conns.delete(controlPath)+ throw e+ }+ return { closed: conn.closed }+ }++ /** Run one parsed `exec` argv. Never rejects: failures are exit 255 with stderr, like ssh. */+ async exec(+ p: Extract<ParsedSsh, { kind: 'exec' }>,+ io: { stdin?: string | Buffer; timeoutMs?: number } = {}+ ): Promise<ExecResult> {+ const cp = p.options.controlPath+ let conn: Conn | undefined = cp ? this.conns.get(cp) : undefined+ let oneOff: Conn | undefined+ try {+ if (!conn?.alive) {+ if (cp && p.options.controlMaster !== 'no') {+ await this.master(cp, p.target, p.options)+ conn = this.conns.get(cp)+ } else {+ oneOff = this.open(`oneoff:${Math.random()}`, p.target, p.options, { interactive: false })+ conn = oneOff+ }+ }+ if (!conn) throw new Error(cp ? noMasterMessage(cp) : 'ssh: no connection')+ await conn.ready+ return await this.runCommand(conn, p.command ?? '', io)+ } catch (e) {+ return fail(e)+ } finally {+ oneOff?.client.end()+ }+ }++ /** A pty channel for an interactive session (`ssh -t … <command>`). */+ async shell(+ p: Extract<ParsedSsh, { kind: 'exec' }>,+ pty: { cols: number; rows: number; term?: string }+ ): Promise<ClientChannel> {+ const cp = p.options.controlPath+ if (!cp) throw new Error('ssh: a pty needs a ControlPath')+ if (!this.conns.get(cp)?.alive) {+ if (p.options.controlMaster === 'no') throw new Error(noMasterMessage(cp))+ await this.master(cp, p.target, p.options)+ }+ const conn = this.conns.get(cp)!+ await conn.ready+ const ptyOpts = { cols: pty.cols, rows: pty.rows, term: pty.term ?? 'xterm-256color' }+ return new Promise((resolve, reject) => {+ const cb = (err: Error | undefined, ch: ClientChannel): void => (err ? reject(err) : resolve(ch))+ if (p.command) conn.client.exec(p.command, { pty: ptyOpts }, cb)+ else conn.client.shell(ptyOpts, cb)+ })+ }++ /**+ * 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+ * with the session.+ */+ async sftp(controlPath: string | undefined, target: SshTarget, options: SshOptions): Promise<SFTPWrapper> {+ let conn = controlPath ? this.conns.get(controlPath) : undefined+ let oneOff = false+ if (!conn?.alive) {+ conn = this.open(`oneoff:${Math.random()}`, target, options, { interactive: false })+ oneOff = true+ }+ const c = conn+ try {+ await c.ready+ const s = await new Promise<SFTPWrapper>((resolve, reject) =>+ c.client.sftp((err, sftp) => (err ? reject(err) : resolve(sftp)))+ )+ if (oneOff) s.on('close', () => c.client.end())+ return s+ } catch (e) {+ if (oneOff) c.client.end()+ throw e+ }+ }++ /** `-O forward -R <remoteSock>:<host>:<port>`: remote unix socket → local TCP. */+ async forward(controlPath: string, fwd: ReverseForward): Promise<void> {+ const conn = this.conns.get(controlPath)+ if (!conn?.alive) throw new Error(noMasterMessage(controlPath))+ await conn.ready+ await new Promise<void>((resolve, reject) =>+ conn.client.openssh_forwardInStreamLocal(fwd.remoteSocket, (err) => (err ? reject(err) : resolve()))+ )+ conn.forwards.set(fwd.remoteSocket, fwd)+ }++ /** `-O cancel -R …`. A forward that is not there is not an error (same as ssh). */+ async cancel(controlPath: string, fwd: ReverseForward): Promise<void> {+ const conn = this.conns.get(controlPath)+ if (!conn?.alive || !conn.forwards.has(fwd.remoteSocket)) return+ conn.forwards.delete(fwd.remoteSocket)+ await new Promise<void>((resolve) =>+ conn.client.openssh_unforwardInStreamLocal(fwd.remoteSocket, () => resolve())+ )+ }++ // ---------------------------------------------------------------------------------------------++ private runCommand(conn: Conn, command: string, io: { stdin?: string | Buffer; timeoutMs?: number }): Promise<ExecResult> {+ return new Promise((resolve) => {+ conn.client.exec(command, (err, ch) => {+ if (err) return resolve(fail(err))+ const out: Buffer[] = []+ const errOut: Buffer[] = []+ let code: number | null = null+ let signal: string | null = null+ let timedOut = false+ let timer: ReturnType<typeof setTimeout> | undefined+ if (io.timeoutMs && io.timeoutMs > 0) {+ timer = setTimeout(() => {+ timedOut = true+ ch.close()+ }, io.timeoutMs)+ }+ ch.on('data', (d: Buffer) => out.push(d))+ ch.stderr.on('data', (d: Buffer) => errOut.push(d))+ ch.on('exit', (c: number | null, s?: string) => {+ code = c+ signal = s ?? null+ })+ ch.on('close', () => {+ if (timer) clearTimeout(timer)+ // A channel that closed with no exit status was cut off (connection dropped, or our own+ // timeout): report it the way a mux'd ssh does, 255.+ if (code === null && signal === null) code = 255+ resolve({ code, signal, stdout: Buffer.concat(out), stderr: Buffer.concat(errOut), timedOut })+ })+ if (io.stdin !== undefined) ch.end(io.stdin)+ else ch.end()+ })+ })+ }++ private open(controlPath: string, target: SshTarget, options: SshOptions, mode: { interactive: boolean }): Conn {+ const client = new Client()+ let resolveClosed!: (why: string) => void+ const closed = new Promise<string>((r) => (resolveClosed = r))+ const conn: Conn = {+ key: targetKey(target),+ client,+ ready: Promise.resolve(),+ alive: true,+ closed,+ forwards: new Map()+ }+ let lastError = ''+ client.on('error', (e: Error & { level?: string }) => {+ lastError = e.message+ this.deps.log?.(`[native-ssh] ${target.user}@${target.host}: ${e.message}`)+ })+ client.on('close', () => {+ conn.alive = false+ if (this.conns.get(controlPath) === conn) this.conns.delete(controlPath)+ resolveClosed(lastError || 'connection closed')+ })+ client.on('unix connection', (info: UNIXConnectionDetails, accept: () => Channel) => {+ const fwd = conn.forwards.get(info.socketPath)+ if (!fwd) return+ const ch = accept()+ const local = net.connect({ host: fwd.localHost, port: fwd.localPort })+ local.on('error', () => ch.close())+ ch.on('error', () => local.destroy())+ ch.pipe(local).pipe(ch)+ })+ conn.ready = this.connect(client, target, options, mode).catch((e: Error) => {+ conn.alive = false+ client.end()+ throw e+ })+ // Nobody may be awaiting `ready` when it fails (a master whose caller gave up): never let+ // that become an unhandled rejection.+ conn.ready.catch(() => {})+ return conn+ }++ private async connect(client: Client, target: SshTarget, options: SshOptions, mode: { interactive: boolean }): 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+ let hostKeyRefusal = ''+ const auth = this.authPlan(target, host, options, mode)+ const cfg: ConnectConfig = {+ sock,+ username: host.user,+ readyTimeout: AUTH_WAIT_MS,+ keepaliveInterval: (options.serverAliveInterval ?? 0) * 1000,+ keepaliveCountMax: options.serverAliveCountMax ?? 3,+ hostVerifier: (key: Buffer): boolean => {+ // accept-new is the only policy the builders ask for; `ask`/`yes` from the user's config+ // are overridden by the command line exactly as they are for OpenSSH.+ const v = acceptNewHostKey(+ { userFiles: host.userKnownHostsFiles, globalFiles: host.globalKnownHostsFiles },+ knownAs,+ host.port,+ key+ )+ if (!v.accept) {+ hostKeyRefusal =+ v.verdict === 'revoked'+ ? `@@@ WARNING: REVOKED HOST KEY DETECTED FOR ${knownAs} @@@`+ : `@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@ Host key verification failed for ${knownAs}.`+ }+ return v.accept+ },+ authHandler: (_methods: unknown, _partial: unknown, next: (a: unknown) => void) => {+ auth.next().then(next, () => next(false))+ }+ } as ConnectConfig+ await new Promise<void>((resolve, reject) => {+ const onReady = (): void => {+ client.removeListener('error', onErr)+ resolve()+ }+ const onErr = (e: Error & { level?: string }): void => {+ client.removeListener('ready', onReady)+ if (hostKeyRefusal) return reject(new Error(hostKeyRefusal))+ if (e.level === 'client-authentication') {+ return reject(new Error(`${target.user}@${target.host}: Permission denied (publickey).`))+ }+ reject(new Error(`ssh: ${e.message}`))+ }+ client.once('ready', onReady)+ client.once('error', onErr)+ client.connect(cfg)+ })+ }++ /**+ * 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+ * passphrase when one is encrypted and prompting is allowed.+ */+ private authPlan(+ target: SshTarget,+ host: ResolvedHost,+ options: SshOptions,+ mode: { interactive: boolean }+ ): { next(): Promise<unknown> } {+ const username = host.user+ const identitiesOnly = options.identitiesOnly ?? host.identitiesOnly+ const files = target.identityFile ? [target.identityFile] : host.identityFiles+ const read = this.deps.readFile ?? ((p: string) => {+ try {+ return fs.readFileSync(p)+ } catch {+ return null+ }+ })+ const agentPath = resolveAgentPath(target.identityAgent ?? host.identityAgent, this.deps.defaultAgent?.())+ const steps: (() => Promise<unknown | null>)[] = []+ if (agentPath) {+ steps.push(async () => {+ if (!identitiesOnly) return { type: 'agent', username, agent: agentPath }+ const pubs = files.map((f) => read(`${f}.pub`)).filter((b): b is Buffer => !!b)+ if (!pubs.length) return null+ return { type: 'agent', username, agent: filteredAgent(agentPath, pubs) }+ })+ }+ for (const file of files) {+ steps.push(async () => {+ const data = read(file)+ if (!data) return null+ let key = utils.parseKey(data)+ if (key instanceof Error && /encrypted|passphrase/i.test(key.message)) {+ if (!mode.interactive || options.batchMode || !this.deps.askPassphrase) return null+ // Up to three tries, like ssh's NumberOfPasswordPrompts default.+ for (let i = 0; i < 3 && key instanceof Error; i++) {+ const pass = await this.deps.askPassphrase(file)+ if (pass === null) return null+ key = utils.parseKey(data, pass)+ }+ }+ if (key instanceof Error) return null+ return { type: 'publickey', username, key: Array.isArray(key) ? key[0] : key }+ })+ }+ let i = 0+ return {+ async next() {+ while (i < steps.length) {+ const step = steps[i++]+ const auth = await step()+ if (auth) return auth+ }+ return false+ }+ }+ }+}++/** 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 {+ if (configured === 'none') return undefined+ if (!configured || configured === 'SSH_AUTH_SOCK' || configured === '$SSH_AUTH_SOCK' || configured === '${SSH_AUTH_SOCK}') {+ return fallback+ }+ return configured+}++/** An agent that only offers keys whose public blob is in `pubs` (IdentitiesOnly). */+function filteredAgent(agentPath: string, pubFiles: Buffer[]): ReturnType<typeof createAgent> {+ const base = createAgent(agentPath)+ const wanted = pubFiles+ .map((b) => {+ const k = utils.parseKey(b)+ const one = Array.isArray(k) ? k[0] : k+ return one instanceof Error ? null : one.getPublicSSH()+ })+ .filter((b): b is Buffer => !!b)+ type AnyKey = string | Buffer | ParsedKey | { pubKey: AnyKey }+ const publicOf = (k: AnyKey): Buffer | null => {+ if (typeof k === 'object' && !Buffer.isBuffer(k) && 'pubKey' in k) return publicOf(k.pubKey)+ if (typeof k === 'string' || Buffer.isBuffer(k)) {+ const p = utils.parseKey(k)+ const one = Array.isArray(p) ? p[0] : p+ return one instanceof Error ? null : one.getPublicSSH()+ }+ return k.getPublicSSH()+ }+ const getIdentities = base.getIdentities.bind(base)+ base.getIdentities = (cb) =>+ getIdentities((err, keys) => {+ if (err || !keys) return cb(err, keys)+ cb(+ undefined,+ keys.filter((k) => {+ const pub = publicOf(k)+ return !!pub && wanted.some((w) => w.equals(pub))+ })+ )+ })+ return base+}++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/ssh-argv.test.ts b/src/core/remote-ssh/native/ssh-argv.test.tsnew file mode 100644index 000000000..638f572b3--- /dev/null+++ b/src/core/remote-ssh/native/ssh-argv.test.ts@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest'+import {+ masterArgs,+ childArgs,+ checkMasterArgs,+ exitMasterArgs,+ masterRoundTripArgs,+ hookForwardArgs,+ hookForwardCancelArgs,+ scpArgs,+ scpDownArgs,+ remoteTmuxPtyArgs,+ remoteListSessionsArgs,+ listDirArgs+} from '../control-master'+import { remoteGitArgs } from '../remote-git'+import { parseSshArgv, parseScpArgv, UnsupportedSshArgv } from './ssh-argv'+import type { SshConnection } from '../../../shared/ssh'++const CP = '/home/u/.nodeterm/ssh-cm/0123456789abcdef.sock'+const plain: SshConnection = { user: 'root', host: 'h.example', port: 2222 }+const keyed: SshConnection = {+ user: 'dev',+ host: '10.0.0.5',+ identityFile: 'C:\\Users\\dev\\.ssh\\id_ed25519',+ identityAgentSock: '/tmp/agent.sock'+}++describe('parseSshArgv reads back every builder in control-master.ts', () => {+ it('master', () => {+ for (const conn of [plain, keyed]) {+ const p = parseSshArgv(masterArgs(conn, CP))+ expect(p.kind).toBe('master')+ expect(p.target).toMatchObject({ user: conn.user, host: conn.host, port: conn.port ?? 22 })+ expect(p.options.controlPath).toBe(CP)+ expect(p.options.passwordAuthentication).toBe(false)+ expect(p.options.kbdInteractiveAuthentication).toBe(false)+ expect(p.options.serverAliveInterval).toBe(15)+ }+ const k = parseSshArgv(masterArgs(keyed, CP))+ expect(k.target.identityFile).toBe(keyed.identityFile)+ expect(k.target.identityAgent).toBe('/tmp/agent.sock')+ expect(k.options.identitiesOnly).toBe(true)+ })++ it('child exec with a remote command, and without one', () => {+ const p = parseSshArgv(childArgs(plain, CP, 'echo hi && ls'))+ expect(p).toMatchObject({ kind: 'exec', tty: false, command: 'echo hi && ls' })+ expect(p.options.controlMaster).toBe('auto')+ expect(parseSshArgv(childArgs(plain, CP)).kind).toBe('exec')+ expect(parseSshArgv(listDirArgs(plain, CP, '~/x')).kind).toBe('exec')+ expect(parseSshArgv(remoteListSessionsArgs(plain, CP)).kind).toBe('exec')+ expect(parseSshArgv(remoteGitArgs(plain, CP, '~/repo', ['status', '--porcelain'])).kind).toBe('exec')+ })++ it('round-trip probe runs `true` without creating a master', () => {+ const p = parseSshArgv(masterRoundTripArgs(plain, CP))+ expect(p).toMatchObject({ kind: 'exec', command: 'true' })+ expect(p.options).toMatchObject({ controlMaster: 'no', batchMode: true })+ })++ it('control ops', () => {+ expect(parseSshArgv(checkMasterArgs(plain, CP))).toMatchObject({ kind: 'control', op: 'check' })+ expect(parseSshArgv(exitMasterArgs(plain, CP))).toMatchObject({ kind: 'control', op: 'exit' })+ const fwd = parseSshArgv(hookForwardArgs(plain, CP, '/home/u/.nodeterm/hook-x.sock', 41234))+ expect(fwd).toMatchObject({+ kind: 'control',+ op: 'forward',+ forward: { remoteSocket: '/home/u/.nodeterm/hook-x.sock', localHost: '127.0.0.1', localPort: 41234 }+ })+ expect(parseSshArgv(hookForwardCancelArgs(plain, CP, '/r.sock', 1))).toMatchObject({ op: 'cancel' })+ })++ it('interactive pty', () => {+ const p = parseSshArgv(remoteTmuxPtyArgs(plain, CP, 'nt-node-1', '~/proj'))+ expect(p.kind).toBe('exec')+ if (p.kind !== 'exec') return+ expect(p.tty).toBe(true)+ expect(p.command).toContain('new-session -A')+ })++ it('refuses what it does not know, naming it', () => {+ expect(() => parseSshArgv(['-L', '8080:localhost:80', 'a@b'])).toThrow(UnsupportedSshArgv)+ expect(() => parseSshArgv(['-o', 'ProxyCommand=nc %h %p', 'a@b'])).toThrow(/ProxyCommand/)+ expect(() => parseSshArgv(['-o', 'BatchMode=maybe', 'a@b'])).toThrow(/BatchMode/)+ expect(() => parseSshArgv(['-O', 'stop', 'a@b'])).toThrow(/-O stop/)+ expect(() => parseSshArgv(['-M', 'a@b', 'ls'])).toThrow(UnsupportedSshArgv)+ expect(() => parseSshArgv(['-R', 'relative.sock:127.0.0.1:1', '-O', 'forward', 'a@b'])).toThrow(/-R/)+ expect(() => parseSshArgv(['-p', '99999', 'a@b'])).toThrow(/-p/)+ expect(() => parseSshArgv(['hostonly'])).toThrow(/destination/)+ })+})++describe('parseScpArgv', () => {+ it('upload and download, with a Windows local path', () => {+ const up = parseScpArgv(scpArgs(keyed, CP, 'C:\\Users\\dev\\file.txt', '/srv/in/file.txt'))+ expect(up).toMatchObject({+ direction: 'up',+ localPath: 'C:\\Users\\dev\\file.txt',+ remotePath: '/srv/in/file.txt',+ recursive: false+ })+ expect(up.target).toMatchObject({ user: 'dev', host: '10.0.0.5', port: 22, identityFile: keyed.identityFile })+ const down = parseScpArgv(scpDownArgs(plain, CP, '~/a dir', 'C:\\tmp\\x.part', true))+ expect(down).toMatchObject({ direction: 'down', remotePath: 'a dir', localPath: 'C:\\tmp\\x.part', recursive: true })+ expect(down.target.port).toBe(2222)+ })+})diff --git a/src/core/remote-ssh/native/ssh-argv.ts b/src/core/remote-ssh/native/ssh-argv.tsnew file mode 100644index 000000000..8c2984188--- /dev/null+++ b/src/core/remote-ssh/native/ssh-argv.ts@@ -0,0 +1,272 @@+// A STRICT parser for the ssh / scp argv this app builds (control-master.ts), so the in-process+// transport can serve every call site without changing any of them: the ~100 remote operations+// keep building OpenSSH argv, and on Windows the argv is read back here and executed over the+// project's one native connection instead of by an ssh binary that cannot multiplex there.+//+// Strict on purpose: an option this file does not know is an ERROR naming the option, never+// ignored. Every builder lives in one module, so an unknown flag means a builder grew one and the+// native path has to learn what it means — silently dropping it would run the command with a+// different meaning than the POSIX path gives it. control-master.native.test.ts builds every+// builder's argv and parses it back, so a new flag fails a test before it fails a user.++export interface SshTarget {+ user: string+ host: string+ port: number+ /** `-i`, which the builders always pair with `IdentitiesOnly=yes`. */+ identityFile?: string+ /** `-o IdentityAgent=` (the #427 pin). */+ identityAgent?: string+}++/** The `-o` values the builders emit, typed. Absent = not given on this command line. */+export interface SshOptions {+ controlMaster?: 'auto' | 'no' | 'yes'+ controlPath?: string+ controlPersist?: string+ batchMode?: boolean+ strictHostKeyChecking?: string+ serverAliveInterval?: number+ serverAliveCountMax?: number+ connectTimeout?: number+ passwordAuthentication?: boolean+ kbdInteractiveAuthentication?: boolean+ addKeysToAgent?: boolean+ identitiesOnly?: boolean+}++export interface ReverseForward {+ /** Remote unix socket path (the builders only ever forward to one). */+ remoteSocket: string+ localHost: string+ localPort: number+}++export type ParsedSsh =+ | { kind: 'master'; target: SshTarget; options: SshOptions; background: boolean }+ | { kind: 'control'; op: 'check' | 'exit'; target: SshTarget; options: SshOptions }+ | {+ kind: 'control'+ op: 'forward' | 'cancel'+ target: SshTarget+ options: SshOptions+ forward: ReverseForward+ }+ | { kind: 'exec'; target: SshTarget; options: SshOptions; tty: boolean; command?: string }++export class UnsupportedSshArgv extends Error {+ constructor(what: string) {+ super(`native ssh transport: unsupported ssh argument ${what}`)+ this.name = 'UnsupportedSshArgv'+ }+}++const YES_NO = (key: string, v: string): boolean => {+ if (v === 'yes') return true+ if (v === 'no') return false+ throw new UnsupportedSshArgv(`-o ${key}=${v}`)+}++function applyOption(o: SshOptions, t: Partial<SshTarget>, kv: string): void {+ const eq = kv.indexOf('=')+ if (eq <= 0) throw new UnsupportedSshArgv(`-o ${kv}`)+ const key = kv.slice(0, eq)+ const v = kv.slice(eq + 1)+ const int = (): number => {+ const n = Number(v)+ if (!Number.isInteger(n) || n < 0) throw new UnsupportedSshArgv(`-o ${kv}`)+ return n+ }+ switch (key) {+ case 'ControlMaster':+ if (v !== 'auto' && v !== 'no' && v !== 'yes') throw new UnsupportedSshArgv(`-o ${kv}`)+ o.controlMaster = v+ return+ case 'ControlPath':+ o.controlPath = v+ return+ case 'ControlPersist':+ o.controlPersist = v+ return+ case 'BatchMode':+ o.batchMode = YES_NO(key, v)+ return+ case 'StrictHostKeyChecking':+ o.strictHostKeyChecking = v+ return+ case 'ServerAliveInterval':+ o.serverAliveInterval = int()+ return+ case 'ServerAliveCountMax':+ o.serverAliveCountMax = int()+ return+ case 'ConnectTimeout':+ o.connectTimeout = int()+ return+ case 'PasswordAuthentication':+ o.passwordAuthentication = YES_NO(key, v)+ return+ case 'KbdInteractiveAuthentication':+ o.kbdInteractiveAuthentication = YES_NO(key, v)+ return+ case 'AddKeysToAgent':+ o.addKeysToAgent = YES_NO(key, v)+ return+ case 'IdentitiesOnly':+ o.identitiesOnly = YES_NO(key, v)+ return+ case 'IdentityAgent':+ t.identityAgent = v+ return+ default:+ throw new UnsupportedSshArgv(`-o ${kv}`)+ }+}++function parseDestination(dest: string, t: Partial<SshTarget>): void {+ const at = dest.lastIndexOf('@')+ if (at <= 0 || at === dest.length - 1) throw new UnsupportedSshArgv(`destination ${JSON.stringify(dest)}`)+ t.user = dest.slice(0, at)+ t.host = dest.slice(at + 1)+}++function parsePort(v: string | undefined, flag: string): number {+ const n = Number(v)+ if (!Number.isInteger(n) || n <= 0 || n > 65535) throw new UnsupportedSshArgv(`${flag} ${v}`)+ return n+}++/** `<remoteSock>:<host>:<port>` — the only -R shape the builders produce (fwdSpec). */+function parseReverse(spec: string): ReverseForward {+ const m = /^(.+):([^:]+):(\d+)$/.exec(spec)+ if (!m || !m[1].startsWith('/')) throw new UnsupportedSshArgv(`-R ${spec}`)+ return { remoteSocket: m[1], localHost: m[2], localPort: parsePort(m[3], '-R port') }+}++/**+ * Parse an ssh argv (without the program). The remote command is every argument after the+ * destination joined with single spaces — exactly what OpenSSH sends to the server, which runs it+ * through the user's login shell.+ */+export function parseSshArgv(argv: string[]): ParsedSsh {+ const o: SshOptions = {}+ const t: Partial<SshTarget> = { port: 22 }+ let master = false+ let noCommand = false+ let background = false+ let tty = false+ let op: string | undefined+ let reverse: ReverseForward | undefined+ let i = 0+ const need = (flag: string): string => {+ const v = argv[++i]+ if (v === undefined) throw new UnsupportedSshArgv(`${flag} without a value`)+ return v+ }+ for (; i < argv.length; i++) {+ const a = argv[i]+ if (!a.startsWith('-') || a === '-') break+ switch (a) {+ case '-M':+ master = true+ break+ case '-N':+ noCommand = true+ break+ case '-f':+ background = true+ break+ case '-t':+ tty = true+ break+ case '-O':+ op = need(a)+ break+ case '-R':+ reverse = parseReverse(need(a))+ break+ case '-p':+ t.port = parsePort(need(a), '-p')+ break+ case '-i':+ t.identityFile = need(a)+ break+ case '-o':+ applyOption(o, t, need(a))+ break+ default:+ throw new UnsupportedSshArgv(a)+ }+ }+ const dest = argv[i++]+ if (dest === undefined) throw new UnsupportedSshArgv('(no destination)')+ parseDestination(dest, t)+ const rest = argv.slice(i)+ const target = t as SshTarget+ if (op !== undefined) {+ if (rest.length) throw new UnsupportedSshArgv(`command with -O ${op}`)+ if (op === 'check' || op === 'exit') {+ if (reverse) throw new UnsupportedSshArgv(`-R with -O ${op}`)+ return { kind: 'control', op, target, options: o }+ }+ if (op === 'forward' || op === 'cancel') {+ if (!reverse) throw new UnsupportedSshArgv(`-O ${op} without -R`)+ return { kind: 'control', op, target, options: o, forward: reverse }+ }+ throw new UnsupportedSshArgv(`-O ${op}`)+ }+ if (reverse) throw new UnsupportedSshArgv('-R outside -O forward/cancel')+ if (master) {+ if (!noCommand || rest.length || tty) throw new UnsupportedSshArgv('-M without -N, or with a command')+ return { kind: 'master', target, options: o, background }+ }+ if (noCommand || background) throw new UnsupportedSshArgv('-N/-f without -M')+ return { kind: 'exec', target, options: o, tty, command: rest.length ? rest.join(' ') : undefined }+}++export type ParsedScp = {+ target: SshTarget+ options: SshOptions+ recursive: boolean+ direction: 'up' | 'down'+ localPath: string+ remotePath: string+}++/** Parse the scp argv scpArgs / scpDownArgs build. */+export function parseScpArgv(argv: string[]): ParsedScp {+ const o: SshOptions = {}+ const t: Partial<SshTarget> = { port: 22 }+ let recursive = false+ let i = 0+ for (; i < argv.length; i++) {+ const a = argv[i]+ if (!a.startsWith('-')) break+ if (a === '-r') recursive = true+ else if (a === '-P') t.port = parsePort(argv[++i], '-P')+ else if (a === '-i') t.identityFile = argv[++i]+ else if (a === '-o') applyOption(o, t, argv[++i] ?? '')+ else throw new UnsupportedSshArgv(`scp ${a}`)+ }+ const rest = argv.slice(i)+ if (rest.length !== 2) throw new UnsupportedSshArgv(`scp operands ${JSON.stringify(rest)}`)+ const remoteOf = (s: string): { dest: string; path: string } | null => {+ // `user@host:path` — the builders always put the user in; a local Windows path `C:\x` has no '@'.+ const m = /^([^@/\\]+@[^:/\\]+):(.*)$/.exec(s)+ return m ? { dest: m[1], path: m[2] } : null+ }+ const [a, b] = rest+ const ra = remoteOf(a)+ const rb = remoteOf(b)+ if ((ra && rb) || (!ra && !rb)) throw new UnsupportedSshArgv(`scp operands ${JSON.stringify(rest)}`)+ const r = (ra ?? rb)!+ parseDestination(r.dest, t)+ return {+ target: t as SshTarget,+ options: o,+ recursive,+ direction: rb ? 'up' : 'down',+ localPath: rb ? a : b,+ remotePath: r.path+ }+}diff --git a/src/core/remote-ssh/native/ssh-config.ts b/src/core/remote-ssh/native/ssh-config.tsnew file mode 100644index 000000000..de0e060e8--- /dev/null+++ b/src/core/remote-ssh/native/ssh-config.ts@@ -0,0 +1,108 @@+// The effective OpenSSH client config for one destination, as `ssh -G` prints it.+//+// The in-process transport (native-mux.ts) replaces the ssh BINARY on Windows, not the user's+// ~/.ssh/config: a Host alias, a non-default port, a per-host IdentityFile, a HostKeyAlias or a+// ProxyJump must mean the same thing whichever transport carries the connection. Re-implementing+// the config grammar (Match blocks, Include, token expansion, first-obtained-wins) would be a second+// definition of it that drifts, so we ask OpenSSH itself: `ssh -G` evaluates the config and prints+// the resolved values without connecting. Windows' own OpenSSH (9.5p2, measured on windows-latest)+// supports it, and so does every OpenSSH a POSIX desktop has.+//+// Command-line values win over the config, exactly as they do for ssh: the argv builders pass+// `-p`, `-i` and `-o IdentitiesOnly=yes`, and `ssh -G` is invoked with the same flags, so what it+// prints already has them applied.++import os from 'os'+import path from 'path'++/** What the native transport needs to know about a destination. */+export interface ResolvedHost {+ /** Real host to dial (HostName, after alias resolution). */+ hostname: string+ port: number+ user: string+ /** Candidate private keys, in config order, `~` expanded. */+ identityFiles: string[]+ /** `IdentitiesOnly yes`: offer only `identityFiles`, never other agent keys. */+ identitiesOnly: boolean+ /** Agent to use: a socket / pipe path, `none`, or undefined for the platform default. */+ 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?: string+ /** Name the host key is recorded under in known_hosts (`HostKeyAlias`), else the host. */+ hostKeyAlias?: string+ userKnownHostsFiles: string[]+ globalKnownHostsFiles: string[]+ /** `yes` | `no` | `ask` | `accept-new` | `off` — the config's own answer; our argv overrides it. */+ strictHostKeyChecking: string+ /** Seconds, or undefined for none. */+ connectTimeout?: number+}++/** `~` / `%d` expansion for path-valued options. `ssh -G` leaves `~` unexpanded. */+export function expandHomePath(p: string, home: string = os.homedir()): string {+ if (p === '~') return home+ if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(home, p.slice(2))+ return p.replace(/%d/g, home)+}++/**+ * Parse `ssh -G` output. Keys are printed lower-case, one `key value…` per line; multi-valued+ * options (identityfile) repeat, list-valued ones (userknownhostsfile) are space-separated.+ */+export function parseSshG(out: string, home: string = os.homedir()): ResolvedHost {+ const single = new Map<string, string>()+ const multi = new Map<string, string[]>()+ for (const raw of out.split(/\r?\n/)) {+ const line = raw.trim()+ if (!line) continue+ const sp = line.indexOf(' ')+ const key = (sp === -1 ? line : line.slice(0, sp)).toLowerCase()+ const value = sp === -1 ? '' : line.slice(sp + 1).trim()+ if (!single.has(key)) single.set(key, value)+ const list = multi.get(key)+ if (list) list.push(value)+ else multi.set(key, [value])+ }+ const hostname = single.get('hostname')+ const user = single.get('user')+ const port = Number(single.get('port') ?? '22')+ if (!hostname || !user || !Number.isInteger(port) || port <= 0 || port > 65535) {+ throw new Error('ssh -G did not report a hostname, user and port')+ }+ const words = (k: string): string[] =>+ (single.get(k) ?? '')+ .split(/\s+/)+ .filter(Boolean)+ .map((p) => expandHomePath(p, home))+ const opt = (k: string): string | undefined => {+ const v = single.get(k)+ return v && v !== 'none' ? v : undefined+ }+ const timeout = Number(single.get('connecttimeout'))+ return {+ hostname,+ port,+ user,+ identityFiles: (multi.get('identityfile') ?? []).map((p) => expandHomePath(p, home)),+ identitiesOnly: single.get('identitiesonly') === 'yes',+ identityAgent: opt('identityagent'),+ proxyJump: opt('proxyjump'),+ proxyCommand: opt('proxycommand'),+ hostKeyAlias: opt('hostkeyalias'),+ userKnownHostsFiles: words('userknownhostsfile'),+ globalKnownHostsFiles: words('globalknownhostsfile'),+ strictHostKeyChecking: single.get('stricthostkeychecking') ?? 'ask',+ connectTimeout: Number.isFinite(timeout) && timeout > 0 ? timeout : undefined+ }+}++/** `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)]+ if (t.identityFile) args.push('-o', 'IdentitiesOnly=yes', '-i', t.identityFile)+ args.push(`${t.user}@${t.host}`)+ return args+}