dsh-remote 1.4.1 → 1.6.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.
@@ -30,7 +30,10 @@
30
30
  // bounded four ways — entry budget, directory budget, wall-clock deadline and a
31
31
  // per-root index cache with stale-while-revalidate. A remote listing failure
32
32
  // opens a short circuit breaker for that root so a broken/unauthenticated host
33
- // cannot make every keystroke wait for an SSH connect timeout.
33
+ // cannot make every keystroke wait for an SSH connect timeout. A missing or
34
+ // unreadable DIRECTORY is not a host failure, though: it answers only its own
35
+ // query (an empty result, like the traversal skipping an unreadable subtree)
36
+ // and never opens the breaker.
34
37
 
35
38
  /** Directory basenames skipped by the remote traversal (mirrors the local
36
39
  * provider's default list, so both namespaces hide the same noise). */
@@ -136,14 +139,51 @@ export function isSafeRelativeDir(rel) {
136
139
  return !s.split('/').some((segment) => segment === '..')
137
140
  }
138
141
 
142
+ /** Error codes that describe ONE path — a missing or unreadable directory.
143
+ * ssh2 keeps SFTP statuses NUMERIC (2 = SSH_FX_NO_SUCH_FILE,
144
+ * 3 = SSH_FX_PERMISSION_DENIED); other layers reuse the Node fs names. */
145
+ const PER_PATH_ERROR_CODES = new Set([
146
+ 2, 3, // ssh2: SSH_FX_NO_SUCH_FILE / SSH_FX_PERMISSION_DENIED
147
+ 'NO_SUCH_FILE', 'NO_SUCH_PATH', 'PERMISSION_DENIED',
148
+ 'ENOENT', 'ENOTDIR', 'EACCES', 'EPERM',
149
+ ])
150
+
151
+ /**
152
+ * Whether a `readDir` failure describes THIS directory (missing or
153
+ * unreadable) rather than the whole transport. A per-path failure answers one
154
+ * query empty — the same degradation scan() applies to an unreadable subtree —
155
+ * instead of surfacing to the overlay's breaker, which would exile every LEGAL
156
+ * query to the local mirror for failureCooldownMs. Transport failures (a broken
157
+ * pool or connection: `ssh sftp failed: …`, `ECONNREFUSED`, handshake
158
+ * timeouts, a generic SFTP `Failure`) match neither branch and keep throwing.
159
+ * main.js's `listDir` re-wraps SFTP errors as `browse failed: <message>`
160
+ * without a code, so the per-path wording is matched as well.
161
+ *
162
+ * @param {unknown} err
163
+ * @returns {boolean}
164
+ */
165
+ function isPerPathError(err) {
166
+ if (err && typeof err === 'object' && PER_PATH_ERROR_CODES.has(err.code)) return true
167
+ const msg = String((err && err.message) || err)
168
+ // Transport markers win over per-path wording: an OpenSSH handshake failure
169
+ // reaches here as "sftp session to <dest> timed out: Permission denied
170
+ // (publickey)" — classifying THAT per-path would make every keystroke pay a
171
+ // full connect timeout without ever tripping the breaker, the exact stall
172
+ // the breaker exists to prevent. Any transport-shaped message is the
173
+ // transport's failure, whatever else it also says.
174
+ if (/ssh sftp failed|sftp session|timed out|econnrefused|econnreset|econnaborted|enotfound|connection|handshake|host key|not connected|channel closed/i.test(msg)) return false
175
+ return /no such file|no such path|not found|does not exist|permission denied|access denied|enoent|enotdir|eacces|eperm/i.test(msg)
176
+ }
177
+
139
178
  /**
140
179
  * Cancellable, cached remote-tree index rooted at one remote workspace.
141
180
  *
142
181
  * `listDir(relDir)` is injected: it returns the direct children of a
143
182
  * workspace-relative directory ('' = the workspace root) as
144
- * `{ name, kind: 'file'|'directory' }` and throws when the host/directory is
145
- * unreachable. Everything else here is pure logic, which is what the unit tests
146
- * exercise without an SSH server.
183
+ * `{ name, kind: 'file'|'directory' }` and throws when the transport fails
184
+ * (a missing or unreadable directory throws too, and `listDirectory()`
185
+ * degrades that per-query). Everything else here is pure logic, which is what
186
+ * the unit tests exercise without an SSH server.
147
187
  */
148
188
  export class RemoteWorkspaceIndex {
149
189
  /**
@@ -230,7 +270,21 @@ export class RemoteWorkspaceIndex {
230
270
  const rel = displayDirectory.replace(/\/+$/, '')
231
271
  if (!isSafeRelativeDir(rel)) return []
232
272
  if (rel.split('/').some((segment) => this.excluded.has(segment))) return []
233
- const items = await this.readDir(rel)
273
+ let items
274
+ try {
275
+ items = await this.readDir(rel)
276
+ } catch (err) {
277
+ // An aborted keystroke is not a listing failure.
278
+ if (signal && signal.aborted) throw err
279
+ // A missing or unreadable directory (a typo like `@nope/fi`, an EACCES
280
+ // subtree) answers only THIS query, so it degrades to an empty result
281
+ // exactly like scan() skipping an unreadable subtree — it must not reach
282
+ // the overlay's breaker and exile every LEGAL query to the local mirror
283
+ // for failureCooldownMs. Transport-level failures still surface for that.
284
+ if (!isPerPathError(err)) throw err
285
+ this.onError?.(err)
286
+ items = []
287
+ }
234
288
  throwIfAborted(signal)
235
289
  const candidates = []
236
290
  for (const item of items) {
@@ -351,8 +405,10 @@ function waitFor(promise, signal) {
351
405
  * that keeps a broken host from stalling every keystroke.
352
406
  *
353
407
  * `list()` never rejects: it returns `null` when the breaker is open or the
354
- * remote listing failed, which tells the overlay to fall back to the original
355
- * (local) provider instead of showing an empty list.
408
+ * remote listing failed at the transport level, which tells the overlay to fall
409
+ * back to the original (local) provider instead of showing an empty list. (A
410
+ * missing or unreadable directory answers `[]` instead — a per-path failure
411
+ * is not a host failure, see isPerPathError.)
356
412
  */
357
413
  export function createRemoteFileReference({ listDir, config = {}, onError, now }) {
358
414
  const index = new RemoteWorkspaceIndex({ listDir, ...config, onError, now })
package/lib/forwards.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // piped through the SSH channel to <targetHost>:<targetPort> on the remote.
5
5
  // Reverse forward: ask the remote to listen on 127.0.0.1:<listenPort> and pipe
6
6
  // incoming connections back to <targetHost>:<targetPort> on the LOCAL side
7
- // (ssh2 `forwardIn` + the client `tcpip` event; requires AllowTcpForwarding on
7
+ // (ssh2 `forwardIn` + the client `tcp connection` event; requires AllowTcpForwarding on
8
8
  // the remote sshd).
9
9
  //
10
10
  // Definitions persist in forwards.json; forwards become active only while the
@@ -31,7 +31,7 @@ export class ForwardManager {
31
31
  this.file = file || null
32
32
  this.defs = this._load()
33
33
  this._migrateLegacy()
34
- this.servers = new Map() // id → { server | remoteListen, sockets:Set, client }
34
+ this.servers = new Map() // id → active local or reverse entry
35
35
  this.starting = new Map() // id → in-flight start promise (see start())
36
36
  /** id → attempt counter; bumping it invalidates a late start result. */
37
37
  this.startGeneration = new Map()
@@ -111,6 +111,10 @@ export class ForwardManager {
111
111
  this.client = client
112
112
  this.connectedMachineId = mid
113
113
  this.onTcpip = (info, accept, reject) => this._handleTcpip(info, accept, reject)
114
+ // ssh2 emits 'tcp connection' for forwarded-tcpip channels. Some very old
115
+ // releases used 'tcpip'; listen to both so neither name leaves the remote
116
+ // listener open with every incoming connection hanging.
117
+ client.on('tcp connection', this.onTcpip)
114
118
  client.on('tcpip', this.onTcpip)
115
119
  // A socket can die WITHOUT the pool calling detach() first (network drop,
116
120
  // keepalive timeout): drop the dead handle so the next start() attaches the
@@ -159,7 +163,10 @@ export class ForwardManager {
159
163
  this.stopAll()
160
164
  this.connGeneration += 1
161
165
  if (this.client) {
162
- if (this.onTcpip) this.client.removeListener('tcpip', this.onTcpip)
166
+ if (this.onTcpip) {
167
+ this.client.removeListener('tcp connection', this.onTcpip)
168
+ this.client.removeListener('tcpip', this.onTcpip)
169
+ }
163
170
  if (this.onClose) this.client.removeListener('close', this.onClose)
164
171
  }
165
172
  this.client = null
@@ -376,17 +383,37 @@ export class ForwardManager {
376
383
  // user-defined local forward. `attach()` does register a `close`
377
384
  // listener that calls stopAll(), but a request can arrive in the window
378
385
  // between the connection dying and that event.
379
- forwardOutChannel(client, { dstHost: d.targetHost, dstPort: d.targetPort }).then((channel) => {
386
+ //
387
+ // The issue #54 line has a SECOND window here, same fatal destination:
388
+ // a live forwardOut resolves on a later turn (the SSH round-trip), and
389
+ // this handler used to wire the socket's 'error' listener only in the
390
+ // .then(). A client that reset in between emitted 'error' with no
391
+ // listener — an uncaught exception from TCP.onconnection, identical in
392
+ // effect to the throw above. Wire the socket the moment it is accepted,
393
+ // before forwardOut is called; `kill` stays idempotent so the late
394
+ // channel wiring can neither double-register nor resurrect a dead pair.
395
+ let dead = false
396
+ let channel = null
397
+ const kill = () => {
398
+ dead = true
399
+ try { socket.destroy() } catch { /* already gone */ }
400
+ try { if (channel) channel.close() } catch { /* already closed */ }
401
+ }
402
+ socket.on('error', kill)
403
+ socket.on('close', kill)
404
+ forwardOutChannel(client, { dstHost: d.targetHost, dstPort: d.targetPort }).then((ch) => {
405
+ // The round-trip can land after the client already reset: close the
406
+ // fresh channel rather than pipe it into a destroyed socket, or every
407
+ // mid-window reset leaks one remote channel.
408
+ channel = ch || null
409
+ if (dead) { kill(); return }
380
410
  socket.pipe(channel)
381
411
  channel.pipe(socket)
382
- const kill = () => { try { socket.destroy() } catch {}; try { channel.close() } catch {} }
383
- socket.on('error', kill)
384
412
  channel.on('error', kill)
385
- socket.on('close', kill)
386
413
  channel.on('close', kill)
387
414
  }).catch(() => {
388
415
  // A dead tunnel is a UI state, not a reason to exit.
389
- try { socket.destroy() } catch { /* already gone */ }
416
+ kill()
390
417
  })
391
418
  })
392
419
  server.on('error', (e) => reject(new Error(`本地转发 ${d.listenPort} 启动失败: ${e.message}`)))
@@ -428,9 +455,15 @@ export class ForwardManager {
428
455
  if (typeof client.forwardIn !== 'function') {
429
456
  return reject(new Error('此 ssh2 版本不支持反向转发 (forwardIn)'))
430
457
  }
431
- client.forwardIn('127.0.0.1', d.listenPort, (err) => {
432
- if (err) return reject(new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`))
433
- resolve({ kind: 'reverse', sockets: new Set(), client })
458
+ // Capture the bind port BEFORE forwardIn runs: the update route refuses
459
+ // bind changes only for registered forwards, so the definition can be
460
+ // EDITED while the bind is still in flight. The entry must carry the
461
+ // port this attempt actually bound — dispatch and teardown must never
462
+ // re-read the (possibly mutated) definition for it.
463
+ const listenPort = Number(d.listenPort)
464
+ client.forwardIn('127.0.0.1', listenPort, (err) => {
465
+ if (err) return reject(new Error(`远端监听 ${listenPort} 失败: ${(err && err.message) || err}`))
466
+ resolve({ kind: 'reverse', connections: new Set(), client, listenPort })
434
467
  })
435
468
  })
436
469
  }
@@ -438,22 +471,23 @@ export class ForwardManager {
438
471
  _handleTcpip(info, accept, reject) {
439
472
  // Only the ssh2 backend reaches here: `ssh -R` handles the remote listener
440
473
  // and its targets entirely inside the CLI, so a 'reverse-cli' entry never
441
- // produces a 'tcpip' event.
474
+ // produces a 'tcp connection' event.
442
475
  for (const entry of this.servers.values()) {
443
- if (entry.kind === 'reverse' && Number(info.destPort) === Number(this._defFor(entry).listenPort)) {
476
+ if (entry.kind === 'reverse' && Number(info.destPort) === this._reversePort(entry)) {
444
477
  const channel = accept()
445
478
  const socket = this.net.connect({ host: this._defFor(entry).targetHost, port: this._defFor(entry).targetPort })
446
- socket.pipe(channel)
447
- channel.pipe(socket)
448
- entry.sockets.add(socket)
449
- const kill = () => {
479
+ const close = () => {
480
+ if (!entry.connections.delete(close)) return
450
481
  try { socket.destroy() } catch {}
451
482
  try { channel.close() } catch {}
452
- entry.sockets.delete(socket)
453
483
  }
454
- socket.on('error', kill)
455
- channel.on('error', kill)
456
- socket.on('close', kill)
484
+ entry.connections.add(close)
485
+ socket.on('error', close)
486
+ channel.on('error', close)
487
+ socket.once('close', close)
488
+ channel.once('close', close)
489
+ socket.pipe(channel)
490
+ channel.pipe(socket)
457
491
  return
458
492
  }
459
493
  }
@@ -467,6 +501,18 @@ export class ForwardManager {
467
501
  return { listenPort: 0, targetHost: '127.0.0.1', targetPort: 0 }
468
502
  }
469
503
 
504
+ /**
505
+ * The remote port a reverse entry actually bound. The entry records it at
506
+ * bind time because the definition can be EDITED while the bind is in
507
+ * flight (the route's bind-change refusal only sees registered forwards);
508
+ * dispatch and unforwardIn must follow the live listener, not the mutated
509
+ * row. Entries from before the port was recorded keep reading the
510
+ * definition.
511
+ */
512
+ _reversePort(entry) {
513
+ return entry.listenPort !== undefined ? Number(entry.listenPort) : Number(this._defFor(entry).listenPort)
514
+ }
515
+
470
516
  /**
471
517
  * Stop one listener. `forget` is for the user-initiated stop in the route:
472
518
  * it clears the persisted `lastActive`, so 自动重连 will not bring the tunnel
@@ -500,14 +546,17 @@ export class ForwardManager {
500
546
  } else if (entry.kind === 'reverse-cli') {
501
547
  // The `ssh -R` child IS the tunnel: killing it closes the remote listener.
502
548
  if (entry.handle && typeof entry.handle.close === 'function') entry.handle.close()
503
- } else if (entry.client && typeof entry.client.unforwardIn === 'function') {
549
+ } else if (entry.kind === 'reverse') {
504
550
  const current = this.servers.get(d.id)
551
+ // Stop accepting connections before closing the established pairs.
552
+ if (current === entry) this.servers.delete(d.id)
553
+ for (const close of entry.connections) close()
505
554
  // ssh2 unforwardIn is keyed by client + port, NOT by our entry. If a
506
555
  // newer attempt already owns that same remote listener on this client,
507
556
  // a stale attempt must not close it. Normal Stop sees current===entry
508
557
  // and still unforwards; with no replacement, stale cleanup can proceed.
509
558
  if (!current || current === entry || current.client !== entry.client) {
510
- entry.client.unforwardIn('127.0.0.1', d.listenPort, () => {})
559
+ entry.client?.unforwardIn?.('127.0.0.1', this._reversePort(entry), () => {})
511
560
  }
512
561
  }
513
562
  } catch {}
package/lib/host-api.js CHANGED
@@ -29,8 +29,8 @@ import {
29
29
  deleteMirrorTree,
30
30
  deleteSessionsFor,
31
31
  dirSizeBytes,
32
- listMirrorEntries,
33
32
  listSessionDirs,
33
+ listWorkspaceSessionDirs,
34
34
  validateMirror,
35
35
  } from './workspace-cleanup.js'
36
36
 
@@ -527,27 +527,22 @@ export function createHostApi(deps = {}) {
527
527
  for (const record of registered) {
528
528
  if (record && typeof record.path === 'string') byPath.set(String(record.path), record)
529
529
  }
530
+ const candidates = projects.filter((project) => project?.dir
531
+ && (!wantedMachine || String(project.machineId || '') === wantedMachine))
532
+ const sessionsByCwd = listWorkspaceSessionDirs({ sessionsRoot, cwds: candidates.map((project) => project.dir) })
530
533
  const out = []
531
- for (const project of projects) {
532
- if (!project || !project.dir) continue
533
- if (wantedMachine && String(project.machineId || '') !== wantedMachine) continue
534
+ for (const project of candidates) {
534
535
  const machine = machines.find((m) => m && String(m.id) === String(project.machineId))
535
536
  || machines.find((m) => m && String(m.host) === String(project.host)
536
537
  && (Number(m.port) || 22) === (Number(project.port) || 22)
537
538
  && String(m.username || '') === String(project.username || ''))
538
539
  if (wantedMachine && !machine) continue
539
- let sessionList
540
- try {
541
- sessionList = listSessionDirs({ sessionsRoot, cwd: project.dir, cwds: [String(project.dir)] })
542
- } catch {
543
- sessionList = []
544
- }
545
540
  const sessions = []
546
- for (const session of sessionList) {
541
+ for (const session of sessionsByCwd.get(project.dir)) {
547
542
  sessions.push({
548
543
  id: String(session.id || ''),
549
544
  modifiedAt: Number(session.modifiedAt) || 0,
550
- live: await liveCheck(session.id, session.dir),
545
+ live: await liveCheck(session.id, session.dir, { cwd: project.dir }),
551
546
  })
552
547
  }
553
548
  let size
@@ -606,12 +601,10 @@ export function createHostApi(deps = {}) {
606
601
  } catch (err) {
607
602
  throw asApiError(err)
608
603
  }
609
- const cwdAliases = [...new Set([validated.real, String(o.localMirror || '')].filter(Boolean))]
610
604
  const report = await deleteSessionsFor({
611
605
  sessionsRoot,
612
606
  cwd: validated.real,
613
- cwds: cwdAliases,
614
- isLive: (id, dir) => liveCheck(id, dir, { deep: true }),
607
+ isLive: (id, dir) => liveCheck(id, dir, { cwd: validated.real, deep: true }),
615
608
  force: o.force === true,
616
609
  })
617
610
  emit('status')
@@ -649,36 +642,32 @@ export function createHostApi(deps = {}) {
649
642
  }
650
643
  const deleteSessions = o.deleteSessions !== false
651
644
  const force = o.force === true
652
- let pending = []
653
- if (deleteSessions) {
645
+ const cwd = validated.real
646
+ if (!force) {
647
+ const live = new Set()
654
648
  try {
655
- pending = listSessionDirs({ sessionsRoot, cwd: validated.real, cwds: [String(o.localMirror || '')] })
656
- } catch {
657
- pending = []
658
- }
659
- if (!force && pending.length > 0) {
660
- const live = []
661
- for (const session of pending) {
662
- if (await liveCheck(session.id, session.dir, { deep: true })) live.push(session.id)
663
- }
664
- if (live.length > 0) {
665
- const error = apiError(
666
- 'WORKSPACE_BUSY',
667
- `还有 ${live.length} 个会话正在使用该工作区,请先在会话管理里停止它们(或退出对应终端)再删除`,
668
- )
669
- error.liveSessions = live
670
- throw error
649
+ for (const id of deps.listLiveWorkspaceSessions?.(cwd) || []) live.add(id)
650
+ } catch { /* sessions service unavailable */ }
651
+ for (const session of listSessionDirs({ sessionsRoot, cwd })) {
652
+ if (!live.has(session.id) && await liveCheck(session.id, session.dir, { cwd, deep: true })) {
653
+ live.add(session.id)
671
654
  }
672
655
  }
656
+ if (live.size > 0) {
657
+ const error = apiError(
658
+ 'WORKSPACE_BUSY',
659
+ `还有 ${live.size} 个会话正在使用该工作区,请先在会话管理里停止它们(或退出对应终端)再删除`,
660
+ )
661
+ error.liveSessions = [...live]
662
+ throw error
663
+ }
673
664
  }
674
665
  let sessionReport = { removed: [], skippedLive: [] }
675
666
  if (deleteSessions) {
676
- const cwdAliases = [...new Set([validated.real, String(o.localMirror || '')].filter(Boolean))]
677
667
  sessionReport = await deleteSessionsFor({
678
668
  sessionsRoot,
679
- cwd: validated.real,
680
- cwds: cwdAliases,
681
- isLive: (id, dir) => liveCheck(id, dir, { deep: true }),
669
+ cwd,
670
+ isLive: (id, dir) => liveCheck(id, dir, { cwd, deep: true }),
682
671
  force,
683
672
  })
684
673
  if (!force && sessionReport.skippedLive.length > 0) {
package/lib/hostkey.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // ssh2 v1.17) is unit-tested against the REAL wire shape — the v0.6.7 bug
4
4
  // class ("mock object hid a contract drift") must not regress.
5
5
  import { createHash } from 'node:crypto'
6
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
6
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
7
7
  import path from 'node:path'
8
8
 
9
9
  /**
@@ -36,30 +36,147 @@ export function keyFingerprint(key) {
36
36
  return createHash('sha256').update(blob).digest('base64')
37
37
  }
38
38
 
39
- export function loadKnownHosts(file) {
40
- if (!file) return {}
39
+ // ── known_hosts trust store: durable writes, visible incidents ──────────────
40
+ //
41
+ // Continues the "never a half-written file" line lib/update.js writeFileAtomic
42
+ // established for installed files (0.8.24, 2d7d9de): createHostKeyGuard used a
43
+ // bare writeFileSync, so a crash mid-write could truncate the store, and
44
+ // loadKnownHosts swallowed ANY parse failure into {} — a truncated store then
45
+ // made isHostKeyKnown false for everything, and a DIFFERENT key (simulated
46
+ // MITM) was silently accepted via accept-new with no signal at all. The store
47
+ // is now written atomically, and an existing-but-unparseable store is an
48
+ // INCIDENT: moved aside as evidence and surfaced through guard.lastError +
49
+ // lastKnownHostsCorruption() + one console.warn (the same "an incident nothing
50
+ // can observe is indistinguishable from one that never happened" rule
51
+ // lib/update.js lastSelfReload enforces), while TOFU keeps accepting unknown
52
+ // hosts — the ssh2 hostVerifier boolean contract is unchanged.
53
+
54
+ /** Most recent known_hosts corruption incident, for diagnostics. */
55
+ let lastCorruptIncident = null
56
+
57
+ /** @returns the latest known_hosts corruption incident
58
+ * (`{ file, error, at, movedTo, moveError? }`, `movedTo` empty when the
59
+ * move-aside failed), or null when none occurred in this process. */
60
+ export function lastKnownHostsCorruption() {
61
+ return lastCorruptIncident
62
+ }
63
+
64
+ /**
65
+ * Move an unparseable known_hosts file aside (`<file>.corrupt-<UTC stamp>`) so
66
+ * the evidence survives and the next write starts from a clean slate — never
67
+ * deleted, never overwritten. Best-effort: when the move fails (read-only
68
+ * directory, exotic filesystem) the file stays put and the incident is still
69
+ * recorded; TOFU continues either way.
70
+ */
71
+ function quarantineKnownHosts(file, reason) {
72
+ const incident = { file, error: reason, at: new Date().toISOString(), movedTo: '' }
73
+ try {
74
+ const stamp = incident.at.replace(/[:.]/g, '-')
75
+ let movedTo = `${file}.corrupt-${stamp}`
76
+ for (let n = 1; existsSync(movedTo); n++) movedTo = `${file}.corrupt-${stamp}-${n}`
77
+ renameSync(file, movedTo)
78
+ incident.movedTo = movedTo
79
+ } catch (error) {
80
+ incident.moveError = String((error && error.message) || error)
81
+ }
82
+ lastCorruptIncident = incident
83
+ // The next connect usually SUCCEEDS (TOFU restarts), so no failure path will
84
+ // print this for us — say it once here, like scheduleSelfReload does.
85
+ console.warn(
86
+ `[dsh-remote] known_hosts trust store is corrupt (${reason}); ` +
87
+ (incident.movedTo ? `moved aside to ${incident.movedTo}` : `could not move it aside: ${incident.moveError}`) +
88
+ ' — stored host keys were lost; review the moved-aside file before trusting new keys',
89
+ )
90
+ return incident
91
+ }
92
+
93
+ /**
94
+ * Read + parse the JSON trust store. A MISSING file is the normal TOFU start
95
+ * (`{ hosts: {} }`); an EXISTING file that cannot be read or parsed as a plain
96
+ * object is an incident — quarantined and reported through `incident` — while
97
+ * `hosts` stays `{}` so every boolean caller (isHostKeyKnown, the ssh2
98
+ * hostVerifier) keeps its exact contract.
99
+ */
100
+ function readKnownHosts(file) {
101
+ if (!file) return { hosts: {} }
102
+ let raw
103
+ try {
104
+ raw = readFileSync(file, 'utf8')
105
+ } catch (error) {
106
+ if (error && error.code === 'ENOENT') return { hosts: {} }
107
+ return { hosts: {}, incident: quarantineKnownHosts(file, `unreadable (${(error && error.message) || error})`) }
108
+ }
109
+ let parsed
41
110
  try {
42
- const j = JSON.parse(readFileSync(file, 'utf8'))
43
- if (j && typeof j === 'object' && !Array.isArray(j)) return j
44
- } catch {}
45
- return {}
111
+ parsed = JSON.parse(raw)
112
+ } catch (error) {
113
+ return { hosts: {}, incident: quarantineKnownHosts(file, `invalid JSON (${(error && error.message) || error})`) }
114
+ }
115
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return { hosts: parsed }
116
+ const shape = parsed === null ? 'null' : Array.isArray(parsed) ? 'an array' : typeof parsed
117
+ return { hosts: {}, incident: quarantineKnownHosts(file, `not a JSON object (${shape})`) }
118
+ }
119
+
120
+ /** Best-effort known_hosts read: the host map only (corrupt stores are
121
+ * quarantined inside — see readKnownHosts). */
122
+ export function loadKnownHosts(file) {
123
+ return readKnownHosts(file).hosts
46
124
  }
47
125
 
48
126
  export function isHostKeyKnown(file, host, port) {
49
127
  return Object.prototype.hasOwnProperty.call(loadKnownHosts(file), `${host}:${port}`)
50
128
  }
51
129
 
130
+ /**
131
+ * Write the trust store atomically: the bytes land in a sibling temp file and
132
+ * are renamed over the target, so a crash mid-write leaves the previous store
133
+ * intact — never a truncated file. Falls back to an in-place copy when the
134
+ * platform refuses the rename, and never leaves the temp file behind.
135
+ *
136
+ * Deliberately NOT lib/update.js writeFileAtomic re-imported: this module is a
137
+ * low-level helper on the SSH connect path, and importing the self-update
138
+ * module (network/proxy machinery, an import-time LOADED_VERSION snapshot)
139
+ * here would invert the dependency direction and couple every connect to the
140
+ * updater.
141
+ */
142
+ function writeKnownHostsAtomic(file, data) {
143
+ const tmp = `${file}.dsh-tmp-${process.pid}-${Date.now().toString(36)}`
144
+ writeFileSync(tmp, data)
145
+ try {
146
+ renameSync(tmp, file)
147
+ } catch {
148
+ try {
149
+ copyFileSync(tmp, file)
150
+ } finally {
151
+ try { rmSync(tmp, { force: true }) } catch {}
152
+ }
153
+ }
154
+ }
155
+
52
156
  /** Build an ssh2 `hostVerifier` bound to the current config + known_hosts file. */
53
157
  export function createHostKeyGuard(config, knownHostsFile) {
54
158
  const id = () => `${config.host}:${config.port}`
55
159
  const mode = config.hostKeyMode === 'verify' || config.hostKeyMode === 'off'
56
160
  ? config.hostKeyMode
57
161
  : 'accept-new'
58
- const read = () => loadKnownHosts(knownHostsFile)
162
+ let incidentNote = ''
163
+ const read = () => {
164
+ const { hosts, incident } = readKnownHosts(knownHostsFile)
165
+ incidentNote = incident
166
+ ? `known_hosts trust store was corrupt (${incident.error}); ` +
167
+ (incident.movedTo ? `moved aside to ${incident.movedTo}` : `move-aside failed (${incident.moveError})`) +
168
+ ' — every stored host key was lost, so keys presented now are accepted as NEW (TOFU restart)'
169
+ : ''
170
+ // Surface the incident through the guard's existing reporting channel
171
+ // (pool.js classifies guard.lastError on connect failure). The boolean
172
+ // contract is untouched: TOFU still accepts the unknown host.
173
+ if (incident) guard.lastError = incidentNote
174
+ return hosts
175
+ }
59
176
  const write = (kh) => {
60
177
  if (!knownHostsFile) return
61
178
  try { mkdirSync(path.dirname(knownHostsFile), { recursive: true }) } catch {}
62
- writeFileSync(knownHostsFile, JSON.stringify(kh, null, 2))
179
+ writeKnownHostsAtomic(knownHostsFile, JSON.stringify(kh, null, 2))
63
180
  }
64
181
  const guard = {
65
182
  mode,
@@ -83,7 +200,8 @@ export function createHostKeyGuard(config, knownHostsFile) {
83
200
  return false
84
201
  }
85
202
  if (mode === 'verify') {
86
- guard.lastError = `unknown host key for ${id()} (hostKeyMode=verify) — trust it first with accept-new`
203
+ guard.lastError = `unknown host key for ${id()} (hostKeyMode=verify) — trust it first with accept-new` +
204
+ (incidentNote ? `; note: ${incidentNote}` : '')
87
205
  return false
88
206
  }
89
207
  kh[id()] = { algo: blobAlgorithm(key) || (key && key.algo) || 'unknown', fingerprint: fp, firstSeen: new Date().toISOString() }