dsh-ris-ide 1.8.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,116 @@
1
+ import assert from 'node:assert/strict'
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import test from 'node:test'
6
+
7
+ import { SIDE_FILES, collectProxyBridgeHealth, createHealthCache } from '../lib/proxybridge-health.js'
8
+
9
+ function seedBundle() {
10
+ const home = mkdtempSync(join(tmpdir(), 'pb-health-'))
11
+ const dir = join(home, 'proxybridge', 'bundle')
12
+ for (const files of Object.values(SIDE_FILES)) {
13
+ for (const relative of files) {
14
+ const path = join(dir, relative)
15
+ mkdirSync(join(path, '..'), { recursive: true })
16
+ writeFileSync(path, 'x')
17
+ }
18
+ }
19
+ return home
20
+ }
21
+
22
+ test('both sides are healthy when every file exists and each CLI answers --version (m11828)', async () => {
23
+ const home = seedBundle()
24
+ const calls = []
25
+ try {
26
+ const health = await collectProxyBridgeHealth({
27
+ home,
28
+ engineRunning: true,
29
+ // Windows cannot launch an exe from the Linux filesystem: the probe targets the
30
+ // copy under %LOCALAPPDATA% (here a fake Windows path).
31
+ windowsExe: 'C:\\Users\\demo\\AppData\\Local\\dsh-ris-ide\\proxybridge\\windows\\ProxyBridge_CLI.exe',
32
+ run: async (command, args) => {
33
+ calls.push([command, args.at(-1) ?? ''])
34
+ return 'ProxyBridge 4.3.0\n'
35
+ },
36
+ })
37
+ assert.equal(health.ok, true)
38
+ assert.equal(health.installed, true)
39
+ assert.equal(health.sides.linux.version, '4.3.0')
40
+ assert.equal(health.sides.windows.version, '4.3.0')
41
+ assert.equal(health.engineRunning, true)
42
+ // Windows binaries cannot be launched straight from the Linux filesystem.
43
+ assert.ok(calls.some(([command]) => command === 'powershell.exe'))
44
+ } finally {
45
+ rmSync(home, { recursive: true, force: true })
46
+ }
47
+ })
48
+
49
+ test('a missing file or an unrunnable CLI is reported per side, not as a dead card', async () => {
50
+ const home = seedBundle()
51
+ try {
52
+ rmSync(join(home, 'proxybridge', 'bundle', 'windows', 'WinDivert.dll'))
53
+ const health = await collectProxyBridgeHealth({
54
+ home,
55
+ engineRunning: true,
56
+ windowsExe: 'C:\\fake\\ProxyBridge_CLI.exe',
57
+ run: async (command) => (command === 'powershell.exe' ? 'boom: missing DLL' : 'ProxyBridge 4.0.0'),
58
+ })
59
+ assert.equal(health.ok, false)
60
+ assert.equal(health.sides.linux.ok, true)
61
+ assert.equal(health.sides.windows.ok, false)
62
+ assert.ok(health.sides.windows.files.missing.includes('bundle/windows/WinDivert.dll'))
63
+ assert.match(health.sides.windows.checks.find((check) => check.id === 'runs').detail, /boom/)
64
+ } finally {
65
+ rmSync(home, { recursive: true, force: true })
66
+ }
67
+ })
68
+
69
+ test('a single-sided host is healthy, not broken (m12019)', async () => {
70
+ const home = seedBundle()
71
+ const run = async () => 'ProxyBridge 4.0.0'
72
+ try {
73
+ const linuxOnly = await collectProxyBridgeHealth({ home, engineRunning: true, linuxApplicable: true, windowsApplicable: false, run })
74
+ assert.equal(linuxOnly.ok, true, 'one side is enough')
75
+ assert.equal(linuxOnly.sides.windows.applicable, false)
76
+ assert.equal(linuxOnly.sides.windows.ok, true, 'a skipped side is neutral')
77
+ assert.match(linuxOnly.sides.windows.note, /没有 Windows 侧/)
78
+
79
+ const windowsOnly = await collectProxyBridgeHealth({ home, engineRunning: true, linuxApplicable: false, windowsApplicable: true, windowsExe: 'C:\\fake\\ProxyBridge_CLI.exe', run })
80
+ assert.equal(windowsOnly.ok, true)
81
+ assert.equal(windowsOnly.sides.linux.applicable, false)
82
+
83
+ // Installed, but the Windows copy has not been materialised yet (first start of
84
+ // the bridge prepares it): that is "not prepared", not "broken".
85
+ const notPrepared = await collectProxyBridgeHealth({ home, engineRunning: true, linuxApplicable: true, windowsApplicable: true, windowsPrepared: false, run })
86
+ assert.equal(notPrepared.ok, true)
87
+ assert.equal(notPrepared.sides.windows.skipped, true)
88
+ assert.match(notPrepared.sides.windows.note, /尚未复制/)
89
+ } finally {
90
+ rmSync(home, { recursive: true, force: true })
91
+ }
92
+ })
93
+
94
+ test('the health cache answers from memory unless forced', async () => {
95
+ const home = seedBundle()
96
+ let probes = 0
97
+ try {
98
+ const cache = createHealthCache()
99
+ const run = async () => { probes += 1; return 'ProxyBridge 4.0.0' }
100
+ const windowsExe = 'C:\\fake\\ProxyBridge_CLI.exe'
101
+ const first = await cache.get({ home, engineRunning: true, run, windowsExe })
102
+ assert.equal(first.cached, false)
103
+ const second = await cache.get({ home, engineRunning: true, run, windowsExe })
104
+ assert.equal(second.cached, true)
105
+ assert.equal(probes, 2, 'two sides probed once, then served from the cache')
106
+ // Applicability decides WHAT is probed, so a host shape with one side must not
107
+ // reuse the other shape's snapshot (review A4-P1-1).
108
+ const linuxOnly = await cache.get({ home, engineRunning: true, run })
109
+ assert.equal(linuxOnly.cached, false, 'a different applicability set is a cache miss')
110
+ assert.equal(probes, 3, 'with no Windows exe only the Linux side runs')
111
+ await cache.get({ home, engineRunning: true, force: true, run, windowsExe })
112
+ assert.equal(probes, 5, 'force re-probes both sides')
113
+ } finally {
114
+ rmSync(home, { recursive: true, force: true })
115
+ }
116
+ })
@@ -554,10 +554,17 @@ test('the elevated watchdog script carries the rules it needs to tear down', asy
554
554
  // leaves an elevated CLI behind — both are silent, so assert the pieces.
555
555
  assert.match(script, /Test-Path \$stopFile/)
556
556
  assert.match(script, /heartbeat-stale/)
557
- assert.match(script, /Get-Process ProxyBridge_CLI .*Stop-Process -Force/)
557
+ assert.match(script, /\(Get-OwnCli\) \| ForEach-Object \{ Stop-Process -Id \$_\.ProcessId -Force \}/)
558
+ // Only CLIs carrying THIS home's profile may be torn down (review A4-P2-1).
559
+ assert.match(script, /IndexOf\(\$ownProfile/)
558
560
  assert.match(script, /Set-Service -Name ProxyBridgeSvc -StartupType \$state\.originalStartType/)
559
561
  assert.match(script, /New-Item -ItemType File -Path \$doneFile/)
560
562
  assert.match(script, /\$age -lt 20/)
563
+ // Two watchdogs fighting over the same reload request restart the CLI twice
564
+ // (m11702): one copy owns a named mutex, the second exits immediately.
565
+ assert.match(script, /System\.Threading\.Mutex/)
566
+ assert.match(script, /WaitOne\(0\)/)
567
+ assert.match(script, /another watchdog owns the mutex; exiting/)
561
568
 
562
569
  const written = mod.writeWatchdogScript()
563
570
  // It returns the WINDOWS path (that is where it runs); the file itself is ours.
@@ -569,3 +576,349 @@ test('the elevated watchdog script carries the rules it needs to tear down', asy
569
576
  rmSync(tmpHome, { recursive: true, force: true })
570
577
  }
571
578
  })
579
+
580
+ test('a bridge start retires the previous elevated watchdog (m11702)', async () => {
581
+ // Every start used to spawn a watchdog and leave the old one running (it only
582
+ // exits on a stop request or a stale heartbeat, and dsh keeps the heartbeat
583
+ // fresh). Two watchdogs then restart the CLI concurrently — one wins the
584
+ // WinDivert handle, the other silently captures nothing. The start script must
585
+ // kill the leftovers in the same elevated context that creates the new one.
586
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
587
+ assert.ok(source.includes('IndexOf($wdScript'), 'the start script must recognise leftover watchdogs by THIS home\'s script path')
588
+ assert.ok(source.includes('Stop-Process -Id $_.ProcessId -Force'), 'the start script must kill them, not just look')
589
+ assert.ok(source.includes('oldWatchdogs='), 'the elevated report should say how many were retired')
590
+ })
591
+
592
+ test('both sides are single-instance: a start lock and duplicate discovery (m11773)', async () => {
593
+ const tmpHome = mkdtempSync(join(tmpdir(), 'single-'))
594
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
595
+ process.env.DSH_RIS_IDE_PROXY_HOME = tmpHome
596
+ const mod = await import('../lib/redirector.js')
597
+ try {
598
+ // 1. A second concurrent start must not get the lock while the first holds it.
599
+ const first = await mod.acquireStartLock('local', { timeoutMs: 200 })
600
+ assert.equal(first.ok, true)
601
+ const second = await mod.acquireStartLock('local', { timeoutMs: 150 })
602
+ assert.equal(second.ok, false)
603
+ assert.match(second.reason ?? '', /另一个进程正在启动/)
604
+ first.release()
605
+ const third = await mod.acquireStartLock('local', { timeoutMs: 150 })
606
+ assert.equal(third.ok, true, 'releasing the lock must let the next start in')
607
+ third.release()
608
+ // 2. A starter that died leaves a stale lock: the owner pid is gone.
609
+ const staleDir = join(tmpHome, 'locks', 'proxybridge-local.lock')
610
+ mkdirSync(staleDir, { recursive: true })
611
+ writeFileSync(join(staleDir, 'owner'), '999999\n')
612
+ const fourth = await mod.acquireStartLock('local', { timeoutMs: 300 })
613
+ assert.equal(fourth.ok, true, 'a dead owner must not block every later start')
614
+ fourth.release()
615
+ // 3. Every local engine is discoverable, not just the first (the old scan
616
+ // returned one pid, so a duplicate could never be reaped).
617
+ mod.__test.setProbeHooks({ localProc: () => [111, 222] })
618
+ assert.deepEqual(mod.localRedirectorPids(), [111, 222])
619
+ mod.__test.resetProbeHooks()
620
+ // 4. The Windows elevated start is serialised too: a second helper reports
621
+ // start-busy instead of racing the first one's CLI.
622
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
623
+ assert.ok(source.includes('start-busy=True'), 'a concurrent Windows start must be reported, not faked')
624
+ assert.ok(source.includes('proxybridge-start-'), 'the start mutex is per proxy home')
625
+ assert.ok(source.includes('旧 watchdog') || source.includes('oldWatchdogs='), 'old watchdogs are still retired at start')
626
+ } finally {
627
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
628
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
629
+ rmSync(tmpHome, { recursive: true, force: true })
630
+ }
631
+ })
632
+ test('the local side falls back to pkexec when sudo is not passwordless (m12606)', async () => {
633
+ // Elevation here is a decision tree, not a UI detail: sudo -n, then pkexec, then
634
+ // the manual command. Keep the strings in the source so a refactor cannot quietly
635
+ // drop the dialog path.
636
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
637
+ assert.match(source, /pkexecAvailable\(\)/)
638
+ assert.match(source, /spawn\('pkexec', \[found\.path, \.\.\.plan\.args\]/)
639
+ assert.match(source, /method: 'pkexec'/)
640
+ assert.match(source, /method: 'manual'/)
641
+ // Clicking 提权启动 must be able to hand the password to a real terminal (m12782).
642
+ assert.match(source, /function openElevatedTerminal\(/)
643
+ assert.match(source, /method: 'terminal'/)
644
+ assert.match(source, /TERMINAL_CANDIDATES/)
645
+ // Headless Linux has no window to open: skip X11 clients without a session (m12884).
646
+ assert.match(source, /function hasGraphicalSession\(/)
647
+ assert.match(source, /candidate\.bin !== 'wt\.exe' && hasGraphicalSession\(\) === false/)
648
+ // The password is typed in the window, then the CLI must survive the window: sudo
649
+ // ticket first, detached `sudo -n` afterwards (m12896).
650
+ assert.match(source, /sudo -v \|\|/)
651
+ assert.match(source, /nohup sudo -n /)
652
+ assert.match(source, /--size/)
653
+ // m13083: -f maximized the window, so it is gone; the size keeps it small.
654
+ assert.match(source, /--size', '64,16'/)
655
+ // m13147/m13257: the helper launches WT itself and centers the one new window,
656
+ // because WT hosts every window in one process (a title or pid cannot identify it).
657
+ assert.match(source, /launchCenteredTerminal/)
658
+ assert.match(source, /MoveWindow/)
659
+ assert.match(source, /center-terminal\.ps1/)
660
+ assert.match(source, /Start-Process -FilePath 'wt\.exe'/)
661
+ })
662
+ test('the elevation script detaches the CLI so the window can close (m12896)', async () => {
663
+ const { mkdtempSync, rmSync } = await import('node:fs')
664
+ const { tmpdir } = await import('node:os')
665
+ const { join } = await import('node:path')
666
+ const { elevationScript } = await import('../lib/redirector.js')
667
+ const dir = mkdtempSync(join(tmpdir(), 'risd-elevate-'))
668
+ try {
669
+ // 'linux' is the page's spelling; the helper/state files are always `local`
670
+ // (review B-P1-1), so this must not produce elevate-linux.*.
671
+ const plan = elevationScript('sudo /opt/ProxyBridge --profile p --verbose 2', 'linux', {
672
+ dir,
673
+ argv: ['/opt/ProxyBridge', '--profile', 'a b', '--verbose', '2'],
674
+ })
675
+ assert.equal(plan.scriptPath, join(dir, 'elevate-local.sh'))
676
+ assert.match(plan.body, /^#!\/bin\/bash/m)
677
+ assert.match(plan.body, /sudo -v \|\|/)
678
+ // argv entries are single-quoted for bash (review B-P2-10): a profile path the
679
+ // user can choose must not be able to inject a command into the sudo line.
680
+ assert.match(plan.body, /nohup sudo -n '\/opt\/ProxyBridge' '--profile' 'a b' '--verbose' '2' > "\$LOG" 2>&1 &/)
681
+ assert.match(plan.body, /sleep 1/)
682
+ } finally {
683
+ rmSync(dir, { recursive: true, force: true })
684
+ }
685
+ })
686
+ test('the elevation note clears when the helper script exits (m12923)', async () => {
687
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs')
688
+ const { tmpdir } = await import('node:os')
689
+ const { join } = await import('node:path')
690
+ const { readElevationState } = await import('../lib/redirector.js')
691
+ const home = mkdtempSync(join(tmpdir(), 'risd-elev-state-'))
692
+ try {
693
+ // The writer puts it in <proxy home>/proxybridge/ (elevationScript's default
694
+ // dir) — reading <proxy home>/elevate-*.json never found it (review B-P1-1).
695
+ const file = join(home, 'proxybridge', 'elevate-local.json')
696
+ mkdirSync(join(home, 'proxybridge'), { recursive: true })
697
+ writeFileSync(file, JSON.stringify({ side: 'local', pid: process.pid, at: new Date().toISOString() }))
698
+ assert.equal(readElevationState('local', { home }).active, true)
699
+ // The page still calls this side 'linux'; both spellings must find the file.
700
+ assert.equal(readElevationState('linux', { home }).active, true)
701
+ rmSync(file)
702
+ assert.equal(readElevationState('local', { home }).active, false)
703
+ // A stale file from a dead pid must not keep the note on screen either.
704
+ writeFileSync(file, JSON.stringify({ side: 'local', pid: 999999, at: new Date().toISOString() }))
705
+ assert.equal(readElevationState('local', { home }).active, false)
706
+ // A SIGKILL leaves the file behind; its TTL stops the note from sticking forever.
707
+ writeFileSync(file, JSON.stringify({ side: 'local', pid: process.pid, at: new Date(Date.now() - 11 * 60 * 1000).toISOString() }))
708
+ assert.equal(readElevationState('local', { home }).active, false)
709
+ // Unknown side names must not be interpolated into a path.
710
+ assert.equal(readElevationState('../evil', { home }).active, false)
711
+ } finally {
712
+ rmSync(home, { recursive: true, force: true })
713
+ }
714
+ })
715
+
716
+ test('only a user-initiated start may raise an interactive prompt (review B-P0-2)', async () => {
717
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
718
+ // The gate must sit BEFORE the pkexec branch: the reconciler calls this every
719
+ // minute, and a prompt there is a polkit dialog / terminal window per minute.
720
+ const gate = source.indexOf("if (options.interactive !== true) {")
721
+ const pkexec = source.indexOf('if (pkexecAvailable() === true) {')
722
+ assert.ok(gate > 0, 'the interactive gate exists')
723
+ assert.ok(pkexec > 0 && gate < pkexec, 'the gate precedes pkexec')
724
+ assert.match(source, /startRedirector\(\{ side, verbose: options\.verbose, interactive: options\.interactive === true \}\)/)
725
+ assert.match(source, /export function localRedirectorOwnPids\(\)/)
726
+ assert.match(source, /const own = localRedirectorOwnPids\(\)/, 'detection adopts our own hand-started bridge')
727
+ })
728
+
729
+ test('the elevated launcher no longer blocks the daemon (review B-P0-1)', async () => {
730
+ const { __test } = await import('../lib/redirector.js')
731
+ // spawnSync waited for the UAC dialog (up to 45 s) with the daemon's 3 s
732
+ // heartbeat and every HTTP route behind it. While the launcher runs, timers must
733
+ // still fire.
734
+ let ticks = 0
735
+ const timer = setInterval(() => { ticks += 1 }, 20)
736
+ try {
737
+ const started = Date.now()
738
+ const result = await __test.spawnDetachedText(process.execPath, ['-e', 'setTimeout(() => {}, 150)'], 2000)
739
+ const elapsed = Date.now() - started
740
+ assert.equal(result.timedOut, false)
741
+ assert.ok(ticks > 0, 'the event loop kept running while the launcher waited')
742
+ assert.ok(elapsed < 1500, `launcher returned after ${elapsed} ms`)
743
+ } finally {
744
+ clearInterval(timer)
745
+ }
746
+ })
747
+
748
+ test('a hung launcher is killed at the timeout (review B-P0-1)', async () => {
749
+ const { __test } = await import('../lib/redirector.js')
750
+ const started = Date.now()
751
+ const result = await __test.spawnDetachedText(process.execPath, ['-e', 'setTimeout(() => {}, 5000)'], 150)
752
+ assert.equal(result.timedOut, true)
753
+ assert.ok(Date.now() - started < 1500, 'the timeout must not wait for the child')
754
+ })
755
+
756
+ test('a stale lock release cannot delete the next owner\'s lock (review B-P2-9)', async () => {
757
+ const { mkdtempSync, rmSync, writeFileSync, existsSync } = await import('node:fs')
758
+ const { tmpdir } = await import('node:os')
759
+ const { join } = await import('node:path')
760
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
761
+ const home = mkdtempSync(join(tmpdir(), 'lock-own-'))
762
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
763
+ const mod = await import('../lib/redirector.js')
764
+ try {
765
+ const lock = await mod.acquireStartLock('local', { timeoutMs: 200 })
766
+ assert.equal(lock.ok, true)
767
+ const dir = join(home, 'locks', 'proxybridge-local.lock')
768
+ // Another starter took the lock over after we were considered stale; our late
769
+ // release must not remove ITS lock.
770
+ writeFileSync(join(dir, 'owner'), `${process.pid + 1}\n`)
771
+ lock.release()
772
+ assert.equal(existsSync(dir), true, 'release only removes our own lock')
773
+ rmSync(dir, { recursive: true, force: true })
774
+ } finally {
775
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
776
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
777
+ rmSync(home, { recursive: true, force: true })
778
+ }
779
+ })
780
+
781
+ test('a failed materialisation is cached briefly, and force retries (review B-P2-13)', async () => {
782
+ const { mkdtempSync, rmSync, writeFileSync, mkdirSync } = await import('node:fs')
783
+ const { tmpdir } = await import('node:os')
784
+ const { join } = await import('node:path')
785
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
786
+ const home = mkdtempSync(join(tmpdir(), 'mat-fail-'))
787
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
788
+ const mod = await import('../lib/redirector.js')
789
+ const { buildProfile } = mod.__test
790
+ try {
791
+ // prepareWindowsBundle refuses to run without a complete bundle (all 8 files).
792
+ const files = {
793
+ 'LICENSE-ProxyBridge.txt': 'license',
794
+ 'NOTICE.md': 'notice',
795
+ 'linux/ProxyBridge': 'linux-cli',
796
+ 'linux/libproxybridge.so': 'linux-so',
797
+ 'windows/ProxyBridgeCore.dll': 'core',
798
+ 'windows/ProxyBridge_CLI.exe': 'cli',
799
+ 'windows/WinDivert.dll': 'divert',
800
+ 'windows/WinDivert64.sys': 'driver',
801
+ }
802
+ for (const [rel, content] of Object.entries(files)) {
803
+ const path = join(home, 'proxybridge', 'bundle', rel)
804
+ mkdirSync(join(path, '..'), { recursive: true })
805
+ writeFileSync(path, content)
806
+ }
807
+ writeFileSync(join(home, 'proxybridge', 'bundle', 'manifest.json'), JSON.stringify({
808
+ version: 1, url: 'x', sha256: 'x', installedAt: 'now',
809
+ files: Object.fromEntries(Object.entries(files).map(([rel, content]) => [rel, content.length])),
810
+ fileHashes: {},
811
+ }))
812
+ // A file where the target directory should be makes the copy fail.
813
+ const blocked = join(home, 'blocked-target')
814
+ writeFileSync(blocked, 'not a directory')
815
+ const { prepareWindowsBundle } = await import('../lib/redirector.js')
816
+ const result1 = prepareWindowsBundle({ targetDir: blocked })
817
+ assert.equal(result1, '')
818
+ const second = prepareWindowsBundle({ targetDir: blocked })
819
+ assert.equal(second, '')
820
+ // force ignores the negative cache and tries again (same failure, but attempted).
821
+ const forced = prepareWindowsBundle({ targetDir: blocked, force: true })
822
+ assert.equal(forced, '')
823
+ } finally {
824
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
825
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
826
+ rmSync(home, { recursive: true, force: true })
827
+ }
828
+ })
829
+
830
+ test('the start-type hint records what the service was before the start (review B-P1-3)', async () => {
831
+ const { mkdtempSync, rmSync, existsSync } = await import('node:fs')
832
+ const { tmpdir } = await import('node:os')
833
+ const { join } = await import('node:path')
834
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
835
+ const home = mkdtempSync(join(tmpdir(), 'start-type-'))
836
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
837
+ const mod = await import('../lib/redirector.js')
838
+ try {
839
+ assert.equal(existsSync(mod.__test.startTypeHintPath()), false)
840
+ assert.equal(mod.__test.readStartTypeHint(), '')
841
+ // Only real service start types are accepted.
842
+ const path = mod.__test.startTypeHintPath()
843
+ const { mkdirSync, writeFileSync } = await import('node:fs')
844
+ mkdirSync(join(home, 'proxybridge'), { recursive: true })
845
+ writeFileSync(path, 'Automatic\n')
846
+ assert.equal(mod.__test.readStartTypeHint(), 'Automatic')
847
+ writeFileSync(path, 'made-up\n')
848
+ assert.equal(mod.__test.readStartTypeHint(), '')
849
+ mod.__test.clearStartTypeHint()
850
+ assert.equal(existsSync(path), false)
851
+ } finally {
852
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
853
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
854
+ rmSync(home, { recursive: true, force: true })
855
+ }
856
+ })
857
+
858
+ test('a root-owned bridge is reported with the command that would stop it (review B-P1-2)', async () => {
859
+ const { __test } = await import('../lib/redirector.js')
860
+ const result = __test.privilegedStopResult(4242, { side: 'local' })
861
+ assert.equal(result.stopped, false)
862
+ assert.equal(result.pid, 4242)
863
+ assert.match(result.reason, /root/)
864
+ assert.equal(result.command, 'sudo kill 4242')
865
+ assert.match(result.hint, /sudo kill 4242/)
866
+ })
867
+
868
+ test('stop answers pendingStart (not "not running") while a start is in flight (review B-P1-5, follow-up b)', async () => {
869
+ const { mkdtempSync, rmSync } = await import('node:fs')
870
+ const { tmpdir } = await import('node:os')
871
+ const { join } = await import('node:path')
872
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
873
+ const home = mkdtempSync(join(tmpdir(), 'stop-lock-'))
874
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
875
+ const mod = await import('../lib/redirector.js')
876
+ try {
877
+ mod.__test.setProbeHooks({ localProc: () => [], windowsPids: () => [] })
878
+ mod.__test.clearProbeCaches()
879
+ const lock = await mod.acquireStartLock('windows', { timeoutMs: 200 })
880
+ assert.equal(lock.ok, true)
881
+ // Nothing is detected (pid files are already cleared during the UAC wait), but
882
+ // the start lock is the truth: stop must say pendingStart and must NOT block for
883
+ // the full 15 s lock timeout on the side it is not touching.
884
+ const started = Date.now()
885
+ const stopped = await mod.__test.stopRedirector({ lockTimeoutMs: 15000 })
886
+ const elapsed = Date.now() - started
887
+ assert.equal(stopped.stopped, false)
888
+ assert.equal(stopped.pendingStart, true)
889
+ assert.equal(stopped.side, 'windows')
890
+ assert.match(stopped.reason ?? '', /另一个进程正在启动/)
891
+ assert.ok(elapsed < 2000, 'stop must probe the lock instead of waiting 15 s per side')
892
+ lock.release()
893
+ } finally {
894
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
895
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
896
+ rmSync(home, { recursive: true, force: true })
897
+ }
898
+ })
899
+
900
+ test('readElevationState treats options.home as the PROXY home (server.js contract, review d)', async () => {
901
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs')
902
+ const { tmpdir } = await import('node:os')
903
+ const { join } = await import('node:path')
904
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
905
+ const home = mkdtempSync(join(tmpdir(), 'elev-home-'))
906
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
907
+ const mod = await import('../lib/redirector.js')
908
+ try {
909
+ mkdirSync(join(home, 'proxybridge'), { recursive: true })
910
+ writeFileSync(join(home, 'proxybridge', 'elevate-local.json'), JSON.stringify({ side: 'local', pid: process.pid, at: new Date().toISOString() }))
911
+ // The daemon passes proxyHomeDir() as `home`; the helper appends proxybridge/.
912
+ assert.equal(mod.readElevationState('local', { home }).active, true)
913
+ assert.equal(mod.readElevationState('linux', { home }).active, true, "'linux' is an alias of 'local'")
914
+ // A direct <home>/elevate-local.json must NOT be picked up: that spelling is
915
+ // what a future redirectorHome() caller would produce (double join).
916
+ writeFileSync(join(home, 'elevate-local.json'), JSON.stringify({ side: 'local', pid: process.pid, at: new Date().toISOString() }))
917
+ rmSync(join(home, 'proxybridge', 'elevate-local.json'))
918
+ assert.equal(mod.readElevationState('local', { home }).active, false, 'home is the proxy home, not the redirector home')
919
+ } finally {
920
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
921
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
922
+ rmSync(home, { recursive: true, force: true })
923
+ }
924
+ })
@@ -15,6 +15,7 @@ import { tmpdir } from 'node:os'
15
15
  import { createHash } from 'node:crypto'
16
16
  import { gzipSync } from 'node:zlib'
17
17
  import { RISD_API_VERSION, risdStatePath } from '../lib/risd/state.js'
18
+ import { successorArgs } from '../lib/risd/server.js'
18
19
  import { bundleLayout } from '../lib/proxybridge-bundle.js'
19
20
  import { readProxyConfig } from '../lib/proxy.js'
20
21
  import { risdConfigRevision } from '../lib/risd/view.js'
@@ -248,6 +249,32 @@ test('the ProxyBridge bundle card reports status and rejects a bad upload', asyn
248
249
  assert.equal(body.actualSha256, null)
249
250
  assert.equal(body.verified, false)
250
251
 
252
+ // Health (m11828/m11838): with the engine stopped the route answers the state
253
+ // without probing binaries — a red "component broken" would be noise.
254
+ const health = await call(state, '/v1/proxybridge/health')
255
+ assert.equal(health.status, 200)
256
+ const healthBody = await health.json()
257
+ assert.equal(healthBody.engineRunning, false)
258
+ assert.equal(healthBody.checked, false)
259
+ assert.equal(healthBody.ok, null)
260
+ assert.deepEqual(healthBody.stray, { linux: false, windows: false })
261
+ assert.deepEqual(healthBody.interception, { linux: false, windows: false })
262
+ // m12359: the card must be able to show the exact sudo command for the Linux side
263
+ // even when no start was attempted in this process.
264
+ assert.equal(typeof healthBody.commands, 'object')
265
+ assert.match(healthBody.commands.linux, /^sudo .*ProxyBridge --profile .*--verbose 2$/)
266
+ // m12486/m12567: the degraded plan covers JVM args, env vars and git.
267
+ assert.ok(Array.isArray(healthBody.degrade.jvmArgs))
268
+ assert.match(healthBody.degrade.jvmArgs.join(' '), /-Dhttps\.proxyHost=127\.0\.0\.1/)
269
+ assert.equal(healthBody.degrade.httpProxyUrl, `http://127.0.0.1:${healthBody.degrade.jvmArgs.find((a) => a.startsWith('-Dhttp.proxyPort=')).split('=')[1]}`)
270
+ assert.equal(typeof healthBody.degrade.note, 'string')
271
+ // A forced probe while stopped still must not spawn anything (nothing to judge).
272
+ const forced = await (await call(state, '/v1/proxybridge/health?force=1')).json()
273
+ assert.equal(forced.checked, false)
274
+ // The reconciler probes the bridge only when there is something to reconcile:
275
+ // a stopped engine with no pid file must not spawn PowerShell on every poll.
276
+ assert.match(readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8'), /engineStopped === true && hasBridgePidFiles\(\) !== true\) return/)
277
+
251
278
  // A non-tar body is answered with a reason, not a crash or a half-installed dir.
252
279
  const bad = await fetch(`${state.url}/v1/proxybridge/upload`, {
253
280
  method: 'POST',
@@ -461,10 +488,27 @@ test('an upload matching the pinned digest installs and verifies (review B-P0-1)
461
488
  test('a restart request hands over to a successor that waits for this pid (m11421)', () => {
462
489
  const server = readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8')
463
490
  assert.match(server, /path === '\/v1\/restart'/, 'the daemon exposes a restart endpoint')
464
- assert.match(server, /spawnRestartSuccessor\(\)\n\s*if \(onShutdown !== null\) onShutdown\(true\)/, 'the restart path spawns the successor then hands off')
465
- assert.match(server, /'serve', '--wait-pid', String\(process\.pid\)/, 'the successor waits for the old pid')
491
+ assert.match(server, /spawnRestartSuccessor\(actualPort\)\n\s*if \(onShutdown !== null\) onShutdown\(true\)/, 'the restart path spawns the successor with the live port then hands off')
492
+ // A4-P2-6: the successor keeps the port this daemon actually bound; A4-P2-5: it
493
+ // also carries the predecessor identity so a reused pid is not waited on.
494
+ const argv = successorArgs({ pid: 4321, port: 11082, startTime: '987654' })
495
+ assert.equal(argv[1], 'serve')
496
+ assert.deepEqual(argv.slice(2, 4), ['--wait-pid', '4321'])
497
+ assert.deepEqual(argv.slice(argv.indexOf('--port'), argv.indexOf('--port') + 2), ['--port', '11082'])
498
+ assert.deepEqual(argv.slice(argv.indexOf('--wait-start'), argv.indexOf('--wait-start') + 2), ['--wait-start', '987654'])
499
+ const noPort = successorArgs({ pid: 7, port: 0, startTime: '' })
500
+ assert.equal(noPort.includes('--port'), false, 'port 0 means "let the OS choose", never --port 0')
501
+ assert.equal(noPort.includes('--wait-start'), false)
466
502
  const cli = readFileSync(new URL('../bin/risd.mjs', import.meta.url), 'utf8')
467
503
  assert.match(cli, /arg === '--wait-pid'/, 'the CLI understands --wait-pid')
468
- assert.match(cli, /await waitForPidExit\(options\.waitPid, 20000\)/, 'serve waits before binding the port')
504
+ assert.match(cli, /arg === '--wait-start'/, 'the CLI understands the pid identity hint')
505
+ assert.match(cli, /await waitForPidExit\(options\.waitPid, 20000, options\.waitStart \?\? ''\)/, 'serve waits before binding the port')
469
506
  })
470
507
 
508
+ test('the daemon only prompts on a user-initiated start and files elevation state per side (review B-P0-2/B-P1-1)', async () => {
509
+ const source = readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8')
510
+ assert.match(source, /const redirector = await serializeBridge\(\(\) => startRedirectors\(\{ interactive: true \}\)\)/)
511
+ const reconcile = source.indexOf('startRedirectors({ sides: missing, interactive: false })')
512
+ assert.ok(reconcile > 0, 'the reconciler starts without an interactive prompt')
513
+ assert.match(source, /linux: readElevationState\('local', \{ home \}\)/, 'the elevation file is named after the side that writes it')
514
+ })