dsh-remote-go 0.2.0 → 0.3.1

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