dsh-remote-vs 0.28.0 → 0.29.0

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.
package/src/pool.ts CHANGED
@@ -9,10 +9,12 @@
9
9
  import { createHash } from 'node:crypto'
10
10
  import { readFileSync } from 'node:fs'
11
11
  import { StringDecoder } from 'node:string_decoder'
12
+ import type { Duplex } from 'node:stream'
12
13
  import { Client, type ClientChannel, type SFTPWrapper } from 'ssh2'
13
- import type { RemoteStore } from './store.ts'
14
+ import type { RemoteStore, ResolvedProxy } from './store.ts'
15
+ import { openProxySocket, ProxyError, type ProxyConfig, type ProxyFailure } from './proxy.ts'
14
16
  import { DeadlineError } from './timeouts.ts'
15
- import type { RemoteConnectionStatus, RemoteExecResult, RemoteHostEntry } from './protocol.ts'
17
+ import type { EgressInfo, RemoteConnectionStatus, RemoteExecResult, RemoteHostEntry } from './protocol.ts'
16
18
 
17
19
  /**
18
20
  * The budget-out type lives in `timeouts.ts` (both halves need it); re-exported
@@ -23,6 +25,35 @@ export { DeadlineError }
23
25
  /** Idle time after which a pooled connection is closed. */
24
26
  const IDLE_MS = 30 * 60 * 1000
25
27
 
28
+ /**
29
+ * How long a port forward waits for its DEDICATED connection before falling back.
30
+ *
31
+ * The dedicated connection is an optimization, so it must never become the reason
32
+ * a local socket waits: a server that silently DROPS the extra connection (a very
33
+ * common `MaxStartups` symptom) would otherwise cost the whole connect watchdog
34
+ * (45s) per forward channel, with the user staring at a hanging page. Three
35
+ * seconds is plenty for a second handshake to a host that is already reachable
36
+ * (the shared connection is up by definition); past that, use the shared one and
37
+ * let the abandoned dial finish in the background.
38
+ *
39
+ * Override with DSH_REMOTE_VS_FORWARD_BUDGET_MS (milliseconds, >= 10) so the gate
40
+ * does not spend three seconds per case.
41
+ */
42
+ const FORWARD_DEDICATED_BUDGET_MS = (() => {
43
+ const raw = Number(process.env.DSH_REMOTE_VS_FORWARD_BUDGET_MS)
44
+ return Number.isFinite(raw) && raw >= 10 ? raw : 3_000
45
+ })()
46
+
47
+ /**
48
+ * How long a refused/timed-out dedicated forward connection is skipped per alias.
49
+ *
50
+ * A browser opens several forward channels per page; retrying the same refused
51
+ * handshake for every one of them is exactly the waiting we just removed. One
52
+ * minute covers the burst; `drop(alias)` (host edited/deleted) and a successful
53
+ * dedicated connection clear it immediately.
54
+ */
55
+ const FORWARD_DEDICATED_BLOCK_MS = 60_000
56
+
26
57
  /**
27
58
  * Connection establishment timeout, including authentication.
28
59
  *
@@ -138,6 +169,12 @@ interface Pooled {
138
169
  connecting: Promise<Client> | undefined
139
170
  /** Live users (channels/sessions); idle eviction only fires at zero. */
140
171
  held: number
172
+ /**
173
+ * The route THIS connection was opened through (set on a successful dial,
174
+ * cleared with the entry). It answers "is this really going through the jump
175
+ * host?" with evidence from the live link instead of the stored config.
176
+ */
177
+ egress?: EgressInfo
141
178
  }
142
179
 
143
180
  /**
@@ -263,6 +300,29 @@ export class RemotePool {
263
300
  * that refuses extra connections still gets a working terminal.
264
301
  */
265
302
  private readonly shellConns = new Map<string, Pooled>()
303
+ /**
304
+ * Dedicated connections for `ssh -L` port forwards (one per alias).
305
+ *
306
+ * The other half of the same argument: a forwarded channel carries arbitrary
307
+ * TCP (a database, an SSH tunnel, a whole browser page), so it is long-lived
308
+ * and can move a lot of data. Multiplexed onto the shared connection it would
309
+ * queue ahead of exec/SFTP channels (SSH has no per-channel priority), and a
310
+ * remote service that stalls would hold the window `git status` needs. A
311
+ * terminal already gets its own connection (`shellConns`); forward traffic gets
312
+ * its own for exactly the same reason.
313
+ *
314
+ * Cost: one extra handshake per alias that actually receives a forwarded
315
+ * connection, plus one held TCP connection while any of its forward channels is
316
+ * open (the 30-minute idle eviction applies once the last one closes).
317
+ * `forwardOut` falls back to the shared connection when this one cannot be
318
+ * established (e.g. the server refuses extra connections), so a forward never
319
+ * stops working because of it — it only loses the isolation.
320
+ */
321
+ private readonly forwardConns = new Map<string, Pooled>()
322
+ /** Aliases whose dedicated-forward downgrade was already logged (once per alias). */
323
+ private readonly forwardFallbackNoted = new Set<string>()
324
+ /** alias -> timestamp until which the dedicated forward connection is skipped. */
325
+ private readonly forwardBlocked = new Map<string, number>()
266
326
  /** TOFU fingerprints observed this process (alias -> sha256). */
267
327
  private readonly hostKeys = new Map<string, string>()
268
328
  /** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
@@ -284,16 +344,23 @@ export class RemotePool {
284
344
  // The host entry can change under an alias, so the capability answer goes
285
345
  // with the connection; the next exec probes again.
286
346
  this.setsidProbes.delete(alias)
287
- // Both connections belong to the host: an edit/removal must end both.
347
+ // All three connections belong to the host: an edit/removal must end all.
288
348
  // (A transient error on ONE of them uses `evictFrom` for that map only, so
289
- // a shared-connection blip does not take live terminals down with it.)
349
+ // a shared-connection blip does not take live terminals/forwards down with it.)
290
350
  this.evictFrom(this.conns, alias)
291
351
  this.evictFrom(this.shellConns, alias)
352
+ this.evictFrom(this.forwardConns, alias)
353
+ // Verdicts about the OLD connection do not survive the host: an edited host
354
+ // (now allowed, or with a new address) must be retried and may be reported.
355
+ this.forwardBlocked.delete(alias)
356
+ this.forwardFallbackNoted.delete(alias)
292
357
  }
293
358
 
294
359
  /** Close every pooled connection. */
295
360
  dispose(): void {
296
- for (const alias of new Set([...this.conns.keys(), ...this.shellConns.keys()])) this.drop(alias)
361
+ for (const alias of new Set([...this.conns.keys(), ...this.shellConns.keys(), ...this.forwardConns.keys()])) {
362
+ this.drop(alias)
363
+ }
297
364
  }
298
365
 
299
366
  /**
@@ -317,28 +384,74 @@ export class RemotePool {
317
384
  */
318
385
  status(): RemoteConnectionStatus[] {
319
386
  const aliases = new Set<string>([...this.conns.keys(), ...this.health.keys()])
387
+ /** The host rows, read ONCE for the whole answer (see `configuredEgress`). */
388
+ const hosts = new Map<string, RemoteHostEntry>()
320
389
  try {
321
- for (const host of this.store.list()) aliases.add(host.alias)
390
+ for (const host of this.store.list()) {
391
+ aliases.add(host.alias)
392
+ hosts.set(host.alias, host)
393
+ }
322
394
  } catch {
323
395
  // Unreadable store: answer what the pool knows rather than failing the route.
324
396
  }
325
397
  return [...aliases].sort().map((alias) => {
326
398
  const entry = this.health.get(alias)
327
399
  const pooled = this.conns.get(alias)
400
+ // The route the HELD connection came through, else the one the stored
401
+ // configuration would take next — never both, so a live answer cannot be
402
+ // passed off as a configuration statement (or the other way round).
403
+ const egress = this.liveEgress(alias)
404
+ const configured = egress === undefined ? this.configuredEgress(alias, hosts.get(alias)) : undefined
328
405
  return {
329
406
  alias,
330
407
  state: entry?.state ?? 'idle',
331
- // connecting means a DIAL is in flight (the pooled entry exists before
332
- // the Client does), so that is not an open connection yet.
408
+ // "open" = any of the three connection classes (shared / PTY / forward) is
409
+ // fully dialed. `connecting` means a DIAL is in flight (the pooled entry
410
+ // exists before the Client does), so that is not an open connection yet.
333
411
  open: (pooled !== undefined && pooled.connecting === undefined)
334
- || (this.shellConns.get(alias)?.connecting === undefined && this.shellConns.has(alias)),
412
+ || (this.shellConns.get(alias)?.connecting === undefined && this.shellConns.has(alias))
413
+ || (this.forwardConns.get(alias)?.connecting === undefined && this.forwardConns.has(alias)),
335
414
  ...(entry?.okAt === undefined ? {} : { okAt: entry.okAt }),
336
415
  ...(entry?.errorAt === undefined ? {} : { errorAt: entry.errorAt }),
337
416
  ...(entry?.error === undefined ? {} : { error: entry.error }),
417
+ ...(egress === undefined ? {} : { egress }),
418
+ ...(configured === undefined ? {} : { configured }),
338
419
  }
339
420
  })
340
421
  }
341
422
 
423
+ /**
424
+ * The egress of the alias' LIVE connection, whichever class owns it.
425
+ *
426
+ * All three classes open through the same resolved route, so the first one
427
+ * that is up answers for the alias; the shared connection is preferred because
428
+ * it is the one exec/browse (the surface the chip describes) rides.
429
+ */
430
+ private liveEgress(alias: string): EgressInfo | undefined {
431
+ for (const map of [this.conns, this.forwardConns, this.shellConns]) {
432
+ const pooled = map.get(alias)
433
+ if (pooled === undefined || pooled.connecting !== undefined) continue
434
+ if (pooled.egress !== undefined) return pooled.egress
435
+ }
436
+ return undefined
437
+ }
438
+
439
+ /**
440
+ * The route the stored configuration resolves to, for an alias with NO live
441
+ * connection. Pure observation, and absorbed: a dangling jump chain or a
442
+ * half-configured proxy makes `resolveProxy` throw, and a status poll must
443
+ * answer "the stored route is broken, here is why" instead of failing — the
444
+ * chip still has to render, and a 500 would hide the reason it exists to show.
445
+ */
446
+ private configuredEgress(alias: string, host: RemoteHostEntry | undefined): EgressInfo | undefined {
447
+ if (host === undefined) return undefined
448
+ try {
449
+ return egressOf(this.store.resolveProxy(alias), host)
450
+ } catch (error) {
451
+ return { ...storedEgress(host), problem: messageOf(error) }
452
+ }
453
+ }
454
+
342
455
  /** Record a successful dial or transport-level operation. */
343
456
  private markOk(alias: string): void {
344
457
  this.health.set(alias, { state: 'ok', okAt: Date.now() })
@@ -743,9 +856,47 @@ export class RemotePool {
743
856
  * debug their network. Real transport failures still arrive through the
744
857
  * pooled connection's own close/error events.
745
858
  */
746
- async forwardOut(alias: string, dstHost: string, dstPort: number, srcPort = 0): Promise<ClientChannel> {
747
- const conn = await this.acquire(alias)
748
- this.hold(alias)
859
+ async forwardOut(
860
+ alias: string,
861
+ dstHost: string,
862
+ dstPort: number,
863
+ srcPort = 0,
864
+ opts: { dedicated?: boolean } = {},
865
+ ): Promise<{ channel: ClientChannel; dedicated: boolean }> {
866
+ /**
867
+ * Prefer the DEDICATED forward connection (see `forwardConns`). A host that
868
+ * refuses the extra connection still forwards: the fallback is the shared
869
+ * connection, i.e. exactly the old behaviour. The downgrade is logged once per
870
+ * alias — a browser opens several forward channels per page, and one warning
871
+ * per server refusal is information while one per channel is noise.
872
+ *
873
+ * Two short-circuits keep that preference from costing time:
874
+ * - a recent refusal/timeout parks the alias for {@link FORWARD_DEDICATED_BLOCK_MS},
875
+ * so the next channel goes straight to the shared connection;
876
+ * - while a dedicated dial is already in flight, a second channel rides the
877
+ * shared connection instead of waiting for the same handshake (it can only
878
+ * be used by ONE `acquireIn` caller anyway).
879
+ */
880
+ let conn: Client
881
+ let dedicated = opts.dedicated !== false
882
+ if (dedicated && this.forwardCoolingDown(alias)) dedicated = false
883
+ if (dedicated && this.forwardConns.get(alias)?.connecting !== undefined) dedicated = false
884
+ if (dedicated) {
885
+ try {
886
+ conn = await this.acquireForward(alias)
887
+ this.holdIn(this.forwardConns, alias)
888
+ // A real dedicated connection clears the cooldown: the host accepts them.
889
+ this.forwardBlocked.delete(alias)
890
+ } catch (error) {
891
+ dedicated = false
892
+ this.blockForward(alias, error)
893
+ conn = await this.acquire(alias)
894
+ this.hold(alias)
895
+ }
896
+ } else {
897
+ conn = await this.acquire(alias)
898
+ this.hold(alias)
899
+ }
749
900
  /**
750
901
  * What the channel-open callback does after the deadline already answered.
751
902
  *
@@ -779,16 +930,66 @@ export class RemotePool {
779
930
  CONTROL_TIMEOUT_MS,
780
931
  `forwarding channel to ${dstHost}:${dstPort} did not open within ${CONTROL_TIMEOUT_MS / 1000}s`,
781
932
  )
782
- channel.once('close', () => this.release(alias))
783
- this.markOk(alias)
784
- return channel
933
+ channel.once('close', () => {
934
+ if (dedicated) this.releaseIn(this.forwardConns, alias)
935
+ else this.release(alias)
936
+ })
937
+ // Only the SHARED path is evidence about the shared link. A dedicated
938
+ // channel that opened says nothing about it (and the dedicated connection's
939
+ // own failures never write health — see `acquireIn`'s `quiet`).
940
+ if (!dedicated) this.markOk(alias)
941
+ return { channel, dedicated }
785
942
  } catch (error) {
786
943
  settled = true
787
- this.release(alias)
944
+ if (dedicated) this.releaseIn(this.forwardConns, alias)
945
+ else this.release(alias)
946
+ /**
947
+ * NO `markError` here — deliberately.
948
+ *
949
+ * ssh2 reports EVERY direct-tcpip failure as
950
+ * `(SSH) Channel open failure: <reason>`, and the pool's
951
+ * `CONNECTION_ERROR_RE` matches `channel open fail`. A closed remote port or
952
+ * `AllowTcpForwarding no` therefore LOOKS like a transport failure and used
953
+ * to paint the connection chip red (sending the user to debug a healthy
954
+ * network, and putting the editor into read-only). The function's contract
955
+ * is the opposite: a channel-open refusal is the RULE's failure
956
+ * (`forward.lastError`), while real transport failures surface through the
957
+ * pooled connection's own close/error events.
958
+ */
788
959
  throw error
789
960
  }
790
961
  }
791
962
 
963
+ /**
964
+ * Is this alias's dedicated forward connection in its short cooldown?
965
+ *
966
+ * Expired entries are dropped eagerly so the map cannot grow per alias forever.
967
+ */
968
+ private forwardCoolingDown(alias: string): boolean {
969
+ const until = this.forwardBlocked.get(alias)
970
+ if (until === undefined) return false
971
+ if (Date.now() >= until) {
972
+ this.forwardBlocked.delete(alias)
973
+ return false
974
+ }
975
+ return true
976
+ }
977
+
978
+ /** Park the dedicated connection for one alias and log the downgrade, once. */
979
+ private blockForward(alias: string, error: unknown): void {
980
+ this.forwardBlocked.set(alias, Date.now() + FORWARD_DEDICATED_BLOCK_MS)
981
+ this.noteForwardFallback(alias, error)
982
+ }
983
+
984
+ /** Log one alias's forward downgrade to the shared connection, once. */
985
+ private noteForwardFallback(alias: string, error: unknown): void {
986
+ if (this.forwardFallbackNoted.has(alias)) return
987
+ this.forwardFallbackNoted.add(alias)
988
+ const detail = error instanceof Error ? error.message : String(error ?? '')
989
+ // eslint-disable-next-line no-console
990
+ console.warn(`[dsh-remote-vs] dedicated forward connection to ${alias} failed; using the shared one:`, detail)
991
+ }
992
+
792
993
  /** Run one callback with a fresh SFTP session (closed afterwards). */
793
994
  async withSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts: SftpOptions = {}): Promise<T> {
794
995
  // An SFTP session IS a channel, so it takes a slot too: the burst that put
@@ -1379,7 +1580,39 @@ export class RemotePool {
1379
1580
  return this.acquireIn(this.shellConns, alias)
1380
1581
  }
1381
1582
 
1382
- private async acquireIn(map: Map<string, Pooled>, alias: string): Promise<Client> {
1583
+ /**
1584
+ * `acquire` for the dedicated port-forward connection map.
1585
+ *
1586
+ * `quiet`: a dedicated forward connection is an OPTIMIZATION. If the server
1587
+ * refuses it (MaxStartups, `MaxSessions`, a per-source limit) the forward still
1588
+ * works over the shared connection, so the shared link is healthy — painting
1589
+ * the connection chip red here would send the user to debug a network that is
1590
+ * fine (and `forwardOut` reports the rule's own error separately).
1591
+ *
1592
+ * The dial also gets its OWN short budget ({@link FORWARD_DEDICATED_BUDGET_MS}):
1593
+ * a server that silently drops the extra connection would otherwise make every
1594
+ * forward channel wait the full connect watchdog before falling back. The
1595
+ * abandoned dial keeps running — if it eventually succeeds the connection is
1596
+ * pooled and the next channel uses it; its failure is already handled inside
1597
+ * `acquireIn`.
1598
+ */
1599
+ private async acquireForward(alias: string): Promise<Client> {
1600
+ const dialing = this.acquireIn(this.forwardConns, alias, true)
1601
+ try {
1602
+ return await withDeadline(
1603
+ dialing,
1604
+ FORWARD_DEDICATED_BUDGET_MS,
1605
+ `dedicated forward connection to ${alias} did not settle within ${FORWARD_DEDICATED_BUDGET_MS / 1000}s`,
1606
+ )
1607
+ } catch (error) {
1608
+ // The race's loser must never surface as an unhandled rejection: the pool
1609
+ // still owns it (its own success/failure updates the map).
1610
+ void dialing.catch(() => undefined)
1611
+ throw error
1612
+ }
1613
+ }
1614
+
1615
+ private async acquireIn(map: Map<string, Pooled>, alias: string, quiet = false): Promise<Client> {
1383
1616
  const pooled = map.get(alias)
1384
1617
  if (pooled !== undefined && pooled.connecting !== undefined) return pooled.connecting
1385
1618
  if (pooled !== undefined) {
@@ -1399,7 +1632,11 @@ export class RemotePool {
1399
1632
  * so no idle timer arms, and `dispose()` only walks the map. Without the
1400
1633
  * failure check, a failed OLD dial deletes the NEW entry by alias.
1401
1634
  */
1402
- entry.connecting = this.dial(alias).then(
1635
+ entry.connecting = this.dial(alias, (egress) => {
1636
+ // The entry object is the ownership token (see just above): a dial that
1637
+ // lost the alias must not paint its route on whatever entry now holds it.
1638
+ if (map.get(alias) === entry) entry.egress = egress
1639
+ }).then(
1403
1640
  (conn) => {
1404
1641
  if (map.get(alias) !== entry) {
1405
1642
  try {
@@ -1411,18 +1648,18 @@ export class RemotePool {
1411
1648
  }
1412
1649
  entry.conn = conn
1413
1650
  entry.connecting = undefined
1414
- this.markOk(alias)
1651
+ if (!quiet) this.markOk(alias)
1415
1652
  conn.on('close', () => {
1416
1653
  // The server went away: record it for the status chip, then evict so
1417
1654
  // the next op redials. Our OWN drop() deleted the entry first, so a
1418
1655
  // normal close (idle eviction, host removal) never lands here.
1419
1656
  if (map.get(alias) !== entry) return
1420
- this.markError(alias, new Error('connection closed'))
1657
+ if (!quiet) this.markError(alias, new Error('connection closed'))
1421
1658
  this.evictFrom(map, alias)
1422
1659
  })
1423
1660
  conn.on('error', (error: Error) => {
1424
1661
  if (map.get(alias) !== entry) return
1425
- this.markError(alias, error)
1662
+ if (!quiet) this.markError(alias, error)
1426
1663
  this.evictFrom(map, alias)
1427
1664
  })
1428
1665
  this.releaseIn(map, alias)
@@ -1430,7 +1667,7 @@ export class RemotePool {
1430
1667
  },
1431
1668
  (error) => {
1432
1669
  if (map.get(alias) === entry) map.delete(alias)
1433
- this.markError(alias, error)
1670
+ if (!quiet) this.markError(alias, error)
1434
1671
  throw error
1435
1672
  },
1436
1673
  )
@@ -1443,6 +1680,9 @@ export class RemotePool {
1443
1680
  if (pooled === undefined) return
1444
1681
  map.delete(alias)
1445
1682
  if (pooled.timer !== undefined) clearTimeout(pooled.timer)
1683
+ // The route belongs to the connection that just ended: leaving it behind
1684
+ // would let a closed link keep claiming the egress it once used.
1685
+ pooled.egress = undefined
1446
1686
  try {
1447
1687
  pooled.conn.end()
1448
1688
  } catch {
@@ -1462,8 +1702,84 @@ export class RemotePool {
1462
1702
  return new Client()
1463
1703
  }
1464
1704
 
1465
- private dial(alias: string): Promise<Client> {
1705
+ /**
1706
+ * Open one SSH connection, through whatever route the store resolves.
1707
+ *
1708
+ * Three routes, and only the first is the pre-proxy code path:
1709
+ * - `direct`: unchanged (`host` / `port` in the connect config);
1710
+ * - `proxy`: the proxy module builds the tunnel and ssh2 rides the returned
1711
+ * socket (`sock`), so `host`/`port` are deliberately omitted (ssh2 ignores
1712
+ * them when `sock` is present);
1713
+ * - `jump`: the tunnel is a `direct-tcpip` channel on the JUMP host's pooled
1714
+ * connection, held for as long as the client lives. Its close/error handlers
1715
+ * close that channel and give the hold back — a leak here would pin the jump
1716
+ * host's connection forever.
1717
+ *
1718
+ * Every failure is a DIAL failure, so it keeps the existing `markError`
1719
+ * semantics; only the message is layered, so the user can tell which hop broke:
1720
+ * `proxy auth failed: …`, `proxy refused: …`, `jump host "x" failed: …`.
1721
+ *
1722
+ * `report` receives the route this dial ACTUALLY settled on, once and only on
1723
+ * success — a caller that asked "did this go through the jump host?" must not
1724
+ * be answered from a configuration that may have changed since. It is a
1725
+ * callback rather than a wider return type so the seam keeps returning the
1726
+ * `Client` the existing callers (and gates) hand around.
1727
+ */
1728
+ private async dial(alias: string, report?: (egress: EgressInfo) => void): Promise<Client> {
1466
1729
  const host: RemoteHostEntry = this.store.require(alias)
1730
+ /** The socket ssh2 will ride, when a proxy/jump built one. */
1731
+ let sock: Duplex | undefined
1732
+ /** Runs once: tears the tunnel down (close the channel, release the jump). */
1733
+ let releaseTunnel: (() => void) | undefined
1734
+ const route = this.store.resolveProxy(alias)
1735
+ const egress = egressOf(route, host)
1736
+ if (route.kind === 'proxy') {
1737
+ try {
1738
+ sock = await openProxySocket(route.proxy, host.host, host.port)
1739
+ } catch (error) {
1740
+ throw proxyDialError(error, route.proxy)
1741
+ }
1742
+ releaseTunnel = () => {
1743
+ try {
1744
+ sock?.destroy()
1745
+ } catch {
1746
+ // Already gone (ssh2 closes it with the connection).
1747
+ }
1748
+ }
1749
+ } else if (route.kind === 'jump') {
1750
+ const via = route.viaAlias
1751
+ try {
1752
+ await this.acquire(via)
1753
+ this.hold(via)
1754
+ } catch (error) {
1755
+ throw new Error(`jump host "${via}" failed: ${messageOf(error)}`)
1756
+ }
1757
+ let channel: ClientChannel
1758
+ try {
1759
+ // Reuse the SHARED jump-host connection that `acquire`+`hold` just
1760
+ // established. `forwardOut` prefers a dedicated per-purpose connection by
1761
+ // default, which here would dial the SAME jump host a second time for a
1762
+ // tunnel that already holds the first one (an extra handshake per jump
1763
+ // dial, and a second connection to a host we are already connected to).
1764
+ channel = (await this.forwardOut(via, host.host, host.port, 0, { dedicated: false })).channel
1765
+ } catch (error) {
1766
+ this.release(via)
1767
+ throw new Error(`jump host "${via}" failed: ${messageOf(error)}`)
1768
+ }
1769
+ let released = false
1770
+ releaseTunnel = () => {
1771
+ if (released) return
1772
+ released = true
1773
+ try {
1774
+ channel.close()
1775
+ } catch {
1776
+ // Already gone.
1777
+ }
1778
+ this.release(via)
1779
+ }
1780
+ // A channel is a duplex stream: ssh2 never learns it is not a raw socket.
1781
+ sock = channel as unknown as Duplex
1782
+ }
1467
1783
  return new Promise<Client>((resolve, reject) => {
1468
1784
  const conn = this.makeClient()
1469
1785
  let settled = false
@@ -1477,12 +1793,14 @@ export class RemotePool {
1477
1793
  } catch {
1478
1794
  // Ignore.
1479
1795
  }
1796
+ releaseTunnel?.()
1480
1797
  reject(explainAuthError(host, error))
1481
1798
  }
1482
1799
  conn.on('ready', () => {
1483
1800
  if (settled) return
1484
1801
  settled = true
1485
1802
  if (guard !== undefined) clearTimeout(guard)
1803
+ report?.(egress)
1486
1804
  resolve(conn)
1487
1805
  })
1488
1806
  conn.on('error', (error: Error) => fail(error))
@@ -1494,6 +1812,12 @@ export class RemotePool {
1494
1812
  * leave this promise pending forever while the caller held a channel slot.
1495
1813
  */
1496
1814
  conn.on('close', () => fail(new Error('connection closed during SSH handshake')))
1815
+ // The tunnel belongs to the connection: however the client ends, the channel
1816
+ // and the jump host's hold go with it (idempotent; `fail` may have run).
1817
+ if (releaseTunnel !== undefined) {
1818
+ conn.once('close', () => releaseTunnel?.())
1819
+ conn.once('error', () => releaseTunnel?.())
1820
+ }
1497
1821
  // Last resort: the library reports nothing at all (neither ready, nor
1498
1822
  // error, nor close). `readyTimeout` cannot cover it because ssh2 clears
1499
1823
  // that timer as soon as the socket closes without emitting an error.
@@ -1535,11 +1859,11 @@ export class RemotePool {
1535
1859
  return true
1536
1860
  }
1537
1861
  try {
1862
+ const transport = sock === undefined ? { host: host.host, port: host.port } : { sock }
1538
1863
  if (host.auth.kind === 'key') {
1539
1864
  const keyPath = host.auth.keyPath as string
1540
1865
  conn.connect({
1541
- host: host.host,
1542
- port: host.port,
1866
+ ...transport,
1543
1867
  username: host.user,
1544
1868
  privateKey: readFileSync(keyPath),
1545
1869
  passphrase: host.auth.passphrase,
@@ -1550,8 +1874,7 @@ export class RemotePool {
1550
1874
  })
1551
1875
  } else {
1552
1876
  conn.connect({
1553
- host: host.host,
1554
- port: host.port,
1877
+ ...transport,
1555
1878
  username: host.user,
1556
1879
  password: host.auth.password,
1557
1880
  tryKeyboard: true,
@@ -1568,6 +1891,78 @@ export class RemotePool {
1568
1891
  }
1569
1892
  }
1570
1893
 
1894
+ /**
1895
+ * The route one resolved proxy decision describes, in the shape the chip prints.
1896
+ *
1897
+ * `detail` is the HOP, never a sentence: the target `host:port` for a direct
1898
+ * connection, the proxy `host:port` for a tunnel, the jump host's alias for a
1899
+ * chain. The wording belongs to the localized client — a second English sentence
1900
+ * baked in here would leak into the Chinese tooltip.
1901
+ */
1902
+ function egressOf(route: ResolvedProxy, host: RemoteHostEntry): EgressInfo {
1903
+ if (route.kind === 'proxy') {
1904
+ return {
1905
+ kind: 'proxy',
1906
+ detail: `${route.proxy.host}:${route.proxy.port}`,
1907
+ source: route.source,
1908
+ proxyKind: route.proxy.kind,
1909
+ }
1910
+ }
1911
+ if (route.kind === 'jump') return { kind: 'jump', detail: route.viaAlias, viaAlias: route.viaAlias }
1912
+ return { kind: 'direct', detail: `${host.host}:${host.port}` }
1913
+ }
1914
+
1915
+ /**
1916
+ * Best-effort route from the STORED fields, for the one case `resolveProxy`
1917
+ * refuses to answer (a dangling jump chain, a self-jump, a proxy setting that
1918
+ * does not validate). The caller adds `problem` with the reason; the shape here
1919
+ * only says WHICH kind of route is broken, so the chip can name it.
1920
+ */
1921
+ function storedEgress(host: RemoteHostEntry): EgressInfo {
1922
+ const jump = host.proxy?.jump?.viaAlias
1923
+ if (host.proxy?.mode === 'jump') {
1924
+ return { kind: 'jump', detail: jump ?? '', ...(jump === undefined ? {} : { viaAlias: jump }) }
1925
+ }
1926
+ const proxy = host.proxy?.proxy
1927
+ if (proxy !== undefined) {
1928
+ return { kind: 'proxy', detail: `${proxy.host}:${proxy.port}`, proxyKind: proxy.kind }
1929
+ }
1930
+ return { kind: 'direct', detail: `${host.host}:${host.port}` }
1931
+ }
1932
+
1933
+ /** Message of an unknown thrown value, without assuming it is an `Error`. */
1934
+ function messageOf(error: unknown): string {
1935
+ return error instanceof Error ? error.message : String(error ?? '')
1936
+ }
1937
+
1938
+ /**
1939
+ * Fixed prefix per proxy failure reason.
1940
+ *
1941
+ * The dial fails either way; the prefix is what tells the user WHICH layer broke —
1942
+ * their password, the proxy host, the tunnel policy, or the destination. The raw
1943
+ * detail is kept after it, so nothing is lost.
1944
+ */
1945
+ const PROXY_FAILURE_PREFIX: Record<ProxyFailure, string> = {
1946
+ unreachable: 'proxy unreachable',
1947
+ timeout: 'proxy timed out',
1948
+ auth: 'proxy auth failed',
1949
+ refused: 'proxy refused',
1950
+ protocol: 'proxy protocol error',
1951
+ target: 'proxy target invalid',
1952
+ }
1953
+
1954
+ /** One proxy dial failure, with the layer in front of the original message. */
1955
+ function proxyDialError(error: unknown, proxy: ProxyConfig): Error {
1956
+ if (error instanceof ProxyError) {
1957
+ const prefix = PROXY_FAILURE_PREFIX[error.reason]
1958
+ // A bad destination is not the proxy's address; naming the proxy there would
1959
+ // send the user to the wrong field.
1960
+ const where = error.reason === 'target' ? '' : ` ${proxy.kind} proxy ${proxy.host}:${proxy.port}`
1961
+ return new Error(`${prefix}${where}: ${error.message}`)
1962
+ }
1963
+ return new Error(`proxy failed: ${proxy.kind} proxy ${proxy.host}:${proxy.port}: ${messageOf(error)}`)
1964
+ }
1965
+
1571
1966
  /**
1572
1967
  * Translate ssh2's generic auth failure into something actionable. Never
1573
1968
  * includes secrets — only the entry shape and the likely server-side causes.