dsh-ris-ide 1.8.1 → 1.8.3

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 (50) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +569 -98
  3. package/lib/debug/vendor/README.md +14 -0
  4. package/lib/debug/vendor/jdwp/client.js +9 -4
  5. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  6. package/lib/index.js +963 -64
  7. package/lib/redirector.js +76 -4
  8. package/lib/risd/lifecycle.js +54 -10
  9. package/lib/risd/ping.js +136 -17
  10. package/lib/risd/server.js +424 -22
  11. package/lib/risd/ui.js +218 -129
  12. package/lib/risd-client.js +4 -1
  13. package/lib/startup.js +27 -7
  14. package/package.json +2 -2
  15. package/test/client-viewer.test.mjs +268 -93
  16. package/test/clipboard.test.mjs +259 -0
  17. package/test/debug-engine.test.mjs +3 -1
  18. package/test/dsh-origin.test.mjs +4 -11
  19. package/test/dsh-window-refresh.test.mjs +166 -1
  20. package/test/harness.test.mjs +1 -1
  21. package/test/helpers/cmd.mjs +29 -0
  22. package/test/helpers/tgz.mjs +71 -0
  23. package/test/host-search.test.mjs +18 -11
  24. package/test/host-tail.test.mjs +190 -25
  25. package/test/proxy-route.test.mjs +61 -0
  26. package/test/proxy-window.test.mjs +5 -0
  27. package/test/proxy.test.mjs +40 -11
  28. package/test/proxybridge-bundle.test.mjs +1 -59
  29. package/test/redirector-bundle.test.mjs +21 -67
  30. package/test/redirector.test.mjs +71 -4
  31. package/test/risd-api.test.mjs +83 -29
  32. package/test/risd-bridge-degrade.test.mjs +3 -29
  33. package/test/risd-cli-home.test.mjs +41 -4
  34. package/test/risd-engine.test.mjs +13 -50
  35. package/test/risd-entry.test.mjs +0 -37
  36. package/test/risd-follow-start.test.mjs +102 -0
  37. package/test/risd-git.test.mjs +7 -5
  38. package/test/risd-handoff.test.mjs +6 -50
  39. package/test/risd-helpers.mjs +150 -3
  40. package/test/risd-host-p2.test.mjs +2 -30
  41. package/test/risd-lifecycle.test.mjs +203 -33
  42. package/test/risd-ping.test.mjs +77 -1
  43. package/test/risd-programs.test.mjs +4 -34
  44. package/test/risd-review-p2.test.mjs +0 -13
  45. package/test/risd-shutdown.test.mjs +5 -38
  46. package/test/risd-teardown.test.mjs +8 -27
  47. package/test/risd-ui.test.mjs +205 -14
  48. package/test/risd-write.test.mjs +2 -1
  49. package/test/startup-reconcile.test.mjs +44 -8
  50. package/test/proxy-restart.test.mjs +0 -39
@@ -5,12 +5,14 @@
5
5
  * Every test gets its own `DSH_RIS_IDE_PROXY_HOME`-style home under the OS temp
6
6
  * dir, so the machine-level `~/.dsh-ris-ide` is never read or written.
7
7
  */
8
- import { mkdtempSync, rmSync } from 'node:fs'
8
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
9
  import { tmpdir } from 'node:os'
10
10
  import { join } from 'node:path'
11
11
  import { spawn } from 'node:child_process'
12
+ import { request } from 'node:http'
13
+ import { Readable } from 'node:stream'
12
14
  import { fileURLToPath } from 'node:url'
13
- import { readRisdState } from '../lib/risd/state.js'
15
+ import { readRisdState, RISD_API_VERSION } from '../lib/risd/state.js'
14
16
 
15
17
  export const RISD_BIN = fileURLToPath(new URL('../bin/risd.mjs', import.meta.url))
16
18
 
@@ -56,6 +58,11 @@ export async function startRisdProcess({ home = makeHome(), port = 0, env = {} }
56
58
  HOME: home,
57
59
  USERPROFILE: home,
58
60
  GIT_CONFIG_GLOBAL: join(home, '.gitconfig'),
61
+ // Answer the two PowerShell probes with "nothing is running" (see
62
+ // `probesStubbed` in lib/redirector.js): a cold `Get-Process` costs ~8 s on WSL
63
+ // and the answer used to be whatever bridge was up on the developer's desktop,
64
+ // so the save paths in these tests were slow AND order-dependent.
65
+ DSH_RIS_IDE_STUB_PROBES: '1',
59
66
  }
60
67
  const child = spawn(process.execPath, [RISD_BIN, 'serve', '--home', home, '--port', String(port)], {
61
68
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -67,7 +74,12 @@ export async function startRisdProcess({ home = makeHome(), port = 0, env = {} }
67
74
  const deadline = Date.now() + 10_000
68
75
  while (Date.now() < deadline) {
69
76
  const state = readRisdState(home)
70
- if (state !== null) {
77
+ // A handoff deliberately leaves the PREDECESSOR's note in place (same home,
78
+ // same port, its token) until the successor rewrites it. Returning that note
79
+ // hands the caller a dead daemon's token: health may answer (it is
80
+ // unauthenticated) while every authenticated route replies 401 — a flake that
81
+ // only shows up when the successor is slow to write its own note.
82
+ if (state !== null && Number(state.pid) === child.pid) {
71
83
  const probe = await health(state.port)
72
84
  if (probe?.ok === true) {
73
85
  return { child, home, state, lines, stop: () => stopRisdProcess(child) }
@@ -106,3 +118,138 @@ export function runRisdCli(args, { env = {} } = {}) {
106
118
  }
107
119
 
108
120
  export { health }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Engine fixtures (risd-engine / risd-handoff / risd-teardown had three copies).
124
+ // ---------------------------------------------------------------------------
125
+
126
+ /** A random high port, so parallel test files do not fight over the engine fixtures. */
127
+ export function pickPort() {
128
+ return 20000 + Math.floor(Math.random() * 20000)
129
+ }
130
+
131
+ /**
132
+ * Write the machine-level `proxy.json` an engine test starts from: one enabled java
133
+ * rule and a dead SOCKS upstream. `workspace` is the row's owner (default: the home).
134
+ */
135
+ export function writeEngineFixture(home, port, { workspace = home } = {}) {
136
+ writeFileSync(join(home, 'proxy.json'), JSON.stringify({
137
+ socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
138
+ listenPort: port,
139
+ rules: [{
140
+ id: 'rule-1',
141
+ program: 'java',
142
+ hosts: ['127.0.0.1'],
143
+ ports: ['443'],
144
+ enabled: true,
145
+ shadow: false,
146
+ source: 'user',
147
+ workspace,
148
+ }],
149
+ }, null, 2))
150
+ }
151
+
152
+ /** Authorization headers for a daemon started by `startRisdProcess`. */
153
+ export function risdHeaders(state) {
154
+ return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
155
+ }
156
+
157
+ /**
158
+ * Poll `fn` until it returns true. 15 s by default: a teardown is 300 ms debounce +
159
+ * the engine's 5 s grace + bridge/git attempts, which exceeds 8 s on a loaded machine.
160
+ */
161
+ export async function waitFor(fn, timeoutMs = 15000, stepMs = 120) {
162
+ const deadline = Date.now() + timeoutMs
163
+ while (Date.now() < deadline) {
164
+ if (await fn()) return true
165
+ await sleep(stepMs)
166
+ }
167
+ return false
168
+ }
169
+
170
+ /** `kill(0)`: is the process still there? */
171
+ export function pidAlive(pid) {
172
+ if (!Number.isInteger(pid) || pid <= 0) return false
173
+ try {
174
+ process.kill(pid, 0)
175
+ return true
176
+ } catch {
177
+ return false
178
+ }
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Fake bridge (risd-bridge-degrade / risd-host-p2 had two copies).
183
+ // ---------------------------------------------------------------------------
184
+
185
+ /** Minimal `ServerResponse` stand-in for the `serveProxy`/`serveProxyAction` tests. */
186
+ export function fakeRes() {
187
+ return {
188
+ status: 0,
189
+ chunks: [],
190
+ writeHead(status) { this.status = status },
191
+ write(chunk) { this.chunks.push(String(chunk)); return true },
192
+ end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
193
+ json() { return JSON.parse(this.chunks.join('')) },
194
+ }
195
+ }
196
+
197
+ /** Minimal `IncomingMessage` (a Readable) for the same tests. */
198
+ export function fakeReq(method, url, body) {
199
+ const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
200
+ const req = Readable.from(chunks)
201
+ req.method = method
202
+ req.url = url
203
+ req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
204
+ return req
205
+ }
206
+
207
+ /**
208
+ * The in-memory bridge `lib/index.js` hands to `__test.setRisdBridge`; `url: null`
209
+ * means "the pointer was already dropped" (degraded, no daemon).
210
+ */
211
+ export function risdBridge({ url = null, port = 9, token = 'token-x', leaseId = 'lease-x', degraded = false, warnedAt = 0, lastProbeAt = Date.now() } = {}) {
212
+ return {
213
+ mode: 'auto',
214
+ state: url === null ? null : { url, token, apiVersion: RISD_API_VERSION, port },
215
+ leaseId,
216
+ pending: null,
217
+ warnedAt,
218
+ degraded,
219
+ lastProbeAt,
220
+ }
221
+ }
222
+
223
+ // ---------------------------------------------------------------------------
224
+ // JSON client (risd-programs / risd-shutdown had two copies of `api`).
225
+ // ---------------------------------------------------------------------------
226
+
227
+ /** One JSON request against a running daemon; transport errors land as `{status: 0}`. */
228
+ export function api(state, path, { method = 'GET', body } = {}) {
229
+ return new Promise((resolve) => {
230
+ const payload = body === undefined ? '' : JSON.stringify(body)
231
+ const req = request({
232
+ host: '127.0.0.1',
233
+ port: state.port,
234
+ path,
235
+ method,
236
+ timeout: 8000,
237
+ headers: Object.assign(
238
+ { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
239
+ payload === '' ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
240
+ ),
241
+ }, (res) => {
242
+ let text = ''
243
+ res.setEncoding('utf8')
244
+ res.on('data', (chunk) => { text += chunk })
245
+ res.on('end', () => {
246
+ let parsed = null
247
+ try { parsed = JSON.parse(text) } catch { parsed = null }
248
+ resolve({ status: res.statusCode, body: parsed })
249
+ })
250
+ })
251
+ req.on('error', (error) => resolve({ status: 0, body: { error: String(error?.message) } }))
252
+ if (payload !== '') req.write(payload)
253
+ req.end()
254
+ })
255
+ }
@@ -12,8 +12,8 @@ import { createServer } from 'node:http'
12
12
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
13
13
  import { tmpdir } from 'node:os'
14
14
  import { join } from 'node:path'
15
- import { Readable } from 'node:stream'
16
15
  import test from 'node:test'
16
+ import { fakeReq, fakeRes, risdBridge } from './risd-helpers.mjs'
17
17
 
18
18
  const home = mkdtempSync(join(tmpdir(), 'risd-host-p2-'))
19
19
  const workspace = mkdtempSync(join(tmpdir(), 'risd-host-p2-ws-'))
@@ -22,26 +22,6 @@ process.env.DSH_RIS_IDE_PROXY_HOME = home
22
22
  const { __test } = await import('../lib/index.js')
23
23
  const { RISD_API_VERSION } = await import('../lib/risd/state.js')
24
24
 
25
- function fakeRes() {
26
- return {
27
- status: 0,
28
- chunks: [],
29
- writeHead(status) { this.status = status },
30
- write(chunk) { this.chunks.push(String(chunk)); return true },
31
- end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
32
- json() { return JSON.parse(this.chunks.join('')) },
33
- }
34
- }
35
-
36
- function fakeReq(method, url, body) {
37
- const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
38
- const req = Readable.from(chunks)
39
- req.method = method
40
- req.url = url
41
- req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
42
- return req
43
- }
44
-
45
25
  /** A fake daemon that answers /v1/health and hands every other request to `reply`. */
46
26
  async function fakeDaemon(reply) {
47
27
  const server = createServer((req, res) => {
@@ -69,15 +49,7 @@ async function stopServer(server) {
69
49
  }
70
50
 
71
51
  function setBridge(url, port) {
72
- __test.setRisdBridge({
73
- mode: 'auto',
74
- state: { url, token: 'token-x', apiVersion: RISD_API_VERSION, port },
75
- leaseId: 'lease-x',
76
- pending: null,
77
- warnedAt: 0,
78
- degraded: false,
79
- lastProbeAt: Date.now(),
80
- })
52
+ __test.setRisdBridge(risdBridge({ url, port }))
81
53
  }
82
54
 
83
55
  const ctx = { sessions: { get: () => ({ header: { cwd: workspace } }) } }
@@ -1,10 +1,12 @@
1
- // Lifecycle settings: which resources follow dsh, and which follow the daemon.
2
- // Defaults must preserve the behaviour that existed before the setting (proxy
3
- // follows dsh, everything else stops with the daemon), and a broken policy file
4
- // must never take the daemon down.
1
+ // Lifecycle settings: each resource has a start half and a stop half for "follows
2
+ // dsh" (m03397). Defaults must preserve the behaviour that existed before the
3
+ // setting (proxy follows dsh, everything else stops with the daemon), a legacy
4
+ // `followDsh` file must migrate to both halves, and a broken policy file must never
5
+ // take the daemon down.
5
6
  import assert from 'node:assert/strict'
6
7
  import test from 'node:test'
7
- import { chmodSync, existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
8
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
8
10
  import { join } from 'node:path'
9
11
 
10
12
  import {
@@ -15,23 +17,88 @@ import {
15
17
  readLifecycle,
16
18
  writeLifecycle,
17
19
  } from '../lib/risd/lifecycle.js'
18
- import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
20
+ import { api, makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
21
+ import { HAS_BASH, skipWithout } from './helpers/cmd.mjs'
19
22
 
20
23
  test('defaults match the behaviour from before the setting existed', () => {
21
24
  const { value, errors } = normalizeLifecycle({})
22
25
  assert.deepEqual(errors, [])
23
26
  assert.deepEqual(value, LIFECYCLE_DEFAULTS)
24
- assert.equal(value.daemon.followDsh, true)
25
- assert.equal(value.proxy.followDsh, true)
26
- assert.equal(value.programs.followDsh, false, 'closing the last dsh must not stop JVMs by default')
27
- assert.equal(value.debug.followDsh, false)
27
+ assert.equal(value.daemon.startWithDsh, true, 'the daemon start half is forced on')
28
+ assert.equal(value.daemon.stopWithDsh, true, 'an idle daemon retires by default')
29
+ assert.equal(value.proxy.startWithDsh, true, 'the proxy follows dsh out of the box')
30
+ assert.equal(value.proxy.stopWithDsh, true)
31
+ assert.equal(value.programs.startWithDsh, false, 'opening dsh must not restore JVMs by default')
32
+ assert.equal(value.programs.stopWithDsh, false, 'closing the last dsh must not stop JVMs by default')
33
+ assert.equal(value.debug.stopWithDsh, false)
34
+ assert.equal('startWithDsh' in value.debug, false, 'a debug session has nothing to auto-start')
35
+ })
36
+
37
+ test('a legacy followDsh file migrates to both halves, and typos are rejected', () => {
38
+ // Files written before m03397 carry one knob per resource. Both halves took it, so
39
+ // reading the old file must keep the old behaviour exactly.
40
+ const legacy = normalizeLifecycle({ daemon: { followDsh: false }, proxy: { followDsh: false }, programs: { followDsh: true }, debug: { followDsh: true } })
41
+ assert.deepEqual(legacy.errors, [])
42
+ assert.equal(legacy.value.daemon.startWithDsh, true, 'the daemon start half is forced on')
43
+ assert.equal(legacy.value.daemon.stopWithDsh, false)
44
+ assert.equal(legacy.value.proxy.startWithDsh, false)
45
+ assert.equal(legacy.value.proxy.stopWithDsh, false)
46
+ assert.equal(legacy.value.programs.startWithDsh, true)
47
+ assert.equal(legacy.value.programs.stopWithDsh, true)
48
+ assert.equal(legacy.value.debug.stopWithDsh, true, 'debug only has a stop half')
49
+ assert.equal('startWithDsh' in legacy.value.debug, false)
50
+
51
+ // An explicit half in the same payload wins over the legacy knob (a caller can
52
+ // move one half without rewriting the file).
53
+ const mixed = normalizeLifecycle({ proxy: { followDsh: false, startWithDsh: true } })
54
+ assert.deepEqual(mixed.errors, [])
55
+ assert.equal(mixed.value.proxy.startWithDsh, true)
56
+ assert.equal(mixed.value.proxy.stopWithDsh, false, 'the legacy value still fills the other half')
57
+
58
+ const bad = normalizeLifecycle({ proxy: { stopWithDsh: 'yes' } })
59
+ assert.equal(bad.changed, false)
60
+ assert.match(bad.errors.join(';'), /proxy\.stopWithDsh 必须是 true\/false/)
61
+
62
+ // A partial save over what is in force keeps the value.
63
+ const current = normalizeLifecycle({ proxy: { followDsh: false } }).value
64
+ const merged = normalizeLifecycle(mergeLifecycle(current, { programs: { stopWithDsh: true } })).value
65
+ assert.equal(merged.proxy.stopWithDsh, false)
66
+ assert.equal(merged.programs.stopWithDsh, true)
67
+ assert.equal(merged.programs.startWithDsh, false)
68
+ })
69
+
70
+ test('the halves a resource cannot have are rejected, not silently dropped', () => {
71
+ // The daemon's start half is forced (a plugin must be able to ask for a daemon).
72
+ const forcedStart = normalizeLifecycle({ daemon: { startWithDsh: false } })
73
+ assert.equal(forcedStart.changed, false)
74
+ assert.match(forcedStart.errors.join(';'), /daemon\.startWithDsh 不可配置/)
75
+
76
+ // A debug session belongs to a page: there is no auto-start to switch.
77
+ const debugStart = normalizeLifecycle({ debug: { startWithDsh: true } })
78
+ assert.equal(debugStart.changed, false)
79
+ assert.match(debugStart.errors.join(';'), /debug\.startWithDsh 不是可配置项(只能配置 stopWithDsh)/)
80
+
81
+ // Following the daemon stays forced (m07741).
82
+ const forced = normalizeLifecycle({ proxy: { startWithDsh: true, followDaemon: false }, programs: { followDaemon: false } })
83
+ assert.equal(forced.changed, false)
84
+ assert.equal(forced.errors.length, 2)
85
+ assert.match(forced.errors.join(';'), /proxy\.followDaemon 不再支持:所有资源强制跟随 daemon/)
86
+ assert.equal('followDaemon' in forced.value.proxy, false)
87
+ assert.equal('followDaemon' in forced.value.programs, false)
88
+
89
+ const bad = normalizeLifecycle({ proxy: { startWithDsh: 'yes' }, debug: 'nope' })
90
+ assert.equal(bad.changed, false)
91
+ assert.equal(bad.errors.length, 2)
92
+ assert.match(bad.errors.join(';'), /proxy\.startWithDsh 必须是 true\/false/)
93
+ assert.match(bad.errors.join(';'), /debug 必须是对象/)
28
94
  })
29
95
 
30
96
  test('partial input keeps the untouched defaults and rejects non-booleans', () => {
31
- const partial = normalizeLifecycle({ programs: { followDsh: true } })
97
+ const partial = normalizeLifecycle({ programs: { stopWithDsh: true } })
32
98
  assert.deepEqual(partial.errors, [])
33
- assert.equal(partial.value.programs.followDsh, true)
34
- assert.equal(partial.value.proxy.followDsh, true)
99
+ assert.equal(partial.value.programs.stopWithDsh, true)
100
+ assert.equal(partial.value.programs.startWithDsh, false, 'the other half keeps its default')
101
+ assert.equal(partial.value.proxy.stopWithDsh, true)
35
102
 
36
103
  // Following the daemon is forced (m07741): the old key is rejected, not stored.
37
104
  const forced = normalizeLifecycle({ proxy: { followDsh: true, followDaemon: false }, programs: { followDaemon: false } })
@@ -51,21 +118,22 @@ test('partial input keeps the untouched defaults and rejects non-booleans', () =
51
118
  test('a partial save merges over the policy in force', () => {
52
119
  // POST /v1/config used to normalize the body alone, so saving one checkbox reset
53
120
  // the other three resources to their defaults (review A2-P2-1).
54
- const current = normalizeLifecycle({ proxy: { followDsh: false }, debug: { followDsh: true } }).value
55
- const merged = normalizeLifecycle(mergeLifecycle(current, { programs: { followDsh: true } })).value
56
- assert.equal(merged.programs.followDsh, true, 'the submitted resource changed')
57
- assert.equal(merged.proxy.followDsh, false, 'the untouched resource kept its value')
58
- assert.equal(merged.debug.followDsh, true, 'the untouched resource kept its value')
59
- assert.equal(merged.daemon.followDsh, true)
121
+ const current = normalizeLifecycle({ proxy: { stopWithDsh: false }, debug: { stopWithDsh: true } }).value
122
+ const merged = normalizeLifecycle(mergeLifecycle(current, { programs: { startWithDsh: true } })).value
123
+ assert.equal(merged.programs.startWithDsh, true, 'the submitted half changed')
124
+ assert.equal(merged.programs.stopWithDsh, false, 'the sibling half kept its default')
125
+ assert.equal(merged.proxy.stopWithDsh, false, 'the untouched resource kept its value')
126
+ assert.equal(merged.debug.stopWithDsh, true, 'the untouched resource kept its value')
127
+ assert.equal(merged.daemon.stopWithDsh, true)
60
128
  })
61
129
 
62
130
  test('unknown resources and keys are rejected instead of silently saved', () => {
63
- const unknownResource = normalizeLifecycle({ engine: { followDsh: true } })
131
+ const unknownResource = normalizeLifecycle({ engine: { startWithDsh: true } })
64
132
  assert.equal(unknownResource.changed, false)
65
133
  assert.match(unknownResource.errors.join(';'), /engine 不是生命周期资源/)
66
134
  assert.equal('engine' in unknownResource.value, false)
67
135
 
68
- const unknownKey = normalizeLifecycle({ proxy: { followDsh: true, keepAlive: true } })
136
+ const unknownKey = normalizeLifecycle({ proxy: { startWithDsh: true, keepAlive: true } })
69
137
  assert.equal(unknownKey.changed, false)
70
138
  assert.match(unknownKey.errors.join(';'), /proxy\.keepAlive 不是可配置项/)
71
139
  })
@@ -88,16 +156,18 @@ test('a missing file reads as defaults; a broken file still yields defaults', ()
88
156
  test('write persists atomically with 0600 and reads back', () => {
89
157
  const home = makeHome('risd-life-')
90
158
  try {
91
- const written = writeLifecycle(home, { programs: { followDsh: true } })
159
+ const written = writeLifecycle(home, { programs: { startWithDsh: true } })
92
160
  assert.deepEqual(written.errors, [])
93
- assert.equal(written.value.programs.followDsh, true)
161
+ assert.equal(written.value.programs.startWithDsh, true)
162
+ assert.equal(written.value.programs.stopWithDsh, false)
94
163
  const path = lifecyclePath(home)
95
164
  assert.ok(existsSync(path))
96
165
  assert.equal(statSync(path).mode & 0o777, 0o600)
97
166
  const parsed = JSON.parse(readFileSync(path, 'utf8'))
98
- assert.equal(parsed.programs.followDsh, true)
167
+ assert.equal(parsed.programs.startWithDsh, true)
99
168
  const again = readLifecycle(home)
100
- assert.equal(again.value.proxy.followDsh, true)
169
+ assert.equal(again.value.proxy.startWithDsh, true)
170
+ assert.equal(again.value.proxy.stopWithDsh, true)
101
171
  } finally { removeHome(home) }
102
172
  })
103
173
 
@@ -114,26 +184,29 @@ test('POST /v1/config stores the policy and GET /v1/config returns it', async ()
114
184
  const saved = await fetch(`http://127.0.0.1:${port}/v1/config`, {
115
185
  method: 'POST',
116
186
  headers,
117
- body: JSON.stringify({ lifecycle: { daemon: { followDsh: false }, programs: { followDsh: true } } }),
187
+ body: JSON.stringify({ lifecycle: { daemon: { stopWithDsh: false }, programs: { stopWithDsh: true, startWithDsh: true } } }),
118
188
  })
119
189
  assert.equal(saved.status, 200)
120
190
  const savedBody = await saved.json()
121
191
  assert.equal(savedBody.ok, true)
122
- assert.equal(savedBody.lifecycle.daemon.followDsh, false)
123
- assert.equal(savedBody.lifecycle.programs.followDsh, true)
192
+ assert.equal(savedBody.lifecycle.daemon.stopWithDsh, false)
193
+ assert.equal(savedBody.lifecycle.daemon.startWithDsh, true, 'the forced half stays on')
194
+ assert.equal(savedBody.lifecycle.programs.stopWithDsh, true)
195
+ assert.equal(savedBody.lifecycle.programs.startWithDsh, true)
124
196
  assert.equal(existsSync(join(home, 'risd-lifecycle.json')), true)
125
197
 
126
198
  const after = await (await fetch(`http://127.0.0.1:${port}/v1/config`, { headers })).json()
127
- assert.equal(after.lifecycle.daemon.followDsh, false)
128
- assert.equal(after.lifecycle.programs.followDsh, true)
199
+ assert.equal(after.lifecycle.daemon.stopWithDsh, false)
200
+ assert.equal(after.lifecycle.programs.stopWithDsh, true)
201
+ assert.equal(after.lifecycle.programs.startWithDsh, true)
129
202
 
130
203
  const bad = await fetch(`http://127.0.0.1:${port}/v1/config`, {
131
204
  method: 'POST',
132
205
  headers,
133
- body: JSON.stringify({ lifecycle: { proxy: { followDsh: 'true' } } }),
206
+ body: JSON.stringify({ lifecycle: { proxy: { stopWithDsh: 'true' } } }),
134
207
  })
135
208
  assert.equal(bad.status, 400)
136
- assert.match((await bad.json()).message, /followDsh 必须是 true\/false/)
209
+ assert.match((await bad.json()).message, /proxy\.stopWithDsh 必须是 true\/false/)
137
210
 
138
211
  const forced = await fetch(`http://127.0.0.1:${port}/v1/config`, {
139
212
  method: 'POST',
@@ -142,6 +215,23 @@ test('POST /v1/config stores the policy and GET /v1/config returns it', async ()
142
215
  })
143
216
  assert.equal(forced.status, 400)
144
217
  assert.match((await forced.json()).message, /followDaemon 不再支持/)
218
+
219
+ // The daemon's start half cannot be switched off, and the debug start half does
220
+ // not exist: both are refused with their own message.
221
+ const forcedStart = await fetch(`http://127.0.0.1:${port}/v1/config`, {
222
+ method: 'POST',
223
+ headers,
224
+ body: JSON.stringify({ lifecycle: { daemon: { startWithDsh: false } } }),
225
+ })
226
+ assert.equal(forcedStart.status, 400)
227
+ assert.match((await forcedStart.json()).message, /daemon\.startWithDsh 不可配置/)
228
+ const debugStart = await fetch(`http://127.0.0.1:${port}/v1/config`, {
229
+ method: 'POST',
230
+ headers,
231
+ body: JSON.stringify({ lifecycle: { debug: { startWithDsh: true } } }),
232
+ })
233
+ assert.equal(debugStart.status, 400)
234
+ assert.match((await debugStart.json()).message, /debug\.startWithDsh 不是可配置项/)
145
235
  } finally {
146
236
  await daemon.stop()
147
237
  await sleep(100)
@@ -165,7 +255,7 @@ test('POST /v1/config rejects unknown resources, keys and non-object resources (
165
255
  })
166
256
  const cases = [
167
257
  [{ engine: { followDsh: true } }, /engine 不是生命周期资源/],
168
- [{ proxy: { followDsh: true, keepAlive: true } }, /proxy\.keepAlive 不是可配置项/],
258
+ [{ proxy: { startWithDsh: true, keepAlive: true } }, /proxy\.keepAlive 不是可配置项/],
169
259
  [{ daemon: { followDaemon: false } }, /daemon\.followDaemon 不再支持/],
170
260
  [{ proxy: true }, /proxy 必须是对象/],
171
261
  [null, /lifecycle 必须是对象/],
@@ -208,3 +298,83 @@ test('a broken lifecycle file is reported by GET /v1/config (review A3-P2-8)', a
208
298
  }
209
299
  })
210
300
 
301
+
302
+ /** A workspace with one custom program row (the shape the panel writes). */
303
+ function makeProgramWorkspace() {
304
+ const workspace = mkdtempSync(join(tmpdir(), 'risd-life-restore-'))
305
+ mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
306
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
307
+ version: 1,
308
+ defaults: {},
309
+ programs: [{
310
+ id: 'demo',
311
+ name: 'demo',
312
+ kind: 'custom',
313
+ dir: workspace,
314
+ relDir: '.',
315
+ project: '',
316
+ logName: 'demo',
317
+ startCommand: `${JSON.stringify(process.execPath)} -e "setInterval(() => {}, 60000)"`,
318
+ stopGraceMs: 3000,
319
+ }],
320
+ }, null, 2)}\n`, 'utf8')
321
+ return workspace
322
+ }
323
+
324
+ test('the programs start half restores what the last daemon left running (m03397)', { skip: skipWithout(HAS_BASH, 'bash') }, async () => {
325
+ const home = makeHome('risd-life-')
326
+ const workspace = makeProgramWorkspace()
327
+ let daemon
328
+ try {
329
+ writeLifecycle(home, { programs: { startWithDsh: true } })
330
+ // A previous daemon recorded this program as live and then went away (crash,
331
+ // reboot, kill -9): the snapshot is the only memory of it.
332
+ writeFileSync(join(home, 'risd-programs-last.json'), `${JSON.stringify({
333
+ at: new Date().toISOString(),
334
+ programs: [{ cwd: workspace, id: 'demo', dir: join(workspace, 'logs') }],
335
+ })}\n`, { mode: 0o600 })
336
+ daemon = await startRisdProcess({ home })
337
+ const lease = await api(daemon.state, '/v1/leases', { method: 'POST', body: { ownerPid: process.pid, cwd: workspace } })
338
+ assert.equal(lease.status, 200, JSON.stringify(lease.body))
339
+ const deadline = Date.now() + 5000
340
+ let demo
341
+ while (Date.now() < deadline) {
342
+ const listed = await api(daemon.state, `/v1/programs?cwd=${encodeURIComponent(workspace)}`)
343
+ demo = listed.body.programs.find((row) => row.id === 'demo')
344
+ if (demo !== undefined && demo.running !== null && demo.running !== undefined && demo.running.alive === true) break
345
+ await sleep(100)
346
+ }
347
+ assert.equal(demo?.running?.alive, true, 'the program the snapshot remembered runs again')
348
+ } finally {
349
+ if (daemon !== undefined) await daemon.stop()
350
+ await sleep(100)
351
+ removeHome(home)
352
+ rmSync(workspace, { recursive: true, force: true })
353
+ }
354
+ })
355
+
356
+ test('the programs start half stays quiet when it is off', { skip: skipWithout(HAS_BASH, 'bash') }, async () => {
357
+ const home = makeHome('risd-life-')
358
+ const workspace = makeProgramWorkspace()
359
+ let daemon
360
+ try {
361
+ // Default policy: programs do NOT follow dsh, so a stale snapshot must not start
362
+ // anything behind the user's back.
363
+ writeFileSync(join(home, 'risd-programs-last.json'), `${JSON.stringify({
364
+ at: new Date().toISOString(),
365
+ programs: [{ cwd: workspace, id: 'demo', dir: join(workspace, 'logs') }],
366
+ })}\n`, { mode: 0o600 })
367
+ daemon = await startRisdProcess({ home })
368
+ await api(daemon.state, '/v1/leases', { method: 'POST', body: { ownerPid: process.pid, cwd: workspace } })
369
+ await sleep(600)
370
+ const listed = await api(daemon.state, `/v1/programs?cwd=${encodeURIComponent(workspace)}`)
371
+ const demo = listed.body.programs.find((row) => row.id === 'demo')
372
+ assert.ok(demo !== undefined)
373
+ assert.notEqual(demo.running?.alive, true, 'nothing was restored while the start half is off')
374
+ } finally {
375
+ if (daemon !== undefined) await daemon.stop()
376
+ await sleep(100)
377
+ removeHome(home)
378
+ rmSync(workspace, { recursive: true, force: true })
379
+ }
380
+ })
@@ -5,7 +5,7 @@ import assert from 'node:assert/strict'
5
5
  import { createServer } from 'node:net'
6
6
  import test from 'node:test'
7
7
 
8
- import { pingSocks } from '../lib/risd/ping.js'
8
+ import { pingSocks, probeTarget } from '../lib/risd/ping.js'
9
9
 
10
10
  /** A server that answers the SOCKS5 greeting with `reply`. */
11
11
  function fakeServer(reply) {
@@ -97,3 +97,79 @@ test('a peer that accepts then closes without answering is reported immediately
97
97
  }
98
98
  })
99
99
 
100
+
101
+ /** A SOCKS5 server that answers the greeting and then the CONNECT request. */
102
+ function fakeSocksWithConnect(connectReply) {
103
+ return new Promise((resolve) => {
104
+ const server = createServer((socket) => {
105
+ let requests = 0
106
+ socket.on('data', () => {
107
+ requests += 1
108
+ if (requests === 1) socket.write(Buffer.from([0x05, 0x00]))
109
+ else socket.write(connectReply)
110
+ })
111
+ })
112
+ server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port }))
113
+ })
114
+ }
115
+
116
+ const CONNECT_OK = Buffer.from([0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
117
+
118
+ test('a SOCKS5 server that forwards the probe destination is reported as usable (m03429)', async () => {
119
+ const { server, port } = await fakeSocksWithConnect(CONNECT_OK)
120
+ try {
121
+ const result = await pingSocks({ host: '127.0.0.1', port, target: { host: 'git.example.com', port: 443 }, timeoutMs: 1500 })
122
+ assert.equal(result.ok, true)
123
+ assert.equal(result.socks, true)
124
+ assert.equal(result.usable, true)
125
+ assert.deepEqual(result.target, { host: 'git.example.com', port: 443 })
126
+ } finally {
127
+ server.close()
128
+ }
129
+ })
130
+
131
+ test('a greeting that passes but cannot forward is NOT usable (m03429)', async () => {
132
+ // rep=5 is SOCKS5 "connection refused": the handshake works, the tunnel does not.
133
+ const refused = Buffer.from([0x05, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
134
+ const { server, port } = await fakeSocksWithConnect(refused)
135
+ try {
136
+ const result = await pingSocks({ host: '127.0.0.1', port, target: { host: 'git.example.com', port: 5432 }, timeoutMs: 1500 })
137
+ assert.equal(result.ok, false)
138
+ assert.equal(result.socks, true)
139
+ assert.equal(result.usable, false)
140
+ assert.match(result.error, /握手正常,但无法转发到 git\.example\.com:5432/)
141
+ assert.match(result.error, /拒绝/)
142
+ } finally {
143
+ server.close()
144
+ }
145
+ })
146
+
147
+ test('without a target the probe reports the greeting only, never a fake verdict (m03429)', async () => {
148
+ const { server, port } = await fakeServer(Buffer.from([0x05, 0x00]))
149
+ try {
150
+ const result = await pingSocks({ host: '127.0.0.1', port, timeoutMs: 1500 })
151
+ assert.equal(result.ok, true)
152
+ assert.equal(result.socks, true)
153
+ assert.equal(result.usable, null)
154
+ assert.equal(result.target, null)
155
+ } finally {
156
+ server.close()
157
+ }
158
+ })
159
+
160
+ test('the probe target comes from a concrete shadow, else from a literal rule (m03429)', () => {
161
+ assert.deepEqual(probeTarget({ shadows: [{ host: '10.0.0.9', port: 1521 }], rules: [] }), { host: '10.0.0.9', port: 1521 })
162
+ assert.deepEqual(probeTarget({
163
+ shadows: [],
164
+ rules: [
165
+ { enabled: true, hosts: '10.0.0.*', ports: '80' },
166
+ { enabled: true, hosts: 'git.example.com,10.0.0.8', ports: '443, 8443' },
167
+ ],
168
+ }), { host: 'git.example.com', port: 443 })
169
+ // A wildcard port and a wildcard host cannot be dialled; guessing would turn a
170
+ // healthy tunnel into a false alarm.
171
+ assert.equal(probeTarget({ shadows: [], rules: [{ enabled: true, hosts: 'git.example.com', ports: '*' }] }), null)
172
+ assert.equal(probeTarget({ shadows: [], rules: [{ enabled: true, hosts: '*', ports: '80' }] }), null)
173
+ assert.equal(probeTarget({ shadows: [], rules: [{ enabled: false, hosts: 'git.example.com', ports: '443' }] }), null)
174
+ assert.equal(probeTarget(null), null)
175
+ })