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,248 @@
1
+ /**
2
+ * OpenSSH-compatible ProxyCommand transport: run the command with the user's
3
+ * shell and expose its stdio as a Duplex that ssh2 accepts as `sock`.
4
+ *
5
+ * The command comes verbatim from the user's own 0600 store file and runs with
6
+ * the DSH host process's privileges — the same trust the `ssh(1)` client gives
7
+ * the identical line in `~/.ssh/config`.
8
+ */
9
+
10
+ import { spawn, type ChildProcess } from 'node:child_process'
11
+ import { Duplex } from 'node:stream'
12
+
13
+ /** Token source for one host: the values %h / %p / %r / %n expand to. */
14
+ export interface ProxyTarget {
15
+ host: string
16
+ port: number
17
+ user: string
18
+ /** The name the user addresses this host by (OpenSSH's %n). */
19
+ alias: string
20
+ }
21
+
22
+ /** Captured stderr budget carried into the failure message (characters). */
23
+ const MAX_STDERR = 4096
24
+
25
+ /** How long a killed proxy command may linger before SIGKILL (ms). */
26
+ const KILL_GRACE_MS = 2_000
27
+
28
+ /** Expand the OpenSSH ProxyCommand tokens; unknown %X sequences stay verbatim. */
29
+ export function expandProxyTokens(command: string, target: ProxyTarget): string {
30
+ return command.replace(/%[hprn%]/g, token => {
31
+ switch (token) {
32
+ case '%h': return target.host
33
+ case '%p': return String(target.port)
34
+ case '%r': return target.user
35
+ case '%n': return target.alias
36
+ default: return '%'
37
+ }
38
+ })
39
+ }
40
+
41
+ /** One spawn specification: the user's shell plus the platform quoting. */
42
+ interface SpawnSpec {
43
+ file: string
44
+ args: string[]
45
+ /** cmd.exe needs the command quoted verbatim (Node's own shell recipe). */
46
+ windowsVerbatimArguments?: boolean
47
+ }
48
+
49
+ /**
50
+ * The shell OpenSSH itself would use on this platform: the user's shell with
51
+ * `-c` on POSIX, cmd.exe on Windows (where the whole command must stay one
52
+ * verbatim argument, exactly as Node's own `shell: true` does it).
53
+ */
54
+ function spawnSpec(command: string): SpawnSpec {
55
+ if (process.platform === 'win32') {
56
+ return {
57
+ file: process.env.ComSpec ?? 'cmd.exe',
58
+ args: ['/d', '/s', '/c', '"' + command + '"'],
59
+ windowsVerbatimArguments: true,
60
+ }
61
+ }
62
+ return { file: process.env.SHELL ?? '/bin/sh', args: ['-c', command] }
63
+ }
64
+
65
+ /** One running proxy command: its transport plus the process behind it. */
66
+ export interface ProxyCommandProcess {
67
+ /** The duplex transport handed to ssh2 as `sock`. */
68
+ stream: Duplex
69
+ /** The spawned shell; killing the stream kills it (and its process group). */
70
+ child: ChildProcess
71
+ }
72
+
73
+ /**
74
+ * Start one ProxyCommand and bridge its stdio into a Duplex.
75
+ *
76
+ * Failure modes are reported through the stream: a spawn error, or an exit
77
+ * before the SSH handshake finished, destroys it with the exit status and the
78
+ * tail of the command's stderr instead of letting ssh2 wait for its own
79
+ * `readyTimeout`.
80
+ */
81
+ export function startProxyCommand(rawCommand: string, target: ProxyTarget): ProxyCommandProcess {
82
+ const command = expandProxyTokens(rawCommand, target)
83
+ const spec = spawnSpec(command)
84
+ const child = spawn(spec.file, spec.args, {
85
+ stdio: ['pipe', 'pipe', 'pipe'],
86
+ windowsHide: true,
87
+ ...(spec.windowsVerbatimArguments === true ? { windowsVerbatimArguments: true } : {}),
88
+ // POSIX only: own process group, so a chained client
89
+ // (`ssh -W %h:%p bastion`) dies with the transport instead of leaking.
90
+ ...(process.platform === 'win32' ? {} : { detached: true }),
91
+ })
92
+
93
+ let stderr = ''
94
+ child.stderr?.on('data', (chunk: Buffer) => {
95
+ stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR)
96
+ })
97
+
98
+ let killed = false
99
+ const kill = (): void => {
100
+ if (killed) return
101
+ killed = true
102
+ const pid = child.pid
103
+ const group = process.platform !== 'win32' && pid !== undefined
104
+ try {
105
+ if (group) process.kill(-pid, 'SIGTERM')
106
+ else child.kill()
107
+ } catch { /* already gone */ }
108
+ const escalate = setTimeout(() => {
109
+ try {
110
+ if (group) process.kill(-pid, 'SIGKILL')
111
+ else child.kill('SIGKILL')
112
+ } catch { /* already gone */ }
113
+ }, KILL_GRACE_MS)
114
+ escalate.unref()
115
+ }
116
+
117
+ function formatExitError(code: number | null, signal: NodeJS.Signals | null, stderrDetail: string): Error {
118
+ const status = signal !== null ? 'signal ' + signal : 'code ' + String(code ?? 'unknown')
119
+ const detail = stderrDetail.trim()
120
+ return new Error('ProxyCommand exited (' + status + ')' + (detail === '' ? '' : ': ' + detail))
121
+ }
122
+
123
+ const stream = new Duplex({
124
+ read() {
125
+ child.stdout?.resume()
126
+ },
127
+ write(chunk, _encoding, callback) {
128
+ const stdin = child.stdin
129
+ if (stream.destroyed || stdin === null || stdin.destroyed) {
130
+ callback(new Error('ProxyCommand stdin is already closed'))
131
+ return
132
+ }
133
+ stdin.write(chunk, (err) => {
134
+ if (!err) {
135
+ callback()
136
+ return
137
+ }
138
+ if ((child.exitCode !== null && child.exitCode !== 0) || child.signalCode !== null) {
139
+ const exitErr = formatExitError(child.exitCode, child.signalCode, stderr)
140
+ fail(exitErr)
141
+ callback(exitErr)
142
+ return
143
+ }
144
+ let resolved = false
145
+ const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
146
+ if (resolved) return
147
+ resolved = true
148
+ clearTimeout(timer)
149
+ const exitErr = (code !== null && code !== 0) || signal !== null
150
+ ? formatExitError(code, signal, stderr)
151
+ : new Error('ProxyCommand transport write failed: ' + err.message)
152
+ fail(exitErr)
153
+ callback(exitErr)
154
+ }
155
+ const timer = setTimeout(() => {
156
+ if (resolved) return
157
+ resolved = true
158
+ child.removeListener('exit', onExit)
159
+ const transportErr = new Error('ProxyCommand transport write failed: ' + err.message)
160
+ fail(transportErr)
161
+ callback(transportErr)
162
+ }, 200)
163
+ timer.unref()
164
+ child.once('exit', onExit)
165
+ })
166
+ },
167
+ final(callback) {
168
+ const stdin = child.stdin
169
+ if (stdin === null || stdin.destroyed) {
170
+ callback()
171
+ return
172
+ }
173
+ stdin.end((err?: Error | null) => {
174
+ if (err) callback(new Error('ProxyCommand transport close failed: ' + err.message))
175
+ else callback()
176
+ })
177
+ },
178
+ destroy(error, callback) {
179
+ kill()
180
+ callback(error)
181
+ },
182
+ })
183
+
184
+ // ssh2 attaches its own error handling once it owns the socket; this listener
185
+ // only guarantees an 'error' emitted before that never reaches the host
186
+ // process as an unhandled event.
187
+ stream.on('error', () => { /* surfaced through the ssh2 client */ })
188
+
189
+ let failed = false
190
+ const fail = (error: Error): void => {
191
+ if (failed || stream.destroyed) return
192
+ failed = true
193
+ stream.destroy(error)
194
+ }
195
+
196
+ // The transport only reports a clean EOF once BOTH the stdout pipe ended and
197
+ // the process exited successfully: a command that dies (bastion client down,
198
+ // typo, refused connection) must surface its own exit status and stderr
199
+ // instead of the generic "connection lost before handshake" ssh2 produces
200
+ // for a socket that simply closed.
201
+ let stdoutEnded = false
202
+ let exited = false
203
+ const finishIfClean = (): void => {
204
+ if (exited && stdoutEnded && !failed && !stream.destroyed) stream.push(null)
205
+ }
206
+
207
+ child.stdout?.on('data', (chunk: Buffer) => {
208
+ if (stream.push(chunk) === false) child.stdout?.pause()
209
+ })
210
+ child.stdout?.on('end', () => {
211
+ stdoutEnded = true
212
+ finishIfClean()
213
+ })
214
+ child.stdout?.on('error', (error: Error) => {
215
+ fail(new Error('ProxyCommand stdout error: ' + error.message))
216
+ })
217
+ child.stdin?.on('error', (error: Error) => {
218
+ // A broken pipe (EPIPE) on stdin occurs naturally when the proxy command
219
+ // exits early or closes its standard input. Prevent unhandled EventEmitter errors.
220
+ if ((child.exitCode !== null && child.exitCode !== 0) || child.signalCode !== null) {
221
+ fail(formatExitError(child.exitCode, child.signalCode, stderr))
222
+ return
223
+ }
224
+ const timer = setTimeout(() => {
225
+ fail(new Error('ProxyCommand transport error: ' + error.message))
226
+ }, 200)
227
+ timer.unref()
228
+ child.once('exit', (code, signal) => {
229
+ clearTimeout(timer)
230
+ if ((code !== null && code !== 0) || signal !== null) {
231
+ fail(formatExitError(code, signal, stderr))
232
+ }
233
+ })
234
+ })
235
+ child.on('error', (error: Error) => {
236
+ fail(new Error('ProxyCommand could not start: ' + error.message))
237
+ })
238
+ child.on('exit', (code, signal) => {
239
+ exited = true
240
+ if ((code !== null && code !== 0) || signal !== null) {
241
+ fail(formatExitError(code, signal, stderr))
242
+ return
243
+ }
244
+ finishIfClean()
245
+ })
246
+
247
+ return { stream, child }
248
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * PTY shell sessions for the web terminal: a standalone (non-pooled)
3
+ * ssh2 connection with a long-lived shell channel, resize, and pausable
4
+ * output delivery.
5
+ */
6
+
7
+ import { connectChain, type KeyboardInteractiveHandler, type PoolEngine } from './connection-pool.ts'
8
+
9
+ /** A live PTY shell session. */
10
+ export interface ShellSession {
11
+ /** Assign to receive remote output. */
12
+ onData?: (data: Buffer) => void
13
+ /** Assign to be notified when the channel closes. */
14
+ onExit?: (code: number | null, error?: string) => void
15
+ /** Write raw input to the shell. */
16
+ send(data: string): void
17
+ /** Resize the remote PTY. */
18
+ resize(cols: number, rows: number): void
19
+ /** Close the session and its channel. */
20
+ close(): void
21
+ /** Pause remote output delivery (transport backpressure). */
22
+ pause(): void
23
+ /** Resume remote output delivery. */
24
+ resume(): void
25
+ }
26
+
27
+ /**
28
+ * Open a PTY shell session for the web terminal (standalone connection).
29
+ * The shell is a long-lived exclusive stream: it uses its own connection so
30
+ * closing it can never tear down a pooled exec/tunnel sharing the alias.
31
+ */
32
+ export async function openShell(
33
+ engine: PoolEngine,
34
+ alias: string,
35
+ size: { cols: number; rows: number },
36
+ onKeyboardInteractive?: KeyboardInteractiveHandler,
37
+ ): Promise<ShellSession> {
38
+ const entry = engine.store.find(alias)
39
+ if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
40
+ const { client, hops } = await connectChain(engine, entry, onKeyboardInteractive)
41
+ return await new Promise<ShellSession>((resolve, reject) => {
42
+ client.shell({ term: 'xterm-256color', cols: size.cols, rows: size.rows }, (error, stream) => {
43
+ if (error !== undefined) {
44
+ try { client.end() } catch { /* closed */ }
45
+ for (const hop of hops) { try { hop.end() } catch { /* closed */ } }
46
+ reject(error)
47
+ return
48
+ }
49
+ let tornDown = false
50
+ const teardown = (): void => {
51
+ if (tornDown) return
52
+ tornDown = true
53
+ try { client.end() } catch { /* closed */ }
54
+ for (const hop of hops) { try { hop.end() } catch { /* closed */ } }
55
+ }
56
+ const session: ShellSession = {
57
+ send: (data) => { try { stream.write(data) } catch { /* channel gone */ } },
58
+ resize: (cols, rows) => { try { stream.setWindow(rows, cols, rows, cols) } catch { /* channel gone */ } },
59
+ close: () => {
60
+ try { stream.close() } catch { /* channel gone */ }
61
+ teardown()
62
+ },
63
+ pause: () => { try { stream.pause() } catch { /* channel gone */ } },
64
+ resume: () => { try { stream.resume() } catch { /* channel gone */ } },
65
+ }
66
+ stream.on('data', (chunk: Buffer) => { session.onData?.(chunk) })
67
+ stream.on('close', (code: number | null) => {
68
+ teardown()
69
+ session.onExit?.(code)
70
+ })
71
+ stream.on('error', (streamError: Error) => {
72
+ teardown()
73
+ session.onExit?.(null, streamError instanceof Error ? streamError.message : String(streamError))
74
+ })
75
+ resolve(session)
76
+ })
77
+ })
78
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * SFTP transfers: upload (file or recursive tree), single-file download, and
3
+ * remote directory listing. Every channel is opened once per operation and
4
+ * released exactly once so sshd's MaxSessions cap is never exhausted.
5
+ */
6
+
7
+ import { existsSync, lstatSync, mkdirSync, readdirSync, statSync } from 'node:fs'
8
+ import { dirname, join, relative, resolve as resolvePath } from 'node:path'
9
+ // Type-only: this module never constructs a Client, so it must not emit a
10
+ // runtime import of the CJS package (see connection-pool.ts for why a named
11
+ // value import of ssh2 does not survive bundling).
12
+ import type { Client, SFTPWrapper } from 'ssh2'
13
+ import type { RemoteDirEntry, TransferProgress } from '../protocol.ts'
14
+ import { withClient, type PoolEngine } from './connection-pool.ts'
15
+
16
+ /** Walk a local directory, collecting relative paths of every file. */
17
+ export function walkLocalDir(root: string): string[] {
18
+ const files: string[] = []
19
+ const visit = (dir: string): void => {
20
+ for (const name of readdirSync(dir)) {
21
+ const full = join(dir, name)
22
+ // lstat, not stat: a symlink must never be followed — a link cycle
23
+ // (ln -s . self) recurses forever under stat, and a link to a file
24
+ // would silently upload the target's bytes.
25
+ const stat = lstatSync(full)
26
+ if (stat.isSymbolicLink()) continue
27
+ if (stat.isDirectory()) visit(full)
28
+ else if (stat.isFile()) files.push(relative(root, full).replaceAll('\\', '/'))
29
+ }
30
+ }
31
+ visit(root)
32
+ return files
33
+ }
34
+
35
+ /** Upload one local file (or directory tree) to a remote path. */
36
+ export async function upload(
37
+ engine: PoolEngine,
38
+ alias: string,
39
+ localPath: string,
40
+ remotePath: string,
41
+ recursive: boolean,
42
+ onProgress?: (progress: TransferProgress) => void,
43
+ ): Promise<{ bytes: number; files: number }> {
44
+ // Remote paths must be absolute: the mkdir chain and fastPut must agree
45
+ // on one resolution (relative paths previously created dirs at the root).
46
+ if (!remotePath.startsWith('/')) {
47
+ throw new Error('remotePath must be an absolute path (got \'' + remotePath + '\')')
48
+ }
49
+ const local = resolvePath(localPath)
50
+ if (!existsSync(local)) throw new Error('local path not found: \'' + localPath + '\'')
51
+ return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
52
+ const stat = statSync(local)
53
+ let files: string[]
54
+ if (stat.isDirectory()) {
55
+ if (!recursive) throw new Error('\'' + localPath + '\' is a directory — enable recursive upload')
56
+ files = walkLocalDir(local)
57
+ await ensureRemoteDir(sftp, remotePath)
58
+ } else {
59
+ files = ['']
60
+ await ensureRemoteDir(sftp, dirname(remotePath))
61
+ }
62
+ let bytes = 0
63
+ for (const rel of files) {
64
+ const src = rel === '' ? local : join(local, rel)
65
+ // Remote paths always use forward slashes; normalize any OS separators.
66
+ const remoteRel = rel.split(/[\\/]/).join('/')
67
+ const dst = rel === '' ? remotePath : remotePath.replace(/\/$/, '') + '/' + remoteRel
68
+ await fastPut(sftp, src, dst, engine.opts.sftpConcurrency, onProgress)
69
+ bytes += statSync(src).size
70
+ }
71
+ return { bytes, files: files.length }
72
+ }))
73
+ }
74
+
75
+ /** Download one remote file to a local path. */
76
+ export async function download(
77
+ engine: PoolEngine,
78
+ alias: string,
79
+ remotePath: string,
80
+ localPath: string,
81
+ onProgress?: (progress: TransferProgress) => void,
82
+ ): Promise<{ bytes: number }> {
83
+ return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
84
+ const stat = await new Promise<{ isDirectory: () => boolean }>((resolve, reject) => {
85
+ sftp.stat(remotePath, (error, stats) => error !== undefined ? reject(error) : resolve(stats))
86
+ })
87
+ if (stat.isDirectory()) {
88
+ throw new Error('\'' + remotePath + '\' is a directory — directory download is not supported yet (download individual files)')
89
+ }
90
+ const local = resolvePath(localPath)
91
+ if (!existsSync(dirname(local))) mkdirSync(dirname(local), { recursive: true })
92
+ await fastGet(sftp, remotePath, local, engine.opts.sftpConcurrency, onProgress)
93
+ return { bytes: statSync(local).size }
94
+ }))
95
+ }
96
+
97
+ /** List a remote directory (file browser). */
98
+ export async function ls(engine: PoolEngine, alias: string, path: string): Promise<RemoteDirEntry[]> {
99
+ return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
100
+ return await new Promise((resolve, reject) => {
101
+ sftp.readdir(path, (error, list) => {
102
+ if (error !== undefined) {
103
+ reject(error)
104
+ return
105
+ }
106
+ const entries: RemoteDirEntry[] = list.map(item => ({
107
+ name: item.filename,
108
+ type: item.attrs.isDirectory() ? 'dir' : item.attrs.isFile() ? 'file' : 'other',
109
+ size: item.attrs.size,
110
+ mtimeMs: item.attrs.mtime * 1000,
111
+ mode: item.attrs.mode,
112
+ }))
113
+ resolve(entries)
114
+ })
115
+ })
116
+ }))
117
+ }
118
+
119
+ /**
120
+ * Open one SFTP channel, run the operation, and release the channel exactly
121
+ * once when the operation settles (success or error). ssh2 keeps each
122
+ * subsystem channel open until end(); without this, every transfer leaks a
123
+ * channel until sshd's MaxSessions cap makes all later opens fail.
124
+ */
125
+ async function withSftp<T>(client: Client, run: (sftp: SFTPWrapper) => Promise<T>): Promise<T> {
126
+ const sftp = await sftpChannel(client)
127
+ let ended = false
128
+ const endOnce = (): void => {
129
+ if (ended) return
130
+ ended = true
131
+ try { sftp.end() } catch { /* channel already closed */ }
132
+ }
133
+ // The channel can also close underneath us (peer reset, timeout); the
134
+ // guard makes the finally below a no-op instead of ending it twice.
135
+ sftp.once('close', endOnce)
136
+ try {
137
+ return await run(sftp)
138
+ } finally {
139
+ endOnce()
140
+ }
141
+ }
142
+
143
+ function sftpChannel(client: Client): Promise<SFTPWrapper> {
144
+ return new Promise((resolve, reject) => {
145
+ client.sftp((error, sftp) => error !== undefined ? reject(error) : resolve(sftp))
146
+ })
147
+ }
148
+
149
+ /** Create a remote directory chain (stat-then-mkdir per segment). */
150
+ function ensureRemoteDir(sftp: SFTPWrapper, remote: string): Promise<void> {
151
+ return new Promise((resolve, reject) => {
152
+ const segments = remote.replace(/^\/+/, '').split('/').filter(segment => segment !== '')
153
+ const walk = (index: number): void => {
154
+ if (index >= segments.length) {
155
+ resolve()
156
+ return
157
+ }
158
+ const current = '/' + segments.slice(0, index + 1).join('/')
159
+ sftp.stat(current, (statError) => {
160
+ if (statError === undefined) {
161
+ walk(index + 1)
162
+ return
163
+ }
164
+ // Statting a missing path fails; mkdir it (idempotent because the
165
+ // stat check runs first — some sftp servers throw on EEXIST).
166
+ sftp.mkdir(current, (mkdirError) => {
167
+ if (mkdirError !== undefined) {
168
+ reject(mkdirError)
169
+ return
170
+ }
171
+ walk(index + 1)
172
+ })
173
+ })
174
+ }
175
+ walk(0)
176
+ })
177
+ }
178
+
179
+ /** One fastPut/fastGet transfer with throttled progress (the two directions share everything but the verb). */
180
+ function fastTransfer(sftp: SFTPWrapper, kind: 'put' | 'get', src: string, dst: string, concurrency: number, onProgress?: (progress: TransferProgress) => void): Promise<void> {
181
+ return new Promise((resolve, reject) => {
182
+ // Progress frames name the destination on upload, the source on download;
183
+ // the final size comes from the local side of the transfer.
184
+ const file = kind === 'put' ? dst : src
185
+ const finalSize = (): number => statSync(kind === 'put' ? src : dst).size
186
+ let last = 0
187
+ let lastEmit = 0
188
+ const started = Date.now()
189
+ if (kind === 'put') {
190
+ onProgress?.({ phase: 'transferring', file, transferred: 0, total: statSync(src).size, percent: 0 })
191
+ }
192
+ const step = (transferred: number, _chunk: number, total: number): void => {
193
+ const now = Date.now()
194
+ // Throttle: high-speed links fire one callback per chunk; the UI only
195
+ // needs ~10 frames per second.
196
+ if (now - lastEmit < 100 && transferred < total) return
197
+ lastEmit = now
198
+ const elapsed = (now - started) / 1000
199
+ onProgress?.({
200
+ phase: 'transferring',
201
+ file,
202
+ transferred,
203
+ total,
204
+ percent: total > 0 ? Math.round((transferred / total) * 1000) / 10 : 0,
205
+ speedBps: elapsed > 0 ? Math.round((transferred - last) / elapsed) : undefined,
206
+ })
207
+ last = transferred
208
+ }
209
+ const done = (error: unknown): void => {
210
+ if (error !== undefined) {
211
+ onProgress?.({ phase: 'error', file, transferred: 0, total: 0, percent: 0, error: String(error) })
212
+ reject(error)
213
+ } else {
214
+ onProgress?.({ phase: 'done', file, transferred: finalSize(), total: finalSize(), percent: 100 })
215
+ resolve()
216
+ }
217
+ }
218
+ if (kind === 'put') sftp.fastPut(src, dst, { concurrency, step }, done)
219
+ else sftp.fastGet(src, dst, { concurrency, step }, done)
220
+ })
221
+ }
222
+
223
+ function fastPut(sftp: SFTPWrapper, src: string, dst: string, concurrency: number, onProgress?: (progress: TransferProgress) => void): Promise<void> {
224
+ return fastTransfer(sftp, 'put', src, dst, concurrency, onProgress)
225
+ }
226
+
227
+ function fastGet(sftp: SFTPWrapper, src: string, dst: string, concurrency: number, onProgress?: (progress: TransferProgress) => void): Promise<void> {
228
+ return fastTransfer(sftp, 'get', src, dst, concurrency, onProgress)
229
+ }