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,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,97 @@ 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
- }
97
- const maxAttempts = settings.autoReconnect.maxAttempts;
98
- 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
- };
68
+ if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled)
69
+ return skip();
70
+ // `maxAttempts` bounds the fast, exponential phase; the patience window then adds slow attempts on top, so a
71
+ // multi-minute outage (reboot, VPN re-dial, carrier handoff) still recovers instead of parking at an error card.
72
+ // `maxAttempts: 0` and a spent patience window both stay "no retry", exactly as before.
73
+ const fastAttempts = Math.max(0, Number(settings.autoReconnect.maxAttempts) || 0);
74
+ const slowDelayMs = Math.max(0, Number(ctx.timers.reconnectSlowDelayMs) || 0);
75
+ const patienceMs = Math.max(0, Number(ctx.timers.reconnectPatienceMs) || 0);
76
+ const slowAttempts = fastAttempts > 0 && slowDelayMs > 0 ? Math.floor(patienceMs / slowDelayMs) : 0;
77
+ const totalAttempts = fastAttempts + slowAttempts;
78
+ if (totalAttempts <= 0 || runtime.reconnectAttempts >= totalAttempts) {
79
+ if (slowAttempts > 0) {
80
+ ctx.progress.log(runtime, 'warn', `auto reconnect gave up after ${totalAttempts} attempts (${fastAttempts} fast + ${slowAttempts} slow, about ${Math.round(patienceMs / 60_000)} min)`);
81
+ }
82
+ const view = toErrorView(errors.network({
83
+ zh: `连接已断开,自动重连 ${totalAttempts} 次均失败。远端任务可能仍在运行。`,
84
+ en: `The connection dropped and ${totalAttempts} automatic retries failed. Remote tasks may still be running.`,
85
+ }));
86
+ const event = { type: 'reconnect.gaveup', maxAttempts: totalAttempts, view };
107
87
  void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' });
108
88
  return;
109
89
  }
110
90
  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 }), {
91
+ const slow = attempt > fastAttempts;
92
+ const baseDelayMs = settings.autoReconnect.baseDelayMs;
93
+ const delay = slow
94
+ ? randomDelay(slowDelayMs * 0.85, slowDelayMs * 1.15)
95
+ : randomDelay(baseDelayMs, baseDelayMs * 2 ** Math.min(attempt, 4));
96
+ const seconds = Math.round(delay / 100) / 10;
97
+ if (slow) {
98
+ // The slow phase is long by design: one line when it starts and every fifth attempt after it, the rest at debug.
99
+ const slowIndex = attempt - fastAttempts;
100
+ const level = slowIndex === 1 || slowIndex % 5 === 0 ? 'info' : 'debug';
101
+ ctx.progress.log(runtime, level, `still offline; retrying in ${seconds}s (slow retry ${slowIndex}/${slowAttempts})`);
102
+ }
103
+ else {
104
+ ctx.progress.log(runtime, 'warn', `link lost; retrying in ${seconds}s (attempt ${attempt}/${fastAttempts})`);
105
+ }
106
+ // `max` stays the fast budget the setting names; a slow retry reports its own count on the card instead.
107
+ const scheduled = {
108
+ type: 'reconnect.scheduled',
109
+ attempt,
110
+ max: fastAttempts,
111
+ delayMs: delay,
112
+ ...(slow ? { slow: true } : {}),
113
+ };
114
+ void dispatch(effectsOf(ctx), runtime, scheduled, scopeFactsFor(ctx, runtime, scheduled), {
114
115
  caller: 'timer',
115
116
  armReconnect: (ms) => {
116
117
  runtime.reconnectTimer = setTimeout(() => {
117
118
  runtime.reconnectTimer = null;
118
119
  onDue();
119
120
  }, ms);
120
- // A pending retry must never keep the host process alive on its own.
121
121
  runtime.reconnectTimer.unref?.();
122
122
  },
123
123
  });
124
124
  }
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
125
  export function scheduleIdleStop(ctx, runtime) {
131
126
  cancelIdleStop(runtime);
132
127
  const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES);
133
128
  runtime.idleTimer = setTimeout(() => {
134
129
  runtime.idleTimer = null;
135
130
  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
- });
131
+ void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' }).then((result) => (result.ok ? stopRemoteForIdle(ctx, runtime) : undefined));
142
132
  }, minutes * 60_000);
143
133
  runtime.idleTimer.unref?.();
144
134
  }
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
135
  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.
136
+ // The timer is a policy for an idle host, never authority over a live link: a manual reconnect
137
+ // must not be torn down by the timer armed before it.
165
138
  const linkLive = runtime.desired === 'connected' || runtime.status === 'connected' || runtime.tunnel !== null;
166
139
  if (linkLive && options.shutdown !== true) {
167
140
  ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
168
141
  return { ok: false, reason: 'still-wanted' };
169
142
  }
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
143
  const capturedSsh = runtime.ssh;
144
+ // The identity proof below awaits and the user may connect in that window: only this session may
145
+ // be released afterwards, never the new one.
173
146
  const stillWanted = () => runtime.ssh !== capturedSsh ||
174
147
  runtime.desired === 'connected' ||
175
148
  runtime.status === 'connected' ||
@@ -184,13 +157,8 @@ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
184
157
  }
185
158
  const layout = layoutForRuntime(runtime);
186
159
  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
160
  if (!isPid(pid))
190
161
  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
162
  const proof = await proveOwnership(ctx, runtime, {
195
163
  ...OWNERSHIP_OPTIONS.idle,
196
164
  pid,
@@ -201,28 +169,25 @@ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
201
169
  ctx.progress.log(runtime, 'warn', `idle stop skipped: ${proof.reason}`);
202
170
  return { ok: false, reason: proof.reason };
203
171
  }
204
- // The user may have connected while the identity was read: the link wins again.
205
172
  if (options.shutdown !== true && stillWanted()) {
206
173
  ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
207
174
  return { ok: false, reason: 'still-wanted' };
208
175
  }
209
176
  const stopped = await ctx.deps.stopWeb(capturedSsh, layout, { pid });
210
177
  if (stopped?.ok !== true) {
211
- ctx.progress.log(runtime, 'warn', `idle stop did not confirm (${stopped?.reason ?? 'unknown'}); the remote may still be running`);
178
+ const why = stopped?.reason ?? 'unknown';
179
+ ctx.progress.log(runtime, 'warn', `idle stop did not confirm (${why}); the remote may still be running`);
212
180
  return { ok: false, reason: stopped?.reason ?? 'not-confirmed' };
213
181
  }
214
182
  runtime.remotePid = null;
215
183
  return { ok: true };
216
184
  }
217
185
  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
186
+ // swallow-ok: the idle stop is best effort; its failure is only a warning and the timer is gone
220
187
  ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error));
221
188
  return { ok: false, reason: 'error' };
222
189
  }
223
190
  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
191
  if (runtime.ssh === capturedSsh)
227
192
  await disposeSsh(runtime);
228
193
  }
@@ -230,8 +195,6 @@ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
230
195
  export async function closeTunnel(runtime) {
231
196
  const tunnel = runtime.tunnel;
232
197
  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
198
  runtime.remote.localPort = null;
236
199
  if (tunnel) {
237
200
  try {
@@ -264,20 +227,6 @@ export async function disposeSsh(runtime) {
264
227
  }
265
228
  }
266
229
  }
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
230
  async function settleTunnelRepair(ctx, runtime) {
282
231
  const repair = runtime.tunnelRepair;
283
232
  if (!repair)
@@ -292,8 +241,6 @@ async function settleTunnelRepair(ctx, runtime) {
292
241
  const outcome = await Promise.race([repair, timeout]);
293
242
  if (outcome === 'timeout') {
294
243
  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
244
  runtime.tunnelRepair = null;
298
245
  }
299
246
  }
@@ -307,18 +254,14 @@ async function settleTunnelRepair(ctx, runtime) {
307
254
  }
308
255
  export async function teardownRuntime(ctx, runtime, options = {}) {
309
256
  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
257
  cancelHostKeyPrompt(runtime);
313
258
  cancelLinkWork(runtime);
314
259
  stopRemoteHeartbeat(runtime);
315
260
  runtime.closing = true;
316
261
  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
262
  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).
263
+ // Remember where the remote lives before the facts below are cleared: the idle policy and a later
264
+ // stop still need the real home, never a literal `~`.
322
265
  if (typeof runtime.facts?.home === 'string' && runtime.facts.home.trim() !== '') {
323
266
  runtime.remoteHome = runtime.facts.home;
324
267
  }
@@ -334,8 +277,6 @@ export async function teardownRuntime(ctx, runtime, options = {}) {
334
277
  const result = await ctx.deps.stopWeb(runtime.ssh, layoutForRuntime(runtime), {
335
278
  pid: runtime.remote.pid ?? undefined,
336
279
  });
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
280
  remoteStopped = result?.ok === true;
340
281
  }
341
282
  catch (error) {
@@ -354,20 +295,6 @@ export async function teardownRuntime(ctx, runtime, options = {}) {
354
295
  runtime.exchange = null;
355
296
  }
356
297
  }
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
298
  export async function disconnectHost(ctx, runtime, options = {}) {
372
299
  ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`);
373
300
  const event = {
@@ -376,19 +303,9 @@ export async function disconnectHost(ctx, runtime, options = {}) {
376
303
  ...(options.stopped === true ? { stopped: true } : {}),
377
304
  };
378
305
  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
306
  runtime.token = null;
382
307
  return { ok: true };
383
308
  }
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
309
  export async function releaseRuntimeForShutdown(ctx, runtime, stopRemote) {
393
310
  await settleTunnelRepair(ctx, runtime);
394
311
  try {
@@ -403,43 +320,22 @@ export async function releaseRuntimeForShutdown(ctx, runtime, stopRemote) {
403
320
  // swallow-ok: shutdown is best effort; every resource is released above
404
321
  }
405
322
  }
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
323
  export async function shutdownAll(ctx) {
411
324
  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
325
  const event = { type: 'shutdown' };
416
326
  await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'silent' });
417
327
  }
418
328
  }
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
- */
329
+ /** The effects of this module bound to one context: it owns the timers and the teardown path, so it builds the effect
330
+ * object instead of importing `effects.ts` (which imports it); `run`/`flushLogs` are unreachable but required. */
428
331
  function effectsOf(ctx) {
429
332
  return {
430
333
  emit: () => ctx.emitState(),
431
334
  log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
432
335
  logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
433
336
  arm: (runtime, timer) => {
434
- if (timer === 'idle') {
337
+ if (timer === 'idle')
435
338
  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
339
  },
444
340
  disarm: (runtime, timer) => {
445
341
  if (timer === 'reconnect')
@@ -463,8 +359,8 @@ function effectsOf(ctx) {
463
359
  }
464
360
  await teardownRuntime(ctx, runtime, {
465
361
  stopRemote: options.stopRemote === true,
466
- ...(options.keepRemote === true ? { keepRemote: true } : {}),
467
- ...(options.keepSshForIdle === true ? { keepSshForIdle: true } : {}),
362
+ keepRemote: options.keepRemote === true,
363
+ keepSshForIdle: options.keepSshForIdle === true,
468
364
  });
469
365
  },
470
366
  apply: (runtime, patch) => {
@@ -478,8 +374,6 @@ function effectsOf(ctx) {
478
374
  return;
479
375
  }
480
376
  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
377
  runtime.remote.uiReady = true;
484
378
  runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
485
379
  runtime.tunnelRepairFailures = 0;
@@ -497,8 +391,6 @@ function effectsOf(ctx) {
497
391
  runtime.remote.uiReady = patch.uiReady === true;
498
392
  runtime.remote.localPort = patch.localPort;
499
393
  },
500
- flushLogs: () => {
501
- // The coalescing flush belongs to `connect-progress`; no rule reached from this module emits it.
502
- },
394
+ flushLogs: () => { },
503
395
  };
504
396
  }
@@ -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
  }