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.
- package/README.md +11 -3
- package/{client.js → dist/client.js} +7144 -8367
- package/dist/index.js +4 -0
- package/dist/src/admission.js +21 -0
- package/dist/src/api.js +380 -0
- package/dist/src/atomic-json.js +201 -0
- package/dist/src/bootstrap.js +96 -0
- package/dist/src/connect/attach.js +21 -0
- package/dist/src/connect/bootstrap.js +8 -0
- package/dist/src/connect/failures.js +29 -0
- package/dist/src/connect/guards.js +36 -0
- package/dist/src/connect/launch.js +70 -0
- package/dist/src/connect/links.js +54 -0
- package/dist/src/connect/ownership.js +139 -0
- package/dist/src/connect/pipeline.js +376 -0
- package/dist/src/connect/reattach.js +191 -0
- package/dist/src/connect/registry.js +10 -0
- package/dist/src/connect/repair.js +97 -0
- package/dist/src/connect/restart.js +255 -0
- package/dist/src/connect/stop.js +164 -0
- package/dist/src/connect/transport.js +101 -0
- package/dist/src/connect/verify.js +30 -0
- package/dist/src/connect/watchdog.js +44 -0
- package/dist/src/connect-log.js +137 -0
- package/dist/src/connect-progress.js +110 -0
- package/dist/src/constants.js +29 -0
- package/dist/src/context.js +96 -0
- package/dist/src/diagnostics.js +133 -0
- package/dist/src/download-jobs.js +221 -0
- package/dist/src/errors.js +228 -0
- package/dist/src/events.js +326 -0
- package/dist/src/host-lifecycle.js +368 -0
- package/dist/src/host-registry.js +181 -0
- package/dist/src/host-runtime.js +77 -0
- package/dist/src/host-view.js +52 -0
- package/dist/src/index.js +196 -0
- package/dist/src/kernel-adapter.js +388 -0
- package/dist/src/key-files.js +39 -0
- package/dist/src/known-hosts.js +104 -0
- package/dist/src/layout.js +26 -0
- package/dist/src/local-download.js +311 -0
- package/dist/src/local-ssh.js +23 -0
- package/dist/src/local-version.js +87 -0
- package/dist/src/node/download.js +157 -0
- package/dist/src/node-runtime.js +327 -0
- package/dist/src/probe.js +95 -0
- package/dist/src/prompts.js +198 -0
- package/dist/src/proxy/cookies.js +102 -0
- package/dist/src/proxy/headers.js +167 -0
- package/dist/src/proxy/http.js +134 -0
- package/dist/src/proxy/index.js +121 -0
- package/dist/src/proxy/limits.js +6 -0
- package/dist/src/proxy/routes.js +32 -0
- package/dist/src/proxy/upgrade.js +160 -0
- package/dist/src/redact.js +85 -0
- package/dist/src/remote-files.js +60 -0
- package/dist/src/remote-path.js +82 -0
- package/dist/src/remote-proc.js +271 -0
- package/dist/src/remote-web/registry.js +107 -0
- package/dist/src/remote-web/resolve.js +229 -0
- package/dist/src/remote-web/start.js +190 -0
- package/dist/src/remote-web/stop.js +74 -0
- package/dist/src/request-trust.js +70 -0
- package/dist/src/runtime/dispatch.js +200 -0
- package/dist/src/runtime/effects.js +81 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +70 -0
- package/dist/src/runtime/rules.js +480 -0
- package/dist/src/secrets.js +119 -0
- package/dist/src/service.js +300 -0
- package/dist/src/settings.js +143 -0
- package/dist/src/ssh-config.js +257 -0
- package/dist/src/ssh-failures.js +71 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +258 -0
- package/dist/src/ssh.js +395 -0
- package/dist/src/store.js +174 -0
- package/dist/src/tool-shared.js +146 -0
- package/dist/src/tools-exec-policy.js +121 -0
- package/dist/src/tools-exec.js +307 -0
- package/dist/src/tools-report.js +357 -0
- package/dist/src/tools.js +337 -0
- package/dist/src/tunnel.js +111 -0
- package/dist/src/util.js +112 -0
- package/dist/src/version.js +108 -0
- package/dist/src/watchdog-bus.js +21 -0
- package/dist/src/watchdog.js +116 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/constants.js +0 -93
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { REMOTE_START_TIMEOUT_MS, SSH_READY_TIMEOUT_MS } from '../constants.js';
|
|
2
|
+
import { beginConnectLog } from '../connect-log.js';
|
|
3
|
+
import { errors } from '../errors.js';
|
|
4
|
+
import { disposeSsh, scheduleReconnect } from '../host-lifecycle.js';
|
|
5
|
+
import { layoutForRuntime } from '../layout.js';
|
|
6
|
+
import { applyManagedNodeFacts, managedNodeVersionFromEngine } from '../node-runtime.js';
|
|
7
|
+
import { requestHostKey } from '../prompts.js';
|
|
8
|
+
import { registryNamesInstance } from '../remote-web/registry.js';
|
|
9
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
10
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
11
|
+
import { messageOf, nowIso } from '../util.js';
|
|
12
|
+
import { normalizeVersion, versionsEqual } from '../version.js';
|
|
13
|
+
import { markConnected } from './attach.js';
|
|
14
|
+
import { normalizeConnectFailure } from './failures.js';
|
|
15
|
+
import { LinkCancelled, assertStillWanted, assertTransportOpen, linkTaken } from './guards.js';
|
|
16
|
+
import { PATCHED_CARRIER_NOTE, resolveForeignConflict } from './launch.js';
|
|
17
|
+
import { rememberBound, rememberLaunched } from './ownership.js';
|
|
18
|
+
import { captureFingerprint, knownFingerprintsFor, openTunnelFor, resolveTargetForRuntime, settlePasswordStorage, } from './transport.js';
|
|
19
|
+
import { verifyRemoteUi } from './verify.js';
|
|
20
|
+
/** Start the pipeline in the background and keep its promise off the rejection path, so a listener or a step outside its error handling cannot become an unhandled rejection. */
|
|
21
|
+
export function startConnectPromise(ctx, runtime) {
|
|
22
|
+
const run = connectPipeline(ctx, runtime).catch((error) => {
|
|
23
|
+
ctx.progress.log(runtime, 'debug', 'connect pipeline stopped outside its error path:', messageOf(error));
|
|
24
|
+
});
|
|
25
|
+
runtime.connectPromise = run;
|
|
26
|
+
void run.finally(() => {
|
|
27
|
+
if (runtime.connectPromise === run)
|
|
28
|
+
runtime.connectPromise = null;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** Re-enter the pipeline after a dropped link, as a `connect.requested` with `retry: true`: it publishes `connecting` and clears the previous failure but must not reset the retry budget the user's connect set. */
|
|
32
|
+
async function reconnectNow(ctx, runtime) {
|
|
33
|
+
if (ctx.state.disposed || runtime.desired !== 'connected')
|
|
34
|
+
return;
|
|
35
|
+
await disposeSsh(runtime);
|
|
36
|
+
// A dropped link's retry is a new connection too: start from a clean log.
|
|
37
|
+
beginConnectLog(runtime);
|
|
38
|
+
const event = { type: 'connect.requested', token: Number(runtime.linkToken) || 0, retry: true };
|
|
39
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
40
|
+
run: () => startConnectPromise(ctx, runtime),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/** A timer callback that starts a retry: report a throw instead of leaving it unhandled. */
|
|
44
|
+
function retryNow(ctx, runtime) {
|
|
45
|
+
void reconnectNow(ctx, runtime).catch((error) => {
|
|
46
|
+
ctx.progress.log(runtime, 'warn', 'the automatic retry could not start:', messageOf(error));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/** Watch one transport for its close; attached before `connect()` so a drop while a host-key prompt is parked resolves that prompt instead of stalling the pipeline. */
|
|
50
|
+
function watchTransport(ctx, runtime, ssh) {
|
|
51
|
+
if (!ssh || typeof ssh.on !== 'function')
|
|
52
|
+
return;
|
|
53
|
+
ssh.on('close', () => {
|
|
54
|
+
// A transport this runtime no longer dials (replaced, or disposed before a new attempt) is not a lost link.
|
|
55
|
+
if (runtime.ssh !== ssh && runtime.jumpSsh !== ssh)
|
|
56
|
+
return;
|
|
57
|
+
if (runtime.closing || runtime.desired !== 'connected')
|
|
58
|
+
return;
|
|
59
|
+
const event = { type: 'transport.closed', transport: ssh };
|
|
60
|
+
void dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
61
|
+
caller: 'callback',
|
|
62
|
+
}).then((result) => {
|
|
63
|
+
// The rule only says "a retry makes sense"; `scheduleReconnect` owns the delay, the budget and the switch.
|
|
64
|
+
const wantsRetry = result.ok && result.effects.some((effect) => effect.type === 'arm' && effect.timer === 'reconnect');
|
|
65
|
+
if (wantsRetry)
|
|
66
|
+
scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime));
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** The dial: direct, or through a jump host with a forwarded stream. The two are separate security contexts, each with its own policy, pin and `onHostKey` role, so a key confirmed for one can never be checked against, or written into, the other. It reads only Config/Transport/Reporter/Store itself but hands `ctx` to `watchTransport`, whose close listener re-enters the pipeline, so the parameter cannot be narrowed. */
|
|
71
|
+
async function openTransport(ctx, runtime, target) {
|
|
72
|
+
const settings = ctx.settings();
|
|
73
|
+
const auth = () => ({
|
|
74
|
+
type: runtime.entry.auth?.type ?? 'key',
|
|
75
|
+
keyPath: runtime.entry.auth?.keyPath ?? null,
|
|
76
|
+
password: runtime.password ?? null,
|
|
77
|
+
});
|
|
78
|
+
const buildOptions = (resolved, role, sock) => {
|
|
79
|
+
const isJump = role === 'jump';
|
|
80
|
+
const resolvedPort = resolved.port ?? 22;
|
|
81
|
+
const hostKeyPolicy = isJump ? settings.hostKeyPolicy : (runtime.entry.hostKeyPolicy ?? settings.hostKeyPolicy);
|
|
82
|
+
const jumpPinMatches = isJump &&
|
|
83
|
+
runtime.jumpFingerprint?.host === resolved.host &&
|
|
84
|
+
(Number(runtime.jumpFingerprint?.port) || 22) === resolvedPort;
|
|
85
|
+
const pinnedFingerprint = isJump
|
|
86
|
+
? jumpPinMatches
|
|
87
|
+
? (runtime.jumpFingerprint?.pinned ?? null)
|
|
88
|
+
: null
|
|
89
|
+
: (runtime.entry.pinnedFingerprint ?? null);
|
|
90
|
+
return {
|
|
91
|
+
host: resolved.host,
|
|
92
|
+
port: resolvedPort,
|
|
93
|
+
username: resolved.username ?? resolved.user ?? null,
|
|
94
|
+
home: ctx.userHome(),
|
|
95
|
+
auth: auth(),
|
|
96
|
+
identityFiles: resolved.identityFiles ?? [],
|
|
97
|
+
hostKeyPolicy,
|
|
98
|
+
pinnedFingerprint,
|
|
99
|
+
knownHostFingerprints: resolved.knownFingerprints ?? [],
|
|
100
|
+
acceptUnknownHostKey: false,
|
|
101
|
+
readyTimeoutMs: settings.connectTimeoutSec * 1000 || SSH_READY_TIMEOUT_MS,
|
|
102
|
+
...(sock ? { sock } : {}),
|
|
103
|
+
onHostKey: (info) => requestHostKey(ctx, runtime, info, { role, host: resolved.host, port: resolvedPort }),
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
if (!target.jumpHost) {
|
|
107
|
+
runtime.ssh = ctx.deps.sshFactory(buildOptions(target, 'target'));
|
|
108
|
+
watchTransport(ctx, runtime, runtime.ssh);
|
|
109
|
+
ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host });
|
|
110
|
+
captureFingerprint(ctx, runtime, await runtime.ssh.connect());
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.jumpHost.host, jump: true });
|
|
114
|
+
const jumpMaterial = await ctx.deps.loadSshMaterial({ home: ctx.userHome() });
|
|
115
|
+
const jumpTarget = {
|
|
116
|
+
...target.jumpHost,
|
|
117
|
+
username: target.jumpHost.user ?? target.username,
|
|
118
|
+
knownFingerprints: knownFingerprintsFor(jumpMaterial, target.jumpHost.host, target.jumpHost.port ?? 22),
|
|
119
|
+
};
|
|
120
|
+
const rememberedJump = runtime.jumpFingerprint;
|
|
121
|
+
const rememberedJumpPort = (Number(rememberedJump?.port) || 22) === (jumpTarget.port ?? 22);
|
|
122
|
+
if (rememberedJump !== null && (!rememberedJumpPort || rememberedJump.host !== jumpTarget.host)) {
|
|
123
|
+
ctx.progress.log(runtime, 'info', `the jump host changed (${rememberedJump.host ?? 'unknown'} -> ${jumpTarget.host}); forgetting its previous host key`);
|
|
124
|
+
runtime.jumpFingerprint = null;
|
|
125
|
+
}
|
|
126
|
+
runtime.jumpSsh = ctx.deps.sshFactory(buildOptions(jumpTarget, 'jump'));
|
|
127
|
+
watchTransport(ctx, runtime, runtime.jumpSsh);
|
|
128
|
+
await runtime.jumpSsh.connect();
|
|
129
|
+
runtime.fingerprint = null;
|
|
130
|
+
ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host, via: target.jumpHost.host });
|
|
131
|
+
const stream = await runtime.jumpSsh.forwardOut(target.host, target.port ?? 22);
|
|
132
|
+
runtime.ssh = ctx.deps.sshFactory(buildOptions(target, 'target', stream));
|
|
133
|
+
watchTransport(ctx, runtime, runtime.ssh);
|
|
134
|
+
captureFingerprint(ctx, runtime, await runtime.ssh.connect());
|
|
135
|
+
}
|
|
136
|
+
async function connectPipeline(ctx, runtime) {
|
|
137
|
+
const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
|
|
138
|
+
const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
|
|
139
|
+
// Guards after every await: the link must still be wanted and the transport open, so a late write cannot revive it.
|
|
140
|
+
const gate = () => {
|
|
141
|
+
assertStillWanted(ctx, runtime);
|
|
142
|
+
assertTransportOpen(runtime);
|
|
143
|
+
};
|
|
144
|
+
// Every attempt entered through `connect.requested`, which owns `closing`, `transportLost`, the disarms and the card.
|
|
145
|
+
runtime.alongsidePids = [];
|
|
146
|
+
runtime.launched = new Map();
|
|
147
|
+
runtime.bound = null;
|
|
148
|
+
runtime.tunnelRepairFailures = 0;
|
|
149
|
+
runtime.nextTunnelRepairAt = 0;
|
|
150
|
+
let remoteStarted = false;
|
|
151
|
+
let layout = null;
|
|
152
|
+
let transportUp = false;
|
|
153
|
+
try {
|
|
154
|
+
const target = await resolveTargetForRuntime(ctx, runtime);
|
|
155
|
+
assertStillWanted(ctx, runtime);
|
|
156
|
+
const { host: targetHost, port: targetPort, username } = target;
|
|
157
|
+
const viaJump = target.jumpHost ? ` via ${target.jumpHost.host}` : '';
|
|
158
|
+
log('debug', `target resolved: ${username ?? '(default)'}@${targetHost}:${targetPort}${viaJump}`);
|
|
159
|
+
if (runtime.entry.auth?.type === 'password' && !runtime.password && ctx.secrets) {
|
|
160
|
+
const remembered = await ctx.secrets.get(runtime.id);
|
|
161
|
+
if (remembered) {
|
|
162
|
+
runtime.password = remembered;
|
|
163
|
+
runtime.passwordSaved = true;
|
|
164
|
+
}
|
|
165
|
+
assertStillWanted(ctx, runtime);
|
|
166
|
+
}
|
|
167
|
+
phase('ssh', 'ssh-connecting', { host: runtime.entry.name });
|
|
168
|
+
// An idle host keeps its SSH session for a fast resume; this attempt replaces it, so release it, do not leak it.
|
|
169
|
+
if (runtime.ssh !== null || runtime.jumpSsh !== null) {
|
|
170
|
+
log('debug', 'releasing the transport kept by the idle policy before dialling again');
|
|
171
|
+
await disposeSsh(runtime);
|
|
172
|
+
assertStillWanted(ctx, runtime);
|
|
173
|
+
}
|
|
174
|
+
await openTransport(ctx, runtime, target);
|
|
175
|
+
gate();
|
|
176
|
+
transportUp = true;
|
|
177
|
+
const fingerprint = runtime.fingerprint?.sha256 ?? 'unknown';
|
|
178
|
+
log('info', `SSH connected to ${targetHost}:${targetPort} as ${username ?? '(default)'} (fingerprint ${fingerprint})`);
|
|
179
|
+
// SSH accepted the credential: prove the password now, before a later bootstrap failure makes the user retype it.
|
|
180
|
+
await settlePasswordStorage(ctx, runtime, log);
|
|
181
|
+
assertStillWanted(ctx, runtime);
|
|
182
|
+
phase('probe', 'probing');
|
|
183
|
+
let facts = await ctx.deps.probe(runtime.ssh);
|
|
184
|
+
gate();
|
|
185
|
+
const freeGb = Math.round(Number(facts.diskFreeKb ?? 0) / 1_048_576);
|
|
186
|
+
log('debug', `probe: ${facts.os}/${facts.arch} · ${String(facts.osName ?? 'unknown OS')} · node ${facts.nodeVersion ?? 'not found'} · ${freeGb} GB free`);
|
|
187
|
+
const profile = ctx.settings().bootstrap.profile;
|
|
188
|
+
const managedVersion = managedNodeVersionFromEngine(ctx.engineNodeRange());
|
|
189
|
+
// A probe that did not report $HOME cannot address the remote layout: `layoutForRuntime` throws.
|
|
190
|
+
const nodeLayout = layoutForRuntime({ facts });
|
|
191
|
+
log('info', `managed Node: expecting v${managedVersion} in ${nodeLayout.nodeDir}`);
|
|
192
|
+
const managed = await ctx.deps.ensureNode(runtime.ssh, {
|
|
193
|
+
facts,
|
|
194
|
+
layout: nodeLayout,
|
|
195
|
+
version: managedVersion,
|
|
196
|
+
onProgress: (event) => ctx.progress.nodeProgress(runtime, event),
|
|
197
|
+
});
|
|
198
|
+
gate();
|
|
199
|
+
// The probe reported every field, so the merged object is a full `RemoteFacts`.
|
|
200
|
+
facts = applyManagedNodeFacts(facts, managed);
|
|
201
|
+
const { version: nodeVersion, installed, nodeBinDir } = managed;
|
|
202
|
+
log('info', `managed Node ${nodeVersion}${installed ? ' installed' : ' reused'} at ${nodeBinDir}`);
|
|
203
|
+
runtime.facts = facts;
|
|
204
|
+
const targetVersion = ctx.localVersion();
|
|
205
|
+
if (!targetVersion) {
|
|
206
|
+
throw errors.invalidInput('version', {
|
|
207
|
+
zh: '无法确定本机 DSH 版本,无法用 npx 固定同版本启动远端。请从 DSH 界面启动本插件,让 Host 读到本机版本。',
|
|
208
|
+
en: 'The local DSH version is unknown, so the remote cannot be pinned to the same version. Start the plugin from the DSH UI so the Host can read the local version.',
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
const plan = ctx.deps.plan({ facts, targetVersion, profile });
|
|
212
|
+
log('info', `runtime plan ${plan.level}: ${plan.reason.en}`);
|
|
213
|
+
phase('start', 'starting-remote', { level: plan.level });
|
|
214
|
+
layout = layoutForRuntime(runtime);
|
|
215
|
+
// Adopt an instance left by a previous local process before the npx preflight: adoption must not need the registry.
|
|
216
|
+
let webInfo = null;
|
|
217
|
+
try {
|
|
218
|
+
const adopted = await ctx.deps.adopt(runtime.ssh, layout, { profile });
|
|
219
|
+
const adoptedVersion = adopted?.version ? normalizeVersion(adopted.version) : null;
|
|
220
|
+
const mismatch = `running remote web version ${adoptedVersion} != ${targetVersion}`;
|
|
221
|
+
if (adopted && (!adoptedVersion || versionsEqual(adoptedVersion, targetVersion))) {
|
|
222
|
+
webInfo = { ...adopted, logPath: layout.logFile, startedAt: nowIso(), rawLine: '' };
|
|
223
|
+
log('info', `adopted running remote web pid=${adopted.pid} port=${adopted.port}`);
|
|
224
|
+
// Only a launch record proves the process is ours to stop; a re-attached one is merely hosted.
|
|
225
|
+
if (adopted.origin !== 'reattach')
|
|
226
|
+
await rememberLaunched(ctx, runtime, adopted.pid, layout, profile);
|
|
227
|
+
else
|
|
228
|
+
await rememberBound(ctx, runtime, adopted.pid, layout, profile, 'reattach');
|
|
229
|
+
}
|
|
230
|
+
else if (adopted && adopted.origin !== 'reattach') {
|
|
231
|
+
log('info', `${mismatch}; stopping it and starting a matching instance`);
|
|
232
|
+
try {
|
|
233
|
+
// The old process owns the same `~/.dsh` profile: leaving it next to the new one would share session files.
|
|
234
|
+
await ctx.deps.stopWeb(runtime.ssh, layout, { pid: adopted.pid });
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
log('warn', 'could not stop the stale remote web:', messageOf(error));
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
else if (adopted) {
|
|
241
|
+
log('warn', `${mismatch}, but it was only re-attached; leaving it running`);
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
log('debug', 'adopt: no running remote web to reuse');
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
log('debug', 'adopt check failed:', messageOf(error));
|
|
249
|
+
}
|
|
250
|
+
gate();
|
|
251
|
+
if (!webInfo) {
|
|
252
|
+
// A row we refused to adopt still names a process on this ~/.dsh profile: two clients must not write the same session files.
|
|
253
|
+
const leftover = await ctx.deps.readRegistry(runtime.ssh, layout);
|
|
254
|
+
assertStillWanted(ctx, runtime);
|
|
255
|
+
const leftoverPid = Number(leftover?.pid ?? 0);
|
|
256
|
+
if (leftover?.origin === 'reattach') {
|
|
257
|
+
log('info', `leaving a re-attached remote web instance alone (pid ${leftoverPid || 'unknown'})`);
|
|
258
|
+
}
|
|
259
|
+
else if (registryNamesInstance(leftover, layout, profile, leftoverPid)) {
|
|
260
|
+
try {
|
|
261
|
+
await ctx.deps.stopWeb(runtime.ssh, layout, { pid: leftoverPid });
|
|
262
|
+
log('info', `stopped a non-adoptable remote web instance pid=${leftoverPid}`);
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
log('warn', 'could not stop the non-adoptable remote web:', messageOf(error));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
await resolveForeignConflict(ctx, runtime, layout, profile);
|
|
269
|
+
gate();
|
|
270
|
+
phase('bootstrap', 'bootstrapping', { level: plan.level });
|
|
271
|
+
// Resolve the exact package in the foreground first: a cold npx download belongs in the connect error, not in a
|
|
272
|
+
// detached process that only leaves a log behind.
|
|
273
|
+
log('info', `npx preflight: resolving @deepseek-ai/dsh@${plan.start.targetVersion}`);
|
|
274
|
+
const onStdout = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion);
|
|
275
|
+
const onStderr = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion);
|
|
276
|
+
await ctx.deps.preflight(runtime.ssh, plan, { onStdout, onStderr });
|
|
277
|
+
gate();
|
|
278
|
+
log('info', `npx preflight ready: @deepseek-ai/dsh@${plan.start.targetVersion}`);
|
|
279
|
+
phase('start', 'starting-remote', { level: plan.level });
|
|
280
|
+
webInfo = await ctx.deps.startWeb(runtime.ssh, {
|
|
281
|
+
plan,
|
|
282
|
+
layout,
|
|
283
|
+
profile,
|
|
284
|
+
timeoutMs: REMOTE_START_TIMEOUT_MS,
|
|
285
|
+
onLine: (line) => log('debug', `remote: ${line}`),
|
|
286
|
+
});
|
|
287
|
+
log('info', `remote DSH started: pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`);
|
|
288
|
+
}
|
|
289
|
+
gate();
|
|
290
|
+
if (webInfo.browserCarrier === 'patched')
|
|
291
|
+
log('info', PATCHED_CARRIER_NOTE);
|
|
292
|
+
remoteStarted = true;
|
|
293
|
+
if (webInfo.adopted !== true)
|
|
294
|
+
await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile);
|
|
295
|
+
assertStillWanted(ctx, runtime);
|
|
296
|
+
runtime.token = webInfo.token;
|
|
297
|
+
runtime.remote = {
|
|
298
|
+
version: targetVersion,
|
|
299
|
+
uiReady: false,
|
|
300
|
+
localPort: null,
|
|
301
|
+
port: webInfo.port,
|
|
302
|
+
pid: webInfo.pid ?? null,
|
|
303
|
+
dshHome: layout.dshHome,
|
|
304
|
+
profile,
|
|
305
|
+
bootstrapLevel: plan.level,
|
|
306
|
+
nodeVersion: facts.nodeVersion,
|
|
307
|
+
nodeSource: 'managed',
|
|
308
|
+
startedAt: webInfo.startedAt ?? nowIso(),
|
|
309
|
+
viewRev: Number(runtime.remote.viewRev) || 0,
|
|
310
|
+
};
|
|
311
|
+
phase('tunnel', 'tunneling');
|
|
312
|
+
const tunnel = await openTunnelFor(ctx, runtime, webInfo.port);
|
|
313
|
+
assertStillWanted(ctx, runtime);
|
|
314
|
+
phase('verifying', 'verifying');
|
|
315
|
+
await verifyRemoteUi(ctx, runtime, webInfo.port, webInfo.token, tunnel.localPort);
|
|
316
|
+
gate();
|
|
317
|
+
// The remote UI is reachable both ways (desktop guest and same-origin proxy): the exchange proves the launch token.
|
|
318
|
+
runtime.remote.uiReady = true;
|
|
319
|
+
await ctx.store.patchHost(runtime.id, { lastOpenedAt: nowIso() });
|
|
320
|
+
gate();
|
|
321
|
+
// The store write is an await: a disconnect may land meanwhile, and a late write must not resurrect the link.
|
|
322
|
+
runtime.entry = ctx.store.getHost(runtime.id) ?? runtime.entry;
|
|
323
|
+
if (ctx.settings().saveTokens) {
|
|
324
|
+
await ctx.store.saveToken(runtime.id, webInfo.token);
|
|
325
|
+
assertStillWanted(ctx, runtime);
|
|
326
|
+
}
|
|
327
|
+
gate();
|
|
328
|
+
// Last gate before publishing: never report a host the user just removed or a tunnel this pipeline no longer owns.
|
|
329
|
+
await markConnected(ctx, runtime);
|
|
330
|
+
const localPort = runtime.tunnel?.localPort ?? runtime.remote.localPort ?? '?';
|
|
331
|
+
log('info', `connected: remote ${runtime.remote.version} on 127.0.0.1:${localPort}`);
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
// Phase is cleared with the status; capture it first so the log says where it stopped.
|
|
335
|
+
const failedPhase = runtime.phase;
|
|
336
|
+
// The link was up earlier in this attempt and is gone now: it dropped, which is what the retry policy is for.
|
|
337
|
+
const droppedTransport = runtime.transportLost === true || (transportUp === true && runtime.ssh?.connected !== true);
|
|
338
|
+
// The transition owns the state, the teardown and the failure lines; the caller keeps only its own
|
|
339
|
+
// publication point.
|
|
340
|
+
const cancelled = error instanceof LinkCancelled || linkTaken(ctx, runtime);
|
|
341
|
+
// The user's "no" is read before the failure transition clears the flag: a refused prompt is final.
|
|
342
|
+
const saidNo = runtime.connectCancelled === true;
|
|
343
|
+
const event = cancelled
|
|
344
|
+
? { type: 'connect.cancelled' }
|
|
345
|
+
: { type: 'connect.failed', view: normalizeConnectFailure(runtime, error), phase: failedPhase };
|
|
346
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
347
|
+
caller: 'script',
|
|
348
|
+
emit: false,
|
|
349
|
+
teardown: {
|
|
350
|
+
stopRemote: remoteStarted && runtime.entry.keepAlive === 'stop',
|
|
351
|
+
keepRemote: remoteStarted && runtime.entry.keepAlive !== 'stop',
|
|
352
|
+
},
|
|
353
|
+
});
|
|
354
|
+
if (cancelled)
|
|
355
|
+
log('info', 'connect cancelled by disconnect');
|
|
356
|
+
// One place decides whether a failed attempt is retried, and the budget lives in `scheduleReconnect`.
|
|
357
|
+
if (!cancelled) {
|
|
358
|
+
const retryable = runtime.error?.retryable !== false && !saidNo;
|
|
359
|
+
const repairAttempt = (Number(runtime.reconnectAttempts) || 0) > 0;
|
|
360
|
+
if (retryable && (repairAttempt || droppedTransport))
|
|
361
|
+
scheduleConnectRetry(ctx, runtime);
|
|
362
|
+
}
|
|
363
|
+
ctx.emitState();
|
|
364
|
+
}
|
|
365
|
+
finally {
|
|
366
|
+
runtime.connectPromise = null;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/** Arm the next automatic attempt; `scheduleReconnect` owns the settings gate and the budget, so a spent budget is reported once. */
|
|
370
|
+
function scheduleConnectRetry(ctx, runtime) {
|
|
371
|
+
if (ctx.state.disposed === true || runtime.desired !== 'connected')
|
|
372
|
+
return;
|
|
373
|
+
if (!runtime.entry.autoReconnect || !ctx.settings().autoReconnect.enabled)
|
|
374
|
+
return;
|
|
375
|
+
scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime));
|
|
376
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/** The re-attach to a remote web that restarted on its own (plugin-market update, supervisor, remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel, take the new launch token and verify. The SSH session and the host entry are untouched. */
|
|
2
|
+
import { REMOTE_REATTACH_ATTEMPTS, REMOTE_REATTACH_INTERVAL_MS } from '../constants.js';
|
|
3
|
+
import { errors, toErrorView } from '../errors.js';
|
|
4
|
+
import { closeTunnel, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
|
|
5
|
+
import { layoutForRuntime } from '../layout.js';
|
|
6
|
+
import { buildRunRegistryRecord } from '../remote-web/registry.js';
|
|
7
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
8
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
9
|
+
import { nowIso, sleep } from '../util.js';
|
|
10
|
+
import { normalizeVersion, versionsEqual } from '../version.js';
|
|
11
|
+
import { markConnected, recordRestart } from './attach.js';
|
|
12
|
+
import { SSH_CLOSED_DETAIL } from './failures.js';
|
|
13
|
+
import { LinkCancelled, linkActionState } from './guards.js';
|
|
14
|
+
import { rememberBound } from './ownership.js';
|
|
15
|
+
import { openTunnelFor } from './transport.js';
|
|
16
|
+
import { verifyRemoteUi } from './verify.js';
|
|
17
|
+
export async function reattachHost(ctx, runtime, info = {}) {
|
|
18
|
+
if (linkActionState(runtime) !== 'connected')
|
|
19
|
+
return { accepted: false, reason: 'not-connected' };
|
|
20
|
+
if (runtime.connectPromise || runtime.linkBusy !== null)
|
|
21
|
+
return { accepted: false, reason: 'busy' };
|
|
22
|
+
const token = (Number(runtime.linkToken) || 0) + 1;
|
|
23
|
+
const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable';
|
|
24
|
+
// One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`); the token
|
|
25
|
+
// is the old `beginLinkWork` one so the late-write filter keeps its semantics.
|
|
26
|
+
const event = { type: 'reattach.requested', token, reason };
|
|
27
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
28
|
+
caller: 'script',
|
|
29
|
+
run: (activity, started) => {
|
|
30
|
+
if (activity !== 'reattach')
|
|
31
|
+
return;
|
|
32
|
+
const work = runReattach(ctx, runtime, info, started);
|
|
33
|
+
runtime.reattachPromise = work;
|
|
34
|
+
void work.finally(() => {
|
|
35
|
+
endLinkWork(runtime, started);
|
|
36
|
+
if (runtime.reattachPromise === work)
|
|
37
|
+
runtime.reattachPromise = null;
|
|
38
|
+
});
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
return { accepted: true };
|
|
42
|
+
}
|
|
43
|
+
async function runReattach(ctx, runtime, info, token) {
|
|
44
|
+
const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
|
|
45
|
+
const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
|
|
46
|
+
const layout = layoutForRuntime(runtime);
|
|
47
|
+
const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile;
|
|
48
|
+
const fromPort = runtime.remote.port;
|
|
49
|
+
const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable';
|
|
50
|
+
let tunnelCreated = false;
|
|
51
|
+
try {
|
|
52
|
+
log('info', `remote restart suspected: ${reason}; re-reading the remote state`);
|
|
53
|
+
const attempts = Math.max(1, Number(ctx.timers.reattachAttempts) || REMOTE_REATTACH_ATTEMPTS);
|
|
54
|
+
const intervalMs = Math.max(0, Number(ctx.timers.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS) || 0);
|
|
55
|
+
let resolved = null;
|
|
56
|
+
// A restart takes a moment to print its new readiness line: retry before giving up.
|
|
57
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
58
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
59
|
+
return;
|
|
60
|
+
resolved = await ctx.deps.resolveRemote(runtime.ssh, layout, { profile });
|
|
61
|
+
if (resolved?.ok === true)
|
|
62
|
+
break;
|
|
63
|
+
const why = resolved?.reason ?? 'unreadable';
|
|
64
|
+
log('debug', `re-attach: remote state not ready yet (${why}), attempt ${attempt}/${attempts}`);
|
|
65
|
+
if (attempt < attempts && intervalMs > 0)
|
|
66
|
+
await sleep(intervalMs);
|
|
67
|
+
}
|
|
68
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
69
|
+
return;
|
|
70
|
+
if (resolved?.ok !== true) {
|
|
71
|
+
const detail = resolved?.reason === 'no-token'
|
|
72
|
+
? {
|
|
73
|
+
zh: '远端 DSH 仍在运行,但它这次重启没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
|
|
74
|
+
en: 'The remote DSH is still running, but its restart left no usable launch token, so it cannot be re-attached; use "Restart" or Reconnect.',
|
|
75
|
+
}
|
|
76
|
+
: {
|
|
77
|
+
zh: `远端 DSH 重启后没有找到可以重新挂载的实例(${resolved?.reason ?? 'unreadable'});主机与配置已保留。`,
|
|
78
|
+
en: `No re-attachable remote DSH instance was found after the restart (${resolved?.reason ?? 'unreadable'}); the host and its settings are kept.`,
|
|
79
|
+
};
|
|
80
|
+
throw errors.remoteUnreachable(detail, {
|
|
81
|
+
technical: `reason=${resolved?.reason ?? 'unknown'} fromPort=${fromPort ?? 'unknown'}`,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
// A takeover needs the new launch token: a real DSH rejects `/?token=` and a cookie-less request,
|
|
85
|
+
// so an empty token can never be treated as success.
|
|
86
|
+
if (typeof resolved.token !== 'string' || resolved.token === '') {
|
|
87
|
+
throw errors.remoteUnreachable({
|
|
88
|
+
zh: '远端 DSH 重启后没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
|
|
89
|
+
en: 'The restarted remote DSH left no usable launch token, so it cannot be re-attached; use "Restart" or Reconnect.',
|
|
90
|
+
}, { technical: `reason=no-token source=${resolved.source ?? 'unknown'} port=${resolved.port ?? 'unknown'}` });
|
|
91
|
+
}
|
|
92
|
+
const targetVersion = ctx.localVersion();
|
|
93
|
+
const remoteVersion = typeof resolved.version === 'string' && resolved.version !== '' ? normalizeVersion(resolved.version) : null;
|
|
94
|
+
// A different DSH under the same ~/.dsh would show a UI that does not match this machine; the
|
|
95
|
+
// user's remedy is the explicit restart, which launches the pinned version.
|
|
96
|
+
if (remoteVersion && targetVersion && !versionsEqual(remoteVersion, targetVersion)) {
|
|
97
|
+
throw errors.versionMismatch(targetVersion, remoteVersion);
|
|
98
|
+
}
|
|
99
|
+
if (remoteVersion === null)
|
|
100
|
+
log('warn', 're-attach: the running DSH version could not be proven; keeping it unknown, not assuming the local one');
|
|
101
|
+
// The pid that listens may differ from the wrapper this connection launched (npx spawns the DSH):
|
|
102
|
+
// keep the kill right only for the pid we are now attached to.
|
|
103
|
+
if (runtime.launched instanceof Map) {
|
|
104
|
+
for (const pid of [...runtime.launched.keys()]) {
|
|
105
|
+
if (pid !== resolved.pid)
|
|
106
|
+
runtime.launched.delete(pid);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
log('info', `re-attach: found remote web pid=${resolved.pid} port=${resolved.port} (source=${resolved.source}); refreshing the run registry`);
|
|
110
|
+
const record = buildRunRegistryRecord({
|
|
111
|
+
pid: resolved.pid,
|
|
112
|
+
port: resolved.port,
|
|
113
|
+
// Never launder an unproven version into the registry.
|
|
114
|
+
version: remoteVersion ?? '',
|
|
115
|
+
profile,
|
|
116
|
+
dshHome: layout.dshHome,
|
|
117
|
+
origin: 'reattach',
|
|
118
|
+
});
|
|
119
|
+
const written = await ctx.deps.writeRegistry(runtime.ssh, layout, record);
|
|
120
|
+
if (written.ok === true)
|
|
121
|
+
log('info', `re-attach: run registry refreshed (pid ${record.pid}, port ${record.port})`);
|
|
122
|
+
else
|
|
123
|
+
log('warn', 're-attach: the run registry could not be refreshed:', written.output);
|
|
124
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
125
|
+
return;
|
|
126
|
+
phase('tunnel', 'tunneling');
|
|
127
|
+
await closeTunnel(runtime);
|
|
128
|
+
runtime.token = resolved.token;
|
|
129
|
+
runtime.remote = {
|
|
130
|
+
...runtime.remote,
|
|
131
|
+
version: remoteVersion,
|
|
132
|
+
uiReady: false,
|
|
133
|
+
localPort: null,
|
|
134
|
+
port: resolved.port,
|
|
135
|
+
pid: resolved.pid,
|
|
136
|
+
dshHome: resolved.dshHome ?? layout.dshHome,
|
|
137
|
+
profile: resolved.profile ?? profile,
|
|
138
|
+
startedAt: nowIso(),
|
|
139
|
+
};
|
|
140
|
+
const tunnel = await openTunnelFor(ctx, runtime, resolved.port);
|
|
141
|
+
tunnelCreated = true;
|
|
142
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
143
|
+
return;
|
|
144
|
+
phase('verifying', 'verifying');
|
|
145
|
+
await verifyRemoteUi(ctx, runtime, resolved.port, resolved.token, tunnel.localPort);
|
|
146
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
147
|
+
return;
|
|
148
|
+
if (ctx.settings().saveTokens)
|
|
149
|
+
await ctx.store.saveToken(runtime.id, resolved.token);
|
|
150
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
151
|
+
return;
|
|
152
|
+
// The re-attached instance is now the one this connection is bound to: it stays out of
|
|
153
|
+
// `launched` (a restart must not kill it), but the explicit stop may end exactly it.
|
|
154
|
+
await rememberBound(ctx, runtime, resolved.pid, layout, profile, 'reattach');
|
|
155
|
+
if (!isLinkWorkCurrent(runtime, token))
|
|
156
|
+
return;
|
|
157
|
+
recordRestart(runtime, {
|
|
158
|
+
kind: 'remote-reattach',
|
|
159
|
+
fromPort,
|
|
160
|
+
toPort: resolved.port,
|
|
161
|
+
pid: resolved.pid,
|
|
162
|
+
reason,
|
|
163
|
+
source: resolved.source,
|
|
164
|
+
});
|
|
165
|
+
await markConnected(ctx, runtime);
|
|
166
|
+
log('info', `re-attached: remote ${runtime.remote.version ?? 'version unknown'} on 127.0.0.1:${runtime.tunnel?.localPort ?? tunnel.localPort} (remote port ${fromPort} -> ${resolved.port})`);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (!isLinkWorkCurrent(runtime, token)) {
|
|
170
|
+
log('debug', 're-attach aborted: the link was replaced by a disconnect or reconnect');
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const view = error instanceof LinkCancelled
|
|
174
|
+
? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during re-attach' }))
|
|
175
|
+
: toErrorView(error);
|
|
176
|
+
// The transition owns the error state, the listener release, the heartbeat disarm, the failure lines
|
|
177
|
+
// (which read the phase they are about to clear) and the publication.
|
|
178
|
+
const failure = { type: 'reattach.failed', view };
|
|
179
|
+
await dispatch(createRuntimeEffects(ctx), runtime, failure, scopeFactsFor(ctx, runtime, failure), {
|
|
180
|
+
caller: 'script',
|
|
181
|
+
emit: false,
|
|
182
|
+
});
|
|
183
|
+
ctx.emitState();
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
// A listener this action created must never outlive the action (see `runRestart`).
|
|
187
|
+
if (tunnelCreated && !isLinkWorkCurrent(runtime, token))
|
|
188
|
+
await closeTunnel(runtime);
|
|
189
|
+
endLinkWork(runtime, token);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { messageOf } from '../util.js';
|
|
2
|
+
export async function readRegistryQuietly(ctx, runtime, layout) {
|
|
3
|
+
try {
|
|
4
|
+
return await ctx.deps.readRegistry(runtime.ssh, layout);
|
|
5
|
+
}
|
|
6
|
+
catch (error) {
|
|
7
|
+
ctx.progress.log(runtime, 'debug', 'restart: registry read failed:', messageOf(error));
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
}
|