@linxin666/dsh-ssh 0.4.19 → 0.4.21

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 (47) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +13 -2
  3. package/README.zh.md +13 -2
  4. package/lib/client.js +726 -109
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +1074 -352
  7. package/lib/types/client/api.d.ts +8 -4
  8. package/lib/types/client/locales.d.ts +27 -1
  9. package/lib/types/client/panel/HostFormDialog.d.ts +3 -3
  10. package/lib/types/client/panel/HostsTab.d.ts +3 -3
  11. package/lib/types/client/panel/KeysTab.d.ts +8 -0
  12. package/lib/types/client/panel/controller.d.ts +1 -1
  13. package/lib/types/connection-trust.d.ts +26 -0
  14. package/lib/types/engine/cluster.d.ts +7 -2
  15. package/lib/types/engine/connection-pool.d.ts +11 -2
  16. package/lib/types/engine/sftp.d.ts +5 -0
  17. package/lib/types/engine/terminal-sessions.d.ts +5 -3
  18. package/lib/types/index.d.ts +6 -5
  19. package/lib/types/protocol.d.ts +41 -0
  20. package/lib/types/routes.d.ts +3 -0
  21. package/lib/types/service.d.ts +148 -0
  22. package/lib/types/store.d.ts +16 -4
  23. package/package.json +1 -1
  24. package/src/client/api.ts +147 -58
  25. package/src/client/locales.ts +55 -2
  26. package/src/client/panel/HostFormDialog.tsx +76 -17
  27. package/src/client/panel/HostsTab.tsx +50 -25
  28. package/src/client/panel/KeysTab.tsx +192 -0
  29. package/src/client/panel/SshPanel.tsx +4 -1
  30. package/src/client/panel/TerminalTab.tsx +14 -9
  31. package/src/client/panel/TunnelsTab.tsx +24 -7
  32. package/src/client/panel/controller.ts +77 -12
  33. package/src/client/panel/helpers.ts +3 -2
  34. package/src/connection-trust.ts +70 -0
  35. package/src/engine/cluster.ts +45 -13
  36. package/src/engine/connection-pool.ts +279 -96
  37. package/src/engine/proxy-command.ts +27 -10
  38. package/src/engine/sftp.ts +69 -35
  39. package/src/engine/terminal-sessions.ts +110 -35
  40. package/src/engine/tunnel.ts +20 -2
  41. package/src/engine.ts +5 -8
  42. package/src/index.ts +113 -39
  43. package/src/protocol.ts +45 -0
  44. package/src/routes.ts +130 -23
  45. package/src/service.ts +158 -0
  46. package/src/store.ts +324 -104
  47. package/src/tools.ts +3 -5
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { existsSync, readFileSync } from 'node:fs'
7
7
  import type { Duplex } from 'node:stream'
8
+ import { StringDecoder } from 'node:string_decoder'
8
9
  import { Client, type ConnectConfig } from 'ssh2'
9
10
  import type { ExecResult, SshHostEntry } from '../protocol.ts'
10
11
  import { expandHome, normalizeAgentPath, type HostStore } from '../store.ts'
@@ -216,14 +217,21 @@ export function connectClient(config: ConnectConfig, onKeyboardInteractive?: Key
216
217
  const cause = error instanceof Error ? error : new Error(String(error))
217
218
  reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause)
218
219
  }
220
+ const onPreReadyClose = (): void => {
221
+ fail(new Error('SSH connection closed before ready'))
222
+ }
219
223
  client.once('handshake', () => {
220
224
  handshakeComplete = true
221
225
  })
222
226
  client.once('ready', () => {
223
227
  if (settled) return
224
228
  settled = true
229
+ client.removeListener?.('close', onPreReadyClose)
225
230
  resolve(client)
226
231
  })
232
+ // ssh2 clears readyTimeout and emits only 'close' (no 'error') when the peer
233
+ // closes cleanly after sending the SSH banner; settle instead of hanging forever.
234
+ client.once('close', onPreReadyClose)
227
235
  client.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {
228
236
  if (onKeyboardInteractive !== undefined) {
229
237
  onKeyboardInteractive(name, instructions, instructionsLang, prompts.map(p => ({ prompt: p.prompt, echo: Boolean(p.echo) })), finish)
@@ -250,18 +258,43 @@ export function connectClient(config: ConnectConfig, onKeyboardInteractive?: Key
250
258
  })
251
259
  }
252
260
 
253
- /** Cap captured output at the configured byte budget (marks truncation). */
254
- export function appendOutput(target: { text: string; truncated: boolean }, chunk: Buffer, maxBytes: number): void {
255
- if (target.truncated) return
256
- if (target.text.length + chunk.length > maxBytes) {
257
- let cut = chunk.toString('utf8').slice(0, maxBytes - target.text.length)
258
- // Never split a surrogate pair at the cut boundary.
259
- if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1)
261
+ /** Truncate `text` so its UTF-8 encoding fits within `maxBytes` without splitting code points. */
262
+ function sliceUtf8ToBytes(text: string, maxBytes: number): string {
263
+ if (maxBytes <= 0 || text === '') return ''
264
+ if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text
265
+ let bytes = 0
266
+ let end = 0
267
+ for (const char of text) {
268
+ const code = char.codePointAt(0)!
269
+ const charBytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
270
+ if (bytes + charBytes > maxBytes) break
271
+ bytes += charBytes
272
+ end += char.length
273
+ }
274
+ return text.slice(0, end)
275
+ }
276
+
277
+ /** Append an already-decoded string chunk under a UTF-8 byte budget. */
278
+ function appendDecodedOutput(target: { text: string; truncated: boolean; bytes?: number }, decoded: string, maxBytes: number): void {
279
+ if (target.truncated || decoded === '') return
280
+ const usedBytes = target.bytes ?? Buffer.byteLength(target.text, 'utf8')
281
+ const decodedBytes = Buffer.byteLength(decoded, 'utf8')
282
+ if (usedBytes + decodedBytes > maxBytes) {
283
+ const cut = sliceUtf8ToBytes(decoded, maxBytes - usedBytes)
260
284
  target.text += cut + '…[output truncated]'
285
+ target.bytes = maxBytes
261
286
  target.truncated = true
262
287
  return
263
288
  }
264
- target.text += chunk.toString('utf8')
289
+ target.text += decoded
290
+ target.bytes = usedBytes + decodedBytes
291
+ }
292
+
293
+ /** Cap captured output at the configured UTF-8 byte budget (marks truncation). */
294
+ export function appendOutput(target: { text: string; truncated: boolean; bytes?: number }, chunk: Buffer, maxBytes: number, decoder?: StringDecoder): void {
295
+ if (target.truncated) return
296
+ const decoded = decoder !== undefined ? decoder.write(chunk) : chunk.toString('utf8')
297
+ appendDecodedOutput(target, decoded, maxBytes)
265
298
  }
266
299
 
267
300
  /** The ProxyCommand token source for one entry. */
@@ -431,8 +464,43 @@ export async function connectChain(
431
464
  }
432
465
  }
433
466
 
467
+ interface PoolLifecycle {
468
+ disposed: boolean
469
+ generations: Map<string, number>
470
+ }
471
+
472
+ const poolLifecycles = new WeakMap<PoolEngine, PoolLifecycle>()
473
+
474
+ function lifecycleOf(engine: PoolEngine): PoolLifecycle {
475
+ let state = poolLifecycles.get(engine)
476
+ if (state === undefined) {
477
+ state = { disposed: false, generations: new Map() }
478
+ poolLifecycles.set(engine, state)
479
+ }
480
+ return state
481
+ }
482
+
483
+ /**
484
+ * Invalidate any in-flight acquire for `alias` so a connection still handshaking
485
+ * under stale config or before a delete cannot enter `engine.pool` after completion.
486
+ */
487
+ export function invalidateAlias(engine: PoolEngine, alias: string): void {
488
+ const state = lifecycleOf(engine)
489
+ state.generations.set(alias, (state.generations.get(alias) ?? 0) + 1)
490
+ engine.acquireQueue.delete(alias)
491
+ }
492
+
493
+ /** Mark the pool disposed so in-flight acquires tear down instead of entering the pool. */
494
+ export function markPoolDisposed(engine: PoolEngine): void {
495
+ const state = lifecycleOf(engine)
496
+ state.disposed = true
497
+ engine.acquireQueue.clear()
498
+ }
499
+
434
500
  /** Connect (or reuse) the pooled chain for one alias; pins nothing. */
435
501
  export async function acquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
502
+ const state = lifecycleOf(engine)
503
+ if (state.disposed) throw new Error('ssh engine has been disposed')
436
504
  const pending = engine.acquireQueue.get(alias)
437
505
  if (pending !== undefined) return pending
438
506
  const task = doAcquire(engine, alias)
@@ -445,12 +513,32 @@ export async function acquire(engine: PoolEngine, alias: string): Promise<PoolRe
445
513
  }
446
514
 
447
515
  async function doAcquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
516
+ const state = lifecycleOf(engine)
517
+ if (state.disposed) throw new Error('ssh engine has been disposed')
518
+ const gen = state.generations.get(alias) ?? 0
448
519
  const entry = engine.store.find(alias)
449
520
  if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
450
521
  const { client, hops } = await connectChain(engine, entry)
451
522
  const record: PoolRecord = { client, hops, idleAt: Date.now(), pinned: false, broken: false, inFlight: 0 }
452
- client.on('error', () => { record.broken = true })
453
- client.on('close', () => { record.broken = true })
523
+ if (state.disposed || (state.generations.get(alias) ?? 0) !== gen) {
524
+ endRecordChain(record)
525
+ throw new Error(state.disposed
526
+ ? 'ssh engine disposed while connecting \'' + alias + '\''
527
+ : 'host \'' + alias + '\' configuration changed while connecting')
528
+ }
529
+ const markBroken = (): void => { record.broken = true }
530
+ const onTargetClosed = (): void => {
531
+ record.broken = true
532
+ for (const hop of record.hops) {
533
+ try { hop.end() } catch { /* already closed */ }
534
+ }
535
+ }
536
+ client.on('error', markBroken)
537
+ client.on('close', onTargetClosed)
538
+ for (const hop of hops) {
539
+ hop.on('error', markBroken)
540
+ hop.on('close', markBroken)
541
+ }
454
542
  engine.pool.set(alias, record)
455
543
  return record
456
544
  }
@@ -486,6 +574,37 @@ export function sweepPool(engine: PoolEngine): void {
486
574
  }
487
575
  }
488
576
 
577
+ /** Read live abort state through a function call so TypeScript does not narrow across `await`. */
578
+ function isAborted(signal?: AbortSignal): boolean {
579
+ return signal?.aborted === true
580
+ }
581
+
582
+ /** Race an in-flight promise against an optional AbortSignal without leaving an unhandled rejection behind. */
583
+ function waitWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
584
+ if (signal === undefined) return promise
585
+ if (signal.aborted) {
586
+ promise.catch(() => undefined)
587
+ return Promise.reject(new Error('command cancelled by the caller'))
588
+ }
589
+ return new Promise<T>((resolve, reject) => {
590
+ const onAbort = (): void => {
591
+ promise.catch(() => undefined)
592
+ reject(new Error('command cancelled by the caller'))
593
+ }
594
+ signal.addEventListener('abort', onAbort, { once: true })
595
+ promise.then(
596
+ (value) => {
597
+ signal.removeEventListener('abort', onAbort)
598
+ resolve(value)
599
+ },
600
+ (error) => {
601
+ signal.removeEventListener('abort', onAbort)
602
+ reject(error)
603
+ },
604
+ )
605
+ })
606
+ }
607
+
489
608
  /**
490
609
  * Run `fn` with a live client for `alias`, reconnecting (up to the
491
610
  * attempt budget) when the connection broke mid-flight.
@@ -493,10 +612,13 @@ export function sweepPool(engine: PoolEngine): void {
493
612
  export async function withClient<T>(engine: PoolEngine, alias: string, fn: (client: Client) => Promise<T>, attempts = 3, signal?: AbortSignal): Promise<T> {
494
613
  let lastError: unknown
495
614
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
615
+ if (isAborted(signal)) {
616
+ throw new Error('command cancelled by the caller')
617
+ }
496
618
  let record = engine.pool.get(alias)
497
619
  if (record === undefined || record.broken) {
498
620
  if (record !== undefined) disposeRecord(engine, alias, record)
499
- record = await acquire(engine, alias)
621
+ record = await waitWithSignal(acquire(engine, alias), signal)
500
622
  }
501
623
  record.idleAt = Date.now()
502
624
  record.inFlight += 1
@@ -508,7 +630,7 @@ export async function withClient<T>(engine: PoolEngine, alias: string, fn: (clie
508
630
  lastError = error
509
631
  // A cancelled call is never replayed: the caller asked for it to stop,
510
632
  // and a retry would re-run a command that may not be idempotent.
511
- if (signal?.aborted === true) throw error
633
+ if (isAborted(signal)) throw error
512
634
  // Retry only when the connection actually broke mid-flight: drop the
513
635
  // corpse and let the next attempt reconnect (a reconnect may replay a
514
636
  // non-idempotent command — the documented trade-off). A failure on a
@@ -525,36 +647,39 @@ export async function withClient<T>(engine: PoolEngine, alias: string, fn: (clie
525
647
  /** Run one command on `alias` (reusing the pooled connection). */
526
648
  export async function execCommand(engine: PoolEngine, alias: string, command: string, timeoutMs?: number, signal?: AbortSignal): Promise<ExecResult> {
527
649
  const started = Date.now()
650
+ if (isAborted(signal)) {
651
+ return {
652
+ success: false,
653
+ exitCode: null,
654
+ timedOut: false,
655
+ stdout: '',
656
+ stderr: '',
657
+ durationMs: Date.now() - started,
658
+ error: 'command cancelled by the caller',
659
+ }
660
+ }
528
661
  const budget = timeoutMs !== undefined && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs
529
- return withClient(engine, alias, async (client) => {
530
- return await new Promise<ExecResult>((resolve, reject) => {
531
- // Caller cancellation is cooperative and quiescent: aborting closes the
532
- // remote channel and settles this call like a timeout does, so the
533
- // command stops without the pool replaying it. The channel is captured
534
- // in a mutable slot because abort may fire before client.exec calls back.
535
- let aborted = signal !== undefined && signal.aborted
536
- let kill = (): void => { /* channel not open yet */ }
537
- const onAbort = (): void => {
538
- aborted = true
539
- kill()
540
- }
541
- if (signal !== undefined && !signal.aborted) signal.addEventListener('abort', onAbort, { once: true })
542
- client.exec(command, (error, stream) => {
543
- if (error !== undefined) {
544
- signal?.removeEventListener('abort', onAbort)
545
- reject(error)
546
- return
547
- }
548
- kill = (): void => {
549
- try { stream.signal('KILL') } catch { /* channel gone */ }
550
- try { stream.close() } catch { /* channel gone */ }
551
- }
552
- // The abort may already have arrived while this channel opened.
553
- if (aborted) kill()
554
- const stdout = { text: '', truncated: false }
555
- const stderr = { text: '', truncated: false }
556
- let timedOut = false
662
+ try {
663
+ return await withClient(engine, alias, async (client) => {
664
+ return await new Promise<ExecResult>((resolve, reject) => {
665
+ // Caller cancellation is cooperative and quiescent: aborting closes the
666
+ // remote channel and settles this call like a timeout does, so the
667
+ // command stops without the pool replaying it. The channel is captured
668
+ // in a mutable slot because abort may fire before client.exec calls back.
669
+ let aborted = signal !== undefined && signal.aborted
557
670
  let settled = false
671
+ const stdout = { text: '', truncated: false, bytes: 0 }
672
+ const stderr = { text: '', truncated: false, bytes: 0 }
673
+ const stdoutDecoder = new StringDecoder('utf8')
674
+ const stderrDecoder = new StringDecoder('utf8')
675
+ const flushDecoders = (): void => {
676
+ const outTail = stdoutDecoder.end()
677
+ if (outTail !== '') appendDecodedOutput(stdout, outTail, engine.opts.maxOutputBytes)
678
+ const errTail = stderrDecoder.end()
679
+ if (errTail !== '') appendDecodedOutput(stderr, errTail, engine.opts.maxOutputBytes)
680
+ }
681
+ let timer: ReturnType<typeof setTimeout> | undefined
682
+ let kill = (): void => { /* channel not open yet */ }
558
683
  /** One cancelled outcome: the remote channel was killed on caller request. */
559
684
  const cancelledResult = (): ExecResult => ({
560
685
  success: false,
@@ -565,71 +690,129 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
565
690
  durationMs: Date.now() - started,
566
691
  error: 'command cancelled by the caller',
567
692
  })
568
- const finish = (): void => {
693
+ const settleCancelled = (): void => {
569
694
  if (settled) return
570
695
  settled = true
571
- clearTimeout(timer)
696
+ if (timer !== undefined) clearTimeout(timer)
572
697
  signal?.removeEventListener('abort', onAbort)
573
- resolve({
574
- success: false,
575
- exitCode: null,
576
- timedOut,
577
- stdout: stdout.text,
578
- stderr: stderr.text,
579
- durationMs: Date.now() - started,
580
- error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
581
- })
698
+ flushDecoders()
699
+ resolve(cancelledResult())
582
700
  }
583
- const timer = setTimeout(() => {
584
- timedOut = true
585
- try { stream.signal('KILL') } catch { /* channel gone */ }
586
- try { stream.close() } catch { /* channel gone */ }
587
- // Hard deadline: settle now even if the peer never acks the
588
- // channel close (the stream 'close' handler is then a no-op).
589
- finish()
590
- }, budget)
591
- stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
592
- stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
593
- stream.on('close', (code: number | null) => {
594
- if (settled) return
595
- settled = true
596
- clearTimeout(timer)
597
- signal?.removeEventListener('abort', onAbort)
598
- // A caller cancellation settles as cancelled, never as a broken
599
- // connection: the latter would send withClient into a retry that
600
- // re-runs a command the caller asked to stop.
601
- if (aborted) {
602
- resolve(cancelledResult())
701
+ const onAbort = (): void => {
702
+ aborted = true
703
+ kill()
704
+ // Hard cancellation deadline: settle immediately even if the peer is
705
+ // half-open and never acks the channel close, matching timeout behavior.
706
+ settleCancelled()
707
+ }
708
+ if (aborted) {
709
+ settleCancelled()
710
+ return
711
+ }
712
+ if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
713
+ client.exec(command, (error, stream) => {
714
+ if (error !== undefined) {
715
+ signal?.removeEventListener('abort', onAbort)
716
+ if (aborted) {
717
+ settleCancelled()
718
+ return
719
+ }
720
+ reject(error)
603
721
  return
604
722
  }
605
- if (typeof code !== 'number' && !timedOut) {
606
- // The channel closed without an exit status: the connection
607
- // dropped mid-flight. Reject so withClient can reconnect and
608
- // retry within the attempt budget.
609
- reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
610
- return
723
+ kill = (): void => {
724
+ try { stream.signal('KILL') } catch { /* channel gone */ }
725
+ try { stream.close() } catch { /* channel gone */ }
611
726
  }
612
- resolve({
613
- success: code === 0,
614
- exitCode: code,
615
- timedOut,
616
- stdout: stdout.text,
617
- stderr: stderr.text,
618
- durationMs: Date.now() - started,
619
- })
620
- })
621
- stream.on('error', (streamError: Error) => {
622
- if (settled) return
623
- settled = true
624
- clearTimeout(timer)
625
- signal?.removeEventListener('abort', onAbort)
727
+ // The abort may already have arrived while this channel opened.
626
728
  if (aborted) {
627
- resolve(cancelledResult())
729
+ kill()
730
+ settleCancelled()
628
731
  return
629
732
  }
630
- reject(streamError)
733
+ let timedOut = false
734
+ const finish = (): void => {
735
+ if (settled) return
736
+ settled = true
737
+ if (timer !== undefined) clearTimeout(timer)
738
+ signal?.removeEventListener('abort', onAbort)
739
+ flushDecoders()
740
+ resolve({
741
+ success: false,
742
+ exitCode: null,
743
+ timedOut,
744
+ stdout: stdout.text,
745
+ stderr: stderr.text,
746
+ durationMs: Date.now() - started,
747
+ error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
748
+ })
749
+ }
750
+ timer = setTimeout(() => {
751
+ timedOut = true
752
+ try { stream.signal('KILL') } catch { /* channel gone */ }
753
+ try { stream.close() } catch { /* channel gone */ }
754
+ // Hard deadline: settle now even if the peer never acks the
755
+ // channel close (the stream 'close' handler is then a no-op).
756
+ finish()
757
+ }, budget)
758
+ stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes, stdoutDecoder))
759
+ stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes, stderrDecoder))
760
+ stream.on('close', (code: number | null) => {
761
+ if (settled) return
762
+ settled = true
763
+ if (timer !== undefined) clearTimeout(timer)
764
+ signal?.removeEventListener('abort', onAbort)
765
+ flushDecoders()
766
+ // A caller cancellation settles as cancelled, never as a broken
767
+ // connection: the latter would send withClient into a retry that
768
+ // re-runs a command the caller asked to stop.
769
+ if (aborted) {
770
+ resolve(cancelledResult())
771
+ return
772
+ }
773
+ if (typeof code !== 'number' && !timedOut) {
774
+ // The channel closed without an exit status: the connection
775
+ // dropped mid-flight. Reject so withClient can reconnect and
776
+ // retry within the attempt budget.
777
+ reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
778
+ return
779
+ }
780
+ resolve({
781
+ success: code === 0,
782
+ exitCode: code,
783
+ timedOut,
784
+ stdout: stdout.text,
785
+ stderr: stderr.text,
786
+ durationMs: Date.now() - started,
787
+ })
788
+ })
789
+ stream.on('error', (streamError: Error) => {
790
+ if (settled) return
791
+ settled = true
792
+ if (timer !== undefined) clearTimeout(timer)
793
+ signal?.removeEventListener('abort', onAbort)
794
+ flushDecoders()
795
+ if (aborted) {
796
+ resolve(cancelledResult())
797
+ return
798
+ }
799
+ reject(streamError)
800
+ })
631
801
  })
632
802
  })
633
- })
634
- })
635
- }
803
+ }, undefined, signal)
804
+ } catch (error) {
805
+ if (isAborted(signal)) {
806
+ return {
807
+ success: false,
808
+ exitCode: null,
809
+ timedOut: false,
810
+ stdout: '',
811
+ stderr: '',
812
+ durationMs: Date.now() - started,
813
+ error: 'command cancelled by the caller',
814
+ }
815
+ }
816
+ throw error
817
+ }
818
+ }
@@ -96,8 +96,15 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
96
96
  })
97
97
 
98
98
  let killed = false
99
+ let exited = false
100
+ let escalateTimer: ReturnType<typeof setTimeout> | undefined
101
+ const clearEscalate = (): void => {
102
+ if (escalateTimer === undefined) return
103
+ clearTimeout(escalateTimer)
104
+ escalateTimer = undefined
105
+ }
99
106
  const kill = (): void => {
100
- if (killed) return
107
+ if (killed || exited || child.exitCode !== null || child.signalCode !== null) return
101
108
  killed = true
102
109
  const pid = child.pid
103
110
  const group = process.platform !== 'win32' && pid !== undefined
@@ -105,13 +112,15 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
105
112
  if (group) process.kill(-pid, 'SIGTERM')
106
113
  else child.kill()
107
114
  } catch { /* already gone */ }
108
- const escalate = setTimeout(() => {
115
+ escalateTimer = setTimeout(() => {
116
+ escalateTimer = undefined
117
+ if (exited || child.exitCode !== null || child.signalCode !== null) return
109
118
  try {
110
119
  if (group) process.kill(-pid, 'SIGKILL')
111
120
  else child.kill('SIGKILL')
112
121
  } catch { /* already gone */ }
113
122
  }, KILL_GRACE_MS)
114
- escalate.unref()
123
+ escalateTimer.unref()
115
124
  }
116
125
 
117
126
  function formatExitError(code: number | null, signal: NodeJS.Signals | null, stderrDetail: string): Error {
@@ -199,7 +208,6 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
199
208
  // instead of the generic "connection lost before handshake" ssh2 produces
200
209
  // for a socket that simply closed.
201
210
  let stdoutEnded = false
202
- let exited = false
203
211
  const finishIfClean = (): void => {
204
212
  if (exited && stdoutEnded && !failed && !stream.destroyed) stream.push(null)
205
213
  }
@@ -214,6 +222,7 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
214
222
  child.stdout?.on('error', (error: Error) => {
215
223
  fail(new Error('ProxyCommand stdout error: ' + error.message))
216
224
  })
225
+ let stdinErrorPending = false
217
226
  child.stdin?.on('error', (error: Error) => {
218
227
  // A broken pipe (EPIPE) on stdin occurs naturally when the proxy command
219
228
  // exits early or closes its standard input. Prevent unhandled EventEmitter errors.
@@ -221,22 +230,30 @@ export function startProxyCommand(rawCommand: string, target: ProxyTarget): Prox
221
230
  fail(formatExitError(child.exitCode, child.signalCode, stderr))
222
231
  return
223
232
  }
224
- const timer = setTimeout(() => {
225
- fail(new Error('ProxyCommand transport error: ' + error.message))
226
- }, 200)
227
- timer.unref()
228
- child.once('exit', (code, signal) => {
233
+ if (exited || child.exitCode !== null || stdinErrorPending || failed || stream.destroyed) return
234
+ stdinErrorPending = true
235
+ const onExit = (code: number | null, signal: NodeJS.Signals | null): void => {
236
+ stdinErrorPending = false
229
237
  clearTimeout(timer)
230
238
  if ((code !== null && code !== 0) || signal !== null) {
231
239
  fail(formatExitError(code, signal, stderr))
232
240
  }
233
- })
241
+ }
242
+ const timer = setTimeout(() => {
243
+ stdinErrorPending = false
244
+ child.removeListener('exit', onExit)
245
+ fail(new Error('ProxyCommand transport error: ' + error.message))
246
+ }, 200)
247
+ timer.unref()
248
+ child.once('exit', onExit)
234
249
  })
235
250
  child.on('error', (error: Error) => {
251
+ clearEscalate()
236
252
  fail(new Error('ProxyCommand could not start: ' + error.message))
237
253
  })
238
254
  child.on('exit', (code, signal) => {
239
255
  exited = true
256
+ clearEscalate()
240
257
  if ((code !== null && code !== 0) || signal !== null) {
241
258
  fail(formatExitError(code, signal, stderr))
242
259
  return