dsh-ris-ide 1.7.2 → 1.8.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 (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,798 @@
1
+ /**
2
+ * ProxyBridge bundle — download the redirector binaries on first use and cache
3
+ * them under `<home>/proxybridge/bundle`.
4
+ *
5
+ * The binaries used to ship inside the plugin (2.9 MB in `lib/vendor`). They are
6
+ * now published as `ris-proxy.4.0.tgz` and fetched the first time the Windows side
7
+ * is needed, so an install/lookup costs one HTTPS request instead of a bigger
8
+ * tarball. This module is deliberately self-contained and dependency-free:
9
+ * `redirector.js` (or a server route) passes `home` explicitly, and tests inject
10
+ * `fetchImpl`/bytes so nothing ever reaches the network.
11
+ *
12
+ * Layout of the tgz (relative to its root) is fixed by `bundleLayout()`; unknown
13
+ * entries are ignored, symlinks/absolute paths/traversal are rejected. An install
14
+ * lands in `<dir>.tmp-<pid>` first and is renamed into place, so a failed or
15
+ * concurrent download never leaves half a bundle behind.
16
+ *
17
+ * @module dsh-ris-ide/proxybridge-bundle
18
+ */
19
+ import { createHash } from 'node:crypto'
20
+ import {
21
+ existsSync,
22
+ mkdirSync,
23
+ readFileSync,
24
+ readdirSync,
25
+ renameSync,
26
+ rmSync,
27
+ statSync,
28
+ writeFileSync,
29
+ } from 'node:fs'
30
+ import { basename, dirname, join } from 'node:path'
31
+ import { gunzipSync } from 'node:zlib'
32
+
33
+ /** Bump when the manifest gains a meaning-changing field; old manifests are ignored. */
34
+ export const MANIFEST_VERSION = 1
35
+ /** Give up on a download after this long (a release asset is ~1 MB). */
36
+ export const DOWNLOAD_TIMEOUT_MS = 60_000
37
+ /** Refuse absurd downloads / decompression bombs (the real asset is ~1 MB). */
38
+ export const MAX_TGZ_BYTES = 16 * 1024 * 1024
39
+ export const MAX_TAR_BYTES = 64 * 1024 * 1024
40
+ /** Relative directory (under the proxy home) that holds the unpacked bundle. */
41
+ export const BUNDLE_DIRNAME = join('proxybridge', 'bundle')
42
+ /** Manifest file name inside that directory. */
43
+ export const MANIFEST_FILENAME = 'manifest.json'
44
+
45
+ /**
46
+ * Where the release asset lives. `ris-proxy.4.0.tgz` (ProxyBridge 4.0 bundle) is
47
+ * attached to the 1.8.0
48
+ * release on BOTH mirrors, so a blocked network on one side still installs:
49
+ * Gitee is the primary repository (the GitHub repo is a mirror), and it is tried
50
+ * first. Both URLs point at the same uploaded bytes.
51
+ */
52
+ export const BUNDLE_URLS = Object.freeze([
53
+ 'https://gitee.com/riscloud/dsh-ris-ide/releases/download/1.8.0/ris-proxy.4.0.tgz',
54
+ 'https://github.com/ris-cloud/dsh-ris-ide/releases/download/1.8.0/ris-proxy.4.0.tgz',
55
+ ])
56
+
57
+ /** Primary download location (kept for callers that display one address). */
58
+ export const DEFAULT_BUNDLE_URL = BUNDLE_URLS[0]
59
+
60
+ /**
61
+ * Pinned sha256 of the release asset `ris-proxy.4.0.tgz` (the 8 files below).
62
+ *
63
+ * The tgz contains native binaries — including the WinDivert kernel driver — and
64
+ * the Windows side starts them elevated. TLS alone is not a strong enough claim
65
+ * for that: a replaced release asset on either mirror would otherwise become
66
+ * elevated code execution (review B-P0-1). The release process sets this constant
67
+ * to the sha256 of the uploaded archive.
68
+ *
69
+ * An explicit empty value overrides the pin for local/lab mirrors:
70
+ * `DSH_RIS_IDE_PROXYBRIDGE_SHA256=''` or `settings.proxybridgeSha256: ''` means
71
+ * "trust on first use" — the first install records its sha256 in the manifest and
72
+ * every later cache hit/install is checked against that recorded value.
73
+ */
74
+ export const BUNDLE_SHA256 = '104456cb674206c2a1419e41825f698bd007351c7be524c23987509b35b31a53'
75
+
76
+ /** Env override for {@link BUNDLE_SHA256} (see its docs for the empty-string case). */
77
+ export const BUNDLE_SHA256_ENV = 'DSH_RIS_IDE_PROXYBRIDGE_SHA256'
78
+
79
+ /**
80
+ * Extra hosts a release-asset request may be redirected to. GitHub serves release
81
+ * downloads through a separate asset host; Gitee does the same for large uploads.
82
+ * A redirect to anything outside this set plus the configured mirror hosts is
83
+ * refused, so a mirror cannot silently hand the download to an unrelated host.
84
+ */
85
+ const BUNDLE_REDIRECT_HOSTS = Object.freeze([
86
+ 'release-assets.githubusercontent.com',
87
+ 'objects.githubusercontent.com',
88
+ 'github-releases.githubusercontent.com',
89
+ 'foruda.gitee.com',
90
+ ])
91
+
92
+ /** The files a usable bundle must contain, relative to the tgz root. */
93
+ const BUNDLE_FILES = Object.freeze([
94
+ 'LICENSE-ProxyBridge.txt',
95
+ 'NOTICE.md',
96
+ 'linux/ProxyBridge',
97
+ 'linux/libproxybridge.so',
98
+ 'windows/ProxyBridgeCore.dll',
99
+ 'windows/ProxyBridge_CLI.exe',
100
+ 'windows/WinDivert.dll',
101
+ 'windows/WinDivert64.sys',
102
+ ])
103
+
104
+ /** Reasonable hint for callers that want to show something actionable. */
105
+ const FAILURE_HINT = '已依次尝试 Gitee 与 GitHub 两个地址(见上方错误)。可检查网络/代理后重试;也可把 DSH_RIS_IDE_PROXYBRIDGE_URL 指向可访问的 ris-proxy.tgz(http 仅允许回环地址),或把该 tgz 手动上传。'
106
+
107
+ export function bundleLayout() {
108
+ return [...BUNDLE_FILES]
109
+ }
110
+
111
+ /** `<home>/proxybridge/bundle`, where `home` is the caller's `~/.dsh-ris-ide`. */
112
+ export function installDir(home) {
113
+ if (typeof home !== 'string' || home.trim() === '') throw new Error('home 必须是目录路径(例如 ~/.dsh-ris-ide)')
114
+ return join(home, BUNDLE_DIRNAME)
115
+ }
116
+
117
+ export function manifestPath(dir) {
118
+ return join(dir, MANIFEST_FILENAME)
119
+ }
120
+
121
+ /** Loopback hosts may use plain http in tests/local mirrors; everything else must be https. */
122
+ function isLoopbackHostname(hostname) {
123
+ const text = String(hostname ?? '').toLowerCase()
124
+ return text === '127.0.0.1' || text === 'localhost' || text === '[::1]' || text === '::1'
125
+ }
126
+
127
+ /** Empty string means "not configured"; an invalid URL throws with its source. */
128
+ function normalizeBundleUrl(value, source) {
129
+ const text = typeof value === 'string' ? value.trim() : ''
130
+ if (text === '') return ''
131
+ let parsed
132
+ try {
133
+ parsed = new URL(text)
134
+ } catch {
135
+ throw new Error(`${source} 不是合法 URL:${text}`)
136
+ }
137
+ if (parsed.protocol === 'https:') return parsed.toString()
138
+ if (parsed.protocol === 'http:' && isLoopbackHostname(parsed.hostname)) return parsed.toString()
139
+ throw new Error(`${source} 必须使用 https(http 只允许回环测试地址):${text}`)
140
+ }
141
+
142
+ /**
143
+ * Candidate tgz URLs in the order they are tried: explicit env/settings override
144
+ * (exactly one address, the caller asked for it) otherwise the mirror pair.
145
+ * @param {{env?: Record<string, string|undefined>, settings?: {proxybridgeUrl?: string}|null}} [options]
146
+ * @returns {string[]} absolute URLs.
147
+ */
148
+ export function resolveBundleUrls(options = {}) {
149
+ const env = options.env ?? process.env
150
+ const settings = options.settings ?? {}
151
+ const fromEnv = normalizeBundleUrl(env?.DSH_RIS_IDE_PROXYBRIDGE_URL, 'DSH_RIS_IDE_PROXYBRIDGE_URL')
152
+ if (fromEnv !== '') return [fromEnv]
153
+ const fromSettings = typeof settings === 'object' && settings !== null
154
+ ? normalizeBundleUrl(settings.proxybridgeUrl, 'settings.proxybridgeUrl')
155
+ : ''
156
+ if (fromSettings !== '') return [fromSettings]
157
+ return [...BUNDLE_URLS]
158
+ }
159
+
160
+ /** First candidate; the single-address view of {@link resolveBundleUrls}. */
161
+ export function resolveBundleUrl(options = {}) {
162
+ return resolveBundleUrls(options)[0]
163
+ }
164
+
165
+ /** Validate a sha256 digest; `''` means "not pinned" and is passed through. */
166
+ function normalizeSha256(value, source) {
167
+ const text = typeof value === 'string' ? value.trim().toLowerCase() : ''
168
+ if (text === '') return ''
169
+ if (/^[0-9a-f]{64}$/.test(text) !== true) {
170
+ throw new Error(`${source} 不是合法的 sha256(需要 64 位十六进制字符):${text}`)
171
+ }
172
+ return text
173
+ }
174
+
175
+ /**
176
+ * The sha256 the next install must match.
177
+ *
178
+ * Resolution order (the single place that decides it, review B-P0-1):
179
+ * 1. `DSH_RIS_IDE_PROXYBRIDGE_SHA256` (an explicit empty string = not pinned),
180
+ * 2. `settings.proxybridgeSha256` (same empty-string meaning),
181
+ * 3. the release constant {@link BUNDLE_SHA256}.
182
+ *
183
+ * @param {{env?: Record<string, string|undefined>, settings?: {proxybridgeSha256?: string}|null}} [options]
184
+ * @returns {string} lowercase digest, or `''` for "trust on first use".
185
+ */
186
+ export function resolveBundleSha256(options = {}) {
187
+ const env = options.env ?? process.env
188
+ if (env !== null && typeof env === 'object' && Object.prototype.hasOwnProperty.call(env, BUNDLE_SHA256_ENV) === true) {
189
+ return normalizeSha256(env[BUNDLE_SHA256_ENV], BUNDLE_SHA256_ENV)
190
+ }
191
+ const settings = options.settings ?? {}
192
+ if (settings !== null && typeof settings === 'object' && Object.prototype.hasOwnProperty.call(settings, 'proxybridgeSha256') === true) {
193
+ return normalizeSha256(settings.proxybridgeSha256, 'settings.proxybridgeSha256')
194
+ }
195
+ return BUNDLE_SHA256
196
+ }
197
+
198
+ /**
199
+ * Non-throwing variants for status/UI readers: a typo in `settings.json` or the
200
+ * env override must degrade to the built-in mirrors plus an error string, not
201
+ * fail the request (review B-P2: `GET /v1/proxybridge` returned 500 and hid the
202
+ * very diagnosis the maintenance card exists for).
203
+ * @returns `{urls, error}` / `{expectedSha256, error}`.
204
+ */
205
+ export function resolveBundleUrlsSafe(options = {}) {
206
+ try {
207
+ return { urls: resolveBundleUrls(options), error: '' }
208
+ } catch (error) {
209
+ return { urls: [...BUNDLE_URLS], error: error?.message ?? String(error) }
210
+ }
211
+ }
212
+
213
+ export function resolveBundleSha256Safe(options = {}) {
214
+ try {
215
+ return { expectedSha256: resolveBundleSha256(options), error: '' }
216
+ } catch (error) {
217
+ return { expectedSha256: BUNDLE_SHA256, error: error?.message ?? String(error) }
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Hosts a download (after following redirects) is allowed to come from: the
223
+ * built-in mirrors, the URL(s) being tried, the known release-asset hosts and
224
+ * anything listed in `DSH_RIS_IDE_PROXYBRIDGE_ALLOWED_HOSTS` (comma separated).
225
+ * @param {string[]} urls - the candidate URLs for this install.
226
+ * @param {Record<string, string|undefined>} [env]
227
+ * @returns {Set<string>}
228
+ */
229
+ function allowedDownloadHosts(urls, env = process.env) {
230
+ const hosts = new Set()
231
+ const add = (value) => {
232
+ try {
233
+ hosts.add(new URL(value).hostname.toLowerCase())
234
+ } catch {
235
+ // An invalid candidate was already rejected by normalizeBundleUrl; ignore it here.
236
+ }
237
+ }
238
+ for (const value of BUNDLE_URLS) add(value)
239
+ for (const value of urls) add(value)
240
+ for (const host of BUNDLE_REDIRECT_HOSTS) hosts.add(host)
241
+ const extra = typeof env?.DSH_RIS_IDE_PROXYBRIDGE_ALLOWED_HOSTS === 'string' ? env.DSH_RIS_IDE_PROXYBRIDGE_ALLOWED_HOSTS : ''
242
+ for (const part of extra.split(',')) {
243
+ const host = part.trim().toLowerCase()
244
+ if (host !== '') hosts.add(host)
245
+ }
246
+ return hosts
247
+ }
248
+
249
+ /** Read the manifest, or null when it is missing/unreadable/from another schema. */
250
+ export function readManifest(dir) {
251
+ try {
252
+ const parsed = JSON.parse(readFileSync(manifestPath(dir), 'utf8'))
253
+ if (parsed === null || typeof parsed !== 'object') return null
254
+ if (parsed.version !== MANIFEST_VERSION) return null
255
+ if (parsed.files === null || typeof parsed.files !== 'object') return null
256
+ return parsed
257
+ } catch {
258
+ return null
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Cheap install check: every expected file exists with the size recorded at
264
+ * install time, and — when `expectedSha256` is non-empty — the whole-archive
265
+ * digest in the manifest matches it. Content is *not* re-hashed here; use
266
+ * {@link verifyInstalled} before trusting a cache (review B-P0-1).
267
+ * @param {string} dir - the bundle install directory.
268
+ * @param {{expectedSha256?: string}} [options]
269
+ * @returns {boolean}
270
+ */
271
+ export function isInstalled(dir, options = {}) {
272
+ const expected = normalizeSha256(options.expectedSha256 ?? '', 'expectedSha256')
273
+ const manifest = readManifest(dir)
274
+ if (manifest === null) return false
275
+ if (expected !== '' && String(manifest.sha256 ?? '').toLowerCase() !== expected) return false
276
+ for (const rel of BUNDLE_FILES) {
277
+ const expectedSize = manifest.files[rel]
278
+ if (!Number.isInteger(expectedSize)) return false
279
+ try {
280
+ const stat = statSync(join(dir, ...rel.split('/')))
281
+ if (stat.isFile() !== true || stat.size !== expectedSize) return false
282
+ } catch {
283
+ return false
284
+ }
285
+ }
286
+ return true
287
+ }
288
+
289
+ /**
290
+ * Full content verification of an installed bundle (review B-P0-1).
291
+ *
292
+ * Hashing all 8 files is cheap (the bundle is ~1 MB), so download/upload finish
293
+ * with this check and `ensureBundle` runs it before trusting a cache hit. It
294
+ * catches same-size corruption that {@link isInstalled} cannot see. Installs
295
+ * written by an older version have no per-file hashes and are therefore reported
296
+ * as unverified (callers reinstall).
297
+ *
298
+ * @param {{home?: string, dir?: string, expectedSha256?: string}} options
299
+ * @returns {{ok: boolean, dir: string, reason: string, expected: string, actual: string, files: string[]}}
300
+ */
301
+ export function verifyInstalled(options = {}) {
302
+ const dir = typeof options.dir === 'string' && options.dir !== ''
303
+ ? options.dir
304
+ : (typeof options.home === 'string' && options.home !== '' ? installDir(options.home) : '')
305
+ const expected = normalizeSha256(options.expectedSha256 ?? '', 'expectedSha256')
306
+ const fail = (reason) => ({ ok: false, dir, reason, expected, actual: typeof options.expectedSha256 === 'string' ? options.expectedSha256 : '', files: [] })
307
+ if (dir === '') return fail('没有指定 bundle 安装目录')
308
+ const manifest = readManifest(dir)
309
+ if (manifest === null) return fail('没有可用的安装记录(manifest.json 缺失或损坏)')
310
+ const actual = String(manifest.sha256 ?? '').toLowerCase()
311
+ if (expected !== '' && actual !== expected) {
312
+ return { ok: false, dir, reason: `安装记录的 sha256 与固定值不一致(期望 ${expected},实际 ${actual || '空'})`, expected, actual, files: [] }
313
+ }
314
+ const hashes = manifest.fileHashes !== null && typeof manifest.fileHashes === 'object' ? manifest.fileHashes : null
315
+ const files = []
316
+ for (const rel of BUNDLE_FILES) {
317
+ const size = manifest.files[rel]
318
+ if (!Number.isInteger(size)) return fail(`安装记录缺少 ${rel} 的大小`)
319
+ const full = join(dir, ...rel.split('/'))
320
+ let buffer
321
+ try {
322
+ const stat = statSync(full)
323
+ if (stat.isFile() !== true) return fail(`${rel} 不是普通文件`)
324
+ if (stat.size !== size) return fail(`${rel} 的大小与安装记录不一致(${stat.size} ≠ ${size})`)
325
+ buffer = readFileSync(full)
326
+ } catch {
327
+ return fail(`缺少文件:${rel}`)
328
+ }
329
+ const recorded = typeof hashes?.[rel] === 'string' ? hashes[rel].toLowerCase() : ''
330
+ if (recorded === '') return fail(`旧版安装缺少 ${rel} 的逐文件哈希,请重新安装`)
331
+ const computed = sha256Of(buffer)
332
+ if (computed !== recorded) return fail(`${rel} 的内容与安装记录不一致(可能被篡改或损坏)`)
333
+ files.push(rel)
334
+ }
335
+ return { ok: true, dir, reason: '', expected, actual, files }
336
+ }
337
+
338
+ const TAR_BLOCK = 512
339
+
340
+ /** Parse an octal numeric field (NUL/space padded); reject GNU base-256 values. */
341
+ function readOctal(field, label) {
342
+ if (field.length > 0 && (field[0] & 0x80) !== 0) throw new Error(`tgz 头部的 ${label} 使用了不支持的 base-256 编码`)
343
+ const text = field.toString('ascii').replace(/[\0 ]+$/g, '').replace(/^ +/g, '')
344
+ if (text === '') return 0
345
+ const value = Number.parseInt(text, 8)
346
+ if (Number.isFinite(value) !== true) throw new Error(`tgz 头部的 ${label} 不是合法的八进制数`)
347
+ return value
348
+ }
349
+
350
+ /** Join ustar `prefix` + `name`, strip a leading `./`, then validate the path. */
351
+ function tarEntryName(header) {
352
+ const name = header.subarray(0, 100).toString('utf8').replace(/\0[\s\S]*$/, '')
353
+ const prefix = header.subarray(345, 500).toString('utf8').replace(/\0[\s\S]*$/, '')
354
+ let full = prefix === '' ? name : `${prefix}/${name}`
355
+ while (full.startsWith('./')) full = full.slice(2)
356
+ full = full.replace(/\/+$/, '')
357
+ if (full === '') return ''
358
+ if (full.startsWith('/') || /^[A-Za-z]:[\\/]/.test(full) === true) throw new Error(`tgz 含绝对路径,拒绝安装:${full}`)
359
+ const segments = full.split('/')
360
+ if (segments.some((segment) => segment === '..' || segment === '.' || segment === '')) {
361
+ throw new Error(`tgz 含不安全的路径,拒绝安装:${full}`)
362
+ }
363
+ return full
364
+ }
365
+
366
+ /**
367
+ * Minimal ustar reader: regular files only (directories skipped), checksums
368
+ * verified. Returns a Map of `relativePath → Buffer` for the requested layout.
369
+ */
370
+ function parseTar(buffer, wanted) {
371
+ const entries = new Map()
372
+ let offset = 0
373
+ while (offset + TAR_BLOCK <= buffer.length) {
374
+ const header = buffer.subarray(offset, offset + TAR_BLOCK)
375
+ if (header.every((byte) => byte === 0)) break
376
+ const storedChecksum = readOctal(header.subarray(148, 156), 'checksum')
377
+ let actualChecksum = 0
378
+ for (let index = 0; index < TAR_BLOCK; index += 1) {
379
+ actualChecksum += index >= 148 && index < 156 ? 0x20 : header[index]
380
+ }
381
+ if (actualChecksum !== storedChecksum) throw new Error('tgz 头部校验和错误(文件已损坏)')
382
+ const size = readOctal(header.subarray(124, 136), 'size')
383
+ const typeflag = String.fromCharCode(header[156] === 0 ? 0x30 : header[156])
384
+ const name = tarEntryName(header)
385
+ const dataStart = offset + TAR_BLOCK
386
+ const dataEnd = dataStart + size
387
+ if (dataEnd > buffer.length) throw new Error(`tgz 已截断:${name}`)
388
+ offset = dataStart + Math.ceil(size / TAR_BLOCK) * TAR_BLOCK
389
+ if (name === '') continue
390
+ if (typeflag === '5') continue // directory
391
+ if (typeflag === '2' || typeflag === '1') throw new Error(`tgz 含符号链接/硬链接,拒绝安装:${name}`)
392
+ // pax/global headers (`x`, `g`) and any other extension are deliberately not
393
+ // supported: the entry they describe is reapplied by the tar writer with a
394
+ // truncated ustar name, so a bundle packed with long paths fails closed with
395
+ // `tgz 缺少文件` instead of being installed under a wrong name. The shipped
396
+ // bundle's file names are all well below the 100-byte ustar limit.
397
+ if (typeflag !== '0') continue
398
+ if (wanted.has(name) !== true) continue // unknown entries are ignored
399
+ entries.set(name, Buffer.from(buffer.subarray(dataStart, dataEnd)))
400
+ }
401
+ const missing = [...wanted].filter((name) => entries.has(name) !== true)
402
+ if (missing.length > 0) throw new Error(`tgz 缺少文件:${missing.join('、')}`)
403
+ return entries
404
+ }
405
+
406
+ /** gunzip + parse + require the full layout. */
407
+ function extractBundle(bytes) {
408
+ if (Buffer.isBuffer(bytes) !== true || bytes.length === 0) throw new Error('tgz 内容为空')
409
+ if (bytes.length > MAX_TGZ_BYTES) throw new Error(`tgz 内容过大(${bytes.length} 字节,上限 ${MAX_TGZ_BYTES})`)
410
+ let tar
411
+ try {
412
+ tar = gunzipSync(bytes, { maxOutputLength: MAX_TAR_BYTES })
413
+ } catch (error) {
414
+ if (error?.code === 'ERR_BUFFER_TOO_LARGE' || error?.code === 'ERR_OUT_OF_RANGE') {
415
+ throw new Error(`tgz 解压后过大(上限 ${MAX_TAR_BYTES} 字节)`)
416
+ }
417
+ throw new Error('不是合法的 .tgz(gzip 解压失败)')
418
+ }
419
+ return parseTar(tar, new Set(BUNDLE_FILES))
420
+ }
421
+
422
+ /** Binaries need +x; text files do not. */
423
+ function fileMode(rel) {
424
+ return /(?:^|\/)(?:ProxyBridge|libproxybridge\.so)$|\.(?:exe|dll|sys)$/i.test(rel) === true ? 0o755 : 0o644
425
+ }
426
+
427
+ function sha256Of(bytes) {
428
+ return createHash('sha256').update(bytes).digest('hex')
429
+ }
430
+
431
+ /** How old a leftover `<dir>.tmp-*` / `<dir>.old-*` must be before it is removed. */
432
+ const STALE_INSTALL_MS = 60 * 60 * 1000
433
+
434
+ /**
435
+ * Remove abandoned staging/backup directories of earlier (crashed) installs.
436
+ * Only directories older than `maxAgeMs` are touched, so a concurrent install in
437
+ * another process is not disturbed (review B-P2 安装残留).
438
+ * @param {string} dir - the bundle install directory.
439
+ * @param {{maxAgeMs?: number}} [options]
440
+ * @returns {string[]} names removed.
441
+ */
442
+ export function cleanupStaleInstalls(dir, options = {}) {
443
+ const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : STALE_INSTALL_MS
444
+ const parent = dirname(dir)
445
+ const base = basename(dir)
446
+ const removed = []
447
+ let names
448
+ try {
449
+ names = readdirSync(parent)
450
+ } catch {
451
+ return removed
452
+ }
453
+ const now = Date.now()
454
+ for (const name of names) {
455
+ const isStaging = name.startsWith(`${base}.tmp-`) === true || name.startsWith(`${base}.old-`) === true
456
+ if (isStaging !== true) continue
457
+ const full = join(parent, name)
458
+ try {
459
+ const stat = statSync(full)
460
+ if (now - stat.mtimeMs < maxAgeMs) continue
461
+ rmSync(full, { recursive: true, force: true })
462
+ removed.push(name)
463
+ } catch {
464
+ // Another process may be removing it right now; nothing to do.
465
+ }
466
+ }
467
+ return removed
468
+ }
469
+
470
+ /** Write a complete tree into `<dir>.tmp-<pid>`, then swap it in atomically. */
471
+ function writeInstall({ dir, url, sha256, files, source = 'download' }) {
472
+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 })
473
+ cleanupStaleInstalls(dir)
474
+ // A daemon can install two bundles at once (an upload while a download is in
475
+ // flight). Staging paths are therefore unique per attempt, not per process —
476
+ // a shared name would let the second attempt `rm -rf` the first one's work.
477
+ const attempt = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
478
+ const tmp = `${dir}.tmp-${attempt}`
479
+ rmSync(tmp, { recursive: true, force: true })
480
+ const backup = `${dir}.old-${attempt}`
481
+ try {
482
+ for (const [rel, content] of files) {
483
+ const to = join(tmp, ...rel.split('/'))
484
+ mkdirSync(dirname(to), { recursive: true, mode: 0o700 })
485
+ writeFileSync(to, content, { mode: fileMode(rel) })
486
+ }
487
+ const manifest = {
488
+ version: MANIFEST_VERSION,
489
+ url,
490
+ sha256,
491
+ source,
492
+ installedAt: new Date().toISOString(),
493
+ files: Object.fromEntries([...files].map(([rel, content]) => [rel, content.length])),
494
+ // Per-file digests let a later cache hit detect same-size tampering/corruption.
495
+ fileHashes: Object.fromEntries([...files].map(([rel, content]) => [rel, sha256Of(content)])),
496
+ }
497
+ writeFileSync(manifestPath(tmp), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 })
498
+ rmSync(backup, { recursive: true, force: true })
499
+ let hadPrevious = false
500
+ if (existsSync(dir) === true) {
501
+ renameSync(dir, backup)
502
+ hadPrevious = true
503
+ }
504
+ try {
505
+ renameSync(tmp, dir)
506
+ } catch (error) {
507
+ if (hadPrevious === true) {
508
+ try {
509
+ renameSync(backup, dir)
510
+ } catch {
511
+ throw new Error(`切换 bundle 安装目录失败(${error?.message ?? String(error)});旧安装保留在 ${backup},请手动恢复`)
512
+ }
513
+ }
514
+ throw error
515
+ }
516
+ if (hadPrevious === true) rmSync(backup, { recursive: true, force: true })
517
+ } catch (error) {
518
+ rmSync(tmp, { recursive: true, force: true })
519
+ throw error
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Download and buffer an archive, refusing oversized bodies and untrusted hosts
525
+ * (review B-P0-1 / B-P1-1).
526
+ *
527
+ * - The host of the *final* URL (after redirects) must be in `allowedHosts`.
528
+ * - `content-length` over the cap is refused before any body is read.
529
+ * - A streaming body is accumulated with a hard cap; cancel it as soon as the
530
+ * cap is crossed so a runaway response cannot be buffered into memory.
531
+ */
532
+ async function downloadBytes(url, fetchImpl, options = {}) {
533
+ const doFetch = typeof fetchImpl === 'function' ? fetchImpl : globalThis.fetch
534
+ if (typeof doFetch !== 'function') throw new Error('当前 Node 没有 fetch,无法下载内置 ProxyBridge(需要 Node 18+)')
535
+ let response
536
+ try {
537
+ response = await doFetch(url, { redirect: 'follow', signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) })
538
+ } catch (error) {
539
+ if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
540
+ throw new Error(`下载超时(${Math.round(DOWNLOAD_TIMEOUT_MS / 1000)}s):${url}`)
541
+ }
542
+ throw new Error(`下载失败:${error?.message ?? String(error)}(${url})`)
543
+ }
544
+ if (response?.ok !== true) throw new Error(`下载失败:HTTP ${response?.status ?? '?'}(${url})`)
545
+ const finalUrl = typeof response.url === 'string' && response.url !== '' ? response.url : url
546
+ let finalHost = ''
547
+ try {
548
+ finalHost = new URL(finalUrl).hostname.toLowerCase()
549
+ } catch {
550
+ finalHost = ''
551
+ }
552
+ const allowed = options.allowedHosts instanceof Set ? options.allowedHosts : null
553
+ if (allowed !== null && allowed.has(finalHost) !== true) {
554
+ throw Object.assign(
555
+ new Error(`下载被重定向到不受信任的主机 ${finalHost || finalUrl}(${finalUrl});已取消安装。请把该主机加入 DSH_RIS_IDE_PROXYBRIDGE_ALLOWED_HOSTS,或改用官方镜像`),
556
+ { code: 'untrusted-host', host: finalHost, url: finalUrl },
557
+ )
558
+ }
559
+ const declared = Number.parseInt(String(response.headers?.get?.('content-length') ?? ''), 10)
560
+ if (Number.isFinite(declared) === true && declared > MAX_TGZ_BYTES) {
561
+ throw Object.assign(
562
+ new Error(`下载内容过大:服务端声明 ${declared} 字节,上限 ${MAX_TGZ_BYTES} 字节`),
563
+ { code: 'too-large', declared, limit: MAX_TGZ_BYTES },
564
+ )
565
+ }
566
+ const chunks = []
567
+ let total = 0
568
+ const stream = response.body
569
+ if (stream !== null && typeof stream === 'object' && typeof stream[Symbol.asyncIterator] === 'function') {
570
+ for await (const chunk of stream) {
571
+ const buffer = Buffer.isBuffer(chunk) === true ? chunk : Buffer.from(chunk)
572
+ total += buffer.length
573
+ if (total > MAX_TGZ_BYTES) {
574
+ try {
575
+ await stream.cancel?.()
576
+ } catch {
577
+ // The response is being discarded anyway.
578
+ }
579
+ throw Object.assign(
580
+ new Error(`下载内容过大(超过 ${MAX_TGZ_BYTES} 字节上限),已中止`),
581
+ { code: 'too-large', limit: MAX_TGZ_BYTES },
582
+ )
583
+ }
584
+ chunks.push(buffer)
585
+ }
586
+ } else {
587
+ const body = await response.arrayBuffer()
588
+ const buffer = Buffer.from(body ?? [])
589
+ total = buffer.length
590
+ if (total > MAX_TGZ_BYTES) {
591
+ throw Object.assign(
592
+ new Error(`下载内容过大(${total} 字节,上限 ${MAX_TGZ_BYTES} 字节)`),
593
+ { code: 'too-large', declared: total, limit: MAX_TGZ_BYTES },
594
+ )
595
+ }
596
+ chunks.push(buffer)
597
+ }
598
+ const bytes = Buffer.concat(chunks, total)
599
+ if (bytes.length === 0) throw new Error(`下载内容为空:${url}`)
600
+ return bytes
601
+ }
602
+
603
+ /**
604
+ * Download `url` and install it into `<home>/proxybridge/bundle`.
605
+ * Throws on any failure (network, host, archive, layout, digest) and never writes
606
+ * a mismatching archive: the digest is checked *before* extraction (review B-P0-1).
607
+ * @param {{home: string, url: string, fetchImpl?: typeof fetch, expectedSha256?: string, env?: Record<string,string|undefined>}} options
608
+ * @returns {Promise<{ok: true, dir: string, files: string[], fileCount: number, bytes: number, fromCache: false, sha256: string, url: string}>}
609
+ */
610
+ export async function downloadAndInstall(options = {}) {
611
+ const { home, fetchImpl } = options
612
+ const url = normalizeBundleUrl(options.url, 'url')
613
+ if (url === '') throw new Error('url 不能为空')
614
+ const expected = normalizeSha256(options.expectedSha256 ?? '', 'expectedSha256')
615
+ const dir = installDir(home)
616
+ const allowedHosts = allowedDownloadHosts([url], options.env ?? process.env)
617
+ const bytes = await downloadBytes(url, fetchImpl, { allowedHosts })
618
+ const sha256 = sha256Of(bytes)
619
+ if (expected !== '' && sha256 !== expected) {
620
+ throw Object.assign(
621
+ new Error(`下载内容与固定 sha256 不一致(期望 ${expected},实际 ${sha256});已拒绝安装。请确认镜像/代理没有替换发布物,或更新固定值`),
622
+ { code: 'hash-mismatch', expected, actual: sha256 },
623
+ )
624
+ }
625
+ const files = extractBundle(bytes)
626
+ writeInstall({ dir, url, sha256, files, source: 'download' })
627
+ return { ok: true, dir, files: [...files.keys()], fileCount: files.size, bytes: bytes.length, fromCache: false, sha256, url }
628
+ }
629
+
630
+ /**
631
+ * Install a bundle the caller already has (upload / offline copy). The manifest
632
+ * records the *real* archive digest, not a placeholder (review B-P0-1).
633
+ * @param {{home: string, bytes: Buffer|Uint8Array, expectedSha256?: string}} options
634
+ * @returns {{ok: true, dir: string, files: string[], fileCount: number, bytes: number, fromCache: false, sha256: string, url: 'upload'}}
635
+ */
636
+ export function installFromTgz(options = {}) {
637
+ const { home, bytes } = options
638
+ const dir = installDir(home)
639
+ const buffer = Buffer.isBuffer(bytes) === true ? bytes : Buffer.from(bytes ?? [])
640
+ const sha256 = sha256Of(buffer)
641
+ const expected = normalizeSha256(options.expectedSha256 ?? '', 'expectedSha256')
642
+ if (expected !== '' && sha256 !== expected) {
643
+ throw Object.assign(
644
+ new Error(`上传的压缩包与固定 sha256 不一致(期望 ${expected},实际 ${sha256});已拒绝安装`),
645
+ { code: 'hash-mismatch', expected, actual: sha256 },
646
+ )
647
+ }
648
+ const files = extractBundle(buffer)
649
+ writeInstall({ dir, url: 'upload', sha256, files, source: 'upload' })
650
+ const verdict = verifyInstalled({ dir, expectedSha256: sha256 })
651
+ if (verdict.ok !== true) throw new Error(`安装后自检失败:${verdict.reason}`)
652
+ return { ok: true, dir, files: [...files.keys()], fileCount: files.size, bytes: buffer.length, fromCache: false, sha256, url: 'upload' }
653
+ }
654
+
655
+ /**
656
+ * Make sure a bundle is installed: reuse a verified cache, otherwise download it.
657
+ * Never throws — a caller (plugin proxy route, CLI) gets `{ok:false}` with the
658
+ * attempted URL and an actionable hint instead.
659
+ * @param {{home: string, url?: string, settings?: {proxybridgeUrl?: string, proxybridgeSha256?: string}, env?: Record<string,string|undefined>, fetchImpl?: typeof fetch, force?: boolean, expectedSha256?: string}} [options]
660
+ * @returns {Promise<Record<string, any>>}
661
+ */
662
+ export async function ensureBundle(options = {}) {
663
+ const { home, fetchImpl, force = false } = options
664
+ const env = options.env ?? process.env
665
+ const settings = options.settings ?? {}
666
+ let dir = ''
667
+ let urls = []
668
+ try {
669
+ const explicit = typeof options.url === 'string' ? normalizeBundleUrl(options.url, 'url') : ''
670
+ urls = explicit === '' ? resolveBundleUrls({ env, settings }) : [explicit]
671
+ const expected = options.expectedSha256 !== undefined
672
+ ? normalizeSha256(options.expectedSha256, 'expectedSha256')
673
+ : resolveBundleSha256({ env, settings })
674
+ dir = installDir(home)
675
+ const manifest = readManifest(dir)
676
+ // `upload` installs are local trust decisions; the pin only guards the network.
677
+ const expectedForCache = manifest?.source === 'upload' ? '' : expected
678
+ const cacheUsable = isInstalled(dir, { expectedSha256: expectedForCache }) === true
679
+ && verifyInstalled({ dir, expectedSha256: '' }).ok === true
680
+ const cacheResult = () => {
681
+ const fresh = readManifest(dir) ?? manifest
682
+ return {
683
+ ok: true,
684
+ dir,
685
+ files: fresh === null ? [] : Object.keys(fresh.files),
686
+ fileCount: fresh === null ? 0 : Object.keys(fresh.files).length,
687
+ bytes: 0,
688
+ fromCache: true,
689
+ sha256: fresh?.sha256 ?? '',
690
+ url: fresh?.url ?? urls[0],
691
+ urls,
692
+ tried: [],
693
+ expectedSha256: expected,
694
+ ...(manifest?.source === 'upload' && expected !== '' && String(manifest?.sha256 ?? '') !== expected
695
+ ? { warning: `已安装的组件来自本机上传,其 sha256 与固定值不一致(${manifest?.sha256 ?? '空'} ≠ ${expected});按本机信任继续使用` }
696
+ : {}),
697
+ }
698
+ }
699
+ if (force !== true && cacheUsable === true) return cacheResult()
700
+ const tried = []
701
+ for (const url of urls) {
702
+ try {
703
+ return Object.assign(await downloadAndInstall({ home, url, fetchImpl, expectedSha256: expected, env }), { urls, tried, expectedSha256: expected })
704
+ } catch (error) {
705
+ // Keep the machine-readable fields: the route layer maps `hash-mismatch`
706
+ // to its own repair instruction, and needs the expected/actual digests.
707
+ tried.push({
708
+ url,
709
+ error: error?.message ?? String(error),
710
+ ...(typeof error?.code === 'string' ? { code: error.code } : {}),
711
+ ...(error?.expected !== undefined ? { expected: error.expected } : {}),
712
+ ...(error?.actual !== undefined ? { actual: error.actual } : {}),
713
+ })
714
+ }
715
+ }
716
+ // A failed refresh must not hide a still-usable cache (review B-P2 force 回退).
717
+ if (isInstalled(dir) === true && verifyInstalled({ dir, expectedSha256: '' }).ok === true) {
718
+ const fresh = readManifest(dir)
719
+ return {
720
+ ok: true,
721
+ dir,
722
+ files: fresh === null ? [] : Object.keys(fresh.files),
723
+ fileCount: fresh === null ? 0 : Object.keys(fresh.files).length,
724
+ bytes: 0,
725
+ fromCache: true,
726
+ sha256: fresh?.sha256 ?? '',
727
+ url: fresh?.url ?? urls[0],
728
+ urls,
729
+ tried,
730
+ expectedSha256: expected,
731
+ warning: `刷新失败,继续使用已安装的组件:${tried.map((row) => row.error).join(';')}`,
732
+ }
733
+ }
734
+ // Mirror the last attempt's failure kind at the top level: a digest mismatch is
735
+ // a different repair instruction than "network down" (review A3-P2-7).
736
+ const last = tried[tried.length - 1]
737
+ return {
738
+ ok: false,
739
+ error: tried.map((row) => `${row.url} → ${row.error}`).join('\n'),
740
+ url: urls[0] ?? '',
741
+ urls,
742
+ tried,
743
+ hint: FAILURE_HINT,
744
+ dir,
745
+ expectedSha256: expected,
746
+ ...(typeof last?.code === 'string' ? { code: last.code } : {}),
747
+ ...(last?.expected !== undefined ? { expected: last.expected } : {}),
748
+ ...(last?.actual !== undefined ? { actual: last.actual } : {}),
749
+ }
750
+ } catch (error) {
751
+ let attemptedDir = dir
752
+ if (attemptedDir === '') {
753
+ try {
754
+ attemptedDir = installDir(home)
755
+ } catch {
756
+ attemptedDir = ''
757
+ }
758
+ }
759
+ return {
760
+ ok: false,
761
+ error: error?.message ?? String(error),
762
+ url: urls[0] ?? '',
763
+ urls,
764
+ tried: [],
765
+ hint: FAILURE_HINT,
766
+ dir: attemptedDir,
767
+ ...(typeof error?.code === 'string' ? { code: error.code } : {}),
768
+ ...(error?.expected !== undefined ? { expected: error.expected } : {}),
769
+ ...(error?.actual !== undefined ? { actual: error.actual } : {}),
770
+ }
771
+ }
772
+ }
773
+
774
+ /** Internals for tests and the server layer (parsing/extraction without I/O). */
775
+ export const __test = {
776
+ BUNDLE_FILES,
777
+ BUNDLE_URLS,
778
+ BUNDLE_SHA256,
779
+ BUNDLE_SHA256_ENV,
780
+ BUNDLE_REDIRECT_HOSTS,
781
+ MAX_TGZ_BYTES,
782
+ MAX_TAR_BYTES,
783
+ extractBundle,
784
+ parseTar,
785
+ readOctal,
786
+ tarEntryName,
787
+ isLoopbackHostname,
788
+ normalizeBundleUrl,
789
+ normalizeSha256,
790
+ resolveBundleUrls,
791
+ resolveBundleUrlsSafe,
792
+ resolveBundleSha256,
793
+ resolveBundleSha256Safe,
794
+ allowedDownloadHosts,
795
+ cleanupStaleInstalls,
796
+ verifyInstalled,
797
+ sha256Of,
798
+ }