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,32 +1,9 @@
1
- /**
2
- * The listener rebuild for a host whose remote UI answers the SSH probe but whose proxied
3
- * requests fail (B8): the tunnel, not the remote, is what broke.
4
- */
1
+ /** The listener rebuild for a host whose remote UI answers the SSH probe but whose proxied requests fail: the tunnel, not the remote, is what broke. Single-flight per host and owned by a link-work token; the replacement is created before the old listener closes (no window without a listener) and its new random local port bumps `viewRev` so the carrier refetches. It reads five slices and never the persistence layer, so it takes `WatchdogCtx` rather than `ConnectCtx`. */
5
2
  import { REMOTE_REPAIR_BACKOFF_MAX_MS, REMOTE_REPAIR_BACKOFF_MS } from '../constants.js';
6
3
  import { errors } from '../errors.js';
7
4
  import { beginLinkWork, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
8
5
  import { isPid, messageOf } from '../util.js';
9
6
  import { noteRemoteUnreachable } from '../watchdog.js';
10
- /**
11
- * Rebuild the local listener for a host whose remote UI answers the SSH probe but whose
12
- * proxied requests fail: the tunnel, not the remote, is what broke. Single-flight per host and
13
- * owned by a link-work token, like restart/reattach: a disconnect, host removal or shutdown
14
- * cancels it and the caller waits for `runtime.tunnelRepair` before tearing down.
15
- *
16
- * The replacement is created before the old listener closes, so there is no window without a
17
- * listener. Its local port is a new random one, so `viewRev` is bumped: the carrier refetches
18
- * `GET /hosts/:id/open` and navigates again (the desktop guest's URL is the loopback origin).
19
- * Existing WebSockets/downloads are dropped by closing the old listener - documented.
20
- *
21
- * It reads five slices and never the persistence layer (`ctx.init`/`ctx.store`/`ctx.secrets`):
22
- * the rebuild publishes through `ctx.emitState()` and logs through `ctx.progress`, so the type is
23
- * `WatchdogCtx`, not the six-slice `ConnectCtx` the other five orchestration entries take. The
24
- * architecture gate measures this, which is why this function is not in its `godCtxParams` list.
25
- *
26
- * @param ctx - the watchdog's five slices (state, config, transport, remote deps, reporter).
27
- * @param runtime - connected host runtime.
28
- * @returns whether the listener was rebuilt.
29
- */
30
7
  export async function repairTunnel(ctx, runtime) {
31
8
  if (ctx.state.disposed === true ||
32
9
  runtime.desired !== 'connected' ||
@@ -39,9 +16,8 @@ export async function repairTunnel(ctx, runtime) {
39
16
  return { ok: false, reason: 'no-transport' };
40
17
  if (runtime.tunnelRepair)
41
18
  return runtime.tunnelRepair;
42
- if (Date.now() < (Number(runtime.nextTunnelRepairAt) || 0)) {
19
+ if (Date.now() < (Number(runtime.nextTunnelRepairAt) || 0))
43
20
  return { ok: false, reason: 'backoff' };
44
- }
45
21
  const port = runtime.remote.port;
46
22
  const previous = runtime.tunnel;
47
23
  const token = beginLinkWork(runtime, 'repair');
@@ -51,9 +27,7 @@ export async function repairTunnel(ctx, runtime) {
51
27
  runtime.status === 'connected' &&
52
28
  runtime.ssh?.connected === true;
53
29
  let created = null;
54
- let work = null;
55
- let settled = null;
56
- work = (async () => {
30
+ const settled = (async () => {
57
31
  try {
58
32
  if (runtime.ssh?.connected !== true)
59
33
  throw errors.internal(new Error('the SSH transport is gone'));
@@ -71,7 +45,6 @@ export async function repairTunnel(ctx, runtime) {
71
45
  }
72
46
  if (!stillCurrent())
73
47
  return { ok: false, reason: 'cancelled' };
74
- // Publish the replacement before closing the old listener: no no-listener window.
75
48
  runtime.tunnel = next;
76
49
  runtime.remote.localPort = nextPort;
77
50
  try {
@@ -82,7 +55,6 @@ export async function repairTunnel(ctx, runtime) {
82
55
  }
83
56
  if (!stillCurrent())
84
57
  return { ok: false, reason: 'cancelled' };
85
- // The local port changed, so the carrier's view of the host did too.
86
58
  runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
87
59
  ctx.progress.log(runtime, 'info', `tunnel rebuilt after a failed request (remote port ${port}, local port ${previous.localPort} -> ${nextPort})`);
88
60
  runtime.tunnelRepairFailures = 0;
@@ -91,8 +63,8 @@ export async function repairTunnel(ctx, runtime) {
91
63
  return { ok: true };
92
64
  }
93
65
  catch (error) {
94
- // swallow-ok: a failed rebuild is a typed, retryable reason (with backoff) for the caller;
95
- // the old listener is still serving, so this is not a connection failure.
66
+ // swallow-ok: a failed rebuild is a typed, retryable reason (with backoff) for the caller; the
67
+ // old listener is still serving, so this is not a connection failure.
96
68
  runtime.tunnelRepairFailures = (Number(runtime.tunnelRepairFailures) || 0) + 1;
97
69
  const backoff = Math.min(REMOTE_REPAIR_BACKOFF_MAX_MS, REMOTE_REPAIR_BACKOFF_MS * 2 ** (runtime.tunnelRepairFailures - 1));
98
70
  runtime.nextTunnelRepairAt = Date.now() + backoff;
@@ -100,8 +72,8 @@ export async function repairTunnel(ctx, runtime) {
100
72
  return { ok: false, reason: 'rebuild-failed' };
101
73
  }
102
74
  finally {
103
- // A listener this rebuild created must never outlive it: on a cancelled token (or if it
104
- // was never published) close it here, and clear the view only when it owned the slot.
75
+ // A listener this rebuild created must never outlive it: close it on a cancelled token (or if it
76
+ // was never published), and clear the view only when it owned the slot.
105
77
  if (created !== null && (!isLinkWorkCurrent(runtime, token) || runtime.tunnel !== created)) {
106
78
  if (runtime.tunnel === created) {
107
79
  runtime.tunnel = null;
@@ -116,8 +88,7 @@ export async function repairTunnel(ctx, runtime) {
116
88
  }
117
89
  endLinkWork(runtime, token);
118
90
  }
119
- })();
120
- settled = work.finally(() => {
91
+ })().finally(() => {
121
92
  if (runtime.tunnelRepair === settled)
122
93
  runtime.tunnelRepair = null;
123
94
  });
@@ -1,13 +1,9 @@
1
- /**
2
- * The local restart of the managed remote web on the same SSH transport: stop exactly the instance
3
- * this connection launched, `[start]` again on the same plan, rebuild the tunnel for the new
4
- * random port, verify and resume.
5
- */
1
+ /** The local restart of the managed remote web on the same SSH transport: stop exactly the instance this connection launched, `[start]` again on the same plan, rebuild the tunnel for the new random port, verify and resume. */
6
2
  import { REMOTE_START_TIMEOUT_MS } from '../constants.js';
7
3
  import { errors, toErrorView } from '../errors.js';
8
4
  import { closeTunnel, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
9
5
  import { layoutForRuntime } from '../layout.js';
10
- import { buildRunRegistryRecord } from '../remote-web/registry.js';
6
+ import { buildRunRegistryRecord, registryNamesInstance } from '../remote-web/registry.js';
11
7
  import { commandMatchesProfile } from '../remote-web/resolve.js';
12
8
  import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
13
9
  import { createRuntimeEffects } from '../runtime/effects.js';
@@ -15,51 +11,23 @@ import { isPid, messageOf, nowIso } from '../util.js';
15
11
  import { markConnected, recordRestart, resumeConnected } from './attach.js';
16
12
  import { planForRuntime } from './bootstrap.js';
17
13
  import { SSH_CLOSED_DETAIL } from './failures.js';
18
- import { LinkCancelled } from './guards.js';
19
- import { resolveForeignConflict } from './launch.js';
14
+ import { LinkCancelled, linkActionState } from './guards.js';
15
+ import { PATCHED_CARRIER_NOTE, resolveForeignConflict } from './launch.js';
20
16
  import { OWNERSHIP_OPTIONS, proveOwnership, rememberLaunched } from './ownership.js';
21
17
  import { readRegistryQuietly } from './registry.js';
22
18
  import { openTunnelFor } from './transport.js';
23
19
  import { verifyRemoteUi } from './verify.js';
24
- /**
25
- * Restart the managed remote web on the same SSH transport: stop the pid the run
26
- * registry names, `[start]` again on the same plan, rebuild the tunnel for the new
27
- * random port and verify. `[ssh]` / `[probe]` / `[bootstrap]` are not re-run, so a
28
- * password or host-key prompt can never appear here.
29
- *
30
- * Only the instance this connection launched is stopped; a process the plugin did
31
- * not start goes through the ordinary conflict prompt instead of being killed.
32
- *
33
- * Available while connected, and also from the `remote-unreachable` error state: that
34
- * state deliberately keeps the SSH transport so the user can restart exactly when a
35
- * remote re-attach found nothing to adopt (docs/design.md §5.6).
36
- *
37
- * @param ctx - service context.
38
- * @param runtime - host runtime with a live transport.
39
- * @returns whether the restart started.
40
- */
20
+ /** Restart the managed remote web on the same SSH transport; `[ssh]`/`[probe]`/`[bootstrap]` are not re-run, so no password or host-key prompt can appear here. Also available from the `remote-unreachable` error state, which keeps the SSH transport on purpose. */
41
21
  export async function restartHost(ctx, runtime) {
42
22
  await ctx.init();
43
23
  if (runtime.connectPromise || runtime.linkBusy !== null)
44
24
  return { accepted: false, reason: 'busy' };
45
- const connected = runtime.status === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null;
46
- const recoverable = runtime.status === 'error' &&
47
- runtime.error?.code === 'remote-unreachable' &&
48
- runtime.ssh?.connected === true &&
49
- runtime.facts !== null;
50
- if (!connected && !recoverable) {
25
+ // A live link, or the `remote-unreachable` error state that deliberately keeps the SSH transport.
26
+ if (linkActionState(runtime) === null)
51
27
  throw errors.restartUnavailable();
52
- }
53
- // One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`).
54
- // The token is the old `beginLinkWork` one: the rule adopts it (`epochAfter`) and hands it to the
55
- // script, so the late-write filter keeps the exact semantics it had.
28
+ // One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`), and adopts the token.
56
29
  const token = (Number(runtime.linkToken) || 0) + 1;
57
- const event = {
58
- type: 'restart.requested',
59
- token,
60
- pid: runtime.remote.pid,
61
- port: runtime.remote.port,
62
- };
30
+ const event = { type: 'restart.requested', token, pid: runtime.remote.pid, port: runtime.remote.port };
63
31
  await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
64
32
  caller: 'script',
65
33
  run: (activity, started) => {
@@ -76,41 +44,25 @@ export async function restartHost(ctx, runtime) {
76
44
  });
77
45
  return { accepted: true };
78
46
  }
79
- /**
80
- * The action body: proof of ownership, the conflict prompt, stop/start, the registry rewrite, the
81
- * tunnel and the verify step all read the same six slices as its entry point, so it takes
82
- * `ConnectCtx` rather than a second copy of the intersection (the gate's `godCtxParams` entry
83
- * names it).
84
- */
47
+ /** The action body: proof of ownership, the conflict prompt, stop/start, the registry rewrite, the tunnel and the verify step all read the same six slices as its entry point. */
85
48
  async function runRestart(ctx, runtime, token) {
86
49
  const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
87
50
  const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
88
51
  const layout = layoutForRuntime(runtime);
89
52
  const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile;
90
53
  const previousPort = runtime.remote.port;
91
- // Restarting from the remote-unreachable error state has no tunnel to keep.
92
54
  const hadTunnel = runtime.tunnel !== null;
93
55
  let killable = false;
94
56
  let stoppedOwn = false;
95
57
  let started = false;
96
58
  let tunnelCreated = false;
97
59
  try {
98
- // `restart.requested` already disarmed the heartbeat/reconnect/idle timers and published the
99
- // `start`/`restarting-remote` card.
100
60
  log('info', `restart requested (pid=${runtime.remote.pid ?? 'unknown'}, remote port=${previousPort ?? 'unknown'})`);
101
- // Whether the running pid is ours to stop needs two independent proofs here: the registry
102
- // names it (below) and this connection launched it with the same /proc identity
103
- // (`OWNERSHIP_OPTIONS.restart`). A pid that a re-attach discovered, or one kept alongside, is
104
- // hosted, never killed.
61
+ // Stopping needs two independent proofs: the registry names this connection's pid, and this connection launched it
62
+ // with the same /proc id. A pid a re-attach found, or one kept alongside, is hosted, never killed.
105
63
  const registry = await readRegistryQuietly(ctx, runtime, layout);
106
64
  const managedPid = Number(runtime.remote.pid ?? 0);
107
- const registeredPid = Number(registry?.pid ?? 0);
108
- const registered = registry !== null &&
109
- registry.dshHome === layout.dshHome &&
110
- registry.profile === profile &&
111
- isPid(managedPid) &&
112
- registeredPid === managedPid;
113
- if (registered) {
65
+ if (registryNamesInstance(registry, layout, profile, managedPid)) {
114
66
  const verdict = await proveOwnership(ctx, runtime, {
115
67
  ...OWNERSHIP_OPTIONS.restart,
116
68
  pid: managedPid,
@@ -119,50 +71,44 @@ async function runRestart(ctx, runtime, token) {
119
71
  });
120
72
  killable = verdict.ok === true;
121
73
  if (verdict.ok !== true) {
122
- log('warn', `restart: not stopping pid ${managedPid} (${verdict.reason}); only a process this connection launched is stopped`);
74
+ const why = `restart: not stopping pid ${managedPid} (${verdict.reason}); only a process this connection launched is stopped`;
75
+ log('warn', why);
123
76
  }
124
77
  }
125
78
  else {
126
- log('warn', `restart: the run registry does not name this connection's pid (${isPid(managedPid) ? managedPid : 'unknown'}); leaving the running instance alone`);
79
+ const which = isPid(managedPid) ? managedPid : 'unknown';
80
+ log('warn', `restart: the run registry does not name this connection's pid (${which}); leaving the running instance alone`);
127
81
  }
128
- // A live instance this connection cannot stop and did not launch (typically the pid a
129
- // re-attach discovered) still occupies this ~/.dsh + profile. It goes through the conflict
130
- // prompt: restarting must never start a second instance silently next to it
131
- // (docs/design.md §5.5). Pids this connection launched are its own current instance; the
132
- // registry mismatch is the caller's existing "leave it alone" behavior, not a foreign one.
82
+ // A live instance this connection cannot stop and did not launch is hosted, not raced: it goes through the conflict prompt.
133
83
  let knownProcess = null;
134
84
  const launchedHere = runtime.launched instanceof Map && runtime.launched.has(managedPid);
135
85
  if (!killable && !launchedHere && isPid(managedPid) && runtime.ssh?.connected === true) {
136
86
  const identity = await ctx.deps.processIdentity(runtime.ssh, managedPid);
137
87
  if (identity.ok === true) {
138
88
  const sameHome = identity.dshHome === '' || identity.dshHome === layout.dshHome;
139
- if (sameHome && commandMatchesProfile(identity.command, profile)) {
89
+ if (sameHome && commandMatchesProfile(identity.command, profile))
140
90
  knownProcess = { pid: managedPid, command: identity.command };
141
- }
91
+ // Alive but not provable: asking is safer than starting a second instance.
142
92
  }
143
93
  else if (identity.reason === 'unreadable') {
144
- // Alive but not provable: asking is safer than starting a second instance.
145
94
  knownProcess = { pid: managedPid, command: `dsh --profile ${profile}` };
146
95
  }
147
96
  }
148
97
  if (!isLinkWorkCurrent(runtime, token))
149
98
  return;
150
- // Ask about foreign instances BEFORE anything is stopped: cancelling the prompt must not
151
- // destroy the instance the user is currently connected to (docs/design.md §5.5).
99
+ // Ask about foreign instances BEFORE anything is stopped: cancelling the prompt must not destroy
100
+ // the instance the user is currently connected to.
152
101
  const decision = await resolveForeignConflict(ctx, runtime, layout, profile, {
153
102
  ignoredPids: Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : [],
154
103
  knownProcess,
155
104
  });
156
105
  if (!isLinkWorkCurrent(runtime, token))
157
106
  return;
158
- // The prompt stopped the instance this connection was attached to: the old attachment is
159
- // gone, so a later failure must not "resume" it.
160
107
  if (decision === 'stop')
161
108
  stoppedOwn = true;
162
109
  if (killable) {
163
- const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid: managedPid });
164
110
  // A stop can take seconds; the link may have been dropped or replaced in the meantime.
165
- // A late action must not write warning/connected state on top of that.
111
+ const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid: managedPid });
166
112
  if (!isLinkWorkCurrent(runtime, token))
167
113
  return;
168
114
  stoppedOwn = stopped?.ok === true;
@@ -172,10 +118,8 @@ async function runRestart(ctx, runtime, token) {
172
118
  runtime.launched.delete(managedPid);
173
119
  }
174
120
  else {
175
- // Never start a second instance next to one whose stop was not confirmed. The old
176
- // tunnel is still open, so the host stays usable and the user can retry. The warning is
177
- // action-scoped data with no transition of its own: it is set here and cleared by
178
- // `connect.succeeded` once a fresh attach replaces the stale instance.
121
+ // Never start a second instance next to one whose stop was not confirmed: the old tunnel still works, so the
122
+ // host stays usable. The warning is action-scoped; `connect.succeeded` clears it once a fresh attach replaces.
179
123
  runtime.warning = {
180
124
  zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试,或先断开再重连。',
181
125
  en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly, or disconnect and reconnect.',
@@ -184,8 +128,8 @@ async function runRestart(ctx, runtime, token) {
184
128
  log('warn', `restart: the managed remote web did not confirm its stop; not launching a second instance (${String(stopped?.output ?? '').slice(0, 300) || 'no output'})`);
185
129
  if (await resumeConnected(ctx, runtime, true))
186
130
  return;
187
- // The link changed under us, or there was no tunnel to keep (restart from the error
188
- // state): never publish a fake "connected" state; explain instead of staying stuck.
131
+ // The link changed under us, or there was no tunnel to keep (restart from the error state):
132
+ // never publish a fake "connected" state; explain instead of staying stuck.
189
133
  if (isLinkWorkCurrent(runtime, token) && runtime.status === 'connecting') {
190
134
  const failure = {
191
135
  type: 'restart.failed',
@@ -219,9 +163,8 @@ async function runRestart(ctx, runtime, token) {
219
163
  if (!isLinkWorkCurrent(runtime, token))
220
164
  return;
221
165
  await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile);
222
- if (webInfo.browserCarrier === 'patched') {
223
- log('info', 'the remote profile disables api-remotes (browser Remote-Event carrier); re-enabled it for this launch');
224
- }
166
+ if (webInfo.browserCarrier === 'patched')
167
+ log('info', PATCHED_CARRIER_NOTE);
225
168
  log('info', `restart: remote DSH started pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`);
226
169
  const record = buildRunRegistryRecord({
227
170
  pid: webInfo.pid,
@@ -282,8 +225,8 @@ async function runRestart(ctx, runtime, token) {
282
225
  log('debug', 'restart aborted: the link was replaced by a disconnect or reconnect');
283
226
  return;
284
227
  }
285
- // Nothing this connection owned was stopped, so the previous attachment is still
286
- // valid: cancelling a conflict prompt (or a failed relaunch) keeps the host usable.
228
+ // Nothing this connection owned was stopped, so the previous attachment is still valid:
229
+ // cancelling a conflict prompt (or a failed relaunch) keeps the host usable.
287
230
  if (!stoppedOwn && !started && hadTunnel && runtime.ssh?.connected === true && runtime.tunnel !== null) {
288
231
  log('warn', `restart cancelled: ${messageOf(error)}; keeping the current remote instance`);
289
232
  await resumeConnected(ctx, runtime);
@@ -292,23 +235,19 @@ async function runRestart(ctx, runtime, token) {
292
235
  const view = error instanceof LinkCancelled
293
236
  ? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during restart' }))
294
237
  : toErrorView(error);
295
- // Phase is cleared with the status; capture it first so the log says where it stopped.
296
- const failedPhase = runtime.phase;
297
- // The transition owns the error state, the failure lines and the teardown; the caller keeps
298
- // its own publication point (`emit:false`, emitted below exactly where it always was).
299
- const failure = { type: 'restart.failed', view, phase: failedPhase };
238
+ const failure = { type: 'restart.failed', view, phase: runtime.phase };
300
239
  await dispatch(createRuntimeEffects(ctx), runtime, failure, scopeFactsFor(ctx, runtime, failure), {
301
240
  caller: 'script',
302
241
  emit: false,
303
- // Only a remote this restart launched is stopped; a restart that failed before the launch
304
- // leaves the instance it never touched alone (the rule cannot tell the two apart).
242
+ // Only a remote this restart launched is stopped; a restart that failed before the launch leaves
243
+ // the instance it never touched alone.
305
244
  teardown: { stopRemote: started && runtime.entry.keepAlive === 'stop' },
306
245
  });
307
246
  ctx.emitState();
308
247
  }
309
248
  finally {
310
- // A listener this action created must never outlive the action: a disconnect (or a host
311
- // removal) during the rebuild would otherwise leave it open with a disposed SSH channel.
249
+ // A listener this action created must never outlive the action: a disconnect during the rebuild
250
+ // would leave it open with a disposed SSH channel.
312
251
  if (tunnelCreated && !isLinkWorkCurrent(runtime, token))
313
252
  await closeTunnel(runtime);
314
253
  endLinkWork(runtime, token);
@@ -4,6 +4,7 @@ import { layoutForRuntime } from '../layout.js';
4
4
  import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
5
5
  import { createRuntimeEffects } from '../runtime/effects.js';
6
6
  import { isPid } from '../util.js';
7
+ import { linkActionState } from './guards.js';
7
8
  import { OWNERSHIP_OPTIONS, proveOwnership } from './ownership.js';
8
9
  /** Why the explicit stop refused, as the bilingual `ErrorView.detail` the Client renders. */
9
10
  function describeStopRefusal(reason, pid) {
@@ -48,22 +49,7 @@ function describeStopRefusal(reason, pid) {
48
49
  };
49
50
  }
50
51
  }
51
- /**
52
- * Stop the remote DSH this connection manages, then release the link: the tunnel closes,
53
- * the SSH session is released and the host lands on `disconnected` (settings and credentials
54
- * kept, no automatic reconnect) so the card offers Reconnect again. `run/web.json` is removed
55
- * by the stop itself, so the next connect starts a clean instance instead of raising the
56
- * "a manually started DSH is already running" conflict.
57
- *
58
- * Unlike the disconnect action this never kills a pid without an ownership proof: it reuses
59
- * the restart's `/proc` identity rules and additionally accepts the re-attached pid this
60
- * connection is bound to (docs/design.md §5.7). Available while connected and in the
61
- * `remote-unreachable` error state, which keeps the SSH session on purpose.
62
- *
63
- * @param ctx - service context.
64
- * @param runtime - host runtime.
65
- * @returns the stopped pid (null when already gone).
66
- */
52
+ /** Stop the remote DSH this connection manages, then release the link so the card offers Reconnect again; unlike disconnect this never kills a pid without an ownership proof. */
67
53
  export async function stopRemoteHost(ctx, runtime) {
68
54
  await ctx.init();
69
55
  if (runtime.connectPromise || runtime.linkBusy !== null) {
@@ -72,27 +58,20 @@ export async function stopRemoteHost(ctx, runtime) {
72
58
  en: 'This host is busy with another link action; wait for it to finish before stopping the remote DSH.',
73
59
  }, { technical: 'reason=link-busy' });
74
60
  }
75
- const connected = runtime.status === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null;
76
- const recoverable = runtime.status === 'error' &&
77
- runtime.error?.code === 'remote-unreachable' &&
78
- runtime.ssh?.connected === true &&
79
- runtime.facts !== null;
80
- if (!connected && !recoverable)
61
+ if (linkActionState(runtime) === null)
81
62
  throw errors.stopRemoteUnavailable();
82
- // The `previous` snapshot is what `stop.refused` restores; it is captured before the action
83
- // writes anything.
63
+ // The `previous` snapshot is what `stop.refused` restores; it is captured before the action writes anything.
84
64
  const previous = {
85
65
  status: runtime.status,
86
66
  phase: runtime.phase,
87
67
  progress: runtime.progress,
88
68
  error: runtime.error,
89
- uiReady: runtime.remote.uiReady,
90
- localPort: runtime.remote.localPort,
69
+ uiReady: runtime.remote.uiReady === true,
70
+ localPort: runtime.remote.localPort ?? null,
91
71
  };
92
- // One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`).
93
- // The token is the old `beginLinkWork` one (the rule adopts it), so `isLinkWorkCurrent` keeps
94
- // the exact late-write semantics.
95
72
  const token = (Number(runtime.linkToken) || 0) + 1;
73
+ // One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`); the token
74
+ // is the old `beginLinkWork` one, so `isLinkWorkCurrent` keeps the exact late-write semantics.
96
75
  const event = { type: 'stop.requested', token, pid: runtime.remote.pid, port: runtime.remote.port };
97
76
  let started = null;
98
77
  try {
@@ -110,22 +89,15 @@ export async function stopRemoteHost(ctx, runtime) {
110
89
  const view = toErrorView(error);
111
90
  const phase = typeof runtime.phase === 'string' ? runtime.phase : previous.phase;
112
91
  if (isLinkWorkCurrent(runtime, token)) {
113
- // The rule restores the previous state itself; `unrestorable` is the design's "link went
114
- // away while the stop was failing" branch, which publishes the coded failure instead.
115
92
  const restorable = previous.status === 'error' ||
116
93
  (runtime.desired === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null);
94
+ // The rule restores the previous state itself; `unrestorable` is the "link went away while the
95
+ // stop was failing" branch, which publishes the coded failure instead.
117
96
  const refusal = {
118
97
  type: 'stop.refused',
119
98
  view,
120
99
  phase,
121
- previous: {
122
- status: previous.status,
123
- phase: previous.phase,
124
- progress: previous.progress,
125
- error: previous.error,
126
- uiReady: previous.uiReady === true,
127
- localPort: previous.localPort ?? null,
128
- },
100
+ previous,
129
101
  ...(restorable ? {} : { unrestorable: true }),
130
102
  };
131
103
  await dispatch(createRuntimeEffects(ctx), runtime, refusal, scopeFactsFor(ctx, runtime, refusal), {
@@ -145,15 +117,13 @@ async function runStopRemote(ctx, runtime, token) {
145
117
  const pid = Number(runtime.remote.pid ?? 0);
146
118
  const port = Number(runtime.remote.port ?? 0);
147
119
  log('info', `stop remote requested (pid=${isPid(pid) ? pid : 'unknown'}, remote port=${isPid(port) ? port : 'unknown'})`);
148
- // `stop.requested` already disarmed the heartbeat/reconnect/idle timers and published the
149
- // `start`/`stopping-remote` card.
150
120
  const verdict = await proveOwnership(ctx, runtime, { ...OWNERSHIP_OPTIONS.stop, pid, layout, profile });
151
121
  if (!isLinkWorkCurrent(runtime, token)) {
152
122
  log('debug', 'stop remote aborted: the link was replaced by a disconnect or reconnect');
153
123
  return { ok: true, pid: null };
154
124
  }
155
- // A pid that is already gone is not a refusal for this action: there is nothing to signal, only
156
- // a stale registry to clear. Every other refusal is the coded error the card explains.
125
+ // A pid that is already gone is not a refusal for this action: there is nothing to signal, only a
126
+ // stale registry to clear. Every other refusal is the coded error the card explains.
157
127
  const gone = verdict.ok !== true && verdict.reason === 'identity-missing';
158
128
  if (verdict.ok !== true && !gone) {
159
129
  throw errors.stopRemoteUnavailable(describeStopRefusal(verdict.reason, pid), {
@@ -161,13 +131,10 @@ async function runStopRemote(ctx, runtime, token) {
161
131
  });
162
132
  }
163
133
  if (gone) {
164
- // Nothing to signal: the process is already gone. Only its stale record remains, and it
165
- // must go away or the next connect would try to stop/adopt a dead pid.
166
134
  log('info', `stop remote: the bound remote process pid=${pid} is already gone; clearing its run registry`);
167
135
  const cleared = await ctx.deps.clearRegistry(runtime.ssh, layout);
168
- if (cleared?.ok !== true) {
136
+ if (cleared?.ok !== true)
169
137
  log('warn', 'stop remote: the stale run registry could not be cleared:', cleared?.output ?? 'no output');
170
- }
171
138
  }
172
139
  else {
173
140
  const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid });
@@ -186,10 +153,9 @@ async function runStopRemote(ctx, runtime, token) {
186
153
  return { ok: true, pid: isPid(pid) ? pid : null };
187
154
  }
188
155
  runtime.bound = null;
189
- // One transition ends the action: `stop.succeeded` is the explicit stop's disconnect (the
190
- // `stopped:true` form keeps the idle policy from arming a second stop). The informational line
191
- // today's `disconnectHost` wrote is part of the operator log, so it stays, in its old position.
192
156
  ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`);
157
+ // One transition ends the action: `stop.succeeded` is the explicit stop's disconnect (the
158
+ // `stopped:true` form keeps the idle policy from arming a second stop).
193
159
  const done = { type: 'stop.succeeded' };
194
160
  await dispatch(createRuntimeEffects(ctx), runtime, done, scopeFactsFor(ctx, runtime, done), { caller: 'script' });
195
161
  runtime.bound = null;
@@ -4,14 +4,17 @@ import { resolveDestination } from '../ssh-config.js';
4
4
  import { isPid } from '../util.js';
5
5
  import { noteRemoteUnreachable } from '../watchdog.js';
6
6
  import { assertStillWanted, assertTransportOpen } from './guards.js';
7
- /** Resolve the SSH destination from the entry + local ssh config, before dialling. */
7
+ /** The known_hosts fingerprints for one host:port, from the SSH material the caller already read: the one lookup both a direct destination and a jump host use. */
8
+ export function knownFingerprintsFor(material, host, port) {
9
+ return findKnownHostEntries(parseKnownHosts(material.knownHostsText), host, port).map((item) => item.fingerprint);
10
+ }
8
11
  export async function resolveTargetForRuntime(ctx, runtime) {
9
12
  const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() });
10
13
  const entry = runtime.entry;
11
14
  const resolved = resolveDestination(entry.address, { configText: material.configText, home: ctx.userHome() });
12
15
  const host = resolved.host || entry.address;
13
16
  const port = entry.port && entry.port !== 22 ? entry.port : (resolved.port ?? 22);
14
- const knownFingerprints = findKnownHostEntries(parseKnownHosts(material.knownHostsText), host, port).map((item) => item.fingerprint);
17
+ const knownFingerprints = knownFingerprintsFor(material, host, port);
15
18
  return {
16
19
  host,
17
20
  port,
@@ -24,29 +27,28 @@ export async function resolveTargetForRuntime(ctx, runtime) {
24
27
  entry,
25
28
  };
26
29
  }
27
- /** Remember the session fingerprint so the host card shows it even without a pin. */
28
30
  export function captureFingerprint(ctx, runtime, info) {
29
31
  if (!info?.fingerprint)
30
32
  return;
31
33
  const pinned = runtime.entry.pinnedFingerprint ?? null;
34
+ const matches = pinned === info.fingerprint;
32
35
  runtime.fingerprint = {
33
36
  sha256: info.fingerprint,
34
37
  keyType: info.keyType ?? 'unknown',
35
- status: pinned === info.fingerprint ? 'pinned' : pinned ? 'changed' : 'observed',
38
+ status: matches ? 'pinned' : pinned ? 'changed' : 'observed',
36
39
  pinned,
37
40
  };
38
- ctx.progress.log(runtime, pinned === info.fingerprint ? 'debug' : 'info', `host key ${info.keyType ?? 'unknown'}: ${info.fingerprint}${pinned === info.fingerprint ? ' (matches the pinned key)' : pinned ? ' (CHANGED from the pinned key)' : ''}`);
41
+ ctx.progress.log(runtime, matches ? 'debug' : 'info', `host key ${info.keyType ?? 'unknown'}: ${info.fingerprint}${matches ? ' (matches the pinned key)' : pinned ? ' (CHANGED from the pinned key)' : ''}`);
39
42
  ctx.emitState();
40
43
  }
41
44
  /** Open the loopback tunnel for one remote port; tunnel-level failures feed the liveness confirmation. */
42
45
  export async function openTunnelFor(ctx, runtime, remotePort) {
43
- // Never hand the tunnel factory a missing transport: a listener created with no SSH channel
44
- // would crash the host process on the first connection (see tunnel.js's own guard).
46
+ // Never hand the tunnel factory a missing transport: a listener with no SSH channel would crash the
47
+ // host process on the first connection.
45
48
  assertTransportOpen(runtime);
46
49
  if (!isPid(remotePort) || remotePort > 65535) {
47
50
  throw errors.internal(new Error(`invalid remote port for the tunnel: ${remotePort}`));
48
51
  }
49
- // Forward import, not a `ctx` callback: the liveness watchdog is a plain module now (§1.7).
50
52
  const onError = () => noteRemoteUnreachable(ctx, runtime, 'tunnel');
51
53
  const tunnel = await ctx.deps.tunnelFactory({ ssh: runtime.ssh, remotePort, onError });
52
54
  const localPort = Number(tunnel?.localPort);
@@ -59,8 +61,6 @@ export async function openTunnelFor(ctx, runtime, remotePort) {
59
61
  }
60
62
  throw errors.internal(new Error(`the tunnel factory returned no usable local port (${tunnel?.localPort})`));
61
63
  }
62
- // The listener was created while the caller awaited the factory: a disconnect or a host
63
- // removal in that window must close it instead of publishing it (H4).
64
64
  try {
65
65
  assertStillWanted(ctx, runtime);
66
66
  assertTransportOpen(runtime);
@@ -79,14 +79,6 @@ export async function openTunnelFor(ctx, runtime, remotePort) {
79
79
  ctx.progress.log(runtime, 'info', `tunnel open: 127.0.0.1:${localPort} -> 127.0.0.1:${remotePort}`);
80
80
  return tunnel;
81
81
  }
82
- /**
83
- * Persist (or forget) the SSH password now that the transport accepted it. Doing this right
84
- * after the handshake rather than after `connected` keeps a credential the server already
85
- * proved even when a later bootstrap step fails, so the next attempt does not ask again.
86
- * @param ctx - service context.
87
- * @param runtime - host runtime.
88
- * @param log - connect log writer.
89
- */
90
82
  export async function settlePasswordStorage(ctx, runtime, log) {
91
83
  const save = runtime.savePassword === true;
92
84
  const forget = runtime.forgetPassword === true;
@@ -1,21 +1,14 @@
1
- /**
2
- * The `[verifying]` step: the remote UI answers through the new listener and the launch token
3
- * exchanges for the cookie the carrier needs. Both halves are guarded across their awaits (H3/H4).
4
- */
1
+ /** The `[verifying]` step: the remote UI answers through the new listener and the launch token exchanges for the cookie the carrier needs; both halves are guarded across their awaits. */
5
2
  import { TUNNEL_PROBE_TIMEOUT_MS } from '../constants.js';
6
3
  import { errors } from '../errors.js';
7
4
  import { isPid } from '../util.js';
8
5
  import { assertStillWanted, assertTransportOpen } from './guards.js';
9
- /** Prove the remote UI answers through the new tunnel and exchange this launch's token. */
10
6
  export async function verifyRemoteUi(ctx, runtime, port, token, localPort) {
11
7
  const tunnelPort = Number(localPort);
12
- if (!Number.isInteger(tunnelPort) || !isPid(tunnelPort) || tunnelPort > 65535) {
8
+ if (!Number.isInteger(tunnelPort) || !isPid(tunnelPort) || tunnelPort > 65535)
13
9
  throw errors.internal(new Error(`the tunnel has no local port to verify (${localPort ?? 'none'})`));
14
- }
15
10
  ctx.progress.log(runtime, 'debug', `verifying the remote UI on 127.0.0.1:${tunnelPort}`);
16
11
  const ui = await ctx.deps.waitUi(runtime.ssh, port, { attempts: 20, intervalMs: 500 });
17
- // The probe retries for up to ten seconds: the user may have cancelled in that window, and
18
- // the token exchange must not touch the (possibly closed) tunnel after it (H4).
19
12
  assertStillWanted(ctx, runtime);
20
13
  assertTransportOpen(runtime);
21
14
  if (!ui.ok) {
@@ -25,9 +18,7 @@ export async function verifyRemoteUi(ctx, runtime, port, token, localPort) {
25
18
  });
26
19
  }
27
20
  ctx.progress.log(runtime, 'debug', `remote UI answered HTTP ${ui.status}; exchanging the launch token`);
28
- const exchange = await ctx.deps.exchange(tunnelPort, token, {
29
- timeoutMs: TUNNEL_PROBE_TIMEOUT_MS,
30
- });
21
+ const exchange = await ctx.deps.exchange(tunnelPort, token, { timeoutMs: TUNNEL_PROBE_TIMEOUT_MS });
31
22
  runtime.exchange = exchange;
32
23
  if (!exchange.ok) {
33
24
  throw errors.remoteUiUnreachable({