@fish-under-sea/dsh-ssh-fish 0.0.0-stage → 1.0.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/LICENSE +202 -0
- package/NOTICE +23 -0
- package/README.en.md +29 -0
- package/README.i18n.yaml +6 -0
- package/README.md +28 -2
- package/README.zh.md +29 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +3 -0
- package/lib/client.js +16487 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +3511 -0
- package/lib/types/client/api.d.ts +141 -0
- package/lib/types/client/index.d.ts +37 -0
- package/lib/types/client/locales.d.ts +164 -0
- package/lib/types/client/native-panel.d.ts +70 -0
- package/lib/types/client/panel/ClusterTab.d.ts +7 -0
- package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
- package/lib/types/client/panel/HostsTab.d.ts +25 -0
- package/lib/types/client/panel/SshPanel.d.ts +14 -0
- package/lib/types/client/panel/TerminalTab.d.ts +22 -0
- package/lib/types/client/panel/TransferTab.d.ts +7 -0
- package/lib/types/client/panel/TunnelsTab.d.ts +19 -0
- package/lib/types/client/panel/controller.d.ts +89 -0
- package/lib/types/client/panel/helpers.d.ts +45 -0
- package/lib/types/client/panel/xterm.css.d.ts +2 -0
- package/lib/types/client/settings-binding.d.ts +61 -0
- package/lib/types/dsh-home.d.ts +16 -0
- package/lib/types/engine/cluster.d.ts +19 -0
- package/lib/types/engine/connection-pool.d.ts +112 -0
- package/lib/types/engine/proxy-command.d.ts +36 -0
- package/lib/types/engine/pty.d.ts +32 -0
- package/lib/types/engine/sftp.d.ts +20 -0
- package/lib/types/engine/terminal-sessions.d.ts +67 -0
- package/lib/types/engine/tunnel.d.ts +36 -0
- package/lib/types/engine.d.ts +89 -0
- package/lib/types/http.d.ts +59 -0
- package/lib/types/index.d.ts +83 -0
- package/lib/types/loopback.d.ts +24 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/lib/types/protocol.d.ts +239 -0
- package/lib/types/routes.d.ts +33 -0
- package/lib/types/ssh-config.d.ts +34 -0
- package/lib/types/store.d.ts +71 -0
- package/lib/types/tool-surface.d.ts +71 -0
- package/lib/types/tools.d.ts +42 -0
- package/package.json +109 -4
- package/src/client/api.ts +562 -0
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +137 -0
- package/src/client/locales.ts +338 -0
- package/src/client/native-panel.tsx +141 -0
- package/src/client/panel/ClusterTab.tsx +123 -0
- package/src/client/panel/HostFormDialog.tsx +258 -0
- package/src/client/panel/HostsTab.tsx +325 -0
- package/src/client/panel/SshPanel.tsx +90 -0
- package/src/client/panel/TerminalTab.tsx +330 -0
- package/src/client/panel/TransferTab.tsx +232 -0
- package/src/client/panel/TunnelsTab.tsx +244 -0
- package/src/client/panel/controller.ts +167 -0
- package/src/client/panel/helpers.ts +84 -0
- package/src/client/panel/panel.module.css +876 -0
- package/src/client/panel/xterm.css.ts +2 -0
- package/src/client/settings-binding.ts +165 -0
- package/src/dsh-home.ts +42 -0
- package/src/engine/cluster.ts +60 -0
- package/src/engine/connection-pool.ts +543 -0
- package/src/engine/proxy-command.ts +248 -0
- package/src/engine/pty.ts +78 -0
- package/src/engine/sftp.ts +226 -0
- package/src/engine/terminal-sessions.ts +280 -0
- package/src/engine/tunnel.ts +194 -0
- package/src/engine.ts +176 -0
- package/src/http.ts +127 -0
- package/src/index.ts +234 -0
- package/src/loopback.ts +63 -0
- package/src/mount-once.ts +142 -0
- package/src/protocol.ts +230 -0
- package/src/routes.ts +494 -0
- package/src/ssh-config.ts +153 -0
- package/src/store.ts +419 -0
- package/src/tool-surface.ts +95 -0
- package/src/tools.ts +404 -0
|
@@ -0,0 +1,543 @@
|
|
|
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
|
+
import { Client, type ConnectConfig } from 'ssh2'
|
|
9
|
+
import type { ExecResult, SshHostEntry } from '../protocol.ts'
|
|
10
|
+
import { expandHome, normalizeAgentPath, type HostStore } from '../store.ts'
|
|
11
|
+
import { startProxyCommand, type ProxyTarget } from './proxy-command.ts'
|
|
12
|
+
|
|
13
|
+
/** Default engine knobs. */
|
|
14
|
+
export interface EngineOptions {
|
|
15
|
+
/** Connections idle longer than this are closed (ms). */
|
|
16
|
+
idleTimeoutMs?: number
|
|
17
|
+
/** SSH handshake timeout (ms). */
|
|
18
|
+
connectTimeoutMs?: number
|
|
19
|
+
/** Keepalive ping interval (ms). */
|
|
20
|
+
keepaliveIntervalMs?: number
|
|
21
|
+
/** Cap on captured stdout/stderr bytes per exec (ms). */
|
|
22
|
+
maxOutputBytes?: number
|
|
23
|
+
/** Default exec timeout (ms). */
|
|
24
|
+
defaultExecTimeoutMs?: number
|
|
25
|
+
/** Default cluster concurrency. */
|
|
26
|
+
defaultMaxWorkers?: number
|
|
27
|
+
/** SFTP concurrent channel count for transfers. */
|
|
28
|
+
sftpConcurrency?: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Default engine knobs (applied when an option is omitted). */
|
|
32
|
+
export const DEFAULTS: Required<EngineOptions> = {
|
|
33
|
+
idleTimeoutMs: 30 * 60_000,
|
|
34
|
+
connectTimeoutMs: 15_000,
|
|
35
|
+
keepaliveIntervalMs: 15_000,
|
|
36
|
+
maxOutputBytes: 2 * 1024 * 1024,
|
|
37
|
+
defaultExecTimeoutMs: 60_000,
|
|
38
|
+
defaultMaxWorkers: 8,
|
|
39
|
+
sftpConcurrency: 8,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One pooled connection record. */
|
|
43
|
+
export interface PoolRecord {
|
|
44
|
+
client: Client
|
|
45
|
+
/** Jump-chain clients kept alive under the target. */
|
|
46
|
+
hops: Client[]
|
|
47
|
+
idleAt: number
|
|
48
|
+
/** Pinned connections (tunnels) are never swept. */
|
|
49
|
+
pinned: boolean
|
|
50
|
+
broken: boolean
|
|
51
|
+
/** Operations currently running on this connection (sweep guard). */
|
|
52
|
+
inFlight: number
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The slice of the engine the pool and exec paths need. The host class
|
|
57
|
+
* (engine.ts facade) satisfies this structurally.
|
|
58
|
+
*/
|
|
59
|
+
export interface PoolEngine {
|
|
60
|
+
readonly store: HostStore
|
|
61
|
+
readonly opts: Required<EngineOptions>
|
|
62
|
+
readonly pool: Map<string, PoolRecord>
|
|
63
|
+
readonly acquireQueue: Map<string, Promise<PoolRecord>>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Build the ssh2 connect config for one entry (key read from disk). */
|
|
67
|
+
export function buildConnectConfig(entry: SshHostEntry, sock: ConnectConfig['sock'] | undefined, opts: Required<EngineOptions>): ConnectConfig {
|
|
68
|
+
const config: ConnectConfig = {
|
|
69
|
+
host: entry.host,
|
|
70
|
+
port: entry.port,
|
|
71
|
+
username: entry.user,
|
|
72
|
+
readyTimeout: opts.connectTimeoutMs,
|
|
73
|
+
keepaliveInterval: opts.keepaliveIntervalMs,
|
|
74
|
+
keepaliveCountMax: 3,
|
|
75
|
+
tryKeyboard: true,
|
|
76
|
+
}
|
|
77
|
+
if (sock !== undefined) config.sock = sock
|
|
78
|
+
if (entry.auth.kind === 'password') {
|
|
79
|
+
config.password = entry.auth.password
|
|
80
|
+
} else if (entry.auth.kind === 'agent') {
|
|
81
|
+
const agentPath = resolveAgentPath(entry.auth.agentPath)
|
|
82
|
+
if (agentPath === undefined) {
|
|
83
|
+
throw new Error('ssh-agent is not available: set SSH_AUTH_SOCK or configure an agent path (use \'pageant\' for PuTTY Pageant on Windows)')
|
|
84
|
+
}
|
|
85
|
+
config.agent = agentPath
|
|
86
|
+
} else {
|
|
87
|
+
const keyPath = entry.auth.keyPath === undefined ? undefined : expandHome(entry.auth.keyPath)
|
|
88
|
+
if (keyPath === undefined || !existsSync(keyPath)) {
|
|
89
|
+
throw new Error('private key not found: ' + (entry.auth.keyPath ?? '(unset)'))
|
|
90
|
+
}
|
|
91
|
+
config.privateKey = readFileSync(keyPath, 'utf8')
|
|
92
|
+
if (entry.auth.passphrase !== undefined && entry.auth.passphrase !== '') {
|
|
93
|
+
config.passphrase = entry.auth.passphrase
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return config
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Resolve the ssh2 agent path for 'agent' auth. */
|
|
100
|
+
export function resolveAgentPath(agentPath?: string): string | undefined {
|
|
101
|
+
const explicit = normalizeAgentPath(agentPath)
|
|
102
|
+
if (explicit !== undefined) return explicit
|
|
103
|
+
const sock = process.env.SSH_AUTH_SOCK
|
|
104
|
+
if (sock !== undefined && sock !== '') return sock
|
|
105
|
+
if (process.platform === 'win32') return 'pageant'
|
|
106
|
+
return undefined
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Keyboard-interactive handler callback for 2FA / dynamic prompt flow. */
|
|
110
|
+
export type KeyboardInteractiveHandler = (
|
|
111
|
+
name: string,
|
|
112
|
+
instructions: string,
|
|
113
|
+
instructionsLang: string,
|
|
114
|
+
prompts: Array<{ prompt: string; echo: boolean }>,
|
|
115
|
+
finish: (responses: string[]) => void,
|
|
116
|
+
) => void
|
|
117
|
+
|
|
118
|
+
/** Connect one ssh2 client (resolve on ready, reject on error/close). */
|
|
119
|
+
export function connectClient(config: ConnectConfig, onKeyboardInteractive?: KeyboardInteractiveHandler): Promise<Client> {
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
const client = new Client()
|
|
122
|
+
let settled = false
|
|
123
|
+
const fail = (error: unknown): void => {
|
|
124
|
+
if (settled) return
|
|
125
|
+
settled = true
|
|
126
|
+
// A caller-supplied transport (a jump forwardOut stream or a
|
|
127
|
+
// ProxyCommand) must not outlive the client that failed to use it, or
|
|
128
|
+
// its child process leaks.
|
|
129
|
+
const sock = config.sock
|
|
130
|
+
if (sock !== undefined && typeof (sock as { destroy?: unknown }).destroy === 'function') {
|
|
131
|
+
try { (sock as { destroy: () => void }).destroy() } catch { /* already closed */ }
|
|
132
|
+
}
|
|
133
|
+
try { client.destroy() } catch { /* already closed */ }
|
|
134
|
+
reject(error instanceof Error ? error : new Error(String(error)))
|
|
135
|
+
}
|
|
136
|
+
client.once('ready', () => {
|
|
137
|
+
if (settled) return
|
|
138
|
+
settled = true
|
|
139
|
+
resolve(client)
|
|
140
|
+
})
|
|
141
|
+
client.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {
|
|
142
|
+
if (onKeyboardInteractive !== undefined) {
|
|
143
|
+
onKeyboardInteractive(name, instructions, instructionsLang, prompts.map(p => ({ prompt: p.prompt, echo: Boolean(p.echo) })), finish)
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
// Step 1: Automatic PAM password fallback: if a password is configured and all prompts ask for password
|
|
147
|
+
if (config.password !== undefined && prompts.length > 0 && prompts.every(p => /password/i.test(p.prompt))) {
|
|
148
|
+
finish(prompts.map(() => config.password as string))
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
fail(new Error('Authentication failed (keyboard-interactive): ' + (prompts.map(p => p.prompt.trim()).join(', ') || 'unsupported interactive challenge')))
|
|
152
|
+
})
|
|
153
|
+
// Keep an error listener attached after the handshake: when TCP connects
|
|
154
|
+
// but the handshake drops, ssh2 can emit a second 'error' after a single
|
|
155
|
+
// once-listener is gone, which would surface as an unhandled 'error' event.
|
|
156
|
+
// The settled guard turns later emissions into a no-op; other callers
|
|
157
|
+
// (like doAcquire) attach their own error listeners and all fire together.
|
|
158
|
+
client.on('error', fail)
|
|
159
|
+
try {
|
|
160
|
+
client.connect(config)
|
|
161
|
+
} catch (error) {
|
|
162
|
+
fail(error)
|
|
163
|
+
}
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Cap captured output at the configured byte budget (marks truncation). */
|
|
168
|
+
export function appendOutput(target: { text: string; truncated: boolean }, chunk: Buffer, maxBytes: number): void {
|
|
169
|
+
if (target.truncated) return
|
|
170
|
+
if (target.text.length + chunk.length > maxBytes) {
|
|
171
|
+
let cut = chunk.toString('utf8').slice(0, maxBytes - target.text.length)
|
|
172
|
+
// Never split a surrogate pair at the cut boundary.
|
|
173
|
+
if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1)
|
|
174
|
+
target.text += cut + '…[output truncated]'
|
|
175
|
+
target.truncated = true
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
target.text += chunk.toString('utf8')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The ProxyCommand token source for one entry. */
|
|
182
|
+
function proxyTargetOf(entry: SshHostEntry): ProxyTarget {
|
|
183
|
+
return { host: entry.host, port: entry.port, user: entry.user, alias: entry.alias }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Parse an OpenSSH jump hop written as an address: `[user@]host[:port]`
|
|
188
|
+
* (an IPv6 literal must be bracketed). Returns undefined when the value is not
|
|
189
|
+
* an address at all.
|
|
190
|
+
*/
|
|
191
|
+
export function parseJumpSpec(spec: string): { host: string; port?: number; user?: string } | undefined {
|
|
192
|
+
const trimmed = spec.trim()
|
|
193
|
+
if (trimmed === '') return undefined
|
|
194
|
+
const at = trimmed.lastIndexOf('@')
|
|
195
|
+
const user = at >= 0 ? trimmed.slice(0, at) : undefined
|
|
196
|
+
const rest = at >= 0 ? trimmed.slice(at + 1) : trimmed
|
|
197
|
+
if (rest === '') return undefined
|
|
198
|
+
let host = rest
|
|
199
|
+
let portText: string | undefined
|
|
200
|
+
if (rest.startsWith('[')) {
|
|
201
|
+
const end = rest.indexOf(']')
|
|
202
|
+
if (end < 0) return undefined
|
|
203
|
+
host = rest.slice(1, end)
|
|
204
|
+
const tail = rest.slice(end + 1)
|
|
205
|
+
if (tail.startsWith(':')) portText = tail.slice(1)
|
|
206
|
+
else if (tail !== '') return undefined
|
|
207
|
+
} else {
|
|
208
|
+
const colon = rest.indexOf(':')
|
|
209
|
+
if (colon >= 0) {
|
|
210
|
+
host = rest.slice(0, colon)
|
|
211
|
+
portText = rest.slice(colon + 1)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (host === '') return undefined
|
|
215
|
+
let port: number | undefined
|
|
216
|
+
if (portText !== undefined) {
|
|
217
|
+
port = Number(portText)
|
|
218
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
host,
|
|
222
|
+
...(port !== undefined ? { port } : {}),
|
|
223
|
+
...(user !== undefined && user !== '' ? { user } : {}),
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Resolve one ProxyJump spec: an alias configured in this plugin wins, and any
|
|
229
|
+
* other value is read as an OpenSSH address whose credentials come from the
|
|
230
|
+
* target entry (an ad-hoc hop has no stored auth of its own).
|
|
231
|
+
*/
|
|
232
|
+
export function resolveHop(engine: PoolEngine, entry: SshHostEntry, spec: string): SshHostEntry {
|
|
233
|
+
const configured = engine.store.find(spec)
|
|
234
|
+
if (configured !== undefined) return configured
|
|
235
|
+
const parsed = parseJumpSpec(spec)
|
|
236
|
+
if (parsed === undefined) {
|
|
237
|
+
throw new Error('proxyJump \'' + spec + '\' is neither a configured alias nor a [user@]host[:port] address')
|
|
238
|
+
}
|
|
239
|
+
const now = Date.now()
|
|
240
|
+
return {
|
|
241
|
+
alias: spec,
|
|
242
|
+
host: parsed.host,
|
|
243
|
+
port: parsed.port ?? 22,
|
|
244
|
+
user: parsed.user ?? process.env.USER ?? entry.user,
|
|
245
|
+
auth: entry.auth,
|
|
246
|
+
proxyJump: [],
|
|
247
|
+
tags: [],
|
|
248
|
+
createdAt: now,
|
|
249
|
+
updatedAt: now,
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Build one full jump chain for an entry: hop clients connected through in
|
|
255
|
+
* order, each forwarding a stream to the next destination, ending with the
|
|
256
|
+
* target client. Shared by the pool and standalone shell sessions.
|
|
257
|
+
*
|
|
258
|
+
* A ProxyCommand is the transport that reaches its own host, so the entry's
|
|
259
|
+
* own command seeds the chain when there is no jump chain, and the first hop's
|
|
260
|
+
* command is used when the hop carries one.
|
|
261
|
+
*/
|
|
262
|
+
export async function connectChain(
|
|
263
|
+
engine: PoolEngine,
|
|
264
|
+
entry: SshHostEntry,
|
|
265
|
+
onKeyboardInteractive?: KeyboardInteractiveHandler,
|
|
266
|
+
): Promise<{ client: Client; hops: Client[] }> {
|
|
267
|
+
const hops: Client[] = []
|
|
268
|
+
const chain = entry.proxyJump
|
|
269
|
+
// The store rejects both transports on one entry; a hand-edited store file
|
|
270
|
+
// can still carry both, and silently picking one would hide the mistake.
|
|
271
|
+
if (chain.length > 0 && entry.proxyCommand !== undefined) {
|
|
272
|
+
throw new Error('entry \'' + entry.alias + '\' declares both proxyCommand and proxyJump — pick one transport per host')
|
|
273
|
+
}
|
|
274
|
+
/** Transports this call started; destroyed on every failure path. */
|
|
275
|
+
const transports: Duplex[] = []
|
|
276
|
+
const startTransport = (owner: SshHostEntry): ConnectConfig['sock'] => {
|
|
277
|
+
const { stream } = startProxyCommand(owner.proxyCommand as string, proxyTargetOf(owner))
|
|
278
|
+
transports.push(stream)
|
|
279
|
+
return stream
|
|
280
|
+
}
|
|
281
|
+
let sock: ConnectConfig['sock'] = entry.proxyCommand !== undefined ? startTransport(entry) : undefined
|
|
282
|
+
try {
|
|
283
|
+
for (let index = 0; index < chain.length; index += 1) {
|
|
284
|
+
const spec = chain[index]
|
|
285
|
+
const hop = resolveHop(engine, entry, spec)
|
|
286
|
+
if (index > 0 && hop.proxyCommand !== undefined) {
|
|
287
|
+
throw new Error('proxyJump hop \'' + spec + '\' declares a proxyCommand, which is only supported on the first hop')
|
|
288
|
+
}
|
|
289
|
+
const hopSock = index === 0 && hop.proxyCommand !== undefined ? startTransport(hop) : sock
|
|
290
|
+
let hopClient: Client
|
|
291
|
+
try {
|
|
292
|
+
hopClient = await connectClient(buildConnectConfig(hop, hopSock, engine.opts), onKeyboardInteractive)
|
|
293
|
+
} catch (error) {
|
|
294
|
+
// Name the hop: an address hop (or a typo'd alias) must stay
|
|
295
|
+
// diagnosable from the error alone.
|
|
296
|
+
throw new Error('proxyJump hop \'' + spec + '\' (' + hop.user + '@' + hop.host + ':' + hop.port + '): '
|
|
297
|
+
+ (error instanceof Error ? error.message : String(error)))
|
|
298
|
+
}
|
|
299
|
+
hops.push(hopClient)
|
|
300
|
+
const next = index + 1 < chain.length ? resolveHop(engine, entry, chain[index + 1]) : undefined
|
|
301
|
+
const nextHost = next !== undefined ? next.host : entry.host
|
|
302
|
+
const nextPort = next !== undefined ? next.port : entry.port
|
|
303
|
+
sock = await new Promise<ConnectConfig['sock']>((resolve, reject) => {
|
|
304
|
+
hopClient.forwardOut('127.0.0.1', 0, nextHost, nextPort, (error, stream) => {
|
|
305
|
+
if (error !== undefined) {
|
|
306
|
+
reject(new Error('proxyJump hop \'' + spec + '\' could not forward to ' + nextHost + ':' + nextPort + ': ' + error.message))
|
|
307
|
+
} else {
|
|
308
|
+
resolve(stream)
|
|
309
|
+
}
|
|
310
|
+
})
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
} catch (error) {
|
|
314
|
+
// A missing alias, a failed hop connect, or a failed forwardOut must all
|
|
315
|
+
// close the hops already connected — and the proxy commands behind them —
|
|
316
|
+
// so a failed ProxyJump never leaks either.
|
|
317
|
+
for (const client of hops) client.end()
|
|
318
|
+
for (const stream of transports) {
|
|
319
|
+
try { stream.destroy() } catch { /* already closed */ }
|
|
320
|
+
}
|
|
321
|
+
throw error
|
|
322
|
+
}
|
|
323
|
+
let target: Client | undefined
|
|
324
|
+
try {
|
|
325
|
+
target = await connectClient(buildConnectConfig(entry, sock, engine.opts), onKeyboardInteractive)
|
|
326
|
+
return { client: target, hops }
|
|
327
|
+
} catch (error) {
|
|
328
|
+
for (const client of hops) client.end()
|
|
329
|
+
for (const stream of transports) {
|
|
330
|
+
try { stream.destroy() } catch { /* already closed */ }
|
|
331
|
+
}
|
|
332
|
+
// connectClient already destroys the failed target on its own failure
|
|
333
|
+
// path; destroy defensively only when a reference leaked through, and
|
|
334
|
+
// guard it so a second destroy is never an issue.
|
|
335
|
+
if (target !== undefined) {
|
|
336
|
+
try { target.destroy() } catch { /* already destroyed */ }
|
|
337
|
+
}
|
|
338
|
+
throw error
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Connect (or reuse) the pooled chain for one alias; pins nothing. */
|
|
343
|
+
export async function acquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
|
|
344
|
+
const pending = engine.acquireQueue.get(alias)
|
|
345
|
+
if (pending !== undefined) return pending
|
|
346
|
+
const task = doAcquire(engine, alias)
|
|
347
|
+
engine.acquireQueue.set(alias, task)
|
|
348
|
+
try {
|
|
349
|
+
return await task
|
|
350
|
+
} finally {
|
|
351
|
+
if (engine.acquireQueue.get(alias) === task) engine.acquireQueue.delete(alias)
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function doAcquire(engine: PoolEngine, alias: string): Promise<PoolRecord> {
|
|
356
|
+
const entry = engine.store.find(alias)
|
|
357
|
+
if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
|
|
358
|
+
const { client, hops } = await connectChain(engine, entry)
|
|
359
|
+
const record: PoolRecord = { client, hops, idleAt: Date.now(), pinned: false, broken: false, inFlight: 0 }
|
|
360
|
+
client.on('error', () => { record.broken = true })
|
|
361
|
+
client.on('close', () => { record.broken = true })
|
|
362
|
+
engine.pool.set(alias, record)
|
|
363
|
+
return record
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Tear down one alias's record. When `record` is given and no longer the
|
|
368
|
+
* pooled record for the alias (a concurrent acquire replaced it), nothing
|
|
369
|
+
* is torn down — the connection belongs to someone else now.
|
|
370
|
+
*/
|
|
371
|
+
export function disposeRecord(engine: PoolEngine, alias: string, record?: PoolRecord): void {
|
|
372
|
+
const current = engine.pool.get(alias)
|
|
373
|
+
if (record !== undefined && current !== record) return
|
|
374
|
+
if (current === undefined) return
|
|
375
|
+
engine.pool.delete(alias)
|
|
376
|
+
endRecordChain(current)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** End one record's client and hop chain (best-effort, safe to repeat). */
|
|
380
|
+
export function endRecordChain(record: PoolRecord): void {
|
|
381
|
+
try { record.client.end() } catch { /* already closed */ }
|
|
382
|
+
for (const hop of record.hops) {
|
|
383
|
+
try { hop.end() } catch { /* already closed */ }
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Close connections idle beyond the threshold (skips pinned and in-flight). */
|
|
388
|
+
export function sweepPool(engine: PoolEngine): void {
|
|
389
|
+
const cutoff = Date.now() - engine.opts.idleTimeoutMs
|
|
390
|
+
for (const [alias, record] of engine.pool) {
|
|
391
|
+
if (!record.pinned && record.inFlight === 0 && record.idleAt < cutoff) {
|
|
392
|
+
disposeRecord(engine, alias, record)
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Run `fn` with a live client for `alias`, reconnecting (up to the
|
|
399
|
+
* attempt budget) when the connection broke mid-flight.
|
|
400
|
+
*/
|
|
401
|
+
export async function withClient<T>(engine: PoolEngine, alias: string, fn: (client: Client) => Promise<T>, attempts = 3, signal?: AbortSignal): Promise<T> {
|
|
402
|
+
let lastError: unknown
|
|
403
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
404
|
+
let record = engine.pool.get(alias)
|
|
405
|
+
if (record === undefined || record.broken) {
|
|
406
|
+
if (record !== undefined) disposeRecord(engine, alias, record)
|
|
407
|
+
record = await acquire(engine, alias)
|
|
408
|
+
}
|
|
409
|
+
record.idleAt = Date.now()
|
|
410
|
+
record.inFlight += 1
|
|
411
|
+
try {
|
|
412
|
+
const result = await fn(record.client)
|
|
413
|
+
record.idleAt = Date.now()
|
|
414
|
+
return result
|
|
415
|
+
} catch (error) {
|
|
416
|
+
lastError = error
|
|
417
|
+
// A cancelled call is never replayed: the caller asked for it to stop,
|
|
418
|
+
// and a retry would re-run a command that may not be idempotent.
|
|
419
|
+
if (signal?.aborted === true) throw error
|
|
420
|
+
// Retry only when the connection actually broke mid-flight: drop the
|
|
421
|
+
// corpse and let the next attempt reconnect (a reconnect may replay a
|
|
422
|
+
// non-idempotent command — the documented trade-off). A failure on a
|
|
423
|
+
// healthy connection is a logic error and is rethrown, not replayed.
|
|
424
|
+
if (!record.broken) throw error
|
|
425
|
+
disposeRecord(engine, alias, record)
|
|
426
|
+
} finally {
|
|
427
|
+
record.inFlight -= 1
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError))
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** Run one command on `alias` (reusing the pooled connection). */
|
|
434
|
+
export async function execCommand(engine: PoolEngine, alias: string, command: string, timeoutMs?: number, signal?: AbortSignal): Promise<ExecResult> {
|
|
435
|
+
const started = Date.now()
|
|
436
|
+
const budget = timeoutMs !== undefined && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs
|
|
437
|
+
return withClient(engine, alias, async (client) => {
|
|
438
|
+
return await new Promise<ExecResult>((resolve, reject) => {
|
|
439
|
+
// Caller cancellation is cooperative and quiescent: aborting closes the
|
|
440
|
+
// remote channel and settles this call like a timeout does, so the
|
|
441
|
+
// command stops without the pool replaying it. The channel is captured
|
|
442
|
+
// in a mutable slot because abort may fire before client.exec calls back.
|
|
443
|
+
let aborted = signal !== undefined && signal.aborted
|
|
444
|
+
let kill = (): void => { /* channel not open yet */ }
|
|
445
|
+
const onAbort = (): void => {
|
|
446
|
+
aborted = true
|
|
447
|
+
kill()
|
|
448
|
+
}
|
|
449
|
+
if (signal !== undefined && !signal.aborted) signal.addEventListener('abort', onAbort, { once: true })
|
|
450
|
+
client.exec(command, (error, stream) => {
|
|
451
|
+
if (error !== undefined) {
|
|
452
|
+
signal?.removeEventListener('abort', onAbort)
|
|
453
|
+
reject(error)
|
|
454
|
+
return
|
|
455
|
+
}
|
|
456
|
+
kill = (): void => {
|
|
457
|
+
try { stream.signal('KILL') } catch { /* channel gone */ }
|
|
458
|
+
try { stream.close() } catch { /* channel gone */ }
|
|
459
|
+
}
|
|
460
|
+
// The abort may already have arrived while this channel opened.
|
|
461
|
+
if (aborted) kill()
|
|
462
|
+
const stdout = { text: '', truncated: false }
|
|
463
|
+
const stderr = { text: '', truncated: false }
|
|
464
|
+
let timedOut = false
|
|
465
|
+
let settled = false
|
|
466
|
+
/** One cancelled outcome: the remote channel was killed on caller request. */
|
|
467
|
+
const cancelledResult = (): ExecResult => ({
|
|
468
|
+
success: false,
|
|
469
|
+
exitCode: null,
|
|
470
|
+
timedOut: false,
|
|
471
|
+
stdout: stdout.text,
|
|
472
|
+
stderr: stderr.text,
|
|
473
|
+
durationMs: Date.now() - started,
|
|
474
|
+
error: 'command cancelled by the caller',
|
|
475
|
+
})
|
|
476
|
+
const finish = (): void => {
|
|
477
|
+
if (settled) return
|
|
478
|
+
settled = true
|
|
479
|
+
clearTimeout(timer)
|
|
480
|
+
signal?.removeEventListener('abort', onAbort)
|
|
481
|
+
resolve({
|
|
482
|
+
success: false,
|
|
483
|
+
exitCode: null,
|
|
484
|
+
timedOut,
|
|
485
|
+
stdout: stdout.text,
|
|
486
|
+
stderr: stderr.text,
|
|
487
|
+
durationMs: Date.now() - started,
|
|
488
|
+
error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
|
|
489
|
+
})
|
|
490
|
+
}
|
|
491
|
+
const timer = setTimeout(() => {
|
|
492
|
+
timedOut = true
|
|
493
|
+
try { stream.signal('KILL') } catch { /* channel gone */ }
|
|
494
|
+
try { stream.close() } catch { /* channel gone */ }
|
|
495
|
+
// Hard deadline: settle now even if the peer never acks the
|
|
496
|
+
// channel close (the stream 'close' handler is then a no-op).
|
|
497
|
+
finish()
|
|
498
|
+
}, budget)
|
|
499
|
+
stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
|
|
500
|
+
stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
|
|
501
|
+
stream.on('close', (code: number | null) => {
|
|
502
|
+
if (settled) return
|
|
503
|
+
settled = true
|
|
504
|
+
clearTimeout(timer)
|
|
505
|
+
signal?.removeEventListener('abort', onAbort)
|
|
506
|
+
// A caller cancellation settles as cancelled, never as a broken
|
|
507
|
+
// connection: the latter would send withClient into a retry that
|
|
508
|
+
// re-runs a command the caller asked to stop.
|
|
509
|
+
if (aborted) {
|
|
510
|
+
resolve(cancelledResult())
|
|
511
|
+
return
|
|
512
|
+
}
|
|
513
|
+
if (typeof code !== 'number' && !timedOut) {
|
|
514
|
+
// The channel closed without an exit status: the connection
|
|
515
|
+
// dropped mid-flight. Reject so withClient can reconnect and
|
|
516
|
+
// retry within the attempt budget.
|
|
517
|
+
reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
resolve({
|
|
521
|
+
success: code === 0,
|
|
522
|
+
exitCode: code,
|
|
523
|
+
timedOut,
|
|
524
|
+
stdout: stdout.text,
|
|
525
|
+
stderr: stderr.text,
|
|
526
|
+
durationMs: Date.now() - started,
|
|
527
|
+
})
|
|
528
|
+
})
|
|
529
|
+
stream.on('error', (streamError: Error) => {
|
|
530
|
+
if (settled) return
|
|
531
|
+
settled = true
|
|
532
|
+
clearTimeout(timer)
|
|
533
|
+
signal?.removeEventListener('abort', onAbort)
|
|
534
|
+
if (aborted) {
|
|
535
|
+
resolve(cancelledResult())
|
|
536
|
+
return
|
|
537
|
+
}
|
|
538
|
+
reject(streamError)
|
|
539
|
+
})
|
|
540
|
+
})
|
|
541
|
+
})
|
|
542
|
+
})
|
|
543
|
+
}
|