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,14 +1,8 @@
1
1
  import { errors } from '../errors.js';
2
- /**
3
- * Recompute the launch plan from the probe facts the connection already recorded. A
4
- * restart reuses the same managed Node, profile and pinned version, so `[ssh]`,
5
- * `[probe]` and `[bootstrap]` are deliberately not run again.
6
- */
7
2
  export function planForRuntime(ctx, runtime, profile) {
8
- const facts = runtime.facts;
3
+ const { facts } = runtime;
9
4
  const targetVersion = ctx.localVersion();
10
- if (!facts || !targetVersion) {
5
+ if (!facts || !targetVersion)
11
6
  throw errors.internal(new Error('the connected host has no recorded probe facts or local version'));
12
- }
13
7
  return { plan: ctx.deps.plan({ facts, targetVersion, profile }), targetVersion, facts };
14
8
  }
@@ -1,31 +1,16 @@
1
- /**
2
- * One classification for a failed connect step (design-arch §3.3, single implementation): a step
3
- * that raced the transport going away must read as a dropped connection (network, retryable),
4
- * never as a bare internal error or as a key decision the user never made (H3).
5
- */
1
+ /** One classification for a failed connect step: a step that raced the transport going away must read as a dropped connection (network, retryable), never as a bare internal error or as a key decision the user never made. */
6
2
  import { errors, RemoteGoError, toErrorView } from '../errors.js';
7
3
  /** The bilingual detail of "the transport this step needed is gone". */
8
4
  export const SSH_CLOSED_DETAIL = {
9
5
  zh: 'SSH 连接已断开,本次操作没有完成;如果主机仍在线,重连即可继续。',
10
6
  en: 'SSH connection is not open; the transport closed before this step finished. Reconnect to continue.',
11
7
  };
12
- /**
13
- * Classify a pipeline failure. A step that raced the transport going away must read as a
14
- * dropped connection (`network`, retryable), never as a bare `internal` error or as a key
15
- * decision the user never made (H3).
16
- * @param runtime - host runtime.
17
- * @param error - the thrown value.
18
- * @returns the Client-facing error view.
19
- */
8
+ /** Classify a pipeline failure, so a step that raced the transport away reads as a dropped connection rather than a key decision the user never made. */
20
9
  export function normalizeConnectFailure(runtime, error) {
21
10
  const view = toErrorView(error);
22
11
  if (runtime.transportLost === true && runtime.ssh?.connected !== true) {
23
- // A prompt parked on the transport was resolved by the close itself: the user made no
24
- // decision, so this must not read as "confirm the host key" / "a manual DSH is running".
25
12
  if (view.code === 'host-key-unknown' || view.code === 'remote-dsh-running') {
26
- return toErrorView(errors.network(SSH_CLOSED_DETAIL, {
27
- technical: `reason=ssh-closed phase-code=${view.code}`,
28
- }));
13
+ return toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: `reason=ssh-closed phase-code=${view.code}` }));
29
14
  }
30
15
  }
31
16
  if (runtime.ssh?.connected === true) {
@@ -1,9 +1,6 @@
1
1
  import { errors } from '../errors.js';
2
2
  import { SSH_CLOSED_DETAIL } from './failures.js';
3
- /**
4
- * Internal marker: a pipeline step ran after the user (or the host process) took the link
5
- * away. It is not a connection failure, so it never reaches the Client as an error.
6
- */
3
+ /** Internal marker: a pipeline step ran after the user (or the host process) took the link away; it is not a connection failure, so it never reaches the Client as an error. */
7
4
  export class LinkCancelled extends Error {
8
5
  constructor(reason) {
9
6
  super(`connect aborted: ${reason}`);
@@ -11,21 +8,29 @@ export class LinkCancelled extends Error {
11
8
  this.code = 'link-cancelled';
12
9
  }
13
10
  }
14
- /** Whether the link is no longer wanted: disconnect, host removal, teardown or shutdown. */
15
11
  export function linkTaken(ctx, runtime) {
16
12
  return (ctx.state.disposed === true ||
17
13
  runtime.closing === true ||
18
14
  runtime.desired !== 'connected' ||
19
15
  !ctx.state.runtimes.has(runtime.id));
20
16
  }
21
- /** Throw unless this attempt may still write state (H4). */
17
+ /** Throw unless this attempt may still write state. */
22
18
  export function assertStillWanted(ctx, runtime) {
23
19
  if (linkTaken(ctx, runtime))
24
20
  throw new LinkCancelled('the link is no longer wanted');
25
21
  }
26
- /** Throw a typed transport error unless the SSH transport is still open (H3). */
22
+ /** Throw a typed transport error unless the SSH transport is still open. */
27
23
  export function assertTransportOpen(runtime) {
28
- if (runtime.ssh?.connected !== true) {
24
+ if (runtime.ssh?.connected !== true)
29
25
  throw errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed' });
26
+ }
27
+ /** The state a one-shot link action may start from: a live link, or the `remote-unreachable` error state that keeps the SSH transport on purpose (so restart and stop also work from it). `null` means the action is not available; the caller names its own refusal. */
28
+ export function linkActionState(runtime) {
29
+ const sshUp = runtime.ssh?.connected === true;
30
+ if (runtime.status === 'connected' && sshUp && runtime.tunnel !== null)
31
+ return 'connected';
32
+ if (runtime.status === 'error' && runtime.error?.code === 'remote-unreachable' && sshUp && runtime.facts !== null) {
33
+ return 'recoverable';
30
34
  }
35
+ return null;
31
36
  }
@@ -1,15 +1,14 @@
1
1
  import { errors } from '../errors.js';
2
2
  import { askConflict } from '../prompts.js';
3
3
  import { isPid, messageOf } from '../util.js';
4
- /**
5
- * Warn when the remote already runs a DSH this plugin did not start, and let the
6
- * user decide: stop it, keep it alongside, or cancel.
7
- * @returns the decision, or null when no prompt was needed.
8
- */
4
+ /** The note a launch logs after it had to re-enable the remote profile's browser Remote-Event carrier. */
5
+ export const PATCHED_CARRIER_NOTE = 'the remote profile disables api-remotes (browser Remote-Event carrier); re-enabled it for this launch';
6
+ /** Warn when the remote already runs a DSH this plugin did not start, and let the user decide: stop it, keep it alongside, or cancel. */
9
7
  export async function resolveForeignConflict(ctx, runtime, layout, profile, options = {}) {
10
- // Processes the user already chose to keep alongside this connection are not asked
11
- // about again (a local restart must not turn that choice into a prompt every time).
12
- const ignorePids = (Array.isArray(options.ignoredPids) ? options.ignoredPids : []).filter((pid) => isPid(pid));
8
+ // Processes the user already chose to keep alongside this connection are not asked about again.
9
+ const answered = Array.isArray(options.ignoredPids) ? options.ignoredPids : [];
10
+ const keptAlongside = answered.map(Number);
11
+ const ignorePids = answered.filter((pid) => isPid(pid));
13
12
  try {
14
13
  const registry = await ctx.deps.readRegistry(runtime.ssh, layout);
15
14
  const pid = Number(registry?.pid);
@@ -22,15 +21,10 @@ export async function resolveForeignConflict(ctx, runtime, layout, profile, opti
22
21
  }
23
22
  const found = await ctx.deps.findForeign(runtime.ssh, { ignorePids });
24
23
  const processes = found.ok === true && Array.isArray(found.processes) ? [...found.processes] : [];
25
- // The registry-named instance is normally ignored by the scan (it is this connection's own
26
- // process). When the caller cannot stop it - a pid a re-attach discovered - it still must be
27
- // put in front of the user: a second instance must never start silently next to it. Merge it
28
- // before failing open on a scan error: its identity came from /proc, not from the scan.
24
+ // The registry-named instance is normally ignored by the scan, but when the caller cannot stop it it must still be
25
+ // shown: a second instance must never start silently next to it. Merged before failing open, since /proc proved it.
29
26
  const known = options.knownProcess;
30
27
  const knownPid = Number(known?.pid);
31
- // A pid the user already chose to keep alongside is never asked about again; the
32
- // registry-named pid, however, must be shown when it could not be stopped.
33
- const keptAlongside = (Array.isArray(options.ignoredPids) ? options.ignoredPids : []).map(Number);
34
28
  if (isPid(knownPid) &&
35
29
  !keptAlongside.includes(knownPid) &&
36
30
  !processes.some((entry) => Number(entry?.pid) === knownPid)) {
@@ -41,8 +35,6 @@ export async function resolveForeignConflict(ctx, runtime, layout, profile, opti
41
35
  }
42
36
  if (found.ok !== true) {
43
37
  ctx.progress.log(runtime, 'debug', 'foreign DSH: scan failed:', found.reason ?? found.technical ?? 'unknown');
44
- // A broken scan must never allow a silent second instance: with a known live process we
45
- // still ask; with nothing known there is nothing to conflict with (the old behavior).
46
38
  if (processes.length === 0)
47
39
  return null;
48
40
  }
@@ -51,11 +43,9 @@ export async function resolveForeignConflict(ctx, runtime, layout, profile, opti
51
43
  const pidList = processes.map((entry) => `pid ${entry.pid}`).join(', ');
52
44
  ctx.progress.log(runtime, 'warn', `foreign DSH on the remote: ${processes.length} process(es) sharing this ~/.dsh (${pidList})`);
53
45
  const decision = await askConflict(ctx, runtime, processes);
54
- if (decision.action === 'cancel') {
55
- // The user said no: retrying would ask the same question again. The `conflict.answered`
56
- // transition already recorded that (its rule owns `connectCancelled`); this is only the throw.
46
+ // The user said no: retrying would ask the same question again (`conflict.answered` already owns the flag).
47
+ if (decision.action === 'cancel')
57
48
  throw errors.remoteDshRunning();
58
- }
59
49
  if (decision.action === 'alongside') {
60
50
  runtime.alongsidePids = processes.map((entry) => entry.pid).filter((pid) => isPid(pid));
61
51
  runtime.warning = {
@@ -1,7 +1,4 @@
1
- /**
2
- * The two connect entries: a user connect (which owns the one-time inputs, the retry budget and
3
- * the log boundary) and the "Reconnect" button's drop-and-redial.
4
- */
1
+ /** The two connect entries: a user connect (which owns the one-time inputs, the retry budget and the log boundary) and the "Reconnect" button's drop-and-redial. */
5
2
  import { beginConnectLog } from '../connect-log.js';
6
3
  import { runtimeOf } from '../host-registry.js';
7
4
  import { cancelIdleStop, disconnectHost, disposeSsh } from '../host-lifecycle.js';
@@ -9,15 +6,7 @@ import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
9
6
  import { createRuntimeEffects } from '../runtime/effects.js';
10
7
  import { isRefusal } from '../runtime/fsm.js';
11
8
  import { startConnectPromise } from './pipeline.js';
12
- function describeTarget(entry) {
13
- const user = entry.username ? `${entry.username}@` : '';
14
- const port = entry.port && entry.port !== 22 ? `:${entry.port}` : '';
15
- return `${user}${entry.address || '?'}${port}`;
16
- }
17
- /**
18
- * Accept a connect request: apply the one-time inputs, stop any pending retry,
19
- * and start the pipeline in the background. Progress travels on `state`.
20
- */
9
+ /** Accept a connect request: apply the one-time inputs, stop any pending retry, and start the pipeline in the background. */
21
10
  export async function startConnect(ctx, id, options = {}) {
22
11
  await ctx.init();
23
12
  const runtime = runtimeOf(ctx, id);
@@ -31,21 +20,16 @@ export async function startConnect(ctx, id, options = {}) {
31
20
  const typedPassword = typeof options.password === 'string' && options.password !== '' ? options.password : null;
32
21
  if (typedPassword !== null)
33
22
  runtime.password = typedPassword;
34
- // Remembering is the default for a password the user just typed (`POST /hosts/:id/connect`
35
- // treats an absent `rememberPassword` as true). An explicit false means "this connection
36
- // only" and also forgets a previously saved record, so an unchecked box cannot leave a stale
37
- // secret behind. A retry or auto-reconnect carries no password of its own and must not
38
- // re-save what the store already holds.
23
+ // Remembering is the default for a typed password; an explicit false means "this connection only" and
24
+ // also forgets a previously saved record, while a retry carries no password and re-saves nothing.
39
25
  runtime.savePassword = typedPassword !== null && options.rememberPassword !== false;
40
26
  runtime.forgetPassword = typedPassword !== null && options.rememberPassword === false;
41
- // This connection starts its own log: the previous attempt's lines are gone before the
42
- // first line of this one, so the panel and a copied log only ever show the live attempt.
43
- // The line keeps the previous attempt's `phase`, exactly as it did before the FSM owned it.
27
+ // This connection starts its own log, so the panel and a copied log only ever show the live attempt.
44
28
  beginConnectLog(runtime);
45
- ctx.progress.log(runtime, 'info', `connect: ${describeTarget(runtime.entry)} (auth=${runtime.entry.auth?.type ?? 'key'}${runtime.entry.jumpHost ? `, jump=${runtime.entry.jumpHost}` : ''})`);
46
- // One transition owns the whole entry: the retry budget and prompt history reset (a *user*
47
- // connect), the timer disarms, the desired flag and the pipeline start (`run`). The token
48
- // invalidates any older one-shot action, the same way the old `cancelLinkWork` did.
29
+ const { entry } = runtime;
30
+ const user = entry.username ? `${entry.username}@` : '';
31
+ const port = entry.port && entry.port !== 22 ? `:${entry.port}` : '';
32
+ ctx.progress.log(runtime, 'info', `connect: ${user}${entry.address || '?'}${port} (auth=${entry.auth?.type ?? 'key'}${entry.jumpHost ? `, jump=${entry.jumpHost}` : ''})`);
49
33
  const token = (Number(runtime.linkToken) || 0) + 1;
50
34
  const event = { type: 'connect.requested', token };
51
35
  const result = await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
@@ -63,8 +47,8 @@ export async function reconnectHost(ctx, runtime) {
63
47
  await disconnectHost(ctx, runtime, { stopRemote: false });
64
48
  cancelIdleStop(runtime);
65
49
  await disposeSsh(runtime);
66
- // A one-shot action cancelled by the disconnect resolves after its transport is gone; it
67
- // can no longer write state, but letting it settle keeps the old code out of the new run.
50
+ // A one-shot action cancelled by the disconnect resolves after its transport is gone; letting it
51
+ // settle keeps the old code out of the new run.
68
52
  await Promise.allSettled([runtime.restartPromise, runtime.reattachPromise].filter((promise) => promise && typeof promise.then === 'function'));
69
53
  return startConnect(ctx, runtime.id, {});
70
54
  }
@@ -1,92 +1,44 @@
1
+ import { registryNamesInstance } from '../remote-web/registry.js';
1
2
  import { commandMatchesProfile } from '../remote-web/resolve.js';
2
3
  import { isPid } from '../util.js';
3
4
  import { readRegistryQuietly } from './registry.js';
4
- /**
5
- * Record a pid this connection is allowed to stop later: it must have been launched by the
6
- * plugin's own start script (or adopted from a `launch` registry record) and its `/proc`
7
- * identity must show this DSH home and profile. Anything that fails this check is still
8
- * hosted and displayed, but never signalled.
9
- */
5
+ function deny(ctx, runtime, tag, pid, detail, tail) {
6
+ ctx.progress.log(runtime, 'debug', `${tag}: pid ${pid} ${detail}; ${tail}`);
7
+ return null;
8
+ }
9
+ /** Record a pid this connection may stop later: it must come from its own start script (or a `launch` registry record) and its `/proc` identity must show this DSH home and profile. Anything else is still displayed but never signalled. */
10
10
  export async function rememberLaunched(ctx, runtime, pid, layout, profile) {
11
11
  if (!isPid(pid))
12
12
  return null;
13
13
  if (!(runtime.launched instanceof Map))
14
14
  runtime.launched = new Map();
15
15
  const identity = await ctx.deps.processIdentity(runtime.ssh, pid);
16
- if (identity.ok !== true) {
17
- ctx.progress.log(runtime, 'debug', `launch: pid ${pid} identity unreadable (${identity.reason}); it will not be stopped`);
18
- return null;
19
- }
20
- if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
21
- ctx.progress.log(runtime, 'debug', `launch: pid ${pid} runs with another DSH_HOME; it will not be stopped`);
22
- return null;
23
- }
24
- if (!commandMatchesProfile(identity.command, profile)) {
25
- ctx.progress.log(runtime, 'debug', `launch: pid ${pid} does not run profile ${profile}; it will not be stopped`);
26
- return null;
27
- }
28
- const record = {
29
- startTime: identity.startTime,
30
- command: identity.command,
31
- dshHome: identity.dshHome,
32
- };
16
+ if (identity.ok !== true)
17
+ return deny(ctx, runtime, 'launch', pid, `identity unreadable (${identity.reason})`, 'it will not be stopped');
18
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome)
19
+ return deny(ctx, runtime, 'launch', pid, 'runs with another DSH_HOME', 'it will not be stopped');
20
+ if (!commandMatchesProfile(identity.command, profile))
21
+ return deny(ctx, runtime, 'launch', pid, `does not run profile ${profile}`, 'it will not be stopped');
22
+ const record = { startTime: identity.startTime, command: identity.command, dshHome: identity.dshHome };
33
23
  runtime.launched.set(pid, record);
34
24
  runtime.bound = { pid, startTime: identity.startTime, origin: 'launch' };
35
25
  return record;
36
26
  }
37
- /**
38
- * Remember the remote web this connection is bound to without granting restart kill rights.
39
- * A re-attach (or the adoption of a re-attached record) names a process this plugin did not
40
- * launch: a restart must leave it running, but the user's explicit "Stop remote DSH" may stop
41
- * exactly this pid. The identity recorded here is what that action re-proves before signalling.
42
- * @param ctx - service context.
43
- * @param runtime - host runtime with a live transport.
44
- * @param pid - the bound remote web pid.
45
- * @param layout - remote layout.
46
- * @param profile - remote DSH profile.
47
- * @param origin - how this connection came to host the process.
48
- * @returns the recorded binding, or null when it cannot be proven.
49
- */
27
+ /** Remember a remote web this connection is bound to without granting restart kill rights: a restart must leave a re-attached process running, but the explicit "Stop remote DSH" may stop exactly this pid. */
50
28
  export async function rememberBound(ctx, runtime, pid, layout, profile, origin) {
51
29
  if (!isPid(pid))
52
30
  return null;
53
31
  const identity = await ctx.deps.processIdentity(runtime.ssh, pid);
54
- if (identity.ok !== true) {
55
- ctx.progress.log(runtime, 'debug', `bind: pid ${pid} identity unreadable (${identity.reason}); it will not be stopped on request`);
56
- return null;
57
- }
58
- if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
59
- ctx.progress.log(runtime, 'debug', `bind: pid ${pid} runs with another DSH_HOME; it cannot be stopped here`);
60
- return null;
61
- }
62
- if (!commandMatchesProfile(identity.command, profile)) {
63
- ctx.progress.log(runtime, 'debug', `bind: pid ${pid} does not run profile ${profile}; it cannot be stopped here`);
64
- return null;
65
- }
32
+ if (identity.ok !== true)
33
+ return deny(ctx, runtime, 'bind', pid, `identity unreadable (${identity.reason})`, 'it will not be stopped on request');
34
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome)
35
+ return deny(ctx, runtime, 'bind', pid, 'runs with another DSH_HOME', 'it cannot be stopped here');
36
+ if (!commandMatchesProfile(identity.command, profile))
37
+ return deny(ctx, runtime, 'bind', pid, `does not run profile ${profile}`, 'it cannot be stopped here');
66
38
  runtime.bound = { pid, startTime: identity.startTime, origin };
67
39
  return runtime.bound;
68
40
  }
69
- /**
70
- * The three call sites' option sets (design-arch §4.3). They live here so the differences are a
71
- * table the tests can read instead of three copies of the same nine checks:
72
- *
73
- * - `restart` is an *implicit* kill: only a process this connection launched may be stopped. The
74
- * registry check belongs to the caller, because a registry mismatch is a conflict prompt, not a
75
- * refusal (design.md §5.5). `strict` because a `launched` record always carries the `/proc`
76
- * start time; one without it is a broken record, and an unprovable pid must not be stopped.
77
- * It proves the record before `alongsidePids`, which is the order its pre-merge form used, and it
78
- * always knows the profile it manages.
79
- * - `stop` is the user pointing at the instance this connection is bound to: it may stop a
80
- * re-attached pid (design.md §5.7), but only that exact pid, and only while `run/web.json` still
81
- * names it with the same home and profile — the written evidence of "the instance this
82
- * connection manages". It knows the profile too; `kept-alongside` stays its first refusal.
83
- * - `idle` has nobody pointing at anything, only a timer: no registry (it may be stale by then),
84
- * but it needs a record of its own; `bound-first` preserves the order the timer always used, and
85
- * an empty profile (a teardown that forgot it) skips the profile comparison instead of refusing.
86
- *
87
- * `noProofReason` and `prefer` exist only to keep the existing wording and order (DECISIONS H5);
88
- * a fourth call site must be registered here with its reason.
89
- */
41
+ /** The three call sites' option sets, kept here as a table instead of three copies of the same nine checks. `restart` is an implicit kill: only what this connection launched, proven before `alongsidePids`, with a strict start time and a mandatory profile (its registry mismatch is the caller's conflict prompt, not a refusal). `stop` is the user pointing at the instance this connection is bound to: that exact pid, and only while `run/web.json` still names it with the same home and profile. `idle` has only a timer: no registry, but a record of its own, bound-first order, and an empty profile that skips the comparison. */
90
42
  export const OWNERSHIP_OPTIONS = {
91
43
  restart: {
92
44
  sources: ['launched'],
@@ -111,33 +63,7 @@ export const OWNERSHIP_OPTIONS = {
111
63
  noProofReason: 'not-owned',
112
64
  },
113
65
  };
114
- /**
115
- * Prove that this connection may signal `pid`, and say why not when it may not.
116
- *
117
- * The judgment order is itself part of the contract (§4.2), and every step is a refusal that
118
- * never signals anything:
119
- *
120
- * ```
121
- * 1 pid is a pid → pid-unknown
122
- * 2 requireProfile && profile is empty → profile-mismatch
123
- * 3 requireBoundPid && remote.pid !== pid → not-the-bound-instance
124
- * 4 !proofBeforeAlongside && forbidAlongside && alongside has pid → kept-alongside
125
- * 5 no record of the allowed sources → noProofReason
126
- * 6 proofBeforeAlongside && forbidAlongside && alongside has pid → kept-alongside
127
- * 7 requireRegistry && the registry does not name it → registry-mismatch
128
- * 8 /proc identity unreadable → identity-unreadable
129
- * /proc says it is gone → identity-missing
130
- * any other read failure → identity-<reason>
131
- * 9 start time differs → pid-reused
132
- * 10 the process runs under another DSH home → dsh-home-mismatch
133
- * 11 the command line carries another profile → profile-mismatch
134
- * ```
135
- *
136
- * @param ctx - transport (the `/proc` reader) and, when `requireRegistry` is set, the registry.
137
- * @param runtime - host runtime the records live on.
138
- * @param options - one of {@link OWNERSHIP_OPTIONS} plus the pid, layout and profile.
139
- * @returns `{ ok: true }` with the evidence, or the frozen reason it refused.
140
- */
66
+ /** Prove that this connection may signal `pid`, and say why not when it may not. The judgment order is part of the contract, and every step is a refusal that never signals anything: pid, profile, bound pid, alongside, record, alongside again, registry, `/proc` identity, start time, DSH home, profile. */
141
67
  export async function proveOwnership(ctx, runtime, options) {
142
68
  const { pid, layout, profile } = options;
143
69
  const sources = options.sources ?? ['launched'];
@@ -147,19 +73,14 @@ export async function proveOwnership(ctx, runtime, options) {
147
73
  const forbidAlongside = options.forbidAlongside !== false;
148
74
  const alongside = Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : [];
149
75
  const launched = sources.includes('launched') && runtime.launched instanceof Map ? runtime.launched.get(pid) : undefined;
150
- const bound = sources.includes('bound') &&
151
- runtime.bound !== null &&
152
- runtime.bound !== undefined &&
153
- Number(runtime.bound.pid) === pid
154
- ? runtime.bound
155
- : null;
76
+ const bound = sources.includes('bound') && runtime.bound != null && Number(runtime.bound.pid) === pid ? runtime.bound : null;
156
77
  const launchedProof = launched ?? null;
157
78
  const proof = prefer === 'bound-first' ? (bound ?? launchedProof) : (launchedProof ?? bound);
158
79
  const source = proof === null ? null : proof === launchedProof ? 'launched' : 'bound';
159
80
  const evidence = {
160
81
  pid,
161
82
  source,
162
- recordedStartTime: proof === null ? null : typeof proof.startTime === 'string' ? proof.startTime : null,
83
+ recordedStartTime: typeof proof?.startTime === 'string' ? proof.startTime : null,
163
84
  identity: null,
164
85
  registry: null,
165
86
  layout,
@@ -168,8 +89,8 @@ export async function proveOwnership(ctx, runtime, options) {
168
89
  const refuse = (reason) => ({ ok: false, reason, evidence });
169
90
  if (!isPid(pid))
170
91
  return refuse('pid-unknown');
171
- // Only the shapes that always know their profile enforce this; the idle timer may have lost it
172
- // in a teardown, which must stay "unknown" rather than become a refusal.
92
+ // Only the shapes that always know their profile enforce this; the idle timer may have lost it in
93
+ // a teardown, which must stay "unknown" rather than become a refusal.
173
94
  if (options.requireProfile === true && profile === '')
174
95
  return refuse('profile-mismatch');
175
96
  if (options.requireBoundPid === true && Number(runtime.remote.pid) !== pid)
@@ -184,11 +105,7 @@ export async function proveOwnership(ctx, runtime, options) {
184
105
  if (options.requireRegistry === true) {
185
106
  const registry = await readRegistryQuietly(ctx, runtime, layout);
186
107
  evidence.registry = registry;
187
- const registered = registry !== null &&
188
- registry.dshHome === layout.dshHome &&
189
- registry.profile === profile &&
190
- Number(registry.pid) === pid;
191
- if (!registered)
108
+ if (!registryNamesInstance(registry, layout, profile, pid))
192
109
  return refuse('registry-mismatch');
193
110
  }
194
111
  let identity;
@@ -201,15 +118,17 @@ export async function proveOwnership(ctx, runtime, options) {
201
118
  }
202
119
  evidence.identity = identity;
203
120
  if (identity.ok !== true) {
204
- // "The process is gone" and "the process could not be read" are different refusals: the
205
- // explicit stop clears a stale registry only for the first one.
121
+ // "The process is gone" and "the process could not be read" are different refusals: the explicit
122
+ // stop clears a stale registry only for the first one.
206
123
  return refuse(identity.reason === 'missing' ? 'identity-missing' : `identity-${identity.reason}`);
207
124
  }
125
+ const recorded = typeof proof.startTime === 'string' ? proof.startTime : null;
208
126
  if (startTimeMode === 'strict') {
209
- if (identity.startTime !== proof.startTime)
127
+ // A `launched` record always carries the start time; one without it is a broken record, so it refuses.
128
+ if (identity.startTime !== recorded)
210
129
  return refuse('pid-reused');
211
130
  }
212
- else if (typeof proof.startTime === 'string' && identity.startTime !== proof.startTime) {
131
+ else if (recorded !== null && identity.startTime !== recorded) {
213
132
  return refuse('pid-reused');
214
133
  }
215
134
  if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome)