dsh-remote-go 0.3.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 (85) hide show
  1. package/dist/client.js +1344 -2095
  2. package/dist/src/admission.js +3 -28
  3. package/dist/src/api.js +37 -99
  4. package/dist/src/atomic-json.js +32 -66
  5. package/dist/src/bootstrap.js +17 -27
  6. package/dist/src/connect/attach.js +3 -25
  7. package/dist/src/connect/bootstrap.js +2 -8
  8. package/dist/src/connect/failures.js +3 -18
  9. package/dist/src/connect/guards.js +13 -8
  10. package/dist/src/connect/launch.js +11 -21
  11. package/dist/src/connect/links.js +11 -27
  12. package/dist/src/connect/ownership.js +33 -114
  13. package/dist/src/connect/pipeline.js +61 -158
  14. package/dist/src/connect/reattach.js +20 -44
  15. package/dist/src/connect/registry.js +0 -1
  16. package/dist/src/connect/repair.js +8 -37
  17. package/dist/src/connect/restart.js +36 -97
  18. package/dist/src/connect/stop.js +16 -50
  19. package/dist/src/connect/transport.js +10 -18
  20. package/dist/src/connect/verify.js +3 -12
  21. package/dist/src/connect/watchdog.js +6 -38
  22. package/dist/src/connect-log.js +16 -41
  23. package/dist/src/connect-progress.js +13 -45
  24. package/dist/src/constants.js +2 -40
  25. package/dist/src/context.js +10 -31
  26. package/dist/src/diagnostics.js +56 -25
  27. package/dist/src/download-jobs.js +11 -20
  28. package/dist/src/errors.js +175 -190
  29. package/dist/src/events.js +20 -84
  30. package/dist/src/host-lifecycle.js +39 -175
  31. package/dist/src/host-registry.js +27 -78
  32. package/dist/src/host-runtime.js +0 -9
  33. package/dist/src/host-view.js +6 -29
  34. package/dist/src/index.js +15 -35
  35. package/dist/src/kernel-adapter.js +34 -80
  36. package/dist/src/key-files.js +10 -23
  37. package/dist/src/known-hosts.js +13 -34
  38. package/dist/src/layout.js +3 -20
  39. package/dist/src/local-download.js +94 -163
  40. package/dist/src/local-ssh.js +12 -19
  41. package/dist/src/local-version.js +35 -49
  42. package/dist/src/node/download.js +1 -4
  43. package/dist/src/node-runtime.js +19 -38
  44. package/dist/src/probe.js +6 -7
  45. package/dist/src/prompts.js +56 -128
  46. package/dist/src/proxy/cookies.js +26 -60
  47. package/dist/src/proxy/headers.js +30 -125
  48. package/dist/src/proxy/http.js +33 -41
  49. package/dist/src/proxy/index.js +20 -34
  50. package/dist/src/proxy/limits.js +4 -6
  51. package/dist/src/proxy/routes.js +10 -17
  52. package/dist/src/proxy/upgrade.js +27 -42
  53. package/dist/src/redact.js +14 -33
  54. package/dist/src/remote-files.js +9 -21
  55. package/dist/src/remote-path.js +21 -62
  56. package/dist/src/remote-proc.js +35 -103
  57. package/dist/src/remote-web/registry.js +10 -50
  58. package/dist/src/remote-web/resolve.js +23 -104
  59. package/dist/src/remote-web/start.js +27 -64
  60. package/dist/src/remote-web/stop.js +6 -25
  61. package/dist/src/request-trust.js +15 -32
  62. package/dist/src/runtime/dispatch.js +33 -143
  63. package/dist/src/runtime/effects.js +7 -17
  64. package/dist/src/runtime/events.js +1 -1
  65. package/dist/src/runtime/fsm.js +11 -61
  66. package/dist/src/runtime/rules.js +113 -198
  67. package/dist/src/secrets.js +15 -38
  68. package/dist/src/service.js +22 -128
  69. package/dist/src/settings.js +41 -42
  70. package/dist/src/ssh-config.js +22 -41
  71. package/dist/src/ssh-failures.js +23 -74
  72. package/dist/src/ssh-sftp.js +47 -86
  73. package/dist/src/ssh.js +95 -177
  74. package/dist/src/store.js +31 -48
  75. package/dist/src/tool-shared.js +17 -52
  76. package/dist/src/tools-exec-policy.js +33 -79
  77. package/dist/src/tools-exec.js +87 -151
  78. package/dist/src/tools-report.js +100 -167
  79. package/dist/src/tools.js +59 -133
  80. package/dist/src/tunnel.js +9 -27
  81. package/dist/src/util.js +19 -56
  82. package/dist/src/version.js +6 -12
  83. package/dist/src/watchdog-bus.js +0 -8
  84. package/dist/src/watchdog.js +7 -47
  85. package/package.json +1 -1
package/dist/src/ssh.js CHANGED
@@ -1,15 +1,6 @@
1
- /**
2
- * The ssh2 adapter for `SshPort` (design-ssh §4).
3
- *
4
- * `SshConnection` is the only class in `src/` that talks to `vendor/ssh2.bundle.cjs`; every other
5
- * module depends on `src/ssh-port.ts`. The class name and its constructor are frozen until P7
6
- * because four integration suites construct it directly against a real (simulated) SSH server.
7
- *
8
- * What lives here is the transport itself: auth-candidate fallback, the five-step host-key
9
- * decision, the handshake lifecycle (including "emit `close` before rejecting during a
10
- * handshake"), `exec`, `forwardOut` and `dispose`. Two concerns moved out without changing a call
11
- * site: the SFTP capability (`ssh-sftp.ts`) and the failure classification (`ssh-failures.ts`).
12
- */
1
+ /** The ssh2 adapter for `SshPort`, the only class here that talks to `vendor/ssh2.bundle.cjs`; its name and constructor
2
+ * are frozen (four integration suites build it directly). It owns auth fallback, the host-key decision, the handshake
3
+ * lifecycle, `exec`/`forwardOut`/`dispose`; SFTP and failure classification live in the two sibling modules. */
13
4
  import { EventEmitter } from 'node:events';
14
5
  import { open } from 'node:fs/promises';
15
6
  import { homedir } from 'node:os';
@@ -22,7 +13,7 @@ import { DEFAULT_EXEC_MAX_BYTES, DEFAULT_EXEC_TIMEOUT_MS, } from './ssh-port.js'
22
13
  import { endSftp, inspectSftpPath, openSftpSession, saveSftpFile, saveSftpTree } from './ssh-sftp.js';
23
14
  import { expandHome } from './util.js';
24
15
  const { Client } = ssh2;
25
- /** Settle a promise at most once; later calls are ignored, so callers need no flag. */
16
+ /** Settle a promise at most once (later calls are ignored), so callers need no flag. */
26
17
  function oneShot(resolve, reject, cleanup) {
27
18
  let settled = false;
28
19
  return (error, value) => {
@@ -30,12 +21,8 @@ function oneShot(resolve, reject, cleanup) {
30
21
  return;
31
22
  settled = true;
32
23
  cleanup?.();
33
- if (error)
34
- reject(error);
35
- // The settled-once contract passes exactly one of error/value, so the success branch
36
- // always carries the value this `as` restates (the optional parameter cannot express it).
37
- else
38
- resolve(value);
24
+ // The settled-once contract passes exactly one of error/value, so the success branch carries it.
25
+ error ? reject(error) : resolve(value);
39
26
  };
40
27
  }
41
28
  export function parseSshKeyType(blob) {
@@ -52,14 +39,15 @@ export function parseSshKeyType(blob) {
52
39
  return 'unknown';
53
40
  }
54
41
  }
55
- /**
56
- * The ssh2 implementation of `SshPort`.
57
- *
58
- * Every failure it produces is a `RemoteGoError` (through `classifySshFailure` / `closedError`),
59
- * and the SFTP capabilities are declared, so `typeof port.saveRemoteFile === 'function'` is how a
60
- * caller tells them from a transport that cannot download.
61
- */
42
+ /** The ssh2 implementation of `SshPort`: every failure is a `RemoteGoError`, and the download members are declared. */
62
43
  export class SshConnection extends EventEmitter {
44
+ client = null;
45
+ fingerprint = null;
46
+ keyType = null;
47
+ closed = false;
48
+ disposed = false;
49
+ hostKeyDecision = null;
50
+ clientFactory = () => new Client();
63
51
  constructor(options) {
64
52
  super();
65
53
  this.options = {
@@ -73,18 +61,10 @@ export class SshConnection extends EventEmitter {
73
61
  ...options,
74
62
  identityFiles: options.identityFiles ?? [],
75
63
  };
76
- this.client = null;
77
- this.fingerprint = null;
78
- this.keyType = null;
79
- this.closed = false;
80
- this.disposed = false;
81
- this.hostKeyDecision = null;
82
- // ssh2 clients emit `error` for every failed auth attempt and again while
83
- // tearing down. EventEmitter treats an unhandled `error` as a thrown
84
- // exception, which would take down the whole DSH host process; keep a
85
- // permanent safety listener so failures stay inside this connection.
64
+ // ssh2 emits `error` on every failed auth attempt and while tearing down; unhandled, it would kill the Host.
86
65
  this.on('error', () => { });
87
- this.clientFactory = typeof options.clientFactory === 'function' ? options.clientFactory : () => new Client();
66
+ if (typeof options.clientFactory === 'function')
67
+ this.clientFactory = options.clientFactory;
88
68
  }
89
69
  get connected() {
90
70
  return this.client !== null && !this.closed;
@@ -103,9 +83,7 @@ export class SshConnection extends EventEmitter {
103
83
  for (const candidate of candidates) {
104
84
  try {
105
85
  const info = await this.connectOnce(candidate);
106
- this.client?.on('error', (error) => {
107
- this.emit('error', error);
108
- });
86
+ this.client?.on('error', (error) => this.emit('error', error));
109
87
  return info;
110
88
  }
111
89
  catch (error) {
@@ -122,48 +100,34 @@ export class SshConnection extends EventEmitter {
122
100
  return new Promise((resolve, reject) => {
123
101
  const settle = oneShot(resolve, reject);
124
102
  const client = this.clientFactory();
103
+ const endpoint = { host: this.options.host, port: this.options.port };
125
104
  this.client = client;
126
- // A rejected earlier candidate tears its transport down through
127
- // `cleanupClient()`, which marks this object closed. A new attempt owns a
128
- // fresh client, so it must clear the flag again; otherwise a successful
129
- // fallback (agent -> key on a machine without an SSH agent) would report
130
- // `connected === false` and every later `exec`/`forwardOut` would throw
131
- // "SSH connection is not open" on a transport that is actually up.
105
+ // A rejected candidate was torn down by `cleanupClient()`, marking this closed; the new attempt owns a fresh
106
+ // client, so the flag must clear or a working fallback would report "not open".
132
107
  this.closed = false;
133
- // An attempt that has already failed is torn down by its own error/close pair (a DNS
134
- // resolution failure emits both synchronously), and that close is the teardown of a
135
- // connection that never existed - not a lost link. Without this flag the wrapper would
136
- // emit `close`, the pipeline would read a transport drop and retry a first connection
137
- // that never got off the ground (review: close-after-error).
108
+ // An attempt that already failed tears itself down (error+close in one tick): without this flag that close
109
+ // would look like a dropped link, and a first connection that never started would be retried as one.
138
110
  let attemptFailed = false;
139
- // Attach the close handling *before* dialling: a transport that dies during the
140
- // handshake (for example while a host-key prompt is open) must be observable and must
141
- // reject the connect promise instead of hanging until the ready timeout. `this.client
142
- // !== client` filters a superseded auth attempt, whose teardown is not a lost link.
111
+ // Attach the close handling *before* dialling: a transport that dies during the handshake (while a host-key
112
+ // prompt is open) must reject the connect promise, and `this.client !== client` filters a superseded attempt,
113
+ // whose teardown is not a lost link.
143
114
  client.once('close', () => {
144
- if (attemptFailed)
145
- return;
146
- if (this.client !== client)
115
+ if (attemptFailed || this.client !== client)
147
116
  return;
148
117
  this.closed = true;
149
- // Decision D3: emit before rejecting. `connect-pipeline`'s two watchers rely on the
150
- // event arriving for a handshake that died while a host-key prompt was parked.
118
+ // Emit before rejecting: connect-pipeline's watchers rely on the event for a parked prompt.
151
119
  this.emit('close');
152
- settle(classifySshFailure(new Error('the connection closed during the SSH handshake'), {
153
- host: this.options.host,
154
- port: this.options.port,
155
- }));
120
+ settle(classifySshFailure(new Error('the connection closed during the SSH handshake'), endpoint));
156
121
  });
157
122
  client.once('ready', () => {
158
123
  const info = { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' };
159
124
  this.emit('ready', info);
160
125
  settle(null, info);
161
126
  });
162
- // Permanent listener: settle the promise on the first error, swallow any
163
- // later teardown errors (they are already reflected in the rejection).
127
+ // Settle on the first error and swallow any later teardown errors.
164
128
  client.on('error', (error) => {
165
129
  attemptFailed = true;
166
- settle(classifySshFailure(error, { host: this.options.host, port: this.options.port }));
130
+ settle(classifySshFailure(error, endpoint));
167
131
  });
168
132
  const config = {
169
133
  host: this.options.host,
@@ -177,7 +141,7 @@ export class SshConnection extends EventEmitter {
177
141
  ...authConfig,
178
142
  hostVerifier: (keyBlob, verify) => {
179
143
  this.verifyHostKey(keyBlob)
180
- .then((accepted) => verify(accepted))
144
+ .then(verify)
181
145
  .catch(() => verify(false));
182
146
  },
183
147
  };
@@ -186,15 +150,13 @@ export class SshConnection extends EventEmitter {
186
150
  }
187
151
  catch (error) {
188
152
  attemptFailed = true;
189
- settle(classifySshFailure(error, { host: this.options.host, port: this.options.port }));
153
+ settle(classifySshFailure(error, endpoint));
190
154
  }
191
155
  });
192
156
  }
193
- /**
194
- * The five-level host-key decision: pin → known_hosts → acceptUnknown → a decision already in
195
- * flight → policy (ask) → refuse. Emits `hostkey-*` as it goes.
196
- * @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`.
197
- */
157
+ /** The five-level host-key decision: pin → known_hosts → acceptUnknown → a decision in flight → policy (strict or
158
+ * ask) → refuse. Emits `hostkey-*` as it goes.
159
+ * @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`. */
198
160
  async verifyHostKey(keyBlob) {
199
161
  const sha256 = fingerprintFromBlob(keyBlob);
200
162
  const keyType = parseSshKeyType(keyBlob);
@@ -221,11 +183,8 @@ export class SshConnection extends EventEmitter {
221
183
  }
222
184
  if (this.hostKeyDecision)
223
185
  return this.hostKeyDecision;
224
- if (this.options.hostKeyPolicy === 'strict') {
225
- throw errors.hostKeyUnknown(sha256);
226
- }
227
- if (typeof this.options.onHostKey !== 'function') {
228
- // No UI attached (tests/automation): refuse rather than silently trust.
186
+ // A strict policy, or no UI attached (tests/automation): refuse rather than silently trust.
187
+ if (this.options.hostKeyPolicy === 'strict' || typeof this.options.onHostKey !== 'function') {
229
188
  throw errors.hostKeyUnknown(sha256);
230
189
  }
231
190
  this.emit('hostkey-pending', info);
@@ -235,29 +194,22 @@ export class SshConnection extends EventEmitter {
235
194
  throw errors.hostKeyUnknown(sha256);
236
195
  return true;
237
196
  }
238
- /**
239
- * The candidate list: a password when one is set, otherwise key files only. There is
240
- * deliberately no agent candidate (``~/.ssh/id_{ed25519,rsa,ecdsa}`` is the fallback chain).
241
- * @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`.
242
- */
197
+ /** The candidate list: a password when one is set, otherwise key files only — deliberately no agent candidate. The
198
+ * configured path wins; the conventional names follow, so a host added with the default key path still connects.
199
+ * @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`. */
243
200
  async resolveAuthCandidates() {
244
201
  const auth = this.options.auth ?? { type: 'key' };
245
- const out = [];
246
- if (auth.type === 'password') {
247
- if (auth.password)
248
- out.push({ password: auth.password, tryKeyboard: true });
249
- return out;
250
- }
251
- // Key-file authentication only: there is deliberately no agent candidate. The
252
- // configured path wins; when it is missing or unset the conventional names are
253
- // tried, so a host added with the default key path still connects.
202
+ if (auth.type === 'password')
203
+ return auth.password ? [{ password: auth.password, tryKeyboard: true }] : [];
204
+ const sshDir = path.join(this.options.home, '.ssh');
254
205
  const keyPaths = [
255
206
  ...(auth.keyPath ? [expandHome(auth.keyPath, this.options.home)] : []),
256
207
  ...(this.options.identityFiles ?? []),
257
- path.join(this.options.home, '.ssh', 'id_ed25519'),
258
- path.join(this.options.home, '.ssh', 'id_rsa'),
259
- path.join(this.options.home, '.ssh', 'id_ecdsa'),
208
+ path.join(sshDir, 'id_ed25519'),
209
+ path.join(sshDir, 'id_rsa'),
210
+ path.join(sshDir, 'id_ecdsa'),
260
211
  ];
212
+ const out = [];
261
213
  const seen = new Set();
262
214
  for (const keyPath of keyPaths) {
263
215
  if (!keyPath)
@@ -280,18 +232,27 @@ export class SshConnection extends EventEmitter {
280
232
  reject(closedError());
281
233
  return;
282
234
  }
283
- let timedOut = false;
284
235
  let timer = null;
285
- const chunks = { stdout: '', stderr: '' };
236
+ const result = { code: null, signal: null, stdout: '', stderr: '', timedOut: false };
286
237
  const finish = oneShot(resolve, reject, () => {
287
238
  if (timer)
288
239
  clearTimeout(timer);
289
240
  options.signal?.removeEventListener?.('abort', onAbort);
290
241
  });
291
- const onAbort = () => {
292
- finish(new Error('aborted'));
293
- };
242
+ const onAbort = () => finish(new Error('aborted'));
294
243
  options.signal?.addEventListener?.('abort', onAbort, { once: true });
244
+ // `maxBytes` truncation is silent by contract: no error, no flag, the excess is dropped.
245
+ const collect = (target, text, listener) => {
246
+ if (result[target].length >= maxBytes)
247
+ return;
248
+ result[target] += text;
249
+ try {
250
+ listener?.(text);
251
+ }
252
+ catch {
253
+ // swallow-ok: stream listeners must not break the command
254
+ }
255
+ };
295
256
  this.client.exec(command, { env: options.env }, (error, stream) => {
296
257
  if (error) {
297
258
  finish(error);
@@ -299,14 +260,13 @@ export class SshConnection extends EventEmitter {
299
260
  }
300
261
  if (timeoutMs > 0) {
301
262
  timer = setTimeout(() => {
302
- // A deadline is a result, not a rejection: `timedOut` is the caller's signal, and
303
- // the existing `{code,signal,stdout,stderr}` contract must not gain a throw path.
304
- timedOut = true;
263
+ // A deadline is a result, not a rejection: `timedOut` is the caller's signal and the result contract
264
+ // must not gain a throw path.
265
+ result.timedOut = true;
305
266
  stream.destroy();
306
267
  }, timeoutMs);
307
268
  }
308
- // Optional stdin (file uploads): the command reads it, so a secret never
309
- // appears on the remote command line.
269
+ // Optional stdin (file uploads): the command reads it, so a secret never reaches the remote command line.
310
270
  if (options.stdin !== undefined) {
311
271
  try {
312
272
  stream.end(String(options.stdin));
@@ -316,40 +276,12 @@ export class SshConnection extends EventEmitter {
316
276
  return;
317
277
  }
318
278
  }
319
- stream.on('data', (data) => {
320
- const text = data.toString('utf8');
321
- // `maxBytes` truncation is silent by contract: no error, no flag, the excess is dropped.
322
- if (chunks.stdout.length < maxBytes) {
323
- chunks.stdout += text;
324
- // The consumer is a progress reporter: its failure must not abort the command.
325
- try {
326
- options.onStdout?.(text);
327
- }
328
- catch {
329
- // swallow-ok: stdout listeners must not break the command
330
- }
331
- }
332
- });
333
- stream.stderr.on('data', (data) => {
334
- const text = data.toString('utf8');
335
- if (chunks.stderr.length < maxBytes) {
336
- chunks.stderr += text;
337
- try {
338
- options.onStderr?.(text);
339
- }
340
- catch {
341
- // swallow-ok: stderr listeners must not break the command
342
- }
343
- }
344
- });
279
+ stream.on('data', (data) => collect('stdout', data.toString('utf8'), options.onStdout));
280
+ stream.stderr.on('data', (data) => collect('stderr', data.toString('utf8'), options.onStderr));
345
281
  stream.on('close', (code, signal) => {
346
- finish(null, {
347
- code: code ?? null,
348
- signal: signal ?? null,
349
- stdout: chunks.stdout,
350
- stderr: chunks.stderr,
351
- timedOut,
352
- });
282
+ result.code = code ?? null;
283
+ result.signal = signal ?? null;
284
+ finish(null, result);
353
285
  });
354
286
  stream.on('error', (streamError) => finish(streamError));
355
287
  });
@@ -361,35 +293,27 @@ export class SshConnection extends EventEmitter {
361
293
  return Promise.reject(closedError());
362
294
  return openSftpSession(this.client);
363
295
  }
364
- /** Stream one remote file into a local path; the session is closed in `finally`. */
365
- async saveRemoteFile(remotePath, localPath, options = {}) {
296
+ /** Run one download step on a fresh SFTP session and close it in `finally`: the three downloads share this. */
297
+ async withSftp(run) {
366
298
  const sftp = await this.openSftp();
367
299
  try {
368
- return await saveSftpFile(sftp, remotePath, localPath, options);
300
+ return await run(sftp);
369
301
  }
370
302
  finally {
371
303
  endSftp(sftp);
372
304
  }
373
305
  }
306
+ /** Stream one remote file into a local path; the session is closed in `finally`. */
307
+ saveRemoteFile(remotePath, localPath, options = {}) {
308
+ return this.withSftp((sftp) => saveSftpFile(sftp, remotePath, localPath, options));
309
+ }
374
310
  /** Inspect one remote path without reading it. */
375
- async inspectRemotePath(remotePath) {
376
- const sftp = await this.openSftp();
377
- try {
378
- return await inspectSftpPath(sftp, remotePath);
379
- }
380
- finally {
381
- endSftp(sftp);
382
- }
311
+ inspectRemotePath(remotePath) {
312
+ return this.withSftp((sftp) => inspectSftpPath(sftp, remotePath));
383
313
  }
384
314
  /** Copy a remote directory to a local directory; see `saveSftpTree` for the exact contract. */
385
- async saveRemoteTree(remotePath, targetRoot, options = {}) {
386
- const sftp = await this.openSftp();
387
- try {
388
- return await saveSftpTree(sftp, remotePath, targetRoot, options);
389
- }
390
- finally {
391
- endSftp(sftp);
392
- }
315
+ saveRemoteTree(remotePath, targetRoot, options = {}) {
316
+ return this.withSftp((sftp) => saveSftpTree(sftp, remotePath, targetRoot, options));
393
317
  }
394
318
  forwardOut(destHost, destPort, srcHost = '127.0.0.1', srcPort = 0) {
395
319
  return new Promise((resolve, reject) => {
@@ -411,6 +335,7 @@ export class SshConnection extends EventEmitter {
411
335
  this.cleanupClient();
412
336
  if (!client)
413
337
  return;
338
+ // The remote never acknowledges, so bound the wait for our own transport to close.
414
339
  await new Promise((resolve) => {
415
340
  const timer = setTimeout(resolve, 1_500);
416
341
  try {
@@ -430,26 +355,20 @@ export class SshConnection extends EventEmitter {
430
355
  const client = this.client;
431
356
  this.client = null;
432
357
  this.closed = true;
433
- if (client) {
434
- try {
435
- // Keep an error sink attached: ssh2 may still emit during teardown.
436
- client.on('error', () => { });
437
- client.end();
438
- }
439
- catch {
440
- // swallow-ok: an error handler is installed above and end() must not throw
441
- }
358
+ if (!client)
359
+ return;
360
+ try {
361
+ // Keep an error sink attached: ssh2 may still emit during teardown.
362
+ client.on('error', () => { });
363
+ client.end();
364
+ }
365
+ catch {
366
+ // swallow-ok: an error handler is installed above and end() must not throw
442
367
  }
443
368
  }
444
369
  }
445
- /**
446
- * The production `SshFactory`: one ssh2 adapter per dial attempt.
447
- *
448
- * `ctx.deps.sshFactory` keeps its `(options) => SshPort` signature (decision D4); the default
449
- * implementation moved from `new SshConnection(...)` to this factory so tests can override the
450
- * injected client without touching the assembly.
451
- * @param options - the port's connect options (plus the adapter's `@internal` client seam).
452
- */
370
+ /** The production `SshFactory`: one ssh2 adapter per dial attempt, keeping the `(options) => SshPort` signature
371
+ * `ctx.deps.sshFactory` expects, so tests can override the injected client without touching the assembly. */
453
372
  export function createSsh2Port(options) {
454
373
  return new SshConnection(options);
455
374
  }
@@ -458,8 +377,7 @@ const MAX_KEY_BYTES = 1024 * 1024;
458
377
  async function readKey(keyPath) {
459
378
  let handle = null;
460
379
  try {
461
- // Measure and read through the *same* handle: a stat followed by a path-based read is a
462
- // race (the file could be swapped in between), and a non-regular file has no place here.
380
+ // Measure and read through the *same* handle: a stat-then-read is a race, and a non-regular file has no place here.
463
381
  handle = await open(keyPath, 'r');
464
382
  const stats = await handle.stat();
465
383
  if (stats.isFile?.() !== true)
package/dist/src/store.js CHANGED
@@ -1,6 +1,4 @@
1
- /**
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
- */
1
+ /** 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. */
4
2
  import { promises as fs } from 'node:fs';
5
3
  import path from 'node:path';
6
4
  import { readJsonFile, withProcessLock, writeJsonAtomic } from './atomic-json.js';
@@ -10,15 +8,17 @@ import { defaultSettings, sanitizeHostEntry, sanitizeSettings } from './settings
10
8
  function asArray(value) {
11
9
  return Array.isArray(value) ? value : [];
12
10
  }
13
- /**
14
- * A JSON object or nothing. Deliberately looser than `isPlainObject`: an array *is* an
15
- * object to `typeof`, and the secrets file has always been adopted as-is in that case, so
16
- * the type must not quietly tighten a persisted shape.
17
- */
11
+ // A JSON object or nothing. Deliberately looser than `isPlainObject`: an array *is* an object to
12
+ // `typeof` and the secrets file was always adopted as-is then, so the type must not tighten it.
18
13
  function asRecord(value) {
19
14
  return value !== null && typeof value === 'object' ? value : null;
20
15
  }
21
16
  export class HostStore {
17
+ data = { hosts: [], settings: defaultSettings() };
18
+ secrets = {};
19
+ /** Basenames of state files that were unreadable and moved aside on this load. */
20
+ corrupt = new Set();
21
+ loaded = false;
22
22
  constructor(options) {
23
23
  this.dir = options.dir;
24
24
  this.logger = options.logger ?? console;
@@ -26,11 +26,6 @@ export class HostStore {
26
26
  this.hostsFile = path.join(this.dir, 'hosts.json');
27
27
  this.settingsFile = path.join(this.dir, 'settings.json');
28
28
  this.secretsFile = path.join(this.dir, 'secrets.json');
29
- this.data = { hosts: [], settings: defaultSettings() };
30
- this.secrets = {};
31
- /** Basenames of state files that were unreadable and moved aside on this load. */
32
- this.corrupt = new Set();
33
- this.loaded = false;
34
29
  }
35
30
  /** Whether `hosts.json` had to be quarantined, i.e. the host list is the empty fallback. */
36
31
  get hostsCorrupt() {
@@ -45,10 +40,10 @@ export class HostStore {
45
40
  catch (error) {
46
41
  this.logger.warn?.('[dsh-remote-go] cannot create state directory:', error);
47
42
  }
48
- this.data.hosts = asArray(await this.#readJson(this.hostsFile, [])).filter((item) => item !== null && typeof item === 'object');
43
+ const hosts = asArray(await this.#readJson(this.hostsFile, []));
44
+ this.data.hosts = hosts.filter((item) => item !== null && typeof item === 'object');
49
45
  this.data.settings = sanitizeSettings(await this.#readJson(this.settingsFile, null));
50
- const secrets = await this.#readJson(this.secretsFile, null);
51
- this.secrets = asRecord(secrets) ?? {};
46
+ this.secrets = asRecord(await this.#readJson(this.secretsFile, null)) ?? {};
52
47
  this.loaded = true;
53
48
  return this.data;
54
49
  }
@@ -56,20 +51,14 @@ export class HostStore {
56
51
  const result = await readJsonFile(file, { fs: this.fs, logger: this.logger });
57
52
  if (result.status === 'ok')
58
53
  return result.value;
59
- // Only bytes that are not JSON are quarantined. A file that merely could not be read right
60
- // now (EACCES, a transient IO error) falls back for this run and is left in place: renaming
61
- // it would turn a permission problem into a silently emptied host list.
62
- // A corrupt file used to fall back to `[]` / defaults silently, and the next write then
63
- // replaced it for good — losing every host, including the pinned fingerprints that make a
64
- // host-key change detectable. Keep the bytes aside first, then recover.
54
+ // Only bytes that are not JSON are quarantined: a transient read error (EACCES) falls back for this run and is left
55
+ // in place, since renaming would turn a permission problem into an emptied host list. A corrupt file used to fall
56
+ // back silently and be replaced for good — losing hosts and the pinned fingerprints that detect a key change.
65
57
  if (result.status === 'corrupt')
66
58
  await this.#quarantine(file);
67
59
  return fallback;
68
60
  }
69
- /**
70
- * Rename one unreadable state file to `<name>.corrupt-<iso>` so it survives the recovery
71
- * write. A failure here is logged and swallowed: recovery must not be blocked by it.
72
- */
61
+ /** Rename one unreadable state file to `<name>.corrupt-<iso>` so it survives the recovery write; a failure here is logged and swallowed, because it must not block that recovery. */
73
62
  async #quarantine(file) {
74
63
  const name = path.basename(file);
75
64
  // The flag means "this file was unreadable", whether or not a copy could be made.
@@ -84,25 +73,20 @@ export class HostStore {
84
73
  this.logger.warn?.(`[dsh-remote-go] cannot keep a copy of the unreadable ${name}:`, error);
85
74
  }
86
75
  }
87
- #writeJson(file, value, mode = 0o600) {
88
- return withProcessLock(`${file}.lock`, { fs: this.fs, logger: this.logger }, () => writeJsonAtomic(file, value, {
76
+ async #writeJson(file, value, mode = 0o600) {
77
+ await withProcessLock(`${file}.lock`, { fs: this.fs, logger: this.logger }, () => writeJsonAtomic(file, value, {
89
78
  dir: this.dir,
90
79
  fs: this.fs,
91
80
  logger: this.logger,
92
81
  fileMode: mode,
93
- })).then((result) => {
94
- // The recovered file is the authority again: the next successful write clears the flag,
95
- // so a user who rebuilds the list is not warned forever about a file that is now valid.
96
- this.corrupt.delete(path.basename(file));
97
- return result;
98
- });
82
+ }));
83
+ // The recovered file is the authority again: the next successful write clears the flag, so a
84
+ // user who rebuilds the list is not warned forever about a file that is now valid.
85
+ this.corrupt.delete(path.basename(file));
99
86
  }
100
87
  async #persistHosts() {
101
88
  await this.#writeJson(this.hostsFile, this.data.hosts);
102
89
  }
103
- async #persistSettings() {
104
- await this.#writeJson(this.settingsFile, this.data.settings);
105
- }
106
90
  async #persistSecrets() {
107
91
  await this.#writeJson(this.secretsFile, this.secrets);
108
92
  }
@@ -115,10 +99,9 @@ export class HostStore {
115
99
  }
116
100
  async upsertHost(rawEntry, options = {}) {
117
101
  await this.load();
118
- // A caller may name an id only if this store already issued it: the id keys the secrets
119
- // file, the proxy's per-host routes and the client's host links, so a client-chosen id
120
- // (malformed, too long, or a duplicate of another host) is not something to adopt. A new
121
- // host always gets a fresh `h_…` and learns it from the returned HostView.
102
+ // A caller may name an id only if this store already issued it: the id keys the secrets file, the proxy's per-host
103
+ // routes and the client's host links, so a client-chosen id (malformed, too long, duplicate) is not adopted. A new
104
+ // host gets a fresh `h_…` from the returned HostView.
122
105
  const rawId = isPlainObject(rawEntry) && typeof rawEntry.id === 'string' ? rawEntry.id : '';
123
106
  const existing = rawId === '' ? null : this.getHost(rawId);
124
107
  const entry = sanitizeHostEntry(rawEntry, { settings: options.settings ?? this.data.settings, existing });
@@ -157,12 +140,12 @@ export class HostStore {
157
140
  }
158
141
  async saveSettings(raw) {
159
142
  await this.load();
160
- const patch = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
161
- // Merge the patch onto the *current* settings. Spreading it over the defaults reset every
162
- // field the patch did not name — a patch of `autoReconnect.maxAttempts` also rewound
163
- // `baseDelayMs` from a configured 5000 back to 800 — which silently undid sibling settings.
143
+ const patch = isPlainObject(raw) ? raw : {};
144
+ // Merge the patch onto the *current* settings. Spreading it over the defaults reset every field
145
+ // the patch did not name — a patch of `autoReconnect.maxAttempts` also rewound `baseDelayMs`
146
+ // from a configured 5000 back to 800 — which silently undid sibling settings.
164
147
  this.data.settings = sanitizeSettings(deepMerge(this.data.settings, patch));
165
- await this.#persistSettings();
148
+ await this.#writeJson(this.settingsFile, this.data.settings);
166
149
  if (!this.data.settings.saveTokens) {
167
150
  this.secrets = {};
168
151
  await this.#persistSecrets();
@@ -170,8 +153,8 @@ export class HostStore {
170
153
  return this.data.settings;
171
154
  }
172
155
  async saveToken(hostId, token) {
173
- // Without this the first token save on a fresh process wrote `{}` over a secrets file that
174
- // still held other hosts' tokens.
156
+ // Without this the first token save on a fresh process wrote `{}` over a secrets file that still
157
+ // held other hosts' tokens.
175
158
  await this.load();
176
159
  if (!this.data.settings.saveTokens)
177
160
  return;