dsh-remote-go 0.2.0 → 0.3.0
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} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -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/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,198 @@
|
|
|
1
|
+
import { errors, toErrorView } from '../errors.js';
|
|
2
|
+
import { endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
|
|
3
|
+
import { layoutForRuntime } from '../layout.js';
|
|
4
|
+
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
5
|
+
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
6
|
+
import { isPid } from '../util.js';
|
|
7
|
+
import { OWNERSHIP_OPTIONS, proveOwnership } from './ownership.js';
|
|
8
|
+
/** Why the explicit stop refused, as the bilingual `ErrorView.detail` the Client renders. */
|
|
9
|
+
function describeStopRefusal(reason, pid) {
|
|
10
|
+
const target = isPid(pid) ? `pid ${pid}` : 'pid unknown';
|
|
11
|
+
switch (reason) {
|
|
12
|
+
case 'kept-alongside':
|
|
13
|
+
return {
|
|
14
|
+
zh: `远端进程 ${target} 是你在冲突提示里选择「保留」的实例,不会被停止。`,
|
|
15
|
+
en: `The remote process ${target} is the one you chose to keep alongside; it will not be stopped.`,
|
|
16
|
+
};
|
|
17
|
+
case 'not-launched-by-this-connection':
|
|
18
|
+
case 'not-the-bound-instance':
|
|
19
|
+
return {
|
|
20
|
+
zh: '远端进程不是本连接启动或接管的实例,无法证明归属,因此没有停止它;可以点「重连」。',
|
|
21
|
+
en: 'The remote process is not the instance this connection launched or took over, so its ownership cannot be proven and it was not stopped; use Reconnect.',
|
|
22
|
+
};
|
|
23
|
+
case 'registry-mismatch':
|
|
24
|
+
return {
|
|
25
|
+
zh: '远端 run/web.json 没有命名本连接的进程(或读不到),无法证明归属,因此没有停止它。',
|
|
26
|
+
en: 'The remote run/web.json does not name this connection\u2019s process (or could not be read), so ownership cannot be proven and nothing was stopped.',
|
|
27
|
+
};
|
|
28
|
+
case 'pid-reused':
|
|
29
|
+
return {
|
|
30
|
+
zh: '这个 pid 已被另一个进程复用,不是本连接启动的 DSH;没有停止它。',
|
|
31
|
+
en: 'This pid was reused by another process, not the DSH this connection launched; nothing was stopped.',
|
|
32
|
+
};
|
|
33
|
+
case 'dsh-home-mismatch':
|
|
34
|
+
case 'profile-mismatch':
|
|
35
|
+
return {
|
|
36
|
+
zh: '远端进程的 DSH home / profile 与本连接不一致,没有停止它。',
|
|
37
|
+
en: 'The remote process runs a different DSH home / profile than this connection; nothing was stopped.',
|
|
38
|
+
};
|
|
39
|
+
case 'pid-unknown':
|
|
40
|
+
return {
|
|
41
|
+
zh: '本连接没有记录远端 DSH 的 pid,无法定位要停止的进程。',
|
|
42
|
+
en: 'This connection has no recorded remote DSH pid, so there is no process to stop.',
|
|
43
|
+
};
|
|
44
|
+
default:
|
|
45
|
+
return {
|
|
46
|
+
zh: `无法读取远端进程 ${target} 的身份(${reason}),没有停止它。`,
|
|
47
|
+
en: `The identity of the remote process ${target} could not be proven (${reason}), so nothing was stopped.`,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Stop the remote DSH this connection manages, then release the link: the tunnel closes,
|
|
53
|
+
* the SSH session is released and the host lands on `disconnected` (settings and credentials
|
|
54
|
+
* kept, no automatic reconnect) so the card offers Reconnect again. `run/web.json` is removed
|
|
55
|
+
* by the stop itself, so the next connect starts a clean instance instead of raising the
|
|
56
|
+
* "a manually started DSH is already running" conflict.
|
|
57
|
+
*
|
|
58
|
+
* Unlike the disconnect action this never kills a pid without an ownership proof: it reuses
|
|
59
|
+
* the restart's `/proc` identity rules and additionally accepts the re-attached pid this
|
|
60
|
+
* connection is bound to (docs/design.md §5.7). Available while connected and in the
|
|
61
|
+
* `remote-unreachable` error state, which keeps the SSH session on purpose.
|
|
62
|
+
*
|
|
63
|
+
* @param ctx - service context.
|
|
64
|
+
* @param runtime - host runtime.
|
|
65
|
+
* @returns the stopped pid (null when already gone).
|
|
66
|
+
*/
|
|
67
|
+
export async function stopRemoteHost(ctx, runtime) {
|
|
68
|
+
await ctx.init();
|
|
69
|
+
if (runtime.connectPromise || runtime.linkBusy !== null) {
|
|
70
|
+
throw errors.stopRemoteUnavailable({
|
|
71
|
+
zh: '这台主机正在执行另一个连接动作,请等它结束后再关闭远端 DSH。',
|
|
72
|
+
en: 'This host is busy with another link action; wait for it to finish before stopping the remote DSH.',
|
|
73
|
+
}, { technical: 'reason=link-busy' });
|
|
74
|
+
}
|
|
75
|
+
const connected = runtime.status === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null;
|
|
76
|
+
const recoverable = runtime.status === 'error' &&
|
|
77
|
+
runtime.error?.code === 'remote-unreachable' &&
|
|
78
|
+
runtime.ssh?.connected === true &&
|
|
79
|
+
runtime.facts !== null;
|
|
80
|
+
if (!connected && !recoverable)
|
|
81
|
+
throw errors.stopRemoteUnavailable();
|
|
82
|
+
// The `previous` snapshot is what `stop.refused` restores; it is captured before the action
|
|
83
|
+
// writes anything.
|
|
84
|
+
const previous = {
|
|
85
|
+
status: runtime.status,
|
|
86
|
+
phase: runtime.phase,
|
|
87
|
+
progress: runtime.progress,
|
|
88
|
+
error: runtime.error,
|
|
89
|
+
uiReady: runtime.remote.uiReady,
|
|
90
|
+
localPort: runtime.remote.localPort,
|
|
91
|
+
};
|
|
92
|
+
// One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`).
|
|
93
|
+
// The token is the old `beginLinkWork` one (the rule adopts it), so `isLinkWorkCurrent` keeps
|
|
94
|
+
// the exact late-write semantics.
|
|
95
|
+
const token = (Number(runtime.linkToken) || 0) + 1;
|
|
96
|
+
const event = { type: 'stop.requested', token, pid: runtime.remote.pid, port: runtime.remote.port };
|
|
97
|
+
let started = null;
|
|
98
|
+
try {
|
|
99
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
100
|
+
caller: 'script',
|
|
101
|
+
run: (activity, actionToken) => {
|
|
102
|
+
if (activity !== 'stop')
|
|
103
|
+
return;
|
|
104
|
+
started = runStopRemote(ctx, runtime, actionToken);
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
return await started;
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
const view = toErrorView(error);
|
|
111
|
+
const phase = typeof runtime.phase === 'string' ? runtime.phase : previous.phase;
|
|
112
|
+
if (isLinkWorkCurrent(runtime, token)) {
|
|
113
|
+
// The rule restores the previous state itself; `unrestorable` is the design's "link went
|
|
114
|
+
// away while the stop was failing" branch, which publishes the coded failure instead.
|
|
115
|
+
const restorable = previous.status === 'error' ||
|
|
116
|
+
(runtime.desired === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null);
|
|
117
|
+
const refusal = {
|
|
118
|
+
type: 'stop.refused',
|
|
119
|
+
view,
|
|
120
|
+
phase,
|
|
121
|
+
previous: {
|
|
122
|
+
status: previous.status,
|
|
123
|
+
phase: previous.phase,
|
|
124
|
+
progress: previous.progress,
|
|
125
|
+
error: previous.error,
|
|
126
|
+
uiReady: previous.uiReady === true,
|
|
127
|
+
localPort: previous.localPort ?? null,
|
|
128
|
+
},
|
|
129
|
+
...(restorable ? {} : { unrestorable: true }),
|
|
130
|
+
};
|
|
131
|
+
await dispatch(createRuntimeEffects(ctx), runtime, refusal, scopeFactsFor(ctx, runtime, refusal), {
|
|
132
|
+
caller: 'script',
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
endLinkWork(runtime, token);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function runStopRemote(ctx, runtime, token) {
|
|
142
|
+
const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
|
|
143
|
+
const layout = layoutForRuntime(runtime);
|
|
144
|
+
const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile;
|
|
145
|
+
const pid = Number(runtime.remote.pid ?? 0);
|
|
146
|
+
const port = Number(runtime.remote.port ?? 0);
|
|
147
|
+
log('info', `stop remote requested (pid=${isPid(pid) ? pid : 'unknown'}, remote port=${isPid(port) ? port : 'unknown'})`);
|
|
148
|
+
// `stop.requested` already disarmed the heartbeat/reconnect/idle timers and published the
|
|
149
|
+
// `start`/`stopping-remote` card.
|
|
150
|
+
const verdict = await proveOwnership(ctx, runtime, { ...OWNERSHIP_OPTIONS.stop, pid, layout, profile });
|
|
151
|
+
if (!isLinkWorkCurrent(runtime, token)) {
|
|
152
|
+
log('debug', 'stop remote aborted: the link was replaced by a disconnect or reconnect');
|
|
153
|
+
return { ok: true, pid: null };
|
|
154
|
+
}
|
|
155
|
+
// A pid that is already gone is not a refusal for this action: there is nothing to signal, only
|
|
156
|
+
// a stale registry to clear. Every other refusal is the coded error the card explains.
|
|
157
|
+
const gone = verdict.ok !== true && verdict.reason === 'identity-missing';
|
|
158
|
+
if (verdict.ok !== true && !gone) {
|
|
159
|
+
throw errors.stopRemoteUnavailable(describeStopRefusal(verdict.reason, pid), {
|
|
160
|
+
technical: `reason=${verdict.reason} pid=${isPid(pid) ? pid : 'unknown'}`,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
if (gone) {
|
|
164
|
+
// Nothing to signal: the process is already gone. Only its stale record remains, and it
|
|
165
|
+
// must go away or the next connect would try to stop/adopt a dead pid.
|
|
166
|
+
log('info', `stop remote: the bound remote process pid=${pid} is already gone; clearing its run registry`);
|
|
167
|
+
const cleared = await ctx.deps.clearRegistry(runtime.ssh, layout);
|
|
168
|
+
if (cleared?.ok !== true) {
|
|
169
|
+
log('warn', 'stop remote: the stale run registry could not be cleared:', cleared?.output ?? 'no output');
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid });
|
|
174
|
+
if (stopped?.ok !== true) {
|
|
175
|
+
throw errors.stopRemoteUnavailable({
|
|
176
|
+
zh: '远端 DSH 进程没有报告干净停止;连接保持原样,可以重试或点「重连」。',
|
|
177
|
+
en: 'The remote DSH process did not report a clean stop; the connection is unchanged, so retry or use Reconnect.',
|
|
178
|
+
}, { technical: String(stopped?.output ?? '').slice(0, 1200) || 'no output' });
|
|
179
|
+
}
|
|
180
|
+
log('info', `stop remote: stopped the managed remote web pid=${pid}`);
|
|
181
|
+
if (runtime.launched instanceof Map)
|
|
182
|
+
runtime.launched.delete(pid);
|
|
183
|
+
}
|
|
184
|
+
if (!isLinkWorkCurrent(runtime, token)) {
|
|
185
|
+
log('debug', 'stop remote: the link was replaced after the stop; leaving the state to that action');
|
|
186
|
+
return { ok: true, pid: isPid(pid) ? pid : null };
|
|
187
|
+
}
|
|
188
|
+
runtime.bound = null;
|
|
189
|
+
// One transition ends the action: `stop.succeeded` is the explicit stop's disconnect (the
|
|
190
|
+
// `stopped:true` form keeps the idle policy from arming a second stop). The informational line
|
|
191
|
+
// today's `disconnectHost` wrote is part of the operator log, so it stays, in its old position.
|
|
192
|
+
ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`);
|
|
193
|
+
const done = { type: 'stop.succeeded' };
|
|
194
|
+
await dispatch(createRuntimeEffects(ctx), runtime, done, scopeFactsFor(ctx, runtime, done), { caller: 'script' });
|
|
195
|
+
runtime.bound = null;
|
|
196
|
+
log('info', 'stop remote: the remote DSH is stopped; the host is kept and can be reconnected');
|
|
197
|
+
return { ok: true, pid: isPid(pid) ? pid : null };
|
|
198
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { errors } from '../errors.js';
|
|
2
|
+
import { findKnownHostEntries, parseKnownHosts } from '../known-hosts.js';
|
|
3
|
+
import { resolveDestination } from '../ssh-config.js';
|
|
4
|
+
import { isPid } from '../util.js';
|
|
5
|
+
import { noteRemoteUnreachable } from '../watchdog.js';
|
|
6
|
+
import { assertStillWanted, assertTransportOpen } from './guards.js';
|
|
7
|
+
/** Resolve the SSH destination from the entry + local ssh config, before dialling. */
|
|
8
|
+
export async function resolveTargetForRuntime(ctx, runtime) {
|
|
9
|
+
const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() });
|
|
10
|
+
const entry = runtime.entry;
|
|
11
|
+
const resolved = resolveDestination(entry.address, { configText: material.configText, home: ctx.userHome() });
|
|
12
|
+
const host = resolved.host || entry.address;
|
|
13
|
+
const port = entry.port && entry.port !== 22 ? entry.port : (resolved.port ?? 22);
|
|
14
|
+
const knownFingerprints = findKnownHostEntries(parseKnownHosts(material.knownHostsText), host, port).map((item) => item.fingerprint);
|
|
15
|
+
return {
|
|
16
|
+
host,
|
|
17
|
+
port,
|
|
18
|
+
username: entry.username || resolved.user || null,
|
|
19
|
+
identityFiles: resolved.identityFiles ?? [],
|
|
20
|
+
knownFingerprints,
|
|
21
|
+
jumpHost: entry.jumpHost
|
|
22
|
+
? resolveDestination(entry.jumpHost, { configText: material.configText, home: ctx.userHome() })
|
|
23
|
+
: null,
|
|
24
|
+
entry,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Remember the session fingerprint so the host card shows it even without a pin. */
|
|
28
|
+
export function captureFingerprint(ctx, runtime, info) {
|
|
29
|
+
if (!info?.fingerprint)
|
|
30
|
+
return;
|
|
31
|
+
const pinned = runtime.entry.pinnedFingerprint ?? null;
|
|
32
|
+
runtime.fingerprint = {
|
|
33
|
+
sha256: info.fingerprint,
|
|
34
|
+
keyType: info.keyType ?? 'unknown',
|
|
35
|
+
status: pinned === info.fingerprint ? 'pinned' : pinned ? 'changed' : 'observed',
|
|
36
|
+
pinned,
|
|
37
|
+
};
|
|
38
|
+
ctx.progress.log(runtime, pinned === info.fingerprint ? 'debug' : 'info', `host key ${info.keyType ?? 'unknown'}: ${info.fingerprint}${pinned === info.fingerprint ? ' (matches the pinned key)' : pinned ? ' (CHANGED from the pinned key)' : ''}`);
|
|
39
|
+
ctx.emitState();
|
|
40
|
+
}
|
|
41
|
+
/** Open the loopback tunnel for one remote port; tunnel-level failures feed the liveness confirmation. */
|
|
42
|
+
export async function openTunnelFor(ctx, runtime, remotePort) {
|
|
43
|
+
// Never hand the tunnel factory a missing transport: a listener created with no SSH channel
|
|
44
|
+
// would crash the host process on the first connection (see tunnel.js's own guard).
|
|
45
|
+
assertTransportOpen(runtime);
|
|
46
|
+
if (!isPid(remotePort) || remotePort > 65535) {
|
|
47
|
+
throw errors.internal(new Error(`invalid remote port for the tunnel: ${remotePort}`));
|
|
48
|
+
}
|
|
49
|
+
// Forward import, not a `ctx` callback: the liveness watchdog is a plain module now (§1.7).
|
|
50
|
+
const onError = () => noteRemoteUnreachable(ctx, runtime, 'tunnel');
|
|
51
|
+
const tunnel = await ctx.deps.tunnelFactory({ ssh: runtime.ssh, remotePort, onError });
|
|
52
|
+
const localPort = Number(tunnel?.localPort);
|
|
53
|
+
if (!Number.isInteger(localPort) || !isPid(localPort) || localPort > 65535) {
|
|
54
|
+
try {
|
|
55
|
+
await tunnel?.close?.();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// swallow-ok: the listener never carried a caller; the internal error is what matters
|
|
59
|
+
}
|
|
60
|
+
throw errors.internal(new Error(`the tunnel factory returned no usable local port (${tunnel?.localPort})`));
|
|
61
|
+
}
|
|
62
|
+
// The listener was created while the caller awaited the factory: a disconnect or a host
|
|
63
|
+
// removal in that window must close it instead of publishing it (H4).
|
|
64
|
+
try {
|
|
65
|
+
assertStillWanted(ctx, runtime);
|
|
66
|
+
assertTransportOpen(runtime);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
try {
|
|
70
|
+
await tunnel.close();
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// swallow-ok: the cancellation error must be rethrown, not masked by a close error
|
|
74
|
+
}
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
runtime.tunnel = tunnel;
|
|
78
|
+
runtime.remote.localPort = localPort;
|
|
79
|
+
ctx.progress.log(runtime, 'info', `tunnel open: 127.0.0.1:${localPort} -> 127.0.0.1:${remotePort}`);
|
|
80
|
+
return tunnel;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Persist (or forget) the SSH password now that the transport accepted it. Doing this right
|
|
84
|
+
* after the handshake rather than after `connected` keeps a credential the server already
|
|
85
|
+
* proved even when a later bootstrap step fails, so the next attempt does not ask again.
|
|
86
|
+
* @param ctx - service context.
|
|
87
|
+
* @param runtime - host runtime.
|
|
88
|
+
* @param log - connect log writer.
|
|
89
|
+
*/
|
|
90
|
+
export async function settlePasswordStorage(ctx, runtime, log) {
|
|
91
|
+
const save = runtime.savePassword === true;
|
|
92
|
+
const forget = runtime.forgetPassword === true;
|
|
93
|
+
runtime.savePassword = false;
|
|
94
|
+
runtime.forgetPassword = false;
|
|
95
|
+
if (!ctx.secrets || typeof runtime.password !== 'string' || runtime.password === '')
|
|
96
|
+
return;
|
|
97
|
+
if (save) {
|
|
98
|
+
runtime.passwordSaved = await ctx.secrets.set(runtime.id, runtime.password);
|
|
99
|
+
if (runtime.passwordSaved)
|
|
100
|
+
log('debug', 'saved the SSH password in the credential store');
|
|
101
|
+
else
|
|
102
|
+
log('warn', 'could not save the SSH password in the credential store');
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (forget) {
|
|
106
|
+
const removed = await ctx.secrets.remove(runtime.id);
|
|
107
|
+
runtime.passwordSaved = !removed;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `[verifying]` step: the remote UI answers through the new listener and the launch token
|
|
3
|
+
* exchanges for the cookie the carrier needs. Both halves are guarded across their awaits (H3/H4).
|
|
4
|
+
*/
|
|
5
|
+
import { TUNNEL_PROBE_TIMEOUT_MS } from '../constants.js';
|
|
6
|
+
import { errors } from '../errors.js';
|
|
7
|
+
import { isPid } from '../util.js';
|
|
8
|
+
import { assertStillWanted, assertTransportOpen } from './guards.js';
|
|
9
|
+
/** Prove the remote UI answers through the new tunnel and exchange this launch's token. */
|
|
10
|
+
export async function verifyRemoteUi(ctx, runtime, port, token, localPort) {
|
|
11
|
+
const tunnelPort = Number(localPort);
|
|
12
|
+
if (!Number.isInteger(tunnelPort) || !isPid(tunnelPort) || tunnelPort > 65535) {
|
|
13
|
+
throw errors.internal(new Error(`the tunnel has no local port to verify (${localPort ?? 'none'})`));
|
|
14
|
+
}
|
|
15
|
+
ctx.progress.log(runtime, 'debug', `verifying the remote UI on 127.0.0.1:${tunnelPort}`);
|
|
16
|
+
const ui = await ctx.deps.waitUi(runtime.ssh, port, { attempts: 20, intervalMs: 500 });
|
|
17
|
+
// The probe retries for up to ten seconds: the user may have cancelled in that window, and
|
|
18
|
+
// the token exchange must not touch the (possibly closed) tunnel after it (H4).
|
|
19
|
+
assertStillWanted(ctx, runtime);
|
|
20
|
+
assertTransportOpen(runtime);
|
|
21
|
+
if (!ui.ok) {
|
|
22
|
+
throw errors.remoteUiUnreachable({
|
|
23
|
+
zh: `远端 DSH 的本地 127.0.0.1:${port} 没有响应(HTTP ${ui.status ?? '无'})。`,
|
|
24
|
+
en: `The remote DSH on 127.0.0.1:${port} did not respond (HTTP ${ui.status ?? 'none'}).`,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
ctx.progress.log(runtime, 'debug', `remote UI answered HTTP ${ui.status}; exchanging the launch token`);
|
|
28
|
+
const exchange = await ctx.deps.exchange(tunnelPort, token, {
|
|
29
|
+
timeoutMs: TUNNEL_PROBE_TIMEOUT_MS,
|
|
30
|
+
});
|
|
31
|
+
runtime.exchange = exchange;
|
|
32
|
+
if (!exchange.ok) {
|
|
33
|
+
throw errors.remoteUiUnreachable({
|
|
34
|
+
zh: `本地隧道完成了 token 交换,但远端界面返回 HTTP ${exchange.status}(首次状态 ${exchange.firstStatus})。`,
|
|
35
|
+
en: `The tunnel exchanged the token but the remote UI answered HTTP ${exchange.status} (first ${exchange.firstStatus}).`,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return exchange;
|
|
39
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { messageOf } from '../util.js';
|
|
2
|
+
import { watchable } from '../watchdog.js';
|
|
3
|
+
/**
|
|
4
|
+
* A liveness episode recovered. The remote answers the SSH probe again, so the local listener is
|
|
5
|
+
* what may still be broken (B8): ask the listener first — one failed upstream connection is not a
|
|
6
|
+
* broken tunnel, and rebuilding would drop live WebSockets for nothing — then rebuild it when it
|
|
7
|
+
* really is down. The `recovered` event is announced once the link is usable again, which is the
|
|
8
|
+
* point in the sequence the pre-bus code announced it at.
|
|
9
|
+
* @param ctx - the actor's three slices.
|
|
10
|
+
* @param entries - the bound orchestration entries.
|
|
11
|
+
* @param runtime - the host whose episode closed.
|
|
12
|
+
* @param source - which reporter saw the remote fail.
|
|
13
|
+
*/
|
|
14
|
+
async function onRecovered(ctx, entries, runtime, source) {
|
|
15
|
+
const transient = source === 'proxy' || source === 'tunnel';
|
|
16
|
+
if (transient) {
|
|
17
|
+
let healthy = false;
|
|
18
|
+
try {
|
|
19
|
+
healthy = (await ctx.deps.tunnelProbe?.(runtime.tunnel?.localPort ?? null)) === true;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// swallow-ok: a probe error means "not healthy"; the rebuild path reports its own failure
|
|
23
|
+
}
|
|
24
|
+
if (healthy) {
|
|
25
|
+
ctx.progress.log(runtime, 'debug', 'the local tunnel still answers; keeping the listener');
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
try {
|
|
29
|
+
const repaired = await entries.repair(runtime);
|
|
30
|
+
if (repaired && repaired.ok !== true) {
|
|
31
|
+
ctx.progress.log(runtime, 'debug', `tunnel rebuild skipped (${repaired.reason ?? 'unknown'})`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
// swallow-ok: a failed repair is reported by the helper; the episode still recovers
|
|
36
|
+
ctx.progress.log(runtime, 'warn', 'tunnel rebuild failed:', messageOf(error));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
ctx.progress.log(runtime, 'info', `remote heartbeat: the remote UI answers again (${source})`);
|
|
41
|
+
if (!watchable(ctx, runtime))
|
|
42
|
+
return;
|
|
43
|
+
ctx.onRemoteUnreachable?.(runtime, { phase: 'recovered', source });
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* One bus event, dispatched to the runtime it names.
|
|
47
|
+
* @param ctx - the actor's three slices.
|
|
48
|
+
* @param entries - the bound orchestration entries.
|
|
49
|
+
* @param event - the action request the liveness detector published.
|
|
50
|
+
*/
|
|
51
|
+
function runWatchdogEvent(ctx, entries, event) {
|
|
52
|
+
const runtime = ctx.state.runtimes.get(event.hostId);
|
|
53
|
+
// A host removed between the probe and the event has nothing to act on.
|
|
54
|
+
if (!runtime)
|
|
55
|
+
return;
|
|
56
|
+
if (event.kind === 'confirmed') {
|
|
57
|
+
void entries.reattach(runtime, { reason: event.reason, source: event.source });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
void onRecovered(ctx, entries, runtime, event.source);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Subscribe this service instance to the watchdog bus.
|
|
64
|
+
*
|
|
65
|
+
* `confirmed` means the probes agreed the remote UI is gone: re-read the remote, refresh the run
|
|
66
|
+
* registry and rebuild the tunnel (`reattachHost`). `recovered` means it answers again: fix the
|
|
67
|
+
* listener and announce the episode (see {@link onRecovered}).
|
|
68
|
+
*
|
|
69
|
+
* @param ctx - the actor's three slices (the subscriber drives orchestration, so the facade binds
|
|
70
|
+
* the entries rather than handing over the whole context).
|
|
71
|
+
* @param entries - the two orchestration entries, bound to the facade's context.
|
|
72
|
+
* @returns the unsubscribe function; `service.shutdown()` must call it before tearing hosts down.
|
|
73
|
+
*/
|
|
74
|
+
export function installWatchdog(ctx, entries) {
|
|
75
|
+
return ctx.bus.subscribe((event) => runWatchdogEvent(ctx, entries, event));
|
|
76
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connect log behind `HostView.logs`: the per-host ring, the per-connection reset, the structured failure lines, its bounded `/state` tail and which statuses print it.
|
|
3
|
+
*/
|
|
4
|
+
import { redactText } from './redact.js';
|
|
5
|
+
import { headTail, isPlainObject } from './util.js';
|
|
6
|
+
export const CONNECT_LOG_STATUSES = Object.freeze(['connecting', 'fingerprint-pending', 'error']);
|
|
7
|
+
export const LOG_RING_LIMIT = 200;
|
|
8
|
+
export const LOG_TAIL_LIMIT = 120;
|
|
9
|
+
/** How much of one technical detail (redacted) the log prints before `headTail` elides it. */
|
|
10
|
+
export const LOG_TECHNICAL_LIMIT = 1200;
|
|
11
|
+
/** How long a single remote-log / technical line may get before it is elided. */
|
|
12
|
+
export const LOG_LINE_LIMIT = 400;
|
|
13
|
+
/** Cap on the remote-log lines a failed start prints, so a chatty tail cannot eat the ring. */
|
|
14
|
+
export const LOG_TAIL_LINES = 60;
|
|
15
|
+
export function connectLogVisible(status) {
|
|
16
|
+
return typeof status === 'string' && CONNECT_LOG_STATUSES.includes(status);
|
|
17
|
+
}
|
|
18
|
+
/** A bilingual line: zh and en side by side, the shape the Client already resolves. */
|
|
19
|
+
function pair(zh, en) {
|
|
20
|
+
return { zh, en };
|
|
21
|
+
}
|
|
22
|
+
/** Accept only a complete { zh, en } pair; a half-resolved object would render as an empty line. */
|
|
23
|
+
function normalizeText(value) {
|
|
24
|
+
if (!isPlainObject(value))
|
|
25
|
+
return null;
|
|
26
|
+
const zh = typeof value.zh === 'string' ? value.zh : '';
|
|
27
|
+
const en = typeof value.en === 'string' ? value.en : '';
|
|
28
|
+
if (zh === '' || en === '')
|
|
29
|
+
return null;
|
|
30
|
+
return pair(zh, en);
|
|
31
|
+
}
|
|
32
|
+
export function appendConnectLog(runtime, input) {
|
|
33
|
+
const raw = typeof input.message === 'string' ? input.message : String(input.message ?? '');
|
|
34
|
+
// The remote's own stdout arrives here (`remote-web/start.js` hands every start line to `onLine`,
|
|
35
|
+
// and the first one is the launch URL with its session token). This ring is the second exit of
|
|
36
|
+
// that text — `HostView.logs`, the SSE state frames and the diagnostics export all read it — so
|
|
37
|
+
// it is redacted at write time, not only when the failure view is built.
|
|
38
|
+
const message = headTail(redactText(raw), LOG_TECHNICAL_LIMIT);
|
|
39
|
+
const entry = {
|
|
40
|
+
seq: (typeof runtime.logSeq === 'number' ? runtime.logSeq : 0) + 1,
|
|
41
|
+
at: typeof input.at === 'string' ? input.at : '',
|
|
42
|
+
level: typeof input.level === 'string' ? input.level : 'info',
|
|
43
|
+
phase: typeof input.phase === 'string' && input.phase !== '' ? input.phase : null,
|
|
44
|
+
message,
|
|
45
|
+
line: `[dsh-remote-go:${runtime.id}] ${message}`,
|
|
46
|
+
};
|
|
47
|
+
const text = normalizeText(input.text);
|
|
48
|
+
if (text !== null)
|
|
49
|
+
entry.text = text;
|
|
50
|
+
if (input.boundary === true)
|
|
51
|
+
entry.boundary = true;
|
|
52
|
+
if (!Array.isArray(runtime.logs))
|
|
53
|
+
runtime.logs = [];
|
|
54
|
+
if (runtime.logs.length >= LOG_RING_LIMIT)
|
|
55
|
+
runtime.logs.shift();
|
|
56
|
+
runtime.logSeq = entry.seq;
|
|
57
|
+
runtime.logs.push(entry);
|
|
58
|
+
return entry;
|
|
59
|
+
}
|
|
60
|
+
/** Forget the previous connection's lines; the sequence restarts with this connection. */
|
|
61
|
+
export function resetConnectLog(runtime) {
|
|
62
|
+
runtime.logs = [];
|
|
63
|
+
runtime.logSeq = 0;
|
|
64
|
+
return runtime;
|
|
65
|
+
}
|
|
66
|
+
/** `YYYY-MM-DD HH:MM:SS` in the Host's own timezone — the clock the user reads. */
|
|
67
|
+
function localClock(date) {
|
|
68
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
69
|
+
return (`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
|
|
70
|
+
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Start one connection's log: drop the previous attempt and write its boundary line, so the
|
|
74
|
+
* panel opens on this attempt only and a copied log says which attempt it belongs to.
|
|
75
|
+
*/
|
|
76
|
+
export function beginConnectLog(runtime, options = {}) {
|
|
77
|
+
const at = typeof options.at === 'string' && options.at !== '' ? options.at : new Date().toISOString();
|
|
78
|
+
const when = new Date(at);
|
|
79
|
+
const attempt = (typeof runtime.connectCount === 'number' ? runtime.connectCount : 0) + 1;
|
|
80
|
+
runtime.connectCount = attempt;
|
|
81
|
+
resetConnectLog(runtime);
|
|
82
|
+
const clock = Number.isNaN(when.getTime()) ? at : localClock(when);
|
|
83
|
+
const text = pair(`— 第 ${attempt} 次连接 · ${clock} —`, `— Connection ${attempt} · ${clock} —`);
|
|
84
|
+
return appendConnectLog(runtime, { at, level: 'info', message: text.en, text, boundary: true });
|
|
85
|
+
}
|
|
86
|
+
/** `{ zh, en }` from any bilingual value, filling a missing side from the other. */
|
|
87
|
+
function say(value) {
|
|
88
|
+
if (typeof value === 'string')
|
|
89
|
+
return value === '' ? null : pair(value, value);
|
|
90
|
+
if (!isPlainObject(value))
|
|
91
|
+
return null;
|
|
92
|
+
const zh = typeof value.zh === 'string' ? value.zh : '';
|
|
93
|
+
const en = typeof value.en === 'string' ? value.en : '';
|
|
94
|
+
if (zh === '' && en === '')
|
|
95
|
+
return null;
|
|
96
|
+
return { zh: zh === '' ? en : zh, en: en === '' ? zh : en };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Turn an `ErrorView` into the lines the connect log prints for a failed connection:
|
|
100
|
+
* the failed phase and code, the localized reason, every hint, then the redacted and
|
|
101
|
+
* head-tail-truncated technical detail — the remote log tail line by line for a failed start.
|
|
102
|
+
*
|
|
103
|
+
* `options.label` replaces the first line for a one-shot action that is not a connect (the
|
|
104
|
+
* explicit remote stop), so its failure is not announced as a connection failure.
|
|
105
|
+
*/
|
|
106
|
+
export function connectFailureLines(view, options = {}) {
|
|
107
|
+
const code = typeof view?.code === 'string' && view.code !== '' ? view.code : 'internal';
|
|
108
|
+
const phase = typeof options.phase === 'string' && options.phase !== '' ? options.phase : null;
|
|
109
|
+
const lines = [];
|
|
110
|
+
const push = (text) => lines.push({ level: 'error', phase, message: text.en, text });
|
|
111
|
+
const raw = (message) => lines.push({ level: 'error', phase, message });
|
|
112
|
+
const label = normalizeText(options.label);
|
|
113
|
+
push(label ??
|
|
114
|
+
(phase === null
|
|
115
|
+
? pair(`连接失败:${code}`, `Connect failed: ${code}`)
|
|
116
|
+
: pair(`连接失败于 ${phase} 阶段:${code}`, `Connect failed in phase ${phase}: ${code}`)));
|
|
117
|
+
// The card explains the failure in one sentence; the log has to carry that sentence.
|
|
118
|
+
const reason = say(view?.detail) ?? say(view?.title);
|
|
119
|
+
if (reason !== null)
|
|
120
|
+
push(pair(`原因:${reason.zh}`, `Reason: ${reason.en}`));
|
|
121
|
+
const hints = Array.isArray(view?.nextSteps) ? view.nextSteps : [];
|
|
122
|
+
for (const hint of hints) {
|
|
123
|
+
const step = say(hint);
|
|
124
|
+
if (step !== null)
|
|
125
|
+
push(pair(`建议:${step.zh}`, `Next: ${step.en}`));
|
|
126
|
+
}
|
|
127
|
+
const technical = typeof view?.technical === 'string' ? view.technical : '';
|
|
128
|
+
if (technical.trim() !== '') {
|
|
129
|
+
const tail = code === 'remote-dsh-start-failed';
|
|
130
|
+
push(tail ? pair('远端日志尾部:', 'Remote log tail:') : pair('技术细节:', 'Details:'));
|
|
131
|
+
// Redaction is the contract of anything copied out of the log; `headTail` keeps both the
|
|
132
|
+
// start of the message (what failed) and its end (the error itself) when it is too long.
|
|
133
|
+
let printed = 0;
|
|
134
|
+
for (const line of headTail(redactText(technical), LOG_TECHNICAL_LIMIT).split(/\r?\n/)) {
|
|
135
|
+
if (printed >= LOG_TAIL_LINES)
|
|
136
|
+
break;
|
|
137
|
+
if (line.trim() === '')
|
|
138
|
+
continue;
|
|
139
|
+
raw(headTail(line, LOG_LINE_LIMIT));
|
|
140
|
+
printed += 1;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return lines;
|
|
144
|
+
}
|
|
145
|
+
export function connectLogTail(runtime) {
|
|
146
|
+
const entries = runtime && Array.isArray(runtime.logs) ? runtime.logs : [];
|
|
147
|
+
return entries.slice(-LOG_TAIL_LIMIT).map((entry) => {
|
|
148
|
+
const item = {
|
|
149
|
+
seq: typeof entry.seq === 'number' ? entry.seq : 0,
|
|
150
|
+
at: typeof entry.at === 'string' ? entry.at : '',
|
|
151
|
+
level: typeof entry.level === 'string' ? entry.level : 'info',
|
|
152
|
+
phase: typeof entry.phase === 'string' && entry.phase !== '' ? entry.phase : null,
|
|
153
|
+
message: typeof entry.message === 'string' ? entry.message : String(entry.line ?? ''),
|
|
154
|
+
};
|
|
155
|
+
const text = normalizeText(entry.text);
|
|
156
|
+
if (text !== null)
|
|
157
|
+
item.text = text;
|
|
158
|
+
if (entry.boundary === true)
|
|
159
|
+
item.boundary = true;
|
|
160
|
+
return item;
|
|
161
|
+
});
|
|
162
|
+
}
|