dsh-ris-ide 1.7.3 → 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 (72) hide show
  1. package/README.md +19 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +287 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +515 -1152
  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/redirector.js +484 -35
  11. package/lib/risd/build.js +91 -0
  12. package/lib/risd/debug.js +374 -0
  13. package/lib/risd/git.js +207 -0
  14. package/lib/risd/leases.js +124 -0
  15. package/lib/risd/lifecycle.js +148 -0
  16. package/lib/risd/log.js +59 -0
  17. package/lib/risd/ping.js +94 -0
  18. package/lib/risd/programs.js +348 -0
  19. package/lib/risd/server.js +1478 -0
  20. package/lib/risd/state.js +137 -0
  21. package/lib/risd/ui.js +1705 -0
  22. package/lib/risd/view.js +79 -0
  23. package/lib/risd-client.js +282 -0
  24. package/lib/standalone/window.html +14 -16
  25. package/lib/startup.js +114 -0
  26. package/package.json +4 -1
  27. package/test/client-build.test.mjs +113 -0
  28. package/test/client-viewer.test.mjs +166 -200
  29. package/test/dsh-origin.test.mjs +140 -0
  30. package/test/dsh-window-refresh.test.mjs +100 -0
  31. package/test/harness.test.mjs +9 -0
  32. package/test/host-noloop.test.mjs +74 -0
  33. package/test/host-tail.test.mjs +21 -4
  34. package/test/host-window.test.mjs +4 -4
  35. package/test/janitor.test.mjs +29 -1
  36. package/test/lifecycle.test.mjs +26 -5
  37. package/test/merge-owners.test.mjs +155 -0
  38. package/test/proxy-restart.test.mjs +37 -0
  39. package/test/proxy-window.test.mjs +45 -0
  40. package/test/proxy.test.mjs +41 -0
  41. package/test/proxybridge-bundle.test.mjs +687 -0
  42. package/test/redirector-bundle.test.mjs +391 -0
  43. package/test/redirector.test.mjs +59 -9
  44. package/test/risd-api.test.mjs +470 -0
  45. package/test/risd-bridge-degrade.test.mjs +101 -0
  46. package/test/risd-build.test.mjs +20 -0
  47. package/test/risd-cli-home.test.mjs +50 -0
  48. package/test/risd-client.test.mjs +130 -0
  49. package/test/risd-debug.test.mjs +261 -0
  50. package/test/risd-election.test.mjs +104 -0
  51. package/test/risd-engine.test.mjs +132 -0
  52. package/test/risd-entry.test.mjs +118 -0
  53. package/test/risd-git.test.mjs +109 -0
  54. package/test/risd-handoff.test.mjs +116 -0
  55. package/test/risd-heal.test.mjs +50 -0
  56. package/test/risd-helpers.mjs +108 -0
  57. package/test/risd-host-p2.test.mjs +147 -0
  58. package/test/risd-janitor-guard.test.mjs +46 -0
  59. package/test/risd-lease.test.mjs +83 -0
  60. package/test/risd-lifecycle.test.mjs +210 -0
  61. package/test/risd-log-follow.test.mjs +227 -0
  62. package/test/risd-mode.test.mjs +161 -0
  63. package/test/risd-ping.test.mjs +99 -0
  64. package/test/risd-programs.test.mjs +169 -0
  65. package/test/risd-review-p2.test.mjs +217 -0
  66. package/test/risd-shutdown.test.mjs +97 -0
  67. package/test/risd-teardown.test.mjs +87 -0
  68. package/test/risd-tools.test.mjs +211 -0
  69. package/test/risd-ui.test.mjs +445 -0
  70. package/test/risd-write.test.mjs +170 -0
  71. package/test/startup-reconcile.test.mjs +100 -0
  72. package/test/windows.test.mjs +37 -2
package/lib/janitor.js CHANGED
@@ -15,12 +15,13 @@
15
15
  */
16
16
 
17
17
  import { spawn, spawnSync } from 'node:child_process'
18
- import { existsSync, readFileSync, unlinkSync, writeFileSync, mkdirSync } from 'node:fs'
18
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync, mkdirSync } from 'node:fs'
19
19
  import { dirname, join } from 'node:path'
20
20
  import { fileURLToPath } from 'node:url'
21
21
 
22
22
  import {
23
23
  PROXY_MARKER,
24
+ pidCommandLine,
24
25
  proxyHomeDir,
25
26
  proxyPidPath,
26
27
  proxyLogPath,
@@ -42,6 +43,8 @@ export const JANITOR_STATE_FILENAME = 'proxy-janitor.json'
42
43
 
43
44
  /** How often the watcher asks whether its owner is still alive. */
44
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
45
48
 
46
49
  /** State files that mean "something of ours is running". */
47
50
  const ENGINE_PID = () => proxyPidPath()
@@ -109,6 +112,38 @@ function removeQuietly(path) {
109
112
  }
110
113
  }
111
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
+
112
147
  /**
113
148
  * What the janitor would clean right now (also used to decide whether it is worth
114
149
  * starting one at all).
@@ -169,34 +204,53 @@ export function cleanupSideEffects({ log, detect, stopBridge, restore } = {}) {
169
204
  say(`service: ${done.service ? '已恢复启动方式' : (restored?.reason ?? '未恢复')}`)
170
205
  }
171
206
 
172
- // git: undo exactly the entries we wrote, on both sides.
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.
173
210
  const gitState = readJson(GIT_STATE())
174
211
  if (gitState !== null) {
175
212
  const key = typeof gitState.key === 'string' ? gitState.key : ''
176
213
  if (key !== '') {
177
- for (const args of [['--global', '--unset', 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 {
178
222
  try {
179
- spawnSyncGit(args)
223
+ spawnSyncGit(['--global', '--unset', key])
224
+ done.git = true
225
+ say(`git: 已清除 ${key}`)
180
226
  } catch (error) {
181
227
  say(`git: 清理失败(${error?.message ?? error})`)
182
228
  }
183
- }
184
- const winGit = windowsGitPath()
185
- if (winGit !== '') {
186
- try {
187
- runWindowsGitConfig(['--global', '--unset', key])
188
- } catch {
189
- /* Windows side is best effort: no git / no rights */
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
+ }
190
236
  }
191
237
  }
192
- done.git = true
193
- say(`git: 已清除 ${key}`)
194
238
  }
195
239
  removeQuietly(GIT_STATE())
196
240
  }
197
241
  return done
198
242
  }
199
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
+
200
254
  function spawnSyncGit(args) {
201
255
  const result = spawnSync('git', ['config', ...args], { encoding: 'utf8', timeout: 5000, windowsHide: true })
202
256
  if (result?.status !== 0 && result?.status !== undefined) {
@@ -231,13 +285,50 @@ export function armJanitor(options = {}) {
231
285
  })
232
286
  child.unref()
233
287
  const state = { pid: child.pid, owner, log: join(proxyHomeDir(), 'janitor.log') }
234
- writeFileSync(janitorStatePath(), `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
288
+ writeStateAtomic(janitorStatePath(), state)
235
289
  return { armed: true, pid: child.pid, owner }
236
290
  } catch (error) {
237
291
  return { armed: false, pid: 0, owner, reason: error?.message ?? String(error) }
238
292
  }
239
293
  }
240
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
+
241
332
  /**
242
333
  * Stop the watcher (graceful shutdown: the host cleans up itself).
243
334
  * @returns {{stopped: boolean, pid: number}} outcome.
@@ -246,7 +337,7 @@ export function disarmJanitor() {
246
337
  const state = readJson(janitorStatePath())
247
338
  const pid = Number.isInteger(state?.pid) ? state.pid : 0
248
339
  let stopped = false
249
- if (pidAlive(pid)) {
340
+ if (pidAlive(pid) && looksLikeJanitor(pid)) {
250
341
  try {
251
342
  process.kill(pid, 'SIGTERM')
252
343
  stopped = true
package/lib/proxy.js CHANGED
@@ -253,6 +253,39 @@ export function isIpv4Literal(host) {
253
253
  return typeof host === 'string' && /^\d{1,3}(\.\d{1,3}){3}$/.test(host)
254
254
  }
255
255
 
256
+ /**
257
+ * Keep a rule's per-workspace ownership map (`yds` writes it, review D-P0-1).
258
+ * Rebuilding rules from a fixed field list dropped it, so `yds stop` could no
259
+ * longer withdraw only its own rows after the config made one round trip.
260
+ *
261
+ * Lives at module scope because both `normalizeConfig` (read path) and
262
+ * `mergeConfigs` (write path) have to preserve it.
263
+ * @param raw - stored `owners` value (object of per-workspace shares).
264
+ * @returns the whitelisted map, or `undefined` when empty/unusable.
265
+ */
266
+ export function normalizeOwners(raw) {
267
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
268
+ const owners = {}
269
+ for (const [key, entry] of Object.entries(raw)) {
270
+ // Keys are opaque: a workspace path, or the driver's reserved `'<legacy>'`
271
+ // bucket for rows migrated from before owners existed. Never normalise a key
272
+ // (and never drop `'<legacy>'`) — only the driver may interpret them.
273
+ if (key === '' || entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue
274
+ const ownerProgram = typeof entry.program === 'string' ? entry.program.trim() : ''
275
+ if (ownerProgram === '') continue
276
+ const list = (value) => (Array.isArray(value) ? value.join(',') : typeof value === 'string' ? value.trim() : '')
277
+ owners[key] = {
278
+ program: ownerProgram,
279
+ hosts: list(entry.hosts),
280
+ ports: list(entry.ports),
281
+ enabled: entry.enabled === true,
282
+ shadow: entry.shadow === true,
283
+ direct: entry.direct === true,
284
+ }
285
+ }
286
+ return Object.keys(owners).length > 0 ? owners : undefined
287
+ }
288
+
256
289
  /**
257
290
  * Normalise a stored config (or `undefined`) into the shape the engine uses.
258
291
  * Unknown fields are dropped, rule rows are validated, and the four auto rows
@@ -325,9 +358,17 @@ export function normalizeConfig(raw) {
325
358
  direct: item.direct === true,
326
359
  source: typeof item.source === 'string' ? item.source : 'user',
327
360
  // Which workspace contributed this row ('' = the generated defaults, which
328
- // belong to the machine). The engine is shared, so this is the only way to
329
- // tell "my rule" from "the other workspace's rule" in the dialog.
361
+ // belong to the machine). Provenance only — the table itself is machine-wide
362
+ // and a save replaces it (m10585), so this is not scoping.
330
363
  workspace: typeof item.workspace === 'string' ? item.workspace : '',
364
+ // Which OS side a driven row is meant for. ProxyBridge matches by image name
365
+ // and `java.exe` never matches the Linux `java` (m10585), so a driver emits
366
+ // one row per side and the page labels it; '' means "either side".
367
+ side: item.side === 'local' || item.side === 'windows' ? item.side : '',
368
+ // Per-workspace shares of a merged row (driven rows only). The daemon never
369
+ // interprets it; it must survive a read→write round trip or the driver loses
370
+ // the ability to withdraw one workspace's endpoints.
371
+ owners: normalizeOwners(item.owners),
331
372
  })
332
373
  }
333
374
  // The table is MACHINE-level: ProxyBridge hooks the kernel and matches by
@@ -1012,11 +1053,19 @@ export function runEngine(config, options = {}) {
1012
1053
  for (const server of servers) {
1013
1054
  try { server.close() } catch { /* already closed */ }
1014
1055
  }
1056
+ // Shadows are listeners too (E2): leaving them bound kept the ports open for
1057
+ // the 50 ms exit grace and, in tests that reuse ports, made the next start
1058
+ // look busy. Closing them is part of "the engine stopped".
1059
+ for (const [, server] of shadowServers) {
1060
+ try { server.close() } catch { /* already closed */ }
1061
+ }
1015
1062
  setTimeout(() => process.exit(code), 50).unref?.()
1016
1063
  }
1017
1064
  process.on('SIGTERM', () => shutdown(0))
1018
1065
  process.on('SIGINT', () => shutdown(0))
1019
- log(`[${PROXY_MARKER}] ready (${servers.length} listeners)`)
1066
+ // E3: the count must include shadows, otherwise the line always says 1 and a
1067
+ // readiness check that trusts it cannot tell a half-up engine from a full one.
1068
+ log(`[${PROXY_MARKER}] ready (${servers.length + shadowServers.size} listeners)`)
1020
1069
  return new Promise(() => {})
1021
1070
  }
1022
1071
 
@@ -1133,6 +1182,10 @@ export async function startProxy(cwd, options = {}) {
1133
1182
  const existing = proxyPid(cwd)
1134
1183
  if (existing !== null) return { ok: true, pid: existing, config, alreadyRunning: true }
1135
1184
  if (config.socks.host === '' || config.socks.port === 0) return { ok: false, config, error: '上游 SOCKS 地址未配置(.env 的 socks.host / socks.port)' }
1185
+ // The child is spawned with `cwd` as its working directory: a missing directory
1186
+ // makes spawn fail with ENOENT, and (worse) the 'error' event has no listener, so
1187
+ // the daemon that asked for the start would die with an unhandled 'error'.
1188
+ if (!existsSync(cwd)) return { ok: false, config, error: `工作目录不存在:${cwd}` }
1136
1189
  const enabled = config.rules.filter((rule) => rule.enabled)
1137
1190
  if (enabled.length === 0) return { ok: false, config, error: '没有启用任何代理规则' }
1138
1191
  // The pidfile and the log live in the machine-wide home, not under the workspace:
@@ -1154,6 +1207,13 @@ export async function startProxy(cwd, options = {}) {
1154
1207
  windowsHide: true,
1155
1208
  })
1156
1209
  closeSync(out)
1210
+ // A spawn failure is delivered asynchronously as an 'error' event; without a
1211
+ // listener Node throws it, and in the daemon that means the whole daemon dies on
1212
+ // a bad workspace path. Record it in the engine log and let the readiness loop
1213
+ // below report the failure normally.
1214
+ child.on('error', (error) => {
1215
+ try { appendFileSync(logPath, `[dsh-ris-ide-proxy] spawn failed: ${error?.message ?? error}\n`) } catch { /* ignore */ }
1216
+ })
1157
1217
  child.unref()
1158
1218
  try { writeFileSync(pidPath, String(child.pid), { encoding: 'utf8', mode: 0o600 }) } catch { /* ignore */ }
1159
1219
  const ports = [config.listenPort, ...shadowTargets(config).map((target) => target.localPort)]
@@ -1435,10 +1495,18 @@ export function mergeConfigs(stored, incoming) {
1435
1495
  // Rules are machine-wide, so a patch never replaces "one workspace's rows":
1436
1496
  // it either replaces all rows of a SOURCE (what the yds bridge does, so a
1437
1497
  // removed endpoint disappears) or upserts rows by id.
1438
- if (typeof patch.replaceRulesFrom === 'string' || patch.replaceRules === true) {
1439
- const source = typeof patch.replaceRulesFrom === 'string' ? patch.replaceRulesFrom : ''
1498
+ // `replaceAllRules` is the whole-table contract the maintenance page and the daemon
1499
+ // use (m10585): the payload IS the table, so rows it does not restate are gone.
1500
+ // The source-scoped forms stay for callers that only own a slice of the file.
1501
+ if (patch.replaceAllRules === true) {
1502
+ for (const rule of mergedRules) dropped.add(rule.id)
1503
+ }
1504
+ const replaceSource = typeof patch.replaceRulesFrom === 'string'
1505
+ ? patch.replaceRulesFrom
1506
+ : (patch.replaceRules === true ? '' : null)
1507
+ if (replaceSource !== null) {
1440
1508
  for (const rule of mergedRules) {
1441
- if (rule.source === source) dropped.add(rule.id)
1509
+ if (rule.source === replaceSource) dropped.add(rule.id)
1442
1510
  }
1443
1511
  }
1444
1512
  if (Array.isArray(patch.rules)) {
@@ -1452,6 +1520,13 @@ export function mergeConfigs(stored, incoming) {
1452
1520
  ? rule.workspace
1453
1521
  : (existing?.workspace ?? patchWorkspace ?? '')
1454
1522
  const index = mergedRules.findIndex((item) => item.id === id)
1523
+ const ruleSource = typeof rule.source === 'string' ? rule.source : 'user'
1524
+ // Per-workspace owners must survive a daemon write the same way they survive
1525
+ // a read (review B-P0-2 / D-P0-1): a patch that does not restate them keeps
1526
+ // the stored map. The exception is a whole-source replacement — that is a
1527
+ // delete-and-recreate of the source's rows, so inheriting the old shares
1528
+ // would silently keep endpoints the driver has just withdrawn.
1529
+ const replacedRow = replaceSource !== null && ruleSource === replaceSource
1455
1530
  const row = {
1456
1531
  id,
1457
1532
  // Provenance label from whoever generated the row ("YonCode java"); an edit
@@ -1470,8 +1545,12 @@ export function mergeConfigs(stored, incoming) {
1470
1545
  // that does not restate it would silently re-enable the allow-list
1471
1546
  // (or silently bypass it, which is worse).
1472
1547
  direct: typeof rule.direct === 'boolean' ? rule.direct : existing?.direct === true,
1473
- source: typeof rule.source === 'string' ? rule.source : 'user',
1548
+ source: ruleSource,
1474
1549
  workspace,
1550
+ // Intrinsic to a driven row (which OS side its image name belongs to); a UI
1551
+ // edit that does not restate it keeps the stored value.
1552
+ side: rule.side === 'local' || rule.side === 'windows' ? rule.side : (existing?.side ?? ''),
1553
+ owners: normalizeOwners(rule.owners) ?? (replacedRow === true ? undefined : normalizeOwners(existing?.owners)),
1475
1554
  }
1476
1555
  if (index === -1) mergedRules.push(row)
1477
1556
  else mergedRules[index] = row