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
@@ -15,6 +15,12 @@ import { readFile } from 'node:fs/promises'
15
15
  import { __test } from '../lib/index.js'
16
16
 
17
17
  const {
18
+ FS_COPY_PATH,
19
+ FS_MOVE_PATH,
20
+ FS_IMPORT_PATH,
21
+ FS_UPLOAD_PATH,
22
+ serveFsOp,
23
+ serveFsImport,
18
24
  CLIPBOARD_FILES_PATH,
19
25
  CLIPBOARD_READ_PATH,
20
26
  CLIPBOARD_MAX_ENTRIES,
@@ -24,6 +30,8 @@ const {
24
30
  stageClipboardCopy,
25
31
  pruneClipboardStage,
26
32
  clipboardStageMapping,
33
+ verifyClipboardStageOriginals,
34
+ CLIPBOARD_STAGE_INTEGRITY_LOG,
27
35
  windowsClipboardScript,
28
36
  windowsClipboardReadScript,
29
37
  parseClipboardRead,
@@ -252,3 +260,254 @@ test('a copy that cannot be staged fails instead of publishing the originals', a
252
260
  assert.match(client, /notify\('没能放到系统剪贴板:' \+ messageOf\(problem\)/)
253
261
  assert.match(client, /if \(code === 'unsupported'\) \{/, 'only "no backend at all" still writes the paths as text')
254
262
  })
263
+
264
+ // ---------------------------------------------------------------------------
265
+ // Overwriting must never delete the SOURCE
266
+ //
267
+ // Second report of the same symptom: 「某些文件操作,复制粘贴等(非剪切删除),
268
+ // 会导致源文件丢失」. The old `/fs/copy|move|import|upload` overwrite deleted the
269
+ // destination first and only then copied; when the destination resolved (through a
270
+ // symlinked folder, an ancestor name, or a hard link) to the SOURCE, the delete
271
+ // destroyed the source and the copy then failed with ENOENT. Four reachable paths,
272
+ // all refused now, at the inode/realpath level rather than by comparing strings.
273
+ // ---------------------------------------------------------------------------
274
+
275
+ /**
276
+ * One `/fs` request, shaped exactly like the page's (loopback host header, POST,
277
+ * JSON body or a raw stream for an upload).
278
+ * @param handler - `serveFsOp`/`serveFsImport`.
279
+ * @param pathname - route, query string included for uploads.
280
+ * @param body - JSON body, or a stream to send as-is.
281
+ * @param cwd - workspace root the session reports.
282
+ * @returns {Promise<{status: number, json: Function}>} recorded response.
283
+ */
284
+ async function postFs(handler, pathname, body, cwd) {
285
+ const { Readable } = await import('node:stream')
286
+ const payload = typeof body?.pipe === 'function' ? body : Readable.from([JSON.stringify(body)])
287
+ const req = Object.assign(payload, {
288
+ method: 'POST',
289
+ url: pathname,
290
+ headers: { host: '127.0.0.1:3080' },
291
+ })
292
+ const res = {
293
+ status: 0,
294
+ text: '',
295
+ writeHead(status) { this.status = status },
296
+ write(chunk) { if (chunk !== undefined && chunk !== null) this.text += chunk.toString() },
297
+ end(chunk) { this.write(chunk) },
298
+ on() {},
299
+ }
300
+ await handler({ sessions: { get: () => ({ header: { cwd } }) } }, req, res, {})
301
+ return { status: res.status, json: () => JSON.parse(res.text) }
302
+ }
303
+
304
+ /** Names left behind in `dir` that the replace machinery should have cleaned up. */
305
+ async function leftovers(dir) {
306
+ const { readdir } = await import('node:fs/promises')
307
+ return (await readdir(dir)).filter((name) => name.includes('.dsh-ris-ide-saving'))
308
+ }
309
+
310
+ test('copying onto an ancestor of the source refuses instead of deleting it', async () => {
311
+ const { mkdtemp, mkdir, writeFile, readFile, readdir } = await import('node:fs/promises')
312
+ const { tmpdir } = await import('node:os')
313
+ const { join } = await import('node:path')
314
+ const root = await mkdtemp(join(tmpdir(), 'dsh-copy-loss-'))
315
+ await mkdir(join(root, 'a', 'b', 'c'), { recursive: true })
316
+ await writeFile(join(root, 'a', 'b', 'c', 'f.txt'), 'KEEP', 'utf8')
317
+ // The old shape: rm(<root>/a/b) — which IS the source's parent — then cp, ENOENT,
318
+ // and `a/b` was gone for good. It also removed a second file that was never copied.
319
+ await writeFile(join(root, 'a', 'b', 'sibling.txt'), 'SIBLING', 'utf8')
320
+
321
+ const result = await postFs(__test.serveFsOp, FS_COPY_PATH, {
322
+ sessionId: 'session-1',
323
+ from: join(root, 'a', 'b', 'c', 'f.txt'),
324
+ toDir: join(root, 'a'),
325
+ name: 'b',
326
+ overwrite: true,
327
+ }, root)
328
+ assert.equal(result.status, 409, 'the overwrite is refused, not attempted')
329
+ assert.match(result.json().message, /包含源的目录/, 'the message says the target contains the source')
330
+ assert.equal(await readFile(join(root, 'a', 'b', 'c', 'f.txt'), 'utf8'), 'KEEP', 'the source file is untouched')
331
+ assert.equal(await readFile(join(root, 'a', 'b', 'sibling.txt'), 'utf8'), 'SIBLING', 'nothing else in the target was deleted either')
332
+ assert.deepEqual((await readdir(root)).sort(), ['a'])
333
+ })
334
+
335
+ test('a symlinked destination folder cannot alias the source out of existence', async () => {
336
+ const { mkdtemp, mkdir, writeFile, readFile, symlink } = await import('node:fs/promises')
337
+ const { tmpdir } = await import('node:os')
338
+ const { join } = await import('node:path')
339
+ const root = await mkdtemp(join(tmpdir(), 'dsh-copy-alias-'))
340
+ await mkdir(join(root, 'src'))
341
+ await writeFile(join(root, 'src', 'f.txt'), 'KEEP', 'utf8')
342
+ await symlink(join(root, 'src'), join(root, 'alias'))
343
+
344
+ const copy = await postFs(__test.serveFsOp, FS_COPY_PATH, {
345
+ sessionId: 'session-1',
346
+ from: join(root, 'src', 'f.txt'),
347
+ toDir: join(root, 'alias'),
348
+ name: 'f.txt',
349
+ overwrite: true,
350
+ }, root)
351
+ assert.equal(copy.status, 409, 'target and source are one file through the symlink')
352
+ assert.match(copy.json().message, /同一个条目/)
353
+ assert.equal(await readFile(join(root, 'src', 'f.txt'), 'utf8'), 'KEEP')
354
+
355
+ // The same alias through /fs/import: `source` may live outside the workspace,
356
+ // so the destination is the only thing standing between a copy and its source.
357
+ const imported = await postFs(__test.serveFsImport, FS_IMPORT_PATH, {
358
+ sessionId: 'session-1',
359
+ from: join(root, 'src', 'f.txt'),
360
+ dir: join(root, 'alias'),
361
+ name: 'f.txt',
362
+ overwrite: true,
363
+ }, root)
364
+ assert.equal(imported.status, 409)
365
+ assert.match(imported.json().message, /同一个条目/)
366
+ assert.equal(await readFile(join(root, 'src', 'f.txt'), 'utf8'), 'KEEP')
367
+ })
368
+
369
+ test('a hard link to the source is refused as an overwrite target', async () => {
370
+ const { mkdtemp, writeFile, readFile, link } = await import('node:fs/promises')
371
+ const { tmpdir } = await import('node:os')
372
+ const { join } = await import('node:path')
373
+ const root = await mkdtemp(join(tmpdir(), 'dsh-copy-link-'))
374
+ await writeFile(join(root, 'f.txt'), 'A', 'utf8')
375
+ await link(join(root, 'f.txt'), join(root, 'g.txt'))
376
+
377
+ const result = await postFs(__test.serveFsOp, FS_COPY_PATH, {
378
+ sessionId: 'session-1',
379
+ from: join(root, 'f.txt'),
380
+ toDir: root,
381
+ name: 'g.txt',
382
+ overwrite: true,
383
+ }, root)
384
+ assert.equal(result.status, 409, 'two names, one inode: overwriting one is a no-op that must not go through rm')
385
+ assert.match(result.json().message, /同一个条目/)
386
+ assert.equal(await readFile(join(root, 'f.txt'), 'utf8'), 'A')
387
+ assert.equal(await readFile(join(root, 'g.txt'), 'utf8'), 'A')
388
+ })
389
+
390
+ test('a real overwrite still replaces the target and leaves no temp file behind', async () => {
391
+ const { mkdtemp, writeFile, readFile } = await import('node:fs/promises')
392
+ const { tmpdir } = await import('node:os')
393
+ const { join } = await import('node:path')
394
+ const root = await mkdtemp(join(tmpdir(), 'dsh-copy-over-'))
395
+ await writeFile(join(root, 'new.txt'), 'A', 'utf8')
396
+ await writeFile(join(root, 'old.txt'), 'OLD', 'utf8')
397
+ // A directory also survives being replaced by a file, and vice versa.
398
+ const { mkdir } = await import('node:fs/promises')
399
+ await mkdir(join(root, 'dir'))
400
+ await writeFile(join(root, 'dir', 'inner.txt'), 'INNER', 'utf8')
401
+
402
+ const overFile = await postFs(__test.serveFsOp, FS_COPY_PATH, {
403
+ sessionId: 'session-1',
404
+ from: join(root, 'new.txt'),
405
+ toDir: root,
406
+ name: 'old.txt',
407
+ overwrite: true,
408
+ }, root)
409
+ assert.equal(overFile.status, 200)
410
+ assert.equal(overFile.json().copied, true)
411
+ assert.equal(await readFile(join(root, 'old.txt'), 'utf8'), 'A', 'the target carries the source bytes')
412
+ assert.equal(await readFile(join(root, 'new.txt'), 'utf8'), 'A', 'the source is still there')
413
+
414
+ const overDir = await postFs(__test.serveFsOp, FS_COPY_PATH, {
415
+ sessionId: 'session-1',
416
+ from: join(root, 'new.txt'),
417
+ toDir: root,
418
+ name: 'dir',
419
+ overwrite: true,
420
+ }, root)
421
+ assert.equal(overDir.status, 200, 'a file may replace a directory when the caller asked for it')
422
+ assert.equal(await readFile(join(root, 'dir'), 'utf8'), 'A')
423
+ assert.deepEqual(await leftovers(root), [], 'the temporary name is renamed away, never left as a row')
424
+ })
425
+
426
+ test('a move-over still moves, and a refused move leaves both sides intact', async () => {
427
+ const { mkdtemp, writeFile, readFile } = await import('node:fs/promises')
428
+ const { tmpdir } = await import('node:os')
429
+ const { join } = await import('node:path')
430
+ const { stat } = await import('node:fs/promises')
431
+ const root = await mkdtemp(join(tmpdir(), 'dsh-move-over-'))
432
+ await writeFile(join(root, 'm.txt'), 'M', 'utf8')
433
+ await writeFile(join(root, 'target.txt'), 'OLD-M', 'utf8')
434
+
435
+ const moved = await postFs(__test.serveFsOp, FS_MOVE_PATH, {
436
+ sessionId: 'session-1',
437
+ from: join(root, 'm.txt'),
438
+ toDir: root,
439
+ name: 'target.txt',
440
+ overwrite: true,
441
+ }, root)
442
+ assert.equal(moved.status, 200)
443
+ assert.equal(await readFile(join(root, 'target.txt'), 'utf8'), 'M')
444
+ assert.equal(await stat(join(root, 'm.txt')).catch(() => undefined), undefined, 'a move removes the source name')
445
+
446
+ // A move whose destination is the source itself is refused before anything runs.
447
+ await writeFile(join(root, 'n.txt'), 'N', 'utf8')
448
+ const same = await postFs(__test.serveFsOp, FS_MOVE_PATH, {
449
+ sessionId: 'session-1',
450
+ from: join(root, 'n.txt'),
451
+ toDir: join(root, '..'),
452
+ name: 'n.txt',
453
+ }, root)
454
+ assert.ok(same.status === 409 || same.status === 403, `a move onto itself is refused (got ${same.status})`)
455
+ assert.equal(await readFile(join(root, 'n.txt'), 'utf8'), 'N')
456
+ assert.deepEqual(await leftovers(root), [])
457
+ })
458
+
459
+ test('a failed upload keeps the previous file byte for byte', async () => {
460
+ const { mkdtemp, writeFile, readFile } = await import('node:fs/promises')
461
+ const { tmpdir } = await import('node:os')
462
+ const { join } = await import('node:path')
463
+ const { Readable } = await import('node:stream')
464
+ const root = await mkdtemp(join(tmpdir(), 'dsh-upload-fail-'))
465
+ await writeFile(join(root, 'keep.txt'), 'OLD-BYTES', 'utf8')
466
+
467
+ const partial = Readable.from((async function* stream() {
468
+ yield Buffer.from('HALF')
469
+ throw new Error('the browser tab closed mid-upload')
470
+ })())
471
+ const query = new URLSearchParams({ sessionId: 'session-1', cwd: root, dir: root, name: 'keep.txt', overwrite: '1' })
472
+ const result = await postFs(__test.serveFsImport, `${FS_UPLOAD_PATH}?${query}`, partial, root)
473
+ assert.equal(result.status, 500, 'the upload fails loudly')
474
+ assert.equal(await readFile(join(root, 'keep.txt'), 'utf8'), 'OLD-BYTES', 'the old file was never truncated')
475
+ assert.deepEqual(await leftovers(root), [], 'the half-written temp name is cleaned up')
476
+ })
477
+
478
+ test('staging records the identity of every original, so a later loss is provable', async () => {
479
+ const { mkdtemp, writeFile, readFile, rm, stat } = await import('node:fs/promises')
480
+ const { tmpdir } = await import('node:os')
481
+ const { join } = await import('node:path')
482
+ const { access } = await import('node:fs/promises')
483
+ const root = await mkdtemp(join(tmpdir(), 'dsh-copy-evidence-'))
484
+ const source = join(root, 'keep.txt')
485
+ await writeFile(source, 'KEEP', 'utf8')
486
+ const stage = await stageClipboardCopy(root, [source])
487
+ const info = await stat(source)
488
+ const manifest = JSON.parse(await readFile(join(stage.batchDir, 'manifest.json'), 'utf8'))
489
+ assert.equal(manifest.snapshot.length, 1, 'the manifest remembers the original')
490
+ assert.equal(manifest.snapshot[0].path, source)
491
+ assert.equal(manifest.snapshot[0].ino, info.ino, 'inode: is it still the same file?')
492
+ assert.equal(manifest.snapshot[0].size, info.size)
493
+ assert.equal(manifest.snapshot[0].kind, 'file')
494
+
495
+ assert.deepEqual(await verifyClipboardStageOriginals(root), [], 'nothing to report right after the copy')
496
+ // An edit is normal life, not a loss: size/mtime drift alone is not reported.
497
+ await writeFile(source, 'KEEP-EDITED', 'utf8')
498
+ assert.deepEqual(await verifyClipboardStageOriginals(root), [])
499
+
500
+ // The symptom itself: the original vanishes while the staged copy is still on the
501
+ // clipboard. The finding names both paths, so the bytes can be copied back.
502
+ await rm(source)
503
+ const findings = await verifyClipboardStageOriginals(root)
504
+ assert.equal(findings.length, 1)
505
+ assert.equal(findings[0].status, 'missing')
506
+ assert.equal(findings[0].staged, stage.staged[0], 'the hard-linked copy still holds the content')
507
+ assert.match(findings[0].message, /不见了/)
508
+ assert.match(findings[0].message, /\.dsh-ris-ide\/trash/, 'the message rules out the plugin as the deleter')
509
+ const log = await readFile(join(root, CLIPBOARD_STAGE_DIR, CLIPBOARD_STAGE_INTEGRITY_LOG), 'utf8')
510
+ assert.match(log, /"status":"missing"/, 'the evidence survives the page session')
511
+ assert.deepEqual(await verifyClipboardStageOriginals(root), [], 'a repeated paste does not repeat the finding')
512
+ assert.equal(await access(join(stage.staged[0])).then(() => true), true, 'the staged file is still readable')
513
+ })
@@ -11,6 +11,7 @@ import { tmpdir } from 'node:os'
11
11
  import { join } from 'node:path'
12
12
 
13
13
  import { __test } from '../lib/index.js'
14
+ import { skipWithout } from './helpers/cmd.mjs'
14
15
 
15
16
  const T = __test
16
17
  const hasJavac = spawnSync('javac', ['-version'], { stdio: 'ignore' }).status === 0
@@ -174,7 +175,8 @@ test('a start in debug mode puts the JDWP agent into both launch plans', () => {
174
175
  })
175
176
 
176
177
  test('real JVM: attach, breakpoint hit, stack, variables, step, detach', {
177
- skip: !hasJavac || !hasJava,
178
+ // 裸镜像里没有 JDK:这不是失败,而是这条用例无从谈起。
179
+ skip: skipWithout(hasJavac && hasJava, 'javac/java'),
178
180
  timeout: 90000,
179
181
  }, async () => {
180
182
  const dir = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-debug-'))
@@ -77,10 +77,12 @@ test('a probe without a dsh session is not recorded as a workspace', async () =>
77
77
  })
78
78
 
79
79
  test('a non-loopback Host is not recorded', async () => {
80
- const before = readWindows().length
80
+ const before = readWindows()
81
81
  const status = await get(`/dsh-ris-ide/windows?sessionId=sess-evil&cwd=${encodeURIComponent(workspace)}`, 'evil.example:80')
82
82
  assert.equal(status, 403)
83
- assert.equal(readWindows().length, before, 'a foreign origin cannot seed the IDE list')
83
+ const after = readWindows()
84
+ assert.equal(after.length, before.length, 'a foreign origin cannot seed the IDE list')
85
+ assert.equal(JSON.stringify(after), JSON.stringify(before), 'a foreign origin leaves the list untouched')
84
86
  })
85
87
 
86
88
  test('a second workspace upserts instead of replacing the list', async () => {
@@ -120,15 +122,6 @@ test('alternating known workspaces does not write on every request', async () =>
120
122
  assert.equal(after, before, 'nothing was rewritten inside the throttle window')
121
123
  })
122
124
 
123
- test('a non-loopback Host header records nothing', async () => {
124
- const before = readWindows()
125
- // The route itself may refuse a non-loopback Host (403); recording must not happen either way.
126
- const status = await get('/dsh-ris-ide/windows?sessionId=sess-evil', 'evil.example.com')
127
- assert.ok(status === 200 || status === 403, `unexpected status ${status}`)
128
- const after = readWindows()
129
- assert.equal(JSON.stringify(after), JSON.stringify(before))
130
- })
131
-
132
125
  test('a request without a workspace does not replace another workspace entry', async () => {
133
126
  // Review C-P1-5: the empty-cwd entry used `existing[0].cwd` as its key, so a
134
127
  // bare /dsh-ris-ide/proxy call overwrote somebody else's window entry.
@@ -3,11 +3,12 @@
3
3
  // daemon page would list only the workspace that happened to call an endpoint
4
4
  // inside the freshness window.
5
5
  import assert from 'node:assert/strict'
6
+ import { createServer, request } from 'node:http'
6
7
  import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
8
  import { tmpdir } from 'node:os'
8
9
  import { join } from 'node:path'
9
10
  import { after, before, test } from 'node:test'
10
- import { __test } from '../lib/index.js'
11
+ import { __test, handleRequest } from '../lib/index.js'
11
12
 
12
13
  let home
13
14
 
@@ -91,6 +92,35 @@ test('a garbage ownerPid makes the row ours, not somebody else\'s', () => {
91
92
  assert.notEqual(readWindows()[0].at, old)
92
93
  })
93
94
 
95
+ test('a rename re-labels the row and refreshes the sidebar snapshot (m13800)', () => {
96
+ // Renaming a workspace only changes its title; the path stays. The refresh tick is
97
+ // the only thing that runs while nobody is clicking, so it must carry the new label
98
+ // to the daemon page, along with the whole sidebar list.
99
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
100
+ writeWindows([{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-a', sessionId: 's-live', title: 'before', at: old }])
101
+ const ctx = {
102
+ sessions: { get: (id) => (id === 's-live' ? { header: { cwd: '/tmp/ws-a' } } : null) },
103
+ get: (name) => (name === 'workspaceRegistry'
104
+ ? {
105
+ list: () => [
106
+ { path: '/tmp/ws-a', title: 'after', sessionIds: ['s-live'] },
107
+ { path: '/tmp/ws-b', title: 'other', sessionIds: [] },
108
+ ],
109
+ }
110
+ : undefined),
111
+ }
112
+ assert.deepEqual(__test.refreshDshWindows(ctx), { changed: 1, windows: 1, dropped: 0 })
113
+ const doc = JSON.parse(readFileSync(join(home, 'dsh-window.json'), 'utf8'))
114
+ assert.equal(doc.windows[0].title, 'after', 'the row keeps its path and takes the new label')
115
+ assert.equal(doc.windows[0].cwd, '/tmp/ws-a')
116
+ assert.deepEqual(doc.workspaces.map((row) => [row.cwd, row.title]), [
117
+ ['/tmp/ws-a', 'after'],
118
+ ['/tmp/ws-b', 'other'],
119
+ ], 'the snapshot mirrors the sidebar, in its order')
120
+ assert.equal(doc.url, 'http://127.0.0.1:3080', 'the origin that answered is remembered')
121
+ assert.ok(Number.isFinite(Date.parse(doc.at)), 'the document says when it was written')
122
+ })
123
+
94
124
  test('a session that reopened on another workspace drops the stale row', () => {
95
125
  const old = new Date(Date.now() - 10 * 60_000).toISOString()
96
126
  writeWindows([{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-moved', sessionId: 's-moved', at: old }])
@@ -98,3 +128,138 @@ test('a session that reopened on another workspace drops the stale row', () => {
98
128
  assert.deepEqual(result, { changed: 0, windows: 0, dropped: 1 })
99
129
  assert.deepEqual(readWindows(), [])
100
130
  })
131
+
132
+ test('a dsh that never opened the IDE panel still publishes its sidebar (m00186)', () => {
133
+ // The reported bug: dsh was running with workspaces, but nobody had opened the IDE
134
+ // panel in that process, so no window row existed — and the tick returned before
135
+ // writing anything. The daemon page then said 「dsh 未运行(没有记住的工作区窗口)」.
136
+ // The registry mirror alone must be enough for the page to offer every workspace.
137
+ rmSync(join(home, 'dsh-window.json'), { force: true })
138
+ const ctx = {
139
+ // liveSessionFor needs list(); the sidebar row keeps that session id, the other
140
+ // row has none (nothing to boot on, the page falls back to the cwd). get() is what
141
+ // marks a row `active` for the page's per-row hint.
142
+ sessions: {
143
+ list: () => [{ id: 's-a', header: { cwd: '/tmp/ws-a' } }],
144
+ get: (id) => (id === 's-a' ? { header: { cwd: '/tmp/ws-a' } } : undefined),
145
+ },
146
+ get: (name) => (name === 'workspaceRegistry'
147
+ ? {
148
+ list: () => [
149
+ { path: '/tmp/ws-a', title: 'alpha', sessionIds: ['s-a'] },
150
+ { path: '/tmp/ws-b', title: 'beta', sessionIds: [] },
151
+ ],
152
+ }
153
+ : undefined),
154
+ // No page has been served yet: the bound address is the only origin available.
155
+ webServer: { getOrigin: () => 'http://127.0.0.1:3080' },
156
+ }
157
+ assert.deepEqual(__test.refreshDshWindows(ctx), { changed: 0, windows: 0, dropped: 0 })
158
+ const doc = JSON.parse(readFileSync(join(home, 'dsh-window.json'), 'utf8'))
159
+ assert.deepEqual(doc.windows, [], 'no window row exists yet')
160
+ assert.deepEqual(doc.workspaces.map((row) => [row.cwd, row.title, row.sessionId]), [
161
+ ['/tmp/ws-a', 'alpha', 's-a'],
162
+ ['/tmp/ws-b', 'beta', ''],
163
+ ], 'the sidebar list, in its order, with the session each workspace is on')
164
+ assert.equal(doc.url, 'http://127.0.0.1:3080', 'the daemon needs an origin to embed the IDE at')
165
+ assert.ok(Number.isFinite(Date.parse(doc.at)), '`at` is the liveness proof the sidebar branch reads')
166
+ assert.deepEqual(doc.workspaces.map((row) => row.active), [true, false],
167
+ 'a workspace without a live session is still listed, only not painted as active')
168
+ // The daemon can also probe this process directly when it cannot use the document:
169
+ // one per-pid file says where a LIVE host answers (m00186).
170
+ const instance = JSON.parse(readFileSync(join(home, 'instances', `dsh-${process.pid}.json`), 'utf8'))
171
+ assert.equal(instance.url, 'http://127.0.0.1:3080')
172
+ assert.equal(instance.pid, process.pid)
173
+ assert.ok(Number.isFinite(Date.parse(instance.at)))
174
+ })
175
+
176
+ test('a process with nothing to publish leaves another instance\'s snapshot alone', () => {
177
+ // Same machine-level home, two dsh processes. An older host without a workspace
178
+ // registry must not erase the newer instance's sidebar snapshot: it has nothing to
179
+ // say, so it says nothing (the write only happens when there is something to keep).
180
+ const now = new Date().toISOString()
181
+ writeFileSync(join(home, 'dsh-window.json'), `${JSON.stringify({
182
+ windows: [],
183
+ workspaces: [{ cwd: '/tmp/ws-other', title: 'other', sessionId: 's-other' }],
184
+ url: 'http://127.0.0.1:3080',
185
+ at: now,
186
+ })}\n`)
187
+ assert.deepEqual(__test.refreshDshWindows({ sessions: { get: () => undefined } }), { changed: 0, windows: 0, dropped: 0 })
188
+ const doc = JSON.parse(readFileSync(join(home, 'dsh-window.json'), 'utf8'))
189
+ assert.deepEqual(doc.workspaces.map((row) => row.cwd), ['/tmp/ws-other'], 'the other instance\'s snapshot survives')
190
+ assert.equal(doc.at, now, 'nothing was rewritten')
191
+ })
192
+
193
+ test('the origin a loopback request really used wins over the bound address (m00186)', () => {
194
+ // getOrigin() can report a LAN address while the page was opened on 127.0.0.1; the
195
+ // request's Host is the address that actually worked, so it must be the one written.
196
+ // A cross-site request must not be able to move it (review A-P2-10).
197
+ __test.rememberDshOrigin({ headers: { host: '127.0.0.1:3999' } })
198
+ __test.rememberDshOrigin({ headers: { host: '203.0.113.9:3999' } })
199
+ rmSync(join(home, 'dsh-window.json'), { force: true })
200
+ const ctx = {
201
+ sessions: { list: () => [] },
202
+ get: (name) => (name === 'workspaceRegistry'
203
+ ? { list: () => [{ path: '/tmp/ws-a', title: 'alpha', sessionIds: [] }] }
204
+ : undefined),
205
+ webServer: { getOrigin: () => 'http://192.168.1.20:3080' },
206
+ }
207
+ __test.refreshDshWindows(ctx)
208
+ const doc = JSON.parse(readFileSync(join(home, 'dsh-window.json'), 'utf8'))
209
+ assert.equal(doc.url, 'http://127.0.0.1:3999', 'the loopback origin a browser used wins')
210
+ assert.equal(doc.workspaces.length, 1)
211
+ })
212
+
213
+ /** One loopback GET against a test server; JSON body parsed when it is JSON. */
214
+ function getJson(port, path, host) {
215
+ return new Promise((resolveGet) => {
216
+ const call = request({ host: '127.0.0.1', port, path, method: 'GET', headers: { host: host ?? `127.0.0.1:${port}` } }, (res) => {
217
+ let body = ''
218
+ res.setEncoding('utf8')
219
+ res.on('data', (chunk) => { body += chunk })
220
+ res.on('end', () => {
221
+ let parsed = null
222
+ try { parsed = JSON.parse(body) } catch { parsed = null }
223
+ resolveGet({ status: res.statusCode, body: parsed })
224
+ })
225
+ })
226
+ call.on('error', () => resolveGet({ status: 0, body: null }))
227
+ call.end()
228
+ })
229
+ }
230
+
231
+ test('GET /dsh-ris-ide/workspaces answers from the live host, loopback only (m00186)', async () => {
232
+ // `/v1/dsh` falls back to asking a live dsh directly when dsh-window.json is missing
233
+ // or stale, so the route must answer from the running context (no file involved) and
234
+ // must stay loopback-only like every other plugin route.
235
+ const ctx = {
236
+ sessions: {
237
+ list: () => [{ id: 's-live', header: { cwd: '/tmp/ws-a' } }],
238
+ get: (id) => (id === 's-live' ? { header: { cwd: '/tmp/ws-a' } } : undefined),
239
+ },
240
+ get: (name) => (name === 'workspaceRegistry'
241
+ ? {
242
+ list: () => [
243
+ { path: '/tmp/ws-a', title: 'alpha', sessionIds: ['s-live'] },
244
+ { path: '/tmp/ws-b', title: 'beta', sessionIds: [] },
245
+ ],
246
+ }
247
+ : undefined),
248
+ }
249
+ const server = createServer((incoming, response) => handleRequest(ctx, incoming, response, { maxBytes: 1024, restrictToCwd: false }))
250
+ await new Promise((resolveListen) => server.listen(0, '127.0.0.1', resolveListen))
251
+ const port = server.address().port
252
+ try {
253
+ const answer = await getJson(port, '/dsh-ris-ide/workspaces')
254
+ assert.equal(answer.status, 200)
255
+ assert.deepEqual(answer.body.workspaces.map((row) => [row.cwd, row.title, row.sessionId, row.active]), [
256
+ ['/tmp/ws-a', 'alpha', 's-live', true],
257
+ ['/tmp/ws-b', 'beta', '', false],
258
+ ])
259
+ assert.equal(answer.body.url, `http://127.0.0.1:${port}`, 'the Host a page used is the origin it can embed')
260
+ const foreign = await getJson(port, '/dsh-ris-ide/workspaces', 'evil.example:80')
261
+ assert.equal(foreign.status, 403, 'a non-loopback Host cannot read the workspace list')
262
+ } finally {
263
+ await new Promise((resolveClose) => server.close(resolveClose))
264
+ }
265
+ })
@@ -66,7 +66,7 @@ test('no internal/private host leaks into tests or docs', async () => {
66
66
 
67
67
  test('npm test needs no install and no network', async () => {
68
68
  const pkg = JSON.parse(await readFile(join(ROOT, 'package.json'), 'utf8'))
69
- assert.equal(pkg.scripts.test, 'node --test "test/*.test.mjs"', 'test script stays dependency-free (node:test only)')
69
+ assert.equal(pkg.scripts.test, 'node --test --test-timeout=120000 "test/*.test.mjs"', 'test script stays dependency-free (node:test only); the per-test timeout turns a hang into a named failure')
70
70
  for (const hook of ['pretest', 'posttest']) {
71
71
  assert.equal(pkg.scripts[hook], undefined, `${hook} must not exist, or npm test stops being self-contained`)
72
72
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * External-command probes for the test suite.
3
+ *
4
+ * The suite must not hard-depend on programs the CI pod may not have (Jenkins runs
5
+ * the bare image: no git, no bash). A test that really exercises an external
6
+ * program declares `{ skip: skipWithout(HAS_X, 'x') }` so it reports a skip with a
7
+ * reason instead of failing with ENOENT — the assertion is never weakened, the
8
+ * test simply does not run where its subject does not exist.
9
+ */
10
+ import { spawnSync } from 'node:child_process'
11
+
12
+ /** True when `name` exists on PATH and exits 0 for `args`. */
13
+ export function hasCommand(name, args = ['--version']) {
14
+ try {
15
+ return spawnSync(name, args, { stdio: 'ignore', windowsHide: true }).status === 0
16
+ } catch {
17
+ return false
18
+ }
19
+ }
20
+
21
+ export const HAS_GIT = hasCommand('git')
22
+ export const HAS_BASH = hasCommand('bash', ['-c', 'true'])
23
+ /** WSL 上把 Linux 路径翻成 Windows 形式要靠它;普通 Linux 用 lib 的测试接缝替代。 */
24
+ export const HAS_WSLPATH = hasCommand('wslpath', ['-w', '/tmp'])
25
+
26
+ /** node:test `skip` value: false when available, else the reason string. */
27
+ export function skipWithout(available, label) {
28
+ return available === true ? false : `${label} is not installed`
29
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Fixture builders shared by the ProxyBridge bundle tests.
3
+ *
4
+ * Fixtures are built in-process: a tiny ustar writer + gzip gives a real `.tgz`,
5
+ * so the parser is exercised end-to-end without network or binaries.
6
+ */
7
+ import assert from 'node:assert/strict'
8
+ import { gzipSync } from 'node:zlib'
9
+
10
+ /** The bytes every fixture entry carries unless the caller overrides them. */
11
+ export const fileContent = (rel) => `fixture bytes for ${rel}\n`
12
+
13
+ /** Octal field: width-1 digits + NUL, as ustar spells numbers. */
14
+ export const octalField = (value, width) => `${value.toString(8).padStart(width - 1, '0')}\0`
15
+
16
+ /** One 512-byte ustar header. */
17
+ export function tarHeader(name, size, { mode = 0o644, type = '0', linkname = '' } = {}) {
18
+ const header = Buffer.alloc(512, 0)
19
+ const encoded = Buffer.from(name, 'utf8')
20
+ assert.ok(encoded.length <= 100, `fixture name too long: ${name}`)
21
+ encoded.copy(header, 0)
22
+ header.write(octalField(mode, 8), 100, 'ascii')
23
+ header.write(octalField(0, 8), 108, 'ascii') // uid
24
+ header.write(octalField(0, 8), 116, 'ascii') // gid
25
+ header.write(octalField(size, 12), 124, 'ascii')
26
+ header.write(octalField(0, 12), 136, 'ascii') // mtime
27
+ header.write(' ', 148, 'ascii') // checksum placeholder
28
+ header.write(type, 156, 'ascii')
29
+ header.write(linkname < 101 ? linkname : linkname.slice(0, 100), 157, 'ascii')
30
+ header.write('ustar\0', 257, 'ascii')
31
+ header.write('00', 263, 'ascii')
32
+ let sum = 0
33
+ for (const byte of header) sum += byte
34
+ header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii')
35
+ return header
36
+ }
37
+
38
+ /** Build a real `.tgz` from `{name, content?, mode?, type?, linkname?}` entries. */
39
+ export function makeTgz(entries, { prefix = '' } = {}) {
40
+ const chunks = []
41
+ for (const entry of entries) {
42
+ const content = Buffer.from(entry.content ?? fileContent(entry.name))
43
+ chunks.push(tarHeader(`${prefix}${entry.name}`, content.length, entry))
44
+ chunks.push(content)
45
+ const pad = (512 - (content.length % 512)) % 512
46
+ if (pad > 0) chunks.push(Buffer.alloc(pad))
47
+ }
48
+ chunks.push(Buffer.alloc(1024)) // end-of-archive: two zero blocks
49
+ return gzipSync(Buffer.concat(chunks))
50
+ }
51
+
52
+ /**
53
+ * `fetch` stand-in serving one body. `calls.count` counts invocations and
54
+ * `calls.urls` records every requested URL; `options.url` mimics `Response.url`
55
+ * after redirects and `options.headers` mimics the header bag.
56
+ */
57
+ export function fetchServing(body, options = {}) {
58
+ const calls = { count: 0, urls: [] }
59
+ const impl = async (requested) => {
60
+ calls.count += 1
61
+ calls.urls.push(String(requested))
62
+ return {
63
+ ok: true,
64
+ status: 200,
65
+ url: options.url ?? requested,
66
+ headers: options.headers ?? { get: () => null },
67
+ arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.length),
68
+ }
69
+ }
70
+ return { impl, calls }
71
+ }