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.
Files changed (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/{src → dist/src}/constants.js +30 -56
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -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/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -1,521 +0,0 @@
1
- /**
2
- * The plugin's own Node.js runtime on the remote: an official build, SHA-256 verified, under `$DSH_HOME/remote-go/node`; commands are fixed templates, never user-composed.
3
- */
4
- import { errors } from './errors.js'
5
- import { headTail, messageOf, shellQuote } from './util.js'
6
- import { MIN_NODE_VERSION, normalizeVersion, parseVersion } from './version.js'
7
-
8
- export const NODE_DIST_BASES = Object.freeze(['https://nodejs.org/dist', 'https://npmmirror.com/mirrors/node'])
9
-
10
- export const MANAGED_NODE_VERSION_FALLBACK = MIN_NODE_VERSION
11
-
12
- export function managedNodeVersionFromEngine(range, fallback = MANAGED_NODE_VERSION_FALLBACK) {
13
- const text = String(range ?? '').trim()
14
- if (text === '') return normalizeVersion(fallback)
15
- const first = text.split('||')[0].trim()
16
- if (first === '' || first === '*' || first === 'latest') return normalizeVersion(fallback)
17
- // A strict `>` needs the next patch; `>=`, `^`, `~`, `=` and a bare version all
18
- // mean that version itself.
19
- const strict = /^>\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first)
20
- if (strict && !first.startsWith('>=')) {
21
- return normalizeVersion(`${Number(strict[1])}.${Number(strict[2] ?? 0)}.${Number(strict[3] ?? 0) + 1}`)
22
- }
23
- const match = /(?:>=|\^|~|=)?\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first)
24
- if (!match) return normalizeVersion(fallback)
25
- return normalizeVersion(`${Number(match[1])}.${Number(match[2] ?? 0)}.${Number(match[3] ?? 0)}`)
26
- }
27
-
28
- const NODE_SCAN_TIMEOUT_MS = 30_000
29
- const NODE_CHECKSUM_TIMEOUT_MS = 240_000
30
- const NODE_INSTALL_TIMEOUT_MS = 30 * 60_000
31
-
32
- const NODE_MIN_FREE_KB = 400 * 1024
33
-
34
- const NODE_MIN_GLIBC = '2.28'
35
-
36
- const DIST_ARCH = new Map([
37
- ['x86_64', 'x64'],
38
- ['amd64', 'x64'],
39
- ['aarch64', 'arm64'],
40
- ['arm64', 'arm64'],
41
- ['armv7l', 'armv7l'],
42
- ['armv7', 'armv7l'],
43
- ['ppc64le', 'ppc64le'],
44
- ['s390x', 's390x'],
45
- ])
46
-
47
- /**
48
- * Pick the downloader both install scripts share: curl when present, else wget.
49
- * Exit 9 is the "neither tool" contract the caller maps to `no-fetch`.
50
- */
51
- const FETCH_PROLOGUE = `if command -v curl >/dev/null 2>&1; then
52
- FETCH=curl
53
- elif command -v wget >/dev/null 2>&1; then
54
- FETCH=wget
55
- else
56
- printf 'FAILED\\tno-fetch\\n'
57
- exit 9
58
- fi`
59
-
60
- export function nodeDistArch(arch) {
61
- return DIST_ARCH.get(String(arch ?? '').toLowerCase()) ?? null
62
- }
63
-
64
- function compareGlibc(left, right) {
65
- const a = String(left ?? '').split('.')
66
- const b = String(right ?? '').split('.')
67
- const length = Math.max(a.length, b.length)
68
- for (let index = 0; index < length; index += 1) {
69
- const x = Number.parseInt(a[index] ?? '0', 10)
70
- const y = Number.parseInt(b[index] ?? '0', 10)
71
- const leftValue = Number.isFinite(x) ? x : 0
72
- const rightValue = Number.isFinite(y) ? y : 0
73
- if (leftValue !== rightValue) return leftValue < rightValue ? -1 : 1
74
- }
75
- return 0
76
- }
77
-
78
- export function buildNodeScanScript(layout) {
79
- return `set -u
80
- NODE_DIR=${shellQuote(layout.nodeDir)}
81
- if [ -d "$NODE_DIR" ]; then
82
- for DIR in "$NODE_DIR"/*; do
83
- [ -d "$DIR" ] || continue
84
- [ -x "$DIR/bin/node" ] || continue
85
- [ -x "$DIR/bin/npx" ] || continue
86
- VER=$("$DIR/bin/node" -v 2>/dev/null || true)
87
- case "$VER" in
88
- v[0-9]*) printf 'NODE\\t%s\\t%s\\n' "\${VER#v}" "$DIR" ;;
89
- esac
90
- done
91
- fi
92
- `
93
- }
94
-
95
- export function parseNodeScanOutput(stdout) {
96
- const versions = []
97
- for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
98
- const parts = rawLine.split('\t')
99
- if (parts[0] !== 'NODE' || parts.length < 3) continue
100
- const version = normalizeVersion(parts[1])
101
- if (!parseVersion(version)) continue
102
- if (versions.some((entry) => entry.version === version)) continue
103
- versions.push({ version, dir: parts[2] })
104
- }
105
- return versions
106
- }
107
-
108
- export function buildNodeChecksumScript(input) {
109
- const bases = (input.bases ?? NODE_DIST_BASES).map((base) => shellQuote(base)).join(' ')
110
- return `set -u
111
- DL=${shellQuote(input.downloadDir)}
112
- VERSION=${shellQuote(input.version)}
113
- FILE="node-v$VERSION-linux-${input.arch}.tar.gz"
114
- mkdir -p "$DL" || exit 3
115
- ${FETCH_PROLOGUE}
116
- fetch() {
117
- URL=$1
118
- OUT=$2
119
- if [ "$FETCH" = curl ]; then
120
- curl -fsSL --connect-timeout 10 --max-time 60 -o "$OUT" "$URL" 2>/dev/null
121
- else
122
- wget -q -T 30 -t 1 -O "$OUT" "$URL" 2>/dev/null
123
- fi
124
- }
125
- for BASE in ${bases}; do
126
- TMP="$DL/.shasums.$$"
127
- if fetch "$BASE/v$VERSION/SHASUMS256.txt" "$TMP"; then
128
- LINE=$(grep -F " $FILE" "$TMP" | head -n 1 || true)
129
- if [ -n "$LINE" ]; then
130
- SHA=$(printf '%s\\n' "$LINE" | awk '{print $1}')
131
- if [ "\${#SHA}" -eq 64 ]; then
132
- printf 'CHECKSUM\\t%s\\t%s\\n' "$BASE" "$SHA"
133
- rm -f "$TMP"
134
- exit 0
135
- fi
136
- fi
137
- fi
138
- rm -f "$TMP"
139
- done
140
- exit 5
141
- `
142
- }
143
-
144
- export function parseNodeChecksumOutput(stdout, input) {
145
- const file = `node-v${input.version}-linux-${input.arch}.tar.gz`
146
- const allowed = input.bases ?? NODE_DIST_BASES
147
- for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
148
- const parts = rawLine.split('\t')
149
- if (parts[0] !== 'CHECKSUM' || parts.length < 3) continue
150
- const [, base, sha256] = parts
151
- if (!allowed.includes(base)) continue
152
- if (!/^[0-9a-f]{64}$/.test(sha256)) continue
153
- return { base, version: input.version, sha256, file }
154
- }
155
- return null
156
- }
157
-
158
- export function buildNodeInstallScript(input) {
159
- const bases = (input.bases ?? NODE_DIST_BASES).map((base) => shellQuote(base)).join(' ')
160
- const { release } = input
161
- return `set -eu
162
- NODE_DIR=${shellQuote(input.layout.nodeDir)}
163
- DL=${shellQuote(input.layout.downloadDir)}
164
- VERSION=${shellQuote(release.version)}
165
- SHA=${shellQuote(release.sha256)}
166
- FILE=${shellQuote(release.file)}
167
- BINDIR="$NODE_DIR/v$VERSION"
168
- mkdir -p "$NODE_DIR" "$DL" || exit 3
169
- if [ -x "$BINDIR/bin/node" ] && [ "$("$BINDIR/bin/node" -v 2>/dev/null || true)" = "v$VERSION" ]; then
170
- printf 'READY\\t%s\\n' "$BINDIR"
171
- exit 0
172
- fi
173
- ${FETCH_PROLOGUE}
174
- verify() {
175
- TARGET=$1
176
- if command -v sha256sum >/dev/null 2>&1; then
177
- printf '%s %s\\n' "$SHA" "$TARGET" | sha256sum -c - >/dev/null 2>&1
178
- elif command -v shasum >/dev/null 2>&1; then
179
- printf '%s %s\\n' "$SHA" "$TARGET" | shasum -a 256 -c - >/dev/null 2>&1
180
- elif command -v openssl >/dev/null 2>&1; then
181
- GOT=$(openssl dgst -sha256 "$TARGET" 2>/dev/null | sed 's/.*= //')
182
- [ "$GOT" = "$SHA" ]
183
- else
184
- return 127
185
- fi
186
- }
187
- TARBALL="$DL/$FILE"
188
- if [ -f "$TARBALL" ] && verify "$TARBALL"; then
189
- echo "STEP\\treuse"
190
- else
191
- OK=0
192
- for BASE in ${bases}; do
193
- PART="$TARBALL.part.$$"
194
- rm -f "$PART"
195
- printf 'STEP\\tdownload\\t%s\\n' "$BASE"
196
- if [ "$FETCH" = curl ]; then
197
- curl -fsSL --connect-timeout 15 --max-time 600 -o "$PART" "$BASE/v$VERSION/$FILE" &
198
- else
199
- wget -q -T 60 -t 3 -O "$PART" "$BASE/v$VERSION/$FILE" &
200
- fi
201
- PID=$!
202
- while kill -0 "$PID" 2>/dev/null; do
203
- printf 'BYTES\\t%s\\n' "$(wc -c < "$PART" 2>/dev/null || echo 0)"
204
- sleep 2
205
- done
206
- if wait "$PID" && verify "$PART"; then
207
- mv "$PART" "$TARBALL"
208
- OK=1
209
- break
210
- fi
211
- printf 'FAILED\\tchecksum\\t%s\\n' "$BASE"
212
- rm -f "$PART"
213
- done
214
- if [ "$OK" -ne 1 ]; then
215
- echo "FAILED\\tdownload"
216
- exit 6
217
- fi
218
- fi
219
- echo "STEP\\textract"
220
- TMPX="$NODE_DIR/.extract.$$"
221
- rm -rf "$TMPX"
222
- mkdir -p "$TMPX"
223
- if ! tar -xzf "$TARBALL" -C "$TMPX" --strip-components=1; then
224
- echo "FAILED\\textract"
225
- rm -rf "$TMPX"
226
- exit 7
227
- fi
228
- if [ ! -x "$TMPX/bin/node" ]; then
229
- echo "FAILED\\textract"
230
- rm -rf "$TMPX"
231
- exit 7
232
- fi
233
- GOT=$("$TMPX/bin/node" -v 2>/dev/null || true)
234
- if [ "$GOT" != "v$VERSION" ]; then
235
- echo "FAILED\\tverify"
236
- rm -rf "$TMPX"
237
- exit 8
238
- fi
239
- rm -rf "$BINDIR"
240
- mv "$TMPX" "$BINDIR"
241
- rm -f "$TARBALL"
242
- for OLD in "$NODE_DIR"/v*; do
243
- [ -d "$OLD" ] || continue
244
- [ "$OLD" = "$BINDIR" ] && continue
245
- rm -rf "$OLD"
246
- done
247
- printf 'READY\\t%s\\n' "$BINDIR"
248
- `
249
- }
250
-
251
- function technicalOf(error) {
252
- return messageOf(error ?? '')
253
- }
254
-
255
- function nodeError(detail, technical) {
256
- return errors.nodeInstallFailed(detail, technical ? { technical } : undefined)
257
- }
258
-
259
- /** Run one remote command and normalize whatever shape the transport returned. */
260
- async function runRemote(ssh, command, options) {
261
- const result = await ssh.exec(command, options)
262
- return {
263
- code: typeof result?.code === 'number' ? result.code : 0,
264
- stdout: String(result?.stdout ?? ''),
265
- stderr: String(result?.stderr ?? ''),
266
- }
267
- }
268
-
269
- async function scanManagedNode(ssh, layout) {
270
- let result
271
- try {
272
- result = await runRemote(ssh, buildNodeScanScript(layout), {
273
- timeoutMs: NODE_SCAN_TIMEOUT_MS,
274
- maxBytes: 200_000,
275
- })
276
- } catch (error) {
277
- throw nodeError(
278
- { zh: '无法检查远端托管的 Node。', en: 'Could not inspect the managed Node on the remote.' },
279
- technicalOf(error),
280
- )
281
- }
282
- if (result.code !== 0) {
283
- throw nodeError(
284
- {
285
- zh: `无法检查远端托管的 Node(退出码 ${result.code})。`,
286
- en: `Could not inspect the managed Node on the remote (exit ${result.code}).`,
287
- },
288
- headTail(result.stderr || result.stdout, 800),
289
- )
290
- }
291
- return parseNodeScanOutput(result.stdout)
292
- }
293
-
294
- async function resolveNodeRelease(ssh, input) {
295
- let result
296
- try {
297
- result = await runRemote(
298
- ssh,
299
- buildNodeChecksumScript({
300
- downloadDir: input.layout.downloadDir,
301
- version: input.version,
302
- arch: input.arch,
303
- bases: input.bases,
304
- }),
305
- { timeoutMs: NODE_CHECKSUM_TIMEOUT_MS, maxBytes: 200_000 },
306
- )
307
- } catch (error) {
308
- // swallow-ok: unreachable — a transport failure is reported as a typed resolution
309
- // reason; the caller turns it into the install error.
310
- return { ok: false, reason: 'unreachable', technical: technicalOf(error) }
311
- }
312
- if (result.code === 0) {
313
- const release = parseNodeChecksumOutput(result.stdout, {
314
- version: input.version,
315
- arch: input.arch,
316
- bases: input.bases,
317
- })
318
- if (release) return { ok: true, release }
319
- return { ok: false, reason: 'no-checksum', technical: headTail(result.stdout, 600) }
320
- }
321
- if (result.code === 9 || result.stdout.includes('FAILED\tno-fetch')) {
322
- return { ok: false, reason: 'no-fetch' }
323
- }
324
- if (result.code === 5) {
325
- return { ok: false, reason: 'unreachable', technical: headTail(result.stderr || result.stdout, 600) }
326
- }
327
- return { ok: false, reason: 'unreachable', technical: headTail(`${result.stdout}\n${result.stderr}`, 600) }
328
- }
329
-
330
- async function installNodeRelease(ssh, input) {
331
- const expectedDir = `${input.layout.nodeDir}/v${input.release.version}`
332
- let buffered = ''
333
- let dir = null
334
- let failure = null
335
- let lastBytes = -1
336
- let lastEmit = 0
337
- const handleLine = (line) => {
338
- if (line === '') return
339
- const parts = line.split('\t')
340
- if (parts[0] === 'BYTES') {
341
- const bytes = Number(parts[1])
342
- if (!Number.isFinite(bytes) || bytes < 0) return
343
- const now = Date.now()
344
- if (bytes - lastBytes < 8 * 1024 * 1024 && now - lastEmit < 5000 && bytes !== 0) return
345
- lastBytes = bytes
346
- lastEmit = now
347
- input.onProgress({ step: 'download', version: input.release.version, bytes })
348
- return
349
- }
350
- if (parts[0] === 'STEP' && parts[1] === 'download') {
351
- input.onProgress({ step: 'download', version: input.release.version, bytes: 0, source: parts[2] })
352
- return
353
- }
354
- if (parts[0] === 'STEP' && parts[1] === 'extract') {
355
- input.onProgress({ step: 'extract', version: input.release.version })
356
- return
357
- }
358
- if (parts[0] === 'READY') {
359
- dir = parts[1] ?? null
360
- return
361
- }
362
- if (parts[0] === 'FAILED') {
363
- failure = parts.slice(1).filter(Boolean).join(' ') || 'failed'
364
- }
365
- }
366
- let result
367
- try {
368
- result = await runRemote(
369
- ssh,
370
- buildNodeInstallScript({ layout: input.layout, release: input.release, bases: input.bases }),
371
- {
372
- timeoutMs: NODE_INSTALL_TIMEOUT_MS,
373
- maxBytes: 400_000,
374
- onStdout: (chunk) => {
375
- buffered += String(chunk ?? '')
376
- const lines = buffered.split('\n')
377
- buffered = lines.pop() ?? ''
378
- for (const piece of lines) handleLine(piece.replace(/\r$/, ''))
379
- },
380
- },
381
- )
382
- } catch (error) {
383
- // swallow-ok: unreachable — same contract as the checksum step: the caller turns
384
- // it into the install error with the technical detail.
385
- return { ok: false, reason: 'unreachable', technical: technicalOf(error) }
386
- }
387
- if (result.code !== 0 || !dir) {
388
- return {
389
- ok: false,
390
- reason: failure ?? `exit ${result.code}`,
391
- technical: headTail(`${result.stdout}\n${result.stderr}`, 800),
392
- }
393
- }
394
- if (dir !== expectedDir) {
395
- return { ok: false, reason: 'unexpected-location', technical: dir }
396
- }
397
- return { ok: true, dir }
398
- }
399
-
400
- export async function ensureRemoteNode(ssh, options) {
401
- const facts = options.facts ?? {}
402
- const layout = options.layout
403
- const version = normalizeVersion(options.version ?? MANAGED_NODE_VERSION_FALLBACK)
404
- const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {}
405
- if (!layout?.nodeDir || !layout?.downloadDir) {
406
- throw errors.internal('remote layout is missing the managed Node directories')
407
- }
408
- if (!parseVersion(version)) throw errors.internal(`invalid managed Node version: ${version}`)
409
- if (!facts.home || !String(layout.nodeDir).startsWith('/')) {
410
- throw nodeError({
411
- zh: '远端主目录未知,无法准备托管的 Node。',
412
- en: 'The remote home directory is unknown, so the managed Node cannot be prepared.',
413
- })
414
- }
415
- if (String(facts.os ?? '') !== 'Linux') {
416
- // The official builds this module installs are Linux-only; refusing here keeps a
417
- // Darwin/Windows remote from downloading a binary that could never run.
418
- throw errors.unsupportedOs(`${facts.os ?? 'unknown'} ${facts.arch ?? ''}`.trim())
419
- }
420
- if (facts.libc === 'glibc' && facts.glibcVersion && compareGlibc(facts.glibcVersion, NODE_MIN_GLIBC) < 0) {
421
- throw nodeError({
422
- zh: `远端 glibc ${facts.glibcVersion} 过低,Node 官方 Linux 构建需要 ≥ ${NODE_MIN_GLIBC}。请升级系统后重试。`,
423
- en: `The remote glibc is ${facts.glibcVersion}, but the official Node Linux build needs >= ${NODE_MIN_GLIBC}. Upgrade the system and retry.`,
424
- })
425
- }
426
- if (facts.libc === 'musl') {
427
- throw nodeError({
428
- zh: '远端使用 musl libc(如 Alpine),Node 官方构建无法运行;插件只使用自己的 Node,请换用 glibc 系统(如 Ubuntu/Debian)。',
429
- 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).',
430
- })
431
- }
432
- const arch = nodeDistArch(facts.arch)
433
- if (!arch) {
434
- throw nodeError({
435
- zh: `远端架构「${facts.arch}」没有对应的 Node 官方构建。插件只使用自己的 Node,请换一台受支持的架构。`,
436
- en: `No official Node build exists for the remote architecture "${facts.arch}". The plugin only uses its own Node, so use a supported architecture.`,
437
- })
438
- }
439
- if (typeof facts.diskFreeKb === 'number' && facts.diskFreeKb > 0 && facts.diskFreeKb < NODE_MIN_FREE_KB) {
440
- throw nodeError({
441
- zh: `远端磁盘空间不足(可用约 ${Math.round(facts.diskFreeKb / 1024)} MB,至少需要 ${Math.round(NODE_MIN_FREE_KB / 1024)} MB)。`,
442
- 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).`,
443
- })
444
- }
445
-
446
- onProgress({ step: 'check', version })
447
- const installed = await scanManagedNode(ssh, layout)
448
- let current = installed.find((entry) => entry.version === version) ?? null
449
- let installedNow = false
450
- if (!current) {
451
- onProgress({ step: 'checksum', version })
452
- const resolved = await resolveNodeRelease(ssh, {
453
- layout,
454
- version,
455
- arch,
456
- bases: options.bases,
457
- })
458
- if (!resolved.ok) {
459
- throw nodeError(resolveFailureDetail(resolved.reason, version), resolved.technical ?? `reason=${resolved.reason}`)
460
- }
461
- onProgress({ step: 'install', version })
462
- const install = await installNodeRelease(ssh, {
463
- layout,
464
- release: resolved.release,
465
- bases: options.bases,
466
- onProgress,
467
- })
468
- if (!install.ok) {
469
- throw nodeError(
470
- {
471
- zh: `自动安装 Node ${version} 失败(${install.reason})。`,
472
- en: `Automatically installing Node ${version} failed (${install.reason}).`,
473
- },
474
- install.technical,
475
- )
476
- }
477
- current = { version, dir: install.dir }
478
- installedNow = true
479
- }
480
- onProgress({ step: 'ready', version })
481
- const nodeBinDir = `${current.dir}/bin`
482
- return {
483
- managed: true,
484
- version: current.version,
485
- nodePath: `${nodeBinDir}/node`,
486
- npmPath: `${nodeBinDir}/npm`,
487
- npxPath: `${nodeBinDir}/npx`,
488
- nodeBinDir,
489
- installed: installedNow,
490
- }
491
- }
492
-
493
- function resolveFailureDetail(reason, version) {
494
- if (reason === 'no-fetch') {
495
- return {
496
- zh: '远端既没有 curl 也没有 wget,无法下载 Node。请安装其中一个后重试。',
497
- en: 'The remote has neither curl nor wget, so Node cannot be downloaded. Install one of them and retry.',
498
- }
499
- }
500
- if (reason === 'no-checksum') {
501
- return {
502
- zh: `没有在 Node 官方索引里找到 v${version} 的 linux 构建校验和。`,
503
- en: `No linux build checksum was found in the official Node index for v${version}.`,
504
- }
505
- }
506
- return {
507
- zh: '无法从 nodejs.org / npmmirror.com 下载 Node(远端网络不可达或被拦截)。',
508
- en: 'Node could not be downloaded from nodejs.org / npmmirror.com (the remote network is unreachable or blocked).',
509
- }
510
- }
511
-
512
- export function applyManagedNodeFacts(facts, managed) {
513
- return {
514
- ...facts,
515
- nodePath: managed.nodePath,
516
- nodeBinDir: managed.nodeBinDir,
517
- nodeVersion: normalizeVersion(managed.version),
518
- npmPath: managed.npmPath ?? facts.npmPath,
519
- npxPath: managed.npxPath,
520
- }
521
- }
package/src/probe.js DELETED
@@ -1,101 +0,0 @@
1
- /**
2
- * One read-only remote probe: a single POSIX `sh` script prints `key<TAB>value` lines that become the facts used by the planner, the Node installer and diagnostics.
3
- */
4
- import { headTail } from './util.js'
5
- import { errors } from './errors.js'
6
- import { normalizeVersion } from './version.js'
7
-
8
- export function buildProbeScript() {
9
- return `set -u
10
- echo "os\t$(uname -s 2>/dev/null || echo unknown)"
11
- echo "arch\t$(uname -m 2>/dev/null || echo unknown)"
12
- echo "os_name\t$(sed -n 's/^PRETTY_NAME="\\(.*\\)"$/\\1/p' /etc/os-release 2>/dev/null | head -n 1)"
13
- echo "user\t$(id -un 2>/dev/null || echo unknown)"
14
- echo "home\t$HOME"
15
- echo "shell\t\${SHELL:-unknown}"
16
- NODE_PATH_1="$(command -v node 2>/dev/null || true)"
17
- echo "node_path\t$NODE_PATH_1"
18
- 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
19
- echo "npm_path\t$(command -v npm 2>/dev/null || true)"
20
- echo "npx_path\t$(command -v npx 2>/dev/null || true)"
21
- echo "curl_path\t$(command -v curl 2>/dev/null || true)"
22
- echo "wget_path\t$(command -v wget 2>/dev/null || true)"
23
- if [ -f /etc/alpine-release ]; then
24
- echo "libc\tmusl"
25
- elif command -v ldd >/dev/null 2>&1 && ldd --version 2>&1 | head -n 1 | grep -qi musl; then
26
- echo "libc\tmusl"
27
- else
28
- echo "libc\tglibc"
29
- fi
30
- echo "glibc_version\t$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $2}' || true)"
31
- echo "disk_free_kb\t$(df -Pk "$HOME" 2>/dev/null | awk 'NR==2 {print $4}' || true)"
32
- if [ -n "\${SSH_CONNECTION:-}" ] || [ -n "\${SSH_TTY:-}" ]; then echo "ssh_connection\tyes"; else echo "ssh_connection\tno"; fi
33
- [ -f "$HOME/.dsh/.credentials.yaml" ] && echo "credentials_file\tyes" || echo "credentials_file\tno"
34
- if [ -n "\${DEEPSEEK_API_KEY:-}" ]; then echo "deepseek_key_env\tyes"; else echo "deepseek_key_env\tno"; fi
35
- echo "provider_env_keys\t$(env 2>/dev/null | sed -n 's/^\\([A-Z0-9_]*\\)_API_KEY=.*/\\1/p' | tr '\\n' ',' | sed 's/,$//')"
36
- `
37
- }
38
-
39
- export function parseProbeOutput(stdout) {
40
- const values = {}
41
- for (const rawLine of String(stdout ?? '').split(/\r?\n/)) {
42
- const tab = rawLine.indexOf('\t')
43
- if (tab < 0) continue
44
- const key = rawLine.slice(0, tab).trim()
45
- const value = rawLine.slice(tab + 1).trim()
46
- if (key !== '') values[key] = value
47
- }
48
- return values
49
- }
50
-
51
- export function toProbeFacts(values) {
52
- const num = (/** @type {string} */ value) => {
53
- const n = Number(value)
54
- return Number.isFinite(n) ? n : null
55
- }
56
- return {
57
- os: values.os || 'unknown',
58
- arch: values.arch || 'unknown',
59
- osName: values.os_name || '',
60
- user: values.user || '',
61
- home: values.home || '',
62
- shell: values.shell || '',
63
- nodePath: values.node_path || null,
64
- nodeVersion: values.node_version ? normalizeVersion(values.node_version) : null,
65
- npmPath: values.npm_path || null,
66
- npxPath: values.npx_path || null,
67
- curlPath: values.curl_path || null,
68
- wgetPath: values.wget_path || null,
69
- libc: values.libc === 'musl' ? 'musl' : values.libc === 'glibc' ? 'glibc' : 'unknown',
70
- glibcVersion: values.glibc_version ? String(values.glibc_version).trim() : null,
71
- diskFreeKb: num(values.disk_free_kb),
72
- sshConnection: values.ssh_connection === 'yes',
73
- credentialsFile: values.credentials_file === 'yes',
74
- deepseekKeyEnv: values.deepseek_key_env === 'yes',
75
- providerEnvKeys: values.provider_env_keys ? values.provider_env_keys.split(',').filter(Boolean) : [],
76
- }
77
- }
78
-
79
- export async function probeRemote(ssh, options = {}) {
80
- const script = buildProbeScript()
81
- const timeoutMs = options.timeoutMs ?? 60_000
82
- const result = await ssh.exec(script, { timeoutMs })
83
- // A probe that ran out of time says nothing about the remote's DSH: report a timeout
84
- // (retryable network), not a missing remote runtime (L).
85
- if (result.timedOut === true) {
86
- throw errors.network(
87
- {
88
- zh: `远端环境探测超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是链路很慢或远端负载过高。`,
89
- en: `The remote environment probe did not finish within ${Math.round(timeoutMs / 1000)}s; the link may be slow or the remote overloaded.`,
90
- },
91
- { technical: `reason=probe-timeout timeoutMs=${timeoutMs}` },
92
- )
93
- }
94
- if (result.code !== 0) {
95
- throw errors.remoteDshMissing({
96
- zh: `远端环境探测失败(退出码 ${result.code}):${headTail(result.stderr || result.stdout, 400)}`,
97
- en: `Remote probe failed (exit ${result.code}): ${headTail(result.stderr || result.stdout, 400)}`,
98
- })
99
- }
100
- return toProbeFacts(parseProbeOutput(result.stdout))
101
- }