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.
Files changed (52) hide show
  1. package/README.md +5 -3
  2. package/bin/risd.mjs +14 -17
  3. package/lib/client.js +400 -93
  4. package/lib/debug/vendor/README.md +14 -0
  5. package/lib/debug/vendor/jdwp/client.js +9 -4
  6. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  7. package/lib/index.js +794 -48
  8. package/lib/proxybridge-bundle.js +1 -1
  9. package/lib/proxybridge-health.js +206 -0
  10. package/lib/redirector.js +1181 -90
  11. package/lib/risd/lifecycle.js +9 -3
  12. package/lib/risd/server.js +762 -26
  13. package/lib/risd/ui.js +419 -98
  14. package/lib/risd-client.js +4 -1
  15. package/lib/startup.js +27 -7
  16. package/package.json +2 -2
  17. package/test/client-viewer.test.mjs +299 -120
  18. package/test/clipboard.test.mjs +259 -0
  19. package/test/debug-engine.test.mjs +3 -1
  20. package/test/dsh-origin.test.mjs +4 -11
  21. package/test/dsh-window-refresh.test.mjs +166 -1
  22. package/test/harness.test.mjs +1 -1
  23. package/test/helpers/cmd.mjs +29 -0
  24. package/test/helpers/tgz.mjs +71 -0
  25. package/test/host-search.test.mjs +18 -11
  26. package/test/host-tail.test.mjs +119 -24
  27. package/test/proxy-route.test.mjs +61 -0
  28. package/test/proxy-window.test.mjs +5 -0
  29. package/test/proxy.test.mjs +13 -1
  30. package/test/proxybridge-bundle.test.mjs +1 -59
  31. package/test/proxybridge-health.test.mjs +116 -0
  32. package/test/redirector-bundle.test.mjs +21 -67
  33. package/test/redirector.test.mjs +395 -5
  34. package/test/risd-api.test.mjs +114 -17
  35. package/test/risd-bridge-degrade.test.mjs +3 -29
  36. package/test/risd-engine.test.mjs +13 -50
  37. package/test/risd-entry.test.mjs +0 -37
  38. package/test/risd-follow-start.test.mjs +101 -0
  39. package/test/risd-git.test.mjs +7 -5
  40. package/test/risd-handoff.test.mjs +6 -50
  41. package/test/risd-helpers.mjs +150 -3
  42. package/test/risd-host-p2.test.mjs +2 -30
  43. package/test/risd-lifecycle.test.mjs +25 -0
  44. package/test/risd-programs.test.mjs +4 -34
  45. package/test/risd-restart.test.mjs +104 -0
  46. package/test/risd-review-p2.test.mjs +0 -13
  47. package/test/risd-shutdown.test.mjs +5 -38
  48. package/test/risd-teardown.test.mjs +8 -27
  49. package/test/risd-ui.test.mjs +322 -4
  50. package/test/risd-write.test.mjs +2 -1
  51. package/test/startup-reconcile.test.mjs +44 -8
  52. package/test/proxy-restart.test.mjs +0 -37
@@ -10,13 +10,43 @@ import assert from 'node:assert/strict'
10
10
  import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, mkdirSync } from 'node:fs'
11
11
  import { tmpdir } from 'node:os'
12
12
  import { join } from 'node:path'
13
- import test from 'node:test'
13
+ import test, { after } from 'node:test'
14
+
15
+ import { engineSide } from '../lib/proxy.js'
16
+ import { HAS_WSLPATH, skipWithout } from './helpers/cmd.mjs'
14
17
 
15
18
  const home = mkdtempSync(join(tmpdir(), 'ris-redirector-home-'))
16
19
  process.env.DSH_RIS_IDE_PROXY_HOME = home
17
20
 
21
+ // `spawnDetachedText` unrefs its timeout and its child on purpose (a launcher that
22
+ // outlives its caller must not hold the daemon open). Those handles can be the ONLY
23
+ // thing a waiting test has, and on node 20/22 the test runner keeps no handle of its
24
+ // own: the loop runs dry, the pending `await` never settles and every later test in
25
+ // the file is cancelled with "Promise resolution is still pending but the event loop
26
+ // has already resolved". node 24 happens to keep the runner referenced, which is why
27
+ // this only failed in CI. Hold ONE referenced timer for the file; the after hook
28
+ // releases it so the runner can still exit.
29
+ const keepLoopAlive = setInterval(() => { /* keep the loop referenced (see above) */ }, 1000)
30
+ after(() => clearInterval(keepLoopAlive))
31
+
18
32
  const { __test } = await import('../lib/redirector.js')
19
33
 
34
+ /**
35
+ * CI runs this suite on a plain Linux host (a k8s pod): no WSL, no `wslpath`, no
36
+ * Windows side — so `windowsPathOf` cannot answer there and the two watchdog
37
+ * tests could only ever run on a developer's WSL machine. On such a host we
38
+ * inject the mapping the WSL box would have produced; production still asks
39
+ * `wslpath` (`test/redirector.test.mjs` is the only caller of this seam).
40
+ */
41
+ const WSL_DISTRO = 'Ubuntu'
42
+ if (engineSide() !== 'wsl') {
43
+ __test.setWindowsPathTranslator((path) => {
44
+ const text = String(path)
45
+ if (text.startsWith('/') !== true) return ''
46
+ return `\\\\wsl.localhost\\${WSL_DISTRO}${text.replace(/\//g, '\\')}`
47
+ })
48
+ }
49
+
20
50
  /**
21
51
  * Every probe that could reach the real Windows side is stubbed for the whole
22
52
  * file. A test run must never enumerate, kill or elevate the user's actual
@@ -31,7 +61,7 @@ const BASE_HOOKS = {
31
61
  taskkill: () => 'ERROR: Access is denied.',
32
62
  }
33
63
  __test.setProbeHooks(BASE_HOOKS)
34
- process.on('exit', () => __test.resetProbeHooks())
64
+ process.on('exit', () => { __test.resetProbeHooks(); __test.setWindowsPathTranslator(null) })
35
65
  /** Use one extra stub for a single test, then fall back to the safe defaults. */
36
66
  const useHooks = (hooks) => {
37
67
  __test.resetProbeHooks()
@@ -66,6 +96,10 @@ test('a Windows command line never carries a WSL-only /mnt path', async () => {
66
96
  cliPath: '/mnt/x/Program Files/ProxyBridge/ProxyBridge_CLI.exe',
67
97
  profilePath: profile,
68
98
  platform: 'win32',
99
+ // The translation rule is what is under test here, not whether THIS machine
100
+ // has a Windows side: on a plain-Linux CI host `engineSide()` is 'linux' and
101
+ // the default gate would keep `/mnt` in the command line.
102
+ translate: true,
69
103
  })
70
104
  assert.equal(plan.display.includes('/mnt/'), false, 'no mnt path may survive in the Windows command')
71
105
  assert.ok(plan.display.includes('X:\\Program Files'), 'the executable must be spelled the Windows way')
@@ -298,7 +332,10 @@ test('the old single pid file is migrated to the side it names (M1)', () => {
298
332
  __test.clearRedirectorPid()
299
333
  })
300
334
 
301
- test('the parked-service state has ONE path shared by writer and watchdog (B2)', async () => {
335
+ // 纯 Linux(Jenkins 裸镜像)用上面的接缝;WSL 上必须真有 wslpath 才能算 Windows 路径。
336
+ const WINDOWS_SIDE = engineSide() !== 'wsl' || HAS_WSLPATH
337
+
338
+ test('the parked-service state has ONE path shared by writer and watchdog (B2)', { skip: skipWithout(WINDOWS_SIDE, 'wslpath') }, async () => {
302
339
  process.env.DSH_RIS_IDE_PROXY_HOME = home
303
340
  const mod = await import('../lib/redirector.js')
304
341
  const canonical = __test.serviceStatePath()
@@ -541,7 +578,7 @@ test('the heartbeat ages out and the stop signals round-trip', async () => {
541
578
  }
542
579
  })
543
580
 
544
- test('the elevated watchdog script carries the rules it needs to tear down', async () => {
581
+ test('the elevated watchdog script carries the rules it needs to tear down', { skip: skipWithout(WINDOWS_SIDE, 'wslpath') }, async () => {
545
582
  const tmpHome = mkdtempSync(join(tmpdir(), 'wd-'))
546
583
  process.env.DSH_RIS_IDE_PROXY_HOME = tmpHome
547
584
  const mod = await import('../lib/redirector.js')
@@ -554,10 +591,17 @@ test('the elevated watchdog script carries the rules it needs to tear down', asy
554
591
  // leaves an elevated CLI behind — both are silent, so assert the pieces.
555
592
  assert.match(script, /Test-Path \$stopFile/)
556
593
  assert.match(script, /heartbeat-stale/)
557
- assert.match(script, /Get-Process ProxyBridge_CLI .*Stop-Process -Force/)
594
+ assert.match(script, /\(Get-OwnCli\) \| ForEach-Object \{ Stop-Process -Id \$_\.ProcessId -Force \}/)
595
+ // Only CLIs carrying THIS home's profile may be torn down (review A4-P2-1).
596
+ assert.match(script, /IndexOf\(\$ownProfile/)
558
597
  assert.match(script, /Set-Service -Name ProxyBridgeSvc -StartupType \$state\.originalStartType/)
559
598
  assert.match(script, /New-Item -ItemType File -Path \$doneFile/)
560
599
  assert.match(script, /\$age -lt 20/)
600
+ // Two watchdogs fighting over the same reload request restart the CLI twice
601
+ // (m11702): one copy owns a named mutex, the second exits immediately.
602
+ assert.match(script, /System\.Threading\.Mutex/)
603
+ assert.match(script, /WaitOne\(0\)/)
604
+ assert.match(script, /another watchdog owns the mutex; exiting/)
561
605
 
562
606
  const written = mod.writeWatchdogScript()
563
607
  // It returns the WINDOWS path (that is where it runs); the file itself is ours.
@@ -569,3 +613,349 @@ test('the elevated watchdog script carries the rules it needs to tear down', asy
569
613
  rmSync(tmpHome, { recursive: true, force: true })
570
614
  }
571
615
  })
616
+
617
+ test('a bridge start retires the previous elevated watchdog (m11702)', async () => {
618
+ // Every start used to spawn a watchdog and leave the old one running (it only
619
+ // exits on a stop request or a stale heartbeat, and dsh keeps the heartbeat
620
+ // fresh). Two watchdogs then restart the CLI concurrently — one wins the
621
+ // WinDivert handle, the other silently captures nothing. The start script must
622
+ // kill the leftovers in the same elevated context that creates the new one.
623
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
624
+ assert.ok(source.includes('IndexOf($wdScript'), 'the start script must recognise leftover watchdogs by THIS home\'s script path')
625
+ assert.ok(source.includes('Stop-Process -Id $_.ProcessId -Force'), 'the start script must kill them, not just look')
626
+ assert.ok(source.includes('oldWatchdogs='), 'the elevated report should say how many were retired')
627
+ })
628
+
629
+ test('both sides are single-instance: a start lock and duplicate discovery (m11773)', async () => {
630
+ const tmpHome = mkdtempSync(join(tmpdir(), 'single-'))
631
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
632
+ process.env.DSH_RIS_IDE_PROXY_HOME = tmpHome
633
+ const mod = await import('../lib/redirector.js')
634
+ try {
635
+ // 1. A second concurrent start must not get the lock while the first holds it.
636
+ const first = await mod.acquireStartLock('local', { timeoutMs: 200 })
637
+ assert.equal(first.ok, true)
638
+ const second = await mod.acquireStartLock('local', { timeoutMs: 150 })
639
+ assert.equal(second.ok, false)
640
+ assert.match(second.reason ?? '', /另一个进程正在启动/)
641
+ first.release()
642
+ const third = await mod.acquireStartLock('local', { timeoutMs: 150 })
643
+ assert.equal(third.ok, true, 'releasing the lock must let the next start in')
644
+ third.release()
645
+ // 2. A starter that died leaves a stale lock: the owner pid is gone.
646
+ const staleDir = join(tmpHome, 'locks', 'proxybridge-local.lock')
647
+ mkdirSync(staleDir, { recursive: true })
648
+ writeFileSync(join(staleDir, 'owner'), '999999\n')
649
+ const fourth = await mod.acquireStartLock('local', { timeoutMs: 300 })
650
+ assert.equal(fourth.ok, true, 'a dead owner must not block every later start')
651
+ fourth.release()
652
+ // 3. Every local engine is discoverable, not just the first (the old scan
653
+ // returned one pid, so a duplicate could never be reaped).
654
+ mod.__test.setProbeHooks({ localProc: () => [111, 222] })
655
+ assert.deepEqual(mod.localRedirectorPids(), [111, 222])
656
+ mod.__test.resetProbeHooks()
657
+ // 4. The Windows elevated start is serialised too: a second helper reports
658
+ // start-busy instead of racing the first one's CLI.
659
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
660
+ assert.ok(source.includes('start-busy=True'), 'a concurrent Windows start must be reported, not faked')
661
+ assert.ok(source.includes('proxybridge-start-'), 'the start mutex is per proxy home')
662
+ assert.ok(source.includes('旧 watchdog') || source.includes('oldWatchdogs='), 'old watchdogs are still retired at start')
663
+ } finally {
664
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
665
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
666
+ rmSync(tmpHome, { recursive: true, force: true })
667
+ }
668
+ })
669
+ test('the local side falls back to pkexec when sudo is not passwordless (m12606)', async () => {
670
+ // Elevation here is a decision tree, not a UI detail: sudo -n, then pkexec, then
671
+ // the manual command. Keep the strings in the source so a refactor cannot quietly
672
+ // drop the dialog path.
673
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
674
+ assert.match(source, /pkexecAvailable\(\)/)
675
+ assert.match(source, /spawn\('pkexec', \[found\.path, \.\.\.plan\.args\]/)
676
+ assert.match(source, /method: 'pkexec'/)
677
+ assert.match(source, /method: 'manual'/)
678
+ // Clicking 提权启动 must be able to hand the password to a real terminal (m12782).
679
+ assert.match(source, /function openElevatedTerminal\(/)
680
+ assert.match(source, /method: 'terminal'/)
681
+ assert.match(source, /TERMINAL_CANDIDATES/)
682
+ // Headless Linux has no window to open: skip X11 clients without a session (m12884).
683
+ assert.match(source, /function hasGraphicalSession\(/)
684
+ assert.match(source, /candidate\.bin !== 'wt\.exe' && hasGraphicalSession\(\) === false/)
685
+ // The password is typed in the window, then the CLI must survive the window: sudo
686
+ // ticket first, detached `sudo -n` afterwards (m12896).
687
+ assert.match(source, /sudo -v \|\|/)
688
+ assert.match(source, /nohup sudo -n /)
689
+ assert.match(source, /--size/)
690
+ // m13083: -f maximized the window, so it is gone; the size keeps it small.
691
+ assert.match(source, /--size', '64,16'/)
692
+ // m13147/m13257: the helper launches WT itself and centers the one new window,
693
+ // because WT hosts every window in one process (a title or pid cannot identify it).
694
+ assert.match(source, /launchCenteredTerminal/)
695
+ assert.match(source, /MoveWindow/)
696
+ assert.match(source, /center-terminal\.ps1/)
697
+ assert.match(source, /Start-Process -FilePath 'wt\.exe'/)
698
+ })
699
+ test('the elevation script detaches the CLI so the window can close (m12896)', async () => {
700
+ const { mkdtempSync, rmSync } = await import('node:fs')
701
+ const { tmpdir } = await import('node:os')
702
+ const { join } = await import('node:path')
703
+ const { elevationScript } = await import('../lib/redirector.js')
704
+ const dir = mkdtempSync(join(tmpdir(), 'risd-elevate-'))
705
+ try {
706
+ // 'linux' is the page's spelling; the helper/state files are always `local`
707
+ // (review B-P1-1), so this must not produce elevate-linux.*.
708
+ const plan = elevationScript('sudo /opt/ProxyBridge --profile p --verbose 2', 'linux', {
709
+ dir,
710
+ argv: ['/opt/ProxyBridge', '--profile', 'a b', '--verbose', '2'],
711
+ })
712
+ assert.equal(plan.scriptPath, join(dir, 'elevate-local.sh'))
713
+ assert.match(plan.body, /^#!\/bin\/bash/m)
714
+ assert.match(plan.body, /sudo -v \|\|/)
715
+ // argv entries are single-quoted for bash (review B-P2-10): a profile path the
716
+ // user can choose must not be able to inject a command into the sudo line.
717
+ assert.match(plan.body, /nohup sudo -n '\/opt\/ProxyBridge' '--profile' 'a b' '--verbose' '2' > "\$LOG" 2>&1 &/)
718
+ assert.match(plan.body, /sleep 1/)
719
+ } finally {
720
+ rmSync(dir, { recursive: true, force: true })
721
+ }
722
+ })
723
+ test('the elevation note clears when the helper script exits (m12923)', async () => {
724
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs')
725
+ const { tmpdir } = await import('node:os')
726
+ const { join } = await import('node:path')
727
+ const { readElevationState } = await import('../lib/redirector.js')
728
+ const home = mkdtempSync(join(tmpdir(), 'risd-elev-state-'))
729
+ try {
730
+ // The writer puts it in <proxy home>/proxybridge/ (elevationScript's default
731
+ // dir) — reading <proxy home>/elevate-*.json never found it (review B-P1-1).
732
+ const file = join(home, 'proxybridge', 'elevate-local.json')
733
+ mkdirSync(join(home, 'proxybridge'), { recursive: true })
734
+ writeFileSync(file, JSON.stringify({ side: 'local', pid: process.pid, at: new Date().toISOString() }))
735
+ assert.equal(readElevationState('local', { home }).active, true)
736
+ // The page still calls this side 'linux'; both spellings must find the file.
737
+ assert.equal(readElevationState('linux', { home }).active, true)
738
+ rmSync(file)
739
+ assert.equal(readElevationState('local', { home }).active, false)
740
+ // A stale file from a dead pid must not keep the note on screen either.
741
+ writeFileSync(file, JSON.stringify({ side: 'local', pid: 999999, at: new Date().toISOString() }))
742
+ assert.equal(readElevationState('local', { home }).active, false)
743
+ // A SIGKILL leaves the file behind; its TTL stops the note from sticking forever.
744
+ writeFileSync(file, JSON.stringify({ side: 'local', pid: process.pid, at: new Date(Date.now() - 11 * 60 * 1000).toISOString() }))
745
+ assert.equal(readElevationState('local', { home }).active, false)
746
+ // Unknown side names must not be interpolated into a path.
747
+ assert.equal(readElevationState('../evil', { home }).active, false)
748
+ } finally {
749
+ rmSync(home, { recursive: true, force: true })
750
+ }
751
+ })
752
+
753
+ test('only a user-initiated start may raise an interactive prompt (review B-P0-2)', async () => {
754
+ const source = readFileSync(new URL('../lib/redirector.js', import.meta.url), 'utf8')
755
+ // The gate must sit BEFORE the pkexec branch: the reconciler calls this every
756
+ // minute, and a prompt there is a polkit dialog / terminal window per minute.
757
+ const gate = source.indexOf("if (options.interactive !== true) {")
758
+ const pkexec = source.indexOf('if (pkexecAvailable() === true) {')
759
+ assert.ok(gate > 0, 'the interactive gate exists')
760
+ assert.ok(pkexec > 0 && gate < pkexec, 'the gate precedes pkexec')
761
+ assert.match(source, /startRedirector\(\{ side, verbose: options\.verbose, interactive: options\.interactive === true \}\)/)
762
+ assert.match(source, /export function localRedirectorOwnPids\(\)/)
763
+ assert.match(source, /const own = localRedirectorOwnPids\(\)/, 'detection adopts our own hand-started bridge')
764
+ })
765
+
766
+ test('the elevated launcher no longer blocks the daemon (review B-P0-1)', async () => {
767
+ const { __test } = await import('../lib/redirector.js')
768
+ // spawnSync waited for the UAC dialog (up to 45 s) with the daemon's 3 s
769
+ // heartbeat and every HTTP route behind it. While the launcher runs, timers must
770
+ // still fire.
771
+ let ticks = 0
772
+ const timer = setInterval(() => { ticks += 1 }, 20)
773
+ try {
774
+ const started = Date.now()
775
+ const result = await __test.spawnDetachedText(process.execPath, ['-e', 'setTimeout(() => {}, 150)'], 2000)
776
+ const elapsed = Date.now() - started
777
+ assert.equal(result.timedOut, false)
778
+ assert.ok(ticks > 0, 'the event loop kept running while the launcher waited')
779
+ assert.ok(elapsed < 1500, `launcher returned after ${elapsed} ms`)
780
+ } finally {
781
+ clearInterval(timer)
782
+ }
783
+ })
784
+
785
+ test('a hung launcher is killed at the timeout (review B-P0-1)', async () => {
786
+ const { __test } = await import('../lib/redirector.js')
787
+ const started = Date.now()
788
+ const result = await __test.spawnDetachedText(process.execPath, ['-e', 'setTimeout(() => {}, 5000)'], 150)
789
+ assert.equal(result.timedOut, true)
790
+ assert.ok(Date.now() - started < 1500, 'the timeout must not wait for the child')
791
+ })
792
+
793
+ test('a stale lock release cannot delete the next owner\'s lock (review B-P2-9)', async () => {
794
+ const { mkdtempSync, rmSync, writeFileSync, existsSync } = await import('node:fs')
795
+ const { tmpdir } = await import('node:os')
796
+ const { join } = await import('node:path')
797
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
798
+ const home = mkdtempSync(join(tmpdir(), 'lock-own-'))
799
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
800
+ const mod = await import('../lib/redirector.js')
801
+ try {
802
+ const lock = await mod.acquireStartLock('local', { timeoutMs: 200 })
803
+ assert.equal(lock.ok, true)
804
+ const dir = join(home, 'locks', 'proxybridge-local.lock')
805
+ // Another starter took the lock over after we were considered stale; our late
806
+ // release must not remove ITS lock.
807
+ writeFileSync(join(dir, 'owner'), `${process.pid + 1}\n`)
808
+ lock.release()
809
+ assert.equal(existsSync(dir), true, 'release only removes our own lock')
810
+ rmSync(dir, { recursive: true, force: true })
811
+ } finally {
812
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
813
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
814
+ rmSync(home, { recursive: true, force: true })
815
+ }
816
+ })
817
+
818
+ test('a failed materialisation is cached briefly, and force retries (review B-P2-13)', async () => {
819
+ const { mkdtempSync, rmSync, writeFileSync, mkdirSync } = await import('node:fs')
820
+ const { tmpdir } = await import('node:os')
821
+ const { join } = await import('node:path')
822
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
823
+ const home = mkdtempSync(join(tmpdir(), 'mat-fail-'))
824
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
825
+ const mod = await import('../lib/redirector.js')
826
+ const { buildProfile } = mod.__test
827
+ try {
828
+ // prepareWindowsBundle refuses to run without a complete bundle (all 8 files).
829
+ const files = {
830
+ 'LICENSE-ProxyBridge.txt': 'license',
831
+ 'NOTICE.md': 'notice',
832
+ 'linux/ProxyBridge': 'linux-cli',
833
+ 'linux/libproxybridge.so': 'linux-so',
834
+ 'windows/ProxyBridgeCore.dll': 'core',
835
+ 'windows/ProxyBridge_CLI.exe': 'cli',
836
+ 'windows/WinDivert.dll': 'divert',
837
+ 'windows/WinDivert64.sys': 'driver',
838
+ }
839
+ for (const [rel, content] of Object.entries(files)) {
840
+ const path = join(home, 'proxybridge', 'bundle', rel)
841
+ mkdirSync(join(path, '..'), { recursive: true })
842
+ writeFileSync(path, content)
843
+ }
844
+ writeFileSync(join(home, 'proxybridge', 'bundle', 'manifest.json'), JSON.stringify({
845
+ version: 1, url: 'x', sha256: 'x', installedAt: 'now',
846
+ files: Object.fromEntries(Object.entries(files).map(([rel, content]) => [rel, content.length])),
847
+ fileHashes: {},
848
+ }))
849
+ // A file where the target directory should be makes the copy fail.
850
+ const blocked = join(home, 'blocked-target')
851
+ writeFileSync(blocked, 'not a directory')
852
+ const { prepareWindowsBundle } = await import('../lib/redirector.js')
853
+ const result1 = prepareWindowsBundle({ targetDir: blocked })
854
+ assert.equal(result1, '')
855
+ const second = prepareWindowsBundle({ targetDir: blocked })
856
+ assert.equal(second, '')
857
+ // force ignores the negative cache and tries again (same failure, but attempted).
858
+ const forced = prepareWindowsBundle({ targetDir: blocked, force: true })
859
+ assert.equal(forced, '')
860
+ } finally {
861
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
862
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
863
+ rmSync(home, { recursive: true, force: true })
864
+ }
865
+ })
866
+
867
+ test('the start-type hint records what the service was before the start (review B-P1-3)', async () => {
868
+ const { mkdtempSync, rmSync, existsSync } = await import('node:fs')
869
+ const { tmpdir } = await import('node:os')
870
+ const { join } = await import('node:path')
871
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
872
+ const home = mkdtempSync(join(tmpdir(), 'start-type-'))
873
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
874
+ const mod = await import('../lib/redirector.js')
875
+ try {
876
+ assert.equal(existsSync(mod.__test.startTypeHintPath()), false)
877
+ assert.equal(mod.__test.readStartTypeHint(), '')
878
+ // Only real service start types are accepted.
879
+ const path = mod.__test.startTypeHintPath()
880
+ const { mkdirSync, writeFileSync } = await import('node:fs')
881
+ mkdirSync(join(home, 'proxybridge'), { recursive: true })
882
+ writeFileSync(path, 'Automatic\n')
883
+ assert.equal(mod.__test.readStartTypeHint(), 'Automatic')
884
+ writeFileSync(path, 'made-up\n')
885
+ assert.equal(mod.__test.readStartTypeHint(), '')
886
+ mod.__test.clearStartTypeHint()
887
+ assert.equal(existsSync(path), false)
888
+ } finally {
889
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
890
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
891
+ rmSync(home, { recursive: true, force: true })
892
+ }
893
+ })
894
+
895
+ test('a root-owned bridge is reported with the command that would stop it (review B-P1-2)', async () => {
896
+ const { __test } = await import('../lib/redirector.js')
897
+ const result = __test.privilegedStopResult(4242, { side: 'local' })
898
+ assert.equal(result.stopped, false)
899
+ assert.equal(result.pid, 4242)
900
+ assert.match(result.reason, /root/)
901
+ assert.equal(result.command, 'sudo kill 4242')
902
+ assert.match(result.hint, /sudo kill 4242/)
903
+ })
904
+
905
+ test('stop answers pendingStart (not "not running") while a start is in flight (review B-P1-5, follow-up b)', async () => {
906
+ const { mkdtempSync, rmSync } = await import('node:fs')
907
+ const { tmpdir } = await import('node:os')
908
+ const { join } = await import('node:path')
909
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
910
+ const home = mkdtempSync(join(tmpdir(), 'stop-lock-'))
911
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
912
+ const mod = await import('../lib/redirector.js')
913
+ try {
914
+ mod.__test.setProbeHooks({ localProc: () => [], windowsPids: () => [] })
915
+ mod.__test.clearProbeCaches()
916
+ const lock = await mod.acquireStartLock('windows', { timeoutMs: 200 })
917
+ assert.equal(lock.ok, true)
918
+ // Nothing is detected (pid files are already cleared during the UAC wait), but
919
+ // the start lock is the truth: stop must say pendingStart and must NOT block for
920
+ // the full 15 s lock timeout on the side it is not touching.
921
+ const started = Date.now()
922
+ const stopped = await mod.__test.stopRedirector({ lockTimeoutMs: 15000 })
923
+ const elapsed = Date.now() - started
924
+ assert.equal(stopped.stopped, false)
925
+ assert.equal(stopped.pendingStart, true)
926
+ assert.equal(stopped.side, 'windows')
927
+ assert.match(stopped.reason ?? '', /另一个进程正在启动/)
928
+ assert.ok(elapsed < 2000, 'stop must probe the lock instead of waiting 15 s per side')
929
+ lock.release()
930
+ } finally {
931
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
932
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
933
+ rmSync(home, { recursive: true, force: true })
934
+ }
935
+ })
936
+
937
+ test('readElevationState treats options.home as the PROXY home (server.js contract, review d)', async () => {
938
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs')
939
+ const { tmpdir } = await import('node:os')
940
+ const { join } = await import('node:path')
941
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
942
+ const home = mkdtempSync(join(tmpdir(), 'elev-home-'))
943
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
944
+ const mod = await import('../lib/redirector.js')
945
+ try {
946
+ mkdirSync(join(home, 'proxybridge'), { recursive: true })
947
+ writeFileSync(join(home, 'proxybridge', 'elevate-local.json'), JSON.stringify({ side: 'local', pid: process.pid, at: new Date().toISOString() }))
948
+ // The daemon passes proxyHomeDir() as `home`; the helper appends proxybridge/.
949
+ assert.equal(mod.readElevationState('local', { home }).active, true)
950
+ assert.equal(mod.readElevationState('linux', { home }).active, true, "'linux' is an alias of 'local'")
951
+ // A direct <home>/elevate-local.json must NOT be picked up: that spelling is
952
+ // what a future redirectorHome() caller would produce (double join).
953
+ writeFileSync(join(home, 'elevate-local.json'), JSON.stringify({ side: 'local', pid: process.pid, at: new Date().toISOString() }))
954
+ rmSync(join(home, 'proxybridge', 'elevate-local.json'))
955
+ assert.equal(mod.readElevationState('local', { home }).active, false, 'home is the proxy home, not the redirector home')
956
+ } finally {
957
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
958
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
959
+ rmSync(home, { recursive: true, force: true })
960
+ }
961
+ })
@@ -9,7 +9,8 @@
9
9
  */
10
10
  import assert from 'node:assert/strict'
11
11
  import test from 'node:test'
12
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
12
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { createServer } from 'node:http'
13
14
  import { join } from 'node:path'
14
15
  import { tmpdir } from 'node:os'
15
16
  import { createHash } from 'node:crypto'
@@ -190,18 +191,21 @@ test('the payload is the whole table: rows it leaves out are retired (m10585)',
190
191
  }), null, 2)}\n`, { mode: 0o600 })
191
192
  const view = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(ws)}`)).json()
192
193
  const userRule = view.rules.find((rule) => rule.id === 'r1')
194
+ // A row the stored table never had proves the upsert direction too (it used to
195
+ // live in a separate test, risd-api:'a sent row is upserted…').
196
+ const newRow = { id: 'kept-1', program: 'java', hosts: '10.0.0.*', ports: '*', enabled: true, source: 'yds' }
193
197
  const saved = await call(state, '/v1/proxy', {
194
198
  method: 'POST',
195
199
  body: {
196
200
  cwd: ws,
197
- config: { socks: view.socks, listenPort: view.listenPort, rules: [userRule] },
201
+ config: { socks: view.socks, listenPort: view.listenPort, rules: [userRule, newRow] },
198
202
  revision: view.revision,
199
203
  },
200
204
  })
201
205
  assert.equal(saved.status, 200)
202
206
  const after = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(ws)}`)).json()
203
- assert.deepEqual(after.rules.map((rule) => rule.id).sort(), ['r1'],
204
- 'only the rows in the payload survive')
207
+ assert.deepEqual(after.rules.map((rule) => rule.id).sort(), ['kept-1', 'r1'],
208
+ 'the sent row is inserted, and only the rows in the payload survive')
205
209
  })
206
210
 
207
211
  test('the ping route probes the configured SOCKS upstream and honours overrides', async (t) => {
@@ -248,6 +252,28 @@ test('the ProxyBridge bundle card reports status and rejects a bad upload', asyn
248
252
  assert.equal(body.actualSha256, null)
249
253
  assert.equal(body.verified, false)
250
254
 
255
+ // Health (m11828/m11838): with the engine stopped the route answers the state
256
+ // without probing binaries — a red "component broken" would be noise.
257
+ const health = await call(state, '/v1/proxybridge/health')
258
+ assert.equal(health.status, 200)
259
+ const healthBody = await health.json()
260
+ assert.equal(healthBody.engineRunning, false)
261
+ assert.equal(healthBody.checked, false)
262
+ assert.equal(healthBody.ok, null)
263
+ assert.deepEqual(healthBody.stray, { linux: false, windows: false })
264
+ assert.deepEqual(healthBody.interception, { linux: false, windows: false })
265
+ // m12359: the card must be able to show the exact sudo command for the Linux side
266
+ // even when no start was attempted in this process.
267
+ assert.equal(typeof healthBody.commands, 'object')
268
+ assert.match(healthBody.commands.linux, /^sudo .*ProxyBridge --profile .*--verbose 2$/)
269
+ // m12486/m12567: the degraded plan covers JVM args, env vars and git.
270
+ assert.ok(Array.isArray(healthBody.degrade.jvmArgs))
271
+ assert.match(healthBody.degrade.jvmArgs.join(' '), /-Dhttps\.proxyHost=127\.0\.0\.1/)
272
+ assert.equal(healthBody.degrade.httpProxyUrl, `http://127.0.0.1:${healthBody.degrade.jvmArgs.find((a) => a.startsWith('-Dhttp.proxyPort=')).split('=')[1]}`)
273
+ assert.equal(typeof healthBody.degrade.note, 'string')
274
+ // A forced probe while stopped still must not spawn anything (nothing to judge).
275
+ const forced = await (await call(state, '/v1/proxybridge/health?force=1')).json()
276
+ assert.equal(forced.checked, false)
251
277
  // A non-tar body is answered with a reason, not a crash or a half-installed dir.
252
278
  const bad = await fetch(`${state.url}/v1/proxybridge/upload`, {
253
279
  method: 'POST',
@@ -382,17 +408,76 @@ test('/v1/dsh drops unusable `at` values and counts them (review A3-P2-6)', asyn
382
408
  assert.equal(body.dropped, 3, 'every unusable timestamp is reported, not silently pruned')
383
409
  })
384
410
 
385
- test('a sent row is upserted and a row left out is retired (no source exceptions)', async (t) => {
386
- const { home, state } = await startFixture(t)
387
- const view = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(home)}`)).json()
388
- const row = { id: 'kept-1', program: 'java', hosts: '10.0.0.*', ports: '*', enabled: true, source: 'yds' }
389
- const saved = await call(state, '/v1/proxy', {
390
- method: 'POST',
391
- body: { cwd: home, config: { socks: view.socks, listenPort: view.listenPort, rules: [row] }, revision: view.revision },
411
+ test('/v1/dsh probes a live host when no usable snapshot exists (m00186)', async (t) => {
412
+ // The daemon cannot read dsh's own API (its launch token lives in dsh's memory), so
413
+ // the plugin advertises one `instances/dsh-<pid>.json` per running host. When the
414
+ // shared document is missing or unusable, the daemon must ask that host directly
415
+ // instead of concluding "dsh is not running".
416
+ const home = makeHome('risd-dsh-probe-')
417
+ const saved = process.env.DSH_RIS_IDE_PROXY_HOME
418
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
419
+ t.after(() => {
420
+ if (saved === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
421
+ else process.env.DSH_RIS_IDE_PROXY_HOME = saved
422
+ removeHome(home)
392
423
  })
393
- assert.equal(saved.status, 200)
394
- const after = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(home)}`)).json()
395
- assert.deepEqual(after.rules.map((rule) => rule.id), ['kept-1'])
424
+ const plugin = createServer((req, res) => {
425
+ if (req.url !== '/dsh-ris-ide/workspaces') {
426
+ res.writeHead(404)
427
+ res.end()
428
+ return
429
+ }
430
+ res.writeHead(200, { 'content-type': 'application/json' })
431
+ res.end(JSON.stringify({
432
+ ok: true,
433
+ url: `http://127.0.0.1:${plugin.address().port}`,
434
+ at: new Date().toISOString(),
435
+ workspaces: [{ cwd: '/tmp/ws-probe', title: 'probed', sessionId: 's-probe', active: true }],
436
+ }))
437
+ })
438
+ await new Promise((resolve) => plugin.listen(0, '127.0.0.1', resolve))
439
+ t.after(() => new Promise((resolve) => plugin.close(resolve)))
440
+ const origin = `http://127.0.0.1:${plugin.address().port}`
441
+ mkdirSync(join(home, 'instances'), { recursive: true })
442
+ writeFileSync(join(home, 'instances', 'dsh-424242.json'), `${JSON.stringify({
443
+ pid: 424242,
444
+ url: origin,
445
+ at: new Date().toISOString(),
446
+ })}\n`)
447
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
448
+ t.after(() => daemon.stop())
449
+ const body = await (await call(daemon.state, '/v1/dsh')).json()
450
+ assert.equal(body.available, true, 'a live instance file is enough to find the host')
451
+ assert.equal(body.url, origin)
452
+ assert.deepEqual(body.windows.map((row) => [row.cwd, row.title, row.sessionId, row.source, row.active]), [
453
+ ['/tmp/ws-probe', 'probed', 's-probe', 'workspace', true],
454
+ ])
455
+ assert.equal(body.knownWorkspaces, 1)
456
+ })
457
+
458
+ test('/v1/dsh names how many workspaces it found when no origin is usable (m00186)', async (t) => {
459
+ // "dsh is not running" and "dsh reported workspaces but no origin to embed" are
460
+ // different answers: the page can only show the count in the second case.
461
+ const home = makeHome('risd-dsh-known-')
462
+ const saved = process.env.DSH_RIS_IDE_PROXY_HOME
463
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
464
+ t.after(() => {
465
+ if (saved === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
466
+ else process.env.DSH_RIS_IDE_PROXY_HOME = saved
467
+ removeHome(home)
468
+ })
469
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
470
+ t.after(() => daemon.stop())
471
+ writeFileSync(join(home, 'dsh-window.json'), `${JSON.stringify({
472
+ windows: [],
473
+ workspaces: [{ cwd: '/tmp/ws-a', title: 'alpha' }, { cwd: '/tmp/ws-b', title: 'beta' }],
474
+ at: new Date().toISOString(),
475
+ })}\n`)
476
+ const body = await (await call(daemon.state, '/v1/dsh')).json()
477
+ assert.equal(body.available, false)
478
+ assert.deepEqual(body.windows, [])
479
+ assert.equal(body.knownWorkspaces, 2)
480
+ assert.match(String(body.reason), /已发现 2 个 dsh 工作区/)
396
481
  })
397
482
 
398
483
  test('an upload whose digest is not the pinned one is rejected (review B-P0-1)', async (t) => {
@@ -461,10 +546,22 @@ test('an upload matching the pinned digest installs and verifies (review B-P0-1)
461
546
  test('a restart request hands over to a successor that waits for this pid (m11421)', () => {
462
547
  const server = readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8')
463
548
  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')
549
+ 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')
550
+ // A4-P2-6: the successor keeps the port this daemon actually bound; A4-P2-5: it
551
+ // also carries the predecessor identity so a reused pid is not waited on.
466
552
  const cli = readFileSync(new URL('../bin/risd.mjs', import.meta.url), 'utf8')
467
553
  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')
554
+ assert.match(cli, /arg === '--wait-start'/, 'the CLI understands the pid identity hint')
555
+ assert.match(cli, /await waitForPidExit\(options\.waitPid, 20000, options\.waitStart \?\? ''\)/, 'serve waits before binding the port')
469
556
  })
470
557
 
558
+ test('the daemon only prompts on a user-initiated start and files elevation state per side (review B-P0-2/B-P1-1)', async () => {
559
+ const source = readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8')
560
+ assert.match(source, /const interactive = parsed\.interactive === true/, 'the flag is opt-in: saving rules and dsh starting never ask for a password')
561
+ assert.match(source, /const redirector = await serializeBridge\(\(\) => startRedirectors\(\{ interactive \}\)\)/)
562
+ const plugin = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
563
+ assert.match(plugin, /const interactive = body\.interactive === true/, 'the plugin forwards the explicit-click flag')
564
+ const reconcile = source.indexOf('startRedirectors({ sides: missing, interactive: false })')
565
+ assert.ok(reconcile > 0, 'the reconciler starts without an interactive prompt')
566
+ assert.match(source, /linux: readElevationState\('local', \{ home \}\)/, 'the elevation file is named after the side that writes it')
567
+ })