dsh-ssh-hub 0.0.0-stage → 0.2.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.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
@@ -0,0 +1,721 @@
1
+ /**
2
+ * Connection pool: per-alias persistent ssh2 connections with multi-hop jump
3
+ * support, the acquire / dispose / sweep lifecycle, and the pooled exec path.
4
+ */
5
+
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import type { Duplex } from 'node:stream'
8
+ // ssh2 is a CommonJS package loaded here through an explicit require.
9
+ //
10
+ // Neither a named import nor a default import of it is reliable: under
11
+ // esbuild's ESM output both resolve to undefined at runtime ("Client is not a
12
+ // constructor", then "Ssh2Client is not a constructor" once the default form
13
+ // was tried), because the host bundle is loaded as ESM by a loader whose CJS
14
+ // interop does not synthesise the bindings. createRequire bypasses the
15
+ // interop entirely and returns the real module.exports object, which is the
16
+ // only form that behaves the same under vitest, a plain node process, and the
17
+ // packaged host bundle.
18
+ import { createRequire } from 'node:module'
19
+ import type { Client, ConnectConfig } from 'ssh2'
20
+
21
+ /** Load a CommonJS package by name, independent of ESM interop. */
22
+ function requireCjs<T>(name: string): T {
23
+ return createRequire(import.meta.url)(name) as T
24
+ }
25
+
26
+ /** The ssh2 module namespace. */
27
+ const ssh2 = requireCjs<typeof import('ssh2')>('ssh2')
28
+
29
+ /** The Client constructor, read off the real CJS export object. */
30
+ const Ssh2Client = ssh2.Client
31
+ import type { ExecResult, SshHostEntry } from '../protocol.ts'
32
+ import { expandHome, keyCandidates, normalizeAgentPath, type HostStore } from '../store.ts'
33
+ import { createHostVerifier, type HostKeyPolicy } from '../security/known-hosts.ts'
34
+ import { startProxyCommand, type ProxyTarget } from './proxy-command.ts'
35
+
36
+ /** Default engine knobs. */
37
+ export interface EngineOptions {
38
+ /** Connections idle longer than this are closed (ms). */
39
+ idleTimeoutMs?: number
40
+ /**
41
+ * Ceiling for the whole pre-ready sequence (ms): TCP connect, SSH key
42
+ * exchange and user authentication. Passed to ssh2's `readyTimeout`.
43
+ */
44
+ connectTimeoutMs?: number
45
+ /** Keepalive ping interval (ms). */
46
+ keepaliveIntervalMs?: number
47
+ /** Cap on captured stdout/stderr bytes per exec (ms). */
48
+ maxOutputBytes?: number
49
+ /** Default exec timeout (ms). */
50
+ defaultExecTimeoutMs?: number
51
+ /** Default cluster concurrency. */
52
+ defaultMaxWorkers?: number
53
+ /** SFTP concurrent channel count for transfers. */
54
+ sftpConcurrency?: number
55
+ /**
56
+ * Host-key verification policy. `off` keeps the base plugin's behaviour
57
+ * (no verification) so an upgrade never locks an existing user out;
58
+ * `tofu` records an unknown host and refuses a changed key; `strict`
59
+ * refuses anything not already in known_hosts.
60
+ */
61
+ hostKeyPolicy?: HostKeyPolicy
62
+ /** The known_hosts file consulted for verification. */
63
+ knownHostsPath?: string
64
+ /** Called when TOFU records a newly trusted host key. */
65
+ onHostKeyRecord?: (host: string, port: number, keyType: string, key: string) => void
66
+ }
67
+
68
+ /**
69
+ * Default ceiling for TCP connect, SSH key exchange and user authentication
70
+ * together (ms). Password authentication behind PAM / LDAP can outlast the
71
+ * previous 15 s ceiling while the server still eventually accepts it.
72
+ */
73
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 30_000
74
+
75
+ /**
76
+ * The engine knobs with every optional filled in.
77
+ *
78
+ * `onHostKeyRecord` is deliberately left optional even here: it is a
79
+ * callback, not a knob, and `Required<>` would force every construction
80
+ * site to spell out `undefined`.
81
+ */
82
+ export type ResolvedEngineOptions = Required<Omit<EngineOptions, 'onHostKeyRecord'>> & Pick<EngineOptions, 'onHostKeyRecord'>
83
+
84
+ /** Default engine knobs (applied when an option is omitted). */
85
+ export const DEFAULTS: ResolvedEngineOptions = {
86
+ idleTimeoutMs: 30 * 60_000,
87
+ connectTimeoutMs: DEFAULT_CONNECT_TIMEOUT_MS,
88
+ keepaliveIntervalMs: 15_000,
89
+ maxOutputBytes: 2 * 1024 * 1024,
90
+ defaultExecTimeoutMs: 60_000,
91
+ defaultMaxWorkers: 8,
92
+ sftpConcurrency: 8,
93
+ hostKeyPolicy: 'off',
94
+ knownHostsPath: '',
95
+ }
96
+
97
+ /** One pooled connection record. */
98
+ export interface PoolRecord {
99
+ client: Client
100
+ /** Jump-chain clients kept alive under the target. */
101
+ hops: Client[]
102
+ idleAt: number
103
+ /** Pinned connections (tunnels) are never swept. */
104
+ pinned: boolean
105
+ broken: boolean
106
+ /** Operations currently running on this connection (sweep guard). */
107
+ inFlight: number
108
+ }
109
+
110
+ /**
111
+ * The slice of the engine the pool and exec paths need. The host class
112
+ * (engine.ts facade) satisfies this structurally.
113
+ */
114
+ export interface PoolEngine {
115
+ readonly store: HostStore
116
+ readonly opts: ResolvedEngineOptions
117
+ readonly pool: Map<string, PoolRecord>
118
+ readonly acquireQueue: Map<string, Promise<PoolRecord>>
119
+ }
120
+
121
+ /** Build the ssh2 connect config for one entry (key read from disk). */
122
+ export function buildConnectConfig(entry: SshHostEntry, sock: ConnectConfig['sock'] | undefined, opts: ResolvedEngineOptions): ConnectConfig {
123
+ const config: ConnectConfig = {
124
+ host: entry.host,
125
+ port: entry.port,
126
+ username: entry.user,
127
+ readyTimeout: opts.connectTimeoutMs,
128
+ keepaliveInterval: opts.keepaliveIntervalMs,
129
+ keepaliveCountMax: 3,
130
+ tryKeyboard: true,
131
+ }
132
+ if (sock !== undefined) config.sock = sock
133
+ // Host-key verification. The base plugin never set a verifier, so every
134
+ // server key was accepted — a real MITM surface. The verifier is bound to
135
+ // this connection's host/port because ssh2 hands it only the key.
136
+ if (opts.hostKeyPolicy !== 'off') {
137
+ config.hostVerifier = createHostVerifier({
138
+ policy: opts.hostKeyPolicy,
139
+ path: opts.knownHostsPath,
140
+ host: entry.host,
141
+ port: entry.port,
142
+ onRecord: opts.onHostKeyRecord,
143
+ })
144
+ }
145
+ if (entry.auth.kind === 'none') {
146
+ // OpenSSH's `PreferredAuthentications none`: the server accepts the
147
+ // username with no credential (some sandboxes bind identity to the user
148
+ // name). There is nothing to look up, so this must not be rejected for
149
+ // "missing credential" — it is the configured method.
150
+ config.authHandler = ['none']
151
+ } else if (entry.auth.kind === 'password') {
152
+ // A password host with no password cannot authenticate. Saying so beats
153
+ // letting ssh2 report "no authentication methods", which sends the
154
+ // operator looking at the server instead of at the credential store.
155
+ if (entry.auth.password === undefined || entry.auth.password === '') {
156
+ throw new Error(
157
+ `no password stored for '${entry.alias}': the credential is missing, or it is encrypted and the master key is not available`,
158
+ )
159
+ }
160
+ config.password = entry.auth.password
161
+ } else if (entry.auth.kind === 'agent') {
162
+ const agentPath = resolveAgentPath(entry.auth.agentPath)
163
+ if (agentPath === undefined) {
164
+ throw new Error('ssh-agent is not available: set SSH_AUTH_SOCK or configure an agent path (use \'pageant\' for PuTTY Pageant on Windows)')
165
+ }
166
+ config.agent = agentPath
167
+ } else {
168
+ // OpenSSH tries every IdentityFile in order and stops at the first key the
169
+ // server accepts. A host configured with two keys must keep both: honouring
170
+ // only the last one turns a working `ssh <alias>` into "All configured
171
+ // authentication methods failed".
172
+ const configured = keyCandidates(entry)
173
+ const present = configured.filter(path => existsSync(path))
174
+ if (present.length === 0) {
175
+ throw new Error('private key not found: ' + (configured[0] ?? '(unset)'))
176
+ }
177
+ const passphrase = entry.auth.passphrase !== undefined && entry.auth.passphrase !== '' ? entry.auth.passphrase : undefined
178
+ if (present.length === 1) {
179
+ config.privateKey = readFileSync(present[0] as string, 'utf8')
180
+ if (passphrase !== undefined) config.passphrase = passphrase
181
+ } else {
182
+ // ssh2 applies the methods in the order given, so the ssh_config order is
183
+ // preserved and a rejected key is skipped rather than fatal.
184
+ config.authHandler = present.map(path => ({
185
+ type: 'publickey' as const,
186
+ username: entry.user,
187
+ key: readFileSync(path, 'utf8'),
188
+ ...(passphrase !== undefined ? { passphrase } : {}),
189
+ }))
190
+ }
191
+ }
192
+ // Agent forwarding is additive: it never changes how the host
193
+ // authenticates, it only lets this connection broker signatures from the
194
+ // local agent for the remote side (OpenSSH ForwardAgent / ssh -A).
195
+ if (entry.forwardAgent === true) {
196
+ // Agent auth already resolved an endpoint, and reusing it keeps the
197
+ // forwarded agent identical to the one that authenticated.
198
+ const agentPath = typeof config.agent === 'string'
199
+ ? config.agent
200
+ : resolveForwardAgentPath(entry.auth.agentPath)
201
+ if (agentPath === undefined) {
202
+ // ssh2's own message for this case ("You must set a valid agent path to
203
+ // allow agent forwarding") names neither the host nor a way out, so the
204
+ // engine refuses first with an actionable one.
205
+ throw new Error('agent forwarding is enabled for this host but no ssh-agent endpoint is available: '
206
+ + 'set SSH_AUTH_SOCK, start Pageant on Windows, or configure an agent path')
207
+ }
208
+ config.agent = agentPath
209
+ config.agentForward = true
210
+ }
211
+ return config
212
+ }
213
+
214
+ /**
215
+ * The default ssh-agent endpoint on Windows: the named pipe the native
216
+ * OpenSSH ssh-agent service listens on. ssh2 connects to a named pipe for any
217
+ * path matching its Windows pipe form, so the default is a real endpoint
218
+ * rather than a protocol name (#1910). PuTTY Pageant is still reachable — it
219
+ * is what the literal `pageant` agent path selects — but it is no longer the
220
+ * assumption.
221
+ */
222
+ export const WINDOWS_AGENT_PIPE = '\\\\.\\pipe\\openssh-ssh-agent'
223
+
224
+ /** Resolve the ssh2 agent path for 'agent' auth. */
225
+ export function resolveAgentPath(agentPath?: string): string | undefined {
226
+ const explicit = normalizeAgentPath(agentPath)
227
+ if (explicit !== undefined) return explicit
228
+ const sock = process.env.SSH_AUTH_SOCK
229
+ if (sock !== undefined && sock !== '') return sock
230
+ if (process.platform === 'win32') return WINDOWS_AGENT_PIPE
231
+ return undefined
232
+ }
233
+
234
+ /**
235
+ * Resolve the ssh-agent endpoint that forwarding brokers signatures through:
236
+ * an explicitly configured agent path wins, then SSH_AUTH_SOCK, then the
237
+ * native OpenSSH named pipe on Windows. Undefined means no endpoint exists on
238
+ * this machine.
239
+ *
240
+ * Forwarding shares the auth resolution on purpose — the endpoint a host
241
+ * signs through is the same one it authenticates with — but it is a separate
242
+ * name so the forwarding path can evolve without touching auth.
243
+ */
244
+ export function resolveForwardAgentPath(agentPath?: string): string | undefined {
245
+ return resolveAgentPath(agentPath)
246
+ }
247
+
248
+ /** Keyboard-interactive handler callback for 2FA / dynamic prompt flow. */
249
+ export type KeyboardInteractiveHandler = (
250
+ name: string,
251
+ instructions: string,
252
+ instructionsLang: string,
253
+ prompts: Array<{ prompt: string; echo: boolean }>,
254
+ finish: (responses: string[]) => void,
255
+ ) => void
256
+
257
+ /**
258
+ * Name the phase that actually stalled. ssh2 reports every pre-ready timeout
259
+ * as "Timed out while waiting for handshake", including one that expires
260
+ * during user authentication after a completed key exchange.
261
+ *
262
+ * @param timeoutMs - the configured `readyTimeout` (0 disables it).
263
+ * @param handshakeComplete - whether ssh2 completed the key exchange.
264
+ * @returns the operator-facing timeout message.
265
+ */
266
+ export function readyTimeoutMessage(timeoutMs: number | undefined, handshakeComplete: boolean): string {
267
+ const budget = typeof timeoutMs === 'number' && timeoutMs > 0 ? ' after ' + timeoutMs + ' ms' : ''
268
+ const hint = ' - raise the dsh-ssh connectTimeoutMs setting if this host is slow'
269
+ return handshakeComplete
270
+ ? 'SSH authentication timed out' + budget + ': TCP connect and key exchange completed, but the server did not finish authenticating the user' + hint
271
+ : 'SSH connection timed out' + budget + ' before key exchange completed: TCP connect or the SSH key exchange did not finish' + hint
272
+ }
273
+
274
+ /**
275
+ * Whether ssh2 ended the attempt with its pre-ready timeout. The level is the
276
+ * stable discriminator; the message is reused for connect, key exchange and
277
+ * authentication alike.
278
+ */
279
+ export function isReadyTimeout(error: Error): boolean {
280
+ return (error as Error & { level?: unknown }).level === 'client-timeout'
281
+ }
282
+
283
+ /** Connect one ssh2 client (resolve on ready, reject on error/close). */
284
+ export function connectClient(config: ConnectConfig, onKeyboardInteractive?: KeyboardInteractiveHandler): Promise<Client> {
285
+ return new Promise((resolve, reject) => {
286
+ const client = new Ssh2Client()
287
+ let settled = false
288
+ // Key exchange completion is the only public phase boundary ssh2 exposes
289
+ // between "TCP connect / SSH handshake" and "user authentication".
290
+ let handshakeComplete = false
291
+ const fail = (error: unknown): void => {
292
+ if (settled) return
293
+ settled = true
294
+ // A caller-supplied transport (a jump forwardOut stream or a
295
+ // ProxyCommand) must not outlive the client that failed to use it, or
296
+ // its child process leaks.
297
+ const sock = config.sock
298
+ if (sock !== undefined && typeof (sock as { destroy?: unknown }).destroy === 'function') {
299
+ try { (sock as { destroy: () => void }).destroy() } catch { /* already closed */ }
300
+ }
301
+ try { client.destroy() } catch { /* already closed */ }
302
+ const cause = error instanceof Error ? error : new Error(String(error))
303
+ reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause)
304
+ }
305
+ client.once('handshake', () => {
306
+ handshakeComplete = true
307
+ })
308
+ client.once('ready', () => {
309
+ if (settled) return
310
+ settled = true
311
+ resolve(client)
312
+ })
313
+ client.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {
314
+ if (onKeyboardInteractive !== undefined) {
315
+ onKeyboardInteractive(name, instructions, instructionsLang, prompts.map(p => ({ prompt: p.prompt, echo: Boolean(p.echo) })), finish)
316
+ return
317
+ }
318
+ // Step 1: Automatic PAM password fallback: if a password is configured and all prompts ask for password
319
+ if (config.password !== undefined && prompts.length > 0 && prompts.every(p => /password/i.test(p.prompt))) {
320
+ finish(prompts.map(() => config.password as string))
321
+ return
322
+ }
323
+ fail(new Error('Authentication failed (keyboard-interactive): ' + (prompts.map(p => p.prompt.trim()).join(', ') || 'unsupported interactive challenge')))
324
+ })
325
+ // Keep an error listener attached after the handshake: when TCP connects
326
+ // but the handshake drops, ssh2 can emit a second 'error' after a single
327
+ // once-listener is gone, which would surface as an unhandled 'error' event.
328
+ // The settled guard turns later emissions into a no-op; other callers
329
+ // (like doAcquire) attach their own error listeners and all fire together.
330
+ client.on('error', fail)
331
+ try {
332
+ client.connect(config)
333
+ } catch (error) {
334
+ fail(error)
335
+ }
336
+ })
337
+ }
338
+
339
+ /** Cap captured output at the configured byte budget (marks truncation). */
340
+ export function appendOutput(target: { text: string; truncated: boolean }, chunk: Buffer, maxBytes: number): void {
341
+ if (target.truncated) return
342
+ if (target.text.length + chunk.length > maxBytes) {
343
+ let cut = chunk.toString('utf8').slice(0, maxBytes - target.text.length)
344
+ // Never split a surrogate pair at the cut boundary.
345
+ if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1)
346
+ target.text += cut + '…[output truncated]'
347
+ target.truncated = true
348
+ return
349
+ }
350
+ target.text += chunk.toString('utf8')
351
+ }
352
+
353
+ /** The ProxyCommand token source for one entry. */
354
+ function proxyTargetOf(entry: SshHostEntry): ProxyTarget {
355
+ return { host: entry.host, port: entry.port, user: entry.user, alias: entry.alias }
356
+ }
357
+
358
+ /**
359
+ * Parse an OpenSSH jump hop written as an address: `[user@]host[:port]`
360
+ * (an IPv6 literal must be bracketed). Returns undefined when the value is not
361
+ * an address at all.
362
+ */
363
+ export function parseJumpSpec(spec: string): { host: string; port?: number; user?: string } | undefined {
364
+ const trimmed = spec.trim()
365
+ if (trimmed === '') return undefined
366
+ const at = trimmed.lastIndexOf('@')
367
+ const user = at >= 0 ? trimmed.slice(0, at) : undefined
368
+ const rest = at >= 0 ? trimmed.slice(at + 1) : trimmed
369
+ if (rest === '') return undefined
370
+ let host = rest
371
+ let portText: string | undefined
372
+ if (rest.startsWith('[')) {
373
+ const end = rest.indexOf(']')
374
+ if (end < 0) return undefined
375
+ host = rest.slice(1, end)
376
+ const tail = rest.slice(end + 1)
377
+ if (tail.startsWith(':')) portText = tail.slice(1)
378
+ else if (tail !== '') return undefined
379
+ } else {
380
+ const colon = rest.indexOf(':')
381
+ if (colon >= 0) {
382
+ host = rest.slice(0, colon)
383
+ portText = rest.slice(colon + 1)
384
+ }
385
+ }
386
+ if (host === '') return undefined
387
+ let port: number | undefined
388
+ if (portText !== undefined) {
389
+ port = Number(portText)
390
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined
391
+ }
392
+ return {
393
+ host,
394
+ ...(port !== undefined ? { port } : {}),
395
+ ...(user !== undefined && user !== '' ? { user } : {}),
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Resolve one ProxyJump spec: an alias configured in this plugin wins, and any
401
+ * other value is read as an OpenSSH address whose credentials come from the
402
+ * target entry (an ad-hoc hop has no stored auth of its own).
403
+ *
404
+ * An address hop deliberately carries no forwardAgent flag: OpenSSH's
405
+ * ForwardAgent is a per-Host setting and an ad-hoc address was never
406
+ * configured, so it must never inherit the target's opt-in. A hop written as
407
+ * an alias uses that alias's own entry, which is how a user forwards on a
408
+ * bastion on purpose.
409
+ */
410
+ export function resolveHop(engine: PoolEngine, entry: SshHostEntry, spec: string): SshHostEntry {
411
+ const configured = engine.store.find(spec)
412
+ if (configured !== undefined) return configured
413
+ const parsed = parseJumpSpec(spec)
414
+ if (parsed === undefined) {
415
+ throw new Error('proxyJump \'' + spec + '\' is neither a configured alias nor a [user@]host[:port] address')
416
+ }
417
+ const now = Date.now()
418
+ return {
419
+ alias: spec,
420
+ host: parsed.host,
421
+ port: parsed.port ?? 22,
422
+ user: parsed.user ?? process.env.USER ?? entry.user,
423
+ auth: entry.auth,
424
+ proxyJump: [],
425
+ tags: [],
426
+ createdAt: now,
427
+ updatedAt: now,
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Build one full jump chain for an entry: hop clients connected through in
433
+ * order, each forwarding a stream to the next destination, ending with the
434
+ * target client. Shared by the pool and standalone shell sessions.
435
+ *
436
+ * A ProxyCommand is the transport that reaches its own host, so the entry's
437
+ * own command seeds the chain when there is no jump chain, and the first hop's
438
+ * command is used when the hop carries one.
439
+ */
440
+ export async function connectChain(
441
+ engine: PoolEngine,
442
+ entry: SshHostEntry,
443
+ onKeyboardInteractive?: KeyboardInteractiveHandler,
444
+ ): Promise<{ client: Client; hops: Client[] }> {
445
+ const hops: Client[] = []
446
+ const chain = entry.proxyJump
447
+ // The store rejects both transports on one entry; a hand-edited store file
448
+ // can still carry both, and silently picking one would hide the mistake.
449
+ if (chain.length > 0 && entry.proxyCommand !== undefined) {
450
+ throw new Error('entry \'' + entry.alias + '\' declares both proxyCommand and proxyJump — pick one transport per host')
451
+ }
452
+ /** Transports this call started; destroyed on every failure path. */
453
+ const transports: Duplex[] = []
454
+ const startTransport = (owner: SshHostEntry): ConnectConfig['sock'] => {
455
+ const { stream } = startProxyCommand(owner.proxyCommand as string, proxyTargetOf(owner))
456
+ transports.push(stream)
457
+ return stream
458
+ }
459
+ let sock: ConnectConfig['sock'] = entry.proxyCommand !== undefined ? startTransport(entry) : undefined
460
+ try {
461
+ for (let index = 0; index < chain.length; index += 1) {
462
+ const spec = chain[index]
463
+ const hop = resolveHop(engine, entry, spec)
464
+ if (index > 0 && hop.proxyCommand !== undefined) {
465
+ throw new Error('proxyJump hop \'' + spec + '\' declares a proxyCommand, which is only supported on the first hop')
466
+ }
467
+ const hopSock = index === 0 && hop.proxyCommand !== undefined ? startTransport(hop) : sock
468
+ let hopClient: Client
469
+ try {
470
+ hopClient = await connectClient(buildConnectConfig(hop, hopSock, engine.opts), onKeyboardInteractive)
471
+ } catch (error) {
472
+ // Name the hop: an address hop (or a typo'd alias) must stay
473
+ // diagnosable from the error alone.
474
+ throw new Error('proxyJump hop \'' + spec + '\' (' + hop.user + '@' + hop.host + ':' + hop.port + '): '
475
+ + (error instanceof Error ? error.message : String(error)), { cause: error })
476
+ }
477
+ hops.push(hopClient)
478
+ const next = index + 1 < chain.length ? resolveHop(engine, entry, chain[index + 1]) : undefined
479
+ const nextHost = next !== undefined ? next.host : entry.host
480
+ const nextPort = next !== undefined ? next.port : entry.port
481
+ sock = await new Promise<ConnectConfig['sock']>((resolve, reject) => {
482
+ hopClient.forwardOut('127.0.0.1', 0, nextHost, nextPort, (error, stream) => {
483
+ if (error !== undefined) {
484
+ reject(new Error('proxyJump hop \'' + spec + '\' could not forward to ' + nextHost + ':' + nextPort + ': ' + error.message))
485
+ } else {
486
+ resolve(stream)
487
+ }
488
+ })
489
+ })
490
+ }
491
+ } catch (error) {
492
+ // A missing alias, a failed hop connect, or a failed forwardOut must all
493
+ // close the hops already connected — and the proxy commands behind them —
494
+ // so a failed ProxyJump never leaks either.
495
+ for (const client of hops) client.end()
496
+ for (const stream of transports) {
497
+ try { stream.destroy() } catch { /* already closed */ }
498
+ }
499
+ throw error
500
+ }
501
+ let target: Client | undefined
502
+ try {
503
+ target = await connectClient(buildConnectConfig(entry, sock, engine.opts), onKeyboardInteractive)
504
+ return { client: target, hops }
505
+ } catch (error) {
506
+ for (const client of hops) client.end()
507
+ for (const stream of transports) {
508
+ try { stream.destroy() } catch { /* already closed */ }
509
+ }
510
+ // connectClient already destroys the failed target on its own failure
511
+ // path; destroy defensively only when a reference leaked through, and
512
+ // guard it so a second destroy is never an issue.
513
+ if (target !== undefined) {
514
+ try { target.destroy() } catch { /* already destroyed */ }
515
+ }
516
+ throw error
517
+ }
518
+ }
519
+
520
+ /** Connect (or reuse) the pooled chain for one alias; pins nothing. */
521
+ export async function acquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
522
+ const pending = engine.acquireQueue.get(alias)
523
+ if (pending !== undefined) return pending
524
+ const task = doAcquire(engine, alias)
525
+ engine.acquireQueue.set(alias, task)
526
+ try {
527
+ return await task
528
+ } finally {
529
+ if (engine.acquireQueue.get(alias) === task) engine.acquireQueue.delete(alias)
530
+ }
531
+ }
532
+
533
+ async function doAcquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
534
+ const entry = engine.store.find(alias)
535
+ if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
536
+ const { client, hops } = await connectChain(engine, entry)
537
+ const record: PoolRecord = { client, hops, idleAt: Date.now(), pinned: false, broken: false, inFlight: 0 }
538
+ client.on('error', () => { record.broken = true })
539
+ client.on('close', () => { record.broken = true })
540
+ engine.pool.set(alias, record)
541
+ return record
542
+ }
543
+
544
+ /**
545
+ * Tear down one alias's record. When `record` is given and no longer the
546
+ * pooled record for the alias (a concurrent acquire replaced it), nothing
547
+ * is torn down — the connection belongs to someone else now.
548
+ */
549
+ export function disposeRecord(engine: PoolEngine, alias: string, record?: PoolRecord): void {
550
+ const current = engine.pool.get(alias)
551
+ if (record !== undefined && current !== record) return
552
+ if (current === undefined) return
553
+ engine.pool.delete(alias)
554
+ endRecordChain(current)
555
+ }
556
+
557
+ /** End one record's client and hop chain (best-effort, safe to repeat). */
558
+ export function endRecordChain(record: PoolRecord): void {
559
+ try { record.client.end() } catch { /* already closed */ }
560
+ for (const hop of record.hops) {
561
+ try { hop.end() } catch { /* already closed */ }
562
+ }
563
+ }
564
+
565
+ /** Close connections idle beyond the threshold (skips pinned and in-flight). */
566
+ export function sweepPool(engine: PoolEngine): void {
567
+ const cutoff = Date.now() - engine.opts.idleTimeoutMs
568
+ for (const [alias, record] of engine.pool) {
569
+ if (!record.pinned && record.inFlight === 0 && record.idleAt < cutoff) {
570
+ disposeRecord(engine, alias, record)
571
+ }
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Run `fn` with a live client for `alias`, reconnecting (up to the
577
+ * attempt budget) when the connection broke mid-flight.
578
+ */
579
+ export async function withClient<T>(engine: PoolEngine, alias: string, fn: (client: Client) => Promise<T>, attempts = 3, signal?: AbortSignal): Promise<T> {
580
+ let lastError: unknown
581
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
582
+ let record = engine.pool.get(alias)
583
+ if (record === undefined || record.broken) {
584
+ if (record !== undefined) disposeRecord(engine, alias, record)
585
+ record = await acquire(engine, alias)
586
+ }
587
+ record.idleAt = Date.now()
588
+ record.inFlight += 1
589
+ try {
590
+ const result = await fn(record.client)
591
+ record.idleAt = Date.now()
592
+ return result
593
+ } catch (error) {
594
+ lastError = error
595
+ // A cancelled call is never replayed: the caller asked for it to stop,
596
+ // and a retry would re-run a command that may not be idempotent.
597
+ if (signal?.aborted === true) throw error
598
+ // Retry only when the connection actually broke mid-flight: drop the
599
+ // corpse and let the next attempt reconnect (a reconnect may replay a
600
+ // non-idempotent command — the documented trade-off). A failure on a
601
+ // healthy connection is a logic error and is rethrown, not replayed.
602
+ if (!record.broken) throw error
603
+ disposeRecord(engine, alias, record)
604
+ } finally {
605
+ record.inFlight -= 1
606
+ }
607
+ }
608
+ throw lastError instanceof Error ? lastError : new Error(String(lastError))
609
+ }
610
+
611
+ /** Run one command on `alias` (reusing the pooled connection). */
612
+ export async function execCommand(engine: PoolEngine, alias: string, command: string, timeoutMs?: number, signal?: AbortSignal): Promise<ExecResult> {
613
+ const started = Date.now()
614
+ const budget = timeoutMs !== undefined && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs
615
+ return withClient(engine, alias, async (client) => {
616
+ return await new Promise<ExecResult>((resolve, reject) => {
617
+ // Caller cancellation is cooperative and quiescent: aborting closes the
618
+ // remote channel and settles this call like a timeout does, so the
619
+ // command stops without the pool replaying it. The channel is captured
620
+ // in a mutable slot because abort may fire before client.exec calls back.
621
+ let aborted = signal !== undefined && signal.aborted
622
+ let kill = (): void => { /* channel not open yet */ }
623
+ const onAbort = (): void => {
624
+ aborted = true
625
+ kill()
626
+ }
627
+ if (signal !== undefined && !signal.aborted) signal.addEventListener('abort', onAbort, { once: true })
628
+ client.exec(command, (error, stream) => {
629
+ if (error !== undefined) {
630
+ signal?.removeEventListener('abort', onAbort)
631
+ reject(error)
632
+ return
633
+ }
634
+ kill = (): void => {
635
+ try { stream.signal('KILL') } catch { /* channel gone */ }
636
+ try { stream.close() } catch { /* channel gone */ }
637
+ }
638
+ // The abort may already have arrived while this channel opened.
639
+ if (aborted) kill()
640
+ const stdout = { text: '', truncated: false }
641
+ const stderr = { text: '', truncated: false }
642
+ let timedOut = false
643
+ let settled = false
644
+ /** One cancelled outcome: the remote channel was killed on caller request. */
645
+ const cancelledResult = (): ExecResult => ({
646
+ success: false,
647
+ exitCode: null,
648
+ timedOut: false,
649
+ stdout: stdout.text,
650
+ stderr: stderr.text,
651
+ durationMs: Date.now() - started,
652
+ error: 'command cancelled by the caller',
653
+ })
654
+ const finish = (): void => {
655
+ if (settled) return
656
+ settled = true
657
+ clearTimeout(timer)
658
+ signal?.removeEventListener('abort', onAbort)
659
+ resolve({
660
+ success: false,
661
+ exitCode: null,
662
+ timedOut,
663
+ stdout: stdout.text,
664
+ stderr: stderr.text,
665
+ durationMs: Date.now() - started,
666
+ error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
667
+ })
668
+ }
669
+ const timer = setTimeout(() => {
670
+ timedOut = true
671
+ try { stream.signal('KILL') } catch { /* channel gone */ }
672
+ try { stream.close() } catch { /* channel gone */ }
673
+ // Hard deadline: settle now even if the peer never acks the
674
+ // channel close (the stream 'close' handler is then a no-op).
675
+ finish()
676
+ }, budget)
677
+ stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
678
+ stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
679
+ stream.on('close', (code: number | null) => {
680
+ if (settled) return
681
+ settled = true
682
+ clearTimeout(timer)
683
+ signal?.removeEventListener('abort', onAbort)
684
+ // A caller cancellation settles as cancelled, never as a broken
685
+ // connection: the latter would send withClient into a retry that
686
+ // re-runs a command the caller asked to stop.
687
+ if (aborted) {
688
+ resolve(cancelledResult())
689
+ return
690
+ }
691
+ if (typeof code !== 'number' && !timedOut) {
692
+ // The channel closed without an exit status: the connection
693
+ // dropped mid-flight. Reject so withClient can reconnect and
694
+ // retry within the attempt budget.
695
+ reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
696
+ return
697
+ }
698
+ resolve({
699
+ success: code === 0,
700
+ exitCode: code,
701
+ timedOut,
702
+ stdout: stdout.text,
703
+ stderr: stderr.text,
704
+ durationMs: Date.now() - started,
705
+ })
706
+ })
707
+ stream.on('error', (streamError: Error) => {
708
+ if (settled) return
709
+ settled = true
710
+ clearTimeout(timer)
711
+ signal?.removeEventListener('abort', onAbort)
712
+ if (aborted) {
713
+ resolve(cancelledResult())
714
+ return
715
+ }
716
+ reject(streamError)
717
+ })
718
+ })
719
+ })
720
+ })
721
+ }