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