dsh-ris-ide 1.7.2 → 1.7.3

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