dsh-remote-go 0.3.0 → 0.3.2

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 (86) hide show
  1. package/README.md +1 -0
  2. package/dist/client.js +1348 -2095
  3. package/dist/src/admission.js +3 -28
  4. package/dist/src/api.js +37 -99
  5. package/dist/src/atomic-json.js +32 -66
  6. package/dist/src/bootstrap.js +17 -27
  7. package/dist/src/connect/attach.js +3 -25
  8. package/dist/src/connect/bootstrap.js +2 -8
  9. package/dist/src/connect/failures.js +3 -18
  10. package/dist/src/connect/guards.js +13 -8
  11. package/dist/src/connect/launch.js +11 -21
  12. package/dist/src/connect/links.js +11 -27
  13. package/dist/src/connect/ownership.js +33 -114
  14. package/dist/src/connect/pipeline.js +62 -159
  15. package/dist/src/connect/reattach.js +26 -44
  16. package/dist/src/connect/registry.js +0 -1
  17. package/dist/src/connect/repair.js +8 -37
  18. package/dist/src/connect/restart.js +36 -97
  19. package/dist/src/connect/stop.js +16 -50
  20. package/dist/src/connect/transport.js +10 -18
  21. package/dist/src/connect/verify.js +3 -12
  22. package/dist/src/connect/watchdog.js +6 -38
  23. package/dist/src/connect-log.js +16 -41
  24. package/dist/src/connect-progress.js +13 -45
  25. package/dist/src/constants.js +18 -43
  26. package/dist/src/context.js +13 -32
  27. package/dist/src/diagnostics.js +56 -25
  28. package/dist/src/download-jobs.js +11 -20
  29. package/dist/src/errors.js +175 -190
  30. package/dist/src/events.js +20 -84
  31. package/dist/src/host-lifecycle.js +69 -177
  32. package/dist/src/host-registry.js +27 -78
  33. package/dist/src/host-runtime.js +0 -9
  34. package/dist/src/host-view.js +6 -29
  35. package/dist/src/index.js +15 -35
  36. package/dist/src/kernel-adapter.js +34 -80
  37. package/dist/src/key-files.js +10 -23
  38. package/dist/src/known-hosts.js +13 -34
  39. package/dist/src/layout.js +3 -20
  40. package/dist/src/local-download.js +94 -163
  41. package/dist/src/local-ssh.js +12 -19
  42. package/dist/src/local-version.js +35 -49
  43. package/dist/src/node/download.js +1 -4
  44. package/dist/src/node-runtime.js +19 -38
  45. package/dist/src/probe.js +6 -7
  46. package/dist/src/prompts.js +56 -128
  47. package/dist/src/proxy/cookies.js +26 -60
  48. package/dist/src/proxy/headers.js +30 -125
  49. package/dist/src/proxy/http.js +33 -41
  50. package/dist/src/proxy/index.js +20 -34
  51. package/dist/src/proxy/limits.js +4 -6
  52. package/dist/src/proxy/routes.js +10 -17
  53. package/dist/src/proxy/upgrade.js +27 -42
  54. package/dist/src/redact.js +14 -33
  55. package/dist/src/remote-files.js +9 -21
  56. package/dist/src/remote-path.js +21 -62
  57. package/dist/src/remote-proc.js +35 -103
  58. package/dist/src/remote-web/registry.js +10 -50
  59. package/dist/src/remote-web/resolve.js +23 -104
  60. package/dist/src/remote-web/start.js +27 -64
  61. package/dist/src/remote-web/stop.js +6 -25
  62. package/dist/src/request-trust.js +15 -32
  63. package/dist/src/runtime/dispatch.js +33 -143
  64. package/dist/src/runtime/effects.js +7 -17
  65. package/dist/src/runtime/events.js +1 -1
  66. package/dist/src/runtime/fsm.js +11 -61
  67. package/dist/src/runtime/rules.js +121 -199
  68. package/dist/src/secrets.js +15 -38
  69. package/dist/src/service.js +22 -128
  70. package/dist/src/settings.js +41 -42
  71. package/dist/src/ssh-config.js +22 -41
  72. package/dist/src/ssh-failures.js +23 -74
  73. package/dist/src/ssh-sftp.js +47 -86
  74. package/dist/src/ssh.js +99 -179
  75. package/dist/src/store.js +31 -48
  76. package/dist/src/tool-shared.js +17 -52
  77. package/dist/src/tools-exec-policy.js +33 -79
  78. package/dist/src/tools-exec.js +87 -151
  79. package/dist/src/tools-report.js +100 -167
  80. package/dist/src/tools.js +59 -133
  81. package/dist/src/tunnel.js +9 -27
  82. package/dist/src/util.js +19 -56
  83. package/dist/src/version.js +6 -12
  84. package/dist/src/watchdog-bus.js +0 -8
  85. package/dist/src/watchdog.js +7 -47
  86. package/package.json +3 -3
@@ -1,6 +1,5 @@
1
- /**
2
- * Orchestration service — the facade over host-registry, the connect workflow (`connect/`), host-lifecycle, prompts and connect-progress; every external step is injected.
3
- */
1
+ /** Orchestration facade over host-registry, the connect workflow, host-lifecycle, prompts and connect-progress; every
2
+ * external step is injected. */
4
3
  import { EventEmitter } from 'node:events';
5
4
  import { MIN_DSH_VERSION, REMOTE_VIEW_PREFIX } from './constants.js';
6
5
  import { connectLogTail, connectLogVisible } from './connect-log.js';
@@ -23,12 +22,8 @@ import { compareVersions, normalizeVersion, parseVersion } from './version.js';
23
22
  import { nowIso } from './util.js';
24
23
  import { noteRemoteUnreachable } from './watchdog.js';
25
24
  export { describePreflightEvent };
26
- /**
27
- * One Host process can create several services (tests, a plugin reload in-process). The
28
- * instance id must differ for each so the Client can tell a new publish generation from a stale
29
- * frame without trusting wall-clock ordering.
30
- */
31
25
  let stateInstanceSequence = 0;
26
+ /** A fresh instance id per service, so a restarted Host's low `rev` is still accepted as newer. */
32
27
  function stateInstanceId() {
33
28
  stateInstanceSequence += 1;
34
29
  const pid = typeof process !== 'undefined' && Number.isInteger(process.pid) ? process.pid.toString(36) : '0';
@@ -41,27 +36,18 @@ export class RemoteGoService extends EventEmitter {
41
36
  this.home = options.home;
42
37
  this.logger = options.logger ?? console;
43
38
  this.localVersion = options.localVersion ?? null;
44
- // `engines.node` of the local DSH package; the managed Node version is its
45
- // lower bound (see `managedNodeVersionFromEngine`). Null until detected.
46
39
  this.engineNodeRange = options.engineNodeRange ?? null;
47
40
  this.secrets = options.secrets ?? null;
48
41
  this.stateRev = 0;
49
42
  this.stateInstance = stateInstanceId();
50
- /**
51
- * What only the facade can supply: the publish revision, the lazy load, the two adopted
52
- * values (it owns them: `api.ts` and `index.ts` read the fields) and the episode event.
53
- */
43
+ // Only the facade can supply these: the publish revision, the lazy load, the two adopted values
44
+ // (`api.ts` and `index.ts` read the fields) and the episode event.
54
45
  const hooks = {
55
46
  publish: () => this.emitState(),
56
47
  publishLogs: (hostId) => this.emitLogs(hostId),
57
48
  load: () => this.init(),
58
49
  localVersion: () => this.localVersion,
59
50
  engineNodeRange: () => this.engineNodeRange,
60
- /**
61
- * The watchdog reports an episode (suspected -> confirmed -> recovered); the Client
62
- * contract gets the same transitions as one SSE event, and the state frames carry the
63
- * `restarting-remote` progress. Never let a listener failure break the probe.
64
- */
65
51
  onEpisode: (runtime, info) => {
66
52
  try {
67
53
  this.emit('remote-unreachable', { hostId: runtime.id, at: nowIso(), ...info });
@@ -71,24 +57,11 @@ export class RemoteGoService extends EventEmitter {
71
57
  }
72
58
  },
73
59
  };
74
- // The assembly root is `context.ts` (P2/1): this class only owns the facade state above.
75
60
  this.ctx = createCtx({ ...options, logger: this.logger }, hooks);
76
- /**
77
- * The watchdog: one bus (assembled in `context.ts`), one subscriber (`connect/watchdog.ts`),
78
- * installed here because the facade owns the lifecycle — it subscribes now and unsubscribes on
79
- * shutdown, exactly where the three reverse callbacks of design-arch §1.7 used to be wired.
80
- * The two orchestration entries are bound here: the actor is not an entry point, so it takes
81
- * the three slices it reads plus these two callbacks instead of the whole context.
82
- */
83
61
  this.uninstallWatchdog = installWatchdog(this.ctx, {
84
62
  reattach: (runtime, info) => reattachHost(this.ctx, runtime, info),
85
63
  repair: (runtime) => repairTunnel(this.ctx, runtime),
86
64
  });
87
- /**
88
- * `noteRemoteUnreachable` is not a capability: `watchdog.ts` is imported forward by every
89
- * production caller. The alias exists because 13 test call sites drive a proxy/tunnel failure
90
- * through `service.ctx` (design-arch §1.7, §1.6).
91
- */
92
65
  this.ctx.noteRemoteUnreachable = (runtime, source) => noteRemoteUnreachable(this.ctx, runtime, source);
93
66
  this.downloads = createDownloadJobs({
94
67
  logger: this.logger,
@@ -107,13 +80,8 @@ export class RemoteGoService extends EventEmitter {
107
80
  }
108
81
  emitState() {
109
82
  try {
110
- // Every emitted frame gets its own monotonic revision. The Client drops a frame whose
111
- // `rev` is not newer than the one on screen, so an out-of-order SSE delivery or a slow
112
- // `GET /state` can no longer repaint the panel backwards (docs/api.md StateView.rev).
113
- //
114
- // Only a change to the *state model* publishes here. A connect log line is not one: it is
115
- // published on the log channel (`emitLogs`) and must not move `rev`, or the Client would
116
- // discard in-flight `/state` reads every 150 ms (docs/api.md v2.12).
83
+ // Every frame gets its own monotonic revision, so an out-of-order SSE delivery or a slow
84
+ // `GET /state` cannot repaint the panel backwards; a connect log row must not move it.
117
85
  this.stateRev += 1;
118
86
  this.emit('state', this.snapshot());
119
87
  }
@@ -121,14 +89,6 @@ export class RemoteGoService extends EventEmitter {
121
89
  this.logger.warn?.('[dsh-remote-go] state listener failed:', error);
122
90
  }
123
91
  }
124
- /**
125
- * One host's log ring grew: publish it on the log channel only (docs/api.md `GET /events/logs`).
126
- *
127
- * The payload is just the host id; a subscriber reads the cursor view itself, so the event
128
- * carries no snapshot and cannot be confused with a state change. Coalescing (150 ms) belongs
129
- * to the event hub, not here.
130
- * @param hostId - the host whose rows changed.
131
- */
132
92
  emitLogs(hostId) {
133
93
  try {
134
94
  this.emit('logs', { hostId });
@@ -137,26 +97,17 @@ export class RemoteGoService extends EventEmitter {
137
97
  this.logger.warn?.('[dsh-remote-go] log listener failed:', error);
138
98
  }
139
99
  }
140
- /**
141
- * Adopt a DSH version for this machine.
142
- *
143
- * `source === 'client'` is the browser's `POST /local-version` backfill: it exists for the
144
- * case where the Host could not detect the version by itself, so it must never overwrite a
145
- * detected one, and it must stay inside the range this plugin supports. Without both guards
146
- * any local page could pin the remote npx runtime (and the version-parity check) to a value
147
- * of its choosing.
148
- * @param version - a DSH semver string.
149
- * @param source - where the value came from; only `client` is distrusted.
150
- * @returns whether the value was adopted.
151
- */
100
+ /** Adopt a DSH version for this machine. A `client` backfill exists for the case where the Host could not detect the
101
+ * version itself, so it must never overwrite a detected one and must stay inside the supported range — without both
102
+ * guards any local page could pin the remote runtime. */
152
103
  setLocalVersion(version, source = 'detected') {
153
104
  const normalized = version ? normalizeVersion(String(version)) : null;
154
105
  const valid = normalized !== null && parseVersion(normalized) !== null;
106
+ // A client backfill must never overwrite a detected version nor name one below the floor,
107
+ // otherwise any local page could pin the remote npx runtime to a value of its choosing.
155
108
  if (source === 'client') {
156
109
  if (this.localVersion !== null)
157
110
  return false;
158
- // A page may only name a real DSH version: a typo or a crafted value is a client mistake
159
- // (400), not a silent no-op the page could mistake for success.
160
111
  if (!valid) {
161
112
  throw errors.invalidInput('version', {
162
113
  zh: '本机 DSH 版本格式不合法。',
@@ -181,22 +132,10 @@ export class RemoteGoService extends EventEmitter {
181
132
  const text = typeof range === 'string' ? range.trim() : '';
182
133
  this.engineNodeRange = text === '' ? null : text;
183
134
  }
184
- /**
185
- * Build the client-facing state snapshot (contract: docs/api.md).
186
- *
187
- * `options.logs === false` is the state-frame shape: every `hosts[].logs` is `[]` (the log
188
- * channel owns the rows). The default keeps the `GET /state` / diagnostics shape, whose tail is
189
- * the authoritative snapshot and the Client's only fallback when the log channel is missing.
190
- * @param options - `logs: false` strips the per-host tails.
191
- */
135
+ /** Build the client-facing state snapshot; `logs: false` is the state-frame shape that strips every tail. */
192
136
  snapshot(options = {}) {
193
137
  return { ...snapshot(this.ctx, options), rev: this.stateRev, instance: this.stateInstance };
194
138
  }
195
- /**
196
- * One host's cursor view for the log channel, or null for an unknown host.
197
- * Reads the live runtime, so a published row is already in the ring by the time it is asked for.
198
- * @param hostId - the host to read.
199
- */
200
139
  logView(hostId) {
201
140
  const runtime = this.ctx.state.runtimes.get(hostId);
202
141
  if (!runtime)
@@ -204,19 +143,17 @@ export class RemoteGoService extends EventEmitter {
204
143
  const logs = Array.isArray(runtime.logs) ? runtime.logs : [];
205
144
  const seq = typeof runtime.logSeq === 'number' ? runtime.logSeq : 0;
206
145
  const oldest = logs[0];
146
+ // An empty ring reports "one past the current cursor", so a cursor from the last row still replays.
207
147
  const firstSeq = oldest !== undefined && typeof oldest.seq === 'number' ? oldest.seq : seq + 1;
208
148
  return {
209
149
  hostId,
210
- // `connectCount` is what the boundary line numbers ("第 N 次连接"); it only moves forward.
211
150
  attempt: typeof runtime.connectCount === 'number' ? runtime.connectCount : 0,
212
151
  visible: connectLogVisible(runtime.status),
213
152
  firstSeq,
214
153
  seq,
215
- // `connectLogTail` is the one exit for the entry shape (redaction happened at write time).
216
154
  entries: connectLogTail(runtime),
217
155
  };
218
156
  }
219
- /** The hosts whose connect window is on screen, i.e. every host the log channel publishes. */
220
157
  logHostIds() {
221
158
  const ids = [];
222
159
  for (const [id, runtime] of this.ctx.state.runtimes) {
@@ -249,13 +186,7 @@ export class RemoteGoService extends EventEmitter {
249
186
  async connect(id, options = {}) {
250
187
  return startConnect(this.ctx, id, options);
251
188
  }
252
- /**
253
- * Remember (or forget) the SSH password without opening a connection. The wizard's plain
254
- * "save" action uses this, and it is the only way to refresh a saved password that does not
255
- * require a successful connect first. The value never enters `hosts.json`; `available:false`
256
- * means no credential store can persist it here.
257
- * @param id - host id.
258
- */
189
+ /** Remember or forget the SSH password without connecting; the value never enters `hosts.json`. */
259
190
  async saveHostPassword(id, options = {}) {
260
191
  await this.init();
261
192
  const runtime = runtimeOf(this.ctx, id);
@@ -264,8 +195,7 @@ export class RemoteGoService extends EventEmitter {
264
195
  return { available: false, saved: false };
265
196
  if (options.clear === true) {
266
197
  const removed = await this.secrets.remove(id);
267
- // The password in memory belonged to the record just removed: a later connect must ask
268
- // instead of silently reusing a credential the user asked to forget.
198
+ // The in-memory password belonged to the record just removed: a later connect must ask again.
269
199
  runtime.password = null;
270
200
  runtime.passwordSaved = !removed;
271
201
  this.emitState();
@@ -276,8 +206,8 @@ export class RemoteGoService extends EventEmitter {
276
206
  throw errors.invalidInput('password', { zh: '密码不能为空。', en: 'The password must not be empty.' });
277
207
  }
278
208
  const saved = await this.secrets.set(id, password);
279
- // An explicit save also arms the in-memory copy, so clicking "connect" next does not ask
280
- // again for a password this process just proved and stored.
209
+ // An explicit save also arms the in-memory copy, so clicking "connect" next does not ask again
210
+ // for a password this process just proved and stored.
281
211
  runtime.password = password;
282
212
  runtime.passwordSaved = saved;
283
213
  this.emitState();
@@ -291,21 +221,13 @@ export class RemoteGoService extends EventEmitter {
291
221
  await this.init();
292
222
  return reconnectHost(this.ctx, runtimeOf(this.ctx, id));
293
223
  }
294
- /**
295
- * Restart the managed remote web on the same SSH session (the "Restart remote DSH"
296
- * card action). Only a connected host can be restarted; the work runs in the
297
- * background and reports through `/state` like a connect does.
298
- */
224
+ /** Restart the managed remote web on the same SSH session (the "Restart remote DSH" card action). */
299
225
  async restart(id) {
300
226
  await this.init();
301
227
  return restartHost(this.ctx, runtimeOf(this.ctx, id));
302
228
  }
303
- /**
304
- * Stop the managed remote web this connection is bound to, then release the link and
305
- * leave the host `disconnected` (the "Stop remote DSH" card action). Runs synchronously
306
- * on the same SSH session: `/state` carries `stopping-remote` while it works, and a
307
- * refusal (wrong state, busy, or an unprovable pid) is thrown as a coded error (HTTP 409).
308
- */
229
+ /** Stop the managed remote web this connection is bound to, then release the link and leave the host `disconnected`;
230
+ * a refusal (wrong state, busy, unprovable pid) is a coded error (HTTP 409). */
309
231
  async stopRemote(id) {
310
232
  await this.init();
311
233
  return stopRemoteHost(this.ctx, runtimeOf(this.ctx, id));
@@ -327,32 +249,21 @@ export class RemoteGoService extends EventEmitter {
327
249
  const token = encodeURIComponent(runtime.token);
328
250
  return {
329
251
  url: `http://127.0.0.1:${runtime.tunnel.localPort}/?token=${token}`,
330
- // The browser half's carrier: same-origin seat of the same UI, proxied to this tunnel.
331
252
  webUrl: `${REMOTE_VIEW_PREFIX}${encodeURIComponent(id)}/?token=${token}`,
332
253
  localPort: runtime.tunnel.localPort,
333
254
  address: `127.0.0.1:${runtime.tunnel.localPort}`,
334
255
  };
335
256
  }
336
- /** Configured host ids (the proxy keeps one stream upgrade route per id). */
337
257
  hostIds() {
338
258
  return [...this.ctx.state.runtimes.keys()];
339
259
  }
340
- /**
341
- * Loopback target of one host's remote web UI, for the same-origin proxy.
342
- * Reads the live runtime, so a reconnect hands the proxy the new tunnel on the next request.
343
- * @param id - host id.
344
- */
345
260
  webViewTarget(id) {
346
261
  const runtime = this.ctx.state.runtimes.get(id);
347
262
  if (!runtime || runtime.status !== 'connected' || !runtime.tunnel)
348
263
  return null;
349
264
  return { localPort: runtime.tunnel.localPort, remotePort: runtime.remote.port };
350
265
  }
351
- /**
352
- * The same-origin proxy could not reach a host's tunnel. One failed request is not a
353
- * restart: it starts the same probe confirmation the heartbeat uses.
354
- * @param id - host id the proxy serves.
355
- */
266
+ /** One failed proxy request is not a restart: it starts the same probe confirmation the heartbeat uses. */
356
267
  noteUpstreamFailure(id) {
357
268
  const runtime = this.ctx.state.runtimes.get(id);
358
269
  if (!runtime)
@@ -363,39 +274,22 @@ export class RemoteGoService extends EventEmitter {
363
274
  await this.init();
364
275
  return diagnoseHost(runtimeOf(this.ctx, id), { targetVersion: this.localVersion });
365
276
  }
366
- /**
367
- * Start preparing one remote file or folder for the client's download.
368
- * @param id - host id.
369
- * @param path - absolute remote path.
370
- * @param options - local destination directory.
371
- * @returns the initial download job view.
372
- */
373
277
  async startRemoteDownload(id, path, options = {}) {
374
278
  await this.init();
375
279
  const runtime = runtimeOf(this.ctx, id);
376
- // One home root for both checks: the pre-flight below and the write itself. Falling back to
377
- // `os.homedir()` later could disagree with `userHome()` when HOME/USERPROFILE is unset, and
378
- // then a destination accepted here would be refused by the job.
379
280
  const home = this.userHome();
380
- // The local folder is checked before a job exists: a refused destination is the caller's
381
- // mistake (HTTP 400 `invalid-input`), not a job that first answers `preparing` and then
382
- // reports the refusal asynchronously (which also wasted a job slot and an SFTP stat).
383
281
  await requireDestination(options.destination, { home });
384
282
  return this.downloads.start(runtime, path, { ...options, home });
385
283
  }
386
- /** Current view of one download job. */
387
284
  async remoteDownloadStatus(jobId) {
388
285
  await this.init();
389
286
  return this.downloads.status(jobId);
390
287
  }
391
- /** Cancel one download job. */
392
288
  async cancelRemoteDownload(jobId) {
393
289
  await this.init();
394
290
  return this.downloads.cancel(jobId);
395
291
  }
396
292
  async shutdown() {
397
- // Stop reacting to watchdog events before the hosts are torn down: a re-attach or a listener
398
- // rebuild started by a closing episode has nowhere to land. Idempotent.
399
293
  this.uninstallWatchdog?.();
400
294
  this.uninstallWatchdog = null;
401
295
  this.ctx.state.disposed = true;
@@ -1,35 +1,25 @@
1
- /**
2
- * Plugin settings: defaults, validation and sanitization; unknown or invalid fields fall back to defaults instead of failing activation.
3
- */
1
+ /** Plugin settings: defaults, validation and sanitization; unknown or invalid fields fall back to defaults instead of failing activation. */
4
2
  import { DEFAULT_IDLE_MINUTES, DEFAULT_KEY_PATH, DEFAULT_REMOTE_PROFILE, REMOTE_HEARTBEAT_DEFAULT_SEC, REMOTE_HEARTBEAT_MAX_SEC, REMOTE_HEARTBEAT_MIN_SEC, SSH_READY_TIMEOUT_MS, } from './constants.js';
5
3
  import { clamp, deepMerge, isPlainObject, parseSshDestination } from './util.js';
6
4
  export function defaultSettings() {
7
5
  return {
8
6
  defaultPort: 22,
9
- // Only a key file (or a one-time password) is supported: there is no SSH
10
- // agent path any more, so the default is the key file the wizard pre-fills.
7
+ // Only a key file (or a one-time password) is supported: there is no SSH agent path any more,
8
+ // so the default is the key file the wizard pre-fills.
11
9
  defaultAuth: 'key',
12
10
  defaultKeyPath: DEFAULT_KEY_PATH,
13
11
  connectTimeoutSec: Math.round(SSH_READY_TIMEOUT_MS / 1000),
14
12
  autoReconnect: { enabled: true, maxAttempts: 5, baseDelayMs: 800 },
15
- /**
16
- * Light liveness probe of a connected host's remote UI. Two consecutive
17
- * failures re-read the remote and re-attach; one failed request never does.
18
- */
13
+ // Light liveness probe: two consecutive failures re-read the remote and re-attach; one never does.
19
14
  remoteHeartbeat: { enabled: true, intervalSec: REMOTE_HEARTBEAT_DEFAULT_SEC },
20
15
  hostKeyPolicy: 'first-use',
21
16
  saveTokens: false,
22
17
  language: 'auto',
23
18
  logLevel: 'info',
24
- bootstrap: {
25
- profile: DEFAULT_REMOTE_PROFILE,
26
- },
19
+ bootstrap: { profile: DEFAULT_REMOTE_PROFILE },
27
20
  };
28
21
  }
29
- /**
30
- * A profile name DSH can boot: one safe path segment, and never `desktop`
31
- * (the Electron app reserves that profile and the CLI refuses it).
32
- */
22
+ /** A profile name DSH can boot: one safe path segment, and never `desktop` (the Electron app reserves that profile and the CLI refuses it). */
33
23
  function normalizeProfileName(value) {
34
24
  const text = typeof value === 'string' ? value.trim() : '';
35
25
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(text))
@@ -50,13 +40,23 @@ function numberIn(value, min, max, fallback) {
50
40
  function boolean(value, fallback) {
51
41
  return typeof value === 'boolean' ? value : fallback;
52
42
  }
43
+ /** A trimmed non-empty string, or `fallback` when the patch names nothing usable. */
44
+ function textOr(value, fallback) {
45
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
46
+ }
47
+ /** A trimmed non-empty string, or `fallback` (null included) when the patch names nothing usable. */
48
+ function optionalText(value, fallback) {
49
+ if (typeof value !== 'string')
50
+ return fallback;
51
+ return value.trim() !== '' ? value.trim() : null;
52
+ }
53
53
  export function sanitizeSettings(raw) {
54
54
  const defaults = defaultSettings();
55
55
  if (!isPlainObject(raw))
56
56
  return defaults;
57
- // A stored file may still carry a retired value (`defaultAuth: "agent"`), so every field is
58
- // read through a loose view: the type says what a *sanitized* settings object holds, not
59
- // what the file on disk holds.
57
+ // A stored file may still carry a retired value (`defaultAuth: "agent"`), so every field is read
58
+ // through a loose view: the type says what a *sanitized* settings object holds, not what the file
59
+ // on disk holds.
60
60
  const input = deepMerge(defaults, raw);
61
61
  const autoReconnect = isPlainObject(input.autoReconnect) ? input.autoReconnect : defaults.autoReconnect;
62
62
  const remoteHeartbeat = isPlainObject(input.remoteHeartbeat) ? input.remoteHeartbeat : defaults.remoteHeartbeat;
@@ -64,12 +64,10 @@ export function sanitizeSettings(raw) {
64
64
  const profile = normalizeProfileName(bootstrap.profile) ?? defaults.bootstrap.profile;
65
65
  return {
66
66
  defaultPort: numberIn(input.defaultPort, 1, 65535, defaults.defaultPort),
67
- // The retired "agent" choice migrates to key-file auth instead of silently
68
- // resetting, because key files are the only non-interactive option left.
67
+ // The retired "agent" choice migrates to key-file auth instead of silently resetting, because
68
+ // key files are the only non-interactive option left.
69
69
  defaultAuth: input.defaultAuth === 'agent' ? 'key' : oneOf(input.defaultAuth, ['key', 'password'], defaults.defaultAuth),
70
- defaultKeyPath: typeof input.defaultKeyPath === 'string' && input.defaultKeyPath.trim() !== ''
71
- ? input.defaultKeyPath.trim()
72
- : defaults.defaultKeyPath,
70
+ defaultKeyPath: textOr(input.defaultKeyPath, defaults.defaultKeyPath),
73
71
  connectTimeoutSec: numberIn(input.connectTimeoutSec, 5, 300, defaults.connectTimeoutSec),
74
72
  autoReconnect: {
75
73
  enabled: boolean(autoReconnect.enabled, defaults.autoReconnect.enabled),
@@ -84,13 +82,21 @@ export function sanitizeSettings(raw) {
84
82
  saveTokens: boolean(input.saveTokens, defaults.saveTokens),
85
83
  language: oneOf(input.language, ['auto', 'zh', 'en'], defaults.language),
86
84
  logLevel: oneOf(input.logLevel, ['error', 'warn', 'info', 'debug'], defaults.logLevel),
87
- bootstrap: {
88
- profile,
89
- },
85
+ bootstrap: { profile },
90
86
  };
91
87
  }
92
88
  /** The only id shape this plugin issues: `randomId('h')` (docs/api.md `HostView.id`). */
93
89
  export const HOST_ID_RE = /^h_[a-z0-9]{1,32}$/;
90
+ /** The persisted auth choice; a payload that names no usable type falls back to the settings default. */
91
+ function readAuthType(auth, existing, settings) {
92
+ if (auth === null)
93
+ return existing?.auth?.type ?? settings.defaultAuth;
94
+ // The retired "agent" choice migrates instead of resetting: key files are the only non-interactive
95
+ // option left, and a silent reset would drop a configured key path from the form.
96
+ if (auth.type === 'agent')
97
+ return 'key';
98
+ return oneOf(auth.type, ['key', 'password'], settings.defaultAuth);
99
+ }
94
100
  export function sanitizeHostEntry(raw, options = {}) {
95
101
  const settings = options.settings ?? defaultSettings();
96
102
  const existing = options.existing ?? null;
@@ -100,36 +106,29 @@ export function sanitizeHostEntry(raw, options = {}) {
100
106
  const address = typeof raw.address === 'string' ? raw.address.trim() : '';
101
107
  if (address === '')
102
108
  throw new Error('address is required');
103
- // `parseSshDestination` never returns an `alias`; the fallback below is dead but the order
104
- // of fallbacks is part of the accepted host-name shape, so it stays.
109
+ // `parseSshDestination` never returns an `alias`; the fallback below is dead but the order of
110
+ // fallbacks is part of the accepted host-name shape, so it stays.
105
111
  const destination = parseSshDestination(address);
106
112
  if (!destination.host)
107
113
  throw new Error('address is invalid');
108
114
  const userInput = typeof raw.username === 'string' ? raw.username.trim() : '';
109
115
  const username = userInput || existing?.username || destination.user || '';
110
- const authType = raw.auth && isPlainObject(raw.auth)
111
- ? raw.auth.type === 'agent'
112
- ? 'key'
113
- : oneOf(raw.auth.type, ['key', 'password'], settings.defaultAuth)
114
- : (existing?.auth?.type ?? settings.defaultAuth);
115
- const keyPathInput = raw.auth && isPlainObject(raw.auth) && typeof raw.auth.keyPath === 'string' ? raw.auth.keyPath.trim() : '';
116
+ const authPatch = isPlainObject(raw.auth) ? raw.auth : null;
117
+ const authType = readAuthType(authPatch, existing, settings);
118
+ const keyPathInput = authPatch !== null && typeof authPatch.keyPath === 'string' ? authPatch.keyPath.trim() : '';
116
119
  const keyPath = keyPathInput || existing?.auth?.keyPath || (authType === 'key' ? settings.defaultKeyPath : '');
117
120
  const keepAlive = oneOf(raw.keepAlive, ['keep', 'stop', 'idle'], existing?.keepAlive ?? 'keep');
118
121
  const hostKeyPolicy = oneOf(raw.hostKeyPolicy, ['first-use', 'strict'], existing?.hostKeyPolicy ?? settings.hostKeyPolicy);
119
122
  return {
120
- // A malformed or over-long id is never echoed: an id names the secrets entry, the proxy
121
- // route and the client's host link, so only the shape this plugin issues is accepted.
123
+ // A malformed or over-long id is never echoed: an id names the secrets entry, the proxy route
124
+ // and the client's host link, so only the shape this plugin issues is accepted.
122
125
  id: typeof raw.id === 'string' && HOST_ID_RE.test(raw.id) ? raw.id : (existing?.id ?? undefined),
123
126
  name: name || destination.host || destination.alias || 'remote',
124
127
  address,
125
128
  port: numberIn(raw.port ?? destination.port ?? existing?.port, 1, 65535, settings.defaultPort),
126
129
  username: username || null,
127
130
  auth: { type: authType, ...(keyPath ? { keyPath } : {}) },
128
- jumpHost: typeof raw.jumpHost === 'string'
129
- ? raw.jumpHost.trim() !== ''
130
- ? raw.jumpHost.trim()
131
- : null
132
- : (existing?.jumpHost ?? null),
131
+ jumpHost: optionalText(raw.jumpHost, existing?.jumpHost ?? null),
133
132
  keepAlive,
134
133
  idleMinutes: numberIn(raw.idleMinutes ?? existing?.idleMinutes, 1, 24 * 60, DEFAULT_IDLE_MINUTES),
135
134
  autoReconnect: boolean(raw.autoReconnect, existing?.autoReconnect ?? settings.autoReconnect.enabled),
@@ -1,6 +1,5 @@
1
- /**
2
- * Read-only `~/.ssh/config` parsing and alias discovery for the subset `ssh_config(5)` defines; `Include`, `Match` and `ProxyCommand` are reported, not guessed.
3
- */
1
+ /** Read-only `~/.ssh/config` parsing and alias discovery for the `ssh_config(5)` subset; `Include`, `Match` and
2
+ * `ProxyCommand` are reported, never guessed. */
4
3
  const KNOWN_OPTIONS = new Set([
5
4
  'hostname',
6
5
  'user',
@@ -15,6 +14,7 @@ const KNOWN_OPTIONS = new Set([
15
14
  'identitiesonly',
16
15
  'preferredauthentications',
17
16
  ]);
17
+ // `Host = x` keeps `= x` as its value: the first whitespace wins unless `=` comes before it.
18
18
  function parseLine(line) {
19
19
  const trimmed = line.trim();
20
20
  if (trimmed === '' || trimmed.startsWith('#'))
@@ -60,6 +60,11 @@ export function parseSshConfig(text) {
60
60
  const globals = {};
61
61
  const unsupported = [];
62
62
  const malformed = [];
63
+ // A repeated keyword appends: `IdentityFile` may legitimately appear several times in one block.
64
+ const appendOption = (target, key, value) => {
65
+ target[key] ??= [];
66
+ target[key].push(value);
67
+ };
63
68
  let current = null;
64
69
  const lines = String(text ?? '').split(/\r?\n/);
65
70
  for (let index = 0; index < lines.length; index += 1) {
@@ -79,8 +84,7 @@ export function parseSshConfig(text) {
79
84
  }
80
85
  if (keyword === 'match') {
81
86
  unsupported.push({ line: lineNo, keyword: 'Match' });
82
- // Options inside a Match block only apply under conditions we cannot
83
- // evaluate; skip them until the next Host block.
87
+ // Options inside a Match block only apply under conditions we cannot evaluate; skip to the next Host.
84
88
  current = { patterns: ['__dsh_remote_go_match_block__'], negated: [], options: {}, line: lineNo };
85
89
  entries.push(current);
86
90
  continue;
@@ -90,8 +94,7 @@ export function parseSshConfig(text) {
90
94
  continue;
91
95
  }
92
96
  if (!KNOWN_OPTIONS.has(keyword)) {
93
- // Unknown-but-harmless options are ignored; only flag keywords that would
94
- // change meaning if misread.
97
+ // Unknown-but-harmless options are ignored; only flag keywords that would change meaning if misread.
95
98
  if (keyword === 'proxycommand' || keyword === 'certificatefile')
96
99
  unsupported.push({ line: lineNo, keyword: parsed.keyword });
97
100
  continue;
@@ -100,14 +103,7 @@ export function parseSshConfig(text) {
100
103
  malformed.push({ line: lineNo, text: lines[index] });
101
104
  continue;
102
105
  }
103
- if (current) {
104
- current.options[keyword] = current.options[keyword] ?? [];
105
- current.options[keyword].push(parsed.value);
106
- }
107
- else {
108
- globals[keyword] = globals[keyword] ?? [];
109
- globals[keyword].push(parsed.value);
110
- }
106
+ appendOption(current ? current.options : globals, keyword, parsed.value);
111
107
  }
112
108
  return { entries, globals, unsupported, malformed };
113
109
  }
@@ -123,8 +119,7 @@ export function matchHostPattern(pattern, value) {
123
119
  export function entryMatches(entry, alias) {
124
120
  if (entry.patterns.includes('__dsh_remote_go_match_block__'))
125
121
  return false;
126
- const positive = entry.patterns.some((pattern) => matchHostPattern(pattern, alias));
127
- if (!positive)
122
+ if (!entry.patterns.some((pattern) => matchHostPattern(pattern, alias)))
128
123
  return false;
129
124
  return !entry.negated.some((pattern) => matchHostPattern(pattern, alias));
130
125
  }
@@ -134,13 +129,10 @@ function effectiveOptions(globals, entries, alias, tokens) {
134
129
  const apply = (options) => {
135
130
  for (const [key, values] of Object.entries(options)) {
136
131
  const expanded = values.map((value) => expandTokens(value, tokens));
137
- if (ADDITIVE_OPTIONS.has(key)) {
132
+ if (ADDITIVE_OPTIONS.has(key))
138
133
  out[key] = [...(out[key] ?? []), ...expanded];
139
- continue;
140
- }
141
- if (out[key] !== undefined)
142
- continue;
143
- out[key] = expanded;
134
+ else if (out[key] === undefined)
135
+ out[key] = expanded;
144
136
  }
145
137
  };
146
138
  apply(globals);
@@ -172,25 +164,14 @@ export function resolveSshAlias(parsed, alias, options = {}) {
172
164
  const user = firstPass.user?.[0] ?? null;
173
165
  const rawPort = firstPass.port?.[0] ?? '22';
174
166
  const port = /^\d+$/.test(rawPort) ? Number(rawPort) : 22;
167
+ // Second pass: `%h`/`%p` now resolve to the values the first pass found.
175
168
  const tokens = { h: host, r: user ?? '~', p: String(port), d: home };
176
169
  const resolved = effectiveOptions(parsed.globals, parsed.entries, alias, tokens);
177
170
  const identityFiles = (resolved.identityfile ?? []).map((value) => expandTilde(value, home));
178
171
  const proxyJump = resolved.proxyjump?.[0] ?? null;
179
- return {
180
- alias,
181
- host,
182
- user,
183
- port,
184
- identityFiles,
185
- proxyJump,
186
- source: 'config',
187
- };
172
+ return { alias, host, user, port, identityFiles, proxyJump, source: 'config' };
188
173
  }
189
- /**
190
- * List concrete, manually-dialable aliases from the config. Wildcard patterns
191
- * (`*`, `?`) and negations are skipped because they cannot be resolved without
192
- * a concrete target.
193
- */
174
+ /** List concrete, manually-dialable aliases: a wildcard or negated pattern cannot resolve without a real target. */
194
175
  export function discoverSshAliases(parsed, options = {}) {
195
176
  const out = [];
196
177
  const seen = new Set();
@@ -212,8 +193,7 @@ export function resolveDestination(destination, options = {}) {
212
193
  const literal = parseDestinationLiteral(text);
213
194
  const parsed = parseSshConfig(options.configText ?? '');
214
195
  const home = options.home ?? '~';
215
- const aliases = discoverSshAliases(parsed, { home });
216
- const alias = aliases.find((item) => item.alias === text);
196
+ const alias = discoverSshAliases(parsed, { home }).find((item) => item.alias === text);
217
197
  if (alias) {
218
198
  const resolved = resolveSshAlias(parsed, text, { home });
219
199
  return {
@@ -227,8 +207,8 @@ export function resolveDestination(destination, options = {}) {
227
207
  source: 'config',
228
208
  };
229
209
  }
230
- // Literal destination: inherit globals (e.g. a global IdentityFile) but not
231
- // Host blocks that do not match the literal text.
210
+ // Literal destination: inherit globals (e.g. a global IdentityFile) but not Host blocks that do not match
211
+ // the literal text, which is why the entries list passed below is empty.
232
212
  const tokens = { h: literal.host, r: literal.user ?? '~', p: String(literal.port ?? 22), d: home };
233
213
  const globals = effectiveOptions(parsed.globals, [], text, tokens);
234
214
  const identityFiles = (globals.identityfile ?? []).map((value) => expandTilde(value, home));
@@ -264,6 +244,7 @@ function parseDestinationLiteral(text) {
264
244
  }
265
245
  else {
266
246
  const colon = rest.lastIndexOf(':');
247
+ // Only an unbracketed `host:port`: a bare IPv6 literal keeps every colon.
267
248
  if (colon > 0 && rest.indexOf(':') === colon) {
268
249
  const maybePort = rest.slice(colon + 1);
269
250
  if (/^\d{1,5}$/.test(maybePort)) {