dsh-ris-ide 1.8.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/redirector.js CHANGED
@@ -31,8 +31,8 @@
31
31
  */
32
32
 
33
33
  import { execFile, spawn, spawnSync } from 'node:child_process'
34
- import { randomUUID } from 'node:crypto'
35
- import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
34
+ import { createHash, randomUUID } from 'node:crypto'
35
+ import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
36
36
  import { homedir } from 'node:os'
37
37
  import { basename, dirname, extname, join } from 'node:path'
38
38
  import { promisify } from 'node:util'
@@ -113,6 +113,8 @@ function clearProbeCaches() {
113
113
  // inherit a previous run's materialised folder (or a remembered failure).
114
114
  localAppDataCache = null
115
115
  windowsBundlePrepared = null
116
+ windowsBundleFailure = null
117
+ windowsBundleFailureCache = null
116
118
  }
117
119
 
118
120
  /**
@@ -140,6 +142,56 @@ function sleepSync(ms) {
140
142
  }
141
143
  }
142
144
 
145
+ /** Sleep without blocking the event loop (the UAC wait can take tens of seconds). */
146
+ function sleepAsync(ms) {
147
+ return new Promise((resolve) => setTimeout(resolve, ms))
148
+ }
149
+
150
+ /**
151
+ * Run a program and wait for it to exit without blocking the event loop.
152
+ *
153
+ * The elevated start is launched through a UAC consent dialog: `spawnSync` returned
154
+ * only after the user answered, which froze the whole daemon (3 s heartbeat, HTTP
155
+ * routes, log follow) for up to 45 s. A hung dialog is killed at `timeoutMs`.
156
+ * @param {string} command - executable.
157
+ * @param {string[]} args - argv.
158
+ * @param {number} timeoutMs - kill the launcher after this long.
159
+ * @returns {Promise<{code: number|null, timedOut: boolean}>} exit status.
160
+ */
161
+ function spawnDetachedText(command, args, timeoutMs) {
162
+ return new Promise((resolve) => {
163
+ let child = null
164
+ let timedOut = false
165
+ let settled = false
166
+ const finish = (code) => {
167
+ if (settled === true) return
168
+ settled = true
169
+ clearTimeout(timer)
170
+ resolve({ code, timedOut })
171
+ }
172
+ const timer = setTimeout(() => {
173
+ timedOut = true
174
+ try { child?.kill() } catch { /* the dialog outlives the launcher */ }
175
+ finish(null)
176
+ }, timeoutMs)
177
+ timer.unref?.()
178
+ try {
179
+ child = spawn(command, args, { stdio: 'ignore', windowsHide: true })
180
+ } catch {
181
+ finish(null)
182
+ return
183
+ }
184
+ child.on('error', () => finish(null))
185
+ child.on('exit', (code) => finish(code))
186
+ child.unref?.()
187
+ })
188
+ }
189
+
190
+ /** Quote one argv entry for bash: `'` becomes `'\''`, so a path can't break out. */
191
+ function shellQuote(value) {
192
+ return "'" + String(value).replace(/'/g, "'\\''") + "'"
193
+ }
194
+
143
195
  /** Where our profile/pid/log live: one folder beside the shared proxy config. */
144
196
  export function redirectorHome() {
145
197
  return join(proxyHomeDir(), REDIRECTOR_DIRNAME)
@@ -474,6 +526,9 @@ function copyBundleFile(from, to, options = {}) {
474
526
  * not installed yet (caller must show "未安装,请下载/上传").
475
527
  */
476
528
  export function prepareWindowsBundle(options = {}) {
529
+ // Every attempt starts with a clean diagnosis: a previous failure (locked DLL, no
530
+ // %LOCALAPPDATA%, missing bundle) must not be reported for this one (review B-P2-14).
531
+ windowsBundleFailure = null
477
532
  const fingerprint = bundleFingerprint()
478
533
  if (options.force !== true && windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint === fingerprint) {
479
534
  // The folder can disappear between calls (user cleanup); redo it rather than
@@ -493,14 +548,27 @@ export function prepareWindowsBundle(options = {}) {
493
548
  const refresh = options.force === true
494
549
  || (windowsBundlePrepared !== null && windowsBundlePrepared.fingerprint !== fingerprint)
495
550
  || materialisedFingerprint(target) !== fingerprint
551
+ // A copy that fails (locked DLL, antivirus, permissions) stays broken for a while;
552
+ // retrying four multi-MB copies through /mnt/c on every status poll is pointless
553
+ // (review B-P2-13). Cache the failure for a TTL; `force` retries immediately.
554
+ const failureKey = `${target}|${fingerprint}`
555
+ if (options.force !== true && windowsBundleFailureCache !== null
556
+ && windowsBundleFailureCache.key === failureKey
557
+ && Date.now() - windowsBundleFailureCache.at < MATERIALISE_RETRY_MS) {
558
+ windowsBundleFailure = { ...windowsBundleFailureCache.failure }
559
+ return ''
560
+ }
496
561
  const source = bundledRedirectorDir({ platform: 'win32' })
497
562
  const names = ['ProxyBridge_CLI.exe', 'ProxyBridgeCore.dll', 'WinDivert.dll', 'WinDivert64.sys']
498
563
  let complete = true
564
+ /** @type {{code: string, message: string, file: string}|null} */
565
+ let firstError = null
499
566
  for (const name of names) {
500
567
  try {
501
568
  if (copyBundleFile(join(source, name), join(target, name), { force: refresh }) !== true) complete = false
502
- } catch {
569
+ } catch (error) {
503
570
  complete = false
571
+ firstError ??= { code: String(error?.code ?? 'copy-failed'), message: String(error?.message ?? error), file: name }
504
572
  }
505
573
  }
506
574
  // The licence texts live at the root of the cached distribution (they cover both
@@ -516,11 +584,34 @@ export function prepareWindowsBundle(options = {}) {
516
584
  }
517
585
  // Only the machine-wide materialisation is worth caching; a caller passing
518
586
  // targetDir is testing (or preparing an explicit folder) and must not poison it.
519
- if (complete === true) rememberMaterialised(target, fingerprint)
587
+ if (complete === true) {
588
+ rememberMaterialised(target, fingerprint)
589
+ windowsBundleFailure = null
590
+ windowsBundleFailureCache = null
591
+ } else {
592
+ windowsBundleFailure = firstError === null
593
+ ? { code: 'copy-failed', message: '文件没有完整复制', file: '' }
594
+ : { ...firstError, target }
595
+ windowsBundleFailureCache = { key: failureKey, at: Date.now(), failure: { ...windowsBundleFailure } }
596
+ }
520
597
  if (options.targetDir === undefined) windowsBundlePrepared = complete ? { dir: target, fingerprint } : null
521
598
  return complete ? target : ''
522
599
  }
523
600
 
601
+ // Why the last materialise attempt failed (`''` target vs a real copy error). The
602
+ // old code printed「无法确定 %LOCALAPPDATA%」for both, which sent people looking at
603
+ // environment variables when the truth was a locked DLL (review m11624).
604
+ let windowsBundleFailure = null
605
+ /** Minimum time between retries of a failed materialisation (review B-P2-13). */
606
+ const MATERIALISE_RETRY_MS = 60 * 1000
607
+ /** Last failure, keyed by target+fingerprint so a new bundle retries at once. */
608
+ let windowsBundleFailureCache = null
609
+
610
+ /** Diagnosis of the last failed {@link prepareWindowsBundle} (`null` after a success). */
611
+ export function windowsBundleDiagnosis() {
612
+ return windowsBundleFailure === null ? null : { ...windowsBundleFailure }
613
+ }
614
+
524
615
  /** Actionable text for "the distribution was never downloaded/uploaded". */
525
616
  export const MISSING_BUNDLE_HINT = `ProxyBridge 组件未安装:打开 risd 维护页「代理 → 组件」点「下载」(或上传 ris-proxy.tgz);也可设 DSH_RIS_IDE_PROXYBRIDGE_URL 指向 tgz。默认地址:${DEFAULT_BUNDLE_URL}`
526
617
 
@@ -863,7 +954,23 @@ function Write-Log($message) {
863
954
  }
864
955
 
865
956
  Write-Log "started pid=$PID"
957
+ # Single instance (m11702): every bridge start spawns a watchdog and nothing killed
958
+ # the previous one while the heartbeat stayed fresh, so restarts piled them up. Two
959
+ # watchdogs then restart the CLI at the same time — one wins the WinDivert handle,
960
+ # the other loads the rules and captures nothing. A named mutex makes the second
961
+ # copy exit instead of accumulating.
962
+ $mutexName = ${quote(paths.mutexName ?? 'Global\\dsh-ris-ide-proxybridge-watchdog')}
963
+ $watchdogMutex = New-Object System.Threading.Mutex($false, $mutexName)
964
+ if (-not $watchdogMutex.WaitOne(0)) { Write-Log 'another watchdog owns the mutex; exiting'; exit 0 }
866
965
  $specFile = ${quote(paths.cliSpec ?? '')}
966
+ $ownProfile = ${quote(paths.profile ?? '')}
967
+ # Only CLIs that carry THIS home's profile are ours: the machine may run another
968
+ # dsh-ris-ide home's bridge, and a teardown must not take it down (review A4-P2-1).
969
+ function Get-OwnCli {
970
+ $all = @(Get-CimInstance Win32_Process -Filter "Name='ProxyBridge_CLI.exe'" -ErrorAction SilentlyContinue)
971
+ if ($ownProfile -eq '') { return @($all) }
972
+ return @($all | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })
973
+ }
867
974
  $reloadFile = ${quote(paths.reloadRequest ?? '')}
868
975
  $reloadDone = ${quote(paths.reloadDone ?? '')}
869
976
  $reloadFailed = ${quote(paths.reloadFailed ?? '')}
@@ -885,14 +992,14 @@ while ($true) {
885
992
  try {
886
993
  if (-not (Test-Path $specFile)) { throw 'no cli spec' }
887
994
  $spec = Get-Content -Path $specFile -Raw | ConvertFrom-Json
888
- Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force
995
+ (Get-OwnCli) | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
889
996
  Start-Sleep -Milliseconds 400
890
997
  Start-Process -FilePath $spec.exe -ArgumentList @($spec.args) -WindowStyle Hidden -RedirectStandardOutput $spec.log -RedirectStandardError ($spec.log + '.err') | Out-Null
891
998
  Start-Sleep -Milliseconds 1500
892
999
  # Liveness alone is not enough: the host's old CLI may still be dying, and
893
1000
  # ProxyBridge.exe is a different process. Match the profile on the command line.
894
1001
  $profileArg = [string]$spec.args[1]
895
- $cim = @(Get-CimInstance Win32_Process -Filter "Name='ProxyBridge_CLI.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID })
1002
+ $cim = @(Get-OwnCli | Where-Object { $_.ProcessId -ne $PID })
896
1003
  $running = @($cim | Where-Object { $profileArg -ne '' -and $_.CommandLine -like ('*' + $profileArg + '*') })
897
1004
  $count = $running.Count
898
1005
  if ($count -gt 0) { $pidText = [string]$running[0].ProcessId } else { $errorText = 'the new CLI is not running with the recorded profile' }
@@ -923,7 +1030,8 @@ while ($true) {
923
1030
 
924
1031
  Write-Log "cleaning up ($reason)"
925
1032
  Remove-Item $reloadFile -Force -ErrorAction SilentlyContinue
926
- Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force
1033
+ # Own-profile CLIs only; another home's bridge keeps running (review A4-P2-1).
1034
+ (Get-OwnCli) | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
927
1035
  if (Test-Path $stateFile) {
928
1036
  # Give the GUI service its hook back: undo the park we did at start.
929
1037
  $state = Get-Content -Path $stateFile -Raw | ConvertFrom-Json
@@ -965,21 +1073,36 @@ export function posixToWindowsPath(value) {
965
1073
 
966
1074
  /** Write the watchdog script and return its WINDOWS path (it runs over there). */
967
1075
  export function writeWatchdogScript() {
968
- const script = windowsWatchdogScript({
969
- heartbeat: windowsPathOf(heartbeatPath()),
970
- // The canonical writer path: the watchdog's teardown reads exactly this file.
971
- stateFile: windowsPathOf(serviceStatePath()),
972
- logFile: windowsPathOf(windowsLogLocalPath()),
973
- stopRequest: windowsPathOf(stopRequestPath()),
974
- stoppedMarker: windowsPathOf(stoppedMarkerPath()),
975
- cliSpec: windowsPathOf(join(proxyHomeDir(), CLI_SPEC_FILENAME)),
976
- reloadRequest: windowsPathOf(reloadRequestPath()),
977
- reloadDone: windowsPathOf(reloadDonePath()),
978
- reloadFailed: windowsPathOf(reloadFailedPath()),
979
- })
1076
+ // The mutex must be shared by all watchdogs of ONE home (two different homes may
1077
+ // legitimately each run their own bridge): derive it from the heartbeat path.
1078
+ // Global\\ so two RDP sessions of the same user still see the same mutex (the
1079
+ // watchdog guards a machine-wide WinDivert handle, review B-P2-6). Single-user
1080
+ // machines keep the old semantics: one watchdog per home, second one exits.
1081
+ const mutexName = `Global\\dsh-ris-ide-proxybridge-watchdog-${createHash('sha1').update(heartbeatPath()).digest('hex').slice(0, 12)}`
1082
+ let script
1083
+ try {
1084
+ script = windowsWatchdogScript({
1085
+ mutexName,
1086
+ heartbeat: windowsPathOf(heartbeatPath(), { mustConvert: true }),
1087
+ // The canonical writer path: the watchdog's teardown reads exactly this file.
1088
+ stateFile: windowsPathOf(serviceStatePath(), { mustConvert: true }),
1089
+ logFile: windowsPathOf(windowsLogLocalPath(), { mustConvert: true }),
1090
+ stopRequest: windowsPathOf(stopRequestPath(), { mustConvert: true }),
1091
+ stoppedMarker: windowsPathOf(stoppedMarkerPath(), { mustConvert: true }),
1092
+ cliSpec: windowsPathOf(join(proxyHomeDir(), CLI_SPEC_FILENAME), { mustConvert: true }),
1093
+ profile: windowsPathOf(redirectorProfilePath(), { mustConvert: true }),
1094
+ reloadRequest: windowsPathOf(reloadRequestPath(), { mustConvert: true }),
1095
+ reloadDone: windowsPathOf(reloadDonePath(), { mustConvert: true }),
1096
+ reloadFailed: windowsPathOf(reloadFailedPath(), { mustConvert: true }),
1097
+ })
1098
+ } catch (error) {
1099
+ // A Linux spelling passed to powershell -File fails silently; surfacing it here
1100
+ // lets startRedirector answer with a real reason instead of "started" (B-P2-12).
1101
+ throw new Error(`无法把看门狗脚本的路径转换为 Windows 形式:${error?.message ?? error}`)
1102
+ }
980
1103
  mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
981
1104
  writeFileSync(watchdogScriptPath(), script, { mode: 0o600 })
982
- return windowsPathOf(watchdogScriptPath())
1105
+ return windowsPathOf(watchdogScriptPath(), { mustConvert: true })
983
1106
  }
984
1107
 
985
1108
  export async function startRedirector(options = {}) {
@@ -993,11 +1116,27 @@ export async function startRedirector(options = {}) {
993
1116
  }
994
1117
  const profile = writeRedirectorProfile(readProxyConfig(''), { path: options.profilePath })
995
1118
  const plan = redirectorCommand({ cliPath: found.path, profilePath: profile.path, verbose: options.verbose, platform: side === 'windows' ? 'win32' : 'linux' })
1119
+ // Serialise detect-then-spawn across processes (daemon vs plugin fallback): two
1120
+ // concurrent starters used to create two engines / two elevated helpers (m11773).
1121
+ const lock = await acquireStartLock(side, { timeoutMs: options.lockTimeoutMs })
1122
+ if (lock.ok !== true) return { started: false, side, command: plan.display, reason: lock.reason ?? '另一个进程正在启动桥接' }
1123
+ try {
996
1124
  const running = detectRunningRedirector()
997
1125
  // Per side: the other side's process must not make this start look redundant.
998
1126
  const sameSide = IS_WINDOWS === true ? running.windows : side === 'windows' ? running.windows : running.local
999
1127
  if (sameSide.pid > 0) {
1000
- if (side !== 'windows' || IS_WINDOWS === true) return { started: false, side, pid: sameSide.pid, command: plan.display, reason: '已在运行(先停止)' }
1128
+ if (side !== 'windows' || IS_WINDOWS === true) {
1129
+ // Local side: a lost pid file used to hide duplicates forever. Reap every
1130
+ // extra engine so "already running" also means "exactly one is running".
1131
+ let reaped = 0
1132
+ if (side === 'local') {
1133
+ for (const pid of localRedirectorOwnPids()) {
1134
+ if (pid === sameSide.pid) continue
1135
+ try { process.kill(pid, 'SIGTERM'); reaped += 1 } catch { /* already gone */ }
1136
+ }
1137
+ }
1138
+ return { started: false, side, pid: sameSide.pid, command: plan.display, reason: '已在运行(先停止)', reaped }
1139
+ }
1001
1140
  // Windows: the engine may be a hand-started CLI, or one whose pid file we lost.
1002
1141
  // It still holds the hook, so take it over instead of refusing to start.
1003
1142
  const killed = await killWindowsCliProcesses()
@@ -1008,26 +1147,56 @@ export async function startRedirector(options = {}) {
1008
1147
  }
1009
1148
  if (side === 'windows') {
1010
1149
  // PowerShell resolves paths as WINDOWS does: /mnt/d/… is invisible there, and the
1011
- // profile we just wrote lives in the Linux home. Both have to be translated.
1012
- const exePath = windowsPathOf(found.path)
1013
- const winArgs = windowsArgsOf(plan.args)
1014
- const winLog = windowsPathOf(windowsLogPath())
1015
- // Fresh start: no stale stop request may remain, and the heartbeat has to exist
1016
- // BEFORE the watchdog looks at it (a missing file counts as stale).
1017
- clearStopSignals()
1018
- clearReloadSignals()
1019
- writeHeartbeat()
1020
- const watchdogScript = writeWatchdogScript()
1150
+ // profile we just wrote lives in the Linux home. Both have to be translated —
1151
+ // and a failure must be reported, not papered over with a Linux path that
1152
+ // PowerShell cannot open (review B-P2-12).
1153
+ let exePath = ''
1154
+ let winArgs = []
1155
+ let winLog = ''
1156
+ let ownProfile = ''
1157
+ let watchdogScript = ''
1158
+ let startTypeHint = ''
1159
+ try {
1160
+ exePath = windowsPathOf(found.path, { mustConvert: true })
1161
+ winArgs = windowsArgsOf(plan.args, { mustConvert: true })
1162
+ winLog = windowsPathOf(windowsLogPath())
1163
+ ownProfile = windowsPathOf(profile.path, { mustConvert: true })
1164
+ startTypeHint = windowsPathOf(startTypeHintPath(), { mustConvert: true })
1165
+ // Fresh start: no stale stop request may remain, and the heartbeat has to exist
1166
+ // BEFORE the watchdog looks at it (a missing file counts as stale).
1167
+ clearStopSignals()
1168
+ clearReloadSignals()
1169
+ writeHeartbeat()
1170
+ watchdogScript = writeWatchdogScript()
1171
+ } catch (error) {
1172
+ return { started: false, side, command: plan.display, reason: error?.message ?? '无法把启动路径转换为 Windows 形式' }
1173
+ }
1021
1174
  const quote = (value) => `'${String(value).replace(/'/g, "''")}'`
1175
+ // Global\: the mutexes guard machine-wide resources (the WinDivert handle and the
1176
+ // one watchdog), so two RDP sessions of the same user must not each take "the"
1177
+ // mutex — the per-home sha suffix keeps separate proxy homes independent.
1178
+ // Global\\ for the same reason as the watchdog mutex: a start in another RDP
1179
+ // session races for the same machine-wide WinDivert handle (single-user boxes
1180
+ // are unaffected).
1181
+ const startMutexName = `Global\\dsh-ris-ide-proxybridge-start-${createHash('sha1').update(join(proxyHomeDir(), 'locks')).digest('hex').slice(0, 12)}`
1022
1182
  // One elevated helper does the whole dance: the GUI's service and the CLI both
1023
1183
  // want the WinDivert handle (mutually exclusive), a stale CLI has to go, and only
1024
1184
  // an already-elevated process may redirect the CLI's output (-Verb RunAs cannot
1025
1185
  // redirect). So: stop service → kill stale CLI → start CLI with logs → report.
1026
1186
  const script = [
1187
+ // One start at a time across processes (m11773): two elevated helpers racing
1188
+ // each stop the "other" CLI and start their own, ending with two CLIs alive.
1189
+ `$startMutex = New-Object System.Threading.Mutex($false, ${quote(startMutexName)})`,
1190
+ "if (-not $startMutex.WaitOne(30000)) { 'start-busy=True;done=1'; return }",
1027
1191
  '$svcWas = $false',
1192
+ `$startTypeHint = ${quote(startTypeHint)}`,
1193
+ // Leave the original service start type behind for the JS side: if the CLI dies
1194
+ // before the report is parsed, the caller still has to put the service back
1195
+ // instead of leaving the machine "stopped + Manual" (review B-P1-3).
1028
1196
  '$svc = Get-Service ProxyBridgeSvc -ErrorAction SilentlyContinue',
1029
1197
  '$startType = $null',
1030
1198
  "if ($svc -ne $null) { $startType = $svc.StartType.ToString() }",
1199
+ 'if ($startType -ne $null) { Set-Content -Path $startTypeHint -Value $startType -Encoding ascii -ErrorAction SilentlyContinue }',
1031
1200
  "if ($svc -ne $null -and $svc.Status -eq 'Running') { Stop-Service ProxyBridgeSvc -Force -ErrorAction SilentlyContinue; $svcWas = $true; Start-Sleep -Milliseconds 900 }",
1032
1201
  // Only one process may own the WinDivert handle: if the service survived the
1033
1202
  // stop it will keep intercepting while our CLI silently captures nothing.
@@ -1036,35 +1205,76 @@ export async function startRedirector(options = {}) {
1036
1205
  // WinDivert handle: our CLI then runs without capturing anything (rules load,
1037
1206
  // no [CONN] lines) while every connection fails. Park it on Manual instead.
1038
1207
  "if ($svc -ne $null -and $startType -eq 'Automatic') { Set-Service ProxyBridgeSvc -StartupType Manual -ErrorAction SilentlyContinue; $parked = $true }",
1039
- 'Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue',
1040
- 'Start-Sleep -Milliseconds 500',
1208
+ // Only CLIs of THIS home are in our way: another dsh-ris-ide home (or a user's
1209
+ // own ProxyBridge) may run its own bridge with its own profile, and killing it
1210
+ // would take down that bridge instead of ours (review A4-P2-1/B-P1-4).
1211
+ `$ownProfile = ${quote(ownProfile)}`,
1212
+ '$ownCim = @(Get-CimInstance Win32_Process -Filter "Name=\'ProxyBridge_CLI.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })',
1213
+ 'if ($ownCim.Count -gt 0) { $ownCim | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 500 }',
1041
1214
  `$log = ${quote(winLog)}`,
1042
1215
  'if (Test-Path $log) { Remove-Item $log -Force -ErrorAction SilentlyContinue }',
1043
1216
  `$argList = @(${winArgs.map(quote).join(',')})`,
1044
1217
  `$p = Start-Process -FilePath ${quote(exePath)} -ArgumentList $argList -PassThru -WindowStyle Hidden -RedirectStandardOutput $log -RedirectStandardError ($log + '.err')`,
1045
1218
  'Start-Sleep -Milliseconds 2000',
1046
1219
  '$alive = [bool](Get-Process -Id $p.Id -ErrorAction SilentlyContinue)',
1047
- // Two CLIs would both try to bind WinDivert: keep ours, drop anything else
1048
- // (a leftover from an earlier session, or one the IDE started meanwhile).
1049
- '$all = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue)',
1220
+ // Two CLIs would both try to bind WinDivert: keep ours, drop anything else that
1221
+ // carries THIS home's profile (a leftover from an earlier session, or one the
1222
+ // IDE started meanwhile). Other homes' CLIs are out of scope.
1223
+ '$all = @(Get-CimInstance Win32_Process -Filter "Name=\'ProxyBridge_CLI.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })',
1050
1224
  '$dups = $all.Count - 1',
1051
- 'if ($dups -gt 0) { $all | Where-Object { $_.Id -ne $p.Id } | Stop-Process -Force -ErrorAction SilentlyContinue; Start-Sleep -Milliseconds 500 }',
1052
- '$final = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue).Count',
1225
+ 'if ($dups -gt 0) { $all | Where-Object { $_.ProcessId -ne $p.Id } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 500 }',
1226
+ '$final = @(Get-CimInstance Win32_Process -Filter "Name=\'ProxyBridge_CLI.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($ownProfile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count',
1053
1227
  // Killing an elevated CLI and restarting the service need admin, which we only
1054
1228
  // have inside this script: spawn the watchdog here so teardown never asks for
1055
1229
  // a second UAC (it ends on a stop request or when the heartbeat goes stale).
1230
+ // One watchdog per machine (m11702): a previous start left one behind, and on
1231
+ // the next reload/stale heartbeat it starts a SECOND CLI. Kill the leftovers
1232
+ // in the same elevated context that creates the new one — but only those that
1233
+ // run THIS home's watchdog script (another home has its own, per-home mutex;
1234
+ // review B-P2-4).
1235
+ `$wdScript = ${quote(watchdogScript)}`,
1236
+ '$oldWatchdogs = @(Get-CimInstance Win32_Process -Filter "Name=\'powershell.exe\'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($wdScript, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })',
1237
+ 'if ($oldWatchdogs.Count -gt 0) { $oldWatchdogs | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 300 }',
1056
1238
  `$wd = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File', ${quote(watchdogScript)}) -PassThru -WindowStyle Hidden`,
1057
1239
  'Start-Sleep -Milliseconds 400',
1058
- '"pid=$($p.Id);svc=$svcWas;startType=$startType;parked=$([bool]$parked);alive=$alive;dups=$dups;count=$final;watchdog=$($wd.Id);done=1"',
1240
+ // Only a fully successful start removes the hint; a failed one leaves it for
1241
+ // the caller to restore the service (review B-P1-3).
1242
+ 'if ($alive -eq $true) { Remove-Item $startTypeHint -Force -ErrorAction SilentlyContinue }',
1243
+ '"pid=$($p.Id);svc=$svcWas;startType=$startType;parked=$([bool]$parked);alive=$alive;dups=$dups;count=$final;own=$($all.Count);watchdog=$($wd.Id);oldWatchdogs=$($oldWatchdogs.Count);done=1"',
1059
1244
  ].join('; ')
1060
- const elevated = await psElevated(script, 45000)
1245
+ // Waiting for the UAC prompt is exactly the window in which the old watchdog
1246
+ // judges our heartbeat stale and tears the bridge down. Keep beating while the
1247
+ // launcher blocks (it may take seconds), so a slow UAC is not a bridge outage
1248
+ // (review B-P0-1).
1249
+ const beat = setInterval(() => { try { writeHeartbeat() } catch {} }, 3000)
1250
+ beat.unref?.()
1251
+ let elevated
1252
+ try {
1253
+ elevated = await psElevated(script, 45000)
1254
+ } finally {
1255
+ clearInterval(beat)
1256
+ }
1061
1257
  // B1: no report for THIS run means the start did not happen — never parse the
1062
1258
  // previous run's leftover output (it looked like success with a dead pid).
1063
1259
  if (elevated.ok !== true) {
1260
+ // The helper may still have stopped the service before it failed; the hint
1261
+ // file (if any) tells recoverWindowsService() what to restore.
1262
+ recoverWindowsService()
1064
1263
  return { started: false, side, command: plan.display, reason: elevated.reason }
1065
1264
  }
1066
1265
  const output = elevated.output
1266
+ // A concurrent start (another window, or the daemon while the plugin fell back)
1267
+ // means the elevated helper could not take the start mutex: report it instead of
1268
+ // pretending a second CLI is fine (m11773). Must be checked BEFORE the pid parse:
1269
+ // this report carries no pid, so the old order always answered with the generic
1270
+ // "未能启动(…)" (review B-P2-1).
1271
+ if (/start-busy=True/.test(output)) {
1272
+ return { started: false, side, command: plan.display, reason: '另一个进程正在启动 Windows 侧拦截,请稍后再试' }
1273
+ }
1067
1274
  if (/svcRunning=True/.test(output)) {
1275
+ // The service was already stopped (and maybe parked) by the script; restore it
1276
+ // instead of leaving the machine with a dead service (review B-P1-3).
1277
+ recoverWindowsService()
1068
1278
  return {
1069
1279
  started: false,
1070
1280
  side,
@@ -1074,6 +1284,7 @@ export async function startRedirector(options = {}) {
1074
1284
  }
1075
1285
  const pid = Number.parseInt((output.match(/pid=(\d+)/) ?? [])[1] ?? '', 10)
1076
1286
  if (Number.isInteger(pid) === false || pid <= 0) {
1287
+ recoverWindowsService()
1077
1288
  return {
1078
1289
  started: false,
1079
1290
  side,
@@ -1107,6 +1318,7 @@ export async function startRedirector(options = {}) {
1107
1318
  const alive = /alive=True/i.test(output)
1108
1319
  if (alive !== true) {
1109
1320
  clearRedirectorPid('windows')
1321
+ recoverWindowsService()
1110
1322
  const log = `${readTail(windowsLogLocalPath(), 4096)}\n${readTail(`${windowsLogLocalPath()}.err`, 2048)}`.trim()
1111
1323
  return {
1112
1324
  started: false,
@@ -1116,6 +1328,7 @@ export async function startRedirector(options = {}) {
1116
1328
  reason: `启动后退出(${log.split('\n').filter((line) => line.trim() !== '').slice(-3).join(' / ').slice(0, 240) || '日志为空'})`,
1117
1329
  }
1118
1330
  }
1331
+ clearStartTypeHint()
1119
1332
  return {
1120
1333
  started: true,
1121
1334
  pid,
@@ -1137,10 +1350,454 @@ export async function startRedirector(options = {}) {
1137
1350
  if (probe.status === 0) {
1138
1351
  const child = spawn('sudo', ['-n', found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1139
1352
  child.unref()
1140
- writeRedirectorPid(child.pid, 'local')
1141
- return { started: true, pid: child.pid, side, command: plan.display }
1353
+ // `sudo` is a supervisor, not the CLI: recording its pid made a later stop kill
1354
+ // the supervisor and report success while the root CLI kept the eBPF hook — the
1355
+ // same trap as pkexec (review B-P1-2). Adopt the real CLI once it appears.
1356
+ const cliPid = await waitForOwnLocalPid({ timeoutMs: options.sudoWaitMs ?? SUDO_CLI_WAIT_MS })
1357
+ const pid = cliPid > 0 ? cliPid : child.pid
1358
+ writeRedirectorPid(pid, 'local')
1359
+ return { started: true, pid, side, command: plan.display, method: 'sudo', askerPid: child.pid }
1360
+ }
1361
+ // Only a user-initiated start may raise an interactive prompt (review B-P0-2): the
1362
+ // reconciler runs every minute, so pkexec/terminal here would pop a polkit dialog
1363
+ // or a whole terminal window per minute on a box where sudo -n is unavailable.
1364
+ // Background starts stop at the `manual` answer below.
1365
+ if (options.interactive !== true) {
1366
+ return { started: false, side, command: plan.display, method: 'manual', reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1367
+ }
1368
+ // 「提权启动」: when sudo is not passwordless, pkexec can still ask through the
1369
+ // desktop's polkit agent (WSLg only — a plain WSL has no agent and exits at once).
1370
+ // It must run detached: the dialog belongs to the agent, and the daemon must not
1371
+ // hold a pipe that would keep the (root) child waiting.
1372
+ if (pkexecAvailable() === true) {
1373
+ const child = spawn('pkexec', [found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1374
+ child.unref()
1375
+ // `pkexec` is only the asker: it forks the elevated CLI and waits for it. Writing
1376
+ // the asker's pid made a later "stop" kill pkexec and report success while the
1377
+ // root CLI kept the hook (review B-P1-2). The CLI is identified by THIS home's
1378
+ // profile path, so a password delay does not turn into a false "already dead".
1379
+ const cliPid = await waitForOwnLocalPid({ timeoutMs: options.pkexecWaitMs })
1380
+ if (cliPid > 0) {
1381
+ writeRedirectorPid(cliPid, 'local')
1382
+ return { started: true, pid: cliPid, side, command: plan.display, method: 'pkexec', askerPid: child.pid }
1383
+ }
1384
+ if (await pidAliveAfter(child.pid, PKEXEC_GRACE_MS) === true) {
1385
+ // The dialog is waiting for a password; the CLI does not exist yet. Do not
1386
+ // write a pid we cannot verify, and do not claim a successful start.
1387
+ return {
1388
+ started: false,
1389
+ side,
1390
+ command: plan.display,
1391
+ method: 'pkexec',
1392
+ deferred: true,
1393
+ reason: '已请求提权:在密码对话框里完成授权后系统层拦截就会启动(如果对话框还开着)',
1394
+ }
1395
+ }
1396
+ return {
1397
+ started: false,
1398
+ side,
1399
+ command: plan.display,
1400
+ method: 'pkexec',
1401
+ reason: '提权窗口没有完成(这台机器可能没有图形认证代理):请在终端里执行上面的命令,或给 sudo 配置免密',
1402
+ }
1403
+ }
1404
+ // A desktop terminal can take the password for us: open one in which the CLI
1405
+ // starts as root, then report that we are waiting. That beats a dead pkexec on a
1406
+ // WSL box without a polkit agent, and the window is the user's to watch (m12782).
1407
+ const opened = await openElevatedTerminal(plan.display, side, { argv: [found.path, ...plan.args] })
1408
+ if (opened === true) {
1409
+ return {
1410
+ started: false,
1411
+ side,
1412
+ command: plan.display,
1413
+ method: 'terminal',
1414
+ deferred: true,
1415
+ reason: '已打开终端窗口:输入 sudo 密码后系统层拦截就会启动(这个窗口可以关闭)',
1416
+ }
1417
+ }
1418
+ return { started: false, side, command: plan.display, method: 'manual', reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1419
+ } finally {
1420
+ lock.release()
1421
+ }
1422
+ }
1423
+
1424
+ /** How long a detached pkexec ask may take before we call it failed (ms). */
1425
+ const PKEXEC_GRACE_MS = 2500
1426
+
1427
+ /**
1428
+ * How long to wait for the real CLI after spawning pkexec (ms).
1429
+ *
1430
+ * The password is typed by a human, so the CLI appears well after `spawn` returns;
1431
+ * recording the asker instead was the bug (review B-P1-2). If the CLI does not show
1432
+ * up in this window we report "deferred", never a fake success.
1433
+ */
1434
+ const PKEXEC_CLI_WAIT_MS = 8000
1435
+ /** Same adoption budget for `sudo -n`, where no password dialog is involved. */
1436
+ const SUDO_CLI_WAIT_MS = 3000
1437
+
1438
+ /**
1439
+ * Wait for our own local CLI to appear (matched by this home's profile path).
1440
+ * @param {{timeoutMs?: number}} [options] - override for tests.
1441
+ * @returns {Promise<number>} the CLI pid, or 0 when it never showed up.
1442
+ */
1443
+ async function waitForOwnLocalPid(options = {}) {
1444
+ const timeoutMs = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : PKEXEC_CLI_WAIT_MS
1445
+ const deadline = Date.now() + timeoutMs
1446
+ for (;;) {
1447
+ const pids = localRedirectorOwnPids()
1448
+ if (pids.length > 0) return pids[0]
1449
+ if (Date.now() >= deadline) return 0
1450
+ await sleepAsync(200)
1451
+ }
1452
+ }
1453
+
1454
+ /** Terminal emulators we know how to open a privileged command in (m12782). */
1455
+ const TERMINAL_CANDIDATES = [
1456
+ // Windows Terminal treats its first non-option token as the command line; a
1457
+ // leading `-e` is a WT option and shows its own usage error (m12840).
1458
+ // `--size` keeps the window small; `-f` (focus mode) maximizes it, so it is not
1459
+ // used anymore (m13083: the window is raised by focusWindowsTerminal instead).
1460
+ // Old WT builds reject unknown options the way they rejected `-e`, so the flags
1461
+ // only go in when the installed version is known to support them.
1462
+ // `--title` gives the window a stable name so the centering helper can find
1463
+ // exactly this window (WT hosts every window in one process, m13221).
1464
+ { bin: 'wt.exe', args: ['--size', '64,16', 'wsl.exe', '-e', 'bash', '-lc'], guardedFlags: 2 },
1465
+ { bin: 'x-terminal-emulator', args: ['-e', 'bash', '-lc'] },
1466
+ { bin: 'gnome-terminal', args: ['--', 'bash', '-lc'] },
1467
+ { bin: 'konsole', args: ['-e', 'bash', '-lc'] },
1468
+ { bin: 'xfce4-terminal', args: ['-x', 'bash', '-lc'] },
1469
+ { bin: 'mate-terminal', args: ['-e', 'bash', '-lc'] },
1470
+ { bin: 'xterm', args: ['-e', 'bash', '-lc'] },
1471
+ ]
1472
+
1473
+ /**
1474
+ * Whether a desktop session can show a terminal window. A headless box may still
1475
+ * have `xterm` on PATH, but spawning it only blocks/ fails — better to skip and
1476
+ * report the command than to claim a window was opened (m12884).
1477
+ * @returns {boolean} true with DISPLAY/WAYLAND_DISPLAY or an X11/Wayland session.
1478
+ */
1479
+ function hasGraphicalSession() {
1480
+ const type = String(process.env.XDG_SESSION_TYPE ?? '').toLowerCase()
1481
+ return Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY || type === 'x11' || type === 'wayland')
1482
+ }
1483
+
1484
+ /** Cached answer to "can this Windows Terminal take --focus?" (m12923). */
1485
+ let wtFocusCache = null
1486
+ /**
1487
+ * Read the installed Windows Terminal version once. `--focus` exists since 1.15,
1488
+ * and an unknown option makes WT show its own error window, so we only pass it
1489
+ * when we are sure (m12840 is the same failure mode with `-e`).
1490
+ * @returns {boolean} whether the host Windows Terminal understands --focus.
1491
+ */
1492
+ function wtSupportsFocus() {
1493
+ if (wtFocusCache !== null) return wtFocusCache
1494
+ try {
1495
+ const probe = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
1496
+ '(Get-AppxPackage Microsoft.WindowsTerminal).Version'], { encoding: 'utf8', timeout: 8000 })
1497
+ const match = /^(\d+)\.(\d+)/.exec(String(probe.stdout || '').trim())
1498
+ // `-f` (focus) and `--size` are safe from 1.15 on; older builds only get the
1499
+ // bare command line.
1500
+ wtFocusCache = match === null ? false : (Number(match[1]) > 1 || Number(match[2]) >= 15)
1501
+ } catch {
1502
+ wtFocusCache = false
1503
+ }
1504
+ return wtFocusCache
1505
+ }
1506
+
1507
+ /** The helper's state file lives this long at most; an old one is not "still open". */
1508
+ const ELEVATION_STATE_TTL_MS = 10 * 60 * 1000
1509
+
1510
+ /**
1511
+ * Canonical side name for the elevation helper: it only knows `local`/`windows`.
1512
+ * `linux` is the name the maintenance page uses for this side, so callers that pass
1513
+ * it must still find the file the helper wrote.
1514
+ * @param {string} side - any caller spelling.
1515
+ * @returns {'local'|'windows'|null} canonical side, or null for unknown input.
1516
+ */
1517
+ function normalizeElevationSide(side) {
1518
+ const text = String(side ?? '').toLowerCase()
1519
+ if (text === 'windows') return 'windows'
1520
+ if (text === '' || text === 'local' || text === 'linux') return 'local'
1521
+ return null
1522
+ }
1523
+
1524
+ /**
1525
+ * Whether the elevated-terminal window for a side is still open. The helper script
1526
+ * writes `<proxy home>/proxybridge/elevate-<side>.json` on start and removes it on
1527
+ * exit, which is exactly the lifetime of the window (m12923).
1528
+ *
1529
+ * A caller that has the proxy home (the daemon does) passes it as `home`; the state
1530
+ * file lives one level down, in `proxybridge/` (review B-P1-1 — reading
1531
+ * `<proxy home>/elevate-*.json` never found what the writer wrote).
1532
+ *
1533
+ * CONTRACT: `options.home` is the PROXY HOME (e.g. `proxyHomeDir()`), and this
1534
+ * function appends `proxybridge/` itself; the daemon does exactly that. Passing
1535
+ * `redirectorHome()` here would double the directory and the window would read as
1536
+ * closed — test/redirector.test.mjs pins this down.
1537
+ * @param {string} side 'linux' | 'windows' | 'local'.
1538
+ * @param {{home?: string}} [options] Proxy home override (tests).
1539
+ * @returns {{active: boolean, at?: string, pid?: number}} state.
1540
+ */
1541
+ export function readElevationState(side, options = {}) {
1542
+ const normalized = normalizeElevationSide(side)
1543
+ if (normalized === null) return { active: false }
1544
+ const base = options.home === undefined ? redirectorHome() : join(options.home, REDIRECTOR_DIRNAME)
1545
+ const path = join(base, 'elevate-' + normalized + '.json')
1546
+ try {
1547
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
1548
+ // A leftover file whose timestamp is old is not a window the user is looking at
1549
+ // (the helper normally removes it; a SIGKILL leaves it behind).
1550
+ const at = Date.parse(String(parsed.at ?? ''))
1551
+ if (Number.isFinite(at) === true && Date.now() - at > ELEVATION_STATE_TTL_MS) return { active: false }
1552
+ const pid = Number(parsed.pid)
1553
+ if (Number.isFinite(pid) && pid > 0) {
1554
+ try { process.kill(pid, 0) } catch (error) {
1555
+ if (error?.code !== 'EPERM') return { active: false }
1556
+ }
1557
+ }
1558
+ return { active: true, at: String(parsed.at ?? ''), pid: Number.isFinite(pid) ? pid : 0 }
1559
+ } catch {
1560
+ return { active: false }
1561
+ }
1562
+ }
1563
+
1564
+ /** @param {string} bin @returns {boolean} whether `bin` resolves on PATH. */
1565
+ function hasBinary(bin) {
1566
+ try {
1567
+ return spawnSync('sh', ['-lc', 'command -v ' + JSON.stringify(bin)], { encoding: 'utf8', timeout: 4000 }).status === 0
1568
+ } catch {
1569
+ return false
1142
1570
  }
1143
- return { started: false, side, command: plan.display, reason: '需要 root:请执行上面的命令(或给 sudo 配置免密)' }
1571
+ }
1572
+
1573
+ /**
1574
+ * The helper script a terminal window runs: it takes the sudo ticket in the
1575
+ * foreground (the window is the TTY), then detaches the CLI so closing the window
1576
+ * does not kill the interception (m12896). Split out so tests can check the text.
1577
+ * @param {string} command Display/executable command (`sudo /path/ProxyBridge …`).
1578
+ * @param {string} side Which side is being started (only names the script/log).
1579
+ * @param {{dir?: string, argv?: string[]}} [options] Directory override (tests use a
1580
+ * temp dir) and the exact argv when known.
1581
+ * @returns {{dir: string, scriptPath: string, logPath: string, body: string}} plan.
1582
+ */
1583
+ export function elevationScript(command, side, options = {}) {
1584
+ const normalizedSide = normalizeElevationSide(side) ?? 'local'
1585
+ const dir = options.dir ?? redirectorHome()
1586
+ const name = 'elevate-' + normalizedSide
1587
+ const scriptPath = join(dir, name + '.sh')
1588
+ const logPath = join(dir, name + '.log')
1589
+ const bare = String(command).replace(/^sudo\s+/, '')
1590
+ // An argv lets us quote every entry for bash; the display string came from a
1591
+ // path that a user (or DSH_RIS_IDE_PROXYBRIDGE) can choose, and pasting it raw
1592
+ // let a `"`/`$(…)` in a directory name break or inject into the detached line
1593
+ // (review B-P2-10).
1594
+ const detached = Array.isArray(options.argv) === true && options.argv.length > 0
1595
+ ? 'nohup sudo -n ' + options.argv.map(shellQuote).join(' ') + ' > "$LOG" 2>&1 &'
1596
+ : 'nohup sudo -n ' + bare + ' > "$LOG" 2>&1 &'
1597
+ // The CLI is the interceptor itself, so it must outlive the terminal: ask sudo
1598
+ // for a ticket in the foreground (that is where the password prompt belongs),
1599
+ // then start the CLI detached with `sudo -n` and close the window (m12896).
1600
+ const body = [
1601
+ '#!/bin/bash',
1602
+ '# generated by risd for 「提权启动」(m12782/m12896)',
1603
+ 'LOG=' + JSON.stringify(logPath),
1604
+ 'STATE=' + JSON.stringify(join(dir, name + '.json')),
1605
+ 'printf \'{"side":"%s","pid":%s,"at":"%s"}\\n\' ' + JSON.stringify(normalizedSide) + ' "$$" "$(date -Is)" > "$STATE"',
1606
+ 'trap \'rm -f "$STATE"\' EXIT',
1607
+ 'sudo -v || { echo; echo "没有拿到 sudo 授权,已取消。"; exit 1; }',
1608
+ detached,
1609
+ 'echo',
1610
+ 'echo "已在后台启动系统层拦截;日志:$LOG"',
1611
+ 'echo "这个窗口会自动关闭。"',
1612
+ 'sleep 1',
1613
+ '',
1614
+ ].join('\n')
1615
+ return { dir, scriptPath, logPath, body }
1616
+ }
1617
+
1618
+ /**
1619
+ * @param {string} command Display/executable command (`sudo /path/ProxyBridge …`).
1620
+ * @param {string} side Which side is being started (only names the script).
1621
+ * @param {{argv?: string[], verifyMs?: number}} [options] - exact argv for safe
1622
+ * quoting, and how long to wait for the helper's state file.
1623
+ * @returns {Promise<boolean>} true when a window actually started the helper.
1624
+ */
1625
+ async function openElevatedTerminal(command, side, options = {}) {
1626
+ // A test run must never pop a real terminal window (m13621): under `node --test`
1627
+ // the runner sets NODE_TEST_CONTEXT, and spawning here would leave a password
1628
+ // prompt on the developer's desktop for every suite run. Callers fall back to the
1629
+ // printed `manual` command, which is all a test can assert anyway.
1630
+ // DSH_RIS_IDE_ALLOW_TERMINAL=1 is the explicit opt-in for a manual check.
1631
+ if (process.env.NODE_TEST_CONTEXT !== undefined && process.env.DSH_RIS_IDE_ALLOW_TERMINAL !== '1') return false
1632
+ let script
1633
+ try {
1634
+ const plan = elevationScript(command, side, { argv: options.argv })
1635
+ mkdirSync(plan.dir, { recursive: true })
1636
+ writeFileSync(plan.scriptPath, plan.body, { mode: 0o755 })
1637
+ script = plan.scriptPath
1638
+ } catch {
1639
+ return false
1640
+ }
1641
+ let launched = false
1642
+ for (const candidate of TERMINAL_CANDIDATES) {
1643
+ // wt.exe is the WSL interop path (the Windows Terminal window belongs to the
1644
+ // host); the rest are X11/Wayland clients that need a session to attach to.
1645
+ if (candidate.bin !== 'wt.exe' && hasGraphicalSession() === false) continue
1646
+ if (hasBinary(candidate.bin) === false) continue
1647
+ const args = candidate.guardedFlags !== undefined && wtSupportsFocus() === false
1648
+ ? [...candidate.args.slice(candidate.guardedFlags), script]
1649
+ : [...candidate.args, script]
1650
+ try {
1651
+ if (candidate.bin === 'wt.exe') {
1652
+ // WT is launched by the helper itself, which then centers the new window.
1653
+ if (launchCenteredTerminal(args) === true) { launched = true; break }
1654
+ continue
1655
+ }
1656
+ const child = spawn(candidate.bin, args, { detached: true, stdio: 'ignore' })
1657
+ child.unref()
1658
+ launched = true
1659
+ break
1660
+ } catch { /* try the next one */ }
1661
+ }
1662
+ if (launched !== true) return false
1663
+ // A successful `spawn` is not a started window: ENOENT arrives as an async error,
1664
+ // and a broken wt.exe shim exits silently. The helper writes `<dir>/elevate-*.json`
1665
+ // as its first action, so that file is the proof (review B-P2-11).
1666
+ const stateSide = side === 'windows' ? 'windows' : 'local'
1667
+ const verifyMs = Number.isInteger(options.verifyMs) && options.verifyMs > 0 ? options.verifyMs : 4000
1668
+ for (let waited = 0; waited < verifyMs; waited += 100) {
1669
+ if (readElevationState(stateSide).active === true) return true
1670
+ await sleepAsync(100)
1671
+ }
1672
+ return false
1673
+ }
1674
+
1675
+ /**
1676
+ * Open Windows Terminal and center the window it creates (m13147/m13221/m13257).
1677
+ *
1678
+ * `wt.exe` has no "center me" flag, and Windows Terminal hosts every window in one
1679
+ * process, so neither `Get-Process WindowsTerminal` nor a window title can identify
1680
+ * *this* window reliably. The helper therefore launches `wt.exe` itself: it records
1681
+ * the CASCADIA windows that already exist, starts the terminal, then moves the one
1682
+ * new window to the middle of the work area.
1683
+ */
1684
+ const CENTER_TERMINAL_PS1 = [
1685
+ 'param([string]$ArgJson)',
1686
+ 'Add-Type -TypeDefinition @"',
1687
+ 'using System;',
1688
+ 'using System.Text;',
1689
+ 'using System.Collections.Generic;',
1690
+ 'using System.Runtime.InteropServices;',
1691
+ 'public class WinPos {',
1692
+ ' public delegate bool EnumProc(IntPtr h, IntPtr l);',
1693
+ ' [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }',
1694
+ ' [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);',
1695
+ ' [DllImport("user32.dll")] public static extern int GetClassName(IntPtr h, StringBuilder s, int n);',
1696
+ ' [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);',
1697
+ ' [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);',
1698
+ ' [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr h, int x, int y, int w, int ht, bool repaint);',
1699
+ ' [DllImport("user32.dll")] public static extern bool SystemParametersInfo(uint a, uint b, ref RECT r, uint f);',
1700
+ ' static List<IntPtr> Windows() {',
1701
+ ' var list = new List<IntPtr>();',
1702
+ ' EnumWindows((h, l) => {',
1703
+ ' if (!IsWindowVisible(h)) return true;',
1704
+ ' var c = new StringBuilder(256); GetClassName(h, c, 256);',
1705
+ ' if (c.ToString().IndexOf("CASCADIA", StringComparison.OrdinalIgnoreCase) >= 0) list.Add(h);',
1706
+ ' return true;',
1707
+ ' }, IntPtr.Zero);',
1708
+ ' return list;',
1709
+ ' }',
1710
+ ' public static string Handles() {',
1711
+ ' var parts = new List<string>();',
1712
+ ' foreach (var h in Windows()) parts.Add(h.ToString());',
1713
+ ' return string.Join(",", parts);',
1714
+ ' }',
1715
+ ' public static string CenterNew(string known) {',
1716
+ " var old = new HashSet<string>((known ?? \"\").Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries));",
1717
+ ' foreach (var h in Windows()) {',
1718
+ ' if (old.Contains(h.ToString())) continue;',
1719
+ ' var r = new RECT(); if (!GetWindowRect(h, out r)) continue;',
1720
+ ' int w = r.Right - r.Left, ht = r.Bottom - r.Top;',
1721
+ ' if (w <= 0 || ht <= 0) continue;',
1722
+ ' var wa = new RECT(); SystemParametersInfo(0x0030, 0, ref wa, 0);',
1723
+ ' int x = wa.Left + (wa.Right - wa.Left - w) / 2;',
1724
+ ' int y = wa.Top + (wa.Bottom - wa.Top - ht) / 2;',
1725
+ ' MoveWindow(h, x, y, w, ht, true);',
1726
+ ' return "moved " + h;',
1727
+ ' }',
1728
+ ' return "none";',
1729
+ ' }',
1730
+ '}',
1731
+ '"@',
1732
+ '$before = [WinPos]::Handles()',
1733
+ '$argv = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ArgJson)) | ConvertFrom-Json',
1734
+ "$cmd = ($argv | ForEach-Object { if ($_ -match '\\s') { '\"' + $_ + '\"' } else { $_ } }) -join ' '",
1735
+ "Start-Process -FilePath 'wt.exe' -ArgumentList $cmd | Out-Null",
1736
+ "$result = 'none'",
1737
+ "for ($i = 0; $i -lt 25 -and $result -eq 'none'; $i++) {",
1738
+ ' Start-Sleep -Milliseconds 200',
1739
+ ' $result = [WinPos]::CenterNew($before)',
1740
+ '}',
1741
+ ].join('\n')
1742
+
1743
+ /**
1744
+ * Launch Windows Terminal through the centering helper. Every argument crosses the
1745
+ * WSL boundary base64-encoded so quoting can never split the script path.
1746
+ * @param {string[]} argv Arguments for `wt.exe` (flags included).
1747
+ * @returns {boolean} true when the helper was spawned.
1748
+ */
1749
+ function launchCenteredTerminal(argv) {
1750
+ try {
1751
+ const scriptPath = join(redirectorHome(), 'center-terminal.ps1')
1752
+ writeFileSync(scriptPath, `${CENTER_TERMINAL_PS1}\n`, { mode: 0o600 })
1753
+ const argJson = Buffer.from(JSON.stringify(argv), 'utf8').toString('base64')
1754
+ // `windowsPathOf` (unlike posixToWindowsPath) turns a WSL home into the
1755
+ // \\wsl.localhost share that Windows PowerShell can actually open; passing a
1756
+ // bare /home/... path made `-File` fail silently and no window appeared (m13375).
1757
+ // It must be a real Windows path: falling back to the Linux spelling only hides
1758
+ // that failure (review B-P2-12).
1759
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
1760
+ '-WindowStyle', 'Hidden', '-File', windowsPathOf(scriptPath, { mustConvert: true }), '-ArgJson', argJson], { detached: true, stdio: 'ignore', windowsHide: true })
1761
+ child.unref()
1762
+ return true
1763
+ } catch {
1764
+ return false
1765
+ }
1766
+ }
1767
+
1768
+ /** Whether a polkit agent can be asked at all (m12606: 提权启动 button). *//** Whether a polkit agent can be asked at all (m12606: 提权启动 button). *//** Whether a polkit agent can be asked at all (m12606: 提权启动 button). */
1769
+ let pkexecCache = null
1770
+ /**
1771
+ * @returns {boolean} true when `pkexec` exists on PATH.
1772
+ */
1773
+ function pkexecAvailable() {
1774
+ if (pkexecCache !== null) return pkexecCache
1775
+ try {
1776
+ const probe = spawnSync('pkexec', ['--version'], { encoding: 'utf8', timeout: 4000, windowsHide: true })
1777
+ pkexecCache = probe.error === undefined && probe.status === 0
1778
+ } catch {
1779
+ pkexecCache = false
1780
+ }
1781
+ return pkexecCache
1782
+ }
1783
+
1784
+ /**
1785
+ * Wait briefly and report whether a detached child is still there, which is how we
1786
+ * tell "pkexec is showing its dialog / started the CLI" from "it bailed out".
1787
+ * @param {number} pid Child pid.
1788
+ * @param {number} ms How long to watch.
1789
+ * @returns {Promise<boolean>} true when the process is still alive at the end.
1790
+ */
1791
+ async function pidAliveAfter(pid, ms) {
1792
+ const deadline = Date.now() + ms
1793
+ while (Date.now() < deadline) {
1794
+ await new Promise((resolve) => setTimeout(resolve, 100))
1795
+ try { process.kill(pid, 0); return true } catch (error) {
1796
+ if (error?.code === 'EPERM') return true
1797
+ return false
1798
+ }
1799
+ }
1800
+ return true
1144
1801
  }
1145
1802
 
1146
1803
  /** Where the vendored distribution for a platform lives (machine-wide, shared). */
@@ -1175,9 +1832,22 @@ export function findRedirector(options = {}) {
1175
1832
  const prepared = options.targetDir === undefined ? prepareWindowsBundle() : prepareWindowsBundle({ targetDir: options.targetDir })
1176
1833
  if (typeof prepared === 'string' && prepared !== '') bundleDir = prepared
1177
1834
  else if (prepared === '' && missingBundle !== true && warnedBundleUnavailable !== true) {
1178
- // Downloaded, but this host has no Windows-addressable %LOCALAPPDATA%.
1835
+ // Downloaded, but the Windows copy could not be made. Two very different
1836
+ // causes used to share one misleading line (m11624): %LOCALAPPDATA% unknown
1837
+ // (no cmd.exe interop) vs a copy that failed (usually EACCES because the
1838
+ // running ProxyBridgeSvc holds the DLLs).
1179
1839
  warnedBundleUnavailable = true
1180
- console.error('[dsh-ris-ide] 无法确定 %LOCALAPPDATA%:Windows 侧代理桥将直接使用下载缓存里的路径。')
1840
+ const diagnosis = windowsBundleDiagnosis()
1841
+ if (diagnosis === null) {
1842
+ console.error('[dsh-ris-ide] 无法确定 %LOCALAPPDATA%:Windows 侧代理桥将直接使用下载缓存里的路径。')
1843
+ } else {
1844
+ // Only "the target is in use/busy" deserves the "stop the interception"
1845
+ // advice; ENOENT/EISDIR mean the copy itself is impossible (a bad bundle
1846
+ // or an unwritable %LOCALAPPDATA%), and telling people to stop a service
1847
+ // that is not running wastes their time.
1848
+ const busy = ['EBUSY', 'EPERM', 'EACCES', 'EEXIST'].includes(diagnosis.code)
1849
+ console.error(`[dsh-ris-ide] 复制 Windows 版 ProxyBridge 失败(${diagnosis.code}${diagnosis.file === '' ? '' : ':' + diagnosis.file}):${busy ? '目标文件可能正被运行中的系统层拦截占用,请先停掉系统层拦截再重启 dsh。' : '请检查下载缓存与 %LOCALAPPDATA% 的可写性。'}Windows 侧将直接使用下载缓存里的路径;要更新副本请先修复上述问题。`)
1850
+ }
1181
1851
  }
1182
1852
  } catch (error) {
1183
1853
  if (warnedBundleUnavailable !== true) {
@@ -1327,13 +1997,26 @@ export function writeRedirectorProfile(config, options = {}) {
1327
1997
  if (rules.length === 0) throw new Error('没有可导出的规则:ProxyBridge 要求至少一条启用且带程序的规则')
1328
1998
  const path = options.path ?? redirectorProfilePath()
1329
1999
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
1330
- writeFileSync(path, JSON.stringify(profile, null, 2), { mode: 0o600 })
2000
+ // Write-then-rename: the CLI reads this file while a rule edit may be writing it,
2001
+ // and a half-written profile made it start with no rules (review B-P2-3).
2002
+ const tmp = `${path}.${process.pid}.tmp`
1331
2003
  try {
1332
- chmodSync(path, 0o600)
1333
- } catch {
1334
- // Filesystems without POSIX modes (a Windows share) simply keep their default.
2004
+ writeFileSync(tmp, JSON.stringify(profile, null, 2), { mode: 0o600 })
2005
+ try {
2006
+ chmodSync(tmp, 0o600)
2007
+ } catch {
2008
+ // Filesystems without POSIX modes (a Windows share) simply keep their default.
2009
+ }
2010
+ renameSync(tmp, path)
2011
+ return { path, rules: rules.length, skipped }
2012
+ } finally {
2013
+ try { unlinkSync(tmp) } catch { /* renamed or never created */ }
1335
2014
  }
1336
- return { path, rules: rules.length, skipped }
2015
+ }
2016
+
2017
+ /** Quote one value for a single-quoted PowerShell literal (`'` becomes `''`). */
2018
+ function psQuote(value) {
2019
+ return "'" + String(value).replace(/'/g, "''") + "'"
1337
2020
  }
1338
2021
 
1339
2022
  /**
@@ -1342,14 +2025,28 @@ export function writeRedirectorProfile(config, options = {}) {
1342
2025
  * A hand-started CLI (or one whose pid file we lost) still owns the hook, and
1343
2026
  * ProxyBridge refuses to run twice — so "already running" means "get it out of the
1344
2027
  * way", not "give up".
2028
+ *
2029
+ * Only processes whose command line carries THIS home's profile path are ours: the
2030
+ * old machine-wide `Get-Process ProxyBridge_CLI | Stop-Process` killed another
2031
+ * dsh-ris-ide home's bridge (or a user's own instance) and then claimed success
2032
+ * (review A4-P2-1/B-P1-4). No match means "not ours", not "kill everything".
2033
+ * @param {{profilePath?: string}} [options] - profile override (tests).
1345
2034
  * @returns {Promise<{ok: boolean, killed?: number, reason?: string}>} outcome.
1346
2035
  */
1347
- export async function killWindowsCliProcesses() {
2036
+ export async function killWindowsCliProcesses(options = {}) {
2037
+ let profile = ''
2038
+ try {
2039
+ profile = windowsPathOf(String(options.profilePath ?? redirectorProfilePath()), { mustConvert: true })
2040
+ } catch (error) {
2041
+ return { ok: false, reason: error?.message ?? '无法确定本 home 的 profile 的 Windows 路径,未结束任何进程' }
2042
+ }
1348
2043
  const script = [
1349
2044
  "$ErrorActionPreference = 'Continue'",
1350
- '$found = @(Get-Process ProxyBridge_CLI -ErrorAction SilentlyContinue)',
2045
+ `$profile = ${psQuote(profile)}`,
2046
+ "$all = @(Get-CimInstance Win32_Process -Filter \"Name='ProxyBridge_CLI.exe'\" -ErrorAction SilentlyContinue)",
2047
+ "$found = @($all | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($profile, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 })",
1351
2048
  'if ($found.Count -eq 0) { "none"; return }',
1352
- '$found | Stop-Process -Force -ErrorAction SilentlyContinue',
2049
+ '$found | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }',
1353
2050
  'Start-Sleep -Milliseconds 800',
1354
2051
  '"killed=" + $found.Count',
1355
2052
  ].join('; ')
@@ -1358,7 +2055,9 @@ export async function killWindowsCliProcesses() {
1358
2055
  const output = elevated.output
1359
2056
  const killed = /killed=(\d+)/.exec(output)
1360
2057
  if (killed !== null) return { ok: true, killed: Number.parseInt(killed[1], 10) }
1361
- if (/none/.test(output)) return { ok: true, killed: 0 }
2058
+ if (/none/.test(output)) {
2059
+ return { ok: false, reason: '正在运行的 ProxyBridge_CLI 不属于当前 profile,未结束它(避免误杀别的实例)' }
2060
+ }
1362
2061
  return {
1363
2062
  ok: false,
1364
2063
  reason: /cancel|取消|拒绝|denied|1223/i.test(output)
@@ -1414,6 +2113,15 @@ export function redirectorCommand(options = {}) {
1414
2113
  export function stopRedirectorSync(options = {}) {
1415
2114
  const sides = options.side === 'local' || options.side === 'windows' ? [options.side] : ['windows', 'local']
1416
2115
  const results = sides.map((side) => Object.assign({ side }, stopRedirectorSideSync(side, options)))
2116
+ // The async path reaps engine duplicates whose pid file was lost; the exit hook
2117
+ // has to keep the same single-instance promise (review B-P2-7). Signals only,
2118
+ // never wait: this runs while dsh is exiting.
2119
+ if (sides.includes('local')) {
2120
+ for (const pid of localRedirectorOwnPids()) {
2121
+ if (results.some((result) => result.pid === pid && result.stopped === true)) continue
2122
+ try { process.kill(pid, 'SIGTERM') } catch { /* either gone, or root — reported elsewhere */ }
2123
+ }
2124
+ }
1417
2125
  const stopped = results.filter((result) => result.stopped === true)
1418
2126
  if (stopped.length > 0) {
1419
2127
  const first = stopped[0]
@@ -1421,6 +2129,20 @@ export function stopRedirectorSync(options = {}) {
1421
2129
  }
1422
2130
  // Nothing was even detected: keep the historical terse answer (the UI shows it).
1423
2131
  if (results.every((result) => result.pid === undefined)) return { stopped: false, reason: '未在运行' }
2132
+ // A root-owned engine cannot be signalled by us: never answer `stopped:true` for
2133
+ // it, and hand the caller the exact command that would finish the job (B-P1-2).
2134
+ const privileged = results.find((result) => result.stopped !== true && result.command !== undefined)
2135
+ if (privileged !== undefined) {
2136
+ return {
2137
+ stopped: false,
2138
+ pid: privileged.pid,
2139
+ side: privileged.side,
2140
+ command: privileged.command,
2141
+ hint: privileged.hint,
2142
+ reason: privileged.reason ?? '该系统层拦截由 root 启动,请用 sudo 停止',
2143
+ results,
2144
+ }
2145
+ }
1424
2146
  return { stopped: false, reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未发现运行中的桥接', results }
1425
2147
  }
1426
2148
 
@@ -1493,17 +2215,42 @@ function stopWindowsSideSync(target, options) {
1493
2215
  return { stopped: false, pid: target.pid, source: target.source, foreign, foreignLogged, reason: `无法停止 Windows 进程 ${target.pid}${hint}(${output.trim().slice(0, 120) || '没有输出'})` }
1494
2216
  }
1495
2217
 
2218
+ /**
2219
+ * The answer for a local engine that belongs to root.
2220
+ *
2221
+ * A root process answers SIGTERM with EPERM and `kill(pid, 0)` still succeeds, so
2222
+ * `stopped:true` would be a lie while the interception keeps running (review
2223
+ * B-P1-2). The caller cannot elevate from a web route, so it gets the exact command.
2224
+ * @param {number} pid - the privileged engine.
2225
+ * @param {object} [extra] - per-side fields to keep.
2226
+ * @returns {object} stop result.
2227
+ */
2228
+ function privilegedStopResult(pid, extra = {}) {
2229
+ const command = `sudo kill ${Number(pid)}`
2230
+ return {
2231
+ stopped: false,
2232
+ pid,
2233
+ ...extra,
2234
+ command,
2235
+ reason: '该系统层拦截由 root 启动,请用 sudo 停止',
2236
+ hint: `在终端执行:${command}`,
2237
+ }
2238
+ }
2239
+
1496
2240
  function stopLocalSideSync(target, options) {
1497
2241
  const foreign = target.source !== undefined && target.source !== 'pidfile'
1498
2242
  const foreignLogged = foreign ? noteForeignStop(target) : false
1499
2243
  try { process.kill(target.pid, 'SIGTERM') } catch (error) {
1500
- if (error?.code === 'EPERM') return { stopped: false, pid: target.pid, side: 'local', foreign, foreignLogged, reason: `需要 sudo kill ${target.pid}` }
2244
+ if (error?.code === 'EPERM') return privilegedStopResult(target.pid, { side: 'local', foreign, foreignLogged })
1501
2245
  }
1502
2246
  // Block the exit hook briefly: SIGTERM on the engine is quick, and leaving a
1503
2247
  // root process behind after dsh quits is worse than a short delay.
1504
2248
  const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 3000)
1505
2249
  while (Date.now() < limit && pidAlive(target.pid)) sleepSync(120)
1506
- if (pidAlive(target.pid)) return { stopped: false, pid: target.pid, side: 'local', foreign, foreignLogged, reason: `进程 ${target.pid} 仍在运行(需要 sudo kill ${target.pid})` }
2250
+ if (pidAlive(target.pid)) {
2251
+ // Alive after TERM and KILL: either root, or a zombie the kernel will reap.
2252
+ return privilegedStopResult(target.pid, { side: 'local', foreign, foreignLogged })
2253
+ }
1507
2254
  clearRedirectorPid('local')
1508
2255
  return { stopped: true, pid: target.pid, source: target.source, side: 'local', foreign, foreignLogged }
1509
2256
  }
@@ -1645,8 +2392,61 @@ export function localRedirectorRunning() {
1645
2392
  * @returns {number} pid or 0.
1646
2393
  */
1647
2394
  function scanLocalProcForRedirector() {
1648
- if (IS_WINDOWS) return 0
1649
- if (typeof probeHooks.localProc === 'function') return Number.parseInt(probeHooks.localProc() ?? 0, 10) || 0
2395
+ const pids = localRedirectorPids()
2396
+ return pids.length > 0 ? pids[0] : 0
2397
+ }
2398
+
2399
+ /**
2400
+ * Local ProxyBridge processes that belong to THIS proxy home (review B-P1-4).
2401
+ *
2402
+ * `localRedirectorPids()` finds every ProxyBridge on the machine, which is right for
2403
+ * diagnostics but wrong for `kill`: two dsh profiles (or a hand-started CLI for a
2404
+ * different profile) must not be reaped by one session's stop/restart. Only a
2405
+ * process whose `--profile` is our own profile file is ours.
2406
+ * @returns {number[]} pids of our own local bridge processes.
2407
+ */
2408
+ export function localRedirectorOwnPids() {
2409
+ if (IS_WINDOWS) return []
2410
+ if (typeof probeHooks.localProc === 'function') {
2411
+ const raw = probeHooks.localProc()
2412
+ return Array.isArray(raw) ? raw.map(Number).filter((pid) => Number.isInteger(pid) && pid > 0) : []
2413
+ }
2414
+ const own = redirectorProfilePath()
2415
+ const pids = []
2416
+ try {
2417
+ for (const entry of readdirSync('/proc')) {
2418
+ if (!/^\d+$/.test(entry)) continue
2419
+ try {
2420
+ const argv = readFileSync(`/proc/${entry}/cmdline`, 'utf8').split('\0').filter((part) => part !== '')
2421
+ if (!argv.some((token) => /(^|[\\/])ProxyBridge(\.exe)?$/i.test(token))) continue
2422
+ let profile = ''
2423
+ for (let index = 0; index < argv.length; index += 1) {
2424
+ if (argv[index] === '--profile') { profile = String(argv[index + 1] ?? ''); break }
2425
+ if (argv[index].startsWith('--profile=')) { profile = argv[index].slice('--profile='.length); break }
2426
+ }
2427
+ if (profile === own) pids.push(Number.parseInt(entry, 10))
2428
+ } catch { /* vanished */ }
2429
+ }
2430
+ } catch { /* no /proc */ }
2431
+ return pids
2432
+ }
2433
+
2434
+ /**
2435
+ * Every local ProxyBridge process, not just the first (m11773).
2436
+ *
2437
+ * A lost pid file used to make the next start spawn a second engine: the scan found
2438
+ * *a* process and reported "already running", but nothing ever reaped the extra one.
2439
+ * Single-instance on this side means knowing all of them, so a start/stop can drop
2440
+ * duplicates and leave exactly the process we mean to keep.
2441
+ * @returns {number[]} live pids running our redirector marker.
2442
+ */
2443
+ export function localRedirectorPids() {
2444
+ if (IS_WINDOWS) return []
2445
+ if (typeof probeHooks.localProc === 'function') {
2446
+ const raw = probeHooks.localProc()
2447
+ return Array.isArray(raw) ? raw.map(Number).filter((pid) => Number.isInteger(pid) && pid > 0) : []
2448
+ }
2449
+ const pids = []
1650
2450
  try {
1651
2451
  for (const entry of readdirSync('/proc')) {
1652
2452
  if (!/^\d+$/.test(entry)) continue
@@ -1654,12 +2454,110 @@ function scanLocalProcForRedirector() {
1654
2454
  const argv = readFileSync(`/proc/${entry}/cmdline`, 'utf8').split('\0').filter((part) => part !== '')
1655
2455
  const isRedirector = argv.some((token) => /(^|[\\/])ProxyBridge(\.exe)?$/i.test(token))
1656
2456
  if (isRedirector && argv.some((token) => token === '--profile' || token.startsWith('--profile='))) {
1657
- return Number.parseInt(entry, 10)
2457
+ pids.push(Number.parseInt(entry, 10))
1658
2458
  }
1659
2459
  } catch { /* vanished */ }
1660
2460
  }
1661
2461
  } catch { /* no /proc */ }
1662
- return 0
2462
+ return pids
2463
+ }
2464
+
2465
+ /**
2466
+ * Age at which an owner-less start lock is considered abandoned.
2467
+ *
2468
+ * A crashed starter can die between `mkdir` and the owner write; the next start
2469
+ * then sees an owner-less directory. Waiting 30 s for it (the old value, longer
2470
+ * than the 15 s default wait) made every start fail until the mtime aged out.
2471
+ */
2472
+ const STALE_LOCK_MS = 5000
2473
+
2474
+ /** Where startRedirector() keeps its per-side "a start is in progress" lock. */
2475
+ function startLockDir(side) {
2476
+ return join(proxyHomeDir(), 'locks', `proxybridge-${side === 'windows' ? 'windows' : 'local'}.lock`)
2477
+ }
2478
+
2479
+ /**
2480
+ * Is somebody holding the start lock for this side right now?
2481
+ *
2482
+ * Used by stopRedirector() when nothing is detected yet: during the UAC wait the
2483
+ * pid files are already gone, so the lock is the only proof that a start is still
2484
+ * in flight. A lock left behind by a crashed starter also answers true; it is
2485
+ * ignored/reaped by the next real starter (STALE_LOCK_MS), and "pendingStart" is a
2486
+ * truthful answer for it (a start is what would happen next, not a stop).
2487
+ * @param {'local'|'windows'} side - which side to probe.
2488
+ * @returns {boolean} true when the lock directory exists.
2489
+ */
2490
+ export function startLockHeld(side) {
2491
+ try { return existsSync(startLockDir(side)) } catch { return false }
2492
+ }
2493
+
2494
+ /**
2495
+ * Cross-process start lock for one side (m11773).
2496
+ *
2497
+ * The daemon and the plugin (its local fallback) can both decide to start the same
2498
+ * bridge at the same second; the Windows side then gets two elevated helpers and the
2499
+ * local side two engines. A lock directory under the shared proxy home serialises
2500
+ * the detect-then-spawn sequence across processes. It is deliberately tiny: create
2501
+ * with `mkdir` (atomic), write the owner pid, remove in `release()`; a lock whose
2502
+ * owner is gone (or which is older than the timeout) is treated as stale.
2503
+ * @param {'local'|'windows'} side - which side to lock.
2504
+ * @param {{timeoutMs?: number}} [options] - how long to wait for a concurrent start.
2505
+ * @returns {Promise<{ok: boolean, stale?: boolean, release?: () => void, reason?: string}>} outcome.
2506
+ */
2507
+ export async function acquireStartLock(side, options = {}) {
2508
+ const timeoutMs = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15000
2509
+ const dir = startLockDir(side)
2510
+ const deadline = Date.now() + timeoutMs
2511
+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 })
2512
+ for (;;) {
2513
+ try {
2514
+ mkdirSync(dir, { mode: 0o700 })
2515
+ try {
2516
+ writeFileSync(join(dir, 'owner'), `${process.pid}\n`, { mode: 0o600 })
2517
+ } catch { /* the dir alone is enough */ }
2518
+ let released = false
2519
+ return {
2520
+ ok: true,
2521
+ release() {
2522
+ if (released === true) return
2523
+ released = true
2524
+ // Only remove OUR lock: if the directory was already reaped as stale and
2525
+ // re-created by a successor, deleting it would hand the next starter a
2526
+ // lock-free window (review B-P2-9).
2527
+ try {
2528
+ const owner = Number.parseInt(readFileSync(join(dir, 'owner'), 'utf8').trim(), 10)
2529
+ const legacy = Number.isInteger(owner) !== true
2530
+ if (legacy === false && owner !== process.pid) return
2531
+ } catch {
2532
+ // No owner file: the starter died before writing it, so this is ours.
2533
+ }
2534
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* best effort */ }
2535
+ },
2536
+ }
2537
+ } catch (error) {
2538
+ if (error?.code !== 'EEXIST') return { ok: false, reason: `无法获取启动锁:${error?.message ?? error}` }
2539
+ }
2540
+ // Stale? A killed starter leaves the directory behind; its owner pid is the proof.
2541
+ let stale = false
2542
+ try {
2543
+ const owner = Number.parseInt(readFileSync(join(dir, 'owner'), 'utf8').trim(), 10)
2544
+ stale = Number.isInteger(owner) && owner > 0 && pidAlive(owner) !== true
2545
+ if (Number.isInteger(owner) !== true) stale = true
2546
+ } catch {
2547
+ // No owner file: only age can tell (the starter may die between mkdir and write).
2548
+ // The threshold must stay well below the default wait (15 s), or a crashed
2549
+ // starter makes the next few starts fail for half a minute (review B-P2-9).
2550
+ try {
2551
+ stale = Date.now() - statSync(dir).mtimeMs > STALE_LOCK_MS
2552
+ } catch { stale = true }
2553
+ }
2554
+ if (stale === true) {
2555
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* retry loop */ }
2556
+ continue
2557
+ }
2558
+ if (Date.now() >= deadline) return { ok: false, reason: '另一个进程正在启动桥接,请稍后再试' }
2559
+ await new Promise((resolve) => setTimeout(resolve, 100))
2560
+ }
1663
2561
  }
1664
2562
 
1665
2563
  /**
@@ -1780,8 +2678,13 @@ function detectSide(side) {
1780
2678
  }
1781
2679
  return null
1782
2680
  }
1783
- const scanned = scanLocalProcForRedirector()
1784
- if (scanned > 0) return { pid: scanned, side, source: 'proc' }
2681
+ const own = localRedirectorOwnPids()
2682
+ if (own.length > 0) {
2683
+ // A bridge started by hand (the card's sudo command) has no pid file; without
2684
+ // adopting it, teardown/空闲退出/崩溃重启 could never stop it (review A4-P1-2).
2685
+ writeRedirectorPid(own[0], 'local')
2686
+ return { pid: own[0], side, source: 'proc' }
2687
+ }
1785
2688
  return null
1786
2689
  }
1787
2690
 
@@ -1803,7 +2706,14 @@ export async function detectRunningRedirectorAsync() {
1803
2706
  windows = { pid: live[0], side: 'windows', source: 'process' }
1804
2707
  }
1805
2708
  }
1806
- const localHit = local ?? (scanLocalProcForRedirector() > 0 ? { pid: scanLocalProcForRedirector(), side: 'local', source: 'proc' } : null)
2709
+ let localHit = local
2710
+ if (localHit === null) {
2711
+ const own = localRedirectorOwnPids()
2712
+ if (own.length > 0) {
2713
+ writeRedirectorPid(own[0], 'local')
2714
+ localHit = { pid: own[0], side: 'local', source: 'proc' }
2715
+ }
2716
+ }
1807
2717
  const primary = localHit ?? windows
1808
2718
  return {
1809
2719
  pid: primary?.pid ?? 0,
@@ -2018,7 +2928,11 @@ async function psElevated(script, timeoutMs = 20000, options = {}) {
2018
2928
  } else if (typeof probeHooks.elevatedLaunch === 'function') {
2019
2929
  await probeHooks.elevatedLaunch({ localPath, windowsPath, nonce, body, timeoutMs: launchTimeout })
2020
2930
  } else {
2021
- spawnSyncText('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', launchEncoded], launchTimeout)
2931
+ // Async on purpose (review B-P0-1): this launcher blocks until the UAC dialog is
2932
+ // answered, which used to freeze the daemon's event loop for up to 45 s. The
2933
+ // caller keeps awaiting the overall deadline, so the visible semantics (and the
2934
+ // 45 s/20 s budgets) are unchanged.
2935
+ await spawnDetachedText('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', launchEncoded], launchTimeout)
2022
2936
  }
2023
2937
  let sawStale = false
2024
2938
  while (Date.now() < deadline) {
@@ -2077,6 +2991,51 @@ export function restoreWindowsService() {
2077
2991
  return { restored: false, reason: `服务未能恢复(${output.trim().slice(0, 120) || '需要管理员'})` }
2078
2992
  }
2079
2993
 
2994
+ /** Where the elevated start leaves the service's original start type. */
2995
+ function startTypeHintPath() {
2996
+ return join(redirectorHome(), 'windows-start-type.txt')
2997
+ }
2998
+
2999
+ /** Read the hint left by the elevated start script (`''` when absent/invalid). */
3000
+ export function readStartTypeHint() {
3001
+ try {
3002
+ const hint = readFileSync(startTypeHintPath(), 'utf8').trim()
3003
+ return /^(Automatic|AutomaticDelayedStart|Manual|Disabled)$/i.test(hint) ? hint : ''
3004
+ } catch {
3005
+ return ''
3006
+ }
3007
+ }
3008
+
3009
+ /** Drop the start-type hint (after a successful start or a restored service). */
3010
+ export function clearStartTypeHint() {
3011
+ try {
3012
+ unlinkSync(startTypeHintPath())
3013
+ } catch {
3014
+ // Nothing to clear.
3015
+ }
3016
+ }
3017
+
3018
+ /**
3019
+ * Put ProxyBridgeSvc back after a Windows start failed.
3020
+ *
3021
+ * The elevated helper stops the service and may park it on Manual before the CLI is
3022
+ * even spawned, so every failure path after that point has to undo it — otherwise
3023
+ * the machine stays "service stopped + StartupType Manual" until the next stop or
3024
+ * dsh exit (review B-P1-3). The original start type reaches us through the script's
3025
+ * hint file because the process may die before it reports anything.
3026
+ * @returns {{restored: boolean, reason?: string}} restoreWindowsService() result.
3027
+ */
3028
+ export function recoverWindowsService() {
3029
+ const state = readWindowsServiceState()
3030
+ const hint = readStartTypeHint()
3031
+ if (state === null && hint !== '') {
3032
+ writeWindowsServiceState({ stoppedByUs: true, originalStartType: hint, parkedOnManual: true })
3033
+ }
3034
+ const restored = restoreWindowsService()
3035
+ clearStartTypeHint()
3036
+ return restored
3037
+ }
3038
+
2080
3039
  /**
2081
3040
  * Assemble the status object from one detection snapshot.
2082
3041
  * @param {object} detection - detectRunningRedirector() result.
@@ -2215,7 +3174,8 @@ export async function syncRedirector(cwd, options = {}) {
2215
3174
  * is launched, and an elevation prompt (UAC on Windows) is the expected outcome
2216
3175
  * rather than an error. A side that needs a password we cannot type is reported
2217
3176
  * with the command instead of failing the whole start.
2218
- * @param {{sides?: string[], verbose?: number}} [options] - sides to consider, in order.
3177
+ * @param {{sides?: string[], verbose?: number, interactive?: boolean}} [options] - sides to consider, in order;
3178
+ * `interactive:true` is the only path allowed to raise a pkexec/terminal prompt (review B-P0-2).
2219
3179
  * @returns {Promise<{started: object[], skipped: object[], running: boolean}>} per-side outcome.
2220
3180
  */
2221
3181
  export async function startRedirectors(options = {}) {
@@ -2265,7 +3225,7 @@ export async function startRedirectors(options = {}) {
2265
3225
  skipped.push({ side, reason: `已在运行(pid ${runningHere.pid})`, pid: runningHere.pid })
2266
3226
  continue
2267
3227
  }
2268
- const result = await startRedirector({ side, verbose: options.verbose })
3228
+ const result = await startRedirector({ side, verbose: options.verbose, interactive: options.interactive === true })
2269
3229
  if (result.started === true) started.push(result)
2270
3230
  else skipped.push(Object.assign({ side }, result))
2271
3231
  }
@@ -2379,31 +3339,104 @@ export async function reloadRedirector(options = {}) {
2379
3339
  * @returns {Promise<{stopped: boolean, pid?: number, side?: string, reason?: string, results?: object[]}>} outcome.
2380
3340
  */
2381
3341
  export async function stopRedirector(options = {}) {
2382
- const detection = detectRunningRedirector()
2383
- if (detection.pid === 0) {
2384
- // Drop dead records so status stops advertising a pid that does not exist.
3342
+ // Serialise with startRedirector (review B-P1-5): the elevated start holds that
3343
+ // side's lock for up to 45 s while UAC waits. A stop that ran meanwhile saw
3344
+ // nothing, answered "未在运行", and the start then finished on an already-stopped
3345
+ // engine. Only the side(s) we are about to touch are locked (review follow-up):
3346
+ // taking both up front made a plain "stop" wait 2x15 s behind a Windows UAC start.
3347
+ const requestedSide = options.side === 'local' || options.side === 'windows' ? options.side : null
3348
+ const preliminary = detectRunningRedirector()
3349
+ const sidesToLock = requestedSide !== null ? [requestedSide]
3350
+ : ['windows', 'local'].filter((side) => preliminary[side]?.pid > 0)
3351
+ const clearDeadRecords = () => {
2385
3352
  for (const side of ['windows', 'local']) {
2386
3353
  if (redirectorPidRecord(side).pid > 0) clearRedirectorPid(side)
2387
3354
  }
2388
- return { stopped: false, reason: '未在运行' }
2389
3355
  }
2390
- const results = []
2391
- if (detection.windows.pid > 0) {
2392
- results.push(Object.assign({ side: 'windows' }, stopRedirectorSync(Object.assign({}, options, { side: 'windows' }))))
3356
+ if (sidesToLock.length === 0) {
3357
+ // Nothing is running *now* — but a start may be mid-flight and its pid files
3358
+ // already cleared (the UAC wait is the long part). The start lock is the only
3359
+ // signal left, so probe it without blocking instead of answering "未在运行".
3360
+ const starting = (requestedSide !== null ? [requestedSide] : ['windows', 'local']).find((side) => startLockHeld(side))
3361
+ if (starting !== undefined) {
3362
+ return { stopped: false, pendingStart: true, side: starting, reason: '另一个进程正在启动桥接,请稍后再试' }
3363
+ }
3364
+ clearDeadRecords()
3365
+ return { stopped: false, reason: '未在运行' }
2393
3366
  }
2394
- if (detection.local.pid > 0) {
2395
- results.push(Object.assign({ side: 'local' }, await stopLocalRedirectorAsync(detection.local.pid, options)))
3367
+ const locks = []
3368
+ for (const side of sidesToLock) {
3369
+ const lock = await acquireStartLock(side, { timeoutMs: options.lockTimeoutMs })
3370
+ if (lock.ok !== true) {
3371
+ for (const held of locks) held.release()
3372
+ return { stopped: false, pendingStart: true, side, reason: lock.reason ?? '另一个进程正在启动桥接,请稍后再试' }
3373
+ }
3374
+ locks.push(lock)
2396
3375
  }
2397
- const stopped = results.filter((result) => result.stopped === true)
2398
- if (stopped.length === 0) {
2399
- return {
2400
- stopped: false,
2401
- pid: detection.pid,
2402
- reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未能停止桥接',
2403
- results,
3376
+ try {
3377
+ // Re-detect under the lock: the start we waited for may have failed, and the
3378
+ // side we detected a moment ago may be gone (or a different one may be up).
3379
+ const detection = detectRunningRedirector()
3380
+ if (detection.pid === 0) {
3381
+ // Drop dead records so status stops advertising a pid that does not exist.
3382
+ clearDeadRecords()
3383
+ return { stopped: false, reason: '未在运行' }
3384
+ }
3385
+ const results = []
3386
+ if (detection.windows.pid > 0) {
3387
+ results.push(Object.assign({ side: 'windows' }, stopRedirectorSync(Object.assign({}, options, { side: 'windows' }))))
3388
+ }
3389
+ if (detection.local.pid > 0) {
3390
+ results.push(Object.assign({ side: 'local' }, await stopLocalRedirectorAsync(detection.local.pid, options)))
3391
+ }
3392
+ // Local duplicates: an engine whose pid file we lost still holds the eBPF hook.
3393
+ // Stopping "the recorded one" is not enough for a single-instance invariant.
3394
+ // A root engine answers SIGTERM with EPERM: that is not "stopped" (review B-P1-2).
3395
+ const blocked = []
3396
+ for (const pid of localRedirectorOwnPids()) {
3397
+ if (results.some((result) => result.pid === pid && result.stopped === true)) continue
3398
+ try { process.kill(pid, 'SIGTERM') } catch (error) {
3399
+ if (error?.code === 'EPERM') blocked.push(pid)
3400
+ }
3401
+ }
3402
+ if (blocked.length > 0) {
3403
+ const command = 'sudo kill ' + blocked.join(' ')
3404
+ return {
3405
+ stopped: false,
3406
+ pid: blocked[0],
3407
+ pids: blocked,
3408
+ command,
3409
+ reason: '该系统层拦截由 root 启动,请用 sudo 停止',
3410
+ hint: `在终端执行:${command}`,
3411
+ results,
3412
+ }
2404
3413
  }
3414
+ const stopped = results.filter((result) => result.stopped === true)
3415
+ // A side stopped while the other reported "root, use sudo" is still an
3416
+ // unfinished stop: saying `stopped:true` hides the interception that is running.
3417
+ const needsSudo = results.find((result) => result.stopped !== true && result.command !== undefined)
3418
+ if (needsSudo !== undefined) {
3419
+ return {
3420
+ stopped: false,
3421
+ pid: needsSudo.pid,
3422
+ side: needsSudo.side,
3423
+ command: needsSudo.command,
3424
+ reason: needsSudo.reason ?? '该系统层拦截由 root 启动,请用 sudo 停止',
3425
+ results,
3426
+ }
3427
+ }
3428
+ if (stopped.length === 0) {
3429
+ return {
3430
+ stopped: false,
3431
+ pid: detection.pid,
3432
+ reason: results.map((result) => result.reason).filter(Boolean)[0] ?? '未能停止桥接',
3433
+ results,
3434
+ }
3435
+ }
3436
+ return { stopped: true, pid: stopped[0].pid, side: stopped[0].side, results }
3437
+ } finally {
3438
+ for (const held of locks) held.release()
2405
3439
  }
2406
- return { stopped: true, pid: stopped[0].pid, side: stopped[0].side, results }
2407
3440
  }
2408
3441
 
2409
3442
  /** Graceful local stop with SIGKILL fallback (the exit hook used to do this inline). */
@@ -2412,10 +3445,11 @@ async function stopLocalRedirectorAsync(pid, options = {}) {
2412
3445
  process.kill(pid, 'SIGTERM')
2413
3446
  } catch (error) {
2414
3447
  const code = error?.code ?? ''
3448
+ if (code === 'EPERM') return privilegedStopResult(pid)
2415
3449
  return {
2416
3450
  stopped: false,
2417
3451
  pid,
2418
- reason: code === 'EPERM' ? `需要管理员/sudo:sudo kill ${pid}` : `无法停止进程 ${pid}(${code || error?.message})`,
3452
+ reason: `无法停止进程 ${pid}(${code || error?.message})`,
2419
3453
  }
2420
3454
  }
2421
3455
  const limit = Date.now() + (Number.isInteger(options.graceMs) && options.graceMs > 0 ? options.graceMs : 5000)
@@ -2426,7 +3460,7 @@ async function stopLocalRedirectorAsync(pid, options = {}) {
2426
3460
  if (pidAlive(pid)) {
2427
3461
  try { process.kill(pid, 'SIGKILL') } catch { /* still privileged: report below */ }
2428
3462
  }
2429
- if (pidAlive(pid)) return { stopped: false, pid, reason: `进程 ${pid} 仍在运行(需要 sudo kill ${pid})` }
3463
+ if (pidAlive(pid)) return privilegedStopResult(pid)
2430
3464
  clearRedirectorPid('local')
2431
3465
  return { stopped: true, pid }
2432
3466
  }
@@ -2439,10 +3473,15 @@ async function stopLocalRedirectorAsync(pid, options = {}) {
2439
3473
  * WSL-only. `wslpath -w` is authoritative when present (it also handles the
2440
3474
  * `\\wsl.localhost\<distro>` form for our home directory); the drive-letter
2441
3475
  * rewrite is the fallback for a distro without it.
3476
+ *
3477
+ * A caller that NEEDS the Windows form (launch a program, read a file from
3478
+ * PowerShell) must pass `{mustConvert:true}`: silently returning the Linux spelling
3479
+ * made the launch fail with no diagnostic at all (review B-P2-12).
2442
3480
  * @param {string} path - an absolute Linux path, possibly under /mnt/<drive>.
3481
+ * @param {{mustConvert?: boolean}} [options] - throw when no Windows form is found.
2443
3482
  * @returns {string} the same location as Windows sees it.
2444
3483
  */
2445
- export function windowsPathOf(path) {
3484
+ export function windowsPathOf(path, options = {}) {
2446
3485
  const text = String(path ?? '')
2447
3486
  if (text === '') return text
2448
3487
  if (/^[A-Za-z]:[\\/]/.test(text)) return text
@@ -2453,6 +3492,9 @@ export function windowsPathOf(path) {
2453
3492
  if (mounted !== null) return `${mounted[1].toUpperCase()}:\\${mounted[2].replace(/\//g, '\\')}`
2454
3493
  const converted = spawnSyncText('wslpath', ['-w', text], 4000).trim()
2455
3494
  if (converted !== '' && /^[A-Za-z]:[\\/]|^\\\\/.test(converted)) return converted
3495
+ if (options.mustConvert === true) {
3496
+ throw new Error(`无法把路径转换为 Windows 形式(wslpath 不可用或失败):${text}`)
3497
+ }
2456
3498
  return text
2457
3499
  }
2458
3500
 
@@ -2466,7 +3508,7 @@ export function windowsPathOf(path) {
2466
3508
  * @param {object[]} args - argv as this side spells it.
2467
3509
  * @returns {object[]} Windows-spelled argv.
2468
3510
  */
2469
- function windowsArgsOf(args) {
3511
+ function windowsArgsOf(args, options = {}) {
2470
3512
  return args.map((arg) => {
2471
3513
  if (typeof arg !== 'string' || arg.startsWith('/') !== true) return arg
2472
3514
  try {
@@ -2474,7 +3516,7 @@ function windowsArgsOf(args) {
2474
3516
  } catch {
2475
3517
  return arg
2476
3518
  }
2477
- return windowsPathOf(arg)
3519
+ return windowsPathOf(arg, options)
2478
3520
  })
2479
3521
  }
2480
3522
 
@@ -2528,11 +3570,20 @@ export const __test = {
2528
3570
  sleepSync,
2529
3571
  psElevated,
2530
3572
  watchdogPid,
3573
+ acquireStartLock,
3574
+ localRedirectorPids,
3575
+ localRedirectorOwnPids,
2531
3576
  writeWatchdogPid,
2532
3577
  reloadDonePath,
2533
3578
  reloadFailedPath,
2534
3579
  windowsPathOf,
2535
3580
  windowsArgsOf,
3581
+ spawnDetachedText,
3582
+ privilegedStopResult,
3583
+ readStartTypeHint,
3584
+ clearStartTypeHint,
3585
+ startTypeHintPath,
3586
+ recoverWindowsService,
2536
3587
  }
2537
3588
 
2538
3589
  const SELF = basename(process.argv[1] ?? '')