dsh-remote-go 0.1.0 → 0.3.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/README.md +64 -95
  2. package/{client.js → dist/client.js} +7805 -5486
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/dist/src/constants.js +67 -0
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +2 -2
  90. package/locale/zh.json +2 -2
  91. package/package.json +40 -21
  92. package/vendor/THIRD_PARTY_NOTICES.md +27 -1
  93. package/src/api.js +0 -340
  94. package/src/atomic-json.js +0 -208
  95. package/src/bootstrap.js +0 -100
  96. package/src/connect-log.js +0 -39
  97. package/src/connect-pipeline.js +0 -463
  98. package/src/connect-progress.js +0 -135
  99. package/src/constants.js +0 -31
  100. package/src/diagnostics.js +0 -157
  101. package/src/download-jobs.js +0 -217
  102. package/src/errors.js +0 -316
  103. package/src/host-lifecycle.js +0 -187
  104. package/src/host-registry.js +0 -145
  105. package/src/host-runtime.js +0 -53
  106. package/src/host-view.js +0 -51
  107. package/src/index.js +0 -162
  108. package/src/key-files.js +0 -49
  109. package/src/known-hosts.js +0 -94
  110. package/src/layout.js +0 -35
  111. package/src/local-download.js +0 -162
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -89
  116. package/src/prompts.js +0 -132
  117. package/src/redact.js +0 -54
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -73
  120. package/src/remote-proc.js +0 -208
  121. package/src/remote-web.js +0 -300
  122. package/src/secrets.js +0 -79
  123. package/src/service.js +0 -250
  124. package/src/settings.js +0 -135
  125. package/src/ssh-config.js +0 -271
  126. package/src/ssh.js +0 -652
  127. package/src/store.js +0 -143
  128. package/src/tunnel.js +0 -73
  129. package/src/util.js +0 -153
  130. package/src/version.js +0 -103
  131. package/src/webapp.js +0 -28
  132. package/vendor/ssh2-entry.mjs +0 -12
  133. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/ssh.js DELETED
@@ -1,652 +0,0 @@
1
- /**
2
- * Promise wrapper over `ssh2`: host-key policy/confirmation, auth fallback, one-shot `exec` with streamed output, and TCP forwarding for the loopback tunnel.
3
- */
4
- import { EventEmitter } from 'node:events'
5
- import { createWriteStream, existsSync } from 'node:fs'
6
- import { mkdir, readFile, rm } from 'node:fs/promises'
7
- import { homedir } from 'node:os'
8
- import path from 'node:path'
9
- import { pipeline } from 'node:stream/promises'
10
- import ssh2 from '../vendor/ssh2.bundle.cjs'
11
- import { fingerprintFromBlob } from './known-hosts.js'
12
- import { expandHome, headTail } from './util.js'
13
- import { errors, RemoteGoError } from './errors.js'
14
- import { safeLocalSegment } from './remote-path.js'
15
-
16
- const { Client } = ssh2
17
-
18
- /** Settle a promise at most once; later calls are ignored, so callers need no flag. */
19
- function oneShot(resolve, reject, cleanup) {
20
- let settled = false
21
- return (error, value) => {
22
- if (settled) return
23
- settled = true
24
- cleanup?.()
25
- if (error) reject(error)
26
- else resolve(value)
27
- }
28
- }
29
-
30
- export function parseSshKeyType(blob) {
31
- try {
32
- const buffer = Buffer.from(blob)
33
- if (buffer.length < 6) return 'unknown'
34
- const length = buffer.readUInt32BE(0)
35
- if (length <= 0 || length > buffer.length - 4) return 'unknown'
36
- return buffer.subarray(4, 4 + length).toString('ascii')
37
- } catch {
38
- return 'unknown'
39
- }
40
- }
41
-
42
- export class SshConnection extends EventEmitter {
43
- constructor(options) {
44
- super()
45
- this.options = {
46
- port: 22,
47
- hostKeyPolicy: 'first-use',
48
- pinnedFingerprint: null,
49
- knownHostFingerprints: [],
50
- readyTimeoutMs: 20_000,
51
- keepaliveIntervalMs: 15_000,
52
- home: homedir(),
53
- ...options,
54
- identityFiles: options.identityFiles ?? [],
55
- }
56
- this.client = null
57
- this.fingerprint = null
58
- this.keyType = null
59
- this.closed = false
60
- this.disposed = false
61
- this.hostKeyDecision = null
62
- // ssh2 clients emit `error` for every failed auth attempt and again while
63
- // tearing down. EventEmitter treats an unhandled `error` as a thrown
64
- // exception, which would take down the whole DSH host process; keep a
65
- // permanent safety listener so failures stay inside this connection.
66
- this.on('error', () => {})
67
- this.clientFactory = typeof options.clientFactory === 'function' ? options.clientFactory : () => new Client()
68
- }
69
-
70
- get connected() {
71
- return this.client !== null && !this.closed
72
- }
73
-
74
- async connect() {
75
- if (this.connected) return { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' }
76
- const candidates = await this.resolveAuthCandidates()
77
- if (candidates.length === 0) {
78
- throw errors.invalidInput('auth', {
79
- zh: '没有可用的 SSH 认证方式:请选择一个可读的私钥文件(或输入一次密码)。',
80
- en: 'No usable SSH authentication: choose a readable private-key file (or enter a one-time password).',
81
- })
82
- }
83
- let lastError = null
84
- for (const candidate of candidates) {
85
- try {
86
- const info = await this.connectOnce(candidate)
87
- this.client?.on('close', () => {
88
- this.closed = true
89
- this.emit('close')
90
- })
91
- this.client?.on('error', (error) => {
92
- this.emit('error', error)
93
- })
94
- return info
95
- } catch (error) {
96
- lastError = error
97
- this.cleanupClient()
98
- // A host-key rejection is a policy decision, not an auth failure.
99
- if (isHostKeyError(error)) throw error
100
- }
101
- }
102
- throw lastError instanceof Error ? lastError : errors.auth()
103
- }
104
-
105
- connectOnce(authConfig) {
106
- return new Promise((resolve, reject) => {
107
- const settle = oneShot(resolve, reject)
108
- const client = this.clientFactory()
109
- this.client = client
110
- // A rejected earlier candidate tears its transport down through
111
- // `cleanupClient()`, which marks this object closed. A new attempt owns a
112
- // fresh client, so it must clear the flag again; otherwise a successful
113
- // fallback (agent -> key on a machine without an SSH agent) would report
114
- // `connected === false` and every later `exec`/`forwardOut` would throw
115
- // "SSH connection is not open" on a transport that is actually up.
116
- this.closed = false
117
- client.once('ready', () => {
118
- settle(null, { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' })
119
- })
120
- // Permanent listener: settle the promise on the first error, swallow any
121
- // later teardown errors (they are already reflected in the rejection).
122
- client.on('error', (error) => {
123
- settle(toSshError(error, this.options.host, this.options.port))
124
- })
125
- const config = {
126
- host: this.options.host,
127
- port: this.options.port,
128
- username: this.options.username ?? undefined,
129
- readyTimeout: this.options.readyTimeoutMs,
130
- keepaliveInterval: this.options.keepaliveIntervalMs,
131
- keepaliveCountMax: 3,
132
- tryKeyboard: false,
133
- ...(this.options.sock ? { sock: this.options.sock } : {}),
134
- ...authConfig,
135
- hostVerifier: (/** @type {Buffer} */ keyBlob, /** @type {any} */ verify) => {
136
- this.verifyHostKey(keyBlob)
137
- .then((accepted) => verify(accepted))
138
- .catch(() => verify(false))
139
- },
140
- }
141
- try {
142
- client.connect(config)
143
- } catch (error) {
144
- settle(toSshError(error, this.options.host, this.options.port))
145
- }
146
- })
147
- }
148
-
149
- async verifyHostKey(keyBlob) {
150
- const sha256 = fingerprintFromBlob(keyBlob)
151
- const keyType = parseSshKeyType(keyBlob)
152
- this.fingerprint = sha256
153
- this.keyType = keyType
154
- const pinned = this.options.pinnedFingerprint
155
- const known = this.options.knownHostFingerprints ?? []
156
- const info = { sha256, keyType, pinned: Boolean(pinned && pinned === sha256) }
157
- if (pinned) {
158
- if (pinned === sha256) return true
159
- this.emit('hostkey-rejected', info)
160
- throw errors.hostKeyChanged(pinned, sha256)
161
- }
162
- if (known.length > 0) {
163
- if (known.includes(sha256)) return true
164
- this.emit('hostkey-rejected', info)
165
- throw errors.hostKeyChanged(known[0], sha256)
166
- }
167
- if (this.options.acceptUnknownHostKey === true) {
168
- this.emit('hostkey-accepted', info)
169
- return true
170
- }
171
- if (this.hostKeyDecision) return this.hostKeyDecision
172
- if (this.options.hostKeyPolicy === 'strict') {
173
- throw errors.hostKeyUnknown(sha256)
174
- }
175
- if (typeof this.options.onHostKey !== 'function') {
176
- // No UI attached (tests/automation): refuse rather than silently trust.
177
- throw errors.hostKeyUnknown(sha256)
178
- }
179
- this.emit('hostkey-pending', info)
180
- this.hostKeyDecision = Promise.resolve(this.options.onHostKey(info)).then(
181
- (accepted) => accepted === true,
182
- () => false,
183
- )
184
- const accepted = await this.hostKeyDecision
185
- if (!accepted) throw errors.hostKeyUnknown(sha256)
186
- return true
187
- }
188
-
189
- async resolveAuthCandidates() {
190
- const auth = this.options.auth ?? { type: 'key' }
191
- const out = []
192
- if (auth.type === 'password') {
193
- if (auth.password) out.push({ password: auth.password, tryKeyboard: true })
194
- return out
195
- }
196
- // Key-file authentication only: there is deliberately no agent candidate. The
197
- // configured path wins; when it is missing or unset the conventional names are
198
- // tried, so a host added with the default key path still connects.
199
- const keyPaths = [
200
- ...(auth.keyPath ? [expandHome(auth.keyPath, this.options.home)] : []),
201
- ...(this.options.identityFiles ?? []),
202
- path.join(this.options.home, '.ssh', 'id_ed25519'),
203
- path.join(this.options.home, '.ssh', 'id_rsa'),
204
- path.join(this.options.home, '.ssh', 'id_ecdsa'),
205
- ]
206
- const seen = new Set()
207
- for (const keyPath of keyPaths) {
208
- if (!keyPath) continue
209
- const normalized = path.resolve(keyPath)
210
- if (seen.has(normalized)) continue
211
- seen.add(normalized)
212
- const privateKey = await readKey(keyPath)
213
- if (privateKey) out.push({ privateKey })
214
- }
215
- return out
216
- }
217
-
218
- exec(command, options = {}) {
219
- const timeoutMs = options.timeoutMs ?? 30_000
220
- const maxBytes = options.maxBytes ?? 2 * 1024 * 1024
221
- return new Promise((resolve, reject) => {
222
- if (!this.client || this.closed) {
223
- reject(new Error('SSH connection is not open'))
224
- return
225
- }
226
- let timedOut = false
227
- let timer = null
228
- const chunks = { stdout: '', stderr: '' }
229
- const finish = oneShot(resolve, reject, () => {
230
- if (timer) clearTimeout(timer)
231
- options.signal?.removeEventListener?.('abort', onAbort)
232
- })
233
- const onAbort = () => {
234
- finish(new Error('aborted'))
235
- }
236
- options.signal?.addEventListener?.('abort', onAbort, { once: true })
237
- this.client.exec(command, { env: options.env }, (error, stream) => {
238
- if (error) {
239
- finish(error)
240
- return
241
- }
242
- if (timeoutMs > 0) {
243
- timer = setTimeout(() => {
244
- timedOut = true
245
- stream.destroy()
246
- }, timeoutMs)
247
- }
248
- // Optional stdin (file uploads): the command reads it, so a secret never
249
- // appears on the remote command line.
250
- if (options.stdin !== undefined) {
251
- try {
252
- stream.end(String(options.stdin))
253
- } catch (writeError) {
254
- finish(writeError)
255
- return
256
- }
257
- }
258
- stream.on('data', (/** @type {Buffer} */ data) => {
259
- const text = data.toString('utf8')
260
- if (chunks.stdout.length < maxBytes) {
261
- chunks.stdout += text
262
- options.onStdout?.(text)
263
- }
264
- })
265
- stream.stderr.on('data', (/** @type {Buffer} */ data) => {
266
- const text = data.toString('utf8')
267
- if (chunks.stderr.length < maxBytes) {
268
- chunks.stderr += text
269
- options.onStderr?.(text)
270
- }
271
- })
272
- stream.on('close', (/** @type {number | null} */ code, /** @type {string | null} */ signal) => {
273
- finish(null, {
274
- code: code ?? null,
275
- signal: signal ?? null,
276
- stdout: chunks.stdout,
277
- stderr: chunks.stderr,
278
- timedOut,
279
- })
280
- })
281
- stream.on('error', (streamError) => finish(streamError))
282
- })
283
- })
284
- }
285
-
286
- /**
287
- * Open one SFTP session on this connection.
288
- * @returns {Promise<any>} the ssh2 SFTP wrapper.
289
- */
290
- openSftp() {
291
- return new Promise((resolve, reject) => {
292
- if (!this.client || this.closed) {
293
- reject(new Error('SSH connection is not open'))
294
- return
295
- }
296
- this.client.sftp((error, sftp) => {
297
- if (error) reject(error)
298
- else resolve(sftp)
299
- })
300
- })
301
- }
302
-
303
- /**
304
- * Stream one remote file into a local path. Nothing is buffered; cancellation
305
- * destroys both streams and removes the partial file.
306
- * @param {string} remotePath - absolute remote file path.
307
- * @param {string} localPath - absolute local file path (parent must exist).
308
- * @param {{ onProgress?: (info: { doneBytes: number, totalBytes: number,
309
- * doneFiles: number, totalFiles: number }) => void, isCancelled?: () => boolean }} [options]
310
- * @returns {Promise<{ size: number }>}
311
- */
312
- async saveRemoteFile(remotePath, localPath, options = {}) {
313
- const sftp = await this.openSftp()
314
- try {
315
- const stats = await new Promise((resolve, reject) => {
316
- sftp.stat(remotePath, (error, value) => (error ? reject(error) : resolve(value)))
317
- })
318
- assertReadableFile(stats)
319
- const totalBytes = Number(stats?.size ?? 0)
320
- let doneBytes = 0
321
- try {
322
- await copySftpFileToLocal(
323
- sftp,
324
- remotePath,
325
- localPath,
326
- (bytes) => {
327
- doneBytes += bytes
328
- if (typeof options.onProgress !== 'function') return
329
- try {
330
- options.onProgress({ doneBytes, totalBytes, doneFiles: 0, totalFiles: 1 })
331
- } catch {
332
- /* progress listeners must not break the transfer */
333
- }
334
- },
335
- options.isCancelled,
336
- )
337
- } catch (error) {
338
- await rm(localPath, { force: true }).catch(() => {})
339
- throw error
340
- }
341
- return { size: doneBytes || totalBytes }
342
- } finally {
343
- endSftp(sftp)
344
- }
345
- }
346
-
347
- /**
348
- * Inspect one remote path without reading it.
349
- * @param {string} remotePath - absolute path on the remote host.
350
- * @returns {Promise<{ isFile: boolean, isDirectory: boolean, size: number, mtime: number }>}
351
- */
352
- async inspectRemotePath(remotePath) {
353
- const sftp = await this.openSftp()
354
- try {
355
- const stats = await new Promise((resolve, reject) => {
356
- sftp.stat(remotePath, (error, value) => (error ? reject(error) : resolve(value)))
357
- })
358
- return {
359
- isFile: Boolean(stats?.isFile?.()),
360
- isDirectory: Boolean(stats?.isDirectory?.()),
361
- size: Number(stats?.size ?? 0),
362
- mtime: Number(stats?.mtime ?? 0),
363
- }
364
- } finally {
365
- endSftp(sftp)
366
- }
367
- }
368
-
369
- /**
370
- * Copy a remote directory to a local directory, one file at a time (no archive).
371
- * Directories are created locally, empty ones included; symlinks are skipped so a
372
- * remote loop cannot cycle. There is no byte/count cap: the local disk is the bound.
373
- * @param {string} remotePath - absolute remote directory.
374
- * @param {string} targetRoot - absolute local directory that receives the tree.
375
- * @param {{ onInventory?: (info: { totalBytes: number, totalFiles: number }) => void,
376
- * onProgress?: (info: { doneBytes: number, totalBytes: number, doneFiles: number,
377
- * totalFiles: number }) => void, isCancelled?: () => boolean }} [options]
378
- * @returns {Promise<{ destination: string, totalBytes: number, totalFiles: number,
379
- * cancelled?: boolean }>}
380
- */
381
- async saveRemoteTree(remotePath, targetRoot, options = {}) {
382
- const sftp = await this.openSftp()
383
- try {
384
- const rootStats = await new Promise((resolve, reject) => {
385
- sftp.stat(remotePath, (error, value) => (error ? reject(error) : resolve(value)))
386
- })
387
- if (!rootStats?.isDirectory?.()) {
388
- throw errors.remoteFileUnavailable({
389
- zh: '这个远端路径不是目录,无法按文件夹下载。',
390
- en: 'This remote path is not a directory and cannot be downloaded as a folder.',
391
- })
392
- }
393
- const localRoot = path.resolve(targetRoot)
394
- const localPathFor = (relative) => {
395
- const segments = String(relative).split('/').filter(Boolean).map(safeLocalSegment)
396
- const resolved = path.resolve(localRoot, ...segments)
397
- if (resolved !== localRoot && !resolved.startsWith(localRoot + path.sep)) {
398
- throw errors.remoteFileUnavailable({
399
- zh: '远端文件名无法安全映射到本地目录。',
400
- en: 'A remote file name cannot be mapped safely into the local directory.',
401
- })
402
- }
403
- return resolved
404
- }
405
- const members = []
406
- let totalBytes = 0
407
- let totalFiles = 0
408
- const walk = async (directory, relative) => {
409
- const listing = await new Promise((resolve, reject) => {
410
- sftp.readdir(directory, (error, value) => (error ? reject(error) : resolve(value)))
411
- })
412
- const items = Array.isArray(listing) ? listing.slice() : []
413
- items.sort((left, right) => String(left?.filename ?? '').localeCompare(String(right?.filename ?? '')))
414
- for (const item of items) {
415
- const filename = String(item?.filename ?? '')
416
- if (filename === '' || filename === '.' || filename === '..') continue
417
- const attrs = item?.attrs ?? {}
418
- if (attrs.isSymbolicLink?.() === true) continue
419
- const childRelative = relative === '' ? filename : relative + '/' + filename
420
- const childPath = path.posix.join(directory, filename)
421
- if (attrs.isDirectory?.() === true) {
422
- members.push({ relative: childRelative, isDirectory: true })
423
- await walk(childPath, childRelative)
424
- } else if (attrs.isFile?.() === true) {
425
- const size = Number(attrs.size ?? 0)
426
- if (!Number.isFinite(size) || size < 0) continue
427
- totalFiles += 1
428
- totalBytes += size
429
- members.push({ relative: childRelative, remotePath: childPath, size })
430
- }
431
- }
432
- }
433
- await walk(remotePath, '')
434
- if (typeof options.onInventory === 'function') {
435
- try {
436
- options.onInventory({ totalBytes, totalFiles })
437
- } catch {
438
- /* progress listeners must not break the download */
439
- }
440
- }
441
- await mkdir(localRoot, { recursive: true })
442
- for (const member of members) {
443
- if (member.isDirectory) await mkdir(localPathFor(member.relative), { recursive: true })
444
- }
445
- let doneBytes = 0
446
- let doneFiles = 0
447
- const report = () => {
448
- if (typeof options.onProgress !== 'function') return
449
- try {
450
- options.onProgress({ doneBytes, totalBytes, doneFiles, totalFiles })
451
- } catch {
452
- /* progress listeners must not break the download */
453
- }
454
- }
455
- for (const member of members) {
456
- if (member.isDirectory || typeof member.remotePath !== 'string') continue
457
- if (typeof options.isCancelled === 'function' && options.isCancelled()) {
458
- await rm(localRoot, { recursive: true, force: true }).catch(() => {})
459
- return { destination: localRoot, totalBytes, totalFiles, cancelled: true }
460
- }
461
- const localPath = localPathFor(member.relative)
462
- await mkdir(path.dirname(localPath), { recursive: true })
463
- try {
464
- await copySftpFileToLocal(
465
- sftp,
466
- member.remotePath,
467
- localPath,
468
- (bytes) => {
469
- doneBytes += bytes
470
- report()
471
- },
472
- options.isCancelled,
473
- )
474
- } catch (error) {
475
- if (typeof options.isCancelled === 'function' && options.isCancelled()) {
476
- await rm(localRoot, { recursive: true, force: true }).catch(() => {})
477
- return { destination: localRoot, totalBytes, totalFiles, cancelled: true }
478
- }
479
- throw error
480
- }
481
- doneFiles += 1
482
- report()
483
- }
484
- return { destination: localRoot, totalBytes, totalFiles }
485
- } finally {
486
- endSftp(sftp)
487
- }
488
- }
489
-
490
- forwardOut(destHost, destPort, srcHost = '127.0.0.1', srcPort = 0) {
491
- return new Promise((resolve, reject) => {
492
- if (!this.client || this.closed) {
493
- reject(new Error('SSH connection is not open'))
494
- return
495
- }
496
- this.client.forwardOut(srcHost, srcPort, destHost, destPort, (error, stream) => {
497
- if (error) reject(error)
498
- else resolve(stream)
499
- })
500
- })
501
- }
502
-
503
- async dispose() {
504
- this.disposed = true
505
- const client = this.client
506
- this.cleanupClient()
507
- if (!client) return
508
- await new Promise((resolve) => {
509
- const timer = setTimeout(resolve, 1_500)
510
- try {
511
- client.once('close', () => {
512
- clearTimeout(timer)
513
- resolve(undefined)
514
- })
515
- client.end()
516
- } catch {
517
- clearTimeout(timer)
518
- resolve(undefined)
519
- }
520
- })
521
- }
522
-
523
- cleanupClient() {
524
- const client = this.client
525
- this.client = null
526
- this.closed = true
527
- if (client) {
528
- try {
529
- // Keep an error sink attached: ssh2 may still emit during teardown.
530
- client.on('error', () => {})
531
- client.end()
532
- } catch {}
533
- }
534
- }
535
- }
536
-
537
- async function readKey(keyPath) {
538
- try {
539
- if (!existsSync(keyPath)) return null
540
- return await readFile(keyPath)
541
- } catch {
542
- return null
543
- }
544
- }
545
-
546
- function endSftp(sftp) {
547
- try {
548
- sftp.end()
549
- } catch {
550
- /* the session may already be gone */
551
- }
552
- }
553
-
554
- function assertReadableFile(stats) {
555
- if (stats?.isDirectory?.()) {
556
- throw errors.remoteFileUnavailable({
557
- zh: '这是一个远端目录,不能作为文件下载。',
558
- en: 'This remote path is a directory, not a downloadable file.',
559
- })
560
- }
561
- }
562
-
563
- /** Pipe one SFTP file into a local file, reporting bytes as they arrive. */
564
- function copySftpFileToLocal(sftp, remotePath, localPath, onChunk, shouldCancel) {
565
- return new Promise((resolve, reject) => {
566
- let input
567
- try {
568
- input = sftp.createReadStream(remotePath)
569
- } catch (error) {
570
- reject(error)
571
- return
572
- }
573
- if (!input || typeof input.on !== 'function') {
574
- reject(new Error('SFTP read stream is unavailable'))
575
- return
576
- }
577
- const output = createWriteStream(localPath, { flags: 'w' })
578
- let settled = false
579
- const fail = (error) => {
580
- if (settled) return
581
- settled = true
582
- try {
583
- input.destroy()
584
- } catch {
585
- /* already gone */
586
- }
587
- const finish = () => reject(error)
588
- try {
589
- if (output.closed === true) {
590
- finish()
591
- } else {
592
- output.once('close', finish)
593
- output.destroy()
594
- }
595
- } catch {
596
- finish()
597
- }
598
- }
599
- input.on('data', (chunk) => {
600
- if (typeof shouldCancel === 'function' && shouldCancel()) {
601
- fail(new Error('download-cancelled'))
602
- return
603
- }
604
- try {
605
- onChunk(Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk))
606
- } catch {
607
- /* progress listeners must not break the transfer */
608
- }
609
- })
610
- pipeline(input, output).then(
611
- () => {
612
- if (!settled) {
613
- settled = true
614
- resolve()
615
- }
616
- },
617
- (error) => fail(error),
618
- )
619
- })
620
- }
621
-
622
- export function toSshError(error, host, port) {
623
- if (!error) return errors.internal('unknown ssh error')
624
- if (error instanceof RemoteGoError) return error
625
- const message = String(error.message ?? error)
626
- const code = String(/** @type {any} */ (error).code ?? '')
627
- if (/host key|hostkey|verification/i.test(message)) {
628
- return errors.network({
629
- zh: `主机密钥校验未通过(${host}:${port})。`,
630
- en: `Host key verification failed for ${host}:${port}.`,
631
- })
632
- }
633
- if (/authentication|All configured authentication methods failed|Permission denied/i.test(message)) {
634
- return errors.auth()
635
- }
636
- if (
637
- /ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|timed out|timeout|Cannot connect|connect failed/i.test(
638
- `${code} ${message}`,
639
- )
640
- ) {
641
- return errors.network()
642
- }
643
- return errors.network({
644
- zh: `SSH 连接失败:${headTail(message, 300)}`,
645
- en: `SSH connection failed: ${headTail(message, 300)}`,
646
- })
647
- }
648
-
649
- function isHostKeyError(error) {
650
- const code = /** @type {any} */ (error)?.code
651
- return code === 'host-key-changed' || code === 'host-key-unknown'
652
- }