dsh-remote-go 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/{src → dist/src}/constants.js +30 -56
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +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/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,477 @@
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
+ */
13
+ import { EventEmitter } from 'node:events';
14
+ import { open } from 'node:fs/promises';
15
+ import { homedir } from 'node:os';
16
+ import path from 'node:path';
17
+ import ssh2 from '../vendor/ssh2.bundle.cjs';
18
+ import { errors } from './errors.js';
19
+ import { fingerprintFromBlob } from './known-hosts.js';
20
+ import { classifySshFailure, closedError, isHostKeyError } from './ssh-failures.js';
21
+ import { DEFAULT_EXEC_MAX_BYTES, DEFAULT_EXEC_TIMEOUT_MS, } from './ssh-port.js';
22
+ import { endSftp, inspectSftpPath, openSftpSession, saveSftpFile, saveSftpTree } from './ssh-sftp.js';
23
+ import { expandHome } from './util.js';
24
+ const { Client } = ssh2;
25
+ /** Settle a promise at most once; later calls are ignored, so callers need no flag. */
26
+ function oneShot(resolve, reject, cleanup) {
27
+ let settled = false;
28
+ return (error, value) => {
29
+ if (settled)
30
+ return;
31
+ settled = true;
32
+ 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);
39
+ };
40
+ }
41
+ export function parseSshKeyType(blob) {
42
+ try {
43
+ const buffer = Buffer.from(blob);
44
+ if (buffer.length < 6)
45
+ return 'unknown';
46
+ const length = buffer.readUInt32BE(0);
47
+ if (length <= 0 || length > buffer.length - 4)
48
+ return 'unknown';
49
+ return buffer.subarray(4, 4 + length).toString('ascii');
50
+ }
51
+ catch {
52
+ return 'unknown';
53
+ }
54
+ }
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
+ */
62
+ export class SshConnection extends EventEmitter {
63
+ constructor(options) {
64
+ super();
65
+ this.options = {
66
+ port: 22,
67
+ hostKeyPolicy: 'first-use',
68
+ pinnedFingerprint: null,
69
+ knownHostFingerprints: [],
70
+ readyTimeoutMs: 20_000,
71
+ keepaliveIntervalMs: 15_000,
72
+ home: homedir(),
73
+ ...options,
74
+ identityFiles: options.identityFiles ?? [],
75
+ };
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.
86
+ this.on('error', () => { });
87
+ this.clientFactory = typeof options.clientFactory === 'function' ? options.clientFactory : () => new Client();
88
+ }
89
+ get connected() {
90
+ return this.client !== null && !this.closed;
91
+ }
92
+ async connect() {
93
+ if (this.connected)
94
+ return { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' };
95
+ const candidates = await this.resolveAuthCandidates();
96
+ if (candidates.length === 0) {
97
+ throw errors.invalidInput('auth', {
98
+ zh: '没有可用的 SSH 认证方式:请选择一个可读的私钥文件(或输入一次密码)。',
99
+ en: 'No usable SSH authentication: choose a readable private-key file (or enter a one-time password).',
100
+ });
101
+ }
102
+ let lastError = null;
103
+ for (const candidate of candidates) {
104
+ try {
105
+ const info = await this.connectOnce(candidate);
106
+ this.client?.on('error', (error) => {
107
+ this.emit('error', error);
108
+ });
109
+ return info;
110
+ }
111
+ catch (error) {
112
+ lastError = error;
113
+ this.cleanupClient();
114
+ // A host-key rejection is a policy decision, not an auth failure.
115
+ if (isHostKeyError(error))
116
+ throw error;
117
+ }
118
+ }
119
+ throw lastError instanceof Error ? lastError : errors.auth();
120
+ }
121
+ connectOnce(authConfig) {
122
+ return new Promise((resolve, reject) => {
123
+ const settle = oneShot(resolve, reject);
124
+ const client = this.clientFactory();
125
+ 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.
132
+ 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).
138
+ 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.
143
+ client.once('close', () => {
144
+ if (attemptFailed)
145
+ return;
146
+ if (this.client !== client)
147
+ return;
148
+ 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.
151
+ 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
+ }));
156
+ });
157
+ client.once('ready', () => {
158
+ const info = { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' };
159
+ this.emit('ready', info);
160
+ settle(null, info);
161
+ });
162
+ // Permanent listener: settle the promise on the first error, swallow any
163
+ // later teardown errors (they are already reflected in the rejection).
164
+ client.on('error', (error) => {
165
+ attemptFailed = true;
166
+ settle(classifySshFailure(error, { host: this.options.host, port: this.options.port }));
167
+ });
168
+ const config = {
169
+ host: this.options.host,
170
+ port: this.options.port,
171
+ username: this.options.username ?? undefined,
172
+ readyTimeout: this.options.readyTimeoutMs,
173
+ keepaliveInterval: this.options.keepaliveIntervalMs,
174
+ keepaliveCountMax: 3,
175
+ tryKeyboard: false,
176
+ ...(this.options.sock ? { sock: this.options.sock } : {}),
177
+ ...authConfig,
178
+ hostVerifier: (keyBlob, verify) => {
179
+ this.verifyHostKey(keyBlob)
180
+ .then((accepted) => verify(accepted))
181
+ .catch(() => verify(false));
182
+ },
183
+ };
184
+ try {
185
+ client.connect(config);
186
+ }
187
+ catch (error) {
188
+ attemptFailed = true;
189
+ settle(classifySshFailure(error, { host: this.options.host, port: this.options.port }));
190
+ }
191
+ });
192
+ }
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
+ */
198
+ async verifyHostKey(keyBlob) {
199
+ const sha256 = fingerprintFromBlob(keyBlob);
200
+ const keyType = parseSshKeyType(keyBlob);
201
+ this.fingerprint = sha256;
202
+ this.keyType = keyType;
203
+ const pinned = this.options.pinnedFingerprint;
204
+ const known = this.options.knownHostFingerprints ?? [];
205
+ const info = { sha256, keyType, pinned: Boolean(pinned && pinned === sha256) };
206
+ if (pinned) {
207
+ if (pinned === sha256)
208
+ return true;
209
+ this.emit('hostkey-rejected', info);
210
+ throw errors.hostKeyChanged(pinned, sha256);
211
+ }
212
+ if (known.length > 0) {
213
+ if (known.includes(sha256))
214
+ return true;
215
+ this.emit('hostkey-rejected', info);
216
+ throw errors.hostKeyChanged(known[0], sha256);
217
+ }
218
+ if (this.options.acceptUnknownHostKey === true) {
219
+ this.emit('hostkey-accepted', info);
220
+ return true;
221
+ }
222
+ if (this.hostKeyDecision)
223
+ 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.
229
+ throw errors.hostKeyUnknown(sha256);
230
+ }
231
+ this.emit('hostkey-pending', info);
232
+ this.hostKeyDecision = Promise.resolve(this.options.onHostKey(info)).then((accepted) => accepted === true, () => false);
233
+ const accepted = await this.hostKeyDecision;
234
+ if (!accepted)
235
+ throw errors.hostKeyUnknown(sha256);
236
+ return true;
237
+ }
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
+ */
243
+ async resolveAuthCandidates() {
244
+ 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.
254
+ const keyPaths = [
255
+ ...(auth.keyPath ? [expandHome(auth.keyPath, this.options.home)] : []),
256
+ ...(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'),
260
+ ];
261
+ const seen = new Set();
262
+ for (const keyPath of keyPaths) {
263
+ if (!keyPath)
264
+ continue;
265
+ const normalized = path.resolve(keyPath);
266
+ if (seen.has(normalized))
267
+ continue;
268
+ seen.add(normalized);
269
+ const privateKey = await readKey(keyPath);
270
+ if (privateKey)
271
+ out.push({ privateKey });
272
+ }
273
+ return out;
274
+ }
275
+ exec(command, options = {}) {
276
+ const timeoutMs = options.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
277
+ const maxBytes = options.maxBytes ?? DEFAULT_EXEC_MAX_BYTES;
278
+ return new Promise((resolve, reject) => {
279
+ if (!this.client || this.closed) {
280
+ reject(closedError());
281
+ return;
282
+ }
283
+ let timedOut = false;
284
+ let timer = null;
285
+ const chunks = { stdout: '', stderr: '' };
286
+ const finish = oneShot(resolve, reject, () => {
287
+ if (timer)
288
+ clearTimeout(timer);
289
+ options.signal?.removeEventListener?.('abort', onAbort);
290
+ });
291
+ const onAbort = () => {
292
+ finish(new Error('aborted'));
293
+ };
294
+ options.signal?.addEventListener?.('abort', onAbort, { once: true });
295
+ this.client.exec(command, { env: options.env }, (error, stream) => {
296
+ if (error) {
297
+ finish(error);
298
+ return;
299
+ }
300
+ if (timeoutMs > 0) {
301
+ 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;
305
+ stream.destroy();
306
+ }, timeoutMs);
307
+ }
308
+ // Optional stdin (file uploads): the command reads it, so a secret never
309
+ // appears on the remote command line.
310
+ if (options.stdin !== undefined) {
311
+ try {
312
+ stream.end(String(options.stdin));
313
+ }
314
+ catch (writeError) {
315
+ finish(writeError);
316
+ return;
317
+ }
318
+ }
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
+ });
345
+ 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
+ });
353
+ });
354
+ stream.on('error', (streamError) => finish(streamError));
355
+ });
356
+ });
357
+ }
358
+ /** Open one SFTP session on this connection (the capability behind the download members). */
359
+ openSftp() {
360
+ if (!this.client || this.closed)
361
+ return Promise.reject(closedError());
362
+ return openSftpSession(this.client);
363
+ }
364
+ /** Stream one remote file into a local path; the session is closed in `finally`. */
365
+ async saveRemoteFile(remotePath, localPath, options = {}) {
366
+ const sftp = await this.openSftp();
367
+ try {
368
+ return await saveSftpFile(sftp, remotePath, localPath, options);
369
+ }
370
+ finally {
371
+ endSftp(sftp);
372
+ }
373
+ }
374
+ /** 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
+ }
383
+ }
384
+ /** 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
+ }
393
+ }
394
+ forwardOut(destHost, destPort, srcHost = '127.0.0.1', srcPort = 0) {
395
+ return new Promise((resolve, reject) => {
396
+ if (!this.client || this.closed) {
397
+ reject(closedError());
398
+ return;
399
+ }
400
+ this.client.forwardOut(srcHost, srcPort, destHost, destPort, (error, stream) => {
401
+ if (error)
402
+ reject(error);
403
+ else
404
+ resolve(stream);
405
+ });
406
+ });
407
+ }
408
+ async dispose() {
409
+ this.disposed = true;
410
+ const client = this.client;
411
+ this.cleanupClient();
412
+ if (!client)
413
+ return;
414
+ await new Promise((resolve) => {
415
+ const timer = setTimeout(resolve, 1_500);
416
+ try {
417
+ client.once('close', () => {
418
+ clearTimeout(timer);
419
+ resolve(undefined);
420
+ });
421
+ client.end();
422
+ }
423
+ catch {
424
+ clearTimeout(timer);
425
+ resolve(undefined);
426
+ }
427
+ });
428
+ }
429
+ cleanupClient() {
430
+ const client = this.client;
431
+ this.client = null;
432
+ 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
+ }
442
+ }
443
+ }
444
+ }
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
+ */
453
+ export function createSsh2Port(options) {
454
+ return new SshConnection(options);
455
+ }
456
+ /** A private key is a few kilobytes; anything larger is not one and must not be read. */
457
+ const MAX_KEY_BYTES = 1024 * 1024;
458
+ async function readKey(keyPath) {
459
+ let handle = null;
460
+ 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.
463
+ handle = await open(keyPath, 'r');
464
+ const stats = await handle.stat();
465
+ if (stats.isFile?.() !== true)
466
+ return null;
467
+ if (typeof stats.size === 'number' && stats.size > MAX_KEY_BYTES)
468
+ return null;
469
+ return await handle.readFile();
470
+ }
471
+ catch {
472
+ return null;
473
+ }
474
+ finally {
475
+ await handle?.close().catch(() => { });
476
+ }
477
+ }
@@ -0,0 +1,191 @@
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
+ */
4
+ import { promises as fs } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { readJsonFile, withProcessLock, writeJsonAtomic } from './atomic-json.js';
7
+ import { deepMerge, isPlainObject, nowIso, randomId } from './util.js';
8
+ import { defaultSettings, sanitizeHostEntry, sanitizeSettings } from './settings.js';
9
+ /** A JSON array or no entries: a state file that is not an array contributes nothing. */
10
+ function asArray(value) {
11
+ return Array.isArray(value) ? value : [];
12
+ }
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
+ */
18
+ function asRecord(value) {
19
+ return value !== null && typeof value === 'object' ? value : null;
20
+ }
21
+ export class HostStore {
22
+ constructor(options) {
23
+ this.dir = options.dir;
24
+ this.logger = options.logger ?? console;
25
+ this.fs = options.fsImpl ?? fs;
26
+ this.hostsFile = path.join(this.dir, 'hosts.json');
27
+ this.settingsFile = path.join(this.dir, 'settings.json');
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
+ }
35
+ /** Whether `hosts.json` had to be quarantined, i.e. the host list is the empty fallback. */
36
+ get hostsCorrupt() {
37
+ return this.corrupt.has('hosts.json');
38
+ }
39
+ async load() {
40
+ if (this.loaded)
41
+ return this.data;
42
+ try {
43
+ await this.fs.mkdir(this.dir, { recursive: true, mode: 0o700 });
44
+ }
45
+ catch (error) {
46
+ this.logger.warn?.('[dsh-remote-go] cannot create state directory:', error);
47
+ }
48
+ this.data.hosts = asArray(await this.#readJson(this.hostsFile, [])).filter((item) => item !== null && typeof item === 'object');
49
+ this.data.settings = sanitizeSettings(await this.#readJson(this.settingsFile, null));
50
+ const secrets = await this.#readJson(this.secretsFile, null);
51
+ this.secrets = asRecord(secrets) ?? {};
52
+ this.loaded = true;
53
+ return this.data;
54
+ }
55
+ async #readJson(file, fallback) {
56
+ const result = await readJsonFile(file, { fs: this.fs, logger: this.logger });
57
+ if (result.status === 'ok')
58
+ 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.
65
+ if (result.status === 'corrupt')
66
+ await this.#quarantine(file);
67
+ return fallback;
68
+ }
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
+ */
73
+ async #quarantine(file) {
74
+ const name = path.basename(file);
75
+ // The flag means "this file was unreadable", whether or not a copy could be made.
76
+ this.corrupt.add(name);
77
+ // Colons and dots are invalid (Windows) or noisy in a file name, so the ISO stamp is flattened.
78
+ const target = `${file}.corrupt-${nowIso().replace(/[:.]/g, '-')}`;
79
+ try {
80
+ await this.fs.rename(file, target);
81
+ this.logger.warn?.(`[dsh-remote-go] ${name} was unreadable; kept a copy as ${path.basename(target)}`);
82
+ }
83
+ catch (error) {
84
+ this.logger.warn?.(`[dsh-remote-go] cannot keep a copy of the unreadable ${name}:`, error);
85
+ }
86
+ }
87
+ #writeJson(file, value, mode = 0o600) {
88
+ return withProcessLock(`${file}.lock`, { fs: this.fs, logger: this.logger }, () => writeJsonAtomic(file, value, {
89
+ dir: this.dir,
90
+ fs: this.fs,
91
+ logger: this.logger,
92
+ 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
+ });
99
+ }
100
+ async #persistHosts() {
101
+ await this.#writeJson(this.hostsFile, this.data.hosts);
102
+ }
103
+ async #persistSettings() {
104
+ await this.#writeJson(this.settingsFile, this.data.settings);
105
+ }
106
+ async #persistSecrets() {
107
+ await this.#writeJson(this.secretsFile, this.secrets);
108
+ }
109
+ listHosts() {
110
+ return this.data.hosts.map((host) => ({ ...host }));
111
+ }
112
+ getHost(id) {
113
+ const host = this.data.hosts.find((item) => item.id === id);
114
+ return host ? { ...host } : null;
115
+ }
116
+ async upsertHost(rawEntry, options = {}) {
117
+ 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.
122
+ const rawId = isPlainObject(rawEntry) && typeof rawEntry.id === 'string' ? rawEntry.id : '';
123
+ const existing = rawId === '' ? null : this.getHost(rawId);
124
+ const entry = sanitizeHostEntry(rawEntry, { settings: options.settings ?? this.data.settings, existing });
125
+ entry.id = existing ? existing.id : randomId('h');
126
+ const index = this.data.hosts.findIndex((item) => item.id === entry.id);
127
+ if (index >= 0)
128
+ this.data.hosts[index] = { ...this.data.hosts[index], ...entry };
129
+ else
130
+ this.data.hosts.push(entry);
131
+ await this.#persistHosts();
132
+ return this.getHost(entry.id);
133
+ }
134
+ async removeHost(id) {
135
+ await this.load();
136
+ const before = this.data.hosts.length;
137
+ this.data.hosts = this.data.hosts.filter((item) => item.id !== id);
138
+ if (this.data.hosts.length !== before)
139
+ await this.#persistHosts();
140
+ if (this.secrets[id]) {
141
+ delete this.secrets[id];
142
+ await this.#persistSecrets();
143
+ }
144
+ return before !== this.data.hosts.length;
145
+ }
146
+ async patchHost(id, patch) {
147
+ await this.load();
148
+ const host = this.data.hosts.find((item) => item.id === id);
149
+ if (!host)
150
+ return null;
151
+ Object.assign(host, patch, { updatedAt: nowIso() });
152
+ await this.#persistHosts();
153
+ return { ...host };
154
+ }
155
+ getSettings() {
156
+ return this.data.settings;
157
+ }
158
+ async saveSettings(raw) {
159
+ 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.
164
+ this.data.settings = sanitizeSettings(deepMerge(this.data.settings, patch));
165
+ await this.#persistSettings();
166
+ if (!this.data.settings.saveTokens) {
167
+ this.secrets = {};
168
+ await this.#persistSecrets();
169
+ }
170
+ return this.data.settings;
171
+ }
172
+ 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.
175
+ await this.load();
176
+ if (!this.data.settings.saveTokens)
177
+ return;
178
+ this.secrets[hostId] = token;
179
+ await this.#persistSecrets();
180
+ }
181
+ }
182
+ export function resolveDshHome(env = process.env) {
183
+ const home = env.DSH_HOME && env.DSH_HOME.trim() !== '' ? env.DSH_HOME.trim() : null;
184
+ if (home)
185
+ return home;
186
+ const userHome = env.USERPROFILE || env.HOME || process.cwd();
187
+ return path.join(userHome, '.dsh');
188
+ }
189
+ export function resolveStateDir(home) {
190
+ return path.join(home, 'remote-go');
191
+ }