dsh-remote-go 0.2.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 (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,96 @@
1
+ /** Remote runtime preparation: `npx` pinned to the local DSH version against the remote's real `$DSH_HOME`; the
2
+ * executor runs only fixed templates. */
3
+ import { errors } from './errors.js';
4
+ import { headTail, shellQuote } from './util.js';
5
+ import { isNodeVersionSupported, normalizeVersion, parseVersion, versionsEqual } from './version.js';
6
+ export function assertSupportedRemote(facts) {
7
+ if (facts.os !== 'Linux')
8
+ throw errors.unsupportedOs(`${facts.os} ${facts.arch}`.trim());
9
+ }
10
+ export function planNpx(input) {
11
+ const targetVersion = normalizeVersion(input.targetVersion);
12
+ if (!parseVersion(targetVersion)) {
13
+ throw errors.invalidInput('targetVersion', {
14
+ zh: `目标版本「${input.targetVersion}」不是合法版本号。`,
15
+ en: `Target version "${input.targetVersion}" is not a valid version.`,
16
+ });
17
+ }
18
+ assertSupportedRemote(input.facts);
19
+ const facts = input.facts;
20
+ if (!isNodeVersionSupported(facts.nodeVersion)) {
21
+ throw errors.remoteDshMissing({
22
+ zh: `远端 Node 不可用或版本过低(需要 ≥ 24.9.0,检测到 ${facts.nodeVersion ?? '无'}),自动准备也没有完成。请检查远端网络,或在远端安装 Node 后重试。`,
23
+ en: `The remote Node is missing or too old (>= 24.9.0 required, detected ${facts.nodeVersion ?? 'none'}) and automatic preparation did not finish. Check the remote network, or install Node on the remote and retry.`,
24
+ });
25
+ }
26
+ if (!facts.npxPath) {
27
+ throw errors.remoteDshMissing({
28
+ zh: '远端没有找到 npx。请安装 npm(随 Node 一起提供),或把 npm 的 bin 目录加入远程 shell 的 PATH。',
29
+ en: 'npx was not found on the remote. Install npm (shipped with Node) or add its bin directory to the remote shell PATH.',
30
+ });
31
+ }
32
+ if (!facts.curlPath && !facts.wgetPath) {
33
+ throw errors.remoteDshMissing({
34
+ zh: '远端既没有 curl 也没有 wget,无法在启动后探活远端界面。请安装其中之一。',
35
+ en: 'The remote has neither curl nor wget, so the remote UI cannot be health-checked after start. Install one of them.',
36
+ });
37
+ }
38
+ return {
39
+ level: 'npx',
40
+ profile: input.profile,
41
+ targetVersion,
42
+ reason: {
43
+ zh: `用 npx 精确版本 ${targetVersion} 启动远端 DSH(Node 运行时由插件准备)`,
44
+ en: `Launch the remote DSH with npx pinned to ${targetVersion} (Node runtime prepared by the plugin)`,
45
+ },
46
+ start: {
47
+ kind: 'npx',
48
+ npxPath: facts.npxPath,
49
+ nodePath: facts.nodePath ?? undefined,
50
+ nodeBinDir: facts.nodePath ? facts.nodePath.replace(/\/node$/, '') : undefined,
51
+ targetVersion,
52
+ },
53
+ };
54
+ }
55
+ /** The npx preflight: resolve and run the exact package once, so a first-run download happens in the foreground.
56
+ * `npm_config_loglevel=http` makes npm report fetches on stderr without a TTY; the caller turns those lines into
57
+ * progress. */
58
+ export function buildPreflightCommand(plan) {
59
+ const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
60
+ return `set -eu
61
+ ${pathPrefix}npm_config_loglevel=http ${shellQuote(plan.start.npxPath)} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --version`;
62
+ }
63
+ export async function verifyNpxVersion(ssh, plan, options = {}) {
64
+ const timeoutMs = options.timeoutMs ?? 0;
65
+ const result = await ssh.exec(buildPreflightCommand(plan), {
66
+ timeoutMs,
67
+ maxBytes: options.maxBytes ?? 4 * 1024 * 1024,
68
+ onStdout: options.onStdout,
69
+ onStderr: options.onStderr,
70
+ });
71
+ // `timeoutMs: 0` means "no timeout" (a cold npx download is unbounded by design); only a
72
+ // caller-supplied deadline can time out, and that is a network condition, not a missing runtime.
73
+ if (result.timedOut === true) {
74
+ throw errors.network({
75
+ zh: `远端 npx 预检超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是下载很慢或远端负载过高。`,
76
+ en: `The remote npx preflight did not finish within ${Math.round(timeoutMs / 1000)}s; the download may be slow or the remote overloaded.`,
77
+ }, { technical: `reason=preflight-timeout timeoutMs=${timeoutMs}` });
78
+ }
79
+ const combined = `${result.stdout}\n${result.stderr}`;
80
+ if (result.code !== 0) {
81
+ const failure = errors.remoteDshMissing({
82
+ zh: `无法通过 npx 运行 @deepseek-ai/dsh@${plan.start.targetVersion}(退出码 ${result.code})。请确认远端能访问 npm registry,且 Node/npm 版本满足要求。`,
83
+ en: `Could not run @deepseek-ai/dsh@${plan.start.targetVersion} through npx (exit ${result.code}). Make sure the remote can reach the npm registry and Node/npm meet the requirements.`,
84
+ });
85
+ failure.technical = headTail(combined, 1500);
86
+ throw failure;
87
+ }
88
+ const lines = String(result.stdout ?? '')
89
+ .split(/\r?\n/)
90
+ .map((line) => line.trim())
91
+ .filter(Boolean);
92
+ const reported = normalizeVersion(lines[lines.length - 1] ?? '');
93
+ if (!versionsEqual(reported, plan.targetVersion))
94
+ throw errors.versionMismatch(plan.targetVersion, reported || 'unknown');
95
+ return reported;
96
+ }
@@ -0,0 +1,21 @@
1
+ import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
2
+ import { createRuntimeEffects } from '../runtime/effects.js';
3
+ import { nowIso } from '../util.js';
4
+ /** Publish the connected state: one transition owns status/phase/progress/error, the retry-budget reset, the idle disarm, the heartbeat arm and `activeHostId`. */
5
+ export async function markConnected(ctx, runtime) {
6
+ const event = { type: 'connect.succeeded' };
7
+ await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
8
+ }
9
+ export function recordRestart(runtime, entry) {
10
+ const history = Array.isArray(runtime.restarts) ? runtime.restarts : [];
11
+ history.push({ at: nowIso(), ...entry });
12
+ runtime.restarts = history.slice(-10);
13
+ }
14
+ /** Put a host back into its connected state without pretending the launch URL changed: one `restart.resumed` transition (`keptInstance` restores the "no new instance was started" warning). */
15
+ export async function resumeConnected(ctx, runtime, keptInstance = false) {
16
+ if (runtime.desired !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null)
17
+ return false;
18
+ const event = { type: 'restart.resumed', ...(keptInstance ? { keptInstance: true } : {}) };
19
+ await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
20
+ return true;
21
+ }
@@ -0,0 +1,8 @@
1
+ import { errors } from '../errors.js';
2
+ export function planForRuntime(ctx, runtime, profile) {
3
+ const { facts } = runtime;
4
+ const targetVersion = ctx.localVersion();
5
+ if (!facts || !targetVersion)
6
+ throw errors.internal(new Error('the connected host has no recorded probe facts or local version'));
7
+ return { plan: ctx.deps.plan({ facts, targetVersion, profile }), targetVersion, facts };
8
+ }
@@ -0,0 +1,29 @@
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. */
2
+ import { errors, RemoteGoError, toErrorView } from '../errors.js';
3
+ /** The bilingual detail of "the transport this step needed is gone". */
4
+ export const SSH_CLOSED_DETAIL = {
5
+ zh: 'SSH 连接已断开,本次操作没有完成;如果主机仍在线,重连即可继续。',
6
+ en: 'SSH connection is not open; the transport closed before this step finished. Reconnect to continue.',
7
+ };
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. */
9
+ export function normalizeConnectFailure(runtime, error) {
10
+ const view = toErrorView(error);
11
+ if (runtime.transportLost === true && runtime.ssh?.connected !== true) {
12
+ if (view.code === 'host-key-unknown' || view.code === 'remote-dsh-running') {
13
+ return toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: `reason=ssh-closed phase-code=${view.code}` }));
14
+ }
15
+ }
16
+ if (runtime.ssh?.connected === true) {
17
+ if (!(error instanceof RemoteGoError) &&
18
+ /\b(?:not open|closed|ECONNRESET|EPIPE|Channel closed)\b/i.test(String(error?.message ?? ''))) {
19
+ return toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: `reason=ssh-closed cause=${error?.message ?? error}` }));
20
+ }
21
+ return view;
22
+ }
23
+ if (view.code === 'internal' || view.code === 'remote-dsh-missing' || view.code === 'remote-node-install-failed') {
24
+ return toErrorView(errors.network(SSH_CLOSED_DETAIL, {
25
+ technical: `reason=ssh-closed phase-code=${view.code} cause=${error instanceof Error ? error.message : String(error ?? '')}`,
26
+ }));
27
+ }
28
+ return view;
29
+ }
@@ -0,0 +1,36 @@
1
+ import { errors } from '../errors.js';
2
+ import { SSH_CLOSED_DETAIL } from './failures.js';
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. */
4
+ export class LinkCancelled extends Error {
5
+ constructor(reason) {
6
+ super(`connect aborted: ${reason}`);
7
+ this.name = 'LinkCancelled';
8
+ this.code = 'link-cancelled';
9
+ }
10
+ }
11
+ export function linkTaken(ctx, runtime) {
12
+ return (ctx.state.disposed === true ||
13
+ runtime.closing === true ||
14
+ runtime.desired !== 'connected' ||
15
+ !ctx.state.runtimes.has(runtime.id));
16
+ }
17
+ /** Throw unless this attempt may still write state. */
18
+ export function assertStillWanted(ctx, runtime) {
19
+ if (linkTaken(ctx, runtime))
20
+ throw new LinkCancelled('the link is no longer wanted');
21
+ }
22
+ /** Throw a typed transport error unless the SSH transport is still open. */
23
+ export function assertTransportOpen(runtime) {
24
+ if (runtime.ssh?.connected !== true)
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';
34
+ }
35
+ return null;
36
+ }
@@ -0,0 +1,70 @@
1
+ import { errors } from '../errors.js';
2
+ import { askConflict } from '../prompts.js';
3
+ import { isPid, messageOf } from '../util.js';
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. */
7
+ export async function resolveForeignConflict(ctx, runtime, layout, profile, options = {}) {
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));
12
+ try {
13
+ const registry = await ctx.deps.readRegistry(runtime.ssh, layout);
14
+ const pid = Number(registry?.pid);
15
+ if (isPid(pid) && registry?.dshHome === layout.dshHome && registry?.profile === profile)
16
+ ignorePids.push(pid);
17
+ }
18
+ catch (error) {
19
+ // swallow-ok: registry absence is normal; the scan below still finds foreign processes
20
+ ctx.progress.log(runtime, 'debug', 'foreign DSH: registry read failed:', messageOf(error));
21
+ }
22
+ const found = await ctx.deps.findForeign(runtime.ssh, { ignorePids });
23
+ const processes = found.ok === true && Array.isArray(found.processes) ? [...found.processes] : [];
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.
26
+ const known = options.knownProcess;
27
+ const knownPid = Number(known?.pid);
28
+ if (isPid(knownPid) &&
29
+ !keptAlongside.includes(knownPid) &&
30
+ !processes.some((entry) => Number(entry?.pid) === knownPid)) {
31
+ processes.push({
32
+ pid: knownPid,
33
+ command: typeof known.command === 'string' && known.command !== '' ? known.command : `dsh --profile ${profile}`,
34
+ });
35
+ }
36
+ if (found.ok !== true) {
37
+ ctx.progress.log(runtime, 'debug', 'foreign DSH: scan failed:', found.reason ?? found.technical ?? 'unknown');
38
+ if (processes.length === 0)
39
+ return null;
40
+ }
41
+ if (processes.length === 0)
42
+ return null;
43
+ const pidList = processes.map((entry) => `pid ${entry.pid}`).join(', ');
44
+ ctx.progress.log(runtime, 'warn', `foreign DSH on the remote: ${processes.length} process(es) sharing this ~/.dsh (${pidList})`);
45
+ const decision = await askConflict(ctx, runtime, processes);
46
+ // The user said no: retrying would ask the same question again (`conflict.answered` already owns the flag).
47
+ if (decision.action === 'cancel')
48
+ throw errors.remoteDshRunning();
49
+ if (decision.action === 'alongside') {
50
+ runtime.alongsidePids = processes.map((entry) => entry.pid).filter((pid) => isPid(pid));
51
+ runtime.warning = {
52
+ zh: '远端已有手工启动的 DSH;已按你的选择并存运行,两者共享 ~/.dsh,请避免同时操作同一会话。',
53
+ en: 'A manually started DSH is already running; it was kept as you chose. Both share ~/.dsh, so avoid editing the same session in both.',
54
+ };
55
+ runtime.warningSource = 'alongside';
56
+ return 'alongside';
57
+ }
58
+ const stopped = await ctx.deps.stopForeign(runtime.ssh, processes);
59
+ if (stopped.ok !== true) {
60
+ throw errors.remoteDshRunning({
61
+ zh: '远端的手工 DSH 进程没有停下来,连接已中止。',
62
+ en: 'The manual remote DSH process did not stop, so the connection was aborted.',
63
+ }, {
64
+ technical: `alive=${stopped.alive.join(',') || 'unknown'} output=${String(stopped.output ?? '').slice(0, 800)}`,
65
+ });
66
+ }
67
+ runtime.alongsidePids = [];
68
+ ctx.progress.log(runtime, 'info', `stopped ${processes.length} manual remote DSH process(es)`);
69
+ return 'stop';
70
+ }
@@ -0,0 +1,54 @@
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. */
2
+ import { beginConnectLog } from '../connect-log.js';
3
+ import { runtimeOf } from '../host-registry.js';
4
+ import { cancelIdleStop, disconnectHost, disposeSsh } from '../host-lifecycle.js';
5
+ import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
6
+ import { createRuntimeEffects } from '../runtime/effects.js';
7
+ import { isRefusal } from '../runtime/fsm.js';
8
+ import { startConnectPromise } from './pipeline.js';
9
+ /** Accept a connect request: apply the one-time inputs, stop any pending retry, and start the pipeline in the background. */
10
+ export async function startConnect(ctx, id, options = {}) {
11
+ await ctx.init();
12
+ const runtime = runtimeOf(ctx, id);
13
+ if (runtime.connectPromise)
14
+ return { accepted: false, reason: 'already-connecting' };
15
+ if (runtime.linkBusy !== null)
16
+ return { accepted: false, reason: 'already-restarting' };
17
+ if (runtime.status === 'connected' && runtime.ssh?.connected)
18
+ return { accepted: false, reason: 'already-connected' };
19
+ runtime.alongsidePids = [];
20
+ const typedPassword = typeof options.password === 'string' && options.password !== '' ? options.password : null;
21
+ if (typedPassword !== null)
22
+ runtime.password = typedPassword;
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.
25
+ runtime.savePassword = typedPassword !== null && options.rememberPassword !== false;
26
+ runtime.forgetPassword = typedPassword !== null && options.rememberPassword === false;
27
+ // This connection starts its own log, so the panel and a copied log only ever show the live attempt.
28
+ beginConnectLog(runtime);
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}` : ''})`);
33
+ const token = (Number(runtime.linkToken) || 0) + 1;
34
+ const event = { type: 'connect.requested', token };
35
+ const result = await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
36
+ run: () => startConnectPromise(ctx, runtime),
37
+ });
38
+ if (isRefusal(result)) {
39
+ // The guards above are the API-visible ones; the machine refusing here means the two disagreed.
40
+ ctx.progress.log(runtime, 'warn', `connect refused: ${result.reason}`);
41
+ return { accepted: false, reason: result.reason === 'already-connecting' ? 'already-connecting' : 'busy' };
42
+ }
43
+ return { accepted: true };
44
+ }
45
+ /** Drop the current link and connect again from scratch (the "Reconnect" button). */
46
+ export async function reconnectHost(ctx, runtime) {
47
+ await disconnectHost(ctx, runtime, { stopRemote: false });
48
+ cancelIdleStop(runtime);
49
+ await disposeSsh(runtime);
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.
52
+ await Promise.allSettled([runtime.restartPromise, runtime.reattachPromise].filter((promise) => promise && typeof promise.then === 'function'));
53
+ return startConnect(ctx, runtime.id, {});
54
+ }
@@ -0,0 +1,139 @@
1
+ import { registryNamesInstance } from '../remote-web/registry.js';
2
+ import { commandMatchesProfile } from '../remote-web/resolve.js';
3
+ import { isPid } from '../util.js';
4
+ import { readRegistryQuietly } from './registry.js';
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
+ export async function rememberLaunched(ctx, runtime, pid, layout, profile) {
11
+ if (!isPid(pid))
12
+ return null;
13
+ if (!(runtime.launched instanceof Map))
14
+ runtime.launched = new Map();
15
+ const identity = await ctx.deps.processIdentity(runtime.ssh, pid);
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 };
23
+ runtime.launched.set(pid, record);
24
+ runtime.bound = { pid, startTime: identity.startTime, origin: 'launch' };
25
+ return record;
26
+ }
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. */
28
+ export async function rememberBound(ctx, runtime, pid, layout, profile, origin) {
29
+ if (!isPid(pid))
30
+ return null;
31
+ const identity = await ctx.deps.processIdentity(runtime.ssh, pid);
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');
38
+ runtime.bound = { pid, startTime: identity.startTime, origin };
39
+ return runtime.bound;
40
+ }
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. */
42
+ export const OWNERSHIP_OPTIONS = {
43
+ restart: {
44
+ sources: ['launched'],
45
+ startTime: 'strict',
46
+ noProofReason: 'not-launched-by-this-connection',
47
+ proofBeforeAlongside: true,
48
+ requireProfile: true,
49
+ },
50
+ stop: {
51
+ sources: ['launched', 'bound'],
52
+ requireBoundPid: true,
53
+ requireRegistry: true,
54
+ startTime: 'when-recorded',
55
+ prefer: 'launched-first',
56
+ noProofReason: 'not-launched-by-this-connection',
57
+ requireProfile: true,
58
+ },
59
+ idle: {
60
+ sources: ['launched', 'bound'],
61
+ startTime: 'when-recorded',
62
+ prefer: 'bound-first',
63
+ noProofReason: 'not-owned',
64
+ },
65
+ };
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. */
67
+ export async function proveOwnership(ctx, runtime, options) {
68
+ const { pid, layout, profile } = options;
69
+ const sources = options.sources ?? ['launched'];
70
+ const prefer = options.prefer ?? 'launched-first';
71
+ const startTimeMode = options.startTime ?? 'when-recorded';
72
+ const noProofReason = options.noProofReason ?? 'not-launched-by-this-connection';
73
+ const forbidAlongside = options.forbidAlongside !== false;
74
+ const alongside = Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : [];
75
+ const launched = sources.includes('launched') && runtime.launched instanceof Map ? runtime.launched.get(pid) : undefined;
76
+ const bound = sources.includes('bound') && runtime.bound != null && Number(runtime.bound.pid) === pid ? runtime.bound : null;
77
+ const launchedProof = launched ?? null;
78
+ const proof = prefer === 'bound-first' ? (bound ?? launchedProof) : (launchedProof ?? bound);
79
+ const source = proof === null ? null : proof === launchedProof ? 'launched' : 'bound';
80
+ const evidence = {
81
+ pid,
82
+ source,
83
+ recordedStartTime: typeof proof?.startTime === 'string' ? proof.startTime : null,
84
+ identity: null,
85
+ registry: null,
86
+ layout,
87
+ profile,
88
+ };
89
+ const refuse = (reason) => ({ ok: false, reason, evidence });
90
+ if (!isPid(pid))
91
+ return refuse('pid-unknown');
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.
94
+ if (options.requireProfile === true && profile === '')
95
+ return refuse('profile-mismatch');
96
+ if (options.requireBoundPid === true && Number(runtime.remote.pid) !== pid)
97
+ return refuse('not-the-bound-instance');
98
+ const keptAlongside = forbidAlongside && alongside.includes(pid);
99
+ if (keptAlongside && options.proofBeforeAlongside !== true)
100
+ return refuse('kept-alongside');
101
+ if (proof === null)
102
+ return refuse(noProofReason);
103
+ if (keptAlongside)
104
+ return refuse('kept-alongside');
105
+ if (options.requireRegistry === true) {
106
+ const registry = await readRegistryQuietly(ctx, runtime, layout);
107
+ evidence.registry = registry;
108
+ if (!registryNamesInstance(registry, layout, profile, pid))
109
+ return refuse('registry-mismatch');
110
+ }
111
+ let identity;
112
+ try {
113
+ identity = await ctx.deps.processIdentity(runtime.ssh, pid);
114
+ }
115
+ catch {
116
+ // swallow-ok: an identity read that throws cannot prove ownership either, so nothing is signalled
117
+ return refuse('identity-unreadable');
118
+ }
119
+ evidence.identity = identity;
120
+ if (identity.ok !== true) {
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.
123
+ return refuse(identity.reason === 'missing' ? 'identity-missing' : `identity-${identity.reason}`);
124
+ }
125
+ const recorded = typeof proof.startTime === 'string' ? proof.startTime : null;
126
+ if (startTimeMode === 'strict') {
127
+ // A `launched` record always carries the start time; one without it is a broken record, so it refuses.
128
+ if (identity.startTime !== recorded)
129
+ return refuse('pid-reused');
130
+ }
131
+ else if (recorded !== null && identity.startTime !== recorded) {
132
+ return refuse('pid-reused');
133
+ }
134
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome)
135
+ return refuse('dsh-home-mismatch');
136
+ if (profile !== '' && !commandMatchesProfile(identity.command, profile))
137
+ return refuse('profile-mismatch');
138
+ return { ok: true, evidence };
139
+ }