dsh-ris-ide 1.7.2 → 1.8.0

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 (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
package/lib/janitor.js ADDED
@@ -0,0 +1,377 @@
1
+ /**
2
+ * Janitor: make sure the proxy layers die with dsh, even when dsh does not.
3
+ *
4
+ * The engine is a detached child and the ProxyBridge bridge runs outside our
5
+ * process tree (its Windows side is a separate elevated process), so nothing
6
+ * stops them when dsh is killed with SIGKILL, crashes, or the terminal is closed.
7
+ * A plain `process.on('exit')` hook covers the graceful cases only.
8
+ *
9
+ * So we arm a tiny detached watcher that polls the owning dsh pid and, once it
10
+ * is gone, performs the same cleanup the exit hook does: stop the engine, stop
11
+ * the bridge, put the Windows service back, drop the git proxy entries, remove
12
+ * the pid files. It is spawned detached (own session) so it outlives dsh, and it
13
+ * only touches state that actually exists, so an idle session leaves nothing
14
+ * behind to clean.
15
+ */
16
+
17
+ import { spawn, spawnSync } from 'node:child_process'
18
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync, mkdirSync } from 'node:fs'
19
+ import { dirname, join } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ import {
23
+ PROXY_MARKER,
24
+ pidCommandLine,
25
+ proxyHomeDir,
26
+ proxyPidPath,
27
+ proxyLogPath,
28
+ readTail,
29
+ runWindowsGitConfig,
30
+ stopProxySync,
31
+ windowsGitPath,
32
+ } from './proxy.js'
33
+ import {
34
+ detectRunningRedirector,
35
+ legacyServiceStatePath,
36
+ restoreWindowsService,
37
+ serviceStatePath,
38
+ stopRedirectorSync,
39
+ } from './redirector.js'
40
+
41
+ /** File holding the janitor's own pid + the dsh pid it watches. */
42
+ export const JANITOR_STATE_FILENAME = 'proxy-janitor.json'
43
+
44
+ /** How often the watcher asks whether its owner is still alive. */
45
+ export const JANITOR_POLL_MS = 3000
46
+ /** How long a watcher waits for a handoff successor before cleaning up itself. */
47
+ export const JANITOR_HANDOFF_GRACE_MS = 12_000
48
+
49
+ /** State files that mean "something of ours is running". */
50
+ const ENGINE_PID = () => proxyPidPath()
51
+ const GIT_STATE = () => join(proxyHomeDir(), 'git-proxy.json')
52
+
53
+ /** True when a parked-service state file exists at either the canonical or old path. */
54
+ function hasServiceState() {
55
+ return existsSync(serviceStatePath()) || existsSync(legacyServiceStatePath())
56
+ }
57
+
58
+ /**
59
+ * Is a bridge running (any side, tracked or hand-started)?
60
+ *
61
+ * A test run must never touch the real machine — a Windows CI box may well have a
62
+ * real ProxyBridge_CLI running, and "clean up" would kill it. `detect` lets a test
63
+ * state the answer, and without the seam a test context answers "nothing running"
64
+ * (the machine is not this test's property).
65
+ * @param {Function} [detect] - override.
66
+ * @returns {boolean} whether bridge cleanup is due.
67
+ */
68
+ function bridgeRunning(detect) {
69
+ if (typeof detect === 'function') return detect() === true
70
+ if (process.env.NODE_TEST_CONTEXT !== undefined) return false
71
+ try {
72
+ return detectRunningRedirector().pid > 0
73
+ } catch {
74
+ return false
75
+ }
76
+ }
77
+
78
+ /** @returns {string} absolute path of the janitor state file. */
79
+ export function janitorStatePath() {
80
+ return join(proxyHomeDir(), JANITOR_STATE_FILENAME)
81
+ }
82
+
83
+ /** The script this module spawns (kept next to bin/, so installs and links agree). */
84
+ function janitorScript() {
85
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'proxy-janitor.mjs')
86
+ }
87
+
88
+ function pidAlive(pid) {
89
+ if (!Number.isInteger(pid) || pid <= 0) return false
90
+ try {
91
+ process.kill(pid, 0)
92
+ return true
93
+ } catch (error) {
94
+ return error?.code === 'EPERM'
95
+ }
96
+ }
97
+
98
+ function readJson(path) {
99
+ try {
100
+ return JSON.parse(readFileSync(path, 'utf8'))
101
+ } catch {
102
+ return null
103
+ }
104
+ }
105
+
106
+ function removeQuietly(path) {
107
+ try {
108
+ unlinkSync(path)
109
+ return true
110
+ } catch {
111
+ return false
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Replace the janitor state file atomically.
117
+ *
118
+ * A half-written file (daemon SIGKILLed mid-write) makes `readJson` return null,
119
+ * which reads as "no watcher armed": the next arm spawns a second watcher and the
120
+ * first one is never disarmed (review B-P2-9).
121
+ * @param {string} path - state file.
122
+ * @param {object} value - JSON-able state.
123
+ */
124
+ export function writeStateAtomic(path, value) {
125
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
126
+ const tmp = `${path}.${process.pid}.tmp`
127
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
128
+ renameSync(tmp, path)
129
+ }
130
+
131
+ /**
132
+ * Remove the watcher's own state file, and only when it is really ours.
133
+ *
134
+ * The watcher's cleanup runs after the owner died; by then a successor may have
135
+ * armed a new watcher and written a fresh state file. Unlinking unconditionally
136
+ * would hide that live watcher from every later `armJanitor`/`disarmJanitor`
137
+ * (review B-P2-9).
138
+ * @param {number} pid - the caller's watcher pid.
139
+ * @returns {boolean} true when the file was ours and is now gone.
140
+ */
141
+ export function removeOwnJanitorState(pid) {
142
+ const state = readJson(janitorStatePath())
143
+ if (state === null || Number(state.pid) !== Number(pid)) return false
144
+ return removeQuietly(janitorStatePath())
145
+ }
146
+
147
+ /**
148
+ * What the janitor would clean right now (also used to decide whether it is worth
149
+ * starting one at all).
150
+ * @param {{detect?: Function}} [options] - test seam for the bridge probe.
151
+ * @returns {{engine: boolean, bridge: boolean, service: boolean, git: boolean}} per-layer state.
152
+ */
153
+ export function pendingSideEffects(options = {}) {
154
+ return {
155
+ engine: existsSync(ENGINE_PID()),
156
+ // Detection, not just our pid file: a hand-started bridge keeps intercepting
157
+ // after its record is gone, so it must still be cleaned up (B5).
158
+ bridge: bridgeRunning(options.detect),
159
+ service: hasServiceState(),
160
+ git: existsSync(GIT_STATE()),
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Stop everything we may have started, the same way the exit hook does.
166
+ *
167
+ * Safe to call when nothing runs: every step is guarded by its own state file.
168
+ * @param {{log?: Function, detect?: Function, stopBridge?: Function, restore?: Function}} [options] - logger and test seams.
169
+ * @returns {{engine: boolean, bridge: boolean, service: boolean, git: boolean, log: string[]}}
170
+ */
171
+ export function cleanupSideEffects({ log, detect, stopBridge, restore } = {}) {
172
+ const done = { engine: false, bridge: false, service: false, git: false, log: [] }
173
+ const say = (line) => {
174
+ done.log.push(line)
175
+ log?.(line)
176
+ }
177
+ const restoreService = typeof restore === 'function' ? restore : restoreWindowsService
178
+ const stopBridgeNow = typeof stopBridge === 'function' ? stopBridge : stopRedirectorSync
179
+
180
+ // Engine: pid file + identity check happen inside stopProxySync.
181
+ if (existsSync(ENGINE_PID())) {
182
+ done.engine = stopProxySync() === true
183
+ say(`engine: ${done.engine ? '已停止' : '未运行/未停止'}`)
184
+ }
185
+
186
+ // Bridge (ProxyBridge CLI on either side) + the Windows service we parked.
187
+ const bridgeDue = bridgeRunning(detect)
188
+ const serviceDue = hasServiceState()
189
+ if (bridgeDue) {
190
+ try {
191
+ const stopped = stopBridgeNow()
192
+ done.bridge = stopped?.stopped === true
193
+ say(`bridge: ${done.bridge ? `已停止 pid=${stopped.pid}` : `未停止(${stopped?.reason ?? '未知原因'})`}`)
194
+ } catch (error) {
195
+ say(`bridge: 停止失败(${error?.message ?? error})`)
196
+ }
197
+ }
198
+ if (serviceDue) {
199
+ const restored = restoreService()
200
+ // restoreWindowsService answers `{restored:true}` — the old check read `.ok`,
201
+ // which never exists, so a recovered service was reported as failed (or worse,
202
+ // a failed one as fine when both were undefined).
203
+ done.service = restored?.restored === true
204
+ say(`service: ${done.service ? '已恢复启动方式' : (restored?.reason ?? '未恢复')}`)
205
+ }
206
+
207
+ // git: undo exactly the entries we wrote, on both sides. E7 (review B-P0-1): the
208
+ // value recorded at write time must still be the current one — a user who set
209
+ // their own scoped proxy after us keeps it; only our stale bookkeeping is dropped.
210
+ const gitState = readJson(GIT_STATE())
211
+ if (gitState !== null) {
212
+ const key = typeof gitState.key === 'string' ? gitState.key : ''
213
+ if (key !== '') {
214
+ const recorded = typeof gitState.value === 'string' ? gitState.value : ''
215
+ const current = readGitValue(key)
216
+ const ours = current !== '' && (recorded !== '' ? current === recorded : current.startsWith('socks5h://'))
217
+ if (current === '') {
218
+ say(`git: ${key} 已不在(无需清理)`)
219
+ } else if (ours !== true) {
220
+ say(`git: ${key} 的当前值不是本工具写入的,保留`)
221
+ } else {
222
+ try {
223
+ spawnSyncGit(['--global', '--unset', key])
224
+ done.git = true
225
+ say(`git: 已清除 ${key}`)
226
+ } catch (error) {
227
+ say(`git: 清理失败(${error?.message ?? error})`)
228
+ }
229
+ const winGit = windowsGitPath()
230
+ if (winGit !== '') {
231
+ try {
232
+ runWindowsGitConfig(['--global', '--unset', key])
233
+ } catch {
234
+ /* Windows side is best effort: no git / no rights */
235
+ }
236
+ }
237
+ }
238
+ }
239
+ removeQuietly(GIT_STATE())
240
+ }
241
+ return done
242
+ }
243
+
244
+ /** Read one `git config --global --get` value synchronously ('' when unset). */
245
+ function readGitValue(key) {
246
+ try {
247
+ const out = spawnSync('git', ['config', '--global', '--get', key], { encoding: 'utf8', timeout: 5000, windowsHide: true })
248
+ return out?.status === 0 && typeof out.stdout === 'string' ? out.stdout.trim() : ''
249
+ } catch {
250
+ return ''
251
+ }
252
+ }
253
+
254
+ function spawnSyncGit(args) {
255
+ const result = spawnSync('git', ['config', ...args], { encoding: 'utf8', timeout: 5000, windowsHide: true })
256
+ if (result?.status !== 0 && result?.status !== undefined) {
257
+ throw new Error((result.stderr ?? '').trim().slice(0, 160) || `git config ${args.join(' ')} 失败`)
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Arm (or re-arm) the watcher for this dsh process.
263
+ *
264
+ * Idempotent per owner: an existing watcher whose owner is the same process is
265
+ * left alone, one watching a dead process is replaced.
266
+ * @param {{ownerPid?: number}} [options] - defaults to the current process.
267
+ * @returns {{armed: boolean, pid: number, owner: number, reason?: string}} state.
268
+ */
269
+ export function armJanitor(options = {}) {
270
+ const owner = Number.isInteger(options.ownerPid) ? options.ownerPid : process.pid
271
+ const existing = janitorStatus()
272
+ if (existing.running === true && existing.owner === owner) {
273
+ return { armed: true, pid: existing.pid, owner, reason: '已在运行' }
274
+ }
275
+ if (existing.running === true) disarmJanitor()
276
+
277
+ const script = janitorScript()
278
+ if (!existsSync(script)) return { armed: false, pid: 0, owner, reason: `找不到 ${script}` }
279
+ try {
280
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
281
+ const child = spawn(process.execPath, [script, '--owner', String(owner), '--home', proxyHomeDir()], {
282
+ detached: true,
283
+ stdio: 'ignore',
284
+ windowsHide: true,
285
+ })
286
+ child.unref()
287
+ const state = { pid: child.pid, owner, log: join(proxyHomeDir(), 'janitor.log') }
288
+ writeStateAtomic(janitorStatePath(), state)
289
+ return { armed: true, pid: child.pid, owner }
290
+ } catch (error) {
291
+ return { armed: false, pid: 0, owner, reason: error?.message ?? String(error) }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Tell the armed watcher that its owner is handing the network to a successor
297
+ * (Phase 1b P6). The watcher must not treat the owner's exit as "the machine is
298
+ * free": it waits `JANITOR_HANDOFF_GRACE_MS` for the successor to arm itself, and
299
+ * only cleans up if nobody claims the network in time.
300
+ *
301
+ * Synchronous on purpose: it runs inside the last step of the predecessor's stop,
302
+ * where an async write could lose the race with `process.exit`.
303
+ * @param {string} [at] - ISO timestamp; defaults to now.
304
+ * @returns {{marked: boolean, reason?: string}} outcome.
305
+ */
306
+ export function markJanitorHandoff(at = new Date().toISOString()) {
307
+ const state = readJson(janitorStatePath())
308
+ if (state === null) return { marked: false, reason: 'no-janitor' }
309
+ try {
310
+ writeStateAtomic(janitorStatePath(), Object.assign({}, state, { handoffAt: at }))
311
+ return { marked: true }
312
+ } catch (error) {
313
+ return { marked: false, reason: error?.message ?? String(error) }
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Whether a pid really is one of our watchers.
319
+ *
320
+ * `pidAlive()` alone is not an identity check: after a reboot or a busy machine
321
+ * the watcher pid can belong to an unrelated process, and SIGTERMing it because a
322
+ * stale state file names that number is exactly the kind of collateral damage a
323
+ * cleanup path must not do (review B-P2-9). Unreadable command lines answer
324
+ * "no": the orphan watcher then exits by itself on the next poll.
325
+ * @param {number} pid - candidate watcher pid.
326
+ * @returns {boolean} true when the command line carries the watcher script name.
327
+ */
328
+ function looksLikeJanitor(pid) {
329
+ return pidCommandLine(pid).includes('proxy-janitor')
330
+ }
331
+
332
+ /**
333
+ * Stop the watcher (graceful shutdown: the host cleans up itself).
334
+ * @returns {{stopped: boolean, pid: number}} outcome.
335
+ */
336
+ export function disarmJanitor() {
337
+ const state = readJson(janitorStatePath())
338
+ const pid = Number.isInteger(state?.pid) ? state.pid : 0
339
+ let stopped = false
340
+ if (pidAlive(pid) && looksLikeJanitor(pid)) {
341
+ try {
342
+ process.kill(pid, 'SIGTERM')
343
+ stopped = true
344
+ } catch {
345
+ stopped = false
346
+ }
347
+ }
348
+ removeQuietly(janitorStatePath())
349
+ return { stopped, pid }
350
+ }
351
+
352
+ /**
353
+ * @returns {{running: boolean, pid: number, owner: number, log: string}} watcher state.
354
+ */
355
+ export function janitorStatus() {
356
+ const state = readJson(janitorStatePath())
357
+ const pid = Number.isInteger(state?.pid) ? state.pid : 0
358
+ const owner = Number.isInteger(state?.owner) ? state.owner : 0
359
+ const running = pid > 0 && pidAlive(pid)
360
+ return { running, pid, owner, log: typeof state?.log === 'string' ? state.log : '' }
361
+ }
362
+
363
+ /** One line for the dialog / `yds proxy status`. */
364
+ export function describeJanitor() {
365
+ const status = janitorStatus()
366
+ if (status.running !== true) return '守护进程: 未运行'
367
+ return `守护进程: 运行中(pid ${status.pid},监视 dsh ${status.owner})`
368
+ }
369
+
370
+ /** Exported for the watching script: tail of the last engine log, for diagnostics. */
371
+ export function janitorDiagnostics() {
372
+ return {
373
+ marker: PROXY_MARKER,
374
+ engineLog: readTail(proxyLogPath(), 2048),
375
+ state: janitorStatus(),
376
+ }
377
+ }