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,327 @@
1
+ /** The plugin's Node.js runtime on the remote: an official build, SHA-256 verified, under `$DSH_HOME/remote-go/node`,
2
+ * installed by fixed command templates (never user-composed). The artifact scripts live in `node/download.ts`. */
3
+ import { errors } from './errors.js';
4
+ import { headTail, messageOf, shellQuote } from './util.js';
5
+ import { MIN_NODE_VERSION, normalizeVersion, parseVersion } from './version.js';
6
+ import { buildNodeChecksumScript, buildNodeInstallScript, parseNodeChecksumOutput } from './node/download.js';
7
+ export const MANAGED_NODE_VERSION_FALLBACK = MIN_NODE_VERSION;
8
+ export function managedNodeVersionFromEngine(range, fallback = MANAGED_NODE_VERSION_FALLBACK) {
9
+ const text = String(range ?? '').trim();
10
+ if (text === '')
11
+ return normalizeVersion(fallback);
12
+ const first = text.split('||')[0].trim();
13
+ if (first === '' || first === '*' || first === 'latest')
14
+ return normalizeVersion(fallback);
15
+ // A strict `>` needs the next patch; `>=`, `^`, `~`, `=` and a bare version all mean that version
16
+ // itself.
17
+ const strict = /^>\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first);
18
+ if (strict && !first.startsWith('>=')) {
19
+ return normalizeVersion(`${Number(strict[1])}.${Number(strict[2] ?? 0)}.${Number(strict[3] ?? 0) + 1}`);
20
+ }
21
+ const match = /(?:>=|\^|~|=)?\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first);
22
+ if (!match)
23
+ return normalizeVersion(fallback);
24
+ return normalizeVersion(`${Number(match[1])}.${Number(match[2] ?? 0)}.${Number(match[3] ?? 0)}`);
25
+ }
26
+ const NODE_SCAN_TIMEOUT_MS = 30_000;
27
+ const NODE_CHECKSUM_TIMEOUT_MS = 240_000;
28
+ const NODE_INSTALL_TIMEOUT_MS = 30 * 60_000;
29
+ const NODE_MIN_FREE_KB = 400 * 1024;
30
+ const NODE_MIN_GLIBC = '2.28';
31
+ const DIST_ARCH = new Map([
32
+ ['x86_64', 'x64'],
33
+ ['amd64', 'x64'],
34
+ ['aarch64', 'arm64'],
35
+ ['arm64', 'arm64'],
36
+ ['armv7l', 'armv7l'],
37
+ ['armv7', 'armv7l'],
38
+ ['ppc64le', 'ppc64le'],
39
+ ['s390x', 's390x'],
40
+ ]);
41
+ export function nodeDistArch(arch) {
42
+ return DIST_ARCH.get(String(arch ?? '').toLowerCase()) ?? null;
43
+ }
44
+ function compareGlibc(left, right) {
45
+ const a = String(left ?? '').split('.');
46
+ const b = String(right ?? '').split('.');
47
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
48
+ const x = Number.parseInt(a[index] ?? '0', 10) || 0;
49
+ const y = Number.parseInt(b[index] ?? '0', 10) || 0;
50
+ if (x !== y)
51
+ return x < y ? -1 : 1;
52
+ }
53
+ return 0;
54
+ }
55
+ export function buildNodeScanScript(layout) {
56
+ return `set -u
57
+ NODE_DIR=${shellQuote(layout.nodeDir)}
58
+ if [ -d "$NODE_DIR" ]; then
59
+ for DIR in "$NODE_DIR"/*; do
60
+ [ -d "$DIR" ] || continue
61
+ [ -x "$DIR/bin/node" ] || continue
62
+ [ -x "$DIR/bin/npx" ] || continue
63
+ VER=$("$DIR/bin/node" -v 2>/dev/null || true)
64
+ case "$VER" in
65
+ v[0-9]*) printf 'NODE\\t%s\\t%s\\n' "\${VER#v}" "$DIR" ;;
66
+ esac
67
+ done
68
+ fi
69
+ `;
70
+ }
71
+ export function parseNodeScanOutput(stdout) {
72
+ const versions = [];
73
+ for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
74
+ const parts = rawLine.split('\t');
75
+ if (parts[0] !== 'NODE' || parts.length < 3)
76
+ continue;
77
+ const version = normalizeVersion(parts[1]);
78
+ if (!parseVersion(version))
79
+ continue;
80
+ if (versions.some((entry) => entry.version === version))
81
+ continue;
82
+ versions.push({ version, dir: parts[2] });
83
+ }
84
+ return versions;
85
+ }
86
+ function nodeError(detail, technical) {
87
+ return errors.nodeInstallFailed(detail, technical ? { technical } : undefined);
88
+ }
89
+ /** Run one remote command and normalize whatever shape the transport returned. */
90
+ async function runRemote(ssh, command, options) {
91
+ const result = await ssh.exec(command, options);
92
+ return {
93
+ code: typeof result?.code === 'number' ? result.code : 0,
94
+ stdout: String(result?.stdout ?? ''),
95
+ stderr: String(result?.stderr ?? ''),
96
+ };
97
+ }
98
+ async function scanManagedNode(ssh, layout) {
99
+ let result;
100
+ try {
101
+ result = await runRemote(ssh, buildNodeScanScript(layout), {
102
+ timeoutMs: NODE_SCAN_TIMEOUT_MS,
103
+ maxBytes: 200_000,
104
+ });
105
+ }
106
+ catch (error) {
107
+ throw nodeError({ zh: '无法检查远端托管的 Node。', en: 'Could not inspect the managed Node on the remote.' }, messageOf(error ?? ''));
108
+ }
109
+ if (result.code !== 0) {
110
+ throw nodeError({
111
+ zh: `无法检查远端托管的 Node(退出码 ${result.code})。`,
112
+ en: `Could not inspect the managed Node on the remote (exit ${result.code}).`,
113
+ }, headTail(result.stderr || result.stdout, 800));
114
+ }
115
+ return parseNodeScanOutput(result.stdout);
116
+ }
117
+ async function resolveNodeRelease(ssh, input) {
118
+ let result;
119
+ try {
120
+ result = await runRemote(ssh, buildNodeChecksumScript({
121
+ downloadDir: input.layout.downloadDir,
122
+ version: input.version,
123
+ arch: input.arch,
124
+ bases: input.bases,
125
+ }), { timeoutMs: NODE_CHECKSUM_TIMEOUT_MS, maxBytes: 200_000 });
126
+ }
127
+ catch (error) {
128
+ // swallow-ok: unreachable — a transport failure is reported as a typed resolution reason
129
+ return { ok: false, reason: 'unreachable', technical: messageOf(error ?? '') };
130
+ }
131
+ if (result.code === 0) {
132
+ const release = parseNodeChecksumOutput(result.stdout, {
133
+ version: input.version,
134
+ arch: input.arch,
135
+ bases: input.bases,
136
+ });
137
+ if (release)
138
+ return { ok: true, release };
139
+ return { ok: false, reason: 'no-checksum', technical: headTail(result.stdout, 600) };
140
+ }
141
+ if (result.code === 9 || result.stdout.includes('FAILED\tno-fetch'))
142
+ return { ok: false, reason: 'no-fetch' };
143
+ if (result.code === 5) {
144
+ return { ok: false, reason: 'unreachable', technical: headTail(result.stderr || result.stdout, 600) };
145
+ }
146
+ return { ok: false, reason: 'unreachable', technical: headTail(`${result.stdout}\n${result.stderr}`, 600) };
147
+ }
148
+ async function installNodeRelease(ssh, input) {
149
+ const expectedDir = `${input.layout.nodeDir}/v${input.release.version}`;
150
+ let buffered = '';
151
+ let dir = null;
152
+ let failure = null;
153
+ let lastBytes = -1;
154
+ let lastEmit = 0;
155
+ const handleLine = (line) => {
156
+ if (line === '')
157
+ return;
158
+ const parts = line.split('\t');
159
+ if (parts[0] === 'BYTES') {
160
+ const bytes = Number(parts[1]);
161
+ if (!Number.isFinite(bytes) || bytes < 0)
162
+ return;
163
+ const now = Date.now();
164
+ if (bytes - lastBytes < 8 * 1024 * 1024 && now - lastEmit < 5000 && bytes !== 0)
165
+ return;
166
+ lastBytes = bytes;
167
+ lastEmit = now;
168
+ input.onProgress({ step: 'download', version: input.release.version, bytes });
169
+ return;
170
+ }
171
+ if (parts[0] === 'STEP' && parts[1] === 'download') {
172
+ input.onProgress({ step: 'download', version: input.release.version, bytes: 0, source: parts[2] });
173
+ return;
174
+ }
175
+ if (parts[0] === 'STEP' && parts[1] === 'extract') {
176
+ input.onProgress({ step: 'extract', version: input.release.version });
177
+ return;
178
+ }
179
+ if (parts[0] === 'READY') {
180
+ dir = parts[1] ?? null;
181
+ return;
182
+ }
183
+ if (parts[0] === 'FAILED') {
184
+ failure = parts.slice(1).filter(Boolean).join(' ') || 'failed';
185
+ }
186
+ };
187
+ let result;
188
+ try {
189
+ result = await runRemote(ssh, buildNodeInstallScript({ layout: input.layout, release: input.release, bases: input.bases }), {
190
+ timeoutMs: NODE_INSTALL_TIMEOUT_MS,
191
+ maxBytes: 400_000,
192
+ onStdout: (chunk) => {
193
+ buffered += String(chunk ?? '');
194
+ const lines = buffered.split('\n');
195
+ buffered = lines.pop() ?? '';
196
+ for (const piece of lines)
197
+ handleLine(piece.replace(/\r$/, ''));
198
+ },
199
+ });
200
+ }
201
+ catch (error) {
202
+ // swallow-ok: unreachable — same contract as the checksum step, the caller reports it
203
+ return { ok: false, reason: 'unreachable', technical: messageOf(error ?? '') };
204
+ }
205
+ if (result.code !== 0 || !dir) {
206
+ return {
207
+ ok: false,
208
+ reason: failure ?? `exit ${result.code}`,
209
+ technical: headTail(`${result.stdout}\n${result.stderr}`, 800),
210
+ };
211
+ }
212
+ if (dir !== expectedDir)
213
+ return { ok: false, reason: 'unexpected-location', technical: dir };
214
+ return { ok: true, dir };
215
+ }
216
+ export async function ensureRemoteNode(ssh, options) {
217
+ const facts = options.facts ?? {};
218
+ const layout = options.layout;
219
+ const version = normalizeVersion(options.version ?? MANAGED_NODE_VERSION_FALLBACK);
220
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => { };
221
+ if (!layout?.nodeDir || !layout?.downloadDir) {
222
+ throw errors.internal('remote layout is missing the managed Node directories');
223
+ }
224
+ if (!parseVersion(version))
225
+ throw errors.internal(`invalid managed Node version: ${version}`);
226
+ if (!facts.home || !String(layout.nodeDir).startsWith('/')) {
227
+ throw nodeError({
228
+ zh: '远端主目录未知,无法准备托管的 Node。',
229
+ en: 'The remote home directory is unknown, so the managed Node cannot be prepared.',
230
+ });
231
+ }
232
+ if (String(facts.os ?? '') !== 'Linux') {
233
+ // The official builds this module installs are Linux-only; refusing here keeps a Darwin/Windows
234
+ // remote from downloading a binary that could never run.
235
+ throw errors.unsupportedOs(`${facts.os ?? 'unknown'} ${facts.arch ?? ''}`.trim());
236
+ }
237
+ if (facts.libc === 'glibc' && facts.glibcVersion && compareGlibc(facts.glibcVersion, NODE_MIN_GLIBC) < 0) {
238
+ throw nodeError({
239
+ zh: `远端 glibc ${facts.glibcVersion} 过低,Node 官方 Linux 构建需要 ≥ ${NODE_MIN_GLIBC}。请升级系统后重试。`,
240
+ en: `The remote glibc is ${facts.glibcVersion}, but the official Node Linux build needs >= ${NODE_MIN_GLIBC}. Upgrade the system and retry.`,
241
+ });
242
+ }
243
+ if (facts.libc === 'musl') {
244
+ throw nodeError({
245
+ zh: '远端使用 musl libc(如 Alpine),Node 官方构建无法运行;插件只使用自己的 Node,请换用 glibc 系统(如 Ubuntu/Debian)。',
246
+ en: 'The remote uses musl libc (for example Alpine), where the official Node build cannot run; the plugin only uses its own Node, so use a glibc system (such as Ubuntu/Debian).',
247
+ });
248
+ }
249
+ const arch = nodeDistArch(facts.arch);
250
+ if (!arch) {
251
+ throw nodeError({
252
+ zh: `远端架构「${facts.arch}」没有对应的 Node 官方构建。插件只使用自己的 Node,请换一台受支持的架构。`,
253
+ en: `No official Node build exists for the remote architecture "${facts.arch}". The plugin only uses its own Node, so use a supported architecture.`,
254
+ });
255
+ }
256
+ if (typeof facts.diskFreeKb === 'number' && facts.diskFreeKb > 0 && facts.diskFreeKb < NODE_MIN_FREE_KB) {
257
+ throw nodeError({
258
+ zh: `远端磁盘空间不足(可用约 ${Math.round(facts.diskFreeKb / 1024)} MB,至少需要 ${Math.round(NODE_MIN_FREE_KB / 1024)} MB)。`,
259
+ en: `The remote has too little free space (about ${Math.round(facts.diskFreeKb / 1024)} MB; at least ${Math.round(NODE_MIN_FREE_KB / 1024)} MB is required).`,
260
+ });
261
+ }
262
+ onProgress({ step: 'check', version });
263
+ const installed = await scanManagedNode(ssh, layout);
264
+ let current = installed.find((entry) => entry.version === version) ?? null;
265
+ let installedNow = false;
266
+ if (!current) {
267
+ onProgress({ step: 'checksum', version });
268
+ const resolved = await resolveNodeRelease(ssh, { layout, version, arch, bases: options.bases });
269
+ if (resolved.ok === false) {
270
+ throw nodeError(resolveFailureDetail(resolved.reason, version), resolved.technical ?? `reason=${resolved.reason}`);
271
+ }
272
+ onProgress({ step: 'install', version });
273
+ const install = await installNodeRelease(ssh, {
274
+ layout,
275
+ release: resolved.release,
276
+ bases: options.bases,
277
+ onProgress,
278
+ });
279
+ if (install.ok === false) {
280
+ throw nodeError({
281
+ zh: `自动安装 Node ${version} 失败(${install.reason})。`,
282
+ en: `Automatically installing Node ${version} failed (${install.reason}).`,
283
+ }, install.technical);
284
+ }
285
+ current = { version, dir: install.dir };
286
+ installedNow = true;
287
+ }
288
+ onProgress({ step: 'ready', version });
289
+ const nodeBinDir = `${current.dir}/bin`;
290
+ return {
291
+ managed: true,
292
+ version: current.version,
293
+ nodePath: `${nodeBinDir}/node`,
294
+ npmPath: `${nodeBinDir}/npm`,
295
+ npxPath: `${nodeBinDir}/npx`,
296
+ nodeBinDir,
297
+ installed: installedNow,
298
+ };
299
+ }
300
+ function resolveFailureDetail(reason, version) {
301
+ if (reason === 'no-fetch') {
302
+ return {
303
+ zh: '远端既没有 curl 也没有 wget,无法下载 Node。请安装其中一个后重试。',
304
+ en: 'The remote has neither curl nor wget, so Node cannot be downloaded. Install one of them and retry.',
305
+ };
306
+ }
307
+ if (reason === 'no-checksum') {
308
+ return {
309
+ zh: `没有在 Node 官方索引里找到 v${version} 的 linux 构建校验和。`,
310
+ en: `No linux build checksum was found in the official Node index for v${version}.`,
311
+ };
312
+ }
313
+ return {
314
+ zh: '无法从 nodejs.org / npmmirror.com 下载 Node(远端网络不可达或被拦截)。',
315
+ en: 'Node could not be downloaded from nodejs.org / npmmirror.com (the remote network is unreachable or blocked).',
316
+ };
317
+ }
318
+ export function applyManagedNodeFacts(facts, managed) {
319
+ return {
320
+ ...facts,
321
+ nodePath: managed.nodePath,
322
+ nodeBinDir: managed.nodeBinDir,
323
+ nodeVersion: normalizeVersion(managed.version),
324
+ npmPath: managed.npmPath ?? facts.npmPath,
325
+ npxPath: managed.npxPath,
326
+ };
327
+ }
@@ -0,0 +1,95 @@
1
+ /** One read-only remote probe: a single POSIX `sh` script prints `key<TAB>value` lines that become the facts used by
2
+ * the planner, the Node installer and diagnostics. */
3
+ import { headTail } from './util.js';
4
+ import { errors } from './errors.js';
5
+ import { normalizeVersion } from './version.js';
6
+ export function buildProbeScript() {
7
+ return `set -u
8
+ echo "os\t$(uname -s 2>/dev/null || echo unknown)"
9
+ echo "arch\t$(uname -m 2>/dev/null || echo unknown)"
10
+ echo "os_name\t$(sed -n 's/^PRETTY_NAME="\\(.*\\)"$/\\1/p' /etc/os-release 2>/dev/null | head -n 1)"
11
+ echo "user\t$(id -un 2>/dev/null || echo unknown)"
12
+ echo "home\t$HOME"
13
+ echo "shell\t\${SHELL:-unknown}"
14
+ NODE_PATH_1="$(command -v node 2>/dev/null || true)"
15
+ echo "node_path\t$NODE_PATH_1"
16
+ if [ -n "$NODE_PATH_1" ]; then echo "node_version\t$(timeout 10 "$NODE_PATH_1" -v 2>/dev/null || true)"; else echo "node_version\t"; fi
17
+ echo "npm_path\t$(command -v npm 2>/dev/null || true)"
18
+ echo "npx_path\t$(command -v npx 2>/dev/null || true)"
19
+ echo "curl_path\t$(command -v curl 2>/dev/null || true)"
20
+ echo "wget_path\t$(command -v wget 2>/dev/null || true)"
21
+ if [ -f /etc/alpine-release ]; then
22
+ echo "libc\tmusl"
23
+ elif command -v ldd >/dev/null 2>&1 && ldd --version 2>&1 | head -n 1 | grep -qi musl; then
24
+ echo "libc\tmusl"
25
+ else
26
+ echo "libc\tglibc"
27
+ fi
28
+ echo "glibc_version\t$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $2}' || true)"
29
+ echo "disk_free_kb\t$(df -Pk "$HOME" 2>/dev/null | awk 'NR==2 {print $4}' || true)"
30
+ if [ -n "\${SSH_CONNECTION:-}" ] || [ -n "\${SSH_TTY:-}" ]; then echo "ssh_connection\tyes"; else echo "ssh_connection\tno"; fi
31
+ [ -f "$HOME/.dsh/.credentials.yaml" ] && echo "credentials_file\tyes" || echo "credentials_file\tno"
32
+ if [ -n "\${DEEPSEEK_API_KEY:-}" ]; then echo "deepseek_key_env\tyes"; else echo "deepseek_key_env\tno"; fi
33
+ echo "provider_env_keys\t$(env 2>/dev/null | sed -n 's/^\\([A-Z0-9_]*\\)_API_KEY=.*/\\1/p' | tr '\\n' ',' | sed 's/,$//')"
34
+ `;
35
+ }
36
+ export function parseProbeOutput(stdout) {
37
+ const values = {};
38
+ for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
39
+ const tab = rawLine.indexOf('\t');
40
+ if (tab < 0)
41
+ continue;
42
+ const key = rawLine.slice(0, tab).trim();
43
+ const value = rawLine.slice(tab + 1).trim();
44
+ if (key !== '')
45
+ values[key] = value;
46
+ }
47
+ return values;
48
+ }
49
+ export function toProbeFacts(values) {
50
+ /** A measured number, or `null` when the remote reported nothing usable. */
51
+ const num = (value) => {
52
+ const n = Number(value);
53
+ return Number.isFinite(n) ? n : null;
54
+ };
55
+ return {
56
+ os: values.os || 'unknown',
57
+ arch: values.arch || 'unknown',
58
+ osName: values.os_name || '',
59
+ user: values.user || '',
60
+ home: values.home || '',
61
+ shell: values.shell || '',
62
+ nodePath: values.node_path || null,
63
+ nodeVersion: values.node_version ? normalizeVersion(values.node_version) : null,
64
+ npmPath: values.npm_path || null,
65
+ npxPath: values.npx_path || null,
66
+ curlPath: values.curl_path || null,
67
+ wgetPath: values.wget_path || null,
68
+ libc: values.libc === 'musl' ? 'musl' : values.libc === 'glibc' ? 'glibc' : 'unknown',
69
+ glibcVersion: values.glibc_version ? String(values.glibc_version).trim() : null,
70
+ diskFreeKb: num(values.disk_free_kb),
71
+ sshConnection: values.ssh_connection === 'yes',
72
+ credentialsFile: values.credentials_file === 'yes',
73
+ deepseekKeyEnv: values.deepseek_key_env === 'yes',
74
+ providerEnvKeys: values.provider_env_keys ? values.provider_env_keys.split(',').filter(Boolean) : [],
75
+ };
76
+ }
77
+ export async function probeRemote(ssh, options = {}) {
78
+ const timeoutMs = options.timeoutMs ?? 60_000;
79
+ const result = await ssh.exec(buildProbeScript(), { timeoutMs });
80
+ // A probe that ran out of time says nothing about the remote's DSH: report a retryable timeout, not a
81
+ // missing remote runtime.
82
+ if (result.timedOut === true) {
83
+ throw errors.network({
84
+ zh: `远端环境探测超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是链路很慢或远端负载过高。`,
85
+ en: `The remote environment probe did not finish within ${Math.round(timeoutMs / 1000)}s; the link may be slow or the remote overloaded.`,
86
+ }, { technical: `reason=probe-timeout timeoutMs=${timeoutMs}` });
87
+ }
88
+ if (result.code !== 0) {
89
+ throw errors.remoteDshMissing({
90
+ zh: `远端环境探测失败(退出码 ${result.code}):${headTail(result.stderr || result.stdout, 400)}`,
91
+ en: `Remote probe failed (exit ${result.code}): ${headTail(result.stderr || result.stdout, 400)}`,
92
+ });
93
+ }
94
+ return toProbeFacts(parseProbeOutput(result.stdout));
95
+ }
@@ -0,0 +1,198 @@
1
+ /** The two prompts a connection can pause on (unknown host key, foreign DSH running) and the Client's answers; each
2
+ * settles exactly once. Only the deferred slots and card data live here — the state writes belong to `dispatch.ts`. */
3
+ import { errors, toErrorView } from './errors.js';
4
+ import { dispatch, promptScopeFacts } from './runtime/dispatch.js';
5
+ import { createDecision, nowIso } from './util.js';
6
+ /** The effect owner of this module: a prompt transition publishes a frame and, for `conflict.answered`, clears the
7
+ * conflict card. The heavy effects are declared for one shape and throw if a rule asks this module to perform one. */
8
+ function promptEffects(ctx) {
9
+ const noEffect = (name) => {
10
+ throw new Error(`dispatch: the prompt module cannot perform the ${name} effect`);
11
+ };
12
+ return {
13
+ emit: () => ctx.emitState(),
14
+ log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
15
+ logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
16
+ arm: () => noEffect('arm'),
17
+ disarm: () => noEffect('disarm'),
18
+ settlePrompts: (runtime) => {
19
+ cancelHostKeyPrompt(runtime);
20
+ cancelConflict(runtime);
21
+ },
22
+ closeLink: () => noEffect('closeLink'),
23
+ teardown: async () => noEffect('teardown'),
24
+ apply: (runtime, patch) => {
25
+ if (patch.kind === 'clear-conflict') {
26
+ runtime.conflict = null;
27
+ return;
28
+ }
29
+ noEffect('apply');
30
+ },
31
+ flushLogs: () => {
32
+ // No prompt rule flushes the log ring.
33
+ },
34
+ };
35
+ }
36
+ /** Publish one prompt transition through this module's effect owner. */
37
+ function publish(ctx, runtime, event, caller) {
38
+ void dispatch(promptEffects(ctx), runtime, event, promptScopeFacts(runtime), { caller });
39
+ }
40
+ /** The two prompt slots are `unknown` on the runtime, and this module is their only writer. */
41
+ const pendingHostKeyOf = (runtime) => runtime.pendingHostKey;
42
+ const pendingConflictOf = (runtime) => runtime.pendingConflict;
43
+ /** A refusal the Client renders: the field it names and the bilingual reason. */
44
+ const reject = (field, zh, en) => errors.invalidInput(field, { zh, en });
45
+ /** Park the SSH handshake until the user answers the fingerprint prompt. The `role` decides which context the answer
46
+ * belongs to: a jump host and the target are different machines with different keys, so neither can cross over. */
47
+ export function requestHostKey(ctx, runtime, info, options = {}) {
48
+ const role = options.role === 'jump' ? 'jump' : 'target';
49
+ const isJump = role === 'jump';
50
+ // A per-host policy describes the saved target; a jump host has its own security context, so only the global applies.
51
+ const policy = isJump
52
+ ? (ctx.settings()?.hostKeyPolicy ?? 'first-use')
53
+ : (runtime.entry.hostKeyPolicy ?? ctx.settings()?.hostKeyPolicy ?? 'first-use');
54
+ if (policy === 'strict')
55
+ throw errors.hostKeyUnknown(info.sha256);
56
+ const where = isJump ? `jump host${options.host ? ` ${options.host}` : ''}` : 'host';
57
+ ctx.progress.log(runtime, 'info', `waiting for the ${where} key to be confirmed (${info.keyType} ${info.sha256}); the SSH handshake is paused`);
58
+ const pending = {
59
+ sha256: info.sha256,
60
+ keyType: info.keyType,
61
+ role,
62
+ host: typeof options.host === 'string' && options.host !== '' ? options.host : null,
63
+ port: Number(options.port) || 22,
64
+ resolve: null,
65
+ };
66
+ const decision = createDecision(ctx.timers.hostKeyConfirmMs, () => {
67
+ // A prompt whose link already went away must not overwrite the state of that teardown.
68
+ if (runtime.pendingHostKey !== pending)
69
+ return false;
70
+ if (runtime.desired !== 'connected' || runtime.closing === true)
71
+ return false;
72
+ // `hostkey.timeout` owns the `error` card and the "do not retry" flag; the slot is cleared here.
73
+ publish(ctx, runtime, { type: 'hostkey.timeout', view: toErrorView(errors.hostKeyUnknown(info.sha256)) }, 'timer');
74
+ runtime.pendingHostKey = null;
75
+ return false;
76
+ }, () => {
77
+ if (runtime.pendingHostKey === pending)
78
+ runtime.pendingHostKey = null;
79
+ });
80
+ pending.resolve = decision.settle;
81
+ runtime.pendingHostKey = pending;
82
+ // The card shows this while the prompt is open: nothing is pinned yet, so `pinned` stays null.
83
+ const fingerprint = {
84
+ sha256: info.sha256,
85
+ keyType: info.keyType,
86
+ status: 'pending',
87
+ pinned: null,
88
+ };
89
+ // The jump pin belongs to *this* jump host: an edited `jumpHost` must not be checked against the previous key.
90
+ // The dialog renders `HostView.fingerprint`, so it shows this pin now.
91
+ runtime.fingerprint = { ...fingerprint };
92
+ if (isJump)
93
+ runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port };
94
+ // The dialog data is in place before the transition publishes the frame that shows it.
95
+ publish(ctx, runtime, {
96
+ type: 'hostkey.pending',
97
+ info: { sha256: info.sha256, keyType: info.keyType },
98
+ role,
99
+ host: pending.host,
100
+ port: pending.port,
101
+ }, 'callback');
102
+ return decision.promise;
103
+ }
104
+ /** Answer the host-key prompt. Pinning is written straight through, so a failed attempt still remembers the accepted
105
+ * key; a jump key stays in memory — the store's `pinnedFingerprint` describes the target and would pin it wrongly. */
106
+ export async function confirmHostKey(ctx, runtime, decision) {
107
+ const pending = pendingHostKeyOf(runtime);
108
+ if (!pending)
109
+ throw reject('fingerprint', '没有待确认的主机指纹。', 'No host key is pending confirmation.');
110
+ // A prompt is answerable only while it is the live one: a timeout, a disconnect or a replacement already settled it.
111
+ if (runtime.status !== 'fingerprint-pending') {
112
+ throw reject('fingerprint', '这个指纹提示已经失效,请在下次连接时重新确认。', 'This host-key prompt is no longer active; confirm the key on the next connection.');
113
+ }
114
+ if (decision.sha256 && pending.sha256 && decision.sha256 !== pending.sha256) {
115
+ throw reject('fingerprint', '确认的指纹与待确认的不一致。', 'The confirmed fingerprint does not match the pending one.');
116
+ }
117
+ if (decision.accept && decision.remember && pending.role !== 'jump') {
118
+ await ctx.store.patchHost(runtime.id, { pinnedFingerprint: pending.sha256 });
119
+ runtime.entry = { ...runtime.entry, pinnedFingerprint: pending.sha256 };
120
+ }
121
+ const fingerprint = {
122
+ sha256: pending.sha256,
123
+ keyType: pending.keyType,
124
+ status: 'pinned',
125
+ pinned: decision.remember ? pending.sha256 : null,
126
+ };
127
+ if (pending.role === 'jump') {
128
+ // Keep the identity with the pin (it serves only the same jump host and port) and keep showing it until the dial.
129
+ runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port };
130
+ runtime.fingerprint = { ...fingerprint };
131
+ ctx.progress.log(runtime, 'info', `jump host key accepted${decision.remember ? ' and remembered for this session' : ''} (${pending.host ?? 'jump host'}: ${pending.sha256})`);
132
+ }
133
+ else {
134
+ runtime.fingerprint = fingerprint;
135
+ }
136
+ // `hostkey.answered` owns the `connecting` card and the "no" flag; its guard reads the slot, cleared after dispatch.
137
+ publish(ctx, runtime, { type: 'hostkey.answered', accept: decision.accept === true }, 'callback');
138
+ runtime.pendingHostKey = null;
139
+ pending.resolve(decision.accept === true);
140
+ return { ok: true };
141
+ }
142
+ /** Abandon a pending host-key prompt (teardown, host removal, lost transport): resolving `false` makes the stalled
143
+ * `verifyHostKey` throw instead of holding the connect promise open until the prompt times out. */
144
+ export function cancelHostKeyPrompt(runtime) {
145
+ const pending = pendingHostKeyOf(runtime);
146
+ runtime.pendingHostKey = null;
147
+ if (pending)
148
+ pending.resolve(false);
149
+ }
150
+ /** Pause the pipeline for a decision about foreign remote processes: a status, a promise, a bounded timeout. */
151
+ export function askConflict(ctx, runtime, processes) {
152
+ // The card data is in place before the transition publishes the frame that renders it.
153
+ runtime.conflict = {
154
+ detectedAt: nowIso(),
155
+ processes: processes.slice(0, 20).map((process) => ({
156
+ pid: process.pid,
157
+ command: String(process.command ?? '').slice(0, 400),
158
+ })),
159
+ };
160
+ // A prompt the user never sees (link cancelled just now) must not throw: its refusal is logged, the caller guards.
161
+ publish(ctx, runtime, { type: 'conflict.pending', count: processes.length }, 'callback');
162
+ const decision = createDecision(ctx.timers.conflictConfirmMs, () => ({ action: 'cancel', timedOut: true }), (value) => {
163
+ // The transition owns the cards and the "user said no" flag; a settlement after a teardown only clears the card.
164
+ if (runtime.status === 'conflict-pending') {
165
+ publish(ctx, runtime, { type: 'conflict.answered', action: value.action, ...(value.timedOut === true ? { timedOut: true } : {}) }, 'silent');
166
+ }
167
+ else {
168
+ runtime.conflict = null;
169
+ }
170
+ if (pendingConflictOf(runtime)?.resolve === decision.settle)
171
+ runtime.pendingConflict = null;
172
+ });
173
+ runtime.pendingConflict = { processes, resolve: decision.settle };
174
+ return decision.promise;
175
+ }
176
+ export function confirmConflict(runtime, decision) {
177
+ const pending = pendingConflictOf(runtime);
178
+ if (!pending)
179
+ throw reject('conflict', '没有待确认的远端 DSH 冲突。', 'No remote DSH conflict is pending confirmation.');
180
+ const action = decision?.action;
181
+ if (action !== 'stop' && action !== 'alongside' && action !== 'cancel') {
182
+ throw reject('conflict', '请选择停止手工实例、与它并存,或取消连接。', 'Choose whether to stop the manual instance, keep it alongside, or cancel.');
183
+ }
184
+ // The three-way guard above is the runtime proof; `ConflictDecision.action` is `unknown` on purpose (the Client's
185
+ // body), and inequality cannot narrow `unknown`, so this assertion only names the type the guard established.
186
+ pending.resolve({ action });
187
+ return { ok: true };
188
+ }
189
+ /** Abandon a pending conflict prompt (teardown): resolving `cancel` makes the stalled `askConflict` call return
190
+ * instead of holding the pipeline open. */
191
+ export function cancelConflict(runtime) {
192
+ const pending = pendingConflictOf(runtime);
193
+ // The answer is delivered while the slot is still installed (the settle hook reads it); both clears are idempotent.
194
+ if (pending)
195
+ pending.resolve({ action: 'cancel' });
196
+ runtime.pendingConflict = null;
197
+ runtime.conflict = null;
198
+ }