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/pool.js CHANGED
@@ -1,1029 +1,1029 @@
1
- // Persistent SSH/SFTP connection pool (one identity → one live client).
2
- import ssh2 from 'ssh2'
3
- import { readFileSync } from 'node:fs'
4
- import { homedir } from 'node:os'
5
- import path from 'node:path'
6
- import { truncate } from './paths.js'
7
- import { createHostKeyGuard } from './hostkey.js'
8
- import { buildSftpSurface } from './sftp-surface.js'
9
- import { friendlyMessage } from './errors.js'
10
- import { SystemOpenSshPool, isSystemOpenSshBackend } from './openssh.js'
11
-
12
- const { Client } = ssh2
13
-
14
- /**
15
- * A key path that names a PUBLIC key. `IdentityFile ~/.ssh/x.pub` is OpenSSH's
16
- * idiom for "the private key lives in the agent (1Password, Bitwarden, rbw…);
17
- * use the agent key matching this file" — it must never be handed to ssh2 as
18
- * a private key.
19
- */
20
- export function isPublicKeyPath(p) {
21
- return /\.pub$/i.test(String(p || ''))
22
- }
23
-
24
- /** The wire blob of an OpenSSH public key line (`type base64 [comment]`). */
25
- export function publicKeyBlob(text) {
26
- const parts = String(text || '').trim().split(/\s+/)
27
- if (parts.length < 2) return null
28
- const blob = Buffer.from(parts[1], 'base64')
29
- return blob.length ? blob : null
30
- }
31
-
32
- /**
33
- * An agent that offers the key matching `wantBlob` FIRST — and, with
34
- * `only` (IdentitiesOnly yes), nothing else. Without the ordering ssh2 offers
35
- * every agent key in turn, and an agent holding many keys trips the server's
36
- * MaxAuthTries before reaching the right one.
37
- */
38
- export class PreferredKeyAgent extends ssh2.BaseAgent {
39
- constructor(inner, wantBlob, only) {
40
- super()
41
- this.inner = inner
42
- this.wantBlob = wantBlob
43
- this.only = !!only
44
- }
45
-
46
- getIdentities(cb) {
47
- this.inner.getIdentities((err, keys) => {
48
- if (err) return cb(err)
49
- const list = Array.isArray(keys) ? keys : []
50
- const isWanted = (k) => {
51
- try { return Buffer.from(k.getPublicSSH()).equals(this.wantBlob) } catch { return false }
52
- }
53
- const wanted = list.filter(isWanted)
54
- cb(null, this.only ? wanted : [...wanted, ...list.filter((k) => !isWanted(k))])
55
- })
56
- }
57
-
58
- sign(...args) {
59
- return this.inner.sign(...args)
60
- }
61
- }
62
-
63
- /**
64
- * Build the pool for a config.
65
- *
66
- * Two backends exist (issue #51): the native one below, which speaks SSH itself
67
- * via ssh2, and the "system OpenSSH" one (lib/openssh.js), which delegates to
68
- * the local `ssh` executable so GSSAPI/Kerberos and the rest of the user's
69
- * `~/.ssh/config` are honoured. Both expose one identical surface, so every
70
- * caller can keep using `new SshPool(...)`-shaped code — this factory only has
71
- * to decide which class to instantiate.
72
- */
73
- /** Hard cap on proxy-chain depth. OpenSSH's ProxyJump has no explicit limit;
74
- * this exists to turn a config CYCLE into a clear error instead of unbounded
75
- * recursion. A legitimate chain is 1-3 hops.
76
- * @type {number} */
77
- export const MAX_JUMP_HOPS = 8
78
-
79
- export function createPool(config, opts) {
80
- return isSystemOpenSshBackend(config)
81
- ? new SystemOpenSshPool(config, opts)
82
- : new SshPool(config, opts)
83
- }
84
-
85
- /**
86
- * Run one `forwardOut` and resolve with the resulting channel.
87
- *
88
- * ssh2 reports a dead connection by THROWING synchronously —
89
- * `if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected')`
90
- * (ssh2 >= 1.16, `Client.forwardOut`) — and never calls the callback, so a
91
- * callback-only error path cannot guard this call (issue #54). Two further
92
- * consequences justify a shared helper rather than an inline try/catch:
93
- *
94
- * • inside a `new Promise(executor)` a bare throw rejects nothing: it becomes
95
- * an unhandled REJECTION and leaves the promise pending forever;
96
- * • called from a `net.Server` connection handler the throw escapes to the
97
- * process top level and kills the host.
98
- *
99
- * This guards the CALLER's side of the contract rather than assuming one
100
- * backend's behaviour: the system-OpenSSH backend (lib/openssh.js `forwardOut`)
101
- * already converts its own spawn failure into a callback error, so for it the
102
- * try/catch below is dead code — but a backend is free to throw, and the one
103
- * that does must not be able to take the process down.
104
- *
105
- * @param {object} client - an ssh2 Client or OpenSshConnection.
106
- * @param {object} spec - `srcHost`/`srcPort`/`dstHost`/`dstPort`.
107
- * @returns {Promise<object>} the forwarded channel / duplex stream.
108
- */
109
- export function forwardOutChannel(client, { srcHost = '127.0.0.1', srcPort = 0, dstHost, dstPort }) {
110
- return new Promise((resolve, reject) => {
111
- // `reject` is called at most once: a callback that fires after a successful
112
- // throw-path rejection would be a no-op, which Promise guarantees.
113
- try {
114
- client.forwardOut(srcHost, srcPort, dstHost, dstPort, (err, channel) => (err ? reject(err) : resolve(channel)))
115
- } catch (err) {
116
- reject(err)
117
- }
118
- })
119
- }
120
-
121
- /**
122
- * The ACTIVE pool: one long-lived object whose concrete implementation can be
123
- * swapped when the current machine's transport backend changes.
124
- *
125
- * Why a delegating facade instead of just constructing the right class once:
126
- * `backend` is a PER-MACHINE field (an enterprise Kerberos host needs
127
- * `openssh` while every other machine stays on `native`), but the plugin keeps
128
- * exactly one active pool for its whole lifetime and hangs `passwordResolver` /
129
- * `onReady` / `onCloseHook` off it once at startup. Replacing the object
130
- * wholesale on every machine switch would silently drop those hooks — the port
131
- * forwards and keychain passwords would stop working after the first switch.
132
- *
133
- * So the facade owns the hooks and the shared `config` object, and forwards
134
- * them to whichever concrete pool is right for the current config. Everything
135
- * else is a straight delegation, which is why callers cannot tell the
136
- * difference (and why the class is deliberately not part of the public story).
137
- */
138
- export class ActivePool {
139
- constructor(config, opts = {}) {
140
- this.config = config
141
- this.opts = opts
142
- // The hooks are assigned by the plugin AFTER construction, so they are
143
- // stored here and re-applied to every delegate this facade ever creates.
144
- this._passwordResolver = null
145
- this._onReady = null
146
- this._onCloseHook = null
147
- this._delegate = null
148
- this._sync()
149
- }
150
-
151
- /** Which concrete class the current config asks for. */
152
- _wantsSystemOpenSsh() {
153
- return isSystemOpenSshBackend(this.config)
154
- }
155
-
156
- _delegateIsCurrent() {
157
- if (!this._delegate) return false
158
- const isOpenssh = this._delegate instanceof SystemOpenSshPool
159
- return isOpenssh === this._wantsSystemOpenSsh()
160
- }
161
-
162
- /** Create (or replace) the delegate so it matches the current config. */
163
- _sync() {
164
- if (this._delegateIsCurrent()) return this._delegate
165
- const previous = this._delegate
166
- const next = createPool(this.config, this.opts)
167
- next.passwordResolver = this._passwordResolver
168
- next.onReady = this._onReady
169
- next.onCloseHook = this._onCloseHook
170
- this._delegate = next
171
- // Tear the old backend down LAST, and never let a teardown error mask the
172
- // new pool: the connection it was holding belongs to the old host anyway.
173
- if (previous) { try { previous.close() } catch { /* already gone */ } }
174
- return next
175
- }
176
-
177
- get delegate() { return this._sync() }
178
-
179
- // ── hooks: stored here, mirrored onto every delegate ──────────────────────
180
- get passwordResolver() { return this._passwordResolver }
181
- set passwordResolver(fn) {
182
- this._passwordResolver = fn
183
- if (this._delegate) this._delegate.passwordResolver = fn
184
- }
185
- get onReady() { return this._onReady }
186
- set onReady(fn) {
187
- this._onReady = fn
188
- if (this._delegate) this._delegate.onReady = fn
189
- }
190
- get onCloseHook() { return this._onCloseHook }
191
- set onCloseHook(fn) {
192
- this._onCloseHook = fn
193
- if (this._delegate) this._delegate.onCloseHook = fn
194
- }
195
-
196
- // ── pass-through state the plugin reads directly ──────────────────────────
197
- get client() { return this._delegate ? this._delegate.client : null }
198
- // Assignable because the plugin's own tests arm a fake live connection on the
199
- // active pool; a getter-only facade would make that assignment a silent
200
- // no-op in sloppy mode and a TypeError in the strict-mode ESM tests.
201
- set client(v) { if (this._sync()) this._delegate.client = v }
202
- get connecting() { return this._delegate ? this._delegate.connecting : null }
203
- get proxyPool() { return this._delegate ? this._delegate.proxyPool : null }
204
- get epoch() { return this._delegate ? this._delegate.epoch : 0 }
205
- get platform() { return this._delegate ? this._delegate.platform : 'unknown' }
206
- set platform(v) { if (this._sync()) this._delegate.platform = v }
207
- get gitBashPath() { return this._delegate ? this._delegate.gitBashPath : '' }
208
- set gitBashPath(v) { if (this._sync()) this._delegate.gitBashPath = v }
209
- get shellMode() { return this._delegate ? this._delegate.shellMode : 'native' }
210
- set shellMode(v) { if (this._sync()) this._delegate.shellMode = v }
211
-
212
- // ── delegated operations ──────────────────────────────────────────────────
213
- /** Re-point at a new target, switching backend first if the machine asks. */
214
- setTarget(fields, previous) {
215
- // The backend may have changed with the machine, so apply that part of the
216
- // request to `config` BEFORE picking the delegate: _sync() chooses the class
217
- // from config.backend, and the old backend must not be handed a host it can
218
- // no longer reach. The delegate then receives the whole request as usual.
219
- if (fields && fields.backend !== undefined) this.config.backend = String(fields.backend)
220
- if (fields && fields.sshBinary !== undefined) this.config.sshBinary = String(fields.sshBinary)
221
- const d = this._sync()
222
- return d.setTarget(fields, previous)
223
- }
224
- connect() { return this.delegate.connect() }
225
- exec(cmd, opts) { return this.delegate.exec(cmd, opts) }
226
- sftp() { return this.delegate.sftp() }
227
- shell(opts) { return this.delegate.shell(opts) }
228
- detect() { return this.delegate.detect() }
229
- invalidate() { return this.delegate.invalidate() }
230
- close() { return this.delegate.close() }
231
- }
232
-
233
- export class SshPool {
234
- constructor(config, opts = {}) {
235
- this.config = config
236
- this._knownHostsFile = opts.knownHostsFile
237
- this.client = null
238
- this.connecting = null
239
- this.proxyPool = null
240
- // Generational token: bumped on every target change / close so a stale
241
- // in-flight connect can never hand this pool a connection to an old host.
242
- this.epoch = 0
243
- /** Auto-detected remote platform: unknown | windows | posix (per target). */
244
- this.platform = 'unknown'
245
- /** Resolved Git Bash bash.exe path on Windows remotes ('' when none). */
246
- this.gitBashPath = ''
247
- /** Resolved terminal strategy: native | git-bash. */
248
- this.shellMode = 'native'
249
- /** In-flight platform detection promise (cached). */
250
- this._detecting = null
251
- /** Optional async resolver for a machine-stored (keychain) password. */
252
- this.passwordResolver = null
253
- /** Optional hook called with the live client after a successful connect. */
254
- this.onReady = null
255
- /** Optional hook called when the pool closes. */
256
- this.onCloseHook = null
257
- /** Consecutive SFTP subchannel-open timeouts (issue #65). */
258
- this._sftpTimeouts = 0
259
- /** One SFTP session per live client/epoch (issue #121). */
260
- this._sftpSession = null
261
- this._sftpRaw = null
262
- this._sftpClient = null
263
- this._sftpEpoch = -1
264
- }
265
-
266
- resolveKeyPath() {
267
- const p = this.config.privateKeyPath
268
- if (!p) return ''
269
- if (p.startsWith('~/') || p === '~') return path.join(homedir(), p.slice(1))
270
- return p
271
- }
272
-
273
- setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
274
- // Collect the requested changes first: an UNCHANGED target is a no-op. The
275
- // old behavior closed the live connection and re-ran platform detection
276
- // even for an identical target, so every picker keystroke
277
- // (POST /current → applyActiveMachine → setTarget) paid a full SSH
278
- // reconnect + re-detect — the "slow remote path autocomplete" bug.
279
- //
280
- // `previous` is the diff BASELINE. Callers whose shared config was already
281
- // mutated BEFORE this call (applyActiveMachine: applyMachine rewrites the
282
- // live config IN PLACE, and pool.config IS that config object) pass a
283
- // pre-mutation snapshot — otherwise the comparison runs the new values
284
- // against themselves, is always equal and never closes even for a machine
285
- // switch (the wrong-host hazard of issue #25). Defaults to the current
286
- // config for callers that pass fresh values read independently of it.
287
- const base = previous || this.config
288
- const wanted = []
289
- if (host !== undefined) wanted.push(['host', String(host)])
290
- if (port !== undefined && Number(port)) wanted.push(['port', Number(port)])
291
- if (username !== undefined) wanted.push(['username', String(username)])
292
- if (password !== undefined && password !== null) wanted.push(['password', String(password)])
293
- if (privateKeyPath !== undefined) wanted.push(['privateKeyPath', String(privateKeyPath)])
294
- if (passphrase !== undefined) wanted.push(['passphrase', String(passphrase)])
295
- if (workspace !== undefined) wanted.push(['workspace', String(workspace)])
296
- if (useAgent !== undefined) wanted.push(['useAgent', !!useAgent])
297
- if (keyboardInteractive !== undefined) wanted.push(['keyboardInteractive', !!keyboardInteractive])
298
- if (proxy !== undefined) wanted.push(['proxy', proxy])
299
- if (hostKeyMode !== undefined) wanted.push(['hostKeyMode', String(hostKeyMode)])
300
- // Issue #51: the transport backend is part of the target identity — changing
301
- // it must close the live connection exactly like changing the host does.
302
- if (backend !== undefined) wanted.push(['backend', String(backend)])
303
- if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
304
- const differs = ([k, v]) => (k === 'proxy'
305
- ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
306
- : base[k] !== v)
307
- // Something actually changed → apply it and force a fresh connection.
308
- // (A caller that WANTS a reconnect for an identical target uses
309
- // invalidate(); setTarget semantics stay "re-point when moved".)
310
- if (wanted.some(differs)) {
311
- for (const [k, v] of wanted) this.config[k] = v
312
- // the new target may be a different OS — re-detect on the next command
313
- this.platform = 'unknown'
314
- this.gitBashPath = ''
315
- this.shellMode = 'native'
316
- this._detecting = null
317
- this.close()
318
- }
319
- return this
320
- }
321
-
322
- connect() {
323
- if (this.client) return Promise.resolve(this.client)
324
- if (this.connecting) return this.connecting
325
- const epoch = this.epoch
326
- const pending = this._doConnect(epoch)
327
- this.connecting = pending
328
- const clear = () => {
329
- if (this.epoch === epoch && this.connecting === pending) this.connecting = null
330
- }
331
- pending.then(clear, clear)
332
- return pending
333
- }
334
-
335
- async _doConnect(epoch) {
336
- const isCurrent = () => this.epoch === epoch
337
- const knownHostsFile = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
338
- const guard = createHostKeyGuard(this.config, knownHostsFile)
339
- const client = new Client()
340
- let settled = false
341
- // Every connect-stage failure is classified HERE, at the layer that knows
342
- // which machine was being dialed: a bare ssh2 errno ("Timed out while
343
- // waiting for handshake") names no host, and on a multi-machine plugin the
344
- // user cannot tell WHICH box failed. friendlyMessage is idempotent, so
345
- // callers that classify again (rw_connect, routes) do not double-wrap.
346
- const classify = (err) => new Error(friendlyMessage(err, { host: this.config.host, port: this.config.port }))
347
- const fail = (err) => {
348
- if (settled) return
349
- settled = true
350
- if (isCurrent() && this.client === client) this.client = null
351
- throw classify(guard.lastError ? new Error(guard.lastError) : err)
352
- }
353
-
354
- // Proxy jump: SSH to the bastion first, then tunnel to the target through it.
355
- //
356
- // MULTI-HOP (OpenSSH `ProxyJump a,b,c` semantics): each bastion may itself
357
- // carry a `proxy`, and the chain is built from the FARTHEST hop inward — hop
358
- // N is dialed through the already-open connection to hop N-1. The recursion
359
- // IS the mechanism, so there is no depth limit beyond what the config
360
- // expresses; MAX_JUMP_HOPS is a cycle/typo guard, not a feature limit.
361
- let sock = null
362
- const proxyCfg = this.config.proxy
363
- if (proxyCfg && proxyCfg.host) {
364
- try {
365
- const depth = Number(this.config._hopDepth) || 0
366
- if (depth >= MAX_JUMP_HOPS) {
367
- throw new Error(`proxy chain is deeper than ${MAX_JUMP_HOPS} hops — check the machine config for a proxy cycle`)
368
- }
369
- this.proxyPool = new SshPool({
370
- ...this.config,
371
- host: proxyCfg.host,
372
- port: Number(proxyCfg.port) || 22,
373
- username: proxyCfg.username || this.config.username || 'root',
374
- // CREDENTIALS DO NOT INHERIT ACROSS HOPS. `...this.config` brings the
375
- // TARGET's key/passphrase along, which is wrong in two ways: it may
376
- // not be authorized on the bastion, and presenting the target's key to
377
- // an intermediate host hands that host a credential it should never
378
- // see. A hop with no key of its own falls back to the agent/default
379
- // discovery path, which is what an operator's own ssh setup provides.
380
- password: proxyCfg.password || '',
381
- privateKeyPath: proxyCfg.privateKeyPath || '',
382
- passphrase: proxyCfg.passphrase || '',
383
- agentSocket: proxyCfg.agentSocket || '',
384
- identitiesOnly: !!proxyCfg.identitiesOnly,
385
- ...(proxyCfg.useAgent !== undefined ? { useAgent: !!proxyCfg.useAgent } : {}),
386
- ...(proxyCfg.keyboardInteractive !== undefined ? { keyboardInteractive: !!proxyCfg.keyboardInteractive } : {}),
387
- ...(proxyCfg.hostKeyMode ? { hostKeyMode: proxyCfg.hostKeyMode } : {}),
388
- // The nested hop keeps its OWN proxy — that is what builds the chain —
389
- // and carries an incremented depth so a cycle is reported instead of
390
- // recursing until the process dies.
391
- proxy: proxyCfg.proxy && proxyCfg.proxy.host ? proxyCfg.proxy : undefined,
392
- _hopDepth: depth + 1,
393
- }, { knownHostsFile: this._knownHostsFile })
394
- const pclient = await this.proxyPool.connect()
395
- if (!isCurrent()) throw new Error('ssh target changed during proxy connect')
396
- try {
397
- sock = await forwardOutChannel(pclient, { dstHost: this.config.host, dstPort: this.config.port })
398
- } catch (e) {
399
- throw new Error('proxy forward to target failed: ' + ((e && e.message) || e))
400
- }
401
- } catch (err) {
402
- return fail(err)
403
- }
404
- }
405
-
406
- return new Promise((resolve, reject) => {
407
- const rejectOnce = (err) => {
408
- if (settled) return
409
- settled = true
410
- if (isCurrent() && this.client === client) this.client = null
411
- reject(classify(guard.lastError ? new Error(guard.lastError) : err))
412
- }
413
- client.on('ready', () => {
414
- if (settled) return
415
- settled = true
416
- if (!isCurrent()) {
417
- try { client.end() } catch {}
418
- reject(classify(new Error('ssh target changed during connect')))
419
- return
420
- }
421
- this.client = client
422
- this._sftpTimeouts = 0
423
- resolve(client)
424
- if (this.onReady) { try { this.onReady(client) } catch {} }
425
- })
426
- client.on('error', (e) => rejectOnce(e))
427
- client.on('close', () => {
428
- if (isCurrent() && this.client === client) {
429
- this.client = null
430
- this._dropSftpSession()
431
- }
432
- rejectOnce(new Error('ssh connection closed'))
433
- })
434
-
435
- const buildOpts = async () => {
436
- const opts = {
437
- host: this.config.host,
438
- port: this.config.port,
439
- username: this.config.username,
440
- readyTimeout: this.config.connectTimeoutMs,
441
- keepaliveInterval: 15000,
442
- keepaliveCountMax: 3,
443
- hostVerifier: (key) => guard.verifier(key),
444
- }
445
- if (sock) opts.sock = sock
446
- // `useAgent` asks for agent auth, but ssh2 can only offer it when this
447
- // PROCESS has an agent socket. On Windows there is no agent by default,
448
- // so the flag alone used to fall through to the generic "no credentials"
449
- // error — which reads as "the plugin lost my settings" rather than "this
450
- // machine has no agent". Track the intent so the failure can say which.
451
- let agentRequested = false
452
- // `IdentityAgent` from ~/.ssh/config (agentSocket) wins over the
453
- // process SSH_AUTH_SOCK, exactly as in ssh; `none` turns the agent off.
454
- const agentSocket = String(this.config.agentSocket || '')
455
- const sockPath = agentSocket === 'none' ? '' : (agentSocket || process.env.SSH_AUTH_SOCK || '')
456
- const keyPathRaw = this.config.privateKeyPath ? this.resolveKeyPath() : ''
457
- const agentKeyHint = isPublicKeyPath(keyPathRaw)
458
- if (this.config.useAgent || agentKeyHint || (agentSocket && agentSocket !== 'none')) {
459
- if (sockPath) opts.agent = sockPath
460
- else agentRequested = true
461
- }
462
- let password = this.config.password || ''
463
- if (!password && this.passwordResolver) {
464
- try { password = (await this.passwordResolver()) || '' } catch {}
465
- }
466
- if (password) {
467
- opts.password = password
468
- opts.tryKeyboard = true
469
- } else if (this.config.keyboardInteractive && !this.config.privateKeyPath) {
470
- opts.tryKeyboard = true
471
- }
472
- if (agentKeyHint) {
473
- // The key file is a PUBLIC key: authenticate through the agent with
474
- // the matching key (see isPublicKeyPath).
475
- if (!opts.agent) {
476
- throw new Error(`no SSH agent available: the identity "${keyPathRaw}" is a public key, so its private key must come from an SSH agent, but neither IdentityAgent nor SSH_AUTH_SOCK gives one to the DSH host process`)
477
- }
478
- let blob
479
- try {
480
- blob = publicKeyBlob(readFileSync(keyPathRaw, 'utf8'))
481
- } catch (err) {
482
- throw new Error(`cannot read public key "${keyPathRaw}": ${err && err.message}`)
483
- }
484
- if (!blob) throw new Error(`cannot parse public key "${keyPathRaw}"`)
485
- opts.agent = new PreferredKeyAgent(ssh2.createAgent(opts.agent), blob, this.config.identitiesOnly)
486
- } else if (this.config.privateKeyPath) {
487
- const keyPath = this.resolveKeyPath()
488
- if (!keyPath) {
489
- throw new Error('no credentials: set a password or a privateKeyPath to connect')
490
- }
491
- let key
492
- try {
493
- key = readFileSync(keyPath)
494
- } catch (err) {
495
- throw new Error(`cannot read private key "${keyPath}": ${err && err.message}`)
496
- }
497
- opts.privateKey = key
498
- opts.passphrase = this.config.passphrase || undefined
499
- } else if (!password && !opts.agent) {
500
- throw new Error(agentRequested
501
- ? 'no SSH agent available: useAgent is enabled for this machine but SSH_AUTH_SOCK is not set in the DSH host process (Windows has no agent by default) — start an agent (or Pageant) before launching DSH, or save a password / private key for this machine'
502
- : 'no credentials: set a password, a privateKeyPath, or enable useAgent to connect')
503
- }
504
- return opts
505
- }
506
-
507
- buildOpts().then(
508
- (opts) => {
509
- if (opts.tryKeyboard) {
510
- client.on('keyboard-interactive', (name, instructions, lang, prompts, finish) => {
511
- finish(prompts.map(() => this.config.password || ''))
512
- })
513
- }
514
- // ssh2 parses the private key SYNCHRONOUSLY inside connect() and
515
- // throws on an unparseable key (the classic case: an encrypted
516
- // OpenSSH key without a passphrase). Left uncaught, that throw
517
- // rejects this orphaned .then chain — an unhandled rejection that
518
- // crashes the whole host process (issue #48: "dsh: fatal load
519
- // failure" on every boot, because boot-restore re-dials the bad
520
- // machine). It also leaves the outer promise pending forever.
521
- // Convert it into a normal rejection so every caller's try/catch —
522
- // boot restore, test-connect, rw_connect — sees a regular failure.
523
- try {
524
- client.connect(opts)
525
- } catch (err) {
526
- rejectOnce(err)
527
- }
528
- },
529
- (err) => rejectOnce(err),
530
- )
531
- })
532
- }
533
-
534
- /** Detect the remote platform + locate Git Bash once; cached per target. */
535
- detect() {
536
- if (this.platform !== 'unknown') return Promise.resolve()
537
- if (this._detecting) return this._detecting
538
- this._detecting = this._detect().finally(() => {
539
- this._detecting = null
540
- })
541
- return this._detecting
542
- }
543
-
544
- async _detect() {
545
- let res
546
- try {
547
- // `cmd /c ver` works under cmd.exe, PowerShell AND Git Bash (all print
548
- // "Microsoft Windows …"); on POSIX hosts `cmd` simply doesn't exist.
549
- res = await this._execRaw('cmd /c ver', { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
550
- } catch (err) {
551
- this.platform = 'unknown'
552
- this.shellMode = 'native'
553
- return
554
- }
555
- const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
556
- if (res.code === 0 && /microsoft windows/i.test(out)) {
557
- this.platform = 'windows'
558
- await this._resolveGitBash()
559
- return
560
- }
561
- // inconclusive — probe for a Git-Bash/MSYS remote (uname prints MINGW64_NT…)
562
- try {
563
- const u = await this._execRaw('uname -s', { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
564
- if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
565
- this.platform = 'windows'
566
- await this._resolveGitBash()
567
- return
568
- }
569
- } catch {}
570
- this.platform = 'posix'
571
- this.shellMode = 'native'
572
- this.gitBashPath = ''
573
- }
574
-
575
- /** On a Windows remote, locate Git Bash (config path → PATH → common installs). */
576
- async _resolveGitBash() {
577
- const cfg = String(this.config.shell || '').trim()
578
- if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
579
- if (await this._cmdExists(cfg)) {
580
- this.gitBashPath = cfg
581
- this.shellMode = 'git-bash'
582
- return
583
- }
584
- }
585
- if (cfg === 'native') {
586
- this.shellMode = 'native'
587
- this.gitBashPath = ''
588
- return
589
- }
590
- try {
591
- const r = await this._execRaw('cmd /c where bash', { timeoutMs: 8000 })
592
- const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
593
- if (first) {
594
- this.gitBashPath = first
595
- this.shellMode = 'git-bash'
596
- return
597
- }
598
- } catch {}
599
- const candidates = [
600
- 'C:\\Program Files\\Git\\bin\\bash.exe',
601
- 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
602
- ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
603
- '%LOCALAPPDATA%\\Programs\\Git\\bin\\bash.exe',
604
- ]
605
- for (const c of candidates) {
606
- if (await this._cmdExists(c)) {
607
- this.gitBashPath = c
608
- this.shellMode = 'git-bash'
609
- return
610
- }
611
- }
612
- this.shellMode = 'git-bash' // wanted but not found — commands fall back to raw
613
- this.gitBashPath = ''
614
- }
615
-
616
- async _cmdExists(p) {
617
- try {
618
- const r = await this._execRaw(`cmd /c if exist "${p}" (echo Y) else (echo N)`, { timeoutMs: 8000 })
619
- return /Y/.test(String(r.stdout || ''))
620
- } catch {
621
- return false
622
- }
623
- }
624
-
625
- /** Run one remote command; resolves { code, signal, stdout, stderr }.
626
- * On Windows remotes with Git Bash the script is piped to `bash -s` over the
627
- * exec-channel stdin — no shell quoting round-trip, so any content (quotes,
628
- * backslashes, newlines) survives verbatim. */
629
- exec(command, timeoutMsOrOpts) {
630
- const opts = timeoutMsOrOpts && typeof timeoutMsOrOpts === 'object' ? timeoutMsOrOpts : { timeoutMs: timeoutMsOrOpts }
631
- return this.detect().then(() => {
632
- if (this.platform === 'windows' && this.gitBashPath) {
633
- const script = String(command)
634
- // Preserve an explicit 0 (no deadline, background jobs) through the
635
- // wrapper: `||` would silently replace it with the default timeout.
636
- return this._execRaw(`"${this.gitBashPath}" -s`, { ...opts, timeoutMs: opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs) }, (stream) => {
637
- try { stream.end(script) } catch {}
638
- })
639
- }
640
- return this._execRaw(command, opts)
641
- })
642
- }
643
-
644
- /** Raw exec (no detection / no wrapper). Optional stdinWriter(stream) feeds
645
- * the remote process stdin (used by the Git Bash `-s` mode).
646
- * `opts.timeoutMs === 0` is explicit: NO deadline (background jobs outlive
647
- * their starting call); an absent value falls back to config.commandTimeoutMs. */
648
- _execRaw(command, opts, stdinWriter) {
649
- const timeoutMs = (opts && opts.timeoutMs === 0) ? 0 : ((opts && opts.timeoutMs) || this.config.commandTimeoutMs)
650
- const signal = opts && opts.signal
651
- // Streaming tap for background jobs (issue #70): a promoted command's value
652
- // is its LIVE output, which the job ring must receive as it arrives rather
653
- // than only as a return value the caller already abandoned. Called with
654
- // ('stdout'|'stderr', chunk); failures inside the tap must never break the
655
- // command itself, so every call site guards it.
656
- const onData = opts && typeof opts.onData === 'function' ? opts.onData : null
657
- return this.connect().then(
658
- (client) =>
659
- new Promise((resolve, reject) => {
660
- let retried = false
661
- // Caller cancellation (issue #44): a tool that hands us exec.signal
662
- // expects the remote command to stop when the turn is cancelled.
663
- // Resolve the same shape as a timeout so callers need no new branch.
664
- let onAbort = null
665
- const cleanupAbort = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort) }
666
- const runOn = (c) => {
667
- const execOpts = {}
668
- if (opts && opts.pty) execOpts.pty = true
669
- if (opts && opts.env && typeof opts.env === 'object') execOpts.env = opts.env
670
- c.exec(command, execOpts, (err, stream) => {
671
- if (err) {
672
- // Channel-open failure — or a session termination — usually
673
- // means the pooled connection died server-side (idle timeout /
674
- // network reset) while keepalive hadn't noticed. Drop it and
675
- // retry ONCE on a fresh connection.
676
- if (!retried && /channel open failure|open failed|unexpected .* session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
677
- retried = true
678
- this.invalidate()
679
- return this.connect().then(
680
- (fresh) => runOn(fresh),
681
- (e2) => reject(new Error('ssh exec failed (reconnect): ' + ((e2 && e2.message) || e2))),
682
- )
683
- }
684
- return reject(new Error('ssh exec failed: ' + ((err && err.message) || err)))
685
- }
686
- let stdout = ''
687
- let stderr = ''
688
- let settled = false
689
- let exitCode = null
690
- let exitSignal = null
691
- const hardCap = Math.max(this.config.maxOutputChars * 4, 1024 * 1024)
692
- const settle = () => {
693
- if (settled) return
694
- settled = true
695
- clearTimeout(timer)
696
- cleanupAbort()
697
- resolve({
698
- code: exitCode,
699
- signal: exitSignal,
700
- stdout: truncate(stdout, this.config.maxOutputChars),
701
- stderr: truncate(stderr, this.config.maxOutputChars),
702
- })
703
- }
704
- // No timer at all for an explicit no-deadline call (0): arming
705
- // one with 0 would fire immediately, and with the config default
706
- // it would SIGTERM a background job mid-promotion (issue #95).
707
- const timer = timeoutMs > 0 ? setTimeout(() => {
708
- if (settled) return
709
- exitCode = -1
710
- exitSignal = 'TIMEOUT'
711
- // Kill the remote command (SIGTERM) rather than just dropping the
712
- // channel, so a runaway process cannot keep running and holding
713
- // the SSH connection after we've given up on its output.
714
- try {
715
- if (typeof stream.signal === 'function') stream.signal('SIGTERM')
716
- } catch {}
717
- const hardClose = setTimeout(() => {
718
- try { stream.close() } catch {}
719
- }, 800)
720
- if (typeof hardClose.unref === 'function') hardClose.unref()
721
- settle()
722
- }, timeoutMs) : null
723
- if (signal) {
724
- if (signal.aborted) {
725
- try { if (typeof stream.signal === 'function') stream.signal('SIGTERM') } catch {}
726
- try { stream.close() } catch {}
727
- exitCode = -1
728
- exitSignal = 'ABORTED'
729
- return settle()
730
- }
731
- onAbort = () => {
732
- if (settled) return
733
- exitCode = -1
734
- exitSignal = 'ABORTED'
735
- try { if (typeof stream.signal === 'function') stream.signal('SIGTERM') } catch {}
736
- const hardClose = setTimeout(() => { try { stream.close() } catch {} }, 500)
737
- if (typeof hardClose.unref === 'function') hardClose.unref()
738
- settle()
739
- }
740
- signal.addEventListener('abort', onAbort, { once: true })
741
- }
742
- stream.on('close', (code, sigName) => {
743
- if (settled) return
744
- exitCode = code
745
- // `sigName` is the signal NAME that killed the remote process
746
- // (e.g. 'SIGTERM'), not the caller's AbortSignal. The rename
747
- // matters: `signal` in this scope is the AbortSignal, and
748
- // assigning it here would leak an object into the result.
749
- exitSignal = sigName
750
- settle()
751
- })
752
- stream.on('data', (d) => {
753
- if (stdout.length < hardCap) stdout += d
754
- if (onData) { try { onData('stdout', d) } catch { /* tap errors are not command errors */ } }
755
- })
756
- stream.stderr.on('data', (d) => {
757
- if (stderr.length < hardCap) stderr += d
758
- if (onData) { try { onData('stderr', d) } catch { /* tap errors are not command errors */ } }
759
- })
760
- stream.on('error', (e) => {
761
- if (settled) return
762
- settled = true
763
- clearTimeout(timer)
764
- cleanupAbort()
765
- reject(new Error('ssh stream error: ' + ((e && e.message) || e)))
766
- })
767
- if (stdinWriter) {
768
- try { stdinWriter(stream) } catch {}
769
- }
770
- })
771
- }
772
- runOn(client)
773
- }),
774
- )
775
- }
776
-
777
- /**
778
- * Open an INTERACTIVE shell channel on the remote host (PTY-backed).
779
- *
780
- * This is what an embedded terminal needs and what `exec` cannot provide:
781
- * `exec` runs one command and closes, with no PTY and no stdin after the
782
- * writer returns. A shell channel keeps the session alive across commands, so
783
- * `vim`, `top`, `sudo` prompts and anything else that talks to a terminal
784
- * works the way it does in an ssh session.
785
- *
786
- * The returned stream is ssh2's channel: write to it for keystrokes, listen
787
- * for `data` for output, call `setWindow(rows, cols, height, width)` on
788
- * resize, and `end()`/`close()` to hang up. Columns/rows are negotiated per
789
- * channel, so two terminals on the same pooled connection stay independent.
790
- *
791
- * @param {{cols?: number, rows?: number, term?: string, pty?: boolean}} [opts]
792
- * @returns {Promise<object>} the ssh2 Channel (interactive stream).
793
- */
794
- shell(opts = {}) {
795
- const cols = Math.max(2, Math.min(Number(opts.cols) || 80, 1000))
796
- const rows = Math.max(2, Math.min(Number(opts.rows) || 24, 1000))
797
- const term = String(opts.term || 'xterm-256color')
798
- return this.connect().then(
799
- (client) =>
800
- new Promise((resolve, reject) => {
801
- let retried = false
802
- const runOn = (c) => {
803
- const wndopts = { cols, rows, height: 0, width: 0, term }
804
- // A shell on a Windows remote is a cmd/PowerShell via the default
805
- // sshd shell; the PTY request is identical either way.
806
- c.shell(wndopts, opts.pty === false ? {} : { pty: wndopts }, (err, stream) => {
807
- if (err) {
808
- // Same stale-connection recovery as exec/sftp: a session
809
- // termination means the pooled client died server-side.
810
- if (!retried && /channel open failure|open failed|session termination|disconnect/i.test(String((err && err.message) || err))) {
811
- retried = true
812
- this.invalidate()
813
- return this.connect().then(
814
- (fresh) => runOn(fresh),
815
- (e2) => reject(new Error('ssh shell failed (reconnect): ' + ((e2 && e2.message) || e2))),
816
- )
817
- }
818
- return reject(new Error('ssh shell failed: ' + ((err && err.message) || err)))
819
- }
820
- // An idle shell must not be killed by the connection's own idle
821
- // handling: keepalive is already on, and the channel lives until
822
- // the client calls end(). Nothing to schedule here.
823
- resolve(stream)
824
- })
825
- }
826
- runOn(client)
827
- }),
828
- )
829
- }
830
-
831
- /**
832
- * Resolve the shared promisified SFTP client for the CURRENT connection.
833
- * Keeping one channel per client/epoch avoids leaking a channel per tool call
834
- * into sshd's MaxSessions limit (issue #121).
835
- */
836
- sftp() { return this._sftp(false) }
837
-
838
- _sftp(isRetry) {
839
- const staleClient = this._sftpClient && this.client && this._sftpClient !== this.client
840
- if (this._sftpSession && (this._sftpEpoch !== this.epoch || staleClient)) this._dropSftpSession()
841
- if (this._sftpSession) return this._sftpSession
842
-
843
- const epoch = this.epoch
844
- const connected = isRetry
845
- ? this.connect().catch((e) => { throw new Error('ssh sftp failed (reconnect): ' + ((e && e.message) || e)) })
846
- : this.connect()
847
- const session = connected.then(
848
- (client) =>
849
- new Promise((resolve, reject) => {
850
- // Bound the subchannel open itself, per attempt. Without this, a
851
- // remote whose sftp subsystem is unresponsive (overloaded sshd,
852
- // exceeded MaxSessions, half-open TCP) leaves `client.sftp(cb)` parked
853
- // forever with no callback — issue #44 point 3.
854
- let timedOut = false
855
- const attemptTimer = setTimeout(() => {
856
- timedOut = true
857
- reject(new Error(`ssh sftp open timed out after ${this.config.commandTimeoutMs}ms`))
858
- }, this.config.commandTimeoutMs)
859
- // ★ 这里**不能 unref**。
860
- //
861
- // 这个定时器是"本次 await 的 sftp 打开"的**唯一结算者**:要么它超时 reject,
862
- // 要么 ssh2 回调 resolve。若把它 unref,而进程此刻没有别的 pending 句柄,
863
- // Node 会认为无事可做而**直接退出**,调用方永远等不到结果。
864
- // 实测症状:CI 上该用例之后的 4 个用例被标记 `cancelledByParent`
865
- // (同文件子进程提前退出),而本地因运行器恰好持着句柄而侥幸通过。
866
- // 注意与上面 exec() 的超时定时器保持一致 —— 那个本来就没有 unref。
867
- const clearAttempt = () => { clearTimeout(attemptTimer) }
868
- try {
869
- client.sftp((err, sftp) => {
870
- clearAttempt()
871
- // A late success after the watchdog rejected still owns a real
872
- // channel. Close it, and never adopt it into the cache.
873
- if (timedOut) {
874
- if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
875
- return
876
- }
877
- const wrongClient = this.client && this.client !== client
878
- if (this.epoch !== epoch || this._sftpSession !== session || wrongClient) {
879
- if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
880
- return reject(new Error('ssh target changed while opening sftp'))
881
- }
882
- if (err) {
883
- // Same dead-connection recovery as before: retry ONCE on a fresh
884
- // connection. The new session has its own epoch and is adopted by
885
- // callers of this promise; isRetry prevents recursive reconnects.
886
- if (!isRetry && /channel open failure|open failed|unexpected sftp session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
887
- this.invalidate()
888
- return resolve(this._sftp(true))
889
- }
890
- return reject(new Error('ssh sftp failed: ' + ((err && err.message) || err)))
891
- }
892
-
893
- const drop = () => {
894
- if (this._sftpSession === session) {
895
- this._sftpSession = null
896
- this._sftpEpoch = -1
897
- }
898
- if (this._sftpRaw === sftp) {
899
- this._sftpRaw = null
900
- this._sftpClient = null
901
- }
902
- }
903
- if (typeof sftp.on === 'function') {
904
- sftp.on('end', drop)
905
- sftp.on('close', drop)
906
- sftp.on('error', drop)
907
- }
908
- this._sftpRaw = sftp
909
- this._sftpClient = client
910
- // A successful open proves the connection healthy: reset the
911
- // consecutive-timeout strike counter (issue #65).
912
- this._sftpTimeouts = 0
913
- try {
914
- resolve(buildSftpSurface(sftp, {
915
- commandTimeoutMs: this.config.commandTimeoutMs,
916
- onTimeout: () => {
917
- // A timed-out channel is dead: close AND forget it so the
918
- // next call reopens instead of returning a dead surface.
919
- try { sftp.end() } catch { /* already gone */ }
920
- drop()
921
- this._noteSftpTimeout()
922
- },
923
- }))
924
- } catch (e) {
925
- drop()
926
- try { sftp.end() } catch { /* already gone */ }
927
- reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
928
- }
929
- })
930
- } catch (e) {
931
- clearAttempt()
932
- reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
933
- }
934
- }),
935
- )
936
- // Never cache a rejected open: the next call must retry rather than get the
937
- // same error back forever. Raw fields are only set after a successful open.
938
- session.catch(() => {
939
- if (this._sftpSession === session) {
940
- this._sftpSession = null
941
- this._sftpEpoch = -1
942
- this._sftpClient = null
943
- }
944
- })
945
- this._sftpSession = session
946
- this._sftpEpoch = epoch
947
- return session
948
- }
949
-
950
- /**
951
- * Count a timed-out SFTP subchannel open. A second consecutive timeout means
952
- * the pooled connection itself is wedged (issue #65): tear it down so the
953
- * next sftp() call re-handshakes instead of queueing behind the dead one.
954
- */
955
- _noteSftpTimeout() {
956
- this._sftpTimeouts = (this._sftpTimeouts || 0) + 1
957
- if (this._sftpTimeouts >= 2) this.invalidate()
958
- }
959
-
960
- _dropSftpSession() {
961
- const session = this._sftpSession
962
- const raw = this._sftpRaw
963
- this._sftpSession = null
964
- this._sftpRaw = null
965
- this._sftpClient = null
966
- this._sftpEpoch = -1
967
- if (raw) { try { raw.end() } catch { /* already gone */ } }
968
- // Swallow the rejection: nobody awaits a session we are tearing down.
969
- if (session && typeof session.catch === 'function') session.catch(() => {})
970
- }
971
-
972
- /**
973
- * Drop the cached client and force a fresh connection on the next call.
974
- * Called when a channel open fails (e.g. "Channel open failure: open
975
- * failed") — the pooled SSH connection is usually dead server-side while
976
- * keepalive has not yet noticed, and reusing it keeps failing. The epoch
977
- * bump orphans any in-flight connect; the client is ended so ssh2 frees
978
- * its sockets.
979
- */
980
- invalidate() {
981
- this.epoch++
982
- const client = this.client
983
- this.client = null
984
- this._dropSftpSession()
985
- const pending = this.connecting
986
- this.connecting = null
987
- if (pending && typeof pending.catch === 'function') {
988
- try { pending.catch(() => {}) } catch {}
989
- }
990
- if (this.proxyPool) {
991
- try { this.proxyPool.close() } catch {}
992
- this.proxyPool = null
993
- }
994
- if (client) {
995
- try { client.end() } catch {}
996
- }
997
- // Same teardown as close(): the forwards manager must detach from the
998
- // dying client, or its stale `close -> stopAll()` listener later tears
999
- // down forwards that were re-attached to the NEW client (onReady does
1000
- // the re-attach on the next successful connect).
1001
- if (this.onCloseHook) {
1002
- try { this.onCloseHook() } catch {}
1003
- }
1004
- }
1005
-
1006
- close() {
1007
- this.epoch++
1008
- const client = this.client
1009
- this.client = null
1010
- this._dropSftpSession()
1011
- const pending = this.connecting
1012
- this.connecting = null
1013
- if (pending && typeof pending.catch === 'function') {
1014
- try { pending.catch(() => {}) } catch {}
1015
- }
1016
- if (this.proxyPool) {
1017
- try { this.proxyPool.close() } catch {}
1018
- this.proxyPool = null
1019
- }
1020
- if (client) {
1021
- try {
1022
- client.end()
1023
- } catch {}
1024
- }
1025
- if (this.onCloseHook) {
1026
- try { this.onCloseHook() } catch {}
1027
- }
1028
- }
1029
- }
1
+ // Persistent SSH/SFTP connection pool (one identity → one live client).
2
+ import ssh2 from 'ssh2'
3
+ import { readFileSync } from 'node:fs'
4
+ import { homedir } from 'node:os'
5
+ import path from 'node:path'
6
+ import { truncate } from './paths.js'
7
+ import { createHostKeyGuard } from './hostkey.js'
8
+ import { buildSftpSurface } from './sftp-surface.js'
9
+ import { friendlyMessage } from './errors.js'
10
+ import { SystemOpenSshPool, isSystemOpenSshBackend } from './openssh.js'
11
+
12
+ const { Client } = ssh2
13
+
14
+ /**
15
+ * A key path that names a PUBLIC key. `IdentityFile ~/.ssh/x.pub` is OpenSSH's
16
+ * idiom for "the private key lives in the agent (1Password, Bitwarden, rbw…);
17
+ * use the agent key matching this file" — it must never be handed to ssh2 as
18
+ * a private key.
19
+ */
20
+ export function isPublicKeyPath(p) {
21
+ return /\.pub$/i.test(String(p || ''))
22
+ }
23
+
24
+ /** The wire blob of an OpenSSH public key line (`type base64 [comment]`). */
25
+ export function publicKeyBlob(text) {
26
+ const parts = String(text || '').trim().split(/\s+/)
27
+ if (parts.length < 2) return null
28
+ const blob = Buffer.from(parts[1], 'base64')
29
+ return blob.length ? blob : null
30
+ }
31
+
32
+ /**
33
+ * An agent that offers the key matching `wantBlob` FIRST — and, with
34
+ * `only` (IdentitiesOnly yes), nothing else. Without the ordering ssh2 offers
35
+ * every agent key in turn, and an agent holding many keys trips the server's
36
+ * MaxAuthTries before reaching the right one.
37
+ */
38
+ export class PreferredKeyAgent extends ssh2.BaseAgent {
39
+ constructor(inner, wantBlob, only) {
40
+ super()
41
+ this.inner = inner
42
+ this.wantBlob = wantBlob
43
+ this.only = !!only
44
+ }
45
+
46
+ getIdentities(cb) {
47
+ this.inner.getIdentities((err, keys) => {
48
+ if (err) return cb(err)
49
+ const list = Array.isArray(keys) ? keys : []
50
+ const isWanted = (k) => {
51
+ try { return Buffer.from(k.getPublicSSH()).equals(this.wantBlob) } catch { return false }
52
+ }
53
+ const wanted = list.filter(isWanted)
54
+ cb(null, this.only ? wanted : [...wanted, ...list.filter((k) => !isWanted(k))])
55
+ })
56
+ }
57
+
58
+ sign(...args) {
59
+ return this.inner.sign(...args)
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Build the pool for a config.
65
+ *
66
+ * Two backends exist (issue #51): the native one below, which speaks SSH itself
67
+ * via ssh2, and the "system OpenSSH" one (lib/openssh.js), which delegates to
68
+ * the local `ssh` executable so GSSAPI/Kerberos and the rest of the user's
69
+ * `~/.ssh/config` are honoured. Both expose one identical surface, so every
70
+ * caller can keep using `new SshPool(...)`-shaped code — this factory only has
71
+ * to decide which class to instantiate.
72
+ */
73
+ /** Hard cap on proxy-chain depth. OpenSSH's ProxyJump has no explicit limit;
74
+ * this exists to turn a config CYCLE into a clear error instead of unbounded
75
+ * recursion. A legitimate chain is 1-3 hops.
76
+ * @type {number} */
77
+ export const MAX_JUMP_HOPS = 8
78
+
79
+ export function createPool(config, opts) {
80
+ return isSystemOpenSshBackend(config)
81
+ ? new SystemOpenSshPool(config, opts)
82
+ : new SshPool(config, opts)
83
+ }
84
+
85
+ /**
86
+ * Run one `forwardOut` and resolve with the resulting channel.
87
+ *
88
+ * ssh2 reports a dead connection by THROWING synchronously —
89
+ * `if (!this._sock || !isWritable(this._sock)) throw new Error('Not connected')`
90
+ * (ssh2 >= 1.16, `Client.forwardOut`) — and never calls the callback, so a
91
+ * callback-only error path cannot guard this call (issue #54). Two further
92
+ * consequences justify a shared helper rather than an inline try/catch:
93
+ *
94
+ * • inside a `new Promise(executor)` a bare throw rejects nothing: it becomes
95
+ * an unhandled REJECTION and leaves the promise pending forever;
96
+ * • called from a `net.Server` connection handler the throw escapes to the
97
+ * process top level and kills the host.
98
+ *
99
+ * This guards the CALLER's side of the contract rather than assuming one
100
+ * backend's behaviour: the system-OpenSSH backend (lib/openssh.js `forwardOut`)
101
+ * already converts its own spawn failure into a callback error, so for it the
102
+ * try/catch below is dead code — but a backend is free to throw, and the one
103
+ * that does must not be able to take the process down.
104
+ *
105
+ * @param {object} client - an ssh2 Client or OpenSshConnection.
106
+ * @param {object} spec - `srcHost`/`srcPort`/`dstHost`/`dstPort`.
107
+ * @returns {Promise<object>} the forwarded channel / duplex stream.
108
+ */
109
+ export function forwardOutChannel(client, { srcHost = '127.0.0.1', srcPort = 0, dstHost, dstPort }) {
110
+ return new Promise((resolve, reject) => {
111
+ // `reject` is called at most once: a callback that fires after a successful
112
+ // throw-path rejection would be a no-op, which Promise guarantees.
113
+ try {
114
+ client.forwardOut(srcHost, srcPort, dstHost, dstPort, (err, channel) => (err ? reject(err) : resolve(channel)))
115
+ } catch (err) {
116
+ reject(err)
117
+ }
118
+ })
119
+ }
120
+
121
+ /**
122
+ * The ACTIVE pool: one long-lived object whose concrete implementation can be
123
+ * swapped when the current machine's transport backend changes.
124
+ *
125
+ * Why a delegating facade instead of just constructing the right class once:
126
+ * `backend` is a PER-MACHINE field (an enterprise Kerberos host needs
127
+ * `openssh` while every other machine stays on `native`), but the plugin keeps
128
+ * exactly one active pool for its whole lifetime and hangs `passwordResolver` /
129
+ * `onReady` / `onCloseHook` off it once at startup. Replacing the object
130
+ * wholesale on every machine switch would silently drop those hooks — the port
131
+ * forwards and keychain passwords would stop working after the first switch.
132
+ *
133
+ * So the facade owns the hooks and the shared `config` object, and forwards
134
+ * them to whichever concrete pool is right for the current config. Everything
135
+ * else is a straight delegation, which is why callers cannot tell the
136
+ * difference (and why the class is deliberately not part of the public story).
137
+ */
138
+ export class ActivePool {
139
+ constructor(config, opts = {}) {
140
+ this.config = config
141
+ this.opts = opts
142
+ // The hooks are assigned by the plugin AFTER construction, so they are
143
+ // stored here and re-applied to every delegate this facade ever creates.
144
+ this._passwordResolver = null
145
+ this._onReady = null
146
+ this._onCloseHook = null
147
+ this._delegate = null
148
+ this._sync()
149
+ }
150
+
151
+ /** Which concrete class the current config asks for. */
152
+ _wantsSystemOpenSsh() {
153
+ return isSystemOpenSshBackend(this.config)
154
+ }
155
+
156
+ _delegateIsCurrent() {
157
+ if (!this._delegate) return false
158
+ const isOpenssh = this._delegate instanceof SystemOpenSshPool
159
+ return isOpenssh === this._wantsSystemOpenSsh()
160
+ }
161
+
162
+ /** Create (or replace) the delegate so it matches the current config. */
163
+ _sync() {
164
+ if (this._delegateIsCurrent()) return this._delegate
165
+ const previous = this._delegate
166
+ const next = createPool(this.config, this.opts)
167
+ next.passwordResolver = this._passwordResolver
168
+ next.onReady = this._onReady
169
+ next.onCloseHook = this._onCloseHook
170
+ this._delegate = next
171
+ // Tear the old backend down LAST, and never let a teardown error mask the
172
+ // new pool: the connection it was holding belongs to the old host anyway.
173
+ if (previous) { try { previous.close() } catch { /* already gone */ } }
174
+ return next
175
+ }
176
+
177
+ get delegate() { return this._sync() }
178
+
179
+ // ── hooks: stored here, mirrored onto every delegate ──────────────────────
180
+ get passwordResolver() { return this._passwordResolver }
181
+ set passwordResolver(fn) {
182
+ this._passwordResolver = fn
183
+ if (this._delegate) this._delegate.passwordResolver = fn
184
+ }
185
+ get onReady() { return this._onReady }
186
+ set onReady(fn) {
187
+ this._onReady = fn
188
+ if (this._delegate) this._delegate.onReady = fn
189
+ }
190
+ get onCloseHook() { return this._onCloseHook }
191
+ set onCloseHook(fn) {
192
+ this._onCloseHook = fn
193
+ if (this._delegate) this._delegate.onCloseHook = fn
194
+ }
195
+
196
+ // ── pass-through state the plugin reads directly ──────────────────────────
197
+ get client() { return this._delegate ? this._delegate.client : null }
198
+ // Assignable because the plugin's own tests arm a fake live connection on the
199
+ // active pool; a getter-only facade would make that assignment a silent
200
+ // no-op in sloppy mode and a TypeError in the strict-mode ESM tests.
201
+ set client(v) { if (this._sync()) this._delegate.client = v }
202
+ get connecting() { return this._delegate ? this._delegate.connecting : null }
203
+ get proxyPool() { return this._delegate ? this._delegate.proxyPool : null }
204
+ get epoch() { return this._delegate ? this._delegate.epoch : 0 }
205
+ get platform() { return this._delegate ? this._delegate.platform : 'unknown' }
206
+ set platform(v) { if (this._sync()) this._delegate.platform = v }
207
+ get gitBashPath() { return this._delegate ? this._delegate.gitBashPath : '' }
208
+ set gitBashPath(v) { if (this._sync()) this._delegate.gitBashPath = v }
209
+ get shellMode() { return this._delegate ? this._delegate.shellMode : 'native' }
210
+ set shellMode(v) { if (this._sync()) this._delegate.shellMode = v }
211
+
212
+ // ── delegated operations ──────────────────────────────────────────────────
213
+ /** Re-point at a new target, switching backend first if the machine asks. */
214
+ setTarget(fields, previous) {
215
+ // The backend may have changed with the machine, so apply that part of the
216
+ // request to `config` BEFORE picking the delegate: _sync() chooses the class
217
+ // from config.backend, and the old backend must not be handed a host it can
218
+ // no longer reach. The delegate then receives the whole request as usual.
219
+ if (fields && fields.backend !== undefined) this.config.backend = String(fields.backend)
220
+ if (fields && fields.sshBinary !== undefined) this.config.sshBinary = String(fields.sshBinary)
221
+ const d = this._sync()
222
+ return d.setTarget(fields, previous)
223
+ }
224
+ connect() { return this.delegate.connect() }
225
+ exec(cmd, opts) { return this.delegate.exec(cmd, opts) }
226
+ sftp() { return this.delegate.sftp() }
227
+ shell(opts) { return this.delegate.shell(opts) }
228
+ detect() { return this.delegate.detect() }
229
+ invalidate() { return this.delegate.invalidate() }
230
+ close() { return this.delegate.close() }
231
+ }
232
+
233
+ export class SshPool {
234
+ constructor(config, opts = {}) {
235
+ this.config = config
236
+ this._knownHostsFile = opts.knownHostsFile
237
+ this.client = null
238
+ this.connecting = null
239
+ this.proxyPool = null
240
+ // Generational token: bumped on every target change / close so a stale
241
+ // in-flight connect can never hand this pool a connection to an old host.
242
+ this.epoch = 0
243
+ /** Auto-detected remote platform: unknown | windows | posix (per target). */
244
+ this.platform = 'unknown'
245
+ /** Resolved Git Bash bash.exe path on Windows remotes ('' when none). */
246
+ this.gitBashPath = ''
247
+ /** Resolved terminal strategy: native | git-bash. */
248
+ this.shellMode = 'native'
249
+ /** In-flight platform detection promise (cached). */
250
+ this._detecting = null
251
+ /** Optional async resolver for a machine-stored (keychain) password. */
252
+ this.passwordResolver = null
253
+ /** Optional hook called with the live client after a successful connect. */
254
+ this.onReady = null
255
+ /** Optional hook called when the pool closes. */
256
+ this.onCloseHook = null
257
+ /** Consecutive SFTP subchannel-open timeouts (issue #65). */
258
+ this._sftpTimeouts = 0
259
+ /** One SFTP session per live client/epoch (issue #121). */
260
+ this._sftpSession = null
261
+ this._sftpRaw = null
262
+ this._sftpClient = null
263
+ this._sftpEpoch = -1
264
+ }
265
+
266
+ resolveKeyPath() {
267
+ const p = this.config.privateKeyPath
268
+ if (!p) return ''
269
+ if (p.startsWith('~/') || p === '~') return path.join(homedir(), p.slice(1))
270
+ return p
271
+ }
272
+
273
+ setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
274
+ // Collect the requested changes first: an UNCHANGED target is a no-op. The
275
+ // old behavior closed the live connection and re-ran platform detection
276
+ // even for an identical target, so every picker keystroke
277
+ // (POST /current → applyActiveMachine → setTarget) paid a full SSH
278
+ // reconnect + re-detect — the "slow remote path autocomplete" bug.
279
+ //
280
+ // `previous` is the diff BASELINE. Callers whose shared config was already
281
+ // mutated BEFORE this call (applyActiveMachine: applyMachine rewrites the
282
+ // live config IN PLACE, and pool.config IS that config object) pass a
283
+ // pre-mutation snapshot — otherwise the comparison runs the new values
284
+ // against themselves, is always equal and never closes even for a machine
285
+ // switch (the wrong-host hazard of issue #25). Defaults to the current
286
+ // config for callers that pass fresh values read independently of it.
287
+ const base = previous || this.config
288
+ const wanted = []
289
+ if (host !== undefined) wanted.push(['host', String(host)])
290
+ if (port !== undefined && Number(port)) wanted.push(['port', Number(port)])
291
+ if (username !== undefined) wanted.push(['username', String(username)])
292
+ if (password !== undefined && password !== null) wanted.push(['password', String(password)])
293
+ if (privateKeyPath !== undefined) wanted.push(['privateKeyPath', String(privateKeyPath)])
294
+ if (passphrase !== undefined) wanted.push(['passphrase', String(passphrase)])
295
+ if (workspace !== undefined) wanted.push(['workspace', String(workspace)])
296
+ if (useAgent !== undefined) wanted.push(['useAgent', !!useAgent])
297
+ if (keyboardInteractive !== undefined) wanted.push(['keyboardInteractive', !!keyboardInteractive])
298
+ if (proxy !== undefined) wanted.push(['proxy', proxy])
299
+ if (hostKeyMode !== undefined) wanted.push(['hostKeyMode', String(hostKeyMode)])
300
+ // Issue #51: the transport backend is part of the target identity — changing
301
+ // it must close the live connection exactly like changing the host does.
302
+ if (backend !== undefined) wanted.push(['backend', String(backend)])
303
+ if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
304
+ const differs = ([k, v]) => (k === 'proxy'
305
+ ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
306
+ : base[k] !== v)
307
+ // Something actually changed → apply it and force a fresh connection.
308
+ // (A caller that WANTS a reconnect for an identical target uses
309
+ // invalidate(); setTarget semantics stay "re-point when moved".)
310
+ if (wanted.some(differs)) {
311
+ for (const [k, v] of wanted) this.config[k] = v
312
+ // the new target may be a different OS — re-detect on the next command
313
+ this.platform = 'unknown'
314
+ this.gitBashPath = ''
315
+ this.shellMode = 'native'
316
+ this._detecting = null
317
+ this.close()
318
+ }
319
+ return this
320
+ }
321
+
322
+ connect() {
323
+ if (this.client) return Promise.resolve(this.client)
324
+ if (this.connecting) return this.connecting
325
+ const epoch = this.epoch
326
+ const pending = this._doConnect(epoch)
327
+ this.connecting = pending
328
+ const clear = () => {
329
+ if (this.epoch === epoch && this.connecting === pending) this.connecting = null
330
+ }
331
+ pending.then(clear, clear)
332
+ return pending
333
+ }
334
+
335
+ async _doConnect(epoch) {
336
+ const isCurrent = () => this.epoch === epoch
337
+ const knownHostsFile = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
338
+ const guard = createHostKeyGuard(this.config, knownHostsFile)
339
+ const client = new Client()
340
+ let settled = false
341
+ // Every connect-stage failure is classified HERE, at the layer that knows
342
+ // which machine was being dialed: a bare ssh2 errno ("Timed out while
343
+ // waiting for handshake") names no host, and on a multi-machine plugin the
344
+ // user cannot tell WHICH box failed. friendlyMessage is idempotent, so
345
+ // callers that classify again (rw_connect, routes) do not double-wrap.
346
+ const classify = (err) => new Error(friendlyMessage(err, { host: this.config.host, port: this.config.port }))
347
+ const fail = (err) => {
348
+ if (settled) return
349
+ settled = true
350
+ if (isCurrent() && this.client === client) this.client = null
351
+ throw classify(guard.lastError ? new Error(guard.lastError) : err)
352
+ }
353
+
354
+ // Proxy jump: SSH to the bastion first, then tunnel to the target through it.
355
+ //
356
+ // MULTI-HOP (OpenSSH `ProxyJump a,b,c` semantics): each bastion may itself
357
+ // carry a `proxy`, and the chain is built from the FARTHEST hop inward — hop
358
+ // N is dialed through the already-open connection to hop N-1. The recursion
359
+ // IS the mechanism, so there is no depth limit beyond what the config
360
+ // expresses; MAX_JUMP_HOPS is a cycle/typo guard, not a feature limit.
361
+ let sock = null
362
+ const proxyCfg = this.config.proxy
363
+ if (proxyCfg && proxyCfg.host) {
364
+ try {
365
+ const depth = Number(this.config._hopDepth) || 0
366
+ if (depth >= MAX_JUMP_HOPS) {
367
+ throw new Error(`proxy chain is deeper than ${MAX_JUMP_HOPS} hops — check the machine config for a proxy cycle`)
368
+ }
369
+ this.proxyPool = new SshPool({
370
+ ...this.config,
371
+ host: proxyCfg.host,
372
+ port: Number(proxyCfg.port) || 22,
373
+ username: proxyCfg.username || this.config.username || 'root',
374
+ // CREDENTIALS DO NOT INHERIT ACROSS HOPS. `...this.config` brings the
375
+ // TARGET's key/passphrase along, which is wrong in two ways: it may
376
+ // not be authorized on the bastion, and presenting the target's key to
377
+ // an intermediate host hands that host a credential it should never
378
+ // see. A hop with no key of its own falls back to the agent/default
379
+ // discovery path, which is what an operator's own ssh setup provides.
380
+ password: proxyCfg.password || '',
381
+ privateKeyPath: proxyCfg.privateKeyPath || '',
382
+ passphrase: proxyCfg.passphrase || '',
383
+ agentSocket: proxyCfg.agentSocket || '',
384
+ identitiesOnly: !!proxyCfg.identitiesOnly,
385
+ ...(proxyCfg.useAgent !== undefined ? { useAgent: !!proxyCfg.useAgent } : {}),
386
+ ...(proxyCfg.keyboardInteractive !== undefined ? { keyboardInteractive: !!proxyCfg.keyboardInteractive } : {}),
387
+ ...(proxyCfg.hostKeyMode ? { hostKeyMode: proxyCfg.hostKeyMode } : {}),
388
+ // The nested hop keeps its OWN proxy — that is what builds the chain —
389
+ // and carries an incremented depth so a cycle is reported instead of
390
+ // recursing until the process dies.
391
+ proxy: proxyCfg.proxy && proxyCfg.proxy.host ? proxyCfg.proxy : undefined,
392
+ _hopDepth: depth + 1,
393
+ }, { knownHostsFile: this._knownHostsFile })
394
+ const pclient = await this.proxyPool.connect()
395
+ if (!isCurrent()) throw new Error('ssh target changed during proxy connect')
396
+ try {
397
+ sock = await forwardOutChannel(pclient, { dstHost: this.config.host, dstPort: this.config.port })
398
+ } catch (e) {
399
+ throw new Error('proxy forward to target failed: ' + ((e && e.message) || e))
400
+ }
401
+ } catch (err) {
402
+ return fail(err)
403
+ }
404
+ }
405
+
406
+ return new Promise((resolve, reject) => {
407
+ const rejectOnce = (err) => {
408
+ if (settled) return
409
+ settled = true
410
+ if (isCurrent() && this.client === client) this.client = null
411
+ reject(classify(guard.lastError ? new Error(guard.lastError) : err))
412
+ }
413
+ client.on('ready', () => {
414
+ if (settled) return
415
+ settled = true
416
+ if (!isCurrent()) {
417
+ try { client.end() } catch {}
418
+ reject(classify(new Error('ssh target changed during connect')))
419
+ return
420
+ }
421
+ this.client = client
422
+ this._sftpTimeouts = 0
423
+ resolve(client)
424
+ if (this.onReady) { try { this.onReady(client) } catch {} }
425
+ })
426
+ client.on('error', (e) => rejectOnce(e))
427
+ client.on('close', () => {
428
+ if (isCurrent() && this.client === client) {
429
+ this.client = null
430
+ this._dropSftpSession()
431
+ }
432
+ rejectOnce(new Error('ssh connection closed'))
433
+ })
434
+
435
+ const buildOpts = async () => {
436
+ const opts = {
437
+ host: this.config.host,
438
+ port: this.config.port,
439
+ username: this.config.username,
440
+ readyTimeout: this.config.connectTimeoutMs,
441
+ keepaliveInterval: 15000,
442
+ keepaliveCountMax: 3,
443
+ hostVerifier: (key) => guard.verifier(key),
444
+ }
445
+ if (sock) opts.sock = sock
446
+ // `useAgent` asks for agent auth, but ssh2 can only offer it when this
447
+ // PROCESS has an agent socket. On Windows there is no agent by default,
448
+ // so the flag alone used to fall through to the generic "no credentials"
449
+ // error — which reads as "the plugin lost my settings" rather than "this
450
+ // machine has no agent". Track the intent so the failure can say which.
451
+ let agentRequested = false
452
+ // `IdentityAgent` from ~/.ssh/config (agentSocket) wins over the
453
+ // process SSH_AUTH_SOCK, exactly as in ssh; `none` turns the agent off.
454
+ const agentSocket = String(this.config.agentSocket || '')
455
+ const sockPath = agentSocket === 'none' ? '' : (agentSocket || process.env.SSH_AUTH_SOCK || '')
456
+ const keyPathRaw = this.config.privateKeyPath ? this.resolveKeyPath() : ''
457
+ const agentKeyHint = isPublicKeyPath(keyPathRaw)
458
+ if (this.config.useAgent || agentKeyHint || (agentSocket && agentSocket !== 'none')) {
459
+ if (sockPath) opts.agent = sockPath
460
+ else agentRequested = true
461
+ }
462
+ let password = this.config.password || ''
463
+ if (!password && this.passwordResolver) {
464
+ try { password = (await this.passwordResolver()) || '' } catch {}
465
+ }
466
+ if (password) {
467
+ opts.password = password
468
+ opts.tryKeyboard = true
469
+ } else if (this.config.keyboardInteractive && !this.config.privateKeyPath) {
470
+ opts.tryKeyboard = true
471
+ }
472
+ if (agentKeyHint) {
473
+ // The key file is a PUBLIC key: authenticate through the agent with
474
+ // the matching key (see isPublicKeyPath).
475
+ if (!opts.agent) {
476
+ throw new Error(`no SSH agent available: the identity "${keyPathRaw}" is a public key, so its private key must come from an SSH agent, but neither IdentityAgent nor SSH_AUTH_SOCK gives one to the DSH host process`)
477
+ }
478
+ let blob
479
+ try {
480
+ blob = publicKeyBlob(readFileSync(keyPathRaw, 'utf8'))
481
+ } catch (err) {
482
+ throw new Error(`cannot read public key "${keyPathRaw}": ${err && err.message}`)
483
+ }
484
+ if (!blob) throw new Error(`cannot parse public key "${keyPathRaw}"`)
485
+ opts.agent = new PreferredKeyAgent(ssh2.createAgent(opts.agent), blob, this.config.identitiesOnly)
486
+ } else if (this.config.privateKeyPath) {
487
+ const keyPath = this.resolveKeyPath()
488
+ if (!keyPath) {
489
+ throw new Error('no credentials: set a password or a privateKeyPath to connect')
490
+ }
491
+ let key
492
+ try {
493
+ key = readFileSync(keyPath)
494
+ } catch (err) {
495
+ throw new Error(`cannot read private key "${keyPath}": ${err && err.message}`)
496
+ }
497
+ opts.privateKey = key
498
+ opts.passphrase = this.config.passphrase || undefined
499
+ } else if (!password && !opts.agent) {
500
+ throw new Error(agentRequested
501
+ ? 'no SSH agent available: useAgent is enabled for this machine but SSH_AUTH_SOCK is not set in the DSH host process (Windows has no agent by default) — start an agent (or Pageant) before launching DSH, or save a password / private key for this machine'
502
+ : 'no credentials: set a password, a privateKeyPath, or enable useAgent to connect')
503
+ }
504
+ return opts
505
+ }
506
+
507
+ buildOpts().then(
508
+ (opts) => {
509
+ if (opts.tryKeyboard) {
510
+ client.on('keyboard-interactive', (name, instructions, lang, prompts, finish) => {
511
+ finish(prompts.map(() => this.config.password || ''))
512
+ })
513
+ }
514
+ // ssh2 parses the private key SYNCHRONOUSLY inside connect() and
515
+ // throws on an unparseable key (the classic case: an encrypted
516
+ // OpenSSH key without a passphrase). Left uncaught, that throw
517
+ // rejects this orphaned .then chain — an unhandled rejection that
518
+ // crashes the whole host process (issue #48: "dsh: fatal load
519
+ // failure" on every boot, because boot-restore re-dials the bad
520
+ // machine). It also leaves the outer promise pending forever.
521
+ // Convert it into a normal rejection so every caller's try/catch —
522
+ // boot restore, test-connect, rw_connect — sees a regular failure.
523
+ try {
524
+ client.connect(opts)
525
+ } catch (err) {
526
+ rejectOnce(err)
527
+ }
528
+ },
529
+ (err) => rejectOnce(err),
530
+ )
531
+ })
532
+ }
533
+
534
+ /** Detect the remote platform + locate Git Bash once; cached per target. */
535
+ detect() {
536
+ if (this.platform !== 'unknown') return Promise.resolve()
537
+ if (this._detecting) return this._detecting
538
+ this._detecting = this._detect().finally(() => {
539
+ this._detecting = null
540
+ })
541
+ return this._detecting
542
+ }
543
+
544
+ async _detect() {
545
+ let res
546
+ try {
547
+ // `cmd /c ver` works under cmd.exe, PowerShell AND Git Bash (all print
548
+ // "Microsoft Windows …"); on POSIX hosts `cmd` simply doesn't exist.
549
+ res = await this._execRaw('cmd /c ver', { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
550
+ } catch (err) {
551
+ this.platform = 'unknown'
552
+ this.shellMode = 'native'
553
+ return
554
+ }
555
+ const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
556
+ if (res.code === 0 && /microsoft windows/i.test(out)) {
557
+ this.platform = 'windows'
558
+ await this._resolveGitBash()
559
+ return
560
+ }
561
+ // inconclusive — probe for a Git-Bash/MSYS remote (uname prints MINGW64_NT…)
562
+ try {
563
+ const u = await this._execRaw('uname -s', { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
564
+ if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
565
+ this.platform = 'windows'
566
+ await this._resolveGitBash()
567
+ return
568
+ }
569
+ } catch {}
570
+ this.platform = 'posix'
571
+ this.shellMode = 'native'
572
+ this.gitBashPath = ''
573
+ }
574
+
575
+ /** On a Windows remote, locate Git Bash (config path → PATH → common installs). */
576
+ async _resolveGitBash() {
577
+ const cfg = String(this.config.shell || '').trim()
578
+ if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
579
+ if (await this._cmdExists(cfg)) {
580
+ this.gitBashPath = cfg
581
+ this.shellMode = 'git-bash'
582
+ return
583
+ }
584
+ }
585
+ if (cfg === 'native') {
586
+ this.shellMode = 'native'
587
+ this.gitBashPath = ''
588
+ return
589
+ }
590
+ try {
591
+ const r = await this._execRaw('cmd /c where bash', { timeoutMs: 8000 })
592
+ const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
593
+ if (first) {
594
+ this.gitBashPath = first
595
+ this.shellMode = 'git-bash'
596
+ return
597
+ }
598
+ } catch {}
599
+ const candidates = [
600
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
601
+ 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
602
+ ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
603
+ '%LOCALAPPDATA%\\Programs\\Git\\bin\\bash.exe',
604
+ ]
605
+ for (const c of candidates) {
606
+ if (await this._cmdExists(c)) {
607
+ this.gitBashPath = c
608
+ this.shellMode = 'git-bash'
609
+ return
610
+ }
611
+ }
612
+ this.shellMode = 'git-bash' // wanted but not found — commands fall back to raw
613
+ this.gitBashPath = ''
614
+ }
615
+
616
+ async _cmdExists(p) {
617
+ try {
618
+ const r = await this._execRaw(`cmd /c if exist "${p}" (echo Y) else (echo N)`, { timeoutMs: 8000 })
619
+ return /Y/.test(String(r.stdout || ''))
620
+ } catch {
621
+ return false
622
+ }
623
+ }
624
+
625
+ /** Run one remote command; resolves { code, signal, stdout, stderr }.
626
+ * On Windows remotes with Git Bash the script is piped to `bash -s` over the
627
+ * exec-channel stdin — no shell quoting round-trip, so any content (quotes,
628
+ * backslashes, newlines) survives verbatim. */
629
+ exec(command, timeoutMsOrOpts) {
630
+ const opts = timeoutMsOrOpts && typeof timeoutMsOrOpts === 'object' ? timeoutMsOrOpts : { timeoutMs: timeoutMsOrOpts }
631
+ return this.detect().then(() => {
632
+ if (this.platform === 'windows' && this.gitBashPath) {
633
+ const script = String(command)
634
+ // Preserve an explicit 0 (no deadline, background jobs) through the
635
+ // wrapper: `||` would silently replace it with the default timeout.
636
+ return this._execRaw(`"${this.gitBashPath}" -s`, { ...opts, timeoutMs: opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs) }, (stream) => {
637
+ try { stream.end(script) } catch {}
638
+ })
639
+ }
640
+ return this._execRaw(command, opts)
641
+ })
642
+ }
643
+
644
+ /** Raw exec (no detection / no wrapper). Optional stdinWriter(stream) feeds
645
+ * the remote process stdin (used by the Git Bash `-s` mode).
646
+ * `opts.timeoutMs === 0` is explicit: NO deadline (background jobs outlive
647
+ * their starting call); an absent value falls back to config.commandTimeoutMs. */
648
+ _execRaw(command, opts, stdinWriter) {
649
+ const timeoutMs = (opts && opts.timeoutMs === 0) ? 0 : ((opts && opts.timeoutMs) || this.config.commandTimeoutMs)
650
+ const signal = opts && opts.signal
651
+ // Streaming tap for background jobs (issue #70): a promoted command's value
652
+ // is its LIVE output, which the job ring must receive as it arrives rather
653
+ // than only as a return value the caller already abandoned. Called with
654
+ // ('stdout'|'stderr', chunk); failures inside the tap must never break the
655
+ // command itself, so every call site guards it.
656
+ const onData = opts && typeof opts.onData === 'function' ? opts.onData : null
657
+ return this.connect().then(
658
+ (client) =>
659
+ new Promise((resolve, reject) => {
660
+ let retried = false
661
+ // Caller cancellation (issue #44): a tool that hands us exec.signal
662
+ // expects the remote command to stop when the turn is cancelled.
663
+ // Resolve the same shape as a timeout so callers need no new branch.
664
+ let onAbort = null
665
+ const cleanupAbort = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort) }
666
+ const runOn = (c) => {
667
+ const execOpts = {}
668
+ if (opts && opts.pty) execOpts.pty = true
669
+ if (opts && opts.env && typeof opts.env === 'object') execOpts.env = opts.env
670
+ c.exec(command, execOpts, (err, stream) => {
671
+ if (err) {
672
+ // Channel-open failure — or a session termination — usually
673
+ // means the pooled connection died server-side (idle timeout /
674
+ // network reset) while keepalive hadn't noticed. Drop it and
675
+ // retry ONCE on a fresh connection.
676
+ if (!retried && /channel open failure|open failed|unexpected .* session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
677
+ retried = true
678
+ this.invalidate()
679
+ return this.connect().then(
680
+ (fresh) => runOn(fresh),
681
+ (e2) => reject(new Error('ssh exec failed (reconnect): ' + ((e2 && e2.message) || e2))),
682
+ )
683
+ }
684
+ return reject(new Error('ssh exec failed: ' + ((err && err.message) || err)))
685
+ }
686
+ let stdout = ''
687
+ let stderr = ''
688
+ let settled = false
689
+ let exitCode = null
690
+ let exitSignal = null
691
+ const hardCap = Math.max(this.config.maxOutputChars * 4, 1024 * 1024)
692
+ const settle = () => {
693
+ if (settled) return
694
+ settled = true
695
+ clearTimeout(timer)
696
+ cleanupAbort()
697
+ resolve({
698
+ code: exitCode,
699
+ signal: exitSignal,
700
+ stdout: truncate(stdout, this.config.maxOutputChars),
701
+ stderr: truncate(stderr, this.config.maxOutputChars),
702
+ })
703
+ }
704
+ // No timer at all for an explicit no-deadline call (0): arming
705
+ // one with 0 would fire immediately, and with the config default
706
+ // it would SIGTERM a background job mid-promotion (issue #95).
707
+ const timer = timeoutMs > 0 ? setTimeout(() => {
708
+ if (settled) return
709
+ exitCode = -1
710
+ exitSignal = 'TIMEOUT'
711
+ // Kill the remote command (SIGTERM) rather than just dropping the
712
+ // channel, so a runaway process cannot keep running and holding
713
+ // the SSH connection after we've given up on its output.
714
+ try {
715
+ if (typeof stream.signal === 'function') stream.signal('SIGTERM')
716
+ } catch {}
717
+ const hardClose = setTimeout(() => {
718
+ try { stream.close() } catch {}
719
+ }, 800)
720
+ if (typeof hardClose.unref === 'function') hardClose.unref()
721
+ settle()
722
+ }, timeoutMs) : null
723
+ if (signal) {
724
+ if (signal.aborted) {
725
+ try { if (typeof stream.signal === 'function') stream.signal('SIGTERM') } catch {}
726
+ try { stream.close() } catch {}
727
+ exitCode = -1
728
+ exitSignal = 'ABORTED'
729
+ return settle()
730
+ }
731
+ onAbort = () => {
732
+ if (settled) return
733
+ exitCode = -1
734
+ exitSignal = 'ABORTED'
735
+ try { if (typeof stream.signal === 'function') stream.signal('SIGTERM') } catch {}
736
+ const hardClose = setTimeout(() => { try { stream.close() } catch {} }, 500)
737
+ if (typeof hardClose.unref === 'function') hardClose.unref()
738
+ settle()
739
+ }
740
+ signal.addEventListener('abort', onAbort, { once: true })
741
+ }
742
+ stream.on('close', (code, sigName) => {
743
+ if (settled) return
744
+ exitCode = code
745
+ // `sigName` is the signal NAME that killed the remote process
746
+ // (e.g. 'SIGTERM'), not the caller's AbortSignal. The rename
747
+ // matters: `signal` in this scope is the AbortSignal, and
748
+ // assigning it here would leak an object into the result.
749
+ exitSignal = sigName
750
+ settle()
751
+ })
752
+ stream.on('data', (d) => {
753
+ if (stdout.length < hardCap) stdout += d
754
+ if (onData) { try { onData('stdout', d) } catch { /* tap errors are not command errors */ } }
755
+ })
756
+ stream.stderr.on('data', (d) => {
757
+ if (stderr.length < hardCap) stderr += d
758
+ if (onData) { try { onData('stderr', d) } catch { /* tap errors are not command errors */ } }
759
+ })
760
+ stream.on('error', (e) => {
761
+ if (settled) return
762
+ settled = true
763
+ clearTimeout(timer)
764
+ cleanupAbort()
765
+ reject(new Error('ssh stream error: ' + ((e && e.message) || e)))
766
+ })
767
+ if (stdinWriter) {
768
+ try { stdinWriter(stream) } catch {}
769
+ }
770
+ })
771
+ }
772
+ runOn(client)
773
+ }),
774
+ )
775
+ }
776
+
777
+ /**
778
+ * Open an INTERACTIVE shell channel on the remote host (PTY-backed).
779
+ *
780
+ * This is what an embedded terminal needs and what `exec` cannot provide:
781
+ * `exec` runs one command and closes, with no PTY and no stdin after the
782
+ * writer returns. A shell channel keeps the session alive across commands, so
783
+ * `vim`, `top`, `sudo` prompts and anything else that talks to a terminal
784
+ * works the way it does in an ssh session.
785
+ *
786
+ * The returned stream is ssh2's channel: write to it for keystrokes, listen
787
+ * for `data` for output, call `setWindow(rows, cols, height, width)` on
788
+ * resize, and `end()`/`close()` to hang up. Columns/rows are negotiated per
789
+ * channel, so two terminals on the same pooled connection stay independent.
790
+ *
791
+ * @param {{cols?: number, rows?: number, term?: string, pty?: boolean}} [opts]
792
+ * @returns {Promise<object>} the ssh2 Channel (interactive stream).
793
+ */
794
+ shell(opts = {}) {
795
+ const cols = Math.max(2, Math.min(Number(opts.cols) || 80, 1000))
796
+ const rows = Math.max(2, Math.min(Number(opts.rows) || 24, 1000))
797
+ const term = String(opts.term || 'xterm-256color')
798
+ return this.connect().then(
799
+ (client) =>
800
+ new Promise((resolve, reject) => {
801
+ let retried = false
802
+ const runOn = (c) => {
803
+ const wndopts = { cols, rows, height: 0, width: 0, term }
804
+ // A shell on a Windows remote is a cmd/PowerShell via the default
805
+ // sshd shell; the PTY request is identical either way.
806
+ c.shell(wndopts, opts.pty === false ? {} : { pty: wndopts }, (err, stream) => {
807
+ if (err) {
808
+ // Same stale-connection recovery as exec/sftp: a session
809
+ // termination means the pooled client died server-side.
810
+ if (!retried && /channel open failure|open failed|session termination|disconnect/i.test(String((err && err.message) || err))) {
811
+ retried = true
812
+ this.invalidate()
813
+ return this.connect().then(
814
+ (fresh) => runOn(fresh),
815
+ (e2) => reject(new Error('ssh shell failed (reconnect): ' + ((e2 && e2.message) || e2))),
816
+ )
817
+ }
818
+ return reject(new Error('ssh shell failed: ' + ((err && err.message) || err)))
819
+ }
820
+ // An idle shell must not be killed by the connection's own idle
821
+ // handling: keepalive is already on, and the channel lives until
822
+ // the client calls end(). Nothing to schedule here.
823
+ resolve(stream)
824
+ })
825
+ }
826
+ runOn(client)
827
+ }),
828
+ )
829
+ }
830
+
831
+ /**
832
+ * Resolve the shared promisified SFTP client for the CURRENT connection.
833
+ * Keeping one channel per client/epoch avoids leaking a channel per tool call
834
+ * into sshd's MaxSessions limit (issue #121).
835
+ */
836
+ sftp() { return this._sftp(false) }
837
+
838
+ _sftp(isRetry) {
839
+ const staleClient = this._sftpClient && this.client && this._sftpClient !== this.client
840
+ if (this._sftpSession && (this._sftpEpoch !== this.epoch || staleClient)) this._dropSftpSession()
841
+ if (this._sftpSession) return this._sftpSession
842
+
843
+ const epoch = this.epoch
844
+ const connected = isRetry
845
+ ? this.connect().catch((e) => { throw new Error('ssh sftp failed (reconnect): ' + ((e && e.message) || e)) })
846
+ : this.connect()
847
+ const session = connected.then(
848
+ (client) =>
849
+ new Promise((resolve, reject) => {
850
+ // Bound the subchannel open itself, per attempt. Without this, a
851
+ // remote whose sftp subsystem is unresponsive (overloaded sshd,
852
+ // exceeded MaxSessions, half-open TCP) leaves `client.sftp(cb)` parked
853
+ // forever with no callback — issue #44 point 3.
854
+ let timedOut = false
855
+ const attemptTimer = setTimeout(() => {
856
+ timedOut = true
857
+ reject(new Error(`ssh sftp open timed out after ${this.config.commandTimeoutMs}ms`))
858
+ }, this.config.commandTimeoutMs)
859
+ // ★ 这里**不能 unref**。
860
+ //
861
+ // 这个定时器是"本次 await 的 sftp 打开"的**唯一结算者**:要么它超时 reject,
862
+ // 要么 ssh2 回调 resolve。若把它 unref,而进程此刻没有别的 pending 句柄,
863
+ // Node 会认为无事可做而**直接退出**,调用方永远等不到结果。
864
+ // 实测症状:CI 上该用例之后的 4 个用例被标记 `cancelledByParent`
865
+ // (同文件子进程提前退出),而本地因运行器恰好持着句柄而侥幸通过。
866
+ // 注意与上面 exec() 的超时定时器保持一致 —— 那个本来就没有 unref。
867
+ const clearAttempt = () => { clearTimeout(attemptTimer) }
868
+ try {
869
+ client.sftp((err, sftp) => {
870
+ clearAttempt()
871
+ // A late success after the watchdog rejected still owns a real
872
+ // channel. Close it, and never adopt it into the cache.
873
+ if (timedOut) {
874
+ if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
875
+ return
876
+ }
877
+ const wrongClient = this.client && this.client !== client
878
+ if (this.epoch !== epoch || this._sftpSession !== session || wrongClient) {
879
+ if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
880
+ return reject(new Error('ssh target changed while opening sftp'))
881
+ }
882
+ if (err) {
883
+ // Same dead-connection recovery as before: retry ONCE on a fresh
884
+ // connection. The new session has its own epoch and is adopted by
885
+ // callers of this promise; isRetry prevents recursive reconnects.
886
+ if (!isRetry && /channel open failure|open failed|unexpected sftp session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
887
+ this.invalidate()
888
+ return resolve(this._sftp(true))
889
+ }
890
+ return reject(new Error('ssh sftp failed: ' + ((err && err.message) || err)))
891
+ }
892
+
893
+ const drop = () => {
894
+ if (this._sftpSession === session) {
895
+ this._sftpSession = null
896
+ this._sftpEpoch = -1
897
+ }
898
+ if (this._sftpRaw === sftp) {
899
+ this._sftpRaw = null
900
+ this._sftpClient = null
901
+ }
902
+ }
903
+ if (typeof sftp.on === 'function') {
904
+ sftp.on('end', drop)
905
+ sftp.on('close', drop)
906
+ sftp.on('error', drop)
907
+ }
908
+ this._sftpRaw = sftp
909
+ this._sftpClient = client
910
+ // A successful open proves the connection healthy: reset the
911
+ // consecutive-timeout strike counter (issue #65).
912
+ this._sftpTimeouts = 0
913
+ try {
914
+ resolve(buildSftpSurface(sftp, {
915
+ commandTimeoutMs: this.config.commandTimeoutMs,
916
+ onTimeout: () => {
917
+ // A timed-out channel is dead: close AND forget it so the
918
+ // next call reopens instead of returning a dead surface.
919
+ try { sftp.end() } catch { /* already gone */ }
920
+ drop()
921
+ this._noteSftpTimeout()
922
+ },
923
+ }))
924
+ } catch (e) {
925
+ drop()
926
+ try { sftp.end() } catch { /* already gone */ }
927
+ reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
928
+ }
929
+ })
930
+ } catch (e) {
931
+ clearAttempt()
932
+ reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
933
+ }
934
+ }),
935
+ )
936
+ // Never cache a rejected open: the next call must retry rather than get the
937
+ // same error back forever. Raw fields are only set after a successful open.
938
+ session.catch(() => {
939
+ if (this._sftpSession === session) {
940
+ this._sftpSession = null
941
+ this._sftpEpoch = -1
942
+ this._sftpClient = null
943
+ }
944
+ })
945
+ this._sftpSession = session
946
+ this._sftpEpoch = epoch
947
+ return session
948
+ }
949
+
950
+ /**
951
+ * Count a timed-out SFTP subchannel open. A second consecutive timeout means
952
+ * the pooled connection itself is wedged (issue #65): tear it down so the
953
+ * next sftp() call re-handshakes instead of queueing behind the dead one.
954
+ */
955
+ _noteSftpTimeout() {
956
+ this._sftpTimeouts = (this._sftpTimeouts || 0) + 1
957
+ if (this._sftpTimeouts >= 2) this.invalidate()
958
+ }
959
+
960
+ _dropSftpSession() {
961
+ const session = this._sftpSession
962
+ const raw = this._sftpRaw
963
+ this._sftpSession = null
964
+ this._sftpRaw = null
965
+ this._sftpClient = null
966
+ this._sftpEpoch = -1
967
+ if (raw) { try { raw.end() } catch { /* already gone */ } }
968
+ // Swallow the rejection: nobody awaits a session we are tearing down.
969
+ if (session && typeof session.catch === 'function') session.catch(() => {})
970
+ }
971
+
972
+ /**
973
+ * Drop the cached client and force a fresh connection on the next call.
974
+ * Called when a channel open fails (e.g. "Channel open failure: open
975
+ * failed") — the pooled SSH connection is usually dead server-side while
976
+ * keepalive has not yet noticed, and reusing it keeps failing. The epoch
977
+ * bump orphans any in-flight connect; the client is ended so ssh2 frees
978
+ * its sockets.
979
+ */
980
+ invalidate() {
981
+ this.epoch++
982
+ const client = this.client
983
+ this.client = null
984
+ this._dropSftpSession()
985
+ const pending = this.connecting
986
+ this.connecting = null
987
+ if (pending && typeof pending.catch === 'function') {
988
+ try { pending.catch(() => {}) } catch {}
989
+ }
990
+ if (this.proxyPool) {
991
+ try { this.proxyPool.close() } catch {}
992
+ this.proxyPool = null
993
+ }
994
+ if (client) {
995
+ try { client.end() } catch {}
996
+ }
997
+ // Same teardown as close(): the forwards manager must detach from the
998
+ // dying client, or its stale `close -> stopAll()` listener later tears
999
+ // down forwards that were re-attached to the NEW client (onReady does
1000
+ // the re-attach on the next successful connect).
1001
+ if (this.onCloseHook) {
1002
+ try { this.onCloseHook() } catch {}
1003
+ }
1004
+ }
1005
+
1006
+ close() {
1007
+ this.epoch++
1008
+ const client = this.client
1009
+ this.client = null
1010
+ this._dropSftpSession()
1011
+ const pending = this.connecting
1012
+ this.connecting = null
1013
+ if (pending && typeof pending.catch === 'function') {
1014
+ try { pending.catch(() => {}) } catch {}
1015
+ }
1016
+ if (this.proxyPool) {
1017
+ try { this.proxyPool.close() } catch {}
1018
+ this.proxyPool = null
1019
+ }
1020
+ if (client) {
1021
+ try {
1022
+ client.end()
1023
+ } catch {}
1024
+ }
1025
+ if (this.onCloseHook) {
1026
+ try { this.onCloseHook() } catch {}
1027
+ }
1028
+ }
1029
+ }