dsh-remote-go 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,395 @@
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. */
4
+ import { EventEmitter } from 'node:events';
5
+ import { open } from 'node:fs/promises';
6
+ import { homedir } from 'node:os';
7
+ import path from 'node:path';
8
+ import ssh2 from '../vendor/ssh2.bundle.cjs';
9
+ import { errors } from './errors.js';
10
+ import { fingerprintFromBlob } from './known-hosts.js';
11
+ import { classifySshFailure, closedError, isHostKeyError } from './ssh-failures.js';
12
+ import { DEFAULT_EXEC_MAX_BYTES, DEFAULT_EXEC_TIMEOUT_MS, } from './ssh-port.js';
13
+ import { endSftp, inspectSftpPath, openSftpSession, saveSftpFile, saveSftpTree } from './ssh-sftp.js';
14
+ import { expandHome } from './util.js';
15
+ const { Client } = ssh2;
16
+ /** Settle a promise at most once (later calls are ignored), so callers need no flag. */
17
+ function oneShot(resolve, reject, cleanup) {
18
+ let settled = false;
19
+ return (error, value) => {
20
+ if (settled)
21
+ return;
22
+ settled = true;
23
+ cleanup?.();
24
+ // The settled-once contract passes exactly one of error/value, so the success branch carries it.
25
+ error ? reject(error) : resolve(value);
26
+ };
27
+ }
28
+ export function parseSshKeyType(blob) {
29
+ try {
30
+ const buffer = Buffer.from(blob);
31
+ if (buffer.length < 6)
32
+ return 'unknown';
33
+ const length = buffer.readUInt32BE(0);
34
+ if (length <= 0 || length > buffer.length - 4)
35
+ return 'unknown';
36
+ return buffer.subarray(4, 4 + length).toString('ascii');
37
+ }
38
+ catch {
39
+ return 'unknown';
40
+ }
41
+ }
42
+ /** The ssh2 implementation of `SshPort`: every failure is a `RemoteGoError`, and the download members are declared. */
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();
51
+ constructor(options) {
52
+ super();
53
+ this.options = {
54
+ port: 22,
55
+ hostKeyPolicy: 'first-use',
56
+ pinnedFingerprint: null,
57
+ knownHostFingerprints: [],
58
+ readyTimeoutMs: 20_000,
59
+ keepaliveIntervalMs: 15_000,
60
+ home: homedir(),
61
+ ...options,
62
+ identityFiles: options.identityFiles ?? [],
63
+ };
64
+ // ssh2 emits `error` on every failed auth attempt and while tearing down; unhandled, it would kill the Host.
65
+ this.on('error', () => { });
66
+ if (typeof options.clientFactory === 'function')
67
+ this.clientFactory = options.clientFactory;
68
+ }
69
+ get connected() {
70
+ return this.client !== null && !this.closed;
71
+ }
72
+ async connect() {
73
+ if (this.connected)
74
+ return { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' };
75
+ const candidates = await this.resolveAuthCandidates();
76
+ if (candidates.length === 0) {
77
+ throw errors.invalidInput('auth', {
78
+ zh: '没有可用的 SSH 认证方式:请选择一个可读的私钥文件(或输入一次密码)。',
79
+ en: 'No usable SSH authentication: choose a readable private-key file (or enter a one-time password).',
80
+ });
81
+ }
82
+ let lastError = null;
83
+ for (const candidate of candidates) {
84
+ try {
85
+ const info = await this.connectOnce(candidate);
86
+ this.client?.on('error', (error) => this.emit('error', error));
87
+ return info;
88
+ }
89
+ catch (error) {
90
+ lastError = error;
91
+ this.cleanupClient();
92
+ // A host-key rejection is a policy decision, not an auth failure.
93
+ if (isHostKeyError(error))
94
+ throw error;
95
+ }
96
+ }
97
+ throw lastError instanceof Error ? lastError : errors.auth();
98
+ }
99
+ connectOnce(authConfig) {
100
+ return new Promise((resolve, reject) => {
101
+ const settle = oneShot(resolve, reject);
102
+ const client = this.clientFactory();
103
+ const endpoint = { host: this.options.host, port: this.options.port };
104
+ this.client = client;
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".
107
+ this.closed = false;
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.
110
+ let attemptFailed = false;
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.
114
+ client.once('close', () => {
115
+ if (attemptFailed || this.client !== client)
116
+ return;
117
+ this.closed = true;
118
+ // Emit before rejecting: connect-pipeline's watchers rely on the event for a parked prompt.
119
+ this.emit('close');
120
+ settle(classifySshFailure(new Error('the connection closed during the SSH handshake'), endpoint));
121
+ });
122
+ client.once('ready', () => {
123
+ const info = { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' };
124
+ this.emit('ready', info);
125
+ settle(null, info);
126
+ });
127
+ // Settle on the first error and swallow any later teardown errors.
128
+ client.on('error', (error) => {
129
+ attemptFailed = true;
130
+ settle(classifySshFailure(error, endpoint));
131
+ });
132
+ const config = {
133
+ host: this.options.host,
134
+ port: this.options.port,
135
+ username: this.options.username ?? undefined,
136
+ readyTimeout: this.options.readyTimeoutMs,
137
+ keepaliveInterval: this.options.keepaliveIntervalMs,
138
+ keepaliveCountMax: 3,
139
+ tryKeyboard: false,
140
+ ...(this.options.sock ? { sock: this.options.sock } : {}),
141
+ ...authConfig,
142
+ hostVerifier: (keyBlob, verify) => {
143
+ this.verifyHostKey(keyBlob)
144
+ .then(verify)
145
+ .catch(() => verify(false));
146
+ },
147
+ };
148
+ try {
149
+ client.connect(config);
150
+ }
151
+ catch (error) {
152
+ attemptFailed = true;
153
+ settle(classifySshFailure(error, endpoint));
154
+ }
155
+ });
156
+ }
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`. */
160
+ async verifyHostKey(keyBlob) {
161
+ const sha256 = fingerprintFromBlob(keyBlob);
162
+ const keyType = parseSshKeyType(keyBlob);
163
+ this.fingerprint = sha256;
164
+ this.keyType = keyType;
165
+ const pinned = this.options.pinnedFingerprint;
166
+ const known = this.options.knownHostFingerprints ?? [];
167
+ const info = { sha256, keyType, pinned: Boolean(pinned && pinned === sha256) };
168
+ if (pinned) {
169
+ if (pinned === sha256)
170
+ return true;
171
+ this.emit('hostkey-rejected', info);
172
+ throw errors.hostKeyChanged(pinned, sha256);
173
+ }
174
+ if (known.length > 0) {
175
+ if (known.includes(sha256))
176
+ return true;
177
+ this.emit('hostkey-rejected', info);
178
+ throw errors.hostKeyChanged(known[0], sha256);
179
+ }
180
+ if (this.options.acceptUnknownHostKey === true) {
181
+ this.emit('hostkey-accepted', info);
182
+ return true;
183
+ }
184
+ if (this.hostKeyDecision)
185
+ return this.hostKeyDecision;
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') {
188
+ throw errors.hostKeyUnknown(sha256);
189
+ }
190
+ this.emit('hostkey-pending', info);
191
+ this.hostKeyDecision = Promise.resolve(this.options.onHostKey(info)).then((accepted) => accepted === true, () => false);
192
+ const accepted = await this.hostKeyDecision;
193
+ if (!accepted)
194
+ throw errors.hostKeyUnknown(sha256);
195
+ return true;
196
+ }
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`. */
200
+ async resolveAuthCandidates() {
201
+ const auth = this.options.auth ?? { type: 'key' };
202
+ if (auth.type === 'password')
203
+ return auth.password ? [{ password: auth.password, tryKeyboard: true }] : [];
204
+ const sshDir = path.join(this.options.home, '.ssh');
205
+ const keyPaths = [
206
+ ...(auth.keyPath ? [expandHome(auth.keyPath, this.options.home)] : []),
207
+ ...(this.options.identityFiles ?? []),
208
+ path.join(sshDir, 'id_ed25519'),
209
+ path.join(sshDir, 'id_rsa'),
210
+ path.join(sshDir, 'id_ecdsa'),
211
+ ];
212
+ const out = [];
213
+ const seen = new Set();
214
+ for (const keyPath of keyPaths) {
215
+ if (!keyPath)
216
+ continue;
217
+ const normalized = path.resolve(keyPath);
218
+ if (seen.has(normalized))
219
+ continue;
220
+ seen.add(normalized);
221
+ const privateKey = await readKey(keyPath);
222
+ if (privateKey)
223
+ out.push({ privateKey });
224
+ }
225
+ return out;
226
+ }
227
+ exec(command, options = {}) {
228
+ const timeoutMs = options.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
229
+ const maxBytes = options.maxBytes ?? DEFAULT_EXEC_MAX_BYTES;
230
+ return new Promise((resolve, reject) => {
231
+ if (!this.client || this.closed) {
232
+ reject(closedError());
233
+ return;
234
+ }
235
+ let timer = null;
236
+ const result = { code: null, signal: null, stdout: '', stderr: '', timedOut: false };
237
+ const finish = oneShot(resolve, reject, () => {
238
+ if (timer)
239
+ clearTimeout(timer);
240
+ options.signal?.removeEventListener?.('abort', onAbort);
241
+ });
242
+ const onAbort = () => finish(new Error('aborted'));
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
+ };
256
+ this.client.exec(command, { env: options.env }, (error, stream) => {
257
+ if (error) {
258
+ finish(error);
259
+ return;
260
+ }
261
+ if (timeoutMs > 0) {
262
+ timer = setTimeout(() => {
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;
266
+ stream.destroy();
267
+ }, timeoutMs);
268
+ }
269
+ // Optional stdin (file uploads): the command reads it, so a secret never reaches the remote command line.
270
+ if (options.stdin !== undefined) {
271
+ try {
272
+ stream.end(String(options.stdin));
273
+ }
274
+ catch (writeError) {
275
+ finish(writeError);
276
+ return;
277
+ }
278
+ }
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));
281
+ stream.on('close', (code, signal) => {
282
+ result.code = code ?? null;
283
+ result.signal = signal ?? null;
284
+ finish(null, result);
285
+ });
286
+ stream.on('error', (streamError) => finish(streamError));
287
+ });
288
+ });
289
+ }
290
+ /** Open one SFTP session on this connection (the capability behind the download members). */
291
+ openSftp() {
292
+ if (!this.client || this.closed)
293
+ return Promise.reject(closedError());
294
+ return openSftpSession(this.client);
295
+ }
296
+ /** Run one download step on a fresh SFTP session and close it in `finally`: the three downloads share this. */
297
+ async withSftp(run) {
298
+ const sftp = await this.openSftp();
299
+ try {
300
+ return await run(sftp);
301
+ }
302
+ finally {
303
+ endSftp(sftp);
304
+ }
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
+ }
310
+ /** Inspect one remote path without reading it. */
311
+ inspectRemotePath(remotePath) {
312
+ return this.withSftp((sftp) => inspectSftpPath(sftp, remotePath));
313
+ }
314
+ /** Copy a remote directory to a local directory; see `saveSftpTree` for the exact contract. */
315
+ saveRemoteTree(remotePath, targetRoot, options = {}) {
316
+ return this.withSftp((sftp) => saveSftpTree(sftp, remotePath, targetRoot, options));
317
+ }
318
+ forwardOut(destHost, destPort, srcHost = '127.0.0.1', srcPort = 0) {
319
+ return new Promise((resolve, reject) => {
320
+ if (!this.client || this.closed) {
321
+ reject(closedError());
322
+ return;
323
+ }
324
+ this.client.forwardOut(srcHost, srcPort, destHost, destPort, (error, stream) => {
325
+ if (error)
326
+ reject(error);
327
+ else
328
+ resolve(stream);
329
+ });
330
+ });
331
+ }
332
+ async dispose() {
333
+ this.disposed = true;
334
+ const client = this.client;
335
+ this.cleanupClient();
336
+ if (!client)
337
+ return;
338
+ // The remote never acknowledges, so bound the wait for our own transport to close.
339
+ await new Promise((resolve) => {
340
+ const timer = setTimeout(resolve, 1_500);
341
+ try {
342
+ client.once('close', () => {
343
+ clearTimeout(timer);
344
+ resolve(undefined);
345
+ });
346
+ client.end();
347
+ }
348
+ catch {
349
+ clearTimeout(timer);
350
+ resolve(undefined);
351
+ }
352
+ });
353
+ }
354
+ cleanupClient() {
355
+ const client = this.client;
356
+ this.client = null;
357
+ this.closed = true;
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
367
+ }
368
+ }
369
+ }
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. */
372
+ export function createSsh2Port(options) {
373
+ return new SshConnection(options);
374
+ }
375
+ /** A private key is a few kilobytes; anything larger is not one and must not be read. */
376
+ const MAX_KEY_BYTES = 1024 * 1024;
377
+ async function readKey(keyPath) {
378
+ let handle = null;
379
+ try {
380
+ // Measure and read through the *same* handle: a stat-then-read is a race, and a non-regular file has no place here.
381
+ handle = await open(keyPath, 'r');
382
+ const stats = await handle.stat();
383
+ if (stats.isFile?.() !== true)
384
+ return null;
385
+ if (typeof stats.size === 'number' && stats.size > MAX_KEY_BYTES)
386
+ return null;
387
+ return await handle.readFile();
388
+ }
389
+ catch {
390
+ return null;
391
+ }
392
+ finally {
393
+ await handle?.close().catch(() => { });
394
+ }
395
+ }
@@ -0,0 +1,174 @@
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. */
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { readJsonFile, withProcessLock, writeJsonAtomic } from './atomic-json.js';
5
+ import { deepMerge, isPlainObject, nowIso, randomId } from './util.js';
6
+ import { defaultSettings, sanitizeHostEntry, sanitizeSettings } from './settings.js';
7
+ /** A JSON array or no entries: a state file that is not an array contributes nothing. */
8
+ function asArray(value) {
9
+ return Array.isArray(value) ? value : [];
10
+ }
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.
13
+ function asRecord(value) {
14
+ return value !== null && typeof value === 'object' ? value : null;
15
+ }
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
+ 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
+ }
30
+ /** Whether `hosts.json` had to be quarantined, i.e. the host list is the empty fallback. */
31
+ get hostsCorrupt() {
32
+ return this.corrupt.has('hosts.json');
33
+ }
34
+ async load() {
35
+ if (this.loaded)
36
+ return this.data;
37
+ try {
38
+ await this.fs.mkdir(this.dir, { recursive: true, mode: 0o700 });
39
+ }
40
+ catch (error) {
41
+ this.logger.warn?.('[dsh-remote-go] cannot create state directory:', error);
42
+ }
43
+ const hosts = asArray(await this.#readJson(this.hostsFile, []));
44
+ this.data.hosts = hosts.filter((item) => item !== null && typeof item === 'object');
45
+ this.data.settings = sanitizeSettings(await this.#readJson(this.settingsFile, null));
46
+ this.secrets = asRecord(await this.#readJson(this.secretsFile, null)) ?? {};
47
+ this.loaded = true;
48
+ return this.data;
49
+ }
50
+ async #readJson(file, fallback) {
51
+ const result = await readJsonFile(file, { fs: this.fs, logger: this.logger });
52
+ if (result.status === 'ok')
53
+ return result.value;
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.
57
+ if (result.status === 'corrupt')
58
+ await this.#quarantine(file);
59
+ return fallback;
60
+ }
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. */
62
+ async #quarantine(file) {
63
+ const name = path.basename(file);
64
+ // The flag means "this file was unreadable", whether or not a copy could be made.
65
+ this.corrupt.add(name);
66
+ // Colons and dots are invalid (Windows) or noisy in a file name, so the ISO stamp is flattened.
67
+ const target = `${file}.corrupt-${nowIso().replace(/[:.]/g, '-')}`;
68
+ try {
69
+ await this.fs.rename(file, target);
70
+ this.logger.warn?.(`[dsh-remote-go] ${name} was unreadable; kept a copy as ${path.basename(target)}`);
71
+ }
72
+ catch (error) {
73
+ this.logger.warn?.(`[dsh-remote-go] cannot keep a copy of the unreadable ${name}:`, error);
74
+ }
75
+ }
76
+ async #writeJson(file, value, mode = 0o600) {
77
+ await withProcessLock(`${file}.lock`, { fs: this.fs, logger: this.logger }, () => writeJsonAtomic(file, value, {
78
+ dir: this.dir,
79
+ fs: this.fs,
80
+ logger: this.logger,
81
+ fileMode: mode,
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));
86
+ }
87
+ async #persistHosts() {
88
+ await this.#writeJson(this.hostsFile, this.data.hosts);
89
+ }
90
+ async #persistSecrets() {
91
+ await this.#writeJson(this.secretsFile, this.secrets);
92
+ }
93
+ listHosts() {
94
+ return this.data.hosts.map((host) => ({ ...host }));
95
+ }
96
+ getHost(id) {
97
+ const host = this.data.hosts.find((item) => item.id === id);
98
+ return host ? { ...host } : null;
99
+ }
100
+ async upsertHost(rawEntry, options = {}) {
101
+ await this.load();
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.
105
+ const rawId = isPlainObject(rawEntry) && typeof rawEntry.id === 'string' ? rawEntry.id : '';
106
+ const existing = rawId === '' ? null : this.getHost(rawId);
107
+ const entry = sanitizeHostEntry(rawEntry, { settings: options.settings ?? this.data.settings, existing });
108
+ entry.id = existing ? existing.id : randomId('h');
109
+ const index = this.data.hosts.findIndex((item) => item.id === entry.id);
110
+ if (index >= 0)
111
+ this.data.hosts[index] = { ...this.data.hosts[index], ...entry };
112
+ else
113
+ this.data.hosts.push(entry);
114
+ await this.#persistHosts();
115
+ return this.getHost(entry.id);
116
+ }
117
+ async removeHost(id) {
118
+ await this.load();
119
+ const before = this.data.hosts.length;
120
+ this.data.hosts = this.data.hosts.filter((item) => item.id !== id);
121
+ if (this.data.hosts.length !== before)
122
+ await this.#persistHosts();
123
+ if (this.secrets[id]) {
124
+ delete this.secrets[id];
125
+ await this.#persistSecrets();
126
+ }
127
+ return before !== this.data.hosts.length;
128
+ }
129
+ async patchHost(id, patch) {
130
+ await this.load();
131
+ const host = this.data.hosts.find((item) => item.id === id);
132
+ if (!host)
133
+ return null;
134
+ Object.assign(host, patch, { updatedAt: nowIso() });
135
+ await this.#persistHosts();
136
+ return { ...host };
137
+ }
138
+ getSettings() {
139
+ return this.data.settings;
140
+ }
141
+ async saveSettings(raw) {
142
+ await this.load();
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.
147
+ this.data.settings = sanitizeSettings(deepMerge(this.data.settings, patch));
148
+ await this.#writeJson(this.settingsFile, this.data.settings);
149
+ if (!this.data.settings.saveTokens) {
150
+ this.secrets = {};
151
+ await this.#persistSecrets();
152
+ }
153
+ return this.data.settings;
154
+ }
155
+ async saveToken(hostId, token) {
156
+ // Without this the first token save on a fresh process wrote `{}` over a secrets file that still
157
+ // held other hosts' tokens.
158
+ await this.load();
159
+ if (!this.data.settings.saveTokens)
160
+ return;
161
+ this.secrets[hostId] = token;
162
+ await this.#persistSecrets();
163
+ }
164
+ }
165
+ export function resolveDshHome(env = process.env) {
166
+ const home = env.DSH_HOME && env.DSH_HOME.trim() !== '' ? env.DSH_HOME.trim() : null;
167
+ if (home)
168
+ return home;
169
+ const userHome = env.USERPROFILE || env.HOME || process.cwd();
170
+ return path.join(userHome, '.dsh');
171
+ }
172
+ export function resolveStateDir(home) {
173
+ return path.join(home, 'remote-go');
174
+ }