dsh-remote-go 0.1.0 → 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.
package/src/ssh.js CHANGED
@@ -2,8 +2,8 @@
2
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
3
  */
4
4
  import { EventEmitter } from 'node:events'
5
- import { createWriteStream, existsSync } from 'node:fs'
6
- import { mkdir, readFile, rm } from 'node:fs/promises'
5
+ import { createWriteStream } from 'node:fs'
6
+ import { mkdir, open, rm } from 'node:fs/promises'
7
7
  import { homedir } from 'node:os'
8
8
  import path from 'node:path'
9
9
  import { pipeline } from 'node:stream/promises'
@@ -11,7 +11,7 @@ import ssh2 from '../vendor/ssh2.bundle.cjs'
11
11
  import { fingerprintFromBlob } from './known-hosts.js'
12
12
  import { expandHome, headTail } from './util.js'
13
13
  import { errors, RemoteGoError } from './errors.js'
14
- import { safeLocalSegment } from './remote-path.js'
14
+ import { isIgnoredLocalName, localPathKey, safeLocalSegment, uniqueLocalPath } from './remote-path.js'
15
15
 
16
16
  const { Client } = ssh2
17
17
 
@@ -39,6 +39,17 @@ export function parseSshKeyType(blob) {
39
39
  }
40
40
  }
41
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
+
42
53
  export class SshConnection extends EventEmitter {
43
54
  constructor(options) {
44
55
  super()
@@ -84,10 +95,6 @@ export class SshConnection extends EventEmitter {
84
95
  for (const candidate of candidates) {
85
96
  try {
86
97
  const info = await this.connectOnce(candidate)
87
- this.client?.on('close', () => {
88
- this.closed = true
89
- this.emit('close')
90
- })
91
98
  this.client?.on('error', (error) => {
92
99
  this.emit('error', error)
93
100
  })
@@ -114,12 +121,32 @@ export class SshConnection extends EventEmitter {
114
121
  // `connected === false` and every later `exec`/`forwardOut` would throw
115
122
  // "SSH connection is not open" on a transport that is actually up.
116
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
+ })
117
143
  client.once('ready', () => {
118
144
  settle(null, { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' })
119
145
  })
120
146
  // Permanent listener: settle the promise on the first error, swallow any
121
147
  // later teardown errors (they are already reflected in the rejection).
122
148
  client.on('error', (error) => {
149
+ attemptFailed = true
123
150
  settle(toSshError(error, this.options.host, this.options.port))
124
151
  })
125
152
  const config = {
@@ -141,6 +168,7 @@ export class SshConnection extends EventEmitter {
141
168
  try {
142
169
  client.connect(config)
143
170
  } catch (error) {
171
+ attemptFailed = true
144
172
  settle(toSshError(error, this.options.host, this.options.port))
145
173
  }
146
174
  })
@@ -220,7 +248,7 @@ export class SshConnection extends EventEmitter {
220
248
  const maxBytes = options.maxBytes ?? 2 * 1024 * 1024
221
249
  return new Promise((resolve, reject) => {
222
250
  if (!this.client || this.closed) {
223
- reject(new Error('SSH connection is not open'))
251
+ reject(closedError())
224
252
  return
225
253
  }
226
254
  let timedOut = false
@@ -259,14 +287,23 @@ export class SshConnection extends EventEmitter {
259
287
  const text = data.toString('utf8')
260
288
  if (chunks.stdout.length < maxBytes) {
261
289
  chunks.stdout += text
262
- options.onStdout?.(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
+ }
263
296
  }
264
297
  })
265
298
  stream.stderr.on('data', (/** @type {Buffer} */ data) => {
266
299
  const text = data.toString('utf8')
267
300
  if (chunks.stderr.length < maxBytes) {
268
301
  chunks.stderr += text
269
- options.onStderr?.(text)
302
+ try {
303
+ options.onStderr?.(text)
304
+ } catch {
305
+ /* stderr listeners must not break the command */
306
+ }
270
307
  }
271
308
  })
272
309
  stream.on('close', (/** @type {number | null} */ code, /** @type {string | null} */ signal) => {
@@ -290,7 +327,7 @@ export class SshConnection extends EventEmitter {
290
327
  openSftp() {
291
328
  return new Promise((resolve, reject) => {
292
329
  if (!this.client || this.closed) {
293
- reject(new Error('SSH connection is not open'))
330
+ reject(closedError())
294
331
  return
295
332
  }
296
333
  this.client.sftp((error, sftp) => {
@@ -374,9 +411,14 @@ export class SshConnection extends EventEmitter {
374
411
  * @param {string} targetRoot - absolute local directory that receives the tree.
375
412
  * @param {{ onInventory?: (info: { totalBytes: number, totalFiles: number }) => void,
376
413
  * onProgress?: (info: { doneBytes: number, totalBytes: number, doneFiles: number,
377
- * totalFiles: number }) => void, isCancelled?: () => boolean }} [options]
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.
378
420
  * @returns {Promise<{ destination: string, totalBytes: number, totalFiles: number,
379
- * cancelled?: boolean }>}
421
+ * renamedFiles?: number, ignoredNames?: string[], cancelled?: boolean }>}
380
422
  */
381
423
  async saveRemoteTree(remotePath, targetRoot, options = {}) {
382
424
  const sftp = await this.openSftp()
@@ -391,9 +433,15 @@ export class SshConnection extends EventEmitter {
391
433
  })
392
434
  }
393
435
  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)
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)
397
445
  if (resolved !== localRoot && !resolved.startsWith(localRoot + path.sep)) {
398
446
  throw errors.remoteFileUnavailable({
399
447
  zh: '远端文件名无法安全映射到本地目录。',
@@ -403,34 +451,48 @@ export class SshConnection extends EventEmitter {
403
451
  return resolved
404
452
  }
405
453
  const members = []
454
+ const ignoredNames = []
406
455
  let totalBytes = 0
407
456
  let totalFiles = 0
408
- const walk = async (directory, relative) => {
457
+ let renamedFiles = 0
458
+ const walk = async (directory, relative, localDir) => {
409
459
  const listing = await new Promise((resolve, reject) => {
410
460
  sftp.readdir(directory, (error, value) => (error ? reject(error) : resolve(value)))
411
461
  })
412
462
  const items = Array.isArray(listing) ? listing.slice() : []
413
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()
414
466
  for (const item of items) {
415
467
  const filename = String(item?.filename ?? '')
416
468
  if (filename === '' || filename === '.' || filename === '..') continue
417
469
  const attrs = item?.attrs ?? {}
418
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
+ }
419
477
  const childRelative = relative === '' ? filename : relative + '/' + filename
420
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 }))
421
482
  if (attrs.isDirectory?.() === true) {
422
- members.push({ relative: childRelative, isDirectory: true })
423
- await walk(childPath, childRelative)
483
+ members.push({ relative: childRelative, isDirectory: true, localPath })
484
+ await walk(childPath, childRelative, localPath)
424
485
  } else if (attrs.isFile?.() === true) {
425
486
  const size = Number(attrs.size ?? 0)
426
487
  if (!Number.isFinite(size) || size < 0) continue
488
+ if (localPath !== desired) renamedFiles += 1
427
489
  totalFiles += 1
428
490
  totalBytes += size
429
- members.push({ relative: childRelative, remotePath: childPath, size })
491
+ members.push({ relative: childRelative, remotePath: childPath, size, localPath })
430
492
  }
431
493
  }
432
494
  }
433
- await walk(remotePath, '')
495
+ await walk(remotePath, '', localRoot)
434
496
  if (typeof options.onInventory === 'function') {
435
497
  try {
436
498
  options.onInventory({ totalBytes, totalFiles })
@@ -438,9 +500,16 @@ export class SshConnection extends EventEmitter {
438
500
  /* progress listeners must not break the download */
439
501
  }
440
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
+ }
441
510
  await mkdir(localRoot, { recursive: true })
442
511
  for (const member of members) {
443
- if (member.isDirectory) await mkdir(localPathFor(member.relative), { recursive: true })
512
+ if (member.isDirectory) await mkdir(member.localPath, { recursive: true })
444
513
  }
445
514
  let doneBytes = 0
446
515
  let doneFiles = 0
@@ -458,13 +527,12 @@ export class SshConnection extends EventEmitter {
458
527
  await rm(localRoot, { recursive: true, force: true }).catch(() => {})
459
528
  return { destination: localRoot, totalBytes, totalFiles, cancelled: true }
460
529
  }
461
- const localPath = localPathFor(member.relative)
462
- await mkdir(path.dirname(localPath), { recursive: true })
530
+ await mkdir(path.dirname(member.localPath), { recursive: true })
463
531
  try {
464
532
  await copySftpFileToLocal(
465
533
  sftp,
466
534
  member.remotePath,
467
- localPath,
535
+ member.localPath,
468
536
  (bytes) => {
469
537
  doneBytes += bytes
470
538
  report()
@@ -481,7 +549,7 @@ export class SshConnection extends EventEmitter {
481
549
  doneFiles += 1
482
550
  report()
483
551
  }
484
- return { destination: localRoot, totalBytes, totalFiles }
552
+ return { destination: localRoot, totalBytes, totalFiles, renamedFiles, ignoredNames }
485
553
  } finally {
486
554
  endSftp(sftp)
487
555
  }
@@ -490,7 +558,7 @@ export class SshConnection extends EventEmitter {
490
558
  forwardOut(destHost, destPort, srcHost = '127.0.0.1', srcPort = 0) {
491
559
  return new Promise((resolve, reject) => {
492
560
  if (!this.client || this.closed) {
493
- reject(new Error('SSH connection is not open'))
561
+ reject(closedError())
494
562
  return
495
563
  }
496
564
  this.client.forwardOut(srcHost, srcPort, destHost, destPort, (error, stream) => {
@@ -534,12 +602,23 @@ export class SshConnection extends EventEmitter {
534
602
  }
535
603
  }
536
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
+
537
608
  async function readKey(keyPath) {
609
+ let handle = null
538
610
  try {
539
- if (!existsSync(keyPath)) return null
540
- return await readFile(keyPath)
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()
541
618
  } catch {
542
619
  return null
620
+ } finally {
621
+ await handle?.close().catch(() => {})
543
622
  }
544
623
  }
545
624
 
package/src/store.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Durable local state under `$DSH_HOME/remote-go/`: hosts.json, settings.json and secrets.json; writes are atomic, a corrupt file falls back to defaults.
2
+ * Durable local state under `$DSH_HOME/remote-go/`: hosts.json, settings.json and secrets.json; writes are atomic, a corrupt file is kept aside before the next write replaces it.
3
3
  */
4
4
  import { promises as fs } from 'node:fs'
5
5
  import path from 'node:path'
6
6
  import { readJsonFile, withProcessLock, writeJsonAtomic } from './atomic-json.js'
7
- import { nowIso, randomId } from './util.js'
7
+ import { deepMerge, nowIso, randomId } from './util.js'
8
8
  import { defaultSettings, sanitizeHostEntry, sanitizeSettings } from './settings.js'
9
9
 
10
10
  export class HostStore {
@@ -17,9 +17,16 @@ export class HostStore {
17
17
  this.secretsFile = path.join(this.dir, 'secrets.json')
18
18
  this.data = { hosts: [], settings: defaultSettings() }
19
19
  this.secrets = {}
20
+ /** Basenames of state files that were unreadable and moved aside on this load. */
21
+ this.corrupt = new Set()
20
22
  this.loaded = false
21
23
  }
22
24
 
25
+ /** Whether `hosts.json` had to be quarantined, i.e. the host list is the empty fallback. */
26
+ get hostsCorrupt() {
27
+ return this.corrupt.has('hosts.json')
28
+ }
29
+
23
30
  async load() {
24
31
  if (this.loaded) return this.data
25
32
  try {
@@ -40,7 +47,34 @@ export class HostStore {
40
47
 
41
48
  async #readJson(file, fallback) {
42
49
  const result = await readJsonFile(file, { fs: this.fs, logger: this.logger })
43
- return result.status === 'ok' ? result.value : fallback
50
+ if (result.status === 'ok') return result.value
51
+ // Only bytes that are not JSON are quarantined. A file that merely could not be read right
52
+ // now (EACCES, a transient IO error) falls back for this run and is left in place: renaming
53
+ // it would turn a permission problem into a silently emptied host list.
54
+ // A corrupt file used to fall back to `[]` / defaults silently, and the next write then
55
+ // replaced it for good — losing every host, including the pinned fingerprints that make a
56
+ // host-key change detectable. Keep the bytes aside first, then recover.
57
+ if (result.status === 'corrupt') await this.#quarantine(file)
58
+ return fallback
59
+ }
60
+
61
+ /**
62
+ * Rename one unreadable state file to `<name>.corrupt-<iso>` so it survives the recovery
63
+ * write. A failure here is logged and swallowed: recovery must not be blocked by it.
64
+ * @param {string} file - absolute path of the corrupt state file.
65
+ */
66
+ async #quarantine(file) {
67
+ const name = path.basename(file)
68
+ // The flag means "this file was unreadable", whether or not a copy could be made.
69
+ this.corrupt.add(name)
70
+ // Colons and dots are invalid (Windows) or noisy in a file name, so the ISO stamp is flattened.
71
+ const target = `${file}.corrupt-${nowIso().replace(/[:.]/g, '-')}`
72
+ try {
73
+ await this.fs.rename(file, target)
74
+ this.logger.warn?.(`[dsh-remote-go] ${name} was unreadable; kept a copy as ${path.basename(target)}`)
75
+ } catch (error) {
76
+ this.logger.warn?.(`[dsh-remote-go] cannot keep a copy of the unreadable ${name}:`, error)
77
+ }
44
78
  }
45
79
 
46
80
  #writeJson(file, value, mode = 0o600) {
@@ -51,7 +85,12 @@ export class HostStore {
51
85
  logger: this.logger,
52
86
  fileMode: mode,
53
87
  }),
54
- )
88
+ ).then((result) => {
89
+ // The recovered file is the authority again: the next successful write clears the flag,
90
+ // so a user who rebuilds the list is not warned forever about a file that is now valid.
91
+ this.corrupt.delete(path.basename(file))
92
+ return result
93
+ })
55
94
  }
56
95
 
57
96
  async #persistHosts() {
@@ -77,10 +116,14 @@ export class HostStore {
77
116
 
78
117
  async upsertHost(rawEntry, options = {}) {
79
118
  await this.load()
80
- const existing =
81
- rawEntry && typeof rawEntry === 'object' && typeof rawEntry.id === 'string' ? this.getHost(rawEntry.id) : null
119
+ // A caller may name an id only if this store already issued it: the id keys the secrets
120
+ // file, the proxy's per-host routes and the client's host links, so a client-chosen id
121
+ // (malformed, too long, or a duplicate of another host) is not something to adopt. A new
122
+ // host always gets a fresh `h_…` and learns it from the returned HostView.
123
+ const rawId = rawEntry && typeof rawEntry === 'object' && typeof rawEntry.id === 'string' ? rawEntry.id : ''
124
+ const existing = rawId === '' ? null : this.getHost(rawId)
82
125
  const entry = sanitizeHostEntry(rawEntry, { settings: options.settings ?? this.data.settings, existing })
83
- if (!entry.id) entry.id = randomId('h')
126
+ entry.id = existing ? existing.id : randomId('h')
84
127
  const index = this.data.hosts.findIndex((item) => item.id === entry.id)
85
128
  if (index >= 0) this.data.hosts[index] = { ...this.data.hosts[index], ...entry }
86
129
  else this.data.hosts.push(entry)
@@ -115,7 +158,11 @@ export class HostStore {
115
158
 
116
159
  async saveSettings(raw) {
117
160
  await this.load()
118
- this.data.settings = sanitizeSettings({ ...this.data.settings, ...(raw && typeof raw === 'object' ? raw : {}) })
161
+ const patch = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
162
+ // Merge the patch onto the *current* settings. Spreading it over the defaults reset every
163
+ // field the patch did not name — a patch of `autoReconnect.maxAttempts` also rewound
164
+ // `baseDelayMs` from a configured 5000 back to 800 — which silently undid sibling settings.
165
+ this.data.settings = sanitizeSettings(deepMerge(this.data.settings, patch))
119
166
  await this.#persistSettings()
120
167
  if (!this.data.settings.saveTokens) {
121
168
  this.secrets = {}
@@ -125,6 +172,9 @@ export class HostStore {
125
172
  }
126
173
 
127
174
  async saveToken(hostId, token) {
175
+ // Without this the first token save on a fresh process wrote `{}` over a secrets file that
176
+ // still held other hosts' tokens.
177
+ await this.load()
128
178
  if (!this.data.settings.saveTokens) return
129
179
  this.secrets[hostId] = token
130
180
  await this.#persistSecrets()