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
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
@@ -22,13 +31,14 @@
22
31
  */
23
32
 
24
33
  import { execFile, spawn, spawnSync } from 'node:child_process'
25
- import { randomUUID } from 'node:crypto'
26
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
34
+ import { createHash, randomUUID } from 'node:crypto'
35
+ import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, 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,12 @@ 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
116
+ windowsBundleFailure = null
117
+ windowsBundleFailureCache = null
99
118
  }
100
119
 
101
120
  /**
@@ -123,6 +142,56 @@ function sleepSync(ms) {
123
142
  }
124
143
  }
125
144
 
145
+ /** Sleep without blocking the event loop (the UAC wait can take tens of seconds). */
146
+ function sleepAsync(ms) {
147
+ return new Promise((resolve) => setTimeout(resolve, ms))
148
+ }
149
+
150
+ /**
151
+ * Run a program and wait for it to exit without blocking the event loop.
152
+ *
153
+ * The elevated start is launched through a UAC consent dialog: `spawnSync` returned
154
+ * only after the user answered, which froze the whole daemon (3 s heartbeat, HTTP
155
+ * routes, log follow) for up to 45 s. A hung dialog is killed at `timeoutMs`.
156
+ * @param {string} command - executable.
157
+ * @param {string[]} args - argv.
158
+ * @param {number} timeoutMs - kill the launcher after this long.
159
+ * @returns {Promise<{code: number|null, timedOut: boolean}>} exit status.
160
+ */
161
+ function spawnDetachedText(command, args, timeoutMs) {
162
+ return new Promise((resolve) => {
163
+ let child = null
164
+ let timedOut = false
165
+ let settled = false
166
+ const finish = (code) => {
167
+ if (settled === true) return
168
+ settled = true
169
+ clearTimeout(timer)
170
+ resolve({ code, timedOut })
171
+ }
172
+ const timer = setTimeout(() => {
173
+ timedOut = true
174
+ try { child?.kill() } catch { /* the dialog outlives the launcher */ }
175
+ finish(null)
176
+ }, timeoutMs)
177
+ timer.unref?.()
178
+ try {
179
+ child = spawn(command, args, { stdio: 'ignore', windowsHide: true })
180
+ } catch {
181
+ finish(null)
182
+ return
183
+ }
184
+ child.on('error', () => finish(null))
185
+ child.on('exit', (code) => finish(code))
186
+ child.unref?.()
187
+ })
188
+ }
189
+
190
+ /** Quote one argv entry for bash: `'` becomes `'\''`, so a path can't break out. */
191
+ function shellQuote(value) {
192
+ return "'" + String(value).replace(/'/g, "'\\''") + "'"
193
+ }
194
+
126
195
  /** Where our profile/pid/log live: one folder beside the shared proxy config. */
127
196
  export function redirectorHome() {
128
197
  return join(proxyHomeDir(), REDIRECTOR_DIRNAME)
@@ -210,6 +279,342 @@ export function redirectorLogPath() {
210
279
  return join(redirectorHome(), REDIRECTOR_LOG_FILENAME)
211
280
  }
212
281
 
282
+ /**
283
+ * The downloaded-and-cached ProxyBridge distribution (machine-wide proxy home).
284
+ *
285
+ * Nothing is shipped inside the plugin any more (2.9 MB of binaries made every
286
+ * install heavy and pinned the upstream version): `lib/proxybridge-bundle.js`
287
+ * downloads/accepts an uploaded `.tgz` here on first use.
288
+ * @returns {string} absolute path to `<proxyHome>/proxybridge/bundle`.
289
+ */
290
+ export function bundledBundleDir() {
291
+ return bundleInstallDir(proxyHomeDir())
292
+ }
293
+
294
+ /**
295
+ * The cached distribution for one platform.
296
+ *
297
+ * The old name is kept for compat (this module and its tests import it), but it no
298
+ * longer points inside the plugin: the folder only exists after a download/upload.
299
+ * @param {{platform?: string, dir?: string}} [options] - platform / install-dir overrides for tests.
300
+ * @returns {string} absolute path to `<bundle>/<windows|linux>`.
301
+ */
302
+ export function bundledRedirectorDir(options = {}) {
303
+ const platform = options.platform ?? process.platform
304
+ return join(options.dir ?? bundledBundleDir(), platform === 'win32' ? 'windows' : 'linux')
305
+ }
306
+
307
+ /** True when the cached distribution is complete (manifest plus every file). */
308
+ export function bundleCacheInstalled() {
309
+ return bundleIsInstalled(bundledBundleDir())
310
+ }
311
+
312
+ /**
313
+ * Identity of the currently installed bundle. The Windows-side copy (below) is
314
+ * materialised from it, so a changed fingerprint means the DLLs/CLI on the Windows
315
+ * side are stale and must be copied again (review B-P1-2).
316
+ * @param {string} [dir] - install directory; defaults to {@link bundledBundleDir}.
317
+ * @returns {string} `sha256:installedAt`, or '' when nothing is installed.
318
+ */
319
+ export function bundleFingerprint(dir = bundledBundleDir()) {
320
+ const manifest = readManifest(dir)
321
+ if (manifest === null) return ''
322
+ return `${manifest.sha256 ?? ''}:${manifest.installedAt ?? ''}`
323
+ }
324
+
325
+ /** Machine-level settings file (`~/.dsh-ris-ide/settings.json`); unreadable counts as empty. */
326
+ function readMachineSettings() {
327
+ try {
328
+ const parsed = JSON.parse(readFileSync(join(proxyHomeDir(), 'settings.json'), 'utf8'))
329
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
330
+ } catch {
331
+ return {}
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Make the ProxyBridge distribution available: reuse the cache, else download it.
337
+ *
338
+ * URL and digest priority now live in exactly one place — `resolveBundleUrls` /
339
+ * `resolveBundleSha256` inside `lib/proxybridge-bundle.js` (env → settings →
340
+ * mirrors), shared with the daemon. This function only forwards the explicit
341
+ * route-level `url` and the machine settings; it must not re-order them
342
+ * (review A3-P2-1/-2). Never throws — the route layer turns `{ok:false}` into a
343
+ * readable failure.
344
+ * @param {{url?: string, fetchImpl?: typeof fetch, force?: boolean}} [options] - overrides for the route/tests.
345
+ * @returns {Promise<{ok: boolean, dir: string, fromCache: boolean, error: string, url: string, hint: string, warning?: string}>} outcome.
346
+ */
347
+ export async function ensureBundleReady(options = {}) {
348
+ const fallbackUrl = DEFAULT_BUNDLE_URL
349
+ try {
350
+ const settings = readMachineSettings()
351
+ const explicit = typeof options.url === 'string' && options.url.trim() !== '' ? options.url.trim() : ''
352
+ const result = await ensureBundle({
353
+ home: proxyHomeDir(),
354
+ settings,
355
+ force: options.force === true,
356
+ ...(explicit === '' ? {} : { url: explicit }),
357
+ ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
358
+ })
359
+ const url = typeof result.url === 'string' && result.url !== '' ? result.url : explicit || fallbackUrl
360
+ if (result.ok === true) {
361
+ return {
362
+ ok: true,
363
+ dir: result.dir,
364
+ fromCache: result.fromCache === true,
365
+ error: '',
366
+ url,
367
+ hint: '',
368
+ ...(typeof result.warning === 'string' ? { warning: result.warning } : {}),
369
+ }
370
+ }
371
+ return {
372
+ ok: false,
373
+ dir: result.dir ?? '',
374
+ fromCache: false,
375
+ error: result.error ?? '下载失败',
376
+ url,
377
+ hint: result.hint ?? '',
378
+ }
379
+ } catch (error) {
380
+ return {
381
+ ok: false,
382
+ dir: '',
383
+ fromCache: false,
384
+ error: error?.message ?? String(error),
385
+ url: fallbackUrl,
386
+ hint: '检查下载地址后重试,或在维护页「代理 → 组件」上传 ris-proxy.4.0.tgz。',
387
+ }
388
+ }
389
+ }
390
+
391
+
392
+ /** How long a failed `%LOCALAPPDATA%` probe is remembered before it is asked again. */
393
+ const LOCAL_APP_DATA_RETRY_MS = 60000
394
+ let localAppDataCache = null // { value: string, at: number }
395
+ let warnedNoWindowsSide = false
396
+ /** `%LOCALAPPDATA%` as a Windows path; '' when it cannot be asked (native Linux/macOS). */
397
+ function windowsLocalAppData() {
398
+ const now = Date.now()
399
+ // A resolved value never changes; an empty one may (WSL interop is enabled after
400
+ // the fact, or `cmd.exe` was briefly unavailable), so only cache it for a minute.
401
+ if (localAppDataCache !== null && (localAppDataCache.value !== '' || now - localAppDataCache.at < LOCAL_APP_DATA_RETRY_MS)) {
402
+ return localAppDataCache.value
403
+ }
404
+ if (process.platform === 'win32') {
405
+ localAppDataCache = { value: process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), at: now }
406
+ return localAppDataCache.value
407
+ }
408
+ if (existsSync('/mnt/c') !== true) {
409
+ if (warnedNoWindowsSide !== true) {
410
+ warnedNoWindowsSide = true
411
+ // One readable line instead of a silent '' — this is the "not WSL" case.
412
+ console.error('[dsh-ris-ide] 没有 /mnt/c:当前环境不是 WSL,跳过 Windows 版 ProxyBridge 的复制(本机不会运行 Windows 侧)。')
413
+ }
414
+ localAppDataCache = { value: '', at: now }
415
+ return ''
416
+ }
417
+ try {
418
+ const out = spawnSync('cmd.exe', ['/d', '/s', '/c', 'echo %LOCALAPPDATA%'], { encoding: 'utf8', timeout: 5000 })
419
+ const value = String(out.stdout ?? '').trim()
420
+ const resolved = /^[A-Za-z]:[\\/]/.test(value) === true ? value : ''
421
+ localAppDataCache = { value: resolved, at: now }
422
+ return resolved
423
+ } catch {
424
+ localAppDataCache = { value: '', at: now }
425
+ return ''
426
+ }
427
+ }
428
+
429
+ /** Test seam: where the Windows bundle should land (production: `%LOCALAPPDATA%`). */
430
+ function bundleTargetDir(platform) {
431
+ if (typeof probeHooks.bundleTarget === 'function') return String(probeHooks.bundleTarget({ platform }) ?? '')
432
+ return windowsBundleDir({ platform })
433
+ }
434
+
435
+ /**
436
+ * Where the Windows side runs the materialised CLI from.
437
+ *
438
+ * The Windows redirector must run on the Windows side of the boundary, so the
439
+ * binary cannot stay inside the Linux filesystem (`\\wsl$` executables are not
440
+ * reliable): it is materialized under `%LOCALAPPDATA%\dsh-ris-ide\proxybridge` and,
441
+ * on WSL, addressed through `/mnt/<drive>`.
442
+ * @param {{platform?: string}} [options] - overrides for tests.
443
+ * @returns {string} posix path on WSL, native path on Windows, '' when unknown.
444
+ */
445
+ export function windowsBundleDir(options = {}) {
446
+ const platform = options.platform ?? process.platform
447
+ const local = platform === 'win32'
448
+ ? (process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'))
449
+ : windowsToPosixPath(windowsLocalAppData())
450
+ if (local === '') return ''
451
+ return join(local, 'dsh-ris-ide', 'proxybridge', 'windows')
452
+ }
453
+
454
+ let windowsBundlePrepared = null // { dir, fingerprint } of a complete copy; failures are never cached
455
+ /** How different a copied file's mtime may be from its source before we re-copy. */
456
+ const BUNDLE_MTIME_TOLERANCE_MS = 2000
457
+ /**
458
+ * Where the "which bundle is materialised where" record lives. It sits in the proxy
459
+ * home, not next to the copies: `%LOCALAPPDATA%` only ever holds the bundle files
460
+ * (users and antivirus look at that folder), while this record must survive a
461
+ * daemon restart so a bundle installed in the meantime still refreshes the Windows
462
+ * side on the next start (review B-P1-2).
463
+ */
464
+ const MATERIALISED_STATE_FILENAME = 'windows-materialised.json'
465
+
466
+ function materialisedStatePath() {
467
+ return join(proxyHomeDir(), REDIRECTOR_DIRNAME, MATERIALISED_STATE_FILENAME)
468
+ }
469
+
470
+ /** @returns {string} fingerprint recorded for `target`, or '' when absent/unreadable. */
471
+ function materialisedFingerprint(target) {
472
+ try {
473
+ const state = JSON.parse(readFileSync(materialisedStatePath(), 'utf8'))
474
+ return state !== null && typeof state === 'object' && state.dir === target && typeof state.fingerprint === 'string' ? state.fingerprint : ''
475
+ } catch {
476
+ return ''
477
+ }
478
+ }
479
+
480
+ /** Record which bundle a materialised copy was made from (best effort). */
481
+ function rememberMaterialised(target, fingerprint) {
482
+ try {
483
+ const file = materialisedStatePath()
484
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
485
+ writeFileSync(file, `${JSON.stringify({ dir: target, fingerprint, at: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 })
486
+ } catch {
487
+ // The marker only saves a re-copy; failing to write it must not fail the launch.
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Copy one bundle file unless the target already matches (size + mtime).
493
+ * `force` copies even when the metadata looks identical: a new bundle can have the
494
+ * same byte count and an mtime within the tolerance window, and then the Windows
495
+ * side would keep running the previous DLLs (review B-P1-2).
496
+ */
497
+ function copyBundleFile(from, to, options = {}) {
498
+ if (existsSync(from) !== true) return false
499
+ const source = statSync(from)
500
+ if (options.force !== true && existsSync(to) === true) {
501
+ const existing = statSync(to)
502
+ // Size AND mtime: a plugin update can ship the same byte count with new bits.
503
+ if (existing.size === source.size && Math.abs(existing.mtimeMs - source.mtimeMs) <= BUNDLE_MTIME_TOLERANCE_MS) return true
504
+ }
505
+ mkdirSync(dirname(to), { recursive: true })
506
+ copyFileSync(from, to)
507
+ // `copyFileSync` stamps "now"; carry the source mtime so the next call can tell a
508
+ // fresh copy from a stale one instead of re-copying the megabytes every time.
509
+ utimesSync(to, source.atime, source.mtime)
510
+ return true
511
+ }
512
+
513
+ /**
514
+ * Materialise the cached Windows files next to each other (idempotent). Run before
515
+ * any Windows-side launch: a Windows process cannot execute a binary that only
516
+ * lives in the Linux filesystem, and the copy must follow the *current* bundle —
517
+ * the cache is keyed by {@link bundleFingerprint}, so a newly downloaded/uploaded
518
+ * bundle always refreshes the Windows copy (review B-P1-2).
519
+ *
520
+ * A failed run is deliberately NOT cached: the next call retries (a missing
521
+ * `%LOCALAPPDATA%` probe or a locked file can heal on its own). Only a complete
522
+ * copy is remembered.
523
+ * @param {{force?: boolean, platform?: string, targetDir?: string}} [options] - overrides for tests.
524
+ * @returns {string|undefined} the folder holding a complete CLI bundle; `''` when no
525
+ * Windows-addressable target exists; `undefined` when the distribution itself is
526
+ * not installed yet (caller must show "未安装,请下载/上传").
527
+ */
528
+ export function prepareWindowsBundle(options = {}) {
529
+ // Every attempt starts with a clean diagnosis: a previous failure (locked DLL, no
530
+ // %LOCALAPPDATA%, missing bundle) must not be reported for this one (review B-P2-14).
531
+ windowsBundleFailure = null
532
+ const fingerprint = bundleFingerprint()
533
+ if (options.force !== true && windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint === fingerprint) {
534
+ // The folder can disappear between calls (user cleanup); redo it rather than
535
+ // hand out a path that no longer holds the CLI.
536
+ if (existsSync(join(windowsBundlePrepared.dir, 'ProxyBridge_CLI.exe')) === true) return windowsBundlePrepared.dir
537
+ windowsBundlePrepared = null
538
+ }
539
+ // No distribution cached yet: there is nothing to copy, and silently pointing at
540
+ // a path that will never appear is exactly the failure this round removes.
541
+ if (bundleIsInstalled(bundledBundleDir()) !== true) return undefined
542
+ const platform = options.platform ?? process.platform
543
+ const target = options.targetDir ?? bundleTargetDir(platform)
544
+ if (target === '') return ''
545
+ // A copy that belongs to a different bundle fingerprint must be replaced, even
546
+ // when the files look identical by size+mtime. Compare against the on-disk marker
547
+ // too: the in-memory cache is empty after a daemon restart.
548
+ const refresh = options.force === true
549
+ || (windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint !== fingerprint)
550
+ || materialisedFingerprint(target) !== fingerprint
551
+ // A copy that fails (locked DLL, antivirus, permissions) stays broken for a while;
552
+ // retrying four multi-MB copies through /mnt/c on every status poll is pointless
553
+ // (review B-P2-13). Cache the failure for a TTL; `force` retries immediately.
554
+ const failureKey = `${target}|${fingerprint}`
555
+ if (options.force !== true && windowsBundleFailureCache !== null
556
+ && windowsBundleFailureCache.key === failureKey
557
+ && Date.now() - windowsBundleFailureCache.at < MATERIALISE_RETRY_MS) {
558
+ windowsBundleFailure = { ...windowsBundleFailureCache.failure }
559
+ return ''
560
+ }
561
+ const source = bundledRedirectorDir({ platform: 'win32' })
562
+ const names = ['ProxyBridge_CLI.exe', 'ProxyBridgeCore.dll', 'WinDivert.dll', 'WinDivert64.sys']
563
+ let complete = true
564
+ /** @type {{code: string, message: string, file: string}|null} */
565
+ let firstError = null
566
+ for (const name of names) {
567
+ try {
568
+ if (copyBundleFile(join(source, name), join(target, name), { force: refresh }) !== true) complete = false
569
+ } catch (error) {
570
+ complete = false
571
+ firstError ??= { code: String(error?.code ?? 'copy-failed'), message: String(error?.message ?? error), file: name }
572
+ }
573
+ }
574
+ // The licence texts live at the root of the cached distribution (they cover both
575
+ // platforms). They are not needed to run the CLI, so a failure here must not make
576
+ // the bundle unusable — but an LGPL/MIT redistribution should carry them.
577
+ const licenceDir = bundledBundleDir()
578
+ for (const name of ['NOTICE.md', 'LICENSE-ProxyBridge.txt']) {
579
+ try {
580
+ copyBundleFile(join(licenceDir, name), join(target, name), { force: refresh })
581
+ } catch {
582
+ // best-effort: the CLI still runs
583
+ }
584
+ }
585
+ // Only the machine-wide materialisation is worth caching; a caller passing
586
+ // targetDir is testing (or preparing an explicit folder) and must not poison it.
587
+ if (complete === true) {
588
+ rememberMaterialised(target, fingerprint)
589
+ windowsBundleFailure = null
590
+ windowsBundleFailureCache = null
591
+ } else {
592
+ windowsBundleFailure = firstError === null
593
+ ? { code: 'copy-failed', message: '文件没有完整复制', file: '' }
594
+ : { ...firstError, target }
595
+ windowsBundleFailureCache = { key: failureKey, at: Date.now(), failure: { ...windowsBundleFailure } }
596
+ }
597
+ if (options.targetDir === undefined) windowsBundlePrepared = complete ? { dir: target, fingerprint } : null
598
+ return complete ? target : ''
599
+ }
600
+
601
+ // Why the last materialise attempt failed (`''` target vs a real copy error). The
602
+ // old code printed「无法确定 %LOCALAPPDATA%」for both, which sent people looking at
603
+ // environment variables when the truth was a locked DLL (review m11624).
604
+ let windowsBundleFailure = null
605
+ /** Minimum time between retries of a failed materialisation (review B-P2-13). */
606
+ const MATERIALISE_RETRY_MS = 60 * 1000
607
+ /** Last failure, keyed by target+fingerprint so a new bundle retries at once. */
608
+ let windowsBundleFailureCache = null
609
+
610
+ /** Diagnosis of the last failed {@link prepareWindowsBundle} (`null` after a success). */
611
+ export function windowsBundleDiagnosis() {
612
+ return windowsBundleFailure === null ? null : { ...windowsBundleFailure }
613
+ }
614
+
615
+ /** Actionable text for "the distribution was never downloaded/uploaded". */
616
+ export const MISSING_BUNDLE_HINT = `ProxyBridge 组件未安装:打开 risd 维护页「代理 → 组件」点「下载」(或上传 ris-proxy.tgz);也可设 DSH_RIS_IDE_PROXYBRIDGE_URL 指向 tgz。默认地址:${DEFAULT_BUNDLE_URL}`
617
+
213
618
  /**
214
619
  * Candidate locations of the redirector CLI, per side of the OS boundary.
215
620
  *
@@ -221,30 +626,61 @@ export function redirectorLogPath() {
221
626
  * Inside WSL both exist and neither replaces the other. An explicit
222
627
  * `DSH_RIS_IDE_PROXYBRIDGE` pins one path (tests, unusual installs) and is
223
628
  * 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.
629
+ *
630
+ * The distribution is not shipped any more, so the first "built-in" candidate is
631
+ * the downloaded cache (`~/.dsh-ris-ide/proxybridge/bundle`). When it is absent the
632
+ * list still carries the expected paths (so diagnostics can show them) and the
633
+ * non-enumerable `missingBundle` flag is set for the caller.
634
+ * @param {{platform?: string, side?: 'local'|'windows', installDir?: string, bundleDir?: string}} [options] - overrides for tests.
635
+ * @returns {string[]} absolute candidate paths, most specific first, plus
636
+ * non-enumerable `bundleDir` / `bundleInstalled` / `missingBundle` fields.
226
637
  */
227
638
  export function redirectorCandidates(options = {}) {
228
639
  const platform = options.platform ?? process.platform
229
640
  const side = options.side ?? 'local'
230
- const wsl = options.wsl ?? (platform === 'linux' && engineSide() === 'wsl')
231
641
  const override = process.env.DSH_RIS_IDE_PROXYBRIDGE
642
+ const installRoot = options.installDir ?? bundledBundleDir()
643
+ const installed = bundleIsInstalled(installRoot)
232
644
  const list = []
233
645
  if (typeof override === 'string' && override !== '') list.push(override)
646
+ // The downloaded cache is the primary source; the materialised windows folder is
647
+ // only known to the caller that prepared it (findRedirector), never guessed here.
648
+ const materialised = typeof options.bundleDir === 'string' ? options.bundleDir : ''
234
649
  if (platform === 'win32') {
235
- list.push('C:\\Program Files\\ProxyBridge\\ProxyBridge_CLI.exe')
236
- return list
650
+ if (materialised !== '') list.push(join(materialised, 'ProxyBridge_CLI.exe'))
651
+ list.push(join(installRoot, 'windows', 'ProxyBridge_CLI.exe'))
652
+ // Manual extraction (old installs) and a machine-wide install as fallbacks.
653
+ list.push(join(redirectorVendorDir({ platform: 'win32' }), 'ProxyBridge_CLI.exe'))
654
+ for (const drive of ['c', 'd', 'e', 'f']) {
655
+ list.push(`${drive.toUpperCase()}:\\Program Files\\ProxyBridge\\ProxyBridge_CLI.exe`)
656
+ }
657
+ return decorateCandidates(list, installRoot, installed)
237
658
  }
238
659
  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.
660
+ if (materialised !== '') list.push(join(materialised, 'ProxyBridge_CLI.exe'))
661
+ list.push(join(installRoot, 'windows', 'ProxyBridge_CLI.exe'))
662
+ list.push(join(redirectorVendorDir({ platform: 'win32' }), 'ProxyBridge_CLI.exe'))
663
+ // A pre-existing install, reached through /mnt. Offsets are the common ones.
664
+ for (const drive of ['d', 'c', 'e']) list.push(`/mnt/${drive}/Program Files/ProxyBridge/ProxyBridge_CLI.exe`)
665
+ return decorateCandidates(list, installRoot, installed)
666
+ }
667
+ // Local side: the downloaded cache first, then a manual extraction, then whatever
668
+ // a package manager put on PATH.
669
+ list.push(join(installRoot, 'linux', 'ProxyBridge'))
245
670
  list.push(join(redirectorVendorDir({ platform }), 'ProxyBridge'))
246
671
  list.push('/usr/local/bin/ProxyBridge')
247
672
  list.push('/usr/bin/ProxyBridge')
673
+ return decorateCandidates(list, installRoot, installed)
674
+ }
675
+
676
+ /**
677
+ * Attach the bundle diagnosis to a candidate list without changing its array shape
678
+ * (callers iterate it; `deepEqual` against a plain array must keep working).
679
+ */
680
+ function decorateCandidates(list, installRoot, installed) {
681
+ Object.defineProperty(list, 'bundleDir', { value: installRoot, enumerable: false })
682
+ Object.defineProperty(list, 'bundleInstalled', { value: installed === true, enumerable: false })
683
+ Object.defineProperty(list, 'missingBundle', { value: installed !== true, enumerable: false })
248
684
  return list
249
685
  }
250
686
  /**
@@ -324,6 +760,11 @@ export function clearStopSignals() {
324
760
  export function requestRedirectorStop() {
325
761
  try {
326
762
  mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
763
+ // A done file left by an earlier stop (or written by a concurrent watchdog
764
+ // answer) would make the wait below return immediately and report a teardown
765
+ // that never happened, so the request removes it first — same rule the reload
766
+ // handshake already follows (review B-P2-7).
767
+ try { unlinkSync(stoppedMarkerPath()) } catch { /* absent */ }
327
768
  writeFileSync(stopRequestPath(), `${new Date().toISOString()}\n`, { mode: 0o600 })
328
769
  return true
329
770
  } catch {
@@ -513,7 +954,23 @@ function Write-Log($message) {
513
954
  }
514
955
 
515
956
  Write-Log "started pid=$PID"
957
+ # Single instance (m11702): every bridge start spawns a watchdog and nothing killed
958
+ # the previous one while the heartbeat stayed fresh, so restarts piled them up. Two
959
+ # watchdogs then restart the CLI at the same time — one wins the WinDivert handle,
960
+ # the other loads the rules and captures nothing. A named mutex makes the second
961
+ # copy exit instead of accumulating.
962
+ $mutexName = ${quote(paths.mutexName ?? 'Global\\dsh-ris-ide-proxybridge-watchdog')}
963
+ $watchdogMutex = New-Object System.Threading.Mutex($false, $mutexName)
964
+ if (-not $watchdogMutex.WaitOne(0)) { Write-Log 'another watchdog owns the mutex; exiting'; exit 0 }
516
965
  $specFile = ${quote(paths.cliSpec ?? '')}
966
+ $ownProfile = ${quote(paths.profile ?? '')}
967
+ # Only CLIs that carry THIS home's profile are ours: the machine may run another
968
+ # dsh-ris-ide home's bridge, and a teardown must not take it down (review A4-P2-1).
969
+ function Get-OwnCli {
970
+ $all = @(Get-CimInstance Win32_Process -Filter "Name='ProxyBridge_CLI.exe'" -ErrorAction SilentlyContinue)
971
+ if ($ownProfile -eq '') { return @($all) }
972
+ return @($all | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })
973
+ }
517
974
  $reloadFile = ${quote(paths.reloadRequest ?? '')}
518
975
  $reloadDone = ${quote(paths.reloadDone ?? '')}
519
976
  $reloadFailed = ${quote(paths.reloadFailed ?? '')}
@@ -535,14 +992,14 @@ while ($true) {
535
992
  try {
536
993
  if (-not (Test-Path $specFile)) { throw 'no cli spec' }
537
994
  $spec = Get-Content -Path $specFile -Raw | ConvertFrom-Json
538
- Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force
995
+ (Get-OwnCli) | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
539
996
  Start-Sleep -Milliseconds 400
540
997
  Start-Process -FilePath $spec.exe -ArgumentList @($spec.args) -WindowStyle Hidden -RedirectStandardOutput $spec.log -RedirectStandardError ($spec.log + '.err') | Out-Null
541
998
  Start-Sleep -Milliseconds 1500
542
999
  # Liveness alone is not enough: the host's old CLI may still be dying, and
543
1000
  # ProxyBridge.exe is a different process. Match the profile on the command line.
544
1001
  $profileArg = [string]$spec.args[1]
545
- $cim = @(Get-CimInstance Win32_Process -Filter "Name='ProxyBridge_CLI.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID })
1002
+ $cim = @(Get-OwnCli | Where-Object { $_.ProcessId -ne $PID })
546
1003
  $running = @($cim | Where-Object { $profileArg -ne '' -and $_.CommandLine -like ('*' + $profileArg + '*') })
547
1004
  $count = $running.Count
548
1005
  if ($count -gt 0) { $pidText = [string]$running[0].ProcessId } else { $errorText = 'the new CLI is not running with the recorded profile' }
@@ -573,7 +1030,8 @@ while ($true) {
573
1030
 
574
1031
  Write-Log "cleaning up ($reason)"
575
1032
  Remove-Item $reloadFile -Force -ErrorAction SilentlyContinue
576
- Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force
1033
+ # Own-profile CLIs only; another home's bridge keeps running (review A4-P2-1).
1034
+ (Get-OwnCli) | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
577
1035
  if (Test-Path $stateFile) {
578
1036
  # Give the GUI service its hook back: undo the park we did at start.
579
1037
  $state = Get-Content -Path $stateFile -Raw | ConvertFrom-Json
@@ -615,21 +1073,36 @@ export function posixToWindowsPath(value) {
615
1073
 
616
1074
  /** Write the watchdog script and return its WINDOWS path (it runs over there). */
617
1075
  export function writeWatchdogScript() {
618
- const script = windowsWatchdogScript({
619
- heartbeat: windowsPathOf(heartbeatPath()),
620
- // The canonical writer path: the watchdog's teardown reads exactly this file.
621
- stateFile: windowsPathOf(serviceStatePath()),
622
- logFile: windowsPathOf(windowsLogLocalPath()),
623
- stopRequest: windowsPathOf(stopRequestPath()),
624
- stoppedMarker: windowsPathOf(stoppedMarkerPath()),
625
- cliSpec: windowsPathOf(join(proxyHomeDir(), CLI_SPEC_FILENAME)),
626
- reloadRequest: windowsPathOf(reloadRequestPath()),
627
- reloadDone: windowsPathOf(reloadDonePath()),
628
- reloadFailed: windowsPathOf(reloadFailedPath()),
629
- })
1076
+ // The mutex must be shared by all watchdogs of ONE home (two different homes may
1077
+ // legitimately each run their own bridge): derive it from the heartbeat path.
1078
+ // Global\\ so two RDP sessions of the same user still see the same mutex (the
1079
+ // watchdog guards a machine-wide WinDivert handle, review B-P2-6). Single-user
1080
+ // machines keep the old semantics: one watchdog per home, second one exits.
1081
+ const mutexName = `Global\\dsh-ris-ide-proxybridge-watchdog-${createHash('sha1').update(heartbeatPath()).digest('hex').slice(0, 12)}`
1082
+ let script
1083
+ try {
1084
+ script = windowsWatchdogScript({
1085
+ mutexName,
1086
+ heartbeat: windowsPathOf(heartbeatPath(), { mustConvert: true }),
1087
+ // The canonical writer path: the watchdog's teardown reads exactly this file.
1088
+ stateFile: windowsPathOf(serviceStatePath(), { mustConvert: true }),
1089
+ logFile: windowsPathOf(windowsLogLocalPath(), { mustConvert: true }),
1090
+ stopRequest: windowsPathOf(stopRequestPath(), { mustConvert: true }),
1091
+ stoppedMarker: windowsPathOf(stoppedMarkerPath(), { mustConvert: true }),
1092
+ cliSpec: windowsPathOf(join(proxyHomeDir(), CLI_SPEC_FILENAME), { mustConvert: true }),
1093
+ profile: windowsPathOf(redirectorProfilePath(), { mustConvert: true }),
1094
+ reloadRequest: windowsPathOf(reloadRequestPath(), { mustConvert: true }),
1095
+ reloadDone: windowsPathOf(reloadDonePath(), { mustConvert: true }),
1096
+ reloadFailed: windowsPathOf(reloadFailedPath(), { mustConvert: true }),
1097
+ })
1098
+ } catch (error) {
1099
+ // A Linux spelling passed to powershell -File fails silently; surfacing it here
1100
+ // lets startRedirector answer with a real reason instead of "started" (B-P2-12).
1101
+ throw new Error(`无法把看门狗脚本的路径转换为 Windows 形式:${error?.message ?? error}`)
1102
+ }
630
1103
  mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
631
1104
  writeFileSync(watchdogScriptPath(), script, { mode: 0o600 })
632
- return windowsPathOf(watchdogScriptPath())
1105
+ return windowsPathOf(watchdogScriptPath(), { mustConvert: true })
633
1106
  }
634
1107
 
635
1108
  export async function startRedirector(options = {}) {
@@ -638,15 +1111,32 @@ export async function startRedirector(options = {}) {
638
1111
  // useless, and "no ProxyBridge" is a much better answer than "no rules".
639
1112
  const found = findRedirector({ side })
640
1113
  if (found.found !== true) {
641
- return { started: false, side, command: '', reason: side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge' }
1114
+ // A missing download is not "no rules": say what to install and where.
1115
+ return { started: false, side, command: '', reason: found.reason ?? (side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge'), missingBundle: found.missingBundle === true }
642
1116
  }
643
1117
  const profile = writeRedirectorProfile(readProxyConfig(''), { path: options.profilePath })
644
1118
  const plan = redirectorCommand({ cliPath: found.path, profilePath: profile.path, verbose: options.verbose, platform: side === 'windows' ? 'win32' : 'linux' })
1119
+ // Serialise detect-then-spawn across processes (daemon vs plugin fallback): two
1120
+ // concurrent starters used to create two engines / two elevated helpers (m11773).
1121
+ const lock = await acquireStartLock(side, { timeoutMs: options.lockTimeoutMs })
1122
+ if (lock.ok !== true) return { started: false, side, command: plan.display, reason: lock.reason ?? '另一个进程正在启动桥接' }
1123
+ try {
645
1124
  const running = detectRunningRedirector()
646
1125
  // Per side: the other side's process must not make this start look redundant.
647
1126
  const sameSide = IS_WINDOWS === true ? running.windows : side === 'windows' ? running.windows : running.local
648
1127
  if (sameSide.pid > 0) {
649
- if (side !== 'windows' || IS_WINDOWS === true) return { started: false, side, pid: sameSide.pid, command: plan.display, reason: '已在运行(先停止)' }
1128
+ if (side !== 'windows' || IS_WINDOWS === true) {
1129
+ // Local side: a lost pid file used to hide duplicates forever. Reap every
1130
+ // extra engine so "already running" also means "exactly one is running".
1131
+ let reaped = 0
1132
+ if (side === 'local') {
1133
+ for (const pid of localRedirectorOwnPids()) {
1134
+ if (pid === sameSide.pid) continue
1135
+ try { process.kill(pid, 'SIGTERM'); reaped += 1 } catch { /* already gone */ }
1136
+ }
1137
+ }
1138
+ return { started: false, side, pid: sameSide.pid, command: plan.display, reason: '已在运行(先停止)', reaped }
1139
+ }
650
1140
  // Windows: the engine may be a hand-started CLI, or one whose pid file we lost.
651
1141
  // It still holds the hook, so take it over instead of refusing to start.
652
1142
  const killed = await killWindowsCliProcesses()
@@ -657,26 +1147,56 @@ export async function startRedirector(options = {}) {
657
1147
  }
658
1148
  if (side === 'windows') {
659
1149
  // PowerShell resolves paths as WINDOWS does: /mnt/d/… is invisible there, and the
660
- // profile we just wrote lives in the Linux home. Both have to be translated.
661
- const exePath = windowsPathOf(found.path)
662
- const winArgs = windowsArgsOf(plan.args)
663
- const winLog = windowsPathOf(windowsLogPath())
664
- // Fresh start: no stale stop request may remain, and the heartbeat has to exist
665
- // BEFORE the watchdog looks at it (a missing file counts as stale).
666
- clearStopSignals()
667
- clearReloadSignals()
668
- writeHeartbeat()
669
- const watchdogScript = writeWatchdogScript()
1150
+ // profile we just wrote lives in the Linux home. Both have to be translated —
1151
+ // and a failure must be reported, not papered over with a Linux path that
1152
+ // PowerShell cannot open (review B-P2-12).
1153
+ let exePath = ''
1154
+ let winArgs = []
1155
+ let winLog = ''
1156
+ let ownProfile = ''
1157
+ let watchdogScript = ''
1158
+ let startTypeHint = ''
1159
+ try {
1160
+ exePath = windowsPathOf(found.path, { mustConvert: true })
1161
+ winArgs = windowsArgsOf(plan.args, { mustConvert: true })
1162
+ winLog = windowsPathOf(windowsLogPath())
1163
+ ownProfile = windowsPathOf(profile.path, { mustConvert: true })
1164
+ startTypeHint = windowsPathOf(startTypeHintPath(), { mustConvert: true })
1165
+ // Fresh start: no stale stop request may remain, and the heartbeat has to exist
1166
+ // BEFORE the watchdog looks at it (a missing file counts as stale).
1167
+ clearStopSignals()
1168
+ clearReloadSignals()
1169
+ writeHeartbeat()
1170
+ watchdogScript = writeWatchdogScript()
1171
+ } catch (error) {
1172
+ return { started: false, side, command: plan.display, reason: error?.message ?? '无法把启动路径转换为 Windows 形式' }
1173
+ }
670
1174
  const quote = (value) => `'${String(value).replace(/'/g, "''")}'`
1175
+ // Global\: the mutexes guard machine-wide resources (the WinDivert handle and the
1176
+ // one watchdog), so two RDP sessions of the same user must not each take "the"
1177
+ // mutex — the per-home sha suffix keeps separate proxy homes independent.
1178
+ // Global\\ for the same reason as the watchdog mutex: a start in another RDP
1179
+ // session races for the same machine-wide WinDivert handle (single-user boxes
1180
+ // are unaffected).
1181
+ const startMutexName = `Global\\dsh-ris-ide-proxybridge-start-${createHash('sha1').update(join(proxyHomeDir(), 'locks')).digest('hex').slice(0, 12)}`
671
1182
  // One elevated helper does the whole dance: the GUI's service and the CLI both
672
1183
  // want the WinDivert handle (mutually exclusive), a stale CLI has to go, and only
673
1184
  // an already-elevated process may redirect the CLI's output (-Verb RunAs cannot
674
1185
  // redirect). So: stop service → kill stale CLI → start CLI with logs → report.
675
1186
  const script = [
1187
+ // One start at a time across processes (m11773): two elevated helpers racing
1188
+ // each stop the "other" CLI and start their own, ending with two CLIs alive.
1189
+ `$startMutex = New-Object System.Threading.Mutex($false, ${quote(startMutexName)})`,
1190
+ "if (-not $startMutex.WaitOne(30000)) { 'start-busy=True;done=1'; return }",
676
1191
  '$svcWas = $false',
1192
+ `$startTypeHint = ${quote(startTypeHint)}`,
1193
+ // Leave the original service start type behind for the JS side: if the CLI dies
1194
+ // before the report is parsed, the caller still has to put the service back
1195
+ // instead of leaving the machine "stopped + Manual" (review B-P1-3).
677
1196
  '$svc = Get-Service ProxyBridgeSvc -ErrorAction SilentlyContinue',
678
1197
  '$startType = $null',
679
1198
  "if ($svc -ne $null) { $startType = $svc.StartType.ToString() }",
1199
+ 'if ($startType -ne $null) { Set-Content -Path $startTypeHint -Value $startType -Encoding ascii -ErrorAction SilentlyContinue }',
680
1200
  "if ($svc -ne $null -and $svc.Status -eq 'Running') { Stop-Service ProxyBridgeSvc -Force -ErrorAction SilentlyContinue; $svcWas = $true; Start-Sleep -Milliseconds 900 }",
681
1201
  // Only one process may own the WinDivert handle: if the service survived the
682
1202
  // stop it will keep intercepting while our CLI silently captures nothing.
@@ -685,35 +1205,76 @@ export async function startRedirector(options = {}) {
685
1205
  // WinDivert handle: our CLI then runs without capturing anything (rules load,
686
1206
  // no [CONN] lines) while every connection fails. Park it on Manual instead.
687
1207
  "if ($svc -ne $null -and $startType -eq 'Automatic') { Set-Service ProxyBridgeSvc -StartupType Manual -ErrorAction SilentlyContinue; $parked = $true }",
688
- 'Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue',
689
- 'Start-Sleep -Milliseconds 500',
1208
+ // Only CLIs of THIS home are in our way: another dsh-ris-ide home (or a user's
1209
+ // own ProxyBridge) may run its own bridge with its own profile, and killing it
1210
+ // would take down that bridge instead of ours (review A4-P2-1/B-P1-4).
1211
+ `$ownProfile = ${quote(ownProfile)}`,
1212
+ '$ownCim = @(Get-CimInstance Win32_Process -Filter "Name=\'ProxyBridge_CLI.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })',
1213
+ 'if ($ownCim.Count -gt 0) { $ownCim | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 500 }',
690
1214
  `$log = ${quote(winLog)}`,
691
1215
  'if (Test-Path $log) { Remove-Item $log -Force -ErrorAction SilentlyContinue }',
692
1216
  `$argList = @(${winArgs.map(quote).join(',')})`,
693
1217
  `$p = Start-Process -FilePath ${quote(exePath)} -ArgumentList $argList -PassThru -WindowStyle Hidden -RedirectStandardOutput $log -RedirectStandardError ($log + '.err')`,
694
1218
  'Start-Sleep -Milliseconds 2000',
695
1219
  '$alive = [bool](Get-Process -Id $p.Id -ErrorAction SilentlyContinue)',
696
- // Two CLIs would both try to bind WinDivert: keep ours, drop anything else
697
- // (a leftover from an earlier session, or one the IDE started meanwhile).
698
- '$all = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue)',
1220
+ // Two CLIs would both try to bind WinDivert: keep ours, drop anything else that
1221
+ // carries THIS home's profile (a leftover from an earlier session, or one the
1222
+ // IDE started meanwhile). Other homes' CLIs are out of scope.
1223
+ '$all = @(Get-CimInstance Win32_Process -Filter "Name=\'ProxyBridge_CLI.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })',
699
1224
  '$dups = $all.Count - 1',
700
- 'if ($dups -gt 0) { $all | Where-Object { $_.Id -ne $p.Id } | Stop-Process -Force -ErrorAction SilentlyContinue; Start-Sleep -Milliseconds 500 }',
701
- '$final = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue).Count',
1225
+ 'if ($dups -gt 0) { $all | Where-Object { $_.ProcessId -ne $p.Id } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 500 }',
1226
+ '$final = @(Get-CimInstance Win32_Process -Filter "Name=\'ProxyBridge_CLI.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count',
702
1227
  // Killing an elevated CLI and restarting the service need admin, which we only
703
1228
  // have inside this script: spawn the watchdog here so teardown never asks for
704
1229
  // a second UAC (it ends on a stop request or when the heartbeat goes stale).
1230
+ // One watchdog per machine (m11702): a previous start left one behind, and on
1231
+ // the next reload/stale heartbeat it starts a SECOND CLI. Kill the leftovers
1232
+ // in the same elevated context that creates the new one — but only those that
1233
+ // run THIS home's watchdog script (another home has its own, per-home mutex;
1234
+ // review B-P2-4).
1235
+ `$wdScript = ${quote(watchdogScript)}`,
1236
+ '$oldWatchdogs = @(Get-CimInstance Win32_Process -Filter "Name=\'powershell.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($wdScript, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })',
1237
+ 'if ($oldWatchdogs.Count -gt 0) { $oldWatchdogs | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 300 }',
705
1238
  `$wd = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File', ${quote(watchdogScript)}) -PassThru -WindowStyle Hidden`,
706
1239
  'Start-Sleep -Milliseconds 400',
707
- '"pid=$($p.Id);svc=$svcWas;startType=$startType;parked=$([bool]$parked);alive=$alive;dups=$dups;count=$final;watchdog=$($wd.Id);done=1"',
1240
+ // Only a fully successful start removes the hint; a failed one leaves it for
1241
+ // the caller to restore the service (review B-P1-3).
1242
+ 'if ($alive -eq $true) { Remove-Item $startTypeHint -Force -ErrorAction SilentlyContinue }',
1243
+ '"pid=$($p.Id);svc=$svcWas;startType=$startType;parked=$([bool]$parked);alive=$alive;dups=$dups;count=$final;own=$($all.Count);watchdog=$($wd.Id);oldWatchdogs=$($oldWatchdogs.Count);done=1"',
708
1244
  ].join('; ')
709
- const elevated = await psElevated(script, 45000)
1245
+ // Waiting for the UAC prompt is exactly the window in which the old watchdog
1246
+ // judges our heartbeat stale and tears the bridge down. Keep beating while the
1247
+ // launcher blocks (it may take seconds), so a slow UAC is not a bridge outage
1248
+ // (review B-P0-1).
1249
+ const beat = setInterval(() => { try { writeHeartbeat() } catch {} }, 3000)
1250
+ beat.unref?.()
1251
+ let elevated
1252
+ try {
1253
+ elevated = await psElevated(script, 45000)
1254
+ } finally {
1255
+ clearInterval(beat)
1256
+ }
710
1257
  // B1: no report for THIS run means the start did not happen — never parse the
711
1258
  // previous run's leftover output (it looked like success with a dead pid).
712
1259
  if (elevated.ok !== true) {
1260
+ // The helper may still have stopped the service before it failed; the hint
1261
+ // file (if any) tells recoverWindowsService() what to restore.
1262
+ recoverWindowsService()
713
1263
  return { started: false, side, command: plan.display, reason: elevated.reason }
714
1264
  }
715
1265
  const output = elevated.output
1266
+ // A concurrent start (another window, or the daemon while the plugin fell back)
1267
+ // means the elevated helper could not take the start mutex: report it instead of
1268
+ // pretending a second CLI is fine (m11773). Must be checked BEFORE the pid parse:
1269
+ // this report carries no pid, so the old order always answered with the generic
1270
+ // "未能启动(…)" (review B-P2-1).
1271
+ if (/start-busy=True/.test(output)) {
1272
+ return { started: false, side, command: plan.display, reason: '另一个进程正在启动 Windows 侧拦截,请稍后再试' }
1273
+ }
716
1274
  if (/svcRunning=True/.test(output)) {
1275
+ // The service was already stopped (and maybe parked) by the script; restore it
1276
+ // instead of leaving the machine with a dead service (review B-P1-3).
1277
+ recoverWindowsService()
717
1278
  return {
718
1279
  started: false,
719
1280
  side,
@@ -723,6 +1284,7 @@ export async function startRedirector(options = {}) {
723
1284
  }
724
1285
  const pid = Number.parseInt((output.match(/pid=(\d+)/) ?? [])[1] ?? '', 10)
725
1286
  if (Number.isInteger(pid) === false || pid <= 0) {
1287
+ recoverWindowsService()
726
1288
  return {
727
1289
  started: false,
728
1290
  side,
@@ -756,6 +1318,7 @@ export async function startRedirector(options = {}) {
756
1318
  const alive = /alive=True/i.test(output)
757
1319
  if (alive !== true) {
758
1320
  clearRedirectorPid('windows')
1321
+ recoverWindowsService()
759
1322
  const log = `${readTail(windowsLogLocalPath(), 4096)}\n${readTail(`${windowsLogLocalPath()}.err`, 2048)}`.trim()
760
1323
  return {
761
1324
  started: false,
@@ -765,6 +1328,7 @@ export async function startRedirector(options = {}) {
765
1328
  reason: `启动后退出(${log.split('\n').filter((line) => line.trim() !== '').slice(-3).join(' / ').slice(0, 240) || '日志为空'})`,
766
1329
  }
767
1330
  }
1331
+ clearStartTypeHint()
768
1332
  return {
769
1333
  started: true,
770
1334
  pid,
@@ -786,10 +1350,454 @@ export async function startRedirector(options = {}) {
786
1350
  if (probe.status === 0) {
787
1351
  const child = spawn('sudo', ['-n', found.path, ...plan.args], { detached: true, stdio: 'ignore' })
788
1352
  child.unref()
789
- writeRedirectorPid(child.pid, 'local')
790
- return { started: true, pid: child.pid, side, command: plan.display }
1353
+ // `sudo` is a supervisor, not the CLI: recording its pid made a later stop kill
1354
+ // the supervisor and report success while the root CLI kept the eBPF hook — the
1355
+ // same trap as pkexec (review B-P1-2). Adopt the real CLI once it appears.
1356
+ const cliPid = await waitForOwnLocalPid({ timeoutMs: options.sudoWaitMs ?? SUDO_CLI_WAIT_MS })
1357
+ const pid = cliPid > 0 ? cliPid : child.pid
1358
+ writeRedirectorPid(pid, 'local')
1359
+ return { started: true, pid, side, command: plan.display, method: 'sudo', askerPid: child.pid }
1360
+ }
1361
+ // Only a user-initiated start may raise an interactive prompt (review B-P0-2): the
1362
+ // reconciler runs every minute, so pkexec/terminal here would pop a polkit dialog
1363
+ // or a whole terminal window per minute on a box where sudo -n is unavailable.
1364
+ // Background starts stop at the `manual` answer below.
1365
+ if (options.interactive !== true) {
1366
+ return { started: false, side, command: plan.display, method: 'manual', reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1367
+ }
1368
+ // 「提权启动」: when sudo is not passwordless, pkexec can still ask through the
1369
+ // desktop's polkit agent (WSLg only — a plain WSL has no agent and exits at once).
1370
+ // It must run detached: the dialog belongs to the agent, and the daemon must not
1371
+ // hold a pipe that would keep the (root) child waiting.
1372
+ if (pkexecAvailable() === true) {
1373
+ const child = spawn('pkexec', [found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1374
+ child.unref()
1375
+ // `pkexec` is only the asker: it forks the elevated CLI and waits for it. Writing
1376
+ // the asker's pid made a later "stop" kill pkexec and report success while the
1377
+ // root CLI kept the hook (review B-P1-2). The CLI is identified by THIS home's
1378
+ // profile path, so a password delay does not turn into a false "already dead".
1379
+ const cliPid = await waitForOwnLocalPid({ timeoutMs: options.pkexecWaitMs })
1380
+ if (cliPid > 0) {
1381
+ writeRedirectorPid(cliPid, 'local')
1382
+ return { started: true, pid: cliPid, side, command: plan.display, method: 'pkexec', askerPid: child.pid }
1383
+ }
1384
+ if (await pidAliveAfter(child.pid, PKEXEC_GRACE_MS) === true) {
1385
+ // The dialog is waiting for a password; the CLI does not exist yet. Do not
1386
+ // write a pid we cannot verify, and do not claim a successful start.
1387
+ return {
1388
+ started: false,
1389
+ side,
1390
+ command: plan.display,
1391
+ method: 'pkexec',
1392
+ deferred: true,
1393
+ reason: '已请求提权:在密码对话框里完成授权后系统层拦截就会启动(如果对话框还开着)',
1394
+ }
1395
+ }
1396
+ return {
1397
+ started: false,
1398
+ side,
1399
+ command: plan.display,
1400
+ method: 'pkexec',
1401
+ reason: '提权窗口没有完成(这台机器可能没有图形认证代理):请在终端里执行上面的命令,或给 sudo 配置免密',
1402
+ }
1403
+ }
1404
+ // A desktop terminal can take the password for us: open one in which the CLI
1405
+ // starts as root, then report that we are waiting. That beats a dead pkexec on a
1406
+ // WSL box without a polkit agent, and the window is the user's to watch (m12782).
1407
+ const opened = await openElevatedTerminal(plan.display, side, { argv: [found.path, ...plan.args] })
1408
+ if (opened === true) {
1409
+ return {
1410
+ started: false,
1411
+ side,
1412
+ command: plan.display,
1413
+ method: 'terminal',
1414
+ deferred: true,
1415
+ reason: '已打开终端窗口:输入 sudo 密码后系统层拦截就会启动(这个窗口可以关闭)',
1416
+ }
1417
+ }
1418
+ return { started: false, side, command: plan.display, method: 'manual', reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1419
+ } finally {
1420
+ lock.release()
1421
+ }
1422
+ }
1423
+
1424
+ /** How long a detached pkexec ask may take before we call it failed (ms). */
1425
+ const PKEXEC_GRACE_MS = 2500
1426
+
1427
+ /**
1428
+ * How long to wait for the real CLI after spawning pkexec (ms).
1429
+ *
1430
+ * The password is typed by a human, so the CLI appears well after `spawn` returns;
1431
+ * recording the asker instead was the bug (review B-P1-2). If the CLI does not show
1432
+ * up in this window we report "deferred", never a fake success.
1433
+ */
1434
+ const PKEXEC_CLI_WAIT_MS = 8000
1435
+ /** Same adoption budget for `sudo -n`, where no password dialog is involved. */
1436
+ const SUDO_CLI_WAIT_MS = 3000
1437
+
1438
+ /**
1439
+ * Wait for our own local CLI to appear (matched by this home's profile path).
1440
+ * @param {{timeoutMs?: number}} [options] - override for tests.
1441
+ * @returns {Promise<number>} the CLI pid, or 0 when it never showed up.
1442
+ */
1443
+ async function waitForOwnLocalPid(options = {}) {
1444
+ const timeoutMs = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : PKEXEC_CLI_WAIT_MS
1445
+ const deadline = Date.now() + timeoutMs
1446
+ for (;;) {
1447
+ const pids = localRedirectorOwnPids()
1448
+ if (pids.length > 0) return pids[0]
1449
+ if (Date.now() >= deadline) return 0
1450
+ await sleepAsync(200)
1451
+ }
1452
+ }
1453
+
1454
+ /** Terminal emulators we know how to open a privileged command in (m12782). */
1455
+ const TERMINAL_CANDIDATES = [
1456
+ // Windows Terminal treats its first non-option token as the command line; a
1457
+ // leading `-e` is a WT option and shows its own usage error (m12840).
1458
+ // `--size` keeps the window small; `-f` (focus mode) maximizes it, so it is not
1459
+ // used anymore (m13083: the window is raised by focusWindowsTerminal instead).
1460
+ // Old WT builds reject unknown options the way they rejected `-e`, so the flags
1461
+ // only go in when the installed version is known to support them.
1462
+ // `--title` gives the window a stable name so the centering helper can find
1463
+ // exactly this window (WT hosts every window in one process, m13221).
1464
+ { bin: 'wt.exe', args: ['--size', '64,16', 'wsl.exe', '-e', 'bash', '-lc'], guardedFlags: 2 },
1465
+ { bin: 'x-terminal-emulator', args: ['-e', 'bash', '-lc'] },
1466
+ { bin: 'gnome-terminal', args: ['--', 'bash', '-lc'] },
1467
+ { bin: 'konsole', args: ['-e', 'bash', '-lc'] },
1468
+ { bin: 'xfce4-terminal', args: ['-x', 'bash', '-lc'] },
1469
+ { bin: 'mate-terminal', args: ['-e', 'bash', '-lc'] },
1470
+ { bin: 'xterm', args: ['-e', 'bash', '-lc'] },
1471
+ ]
1472
+
1473
+ /**
1474
+ * Whether a desktop session can show a terminal window. A headless box may still
1475
+ * have `xterm` on PATH, but spawning it only blocks/ fails — better to skip and
1476
+ * report the command than to claim a window was opened (m12884).
1477
+ * @returns {boolean} true with DISPLAY/WAYLAND_DISPLAY or an X11/Wayland session.
1478
+ */
1479
+ function hasGraphicalSession() {
1480
+ const type = String(process.env.XDG_SESSION_TYPE ?? '').toLowerCase()
1481
+ return Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY || type === 'x11' || type === 'wayland')
1482
+ }
1483
+
1484
+ /** Cached answer to "can this Windows Terminal take --focus?" (m12923). */
1485
+ let wtFocusCache = null
1486
+ /**
1487
+ * Read the installed Windows Terminal version once. `--focus` exists since 1.15,
1488
+ * and an unknown option makes WT show its own error window, so we only pass it
1489
+ * when we are sure (m12840 is the same failure mode with `-e`).
1490
+ * @returns {boolean} whether the host Windows Terminal understands --focus.
1491
+ */
1492
+ function wtSupportsFocus() {
1493
+ if (wtFocusCache !== null) return wtFocusCache
1494
+ try {
1495
+ const probe = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
1496
+ '(Get-AppxPackage Microsoft.WindowsTerminal).Version'], { encoding: 'utf8', timeout: 8000 })
1497
+ const match = /^(\d+)\.(\d+)/.exec(String(probe.stdout || '').trim())
1498
+ // `-f` (focus) and `--size` are safe from 1.15 on; older builds only get the
1499
+ // bare command line.
1500
+ wtFocusCache = match === null ? false : (Number(match[1]) > 1 || Number(match[2]) >= 15)
1501
+ } catch {
1502
+ wtFocusCache = false
1503
+ }
1504
+ return wtFocusCache
1505
+ }
1506
+
1507
+ /** The helper's state file lives this long at most; an old one is not "still open". */
1508
+ const ELEVATION_STATE_TTL_MS = 10 * 60 * 1000
1509
+
1510
+ /**
1511
+ * Canonical side name for the elevation helper: it only knows `local`/`windows`.
1512
+ * `linux` is the name the maintenance page uses for this side, so callers that pass
1513
+ * it must still find the file the helper wrote.
1514
+ * @param {string} side - any caller spelling.
1515
+ * @returns {'local'|'windows'|null} canonical side, or null for unknown input.
1516
+ */
1517
+ function normalizeElevationSide(side) {
1518
+ const text = String(side ?? '').toLowerCase()
1519
+ if (text === 'windows') return 'windows'
1520
+ if (text === '' || text === 'local' || text === 'linux') return 'local'
1521
+ return null
1522
+ }
1523
+
1524
+ /**
1525
+ * Whether the elevated-terminal window for a side is still open. The helper script
1526
+ * writes `<proxy home>/proxybridge/elevate-<side>.json` on start and removes it on
1527
+ * exit, which is exactly the lifetime of the window (m12923).
1528
+ *
1529
+ * A caller that has the proxy home (the daemon does) passes it as `home`; the state
1530
+ * file lives one level down, in `proxybridge/` (review B-P1-1 — reading
1531
+ * `<proxy home>/elevate-*.json` never found what the writer wrote).
1532
+ *
1533
+ * CONTRACT: `options.home` is the PROXY HOME (e.g. `proxyHomeDir()`), and this
1534
+ * function appends `proxybridge/` itself; the daemon does exactly that. Passing
1535
+ * `redirectorHome()` here would double the directory and the window would read as
1536
+ * closed — test/redirector.test.mjs pins this down.
1537
+ * @param {string} side 'linux' | 'windows' | 'local'.
1538
+ * @param {{home?: string}} [options] Proxy home override (tests).
1539
+ * @returns {{active: boolean, at?: string, pid?: number}} state.
1540
+ */
1541
+ export function readElevationState(side, options = {}) {
1542
+ const normalized = normalizeElevationSide(side)
1543
+ if (normalized === null) return { active: false }
1544
+ const base = options.home === undefined ? redirectorHome() : join(options.home, REDIRECTOR_DIRNAME)
1545
+ const path = join(base, 'elevate-' + normalized + '.json')
1546
+ try {
1547
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
1548
+ // A leftover file whose timestamp is old is not a window the user is looking at
1549
+ // (the helper normally removes it; a SIGKILL leaves it behind).
1550
+ const at = Date.parse(String(parsed.at ?? ''))
1551
+ if (Number.isFinite(at) === true && Date.now() - at > ELEVATION_STATE_TTL_MS) return { active: false }
1552
+ const pid = Number(parsed.pid)
1553
+ if (Number.isFinite(pid) && pid > 0) {
1554
+ try { process.kill(pid, 0) } catch (error) {
1555
+ if (error?.code !== 'EPERM') return { active: false }
1556
+ }
1557
+ }
1558
+ return { active: true, at: String(parsed.at ?? ''), pid: Number.isFinite(pid) ? pid : 0 }
1559
+ } catch {
1560
+ return { active: false }
1561
+ }
1562
+ }
1563
+
1564
+ /** @param {string} bin @returns {boolean} whether `bin` resolves on PATH. */
1565
+ function hasBinary(bin) {
1566
+ try {
1567
+ return spawnSync('sh', ['-lc', 'command -v ' + JSON.stringify(bin)], { encoding: 'utf8', timeout: 4000 }).status === 0
1568
+ } catch {
1569
+ return false
1570
+ }
1571
+ }
1572
+
1573
+ /**
1574
+ * The helper script a terminal window runs: it takes the sudo ticket in the
1575
+ * foreground (the window is the TTY), then detaches the CLI so closing the window
1576
+ * does not kill the interception (m12896). Split out so tests can check the text.
1577
+ * @param {string} command Display/executable command (`sudo /path/ProxyBridge …`).
1578
+ * @param {string} side Which side is being started (only names the script/log).
1579
+ * @param {{dir?: string, argv?: string[]}} [options] Directory override (tests use a
1580
+ * temp dir) and the exact argv when known.
1581
+ * @returns {{dir: string, scriptPath: string, logPath: string, body: string}} plan.
1582
+ */
1583
+ export function elevationScript(command, side, options = {}) {
1584
+ const normalizedSide = normalizeElevationSide(side) ?? 'local'
1585
+ const dir = options.dir ?? redirectorHome()
1586
+ const name = 'elevate-' + normalizedSide
1587
+ const scriptPath = join(dir, name + '.sh')
1588
+ const logPath = join(dir, name + '.log')
1589
+ const bare = String(command).replace(/^sudo\s+/, '')
1590
+ // An argv lets us quote every entry for bash; the display string came from a
1591
+ // path that a user (or DSH_RIS_IDE_PROXYBRIDGE) can choose, and pasting it raw
1592
+ // let a `"`/`$(…)` in a directory name break or inject into the detached line
1593
+ // (review B-P2-10).
1594
+ const detached = Array.isArray(options.argv) === true && options.argv.length > 0
1595
+ ? 'nohup sudo -n ' + options.argv.map(shellQuote).join(' ') + ' > "$LOG" 2>&1 &'
1596
+ : 'nohup sudo -n ' + bare + ' > "$LOG" 2>&1 &'
1597
+ // The CLI is the interceptor itself, so it must outlive the terminal: ask sudo
1598
+ // for a ticket in the foreground (that is where the password prompt belongs),
1599
+ // then start the CLI detached with `sudo -n` and close the window (m12896).
1600
+ const body = [
1601
+ '#!/bin/bash',
1602
+ '# generated by risd for 「提权启动」(m12782/m12896)',
1603
+ 'LOG=' + JSON.stringify(logPath),
1604
+ 'STATE=' + JSON.stringify(join(dir, name + '.json')),
1605
+ 'printf \'{"side":"%s","pid":%s,"at":"%s"}\\n\' ' + JSON.stringify(normalizedSide) + ' "$$" "$(date -Is)" > "$STATE"',
1606
+ 'trap \'rm -f "$STATE"\' EXIT',
1607
+ 'sudo -v || { echo; echo "没有拿到 sudo 授权,已取消。"; exit 1; }',
1608
+ detached,
1609
+ 'echo',
1610
+ 'echo "已在后台启动系统层拦截;日志:$LOG"',
1611
+ 'echo "这个窗口会自动关闭。"',
1612
+ 'sleep 1',
1613
+ '',
1614
+ ].join('\n')
1615
+ return { dir, scriptPath, logPath, body }
1616
+ }
1617
+
1618
+ /**
1619
+ * @param {string} command Display/executable command (`sudo /path/ProxyBridge …`).
1620
+ * @param {string} side Which side is being started (only names the script).
1621
+ * @param {{argv?: string[], verifyMs?: number}} [options] - exact argv for safe
1622
+ * quoting, and how long to wait for the helper's state file.
1623
+ * @returns {Promise<boolean>} true when a window actually started the helper.
1624
+ */
1625
+ async function openElevatedTerminal(command, side, options = {}) {
1626
+ // A test run must never pop a real terminal window (m13621): under `node --test`
1627
+ // the runner sets NODE_TEST_CONTEXT, and spawning here would leave a password
1628
+ // prompt on the developer's desktop for every suite run. Callers fall back to the
1629
+ // printed `manual` command, which is all a test can assert anyway.
1630
+ // DSH_RIS_IDE_ALLOW_TERMINAL=1 is the explicit opt-in for a manual check.
1631
+ if (process.env.NODE_TEST_CONTEXT !== undefined && process.env.DSH_RIS_IDE_ALLOW_TERMINAL !== '1') return false
1632
+ let script
1633
+ try {
1634
+ const plan = elevationScript(command, side, { argv: options.argv })
1635
+ mkdirSync(plan.dir, { recursive: true })
1636
+ writeFileSync(plan.scriptPath, plan.body, { mode: 0o755 })
1637
+ script = plan.scriptPath
1638
+ } catch {
1639
+ return false
1640
+ }
1641
+ let launched = false
1642
+ for (const candidate of TERMINAL_CANDIDATES) {
1643
+ // wt.exe is the WSL interop path (the Windows Terminal window belongs to the
1644
+ // host); the rest are X11/Wayland clients that need a session to attach to.
1645
+ if (candidate.bin !== 'wt.exe' && hasGraphicalSession() === false) continue
1646
+ if (hasBinary(candidate.bin) === false) continue
1647
+ const args = candidate.guardedFlags !== undefined && wtSupportsFocus() === false
1648
+ ? [...candidate.args.slice(candidate.guardedFlags), script]
1649
+ : [...candidate.args, script]
1650
+ try {
1651
+ if (candidate.bin === 'wt.exe') {
1652
+ // WT is launched by the helper itself, which then centers the new window.
1653
+ if (launchCenteredTerminal(args) === true) { launched = true; break }
1654
+ continue
1655
+ }
1656
+ const child = spawn(candidate.bin, args, { detached: true, stdio: 'ignore' })
1657
+ child.unref()
1658
+ launched = true
1659
+ break
1660
+ } catch { /* try the next one */ }
1661
+ }
1662
+ if (launched !== true) return false
1663
+ // A successful `spawn` is not a started window: ENOENT arrives as an async error,
1664
+ // and a broken wt.exe shim exits silently. The helper writes `<dir>/elevate-*.json`
1665
+ // as its first action, so that file is the proof (review B-P2-11).
1666
+ const stateSide = side === 'windows' ? 'windows' : 'local'
1667
+ const verifyMs = Number.isInteger(options.verifyMs) && options.verifyMs > 0 ? options.verifyMs : 4000
1668
+ for (let waited = 0; waited < verifyMs; waited += 100) {
1669
+ if (readElevationState(stateSide).active === true) return true
1670
+ await sleepAsync(100)
1671
+ }
1672
+ return false
1673
+ }
1674
+
1675
+ /**
1676
+ * Open Windows Terminal and center the window it creates (m13147/m13221/m13257).
1677
+ *
1678
+ * `wt.exe` has no "center me" flag, and Windows Terminal hosts every window in one
1679
+ * process, so neither `Get-Process WindowsTerminal` nor a window title can identify
1680
+ * *this* window reliably. The helper therefore launches `wt.exe` itself: it records
1681
+ * the CASCADIA windows that already exist, starts the terminal, then moves the one
1682
+ * new window to the middle of the work area.
1683
+ */
1684
+ const CENTER_TERMINAL_PS1 = [
1685
+ 'param([string]$ArgJson)',
1686
+ 'Add-Type -TypeDefinition @"',
1687
+ 'using System;',
1688
+ 'using System.Text;',
1689
+ 'using System.Collections.Generic;',
1690
+ 'using System.Runtime.InteropServices;',
1691
+ 'public class WinPos {',
1692
+ ' public delegate bool EnumProc(IntPtr h, IntPtr l);',
1693
+ ' [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }',
1694
+ ' [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);',
1695
+ ' [DllImport("user32.dll")] public static extern int GetClassName(IntPtr h, StringBuilder s, int n);',
1696
+ ' [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);',
1697
+ ' [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);',
1698
+ ' [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr h, int x, int y, int w, int ht, bool repaint);',
1699
+ ' [DllImport("user32.dll")] public static extern bool SystemParametersInfo(uint a, uint b, ref RECT r, uint f);',
1700
+ ' static List<IntPtr> Windows() {',
1701
+ ' var list = new List<IntPtr>();',
1702
+ ' EnumWindows((h, l) => {',
1703
+ ' if (!IsWindowVisible(h)) return true;',
1704
+ ' var c = new StringBuilder(256); GetClassName(h, c, 256);',
1705
+ ' if (c.ToString().IndexOf("CASCADIA", StringComparison.OrdinalIgnoreCase) >= 0) list.Add(h);',
1706
+ ' return true;',
1707
+ ' }, IntPtr.Zero);',
1708
+ ' return list;',
1709
+ ' }',
1710
+ ' public static string Handles() {',
1711
+ ' var parts = new List<string>();',
1712
+ ' foreach (var h in Windows()) parts.Add(h.ToString());',
1713
+ ' return string.Join(",", parts);',
1714
+ ' }',
1715
+ ' public static string CenterNew(string known) {',
1716
+ " var old = new HashSet<string>((known ?? \"\").Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries));",
1717
+ ' foreach (var h in Windows()) {',
1718
+ ' if (old.Contains(h.ToString())) continue;',
1719
+ ' var r = new RECT(); if (!GetWindowRect(h, out r)) continue;',
1720
+ ' int w = r.Right - r.Left, ht = r.Bottom - r.Top;',
1721
+ ' if (w <= 0 || ht <= 0) continue;',
1722
+ ' var wa = new RECT(); SystemParametersInfo(0x0030, 0, ref wa, 0);',
1723
+ ' int x = wa.Left + (wa.Right - wa.Left - w) / 2;',
1724
+ ' int y = wa.Top + (wa.Bottom - wa.Top - ht) / 2;',
1725
+ ' MoveWindow(h, x, y, w, ht, true);',
1726
+ ' return "moved " + h;',
1727
+ ' }',
1728
+ ' return "none";',
1729
+ ' }',
1730
+ '}',
1731
+ '"@',
1732
+ '$before = [WinPos]::Handles()',
1733
+ '$argv = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ArgJson)) | ConvertFrom-Json',
1734
+ "$cmd = ($argv | ForEach-Object { if ($_ -match '\\s') { '\"' + $_ + '\"' } else { $_ } }) -join ' '",
1735
+ "Start-Process -FilePath 'wt.exe' -ArgumentList $cmd | Out-Null",
1736
+ "$result = 'none'",
1737
+ "for ($i = 0; $i -lt 25 -and $result -eq 'none'; $i++) {",
1738
+ ' Start-Sleep -Milliseconds 200',
1739
+ ' $result = [WinPos]::CenterNew($before)',
1740
+ '}',
1741
+ ].join('\n')
1742
+
1743
+ /**
1744
+ * Launch Windows Terminal through the centering helper. Every argument crosses the
1745
+ * WSL boundary base64-encoded so quoting can never split the script path.
1746
+ * @param {string[]} argv Arguments for `wt.exe` (flags included).
1747
+ * @returns {boolean} true when the helper was spawned.
1748
+ */
1749
+ function launchCenteredTerminal(argv) {
1750
+ try {
1751
+ const scriptPath = join(redirectorHome(), 'center-terminal.ps1')
1752
+ writeFileSync(scriptPath, `${CENTER_TERMINAL_PS1}\n`, { mode: 0o600 })
1753
+ const argJson = Buffer.from(JSON.stringify(argv), 'utf8').toString('base64')
1754
+ // `windowsPathOf` (unlike posixToWindowsPath) turns a WSL home into the
1755
+ // \\wsl.localhost share that Windows PowerShell can actually open; passing a
1756
+ // bare /home/... path made `-File` fail silently and no window appeared (m13375).
1757
+ // It must be a real Windows path: falling back to the Linux spelling only hides
1758
+ // that failure (review B-P2-12).
1759
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
1760
+ '-WindowStyle', 'Hidden', '-File', windowsPathOf(scriptPath, { mustConvert: true }), '-ArgJson', argJson], { detached: true, stdio: 'ignore', windowsHide: true })
1761
+ child.unref()
1762
+ return true
1763
+ } catch {
1764
+ return false
791
1765
  }
792
- return { started: false, side, command: plan.display, reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1766
+ }
1767
+
1768
+ /** Whether a polkit agent can be asked at all (m12606: 提权启动 button). *//** Whether a polkit agent can be asked at all (m12606: 提权启动 button). *//** Whether a polkit agent can be asked at all (m12606: 提权启动 button). */
1769
+ let pkexecCache = null
1770
+ /**
1771
+ * @returns {boolean} true when `pkexec` exists on PATH.
1772
+ */
1773
+ function pkexecAvailable() {
1774
+ if (pkexecCache !== null) return pkexecCache
1775
+ try {
1776
+ const probe = spawnSync('pkexec', ['--version'], { encoding: 'utf8', timeout: 4000, windowsHide: true })
1777
+ pkexecCache = probe.error === undefined && probe.status === 0
1778
+ } catch {
1779
+ pkexecCache = false
1780
+ }
1781
+ return pkexecCache
1782
+ }
1783
+
1784
+ /**
1785
+ * Wait briefly and report whether a detached child is still there, which is how we
1786
+ * tell "pkexec is showing its dialog / started the CLI" from "it bailed out".
1787
+ * @param {number} pid Child pid.
1788
+ * @param {number} ms How long to watch.
1789
+ * @returns {Promise<boolean>} true when the process is still alive at the end.
1790
+ */
1791
+ async function pidAliveAfter(pid, ms) {
1792
+ const deadline = Date.now() + ms
1793
+ while (Date.now() < deadline) {
1794
+ await new Promise((resolve) => setTimeout(resolve, 100))
1795
+ try { process.kill(pid, 0); return true } catch (error) {
1796
+ if (error?.code === 'EPERM') return true
1797
+ return false
1798
+ }
1799
+ }
1800
+ return true
793
1801
  }
794
1802
 
795
1803
  /** Where the vendored distribution for a platform lives (machine-wide, shared). */
@@ -798,24 +1806,69 @@ export function redirectorVendorDir(options = {}) {
798
1806
  return join(redirectorHome(), 'vendor', platform === 'win32' ? 'windows' : 'linux')
799
1807
  }
800
1808
 
1809
+ let warnedBundleUnavailable = false
801
1810
  /**
802
1811
  * Find a usable CLI for one side.
803
1812
  *
804
1813
  * `side` names the network stack that gets hooked, not the platform this process
805
1814
  * 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.
1815
+ *
1816
+ * Before a Windows-side lookup, the cached distribution is materialised under
1817
+ * `%LOCALAPPDATA%` (unless the caller pinned `platform`, the test-only override).
1818
+ * Nothing is downloaded here — the maintenance page owns that — so a missing
1819
+ * distribution is reported through `missingBundle`/`reason`, never as silence.
1820
+ * @param {{side?: 'local'|'windows', platform?: string, targetDir?: string, bundleDir?: string}} [options] - overrides for tests.
1821
+ * @returns {{found: boolean, path: string, kind: string, candidates: string[], bundleDir: string, missingBundle: boolean, reason?: string}} the first hit plus the bundle diagnosis.
808
1822
  */
809
1823
  export function findRedirector(options = {}) {
810
1824
  const platform = options.platform ?? process.platform
811
1825
  const side = options.side === 'windows' ? 'windows' : 'local'
812
- const candidates = redirectorCandidates({ platform, side, wsl: options.wsl })
1826
+ let bundleDir = options.bundleDir
1827
+ const needsWindowsBundle = platform === 'win32' || side === 'windows'
1828
+ const installed = bundleIsInstalled(bundledBundleDir())
1829
+ const missingBundle = installed !== true
1830
+ if (bundleDir === undefined && options.platform === undefined && needsWindowsBundle) {
1831
+ try {
1832
+ const prepared = options.targetDir === undefined ? prepareWindowsBundle() : prepareWindowsBundle({ targetDir: options.targetDir })
1833
+ if (typeof prepared === 'string' && prepared !== '') bundleDir = prepared
1834
+ else if (prepared === '' && missingBundle !== true && warnedBundleUnavailable !== true) {
1835
+ // Downloaded, but the Windows copy could not be made. Two very different
1836
+ // causes used to share one misleading line (m11624): %LOCALAPPDATA% unknown
1837
+ // (no cmd.exe interop) vs a copy that failed (usually EACCES because the
1838
+ // running ProxyBridgeSvc holds the DLLs).
1839
+ warnedBundleUnavailable = true
1840
+ const diagnosis = windowsBundleDiagnosis()
1841
+ if (diagnosis === null) {
1842
+ console.error('[dsh-ris-ide] 无法确定 %LOCALAPPDATA%:Windows 侧代理桥将直接使用下载缓存里的路径。')
1843
+ } else {
1844
+ // Only "the target is in use/busy" deserves the "stop the interception"
1845
+ // advice; ENOENT/EISDIR mean the copy itself is impossible (a bad bundle
1846
+ // or an unwritable %LOCALAPPDATA%), and telling people to stop a service
1847
+ // that is not running wastes their time.
1848
+ const busy = ['EBUSY', 'EPERM', 'EACCES', 'EEXIST'].includes(diagnosis.code)
1849
+ console.error(`[dsh-ris-ide] 复制 Windows 版 ProxyBridge 失败(${diagnosis.code}${diagnosis.file === '' ? '' : ':' + diagnosis.file}):${busy ? '目标文件可能正被运行中的系统层拦截占用,请先停掉系统层拦截再重启 dsh。' : '请检查下载缓存与 %LOCALAPPDATA% 的可写性。'}Windows 侧将直接使用下载缓存里的路径;要更新副本请先修复上述问题。`)
1850
+ }
1851
+ }
1852
+ } catch (error) {
1853
+ if (warnedBundleUnavailable !== true) {
1854
+ warnedBundleUnavailable = true
1855
+ console.error(`[dsh-ris-ide] 准备 Windows 版 ProxyBridge 失败:${error?.message ?? String(error)}`)
1856
+ }
1857
+ }
1858
+ }
1859
+ const candidates = redirectorCandidates({ platform, side, ...(bundleDir === undefined ? {} : { bundleDir }) })
813
1860
  for (const path of candidates) {
814
1861
  if (existsSync(path) !== true) continue
815
1862
  const kind = /\.exe$/i.test(path) === true ? 'windows-cli' : 'linux-cli'
816
- return { found: true, path, kind, candidates }
1863
+ // A CLI we can actually run means the component is NOT missing, even when it
1864
+ // came from DSH_RIS_IDE_PROXYBRIDGE, a vendor/Program Files install, or an
1865
+ // explicit bundleDir instead of our download cache (review B-P2 missingBundle).
1866
+ return { found: true, path, kind, candidates, bundleDir: candidates.bundleDir, bundleCached: installed === true, missingBundle: false }
817
1867
  }
818
- return { found: false, path: candidates[0] ?? '', kind: '', candidates }
1868
+ const result = { found: false, path: candidates[0] ?? '', kind: '', candidates, bundleDir: candidates.bundleDir, bundleCached: installed === true, missingBundle: candidates.missingBundle === true }
1869
+ if (result.missingBundle === true) result.reason = MISSING_BUNDLE_HINT
1870
+ else result.reason = side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge'
1871
+ return result
819
1872
  }
820
1873
 
821
1874
  /** Ask the CLI for its version; '' when it cannot answer (cached: it never changes). */
@@ -944,13 +1997,26 @@ export function writeRedirectorProfile(config, options = {}) {
944
1997
  if (rules.length === 0) throw new Error('没有可导出的规则:ProxyBridge 要求至少一条启用且带程序的规则')
945
1998
  const path = options.path ?? redirectorProfilePath()
946
1999
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
947
- writeFileSync(path, JSON.stringify(profile, null, 2), { mode: 0o600 })
2000
+ // Write-then-rename: the CLI reads this file while a rule edit may be writing it,
2001
+ // and a half-written profile made it start with no rules (review B-P2-3).
2002
+ const tmp = `${path}.${process.pid}.tmp`
948
2003
  try {
949
- chmodSync(path, 0o600)
950
- } catch {
951
- // Filesystems without POSIX modes (a Windows share) simply keep their default.
2004
+ writeFileSync(tmp, JSON.stringify(profile, null, 2), { mode: 0o600 })
2005
+ try {
2006
+ chmodSync(tmp, 0o600)
2007
+ } catch {
2008
+ // Filesystems without POSIX modes (a Windows share) simply keep their default.
2009
+ }
2010
+ renameSync(tmp, path)
2011
+ return { path, rules: rules.length, skipped }
2012
+ } finally {
2013
+ try { unlinkSync(tmp) } catch { /* renamed or never created */ }
952
2014
  }
953
- return { path, rules: rules.length, skipped }
2015
+ }
2016
+
2017
+ /** Quote one value for a single-quoted PowerShell literal (`'` becomes `''`). */
2018
+ function psQuote(value) {
2019
+ return "'" + String(value).replace(/'/g, "''") + "'"
954
2020
  }
955
2021
 
956
2022
  /**
@@ -959,14 +2025,28 @@ export function writeRedirectorProfile(config, options = {}) {
959
2025
  * A hand-started CLI (or one whose pid file we lost) still owns the hook, and
960
2026
  * ProxyBridge refuses to run twice — so "already running" means "get it out of the
961
2027
  * way", not "give up".
2028
+ *
2029
+ * Only processes whose command line carries THIS home's profile path are ours: the
2030
+ * old machine-wide `Get-Process ProxyBridge_CLI | Stop-Process` killed another
2031
+ * dsh-ris-ide home's bridge (or a user's own instance) and then claimed success
2032
+ * (review A4-P2-1/B-P1-4). No match means "not ours", not "kill everything".
2033
+ * @param {{profilePath?: string}} [options] - profile override (tests).
962
2034
  * @returns {Promise<{ok: boolean, killed?: number, reason?: string}>} outcome.
963
2035
  */
964
- export async function killWindowsCliProcesses() {
2036
+ export async function killWindowsCliProcesses(options = {}) {
2037
+ let profile = ''
2038
+ try {
2039
+ profile = windowsPathOf(String(options.profilePath ?? redirectorProfilePath()), { mustConvert: true })
2040
+ } catch (error) {
2041
+ return { ok: false, reason: error?.message ?? '无法确定本 home 的 profile 的 Windows 路径,未结束任何进程' }
2042
+ }
965
2043
  const script = [
966
2044
  "$ErrorActionPreference = 'Continue'",
967
- '$found = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue)',
2045
+ `$profile = ${psQuote(profile)}`,
2046
+ "$all = @(Get-CimInstance Win32_Process -Filter \"Name='ProxyBridge_CLI.exe'\" -ErrorAction SilentlyContinue)",
2047
+ "$found = @($all | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($profile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })",
968
2048
  'if ($found.Count -eq 0) { "none"; return }',
969
- '$found | Stop-Process -Force -ErrorAction SilentlyContinue',
2049
+ '$found | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }',
970
2050
  'Start-Sleep -Milliseconds 800',
971
2051
  '"killed=" + $found.Count',
972
2052
  ].join('; ')
@@ -975,7 +2055,9 @@ export async function killWindowsCliProcesses() {
975
2055
  const output = elevated.output
976
2056
  const killed = /killed=(\d+)/.exec(output)
977
2057
  if (killed !== null) return { ok: true, killed: Number.parseInt(killed[1], 10) }
978
- if (/none/.test(output)) return { ok: true, killed: 0 }
2058
+ if (/none/.test(output)) {
2059
+ return { ok: false, reason: '正在运行的 ProxyBridge_CLI 不属于当前 profile,未结束它(避免误杀别的实例)' }
2060
+ }
979
2061
  return {
980
2062
  ok: false,
981
2063
  reason: /cancel|取消|拒绝|denied|1223/i.test(output)
@@ -1031,16 +2113,60 @@ export function redirectorCommand(options = {}) {
1031
2113
  export function stopRedirectorSync(options = {}) {
1032
2114
  const sides = options.side === 'local' || options.side === 'windows' ? [options.side] : ['windows', 'local']
1033
2115
  const results = sides.map((side) => Object.assign({ side }, stopRedirectorSideSync(side, options)))
2116
+ // The async path reaps engine duplicates whose pid file was lost; the exit hook
2117
+ // has to keep the same single-instance promise (review B-P2-7). Signals only,
2118
+ // never wait: this runs while dsh is exiting.
2119
+ if (sides.includes('local')) {
2120
+ for (const pid of localRedirectorOwnPids()) {
2121
+ if (results.some((result) => result.pid === pid && result.stopped === true)) continue
2122
+ try { process.kill(pid, 'SIGTERM') } catch { /* either gone, or root — reported elsewhere */ }
2123
+ }
2124
+ }
1034
2125
  const stopped = results.filter((result) => result.stopped === true)
1035
2126
  if (stopped.length > 0) {
1036
2127
  const first = stopped[0]
1037
- return { stopped: true, pid: first.pid, side: first.side, service: first.service, byWatchdog: first.byWatchdog, results }
2128
+ return { stopped: true, pid: first.pid, side: first.side, service: first.service, byWatchdog: first.byWatchdog, foreign: first.foreign === true, results }
1038
2129
  }
1039
2130
  // Nothing was even detected: keep the historical terse answer (the UI shows it).
1040
2131
  if (results.every((result) => result.pid === undefined)) return { stopped: false, reason: '未在运行' }
2132
+ // A root-owned engine cannot be signalled by us: never answer `stopped:true` for
2133
+ // it, and hand the caller the exact command that would finish the job (B-P1-2).
2134
+ const privileged = results.find((result) => result.stopped !== true && result.command !== undefined)
2135
+ if (privileged !== undefined) {
2136
+ return {
2137
+ stopped: false,
2138
+ pid: privileged.pid,
2139
+ side: privileged.side,
2140
+ command: privileged.command,
2141
+ hint: privileged.hint,
2142
+ reason: privileged.reason ?? '该系统层拦截由 root 启动,请用 sudo 停止',
2143
+ results,
2144
+ }
2145
+ }
1041
2146
  return { stopped: false, reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未发现运行中的桥接', results }
1042
2147
  }
1043
2148
 
2149
+ /**
2150
+ * Record that a stop hit a bridge we never wrote a pid file for.
2151
+ *
2152
+ * `stopRedirector()` also stops a hand-started CLI (the user pasted the sudo
2153
+ * command), which is deliberate — leaving root interception behind is worse.
2154
+ * But the daemon's own exit therefore ends another program some human started,
2155
+ * so the engine log must say so: a silent kill is indistinguishable from a crash
2156
+ * (review B-P2-10).
2157
+ * @param {{pid: number, source?: string}} target - detection result being stopped.
2158
+ * @returns {boolean} true when the entry was written.
2159
+ */
2160
+ function noteForeignStop(target) {
2161
+ if (target.source === 'pidfile' || target.source === undefined) return false
2162
+ try {
2163
+ appendFileSync(proxyLogPath(), `${new Date().toISOString()} [dsh-ris-ide] 停止了一个非本工具记录的桥接 pid=${target.pid} (source=${target.source})\n`)
2164
+ return true
2165
+ } catch {
2166
+ return false
2167
+ }
2168
+ }
2169
+
1044
2170
  /** Stop one side; detection first, so a dead record can never fake success. */
1045
2171
  function stopRedirectorSideSync(side, options) {
1046
2172
  const record = redirectorPidRecord(side)
@@ -1067,6 +2193,8 @@ function stopRedirectorSideSync(side, options) {
1067
2193
  * the CLI and puts ProxyBridgeSvc back, with no second UAC.
1068
2194
  */
1069
2195
  function stopWindowsSideSync(target, options) {
2196
+ const foreign = target.source !== undefined && target.source !== 'pidfile'
2197
+ const foreignLogged = foreign ? noteForeignStop(target) : false
1070
2198
  requestRedirectorStop()
1071
2199
  const graceMs = Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 4000
1072
2200
  const deadline = Date.now() + graceMs
@@ -1081,23 +2209,50 @@ function stopWindowsSideSync(target, options) {
1081
2209
  // watchdog normally already did it; a hand-started CLI still needs this).
1082
2210
  const service = restoreWindowsService()
1083
2211
  clearStopSignals()
1084
- return { stopped: true, pid: target.pid, source: target.source, service, byWatchdog }
2212
+ return { stopped: true, pid: target.pid, source: target.source, service, byWatchdog, foreign, foreignLogged }
1085
2213
  }
1086
2214
  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) || '没有输出'})` }
2215
+ return { stopped: false, pid: target.pid, source: target.source, foreign, foreignLogged, reason: `无法停止 Windows 进程 ${target.pid}${hint}(${output.trim().slice(0, 120) || '没有输出'})` }
2216
+ }
2217
+
2218
+ /**
2219
+ * The answer for a local engine that belongs to root.
2220
+ *
2221
+ * A root process answers SIGTERM with EPERM and `kill(pid, 0)` still succeeds, so
2222
+ * `stopped:true` would be a lie while the interception keeps running (review
2223
+ * B-P1-2). The caller cannot elevate from a web route, so it gets the exact command.
2224
+ * @param {number} pid - the privileged engine.
2225
+ * @param {object} [extra] - per-side fields to keep.
2226
+ * @returns {object} stop result.
2227
+ */
2228
+ function privilegedStopResult(pid, extra = {}) {
2229
+ const command = `sudo kill ${Number(pid)}`
2230
+ return {
2231
+ stopped: false,
2232
+ pid,
2233
+ ...extra,
2234
+ command,
2235
+ reason: '该系统层拦截由 root 启动,请用 sudo 停止',
2236
+ hint: `在终端执行:${command}`,
2237
+ }
1088
2238
  }
1089
2239
 
1090
2240
  function stopLocalSideSync(target, options) {
2241
+ const foreign = target.source !== undefined && target.source !== 'pidfile'
2242
+ const foreignLogged = foreign ? noteForeignStop(target) : false
1091
2243
  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}` }
2244
+ if (error?.code === 'EPERM') return privilegedStopResult(target.pid, { side: 'local', foreign, foreignLogged })
1093
2245
  }
1094
2246
  // Block the exit hook briefly: SIGTERM on the engine is quick, and leaving a
1095
2247
  // root process behind after dsh quits is worse than a short delay.
1096
2248
  const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 3000)
1097
2249
  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})` }
2250
+ if (pidAlive(target.pid)) {
2251
+ // Alive after TERM and KILL: either root, or a zombie the kernel will reap.
2252
+ return privilegedStopResult(target.pid, { side: 'local', foreign, foreignLogged })
2253
+ }
1099
2254
  clearRedirectorPid('local')
1100
- return { stopped: true, pid: target.pid, source: target.source, side: 'local' }
2255
+ return { stopped: true, pid: target.pid, source: target.source, side: 'local', foreign, foreignLogged }
1101
2256
  }
1102
2257
 
1103
2258
  /** taskkill one pid (checked from the pid file) — test seam `taskkill` overrides it. */
@@ -1237,8 +2392,61 @@ export function localRedirectorRunning() {
1237
2392
  * @returns {number} pid or 0.
1238
2393
  */
1239
2394
  function scanLocalProcForRedirector() {
1240
- if (IS_WINDOWS) return 0
1241
- if (typeof probeHooks.localProc === 'function') return Number.parseInt(probeHooks.localProc() ?? 0, 10) || 0
2395
+ const pids = localRedirectorPids()
2396
+ return pids.length > 0 ? pids[0] : 0
2397
+ }
2398
+
2399
+ /**
2400
+ * Local ProxyBridge processes that belong to THIS proxy home (review B-P1-4).
2401
+ *
2402
+ * `localRedirectorPids()` finds every ProxyBridge on the machine, which is right for
2403
+ * diagnostics but wrong for `kill`: two dsh profiles (or a hand-started CLI for a
2404
+ * different profile) must not be reaped by one session's stop/restart. Only a
2405
+ * process whose `--profile` is our own profile file is ours.
2406
+ * @returns {number[]} pids of our own local bridge processes.
2407
+ */
2408
+ export function localRedirectorOwnPids() {
2409
+ if (IS_WINDOWS) return []
2410
+ if (typeof probeHooks.localProc === 'function') {
2411
+ const raw = probeHooks.localProc()
2412
+ return Array.isArray(raw) ? raw.map(Number).filter((pid) => Number.isInteger(pid) && pid > 0) : []
2413
+ }
2414
+ const own = redirectorProfilePath()
2415
+ const pids = []
2416
+ try {
2417
+ for (const entry of readdirSync('/proc')) {
2418
+ if (!/^\d+$/.test(entry)) continue
2419
+ try {
2420
+ const argv = readFileSync(`/proc/${entry}/cmdline`, 'utf8').split('\0').filter((part) => part !== '')
2421
+ if (!argv.some((token) => /(^|[\\/])ProxyBridge(\.exe)?$/i.test(token))) continue
2422
+ let profile = ''
2423
+ for (let index = 0; index < argv.length; index += 1) {
2424
+ if (argv[index] === '--profile') { profile = String(argv[index + 1] ?? ''); break }
2425
+ if (argv[index].startsWith('--profile=')) { profile = argv[index].slice('--profile='.length); break }
2426
+ }
2427
+ if (profile === own) pids.push(Number.parseInt(entry, 10))
2428
+ } catch { /* vanished */ }
2429
+ }
2430
+ } catch { /* no /proc */ }
2431
+ return pids
2432
+ }
2433
+
2434
+ /**
2435
+ * Every local ProxyBridge process, not just the first (m11773).
2436
+ *
2437
+ * A lost pid file used to make the next start spawn a second engine: the scan found
2438
+ * *a* process and reported "already running", but nothing ever reaped the extra one.
2439
+ * Single-instance on this side means knowing all of them, so a start/stop can drop
2440
+ * duplicates and leave exactly the process we mean to keep.
2441
+ * @returns {number[]} live pids running our redirector marker.
2442
+ */
2443
+ export function localRedirectorPids() {
2444
+ if (IS_WINDOWS) return []
2445
+ if (typeof probeHooks.localProc === 'function') {
2446
+ const raw = probeHooks.localProc()
2447
+ return Array.isArray(raw) ? raw.map(Number).filter((pid) => Number.isInteger(pid) && pid > 0) : []
2448
+ }
2449
+ const pids = []
1242
2450
  try {
1243
2451
  for (const entry of readdirSync('/proc')) {
1244
2452
  if (!/^\d+$/.test(entry)) continue
@@ -1246,12 +2454,110 @@ function scanLocalProcForRedirector() {
1246
2454
  const argv = readFileSync(`/proc/${entry}/cmdline`, 'utf8').split('\0').filter((part) => part !== '')
1247
2455
  const isRedirector = argv.some((token) => /(^|[\\/])ProxyBridge(\.exe)?$/i.test(token))
1248
2456
  if (isRedirector && argv.some((token) => token === '--profile' || token.startsWith('--profile='))) {
1249
- return Number.parseInt(entry, 10)
2457
+ pids.push(Number.parseInt(entry, 10))
1250
2458
  }
1251
2459
  } catch { /* vanished */ }
1252
2460
  }
1253
2461
  } catch { /* no /proc */ }
1254
- return 0
2462
+ return pids
2463
+ }
2464
+
2465
+ /**
2466
+ * Age at which an owner-less start lock is considered abandoned.
2467
+ *
2468
+ * A crashed starter can die between `mkdir` and the owner write; the next start
2469
+ * then sees an owner-less directory. Waiting 30 s for it (the old value, longer
2470
+ * than the 15 s default wait) made every start fail until the mtime aged out.
2471
+ */
2472
+ const STALE_LOCK_MS = 5000
2473
+
2474
+ /** Where startRedirector() keeps its per-side "a start is in progress" lock. */
2475
+ function startLockDir(side) {
2476
+ return join(proxyHomeDir(), 'locks', `proxybridge-${side === 'windows' ? 'windows' : 'local'}.lock`)
2477
+ }
2478
+
2479
+ /**
2480
+ * Is somebody holding the start lock for this side right now?
2481
+ *
2482
+ * Used by stopRedirector() when nothing is detected yet: during the UAC wait the
2483
+ * pid files are already gone, so the lock is the only proof that a start is still
2484
+ * in flight. A lock left behind by a crashed starter also answers true; it is
2485
+ * ignored/reaped by the next real starter (STALE_LOCK_MS), and "pendingStart" is a
2486
+ * truthful answer for it (a start is what would happen next, not a stop).
2487
+ * @param {'local'|'windows'} side - which side to probe.
2488
+ * @returns {boolean} true when the lock directory exists.
2489
+ */
2490
+ export function startLockHeld(side) {
2491
+ try { return existsSync(startLockDir(side)) } catch { return false }
2492
+ }
2493
+
2494
+ /**
2495
+ * Cross-process start lock for one side (m11773).
2496
+ *
2497
+ * The daemon and the plugin (its local fallback) can both decide to start the same
2498
+ * bridge at the same second; the Windows side then gets two elevated helpers and the
2499
+ * local side two engines. A lock directory under the shared proxy home serialises
2500
+ * the detect-then-spawn sequence across processes. It is deliberately tiny: create
2501
+ * with `mkdir` (atomic), write the owner pid, remove in `release()`; a lock whose
2502
+ * owner is gone (or which is older than the timeout) is treated as stale.
2503
+ * @param {'local'|'windows'} side - which side to lock.
2504
+ * @param {{timeoutMs?: number}} [options] - how long to wait for a concurrent start.
2505
+ * @returns {Promise<{ok: boolean, stale?: boolean, release?: () => void, reason?: string}>} outcome.
2506
+ */
2507
+ export async function acquireStartLock(side, options = {}) {
2508
+ const timeoutMs = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15000
2509
+ const dir = startLockDir(side)
2510
+ const deadline = Date.now() + timeoutMs
2511
+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 })
2512
+ for (;;) {
2513
+ try {
2514
+ mkdirSync(dir, { mode: 0o700 })
2515
+ try {
2516
+ writeFileSync(join(dir, 'owner'), `${process.pid}\n`, { mode: 0o600 })
2517
+ } catch { /* the dir alone is enough */ }
2518
+ let released = false
2519
+ return {
2520
+ ok: true,
2521
+ release() {
2522
+ if (released === true) return
2523
+ released = true
2524
+ // Only remove OUR lock: if the directory was already reaped as stale and
2525
+ // re-created by a successor, deleting it would hand the next starter a
2526
+ // lock-free window (review B-P2-9).
2527
+ try {
2528
+ const owner = Number.parseInt(readFileSync(join(dir, 'owner'), 'utf8').trim(), 10)
2529
+ const legacy = Number.isInteger(owner) !== true
2530
+ if (legacy === false && owner !== process.pid) return
2531
+ } catch {
2532
+ // No owner file: the starter died before writing it, so this is ours.
2533
+ }
2534
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* best effort */ }
2535
+ },
2536
+ }
2537
+ } catch (error) {
2538
+ if (error?.code !== 'EEXIST') return { ok: false, reason: `无法获取启动锁:${error?.message ?? error}` }
2539
+ }
2540
+ // Stale? A killed starter leaves the directory behind; its owner pid is the proof.
2541
+ let stale = false
2542
+ try {
2543
+ const owner = Number.parseInt(readFileSync(join(dir, 'owner'), 'utf8').trim(), 10)
2544
+ stale = Number.isInteger(owner) && owner > 0 && pidAlive(owner) !== true
2545
+ if (Number.isInteger(owner) !== true) stale = true
2546
+ } catch {
2547
+ // No owner file: only age can tell (the starter may die between mkdir and write).
2548
+ // The threshold must stay well below the default wait (15 s), or a crashed
2549
+ // starter makes the next few starts fail for half a minute (review B-P2-9).
2550
+ try {
2551
+ stale = Date.now() - statSync(dir).mtimeMs > STALE_LOCK_MS
2552
+ } catch { stale = true }
2553
+ }
2554
+ if (stale === true) {
2555
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* retry loop */ }
2556
+ continue
2557
+ }
2558
+ if (Date.now() >= deadline) return { ok: false, reason: '另一个进程正在启动桥接,请稍后再试' }
2559
+ await new Promise((resolve) => setTimeout(resolve, 100))
2560
+ }
1255
2561
  }
1256
2562
 
1257
2563
  /**
@@ -1372,8 +2678,13 @@ function detectSide(side) {
1372
2678
  }
1373
2679
  return null
1374
2680
  }
1375
- const scanned = scanLocalProcForRedirector()
1376
- if (scanned > 0) return { pid: scanned, side, source: 'proc' }
2681
+ const own = localRedirectorOwnPids()
2682
+ if (own.length > 0) {
2683
+ // A bridge started by hand (the card's sudo command) has no pid file; without
2684
+ // adopting it, teardown/空闲退出/崩溃重启 could never stop it (review A4-P1-2).
2685
+ writeRedirectorPid(own[0], 'local')
2686
+ return { pid: own[0], side, source: 'proc' }
2687
+ }
1377
2688
  return null
1378
2689
  }
1379
2690
 
@@ -1395,7 +2706,14 @@ export async function detectRunningRedirectorAsync() {
1395
2706
  windows = { pid: live[0], side: 'windows', source: 'process' }
1396
2707
  }
1397
2708
  }
1398
- const localHit = local ?? (scanLocalProcForRedirector() > 0 ? { pid: scanLocalProcForRedirector(), side: 'local', source: 'proc' } : null)
2709
+ let localHit = local
2710
+ if (localHit === null) {
2711
+ const own = localRedirectorOwnPids()
2712
+ if (own.length > 0) {
2713
+ writeRedirectorPid(own[0], 'local')
2714
+ localHit = { pid: own[0], side: 'local', source: 'proc' }
2715
+ }
2716
+ }
1399
2717
  const primary = localHit ?? windows
1400
2718
  return {
1401
2719
  pid: primary?.pid ?? 0,
@@ -1610,7 +2928,11 @@ async function psElevated(script, timeoutMs = 20000, options = {}) {
1610
2928
  } else if (typeof probeHooks.elevatedLaunch === 'function') {
1611
2929
  await probeHooks.elevatedLaunch({ localPath, windowsPath, nonce, body, timeoutMs: launchTimeout })
1612
2930
  } else {
1613
- spawnSyncText('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', launchEncoded], launchTimeout)
2931
+ // Async on purpose (review B-P0-1): this launcher blocks until the UAC dialog is
2932
+ // answered, which used to freeze the daemon's event loop for up to 45 s. The
2933
+ // caller keeps awaiting the overall deadline, so the visible semantics (and the
2934
+ // 45 s/20 s budgets) are unchanged.
2935
+ await spawnDetachedText('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', launchEncoded], launchTimeout)
1614
2936
  }
1615
2937
  let sawStale = false
1616
2938
  while (Date.now() < deadline) {
@@ -1669,6 +2991,51 @@ export function restoreWindowsService() {
1669
2991
  return { restored: false, reason: `服务未能恢复(${output.trim().slice(0, 120) || '需要管理员'})` }
1670
2992
  }
1671
2993
 
2994
+ /** Where the elevated start leaves the service's original start type. */
2995
+ function startTypeHintPath() {
2996
+ return join(redirectorHome(), 'windows-start-type.txt')
2997
+ }
2998
+
2999
+ /** Read the hint left by the elevated start script (`''` when absent/invalid). */
3000
+ export function readStartTypeHint() {
3001
+ try {
3002
+ const hint = readFileSync(startTypeHintPath(), 'utf8').trim()
3003
+ return /^(Automatic|AutomaticDelayedStart|Manual|Disabled)$/i.test(hint) ? hint : ''
3004
+ } catch {
3005
+ return ''
3006
+ }
3007
+ }
3008
+
3009
+ /** Drop the start-type hint (after a successful start or a restored service). */
3010
+ export function clearStartTypeHint() {
3011
+ try {
3012
+ unlinkSync(startTypeHintPath())
3013
+ } catch {
3014
+ // Nothing to clear.
3015
+ }
3016
+ }
3017
+
3018
+ /**
3019
+ * Put ProxyBridgeSvc back after a Windows start failed.
3020
+ *
3021
+ * The elevated helper stops the service and may park it on Manual before the CLI is
3022
+ * even spawned, so every failure path after that point has to undo it — otherwise
3023
+ * the machine stays "service stopped + StartupType Manual" until the next stop or
3024
+ * dsh exit (review B-P1-3). The original start type reaches us through the script's
3025
+ * hint file because the process may die before it reports anything.
3026
+ * @returns {{restored: boolean, reason?: string}} restoreWindowsService() result.
3027
+ */
3028
+ export function recoverWindowsService() {
3029
+ const state = readWindowsServiceState()
3030
+ const hint = readStartTypeHint()
3031
+ if (state === null && hint !== '') {
3032
+ writeWindowsServiceState({ stoppedByUs: true, originalStartType: hint, parkedOnManual: true })
3033
+ }
3034
+ const restored = restoreWindowsService()
3035
+ clearStartTypeHint()
3036
+ return restored
3037
+ }
3038
+
1672
3039
  /**
1673
3040
  * Assemble the status object from one detection snapshot.
1674
3041
  * @param {object} detection - detectRunningRedirector() result.
@@ -1683,7 +3050,16 @@ function buildStatus(detection, mode) {
1683
3050
  // The async route must not block 6 s on `--version`: take it from the cache.
1684
3051
  version = mode === 'async' ? (versionCache.get(found.path)?.version ?? '') : redirectorVersion(found.path)
1685
3052
  }
1686
- return { available: found.found, path: found.path, kind: found.kind, version }
3053
+ // `missingBundle` + `reason` let the maintenance page say "download/upload the
3054
+ // component" instead of showing an unexplained empty path.
3055
+ return {
3056
+ available: found.found,
3057
+ path: found.path,
3058
+ kind: found.kind,
3059
+ version,
3060
+ missingBundle: found.missingBundle === true,
3061
+ ...(found.reason === undefined ? {} : { reason: found.reason }),
3062
+ }
1687
3063
  }
1688
3064
  const profilePath = redirectorProfilePath()
1689
3065
  return {
@@ -1777,7 +3153,7 @@ export async function syncRedirector(cwd, options = {}) {
1777
3153
  const written = writeRedirectorProfile(config, { upstream: options.upstream })
1778
3154
  const found = findRedirector({ side: options.side })
1779
3155
  if (found.found === false) {
1780
- return { written, command: '', started: false, reason: '未找到 ProxyBridge CLI(可用 DSH_RIS_IDE_PROXYBRIDGE 指定,或把发行版解压到 vendor 目录)' }
3156
+ return { written, command: '', started: false, reason: found.reason ?? '未找到 ProxyBridge CLI(可用 DSH_RIS_IDE_PROXYBRIDGE 指定,或在维护页「代理 → 组件」上传/下载组件)', missingBundle: found.missingBundle === true }
1781
3157
  }
1782
3158
  const command = redirectorCommand({ cliPath: found.path, profilePath: written.path, verbose: options.verbose })
1783
3159
  if (options.start === false) return { written, command, started: false, reason: '' }
@@ -1798,7 +3174,8 @@ export async function syncRedirector(cwd, options = {}) {
1798
3174
  * is launched, and an elevation prompt (UAC on Windows) is the expected outcome
1799
3175
  * rather than an error. A side that needs a password we cannot type is reported
1800
3176
  * with the command instead of failing the whole start.
1801
- * @param {{sides?: string[], verbose?: number}} [options] - sides to consider, in order.
3177
+ * @param {{sides?: string[], verbose?: number, interactive?: boolean}} [options] - sides to consider, in order;
3178
+ * `interactive:true` is the only path allowed to raise a pkexec/terminal prompt (review B-P0-2).
1802
3179
  * @returns {Promise<{started: object[], skipped: object[], running: boolean}>} per-side outcome.
1803
3180
  */
1804
3181
  export async function startRedirectors(options = {}) {
@@ -1808,7 +3185,12 @@ export async function startRedirectors(options = {}) {
1808
3185
  if (process.env.NODE_TEST_CONTEXT !== undefined) {
1809
3186
  return { started: [], skipped: [{ side: '', reason: '测试环境不启动系统层拦截' }], running: false }
1810
3187
  }
1811
- const sides = Array.isArray(options.sides) && options.sides.length > 0 ? options.sides : ['windows', 'local']
3188
+ // A Windows host has only one machine: 'local' would resolve to the same
3189
+ // ProxyBridge_CLI.exe and the second start would fight for the WinDivert handle.
3190
+ // The plugin now ships that CLI, so the default there is the windows side alone.
3191
+ const sides = Array.isArray(options.sides) && options.sides.length > 0
3192
+ ? options.sides
3193
+ : (process.platform === 'win32' ? ['windows'] : ['windows', 'local'])
1812
3194
  // `reload` applies edited rules to a bridge that is already running.
1813
3195
  const reload = options.reload === true
1814
3196
  const started = []
@@ -1821,7 +3203,7 @@ export async function startRedirectors(options = {}) {
1821
3203
  for (const side of sides) {
1822
3204
  const found = findRedirector({ side })
1823
3205
  if (found.found !== true) {
1824
- skipped.push({ side, reason: `未找到 ${side === 'windows' ? 'Windows' : '本侧'} ProxyBridge` })
3206
+ skipped.push({ side, reason: found.reason ?? `未找到 ${side === 'windows' ? 'Windows' : '本侧'} ProxyBridge`, missingBundle: found.missingBundle === true })
1825
3207
  continue
1826
3208
  }
1827
3209
  if (claimed.has(found.path)) {
@@ -1843,7 +3225,7 @@ export async function startRedirectors(options = {}) {
1843
3225
  skipped.push({ side, reason: `已在运行(pid ${runningHere.pid})`, pid: runningHere.pid })
1844
3226
  continue
1845
3227
  }
1846
- const result = await startRedirector({ side, verbose: options.verbose })
3228
+ const result = await startRedirector({ side, verbose: options.verbose, interactive: options.interactive === true })
1847
3229
  if (result.started === true) started.push(result)
1848
3230
  else skipped.push(Object.assign({ side }, result))
1849
3231
  }
@@ -1861,7 +3243,12 @@ export async function startRedirectors(options = {}) {
1861
3243
  * @returns {Promise<{ok: boolean, written: {path: string, rules: number, skipped: object[]}, reloaded: object[], skipped: object[], reason?: string}>} outcome.
1862
3244
  */
1863
3245
  export async function reloadRedirectorsWithProfile(cwd, options = {}) {
1864
- const sides = Array.isArray(options.sides) && options.sides.length > 0 ? options.sides : ['windows', 'local']
3246
+ // A Windows host has only one machine: 'local' would resolve to the same
3247
+ // ProxyBridge_CLI.exe and the second start would fight for the WinDivert handle.
3248
+ // The plugin now ships that CLI, so the default there is the windows side alone.
3249
+ const sides = Array.isArray(options.sides) && options.sides.length > 0
3250
+ ? options.sides
3251
+ : (process.platform === 'win32' ? ['windows'] : ['windows', 'local'])
1865
3252
  let written = null
1866
3253
  try {
1867
3254
  written = writeRedirectorProfile(readProxyConfig(cwd), { upstream: options.upstream, path: options.profilePath })
@@ -1952,31 +3339,104 @@ export async function reloadRedirector(options = {}) {
1952
3339
  * @returns {Promise<{stopped: boolean, pid?: number, side?: string, reason?: string, results?: object[]}>} outcome.
1953
3340
  */
1954
3341
  export async function stopRedirector(options = {}) {
1955
- const detection = detectRunningRedirector()
1956
- if (detection.pid === 0) {
1957
- // Drop dead records so status stops advertising a pid that does not exist.
3342
+ // Serialise with startRedirector (review B-P1-5): the elevated start holds that
3343
+ // side's lock for up to 45 s while UAC waits. A stop that ran meanwhile saw
3344
+ // nothing, answered "未在运行", and the start then finished on an already-stopped
3345
+ // engine. Only the side(s) we are about to touch are locked (review follow-up):
3346
+ // taking both up front made a plain "stop" wait 2x15 s behind a Windows UAC start.
3347
+ const requestedSide = options.side === 'local' || options.side === 'windows' ? options.side : null
3348
+ const preliminary = detectRunningRedirector()
3349
+ const sidesToLock = requestedSide !== null ? [requestedSide]
3350
+ : ['windows', 'local'].filter((side) => preliminary[side]?.pid > 0)
3351
+ const clearDeadRecords = () => {
1958
3352
  for (const side of ['windows', 'local']) {
1959
3353
  if (redirectorPidRecord(side).pid > 0) clearRedirectorPid(side)
1960
3354
  }
1961
- return { stopped: false, reason: '未在运行' }
1962
3355
  }
1963
- const results = []
1964
- if (detection.windows.pid > 0) {
1965
- results.push(Object.assign({ side: 'windows' }, stopRedirectorSync(Object.assign({}, options, { side: 'windows' }))))
3356
+ if (sidesToLock.length === 0) {
3357
+ // Nothing is running *now* — but a start may be mid-flight and its pid files
3358
+ // already cleared (the UAC wait is the long part). The start lock is the only
3359
+ // signal left, so probe it without blocking instead of answering "未在运行".
3360
+ const starting = (requestedSide !== null ? [requestedSide] : ['windows', 'local']).find((side) => startLockHeld(side))
3361
+ if (starting !== undefined) {
3362
+ return { stopped: false, pendingStart: true, side: starting, reason: '另一个进程正在启动桥接,请稍后再试' }
3363
+ }
3364
+ clearDeadRecords()
3365
+ return { stopped: false, reason: '未在运行' }
1966
3366
  }
1967
- if (detection.local.pid > 0) {
1968
- results.push(Object.assign({ side: 'local' }, await stopLocalRedirectorAsync(detection.local.pid, options)))
3367
+ const locks = []
3368
+ for (const side of sidesToLock) {
3369
+ const lock = await acquireStartLock(side, { timeoutMs: options.lockTimeoutMs })
3370
+ if (lock.ok !== true) {
3371
+ for (const held of locks) held.release()
3372
+ return { stopped: false, pendingStart: true, side, reason: lock.reason ?? '另一个进程正在启动桥接,请稍后再试' }
3373
+ }
3374
+ locks.push(lock)
1969
3375
  }
1970
- const stopped = results.filter((result) => result.stopped === true)
1971
- if (stopped.length === 0) {
1972
- return {
1973
- stopped: false,
1974
- pid: detection.pid,
1975
- reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未能停止桥接',
1976
- results,
3376
+ try {
3377
+ // Re-detect under the lock: the start we waited for may have failed, and the
3378
+ // side we detected a moment ago may be gone (or a different one may be up).
3379
+ const detection = detectRunningRedirector()
3380
+ if (detection.pid === 0) {
3381
+ // Drop dead records so status stops advertising a pid that does not exist.
3382
+ clearDeadRecords()
3383
+ return { stopped: false, reason: '未在运行' }
3384
+ }
3385
+ const results = []
3386
+ if (detection.windows.pid > 0) {
3387
+ results.push(Object.assign({ side: 'windows' }, stopRedirectorSync(Object.assign({}, options, { side: 'windows' }))))
3388
+ }
3389
+ if (detection.local.pid > 0) {
3390
+ results.push(Object.assign({ side: 'local' }, await stopLocalRedirectorAsync(detection.local.pid, options)))
3391
+ }
3392
+ // Local duplicates: an engine whose pid file we lost still holds the eBPF hook.
3393
+ // Stopping "the recorded one" is not enough for a single-instance invariant.
3394
+ // A root engine answers SIGTERM with EPERM: that is not "stopped" (review B-P1-2).
3395
+ const blocked = []
3396
+ for (const pid of localRedirectorOwnPids()) {
3397
+ if (results.some((result) => result.pid === pid && result.stopped === true)) continue
3398
+ try { process.kill(pid, 'SIGTERM') } catch (error) {
3399
+ if (error?.code === 'EPERM') blocked.push(pid)
3400
+ }
3401
+ }
3402
+ if (blocked.length > 0) {
3403
+ const command = 'sudo kill ' + blocked.join(' ')
3404
+ return {
3405
+ stopped: false,
3406
+ pid: blocked[0],
3407
+ pids: blocked,
3408
+ command,
3409
+ reason: '该系统层拦截由 root 启动,请用 sudo 停止',
3410
+ hint: `在终端执行:${command}`,
3411
+ results,
3412
+ }
3413
+ }
3414
+ const stopped = results.filter((result) => result.stopped === true)
3415
+ // A side stopped while the other reported "root, use sudo" is still an
3416
+ // unfinished stop: saying `stopped:true` hides the interception that is running.
3417
+ const needsSudo = results.find((result) => result.stopped !== true && result.command !== undefined)
3418
+ if (needsSudo !== undefined) {
3419
+ return {
3420
+ stopped: false,
3421
+ pid: needsSudo.pid,
3422
+ side: needsSudo.side,
3423
+ command: needsSudo.command,
3424
+ reason: needsSudo.reason ?? '该系统层拦截由 root 启动,请用 sudo 停止',
3425
+ results,
3426
+ }
1977
3427
  }
3428
+ if (stopped.length === 0) {
3429
+ return {
3430
+ stopped: false,
3431
+ pid: detection.pid,
3432
+ reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未能停止桥接',
3433
+ results,
3434
+ }
3435
+ }
3436
+ return { stopped: true, pid: stopped[0].pid, side: stopped[0].side, results }
3437
+ } finally {
3438
+ for (const held of locks) held.release()
1978
3439
  }
1979
- return { stopped: true, pid: stopped[0].pid, side: stopped[0].side, results }
1980
3440
  }
1981
3441
 
1982
3442
  /** Graceful local stop with SIGKILL fallback (the exit hook used to do this inline). */
@@ -1985,10 +3445,11 @@ async function stopLocalRedirectorAsync(pid, options = {}) {
1985
3445
  process.kill(pid, 'SIGTERM')
1986
3446
  } catch (error) {
1987
3447
  const code = error?.code ?? ''
3448
+ if (code === 'EPERM') return privilegedStopResult(pid)
1988
3449
  return {
1989
3450
  stopped: false,
1990
3451
  pid,
1991
- reason: code === 'EPERM' ? `需要管理员/sudo:sudo kill ${pid}` : `无法停止进程 ${pid}(${code || error?.message})`,
3452
+ reason: `无法停止进程 ${pid}(${code || error?.message})`,
1992
3453
  }
1993
3454
  }
1994
3455
  const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 5000)
@@ -1999,7 +3460,7 @@ async function stopLocalRedirectorAsync(pid, options = {}) {
1999
3460
  if (pidAlive(pid)) {
2000
3461
  try { process.kill(pid, 'SIGKILL') } catch { /* still privileged: report below */ }
2001
3462
  }
2002
- if (pidAlive(pid)) return { stopped: false, pid, reason: `进程 ${pid} 仍在运行(需要 sudo kill ${pid})` }
3463
+ if (pidAlive(pid)) return privilegedStopResult(pid)
2003
3464
  clearRedirectorPid('local')
2004
3465
  return { stopped: true, pid }
2005
3466
  }
@@ -2012,10 +3473,15 @@ async function stopLocalRedirectorAsync(pid, options = {}) {
2012
3473
  * WSL-only. `wslpath -w` is authoritative when present (it also handles the
2013
3474
  * `\\wsl.localhost\<distro>` form for our home directory); the drive-letter
2014
3475
  * rewrite is the fallback for a distro without it.
3476
+ *
3477
+ * A caller that NEEDS the Windows form (launch a program, read a file from
3478
+ * PowerShell) must pass `{mustConvert:true}`: silently returning the Linux spelling
3479
+ * made the launch fail with no diagnostic at all (review B-P2-12).
2015
3480
  * @param {string} path - an absolute Linux path, possibly under /mnt/<drive>.
3481
+ * @param {{mustConvert?: boolean}} [options] - throw when no Windows form is found.
2016
3482
  * @returns {string} the same location as Windows sees it.
2017
3483
  */
2018
- export function windowsPathOf(path) {
3484
+ export function windowsPathOf(path, options = {}) {
2019
3485
  const text = String(path ?? '')
2020
3486
  if (text === '') return text
2021
3487
  if (/^[A-Za-z]:[\\/]/.test(text)) return text
@@ -2026,12 +3492,32 @@ export function windowsPathOf(path) {
2026
3492
  if (mounted !== null) return `${mounted[1].toUpperCase()}:\\${mounted[2].replace(/\//g, '\\')}`
2027
3493
  const converted = spawnSyncText('wslpath', ['-w', text], 4000).trim()
2028
3494
  if (converted !== '' && /^[A-Za-z]:[\\/]|^\\\\/.test(converted)) return converted
3495
+ if (options.mustConvert === true) {
3496
+ throw new Error(`无法把路径转换为 Windows 形式(wslpath 不可用或失败):${text}`)
3497
+ }
2029
3498
  return text
2030
3499
  }
2031
3500
 
2032
- /** @param {object[]} args - argv as this side spells it. @returns {object[]} Windows-spelled argv. */
2033
- function windowsArgsOf(args) {
2034
- return args.map((arg) => (typeof arg === 'string' && arg.startsWith('/') ? windowsPathOf(arg) : arg))
3501
+ /**
3502
+ * Translate only the argv entries that really are existing files.
3503
+ *
3504
+ * ProxyBridge's own flags look like paths (`/d`, `/p:key=value`), so "starts with
3505
+ * `/`" is not enough: translating those into `\d` / `\p:key=value` corrupts the
3506
+ * command line. Windows-spelled values (`C:\…`, `\\wsl.localhost\…`) are already
3507
+ * correct for the other side and must be left untouched.
3508
+ * @param {object[]} args - argv as this side spells it.
3509
+ * @returns {object[]} Windows-spelled argv.
3510
+ */
3511
+ function windowsArgsOf(args, options = {}) {
3512
+ return args.map((arg) => {
3513
+ if (typeof arg !== 'string' || arg.startsWith('/') !== true) return arg
3514
+ try {
3515
+ if (existsSync(arg) !== true || statSync(arg).isFile() !== true) return arg
3516
+ } catch {
3517
+ return arg
3518
+ }
3519
+ return windowsPathOf(arg, options)
3520
+ })
2035
3521
  }
2036
3522
 
2037
3523
  function spawnSyncText(command, args, timeoutMs) {
@@ -2041,6 +3527,10 @@ function spawnSyncText(command, args, timeoutMs) {
2041
3527
 
2042
3528
  export const __test = {
2043
3529
  PROFILE_VERSION,
3530
+ bundledBundleDir,
3531
+ bundleCacheInstalled,
3532
+ ensureBundleReady,
3533
+ MISSING_BUNDLE_HINT,
2044
3534
  startRedirector,
2045
3535
  stopRedirectorSync,
2046
3536
  pidAliveOn,
@@ -2080,10 +3570,20 @@ export const __test = {
2080
3570
  sleepSync,
2081
3571
  psElevated,
2082
3572
  watchdogPid,
3573
+ acquireStartLock,
3574
+ localRedirectorPids,
3575
+ localRedirectorOwnPids,
2083
3576
  writeWatchdogPid,
2084
3577
  reloadDonePath,
2085
3578
  reloadFailedPath,
2086
3579
  windowsPathOf,
3580
+ windowsArgsOf,
3581
+ spawnDetachedText,
3582
+ privilegedStopResult,
3583
+ readStartTypeHint,
3584
+ clearStartTypeHint,
3585
+ startTypeHintPath,
3586
+ recoverWindowsService,
2087
3587
  }
2088
3588
 
2089
3589
  const SELF = basename(process.argv[1] ?? '')