dsh-ris-ide 1.7.3 → 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 (72) hide show
  1. package/README.md +19 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +287 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +515 -1152
  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/redirector.js +484 -35
  11. package/lib/risd/build.js +91 -0
  12. package/lib/risd/debug.js +374 -0
  13. package/lib/risd/git.js +207 -0
  14. package/lib/risd/leases.js +124 -0
  15. package/lib/risd/lifecycle.js +148 -0
  16. package/lib/risd/log.js +59 -0
  17. package/lib/risd/ping.js +94 -0
  18. package/lib/risd/programs.js +348 -0
  19. package/lib/risd/server.js +1478 -0
  20. package/lib/risd/state.js +137 -0
  21. package/lib/risd/ui.js +1705 -0
  22. package/lib/risd/view.js +79 -0
  23. package/lib/risd-client.js +282 -0
  24. package/lib/standalone/window.html +14 -16
  25. package/lib/startup.js +114 -0
  26. package/package.json +4 -1
  27. package/test/client-build.test.mjs +113 -0
  28. package/test/client-viewer.test.mjs +166 -200
  29. package/test/dsh-origin.test.mjs +140 -0
  30. package/test/dsh-window-refresh.test.mjs +100 -0
  31. package/test/harness.test.mjs +9 -0
  32. package/test/host-noloop.test.mjs +74 -0
  33. package/test/host-tail.test.mjs +21 -4
  34. package/test/host-window.test.mjs +4 -4
  35. package/test/janitor.test.mjs +29 -1
  36. package/test/lifecycle.test.mjs +26 -5
  37. package/test/merge-owners.test.mjs +155 -0
  38. package/test/proxy-restart.test.mjs +37 -0
  39. package/test/proxy-window.test.mjs +45 -0
  40. package/test/proxy.test.mjs +41 -0
  41. package/test/proxybridge-bundle.test.mjs +687 -0
  42. package/test/redirector-bundle.test.mjs +391 -0
  43. package/test/redirector.test.mjs +59 -9
  44. package/test/risd-api.test.mjs +470 -0
  45. package/test/risd-bridge-degrade.test.mjs +101 -0
  46. package/test/risd-build.test.mjs +20 -0
  47. package/test/risd-cli-home.test.mjs +50 -0
  48. package/test/risd-client.test.mjs +130 -0
  49. package/test/risd-debug.test.mjs +261 -0
  50. package/test/risd-election.test.mjs +104 -0
  51. package/test/risd-engine.test.mjs +132 -0
  52. package/test/risd-entry.test.mjs +118 -0
  53. package/test/risd-git.test.mjs +109 -0
  54. package/test/risd-handoff.test.mjs +116 -0
  55. package/test/risd-heal.test.mjs +50 -0
  56. package/test/risd-helpers.mjs +108 -0
  57. package/test/risd-host-p2.test.mjs +147 -0
  58. package/test/risd-janitor-guard.test.mjs +46 -0
  59. package/test/risd-lease.test.mjs +83 -0
  60. package/test/risd-lifecycle.test.mjs +210 -0
  61. package/test/risd-log-follow.test.mjs +227 -0
  62. package/test/risd-mode.test.mjs +161 -0
  63. package/test/risd-ping.test.mjs +99 -0
  64. package/test/risd-programs.test.mjs +169 -0
  65. package/test/risd-review-p2.test.mjs +217 -0
  66. package/test/risd-shutdown.test.mjs +97 -0
  67. package/test/risd-teardown.test.mjs +87 -0
  68. package/test/risd-tools.test.mjs +211 -0
  69. package/test/risd-ui.test.mjs +445 -0
  70. package/test/risd-write.test.mjs +170 -0
  71. package/test/startup-reconcile.test.mjs +100 -0
  72. package/test/windows.test.mjs +37 -2
package/lib/redirector.js CHANGED
@@ -9,12 +9,21 @@
9
9
  * sends matching connections to a SOCKS5/HTTP proxy.
10
10
  *
11
11
  * It is driven entirely by a `.pbprofile` JSON file, so we do not reimplement its
12
- * engine: we map our rule table onto that file and hand it over. Two facts make
13
- * this usable without installing anything:
14
- * - Linux: `ProxyBridge --profile ./x.pbprofile` runs from an extracted folder
12
+ * engine: we map our rule table onto that file and hand it over. The CLI itself is
13
+ * **downloaded on first use** (an uploaded `.tgz` works as well) and cached under
14
+ * `~/.dsh-ris-ide/proxybridge/bundle/{linux,windows}` by `lib/proxybridge-bundle.js`
15
+ * — the plugin no longer ships any binaries:
16
+ * - Linux: `ProxyBridge --profile ./x.pbprofile` runs from that folder
15
17
  * ("Nothing is installed"); it needs root, but no systemd unit.
16
18
  * - Windows: `ProxyBridge_CLI.exe` next to `ProxyBridgeCore.dll`, `WinDivert.dll`
17
19
  * and `WinDivert64.sys` is the stand-alone form; it needs an elevated start.
20
+ * Where Windows can see the filesystem, the windows folder is materialised under
21
+ * %LOCALAPPDATA% first, because a Windows process cannot launch a binary that
22
+ * only exists in Linux.
23
+ *
24
+ * Nothing here downloads by itself: the HTTP layer (maintenance page → 代理 → 组件)
25
+ * calls `ensureBundleReady`, and the lookup only *reports* `missingBundle` so a
26
+ * caller can show "未安装,请下载/上传" instead of failing silently.
18
27
  *
19
28
  * Elevation is the one thing we cannot do silently: on Windows it is a UAC prompt,
20
29
  * on WSL/Linux a sudo password. So `start` reports the exact command and only
@@ -23,12 +32,13 @@
23
32
 
24
33
  import { execFile, spawn, spawnSync } from 'node:child_process'
25
34
  import { randomUUID } from 'node:crypto'
26
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
35
+ import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
27
36
  import { homedir } from 'node:os'
28
37
  import { basename, dirname, extname, join } from 'node:path'
29
38
  import { promisify } from 'node:util'
30
39
 
31
- import { IS_WINDOWS, engineSide, pidAlive, proxyConfigPath, proxyHomeDir, readProxyConfig, readTail, ruleEffectiveness } from './proxy.js'
40
+ import { IS_WINDOWS, engineSide, pidAlive, proxyConfigPath, proxyHomeDir, proxyLogPath, readProxyConfig, readTail, ruleEffectiveness } from './proxy.js'
41
+ import { DEFAULT_BUNDLE_URL, ensureBundle, installDir as bundleInstallDir, isInstalled as bundleIsInstalled, readManifest } from './proxybridge-bundle.js'
32
42
 
33
43
  /** Directory (under the shared proxy home) holding our profile, pid and log. */
34
44
  export const REDIRECTOR_DIRNAME = 'proxybridge'
@@ -59,6 +69,9 @@ const PROFILE_VERSION = '1.0'
59
69
  * Production leaves the object empty; tests fill it so a lifecycle test can run
60
70
  * deterministically without touching the real Windows side (no UAC, no driver,
61
71
  * no process killing).
72
+ *
73
+ * `bundleTarget({platform})` overrides where the Windows bundle is materialised, so
74
+ * a test can prove the copy happens without writing into a real `%LOCALAPPDATA%`.
62
75
  */
63
76
  const probeHooks = {}
64
77
 
@@ -96,6 +109,10 @@ function clearProbeCaches() {
96
109
  versionCache.clear()
97
110
  statusCache = { at: 0, value: null }
98
111
  statusInflight = null
112
+ // The bundle caches are process-wide too: a test that pins a temp target must not
113
+ // inherit a previous run's materialised folder (or a remembered failure).
114
+ localAppDataCache = null
115
+ windowsBundlePrepared = null
99
116
  }
100
117
 
101
118
  /**
@@ -210,6 +227,303 @@ export function redirectorLogPath() {
210
227
  return join(redirectorHome(), REDIRECTOR_LOG_FILENAME)
211
228
  }
212
229
 
230
+ /**
231
+ * The downloaded-and-cached ProxyBridge distribution (machine-wide proxy home).
232
+ *
233
+ * Nothing is shipped inside the plugin any more (2.9 MB of binaries made every
234
+ * install heavy and pinned the upstream version): `lib/proxybridge-bundle.js`
235
+ * downloads/accepts an uploaded `.tgz` here on first use.
236
+ * @returns {string} absolute path to `<proxyHome>/proxybridge/bundle`.
237
+ */
238
+ export function bundledBundleDir() {
239
+ return bundleInstallDir(proxyHomeDir())
240
+ }
241
+
242
+ /**
243
+ * The cached distribution for one platform.
244
+ *
245
+ * The old name is kept for compat (this module and its tests import it), but it no
246
+ * longer points inside the plugin: the folder only exists after a download/upload.
247
+ * @param {{platform?: string, dir?: string}} [options] - platform / install-dir overrides for tests.
248
+ * @returns {string} absolute path to `<bundle>/<windows|linux>`.
249
+ */
250
+ export function bundledRedirectorDir(options = {}) {
251
+ const platform = options.platform ?? process.platform
252
+ return join(options.dir ?? bundledBundleDir(), platform === 'win32' ? 'windows' : 'linux')
253
+ }
254
+
255
+ /** True when the cached distribution is complete (manifest plus every file). */
256
+ export function bundleCacheInstalled() {
257
+ return bundleIsInstalled(bundledBundleDir())
258
+ }
259
+
260
+ /**
261
+ * Identity of the currently installed bundle. The Windows-side copy (below) is
262
+ * materialised from it, so a changed fingerprint means the DLLs/CLI on the Windows
263
+ * side are stale and must be copied again (review B-P1-2).
264
+ * @param {string} [dir] - install directory; defaults to {@link bundledBundleDir}.
265
+ * @returns {string} `sha256:installedAt`, or '' when nothing is installed.
266
+ */
267
+ export function bundleFingerprint(dir = bundledBundleDir()) {
268
+ const manifest = readManifest(dir)
269
+ if (manifest === null) return ''
270
+ return `${manifest.sha256 ?? ''}:${manifest.installedAt ?? ''}`
271
+ }
272
+
273
+ /** Machine-level settings file (`~/.dsh-ris-ide/settings.json`); unreadable counts as empty. */
274
+ function readMachineSettings() {
275
+ try {
276
+ const parsed = JSON.parse(readFileSync(join(proxyHomeDir(), 'settings.json'), 'utf8'))
277
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
278
+ } catch {
279
+ return {}
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Make the ProxyBridge distribution available: reuse the cache, else download it.
285
+ *
286
+ * URL and digest priority now live in exactly one place — `resolveBundleUrls` /
287
+ * `resolveBundleSha256` inside `lib/proxybridge-bundle.js` (env → settings →
288
+ * mirrors), shared with the daemon. This function only forwards the explicit
289
+ * route-level `url` and the machine settings; it must not re-order them
290
+ * (review A3-P2-1/-2). Never throws — the route layer turns `{ok:false}` into a
291
+ * readable failure.
292
+ * @param {{url?: string, fetchImpl?: typeof fetch, force?: boolean}} [options] - overrides for the route/tests.
293
+ * @returns {Promise<{ok: boolean, dir: string, fromCache: boolean, error: string, url: string, hint: string, warning?: string}>} outcome.
294
+ */
295
+ export async function ensureBundleReady(options = {}) {
296
+ const fallbackUrl = DEFAULT_BUNDLE_URL
297
+ try {
298
+ const settings = readMachineSettings()
299
+ const explicit = typeof options.url === 'string' && options.url.trim() !== '' ? options.url.trim() : ''
300
+ const result = await ensureBundle({
301
+ home: proxyHomeDir(),
302
+ settings,
303
+ force: options.force === true,
304
+ ...(explicit === '' ? {} : { url: explicit }),
305
+ ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
306
+ })
307
+ const url = typeof result.url === 'string' && result.url !== '' ? result.url : explicit || fallbackUrl
308
+ if (result.ok === true) {
309
+ return {
310
+ ok: true,
311
+ dir: result.dir,
312
+ fromCache: result.fromCache === true,
313
+ error: '',
314
+ url,
315
+ hint: '',
316
+ ...(typeof result.warning === 'string' ? { warning: result.warning } : {}),
317
+ }
318
+ }
319
+ return {
320
+ ok: false,
321
+ dir: result.dir ?? '',
322
+ fromCache: false,
323
+ error: result.error ?? '下载失败',
324
+ url,
325
+ hint: result.hint ?? '',
326
+ }
327
+ } catch (error) {
328
+ return {
329
+ ok: false,
330
+ dir: '',
331
+ fromCache: false,
332
+ error: error?.message ?? String(error),
333
+ url: fallbackUrl,
334
+ hint: '检查下载地址后重试,或在维护页「代理 → 组件」上传 ris-proxy.4.0.tgz。',
335
+ }
336
+ }
337
+ }
338
+
339
+
340
+ /** How long a failed `%LOCALAPPDATA%` probe is remembered before it is asked again. */
341
+ const LOCAL_APP_DATA_RETRY_MS = 60000
342
+ let localAppDataCache = null // { value: string, at: number }
343
+ let warnedNoWindowsSide = false
344
+ /** `%LOCALAPPDATA%` as a Windows path; '' when it cannot be asked (native Linux/macOS). */
345
+ function windowsLocalAppData() {
346
+ const now = Date.now()
347
+ // A resolved value never changes; an empty one may (WSL interop is enabled after
348
+ // the fact, or `cmd.exe` was briefly unavailable), so only cache it for a minute.
349
+ if (localAppDataCache !== null && (localAppDataCache.value !== '' || now - localAppDataCache.at < LOCAL_APP_DATA_RETRY_MS)) {
350
+ return localAppDataCache.value
351
+ }
352
+ if (process.platform === 'win32') {
353
+ localAppDataCache = { value: process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), at: now }
354
+ return localAppDataCache.value
355
+ }
356
+ if (existsSync('/mnt/c') !== true) {
357
+ if (warnedNoWindowsSide !== true) {
358
+ warnedNoWindowsSide = true
359
+ // One readable line instead of a silent '' — this is the "not WSL" case.
360
+ console.error('[dsh-ris-ide] 没有 /mnt/c:当前环境不是 WSL,跳过 Windows 版 ProxyBridge 的复制(本机不会运行 Windows 侧)。')
361
+ }
362
+ localAppDataCache = { value: '', at: now }
363
+ return ''
364
+ }
365
+ try {
366
+ const out = spawnSync('cmd.exe', ['/d', '/s', '/c', 'echo %LOCALAPPDATA%'], { encoding: 'utf8', timeout: 5000 })
367
+ const value = String(out.stdout ?? '').trim()
368
+ const resolved = /^[A-Za-z]:[\\/]/.test(value) === true ? value : ''
369
+ localAppDataCache = { value: resolved, at: now }
370
+ return resolved
371
+ } catch {
372
+ localAppDataCache = { value: '', at: now }
373
+ return ''
374
+ }
375
+ }
376
+
377
+ /** Test seam: where the Windows bundle should land (production: `%LOCALAPPDATA%`). */
378
+ function bundleTargetDir(platform) {
379
+ if (typeof probeHooks.bundleTarget === 'function') return String(probeHooks.bundleTarget({ platform }) ?? '')
380
+ return windowsBundleDir({ platform })
381
+ }
382
+
383
+ /**
384
+ * Where the Windows side runs the materialised CLI from.
385
+ *
386
+ * The Windows redirector must run on the Windows side of the boundary, so the
387
+ * binary cannot stay inside the Linux filesystem (`\\wsl$` executables are not
388
+ * reliable): it is materialized under `%LOCALAPPDATA%\dsh-ris-ide\proxybridge` and,
389
+ * on WSL, addressed through `/mnt/<drive>`.
390
+ * @param {{platform?: string}} [options] - overrides for tests.
391
+ * @returns {string} posix path on WSL, native path on Windows, '' when unknown.
392
+ */
393
+ export function windowsBundleDir(options = {}) {
394
+ const platform = options.platform ?? process.platform
395
+ const local = platform === 'win32'
396
+ ? (process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'))
397
+ : windowsToPosixPath(windowsLocalAppData())
398
+ if (local === '') return ''
399
+ return join(local, 'dsh-ris-ide', 'proxybridge', 'windows')
400
+ }
401
+
402
+ let windowsBundlePrepared = null // { dir, fingerprint } of a complete copy; failures are never cached
403
+ /** How different a copied file's mtime may be from its source before we re-copy. */
404
+ const BUNDLE_MTIME_TOLERANCE_MS = 2000
405
+ /**
406
+ * Where the "which bundle is materialised where" record lives. It sits in the proxy
407
+ * home, not next to the copies: `%LOCALAPPDATA%` only ever holds the bundle files
408
+ * (users and antivirus look at that folder), while this record must survive a
409
+ * daemon restart so a bundle installed in the meantime still refreshes the Windows
410
+ * side on the next start (review B-P1-2).
411
+ */
412
+ const MATERIALISED_STATE_FILENAME = 'windows-materialised.json'
413
+
414
+ function materialisedStatePath() {
415
+ return join(proxyHomeDir(), REDIRECTOR_DIRNAME, MATERIALISED_STATE_FILENAME)
416
+ }
417
+
418
+ /** @returns {string} fingerprint recorded for `target`, or '' when absent/unreadable. */
419
+ function materialisedFingerprint(target) {
420
+ try {
421
+ const state = JSON.parse(readFileSync(materialisedStatePath(), 'utf8'))
422
+ return state !== null && typeof state === 'object' && state.dir === target && typeof state.fingerprint === 'string' ? state.fingerprint : ''
423
+ } catch {
424
+ return ''
425
+ }
426
+ }
427
+
428
+ /** Record which bundle a materialised copy was made from (best effort). */
429
+ function rememberMaterialised(target, fingerprint) {
430
+ try {
431
+ const file = materialisedStatePath()
432
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
433
+ writeFileSync(file, `${JSON.stringify({ dir: target, fingerprint, at: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 })
434
+ } catch {
435
+ // The marker only saves a re-copy; failing to write it must not fail the launch.
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Copy one bundle file unless the target already matches (size + mtime).
441
+ * `force` copies even when the metadata looks identical: a new bundle can have the
442
+ * same byte count and an mtime within the tolerance window, and then the Windows
443
+ * side would keep running the previous DLLs (review B-P1-2).
444
+ */
445
+ function copyBundleFile(from, to, options = {}) {
446
+ if (existsSync(from) !== true) return false
447
+ const source = statSync(from)
448
+ if (options.force !== true && existsSync(to) === true) {
449
+ const existing = statSync(to)
450
+ // Size AND mtime: a plugin update can ship the same byte count with new bits.
451
+ if (existing.size === source.size && Math.abs(existing.mtimeMs - source.mtimeMs) <= BUNDLE_MTIME_TOLERANCE_MS) return true
452
+ }
453
+ mkdirSync(dirname(to), { recursive: true })
454
+ copyFileSync(from, to)
455
+ // `copyFileSync` stamps "now"; carry the source mtime so the next call can tell a
456
+ // fresh copy from a stale one instead of re-copying the megabytes every time.
457
+ utimesSync(to, source.atime, source.mtime)
458
+ return true
459
+ }
460
+
461
+ /**
462
+ * Materialise the cached Windows files next to each other (idempotent). Run before
463
+ * any Windows-side launch: a Windows process cannot execute a binary that only
464
+ * lives in the Linux filesystem, and the copy must follow the *current* bundle —
465
+ * the cache is keyed by {@link bundleFingerprint}, so a newly downloaded/uploaded
466
+ * bundle always refreshes the Windows copy (review B-P1-2).
467
+ *
468
+ * A failed run is deliberately NOT cached: the next call retries (a missing
469
+ * `%LOCALAPPDATA%` probe or a locked file can heal on its own). Only a complete
470
+ * copy is remembered.
471
+ * @param {{force?: boolean, platform?: string, targetDir?: string}} [options] - overrides for tests.
472
+ * @returns {string|undefined} the folder holding a complete CLI bundle; `''` when no
473
+ * Windows-addressable target exists; `undefined` when the distribution itself is
474
+ * not installed yet (caller must show "未安装,请下载/上传").
475
+ */
476
+ export function prepareWindowsBundle(options = {}) {
477
+ const fingerprint = bundleFingerprint()
478
+ if (options.force !== true && windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint === fingerprint) {
479
+ // The folder can disappear between calls (user cleanup); redo it rather than
480
+ // hand out a path that no longer holds the CLI.
481
+ if (existsSync(join(windowsBundlePrepared.dir, 'ProxyBridge_CLI.exe')) === true) return windowsBundlePrepared.dir
482
+ windowsBundlePrepared = null
483
+ }
484
+ // No distribution cached yet: there is nothing to copy, and silently pointing at
485
+ // a path that will never appear is exactly the failure this round removes.
486
+ if (bundleIsInstalled(bundledBundleDir()) !== true) return undefined
487
+ const platform = options.platform ?? process.platform
488
+ const target = options.targetDir ?? bundleTargetDir(platform)
489
+ if (target === '') return ''
490
+ // A copy that belongs to a different bundle fingerprint must be replaced, even
491
+ // when the files look identical by size+mtime. Compare against the on-disk marker
492
+ // too: the in-memory cache is empty after a daemon restart.
493
+ const refresh = options.force === true
494
+ || (windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint !== fingerprint)
495
+ || materialisedFingerprint(target) !== fingerprint
496
+ const source = bundledRedirectorDir({ platform: 'win32' })
497
+ const names = ['ProxyBridge_CLI.exe', 'ProxyBridgeCore.dll', 'WinDivert.dll', 'WinDivert64.sys']
498
+ let complete = true
499
+ for (const name of names) {
500
+ try {
501
+ if (copyBundleFile(join(source, name), join(target, name), { force: refresh }) !== true) complete = false
502
+ } catch {
503
+ complete = false
504
+ }
505
+ }
506
+ // The licence texts live at the root of the cached distribution (they cover both
507
+ // platforms). They are not needed to run the CLI, so a failure here must not make
508
+ // the bundle unusable — but an LGPL/MIT redistribution should carry them.
509
+ const licenceDir = bundledBundleDir()
510
+ for (const name of ['NOTICE.md', 'LICENSE-ProxyBridge.txt']) {
511
+ try {
512
+ copyBundleFile(join(licenceDir, name), join(target, name), { force: refresh })
513
+ } catch {
514
+ // best-effort: the CLI still runs
515
+ }
516
+ }
517
+ // Only the machine-wide materialisation is worth caching; a caller passing
518
+ // targetDir is testing (or preparing an explicit folder) and must not poison it.
519
+ if (complete === true) rememberMaterialised(target, fingerprint)
520
+ if (options.targetDir === undefined) windowsBundlePrepared = complete ? { dir: target, fingerprint } : null
521
+ return complete ? target : ''
522
+ }
523
+
524
+ /** Actionable text for "the distribution was never downloaded/uploaded". */
525
+ export const MISSING_BUNDLE_HINT = `ProxyBridge 组件未安装:打开 risd 维护页「代理 → 组件」点「下载」(或上传 ris-proxy.tgz);也可设 DSH_RIS_IDE_PROXYBRIDGE_URL 指向 tgz。默认地址:${DEFAULT_BUNDLE_URL}`
526
+
213
527
  /**
214
528
  * Candidate locations of the redirector CLI, per side of the OS boundary.
215
529
  *
@@ -221,30 +535,61 @@ export function redirectorLogPath() {
221
535
  * Inside WSL both exist and neither replaces the other. An explicit
222
536
  * `DSH_RIS_IDE_PROXYBRIDGE` pins one path (tests, unusual installs) and is
223
537
  * reported on both sides.
224
- * @param {{platform?: string, wsl?: boolean, side?: 'local'|'windows'}} [options] - overrides for tests.
225
- * @returns absolute candidate paths, most specific first.
538
+ *
539
+ * The distribution is not shipped any more, so the first "built-in" candidate is
540
+ * the downloaded cache (`~/.dsh-ris-ide/proxybridge/bundle`). When it is absent the
541
+ * list still carries the expected paths (so diagnostics can show them) and the
542
+ * non-enumerable `missingBundle` flag is set for the caller.
543
+ * @param {{platform?: string, side?: 'local'|'windows', installDir?: string, bundleDir?: string}} [options] - overrides for tests.
544
+ * @returns {string[]} absolute candidate paths, most specific first, plus
545
+ * non-enumerable `bundleDir` / `bundleInstalled` / `missingBundle` fields.
226
546
  */
227
547
  export function redirectorCandidates(options = {}) {
228
548
  const platform = options.platform ?? process.platform
229
549
  const side = options.side ?? 'local'
230
- const wsl = options.wsl ?? (platform === 'linux' && engineSide() === 'wsl')
231
550
  const override = process.env.DSH_RIS_IDE_PROXYBRIDGE
551
+ const installRoot = options.installDir ?? bundledBundleDir()
552
+ const installed = bundleIsInstalled(installRoot)
232
553
  const list = []
233
554
  if (typeof override === 'string' && override !== '') list.push(override)
555
+ // The downloaded cache is the primary source; the materialised windows folder is
556
+ // only known to the caller that prepared it (findRedirector), never guessed here.
557
+ const materialised = typeof options.bundleDir === 'string' ? options.bundleDir : ''
234
558
  if (platform === 'win32') {
235
- list.push('C:\\Program Files\\ProxyBridge\\ProxyBridge_CLI.exe')
236
- return list
559
+ if (materialised !== '') list.push(join(materialised, 'ProxyBridge_CLI.exe'))
560
+ list.push(join(installRoot, 'windows', 'ProxyBridge_CLI.exe'))
561
+ // Manual extraction (old installs) and a machine-wide install as fallbacks.
562
+ list.push(join(redirectorVendorDir({ platform: 'win32' }), 'ProxyBridge_CLI.exe'))
563
+ for (const drive of ['c', 'd', 'e', 'f']) {
564
+ list.push(`${drive.toUpperCase()}:\\Program Files\\ProxyBridge\\ProxyBridge_CLI.exe`)
565
+ }
566
+ return decorateCandidates(list, installRoot, installed)
237
567
  }
238
568
  if (side === 'windows') {
239
- // The Windows host's install, reached through /mnt. Offsets are the common ones.
240
- for (const drive of ['d', 'c']) list.push(`/mnt/${drive}/Program Files/ProxyBridge/ProxyBridge_CLI.exe`)
241
- return list
242
- }
243
- // Local side: the vendored copy first (works on any distro without a system
244
- // install), then whatever a package manager put on PATH.
569
+ if (materialised !== '') list.push(join(materialised, 'ProxyBridge_CLI.exe'))
570
+ list.push(join(installRoot, 'windows', 'ProxyBridge_CLI.exe'))
571
+ list.push(join(redirectorVendorDir({ platform: 'win32' }), 'ProxyBridge_CLI.exe'))
572
+ // A pre-existing install, reached through /mnt. Offsets are the common ones.
573
+ for (const drive of ['d', 'c', 'e']) list.push(`/mnt/${drive}/Program Files/ProxyBridge/ProxyBridge_CLI.exe`)
574
+ return decorateCandidates(list, installRoot, installed)
575
+ }
576
+ // Local side: the downloaded cache first, then a manual extraction, then whatever
577
+ // a package manager put on PATH.
578
+ list.push(join(installRoot, 'linux', 'ProxyBridge'))
245
579
  list.push(join(redirectorVendorDir({ platform }), 'ProxyBridge'))
246
580
  list.push('/usr/local/bin/ProxyBridge')
247
581
  list.push('/usr/bin/ProxyBridge')
582
+ return decorateCandidates(list, installRoot, installed)
583
+ }
584
+
585
+ /**
586
+ * Attach the bundle diagnosis to a candidate list without changing its array shape
587
+ * (callers iterate it; `deepEqual` against a plain array must keep working).
588
+ */
589
+ function decorateCandidates(list, installRoot, installed) {
590
+ Object.defineProperty(list, 'bundleDir', { value: installRoot, enumerable: false })
591
+ Object.defineProperty(list, 'bundleInstalled', { value: installed === true, enumerable: false })
592
+ Object.defineProperty(list, 'missingBundle', { value: installed !== true, enumerable: false })
248
593
  return list
249
594
  }
250
595
  /**
@@ -324,6 +669,11 @@ export function clearStopSignals() {
324
669
  export function requestRedirectorStop() {
325
670
  try {
326
671
  mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
672
+ // A done file left by an earlier stop (or written by a concurrent watchdog
673
+ // answer) would make the wait below return immediately and report a teardown
674
+ // that never happened, so the request removes it first — same rule the reload
675
+ // handshake already follows (review B-P2-7).
676
+ try { unlinkSync(stoppedMarkerPath()) } catch { /* absent */ }
327
677
  writeFileSync(stopRequestPath(), `${new Date().toISOString()}\n`, { mode: 0o600 })
328
678
  return true
329
679
  } catch {
@@ -638,7 +988,8 @@ export async function startRedirector(options = {}) {
638
988
  // useless, and "no ProxyBridge" is a much better answer than "no rules".
639
989
  const found = findRedirector({ side })
640
990
  if (found.found !== true) {
641
- return { started: false, side, command: '', reason: side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge' }
991
+ // A missing download is not "no rules": say what to install and where.
992
+ return { started: false, side, command: '', reason: found.reason ?? (side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge'), missingBundle: found.missingBundle === true }
642
993
  }
643
994
  const profile = writeRedirectorProfile(readProxyConfig(''), { path: options.profilePath })
644
995
  const plan = redirectorCommand({ cliPath: found.path, profilePath: profile.path, verbose: options.verbose, platform: side === 'windows' ? 'win32' : 'linux' })
@@ -798,24 +1149,56 @@ export function redirectorVendorDir(options = {}) {
798
1149
  return join(redirectorHome(), 'vendor', platform === 'win32' ? 'windows' : 'linux')
799
1150
  }
800
1151
 
1152
+ let warnedBundleUnavailable = false
801
1153
  /**
802
1154
  * Find a usable CLI for one side.
803
1155
  *
804
1156
  * `side` names the network stack that gets hooked, not the platform this process
805
1157
  * runs on: inside WSL both sides exist and neither replaces the other.
806
- * @param {{side?: 'local'|'windows', platform?: string, wsl?: boolean}} [options] - overrides for tests.
807
- * @returns {{found: boolean, path: string, kind: string, candidates: string[]}} the first hit.
1158
+ *
1159
+ * Before a Windows-side lookup, the cached distribution is materialised under
1160
+ * `%LOCALAPPDATA%` (unless the caller pinned `platform`, the test-only override).
1161
+ * Nothing is downloaded here — the maintenance page owns that — so a missing
1162
+ * distribution is reported through `missingBundle`/`reason`, never as silence.
1163
+ * @param {{side?: 'local'|'windows', platform?: string, targetDir?: string, bundleDir?: string}} [options] - overrides for tests.
1164
+ * @returns {{found: boolean, path: string, kind: string, candidates: string[], bundleDir: string, missingBundle: boolean, reason?: string}} the first hit plus the bundle diagnosis.
808
1165
  */
809
1166
  export function findRedirector(options = {}) {
810
1167
  const platform = options.platform ?? process.platform
811
1168
  const side = options.side === 'windows' ? 'windows' : 'local'
812
- const candidates = redirectorCandidates({ platform, side, wsl: options.wsl })
1169
+ let bundleDir = options.bundleDir
1170
+ const needsWindowsBundle = platform === 'win32' || side === 'windows'
1171
+ const installed = bundleIsInstalled(bundledBundleDir())
1172
+ const missingBundle = installed !== true
1173
+ if (bundleDir === undefined && options.platform === undefined && needsWindowsBundle) {
1174
+ try {
1175
+ const prepared = options.targetDir === undefined ? prepareWindowsBundle() : prepareWindowsBundle({ targetDir: options.targetDir })
1176
+ if (typeof prepared === 'string' && prepared !== '') bundleDir = prepared
1177
+ else if (prepared === '' && missingBundle !== true && warnedBundleUnavailable !== true) {
1178
+ // Downloaded, but this host has no Windows-addressable %LOCALAPPDATA%.
1179
+ warnedBundleUnavailable = true
1180
+ console.error('[dsh-ris-ide] 无法确定 %LOCALAPPDATA%:Windows 侧代理桥将直接使用下载缓存里的路径。')
1181
+ }
1182
+ } catch (error) {
1183
+ if (warnedBundleUnavailable !== true) {
1184
+ warnedBundleUnavailable = true
1185
+ console.error(`[dsh-ris-ide] 准备 Windows 版 ProxyBridge 失败:${error?.message ?? String(error)}`)
1186
+ }
1187
+ }
1188
+ }
1189
+ const candidates = redirectorCandidates({ platform, side, ...(bundleDir === undefined ? {} : { bundleDir }) })
813
1190
  for (const path of candidates) {
814
1191
  if (existsSync(path) !== true) continue
815
1192
  const kind = /\.exe$/i.test(path) === true ? 'windows-cli' : 'linux-cli'
816
- return { found: true, path, kind, candidates }
1193
+ // A CLI we can actually run means the component is NOT missing, even when it
1194
+ // came from DSH_RIS_IDE_PROXYBRIDGE, a vendor/Program Files install, or an
1195
+ // explicit bundleDir instead of our download cache (review B-P2 missingBundle).
1196
+ return { found: true, path, kind, candidates, bundleDir: candidates.bundleDir, bundleCached: installed === true, missingBundle: false }
817
1197
  }
818
- return { found: false, path: candidates[0] ?? '', kind: '', candidates }
1198
+ const result = { found: false, path: candidates[0] ?? '', kind: '', candidates, bundleDir: candidates.bundleDir, bundleCached: installed === true, missingBundle: candidates.missingBundle === true }
1199
+ if (result.missingBundle === true) result.reason = MISSING_BUNDLE_HINT
1200
+ else result.reason = side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge'
1201
+ return result
819
1202
  }
820
1203
 
821
1204
  /** Ask the CLI for its version; '' when it cannot answer (cached: it never changes). */
@@ -1034,13 +1417,34 @@ export function stopRedirectorSync(options = {}) {
1034
1417
  const stopped = results.filter((result) => result.stopped === true)
1035
1418
  if (stopped.length > 0) {
1036
1419
  const first = stopped[0]
1037
- return { stopped: true, pid: first.pid, side: first.side, service: first.service, byWatchdog: first.byWatchdog, results }
1420
+ return { stopped: true, pid: first.pid, side: first.side, service: first.service, byWatchdog: first.byWatchdog, foreign: first.foreign === true, results }
1038
1421
  }
1039
1422
  // Nothing was even detected: keep the historical terse answer (the UI shows it).
1040
1423
  if (results.every((result) => result.pid === undefined)) return { stopped: false, reason: '未在运行' }
1041
1424
  return { stopped: false, reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未发现运行中的桥接', results }
1042
1425
  }
1043
1426
 
1427
+ /**
1428
+ * Record that a stop hit a bridge we never wrote a pid file for.
1429
+ *
1430
+ * `stopRedirector()` also stops a hand-started CLI (the user pasted the sudo
1431
+ * command), which is deliberate — leaving root interception behind is worse.
1432
+ * But the daemon's own exit therefore ends another program some human started,
1433
+ * so the engine log must say so: a silent kill is indistinguishable from a crash
1434
+ * (review B-P2-10).
1435
+ * @param {{pid: number, source?: string}} target - detection result being stopped.
1436
+ * @returns {boolean} true when the entry was written.
1437
+ */
1438
+ function noteForeignStop(target) {
1439
+ if (target.source === 'pidfile' || target.source === undefined) return false
1440
+ try {
1441
+ appendFileSync(proxyLogPath(), `${new Date().toISOString()} [dsh-ris-ide] 停止了一个非本工具记录的桥接 pid=${target.pid} (source=${target.source})\n`)
1442
+ return true
1443
+ } catch {
1444
+ return false
1445
+ }
1446
+ }
1447
+
1044
1448
  /** Stop one side; detection first, so a dead record can never fake success. */
1045
1449
  function stopRedirectorSideSync(side, options) {
1046
1450
  const record = redirectorPidRecord(side)
@@ -1067,6 +1471,8 @@ function stopRedirectorSideSync(side, options) {
1067
1471
  * the CLI and puts ProxyBridgeSvc back, with no second UAC.
1068
1472
  */
1069
1473
  function stopWindowsSideSync(target, options) {
1474
+ const foreign = target.source !== undefined && target.source !== 'pidfile'
1475
+ const foreignLogged = foreign ? noteForeignStop(target) : false
1070
1476
  requestRedirectorStop()
1071
1477
  const graceMs = Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 4000
1072
1478
  const deadline = Date.now() + graceMs
@@ -1081,23 +1487,25 @@ function stopWindowsSideSync(target, options) {
1081
1487
  // watchdog normally already did it; a hand-started CLI still needs this).
1082
1488
  const service = restoreWindowsService()
1083
1489
  clearStopSignals()
1084
- return { stopped: true, pid: target.pid, source: target.source, service, byWatchdog }
1490
+ return { stopped: true, pid: target.pid, source: target.source, service, byWatchdog, foreign, foreignLogged }
1085
1491
  }
1086
1492
  const hint = target.source === 'pidfile' ? '' : '(检测到进程但不在记录中,可能需要管理员权限)'
1087
- return { stopped: false, pid: target.pid, source: target.source, reason: `无法停止 Windows 进程 ${target.pid}${hint}(${output.trim().slice(0, 120) || '没有输出'})` }
1493
+ return { stopped: false, pid: target.pid, source: target.source, foreign, foreignLogged, reason: `无法停止 Windows 进程 ${target.pid}${hint}(${output.trim().slice(0, 120) || '没有输出'})` }
1088
1494
  }
1089
1495
 
1090
1496
  function stopLocalSideSync(target, options) {
1497
+ const foreign = target.source !== undefined && target.source !== 'pidfile'
1498
+ const foreignLogged = foreign ? noteForeignStop(target) : false
1091
1499
  try { process.kill(target.pid, 'SIGTERM') } catch (error) {
1092
- if (error?.code === 'EPERM') return { stopped: false, pid: target.pid, side: 'local', reason: `需要 sudo kill ${target.pid}` }
1500
+ if (error?.code === 'EPERM') return { stopped: false, pid: target.pid, side: 'local', foreign, foreignLogged, reason: `需要 sudo kill ${target.pid}` }
1093
1501
  }
1094
1502
  // Block the exit hook briefly: SIGTERM on the engine is quick, and leaving a
1095
1503
  // root process behind after dsh quits is worse than a short delay.
1096
1504
  const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 3000)
1097
1505
  while (Date.now() < limit && pidAlive(target.pid)) sleepSync(120)
1098
- if (pidAlive(target.pid)) return { stopped: false, pid: target.pid, side: 'local', reason: `进程 ${target.pid} 仍在运行(需要 sudo kill ${target.pid})` }
1506
+ if (pidAlive(target.pid)) return { stopped: false, pid: target.pid, side: 'local', foreign, foreignLogged, reason: `进程 ${target.pid} 仍在运行(需要 sudo kill ${target.pid})` }
1099
1507
  clearRedirectorPid('local')
1100
- return { stopped: true, pid: target.pid, source: target.source, side: 'local' }
1508
+ return { stopped: true, pid: target.pid, source: target.source, side: 'local', foreign, foreignLogged }
1101
1509
  }
1102
1510
 
1103
1511
  /** taskkill one pid (checked from the pid file) — test seam `taskkill` overrides it. */
@@ -1683,7 +2091,16 @@ function buildStatus(detection, mode) {
1683
2091
  // The async route must not block 6 s on `--version`: take it from the cache.
1684
2092
  version = mode === 'async' ? (versionCache.get(found.path)?.version ?? '') : redirectorVersion(found.path)
1685
2093
  }
1686
- return { available: found.found, path: found.path, kind: found.kind, version }
2094
+ // `missingBundle` + `reason` let the maintenance page say "download/upload the
2095
+ // component" instead of showing an unexplained empty path.
2096
+ return {
2097
+ available: found.found,
2098
+ path: found.path,
2099
+ kind: found.kind,
2100
+ version,
2101
+ missingBundle: found.missingBundle === true,
2102
+ ...(found.reason === undefined ? {} : { reason: found.reason }),
2103
+ }
1687
2104
  }
1688
2105
  const profilePath = redirectorProfilePath()
1689
2106
  return {
@@ -1777,7 +2194,7 @@ export async function syncRedirector(cwd, options = {}) {
1777
2194
  const written = writeRedirectorProfile(config, { upstream: options.upstream })
1778
2195
  const found = findRedirector({ side: options.side })
1779
2196
  if (found.found === false) {
1780
- return { written, command: '', started: false, reason: '未找到 ProxyBridge CLI(可用 DSH_RIS_IDE_PROXYBRIDGE 指定,或把发行版解压到 vendor 目录)' }
2197
+ return { written, command: '', started: false, reason: found.reason ?? '未找到 ProxyBridge CLI(可用 DSH_RIS_IDE_PROXYBRIDGE 指定,或在维护页「代理 → 组件」上传/下载组件)', missingBundle: found.missingBundle === true }
1781
2198
  }
1782
2199
  const command = redirectorCommand({ cliPath: found.path, profilePath: written.path, verbose: options.verbose })
1783
2200
  if (options.start === false) return { written, command, started: false, reason: '' }
@@ -1808,7 +2225,12 @@ export async function startRedirectors(options = {}) {
1808
2225
  if (process.env.NODE_TEST_CONTEXT !== undefined) {
1809
2226
  return { started: [], skipped: [{ side: '', reason: '测试环境不启动系统层拦截' }], running: false }
1810
2227
  }
1811
- const sides = Array.isArray(options.sides) && options.sides.length > 0 ? options.sides : ['windows', 'local']
2228
+ // A Windows host has only one machine: 'local' would resolve to the same
2229
+ // ProxyBridge_CLI.exe and the second start would fight for the WinDivert handle.
2230
+ // The plugin now ships that CLI, so the default there is the windows side alone.
2231
+ const sides = Array.isArray(options.sides) && options.sides.length > 0
2232
+ ? options.sides
2233
+ : (process.platform === 'win32' ? ['windows'] : ['windows', 'local'])
1812
2234
  // `reload` applies edited rules to a bridge that is already running.
1813
2235
  const reload = options.reload === true
1814
2236
  const started = []
@@ -1821,7 +2243,7 @@ export async function startRedirectors(options = {}) {
1821
2243
  for (const side of sides) {
1822
2244
  const found = findRedirector({ side })
1823
2245
  if (found.found !== true) {
1824
- skipped.push({ side, reason: `未找到 ${side === 'windows' ? 'Windows' : '本侧'} ProxyBridge` })
2246
+ skipped.push({ side, reason: found.reason ?? `未找到 ${side === 'windows' ? 'Windows' : '本侧'} ProxyBridge`, missingBundle: found.missingBundle === true })
1825
2247
  continue
1826
2248
  }
1827
2249
  if (claimed.has(found.path)) {
@@ -1861,7 +2283,12 @@ export async function startRedirectors(options = {}) {
1861
2283
  * @returns {Promise<{ok: boolean, written: {path: string, rules: number, skipped: object[]}, reloaded: object[], skipped: object[], reason?: string}>} outcome.
1862
2284
  */
1863
2285
  export async function reloadRedirectorsWithProfile(cwd, options = {}) {
1864
- const sides = Array.isArray(options.sides) && options.sides.length > 0 ? options.sides : ['windows', 'local']
2286
+ // A Windows host has only one machine: 'local' would resolve to the same
2287
+ // ProxyBridge_CLI.exe and the second start would fight for the WinDivert handle.
2288
+ // The plugin now ships that CLI, so the default there is the windows side alone.
2289
+ const sides = Array.isArray(options.sides) && options.sides.length > 0
2290
+ ? options.sides
2291
+ : (process.platform === 'win32' ? ['windows'] : ['windows', 'local'])
1865
2292
  let written = null
1866
2293
  try {
1867
2294
  written = writeRedirectorProfile(readProxyConfig(cwd), { upstream: options.upstream, path: options.profilePath })
@@ -2029,9 +2456,26 @@ export function windowsPathOf(path) {
2029
2456
  return text
2030
2457
  }
2031
2458
 
2032
- /** @param {object[]} args - argv as this side spells it. @returns {object[]} Windows-spelled argv. */
2459
+ /**
2460
+ * Translate only the argv entries that really are existing files.
2461
+ *
2462
+ * ProxyBridge's own flags look like paths (`/d`, `/p:key=value`), so "starts with
2463
+ * `/`" is not enough: translating those into `\d` / `\p:key=value` corrupts the
2464
+ * command line. Windows-spelled values (`C:\…`, `\\wsl.localhost\…`) are already
2465
+ * correct for the other side and must be left untouched.
2466
+ * @param {object[]} args - argv as this side spells it.
2467
+ * @returns {object[]} Windows-spelled argv.
2468
+ */
2033
2469
  function windowsArgsOf(args) {
2034
- return args.map((arg) => (typeof arg === 'string' && arg.startsWith('/') ? windowsPathOf(arg) : arg))
2470
+ return args.map((arg) => {
2471
+ if (typeof arg !== 'string' || arg.startsWith('/') !== true) return arg
2472
+ try {
2473
+ if (existsSync(arg) !== true || statSync(arg).isFile() !== true) return arg
2474
+ } catch {
2475
+ return arg
2476
+ }
2477
+ return windowsPathOf(arg)
2478
+ })
2035
2479
  }
2036
2480
 
2037
2481
  function spawnSyncText(command, args, timeoutMs) {
@@ -2041,6 +2485,10 @@ function spawnSyncText(command, args, timeoutMs) {
2041
2485
 
2042
2486
  export const __test = {
2043
2487
  PROFILE_VERSION,
2488
+ bundledBundleDir,
2489
+ bundleCacheInstalled,
2490
+ ensureBundleReady,
2491
+ MISSING_BUNDLE_HINT,
2044
2492
  startRedirector,
2045
2493
  stopRedirectorSync,
2046
2494
  pidAliveOn,
@@ -2084,6 +2532,7 @@ export const __test = {
2084
2532
  reloadDonePath,
2085
2533
  reloadFailedPath,
2086
2534
  windowsPathOf,
2535
+ windowsArgsOf,
2087
2536
  }
2088
2537
 
2089
2538
  const SELF = basename(process.argv[1] ?? '')