dsh-ris-ide 1.7.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,2558 @@
1
+ /**
2
+ * ProxyBridge redirector adapter.
3
+ *
4
+ * Why this exists: our own proxy engine can only help a program we launch (env /
5
+ * JVM flags) or a client that accepts a `127.0.0.1:port` address (JDBC, Navicat).
6
+ * A program started elsewhere — an IDE's F5, a terminal, a GUI database tool —
7
+ * cannot be injected at all. ProxyBridge does exactly that missing job: it hooks
8
+ * the socket layer by process name (WinDivert on Windows, eBPF on Linux) and
9
+ * sends matching connections to a SOCKS5/HTTP proxy.
10
+ *
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. 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
17
+ * ("Nothing is installed"); it needs root, but no systemd unit.
18
+ * - Windows: `ProxyBridge_CLI.exe` next to `ProxyBridgeCore.dll`, `WinDivert.dll`
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.
27
+ *
28
+ * Elevation is the one thing we cannot do silently: on Windows it is a UAC prompt,
29
+ * on WSL/Linux a sudo password. So `start` reports the exact command and only
30
+ * spawns when the caller already has the rights.
31
+ */
32
+
33
+ import { execFile, spawn, spawnSync } from 'node:child_process'
34
+ import { randomUUID } from 'node:crypto'
35
+ import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
36
+ import { homedir } from 'node:os'
37
+ import { basename, dirname, extname, join } from 'node:path'
38
+ import { promisify } from 'node:util'
39
+
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'
42
+
43
+ /** Directory (under the shared proxy home) holding our profile, pid and log. */
44
+ export const REDIRECTOR_DIRNAME = 'proxybridge'
45
+ /** The profile file name; the ProxyBridge GUI shows it as one more profile. */
46
+ export const REDIRECTOR_PROFILE_FILENAME = 'dsh-ris-ide.pbprofile'
47
+ /** The single pid file older versions wrote; migrated to the per-side files below. */
48
+ export const REDIRECTOR_PID_FILENAME = 'proxybridge.pid'
49
+ /**
50
+ * Per-side pid files: a Windows CLI and the local engine hook different network
51
+ * stacks, so they can run at the same time. One shared record made one start
52
+ * erase the other side's pid (the local engine then became an orphan).
53
+ */
54
+ export const REDIRECTOR_PID_FILENAMES = Object.freeze({
55
+ local: 'proxybridge.local.pid',
56
+ windows: 'proxybridge.windows.pid',
57
+ })
58
+ export const REDIRECTOR_LOG_FILENAME = 'proxybridge.log'
59
+ /** Substring of the redirector's command line, used to verify a pid is ours. */
60
+ export const REDIRECTOR_MARKER = 'ProxyBridge'
61
+ /** Profile rules are per-connection decisions, so TCP+UDP is the useful default. */
62
+ const PROFILE_VERSION = '1.0'
63
+
64
+ /**
65
+ * Test-only probe overrides.
66
+ *
67
+ * Every call that would spawn PowerShell, run the CLI for `--version`, kill a
68
+ * Windows process or start the elevated helper goes through one of these seats.
69
+ * Production leaves the object empty; tests fill it so a lifecycle test can run
70
+ * deterministically without touching the real Windows side (no UAC, no driver,
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%`.
75
+ */
76
+ const probeHooks = {}
77
+
78
+ /** @param {object} hooks - overrides keyed as documented in __test.setProbeHooks. */
79
+ function setProbeHooks(hooks) {
80
+ for (const key of Object.keys(hooks ?? {})) {
81
+ if (typeof hooks[key] === 'function') probeHooks[key] = hooks[key]
82
+ }
83
+ }
84
+
85
+ /** Drop every probe override (tests call this in `finally`). */
86
+ function resetProbeHooks() {
87
+ for (const key of Object.keys(probeHooks)) delete probeHooks[key]
88
+ }
89
+
90
+ /** TTL of the process-table probes: the UI polls status, PowerShell takes seconds. */
91
+ const PROBE_TTL_MS = 5000
92
+ /** The CLI's version does not change while a process is alive. */
93
+ const VERSION_TTL_MS = 60000
94
+ /** TTL of the cached status snapshot served to the HTTP route. */
95
+ const STATUS_TTL_MS = 5000
96
+ /** One suspended-promise dedupe slot for the async probes. */
97
+ const execFileAsync = promisify(execFile)
98
+
99
+ let windowsPidsCache = { at: 0, pids: null }
100
+ const windowsAliveCache = new Map()
101
+ const versionCache = new Map()
102
+ let statusCache = { at: 0, value: null }
103
+ let statusInflight = null
104
+
105
+ /** Clear every TTL cache (tests need a deterministic start and per-call counts). */
106
+ function clearProbeCaches() {
107
+ windowsPidsCache = { at: 0, pids: null }
108
+ windowsAliveCache.clear()
109
+ versionCache.clear()
110
+ statusCache = { at: 0, value: null }
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
+ }
117
+
118
+ /**
119
+ * Run a command asynchronously and return its combined output (never throws).
120
+ *
121
+ * `spawnSync` PowerShell calls block the host's event loop for 3–4 s, which froze
122
+ * the whole web/terminal/agent process on every `GET /proxy`. `execFile` keeps the
123
+ * loop free; the timeout still kills a hung child.
124
+ */
125
+ async function runTextAsync(command, args, timeoutMs) {
126
+ try {
127
+ const result = await execFileAsync(command, args, { encoding: 'utf8', timeout: timeoutMs, windowsHide: true, maxBuffer: 1024 * 1024 })
128
+ return `${result.stdout ?? ''}${result.stderr ?? ''}`
129
+ } catch (error) {
130
+ return `${error?.stdout ?? ''}${error?.stderr ?? ''}`
131
+ }
132
+ }
133
+
134
+ /** Sleep without spawning a node process per tick (the old "sleep" blocked too). */
135
+ function sleepSync(ms) {
136
+ try {
137
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
138
+ } catch {
139
+ spawnSyncText(process.execPath, ['-e', 'setTimeout(() => {}, 100)'], 2000)
140
+ }
141
+ }
142
+
143
+ /** Where our profile/pid/log live: one folder beside the shared proxy config. */
144
+ export function redirectorHome() {
145
+ return join(proxyHomeDir(), REDIRECTOR_DIRNAME)
146
+ }
147
+
148
+ export function redirectorProfilePath() {
149
+ return join(redirectorHome(), REDIRECTOR_PROFILE_FILENAME)
150
+ }
151
+
152
+ /** The legacy single pid file: every version before the split wrote this one path. */
153
+ export function redirectorPidPath() {
154
+ return join(redirectorHome(), REDIRECTOR_PID_FILENAME)
155
+ }
156
+
157
+ /**
158
+ * Pid file of one side.
159
+ *
160
+ * Both sides can run at once (Windows hooks the host's processes, the local
161
+ * engine hooks ours), so each side records its own pid. A shared file made the
162
+ * second start overwrite the first side's record, which is how the local engine
163
+ * became an orphan nobody could stop.
164
+ * @param {'local'|'windows'} side - which side.
165
+ * @returns {string} absolute path.
166
+ */
167
+ export function redirectorSidePidPath(side) {
168
+ const name = side === 'windows' ? REDIRECTOR_PID_FILENAMES.windows : REDIRECTOR_PID_FILENAMES.local
169
+ return join(redirectorHome(), name)
170
+ }
171
+
172
+ /** Read one pid record file without any compatibility fallback. */
173
+ function readPidFileAt(path) {
174
+ try {
175
+ const text = readFileSync(path, 'utf8').trim()
176
+ const match = /^(\d+)\s*(\S*)$/.exec(text)
177
+ if (match === null) return null
178
+ const pid = Number.parseInt(match[1], 10)
179
+ if (!Number.isInteger(pid) || pid <= 0) return null
180
+ const side = match[2] === 'windows' ? 'windows' : 'local'
181
+ return { pid, side }
182
+ } catch {
183
+ return null
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Move the pre-split single pid file to its per-side home.
189
+ *
190
+ * The old file names the side inside its content (`<pid> <side>`), so the record
191
+ * survives the upgrade instead of turning into an orphan we can no longer stop.
192
+ * @returns {{migrated: boolean, pid: number, side: string}} what was found.
193
+ */
194
+ export function migrateLegacyPidFile() {
195
+ const legacy = redirectorPidPath()
196
+ if (existsSync(legacy) !== true) return { migrated: false, pid: 0, side: 'local' }
197
+ const record = readPidFileAt(legacy)
198
+ if (record === null) {
199
+ // Unreadable garbage: keeping it would make every status call look busy.
200
+ try {
201
+ unlinkSync(legacy)
202
+ } catch {
203
+ // best-effort: a read-only home keeps the file, callers still ignore it
204
+ }
205
+ return { migrated: false, pid: 0, side: 'local' }
206
+ }
207
+ const target = redirectorSidePidPath(record.side)
208
+ if (existsSync(target) !== true) {
209
+ try {
210
+ mkdirSync(redirectorHome(), { recursive: true, mode: 0o700 })
211
+ writeFileSync(target, `${record.pid} ${record.side}\n`, { mode: 0o600 })
212
+ } catch {
213
+ // best-effort: the legacy file stays readable until the next attempt
214
+ }
215
+ }
216
+ if (existsSync(target) === true) {
217
+ try {
218
+ unlinkSync(legacy)
219
+ } catch {
220
+ // best-effort: duplicate is harmless, reads prefer the per-side file
221
+ }
222
+ }
223
+ return { migrated: existsSync(target) === true, pid: record.pid, side: record.side }
224
+ }
225
+
226
+ export function redirectorLogPath() {
227
+ return join(redirectorHome(), REDIRECTOR_LOG_FILENAME)
228
+ }
229
+
230
+ /**
231
+ * The downloaded-and-cached ProxyBridge distribution (machine-wide proxy home).
232
+ *
233
+ * Nothing is shipped inside the plugin any more (2.9 MB of binaries made every
234
+ * install heavy and pinned the upstream version): `lib/proxybridge-bundle.js`
235
+ * downloads/accepts an uploaded `.tgz` here on first use.
236
+ * @returns {string} absolute path to `<proxyHome>/proxybridge/bundle`.
237
+ */
238
+ export function bundledBundleDir() {
239
+ return bundleInstallDir(proxyHomeDir())
240
+ }
241
+
242
+ /**
243
+ * The cached distribution for one platform.
244
+ *
245
+ * The old name is kept for compat (this module and its tests import it), but it no
246
+ * longer points inside the plugin: the folder only exists after a download/upload.
247
+ * @param {{platform?: string, dir?: string}} [options] - platform / install-dir overrides for tests.
248
+ * @returns {string} absolute path to `<bundle>/<windows|linux>`.
249
+ */
250
+ export function bundledRedirectorDir(options = {}) {
251
+ const platform = options.platform ?? process.platform
252
+ return join(options.dir ?? bundledBundleDir(), platform === 'win32' ? 'windows' : 'linux')
253
+ }
254
+
255
+ /** True when the cached distribution is complete (manifest plus every file). */
256
+ export function bundleCacheInstalled() {
257
+ return bundleIsInstalled(bundledBundleDir())
258
+ }
259
+
260
+ /**
261
+ * Identity of the currently installed bundle. The Windows-side copy (below) is
262
+ * materialised from it, so a changed fingerprint means the DLLs/CLI on the Windows
263
+ * side are stale and must be copied again (review B-P1-2).
264
+ * @param {string} [dir] - install directory; defaults to {@link bundledBundleDir}.
265
+ * @returns {string} `sha256:installedAt`, or '' when nothing is installed.
266
+ */
267
+ export function bundleFingerprint(dir = bundledBundleDir()) {
268
+ const manifest = readManifest(dir)
269
+ if (manifest === null) return ''
270
+ return `${manifest.sha256 ?? ''}:${manifest.installedAt ?? ''}`
271
+ }
272
+
273
+ /** Machine-level settings file (`~/.dsh-ris-ide/settings.json`); unreadable counts as empty. */
274
+ function readMachineSettings() {
275
+ try {
276
+ const parsed = JSON.parse(readFileSync(join(proxyHomeDir(), 'settings.json'), 'utf8'))
277
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
278
+ } catch {
279
+ return {}
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Make the ProxyBridge distribution available: reuse the cache, else download it.
285
+ *
286
+ * URL and digest priority now live in exactly one place — `resolveBundleUrls` /
287
+ * `resolveBundleSha256` inside `lib/proxybridge-bundle.js` (env → settings →
288
+ * mirrors), shared with the daemon. This function only forwards the explicit
289
+ * route-level `url` and the machine settings; it must not re-order them
290
+ * (review A3-P2-1/-2). Never throws — the route layer turns `{ok:false}` into a
291
+ * readable failure.
292
+ * @param {{url?: string, fetchImpl?: typeof fetch, force?: boolean}} [options] - overrides for the route/tests.
293
+ * @returns {Promise<{ok: boolean, dir: string, fromCache: boolean, error: string, url: string, hint: string, warning?: string}>} outcome.
294
+ */
295
+ export async function ensureBundleReady(options = {}) {
296
+ const fallbackUrl = DEFAULT_BUNDLE_URL
297
+ try {
298
+ const settings = readMachineSettings()
299
+ const explicit = typeof options.url === 'string' && options.url.trim() !== '' ? options.url.trim() : ''
300
+ const result = await ensureBundle({
301
+ home: proxyHomeDir(),
302
+ settings,
303
+ force: options.force === true,
304
+ ...(explicit === '' ? {} : { url: explicit }),
305
+ ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),
306
+ })
307
+ const url = typeof result.url === 'string' && result.url !== '' ? result.url : explicit || fallbackUrl
308
+ if (result.ok === true) {
309
+ return {
310
+ ok: true,
311
+ dir: result.dir,
312
+ fromCache: result.fromCache === true,
313
+ error: '',
314
+ url,
315
+ hint: '',
316
+ ...(typeof result.warning === 'string' ? { warning: result.warning } : {}),
317
+ }
318
+ }
319
+ return {
320
+ ok: false,
321
+ dir: result.dir ?? '',
322
+ fromCache: false,
323
+ error: result.error ?? '下载失败',
324
+ url,
325
+ hint: result.hint ?? '',
326
+ }
327
+ } catch (error) {
328
+ return {
329
+ ok: false,
330
+ dir: '',
331
+ fromCache: false,
332
+ error: error?.message ?? String(error),
333
+ url: fallbackUrl,
334
+ hint: '检查下载地址后重试,或在维护页「代理 → 组件」上传 ris-proxy.4.0.tgz。',
335
+ }
336
+ }
337
+ }
338
+
339
+
340
+ /** How long a failed `%LOCALAPPDATA%` probe is remembered before it is asked again. */
341
+ const LOCAL_APP_DATA_RETRY_MS = 60000
342
+ let localAppDataCache = null // { value: string, at: number }
343
+ let warnedNoWindowsSide = false
344
+ /** `%LOCALAPPDATA%` as a Windows path; '' when it cannot be asked (native Linux/macOS). */
345
+ function windowsLocalAppData() {
346
+ const now = Date.now()
347
+ // A resolved value never changes; an empty one may (WSL interop is enabled after
348
+ // the fact, or `cmd.exe` was briefly unavailable), so only cache it for a minute.
349
+ if (localAppDataCache !== null && (localAppDataCache.value !== '' || now - localAppDataCache.at < LOCAL_APP_DATA_RETRY_MS)) {
350
+ return localAppDataCache.value
351
+ }
352
+ if (process.platform === 'win32') {
353
+ localAppDataCache = { value: process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), at: now }
354
+ return localAppDataCache.value
355
+ }
356
+ if (existsSync('/mnt/c') !== true) {
357
+ if (warnedNoWindowsSide !== true) {
358
+ warnedNoWindowsSide = true
359
+ // One readable line instead of a silent '' — this is the "not WSL" case.
360
+ console.error('[dsh-ris-ide] 没有 /mnt/c:当前环境不是 WSL,跳过 Windows 版 ProxyBridge 的复制(本机不会运行 Windows 侧)。')
361
+ }
362
+ localAppDataCache = { value: '', at: now }
363
+ return ''
364
+ }
365
+ try {
366
+ const out = spawnSync('cmd.exe', ['/d', '/s', '/c', 'echo %LOCALAPPDATA%'], { encoding: 'utf8', timeout: 5000 })
367
+ const value = String(out.stdout ?? '').trim()
368
+ const resolved = /^[A-Za-z]:[\\/]/.test(value) === true ? value : ''
369
+ localAppDataCache = { value: resolved, at: now }
370
+ return resolved
371
+ } catch {
372
+ localAppDataCache = { value: '', at: now }
373
+ return ''
374
+ }
375
+ }
376
+
377
+ /** Test seam: where the Windows bundle should land (production: `%LOCALAPPDATA%`). */
378
+ function bundleTargetDir(platform) {
379
+ if (typeof probeHooks.bundleTarget === 'function') return String(probeHooks.bundleTarget({ platform }) ?? '')
380
+ return windowsBundleDir({ platform })
381
+ }
382
+
383
+ /**
384
+ * Where the Windows side runs the materialised CLI from.
385
+ *
386
+ * The Windows redirector must run on the Windows side of the boundary, so the
387
+ * binary cannot stay inside the Linux filesystem (`\\wsl$` executables are not
388
+ * reliable): it is materialized under `%LOCALAPPDATA%\dsh-ris-ide\proxybridge` and,
389
+ * on WSL, addressed through `/mnt/<drive>`.
390
+ * @param {{platform?: string}} [options] - overrides for tests.
391
+ * @returns {string} posix path on WSL, native path on Windows, '' when unknown.
392
+ */
393
+ export function windowsBundleDir(options = {}) {
394
+ const platform = options.platform ?? process.platform
395
+ const local = platform === 'win32'
396
+ ? (process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'))
397
+ : windowsToPosixPath(windowsLocalAppData())
398
+ if (local === '') return ''
399
+ return join(local, 'dsh-ris-ide', 'proxybridge', 'windows')
400
+ }
401
+
402
+ let windowsBundlePrepared = null // { dir, fingerprint } of a complete copy; failures are never cached
403
+ /** How different a copied file's mtime may be from its source before we re-copy. */
404
+ const BUNDLE_MTIME_TOLERANCE_MS = 2000
405
+ /**
406
+ * Where the "which bundle is materialised where" record lives. It sits in the proxy
407
+ * home, not next to the copies: `%LOCALAPPDATA%` only ever holds the bundle files
408
+ * (users and antivirus look at that folder), while this record must survive a
409
+ * daemon restart so a bundle installed in the meantime still refreshes the Windows
410
+ * side on the next start (review B-P1-2).
411
+ */
412
+ const MATERIALISED_STATE_FILENAME = 'windows-materialised.json'
413
+
414
+ function materialisedStatePath() {
415
+ return join(proxyHomeDir(), REDIRECTOR_DIRNAME, MATERIALISED_STATE_FILENAME)
416
+ }
417
+
418
+ /** @returns {string} fingerprint recorded for `target`, or '' when absent/unreadable. */
419
+ function materialisedFingerprint(target) {
420
+ try {
421
+ const state = JSON.parse(readFileSync(materialisedStatePath(), 'utf8'))
422
+ return state !== null && typeof state === 'object' && state.dir === target && typeof state.fingerprint === 'string' ? state.fingerprint : ''
423
+ } catch {
424
+ return ''
425
+ }
426
+ }
427
+
428
+ /** Record which bundle a materialised copy was made from (best effort). */
429
+ function rememberMaterialised(target, fingerprint) {
430
+ try {
431
+ const file = materialisedStatePath()
432
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
433
+ writeFileSync(file, `${JSON.stringify({ dir: target, fingerprint, at: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 })
434
+ } catch {
435
+ // The marker only saves a re-copy; failing to write it must not fail the launch.
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Copy one bundle file unless the target already matches (size + mtime).
441
+ * `force` copies even when the metadata looks identical: a new bundle can have the
442
+ * same byte count and an mtime within the tolerance window, and then the Windows
443
+ * side would keep running the previous DLLs (review B-P1-2).
444
+ */
445
+ function copyBundleFile(from, to, options = {}) {
446
+ if (existsSync(from) !== true) return false
447
+ const source = statSync(from)
448
+ if (options.force !== true && existsSync(to) === true) {
449
+ const existing = statSync(to)
450
+ // Size AND mtime: a plugin update can ship the same byte count with new bits.
451
+ if (existing.size === source.size && Math.abs(existing.mtimeMs - source.mtimeMs) <= BUNDLE_MTIME_TOLERANCE_MS) return true
452
+ }
453
+ mkdirSync(dirname(to), { recursive: true })
454
+ copyFileSync(from, to)
455
+ // `copyFileSync` stamps "now"; carry the source mtime so the next call can tell a
456
+ // fresh copy from a stale one instead of re-copying the megabytes every time.
457
+ utimesSync(to, source.atime, source.mtime)
458
+ return true
459
+ }
460
+
461
+ /**
462
+ * Materialise the cached Windows files next to each other (idempotent). Run before
463
+ * any Windows-side launch: a Windows process cannot execute a binary that only
464
+ * lives in the Linux filesystem, and the copy must follow the *current* bundle —
465
+ * the cache is keyed by {@link bundleFingerprint}, so a newly downloaded/uploaded
466
+ * bundle always refreshes the Windows copy (review B-P1-2).
467
+ *
468
+ * A failed run is deliberately NOT cached: the next call retries (a missing
469
+ * `%LOCALAPPDATA%` probe or a locked file can heal on its own). Only a complete
470
+ * copy is remembered.
471
+ * @param {{force?: boolean, platform?: string, targetDir?: string}} [options] - overrides for tests.
472
+ * @returns {string|undefined} the folder holding a complete CLI bundle; `''` when no
473
+ * Windows-addressable target exists; `undefined` when the distribution itself is
474
+ * not installed yet (caller must show "未安装,请下载/上传").
475
+ */
476
+ export function prepareWindowsBundle(options = {}) {
477
+ const fingerprint = bundleFingerprint()
478
+ if (options.force !== true && windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint === fingerprint) {
479
+ // The folder can disappear between calls (user cleanup); redo it rather than
480
+ // hand out a path that no longer holds the CLI.
481
+ if (existsSync(join(windowsBundlePrepared.dir, 'ProxyBridge_CLI.exe')) === true) return windowsBundlePrepared.dir
482
+ windowsBundlePrepared = null
483
+ }
484
+ // No distribution cached yet: there is nothing to copy, and silently pointing at
485
+ // a path that will never appear is exactly the failure this round removes.
486
+ if (bundleIsInstalled(bundledBundleDir()) !== true) return undefined
487
+ const platform = options.platform ?? process.platform
488
+ const target = options.targetDir ?? bundleTargetDir(platform)
489
+ if (target === '') return ''
490
+ // A copy that belongs to a different bundle fingerprint must be replaced, even
491
+ // when the files look identical by size+mtime. Compare against the on-disk marker
492
+ // too: the in-memory cache is empty after a daemon restart.
493
+ const refresh = options.force === true
494
+ || (windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint !== fingerprint)
495
+ || materialisedFingerprint(target) !== fingerprint
496
+ const source = bundledRedirectorDir({ platform: 'win32' })
497
+ const names = ['ProxyBridge_CLI.exe', 'ProxyBridgeCore.dll', 'WinDivert.dll', 'WinDivert64.sys']
498
+ let complete = true
499
+ for (const name of names) {
500
+ try {
501
+ if (copyBundleFile(join(source, name), join(target, name), { force: refresh }) !== true) complete = false
502
+ } catch {
503
+ complete = false
504
+ }
505
+ }
506
+ // The licence texts live at the root of the cached distribution (they cover both
507
+ // platforms). They are not needed to run the CLI, so a failure here must not make
508
+ // the bundle unusable — but an LGPL/MIT redistribution should carry them.
509
+ const licenceDir = bundledBundleDir()
510
+ for (const name of ['NOTICE.md', 'LICENSE-ProxyBridge.txt']) {
511
+ try {
512
+ copyBundleFile(join(licenceDir, name), join(target, name), { force: refresh })
513
+ } catch {
514
+ // best-effort: the CLI still runs
515
+ }
516
+ }
517
+ // Only the machine-wide materialisation is worth caching; a caller passing
518
+ // targetDir is testing (or preparing an explicit folder) and must not poison it.
519
+ if (complete === true) rememberMaterialised(target, fingerprint)
520
+ if (options.targetDir === undefined) windowsBundlePrepared = complete ? { dir: target, fingerprint } : null
521
+ return complete ? target : ''
522
+ }
523
+
524
+ /** Actionable text for "the distribution was never downloaded/uploaded". */
525
+ export const MISSING_BUNDLE_HINT = `ProxyBridge 组件未安装:打开 risd 维护页「代理 → 组件」点「下载」(或上传 ris-proxy.tgz);也可设 DSH_RIS_IDE_PROXYBRIDGE_URL 指向 tgz。默认地址:${DEFAULT_BUNDLE_URL}`
526
+
527
+ /**
528
+ * Candidate locations of the redirector CLI, per side of the OS boundary.
529
+ *
530
+ * There are two different jobs, so the two sides are reported separately:
531
+ * - `local` runs where this process runs (Linux in WSL) and proxies OUR
532
+ * processes — the backend, git, npm.
533
+ * - `windows` runs on the Windows host and proxies ITS processes — Navicat,
534
+ * the IDE's java.
535
+ * Inside WSL both exist and neither replaces the other. An explicit
536
+ * `DSH_RIS_IDE_PROXYBRIDGE` pins one path (tests, unusual installs) and is
537
+ * reported on both sides.
538
+ *
539
+ * The distribution is not shipped any more, so the first "built-in" candidate is
540
+ * the downloaded cache (`~/.dsh-ris-ide/proxybridge/bundle`). When it is absent the
541
+ * list still carries the expected paths (so diagnostics can show them) and the
542
+ * non-enumerable `missingBundle` flag is set for the caller.
543
+ * @param {{platform?: string, side?: 'local'|'windows', installDir?: string, bundleDir?: string}} [options] - overrides for tests.
544
+ * @returns {string[]} absolute candidate paths, most specific first, plus
545
+ * non-enumerable `bundleDir` / `bundleInstalled` / `missingBundle` fields.
546
+ */
547
+ export function redirectorCandidates(options = {}) {
548
+ const platform = options.platform ?? process.platform
549
+ const side = options.side ?? 'local'
550
+ const override = process.env.DSH_RIS_IDE_PROXYBRIDGE
551
+ const installRoot = options.installDir ?? bundledBundleDir()
552
+ const installed = bundleIsInstalled(installRoot)
553
+ const list = []
554
+ if (typeof override === 'string' && override !== '') list.push(override)
555
+ // The downloaded cache is the primary source; the materialised windows folder is
556
+ // only known to the caller that prepared it (findRedirector), never guessed here.
557
+ const materialised = typeof options.bundleDir === 'string' ? options.bundleDir : ''
558
+ if (platform === 'win32') {
559
+ if (materialised !== '') list.push(join(materialised, 'ProxyBridge_CLI.exe'))
560
+ list.push(join(installRoot, 'windows', 'ProxyBridge_CLI.exe'))
561
+ // Manual extraction (old installs) and a machine-wide install as fallbacks.
562
+ list.push(join(redirectorVendorDir({ platform: 'win32' }), 'ProxyBridge_CLI.exe'))
563
+ for (const drive of ['c', 'd', 'e', 'f']) {
564
+ list.push(`${drive.toUpperCase()}:\\Program Files\\ProxyBridge\\ProxyBridge_CLI.exe`)
565
+ }
566
+ return decorateCandidates(list, installRoot, installed)
567
+ }
568
+ if (side === 'windows') {
569
+ if (materialised !== '') list.push(join(materialised, 'ProxyBridge_CLI.exe'))
570
+ list.push(join(installRoot, 'windows', 'ProxyBridge_CLI.exe'))
571
+ list.push(join(redirectorVendorDir({ platform: 'win32' }), 'ProxyBridge_CLI.exe'))
572
+ // A pre-existing install, reached through /mnt. Offsets are the common ones.
573
+ for (const drive of ['d', 'c', 'e']) list.push(`/mnt/${drive}/Program Files/ProxyBridge/ProxyBridge_CLI.exe`)
574
+ return decorateCandidates(list, installRoot, installed)
575
+ }
576
+ // Local side: the downloaded cache first, then a manual extraction, then whatever
577
+ // a package manager put on PATH.
578
+ list.push(join(installRoot, 'linux', 'ProxyBridge'))
579
+ list.push(join(redirectorVendorDir({ platform }), 'ProxyBridge'))
580
+ list.push('/usr/local/bin/ProxyBridge')
581
+ list.push('/usr/bin/ProxyBridge')
582
+ return decorateCandidates(list, installRoot, installed)
583
+ }
584
+
585
+ /**
586
+ * Attach the bundle diagnosis to a candidate list without changing its array shape
587
+ * (callers iterate it; `deepEqual` against a plain array must keep working).
588
+ */
589
+ function decorateCandidates(list, installRoot, installed) {
590
+ Object.defineProperty(list, 'bundleDir', { value: installRoot, enumerable: false })
591
+ Object.defineProperty(list, 'bundleInstalled', { value: installed === true, enumerable: false })
592
+ Object.defineProperty(list, 'missingBundle', { value: installed !== true, enumerable: false })
593
+ return list
594
+ }
595
+ /**
596
+ * Start the system-level interception for one side of the OS boundary.
597
+ *
598
+ * Elevation is expected, not an error: Windows raises a UAC prompt (through one
599
+ * elevated helper that also stops the GUI's service and clears a stale CLI), Linux
600
+ * needs root for eBPF and can only proceed when sudo is passwordless.
601
+ * @param {{side?: 'local'|'windows', verbose?: number, profilePath?: string}} [options] - side to start.
602
+ * @returns {Promise<{started: boolean, side: string, pid?: number, command: string, reason?: string}>} outcome.
603
+ */
604
+
605
+ /** Liveness signal the unelevated host keeps touching while dsh is alive. */
606
+ export const HEARTBEAT_FILENAME = 'janitor-heartbeat'
607
+ /** Written by a normal stop: the watchdog stands down instead of cleaning up. */
608
+ export const STOP_REQUEST_FILENAME = 'proxybridge-stop.request'
609
+ /** Written by the watchdog once it has torn the bridge down. */
610
+ export const STOPPED_MARKER_FILENAME = 'proxybridge-stop.done'
611
+ /** The generated elevated watchdog script. */
612
+ export const WATCHDOG_SCRIPT_FILENAME = 'proxybridge-watchdog.ps1'
613
+ /** Where the watchdog's pid is recorded. */
614
+ export const WATCHDOG_STATE_FILENAME = 'proxybridge-watchdog.json'
615
+ /** "reload the rules" request: the watchdog restarts the CLI with the same profile. */
616
+ export const RELOAD_REQUEST_FILENAME = 'proxybridge-reload.request'
617
+ /** Written by the watchdog once the CLI came back with the new profile. */
618
+ export const RELOAD_DONE_FILENAME = 'proxybridge-reload.done'
619
+ /** Written instead of the done file when the restart failed (structured reason). */
620
+ export const RELOAD_FAILED_FILENAME = 'proxybridge-reload.failed'
621
+ /** The CLI invocation kept around so the elevated watchdog can restart it. */
622
+ export const CLI_SPEC_FILENAME = 'proxybridge-cli.json'
623
+
624
+ /** Heartbeat file inside the machine-level proxy home. */
625
+ export function heartbeatPath() {
626
+ return join(proxyHomeDir(), HEARTBEAT_FILENAME)
627
+ }
628
+
629
+ /** Touch the heartbeat (cheap: the file's mtime is the whole protocol). */
630
+ export function writeHeartbeat() {
631
+ try {
632
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
633
+ const now = new Date()
634
+ writeFileSync(heartbeatPath(), `${now.toISOString()}\n`, { mode: 0o600 })
635
+ utimesSync(heartbeatPath(), now, now)
636
+ return true
637
+ } catch {
638
+ return false
639
+ }
640
+ }
641
+
642
+ /** @returns {number} age of the heartbeat in ms, or Infinity when missing. */
643
+ export function heartbeatAgeMs() {
644
+ try {
645
+ return Date.now() - statSync(heartbeatPath()).mtimeMs
646
+ } catch {
647
+ return Number.POSITIVE_INFINITY
648
+ }
649
+ }
650
+
651
+ /** Path of the "please stop" request file. */
652
+ export function stopRequestPath() {
653
+ return join(proxyHomeDir(), STOP_REQUEST_FILENAME)
654
+ }
655
+
656
+ /** Path of the "the watchdog stopped it" marker. */
657
+ export function stoppedMarkerPath() {
658
+ return join(proxyHomeDir(), STOPPED_MARKER_FILENAME)
659
+ }
660
+
661
+ /** Clear both signals; called when a bridge starts. */
662
+ export function clearStopSignals() {
663
+ for (const path of [stopRequestPath(), stoppedMarkerPath()]) {
664
+ try { unlinkSync(path) } catch { /* absent */ }
665
+ }
666
+ }
667
+
668
+ /** Ask the watchdog to tear the bridge down (no elevation needed: it has it). */
669
+ export function requestRedirectorStop() {
670
+ try {
671
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
672
+ // A done file left by an earlier stop (or written by a concurrent watchdog
673
+ // answer) would make the wait below return immediately and report a teardown
674
+ // that never happened, so the request removes it first — same rule the reload
675
+ // handshake already follows (review B-P2-7).
676
+ try { unlinkSync(stoppedMarkerPath()) } catch { /* absent */ }
677
+ writeFileSync(stopRequestPath(), `${new Date().toISOString()}\n`, { mode: 0o600 })
678
+ return true
679
+ } catch {
680
+ return false
681
+ }
682
+ }
683
+
684
+ /** @returns {boolean} true when the watchdog reported the teardown finished. */
685
+ export function stopCompleted() {
686
+ try {
687
+ return statSync(stoppedMarkerPath()).isFile()
688
+ } catch {
689
+ return false
690
+ }
691
+ }
692
+
693
+ /** Path of the reload request file. */
694
+ export function reloadRequestPath() {
695
+ return join(proxyHomeDir(), RELOAD_REQUEST_FILENAME)
696
+ }
697
+
698
+ /** Path of the reload-completed marker (structured JSON since the B4 fix). */
699
+ export function reloadDonePath() {
700
+ return join(proxyHomeDir(), RELOAD_DONE_FILENAME)
701
+ }
702
+
703
+ /** Path of the reload failure marker (written when the watchdog could not restart). */
704
+ export function reloadFailedPath() {
705
+ return join(proxyHomeDir(), RELOAD_FAILED_FILENAME)
706
+ }
707
+
708
+ /**
709
+ * Ask the watchdog to restart the bridge with the profile on disk.
710
+ *
711
+ * The CLI reads its profile once at start, so edited rules mean a restart. Doing
712
+ * that from here would need another UAC; the watchdog is already elevated, so it
713
+ * does it instead (kill + start with the recorded spec).
714
+ *
715
+ * Every request carries an id so a late answer from an older request (or a
716
+ * leftover done file) is never mistaken for this one.
717
+ * @param {{id?: string}} [options] - request id; generated when omitted.
718
+ * @returns {boolean} true when the request was written.
719
+ */
720
+ export function requestRedirectorReload(options = {}) {
721
+ try {
722
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
723
+ for (const path of [reloadDonePath(), reloadFailedPath()]) {
724
+ try { unlinkSync(path) } catch { /* absent */ }
725
+ }
726
+ const id = typeof options.id === 'string' && options.id !== '' ? options.id : `reload-${randomUUID()}`
727
+ writeFileSync(reloadRequestPath(), `${JSON.stringify({ id, at: Date.now() })}\n`, { mode: 0o600 })
728
+ return true
729
+ } catch {
730
+ return false
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Parse a watchdog reload report.
736
+ *
737
+ * The report is structured (`{ok, id, pid, count, error}`) so "the file exists"
738
+ * no longer means "the restart worked": the old watchdog wrote the done file even
739
+ * when the spec was missing or Start-Process threw, and the host then told the
740
+ * user the new rules were live while the CLI kept the old profile.
741
+ * A legacy bare-timestamp file is accepted as "restarted" but carries no pid.
742
+ * @param {string} path - done or failed marker.
743
+ * @returns {{ok: boolean, id: string, pid: number, count: number, error: string, legacy: boolean}|null} report, or null when absent.
744
+ */
745
+ export function readReloadResult(path) {
746
+ let raw = ''
747
+ try {
748
+ raw = readFileSync(path, 'utf8').trim()
749
+ } catch {
750
+ return null
751
+ }
752
+ if (raw === '') return { ok: true, id: '', pid: 0, count: 0, error: '', legacy: true }
753
+ try {
754
+ const parsed = JSON.parse(raw)
755
+ return {
756
+ ok: parsed?.ok === true,
757
+ id: typeof parsed?.id === 'string' ? parsed.id : '',
758
+ pid: Number.isInteger(parsed?.pid) ? parsed.pid : 0,
759
+ count: Number.isInteger(parsed?.count) ? parsed.count : 0,
760
+ error: typeof parsed?.error === 'string' ? parsed.error : '',
761
+ legacy: false,
762
+ }
763
+ } catch {
764
+ // Older watchdogs wrote the request timestamp here; "restarted" is all it says.
765
+ return { ok: true, id: '', pid: 0, count: 0, error: '', legacy: true }
766
+ }
767
+ }
768
+
769
+ /** @returns {object|null} the watchdog's success report. */
770
+ export function readReloadDone() {
771
+ return readReloadResult(reloadDonePath())
772
+ }
773
+
774
+ /** @returns {object|null} the watchdog's failure report. */
775
+ export function readReloadFailure() {
776
+ return readReloadResult(reloadFailedPath())
777
+ }
778
+
779
+ /**
780
+ * @param {{id?: string}} [options] - only accept the answer to this request id.
781
+ * @returns {boolean} true when the watchdog reports a successful restart.
782
+ */
783
+ export function reloadCompleted(options = {}) {
784
+ const done = readReloadDone()
785
+ if (done === null || done.ok !== true) return false
786
+ if (typeof options.id === 'string' && options.id !== '' && done.legacy !== true && done.id !== '' && done.id !== options.id) return false
787
+ return true
788
+ }
789
+
790
+ /** Clear the reload signals (start, stop, or after the caller saw them). */
791
+ export function clearReloadSignals() {
792
+ for (const path of [reloadRequestPath(), reloadDonePath(), reloadFailedPath()]) {
793
+ try { unlinkSync(path) } catch { /* absent */ }
794
+ }
795
+ }
796
+
797
+ /** Remember how the CLI was launched, so a reload can repeat it verbatim. */
798
+ export function writeCliSpec(spec) {
799
+ try {
800
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
801
+ writeFileSync(join(proxyHomeDir(), CLI_SPEC_FILENAME), `${JSON.stringify(spec, null, 2)}\n`, { mode: 0o600 })
802
+ return true
803
+ } catch {
804
+ return false
805
+ }
806
+ }
807
+
808
+ /** @returns {{exe: string, args: string[], log: string}|null} recorded CLI invocation. */
809
+ export function readCliSpec() {
810
+ try {
811
+ const parsed = JSON.parse(readFileSync(join(proxyHomeDir(), CLI_SPEC_FILENAME), 'utf8'))
812
+ if (typeof parsed?.exe !== 'string' || Array.isArray(parsed?.args) !== true) return null
813
+ return { exe: parsed.exe, args: parsed.args.map(String), log: typeof parsed.log === 'string' ? parsed.log : '' }
814
+ } catch {
815
+ return null
816
+ }
817
+ }
818
+
819
+ /** Path of the generated watchdog script. */
820
+ export function watchdogScriptPath() {
821
+ return join(proxyHomeDir(), WATCHDOG_SCRIPT_FILENAME)
822
+ }
823
+
824
+ /** Record the running watchdog so a stop can find it. */
825
+ export function writeWatchdogPid(pid) {
826
+ try {
827
+ writeFileSync(join(proxyHomeDir(), WATCHDOG_STATE_FILENAME), `${JSON.stringify({ pid }, null, 2)}\n`, { mode: 0o600 })
828
+ } catch { /* best effort */ }
829
+ }
830
+
831
+ /** @returns {number} recorded watchdog pid (0 when unknown). */
832
+ export function watchdogPid() {
833
+ try {
834
+ const parsed = JSON.parse(readFileSync(join(proxyHomeDir(), WATCHDOG_STATE_FILENAME), 'utf8'))
835
+ return Number.isInteger(parsed?.pid) ? parsed.pid : 0
836
+ } catch {
837
+ return 0
838
+ }
839
+ }
840
+
841
+ /**
842
+ * The elevated watchdog: tears down what we cannot.
843
+ *
844
+ * Killing an elevated ProxyBridge_CLI and restoring ProxyBridgeSvc need admin
845
+ * rights, which the host process does not have and must not ask for twice. So the
846
+ * one elevation we do at start also spawns this loop. Two triggers end it: a stop
847
+ * request (normal shutdown) or a stale heartbeat (dsh was killed, closed, or
848
+ * crashed). Either way it kills the CLI, puts the service back, and drops a marker.
849
+ * @param {{heartbeat: string, stateFile: string, logFile: string, stopRequest: string, stoppedMarker: string, cliSpec?: string, reloadRequest?: string, reloadDone?: string, reloadFailed?: string}} paths - Windows paths.
850
+ * @returns {string} the script text.
851
+ */
852
+ export function windowsWatchdogScript(paths) {
853
+ const quote = (value) => `'${String(value).replace(/'/g, "''")}'`
854
+ return `$ErrorActionPreference = 'SilentlyContinue'
855
+ $hb = ${quote(paths.heartbeat)}
856
+ $stateFile = ${quote(paths.stateFile)}
857
+ $logFile = ${quote(paths.logFile)}
858
+ $stopFile = ${quote(paths.stopRequest)}
859
+ $doneFile = ${quote(paths.stoppedMarker)}
860
+
861
+ function Write-Log($message) {
862
+ Add-Content -Path $logFile -Value ("{0} [watchdog] {1}" -f (Get-Date -Format o), $message)
863
+ }
864
+
865
+ Write-Log "started pid=$PID"
866
+ $specFile = ${quote(paths.cliSpec ?? '')}
867
+ $reloadFile = ${quote(paths.reloadRequest ?? '')}
868
+ $reloadDone = ${quote(paths.reloadDone ?? '')}
869
+ $reloadFailed = ${quote(paths.reloadFailed ?? '')}
870
+
871
+ $reason = ''
872
+ while ($true) {
873
+ Start-Sleep -Seconds 2
874
+ if (Test-Path $stopFile) { $reason = 'stop-request'; break }
875
+ if (Test-Path $reloadFile) {
876
+ # Rules changed: the CLI reads its profile only at start, so restart it here
877
+ # (no second UAC — this process is already elevated). The report is structured
878
+ # and truthful: a done file may only claim success when the new process is up.
879
+ $requestId = ''
880
+ try { $requestId = [string](Get-Content -Path $reloadFile -Raw | ConvertFrom-Json).id } catch { $requestId = '' }
881
+ $pidText = ''
882
+ $count = 0
883
+ $errorText = ''
884
+ Write-Log 'reloading'
885
+ try {
886
+ if (-not (Test-Path $specFile)) { throw 'no cli spec' }
887
+ $spec = Get-Content -Path $specFile -Raw | ConvertFrom-Json
888
+ Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force
889
+ Start-Sleep -Milliseconds 400
890
+ Start-Process -FilePath $spec.exe -ArgumentList @($spec.args) -WindowStyle Hidden -RedirectStandardOutput $spec.log -RedirectStandardError ($spec.log + '.err') | Out-Null
891
+ Start-Sleep -Milliseconds 1500
892
+ # Liveness alone is not enough: the host's old CLI may still be dying, and
893
+ # ProxyBridge.exe is a different process. Match the profile on the command line.
894
+ $profileArg = [string]$spec.args[1]
895
+ $cim = @(Get-CimInstance Win32_Process -Filter "Name='ProxyBridge_CLI.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID })
896
+ $running = @($cim | Where-Object { $profileArg -ne '' -and $_.CommandLine -like ('*' + $profileArg + '*') })
897
+ $count = $running.Count
898
+ if ($count -gt 0) { $pidText = [string]$running[0].ProcessId } else { $errorText = 'the new CLI is not running with the recorded profile' }
899
+ } catch {
900
+ $errorText = $_.Exception.Message
901
+ }
902
+ # A failed restart leaves the machine WITHOUT interception: record the failure
903
+ # and let the host tell the user, instead of faking "reloaded".
904
+ if ($errorText -eq '') {
905
+ Remove-Item $reloadFailed -Force -ErrorAction SilentlyContinue
906
+ (@{ ok = $true; id = $requestId; pid = [int]$pidText; count = $count } | ConvertTo-Json -Compress) | Set-Content -Path $reloadDone -Encoding utf8
907
+ Write-Log ("reloaded pid=" + $pidText + " count=" + $count)
908
+ } else {
909
+ Remove-Item $reloadDone -Force -ErrorAction SilentlyContinue
910
+ (@{ ok = $false; id = $requestId; pid = 0; count = $count; error = $errorText } | ConvertTo-Json -Compress) | Set-Content -Path $reloadFailed -Encoding utf8
911
+ Write-Log ("reload failed: " + $errorText)
912
+ }
913
+ Remove-Item $reloadFile -Force -ErrorAction SilentlyContinue
914
+ continue
915
+ }
916
+ $fresh = $false
917
+ if (Test-Path $hb) {
918
+ $age = ((Get-Date) - (Get-Item $hb).LastWriteTime).TotalSeconds
919
+ if ($age -lt 20) { $fresh = $true }
920
+ }
921
+ if (-not $fresh) { $reason = 'heartbeat-stale'; break }
922
+ }
923
+
924
+ Write-Log "cleaning up ($reason)"
925
+ Remove-Item $reloadFile -Force -ErrorAction SilentlyContinue
926
+ Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force
927
+ if (Test-Path $stateFile) {
928
+ # Give the GUI service its hook back: undo the park we did at start.
929
+ $state = Get-Content -Path $stateFile -Raw | ConvertFrom-Json
930
+ if ($state.originalStartType) { Set-Service -Name ProxyBridgeSvc -StartupType $state.originalStartType -ErrorAction SilentlyContinue }
931
+ $svc = Get-Service -Name ProxyBridgeSvc -ErrorAction SilentlyContinue
932
+ if ($svc -ne $null -and $svc.Status -ne 'Running') { Start-Service -Name ProxyBridgeSvc -ErrorAction SilentlyContinue }
933
+ }
934
+ New-Item -ItemType File -Path $doneFile -Force | Out-Null
935
+ Write-Log 'cleaned up'
936
+ `
937
+ }
938
+
939
+ /**
940
+ * Translate a Windows path into the /mnt form Linux can read.
941
+ *
942
+ * The picker browses Windows folders from inside WSL, so both spellings are needed:
943
+ * the UI edits `D:\Program Files\…`, the filesystem needs `/mnt/d/Program Files/…`.
944
+ * @param {string} value - Windows path (`D:\x`, `D:/x`).
945
+ * @returns {string} posix path, or '' when it is not a Windows drive path.
946
+ */
947
+ export function windowsToPosixPath(value) {
948
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(String(value ?? '').trim())
949
+ if (match === null) return ''
950
+ const rest = match[2].replace(/\\/g, '/')
951
+ return `/mnt/${match[1].toLowerCase()}/${rest}`.replace(/\/+$/, '') || `/mnt/${match[1].toLowerCase()}`
952
+ }
953
+
954
+ /**
955
+ * The reverse: `/mnt/d/x` → `D:\x`. Anything else is returned unchanged.
956
+ * @param {string} value - posix path.
957
+ * @returns {string} Windows path.
958
+ */
959
+ export function posixToWindowsPath(value) {
960
+ const match = /^\/mnt\/([A-Za-z])(\/.*)?$/.exec(String(value ?? '').trim())
961
+ if (match === null) return String(value ?? '')
962
+ const rest = (match[2] ?? '').replace(/\//g, '\\')
963
+ return `${match[1].toUpperCase()}:${rest === '' ? '\\' : rest}`
964
+ }
965
+
966
+ /** Write the watchdog script and return its WINDOWS path (it runs over there). */
967
+ export function writeWatchdogScript() {
968
+ const script = windowsWatchdogScript({
969
+ heartbeat: windowsPathOf(heartbeatPath()),
970
+ // The canonical writer path: the watchdog's teardown reads exactly this file.
971
+ stateFile: windowsPathOf(serviceStatePath()),
972
+ logFile: windowsPathOf(windowsLogLocalPath()),
973
+ stopRequest: windowsPathOf(stopRequestPath()),
974
+ stoppedMarker: windowsPathOf(stoppedMarkerPath()),
975
+ cliSpec: windowsPathOf(join(proxyHomeDir(), CLI_SPEC_FILENAME)),
976
+ reloadRequest: windowsPathOf(reloadRequestPath()),
977
+ reloadDone: windowsPathOf(reloadDonePath()),
978
+ reloadFailed: windowsPathOf(reloadFailedPath()),
979
+ })
980
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
981
+ writeFileSync(watchdogScriptPath(), script, { mode: 0o600 })
982
+ return windowsPathOf(watchdogScriptPath())
983
+ }
984
+
985
+ export async function startRedirector(options = {}) {
986
+ const side = options.side === 'windows' ? 'windows' : 'local'
987
+ // Resolve the binary BEFORE writing the profile: without a CLI the profile is
988
+ // useless, and "no ProxyBridge" is a much better answer than "no rules".
989
+ const found = findRedirector({ side })
990
+ if (found.found !== true) {
991
+ // A missing download is not "no rules": say what to install and where.
992
+ return { started: false, side, command: '', reason: found.reason ?? (side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge'), missingBundle: found.missingBundle === true }
993
+ }
994
+ const profile = writeRedirectorProfile(readProxyConfig(''), { path: options.profilePath })
995
+ const plan = redirectorCommand({ cliPath: found.path, profilePath: profile.path, verbose: options.verbose, platform: side === 'windows' ? 'win32' : 'linux' })
996
+ const running = detectRunningRedirector()
997
+ // Per side: the other side's process must not make this start look redundant.
998
+ const sameSide = IS_WINDOWS === true ? running.windows : side === 'windows' ? running.windows : running.local
999
+ if (sameSide.pid > 0) {
1000
+ if (side !== 'windows' || IS_WINDOWS === true) return { started: false, side, pid: sameSide.pid, command: plan.display, reason: '已在运行(先停止)' }
1001
+ // Windows: the engine may be a hand-started CLI, or one whose pid file we lost.
1002
+ // It still holds the hook, so take it over instead of refusing to start.
1003
+ const killed = await killWindowsCliProcesses()
1004
+ if (killed.ok !== true) {
1005
+ return { started: false, side, pid: sameSide.pid, command: plan.display, reason: killed.reason ?? '已有 ProxyBridge_CLI 在运行,且无法结束它' }
1006
+ }
1007
+ clearRedirectorPid('windows')
1008
+ }
1009
+ if (side === 'windows') {
1010
+ // PowerShell resolves paths as WINDOWS does: /mnt/d/… is invisible there, and the
1011
+ // profile we just wrote lives in the Linux home. Both have to be translated.
1012
+ const exePath = windowsPathOf(found.path)
1013
+ const winArgs = windowsArgsOf(plan.args)
1014
+ const winLog = windowsPathOf(windowsLogPath())
1015
+ // Fresh start: no stale stop request may remain, and the heartbeat has to exist
1016
+ // BEFORE the watchdog looks at it (a missing file counts as stale).
1017
+ clearStopSignals()
1018
+ clearReloadSignals()
1019
+ writeHeartbeat()
1020
+ const watchdogScript = writeWatchdogScript()
1021
+ const quote = (value) => `'${String(value).replace(/'/g, "''")}'`
1022
+ // One elevated helper does the whole dance: the GUI's service and the CLI both
1023
+ // want the WinDivert handle (mutually exclusive), a stale CLI has to go, and only
1024
+ // an already-elevated process may redirect the CLI's output (-Verb RunAs cannot
1025
+ // redirect). So: stop service → kill stale CLI → start CLI with logs → report.
1026
+ const script = [
1027
+ '$svcWas = $false',
1028
+ '$svc = Get-Service ProxyBridgeSvc -ErrorAction SilentlyContinue',
1029
+ '$startType = $null',
1030
+ "if ($svc -ne $null) { $startType = $svc.StartType.ToString() }",
1031
+ "if ($svc -ne $null -and $svc.Status -eq 'Running') { Stop-Service ProxyBridgeSvc -Force -ErrorAction SilentlyContinue; $svcWas = $true; Start-Sleep -Milliseconds 900 }",
1032
+ // Only one process may own the WinDivert handle: if the service survived the
1033
+ // stop it will keep intercepting while our CLI silently captures nothing.
1034
+ "if ($svc -ne $null -and (Get-Service ProxyBridgeSvc -ErrorAction SilentlyContinue).Status -eq 'Running') { 'svcRunning=True;done=1'; return }",
1035
+ // An Automatic service comes back minutes later and silently steals the
1036
+ // WinDivert handle: our CLI then runs without capturing anything (rules load,
1037
+ // no [CONN] lines) while every connection fails. Park it on Manual instead.
1038
+ "if ($svc -ne $null -and $startType -eq 'Automatic') { Set-Service ProxyBridgeSvc -StartupType Manual -ErrorAction SilentlyContinue; $parked = $true }",
1039
+ 'Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue',
1040
+ 'Start-Sleep -Milliseconds 500',
1041
+ `$log = ${quote(winLog)}`,
1042
+ 'if (Test-Path $log) { Remove-Item $log -Force -ErrorAction SilentlyContinue }',
1043
+ `$argList = @(${winArgs.map(quote).join(',')})`,
1044
+ `$p = Start-Process -FilePath ${quote(exePath)} -ArgumentList $argList -PassThru -WindowStyle Hidden -RedirectStandardOutput $log -RedirectStandardError ($log + '.err')`,
1045
+ 'Start-Sleep -Milliseconds 2000',
1046
+ '$alive = [bool](Get-Process -Id $p.Id -ErrorAction SilentlyContinue)',
1047
+ // Two CLIs would both try to bind WinDivert: keep ours, drop anything else
1048
+ // (a leftover from an earlier session, or one the IDE started meanwhile).
1049
+ '$all = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue)',
1050
+ '$dups = $all.Count - 1',
1051
+ 'if ($dups -gt 0) { $all | Where-Object { $_.Id -ne $p.Id } | Stop-Process -Force -ErrorAction SilentlyContinue; Start-Sleep -Milliseconds 500 }',
1052
+ '$final = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue).Count',
1053
+ // Killing an elevated CLI and restarting the service need admin, which we only
1054
+ // have inside this script: spawn the watchdog here so teardown never asks for
1055
+ // a second UAC (it ends on a stop request or when the heartbeat goes stale).
1056
+ `$wd = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File', ${quote(watchdogScript)}) -PassThru -WindowStyle Hidden`,
1057
+ 'Start-Sleep -Milliseconds 400',
1058
+ '"pid=$($p.Id);svc=$svcWas;startType=$startType;parked=$([bool]$parked);alive=$alive;dups=$dups;count=$final;watchdog=$($wd.Id);done=1"',
1059
+ ].join('; ')
1060
+ const elevated = await psElevated(script, 45000)
1061
+ // B1: no report for THIS run means the start did not happen — never parse the
1062
+ // previous run's leftover output (it looked like success with a dead pid).
1063
+ if (elevated.ok !== true) {
1064
+ return { started: false, side, command: plan.display, reason: elevated.reason }
1065
+ }
1066
+ const output = elevated.output
1067
+ if (/svcRunning=True/.test(output)) {
1068
+ return {
1069
+ started: false,
1070
+ side,
1071
+ command: plan.display,
1072
+ reason: 'ProxyBridgeSvc 服务停不下来,它会和 CLI 抢 WinDivert 句柄(表现为拦截器在跑但一条 [CONN] 都没有)——用管理员结束该服务后重试',
1073
+ }
1074
+ }
1075
+ const pid = Number.parseInt((output.match(/pid=(\d+)/) ?? [])[1] ?? '', 10)
1076
+ if (Number.isInteger(pid) === false || pid <= 0) {
1077
+ return {
1078
+ started: false,
1079
+ side,
1080
+ command: plan.display,
1081
+ reason: /cancel|取消|拒绝|denied|1223/i.test(output) ? 'UAC 被取消' : `未能启动(${output.trim().slice(0, 200) || '没有输出'})`,
1082
+ }
1083
+ }
1084
+ writeRedirectorPid(pid, 'windows')
1085
+ // Keep the exact invocation: a later reload restarts the CLI from this, so the
1086
+ // profile path and verbose level cannot drift between starts.
1087
+ writeCliSpec({ exe: exePath, args: winArgs, log: winLog })
1088
+ const watchdog = Number.parseInt((output.match(/watchdog=(\d+)/) ?? [])[1] ?? '', 10)
1089
+ if (Number.isInteger(watchdog) && watchdog > 0) writeWatchdogPid(watchdog)
1090
+ // `dups` > 0 means a second CLI was still holding (or fighting for) the hook when
1091
+ // ours came up; the elevated script killed it, but say so — silent handle sharing
1092
+ // is exactly the failure that looks like "interception works, nothing captured".
1093
+ const duplicates = Number.parseInt((output.match(/dups=(-?\d+)/) ?? [])[1] ?? '0', 10)
1094
+ // Remember how the service was configured: we park an Automatic service on
1095
+ // Manual (otherwise Windows restarts it and steals the handle back), so the
1096
+ // original start type has to be written down to restore it on stop.
1097
+ const startType = (output.match(/startType=(\w+)/) ?? [])[1] ?? ''
1098
+ if (/svc=True/i.test(output)) {
1099
+ writeWindowsServiceState({
1100
+ stoppedByUs: true,
1101
+ originalStartType: startType === '' ? undefined : startType,
1102
+ parkedOnManual: /parked=True/i.test(output),
1103
+ })
1104
+ }
1105
+ // A CLI that exits immediately (bad profile, handle already taken) used to look
1106
+ // like success: the pid was written and never checked again.
1107
+ const alive = /alive=True/i.test(output)
1108
+ if (alive !== true) {
1109
+ clearRedirectorPid('windows')
1110
+ const log = `${readTail(windowsLogLocalPath(), 4096)}\n${readTail(`${windowsLogLocalPath()}.err`, 2048)}`.trim()
1111
+ return {
1112
+ started: false,
1113
+ side,
1114
+ pid,
1115
+ command: plan.display,
1116
+ reason: `启动后退出(${log.split('\n').filter((line) => line.trim() !== '').slice(-3).join(' / ').slice(0, 240) || '日志为空'})`,
1117
+ }
1118
+ }
1119
+ return {
1120
+ started: true,
1121
+ pid,
1122
+ side,
1123
+ command: plan.display,
1124
+ duplicatesKilled: duplicates > 0 ? duplicates : 0,
1125
+ watchdog: Number.parseInt((output.match(/watchdog=(\d+)/) ?? [])[1] ?? '0', 10) || 0,
1126
+ }
1127
+ }
1128
+
1129
+ if (hasElevation() === true) {
1130
+ const child = spawn(found.path, plan.args, { detached: true, stdio: 'ignore' })
1131
+ child.unref()
1132
+ writeRedirectorPid(child.pid, 'local')
1133
+ return { started: true, pid: child.pid, side, command: plan.display }
1134
+ }
1135
+ // Passwordless sudo only: asking for a password from a web route would hang.
1136
+ const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true })
1137
+ if (probe.status === 0) {
1138
+ const child = spawn('sudo', ['-n', found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1139
+ child.unref()
1140
+ writeRedirectorPid(child.pid, 'local')
1141
+ return { started: true, pid: child.pid, side, command: plan.display }
1142
+ }
1143
+ return { started: false, side, command: plan.display, reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1144
+ }
1145
+
1146
+ /** Where the vendored distribution for a platform lives (machine-wide, shared). */
1147
+ export function redirectorVendorDir(options = {}) {
1148
+ const platform = options.platform ?? process.platform
1149
+ return join(redirectorHome(), 'vendor', platform === 'win32' ? 'windows' : 'linux')
1150
+ }
1151
+
1152
+ let warnedBundleUnavailable = false
1153
+ /**
1154
+ * Find a usable CLI for one side.
1155
+ *
1156
+ * `side` names the network stack that gets hooked, not the platform this process
1157
+ * runs on: inside WSL both sides exist and neither replaces the other.
1158
+ *
1159
+ * Before a Windows-side lookup, the cached distribution is materialised under
1160
+ * `%LOCALAPPDATA%` (unless the caller pinned `platform`, the test-only override).
1161
+ * Nothing is downloaded here — the maintenance page owns that — so a missing
1162
+ * distribution is reported through `missingBundle`/`reason`, never as silence.
1163
+ * @param {{side?: 'local'|'windows', platform?: string, targetDir?: string, bundleDir?: string}} [options] - overrides for tests.
1164
+ * @returns {{found: boolean, path: string, kind: string, candidates: string[], bundleDir: string, missingBundle: boolean, reason?: string}} the first hit plus the bundle diagnosis.
1165
+ */
1166
+ export function findRedirector(options = {}) {
1167
+ const platform = options.platform ?? process.platform
1168
+ const side = options.side === 'windows' ? 'windows' : 'local'
1169
+ let bundleDir = options.bundleDir
1170
+ const needsWindowsBundle = platform === 'win32' || side === 'windows'
1171
+ const installed = bundleIsInstalled(bundledBundleDir())
1172
+ const missingBundle = installed !== true
1173
+ if (bundleDir === undefined && options.platform === undefined && needsWindowsBundle) {
1174
+ try {
1175
+ const prepared = options.targetDir === undefined ? prepareWindowsBundle() : prepareWindowsBundle({ targetDir: options.targetDir })
1176
+ if (typeof prepared === 'string' && prepared !== '') bundleDir = prepared
1177
+ else if (prepared === '' && missingBundle !== true && warnedBundleUnavailable !== true) {
1178
+ // Downloaded, but this host has no Windows-addressable %LOCALAPPDATA%.
1179
+ warnedBundleUnavailable = true
1180
+ console.error('[dsh-ris-ide] 无法确定 %LOCALAPPDATA%:Windows 侧代理桥将直接使用下载缓存里的路径。')
1181
+ }
1182
+ } catch (error) {
1183
+ if (warnedBundleUnavailable !== true) {
1184
+ warnedBundleUnavailable = true
1185
+ console.error(`[dsh-ris-ide] 准备 Windows 版 ProxyBridge 失败:${error?.message ?? String(error)}`)
1186
+ }
1187
+ }
1188
+ }
1189
+ const candidates = redirectorCandidates({ platform, side, ...(bundleDir === undefined ? {} : { bundleDir }) })
1190
+ for (const path of candidates) {
1191
+ if (existsSync(path) !== true) continue
1192
+ const kind = /\.exe$/i.test(path) === true ? 'windows-cli' : 'linux-cli'
1193
+ // A CLI we can actually run means the component is NOT missing, even when it
1194
+ // came from DSH_RIS_IDE_PROXYBRIDGE, a vendor/Program Files install, or an
1195
+ // explicit bundleDir instead of our download cache (review B-P2 missingBundle).
1196
+ return { found: true, path, kind, candidates, bundleDir: candidates.bundleDir, bundleCached: installed === true, missingBundle: false }
1197
+ }
1198
+ const result = { found: false, path: candidates[0] ?? '', kind: '', candidates, bundleDir: candidates.bundleDir, bundleCached: installed === true, missingBundle: candidates.missingBundle === true }
1199
+ if (result.missingBundle === true) result.reason = MISSING_BUNDLE_HINT
1200
+ else result.reason = side === 'windows' ? '未找到 Windows 版 ProxyBridge_CLI.exe' : '未找到本侧 ProxyBridge'
1201
+ return result
1202
+ }
1203
+
1204
+ /** Ask the CLI for its version; '' when it cannot answer (cached: it never changes). */
1205
+ export function redirectorVersion(cliPath) {
1206
+ if (typeof cliPath !== 'string' || cliPath === '' || existsSync(cliPath) !== true) return ''
1207
+ const now = Date.now()
1208
+ const cached = versionCache.get(cliPath)
1209
+ if (cached !== undefined && now - cached.at < VERSION_TTL_MS) return cached.version
1210
+ const run = () => probeVersionNow(cliPath)
1211
+ const version = typeof probeHooks.version === 'function' ? String(probeHooks.version(cliPath, run) ?? '') : run()
1212
+ versionCache.set(cliPath, { at: now, version })
1213
+ return version
1214
+ }
1215
+
1216
+ function probeVersionNow(cliPath) {
1217
+ try {
1218
+ const output = spawnSyncText(cliPath, ['--version'], 6000)
1219
+ const match = /(\d+\.\d+\.\d+)/.exec(output)
1220
+ return match === null ? '' : match[1]
1221
+ } catch {
1222
+ return ''
1223
+ }
1224
+ }
1225
+
1226
+ /**
1227
+ * A rule's `program` as ProxyBridge's ProcessName.
1228
+ *
1229
+ * A bare name has to match the image on both sides, so it is wrapped in stars
1230
+ * (`*java*` sees java.exe on Windows and java on Linux). A path is pinned to its
1231
+ * directory — YonCode keeps several JDKs around and only one of them is ours.
1232
+ * @param {string} value - program name or path.
1233
+ * @returns {string} ProcessName pattern.
1234
+ */
1235
+ export function processPattern(value) {
1236
+ const text = typeof value === 'string' ? value.trim() : ''
1237
+ if (text === '') return ''
1238
+ const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
1239
+ if (cut === -1) return extname(text) === '' ? `*${text}*` : text
1240
+ const dir = text.slice(0, cut)
1241
+ const name = text.slice(cut + 1)
1242
+ const ext = extname(name)
1243
+ return ext === '' ? `${dir}${text[cut]}*` : `${dir}${text[cut]}*${ext}`
1244
+ }
1245
+
1246
+ /**
1247
+ * Turn the rule table into a `.pbprofile`.
1248
+ *
1249
+ * Shape follows an export from the GUI: no `TargetDomains` (a "*" there reads as
1250
+ * "requests that have a domain", which would drop bare-IP targets), no
1251
+ * `LocalhostViaProxy` (the GUI omits it and false is the default — loopback must
1252
+ * stay local).
1253
+ * @param {object} config - engine config (`rules`, `socks`, `listenPort`).
1254
+ * @param {{upstream?: 'socks'|'engine', name?: string}} [options] - who terminates the tunnel.
1255
+ * @returns {{profile: object, rules: object[], skipped: string[]}} profile plus what was dropped and why.
1256
+ */
1257
+ export function buildProfile(config, options = {}) {
1258
+ const upstream = options.upstream === 'engine' ? 'engine' : 'socks'
1259
+ const socks = config?.socks ?? { host: '', port: 0 }
1260
+ const proxyConfig = upstream === 'engine'
1261
+ ? { Id: 1, Name: 'dsh-ris-ide engine', Type: 'HTTP', Host: '127.0.0.1', Port: String(config?.listenPort ?? 0), Username: '', Password: '', SendDomainToProxy: false }
1262
+ : { Id: 1, Name: 'socks', Type: 'SOCKS5', Host: String(socks.host ?? ''), Port: String(socks.port ?? ''), Username: '', Password: '', SendDomainToProxy: true }
1263
+ const rules = []
1264
+ const skipped = []
1265
+ for (const rule of config?.rules ?? []) {
1266
+ if (rule.enabled !== true) {
1267
+ skipped.push(`${rule.id}: disabled`)
1268
+ continue
1269
+ }
1270
+ const processName = processPattern(rule.program)
1271
+ if (processName === '') {
1272
+ skipped.push(`${rule.id}: no program`)
1273
+ continue
1274
+ }
1275
+ const hosts = String(rule.hosts ?? '').trim()
1276
+ const ports = String(rule.ports ?? '').trim()
1277
+ // Every axis must be explicit and "everything" must be spelled `*`: a blank
1278
+ // host/port used to be coerced to `*`, which silently proxied the whole
1279
+ // internet for a half-written row.
1280
+ const verdict = ruleEffectiveness(rule)
1281
+ if (verdict.effective !== true) {
1282
+ skipped.push(`${rule.id}: ${verdict.reason}`)
1283
+ continue
1284
+ }
1285
+ rules.push({
1286
+ // ProxyBridge's GUI/CLI log shows this name, so a row that came from a
1287
+ // provider ("YonCode java") stays recognisable there too.
1288
+ Name: typeof rule.label === 'string' && rule.label !== '' ? rule.label : rule.id,
1289
+ ProcessName: processName,
1290
+ TargetHosts: hosts.replace(/\s+/g, ''),
1291
+ TargetPorts: ports.replace(/\s+/g, ''),
1292
+ // UDP as well: DNS and QUIC go over UDP, and a matching process should not
1293
+ // leak them around the tunnel.
1294
+ Protocol: 'BOTH',
1295
+ Action: 'PROXY',
1296
+ IsEnabled: true,
1297
+ ProxyConfigId: 1,
1298
+ })
1299
+ }
1300
+ const profile = {
1301
+ Version: PROFILE_VERSION,
1302
+ Name: options.name ?? 'dsh-ris-ide',
1303
+ // Connection logging on: without it a working interception and a dead one look
1304
+ // identical in the log (both show rules, neither shows traffic), which is exactly
1305
+ // the wrong thing to leave ambiguous in a developer tool.
1306
+ IsTrafficLoggingEnabled: true,
1307
+ AutoClearConnectionLogs: true,
1308
+ LogEveryConnection: true,
1309
+ Language: 'zh',
1310
+ CloseToTray: true,
1311
+ FontZoom: 100,
1312
+ NextProxyConfigId: 2,
1313
+ ProxyConfigs: [proxyConfig],
1314
+ ProxyRules: rules,
1315
+ LogFilters: [],
1316
+ }
1317
+ return { profile, rules, skipped }
1318
+ }
1319
+
1320
+ /**
1321
+ * Write the profile, private: it carries the proxy address and possibly a password.
1322
+ * @throws when no rule survives — ProxyBridge rejects an empty rule set and a silent
1323
+ * empty profile would look like a working setup that proxies nothing.
1324
+ */
1325
+ export function writeRedirectorProfile(config, options = {}) {
1326
+ const { profile, rules, skipped } = buildProfile(config, options)
1327
+ if (rules.length === 0) throw new Error('没有可导出的规则:ProxyBridge 要求至少一条启用且带程序的规则')
1328
+ const path = options.path ?? redirectorProfilePath()
1329
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
1330
+ writeFileSync(path, JSON.stringify(profile, null, 2), { mode: 0o600 })
1331
+ try {
1332
+ chmodSync(path, 0o600)
1333
+ } catch {
1334
+ // Filesystems without POSIX modes (a Windows share) simply keep their default.
1335
+ }
1336
+ return { path, rules: rules.length, skipped }
1337
+ }
1338
+
1339
+ /**
1340
+ * End every Windows CLI, tracked or not.
1341
+ *
1342
+ * A hand-started CLI (or one whose pid file we lost) still owns the hook, and
1343
+ * ProxyBridge refuses to run twice — so "already running" means "get it out of the
1344
+ * way", not "give up".
1345
+ * @returns {Promise<{ok: boolean, killed?: number, reason?: string}>} outcome.
1346
+ */
1347
+ export async function killWindowsCliProcesses() {
1348
+ const script = [
1349
+ "$ErrorActionPreference = 'Continue'",
1350
+ '$found = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue)',
1351
+ 'if ($found.Count -eq 0) { "none"; return }',
1352
+ '$found | Stop-Process -Force -ErrorAction SilentlyContinue',
1353
+ 'Start-Sleep -Milliseconds 800',
1354
+ '"killed=" + $found.Count',
1355
+ ].join('; ')
1356
+ const elevated = await psElevated(script, 20000)
1357
+ if (elevated.ok !== true) return { ok: false, reason: elevated.reason }
1358
+ const output = elevated.output
1359
+ const killed = /killed=(\d+)/.exec(output)
1360
+ if (killed !== null) return { ok: true, killed: Number.parseInt(killed[1], 10) }
1361
+ if (/none/.test(output)) return { ok: true, killed: 0 }
1362
+ return {
1363
+ ok: false,
1364
+ reason: /cancel|取消|拒绝|denied|1223/i.test(output)
1365
+ ? 'UAC 被取消'
1366
+ : `无法结束已有的 ProxyBridge_CLI(${output.trim().slice(0, 160) || '没有输出'})`,
1367
+ }
1368
+ }
1369
+
1370
+ /**
1371
+ * The command that starts the CLI, spelled for the platform that will run it.
1372
+ *
1373
+ * On Windows the launch itself elevates (UAC), so the command is the exe; on Linux
1374
+ * the whole thing is a `sudo`. In WSL the Windows command must be translated: a
1375
+ * `/mnt/...` path does not exist in the Windows namespace.
1376
+ * @param {{cliPath: string, profilePath: string, verbose?: number, platform?: string}} options - inputs.
1377
+ * @returns {{command: string, args: string[], display: string, needsElevation: boolean}} runnable plan.
1378
+ */
1379
+ export function redirectorCommand(options = {}) {
1380
+ const platform = options.platform ?? process.platform
1381
+ // 2 = per-connection lines (`[CONN] java.exe (PID) -> host:port via Proxy …`).
1382
+ // Level 1 only prints the rules, which makes a working interception and a dead
1383
+ // one look the same — the exact ambiguity that cost us an hour of guessing.
1384
+ const verbose = Number.isInteger(options.verbose) ? options.verbose : 2
1385
+ const args = ['--profile', String(options.profilePath ?? ''), '--verbose', String(verbose)]
1386
+ const translate = platform === 'win32' && engineSide() === 'wsl'
1387
+ const exe = translate ? windowsPathOf(String(options.cliPath ?? '')) : String(options.cliPath ?? '')
1388
+ const shownArgs = translate ? windowsArgsOf(args) : args
1389
+ const quote = (value) => (/[ \t]/.test(value) === true ? `"${value}"` : value)
1390
+ const display = [quote(exe), ...shownArgs.map(quote)].join(' ')
1391
+ if (platform === 'win32') return { command: exe, args: shownArgs, display, needsElevation: true }
1392
+ return {
1393
+ command: 'sudo',
1394
+ args: [String(options.cliPath ?? ''), ...args],
1395
+ display: `sudo ${quote(String(options.cliPath ?? ''))} ${args.map(quote).join(' ')}`,
1396
+ needsElevation: true,
1397
+ }
1398
+ }
1399
+
1400
+ /**
1401
+ * Stop the redirector(s).
1402
+ *
1403
+ * Synchronous by design: it is also called from the dsh exit hook, where async
1404
+ * cleanup does not run.
1405
+ *
1406
+ * Detection comes first (B5): a dead pid file used to make taskkill fail, the
1407
+ * liveness probe report "gone", and the caller show a clean stop while the real
1408
+ * elevated CLI kept intercepting. The three states are: nothing running, our
1409
+ * recorded process running, and a visible process we did not record (started by
1410
+ * hand, or after a lost pid file) — that one is stopped by image and reported.
1411
+ * @param {{graceMs?: number, side?: 'local'|'windows'}} [options] - wait budget / one side only.
1412
+ * @returns {{stopped: boolean, pid?: number, side?: string, service?: object, byWatchdog?: boolean, reason?: string, results?: object[]}} outcome.
1413
+ */
1414
+ export function stopRedirectorSync(options = {}) {
1415
+ const sides = options.side === 'local' || options.side === 'windows' ? [options.side] : ['windows', 'local']
1416
+ const results = sides.map((side) => Object.assign({ side }, stopRedirectorSideSync(side, options)))
1417
+ const stopped = results.filter((result) => result.stopped === true)
1418
+ if (stopped.length > 0) {
1419
+ const first = stopped[0]
1420
+ return { stopped: true, pid: first.pid, side: first.side, service: first.service, byWatchdog: first.byWatchdog, foreign: first.foreign === true, results }
1421
+ }
1422
+ // Nothing was even detected: keep the historical terse answer (the UI shows it).
1423
+ if (results.every((result) => result.pid === undefined)) return { stopped: false, reason: '未在运行' }
1424
+ return { stopped: false, reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未发现运行中的桥接', results }
1425
+ }
1426
+
1427
+ /**
1428
+ * Record that a stop hit a bridge we never wrote a pid file for.
1429
+ *
1430
+ * `stopRedirector()` also stops a hand-started CLI (the user pasted the sudo
1431
+ * command), which is deliberate — leaving root interception behind is worse.
1432
+ * But the daemon's own exit therefore ends another program some human started,
1433
+ * so the engine log must say so: a silent kill is indistinguishable from a crash
1434
+ * (review B-P2-10).
1435
+ * @param {{pid: number, source?: string}} target - detection result being stopped.
1436
+ * @returns {boolean} true when the entry was written.
1437
+ */
1438
+ function noteForeignStop(target) {
1439
+ if (target.source === 'pidfile' || target.source === undefined) return false
1440
+ try {
1441
+ appendFileSync(proxyLogPath(), `${new Date().toISOString()} [dsh-ris-ide] 停止了一个非本工具记录的桥接 pid=${target.pid} (source=${target.source})\n`)
1442
+ return true
1443
+ } catch {
1444
+ return false
1445
+ }
1446
+ }
1447
+
1448
+ /** Stop one side; detection first, so a dead record can never fake success. */
1449
+ function stopRedirectorSideSync(side, options) {
1450
+ const record = redirectorPidRecord(side)
1451
+ let target = null
1452
+ if (record.pid > 0 && pidAliveOn(record.pid, side)) target = { pid: record.pid, source: 'pidfile' }
1453
+ if (target === null) {
1454
+ const detection = detectRunningRedirector()
1455
+ const found = side === 'windows' ? detection.windows : detection.local
1456
+ if (found.pid > 0) target = { pid: found.pid, source: found.source }
1457
+ }
1458
+ if (target === null) {
1459
+ // Drop a dead record: otherwise the next status keeps advertising a pid that
1460
+ // does not exist and the user cannot tell "stopped" from "lost track".
1461
+ if (record.pid > 0) clearRedirectorPid(side)
1462
+ return { stopped: false, reason: '未发现运行中的桥接' }
1463
+ }
1464
+ if (side === 'windows') return stopWindowsSideSync(target, options)
1465
+ return stopLocalSideSync(target, options)
1466
+ }
1467
+
1468
+ /**
1469
+ * Windows side: the CLI runs elevated, so a plain taskkill from here cannot touch
1470
+ * it. Ask the watchdog (the elevated helper we spawned at start) first: it kills
1471
+ * the CLI and puts ProxyBridgeSvc back, with no second UAC.
1472
+ */
1473
+ function stopWindowsSideSync(target, options) {
1474
+ const foreign = target.source !== undefined && target.source !== 'pidfile'
1475
+ const foreignLogged = foreign ? noteForeignStop(target) : false
1476
+ requestRedirectorStop()
1477
+ const graceMs = Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 4000
1478
+ const deadline = Date.now() + graceMs
1479
+ while (Date.now() < deadline && stopCompleted() !== true) sleepSync(100)
1480
+ const byWatchdog = stopCompleted() === true
1481
+ const output = byWatchdog === true ? 'SUCCESS' : runTaskkillSync(target.pid)
1482
+ // The liveness answer must not come from a 5 s cache filled before the kill.
1483
+ const gone = byWatchdog !== true && pidAliveOn(target.pid, 'windows', { force: true }) === false
1484
+ if (byWatchdog === true || /SUCCESS|成功/i.test(output) || gone) {
1485
+ clearRedirectorPid('windows')
1486
+ // Give the GUI service its hook back if we were the ones who stopped it (the
1487
+ // watchdog normally already did it; a hand-started CLI still needs this).
1488
+ const service = restoreWindowsService()
1489
+ clearStopSignals()
1490
+ return { stopped: true, pid: target.pid, source: target.source, service, byWatchdog, foreign, foreignLogged }
1491
+ }
1492
+ const hint = target.source === 'pidfile' ? '' : '(检测到进程但不在记录中,可能需要管理员权限)'
1493
+ return { stopped: false, pid: target.pid, source: target.source, foreign, foreignLogged, reason: `无法停止 Windows 进程 ${target.pid}${hint}(${output.trim().slice(0, 120) || '没有输出'})` }
1494
+ }
1495
+
1496
+ function stopLocalSideSync(target, options) {
1497
+ const foreign = target.source !== undefined && target.source !== 'pidfile'
1498
+ const foreignLogged = foreign ? noteForeignStop(target) : false
1499
+ try { process.kill(target.pid, 'SIGTERM') } catch (error) {
1500
+ if (error?.code === 'EPERM') return { stopped: false, pid: target.pid, side: 'local', foreign, foreignLogged, reason: `需要 sudo kill ${target.pid}` }
1501
+ }
1502
+ // Block the exit hook briefly: SIGTERM on the engine is quick, and leaving a
1503
+ // root process behind after dsh quits is worse than a short delay.
1504
+ const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 3000)
1505
+ while (Date.now() < limit && pidAlive(target.pid)) sleepSync(120)
1506
+ if (pidAlive(target.pid)) return { stopped: false, pid: target.pid, side: 'local', foreign, foreignLogged, reason: `进程 ${target.pid} 仍在运行(需要 sudo kill ${target.pid})` }
1507
+ clearRedirectorPid('local')
1508
+ return { stopped: true, pid: target.pid, source: target.source, side: 'local', foreign, foreignLogged }
1509
+ }
1510
+
1511
+ /** taskkill one pid (checked from the pid file) — test seam `taskkill` overrides it. */
1512
+ function runTaskkillSync(pid) {
1513
+ if (typeof probeHooks.taskkill === 'function') return String(probeHooks.taskkill(pid) ?? '')
1514
+ return spawnSyncText('taskkill.exe', ['/PID', String(pid), '/T', '/F'], 8000)
1515
+ }
1516
+
1517
+ /** Whether this process already has the rights the redirector needs. */
1518
+ export function hasElevation() {
1519
+ if (IS_WINDOWS) return false
1520
+ return typeof process.getuid === 'function' && process.getuid() === 0
1521
+ }
1522
+
1523
+ /**
1524
+ * Live Windows CLI pids, cached for a few seconds.
1525
+ *
1526
+ * This used to be a blocking PowerShell call (15 s timeout, 3–4 s real) on every
1527
+ * status render; it froze the whole dsh process while it ran. The answer is cached
1528
+ * for PROBE_TTL_MS and an async variant exists so HTTP routes never block (M3).
1529
+ * @param {{force?: boolean}} [options] - bypass the cache.
1530
+ * @returns {number[]} live pids; empty when this host has no Windows side.
1531
+ */
1532
+ export function windowsRedirectorPids(options = {}) {
1533
+ if (typeof probeHooks.windowsPids !== 'function' && IS_WINDOWS !== true && existsSync('/mnt/c') !== true) return []
1534
+ const now = Date.now()
1535
+ if (options.force !== true && windowsPidsCache.pids !== null && now - windowsPidsCache.at < PROBE_TTL_MS) return windowsPidsCache.pids.slice()
1536
+ const probed = typeof probeHooks.windowsPids === 'function' ? probeHooks.windowsPids() : readWindowsPidsSync()
1537
+ const pids = Array.isArray(probed) ? probed.filter((pid) => Number.isInteger(pid) && pid > 0) : []
1538
+ windowsPidsCache = { at: now, pids }
1539
+ return pids.slice()
1540
+ }
1541
+
1542
+ /** Async variant of {@link windowsRedirectorPids}: never blocks the event loop. */
1543
+ export async function windowsRedirectorPidsAsync(options = {}) {
1544
+ if (typeof probeHooks.windowsPidsAsync !== 'function' && typeof probeHooks.windowsPids !== 'function' && IS_WINDOWS !== true && existsSync('/mnt/c') !== true) return []
1545
+ const now = Date.now()
1546
+ if (options.force !== true && windowsPidsCache.pids !== null && now - windowsPidsCache.at < PROBE_TTL_MS) return windowsPidsCache.pids.slice()
1547
+ let probed = null
1548
+ if (typeof probeHooks.windowsPidsAsync === 'function') probed = await probeHooks.windowsPidsAsync()
1549
+ else if (typeof probeHooks.windowsPids === 'function') probed = probeHooks.windowsPids()
1550
+ else probed = await readWindowsPidsAsync()
1551
+ const pids = Array.isArray(probed) ? probed.filter((pid) => Number.isInteger(pid) && pid > 0) : []
1552
+ windowsPidsCache = { at: Date.now(), pids }
1553
+ return pids.slice()
1554
+ }
1555
+
1556
+ function readWindowsPidsSync() {
1557
+ try {
1558
+ const out = spawnSync(
1559
+ 'powershell.exe',
1560
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
1561
+ '@(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue) | ForEach-Object { $_.Id }'],
1562
+ { encoding: 'utf8', timeout: 15000, windowsHide: true },
1563
+ )
1564
+ if (out.status !== 0) return []
1565
+ return String(out.stdout ?? '')
1566
+ .split(/\s+/)
1567
+ .map((value) => Number.parseInt(value, 10))
1568
+ .filter((value) => Number.isInteger(value) && value > 0)
1569
+ } catch {
1570
+ return []
1571
+ }
1572
+ }
1573
+
1574
+ async function readWindowsPidsAsync() {
1575
+ const output = await runTextAsync(
1576
+ 'powershell.exe',
1577
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
1578
+ '@(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue) | ForEach-Object { $_.Id }'],
1579
+ 15000,
1580
+ )
1581
+ return output
1582
+ .split(/\s+/)
1583
+ .map((value) => Number.parseInt(value, 10))
1584
+ .filter((value) => Number.isInteger(value) && value > 0)
1585
+ }
1586
+
1587
+ /**
1588
+ * @param {'local'|'windows'} [side] - omit for the first side that has a record.
1589
+ * @returns {number} live pid, or 0.
1590
+ */
1591
+ export function redirectorPid(side) {
1592
+ const record = redirectorPidRecord(side)
1593
+ return record.pid > 0 && pidAliveOn(record.pid, record.side) ? record.pid : 0
1594
+ }
1595
+
1596
+ /**
1597
+ * The raw pid record of one side (or of whichever side has one).
1598
+ *
1599
+ * The legacy single file is migrated on read, so an upgrade does not turn a running
1600
+ * bridge into an orphan. Liveness is NOT checked here — see redirectorPid().
1601
+ * @param {'local'|'windows'} [side] - which side; omit for local-then-windows.
1602
+ * @returns {{pid: number, side: 'local'|'windows'}} record (pid 0 when absent).
1603
+ */
1604
+ export function redirectorPidRecord(side) {
1605
+ migrateLegacyPidFile()
1606
+ if (side === 'local' || side === 'windows') {
1607
+ return readPidFileAt(redirectorSidePidPath(side)) ?? { pid: 0, side }
1608
+ }
1609
+ const local = readPidFileAt(redirectorSidePidPath('local'))
1610
+ if (local !== null) return local
1611
+ const windows = readPidFileAt(redirectorSidePidPath('windows'))
1612
+ if (windows !== null) return windows
1613
+ return { pid: 0, side: 'local' }
1614
+ }
1615
+
1616
+ /**
1617
+ * Whether the THIS-SIDE engine is running.
1618
+ *
1619
+ * The two sides are not interchangeable: a Windows ProxyBridge hooks the Windows
1620
+ * network stack, so a Java process we start in WSL is invisible to it. Deciding
1621
+ * "interception covers us" therefore has to ask about the local side only.
1622
+ * @returns {boolean} true when a Linux/macOS ProxyBridge of ours is alive.
1623
+ */
1624
+ export function localRedirectorRunning() {
1625
+ const record = redirectorPidRecord('local')
1626
+ if (record.pid > 0 && pidAlive(record.pid)) return true
1627
+ // dsh on Windows: there is only one machine, so the 'windows' record IS the local
1628
+ // one — otherwise a running interceptor would not count and the config would be
1629
+ // adapted to the fallback path while the kernel hook is actually live.
1630
+ if (IS_WINDOWS) {
1631
+ const onWindows = redirectorPidRecord('windows')
1632
+ return onWindows.pid > 0 && pidAliveOn(onWindows.pid, 'windows')
1633
+ }
1634
+ // A hand-started `sudo ProxyBridge …` has no pidfile entry of ours.
1635
+ return scanLocalProcForRedirector() > 0
1636
+ }
1637
+
1638
+ /**
1639
+ * Scan /proc for a hand-started engine (`/path/ProxyBridge … --profile …`).
1640
+ *
1641
+ * The argv[0] check matters: "some process whose command line mentions
1642
+ * ProxyBridge" also matches a shell that merely greps for it, and acting on that
1643
+ * pid would signal the wrong process. The redirector's own binary name is the only
1644
+ * safe identity we have without elevation.
1645
+ * @returns {number} pid or 0.
1646
+ */
1647
+ function scanLocalProcForRedirector() {
1648
+ if (IS_WINDOWS) return 0
1649
+ if (typeof probeHooks.localProc === 'function') return Number.parseInt(probeHooks.localProc() ?? 0, 10) || 0
1650
+ try {
1651
+ for (const entry of readdirSync('/proc')) {
1652
+ if (!/^\d+$/.test(entry)) continue
1653
+ try {
1654
+ const argv = readFileSync(`/proc/${entry}/cmdline`, 'utf8').split('\0').filter((part) => part !== '')
1655
+ const isRedirector = argv.some((token) => /(^|[\\/])ProxyBridge(\.exe)?$/i.test(token))
1656
+ if (isRedirector && argv.some((token) => token === '--profile' || token.startsWith('--profile='))) {
1657
+ return Number.parseInt(entry, 10)
1658
+ }
1659
+ } catch { /* vanished */ }
1660
+ }
1661
+ } catch { /* no /proc */ }
1662
+ return 0
1663
+ }
1664
+
1665
+ /**
1666
+ * Is a pid alive on a given side?
1667
+ *
1668
+ * Windows pids are invisible to `process.kill` on Linux, so they are asked about
1669
+ * through PowerShell's CIM provider. The answer is cached for PROBE_TTL_MS because
1670
+ * status renders ask on every request; pass `{force:true}` when the answer decides
1671
+ * what to do next (e.g. after a taskkill).
1672
+ * @param {number} pid - the process to check.
1673
+ * @param {'local'|'windows'} side - which machine owns that pid.
1674
+ * @param {{force?: boolean}} [options] - bypass the cache.
1675
+ * @returns {boolean} liveness.
1676
+ */
1677
+ export function pidAliveOn(pid, side, options = {}) {
1678
+ if (side !== 'windows') return pidAlive(pid)
1679
+ if (IS_WINDOWS) return pidAlive(pid)
1680
+ const now = Date.now()
1681
+ const cached = windowsAliveCache.get(pid)
1682
+ if (options.force !== true && cached !== undefined && now - cached.at < PROBE_TTL_MS) return cached.alive
1683
+ const alive = typeof probeHooks.windowsAlive === 'function' ? probeHooks.windowsAlive(pid) === true : readWindowsAliveSync(pid)
1684
+ windowsAliveCache.set(pid, { at: now, alive })
1685
+ return alive
1686
+ }
1687
+
1688
+ /** Async variant of {@link pidAliveOn}; never blocks the event loop. */
1689
+ export async function pidAliveOnAsync(pid, side, options = {}) {
1690
+ if (side !== 'windows') return pidAlive(pid)
1691
+ if (IS_WINDOWS) return pidAlive(pid)
1692
+ const now = Date.now()
1693
+ const cached = windowsAliveCache.get(pid)
1694
+ if (options.force !== true && cached !== undefined && now - cached.at < PROBE_TTL_MS) return cached.alive
1695
+ const alive = typeof probeHooks.windowsAliveAsync === 'function'
1696
+ ? await probeHooks.windowsAliveAsync(pid) === true
1697
+ : await readWindowsAliveAsync(pid)
1698
+ windowsAliveCache.set(pid, { at: Date.now(), alive })
1699
+ return alive
1700
+ }
1701
+
1702
+ function readWindowsAliveSync(pid) {
1703
+ // Get-Process, not Win32_Process: the CLI runs elevated and a non-elevated CIM
1704
+ // query for another account's process comes back empty, which would report a
1705
+ // running engine as dead (and make `stop` skip the taskkill).
1706
+ const output = spawnSyncText('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
1707
+ `if (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { 'alive' } else { 'gone' }`], 6000)
1708
+ return /alive/.test(output)
1709
+ }
1710
+
1711
+ async function readWindowsAliveAsync(pid) {
1712
+ const output = await runTextAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
1713
+ `if (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { 'alive' } else { 'gone' }`], 6000)
1714
+ return /alive/.test(output)
1715
+ }
1716
+
1717
+ /**
1718
+ * Write one side's pid file (only after the process is confirmed alive).
1719
+ * @param {number} pid - process id.
1720
+ * @param {'local'|'windows'} [side] - which machine it runs on.
1721
+ */
1722
+ export function writeRedirectorPid(pid, side = 'local') {
1723
+ const which = side === 'windows' ? 'windows' : 'local'
1724
+ mkdirSync(redirectorHome(), { recursive: true, mode: 0o700 })
1725
+ writeFileSync(redirectorSidePidPath(which), `${pid} ${which}\n`, { encoding: 'utf8', mode: 0o600 })
1726
+ // The per-side file supersedes the legacy one; keeping both invites confusion.
1727
+ try { unlinkSync(redirectorPidPath()) } catch { /* absent */ }
1728
+ }
1729
+
1730
+ /**
1731
+ * Remove a pid file.
1732
+ * @param {'local'|'windows'} [side] - one side; omit for both (plus the legacy file).
1733
+ */
1734
+ export function clearRedirectorPid(side) {
1735
+ const paths = side === 'local' || side === 'windows'
1736
+ ? [redirectorSidePidPath(side)]
1737
+ : [redirectorSidePidPath('local'), redirectorSidePidPath('windows'), redirectorPidPath()]
1738
+ for (const path of paths) {
1739
+ try { unlinkSync(path) } catch { /* already gone */ }
1740
+ }
1741
+ }
1742
+
1743
+ /**
1744
+ * Find running redirectors, per side, including ones started by hand.
1745
+ *
1746
+ * The pidfile only exists when WE spawned it; a user who pasted the sudo command
1747
+ * starts a process we never saw, and reporting "not running" then is a lie the
1748
+ * dialog shows. So the per-side pidfile is the fast path, a `/proc` scan is the
1749
+ * local fallback (root cmdlines stay readable unless hidepid is on) and the
1750
+ * Windows process table covers the other side.
1751
+ *
1752
+ * Three discovery sources, named for what they looked at: `pidfile` (we spawned
1753
+ * it), `proc` (`/proc` command lines, POSIX) and `process` (Windows process
1754
+ * table). `''` means nothing was found.
1755
+ * @returns {{pid: number, source: string, side: string, local: {pid: number, source: string}, windows: {pid: number, source: string}}} discovery result; `pid` is the first live hit.
1756
+ */
1757
+ export function detectRunningRedirector() {
1758
+ migrateLegacyPidFile()
1759
+ const local = detectSide('local')
1760
+ const windows = detectSide('windows')
1761
+ const primary = local ?? windows
1762
+ return {
1763
+ pid: primary?.pid ?? 0,
1764
+ source: primary?.source ?? '',
1765
+ side: primary?.side ?? '',
1766
+ local: local === null ? { pid: 0, source: '' } : { pid: local.pid, source: local.source },
1767
+ windows: windows === null ? { pid: 0, source: '' } : { pid: windows.pid, source: windows.source },
1768
+ }
1769
+ }
1770
+
1771
+ /** @returns {object|null} discovery hit for one side. */
1772
+ function detectSide(side) {
1773
+ const record = redirectorPidRecord(side)
1774
+ if (record.pid > 0 && pidAliveOn(record.pid, side)) return { pid: record.pid, side, source: 'pidfile' }
1775
+ if (side === 'windows') {
1776
+ const live = windowsRedirectorPids()
1777
+ if (live.length > 0) {
1778
+ writeRedirectorPid(live[0], 'windows')
1779
+ return { pid: live[0], side, source: 'process' }
1780
+ }
1781
+ return null
1782
+ }
1783
+ const scanned = scanLocalProcForRedirector()
1784
+ if (scanned > 0) return { pid: scanned, side, source: 'proc' }
1785
+ return null
1786
+ }
1787
+
1788
+ /** Async variant of {@link detectRunningRedirector}: safe to call from HTTP routes. */
1789
+ export async function detectRunningRedirectorAsync() {
1790
+ migrateLegacyPidFile()
1791
+ const record = redirectorPidRecord('local')
1792
+ const local = record.pid > 0 && await pidAliveOnAsync(record.pid, 'local')
1793
+ ? { pid: record.pid, side: 'local', source: 'pidfile' }
1794
+ : null
1795
+ let windows = null
1796
+ const windowsRecord = redirectorPidRecord('windows')
1797
+ if (windowsRecord.pid > 0 && await pidAliveOnAsync(windowsRecord.pid, 'windows')) {
1798
+ windows = { pid: windowsRecord.pid, side: 'windows', source: 'pidfile' }
1799
+ } else {
1800
+ const live = await windowsRedirectorPidsAsync()
1801
+ if (live.length > 0) {
1802
+ writeRedirectorPid(live[0], 'windows')
1803
+ windows = { pid: live[0], side: 'windows', source: 'process' }
1804
+ }
1805
+ }
1806
+ const localHit = local ?? (scanLocalProcForRedirector() > 0 ? { pid: scanLocalProcForRedirector(), side: 'local', source: 'proc' } : null)
1807
+ const primary = localHit ?? windows
1808
+ return {
1809
+ pid: primary?.pid ?? 0,
1810
+ source: primary?.source ?? '',
1811
+ side: primary?.side ?? '',
1812
+ local: localHit === null ? { pid: 0, source: '' } : { pid: localHit.pid, source: localHit.source },
1813
+ windows: windows === null ? { pid: 0, source: '' } : { pid: windows.pid, source: windows.source },
1814
+ }
1815
+ }
1816
+
1817
+ /**
1818
+ * Current redirector state, for the dialog and the CLI.
1819
+ *
1820
+ * `local` and `windows` are independent: uninstalling the Windows app leaves the
1821
+ * Windows side unavailable while the WSL side keeps working, and vice versa.
1822
+ * @returns {{local: object, windows: object, profilePath: string, profileExists: boolean, running: boolean, pid: number, logPath: string, elevated: boolean}} state.
1823
+ */
1824
+ /**
1825
+ * Where the Windows CLI's stdout goes (it has no log-file option of its own).
1826
+ *
1827
+ * It cannot be a path inside our home: the elevated process that writes it cannot
1828
+ * reach the WSL share, so the file has to live on the Windows side and be read back
1829
+ * through /mnt. Two spellings, one file.
1830
+ */
1831
+ export function windowsLogPath() {
1832
+ return `${windowsTempDir()}\\dsh-ris-proxybridge.log`
1833
+ }
1834
+
1835
+ let windowsTempDirCache = ''
1836
+
1837
+ /**
1838
+ * `%TEMP%` as Windows spells it.
1839
+ *
1840
+ * The WSL login name is not the Windows account name often enough to matter (here
1841
+ * they differ), so ask cmd.exe once instead of guessing a profile directory.
1842
+ */
1843
+ export function windowsTempDir() {
1844
+ if (windowsTempDirCache !== '') return windowsTempDirCache
1845
+ const output = spawnSyncText('cmd.exe', ['/c', 'echo %TEMP%'], 6000)
1846
+ const first = output.split(/\r?\n/).map((line) => line.trim()).find((line) => /^[A-Za-z]:\\/.test(line) === true)
1847
+ windowsTempDirCache = first ?? 'C:\\Windows\\Temp'
1848
+ return windowsTempDirCache
1849
+ }
1850
+
1851
+ /** The same file, as a path this process can read. */
1852
+ export function windowsLogLocalPath() {
1853
+ const match = /^([A-Za-z]):\\(.*)$/.exec(windowsLogPath())
1854
+ if (match === null) return windowsLogPath()
1855
+ return join(`/mnt/${match[1].toLowerCase()}`, match[2].replace(/\\/g, '/'))
1856
+ }
1857
+
1858
+ export const SERVICE_STATE_FILENAME = 'proxybridge-service.json'
1859
+
1860
+ /**
1861
+ * Where we remember the parked Windows service.
1862
+ *
1863
+ * The writer, the watchdog and the janitor must agree on this ONE path: the
1864
+ * watchdog used to receive `proxyHomeDir()/…` while the writer stored
1865
+ * `proxyHomeDir()/proxybridge/…`, so the teardown's Set-Service/Start-Service never
1866
+ * ran and the user's service stayed stopped.
1867
+ * @returns {string} absolute path.
1868
+ */
1869
+ export function serviceStatePath() {
1870
+ return join(redirectorHome(), SERVICE_STATE_FILENAME)
1871
+ }
1872
+
1873
+ /** The pre-fix location (one directory too high); only read to migrate it away. */
1874
+ export function legacyServiceStatePath() {
1875
+ return join(proxyHomeDir(), SERVICE_STATE_FILENAME)
1876
+ }
1877
+
1878
+ /**
1879
+ * Move a parked-service state file from the old wrong location into `proxybridge/`.
1880
+ * @returns {boolean} true when a usable state file is now at the canonical path.
1881
+ */
1882
+ export function migrateLegacyServiceState() {
1883
+ const legacy = legacyServiceStatePath()
1884
+ const target = serviceStatePath()
1885
+ if (existsSync(legacy) !== true) return existsSync(target)
1886
+ try {
1887
+ if (existsSync(target) !== true) {
1888
+ mkdirSync(redirectorHome(), { recursive: true, mode: 0o700 })
1889
+ writeFileSync(target, readFileSync(legacy), { mode: 0o600 })
1890
+ }
1891
+ unlinkSync(legacy)
1892
+ return true
1893
+ } catch {
1894
+ // Best effort: reading the legacy path still works below until the next try.
1895
+ return existsSync(target)
1896
+ }
1897
+ }
1898
+
1899
+ /**
1900
+ * Remember that we stopped the GUI's Windows service on the way in.
1901
+ *
1902
+ * ProxyBridge's service and its CLI are mutually exclusive (both want the WinDivert
1903
+ * handle), so starting the CLI means the service must yield — but silently leaving
1904
+ * a service the user installed stopped after our session is not acceptable either.
1905
+ */
1906
+ export function writeWindowsServiceState(state) {
1907
+ try {
1908
+ mkdirSync(redirectorHome(), { recursive: true, mode: 0o700 })
1909
+ writeFileSync(serviceStatePath(), JSON.stringify(Object.assign({ at: Date.now() }, state), null, 2), { mode: 0o600 })
1910
+ } catch {
1911
+ // Best effort: losing this only means the service is not restarted for us.
1912
+ }
1913
+ }
1914
+
1915
+ export function readWindowsServiceState() {
1916
+ migrateLegacyServiceState()
1917
+ try {
1918
+ return JSON.parse(readFileSync(serviceStatePath(), 'utf8'))
1919
+ } catch {
1920
+ return null
1921
+ }
1922
+ }
1923
+
1924
+ export function clearWindowsServiceState() {
1925
+ for (const path of [serviceStatePath(), legacyServiceStatePath()]) {
1926
+ try {
1927
+ unlinkSync(path)
1928
+ } catch {
1929
+ // Already gone.
1930
+ }
1931
+ }
1932
+ }
1933
+
1934
+ /**
1935
+ * Windows path of the file the elevated helper writes its report into.
1936
+ *
1937
+ * Start-Process can either elevate or redirect, never both, so the snippet writes
1938
+ * this file and the host reads it through the /mnt view.
1939
+ */
1940
+ export function elevatedOutputWindowsPath() {
1941
+ return windowsLogPath().replace(/dsh-ris-proxybridge\.log$/, 'dsh-ris-elevated.out')
1942
+ }
1943
+
1944
+ /** The same file as a path this process can read. */
1945
+ export function elevatedOutputLocalPath() {
1946
+ return windowsLogLocalPath().replace(/dsh-ris-proxybridge\.log$/, 'dsh-ris-elevated.out')
1947
+ }
1948
+
1949
+ /** First-line marker of this run's report; a leftover file carries an older one. */
1950
+ const ELEVATED_NONCE_PREFIX = '@RUN '
1951
+
1952
+ /**
1953
+ * Read the elevated helper's report, accepting only THIS run's.
1954
+ * @param {string} localPath - file as seen here.
1955
+ * @param {string} nonce - this run's id.
1956
+ * @returns {{state: 'pending'|'stale'|'match', output: string}} what was found.
1957
+ */
1958
+ function readElevatedReport(localPath, nonce) {
1959
+ // The nonce is the FIRST line, so read from the start; a tail read would cut it
1960
+ // off as soon as the snippet prints more than the tail budget.
1961
+ let text = ''
1962
+ try {
1963
+ text = readFileSync(localPath, 'utf8').slice(0, 1024 * 1024)
1964
+ } catch {
1965
+ return { state: 'pending', output: '' }
1966
+ }
1967
+ if (text.trim() === '') return { state: 'pending', output: '' }
1968
+ const lines = text.replace(/\r\n/g, '\n').split('\n')
1969
+ if (lines[0].trim() === `${ELEVATED_NONCE_PREFIX}${nonce}`) {
1970
+ return { state: 'match', output: lines.slice(1).join('\n').trim() }
1971
+ }
1972
+ return { state: 'stale', output: '' }
1973
+ }
1974
+
1975
+ /**
1976
+ * Run a PowerShell snippet elevated and bring its output back.
1977
+ *
1978
+ * Start-Process can either elevate or redirect, never both, so the snippet writes to
1979
+ * a file we then read. That file survives across calls, so the previous run's output
1980
+ * is a trap: it was read as this run's success and produced a "started" answer with
1981
+ * a dead pid (B1). We delete it first and only accept a report stamped with this
1982
+ * run's nonce; a stale-only observation is a failure with a readable reason.
1983
+ * @param {string} script - PowerShell body.
1984
+ * @param {number} timeoutMs - one overall deadline for launch + report.
1985
+ * @param {{localPath?: string, windowsPath?: string, nonce?: string, pollMs?: number, launch?: Function}} [options] - test seams.
1986
+ * @returns {Promise<{ok: boolean, output: string, nonce: string, timedOut: boolean, reason?: string}>} result.
1987
+ */
1988
+ async function psElevated(script, timeoutMs = 20000, options = {}) {
1989
+ const localPath = options.localPath ?? elevatedOutputLocalPath()
1990
+ const windowsPath = options.windowsPath ?? elevatedOutputWindowsPath()
1991
+ const nonce = typeof options.nonce === 'string' && options.nonce !== '' ? options.nonce : `run-${randomUUID()}`
1992
+ const pollMs = Number.isInteger(options.pollMs) && options.pollMs > 0 ? options.pollMs : 300
1993
+ const deadline = Date.now() + timeoutMs
1994
+ // The file is shared with earlier runs: a leftover must never answer for this one.
1995
+ try {
1996
+ unlinkSync(localPath)
1997
+ } catch {
1998
+ try {
1999
+ writeFileSync(localPath, '', { mode: 0o600 })
2000
+ } catch {
2001
+ // Read-only: the nonce check still rejects a stale report.
2002
+ }
2003
+ }
2004
+ const body = [
2005
+ "$ErrorActionPreference = 'Continue'",
2006
+ `$out = '${windowsPath.replace(/'/g, "''")}'`,
2007
+ `$nonce = '${nonce.replace(/'/g, "''")}'`,
2008
+ "$text = ''",
2009
+ `try { $text = (& { ${script} } 2>&1 | Out-String) } catch { $text = ('ERR: ' + $_.Exception.Message) }`,
2010
+ "(@('@RUN ' + $nonce) + @($text)) | Set-Content -Path $out -Encoding utf8",
2011
+ ].join('; ')
2012
+ const encoded = Buffer.from(body, 'utf16le').toString('base64')
2013
+ const launch = `Start-Process -FilePath 'powershell.exe' -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-EncodedCommand','${encoded}' -Verb RunAs -PassThru -WindowStyle Hidden | Out-Null`
2014
+ const launchEncoded = Buffer.from(launch, 'utf16le').toString('base64')
2015
+ const launchTimeout = Math.max(1000, deadline - Date.now())
2016
+ if (typeof options.launch === 'function') {
2017
+ await options.launch({ localPath, windowsPath, nonce, body, timeoutMs: launchTimeout })
2018
+ } else if (typeof probeHooks.elevatedLaunch === 'function') {
2019
+ await probeHooks.elevatedLaunch({ localPath, windowsPath, nonce, body, timeoutMs: launchTimeout })
2020
+ } else {
2021
+ spawnSyncText('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', launchEncoded], launchTimeout)
2022
+ }
2023
+ let sawStale = false
2024
+ while (Date.now() < deadline) {
2025
+ const report = readElevatedReport(localPath, nonce)
2026
+ if (report.state === 'match') return { ok: true, output: report.output, nonce, timedOut: false }
2027
+ if (report.state === 'stale') sawStale = true
2028
+ await new Promise((resolve) => setTimeout(resolve, pollMs))
2029
+ }
2030
+ const report = readElevatedReport(localPath, nonce)
2031
+ if (report.state === 'match') return { ok: true, output: report.output, nonce, timedOut: false }
2032
+ return {
2033
+ ok: false,
2034
+ output: '',
2035
+ nonce,
2036
+ timedOut: true,
2037
+ reason: sawStale === true
2038
+ ? '只读到上一轮的提权输出,本轮没有写出结果(UAC 未响应或脚本失败)'
2039
+ : '等待提权结果超时(UAC 未响应或脚本没有写出结果)',
2040
+ }
2041
+ }
2042
+
2043
+ /** Wait until a pid started through cmd.exe/UAC is actually up. */
2044
+ export async function waitForWindowsAlive(pid, timeoutMs = 3000) {
2045
+ if (Number.isInteger(pid) !== true || pid <= 0) return false
2046
+ const deadline = Date.now() + timeoutMs
2047
+ while (Date.now() < deadline) {
2048
+ await new Promise((resolve) => setTimeout(resolve, 250))
2049
+ const output = spawnSyncText('powershell.exe', [
2050
+ '-NoProfile', '-NonInteractive', '-Command',
2051
+ `if (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { 'alive' }`,
2052
+ ], 6000)
2053
+ if (/alive/.test(output)) return true
2054
+ }
2055
+ return false
2056
+ }
2057
+
2058
+ /** Restart the GUI service we stopped, if it is still installed. */
2059
+ export function restoreWindowsService() {
2060
+ const state = readWindowsServiceState()
2061
+ if (state === null || state.stoppedByUs !== true) return { restored: false, reason: '未停止过服务' }
2062
+ // Put the start type back first: we parked it on Manual so Windows would stop
2063
+ // resurrecting the service mid-session, and leaving it that way would change the
2064
+ // machine's boot behaviour behind the user's back.
2065
+ if (typeof state.originalStartType === 'string' && state.originalStartType !== '') {
2066
+ spawnSyncText('powershell.exe', [
2067
+ '-NoProfile', '-NonInteractive', '-Command',
2068
+ `Set-Service ProxyBridgeSvc -StartupType ${state.originalStartType} -ErrorAction SilentlyContinue`,
2069
+ ], 10000)
2070
+ }
2071
+ const output = spawnSyncText('powershell.exe', [
2072
+ '-NoProfile', '-NonInteractive', '-Command',
2073
+ "Start-Service ProxyBridgeSvc -ErrorAction SilentlyContinue; (Get-Service ProxyBridgeSvc -ErrorAction SilentlyContinue).Status",
2074
+ ], 20000)
2075
+ clearWindowsServiceState()
2076
+ if (/Running/i.test(output)) return { restored: true }
2077
+ return { restored: false, reason: `服务未能恢复(${output.trim().slice(0, 120) || '需要管理员'})` }
2078
+ }
2079
+
2080
+ /**
2081
+ * Assemble the status object from one detection snapshot.
2082
+ * @param {object} detection - detectRunningRedirector() result.
2083
+ * @param {'sync'|'async'} mode - async mode must never spawn (version comes from cache).
2084
+ * @returns {object} status.
2085
+ */
2086
+ function buildStatus(detection, mode) {
2087
+ const describe = (side) => {
2088
+ const found = findRedirector({ side })
2089
+ let version = ''
2090
+ if (found.found === true) {
2091
+ // The async route must not block 6 s on `--version`: take it from the cache.
2092
+ version = mode === 'async' ? (versionCache.get(found.path)?.version ?? '') : redirectorVersion(found.path)
2093
+ }
2094
+ // `missingBundle` + `reason` let the maintenance page say "download/upload the
2095
+ // component" instead of showing an unexplained empty path.
2096
+ return {
2097
+ available: found.found,
2098
+ path: found.path,
2099
+ kind: found.kind,
2100
+ version,
2101
+ missingBundle: found.missingBundle === true,
2102
+ ...(found.reason === undefined ? {} : { reason: found.reason }),
2103
+ }
2104
+ }
2105
+ const profilePath = redirectorProfilePath()
2106
+ return {
2107
+ local: describe('local'),
2108
+ windows: describe('windows'),
2109
+ profilePath,
2110
+ profileExists: existsSync(profilePath),
2111
+ running: detection.pid > 0,
2112
+ // 'proc' = started outside the plugin (the user pasted our command), so
2113
+ // `stop` will need their sudo as well.
2114
+ runningSource: detection.source,
2115
+ // Which machine owns the pid: a Windows redirector is stopped with taskkill,
2116
+ // never with a signal from this side.
2117
+ runningSide: detection.side || redirectorPidRecord().side,
2118
+ // Per side: the rules only apply where the bridge actually runs.
2119
+ runningLocal: detection.local.pid > 0,
2120
+ runningWindows: detection.windows.pid > 0,
2121
+ localPid: detection.local.pid,
2122
+ windowsPid: detection.windows.pid,
2123
+ pid: detection.pid,
2124
+ logPath: redirectorLogPath(),
2125
+ elevated: hasElevation(),
2126
+ }
2127
+ }
2128
+
2129
+ /**
2130
+ * Current redirector state, synchronously (the CLI, the exit hook, editors).
2131
+ *
2132
+ * Every probe is cached (pid table 5 s, alive 5 s, version 60 s), so repeated calls
2133
+ * stop costing 3–4 s of blocked event loop per status render.
2134
+ * @returns {object} state.
2135
+ */
2136
+ export function redirectorStatus() {
2137
+ return buildStatus(detectRunningRedirector(), 'sync')
2138
+ }
2139
+
2140
+ /**
2141
+ * Status for HTTP routes: cached for STATUS_TTL_MS, so a burst of requests costs
2142
+ * one detection instead of one each.
2143
+ * @param {{ttlMs?: number}} [options] - override the TTL (tests).
2144
+ * @returns {object} status plus `{cached, ageMs}`.
2145
+ */
2146
+ export function redirectorStatusCached(options = {}) {
2147
+ const now = Date.now()
2148
+ const ttl = Number.isInteger(options.ttlMs) && options.ttlMs >= 0 ? options.ttlMs : STATUS_TTL_MS
2149
+ if (statusCache.value !== null && now - statusCache.at < ttl) {
2150
+ return Object.assign({}, statusCache.value, { cached: true, ageMs: now - statusCache.at })
2151
+ }
2152
+ const value = redirectorStatus()
2153
+ statusCache = { at: Date.now(), value }
2154
+ return Object.assign({}, value, { cached: false, ageMs: 0 })
2155
+ }
2156
+
2157
+ /**
2158
+ * Status for HTTP routes, fully asynchronous: no spawnSync, no blocked event loop.
2159
+ * Concurrent callers share one in-flight probe instead of stacking PowerShell runs.
2160
+ * @param {{ttlMs?: number}} [options] - override the TTL (tests).
2161
+ * @returns {Promise<object>} status plus `{cached, ageMs}`.
2162
+ */
2163
+ export async function redirectorStatusAsync(options = {}) {
2164
+ const now = Date.now()
2165
+ const ttl = Number.isInteger(options.ttlMs) && options.ttlMs >= 0 ? options.ttlMs : STATUS_TTL_MS
2166
+ if (statusCache.value !== null && now - statusCache.at < ttl) {
2167
+ return Object.assign({}, statusCache.value, { cached: true, ageMs: now - statusCache.at })
2168
+ }
2169
+ if (statusInflight !== null) return statusInflight
2170
+ statusInflight = (async () => {
2171
+ try {
2172
+ const detection = await detectRunningRedirectorAsync()
2173
+ const value = buildStatus(detection, 'async')
2174
+ statusCache = { at: Date.now(), value }
2175
+ return Object.assign({}, value, { cached: false, ageMs: 0 })
2176
+ } finally {
2177
+ statusInflight = null
2178
+ }
2179
+ })()
2180
+ return statusInflight
2181
+ }
2182
+
2183
+ /**
2184
+ * Export the profile and (only when we already have the rights) start it.
2185
+ *
2186
+ * When we cannot elevate we still write the profile and return the command, so the
2187
+ * user can paste it — better than a failure that leaves nothing behind.
2188
+ * @param {string} cwd - workspace whose rules are exported.
2189
+ * @param {{upstream?: 'socks'|'engine', start?: boolean, verbose?: number}} [options] - behaviour.
2190
+ * @returns {Promise<object>} summary with `written`, `command`, `started`/`pid`, or `reason`.
2191
+ */
2192
+ export async function syncRedirector(cwd, options = {}) {
2193
+ const config = readProxyConfig(cwd)
2194
+ const written = writeRedirectorProfile(config, { upstream: options.upstream })
2195
+ const found = findRedirector({ side: options.side })
2196
+ if (found.found === false) {
2197
+ return { written, command: '', started: false, reason: found.reason ?? '未找到 ProxyBridge CLI(可用 DSH_RIS_IDE_PROXYBRIDGE 指定,或在维护页「代理 → 组件」上传/下载组件)', missingBundle: found.missingBundle === true }
2198
+ }
2199
+ const command = redirectorCommand({ cliPath: found.path, profilePath: written.path, verbose: options.verbose })
2200
+ if (options.start === false) return { written, command, started: false, reason: '' }
2201
+ const running = redirectorPid()
2202
+ if (running > 0) return { written, command, started: false, pid: running, reason: '已在运行(先 stop)' }
2203
+ if (hasElevation() === false) return { written, command, started: false, reason: '需要管理员/sudo:请执行上面的命令' }
2204
+ const child = spawn(command.command, command.args, { detached: true, stdio: 'ignore' })
2205
+ child.unref()
2206
+ writeRedirectorPid(child.pid)
2207
+ return { written, command, started: true, pid: child.pid }
2208
+ }
2209
+
2210
+ /**
2211
+ * Start the system-level interception that pairs with the proxy engine.
2212
+ *
2213
+ * The engine alone cannot cover a program it did not spawn, so the two are
2214
+ * started together: every side that has a ProxyBridge CLI and is not running yet
2215
+ * is launched, and an elevation prompt (UAC on Windows) is the expected outcome
2216
+ * rather than an error. A side that needs a password we cannot type is reported
2217
+ * with the command instead of failing the whole start.
2218
+ * @param {{sides?: string[], verbose?: number}} [options] - sides to consider, in order.
2219
+ * @returns {Promise<{started: object[], skipped: object[], running: boolean}>} per-side outcome.
2220
+ */
2221
+ export async function startRedirectors(options = {}) {
2222
+ // Never pop an elevation prompt from a test run: node --test marks its children
2223
+ // with NODE_TEST_CONTEXT, and a UAC dialog would block the suite on a desktop
2224
+ // nobody is watching.
2225
+ if (process.env.NODE_TEST_CONTEXT !== undefined) {
2226
+ return { started: [], skipped: [{ side: '', reason: '测试环境不启动系统层拦截' }], running: false }
2227
+ }
2228
+ // A Windows host has only one machine: 'local' would resolve to the same
2229
+ // ProxyBridge_CLI.exe and the second start would fight for the WinDivert handle.
2230
+ // The plugin now ships that CLI, so the default there is the windows side alone.
2231
+ const sides = Array.isArray(options.sides) && options.sides.length > 0
2232
+ ? options.sides
2233
+ : (process.platform === 'win32' ? ['windows'] : ['windows', 'local'])
2234
+ // `reload` applies edited rules to a bridge that is already running.
2235
+ const reload = options.reload === true
2236
+ const started = []
2237
+ const skipped = []
2238
+ const detection = detectRunningRedirector()
2239
+ // On a Windows host there is no second machine: 'local' and 'windows' resolve to
2240
+ // the same ProxyBridge_CLI.exe, and starting it twice means two engines fighting
2241
+ // for the WinDivert handle. Keep the first side that claims a given binary.
2242
+ const claimed = new Set()
2243
+ for (const side of sides) {
2244
+ const found = findRedirector({ side })
2245
+ if (found.found !== true) {
2246
+ skipped.push({ side, reason: found.reason ?? `未找到 ${side === 'windows' ? 'Windows' : '本侧'} ProxyBridge`, missingBundle: found.missingBundle === true })
2247
+ continue
2248
+ }
2249
+ if (claimed.has(found.path)) {
2250
+ skipped.push({ side, reason: '与另一侧是同一个可执行文件(单机 Windows),已由该侧启动' })
2251
+ continue
2252
+ }
2253
+ claimed.add(found.path)
2254
+ // One redirector per side: an already running engine there owns the hook.
2255
+ const runningHere = side === 'windows' ? detection.windows : detection.local
2256
+ if (runningHere.pid > 0) {
2257
+ // Editing rules must not require another UAC: the elevated watchdog restarts
2258
+ // the CLI with the profile we just wrote (it reads the profile only at start).
2259
+ if (reload === true) {
2260
+ const reloaded = await reloadRedirector({ side, pid: runningHere.pid })
2261
+ if (reloaded.reloaded === true) started.push({ side, pid: reloaded.pid ?? runningHere.pid, reloaded: true })
2262
+ else skipped.push({ side, reason: reloaded.reason, pid: runningHere.pid })
2263
+ continue
2264
+ }
2265
+ skipped.push({ side, reason: `已在运行(pid ${runningHere.pid})`, pid: runningHere.pid })
2266
+ continue
2267
+ }
2268
+ const result = await startRedirector({ side, verbose: options.verbose })
2269
+ if (result.started === true) started.push(result)
2270
+ else skipped.push(Object.assign({ side }, result))
2271
+ }
2272
+ return { started, skipped, running: started.length > 0 || detection.pid > 0 }
2273
+ }
2274
+
2275
+ /**
2276
+ * Rewrite the profile for a workspace and reload whichever bridges are running.
2277
+ *
2278
+ * This is the helper a save-rules route should call (B3): the old route asked the
2279
+ * redirectors to "reload" without writing the new profile first, so the watchdog
2280
+ * restarted the CLI on the OLD rules and the UI said "已重启".
2281
+ * @param {string} cwd - workspace whose proxy rules were just saved.
2282
+ * @param {{sides?: string[], upstream?: 'socks'|'engine', timeoutMs?: number, profilePath?: string}} [options] - behaviour.
2283
+ * @returns {Promise<{ok: boolean, written: {path: string, rules: number, skipped: object[]}, reloaded: object[], skipped: object[], reason?: string}>} outcome.
2284
+ */
2285
+ export async function reloadRedirectorsWithProfile(cwd, options = {}) {
2286
+ // A Windows host has only one machine: 'local' would resolve to the same
2287
+ // ProxyBridge_CLI.exe and the second start would fight for the WinDivert handle.
2288
+ // The plugin now ships that CLI, so the default there is the windows side alone.
2289
+ const sides = Array.isArray(options.sides) && options.sides.length > 0
2290
+ ? options.sides
2291
+ : (process.platform === 'win32' ? ['windows'] : ['windows', 'local'])
2292
+ let written = null
2293
+ try {
2294
+ written = writeRedirectorProfile(readProxyConfig(cwd), { upstream: options.upstream, path: options.profilePath })
2295
+ } catch (error) {
2296
+ // A profile with no usable rule is a real failure: a reload would restart the
2297
+ // bridge with rules that proxy nothing.
2298
+ return { ok: false, written: null, reloaded: [], skipped: [], reason: `规则未能写入:${error?.message ?? error}` }
2299
+ }
2300
+ const detection = detectRunningRedirector()
2301
+ const reloaded = []
2302
+ const skipped = []
2303
+ for (const side of sides) {
2304
+ const runningHere = side === 'windows' ? detection.windows : detection.local
2305
+ if (runningHere.pid <= 0) {
2306
+ skipped.push({ side, reason: '未运行' })
2307
+ continue
2308
+ }
2309
+ if (side !== 'windows') {
2310
+ skipped.push({ side, pid: runningHere.pid, reason: '本侧由 root 启动,编辑规则请重启(sudo)' })
2311
+ continue
2312
+ }
2313
+ const result = await reloadRedirector({ side, pid: runningHere.pid, timeoutMs: options.timeoutMs })
2314
+ if (result.reloaded === true) reloaded.push({ side, pid: result.pid ?? runningHere.pid })
2315
+ else skipped.push({ side, pid: runningHere.pid, reason: result.reason })
2316
+ }
2317
+ return { ok: reloaded.length > 0, written, reloaded, skipped }
2318
+ }
2319
+
2320
+ /**
2321
+ * Restart a running bridge so it picks up the profile on disk.
2322
+ *
2323
+ * The CLI parses `--profile` once at start, so edited rules otherwise only apply
2324
+ * after a manual stop/start (which costs a UAC prompt). The watchdog is already
2325
+ * elevated: it kills the CLI and starts it again from the recorded spec.
2326
+ *
2327
+ * The watchdog's report is structured and must prove the new process is alive with
2328
+ * the recorded profile (B4): "the done file exists" used to be the whole check, so a
2329
+ * failed restart still reported success. On success the NEW pid is recorded (M2).
2330
+ * @param {{side?: string, pid?: number, timeoutMs?: number}} options - which side and how long to wait.
2331
+ * @returns {Promise<{reloaded: boolean, pid?: number, reason: string}>} outcome.
2332
+ */
2333
+ export async function reloadRedirector(options = {}) {
2334
+ const side = options.side === 'windows' ? 'windows' : 'local'
2335
+ if (side !== 'windows') return { reloaded: false, reason: '本侧由 root 启动,编辑规则请重启(sudo)' }
2336
+ if (watchdogPid() <= 0) return { reloaded: false, reason: '没有提权看门狗(旧版本启动的),请停止后重新启动一次' }
2337
+ const id = `reload-${randomUUID()}`
2338
+ clearReloadSignals()
2339
+ // The seam lets a test answer the request itself (no real watchdog needed).
2340
+ const requested = typeof probeHooks.requestReload === 'function'
2341
+ ? probeHooks.requestReload({ id }) === true
2342
+ : requestRedirectorReload({ id }) === true
2343
+ if (requested !== true) return { reloaded: false, reason: '无法写入重载请求' }
2344
+ const timeoutMs = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 8000
2345
+ const deadline = Date.now() + timeoutMs
2346
+ while (Date.now() < deadline) {
2347
+ const done = readReloadDone()
2348
+ if (done !== null && done.ok === true && (done.legacy === true || done.id === '' || done.id === id)) {
2349
+ // A done file that cannot name a live new process is not evidence of success.
2350
+ if (done.legacy === true || done.pid <= 0) {
2351
+ return { reloaded: false, reason: '看门狗报告成功但没有新进程 pid(旧版看门狗),请停止后重新启动一次' }
2352
+ }
2353
+ if (pidAliveOn(done.pid, 'windows', { force: true }) !== true) {
2354
+ return { reloaded: false, reason: `看门狗报告新进程 ${done.pid} 但已不在运行(规则可能有问题)` }
2355
+ }
2356
+ const specs = readCliSpec()
2357
+ if (specs !== null) writeRedirectorPid(done.pid, 'windows')
2358
+ return { reloaded: true, pid: done.pid, reason: '已按新规则重启桥接' }
2359
+ }
2360
+ const failed = readReloadFailure()
2361
+ if (failed !== null && failed.ok !== true) {
2362
+ return { reloaded: false, reason: `看门狗重载失败:${failed.error || '未知原因'}` }
2363
+ }
2364
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 150))
2365
+ }
2366
+ return { reloaded: false, reason: `看门狗未在 ${Math.round(timeoutMs / 1000)}s 内完成重载` }
2367
+ }
2368
+
2369
+ /**
2370
+ * Stop the redirector started by startRedirector(), both sides if needed.
2371
+ *
2372
+ * It runs as root (Linux) or elevated (Windows), so a normal user cannot signal
2373
+ * it: the failure is reported as "run this as root" rather than thrown, because
2374
+ * the caller (a web route) has no way to elevate.
2375
+ *
2376
+ * Detection comes first (B5): "the recorded pid is dead" is not "nothing runs" —
2377
+ * a CLI started by hand, or after a lost pid file, still intercepts.
2378
+ * @param {{graceMs?: number, side?: 'local'|'windows'}} [options] - how long to wait / one side.
2379
+ * @returns {Promise<{stopped: boolean, pid?: number, side?: string, reason?: string, results?: object[]}>} outcome.
2380
+ */
2381
+ export async function stopRedirector(options = {}) {
2382
+ const detection = detectRunningRedirector()
2383
+ if (detection.pid === 0) {
2384
+ // Drop dead records so status stops advertising a pid that does not exist.
2385
+ for (const side of ['windows', 'local']) {
2386
+ if (redirectorPidRecord(side).pid > 0) clearRedirectorPid(side)
2387
+ }
2388
+ return { stopped: false, reason: '未在运行' }
2389
+ }
2390
+ const results = []
2391
+ if (detection.windows.pid > 0) {
2392
+ results.push(Object.assign({ side: 'windows' }, stopRedirectorSync(Object.assign({}, options, { side: 'windows' }))))
2393
+ }
2394
+ if (detection.local.pid > 0) {
2395
+ results.push(Object.assign({ side: 'local' }, await stopLocalRedirectorAsync(detection.local.pid, options)))
2396
+ }
2397
+ const stopped = results.filter((result) => result.stopped === true)
2398
+ if (stopped.length === 0) {
2399
+ return {
2400
+ stopped: false,
2401
+ pid: detection.pid,
2402
+ reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未能停止桥接',
2403
+ results,
2404
+ }
2405
+ }
2406
+ return { stopped: true, pid: stopped[0].pid, side: stopped[0].side, results }
2407
+ }
2408
+
2409
+ /** Graceful local stop with SIGKILL fallback (the exit hook used to do this inline). */
2410
+ async function stopLocalRedirectorAsync(pid, options = {}) {
2411
+ try {
2412
+ process.kill(pid, 'SIGTERM')
2413
+ } catch (error) {
2414
+ const code = error?.code ?? ''
2415
+ return {
2416
+ stopped: false,
2417
+ pid,
2418
+ reason: code === 'EPERM' ? `需要管理员/sudo:sudo kill ${pid}` : `无法停止进程 ${pid}(${code || error?.message})`,
2419
+ }
2420
+ }
2421
+ const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 5000)
2422
+ while (Date.now() < limit) {
2423
+ if (pidAlive(pid) === false) break
2424
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 120))
2425
+ }
2426
+ if (pidAlive(pid)) {
2427
+ try { process.kill(pid, 'SIGKILL') } catch { /* still privileged: report below */ }
2428
+ }
2429
+ if (pidAlive(pid)) return { stopped: false, pid, reason: `进程 ${pid} 仍在运行(需要 sudo kill ${pid})` }
2430
+ clearRedirectorPid('local')
2431
+ return { stopped: true, pid }
2432
+ }
2433
+
2434
+ /** Run a command and return its combined output as text (no throw). */
2435
+ /**
2436
+ * The Windows spelling of a path this side of the OS boundary can see.
2437
+ *
2438
+ * `Start-Process -FilePath '/mnt/d/…'` fails with "系统找不到指定的文件": mnt paths are
2439
+ * WSL-only. `wslpath -w` is authoritative when present (it also handles the
2440
+ * `\\wsl.localhost\<distro>` form for our home directory); the drive-letter
2441
+ * rewrite is the fallback for a distro without it.
2442
+ * @param {string} path - an absolute Linux path, possibly under /mnt/<drive>.
2443
+ * @returns {string} the same location as Windows sees it.
2444
+ */
2445
+ export function windowsPathOf(path) {
2446
+ const text = String(path ?? '')
2447
+ if (text === '') return text
2448
+ if (/^[A-Za-z]:[\\/]/.test(text)) return text
2449
+ // /mnt/<letter>/ IS drive <letter> by definition, and doing it first keeps the
2450
+ // answer right even for a path that does not exist yet (`wslpath` would then
2451
+ // answer with a \\wsl.localhost\… share that Windows cannot open).
2452
+ const mounted = /^\/mnt\/([A-Za-z])\/(.*)$/.exec(text)
2453
+ if (mounted !== null) return `${mounted[1].toUpperCase()}:\\${mounted[2].replace(/\//g, '\\')}`
2454
+ const converted = spawnSyncText('wslpath', ['-w', text], 4000).trim()
2455
+ if (converted !== '' && /^[A-Za-z]:[\\/]|^\\\\/.test(converted)) return converted
2456
+ return text
2457
+ }
2458
+
2459
+ /**
2460
+ * Translate only the argv entries that really are existing files.
2461
+ *
2462
+ * ProxyBridge's own flags look like paths (`/d`, `/p:key=value`), so "starts with
2463
+ * `/`" is not enough: translating those into `\d` / `\p:key=value` corrupts the
2464
+ * command line. Windows-spelled values (`C:\…`, `\\wsl.localhost\…`) are already
2465
+ * correct for the other side and must be left untouched.
2466
+ * @param {object[]} args - argv as this side spells it.
2467
+ * @returns {object[]} Windows-spelled argv.
2468
+ */
2469
+ function windowsArgsOf(args) {
2470
+ return args.map((arg) => {
2471
+ if (typeof arg !== 'string' || arg.startsWith('/') !== true) return arg
2472
+ try {
2473
+ if (existsSync(arg) !== true || statSync(arg).isFile() !== true) return arg
2474
+ } catch {
2475
+ return arg
2476
+ }
2477
+ return windowsPathOf(arg)
2478
+ })
2479
+ }
2480
+
2481
+ function spawnSyncText(command, args, timeoutMs) {
2482
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: timeoutMs, windowsHide: true })
2483
+ return `${result.stdout ?? ''}${result.stderr ?? ''}`
2484
+ }
2485
+
2486
+ export const __test = {
2487
+ PROFILE_VERSION,
2488
+ bundledBundleDir,
2489
+ bundleCacheInstalled,
2490
+ ensureBundleReady,
2491
+ MISSING_BUNDLE_HINT,
2492
+ startRedirector,
2493
+ stopRedirectorSync,
2494
+ pidAliveOn,
2495
+ pidAliveOnAsync,
2496
+ redirectorPidRecord,
2497
+ detectRunningRedirector,
2498
+ detectRunningRedirectorAsync,
2499
+ stopRedirector,
2500
+ redirectorVendorDir,
2501
+ redirectorHome,
2502
+ redirectorProfilePath,
2503
+ buildProfile,
2504
+ processPattern,
2505
+ redirectorCommand,
2506
+ findRedirector,
2507
+ redirectorCandidates,
2508
+ writeRedirectorProfile,
2509
+ redirectorStatus,
2510
+ redirectorStatusCached,
2511
+ redirectorStatusAsync,
2512
+ reloadRedirector,
2513
+ reloadRedirectorsWithProfile,
2514
+ redirectorPid,
2515
+ writeRedirectorPid,
2516
+ clearRedirectorPid,
2517
+ redirectorSidePidPath,
2518
+ serviceStatePath,
2519
+ migrateLegacyPidFile,
2520
+ migrateLegacyServiceState,
2521
+ windowsRedirectorPids,
2522
+ windowsRedirectorPidsAsync,
2523
+ readReloadDone,
2524
+ readReloadFailure,
2525
+ setProbeHooks,
2526
+ resetProbeHooks,
2527
+ clearProbeCaches,
2528
+ sleepSync,
2529
+ psElevated,
2530
+ watchdogPid,
2531
+ writeWatchdogPid,
2532
+ reloadDonePath,
2533
+ reloadFailedPath,
2534
+ windowsPathOf,
2535
+ windowsArgsOf,
2536
+ }
2537
+
2538
+ const SELF = basename(process.argv[1] ?? '')
2539
+ if (/^redirector\.mjs$|^redirector\.js$/.test(SELF)) {
2540
+ const command = process.argv[2] ?? 'status'
2541
+ const cwd = process.argv[3] ?? process.cwd()
2542
+ const run = async () => {
2543
+ if (command === 'status') {
2544
+ console.log(JSON.stringify(redirectorStatus(), null, 2))
2545
+ return
2546
+ }
2547
+ if (command === 'sync' || command === 'start' || command === 'profile') {
2548
+ const result = await syncRedirector(cwd, { start: command === 'start' })
2549
+ console.log(JSON.stringify(result, null, 2))
2550
+ if (result.written) console.log(`profile: ${result.written.path} (${result.written.rules} 条规则)`)
2551
+ if (result.command) console.log(`命令: ${result.command.display}`)
2552
+ return
2553
+ }
2554
+ console.error(`unknown command "${command}" (status|profile|sync|start)`)
2555
+ process.exitCode = 1
2556
+ }
2557
+ await run()
2558
+ }