dsh-remote-go 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/client.js +1344 -2095
  2. package/dist/src/admission.js +3 -28
  3. package/dist/src/api.js +37 -99
  4. package/dist/src/atomic-json.js +32 -66
  5. package/dist/src/bootstrap.js +17 -27
  6. package/dist/src/connect/attach.js +3 -25
  7. package/dist/src/connect/bootstrap.js +2 -8
  8. package/dist/src/connect/failures.js +3 -18
  9. package/dist/src/connect/guards.js +13 -8
  10. package/dist/src/connect/launch.js +11 -21
  11. package/dist/src/connect/links.js +11 -27
  12. package/dist/src/connect/ownership.js +33 -114
  13. package/dist/src/connect/pipeline.js +61 -158
  14. package/dist/src/connect/reattach.js +20 -44
  15. package/dist/src/connect/registry.js +0 -1
  16. package/dist/src/connect/repair.js +8 -37
  17. package/dist/src/connect/restart.js +36 -97
  18. package/dist/src/connect/stop.js +16 -50
  19. package/dist/src/connect/transport.js +10 -18
  20. package/dist/src/connect/verify.js +3 -12
  21. package/dist/src/connect/watchdog.js +6 -38
  22. package/dist/src/connect-log.js +16 -41
  23. package/dist/src/connect-progress.js +13 -45
  24. package/dist/src/constants.js +2 -40
  25. package/dist/src/context.js +10 -31
  26. package/dist/src/diagnostics.js +56 -25
  27. package/dist/src/download-jobs.js +11 -20
  28. package/dist/src/errors.js +175 -190
  29. package/dist/src/events.js +20 -84
  30. package/dist/src/host-lifecycle.js +39 -175
  31. package/dist/src/host-registry.js +27 -78
  32. package/dist/src/host-runtime.js +0 -9
  33. package/dist/src/host-view.js +6 -29
  34. package/dist/src/index.js +15 -35
  35. package/dist/src/kernel-adapter.js +34 -80
  36. package/dist/src/key-files.js +10 -23
  37. package/dist/src/known-hosts.js +13 -34
  38. package/dist/src/layout.js +3 -20
  39. package/dist/src/local-download.js +94 -163
  40. package/dist/src/local-ssh.js +12 -19
  41. package/dist/src/local-version.js +35 -49
  42. package/dist/src/node/download.js +1 -4
  43. package/dist/src/node-runtime.js +19 -38
  44. package/dist/src/probe.js +6 -7
  45. package/dist/src/prompts.js +56 -128
  46. package/dist/src/proxy/cookies.js +26 -60
  47. package/dist/src/proxy/headers.js +30 -125
  48. package/dist/src/proxy/http.js +33 -41
  49. package/dist/src/proxy/index.js +20 -34
  50. package/dist/src/proxy/limits.js +4 -6
  51. package/dist/src/proxy/routes.js +10 -17
  52. package/dist/src/proxy/upgrade.js +27 -42
  53. package/dist/src/redact.js +14 -33
  54. package/dist/src/remote-files.js +9 -21
  55. package/dist/src/remote-path.js +21 -62
  56. package/dist/src/remote-proc.js +35 -103
  57. package/dist/src/remote-web/registry.js +10 -50
  58. package/dist/src/remote-web/resolve.js +23 -104
  59. package/dist/src/remote-web/start.js +27 -64
  60. package/dist/src/remote-web/stop.js +6 -25
  61. package/dist/src/request-trust.js +15 -32
  62. package/dist/src/runtime/dispatch.js +33 -143
  63. package/dist/src/runtime/effects.js +7 -17
  64. package/dist/src/runtime/events.js +1 -1
  65. package/dist/src/runtime/fsm.js +11 -61
  66. package/dist/src/runtime/rules.js +113 -198
  67. package/dist/src/secrets.js +15 -38
  68. package/dist/src/service.js +22 -128
  69. package/dist/src/settings.js +41 -42
  70. package/dist/src/ssh-config.js +22 -41
  71. package/dist/src/ssh-failures.js +23 -74
  72. package/dist/src/ssh-sftp.js +47 -86
  73. package/dist/src/ssh.js +95 -177
  74. package/dist/src/store.js +31 -48
  75. package/dist/src/tool-shared.js +17 -52
  76. package/dist/src/tools-exec-policy.js +33 -79
  77. package/dist/src/tools-exec.js +87 -151
  78. package/dist/src/tools-report.js +100 -167
  79. package/dist/src/tools.js +59 -133
  80. package/dist/src/tunnel.js +9 -27
  81. package/dist/src/util.js +19 -56
  82. package/dist/src/version.js +6 -12
  83. package/dist/src/watchdog-bus.js +0 -8
  84. package/dist/src/watchdog.js +7 -47
  85. package/package.json +1 -1
@@ -1,9 +1,5 @@
1
- /**
2
- * Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path; the
3
- * reconnect timer gets a callback, so this never imports the pipeline. The liveness watchdog that
4
- * used to live here moved to `watchdog.ts` (P2 step 9); only the timer primitives it disarms stay,
5
- * because this module owns the runtime's timer block.
6
- */
1
+ /** Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path. The reconnect timer is
2
+ * created through a callback, so this module never imports the pipeline; only the timer primitives live here. */
7
3
  import { DEFAULT_IDLE_MINUTES, REMOTE_TUNNEL_REPAIR_SETTLE_MS } from './constants.js';
8
4
  import { OWNERSHIP_OPTIONS, proveOwnership } from './connect/ownership.js';
9
5
  import { errors, toErrorView } from './errors.js';
@@ -24,14 +20,6 @@ export function cancelIdleStop(runtime) {
24
20
  runtime.idleTimer = null;
25
21
  }
26
22
  }
27
- /**
28
- * One-shot link actions (a local restart, a remote re-attach, a tunnel rebuild) share a
29
- * token so a disconnect, a dropped transport or a newer action can invalidate an older one:
30
- * an action must never write state on top of whatever replaced it.
31
- * @param runtime - host runtime.
32
- * @param kind - `restart`, `reattach`, `repair` or `stop`.
33
- * @returns the token that owns the action.
34
- */
35
23
  export function beginLinkWork(runtime, kind) {
36
24
  runtime.linkToken = (Number(runtime.linkToken) || 0) + 1;
37
25
  runtime.linkBusy = kind;
@@ -45,7 +33,6 @@ export function endLinkWork(runtime, token) {
45
33
  return;
46
34
  runtime.linkBusy = null;
47
35
  }
48
- /** Invalidate whatever one-shot action was running; safe when there is none. */
49
36
  export function cancelLinkWork(runtime) {
50
37
  runtime.linkToken = (Number(runtime.linkToken) || 0) + 1;
51
38
  runtime.linkBusy = null;
@@ -56,7 +43,6 @@ export function cancelRemoteCheck(runtime) {
56
43
  runtime.remoteCheckTimer = null;
57
44
  }
58
45
  }
59
- /** Stop probing: called on connect, disconnect, re-attach and shutdown. */
60
46
  export function stopRemoteHeartbeat(runtime) {
61
47
  if (runtime.heartbeatTimer) {
62
48
  clearInterval(runtime.heartbeatTimer);
@@ -66,110 +52,69 @@ export function stopRemoteHeartbeat(runtime) {
66
52
  runtime.remoteFailures = 0;
67
53
  runtime.remoteEpisode = false;
68
54
  runtime.episodeSource = null;
69
- // A new attach starts a new episode budget; the cooldown only exists to damp one connection.
70
55
  runtime.episodeCooldownUntil = 0;
71
56
  }
72
- /**
73
- * Arm the next reconnect attempt, or give up once the configured budget is spent.
74
- *
75
- * The timer is created through `reconnect.scheduled`; that event is the **only** `arm(reconnect)`
76
- * the executor turns into a timeout (the design's P2b hand-off: the connect-failure paths also ask
77
- * for a retry, and honouring those would run a second loop). The rule decides whether the attempt
78
- * is still wanted, the policy/budget/randomized delay stay here.
79
- */
80
57
  export function scheduleReconnect(ctx, runtime, onDue) {
81
58
  cancelReconnect(runtime);
82
- // A retry only makes sense while the user still wants the link: a disconnect, a host
83
- // removal or a shutdown that raced the timer must not resurrect the connection.
84
- if (ctx.state.disposed === true || runtime.desired !== 'connected') {
85
- void dispatch(effectsOf(ctx), runtime, { type: 'reconnect.skipped' }, scopeFactsFor(ctx, runtime, { type: 'reconnect.skipped' }), {
86
- caller: 'timer',
87
- });
88
- return;
89
- }
59
+ // Only `reconnect.scheduled` may arm the one retry timer: the connect-failure paths also ask for a
60
+ // retry, and honouring those here would run a second loop.
61
+ const skipped = { type: 'reconnect.skipped' };
62
+ const skip = () => {
63
+ void dispatch(effectsOf(ctx), runtime, skipped, scopeFactsFor(ctx, runtime, skipped), { caller: 'timer' });
64
+ };
65
+ if (ctx.state.disposed === true || runtime.desired !== 'connected')
66
+ return skip();
90
67
  const settings = ctx.settings();
91
- if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled) {
92
- void dispatch(effectsOf(ctx), runtime, { type: 'reconnect.skipped' }, scopeFactsFor(ctx, runtime, { type: 'reconnect.skipped' }), {
93
- caller: 'timer',
94
- });
95
- return;
96
- }
68
+ if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled)
69
+ return skip();
97
70
  const maxAttempts = settings.autoReconnect.maxAttempts;
98
71
  if (runtime.reconnectAttempts >= maxAttempts) {
99
- const event = {
100
- type: 'reconnect.gaveup',
101
- maxAttempts,
102
- view: toErrorView(errors.network({
103
- zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
104
- en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
105
- })),
106
- };
72
+ const view = toErrorView(errors.network({
73
+ zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
74
+ en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
75
+ }));
76
+ const event = { type: 'reconnect.gaveup', maxAttempts, view };
107
77
  void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' });
108
78
  return;
109
79
  }
110
80
  const attempt = runtime.reconnectAttempts + 1;
111
- const delay = randomDelay(settings.autoReconnect.baseDelayMs, settings.autoReconnect.baseDelayMs * 2 ** Math.min(attempt, 4));
112
- ctx.progress.log(runtime, 'warn', `link lost; retrying in ${Math.round(delay / 100) / 10}s (attempt ${attempt}/${maxAttempts})`);
113
- void dispatch(effectsOf(ctx), runtime, { type: 'reconnect.scheduled', attempt, max: maxAttempts, delayMs: delay }, scopeFactsFor(ctx, runtime, { type: 'reconnect.scheduled', attempt, max: maxAttempts, delayMs: delay }), {
81
+ const baseDelayMs = settings.autoReconnect.baseDelayMs;
82
+ const delay = randomDelay(baseDelayMs, baseDelayMs * 2 ** Math.min(attempt, 4));
83
+ const seconds = Math.round(delay / 100) / 10;
84
+ ctx.progress.log(runtime, 'warn', `link lost; retrying in ${seconds}s (attempt ${attempt}/${maxAttempts})`);
85
+ const scheduled = { type: 'reconnect.scheduled', attempt, max: maxAttempts, delayMs: delay };
86
+ void dispatch(effectsOf(ctx), runtime, scheduled, scopeFactsFor(ctx, runtime, scheduled), {
114
87
  caller: 'timer',
115
88
  armReconnect: (ms) => {
116
89
  runtime.reconnectTimer = setTimeout(() => {
117
90
  runtime.reconnectTimer = null;
118
91
  onDue();
119
92
  }, ms);
120
- // A pending retry must never keep the host process alive on its own.
121
93
  runtime.reconnectTimer.unref?.();
122
94
  },
123
95
  });
124
96
  }
125
- /**
126
- * The idle policy's timer. It is a *guard* first and a stop second: `idle.elapsed` is the FSM's
127
- * statement that the host is no longer wanted (`stillWanted`), and a refusal — the user connected
128
- * again while the timer was armed — is logged at debug by the event itself, never as a warning.
129
- */
130
97
  export function scheduleIdleStop(ctx, runtime) {
131
98
  cancelIdleStop(runtime);
132
99
  const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES);
133
100
  runtime.idleTimer = setTimeout(() => {
134
101
  runtime.idleTimer = null;
135
102
  const event = { type: 'idle.elapsed' };
136
- void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' }).then(async (result) => {
137
- // The rule allows the stop only while the host is idle; `stopRemoteForIdle` re-checks the
138
- // same condition and remains the single implementation of the policy itself.
139
- if (result.ok)
140
- await stopRemoteForIdle(ctx, runtime);
141
- });
103
+ void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' }).then((result) => (result.ok ? stopRemoteForIdle(ctx, runtime) : undefined));
142
104
  }, minutes * 60_000);
143
105
  runtime.idleTimer.unref?.();
144
106
  }
145
- /**
146
- * Best-effort stop of the remote web for the idle policy, then drop the transport.
147
- *
148
- * The teardown that armed this timer clears `facts` and `remote`, so the stop has to use the
149
- * home and pid remembered before that clearing: the old fallback built a layout with a
150
- * literal `~`, whose `kill -0` is a no-op that still reported success (H1).
151
- *
152
- * The timer is a *policy for an idle host*, never authority over a live link: the user may
153
- * have connected again (the timer would otherwise kill the link just brought up), and a pid
154
- * that answers `/proc` is not proof it is still the process this connection started
155
- * (review: idle-timer zombie / pid reuse). Shutdown is the one caller that deliberately
156
- * overrides the "still wanted" guard, because it is stopping the whole host process.
157
- *
158
- * @param ctx - service context.
159
- * @param runtime - host runtime that went idle.
160
- * @returns the stop verdict (best effort).
161
- */
162
107
  export async function stopRemoteForIdle(ctx, runtime, options = {}) {
163
- // A live link wins over the idle policy, whichever timer fired it. This is what keeps a
164
- // manual reconnect from being torn down by the timer armed before it.
108
+ // The timer is a policy for an idle host, never authority over a live link: a manual reconnect
109
+ // must not be torn down by the timer armed before it.
165
110
  const linkLive = runtime.desired === 'connected' || runtime.status === 'connected' || runtime.tunnel !== null;
166
111
  if (linkLive && options.shutdown !== true) {
167
112
  ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
168
113
  return { ok: false, reason: 'still-wanted' };
169
114
  }
170
- // The transport this call owns: the identity proof below awaits, and the user may connect
171
- // in that window. Only this session may be released afterwards, never the new one.
172
115
  const capturedSsh = runtime.ssh;
116
+ // The identity proof below awaits and the user may connect in that window: only this session may
117
+ // be released afterwards, never the new one.
173
118
  const stillWanted = () => runtime.ssh !== capturedSsh ||
174
119
  runtime.desired === 'connected' ||
175
120
  runtime.status === 'connected' ||
@@ -184,13 +129,8 @@ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
184
129
  }
185
130
  const layout = layoutForRuntime(runtime);
186
131
  const pid = Number(runtime.remote.pid ?? runtime.remotePid ?? 0);
187
- // Without a pid there is nothing this policy may signal: `stopRemoteWeb` would fall back
188
- // to the run registry and could stop an instance this connection did not launch.
189
132
  if (!isPid(pid))
190
133
  return { ok: false, reason: 'pid-unknown' };
191
- // Same `/proc` identity proof the explicit stop uses (`OWNERSHIP_OPTIONS.idle`): a reused
192
- // pid, another DSH home or another profile is not this connection's process and must not be
193
- // signalled — and unlike the stop, nobody pointed at it, only the timer fired.
194
134
  const proof = await proveOwnership(ctx, runtime, {
195
135
  ...OWNERSHIP_OPTIONS.idle,
196
136
  pid,
@@ -201,28 +141,25 @@ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
201
141
  ctx.progress.log(runtime, 'warn', `idle stop skipped: ${proof.reason}`);
202
142
  return { ok: false, reason: proof.reason };
203
143
  }
204
- // The user may have connected while the identity was read: the link wins again.
205
144
  if (options.shutdown !== true && stillWanted()) {
206
145
  ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
207
146
  return { ok: false, reason: 'still-wanted' };
208
147
  }
209
148
  const stopped = await ctx.deps.stopWeb(capturedSsh, layout, { pid });
210
149
  if (stopped?.ok !== true) {
211
- ctx.progress.log(runtime, 'warn', `idle stop did not confirm (${stopped?.reason ?? 'unknown'}); the remote may still be running`);
150
+ const why = stopped?.reason ?? 'unknown';
151
+ ctx.progress.log(runtime, 'warn', `idle stop did not confirm (${why}); the remote may still be running`);
212
152
  return { ok: false, reason: stopped?.reason ?? 'not-confirmed' };
213
153
  }
214
154
  runtime.remotePid = null;
215
155
  return { ok: true };
216
156
  }
217
157
  catch (error) {
218
- // swallow-ok: the idle stop is best effort; its failure is only a warning and the timer
219
- // is already gone, so the host stays idle either way
158
+ // swallow-ok: the idle stop is best effort; its failure is only a warning and the timer is gone
220
159
  ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error));
221
160
  return { ok: false, reason: 'error' };
222
161
  }
223
162
  finally {
224
- // Release only the transport this call captured: when a new connection owns the link by
225
- // now, its session is not ours to dispose.
226
163
  if (runtime.ssh === capturedSsh)
227
164
  await disposeSsh(runtime);
228
165
  }
@@ -230,8 +167,6 @@ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
230
167
  export async function closeTunnel(runtime) {
231
168
  const tunnel = runtime.tunnel;
232
169
  runtime.tunnel = null;
233
- // `localPort` is a view of the live listener: a closed tunnel must not leave a stale port
234
- // behind (the proxy and diagnostics read this field).
235
170
  runtime.remote.localPort = null;
236
171
  if (tunnel) {
237
172
  try {
@@ -264,20 +199,6 @@ export async function disposeSsh(runtime) {
264
199
  }
265
200
  }
266
201
  }
267
- /**
268
- * The single teardown path. `stopRemote` also stops the remote web (keep-alive
269
- * `stop`), `keepSshForIdle` leaves the transport up for a fast resume, and
270
- * `keepRemote` preserves the remote facts so the card still describes what is
271
- * running on the other side.
272
- */
273
- /**
274
- * Wait for an in-flight tunnel rebuild (if any) after the caller cancelled link work.
275
- * The rebuild closes its own replacement in `finally` when its token is gone, so awaiting
276
- * here is what makes disconnect / removeHost / shutdown leak-free. Bounded: a stuck rebuild
277
- * must not delay teardown forever; its token is already cancelled, so it cannot publish.
278
- * @param ctx - service context.
279
- * @param runtime - host runtime.
280
- */
281
202
  async function settleTunnelRepair(ctx, runtime) {
282
203
  const repair = runtime.tunnelRepair;
283
204
  if (!repair)
@@ -292,8 +213,6 @@ async function settleTunnelRepair(ctx, runtime) {
292
213
  const outcome = await Promise.race([repair, timeout]);
293
214
  if (outcome === 'timeout') {
294
215
  ctx.progress.log(runtime, 'warn', 'tunnel rebuild did not finish in time; abandoning it');
295
- // The rebuild was cancelled via cancelLinkWork; its own finally will close any listener
296
- // it creates. Clear the slot so teardown never waits on it again.
297
216
  runtime.tunnelRepair = null;
298
217
  }
299
218
  }
@@ -307,18 +226,14 @@ async function settleTunnelRepair(ctx, runtime) {
307
226
  }
308
227
  export async function teardownRuntime(ctx, runtime, options = {}) {
309
228
  cancelConflict(runtime);
310
- // A prompt parked on the transport that is about to go away can never be answered: settle
311
- // it now instead of letting the connect promise wait for its 120s timeout (M1).
312
229
  cancelHostKeyPrompt(runtime);
313
230
  cancelLinkWork(runtime);
314
231
  stopRemoteHeartbeat(runtime);
315
232
  runtime.closing = true;
316
233
  cancelIdleStop(runtime);
317
- // A tunnel rebuild owns a listener it may be creating right now. Cancel it (above), then
318
- // wait for it to clean up: otherwise the listener would be assigned after this teardown.
319
234
  await settleTunnelRepair(ctx, runtime);
320
- // Remember where the remote lives before the facts below are cleared: the idle policy and
321
- // a later stop still need the real home, never a literal `~` (H1).
235
+ // Remember where the remote lives before the facts below are cleared: the idle policy and a later
236
+ // stop still need the real home, never a literal `~`.
322
237
  if (typeof runtime.facts?.home === 'string' && runtime.facts.home.trim() !== '') {
323
238
  runtime.remoteHome = runtime.facts.home;
324
239
  }
@@ -334,8 +249,6 @@ export async function teardownRuntime(ctx, runtime, options = {}) {
334
249
  const result = await ctx.deps.stopWeb(runtime.ssh, layoutForRuntime(runtime), {
335
250
  pid: runtime.remote.pid ?? undefined,
336
251
  });
337
- // Only a confirmed stop means the pid is gone; a refusal keeps the memory so a later
338
- // stop can try again instead of reporting a process that never stopped.
339
252
  remoteStopped = result?.ok === true;
340
253
  }
341
254
  catch (error) {
@@ -354,20 +267,6 @@ export async function teardownRuntime(ctx, runtime, options = {}) {
354
267
  runtime.exchange = null;
355
268
  }
356
269
  }
357
- /**
358
- * Tear one host down and leave it idle: the keep-alive policy decides whether the
359
- * remote web is stopped and whether the transport survives for a fast resume.
360
- * `stopped` says the caller already stopped the remote web itself (the explicit
361
- * "stop remote DSH" action): the policy must then neither arm an idle stop nor send
362
- * a second stop signal. That second signal would be based on a pid captured several
363
- * SSH round-trips earlier - a pid the action just proved is the right one (or that
364
- * it is already gone), so re-signalling it is at best redundant and at worst kills
365
- * an unrelated process after a pid reuse.
366
- *
367
- * The state write, the timer disarms, the prompt settlement, the teardown and the idle timer are
368
- * one transition (`disconnect.requested`); this function only keeps the log line and the event
369
- * arguments the API passes.
370
- */
371
270
  export async function disconnectHost(ctx, runtime, options = {}) {
372
271
  ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`);
373
272
  const event = {
@@ -376,19 +275,9 @@ export async function disconnectHost(ctx, runtime, options = {}) {
376
275
  ...(options.stopped === true ? { stopped: true } : {}),
377
276
  };
378
277
  await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
379
- // The explicit stop action may have kept the transport for its own teardown; the disconnect
380
- // still releases the token (the teardown path already dropped it, this is the idempotent half).
381
278
  runtime.token = null;
382
279
  return { ok: true };
383
280
  }
384
- /**
385
- * Release one runtime during shutdown. This is today's shutdown branch: the `stop` policy stops
386
- * the managed remote web through the idle-policy proof, every other policy just drops the
387
- * listener and the transport (the remote keeps running, and the runtime keeps its facts).
388
- * @param ctx - service context.
389
- * @param runtime - host runtime being released.
390
- * @param stopRemote - whether the keep-alive policy says "stop".
391
- */
392
281
  export async function releaseRuntimeForShutdown(ctx, runtime, stopRemote) {
393
282
  await settleTunnelRepair(ctx, runtime);
394
283
  try {
@@ -403,43 +292,22 @@ export async function releaseRuntimeForShutdown(ctx, runtime, stopRemote) {
403
292
  // swallow-ok: shutdown is best effort; every resource is released above
404
293
  }
405
294
  }
406
- /**
407
- * Stop every host's timers and release its transport. The `stop` keep-alive
408
- * policy also stops the remote web so nothing is left running unowned.
409
- */
410
295
  export async function shutdownAll(ctx) {
411
296
  for (const runtime of ctx.state.runtimes.values()) {
412
- // One transition per runtime: it marks the link dead before the first await (a dependent
413
- // action must not start, or retry, while shutdown is still walking the list) and then
414
- // releases the transport through the same shutdown branch as before.
415
297
  const event = { type: 'shutdown' };
416
298
  await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'silent' });
417
299
  }
418
300
  }
419
- /**
420
- * The effects of this module, bound to one context.
421
- *
422
- * `host-lifecycle` owns the timers and the teardown path, so it builds the effect object itself
423
- * instead of importing `runtime/effects.ts` (which imports this module). `run` is never reached
424
- * from here; it is declared because the interface requires it.
425
- * @param ctx - the watchdog/teardown context.
426
- * @returns the effect owner for one dispatch call.
427
- */
301
+ /** The effects of this module bound to one context: it owns the timers and the teardown path, so it builds the effect
302
+ * object instead of importing `effects.ts` (which imports it); `run`/`flushLogs` are unreachable but required. */
428
303
  function effectsOf(ctx) {
429
304
  return {
430
305
  emit: () => ctx.emitState(),
431
306
  log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
432
307
  logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
433
308
  arm: (runtime, timer) => {
434
- if (timer === 'idle') {
309
+ if (timer === 'idle')
435
310
  scheduleIdleStop(ctx, runtime);
436
- return;
437
- }
438
- // No rule reachable from this module arms the heartbeat: the events that do
439
- // (`connect.succeeded`, `restart.resumed`, `stop.refused`) are dispatched by `connect/*`,
440
- // whose effect owner is `runtime/effects.ts`. Importing `watchdog.ts` from here would close
441
- // the `host-lifecycle -> connect` edge the design forbids, so the branch stays a no-op —
442
- // declared because the interface requires it, like `run`/`flushLogs` below.
443
311
  },
444
312
  disarm: (runtime, timer) => {
445
313
  if (timer === 'reconnect')
@@ -463,8 +331,8 @@ function effectsOf(ctx) {
463
331
  }
464
332
  await teardownRuntime(ctx, runtime, {
465
333
  stopRemote: options.stopRemote === true,
466
- ...(options.keepRemote === true ? { keepRemote: true } : {}),
467
- ...(options.keepSshForIdle === true ? { keepSshForIdle: true } : {}),
334
+ keepRemote: options.keepRemote === true,
335
+ keepSshForIdle: options.keepSshForIdle === true,
468
336
  });
469
337
  },
470
338
  apply: (runtime, patch) => {
@@ -478,8 +346,6 @@ function effectsOf(ctx) {
478
346
  return;
479
347
  }
480
348
  if (patch.kind === 'mark-attached') {
481
- // Kept in step with `runtime/effects.ts#markAttached` (the two effect owners cannot share
482
- // a module without an import cycle). `connect.succeeded` is the only producer.
483
349
  runtime.remote.uiReady = true;
484
350
  runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
485
351
  runtime.tunnelRepairFailures = 0;
@@ -497,8 +363,6 @@ function effectsOf(ctx) {
497
363
  runtime.remote.uiReady = patch.uiReady === true;
498
364
  runtime.remote.localPort = patch.localPort;
499
365
  },
500
- flushLogs: () => {
501
- // The coalescing flush belongs to `connect-progress`; no rule reached from this module emits it.
502
- },
366
+ flushLogs: () => { },
503
367
  };
504
368
  }
@@ -1,6 +1,5 @@
1
- /**
2
- * The host registry: the configured hosts, their runtime objects and the client-facing snapshot; reads are pure, writes re-emit the snapshot after `store`.
3
- */
1
+ /** The host registry: configured hosts, their runtime objects and the client-facing snapshot; reads are pure, writes
2
+ * re-emit the snapshot after `store`. */
4
3
  import { homedir } from 'node:os';
5
4
  import path from 'node:path';
6
5
  import { errors } from './errors.js';
@@ -19,8 +18,8 @@ function ensureRuntime(ctx, host) {
19
18
  existing.entry = host;
20
19
  return existing;
21
20
  }
22
- // The store issues the id (`sanitizeHostEntry`) and the runtime map is keyed by it; an entry
23
- // without one can only come from a caller that never saved it, never from `listHosts`.
21
+ // The store issues the id and the map is keyed by it; an entry without one can only come from a
22
+ // caller that never saved it, never from `listHosts`.
24
23
  const runtime = createHostRuntime(host);
25
24
  ctx.state.runtimes.set(host.id, runtime);
26
25
  return runtime;
@@ -37,41 +36,26 @@ export async function initRegistry(ctx) {
37
36
  await ctx.store.load();
38
37
  for (const host of ctx.store.listHosts())
39
38
  ensureRuntime(ctx, host);
40
- // `passwordSaved` is a fact about the credential store, not about this process: without this
41
- // read the Client would ask again after every DSH restart even though the password is saved,
42
- // and the saved value would never be tried.
43
- await restoreSavedPasswords(ctx);
39
+ // `passwordSaved` is a fact about the credential store, not this process: without this read the
40
+ // Client would ask again after every DSH restart even though the password is saved.
41
+ if (ctx.secrets) {
42
+ await Promise.all([...ctx.state.runtimes.values()].map(async (runtime) => {
43
+ if (runtime.entry.auth?.type !== 'password') {
44
+ runtime.passwordSaved = false;
45
+ return;
46
+ }
47
+ runtime.passwordSaved = await ctx.secrets.has(runtime.id);
48
+ }));
49
+ }
44
50
  ctx.state.initialized = true;
45
51
  }
46
- /**
47
- * Re-read which password-auth hosts have a saved password. Only presence is loaded; the secret
48
- * itself stays in the credential store until a connection actually needs it.
49
- * @param ctx - service context.
50
- */
51
- async function restoreSavedPasswords(ctx) {
52
- if (!ctx.secrets)
53
- return;
54
- await Promise.all([...ctx.state.runtimes.values()].map(async (runtime) => {
55
- if (runtime.entry.auth?.type !== 'password') {
56
- runtime.passwordSaved = false;
57
- return;
58
- }
59
- runtime.passwordSaved = await ctx.secrets.has(runtime.id);
60
- }));
61
- }
62
52
  function hostViewFor(ctx, runtime, options = {}) {
63
53
  return hostView(runtime, {
64
54
  targetVersion: ctx.localVersion(),
65
55
  passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
66
- // A quarantined hosts.json means the list beside it is the empty recovery fallback.
67
56
  storeCorrupt: ctx.store?.hostsCorrupt === true,
68
57
  }, options);
69
58
  }
70
- /**
71
- * Build the client-facing state snapshot (contract: docs/api.md).
72
- * @param ctx - the service context.
73
- * @param options - `logs: false` strips every tail (the SSE state frame's shape).
74
- */
75
59
  export function snapshot(ctx, options = {}) {
76
60
  const localVersion = ctx.localVersion();
77
61
  const hosts = [...ctx.state.runtimes.values()].map((runtime) => hostViewFor(ctx, runtime, options));
@@ -82,17 +66,12 @@ export function snapshot(ctx, options = {}) {
82
66
  settings: ctx.store.getSettings(),
83
67
  activeHostId: ctx.state.activeHostId,
84
68
  firstRun: hosts.length === 0,
85
- /** Whether a password typed for any host can be persisted at all (the Client hides the choice). */
86
69
  passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
87
- // Store-wide, and deliberately not per host: a quarantined hosts.json leaves this list
88
- // empty, which is exactly the case the user has to be told about.
89
70
  storeCorrupt: ctx.store?.hostsCorrupt === true,
90
71
  };
91
72
  }
92
73
  export async function saveHost(ctx, rawHost) {
93
74
  await ctx.init();
94
- // The auth mode as it is stored now: a switch away from password must not leave its secret
95
- // behind as an orphaned credential record.
96
75
  const previousAuth = rawHost && typeof rawHost === 'object' && typeof rawHost.id === 'string'
97
76
  ? (ctx.store.getHost(rawHost.id)?.auth?.type ?? null)
98
77
  : null;
@@ -101,8 +80,6 @@ export async function saveHost(ctx, rawHost) {
101
80
  entry = await ctx.store.upsertHost(rawHost, { settings: ctx.store.getSettings() });
102
81
  }
103
82
  catch (error) {
104
- // The store's validators throw bare messages; map them to the client's field
105
- // errors here so the contract stays typed.
106
83
  const message = error instanceof Error ? error.message : String(error);
107
84
  if (message === 'address is required') {
108
85
  throw errors.invalidInput('address', {
@@ -113,10 +90,7 @@ export async function saveHost(ctx, rawHost) {
113
90
  if (message === 'address is invalid') {
114
91
  throw errors.invalidInput('address', { zh: '服务器地址格式不正确。', en: 'The server address is not valid.' });
115
92
  }
116
- throw errors.invalidInput('host', {
117
- zh: `主机配置不合法:${message}`,
118
- en: `Invalid host entry: ${message}`,
119
- });
93
+ throw errors.invalidInput('host', { zh: `主机配置不合法:${message}`, en: `Invalid host entry: ${message}` });
120
94
  }
121
95
  const runtime = ensureRuntime(ctx, entry);
122
96
  if (previousAuth === 'password' && entry.auth?.type !== 'password') {
@@ -127,24 +101,18 @@ export async function saveHost(ctx, rawHost) {
127
101
  ctx.emitState();
128
102
  return hostViewFor(ctx, runtime);
129
103
  }
130
- /**
131
- * Delete one host. It is the whole context, not a slice: the teardown it runs needs the watchdog's
132
- * five slices (`createRuntimeEffects`/`scopeFactsFor`) and the deletion itself needs `Store`, so
133
- * `Store & TeardownCtx` was the full six written the long way. The gate registers this function
134
- * (`godCtxParams` in the architecture budget) rather than pretending it is narrow.
135
- */
104
+ /** Delete one host. The teardown needs the watchdog's five slices and the deletion needs `Store`, so the gate registers
105
+ * this function in `godCtxParams` rather than pretending it is narrow. */
136
106
  export async function removeHost(ctx, id) {
137
107
  await ctx.init();
138
108
  const runtime = ctx.state.runtimes.get(id);
139
109
  if (runtime) {
140
- // A deleted host must not be resurrected by a timer scheduled before deletion, and a
141
- // connect pipeline still in flight must see that the user no longer wants it: it may
142
- // never publish a connected state or a fresh `activeHostId` afterwards (H4).
110
+ // A deleted host must not be resurrected by a timer, and a connect pipeline still in flight must
111
+ // see that the user no longer wants it: it may never publish a connected state afterwards.
143
112
  if (ctx.state.activeHostId === id)
144
113
  ctx.state.activeHostId = null;
145
- // `host.removed` owns the desired flag, the token bump, the timer disarms, the prompt
146
- // settlement and the teardown; the frame is published below with the host already gone, so
147
- // this call must not emit on its own.
114
+ // `host.removed` owns the desired flag, the token bump, the timer disarms, the prompt settlement
115
+ // and the teardown; the frame is published below with the host already gone.
148
116
  const event = { type: 'host.removed', keepAlive: runtime.entry.keepAlive };
149
117
  await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
150
118
  caller: 'silent',
@@ -153,7 +121,6 @@ export async function removeHost(ctx, id) {
153
121
  }
154
122
  ctx.state.runtimes.delete(id);
155
123
  await ctx.store.removeHost(id);
156
- // The host is gone: its saved password must not outlive it in the credential store.
157
124
  await ctx.secrets?.remove(id);
158
125
  if (ctx.state.activeHostId === id)
159
126
  ctx.state.activeHostId = null;
@@ -166,15 +133,9 @@ export function setActiveHost(ctx, id) {
166
133
  ctx.state.activeHostId = id;
167
134
  ctx.emitState();
168
135
  }
169
- /**
170
- * Persist settings and restart the heartbeat of every connected host. Saving needs `Store`; the
171
- * heartbeat policy needs the watchdog's slice set, so the two together are the whole context (the
172
- * gate's `godCtxParams` entry names it).
173
- */
174
136
  export async function saveSettings(ctx, patch) {
175
137
  await ctx.init();
176
138
  const settings = await ctx.store.saveSettings(patch);
177
- // The liveness switch applies to hosts that are already connected, not just the next one.
178
139
  for (const runtime of ctx.state.runtimes.values()) {
179
140
  if (runtime.status !== 'connected')
180
141
  continue;
@@ -186,22 +147,17 @@ export async function saveSettings(ctx, patch) {
186
147
  ctx.emitState();
187
148
  return settings;
188
149
  }
189
- /**
190
- * Browse directories inside the user's home so the client can pick a private-key
191
- * file instead of typing an absolute path. Read-only and home-confined.
192
- */
193
150
  export async function listKeyFiles(ctx, dir) {
194
- // The picker is rooted at the OS user home, not DSH_HOME: private keys live in
195
- // `~/.ssh` of the account, while the service's `home` is the DSH state root.
151
+ // The picker is rooted at the OS user home, not DSH_HOME: private keys live in `~/.ssh` of the
152
+ // account, while the service's `home` is the DSH state root.
196
153
  const userHome = homedir();
197
154
  let listing;
198
155
  try {
199
156
  listing = await listKeyFilesInHome({ home: userHome, dir: typeof dir === 'string' ? dir : '' });
200
157
  }
201
158
  catch (error) {
202
- // A path outside the home directory (`C:\Windows`, `..`, a symlink escape) or an
203
- // unreadable one is the caller's mistake: answer 400 instead of turning a bare `Error`
204
- // into a 500, and never echo the requested path back in `technical`.
159
+ // A path outside the home directory (or an unreadable one) is the caller's mistake: answer 400
160
+ // instead of turning a bare `Error` into a 500, and never echo the path back in `technical`.
205
161
  if (error?.code === OUTSIDE_HOME || ['ENOENT', 'EACCES', 'EPERM', 'ENOTDIR'].includes(error?.code)) {
206
162
  throw errors.invalidInput('path', {
207
163
  zh: '这个目录不在用户主目录内,或无法读取。',
@@ -213,20 +169,13 @@ export async function listKeyFiles(ctx, dir) {
213
169
  const settings = ctx.store.getSettings();
214
170
  return { ...listing, defaultKeyPath: settings.defaultKeyPath, defaultDir: path.join(userHome, '.ssh') };
215
171
  }
216
- /** Read-only SSH discovery for the wizard (design §15.1). */
217
172
  export async function discoverSshAliases(ctx) {
218
173
  const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() });
219
174
  const parsed = parseSshConfig(material.configText);
220
175
  const aliases = discoverAliasesFromConfig(parsed, { home: ctx.userHome() });
221
176
  const knownHosts = parseKnownHosts(material.knownHostsText);
222
177
  return {
223
- aliases: aliases.map((alias) => ({
224
- alias: alias.alias,
225
- host: alias.host,
226
- user: alias.user,
227
- port: alias.port,
228
- source: 'config',
229
- })),
178
+ aliases: aliases.map(({ alias, host, user, port }) => ({ alias, host, user, port, source: 'config' })),
230
179
  knownHosts: summarizeKnownHosts(knownHosts),
231
180
  };
232
181
  }
@@ -1,4 +1,3 @@
1
- /** An empty `RemoteRuntime`; the teardown path resets to it while keeping the version. */
2
1
  export function emptyRemote() {
3
2
  return {
4
3
  version: null,
@@ -15,14 +14,6 @@ export function emptyRemote() {
15
14
  viewRev: 0,
16
15
  };
17
16
  }
18
- /**
19
- * Build the mutable state for one host. The entry always carries the id the store issued.
20
- *
21
- * The return annotation types the literal field by field, so an empty container needs no `as`
22
- * (contextual typing supplies its element type) and a missing or extra field is a compile error.
23
- * @param host - the stored host, already carrying its id.
24
- * @returns a fresh runtime in the `unconfigured` state.
25
- */
26
17
  export function createHostRuntime(host) {
27
18
  return {
28
19
  id: host.id,