dsh-remote 0.8.92 → 0.8.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +369 -369
  3. package/README.md +354 -354
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/binding.js +172 -172
  7. package/lib/boot.js +42 -0
  8. package/lib/client.js +4661 -4647
  9. package/lib/credential.js +270 -270
  10. package/lib/errors.js +141 -141
  11. package/lib/exec-job.js +242 -242
  12. package/lib/file-reference.js +457 -457
  13. package/lib/forwards.js +258 -258
  14. package/lib/host-api.js +822 -822
  15. package/lib/hostkey.js +108 -108
  16. package/lib/http-transport.js +201 -201
  17. package/lib/ignore.js +202 -202
  18. package/lib/index.js +4488 -4488
  19. package/lib/instructions-dynamic.js +415 -415
  20. package/lib/instructions.js +288 -288
  21. package/lib/open-folder.js +56 -56
  22. package/lib/openssh.js +940 -940
  23. package/lib/paths.js +292 -292
  24. package/lib/pool.js +1029 -1029
  25. package/lib/posix-shell.cjs +34 -34
  26. package/lib/registry.js +296 -296
  27. package/lib/remote-fs.js +173 -173
  28. package/lib/remote-sandbox.js +183 -183
  29. package/lib/remote-shell-child.cjs +397 -397
  30. package/lib/remote-shell.js +697 -697
  31. package/lib/remote-skills.js +312 -312
  32. package/lib/routes-audit.js +58 -58
  33. package/lib/routes-forwards.js +72 -72
  34. package/lib/routes-fs.js +251 -251
  35. package/lib/routes-machines.js +186 -186
  36. package/lib/routes-misc.js +187 -187
  37. package/lib/routes-term.js +169 -169
  38. package/lib/routes-update.js +143 -143
  39. package/lib/routes-web-attach.js +112 -112
  40. package/lib/routes-workspace.js +312 -312
  41. package/lib/search.js +235 -235
  42. package/lib/self-heal.js +130 -0
  43. package/lib/sftp-surface.js +119 -119
  44. package/lib/sshconfig.js +779 -779
  45. package/lib/sync.js +350 -350
  46. package/lib/tasks.js +95 -95
  47. package/lib/telemetry.js +247 -247
  48. package/lib/terminal.js +205 -205
  49. package/lib/tui/flow.js +130 -130
  50. package/lib/tui/format.js +380 -380
  51. package/lib/tui/i18n.js +350 -350
  52. package/lib/tui/index.js +531 -531
  53. package/lib/tui/provider.js +344 -344
  54. package/lib/tui/scene.js +986 -986
  55. package/lib/update.js +490 -472
  56. package/lib/web-attach.js +860 -860
  57. package/lib/workspace-cleanup.js +337 -337
  58. package/package.json +103 -103
package/lib/openssh.js CHANGED
@@ -1,940 +1,940 @@
1
- // dsh-remote — the "system OpenSSH" SSH backend (issue #51).
2
- //
3
- // ## Why this exists
4
- //
5
- // The default backend (lib/pool.js) speaks SSH itself through ssh2, so it can
6
- // only use the authentication methods ssh2 implements: password, private key,
7
- // ssh-agent and keyboard-interactive. Enterprise hosts that only allow
8
- // GSSAPI/Kerberos are unreachable, even though `ssh <alias>` in the user's own
9
- // terminal works — the local Kerberos ticket (kinit) is simply not something
10
- // ssh2 knows how to present.
11
- //
12
- // This backend delegates the transport to the LOCAL `ssh` executable, so every
13
- // `~/.ssh/config` feature the user already relies on applies: gssapi-with-mic,
14
- // ProxyJump, ProxyCommand, ControlPath, Host aliases, IdentityFile,
15
- // PKCS11Provider, Match blocks… Anything OpenSSH can do, this backend can do,
16
- // because OpenSSH is the one doing it.
17
- //
18
- // ## How each primitive is implemented
19
- //
20
- // exec → `ssh <opts> -- <dest> <command>` (one process per call)
21
- // sftp → `ssh <opts> -s <dest> sftp` + ssh2's OWN SFTP protocol engine
22
- // driven over the resulting raw byte stream
23
- // forwardOut → `ssh <opts> -W <host>:<port> <dest>` (one process per tunnel)
24
- // reverse → `ssh <opts> -N -R <bind>:<port>:<h>:<p> <dest>`
25
- //
26
- // The SFTP one deserves a note, because it is the reason this backend did not
27
- // have to reimplement file transfer: `ssh -s <dest> sftp` on stdio is a PLAIN
28
- // SFTP v3 byte stream (verified against a real host — the subsystem replies
29
- // with its VERSION packet and nothing else on stdout). ssh2 already ships a
30
- // complete, battle-tested SFTP implementation that speaks exactly that protocol
31
- // over a duplex stream, so this module gives it a minimal `_protocol` shim and
32
- // hands it the child process's stdio. File transfer therefore has the same
33
- // semantics — and the same large-packet optimisations — as the native backend.
34
- //
35
- // ## Trade-offs (documented, not hidden)
36
- //
37
- // • spawn-per-operation: unlike the native pool there is no long-lived
38
- // connection multiplexed across commands, so each `exec`/`forwardOut` pays
39
- // a fresh SSH handshake. That is inherent to delegating to the `ssh` CLI:
40
- // Windows OpenSSH rejects ControlMaster ("getsockname failed: Not a
41
- // socket", measured), and a portable multiplexing layer would be a second
42
- // implementation of what the native backend already does. The SFTP path IS
43
- // kept persistent, because the workspace picker and the explorer hammer it.
44
- // • the passphrase/password prompt: OpenSSH asks for both through the same
45
- // askpass channel, so when a secret is configured this backend offers it
46
- // for whichever prompt appears (password first, then passphrase). A host
47
- // needing two DIFFERENT secrets is not representable here — use the native
48
- // backend for that.
49
- // • reverse forwards need their target up front (the CLI takes it as an
50
- // argument), so they are exposed as `reverseForward()` and ForwardManager
51
- // prefers it when present.
52
- // • host keys are checked by ssh itself against the user's own known_hosts,
53
- // not against the plugin's TOFU store: making `ssh` use a different trust
54
- // anchor per machine is exactly the kind of override that breaks the
55
- // enterprise setups this backend exists to serve. `hostKeyMode` maps onto
56
- // StrictHostKeyChecking instead.
57
-
58
- import { spawn } from 'node:child_process'
59
- import { accessSync, chmodSync, constants as fsConstants, mkdirSync, writeFileSync } from 'node:fs'
60
- import { createRequire } from 'node:module'
61
- import { EventEmitter } from 'node:events'
62
- import { homedir, tmpdir } from 'node:os'
63
- import path from 'node:path'
64
- import { Duplex } from 'node:stream'
65
- import { buildSftpSurface } from './sftp-surface.js'
66
- import { truncate } from './paths.js'
67
-
68
- // The SFTP protocol engine lives at lib/protocol/SFTP.js inside ssh2 and is not
69
- // part of its public API. Creating it through createRequire keeps this module
70
- // ESM-clean while still reaching it; if a future ssh2 moves it, this fails with
71
- // an actionable message instead of a bare MODULE_NOT_FOUND at connect time.
72
- const require_ = createRequire(import.meta.url)
73
- let SftpEngine = null
74
- export function loadSftpEngine() {
75
- if (SftpEngine) return SftpEngine
76
- try {
77
- const entry = require_.resolve('ssh2')
78
- const sftpPath = entry.replace(/lib[\\/]index\.js$/, 'lib/protocol/SFTP.js')
79
- SftpEngine = require_(sftpPath).SFTP
80
- } catch (err) {
81
- throw new Error("system-OpenSSH backend could not load ssh2's SFTP engine: " + ((err && err.message) || err))
82
- }
83
- if (typeof SftpEngine !== 'function') {
84
- throw new Error("system-OpenSSH backend found no SFTP engine in this ssh2 install")
85
- }
86
- return SftpEngine
87
- }
88
-
89
- /** The `ssh` executable this backend drives (config override wins). */
90
- export function resolveSshBinary(config = {}) {
91
- return String(config.sshBinary || '').trim() || 'ssh'
92
- }
93
-
94
- /**
95
- * Path of the user's own known_hosts. Exposed for the UI; the backend itself
96
- * never points ssh at a different file (see the header).
97
- */
98
- export function defaultKnownHostsPath() {
99
- return path.join(homedir(), '.ssh', 'known_hosts')
100
- }
101
-
102
- /**
103
- * Translate `hostKeyMode` into OpenSSH's StrictHostKeyChecking.
104
- *
105
- * `accept-new` is ssh's own default on modern OpenSSH and matches the plugin's
106
- * TOFU default; `verify` refuses unknown hosts; `off` accepts anything.
107
- */
108
- export function hostKeyArgs(config = {}) {
109
- const mode = config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new'
110
- const strict = mode === 'verify' ? 'yes' : mode === 'off' ? 'no' : 'accept-new'
111
- return ['-o', `StrictHostKeyChecking=${strict}`]
112
- }
113
-
114
- /**
115
- * Where the generated askpass helper lives. One stable directory per user, so
116
- * the helper is written once and reused; the helper carries NO secret (it reads
117
- * the secret from the environment), which is why writing it to disk is safe.
118
- */
119
- export function askpassDir() {
120
- return path.join(tmpdir(), 'dsh-remote-askpass')
121
- }
122
-
123
- /**
124
- * Ensure an askpass helper exists and return its path.
125
- *
126
- * The helper prints $DSH_REMOTE_SSH_SECRET. Passing the secret through the
127
- * environment (rather than as an argument or a file) keeps it out of `ps`,
128
- * argv and the filesystem. The Windows helper is a .cmd that invokes Node via
129
- * `process.execPath`, because `@echo %VAR%` would mangle secrets containing cmd
130
- * metacharacters (&, %, ^ …) and a bare `echo` is not a shell we control.
131
- */
132
- export function ensureAskpassHelper() {
133
- const dir = askpassDir()
134
- try { mkdirSync(dir, { recursive: true }) } catch { /* already there */ }
135
- if (process.platform === 'win32') {
136
- const js = path.join(dir, 'askpass.js')
137
- const cmd = path.join(dir, 'askpass.cmd')
138
- try {
139
- writeFileSync(js, 'process.stdout.write((process.env.DSH_REMOTE_SSH_SECRET || "") + "\\n")\n')
140
- writeFileSync(cmd, '@echo off\r\n"' + process.execPath + '" "' + js + '"\r\n')
141
- } catch (err) {
142
- throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
143
- }
144
- return cmd
145
- }
146
- const sh = path.join(dir, 'askpass.sh')
147
- try {
148
- writeFileSync(sh, '#!/bin/sh\nprintf \'%s\\n\' "$DSH_REMOTE_SSH_SECRET"\n')
149
- try { chmodSync(sh, 0o700) } catch { /* best effort on odd filesystems */ }
150
- } catch (err) {
151
- throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
152
- }
153
- return sh
154
- }
155
-
156
- /** Env that hands the secret to the askpass helper (never argv, never a file). */
157
- export function askpassEnv(secret) {
158
- return {
159
- ...process.env,
160
- SSH_ASKPASS: ensureAskpassHelper(),
161
- SSH_ASKPASS_REQUIRE: 'force',
162
- DISPLAY: process.env.DISPLAY || ':0',
163
- DSH_REMOTE_SSH_SECRET: String(secret),
164
- }
165
- }
166
-
167
- /**
168
- * Keep an EPIPE on a child's stdin from becoming a process-wide crash.
169
- *
170
- * A child that stops reading — the remote side of `ssh -s sftp` dying mid-
171
- * transfer is the one that bites — makes the NEXT write to its stdin fail. Node
172
- * reports that asynchronously through the Writable's `'error'` event, so a
173
- * synchronous `try/catch` around `write()` never sees it; an unhandled
174
- * `'error'` on a stream is an uncaught exception, and the Host treats one of
175
- * those as fatal (issue #118: `dsh: fatal uncaught exception: Error: write
176
- * EPIPE` → the whole app's host process exits and every session is lost).
177
- *
178
- * Every `spawn` in this file therefore gets this hook: swallow the pipe error,
179
- * report it to `onError` when the caller has cleanup to do, and let the
180
- * existing `'close'`/`'error'` handling own the rest. A missing `ssh` binary
181
- * is a different signal — spawn reports it on the CHILD, not on its stdin — so
182
- * it still reaches the caller as a real error.
183
- *
184
- * @param {import('node:child_process').ChildProcess} child
185
- * @param {(err: Error) => void} [onError] - e.g. drop the cached SFTP session.
186
- * @returns {import('node:child_process').ChildProcess} the same child.
187
- */
188
- export function guardChildStdin(child, onError) {
189
- const stdin = child && child.stdin
190
- if (!stdin || typeof stdin.on !== 'function') return child
191
- // A listener is the difference between "this stream reported a problem" and
192
- // "this process died": without one Node re-throws the error as an uncaught
193
- // exception. There is nothing to retry here — the pipe is gone — so all that
194
- // is left is to let the caller drop whatever it cached for this child; the
195
- // child's own 'close'/'error' handling still reports the real failure.
196
- stdin.on('error', (err) => {
197
- if (typeof onError === 'function') { try { onError(err) } catch { /* best effort */ } }
198
- })
199
- return child
200
- }
201
-
202
- /** Is `ssh` runnable? Used to fail with an actionable message, not ENOENT. */
203
- export function sshBinaryAvailable(binary) {
204
- if (binary.includes('/') || binary.includes('\\')) {
205
- try { accessSync(binary, fsConstants.X_OK); return true } catch { return false }
206
- }
207
- const exts = process.platform === 'win32'
208
- ? String(process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').filter(Boolean)
209
- : ['']
210
- for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
211
- if (!dir) continue
212
- for (const ext of exts) {
213
- try { accessSync(path.join(dir, binary + ext), fsConstants.X_OK); return true } catch { /* keep looking */ }
214
- }
215
- }
216
- return false
217
- }
218
-
219
- /**
220
- * Options shared by every `ssh` invocation for this target.
221
- *
222
- * Deliberately NOT passed: PreferredAuthentications / GSSAPIAuthentication /
223
- * PubkeyAcceptedKeyTypes / IdentitiesOnly-from-the-alias / ProxyJump-from-the-
224
- * alias. Those must come from the user's `~/.ssh/config` — overriding them is
225
- * precisely what would break the enterprise setups this backend exists for.
226
- *
227
- * @param {object} config - the pool config.
228
- * @param {object} [opts]
229
- * @param {boolean} [opts.forSecret] - true when a secret will be offered via
230
- * askpass, which means BatchMode must be OFF (BatchMode forbids every
231
- * interactive prompt, askpass included) and the prompt count bounded instead.
232
- */
233
- export function baseSshArgs(config, { forSecret = false } = {}) {
234
- const args = []
235
- if (config.port && Number(config.port) !== 22) args.push('-p', String(Number(config.port)))
236
- if (config.username) args.push('-l', String(config.username))
237
- if (config.privateKeyPath) args.push('-i', String(config.privateKeyPath))
238
- // An explicit jump host — the same shape the native backend's `proxy` takes.
239
- // A jump host that comes from ~/.ssh/config needs nothing here.
240
- const proxy = config.proxy
241
- if (proxy && proxy.host) {
242
- const user = proxy.username ? `${proxy.username}@` : ''
243
- const port = proxy.port && Number(proxy.port) !== 22 ? `:${Number(proxy.port)}` : ''
244
- args.push('-J', `${user}${proxy.host}${port}`)
245
- }
246
- // An explicit known_hosts file (tests keep loopback keys OUT of the user's
247
- // real ~/.ssh/known_hosts with this; ssh ignores $HOME on some platforms).
248
- // Checking strength is unchanged — StrictHostKeyChecking below still applies.
249
- if (config.knownHostsFile) args.push('-o', `UserKnownHostsFile=${config.knownHostsFile}`)
250
- args.push(...hostKeyArgs(config))
251
- const connectSecs = Math.max(1, Math.round((Number(config.connectTimeoutMs) || 15000) / 1000))
252
- args.push('-o', `ConnectTimeout=${connectSecs}`, '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3')
253
- // Without a configured secret we must not hang on an interactive prompt:
254
- // BatchMode makes ssh fail fast instead, and leaves key/agent/GSSAPI intact.
255
- if (!forSecret) args.push('-o', 'BatchMode=yes')
256
- else args.push('-o', 'NumberOfPasswordPrompts=1')
257
- return args
258
- }
259
-
260
- /**
261
- * One live system-OpenSSH connection.
262
- *
263
- * This deliberately mimics the ssh2 Client surface the rest of the plugin
264
- * consumes — `forwardOut` plus a reverse-forward capability — so
265
- * ForwardManager/WebAttach work unchanged. It is an EventEmitter because the
266
- * native pool's client is one and callers attach listeners to it.
267
- */
268
- export class OpenSshConnection extends EventEmitter {
269
- constructor(pool, { sshBinary, secret }) {
270
- super()
271
- this.pool = pool
272
- this.sshBinary = sshBinary
273
- this.secret = secret
274
- this.closed = false
275
- /** Live child processes to reap on close. */
276
- this.children = new Set()
277
- }
278
-
279
- shortDescription() {
280
- return `${this.pool.destination()} via ${this.sshBinary}`
281
- }
282
-
283
- spawnSsh(extraArgs, { tty = false } = {}) {
284
- if (this.closed) throw new Error('ssh connection closed')
285
- const args = [
286
- ...baseSshArgs(this.pool._argConfig(), { forSecret: !!this.secret }),
287
- ...extraArgs,
288
- ]
289
- const child = spawn(this.sshBinary, args, {
290
- stdio: ['pipe', 'pipe', 'pipe'],
291
- env: this.secret ? askpassEnv(this.secret) : undefined,
292
- })
293
- this.children.add(child)
294
- const reap = () => this.children.delete(child)
295
- // Every connection-level child goes through here (the `ssh -W` forward
296
- // channel and the `ssh -N` reverse forward), so the stdin guard for those
297
- // two paths belongs here rather than at each call site: a tunnel whose peer
298
- // vanished must end as a closed channel, not as a fatal EPIPE (issue #118).
299
- guardChildStdin(child)
300
- child.on('close', reap)
301
- child.on('error', reap)
302
- if (tty) { /* no pty support through the CLI without a tty helper */ }
303
- return child
304
- }
305
-
306
- /**
307
- * Local forward: carry bytes to <destHost>:<destPort> as seen FROM the
308
- * remote, through `ssh -W`.
309
- *
310
- * @returns {boolean} true synchronously, so capability probes can be sync.
311
- */
312
- forwardOut(_srcHost, _srcPort, destHost, destPort, cb) {
313
- let child
314
- try {
315
- child = this.spawnSsh(['-W', `${destHost}:${destPort}`, '--', this.pool.destination()])
316
- } catch (err) {
317
- setImmediate(() => cb(err))
318
- return true
319
- }
320
- // `ssh -W` reports failures on stderr and then exits; surface that as the
321
- // channel error so the caller destroys its socket instead of hanging.
322
- let stderr = ''
323
- let handed = false
324
- const channel = new Duplex({
325
- read() {},
326
- write(chunk, _enc, done) { try { child.stdin.write(chunk, done) } catch (e) { done(e) } },
327
- final(done) { try { child.stdin.end(done) } catch { done() } },
328
- destroy(err, done) { try { child.kill() } catch {} ; done(err) },
329
- })
330
- channel.close = () => { try { child.kill() } catch {} }
331
- child.stderr.on('data', (d) => { stderr += d })
332
- child.stdout.on('data', (d) => channel.push(d))
333
- child.stdout.on('end', () => channel.push(null))
334
- child.on('error', (e) => { if (!handed) { handed = true; cb(e); return } channel.destroy(e) })
335
- child.on('close', (code) => {
336
- if (handed) { channel.push(null); return }
337
- handed = true
338
- if (code === 0) { cb(null, channel); return }
339
- cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
340
- })
341
- return true
342
- }
343
-
344
- /** Tells ForwardManager that the CLI-specific reverse path is available. */
345
- get supportsReverseForward() { return true }
346
-
347
- /**
348
- * Reverse forward: ask the REMOTE to listen on <bindHost>:<listenPort> and
349
- * carry connections to <targetHost>:<targetPort>. Unlike ssh2's two-phase
350
- * `forwardIn` + `tcpip`, the `ssh -R` CLI takes the final target as an
351
- * argument, so nothing has to be resolved lazily.
352
- *
353
- * @returns {Promise<{child: object, close: Function}>}
354
- */
355
- reverseForward({ bindHost = '127.0.0.1', listenPort, targetHost = '127.0.0.1', targetPort }) {
356
- return new Promise((resolve, reject) => {
357
- const spec = `${bindHost}:${listenPort}:${targetHost}:${targetPort}`
358
- let child
359
- try {
360
- child = this.spawnSsh(['-N', '-o', 'ExitOnForwardFailure=yes', '-R', spec, '--', this.pool.destination()])
361
- } catch (err) { return reject(err) }
362
- let stderr = ''
363
- let settled = false
364
- const fail = (err) => {
365
- if (settled) return
366
- settled = true
367
- clearTimeout(timer)
368
- try { child.kill() } catch {}
369
- reject(err)
370
- }
371
- child.stderr.on('data', (d) => {
372
- stderr += d
373
- // Nothing prints on success; an error before the grace window is the
374
- // only signal `ssh -N` gives that the forward did not take.
375
- if (/warning|error|failed|refused|denied|cannot|not permitted|unable/i.test(String(d))) {
376
- fail(new Error(`reverse forward ${spec} failed: ${stderr.trim()}`))
377
- }
378
- })
379
- child.on('error', fail)
380
- // `ssh -N` stays in the foreground; a process that outlives the grace
381
- // window means the remote listener was accepted.
382
- const timer = setTimeout(() => {
383
- if (settled) return
384
- settled = true
385
- resolve({ child, close: () => { try { child.kill() } catch {} } })
386
- }, 700)
387
- child.on('close', (code) => {
388
- if (settled) return
389
- settled = true
390
- clearTimeout(timer)
391
- reject(new Error(`reverse forward ${spec} exited early (${code})${stderr ? ': ' + stderr.trim() : ''}`))
392
- })
393
- })
394
- }
395
-
396
- /** Superseded by reverseForward() (the CLI needs the target up front). */
397
- forwardIn(_host, _port, cb) {
398
- setImmediate(() => cb(new Error(
399
- 'the system-OpenSSH backend opens reverse forwards with `ssh -R`, which needs the target up front — use reverseForward()',
400
- )))
401
- }
402
-
403
- close() {
404
- this.closed = true
405
- for (const child of [...this.children]) {
406
- try { child.kill() } catch {}
407
- }
408
- this.children.clear()
409
- }
410
- }
411
-
412
- /**
413
- * A system-OpenSSH pool: the same public surface as lib/pool.js's SshPool,
414
- * backed by the local `ssh` CLI. Callers cannot tell the two apart — see
415
- * test/openssh-backend.test.js, which drives both through one shared contract.
416
- */
417
- export class SystemOpenSshPool {
418
- constructor(config, opts = {}) {
419
- this.config = config
420
- // The native backend's JSON fingerprint registry is NOT an OpenSSH
421
- // known_hosts file. ActivePool supplies a dedicated plain-text path; the
422
- // fallback preserves direct-construction compatibility (issue #118).
423
- this._knownHostsFile = opts.opensshKnownHostsFile ?? opts.knownHostsFile
424
- this.client = null
425
- this.connecting = null
426
- this.proxyPool = null
427
- // Generational token, exactly as the native pool: a stale in-flight connect
428
- // must never hand this pool a connection to an old host.
429
- this.epoch = 0
430
- this.platform = 'unknown'
431
- this.gitBashPath = ''
432
- this.shellMode = 'native'
433
- this._detecting = null
434
- this.passwordResolver = null
435
- this.onReady = null
436
- this.onCloseHook = null
437
- /** The persistent `ssh -s ... sftp` session (kept across calls). */
438
- this._sftpSession = null
439
- this._sftpChild = null
440
- /** Memoized askpass secret for this target (null = not resolved yet). */
441
- this._secret = null
442
- this._secretPromise = null
443
- }
444
-
445
- /**
446
- * The config baseSshArgs should see. `opts.knownHostsFile` (a path, or a
447
- * function returning one, exactly like the native pool) used to be stored
448
- * and silently dropped — so a custom known_hosts never reached the CLI, and
449
- * tests had no way to keep loopback keys out of the user's real file.
450
- * Resolved per call so a function value is honored as late as the native
451
- * backend resolves it.
452
- */
453
- _argConfig() {
454
- const kh = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
455
- return kh ? { ...this.config, knownHostsFile: kh } : this.config
456
- }
457
-
458
- /** The destination OpenSSH should connect to (an alias passes through). */
459
- destination() {
460
- // A bare alias resolves through ~/.ssh/config inside ssh itself, so it is
461
- // handed over untouched; user/port ride on `-l`/`-p` when recorded.
462
- return String(this.config.host || '')
463
- }
464
-
465
- setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
466
- const base = previous || this.config
467
- const wanted = []
468
- if (host !== undefined) wanted.push(['host', String(host)])
469
- if (port !== undefined && Number(port)) wanted.push(['port', Number(port)])
470
- if (username !== undefined) wanted.push(['username', String(username)])
471
- if (password !== undefined && password !== null) wanted.push(['password', String(password)])
472
- if (privateKeyPath !== undefined) wanted.push(['privateKeyPath', String(privateKeyPath)])
473
- if (passphrase !== undefined) wanted.push(['passphrase', String(passphrase)])
474
- if (workspace !== undefined) wanted.push(['workspace', String(workspace)])
475
- if (useAgent !== undefined) wanted.push(['useAgent', !!useAgent])
476
- if (keyboardInteractive !== undefined) wanted.push(['keyboardInteractive', !!keyboardInteractive])
477
- if (proxy !== undefined) wanted.push(['proxy', proxy])
478
- if (hostKeyMode !== undefined) wanted.push(['hostKeyMode', String(hostKeyMode)])
479
- // Issue #51: kept in step with the native pool's setTarget — the two
480
- // backends share one contract (see test/issue51-openssh-backend.test.js), so
481
- // a field one of them diffs must not be silently ignored by the other.
482
- if (backend !== undefined) wanted.push(['backend', String(backend)])
483
- if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
484
- const differs = ([k, v]) => (k === 'proxy'
485
- ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
486
- : base[k] !== v)
487
- if (wanted.some(differs)) {
488
- for (const [k, v] of wanted) this.config[k] = v
489
- this.platform = 'unknown'
490
- this.gitBashPath = ''
491
- this.shellMode = 'native'
492
- this._detecting = null
493
- this.close()
494
- }
495
- return this
496
- }
497
-
498
- /**
499
- * The secret to offer askpass, resolved once per target.
500
- *
501
- * `connect()` no longer has to run first: `exec`/`sftp` call this themselves,
502
- * so a pool that is only ever used for file listing still authenticates.
503
- */
504
- _resolveSecret() {
505
- if (this._secret !== null) return Promise.resolve(this._secret)
506
- if (this._secretPromise) return this._secretPromise
507
- const epoch = this.epoch
508
- this._secretPromise = (async () => {
509
- let secret = this.config.password || ''
510
- if (!secret && this.passwordResolver) {
511
- try { secret = (await this.passwordResolver()) || '' } catch { /* fall through */ }
512
- }
513
- if (!secret) secret = this.config.passphrase || ''
514
- // A target switch invalidates the answer; leave the memo for the new one.
515
- if (this.epoch === epoch) this._secret = String(secret || '')
516
- this._secretPromise = null
517
- return String(secret || '')
518
- })()
519
- return this._secretPromise
520
- }
521
-
522
- /** Validate the environment; there is no socket to hold open. */
523
- connect() {
524
- if (this.client) return Promise.resolve(this.client)
525
- if (this.connecting) return this.connecting
526
- const epoch = this.epoch
527
- const pending = this._doConnect(epoch)
528
- this.connecting = pending
529
- const clear = () => { if (this.epoch === epoch && this.connecting === pending) this.connecting = null }
530
- pending.then(clear, clear)
531
- return pending
532
- }
533
-
534
- async _doConnect(epoch) {
535
- const isCurrent = () => this.epoch === epoch
536
- const sshBinary = resolveSshBinary(this.config)
537
- if (!this.config.host) throw new Error('no host configured')
538
- if (!sshBinaryAvailable(sshBinary)) {
539
- throw new Error(
540
- `the system-OpenSSH backend needs a \`${sshBinary}\` executable on PATH`
541
- + ' — install OpenSSH, or set the backend back to "native"',
542
- )
543
- }
544
- const secret = await this._resolveSecret()
545
- if (!isCurrent()) throw new Error('ssh target changed during connect')
546
- // Native semantics are "connect() throws when the SSH connection fails", and
547
- // a probe also gives the settings page a real latency number. The CLI has no
548
- // socket to keep, so this is the only point where the target is proven.
549
- const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
550
- if (!isCurrent()) throw new Error('ssh target changed during connect')
551
- if (probe.code !== 0) {
552
- throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
553
- }
554
- void secret
555
- const conn = new OpenSshConnection(this, { sshBinary, secret })
556
- this.client = conn
557
- if (this.onReady) { try { this.onReady(conn) } catch {} }
558
- return conn
559
- }
560
-
561
- /**
562
- * Run one `ssh` invocation and collect its result.
563
- *
564
- * @param {string[]} extraArgs - arguments appended after the shared base.
565
- * @param {object} [opts] - `timeoutMs`, `signal` (AbortSignal), `stdin`,
566
- * `onData(channel, chunk)` — a streaming tap the native backend has had
567
- * since issue #70. A background job's value is its LIVE output, which the
568
- * job ring must receive as it arrives; a backend that only returns the
569
- * accumulated text loses every byte the caller stopped waiting for
570
- * (issue #80). Tap errors are not command errors, so the call is guarded.
571
- * @returns {Promise<{code: number|null, signal: string|null, stdout: string, stderr: string}>}
572
- */
573
- async _runSsh(extraArgs, opts = {}) {
574
- if (!this.config.host) throw new Error('no host configured')
575
- const secret = await this._resolveSecret()
576
- const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
577
- const sshBinary = resolveSshBinary(this.config)
578
- const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), ...extraArgs]
579
- return new Promise((resolve) => {
580
- let child
581
- try {
582
- child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
583
- } catch (err) {
584
- return resolve({ code: -1, signal: 'SPAWN_FAILED', stdout: '', stderr: String((err && err.message) || err) })
585
- }
586
- // This path may stream a script into `bash -s` and can be written to
587
- // after the command already exited (Git Bash); a broken pipe there must
588
- // fail the call, not the process (issue #118).
589
- guardChildStdin(child)
590
- let stdout = ''
591
- let stderr = ''
592
- let settled = false
593
- let exitCode = null
594
- let exitSignal = null
595
- const cap = Math.max(this.config.maxOutputChars * 4, 1024 * 1024)
596
- const onData = typeof opts.onData === 'function' ? opts.onData : null
597
- const cleanupAbort = () => { if (opts.signal && onAbort) opts.signal.removeEventListener('abort', onAbort) }
598
- let onAbort = null
599
- const finish = () => {
600
- if (settled) return
601
- settled = true
602
- clearTimeout(timer)
603
- cleanupAbort()
604
- resolve({
605
- code: exitCode,
606
- signal: exitSignal,
607
- stdout: truncate(stdout, this.config.maxOutputChars),
608
- stderr: truncate(stderr, this.config.maxOutputChars),
609
- })
610
- }
611
- const killHard = () => { try { setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 800).unref?.() } catch {} }
612
- // No timer at all for an explicit no-deadline call (0) — see pool.js
613
- // _execRaw; arming one would fire at once or kill a promoted job (issue #95).
614
- const timer = timeoutMs > 0 ? setTimeout(() => {
615
- if (settled) return
616
- exitCode = -1
617
- exitSignal = 'TIMEOUT'
618
- try { child.kill() } catch {}
619
- killHard()
620
- finish()
621
- }, timeoutMs) : null
622
- if (opts.signal) {
623
- if (opts.signal.aborted) {
624
- try { child.kill() } catch {}
625
- exitCode = -1; exitSignal = 'ABORTED'
626
- return finish()
627
- }
628
- onAbort = () => {
629
- if (settled) return
630
- exitCode = -1; exitSignal = 'ABORTED'
631
- try { child.kill() } catch {}
632
- killHard()
633
- finish()
634
- }
635
- opts.signal.addEventListener('abort', onAbort, { once: true })
636
- }
637
- // The tap fires even past the local cap, exactly like the native
638
- // backend's: a promoted job's ring has its own bounds and must keep
639
- // receiving output the truncated return value no longer holds.
640
- child.stdout.on('data', (d) => {
641
- if (stdout.length < cap) stdout += d
642
- if (onData) { try { onData('stdout', d) } catch { /* tap errors are not command errors */ } }
643
- })
644
- child.stderr.on('data', (d) => {
645
- if (stderr.length < cap) stderr += d
646
- if (onData) { try { onData('stderr', d) } catch { /* tap errors are not command errors */ } }
647
- })
648
- child.on('error', (e) => {
649
- if (settled) return
650
- stderr += String((e && e.message) || e)
651
- exitCode = -1
652
- finish()
653
- })
654
- child.on('close', (code, sig) => {
655
- if (settled) return
656
- exitCode = code
657
- exitSignal = sig || null
658
- finish()
659
- })
660
- try { child.stdin.end(opts.stdin === undefined || opts.stdin === null ? undefined : String(opts.stdin)) } catch {}
661
- })
662
- }
663
-
664
- /** Detect the remote platform + locate Git Bash once; cached per target. */
665
- detect() {
666
- if (this.platform !== 'unknown') return Promise.resolve()
667
- if (this._detecting) return this._detecting
668
- this._detecting = this._detect().finally(() => { this._detecting = null })
669
- return this._detecting
670
- }
671
-
672
- async _detect() {
673
- let res
674
- try {
675
- res = await this._runSsh(['--', this.destination(), 'cmd /c ver'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
676
- } catch {
677
- this.platform = 'unknown'
678
- this.shellMode = 'native'
679
- return
680
- }
681
- const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
682
- if (res.code === 0 && /microsoft windows/i.test(out)) {
683
- this.platform = 'windows'
684
- await this._resolveGitBash()
685
- return
686
- }
687
- try {
688
- const u = await this._runSsh(['--', this.destination(), 'uname -s'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
689
- if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
690
- this.platform = 'windows'
691
- await this._resolveGitBash()
692
- return
693
- }
694
- } catch { /* inconclusive — fall through to posix */ }
695
- this.platform = 'posix'
696
- this.shellMode = 'native'
697
- this.gitBashPath = ''
698
- }
699
-
700
- async _resolveGitBash() {
701
- const cfg = String(this.config.shell || '').trim()
702
- const exists = async (p) => {
703
- const r = await this._runSsh(['--', this.destination(), `cmd /c if exist "${p}" (echo Y) else (echo N)`], { timeoutMs: 8000 })
704
- return /Y/.test(String(r.stdout || ''))
705
- }
706
- if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
707
- if (await exists(cfg)) { this.gitBashPath = cfg; this.shellMode = 'git-bash'; return }
708
- }
709
- if (cfg === 'native') { this.shellMode = 'native'; this.gitBashPath = ''; return }
710
- try {
711
- const r = await this._runSsh(['--', this.destination(), 'cmd /c where bash'], { timeoutMs: 8000 })
712
- const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
713
- if (first) { this.gitBashPath = first; this.shellMode = 'git-bash'; return }
714
- } catch { /* fall through to the candidate list */ }
715
- const candidates = [
716
- 'C:\\Program Files\\Git\\bin\\bash.exe',
717
- 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
718
- ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
719
- ]
720
- for (const c of candidates) {
721
- if (await exists(c)) { this.gitBashPath = c; this.shellMode = 'git-bash'; return }
722
- }
723
- this.shellMode = 'git-bash'
724
- this.gitBashPath = ''
725
- }
726
-
727
- /** Run one remote command (Windows + Git Bash is wrapped exactly as native). */
728
- exec(command, timeoutMsOrOpts) {
729
- const opts = timeoutMsOrOpts && typeof timeoutMsOrOpts === 'object' ? timeoutMsOrOpts : { timeoutMs: timeoutMsOrOpts }
730
- return this.detect().then(() => {
731
- const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
732
- if (this.platform === 'windows' && this.gitBashPath) {
733
- // Pipe the script to `bash -s` over stdin: no quoting round-trip, so
734
- // quotes/backslashes/newlines survive verbatim (same as the native pool).
735
- return this._runSsh(['--', this.destination(), `"${this.gitBashPath}" -s`], { timeoutMs, signal: opts.signal, stdin: String(command), onData: opts.onData })
736
- }
737
- return this._runSsh(['--', this.destination(), String(command)], { timeoutMs, signal: opts.signal, onData: opts.onData })
738
- })
739
- }
740
-
741
- /** Open a fresh `ssh -s <dest> sftp` session and its ssh2 SFTP engine. */
742
- async _openSftpChannel() {
743
- const Sftp = loadSftpEngine()
744
- const secret = await this._resolveSecret()
745
- const sshBinary = resolveSshBinary(this.config)
746
- const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), '-s', this.destination(), 'sftp']
747
- const child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
748
-
749
- // ssh2's SFTP engine only reaches `_protocol` for channelData/channelClose,
750
- // and reads `_remoteIdentRaw` to pick its packet sizes.
751
- //
752
- // ## Flow control, the subtle part
753
- //
754
- // Over real SSH the engine's send window is topped up by CHANNEL_WINDOW_ADJUST
755
- // messages from the peer. On a raw `ssh -s sftp` pipe THERE ARE NO SUCH
756
- // MESSAGES — the local ssh owns the SSH-layer window and the server's grants,
757
- // and all we have is a byte pipe with OS-level backpressure. So the engine's
758
- // window has to be mapped onto the pipe's writability:
759
- //
760
- // • a write the pipe accepts → more will fit;
761
- // • the pipe fills (`stdin.write` returns false) → clamp the window so the
762
- // engine buffers the remainder instead of queueing it all in memory;
763
- // • the pipe drains → grant the window back and let the engine flush.
764
- //
765
- // The trap, and why the constants below are what they are: ssh2 arms its
766
- // flush callback (`_waitWindow` / `_chunkcb = drainBuffer`) ONLY from inside
767
- // its own subtraction, at the moment that subtraction takes the window to
768
- // exactly 0. So the window must be handed over in EXACT MULTIPLES of
769
- // packetSize and then left alone: the engine's own arithmetic then lands on 0
770
- // during normal operation and arms the flush callback we depend on.
771
- //
772
- // Do NOT "help" by clamping the window to 0 from inside channelData when the
773
- // pipe reports itself full. That sets the window to 0 AFTER the subtraction
774
- // has already happened, so the callback is never armed and the buffered
775
- // remainder is never flushed — the transfer deadlocks with a full window.
776
- // (Measured: a 4 MB upload stopped dead after 32 KB, with `_buffer.length`
777
- // stuck at 1 and no callback pending.) The pipe's own `drain` event is the
778
- // only place the window is refilled.
779
- //
780
- // Also tempting-but-wrong: adding each received packet's length to the
781
- // window. That happens to work for a DOWNLOAD (the peer's data is the
782
- // window) and deadlocks an upload, because a write's acknowledgements are
783
- // tiny status packets while each send consumes ~32 KB.
784
- //
785
- // See scripts/integration-openssh-large.mjs, which is what caught all of this.
786
- const PACKET = 32768
787
- const GRANT = PACKET * 8 // 256 KB per burst, and a multiple of packetSize
788
- const chan = { sftp: null }
789
- const fakeClient = {
790
- _protocol: {
791
- _remoteIdentRaw: Buffer.from('SSH-2.0-OpenSSH'),
792
- // Hand the bytes to the pipe and nothing else. Backpressure is expressed
793
- // through the engine's own window draining (see above); the OS pipe
794
- // buffer plus Node's write buffer absorb the in-flight remainder.
795
- channelData(_id, data) { try { child.stdin.write(data) } catch { /* close handles it */ } },
796
- channelClose() { try { child.stdin.end() } catch {} },
797
- },
798
- }
799
- const chanInfo = {
800
- type: 'sftp',
801
- incoming: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
802
- outgoing: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
803
- }
804
- // The stdin pipe can die underneath the engine at any moment (the remote
805
- // side of the sftp subsystem exits, the link drops — issue #118). Each write
806
- // after that fails, and without an 'error' listener the failure is an
807
- // uncaught exception that takes the whole Host down. Registering the guard
808
- // here, next to the only two places that write to this pipe, keeps the
809
- // blast radius at "this session is gone": 'close' fires as usual and the
810
- // cached session is dropped by sftp()'s own handler.
811
- guardChildStdin(child, () => { try { child.kill() } catch { /* already gone */ } })
812
- const sftp = new Sftp(fakeClient, chanInfo, {})
813
- chan.sftp = sftp
814
-
815
- // The pipe has room again: grant the window back and let the engine flush
816
- // whatever it buffered while the pipe was full.
817
- const onStdinDrain = () => {
818
- if (!chan.sftp) return
819
- chan.sftp.outgoing.window = GRANT
820
- if (chan.sftp._waitWindow) {
821
- chan.sftp._waitWindow = false
822
- const cb = chan.sftp._chunkcb
823
- chan.sftp._chunkcb = undefined
824
- if (typeof cb === 'function') cb.call(chan.sftp)
825
- }
826
- }
827
- child.stdin.on('drain', onStdinDrain)
828
- // A dead SSH process reports stdin EPIPE asynchronously. Without a stream
829
- // error listener Node crashes the host before close/drop can reset the
830
- // cached session (issue #118); kill it so that existing recovery runs.
831
- child.stdin.on('error', () => { try { child.kill() } catch {} })
832
-
833
- return new Promise((resolve, reject) => {
834
- let stderr = ''
835
- let settled = false
836
- const done = (err) => {
837
- if (settled) return
838
- settled = true
839
- clearTimeout(timer)
840
- if (err) { try { child.kill() } catch {} ; reject(err) } else resolve({ child, sftp })
841
- }
842
- const timer = setTimeout(() => {
843
- done(new Error(`sftp session to ${this.destination()} timed out${stderr ? ': ' + stderr.trim() : ''}`))
844
- }, this.config.commandTimeoutMs)
845
- child.stderr.on('data', (d) => { stderr += d })
846
- sftp.on('error', (e) => done(new Error('sftp session failed: ' + ((e && e.message) || e))))
847
- sftp.on('ready', () => done(null))
848
- child.on('error', (e) => done(e))
849
- child.on('close', (code) => done(new Error(`ssh sftp exited (${code})${stderr ? ': ' + stderr.trim() : ''}`)))
850
- // Inbound is simpler: the local ssh already did the SSH-level window
851
- // accounting before handing us these bytes, so they just go straight in.
852
- child.stdout.on('data', (d) => { sftp.push(d) })
853
- child.stdout.on('end', () => { try { sftp.push(null) } catch { /* already gone */ } })
854
- sftp._init()
855
- })
856
- }
857
-
858
- /**
859
- * A persistent SFTP session, kept across calls: the picker and the explorer
860
- * issue one listing per interaction, and re-handshaking each time would be
861
- * visibly slow. A session that dies is dropped so the next call reconnects.
862
- */
863
- sftp() {
864
- if (this._sftpSession) return this._sftpSession
865
- const epoch = this.epoch
866
- const session = this._openSftpChannel().then(({ child, sftp }) => {
867
- const drop = () => {
868
- if (this._sftpSession === session) this._sftpSession = null
869
- if (this._sftpChild === child) this._sftpChild = null
870
- }
871
- child.on('close', drop)
872
- sftp.on('end', drop)
873
- sftp.on('error', drop)
874
- // A target switch during the handshake must not adopt the old host's
875
- // session (the same generational guard connect() uses).
876
- if (this.epoch !== epoch) {
877
- try { child.kill() } catch {}
878
- throw new Error('ssh target changed while opening sftp')
879
- }
880
- this._sftpChild = child
881
- return buildSftpSurface(sftp, {
882
- commandTimeoutMs: this.config.commandTimeoutMs,
883
- onTimeout: () => {
884
- // A timed-out SFTP session is dead: kill the child and drop the cached
885
- // session so the next call re-handshakes instead of queueing behind the
886
- // wedged one (issue #65).
887
- try { child.kill() } catch { /* already gone */ }
888
- drop()
889
- },
890
- })
891
- })
892
- // Never cache a rejected open: the next call must retry rather than get the
893
- // same error back forever (a failed handshake is usually transient).
894
- session.catch(() => { if (this._sftpSession === session) this._sftpSession = null })
895
- this._sftpSession = session
896
- return session
897
- }
898
-
899
- invalidate() {
900
- this.epoch++
901
- const client = this.client
902
- this.client = null
903
- this.connecting = null
904
- this._secret = null
905
- this._secretPromise = null
906
- if (client) { try { client.close() } catch {} }
907
- this._dropSftpSession()
908
- if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
909
- if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
910
- }
911
-
912
- _dropSftpSession() {
913
- const session = this._sftpSession
914
- this._sftpSession = null
915
- if (this._sftpChild) {
916
- try { this._sftpChild.kill() } catch {}
917
- this._sftpChild = null
918
- }
919
- // Swallow the rejection: nobody awaits a session we are tearing down.
920
- if (session && typeof session.catch === 'function') session.catch(() => {})
921
- }
922
-
923
- close() {
924
- this.epoch++
925
- const client = this.client
926
- this.client = null
927
- this.connecting = null
928
- this._secret = null
929
- this._secretPromise = null
930
- if (client) { try { client.close() } catch {} }
931
- this._dropSftpSession()
932
- if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
933
- if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
934
- }
935
- }
936
-
937
- /** Pick the pool class for a config: 'openssh' backend, else the native pool. */
938
- export function isSystemOpenSshBackend(config = {}) {
939
- return String(config.backend || '').toLowerCase() === 'openssh'
940
- }
1
+ // dsh-remote — the "system OpenSSH" SSH backend (issue #51).
2
+ //
3
+ // ## Why this exists
4
+ //
5
+ // The default backend (lib/pool.js) speaks SSH itself through ssh2, so it can
6
+ // only use the authentication methods ssh2 implements: password, private key,
7
+ // ssh-agent and keyboard-interactive. Enterprise hosts that only allow
8
+ // GSSAPI/Kerberos are unreachable, even though `ssh <alias>` in the user's own
9
+ // terminal works — the local Kerberos ticket (kinit) is simply not something
10
+ // ssh2 knows how to present.
11
+ //
12
+ // This backend delegates the transport to the LOCAL `ssh` executable, so every
13
+ // `~/.ssh/config` feature the user already relies on applies: gssapi-with-mic,
14
+ // ProxyJump, ProxyCommand, ControlPath, Host aliases, IdentityFile,
15
+ // PKCS11Provider, Match blocks… Anything OpenSSH can do, this backend can do,
16
+ // because OpenSSH is the one doing it.
17
+ //
18
+ // ## How each primitive is implemented
19
+ //
20
+ // exec → `ssh <opts> -- <dest> <command>` (one process per call)
21
+ // sftp → `ssh <opts> -s <dest> sftp` + ssh2's OWN SFTP protocol engine
22
+ // driven over the resulting raw byte stream
23
+ // forwardOut → `ssh <opts> -W <host>:<port> <dest>` (one process per tunnel)
24
+ // reverse → `ssh <opts> -N -R <bind>:<port>:<h>:<p> <dest>`
25
+ //
26
+ // The SFTP one deserves a note, because it is the reason this backend did not
27
+ // have to reimplement file transfer: `ssh -s <dest> sftp` on stdio is a PLAIN
28
+ // SFTP v3 byte stream (verified against a real host — the subsystem replies
29
+ // with its VERSION packet and nothing else on stdout). ssh2 already ships a
30
+ // complete, battle-tested SFTP implementation that speaks exactly that protocol
31
+ // over a duplex stream, so this module gives it a minimal `_protocol` shim and
32
+ // hands it the child process's stdio. File transfer therefore has the same
33
+ // semantics — and the same large-packet optimisations — as the native backend.
34
+ //
35
+ // ## Trade-offs (documented, not hidden)
36
+ //
37
+ // • spawn-per-operation: unlike the native pool there is no long-lived
38
+ // connection multiplexed across commands, so each `exec`/`forwardOut` pays
39
+ // a fresh SSH handshake. That is inherent to delegating to the `ssh` CLI:
40
+ // Windows OpenSSH rejects ControlMaster ("getsockname failed: Not a
41
+ // socket", measured), and a portable multiplexing layer would be a second
42
+ // implementation of what the native backend already does. The SFTP path IS
43
+ // kept persistent, because the workspace picker and the explorer hammer it.
44
+ // • the passphrase/password prompt: OpenSSH asks for both through the same
45
+ // askpass channel, so when a secret is configured this backend offers it
46
+ // for whichever prompt appears (password first, then passphrase). A host
47
+ // needing two DIFFERENT secrets is not representable here — use the native
48
+ // backend for that.
49
+ // • reverse forwards need their target up front (the CLI takes it as an
50
+ // argument), so they are exposed as `reverseForward()` and ForwardManager
51
+ // prefers it when present.
52
+ // • host keys are checked by ssh itself against the user's own known_hosts,
53
+ // not against the plugin's TOFU store: making `ssh` use a different trust
54
+ // anchor per machine is exactly the kind of override that breaks the
55
+ // enterprise setups this backend exists to serve. `hostKeyMode` maps onto
56
+ // StrictHostKeyChecking instead.
57
+
58
+ import { spawn } from 'node:child_process'
59
+ import { accessSync, chmodSync, constants as fsConstants, mkdirSync, writeFileSync } from 'node:fs'
60
+ import { createRequire } from 'node:module'
61
+ import { EventEmitter } from 'node:events'
62
+ import { homedir, tmpdir } from 'node:os'
63
+ import path from 'node:path'
64
+ import { Duplex } from 'node:stream'
65
+ import { buildSftpSurface } from './sftp-surface.js'
66
+ import { truncate } from './paths.js'
67
+
68
+ // The SFTP protocol engine lives at lib/protocol/SFTP.js inside ssh2 and is not
69
+ // part of its public API. Creating it through createRequire keeps this module
70
+ // ESM-clean while still reaching it; if a future ssh2 moves it, this fails with
71
+ // an actionable message instead of a bare MODULE_NOT_FOUND at connect time.
72
+ const require_ = createRequire(import.meta.url)
73
+ let SftpEngine = null
74
+ export function loadSftpEngine() {
75
+ if (SftpEngine) return SftpEngine
76
+ try {
77
+ const entry = require_.resolve('ssh2')
78
+ const sftpPath = entry.replace(/lib[\\/]index\.js$/, 'lib/protocol/SFTP.js')
79
+ SftpEngine = require_(sftpPath).SFTP
80
+ } catch (err) {
81
+ throw new Error("system-OpenSSH backend could not load ssh2's SFTP engine: " + ((err && err.message) || err))
82
+ }
83
+ if (typeof SftpEngine !== 'function') {
84
+ throw new Error("system-OpenSSH backend found no SFTP engine in this ssh2 install")
85
+ }
86
+ return SftpEngine
87
+ }
88
+
89
+ /** The `ssh` executable this backend drives (config override wins). */
90
+ export function resolveSshBinary(config = {}) {
91
+ return String(config.sshBinary || '').trim() || 'ssh'
92
+ }
93
+
94
+ /**
95
+ * Path of the user's own known_hosts. Exposed for the UI; the backend itself
96
+ * never points ssh at a different file (see the header).
97
+ */
98
+ export function defaultKnownHostsPath() {
99
+ return path.join(homedir(), '.ssh', 'known_hosts')
100
+ }
101
+
102
+ /**
103
+ * Translate `hostKeyMode` into OpenSSH's StrictHostKeyChecking.
104
+ *
105
+ * `accept-new` is ssh's own default on modern OpenSSH and matches the plugin's
106
+ * TOFU default; `verify` refuses unknown hosts; `off` accepts anything.
107
+ */
108
+ export function hostKeyArgs(config = {}) {
109
+ const mode = config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new'
110
+ const strict = mode === 'verify' ? 'yes' : mode === 'off' ? 'no' : 'accept-new'
111
+ return ['-o', `StrictHostKeyChecking=${strict}`]
112
+ }
113
+
114
+ /**
115
+ * Where the generated askpass helper lives. One stable directory per user, so
116
+ * the helper is written once and reused; the helper carries NO secret (it reads
117
+ * the secret from the environment), which is why writing it to disk is safe.
118
+ */
119
+ export function askpassDir() {
120
+ return path.join(tmpdir(), 'dsh-remote-askpass')
121
+ }
122
+
123
+ /**
124
+ * Ensure an askpass helper exists and return its path.
125
+ *
126
+ * The helper prints $DSH_REMOTE_SSH_SECRET. Passing the secret through the
127
+ * environment (rather than as an argument or a file) keeps it out of `ps`,
128
+ * argv and the filesystem. The Windows helper is a .cmd that invokes Node via
129
+ * `process.execPath`, because `@echo %VAR%` would mangle secrets containing cmd
130
+ * metacharacters (&, %, ^ …) and a bare `echo` is not a shell we control.
131
+ */
132
+ export function ensureAskpassHelper() {
133
+ const dir = askpassDir()
134
+ try { mkdirSync(dir, { recursive: true }) } catch { /* already there */ }
135
+ if (process.platform === 'win32') {
136
+ const js = path.join(dir, 'askpass.js')
137
+ const cmd = path.join(dir, 'askpass.cmd')
138
+ try {
139
+ writeFileSync(js, 'process.stdout.write((process.env.DSH_REMOTE_SSH_SECRET || "") + "\\n")\n')
140
+ writeFileSync(cmd, '@echo off\r\n"' + process.execPath + '" "' + js + '"\r\n')
141
+ } catch (err) {
142
+ throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
143
+ }
144
+ return cmd
145
+ }
146
+ const sh = path.join(dir, 'askpass.sh')
147
+ try {
148
+ writeFileSync(sh, '#!/bin/sh\nprintf \'%s\\n\' "$DSH_REMOTE_SSH_SECRET"\n')
149
+ try { chmodSync(sh, 0o700) } catch { /* best effort on odd filesystems */ }
150
+ } catch (err) {
151
+ throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
152
+ }
153
+ return sh
154
+ }
155
+
156
+ /** Env that hands the secret to the askpass helper (never argv, never a file). */
157
+ export function askpassEnv(secret) {
158
+ return {
159
+ ...process.env,
160
+ SSH_ASKPASS: ensureAskpassHelper(),
161
+ SSH_ASKPASS_REQUIRE: 'force',
162
+ DISPLAY: process.env.DISPLAY || ':0',
163
+ DSH_REMOTE_SSH_SECRET: String(secret),
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Keep an EPIPE on a child's stdin from becoming a process-wide crash.
169
+ *
170
+ * A child that stops reading — the remote side of `ssh -s sftp` dying mid-
171
+ * transfer is the one that bites — makes the NEXT write to its stdin fail. Node
172
+ * reports that asynchronously through the Writable's `'error'` event, so a
173
+ * synchronous `try/catch` around `write()` never sees it; an unhandled
174
+ * `'error'` on a stream is an uncaught exception, and the Host treats one of
175
+ * those as fatal (issue #118: `dsh: fatal uncaught exception: Error: write
176
+ * EPIPE` → the whole app's host process exits and every session is lost).
177
+ *
178
+ * Every `spawn` in this file therefore gets this hook: swallow the pipe error,
179
+ * report it to `onError` when the caller has cleanup to do, and let the
180
+ * existing `'close'`/`'error'` handling own the rest. A missing `ssh` binary
181
+ * is a different signal — spawn reports it on the CHILD, not on its stdin — so
182
+ * it still reaches the caller as a real error.
183
+ *
184
+ * @param {import('node:child_process').ChildProcess} child
185
+ * @param {(err: Error) => void} [onError] - e.g. drop the cached SFTP session.
186
+ * @returns {import('node:child_process').ChildProcess} the same child.
187
+ */
188
+ export function guardChildStdin(child, onError) {
189
+ const stdin = child && child.stdin
190
+ if (!stdin || typeof stdin.on !== 'function') return child
191
+ // A listener is the difference between "this stream reported a problem" and
192
+ // "this process died": without one Node re-throws the error as an uncaught
193
+ // exception. There is nothing to retry here — the pipe is gone — so all that
194
+ // is left is to let the caller drop whatever it cached for this child; the
195
+ // child's own 'close'/'error' handling still reports the real failure.
196
+ stdin.on('error', (err) => {
197
+ if (typeof onError === 'function') { try { onError(err) } catch { /* best effort */ } }
198
+ })
199
+ return child
200
+ }
201
+
202
+ /** Is `ssh` runnable? Used to fail with an actionable message, not ENOENT. */
203
+ export function sshBinaryAvailable(binary) {
204
+ if (binary.includes('/') || binary.includes('\\')) {
205
+ try { accessSync(binary, fsConstants.X_OK); return true } catch { return false }
206
+ }
207
+ const exts = process.platform === 'win32'
208
+ ? String(process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').filter(Boolean)
209
+ : ['']
210
+ for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
211
+ if (!dir) continue
212
+ for (const ext of exts) {
213
+ try { accessSync(path.join(dir, binary + ext), fsConstants.X_OK); return true } catch { /* keep looking */ }
214
+ }
215
+ }
216
+ return false
217
+ }
218
+
219
+ /**
220
+ * Options shared by every `ssh` invocation for this target.
221
+ *
222
+ * Deliberately NOT passed: PreferredAuthentications / GSSAPIAuthentication /
223
+ * PubkeyAcceptedKeyTypes / IdentitiesOnly-from-the-alias / ProxyJump-from-the-
224
+ * alias. Those must come from the user's `~/.ssh/config` — overriding them is
225
+ * precisely what would break the enterprise setups this backend exists for.
226
+ *
227
+ * @param {object} config - the pool config.
228
+ * @param {object} [opts]
229
+ * @param {boolean} [opts.forSecret] - true when a secret will be offered via
230
+ * askpass, which means BatchMode must be OFF (BatchMode forbids every
231
+ * interactive prompt, askpass included) and the prompt count bounded instead.
232
+ */
233
+ export function baseSshArgs(config, { forSecret = false } = {}) {
234
+ const args = []
235
+ if (config.port && Number(config.port) !== 22) args.push('-p', String(Number(config.port)))
236
+ if (config.username) args.push('-l', String(config.username))
237
+ if (config.privateKeyPath) args.push('-i', String(config.privateKeyPath))
238
+ // An explicit jump host — the same shape the native backend's `proxy` takes.
239
+ // A jump host that comes from ~/.ssh/config needs nothing here.
240
+ const proxy = config.proxy
241
+ if (proxy && proxy.host) {
242
+ const user = proxy.username ? `${proxy.username}@` : ''
243
+ const port = proxy.port && Number(proxy.port) !== 22 ? `:${Number(proxy.port)}` : ''
244
+ args.push('-J', `${user}${proxy.host}${port}`)
245
+ }
246
+ // An explicit known_hosts file (tests keep loopback keys OUT of the user's
247
+ // real ~/.ssh/known_hosts with this; ssh ignores $HOME on some platforms).
248
+ // Checking strength is unchanged — StrictHostKeyChecking below still applies.
249
+ if (config.knownHostsFile) args.push('-o', `UserKnownHostsFile=${config.knownHostsFile}`)
250
+ args.push(...hostKeyArgs(config))
251
+ const connectSecs = Math.max(1, Math.round((Number(config.connectTimeoutMs) || 15000) / 1000))
252
+ args.push('-o', `ConnectTimeout=${connectSecs}`, '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3')
253
+ // Without a configured secret we must not hang on an interactive prompt:
254
+ // BatchMode makes ssh fail fast instead, and leaves key/agent/GSSAPI intact.
255
+ if (!forSecret) args.push('-o', 'BatchMode=yes')
256
+ else args.push('-o', 'NumberOfPasswordPrompts=1')
257
+ return args
258
+ }
259
+
260
+ /**
261
+ * One live system-OpenSSH connection.
262
+ *
263
+ * This deliberately mimics the ssh2 Client surface the rest of the plugin
264
+ * consumes — `forwardOut` plus a reverse-forward capability — so
265
+ * ForwardManager/WebAttach work unchanged. It is an EventEmitter because the
266
+ * native pool's client is one and callers attach listeners to it.
267
+ */
268
+ export class OpenSshConnection extends EventEmitter {
269
+ constructor(pool, { sshBinary, secret }) {
270
+ super()
271
+ this.pool = pool
272
+ this.sshBinary = sshBinary
273
+ this.secret = secret
274
+ this.closed = false
275
+ /** Live child processes to reap on close. */
276
+ this.children = new Set()
277
+ }
278
+
279
+ shortDescription() {
280
+ return `${this.pool.destination()} via ${this.sshBinary}`
281
+ }
282
+
283
+ spawnSsh(extraArgs, { tty = false } = {}) {
284
+ if (this.closed) throw new Error('ssh connection closed')
285
+ const args = [
286
+ ...baseSshArgs(this.pool._argConfig(), { forSecret: !!this.secret }),
287
+ ...extraArgs,
288
+ ]
289
+ const child = spawn(this.sshBinary, args, {
290
+ stdio: ['pipe', 'pipe', 'pipe'],
291
+ env: this.secret ? askpassEnv(this.secret) : undefined,
292
+ })
293
+ this.children.add(child)
294
+ const reap = () => this.children.delete(child)
295
+ // Every connection-level child goes through here (the `ssh -W` forward
296
+ // channel and the `ssh -N` reverse forward), so the stdin guard for those
297
+ // two paths belongs here rather than at each call site: a tunnel whose peer
298
+ // vanished must end as a closed channel, not as a fatal EPIPE (issue #118).
299
+ guardChildStdin(child)
300
+ child.on('close', reap)
301
+ child.on('error', reap)
302
+ if (tty) { /* no pty support through the CLI without a tty helper */ }
303
+ return child
304
+ }
305
+
306
+ /**
307
+ * Local forward: carry bytes to <destHost>:<destPort> as seen FROM the
308
+ * remote, through `ssh -W`.
309
+ *
310
+ * @returns {boolean} true synchronously, so capability probes can be sync.
311
+ */
312
+ forwardOut(_srcHost, _srcPort, destHost, destPort, cb) {
313
+ let child
314
+ try {
315
+ child = this.spawnSsh(['-W', `${destHost}:${destPort}`, '--', this.pool.destination()])
316
+ } catch (err) {
317
+ setImmediate(() => cb(err))
318
+ return true
319
+ }
320
+ // `ssh -W` reports failures on stderr and then exits; surface that as the
321
+ // channel error so the caller destroys its socket instead of hanging.
322
+ let stderr = ''
323
+ let handed = false
324
+ const channel = new Duplex({
325
+ read() {},
326
+ write(chunk, _enc, done) { try { child.stdin.write(chunk, done) } catch (e) { done(e) } },
327
+ final(done) { try { child.stdin.end(done) } catch { done() } },
328
+ destroy(err, done) { try { child.kill() } catch {} ; done(err) },
329
+ })
330
+ channel.close = () => { try { child.kill() } catch {} }
331
+ child.stderr.on('data', (d) => { stderr += d })
332
+ child.stdout.on('data', (d) => channel.push(d))
333
+ child.stdout.on('end', () => channel.push(null))
334
+ child.on('error', (e) => { if (!handed) { handed = true; cb(e); return } channel.destroy(e) })
335
+ child.on('close', (code) => {
336
+ if (handed) { channel.push(null); return }
337
+ handed = true
338
+ if (code === 0) { cb(null, channel); return }
339
+ cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
340
+ })
341
+ return true
342
+ }
343
+
344
+ /** Tells ForwardManager that the CLI-specific reverse path is available. */
345
+ get supportsReverseForward() { return true }
346
+
347
+ /**
348
+ * Reverse forward: ask the REMOTE to listen on <bindHost>:<listenPort> and
349
+ * carry connections to <targetHost>:<targetPort>. Unlike ssh2's two-phase
350
+ * `forwardIn` + `tcpip`, the `ssh -R` CLI takes the final target as an
351
+ * argument, so nothing has to be resolved lazily.
352
+ *
353
+ * @returns {Promise<{child: object, close: Function}>}
354
+ */
355
+ reverseForward({ bindHost = '127.0.0.1', listenPort, targetHost = '127.0.0.1', targetPort }) {
356
+ return new Promise((resolve, reject) => {
357
+ const spec = `${bindHost}:${listenPort}:${targetHost}:${targetPort}`
358
+ let child
359
+ try {
360
+ child = this.spawnSsh(['-N', '-o', 'ExitOnForwardFailure=yes', '-R', spec, '--', this.pool.destination()])
361
+ } catch (err) { return reject(err) }
362
+ let stderr = ''
363
+ let settled = false
364
+ const fail = (err) => {
365
+ if (settled) return
366
+ settled = true
367
+ clearTimeout(timer)
368
+ try { child.kill() } catch {}
369
+ reject(err)
370
+ }
371
+ child.stderr.on('data', (d) => {
372
+ stderr += d
373
+ // Nothing prints on success; an error before the grace window is the
374
+ // only signal `ssh -N` gives that the forward did not take.
375
+ if (/warning|error|failed|refused|denied|cannot|not permitted|unable/i.test(String(d))) {
376
+ fail(new Error(`reverse forward ${spec} failed: ${stderr.trim()}`))
377
+ }
378
+ })
379
+ child.on('error', fail)
380
+ // `ssh -N` stays in the foreground; a process that outlives the grace
381
+ // window means the remote listener was accepted.
382
+ const timer = setTimeout(() => {
383
+ if (settled) return
384
+ settled = true
385
+ resolve({ child, close: () => { try { child.kill() } catch {} } })
386
+ }, 700)
387
+ child.on('close', (code) => {
388
+ if (settled) return
389
+ settled = true
390
+ clearTimeout(timer)
391
+ reject(new Error(`reverse forward ${spec} exited early (${code})${stderr ? ': ' + stderr.trim() : ''}`))
392
+ })
393
+ })
394
+ }
395
+
396
+ /** Superseded by reverseForward() (the CLI needs the target up front). */
397
+ forwardIn(_host, _port, cb) {
398
+ setImmediate(() => cb(new Error(
399
+ 'the system-OpenSSH backend opens reverse forwards with `ssh -R`, which needs the target up front — use reverseForward()',
400
+ )))
401
+ }
402
+
403
+ close() {
404
+ this.closed = true
405
+ for (const child of [...this.children]) {
406
+ try { child.kill() } catch {}
407
+ }
408
+ this.children.clear()
409
+ }
410
+ }
411
+
412
+ /**
413
+ * A system-OpenSSH pool: the same public surface as lib/pool.js's SshPool,
414
+ * backed by the local `ssh` CLI. Callers cannot tell the two apart — see
415
+ * test/openssh-backend.test.js, which drives both through one shared contract.
416
+ */
417
+ export class SystemOpenSshPool {
418
+ constructor(config, opts = {}) {
419
+ this.config = config
420
+ // The native backend's JSON fingerprint registry is NOT an OpenSSH
421
+ // known_hosts file. ActivePool supplies a dedicated plain-text path; the
422
+ // fallback preserves direct-construction compatibility (issue #118).
423
+ this._knownHostsFile = opts.opensshKnownHostsFile ?? opts.knownHostsFile
424
+ this.client = null
425
+ this.connecting = null
426
+ this.proxyPool = null
427
+ // Generational token, exactly as the native pool: a stale in-flight connect
428
+ // must never hand this pool a connection to an old host.
429
+ this.epoch = 0
430
+ this.platform = 'unknown'
431
+ this.gitBashPath = ''
432
+ this.shellMode = 'native'
433
+ this._detecting = null
434
+ this.passwordResolver = null
435
+ this.onReady = null
436
+ this.onCloseHook = null
437
+ /** The persistent `ssh -s ... sftp` session (kept across calls). */
438
+ this._sftpSession = null
439
+ this._sftpChild = null
440
+ /** Memoized askpass secret for this target (null = not resolved yet). */
441
+ this._secret = null
442
+ this._secretPromise = null
443
+ }
444
+
445
+ /**
446
+ * The config baseSshArgs should see. `opts.knownHostsFile` (a path, or a
447
+ * function returning one, exactly like the native pool) used to be stored
448
+ * and silently dropped — so a custom known_hosts never reached the CLI, and
449
+ * tests had no way to keep loopback keys out of the user's real file.
450
+ * Resolved per call so a function value is honored as late as the native
451
+ * backend resolves it.
452
+ */
453
+ _argConfig() {
454
+ const kh = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
455
+ return kh ? { ...this.config, knownHostsFile: kh } : this.config
456
+ }
457
+
458
+ /** The destination OpenSSH should connect to (an alias passes through). */
459
+ destination() {
460
+ // A bare alias resolves through ~/.ssh/config inside ssh itself, so it is
461
+ // handed over untouched; user/port ride on `-l`/`-p` when recorded.
462
+ return String(this.config.host || '')
463
+ }
464
+
465
+ setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
466
+ const base = previous || this.config
467
+ const wanted = []
468
+ if (host !== undefined) wanted.push(['host', String(host)])
469
+ if (port !== undefined && Number(port)) wanted.push(['port', Number(port)])
470
+ if (username !== undefined) wanted.push(['username', String(username)])
471
+ if (password !== undefined && password !== null) wanted.push(['password', String(password)])
472
+ if (privateKeyPath !== undefined) wanted.push(['privateKeyPath', String(privateKeyPath)])
473
+ if (passphrase !== undefined) wanted.push(['passphrase', String(passphrase)])
474
+ if (workspace !== undefined) wanted.push(['workspace', String(workspace)])
475
+ if (useAgent !== undefined) wanted.push(['useAgent', !!useAgent])
476
+ if (keyboardInteractive !== undefined) wanted.push(['keyboardInteractive', !!keyboardInteractive])
477
+ if (proxy !== undefined) wanted.push(['proxy', proxy])
478
+ if (hostKeyMode !== undefined) wanted.push(['hostKeyMode', String(hostKeyMode)])
479
+ // Issue #51: kept in step with the native pool's setTarget — the two
480
+ // backends share one contract (see test/issue51-openssh-backend.test.js), so
481
+ // a field one of them diffs must not be silently ignored by the other.
482
+ if (backend !== undefined) wanted.push(['backend', String(backend)])
483
+ if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
484
+ const differs = ([k, v]) => (k === 'proxy'
485
+ ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
486
+ : base[k] !== v)
487
+ if (wanted.some(differs)) {
488
+ for (const [k, v] of wanted) this.config[k] = v
489
+ this.platform = 'unknown'
490
+ this.gitBashPath = ''
491
+ this.shellMode = 'native'
492
+ this._detecting = null
493
+ this.close()
494
+ }
495
+ return this
496
+ }
497
+
498
+ /**
499
+ * The secret to offer askpass, resolved once per target.
500
+ *
501
+ * `connect()` no longer has to run first: `exec`/`sftp` call this themselves,
502
+ * so a pool that is only ever used for file listing still authenticates.
503
+ */
504
+ _resolveSecret() {
505
+ if (this._secret !== null) return Promise.resolve(this._secret)
506
+ if (this._secretPromise) return this._secretPromise
507
+ const epoch = this.epoch
508
+ this._secretPromise = (async () => {
509
+ let secret = this.config.password || ''
510
+ if (!secret && this.passwordResolver) {
511
+ try { secret = (await this.passwordResolver()) || '' } catch { /* fall through */ }
512
+ }
513
+ if (!secret) secret = this.config.passphrase || ''
514
+ // A target switch invalidates the answer; leave the memo for the new one.
515
+ if (this.epoch === epoch) this._secret = String(secret || '')
516
+ this._secretPromise = null
517
+ return String(secret || '')
518
+ })()
519
+ return this._secretPromise
520
+ }
521
+
522
+ /** Validate the environment; there is no socket to hold open. */
523
+ connect() {
524
+ if (this.client) return Promise.resolve(this.client)
525
+ if (this.connecting) return this.connecting
526
+ const epoch = this.epoch
527
+ const pending = this._doConnect(epoch)
528
+ this.connecting = pending
529
+ const clear = () => { if (this.epoch === epoch && this.connecting === pending) this.connecting = null }
530
+ pending.then(clear, clear)
531
+ return pending
532
+ }
533
+
534
+ async _doConnect(epoch) {
535
+ const isCurrent = () => this.epoch === epoch
536
+ const sshBinary = resolveSshBinary(this.config)
537
+ if (!this.config.host) throw new Error('no host configured')
538
+ if (!sshBinaryAvailable(sshBinary)) {
539
+ throw new Error(
540
+ `the system-OpenSSH backend needs a \`${sshBinary}\` executable on PATH`
541
+ + ' — install OpenSSH, or set the backend back to "native"',
542
+ )
543
+ }
544
+ const secret = await this._resolveSecret()
545
+ if (!isCurrent()) throw new Error('ssh target changed during connect')
546
+ // Native semantics are "connect() throws when the SSH connection fails", and
547
+ // a probe also gives the settings page a real latency number. The CLI has no
548
+ // socket to keep, so this is the only point where the target is proven.
549
+ const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
550
+ if (!isCurrent()) throw new Error('ssh target changed during connect')
551
+ if (probe.code !== 0) {
552
+ throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
553
+ }
554
+ void secret
555
+ const conn = new OpenSshConnection(this, { sshBinary, secret })
556
+ this.client = conn
557
+ if (this.onReady) { try { this.onReady(conn) } catch {} }
558
+ return conn
559
+ }
560
+
561
+ /**
562
+ * Run one `ssh` invocation and collect its result.
563
+ *
564
+ * @param {string[]} extraArgs - arguments appended after the shared base.
565
+ * @param {object} [opts] - `timeoutMs`, `signal` (AbortSignal), `stdin`,
566
+ * `onData(channel, chunk)` — a streaming tap the native backend has had
567
+ * since issue #70. A background job's value is its LIVE output, which the
568
+ * job ring must receive as it arrives; a backend that only returns the
569
+ * accumulated text loses every byte the caller stopped waiting for
570
+ * (issue #80). Tap errors are not command errors, so the call is guarded.
571
+ * @returns {Promise<{code: number|null, signal: string|null, stdout: string, stderr: string}>}
572
+ */
573
+ async _runSsh(extraArgs, opts = {}) {
574
+ if (!this.config.host) throw new Error('no host configured')
575
+ const secret = await this._resolveSecret()
576
+ const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
577
+ const sshBinary = resolveSshBinary(this.config)
578
+ const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), ...extraArgs]
579
+ return new Promise((resolve) => {
580
+ let child
581
+ try {
582
+ child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
583
+ } catch (err) {
584
+ return resolve({ code: -1, signal: 'SPAWN_FAILED', stdout: '', stderr: String((err && err.message) || err) })
585
+ }
586
+ // This path may stream a script into `bash -s` and can be written to
587
+ // after the command already exited (Git Bash); a broken pipe there must
588
+ // fail the call, not the process (issue #118).
589
+ guardChildStdin(child)
590
+ let stdout = ''
591
+ let stderr = ''
592
+ let settled = false
593
+ let exitCode = null
594
+ let exitSignal = null
595
+ const cap = Math.max(this.config.maxOutputChars * 4, 1024 * 1024)
596
+ const onData = typeof opts.onData === 'function' ? opts.onData : null
597
+ const cleanupAbort = () => { if (opts.signal && onAbort) opts.signal.removeEventListener('abort', onAbort) }
598
+ let onAbort = null
599
+ const finish = () => {
600
+ if (settled) return
601
+ settled = true
602
+ clearTimeout(timer)
603
+ cleanupAbort()
604
+ resolve({
605
+ code: exitCode,
606
+ signal: exitSignal,
607
+ stdout: truncate(stdout, this.config.maxOutputChars),
608
+ stderr: truncate(stderr, this.config.maxOutputChars),
609
+ })
610
+ }
611
+ const killHard = () => { try { setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 800).unref?.() } catch {} }
612
+ // No timer at all for an explicit no-deadline call (0) — see pool.js
613
+ // _execRaw; arming one would fire at once or kill a promoted job (issue #95).
614
+ const timer = timeoutMs > 0 ? setTimeout(() => {
615
+ if (settled) return
616
+ exitCode = -1
617
+ exitSignal = 'TIMEOUT'
618
+ try { child.kill() } catch {}
619
+ killHard()
620
+ finish()
621
+ }, timeoutMs) : null
622
+ if (opts.signal) {
623
+ if (opts.signal.aborted) {
624
+ try { child.kill() } catch {}
625
+ exitCode = -1; exitSignal = 'ABORTED'
626
+ return finish()
627
+ }
628
+ onAbort = () => {
629
+ if (settled) return
630
+ exitCode = -1; exitSignal = 'ABORTED'
631
+ try { child.kill() } catch {}
632
+ killHard()
633
+ finish()
634
+ }
635
+ opts.signal.addEventListener('abort', onAbort, { once: true })
636
+ }
637
+ // The tap fires even past the local cap, exactly like the native
638
+ // backend's: a promoted job's ring has its own bounds and must keep
639
+ // receiving output the truncated return value no longer holds.
640
+ child.stdout.on('data', (d) => {
641
+ if (stdout.length < cap) stdout += d
642
+ if (onData) { try { onData('stdout', d) } catch { /* tap errors are not command errors */ } }
643
+ })
644
+ child.stderr.on('data', (d) => {
645
+ if (stderr.length < cap) stderr += d
646
+ if (onData) { try { onData('stderr', d) } catch { /* tap errors are not command errors */ } }
647
+ })
648
+ child.on('error', (e) => {
649
+ if (settled) return
650
+ stderr += String((e && e.message) || e)
651
+ exitCode = -1
652
+ finish()
653
+ })
654
+ child.on('close', (code, sig) => {
655
+ if (settled) return
656
+ exitCode = code
657
+ exitSignal = sig || null
658
+ finish()
659
+ })
660
+ try { child.stdin.end(opts.stdin === undefined || opts.stdin === null ? undefined : String(opts.stdin)) } catch {}
661
+ })
662
+ }
663
+
664
+ /** Detect the remote platform + locate Git Bash once; cached per target. */
665
+ detect() {
666
+ if (this.platform !== 'unknown') return Promise.resolve()
667
+ if (this._detecting) return this._detecting
668
+ this._detecting = this._detect().finally(() => { this._detecting = null })
669
+ return this._detecting
670
+ }
671
+
672
+ async _detect() {
673
+ let res
674
+ try {
675
+ res = await this._runSsh(['--', this.destination(), 'cmd /c ver'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
676
+ } catch {
677
+ this.platform = 'unknown'
678
+ this.shellMode = 'native'
679
+ return
680
+ }
681
+ const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
682
+ if (res.code === 0 && /microsoft windows/i.test(out)) {
683
+ this.platform = 'windows'
684
+ await this._resolveGitBash()
685
+ return
686
+ }
687
+ try {
688
+ const u = await this._runSsh(['--', this.destination(), 'uname -s'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
689
+ if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
690
+ this.platform = 'windows'
691
+ await this._resolveGitBash()
692
+ return
693
+ }
694
+ } catch { /* inconclusive — fall through to posix */ }
695
+ this.platform = 'posix'
696
+ this.shellMode = 'native'
697
+ this.gitBashPath = ''
698
+ }
699
+
700
+ async _resolveGitBash() {
701
+ const cfg = String(this.config.shell || '').trim()
702
+ const exists = async (p) => {
703
+ const r = await this._runSsh(['--', this.destination(), `cmd /c if exist "${p}" (echo Y) else (echo N)`], { timeoutMs: 8000 })
704
+ return /Y/.test(String(r.stdout || ''))
705
+ }
706
+ if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
707
+ if (await exists(cfg)) { this.gitBashPath = cfg; this.shellMode = 'git-bash'; return }
708
+ }
709
+ if (cfg === 'native') { this.shellMode = 'native'; this.gitBashPath = ''; return }
710
+ try {
711
+ const r = await this._runSsh(['--', this.destination(), 'cmd /c where bash'], { timeoutMs: 8000 })
712
+ const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
713
+ if (first) { this.gitBashPath = first; this.shellMode = 'git-bash'; return }
714
+ } catch { /* fall through to the candidate list */ }
715
+ const candidates = [
716
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
717
+ 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
718
+ ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
719
+ ]
720
+ for (const c of candidates) {
721
+ if (await exists(c)) { this.gitBashPath = c; this.shellMode = 'git-bash'; return }
722
+ }
723
+ this.shellMode = 'git-bash'
724
+ this.gitBashPath = ''
725
+ }
726
+
727
+ /** Run one remote command (Windows + Git Bash is wrapped exactly as native). */
728
+ exec(command, timeoutMsOrOpts) {
729
+ const opts = timeoutMsOrOpts && typeof timeoutMsOrOpts === 'object' ? timeoutMsOrOpts : { timeoutMs: timeoutMsOrOpts }
730
+ return this.detect().then(() => {
731
+ const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
732
+ if (this.platform === 'windows' && this.gitBashPath) {
733
+ // Pipe the script to `bash -s` over stdin: no quoting round-trip, so
734
+ // quotes/backslashes/newlines survive verbatim (same as the native pool).
735
+ return this._runSsh(['--', this.destination(), `"${this.gitBashPath}" -s`], { timeoutMs, signal: opts.signal, stdin: String(command), onData: opts.onData })
736
+ }
737
+ return this._runSsh(['--', this.destination(), String(command)], { timeoutMs, signal: opts.signal, onData: opts.onData })
738
+ })
739
+ }
740
+
741
+ /** Open a fresh `ssh -s <dest> sftp` session and its ssh2 SFTP engine. */
742
+ async _openSftpChannel() {
743
+ const Sftp = loadSftpEngine()
744
+ const secret = await this._resolveSecret()
745
+ const sshBinary = resolveSshBinary(this.config)
746
+ const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), '-s', this.destination(), 'sftp']
747
+ const child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
748
+
749
+ // ssh2's SFTP engine only reaches `_protocol` for channelData/channelClose,
750
+ // and reads `_remoteIdentRaw` to pick its packet sizes.
751
+ //
752
+ // ## Flow control, the subtle part
753
+ //
754
+ // Over real SSH the engine's send window is topped up by CHANNEL_WINDOW_ADJUST
755
+ // messages from the peer. On a raw `ssh -s sftp` pipe THERE ARE NO SUCH
756
+ // MESSAGES — the local ssh owns the SSH-layer window and the server's grants,
757
+ // and all we have is a byte pipe with OS-level backpressure. So the engine's
758
+ // window has to be mapped onto the pipe's writability:
759
+ //
760
+ // • a write the pipe accepts → more will fit;
761
+ // • the pipe fills (`stdin.write` returns false) → clamp the window so the
762
+ // engine buffers the remainder instead of queueing it all in memory;
763
+ // • the pipe drains → grant the window back and let the engine flush.
764
+ //
765
+ // The trap, and why the constants below are what they are: ssh2 arms its
766
+ // flush callback (`_waitWindow` / `_chunkcb = drainBuffer`) ONLY from inside
767
+ // its own subtraction, at the moment that subtraction takes the window to
768
+ // exactly 0. So the window must be handed over in EXACT MULTIPLES of
769
+ // packetSize and then left alone: the engine's own arithmetic then lands on 0
770
+ // during normal operation and arms the flush callback we depend on.
771
+ //
772
+ // Do NOT "help" by clamping the window to 0 from inside channelData when the
773
+ // pipe reports itself full. That sets the window to 0 AFTER the subtraction
774
+ // has already happened, so the callback is never armed and the buffered
775
+ // remainder is never flushed — the transfer deadlocks with a full window.
776
+ // (Measured: a 4 MB upload stopped dead after 32 KB, with `_buffer.length`
777
+ // stuck at 1 and no callback pending.) The pipe's own `drain` event is the
778
+ // only place the window is refilled.
779
+ //
780
+ // Also tempting-but-wrong: adding each received packet's length to the
781
+ // window. That happens to work for a DOWNLOAD (the peer's data is the
782
+ // window) and deadlocks an upload, because a write's acknowledgements are
783
+ // tiny status packets while each send consumes ~32 KB.
784
+ //
785
+ // See scripts/integration-openssh-large.mjs, which is what caught all of this.
786
+ const PACKET = 32768
787
+ const GRANT = PACKET * 8 // 256 KB per burst, and a multiple of packetSize
788
+ const chan = { sftp: null }
789
+ const fakeClient = {
790
+ _protocol: {
791
+ _remoteIdentRaw: Buffer.from('SSH-2.0-OpenSSH'),
792
+ // Hand the bytes to the pipe and nothing else. Backpressure is expressed
793
+ // through the engine's own window draining (see above); the OS pipe
794
+ // buffer plus Node's write buffer absorb the in-flight remainder.
795
+ channelData(_id, data) { try { child.stdin.write(data) } catch { /* close handles it */ } },
796
+ channelClose() { try { child.stdin.end() } catch {} },
797
+ },
798
+ }
799
+ const chanInfo = {
800
+ type: 'sftp',
801
+ incoming: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
802
+ outgoing: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
803
+ }
804
+ // The stdin pipe can die underneath the engine at any moment (the remote
805
+ // side of the sftp subsystem exits, the link drops — issue #118). Each write
806
+ // after that fails, and without an 'error' listener the failure is an
807
+ // uncaught exception that takes the whole Host down. Registering the guard
808
+ // here, next to the only two places that write to this pipe, keeps the
809
+ // blast radius at "this session is gone": 'close' fires as usual and the
810
+ // cached session is dropped by sftp()'s own handler.
811
+ guardChildStdin(child, () => { try { child.kill() } catch { /* already gone */ } })
812
+ const sftp = new Sftp(fakeClient, chanInfo, {})
813
+ chan.sftp = sftp
814
+
815
+ // The pipe has room again: grant the window back and let the engine flush
816
+ // whatever it buffered while the pipe was full.
817
+ const onStdinDrain = () => {
818
+ if (!chan.sftp) return
819
+ chan.sftp.outgoing.window = GRANT
820
+ if (chan.sftp._waitWindow) {
821
+ chan.sftp._waitWindow = false
822
+ const cb = chan.sftp._chunkcb
823
+ chan.sftp._chunkcb = undefined
824
+ if (typeof cb === 'function') cb.call(chan.sftp)
825
+ }
826
+ }
827
+ child.stdin.on('drain', onStdinDrain)
828
+ // A dead SSH process reports stdin EPIPE asynchronously. Without a stream
829
+ // error listener Node crashes the host before close/drop can reset the
830
+ // cached session (issue #118); kill it so that existing recovery runs.
831
+ child.stdin.on('error', () => { try { child.kill() } catch {} })
832
+
833
+ return new Promise((resolve, reject) => {
834
+ let stderr = ''
835
+ let settled = false
836
+ const done = (err) => {
837
+ if (settled) return
838
+ settled = true
839
+ clearTimeout(timer)
840
+ if (err) { try { child.kill() } catch {} ; reject(err) } else resolve({ child, sftp })
841
+ }
842
+ const timer = setTimeout(() => {
843
+ done(new Error(`sftp session to ${this.destination()} timed out${stderr ? ': ' + stderr.trim() : ''}`))
844
+ }, this.config.commandTimeoutMs)
845
+ child.stderr.on('data', (d) => { stderr += d })
846
+ sftp.on('error', (e) => done(new Error('sftp session failed: ' + ((e && e.message) || e))))
847
+ sftp.on('ready', () => done(null))
848
+ child.on('error', (e) => done(e))
849
+ child.on('close', (code) => done(new Error(`ssh sftp exited (${code})${stderr ? ': ' + stderr.trim() : ''}`)))
850
+ // Inbound is simpler: the local ssh already did the SSH-level window
851
+ // accounting before handing us these bytes, so they just go straight in.
852
+ child.stdout.on('data', (d) => { sftp.push(d) })
853
+ child.stdout.on('end', () => { try { sftp.push(null) } catch { /* already gone */ } })
854
+ sftp._init()
855
+ })
856
+ }
857
+
858
+ /**
859
+ * A persistent SFTP session, kept across calls: the picker and the explorer
860
+ * issue one listing per interaction, and re-handshaking each time would be
861
+ * visibly slow. A session that dies is dropped so the next call reconnects.
862
+ */
863
+ sftp() {
864
+ if (this._sftpSession) return this._sftpSession
865
+ const epoch = this.epoch
866
+ const session = this._openSftpChannel().then(({ child, sftp }) => {
867
+ const drop = () => {
868
+ if (this._sftpSession === session) this._sftpSession = null
869
+ if (this._sftpChild === child) this._sftpChild = null
870
+ }
871
+ child.on('close', drop)
872
+ sftp.on('end', drop)
873
+ sftp.on('error', drop)
874
+ // A target switch during the handshake must not adopt the old host's
875
+ // session (the same generational guard connect() uses).
876
+ if (this.epoch !== epoch) {
877
+ try { child.kill() } catch {}
878
+ throw new Error('ssh target changed while opening sftp')
879
+ }
880
+ this._sftpChild = child
881
+ return buildSftpSurface(sftp, {
882
+ commandTimeoutMs: this.config.commandTimeoutMs,
883
+ onTimeout: () => {
884
+ // A timed-out SFTP session is dead: kill the child and drop the cached
885
+ // session so the next call re-handshakes instead of queueing behind the
886
+ // wedged one (issue #65).
887
+ try { child.kill() } catch { /* already gone */ }
888
+ drop()
889
+ },
890
+ })
891
+ })
892
+ // Never cache a rejected open: the next call must retry rather than get the
893
+ // same error back forever (a failed handshake is usually transient).
894
+ session.catch(() => { if (this._sftpSession === session) this._sftpSession = null })
895
+ this._sftpSession = session
896
+ return session
897
+ }
898
+
899
+ invalidate() {
900
+ this.epoch++
901
+ const client = this.client
902
+ this.client = null
903
+ this.connecting = null
904
+ this._secret = null
905
+ this._secretPromise = null
906
+ if (client) { try { client.close() } catch {} }
907
+ this._dropSftpSession()
908
+ if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
909
+ if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
910
+ }
911
+
912
+ _dropSftpSession() {
913
+ const session = this._sftpSession
914
+ this._sftpSession = null
915
+ if (this._sftpChild) {
916
+ try { this._sftpChild.kill() } catch {}
917
+ this._sftpChild = null
918
+ }
919
+ // Swallow the rejection: nobody awaits a session we are tearing down.
920
+ if (session && typeof session.catch === 'function') session.catch(() => {})
921
+ }
922
+
923
+ close() {
924
+ this.epoch++
925
+ const client = this.client
926
+ this.client = null
927
+ this.connecting = null
928
+ this._secret = null
929
+ this._secretPromise = null
930
+ if (client) { try { client.close() } catch {} }
931
+ this._dropSftpSession()
932
+ if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
933
+ if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
934
+ }
935
+ }
936
+
937
+ /** Pick the pool class for a config: 'openssh' backend, else the native pool. */
938
+ export function isSystemOpenSshBackend(config = {}) {
939
+ return String(config.backend || '').toLowerCase() === 'openssh'
940
+ }