dsh-ris-ide 1.7.3 → 1.8.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 (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,687 @@
1
+ /**
2
+ * Tests for the downloaded ProxyBridge bundle (`lib/proxybridge-bundle.js`).
3
+ *
4
+ * The fixtures are built in-process: a tiny ustar writer + gzip gives a real
5
+ * `.tgz`, so the parser is exercised end-to-end without network or binaries.
6
+ * `fetchImpl` is always a stub — these tests never touch the network.
7
+ */
8
+ import assert from 'node:assert/strict'
9
+ import { createHash } from 'node:crypto'
10
+ import {
11
+ appendFileSync,
12
+ existsSync,
13
+ mkdirSync,
14
+ mkdtempSync,
15
+ readdirSync,
16
+ readFileSync,
17
+ rmSync,
18
+ statSync,
19
+ utimesSync,
20
+ writeFileSync,
21
+ } from 'node:fs'
22
+ import { tmpdir } from 'node:os'
23
+ import { dirname, join } from 'node:path'
24
+ import test from 'node:test'
25
+ import { gzipSync } from 'node:zlib'
26
+
27
+ import {
28
+ BUNDLE_SHA256,
29
+ BUNDLE_URLS,
30
+ DEFAULT_BUNDLE_URL,
31
+ __test,
32
+ bundleLayout,
33
+ downloadAndInstall,
34
+ ensureBundle,
35
+ installDir,
36
+ installFromTgz,
37
+ isInstalled,
38
+ manifestPath,
39
+ readManifest,
40
+ resolveBundleSha256,
41
+ resolveBundleSha256Safe,
42
+ resolveBundleUrl,
43
+ resolveBundleUrls,
44
+ resolveBundleUrlsSafe,
45
+ verifyInstalled,
46
+ } from '../lib/proxybridge-bundle.js'
47
+
48
+ const LAYOUT = [
49
+ 'LICENSE-ProxyBridge.txt',
50
+ 'NOTICE.md',
51
+ 'linux/ProxyBridge',
52
+ 'linux/libproxybridge.so',
53
+ 'windows/ProxyBridgeCore.dll',
54
+ 'windows/ProxyBridge_CLI.exe',
55
+ 'windows/WinDivert.dll',
56
+ 'windows/WinDivert64.sys',
57
+ ]
58
+
59
+ const fileContent = (rel) => `fixture bytes for ${rel}\n`
60
+ const shaOf = (bytes) => createHash('sha256').update(bytes).digest('hex')
61
+
62
+ /** Octal field: width-1 digits + NUL, as ustar spells numbers. */
63
+ const octalField = (value, width) => `${value.toString(8).padStart(width - 1, '0')}\0`
64
+
65
+ function tarHeader(name, size, { mode = 0o644, type = '0', linkname = '' } = {}) {
66
+ const header = Buffer.alloc(512, 0)
67
+ const encoded = Buffer.from(name, 'utf8')
68
+ assert.ok(encoded.length <= 100, `fixture name too long: ${name}`)
69
+ encoded.copy(header, 0)
70
+ header.write(octalField(mode, 8), 100, 'ascii')
71
+ header.write(octalField(0, 8), 108, 'ascii') // uid
72
+ header.write(octalField(0, 8), 116, 'ascii') // gid
73
+ header.write(octalField(size, 12), 124, 'ascii')
74
+ header.write(octalField(0, 12), 136, 'ascii') // mtime
75
+ header.write(' ', 148, 'ascii') // checksum placeholder
76
+ header.write(type, 156, 'ascii')
77
+ header.write(linkname < 101 ? linkname : linkname.slice(0, 100), 157, 'ascii')
78
+ header.write('ustar\0', 257, 'ascii')
79
+ header.write('00', 263, 'ascii')
80
+ let sum = 0
81
+ for (const byte of header) sum += byte
82
+ header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii')
83
+ return header
84
+ }
85
+
86
+ /** Build a real `.tgz` from `{name, content?, mode?, type?, linkname?}` entries. */
87
+ function makeTgz(entries, { prefix = '' } = {}) {
88
+ const chunks = []
89
+ for (const entry of entries) {
90
+ const content = Buffer.from(entry.content ?? fileContent(entry.name))
91
+ chunks.push(tarHeader(`${prefix}${entry.name}`, content.length, entry))
92
+ chunks.push(content)
93
+ const pad = (512 - (content.length % 512)) % 512
94
+ if (pad > 0) chunks.push(Buffer.alloc(pad))
95
+ }
96
+ chunks.push(Buffer.alloc(1024)) // end-of-archive: two zero blocks
97
+ return gzipSync(Buffer.concat(chunks))
98
+ }
99
+
100
+ const bundleTgz = (extra = []) => makeTgz([
101
+ ...LAYOUT.map((rel) => ({
102
+ name: rel,
103
+ content: fileContent(rel),
104
+ mode: /\.(exe|dll|sys|so)$|ProxyBridge$/.test(rel) === true ? 0o755 : 0o644,
105
+ })),
106
+ ...extra,
107
+ ])
108
+
109
+ /**
110
+ * `fetch` stand-in serving one body; `calls` counts invocations.
111
+ * `url` mimics `Response.url` after redirects; `headers` mimics the header bag.
112
+ */
113
+ function fetchServing(body, options = {}) {
114
+ const calls = { count: 0 }
115
+ const impl = async (requested) => {
116
+ calls.count += 1
117
+ return {
118
+ ok: true,
119
+ status: 200,
120
+ url: options.url ?? requested,
121
+ headers: options.headers ?? { get: () => null },
122
+ arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.length),
123
+ }
124
+ }
125
+ return { impl, calls }
126
+ }
127
+
128
+ function tempHome() {
129
+ return mkdtempSync(join(tmpdir(), 'ris-ide-bundle-home-'))
130
+ }
131
+
132
+ test('bundleLayout lists the eight files the tgz must carry', () => {
133
+ assert.deepEqual(bundleLayout(), LAYOUT)
134
+ // A copy, not the module-level array: callers cannot mutate the contract.
135
+ bundleLayout().push('nope')
136
+ assert.equal(bundleLayout().length, 8)
137
+ })
138
+
139
+ test('resolveBundleUrl prefers the env override, then settings, then the default', () => {
140
+ const env = { DSH_RIS_IDE_PROXYBRIDGE_URL: 'https://example.com/env.tgz' }
141
+ assert.equal(resolveBundleUrl({ env, settings: { proxybridgeUrl: 'https://example.com/settings.tgz' } }), 'https://example.com/env.tgz')
142
+ assert.equal(resolveBundleUrl({ env: {}, settings: { proxybridgeUrl: 'https://example.com/settings.tgz' } }), 'https://example.com/settings.tgz')
143
+ assert.equal(resolveBundleUrl({ env: {}, settings: {} }), DEFAULT_BUNDLE_URL)
144
+ assert.equal(resolveBundleUrl({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: ' ' }, settings: null }), DEFAULT_BUNDLE_URL)
145
+ // Loopback http is what a local test server uses.
146
+ assert.equal(resolveBundleUrl({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: 'http://127.0.0.1:8123/ris-proxy.tgz' } }), 'http://127.0.0.1:8123/ris-proxy.tgz')
147
+ assert.equal(resolveBundleUrl({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: 'http://localhost:8123/x.tgz' } }), 'http://localhost:8123/x.tgz')
148
+ })
149
+
150
+ test('resolveBundleUrl rejects plain http outside loopback and malformed URLs', () => {
151
+ assert.throws(() => resolveBundleUrl({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: 'http://example.com/x.tgz' } }), /https/)
152
+ assert.throws(() => resolveBundleUrl({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: 'not a url' } }), /不是合法 URL/)
153
+ assert.throws(() => resolveBundleUrl({ env: {}, settings: { proxybridgeUrl: 'ftp://example.com/x.tgz' } }), /https/)
154
+ })
155
+
156
+ test('resolveBundleSha256 pins the release by default and lets env/settings override it', () => {
157
+ assert.equal(resolveBundleSha256({ env: {}, settings: {} }), BUNDLE_SHA256)
158
+ assert.match(BUNDLE_SHA256, /^[0-9a-f]{64}$/)
159
+ const pinned = 'b'.repeat(64)
160
+ assert.equal(resolveBundleSha256({ env: { DSH_RIS_IDE_PROXYBRIDGE_SHA256: pinned }, settings: { proxybridgeSha256: 'c'.repeat(64) } }), pinned)
161
+ assert.equal(resolveBundleSha256({ env: {}, settings: { proxybridgeSha256: 'c'.repeat(64) } }), 'c'.repeat(64))
162
+ // An explicit empty value means "trust on first use", not "fall back to the pin".
163
+ assert.equal(resolveBundleSha256({ env: { DSH_RIS_IDE_PROXYBRIDGE_SHA256: '' }, settings: { proxybridgeSha256: 'c'.repeat(64) } }), '')
164
+ assert.equal(resolveBundleSha256({ env: {}, settings: { proxybridgeSha256: '' } }), '')
165
+ assert.throws(() => resolveBundleSha256({ env: { DSH_RIS_IDE_PROXYBRIDGE_SHA256: 'nope' } }), /sha256/)
166
+ assert.throws(() => resolveBundleSha256({ env: {}, settings: { proxybridgeSha256: 'zz' } }), /sha256/)
167
+ })
168
+
169
+ test('a misconfigured URL or digest degrades to the built-in mirrors for status readers', () => {
170
+ const badUrl = resolveBundleUrlsSafe({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: 'ftp://example.com/x.tgz' }, settings: {} })
171
+ assert.deepEqual(badUrl.urls, BUNDLE_URLS)
172
+ assert.match(badUrl.error, /https/)
173
+
174
+ const goodUrl = resolveBundleUrlsSafe({ env: { DSH_RIS_IDE_PROXYBRIDGE_URL: 'https://example.com/x.tgz' }, settings: {} })
175
+ assert.deepEqual(goodUrl.urls, ['https://example.com/x.tgz'])
176
+ assert.equal(goodUrl.error, '')
177
+
178
+ assert.deepEqual(resolveBundleUrls({ env: {}, settings: {} }), BUNDLE_URLS)
179
+
180
+ const badSha = resolveBundleSha256Safe({ env: { DSH_RIS_IDE_PROXYBRIDGE_SHA256: 'nope' }, settings: {} })
181
+ assert.equal(badSha.expectedSha256, BUNDLE_SHA256, 'a broken pin falls back to the release pin')
182
+ assert.match(badSha.error, /sha256/)
183
+ assert.equal(resolveBundleSha256Safe({ env: {}, settings: {} }).expectedSha256, BUNDLE_SHA256)
184
+ })
185
+
186
+ test('downloadAndInstall unpacks the layout and records a manifest', async () => {
187
+ const home = tempHome()
188
+ try {
189
+ const tgz = bundleTgz()
190
+ const { impl, calls } = fetchServing(tgz)
191
+ const url = 'https://example.com/ris-proxy.tgz'
192
+ const result = await downloadAndInstall({ home, url, fetchImpl: impl, expectedSha256: shaOf(tgz) })
193
+ assert.equal(result.ok, true)
194
+ assert.equal(result.dir, installDir(home))
195
+ assert.deepEqual(result.files, LAYOUT)
196
+ assert.equal(result.fileCount, 8)
197
+ assert.equal(result.bytes, tgz.length)
198
+ assert.equal(result.fromCache, false)
199
+ assert.equal(calls.count, 1)
200
+ assert.equal(result.sha256, shaOf(tgz))
201
+ assert.equal(isInstalled(result.dir), true)
202
+ assert.equal(verifyInstalled({ dir: result.dir }).ok, true, 'the freshly installed files match their recorded hashes')
203
+ for (const rel of LAYOUT) {
204
+ assert.equal(readFileSync(join(result.dir, ...rel.split('/')), 'utf8'), fileContent(rel), `${rel} bytes`)
205
+ }
206
+ const manifest = readManifest(result.dir)
207
+ assert.equal(manifest.version, 1)
208
+ assert.equal(manifest.url, url)
209
+ assert.equal(manifest.source, 'download')
210
+ assert.equal(manifest.sha256, result.sha256)
211
+ assert.ok(Number.isNaN(Date.parse(manifest.installedAt)) === false)
212
+ assert.deepEqual(Object.keys(manifest.files).sort(), [...LAYOUT].sort())
213
+ assert.deepEqual(Object.keys(manifest.fileHashes).sort(), [...LAYOUT].sort())
214
+ // Binaries are executable, licence text is not.
215
+ assert.notEqual(statSync(join(result.dir, 'linux', 'ProxyBridge')).mode & 0o111, 0)
216
+ assert.equal(statSync(join(result.dir, 'NOTICE.md')).mode & 0o111, 0)
217
+ assert.equal(existsSync(manifestPath(result.dir)), true)
218
+ } finally {
219
+ rmSync(home, { recursive: true, force: true })
220
+ }
221
+ })
222
+
223
+ test('a ./-prefixed archive installs and unknown files/directories are ignored', async () => {
224
+ const home = tempHome()
225
+ try {
226
+ const tgz = makeTgz([
227
+ { name: 'linux/', type: '5', content: '' },
228
+ ...LAYOUT.map((rel) => ({ name: rel })),
229
+ { name: 'README-extra.md' },
230
+ ], { prefix: './' })
231
+ const result = await downloadAndInstall({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: '' })
232
+ assert.equal(result.ok, true)
233
+ assert.equal(isInstalled(result.dir), true)
234
+ assert.equal(existsSync(join(result.dir, 'README-extra.md')), false, 'unknown entries are not extracted')
235
+ assert.equal(existsSync(join(result.dir, 'windows', 'README-extra.md')), false)
236
+ } finally {
237
+ rmSync(home, { recursive: true, force: true })
238
+ }
239
+ })
240
+
241
+ test('pax/global long-name headers are skipped rather than guessed', async () => {
242
+ // GNU pax records a long path in an 'x' entry that precedes the real file; we do
243
+ // not interpret those, so a bundle repacked that way fails closed (missing file)
244
+ // instead of installing a truncated name. Documented behaviour, see review B-P2.
245
+ const home = tempHome()
246
+ try {
247
+ const tgz = makeTgz([
248
+ ...LAYOUT.map((rel) => ({ name: rel })),
249
+ { name: 'PaxHeaders/x', type: 'x', content: '30 path=linux/a-very-long-pax-name\n' },
250
+ ])
251
+ const result = await downloadAndInstall({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: '' })
252
+ assert.equal(result.ok, true, 'the extra pax entry is ignored and the 8 known files still install')
253
+ } finally {
254
+ rmSync(home, { recursive: true, force: true })
255
+ }
256
+ })
257
+
258
+ test('ensureBundle reuses a valid cache without fetching', async () => {
259
+ const home = tempHome()
260
+ try {
261
+ const tgz = bundleTgz()
262
+ const { impl, calls } = fetchServing(tgz)
263
+ const first = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: impl, expectedSha256: shaOf(tgz) })
264
+ assert.equal(first.ok, true)
265
+ assert.equal(first.fromCache, false)
266
+ assert.equal(calls.count, 1)
267
+ const second = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: impl, expectedSha256: shaOf(tgz) })
268
+ assert.equal(second.ok, true)
269
+ assert.equal(second.fromCache, true)
270
+ assert.equal(second.dir, first.dir)
271
+ assert.deepEqual(second.files, LAYOUT)
272
+ assert.equal(second.fileCount, 8)
273
+ assert.equal(second.sha256, shaOf(tgz))
274
+ assert.equal(calls.count, 1, 'the cache must short-circuit the download')
275
+ } finally {
276
+ rmSync(home, { recursive: true, force: true })
277
+ }
278
+ })
279
+
280
+ test('the mirror pair is tried in order and the second one can save the install', async () => {
281
+ const home = tempHome()
282
+ try {
283
+ assert.deepEqual(resolveBundleUrls({ env: {}, settings: {} }), [...BUNDLE_URLS])
284
+ assert.ok(BUNDLE_URLS[0].includes('gitee.com'), 'gitee is the primary mirror')
285
+ assert.ok(BUNDLE_URLS[1].includes('github.com'), 'github is the fallback')
286
+ for (const url of BUNDLE_URLS) {
287
+ assert.match(url, /\/releases\/download\/1\.8\.0\/ris-proxy\.4\.0\.tgz$/, 'both mirrors carry the same versioned asset')
288
+ }
289
+
290
+ // Gitee 502 → the same bytes are fetched from GitHub and installed.
291
+ const bytes = bundleTgz()
292
+ const calls = []
293
+ const impl = async (url) => {
294
+ calls.push(url)
295
+ if (url === BUNDLE_URLS[0]) return { ok: false, status: 502, url, arrayBuffer: async () => new ArrayBuffer(0) }
296
+ return { ok: true, status: 200, url, arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) }
297
+ }
298
+ const result = await ensureBundle({ home, fetchImpl: impl, expectedSha256: shaOf(bytes) })
299
+ assert.equal(result.ok, true)
300
+ assert.equal(result.url, BUNDLE_URLS[1])
301
+ assert.equal(result.tried.length, 1)
302
+ assert.match(result.tried[0].error, /502/)
303
+ assert.equal(isInstalled(installDir(home)), true)
304
+ assert.equal(calls.length, 2, 'both mirrors were attempted once')
305
+ } finally {
306
+ rmSync(home, { recursive: true, force: true })
307
+ }
308
+ })
309
+
310
+ test('a bundle that does not match the pinned sha256 is never installed', async () => {
311
+ const home = tempHome()
312
+ try {
313
+ const tgz = bundleTgz()
314
+ const wrong = 'd'.repeat(64)
315
+ const error = await downloadAndInstall({
316
+ home,
317
+ url: 'https://example.com/x.tgz',
318
+ fetchImpl: fetchServing(tgz).impl,
319
+ expectedSha256: wrong,
320
+ }).then(() => null, (thrown) => thrown)
321
+ assert.notEqual(error, null)
322
+ assert.equal(error.code, 'hash-mismatch')
323
+ assert.equal(error.expected, wrong)
324
+ assert.equal(error.actual, shaOf(tgz))
325
+ // Rejected before extraction/write: nothing half-installed on disk.
326
+ assert.equal(existsSync(installDir(home)), false)
327
+
328
+ const viaEnsure = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: wrong })
329
+ assert.equal(viaEnsure.ok, false)
330
+ assert.match(viaEnsure.error, /固定 sha256 不一致/)
331
+ // The route layer needs the machine-readable kind and both digests, not just text.
332
+ assert.equal(viaEnsure.code, 'hash-mismatch')
333
+ assert.equal(viaEnsure.expected, wrong)
334
+ assert.equal(viaEnsure.actual, shaOf(tgz))
335
+ assert.equal(viaEnsure.tried[0].code, 'hash-mismatch')
336
+ assert.equal(existsSync(installDir(home)), false)
337
+ } finally {
338
+ rmSync(home, { recursive: true, force: true })
339
+ }
340
+ })
341
+
342
+ test('ensureBundle reports failures instead of throwing', async () => {
343
+ const home = tempHome()
344
+ try {
345
+ const boom = await ensureBundle({
346
+ home,
347
+ url: 'https://example.com/x.tgz',
348
+ expectedSha256: '',
349
+ fetchImpl: async () => {
350
+ throw new Error('boom')
351
+ },
352
+ })
353
+ assert.equal(boom.ok, false)
354
+ assert.match(boom.error, /boom/)
355
+ assert.equal(boom.url, 'https://example.com/x.tgz')
356
+ assert.equal(typeof boom.hint, 'string')
357
+ assert.equal(boom.dir, installDir(home))
358
+ const http500 = await ensureBundle({
359
+ home,
360
+ url: 'https://example.com/x.tgz',
361
+ expectedSha256: '',
362
+ fetchImpl: async () => ({ ok: false, status: 500, arrayBuffer: async () => new ArrayBuffer(0) }),
363
+ })
364
+ assert.equal(http500.ok, false)
365
+ assert.match(http500.error, /HTTP 500/)
366
+ // Nothing half-installed.
367
+ assert.equal(existsSync(installDir(home)), false)
368
+ } finally {
369
+ rmSync(home, { recursive: true, force: true })
370
+ }
371
+ })
372
+
373
+ test('downloads redirected to an untrusted host are refused', async () => {
374
+ const home = tempHome()
375
+ try {
376
+ const tgz = bundleTgz()
377
+ const error = await downloadAndInstall({
378
+ home,
379
+ url: 'https://example.com/x.tgz',
380
+ fetchImpl: fetchServing(tgz, { url: 'https://evil.example/payload.tgz' }).impl,
381
+ expectedSha256: '',
382
+ }).then(() => null, (thrown) => thrown)
383
+ assert.notEqual(error, null)
384
+ assert.equal(error.code, 'untrusted-host')
385
+ assert.equal(error.host, 'evil.example')
386
+ assert.equal(existsSync(installDir(home)), false)
387
+
388
+ // The release-asset host GitHub redirects to is allowed.
389
+ const allowed = await downloadAndInstall({
390
+ home,
391
+ url: 'https://example.com/x.tgz',
392
+ fetchImpl: fetchServing(tgz, { url: 'https://release-assets.githubusercontent.com/github-production-release-asset/x.tgz' }).impl,
393
+ expectedSha256: shaOf(tgz),
394
+ })
395
+ assert.equal(allowed.ok, true)
396
+ } finally {
397
+ rmSync(home, { recursive: true, force: true })
398
+ }
399
+ })
400
+
401
+ test('a declared or streamed body over the cap is refused before it is buffered', async () => {
402
+ const home = tempHome()
403
+ try {
404
+ const declared = await downloadAndInstall({
405
+ home,
406
+ url: 'https://example.com/x.tgz',
407
+ fetchImpl: fetchServing(Buffer.alloc(0), {
408
+ headers: { get: (name) => (name === 'content-length' ? String(__test.MAX_TGZ_BYTES + 1) : null) },
409
+ }).impl,
410
+ expectedSha256: '',
411
+ }).then(() => null, (thrown) => thrown)
412
+ assert.notEqual(declared, null)
413
+ assert.equal(declared.code, 'too-large')
414
+
415
+ // A streaming body that crosses the cap aborts mid-flight (no arrayBuffer()).
416
+ let pulled = 0
417
+ const streaming = async () => ({
418
+ ok: true,
419
+ status: 200,
420
+ url: 'https://example.com/x.tgz',
421
+ headers: { get: () => null },
422
+ body: {
423
+ async *[Symbol.asyncIterator]() {
424
+ for (let index = 0; index < 2; index += 1) {
425
+ pulled += 1
426
+ yield Buffer.alloc(__test.MAX_TGZ_BYTES)
427
+ }
428
+ },
429
+ async cancel() {},
430
+ },
431
+ })
432
+ const streamed = await downloadAndInstall({ home, url: 'https://example.com/x.tgz', fetchImpl: streaming, expectedSha256: '' })
433
+ .then(() => null, (thrown) => thrown)
434
+ assert.notEqual(streamed, null)
435
+ assert.equal(streamed.code, 'too-large')
436
+ assert.equal(pulled, 2, 'the response is cancelled as soon as the cap is crossed')
437
+ assert.equal(existsSync(installDir(home)), false)
438
+ } finally {
439
+ rmSync(home, { recursive: true, force: true })
440
+ }
441
+ })
442
+
443
+ test('a tgz missing a file is rejected and the previous install survives', async () => {
444
+ const home = tempHome()
445
+ try {
446
+ const goodTgz = bundleTgz()
447
+ const good = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(goodTgz).impl, expectedSha256: shaOf(goodTgz) })
448
+ assert.equal(good.ok, true)
449
+ const before = readFileSync(join(good.dir, 'windows', 'ProxyBridge_CLI.exe'), 'utf8')
450
+ const incomplete = makeTgz(LAYOUT.filter((rel) => rel !== 'windows/WinDivert64.sys').map((rel) => ({ name: rel })))
451
+ const failed = await ensureBundle({
452
+ home,
453
+ url: 'https://example.com/x.tgz',
454
+ force: true,
455
+ expectedSha256: '',
456
+ fetchImpl: fetchServing(incomplete).impl,
457
+ })
458
+ // There is still a complete, verified install on disk: a failed forced refresh
459
+ // must keep it usable and say so, instead of reporting the component as missing.
460
+ assert.equal(failed.ok, true)
461
+ assert.equal(failed.fromCache, true)
462
+ assert.match(failed.warning, /缺少文件.*WinDivert64\.sys/)
463
+ assert.equal(isInstalled(installDir(home)), true, 'the previous complete bundle is untouched')
464
+ assert.equal(readFileSync(join(good.dir, 'windows', 'ProxyBridge_CLI.exe'), 'utf8'), before)
465
+ assert.deepEqual(readdirSync(installDir(home)).filter((name) => name.includes('.tmp-')), [])
466
+ } finally {
467
+ rmSync(home, { recursive: true, force: true })
468
+ }
469
+ })
470
+
471
+ test('path traversal, absolute paths and links are rejected', async () => {
472
+ const home = tempHome()
473
+ try {
474
+ const traversal = makeTgz([...LAYOUT.map((rel) => ({ name: rel })), { name: '../evil', content: 'pwned' }])
475
+ const failed = await ensureBundle({ home, url: 'https://example.com/x.tgz', expectedSha256: '', fetchImpl: fetchServing(traversal).impl })
476
+ assert.equal(failed.ok, false)
477
+ assert.match(failed.error, /不安全|绝对路径/)
478
+ assert.equal(existsSync(installDir(home)), false)
479
+
480
+ const absolute = makeTgz([...LAYOUT.map((rel) => ({ name: rel })), { name: '/etc/passwd', content: 'pwned' }])
481
+ const absoluteFailed = await ensureBundle({ home, url: 'https://example.com/x.tgz', expectedSha256: '', fetchImpl: fetchServing(absolute).impl })
482
+ assert.equal(absoluteFailed.ok, false)
483
+
484
+ const link = makeTgz([...LAYOUT.map((rel) => ({ name: rel })), { name: 'windows/link', type: '2', content: '', linkname: '../../etc/passwd' }])
485
+ const linkFailed = await ensureBundle({ home, url: 'https://example.com/x.tgz', expectedSha256: '', fetchImpl: fetchServing(link).impl })
486
+ assert.equal(linkFailed.ok, false)
487
+ assert.match(linkFailed.error, /符号链接/)
488
+ } finally {
489
+ rmSync(home, { recursive: true, force: true })
490
+ }
491
+ })
492
+
493
+ test('installFromTgz installs an uploaded bundle and records its real digest', () => {
494
+ const home = tempHome()
495
+ try {
496
+ const tgz = bundleTgz()
497
+ const result = installFromTgz({ home, bytes: tgz })
498
+ assert.equal(result.ok, true)
499
+ assert.deepEqual(result.files, LAYOUT)
500
+ assert.equal(result.fileCount, 8)
501
+ assert.equal(result.bytes, tgz.length)
502
+ assert.equal(result.sha256, shaOf(tgz))
503
+ assert.equal(result.url, 'upload')
504
+ assert.equal(isInstalled(result.dir), true)
505
+ const manifest = readManifest(result.dir)
506
+ assert.equal(manifest.sha256, shaOf(tgz))
507
+ assert.equal(manifest.source, 'upload')
508
+ assert.equal(verifyInstalled({ dir: result.dir, expectedSha256: shaOf(tgz) }).ok, true)
509
+ assert.equal(readFileSync(join(result.dir, 'windows', 'WinDivert.dll'), 'utf8'), fileContent('windows/WinDivert.dll'))
510
+ } finally {
511
+ rmSync(home, { recursive: true, force: true })
512
+ }
513
+ })
514
+
515
+ test('same-size tampering is caught by verifyInstalled and repaired by ensureBundle', async () => {
516
+ const home = tempHome()
517
+ try {
518
+ const tgz = bundleTgz()
519
+ const { impl, calls } = fetchServing(tgz)
520
+ const result = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: impl, expectedSha256: shaOf(tgz) })
521
+ assert.equal(result.ok, true)
522
+ const target = join(result.dir, 'linux', 'ProxyBridge')
523
+ const original = readFileSync(target)
524
+ const tampered = Buffer.from(original)
525
+ tampered[tampered.length - 2] = tampered[tampered.length - 2] ^ 0xff
526
+ assert.equal(tampered.length, original.length, 'the fixture stays the same size')
527
+ writeFileSync(target, tampered)
528
+
529
+ // Cheap check cannot see it (size unchanged) …
530
+ assert.equal(isInstalled(result.dir), true)
531
+ // … the content check can.
532
+ const verdict = verifyInstalled({ dir: result.dir })
533
+ assert.equal(verdict.ok, false)
534
+ assert.match(verdict.reason, /内容与安装记录不一致/)
535
+
536
+ const repaired = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: impl, expectedSha256: shaOf(tgz) })
537
+ assert.equal(repaired.ok, true)
538
+ assert.equal(repaired.fromCache, false, 'a corrupt cache must be downloaded again')
539
+ assert.equal(calls.count, 2)
540
+ assert.equal(readFileSync(target).equals(original), true)
541
+ assert.equal(verifyInstalled({ dir: result.dir }).ok, true)
542
+ } finally {
543
+ rmSync(home, { recursive: true, force: true })
544
+ }
545
+ })
546
+
547
+ test('isInstalled notices a changed size or a missing file', async () => {
548
+ const home = tempHome()
549
+ try {
550
+ const tgz = bundleTgz()
551
+ const result = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: shaOf(tgz) })
552
+ assert.equal(isInstalled(result.dir), true)
553
+ appendFileSync(join(result.dir, 'windows', 'WinDivert.dll'), 'x')
554
+ assert.equal(isInstalled(result.dir), false, 'a size change invalidates the cache')
555
+ rmSync(join(result.dir, 'LICENSE-ProxyBridge.txt'))
556
+ assert.equal(isInstalled(result.dir), false, 'a missing file invalidates the cache')
557
+ } finally {
558
+ rmSync(home, { recursive: true, force: true })
559
+ }
560
+ })
561
+
562
+ test('a legacy install without per-file hashes is reported as unverified', async () => {
563
+ const home = tempHome()
564
+ try {
565
+ const tgz = bundleTgz()
566
+ const result = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: shaOf(tgz) })
567
+ assert.equal(result.ok, true)
568
+ const manifest = readManifest(result.dir)
569
+ delete manifest.fileHashes
570
+ writeFileSync(manifestPath(result.dir), JSON.stringify(manifest))
571
+ assert.equal(isInstalled(result.dir), true, 'the cheap check still passes')
572
+ const verdict = verifyInstalled({ dir: result.dir })
573
+ assert.equal(verdict.ok, false)
574
+ assert.match(verdict.reason, /重新安装/)
575
+ } finally {
576
+ rmSync(home, { recursive: true, force: true })
577
+ }
578
+ })
579
+
580
+ test('a failed refresh falls back to a still-usable cache', async () => {
581
+ const home = tempHome()
582
+ try {
583
+ const tgz = bundleTgz()
584
+ const first = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: shaOf(tgz) })
585
+ assert.equal(first.ok, true)
586
+ const fallback = await ensureBundle({
587
+ home,
588
+ url: 'https://example.com/x.tgz',
589
+ force: true,
590
+ expectedSha256: shaOf(tgz),
591
+ fetchImpl: async () => {
592
+ throw new Error('offline again')
593
+ },
594
+ })
595
+ assert.equal(fallback.ok, true)
596
+ assert.equal(fallback.fromCache, true)
597
+ assert.match(fallback.warning, /继续使用已安装的组件/)
598
+ assert.equal(isInstalled(fallback.dir), true)
599
+ } finally {
600
+ rmSync(home, { recursive: true, force: true })
601
+ }
602
+ })
603
+
604
+ test('trust-on-first-use records the digest and reuses it', async () => {
605
+ const home = tempHome()
606
+ try {
607
+ const tgz = bundleTgz()
608
+ const { impl, calls } = fetchServing(tgz)
609
+ const first = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: impl, expectedSha256: '' })
610
+ assert.equal(first.ok, true)
611
+ assert.equal(first.sha256, shaOf(tgz))
612
+ const second = await ensureBundle({ home, url: 'https://example.com/x.tgz', fetchImpl: impl, expectedSha256: '' })
613
+ assert.equal(second.ok, true)
614
+ assert.equal(second.fromCache, true)
615
+ assert.equal(calls.count, 1)
616
+ } finally {
617
+ rmSync(home, { recursive: true, force: true })
618
+ }
619
+ })
620
+
621
+ test('abandoned staging directories are collected, recent ones are left alone', async () => {
622
+ const home = tempHome()
623
+ try {
624
+ const dir = installDir(home)
625
+ const parent = dirname(dir)
626
+ mkdirSync(parent, { recursive: true })
627
+ const stale = `${dir}.tmp-999999`
628
+ const fresh = `${dir}.old-999998`
629
+ mkdirSync(stale, { recursive: true })
630
+ mkdirSync(fresh, { recursive: true })
631
+ writeFileSync(join(stale, 'leftover'), 'x')
632
+ writeFileSync(join(fresh, 'leftover'), 'x')
633
+ const old = new Date(Date.now() - 2 * 60 * 60 * 1000)
634
+ utimesSync(stale, old, old)
635
+ utimesSync(fresh, old, old)
636
+ // Fresh (within the hour) staging is NOT removed: another process may still be
637
+ // writing it. Touching it with "now" simulates that.
638
+ const now = new Date()
639
+ utimesSync(fresh, now, now)
640
+
641
+ const tgz = bundleTgz()
642
+ const result = await downloadAndInstall({ home, url: 'https://example.com/x.tgz', fetchImpl: fetchServing(tgz).impl, expectedSha256: shaOf(tgz) })
643
+ assert.equal(result.ok, true)
644
+ assert.equal(existsSync(stale), false, 'an hour-old staging directory is collected')
645
+ assert.equal(existsSync(fresh), true, 'a recent staging directory is left for its owner')
646
+ } finally {
647
+ rmSync(home, { recursive: true, force: true })
648
+ }
649
+ })
650
+
651
+ test('__test exposes the tar parsing helpers without touching the disk', () => {
652
+ assert.equal(typeof __test.parseTar, 'function')
653
+ assert.equal(typeof __test.extractBundle, 'function')
654
+ assert.equal(typeof __test.sha256Of, 'function')
655
+ assert.equal(typeof __test.verifyInstalled, 'function')
656
+ assert.equal(typeof __test.resolveBundleSha256, 'function')
657
+ assert.equal(typeof __test.cleanupStaleInstalls, 'function')
658
+ assert.throws(() => __test.extractBundle(Buffer.from('not gzip')), /gzip/)
659
+ assert.throws(() => __test.extractBundle(Buffer.alloc(__test.MAX_TGZ_BYTES + 1)), /过大/)
660
+ })
661
+
662
+ test('ensureBundle resolves the URL from settings when none is passed', async () => {
663
+ const home = tempHome()
664
+ try {
665
+ const failed = await ensureBundle({
666
+ home,
667
+ settings: { proxybridgeUrl: 'https://example.com/from-settings.tgz' },
668
+ expectedSha256: '',
669
+ fetchImpl: async () => {
670
+ throw new Error('offline')
671
+ },
672
+ })
673
+ assert.equal(failed.ok, false)
674
+ assert.equal(failed.url, 'https://example.com/from-settings.tgz')
675
+ } finally {
676
+ rmSync(home, { recursive: true, force: true })
677
+ }
678
+ })
679
+
680
+ test('downloadAndInstall rejects an https-less URL before fetching', async () => {
681
+ let fetched = 0
682
+ await assert.rejects(
683
+ () => downloadAndInstall({ home: tempHome(), url: 'http://example.com/x.tgz', fetchImpl: async () => { fetched += 1 } }),
684
+ /https/,
685
+ )
686
+ assert.equal(fetched, 0, 'the URL is validated before any request')
687
+ })