dsh-ris-ide 1.7.3 → 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.
Files changed (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
@@ -56,9 +56,15 @@ test('a Windows command line never carries a WSL-only /mnt path', async () => {
56
56
  'Start-Process cannot resolve /mnt paths: they are WSL-only')
57
57
  const already = 'D:\\apps\\ProxyBridge_CLI.exe'
58
58
  assert.equal(windowsPathOf(already), already, 'an already-Windows path is left alone')
59
+ // Only arguments that are existing files are treated as paths (a `/d` or
60
+ // `/p:key=value` switch is not), so the profile has to exist here — exactly the
61
+ // situation at runtime, where writeRedirectorProfile just wrote it.
62
+ const profileDir = mkdtempSync(join(tmpdir(), 'ris-ide-plan-'))
63
+ const profile = join(profileDir, 'dsh-ris-ide.pbprofile')
64
+ writeFileSync(profile, '{}')
59
65
  const plan = redirectorCommand({
60
66
  cliPath: '/mnt/x/Program Files/ProxyBridge/ProxyBridge_CLI.exe',
61
- profilePath: '/mnt/x/pb/dsh-ris-ide.pbprofile',
67
+ profilePath: profile,
62
68
  platform: 'win32',
63
69
  })
64
70
  assert.equal(plan.display.includes('/mnt/'), false, 'no mnt path may survive in the Windows command')
@@ -159,16 +165,21 @@ test('the start command carries the elevation requirement of each platform', ()
159
165
  })
160
166
 
161
167
  test('detection reports the two sides independently', () => {
168
+ // The distribution is downloaded into ~/.dsh-ris-ide/proxybridge/bundle; when it
169
+ // is not installed yet a machine-wide (manually extracted / packaged) copy is
170
+ // still honoured, which is what this test pins.
162
171
  const vendor = __test.redirectorVendorDir({ platform: 'linux' })
163
172
  mkdirSync(vendor, { recursive: true })
164
173
  const fake = join(vendor, 'ProxyBridge')
165
174
  writeFileSync(fake, '#!/bin/sh\necho "ProxyBridge CLI V9.9.9"\n', { encoding: 'utf8' })
166
175
  chmodSync(fake, 0o755)
167
176
  try {
177
+ __test.clearProbeCaches()
168
178
  const status = __test.redirectorStatus()
169
- assert.equal(status.local.available, true, 'the vendored copy is what WSL uses')
179
+ assert.equal(status.local.available, true)
170
180
  assert.equal(status.local.kind, 'linux-cli')
171
- assert.equal(status.local.version, '9.9.9')
181
+ assert.equal(status.local.path, fake, 'the machine-wide fallback is used when no download exists')
182
+ assert.match(String(status.local.version), /^\d+\.\d+\.\d+$/)
172
183
  // Windows side depends on the machine, so only its shape is checked.
173
184
  assert.equal(typeof status.windows.available, 'boolean')
174
185
  assert.equal(typeof status.windows.path, 'string')
@@ -209,17 +220,25 @@ test('stopping a redirector that is not running is a no-op, not a throw', () =>
209
220
  assert.deepEqual(__test.stopRedirectorSync(), { stopped: false, reason: '未在运行' })
210
221
  })
211
222
 
212
- test('starting without a CLI reports why instead of throwing', async () => {
223
+ test('a missing override falls back to the machine-wide copy', () => {
224
+ // The explicit override is only a preference: a stale path must not hide a real
225
+ // installation (the downloaded cache replaces the old in-repo vendor folder).
226
+ const vendor = __test.redirectorVendorDir({ platform: 'linux' })
227
+ mkdirSync(vendor, { recursive: true })
228
+ const fake = join(vendor, 'ProxyBridge')
229
+ writeFileSync(fake, '#!/bin/sh\necho "x V1.0.0"\n', { encoding: 'utf8' })
230
+ chmodSync(fake, 0o755)
213
231
  const real = process.env.DSH_RIS_IDE_PROXYBRIDGE
214
- process.env.DSH_RIS_IDE_PROXYBRIDGE = join(home, 'proxybridge', 'vendor', 'linux', 'ProxyBridge')
215
- rmSync(join(home, 'proxybridge', 'vendor'), { recursive: true, force: true })
232
+ process.env.DSH_RIS_IDE_PROXYBRIDGE = join(home, 'proxybridge', 'vendor', 'linux', 'missing-ProxyBridge')
216
233
  try {
217
- const result = await __test.startRedirector({ side: 'local' })
218
- assert.equal(result.started, false)
219
- assert.match(String(result.reason), /未找到/)
234
+ __test.clearProbeCaches()
235
+ const found = __test.findRedirector({ side: 'local' })
236
+ assert.equal(found.found, true)
237
+ assert.equal(found.path, fake)
220
238
  } finally {
221
239
  if (real === undefined) delete process.env.DSH_RIS_IDE_PROXYBRIDGE
222
240
  else process.env.DSH_RIS_IDE_PROXYBRIDGE = real
241
+ rmSync(fake, { force: true })
223
242
  }
224
243
  })
225
244
 
@@ -466,6 +485,37 @@ test('the profile names a rule by its label so the ProxyBridge console stays rea
466
485
  assert.equal(plain.profile.ProxyRules[0].Name, 'yds-java')
467
486
  })
468
487
 
488
+ test('a stale stop marker never answers the next stop request (B-P2-7)', async () => {
489
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
490
+ const mod = await import('../lib/redirector.js')
491
+ // The watchdog wrote "done" for an earlier stop; nothing has been asked for the
492
+ // new one yet, so a plain "does the file exist" read would report success while
493
+ // the CLI is still intercepting.
494
+ writeFileSync(mod.stoppedMarkerPath(), 'done\n')
495
+ assert.equal(mod.stopCompleted(), true)
496
+ assert.equal(mod.requestRedirectorStop(), true)
497
+ assert.equal(mod.stopCompleted(), false, 'the request cleared the previous answer')
498
+ assert.equal(existsSync(mod.stopRequestPath()), true)
499
+ mod.clearStopSignals()
500
+ })
501
+
502
+ test('stopping a hand-started bridge is recorded instead of silently killed (B-P2-10)', () => {
503
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
504
+ __test.clearRedirectorPid()
505
+ useHooks({ windowsPids: () => [5555], windowsAlive: () => false, taskkill: () => 'SUCCESS' })
506
+ try {
507
+ const result = __test.stopRedirectorSync({ graceMs: 100 })
508
+ assert.equal(result.stopped, true)
509
+ assert.equal(result.foreign, true, 'the pid came from detection, not from our pid file')
510
+ const log = readFileSync(join(home, 'proxy-forward.log'), 'utf8')
511
+ assert.match(log, /非本工具记录的桥接 pid=5555/)
512
+ } finally {
513
+ useHooks({})
514
+ __test.clearRedirectorPid()
515
+ rmSync(join(home, 'proxy-forward.log'), { force: true })
516
+ }
517
+ })
518
+
469
519
  test('the heartbeat ages out and the stop signals round-trip', async () => {
470
520
  const tmpHome = mkdtempSync(join(tmpdir(), 'hb-'))
471
521
  process.env.DSH_RIS_IDE_PROXY_HOME = tmpHome
@@ -504,10 +554,17 @@ test('the elevated watchdog script carries the rules it needs to tear down', asy
504
554
  // leaves an elevated CLI behind — both are silent, so assert the pieces.
505
555
  assert.match(script, /Test-Path \$stopFile/)
506
556
  assert.match(script, /heartbeat-stale/)
507
- 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/)
508
560
  assert.match(script, /Set-Service -Name ProxyBridgeSvc -StartupType \$state\.originalStartType/)
509
561
  assert.match(script, /New-Item -ItemType File -Path \$doneFile/)
510
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/)
511
568
 
512
569
  const written = mod.writeWatchdogScript()
513
570
  // It returns the WINDOWS path (that is where it runs); the file itself is ours.
@@ -519,3 +576,349 @@ test('the elevated watchdog script carries the rules it needs to tear down', asy
519
576
  rmSync(tmpHome, { recursive: true, force: true })
520
577
  }
521
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
+ })