dsh-ris-ide 1.7.1 → 1.7.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.
@@ -0,0 +1,599 @@
1
+ // Route-level tests for the proxy dialog: read, save, action, program picker.
2
+ // These call the host handlers directly (the same shape the HTTP server uses).
3
+ import assert from 'node:assert/strict'
4
+ import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { Readable } from 'node:stream'
8
+ import test from 'node:test'
9
+
10
+ // The proxy config/pid/log live in ONE machine-level directory now (that is the
11
+ // whole point of the shared engine), so every test run gets its own throwaway
12
+ // home instead of writing into the developer's ~/.dsh-ris-ide.
13
+ process.env.DSH_RIS_IDE_PROXY_HOME = mkdtempSync(join(tmpdir(), 'ris-proxy-home-'))
14
+
15
+ import { __test } from '../lib/index.js'
16
+ import { readProxyConfig, writeProxyConfig } from '../lib/proxy.js'
17
+
18
+ /** A response face that collects the JSON body. */
19
+ function fakeRes() {
20
+ return {
21
+ status: 0,
22
+ headers: {},
23
+ chunks: [],
24
+ writeHead(status, headers) { this.status = status; this.headers = headers },
25
+ write(chunk) { this.chunks.push(String(chunk)); return true },
26
+ end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
27
+ json() { return JSON.parse(this.chunks.join('')) },
28
+ }
29
+ }
30
+
31
+ /**
32
+ * A request face with a loopback host header and a JSON body. The body arrives
33
+ * as a real Readable so `readJsonBody` (which iterates the stream) works exactly
34
+ * as it does under the HTTP server.
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
+ const ctx = (cwd) => ({ sessions: { get: () => ({ header: { cwd } }) } })
46
+
47
+ test('the proxy routes are advertised under the plugin prefix', () => {
48
+ assert.equal(__test.PROXY_PATH, '/dsh-ris-ide/proxy')
49
+ assert.equal(__test.PROXY_ACTION_PATH, '/dsh-ris-ide/proxy/action')
50
+ assert.equal(__test.PROXY_PROGRAMS_PATH, '/dsh-ris-ide/proxy/programs')
51
+ })
52
+
53
+ test('GET reports the generated rules, disabled, with parse diagnostics', async () => {
54
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
55
+ try {
56
+ const res = fakeRes()
57
+ await __test.serveProxy(ctx(dir), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
58
+ assert.equal(res.status, 200)
59
+ const body = res.json()
60
+ assert.equal(body.ok, true)
61
+ assert.equal(typeof body.side, 'string')
62
+ assert.deepEqual(body.rules.filter((rule) => rule.source === 'auto').map((rule) => rule.program), ['java', 'git'])
63
+ assert.equal(body.rules.every((rule) => rule.enabled === false), true)
64
+ assert.equal(body.running, false)
65
+ assert.equal(body.configPath, join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), 'ONE shared file, not a per-workspace one')
66
+ assert.equal(body.shared, true)
67
+ assert.equal(body.workspace, dir)
68
+ assert.deepEqual(body.rules[0].hostsParsed, [])
69
+ } finally {
70
+ rmSync(dir, { recursive: true, force: true })
71
+ }
72
+ })
73
+
74
+ test('POST saves the form and echoes the rejected fragments', async () => {
75
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
76
+ try {
77
+ const res = fakeRes()
78
+ await __test.serveProxy(ctx(dir), fakeReq('POST', '/dsh-ris-ide/proxy', {
79
+ sessionId: 's1',
80
+ config: {
81
+ socks: { host: '10.3.91.121', port: 1080 },
82
+ listenPort: 11081,
83
+ rules: [
84
+ { id: 'db', program: 'navicat', hosts: '172.20.235.*, bad host!', ports: '1521, 70000', enabled: true, shadow: false },
85
+ ],
86
+ },
87
+ }), res)
88
+ assert.equal(res.status, 200)
89
+ const body = res.json()
90
+ const db = body.rules.find((rule) => rule.id === 'db')
91
+ assert.deepEqual(db.hostsParsed, ['172.20.235.*'])
92
+ assert.deepEqual(db.hostsInvalid, ['bad host!'])
93
+ assert.deepEqual(db.portsParsed, [1521])
94
+ assert.deepEqual(db.portsInvalid, ['70000'])
95
+ assert.equal(db.shadowable, false)
96
+ assert.equal(body.socks.host, '10.3.91.121')
97
+ // …and it really landed on disk (that is what the engine reads).
98
+ assert.equal(readProxyConfig(dir).rules.find((rule) => rule.id === 'db').enabled, true)
99
+ } finally {
100
+ rmSync(dir, { recursive: true, force: true })
101
+ }
102
+ })
103
+
104
+ test('starter rows are marked, and a save does not freeze them into the table', async () => {
105
+ // The dialog shows 4 starter rows off an empty table. If the first save wrote them,
106
+ // today's suggestion would become a stored rule forever (and the host could never
107
+ // change its mind about which programs get one).
108
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-template-'))
109
+ try {
110
+ const readRes = fakeRes()
111
+ await __test.serveProxy(ctx(dir), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), readRes)
112
+ const view = readRes.json()
113
+ const templates = view.rules.filter((rule) => rule.template === true)
114
+ assert.ok(templates.length >= 2, 'the starter rows are marked as such')
115
+ assert.ok(templates.every((rule) => rule.id.startsWith('auto-')))
116
+ // A save that carries only real rows leaves the table without any auto row.
117
+ const saveRes = fakeRes()
118
+ await __test.serveProxy(ctx(dir), fakeReq('POST', '/dsh-ris-ide/proxy', {
119
+ sessionId: 's1',
120
+ revision: view.revision,
121
+ config: {
122
+ socks: view.socks,
123
+ listenPort: view.listenPort,
124
+ rules: [{ id: 'real', program: 'java', hosts: '172.20.235.*', ports: '*', enabled: true }],
125
+ },
126
+ }), saveRes)
127
+ assert.equal(saveRes.status, 200)
128
+ const stored = readProxyConfig(dir).rules.map((rule) => rule.id)
129
+ assert.deepEqual(stored, ['real'], 'no starter row was written to disk')
130
+ } finally {
131
+ rmSync(dir, { recursive: true, force: true })
132
+ }
133
+ })
134
+
135
+ test('a reload rewrites the profile BEFORE restarting the interceptor', () => {
136
+ // ProxyBridge reads its profile only at start. Reloading without rewriting it
137
+ // relaunches the OLD rules and still reports "已按新规则自动重启" — the exact
138
+ // failure B3 described.
139
+ const source = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
140
+ const start = source.indexOf('async function serveProxy(')
141
+ const body = source.slice(start, start + 20000)
142
+ // Rewriting the profile and restarting are ONE step now (a bare restart relaunched
143
+ // the old profile and lied about it — the helper writes first, then reloads).
144
+ assert.ok(body.includes('await reloadRedirectorsWithProfile(cwd'), 'the save reloads through the profile-writing helper')
145
+ assert.equal(body.includes('startRedirectors({ reload: true'), false, 'no bare restart path is left')
146
+ // B-M3: a GET must not block the event loop on the 3.5s PowerShell probe.
147
+ assert.ok(body.includes('redirectorStatusCached()'), 'status comes from the cached probe')
148
+ assert.ok(source.includes('redirector: Object.assign(redirectorStatusCached()'), 'the view uses it too')
149
+ })
150
+
151
+ test('a save rendered from a stale table is refused, not applied', async () => {
152
+ // Two windows hold the same table; the second save must not silently drop the
153
+ // first one's row. The payload names the table it was rendered from.
154
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-conflict-'))
155
+ try {
156
+ writeProxyConfig(dir, {
157
+ socks: { host: '10.3.91.121', port: 1080 },
158
+ rules: [{ id: 'first', program: 'navicat', hosts: '172.20.235.80', ports: '1521', enabled: true }],
159
+ })
160
+ const readRes = fakeRes()
161
+ await __test.serveProxy(ctx(dir), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), readRes)
162
+ const rendered = readRes.json()
163
+ assert.equal(typeof rendered.revision, 'string')
164
+ assert.ok(rendered.revision !== '')
165
+
166
+ // Window A saves (the table now differs from what window B rendered).
167
+ const aRes = fakeRes()
168
+ await __test.serveProxy(ctx(dir), fakeReq('POST', '/dsh-ris-ide/proxy', {
169
+ sessionId: 's1',
170
+ revision: rendered.revision,
171
+ config: {
172
+ socks: { host: '10.3.91.121', port: 1080 },
173
+ rules: [
174
+ { id: 'first', program: 'navicat', hosts: '172.20.235.80', ports: '1521', enabled: true },
175
+ { id: 'from-a', program: 'psql', hosts: '172.20.235.80', ports: '*', enabled: true },
176
+ ],
177
+ },
178
+ }), aRes)
179
+ assert.equal(aRes.status, 200)
180
+
181
+ // Window B saves with the SAME (now stale) revision: refused, table untouched.
182
+ const bRes = fakeRes()
183
+ await __test.serveProxy(ctx(dir), fakeReq('POST', '/dsh-ris-ide/proxy', {
184
+ sessionId: 's1',
185
+ revision: rendered.revision,
186
+ config: {
187
+ socks: { host: '10.3.91.121', port: 1080 },
188
+ rules: [{ id: 'from-b', program: 'mysql', hosts: '172.20.235.80', ports: '3306', enabled: true }],
189
+ },
190
+ }), bRes)
191
+ assert.equal(bRes.status, 409)
192
+ const conflict = bRes.json()
193
+ assert.equal(conflict.conflict, true)
194
+ assert.equal(typeof conflict.message, 'string')
195
+ // The view comes back so the dialog can reload instead of guessing.
196
+ assert.equal(conflict.view.rules.some((rule) => rule.id === 'from-a'), true)
197
+ const onDisk = readProxyConfig(dir).rules.map((rule) => rule.id)
198
+ assert.equal(onDisk.includes('from-b'), false, 'the stale save changed nothing')
199
+ assert.equal(onDisk.includes('from-a'), true)
200
+ // The revision it reports is the CURRENT one, so the reload can save again.
201
+ assert.notEqual(conflict.revision, rendered.revision)
202
+ } finally {
203
+ writeProxyConfig(dir, { socks: { host: '', port: 0 }, rules: [] })
204
+ rmSync(dir, { recursive: true, force: true })
205
+ }
206
+ })
207
+
208
+ test('the shadow flag is what makes a literal rule bindable', async () => {
209
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
210
+ try {
211
+ writeProxyConfig(dir, { rules: [{ id: 'lit', program: 'navicat', hosts: '172.20.235.80', ports: '1521', enabled: true, shadow: true }] })
212
+ const res = fakeRes()
213
+ await __test.serveProxy(ctx(dir), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
214
+ const rule = res.json().rules.find((item) => item.id === 'lit')
215
+ assert.equal(rule.shadowable, true, 'a literal IPv4 rule can be mapped onto 127.0.0.1')
216
+ assert.equal(rule.shadow, true)
217
+ } finally {
218
+ rmSync(dir, { recursive: true, force: true })
219
+ }
220
+ })
221
+
222
+ test('the shadow column follows what can be bound, not what parses', async () => {
223
+ // `*` parses to port 0 = "any port": a loopback listener cannot bind it, so that row
224
+ // must not claim to be shadowable (the flag is exactly what the engine binds).
225
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-bindable-'))
226
+ try {
227
+ writeProxyConfig(dir, {
228
+ socks: { host: '10.0.0.1', port: 1080 },
229
+ rules: [
230
+ { id: 'any-port', program: 'java', hosts: '172.20.235.80', ports: '*', enabled: true },
231
+ { id: 'real-port', program: 'navicat', hosts: '172.20.235.80', ports: '1521', enabled: true },
232
+ { id: 'spaced-range', program: 'psql', hosts: '172.20.235.80', ports: '1000 - 1003', enabled: true },
233
+ ],
234
+ })
235
+ const res = fakeRes()
236
+ await __test.serveProxy(ctx(dir), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
237
+ const rules = res.json().rules
238
+ const byId = (id) => rules.find((rule) => rule.id === id)
239
+ assert.equal(byId('any-port').shadowable, false)
240
+ assert.equal(byId('real-port').shadowable, true)
241
+ // One grammar for host and dialog: `1000 - 1003` is a range on both sides.
242
+ assert.deepEqual(byId('spaced-range').portsParsed, [1000, 1001, 1002, 1003])
243
+ assert.deepEqual(byId('spaced-range').portsInvalid, [])
244
+ } finally {
245
+ // The table is machine-wide: leaving a SOCKS address behind would make the next
246
+ // test see an upstream it never configured.
247
+ writeProxyConfig(dir, { socks: { host: '', port: 0 }, rules: [] })
248
+ rmSync(dir, { recursive: true, force: true })
249
+ }
250
+ })
251
+
252
+ test('action=status answers without touching anything', async () => {
253
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
254
+ try {
255
+ const res = fakeRes()
256
+ await __test.serveProxyAction(ctx(dir), fakeReq('POST', '/dsh-ris-ide/proxy/action', { sessionId: 's1', action: 'status' }), res)
257
+ assert.equal(res.status, 200)
258
+ assert.equal(res.json().running, false)
259
+ } finally {
260
+ rmSync(dir, { recursive: true, force: true })
261
+ }
262
+ })
263
+
264
+ test('start refuses without an upstream SOCKS address', async () => {
265
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
266
+ try {
267
+ const res = fakeRes()
268
+ await __test.serveProxyAction(ctx(dir), fakeReq('POST', '/dsh-ris-ide/proxy/action', { sessionId: 's1', action: 'start' }), res)
269
+ assert.equal(res.status, 200)
270
+ const body = res.json()
271
+ assert.equal(body.result.ok, false)
272
+ assert.match(body.result.error, /SOCKS/)
273
+ assert.equal(body.running, false)
274
+ } finally {
275
+ rmSync(dir, { recursive: true, force: true })
276
+ }
277
+ })
278
+
279
+ test('the program picker lists suggestions and marks the engine side', async () => {
280
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
281
+ try {
282
+ const res = fakeRes()
283
+ await __test.serveProxyPrograms(ctx(dir), fakeReq('GET', '/dsh-ris-ide/proxy/programs?sessionId=s1'), res)
284
+ assert.equal(res.status, 200)
285
+ const body = res.json()
286
+ assert.ok(['windows', 'wsl', 'linux', 'macos'].includes(body.side))
287
+ const names = body.programs.map((item) => item.name.toLowerCase())
288
+ // Only SOCKS-aware programs are offered: injecting a tunnel means handing the
289
+ // program a SOCKS address, which a non-SOCKS client cannot use — those are
290
+ // mapped on 127.0.0.1 instead and need no picker entry.
291
+ for (const expected of ['java', 'git', 'node', 'curl']) {
292
+ assert.equal(names.includes(expected), true, `picker should offer ${expected}`)
293
+ }
294
+ for (const hidden of ['navicat', 'navicat.exe', 'mysql', 'redis-cli', 'psql']) {
295
+ assert.equal(names.includes(hidden), false, `picker must not offer ${hidden} (no SOCKS support)`)
296
+ }
297
+ assert.ok(body.programs.every((item) => typeof item.side === 'string'))
298
+ assert.match(String(body.note || ''), /127\.0\.0\.1/)
299
+ } finally {
300
+ rmSync(dir, { recursive: true, force: true })
301
+ }
302
+ })
303
+
304
+ test('a request from a non-loopback peer is refused', async () => {
305
+ const dir = mkdtempSync(join(tmpdir(), 'ris-ide-proxy-route-'))
306
+ try {
307
+ const res = fakeRes()
308
+ const req = fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1')
309
+ req.headers = { host: '10.0.0.9:3080' }
310
+ await __test.serveProxy(ctx(dir), req, res)
311
+ assert.equal(res.status, 403)
312
+ } finally {
313
+ rmSync(dir, { recursive: true, force: true })
314
+ }
315
+ })
316
+
317
+ test('the file browser lists programs it can offer, and refuses a missing directory', async () => {
318
+ const { mkdirSync, writeFileSync, chmodSync } = await import('node:fs')
319
+ const root = mkdtempSync(join(tmpdir(), 'ris-browse-'))
320
+ mkdirSync(join(root, 'bin'))
321
+ mkdirSync(join(root, 'node_modules'))
322
+ writeFileSync(join(root, 'run.sh'), '#!/bin/sh\n')
323
+ chmodSync(join(root, 'run.sh'), 0o755)
324
+ writeFileSync(join(root, 'notes.txt'), 'x')
325
+ try {
326
+ const list = fakeRes()
327
+ await __test.serveProxyBrowse(ctx(root), fakeReq('GET', '/dsh-ris-ide/proxy/browse?sessionId=s1'), list)
328
+ assert.equal(list.status, 200)
329
+ const body = list.json()
330
+ assert.equal(body.ok, true)
331
+ assert.equal(body.path, root, 'no ?path lists the workspace itself')
332
+ assert.deepEqual(body.dirs.map((dir) => dir.name), ['bin'], 'node_modules is skipped')
333
+ assert.deepEqual(body.files.map((file) => file.name), ['run.sh'], 'only executable-looking files')
334
+ assert.ok(Array.isArray(body.roots) && body.roots.length >= 1, 'entry points are offered')
335
+ // The tree starts at `/` and the Windows disks and nothing else: a program that
336
+ // lives outside workspace/home/temp must be reachable without typing its path.
337
+ const names = body.roots.map((entry) => entry.path)
338
+ assert.equal(names.includes('/'), true, '/ is an entry point')
339
+ assert.equal(names.every((path) => path === '/' || path.startsWith('/mnt/')), true,
340
+ 'no workspace/home/temp shortcuts in front of the real start')
341
+
342
+ const atRoot = fakeRes()
343
+ await __test.serveProxyBrowse(ctx(root), fakeReq('GET', '/dsh-ris-ide/proxy/browse?sessionId=s1&path=%2F'), atRoot)
344
+ assert.equal(atRoot.json().path, '/')
345
+ assert.equal(Array.isArray(atRoot.json().dirs), true)
346
+
347
+ const deeper = fakeRes()
348
+ await __test.serveProxyBrowse(ctx(root), fakeReq('GET', `/dsh-ris-ide/proxy/browse?sessionId=s1&path=${encodeURIComponent(join(root, 'bin'))}`), deeper)
349
+ assert.equal(deeper.json().path, join(root, 'bin'))
350
+ assert.equal(deeper.json().parent, root)
351
+
352
+ const missing = fakeRes()
353
+ await __test.serveProxyBrowse(ctx(root), fakeReq('GET', `/dsh-ris-ide/proxy/browse?sessionId=s1&path=${encodeURIComponent(join(root, 'nope'))}`), missing)
354
+ assert.equal(missing.status, 400)
355
+ assert.match(String(missing.json().message), /无法读取目录/)
356
+ } finally {
357
+ rmSync(root, { recursive: true, force: true })
358
+ }
359
+ })
360
+
361
+ test('a started program only gets proxy env when an enabled rule names it', async () => {
362
+ const { mkdirSync, writeFileSync } = await import('node:fs')
363
+ const root = mkdtempSync(join(tmpdir(), 'ris-env-'))
364
+ try {
365
+ mkdirSync(process.env.DSH_RIS_IDE_PROXY_HOME, { recursive: true })
366
+ const rules = [
367
+ { id: 'java', program: 'java', hosts: '172.20.*', ports: '*', enabled: true, shadow: false, source: 'user', workspace: root },
368
+ { id: 'git', program: 'git', hosts: '172.20.*', ports: '*', enabled: false, shadow: false, source: 'user', workspace: root },
369
+ ]
370
+ writeFileSync(join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), JSON.stringify({ listenPort: 11081, socks: { host: '10.3.91.121', port: 1080 }, rules }))
371
+ const javaEnv = __test.proxyEnvFor({ name: 'java', kind: 'spring' }, root)
372
+ // A-M1: the injected address is the LOCAL listener, so every connection still
373
+ // passes the allow-list; handing out the upstream address would bypass it.
374
+ assert.equal(javaEnv.ALL_PROXY, 'http://127.0.0.1:11081')
375
+ assert.match(String(javaEnv.JAVA_TOOL_OPTIONS), /-Dhttp\.proxyHost=127\.0\.0\.1/)
376
+ // …unless the row explicitly asks to bind straight to the upstream SOCKS server.
377
+ rules[0].direct = true
378
+ writeFileSync(join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), JSON.stringify({ listenPort: 11081, socks: { host: '10.3.91.121', port: 1080 }, rules }))
379
+ const directEnv = __test.proxyEnvFor({ name: 'java', kind: 'spring' }, root)
380
+ assert.equal(directEnv.ALL_PROXY, 'socks5h://10.3.91.121:1080')
381
+ assert.match(String(directEnv.JAVA_TOOL_OPTIONS), /-DsocksProxyHost=10\.3\.91\.121/)
382
+ delete rules[0].direct
383
+ writeFileSync(join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), JSON.stringify({ listenPort: 11081, socks: { host: '10.3.91.121', port: 1080 }, rules }))
384
+ assert.deepEqual(__test.proxyEnvFor({ name: 'postgres', kind: 'other' }, root), {}, 'no rule → the program starts untouched')
385
+ assert.deepEqual(__test.proxyEnvFor({ name: 'git', kind: 'other' }, root), {}, 'a disabled rule injects nothing')
386
+ writeFileSync(join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), JSON.stringify({ listenPort: 11081, socks: { host: '', port: 0 }, rules }))
387
+ assert.deepEqual(__test.proxyEnvFor({ name: 'java', kind: 'spring' }, root), {}, 'no upstream → no injection')
388
+ } finally {
389
+ rmSync(root, { recursive: true, force: true })
390
+ }
391
+ })
392
+
393
+ test('the dialog saves the machine-wide table it was shown', async () => {
394
+ const wsA = mkdtempSync(join(tmpdir(), 'ris-ws-a-'))
395
+ const wsB = mkdtempSync(join(tmpdir(), 'ris-ws-b-'))
396
+ try {
397
+ // The file is machine-wide, so earlier tests in this file left rows behind.
398
+ writeFileSync(join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), JSON.stringify({ socks: { host: '', port: 0 }, listenPort: 11081, rules: [] }))
399
+ const save = async (ws, ruleOrRules) => {
400
+ const rules = Array.isArray(ruleOrRules) ? ruleOrRules : [ruleOrRules]
401
+ const res = fakeRes()
402
+ await __test.serveProxy(ctx(ws), fakeReq('POST', '/dsh-ris-ide/proxy', {
403
+ sessionId: 's1',
404
+ config: { socks: { host: '10.3.91.121', port: 1080 }, listenPort: 11081, rules },
405
+ }), res)
406
+ assert.equal(res.status, 200, JSON.stringify(res.json()))
407
+ return res.json()
408
+ }
409
+ await save(wsA, { id: 'a', program: 'navicat', hosts: '172.20.235.80', ports: '1521', enabled: true })
410
+ // The dialog always posts back the WHOLE table, so rows from both workspaces
411
+ // survive a save made from either one, each keeping its provenance.
412
+ const after = await save(wsB, [
413
+ { id: 'a', program: 'navicat', hosts: '172.20.235.80', ports: '1521', enabled: true, workspace: wsA },
414
+ { id: 'b', program: 'java', hosts: '172.20.235.*', ports: '1521,3306', enabled: true },
415
+ ])
416
+ assert.equal(after.shared, true)
417
+ const rules = readProxyConfig(wsB).rules
418
+ assert.deepEqual(rules.map((rule) => `${rule.workspace === wsA ? 'A' : rule.workspace === wsB ? 'B' : '?'}:${rule.id}`).sort(), ['A:a', 'B:b'])
419
+ assert.equal(rules.find((rule) => rule.id === 'a').enabled, true)
420
+ // A row missing from the payload was deleted by the human: the table shrinks.
421
+ const shrunk = await save(wsB, [{ id: 'b', program: 'java', hosts: '172.20.235.*', ports: '1521,3306', enabled: true }])
422
+ assert.deepEqual(shrunk.rules.filter((rule) => rule.source !== 'auto').map((rule) => rule.id), ['b'])
423
+ } finally {
424
+ rmSync(wsA, { recursive: true, force: true })
425
+ rmSync(wsB, { recursive: true, force: true })
426
+ }
427
+ })
428
+
429
+ test('the redirector actions export the machine table and never claim to have started what needs root', async () => {
430
+ const ws = mkdtempSync(join(tmpdir(), 'ris-ws-red-'))
431
+ // A stand-in CLI: the real one lives in the user's home and may not exist on a
432
+ // fresh machine, but the route's contract must not depend on that.
433
+ const cliDir = mkdtempSync(join(tmpdir(), 'ris-cli-'))
434
+ const cli = join(cliDir, 'ProxyBridge')
435
+ writeFileSync(cli, '#!/bin/sh\necho "ProxyBridge CLI V9.9.9"\n', { encoding: 'utf8' })
436
+ chmodSync(cli, 0o755)
437
+ process.env.DSH_RIS_IDE_PROXYBRIDGE = cli
438
+ try {
439
+ writeFileSync(join(process.env.DSH_RIS_IDE_PROXY_HOME, 'proxy.json'), JSON.stringify({ socks: { host: '10.3.91.121', port: 1080 }, listenPort: 11081, rules: [] }))
440
+ const saved = fakeRes()
441
+ await __test.serveProxy(ctx(ws), fakeReq('POST', '/dsh-ris-ide/proxy', {
442
+ sessionId: 's1',
443
+ config: {
444
+ socks: { host: '10.3.91.121', port: 1080 },
445
+ listenPort: 11081,
446
+ rules: [{ id: 'java-235', program: 'java', hosts: '172.20.235.*', ports: '1521', enabled: true }],
447
+ },
448
+ }), saved)
449
+ assert.equal(saved.status, 200, JSON.stringify(saved.json()))
450
+ assert.equal(typeof saved.json().redirector, 'object', 'the view carries ProxyBridge state for both sides')
451
+ assert.equal(saved.json().redirector.profilePath.endsWith('dsh-ris-ide.pbprofile'), true)
452
+
453
+ const res = fakeRes()
454
+ await __test.serveProxyAction(ctx(ws), fakeReq('POST', '/dsh-ris-ide/proxy/action', {
455
+ sessionId: 's1', action: 'redirector-sync',
456
+ }), res)
457
+ assert.equal(res.status, 200, JSON.stringify(res.json()))
458
+ const result = res.json().result
459
+ assert.equal(result.written.rules, 1, 'the enabled rule reached the profile')
460
+ // Starting it needs root/UAC; the route reports the command instead of lying.
461
+ assert.equal(result.started, false)
462
+ assert.match(result.command.display, /ProxyBridge/)
463
+ assert.match(result.command.display, /--profile/)
464
+ } finally {
465
+ delete process.env.DSH_RIS_IDE_PROXYBRIDGE
466
+ rmSync(ws, { recursive: true, force: true })
467
+ rmSync(cliDir, { recursive: true, force: true })
468
+ }
469
+ })
470
+
471
+ test('the dialog marks which programs need a loopback mapping', async () => {
472
+ const ws = mkdtempSync(join(tmpdir(), 'ris-ws-cap-'))
473
+ try {
474
+ writeProxyConfig(ws, {
475
+ socks: { host: '10.3.91.121', port: 1080 },
476
+ rules: [
477
+ { id: 'jdbc', program: 'jdbc', hosts: '172.20.235.80', ports: '1521', enabled: true, workspace: ws },
478
+ { id: 'java', program: 'java', hosts: '172.20.235.80', ports: '443', enabled: true, workspace: ws },
479
+ ],
480
+ })
481
+ const res = fakeRes()
482
+ await __test.serveProxy(ctx(ws), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
483
+ const byId = Object.fromEntries(res.json().rules.map((rule) => [rule.id, rule]))
484
+ assert.equal(byId.jdbc.socksCapable, false)
485
+ assert.equal(byId.jdbc.autoShadow, true, 'a JDBC client can only reach the tunnel through 127.0.0.1')
486
+ assert.equal(byId.jdbc.shadow, true, 'so the mapping is on by default')
487
+ assert.equal(byId.java.socksCapable, true)
488
+ assert.equal(byId.java.autoShadow, false, 'java is told the SOCKS address instead')
489
+ assert.equal(byId.java.shadow, false)
490
+ } finally {
491
+ rmSync(ws, { recursive: true, force: true })
492
+ }
493
+ })
494
+
495
+ test('a rule may name a program bare (any path) or a specific executable path', async () => {
496
+ const ws = mkdtempSync(join(tmpdir(), 'ris-ws-name-'))
497
+ try {
498
+ writeProxyConfig(ws, { socks: { host: '10.3.91.121', port: 1080 }, rules: [{ id: 'bare', program: 'java', hosts: '1.2.3.4', ports: '443', enabled: true, workspace: ws }] })
499
+ const bare = __test.proxyEnvFor({ name: 'java', exe: '/usr/lib/jvm/java-21/bin/java', command: '/usr/lib/jvm/java-21/bin/java -jar x.jar' }, ws)
500
+ assert.equal(bare.ALL_PROXY, 'http://127.0.0.1:11081', 'a bare program name matches whatever path it runs from')
501
+ assert.equal(__test.proxyEnvFor({ name: 'git' }, ws).ALL_PROXY, undefined, 'other programs stay untouched')
502
+
503
+ writeProxyConfig(ws, { socks: { host: '10.3.91.121', port: 1080 }, rules: [{ id: 'path', program: '/opt/tools/java', hosts: '1.2.3.4', ports: '443', enabled: true, workspace: ws }] })
504
+ assert.equal(__test.proxyEnvFor({ name: 'java', exe: '/usr/lib/jvm/java-21/bin/java' }, ws).ALL_PROXY, undefined, 'a path rule does not match a different executable')
505
+ assert.equal(__test.proxyEnvFor({ name: 'java', exe: '/opt/tools/java' }, ws).ALL_PROXY, 'http://127.0.0.1:11081', 'it matches the executable it names')
506
+ const windowsStyle = __test.proxyEnvFor({ name: 'java', exe: 'C:\\opt\\tools\\java.exe' }, ws)
507
+ assert.equal(windowsStyle.ALL_PROXY, undefined, 'separators are normalised, not string-compared')
508
+ } finally {
509
+ rmSync(ws, { recursive: true, force: true })
510
+ }
511
+ })
512
+
513
+ test('the run button only exists for rules we can actually inject', async () => {
514
+ const ws = mkdtempSync(join(tmpdir(), 'ris-ws-run-'))
515
+ try {
516
+ writeProxyConfig(ws, {
517
+ socks: { host: '10.3.91.121', port: 1080 },
518
+ rules: [
519
+ { id: 'java', program: 'java', hosts: '1.2.3.4', ports: '443', enabled: true, workspace: ws },
520
+ { id: 'navicat', program: 'navicat', hosts: '1.2.3.4', ports: '3306', enabled: true, workspace: ws },
521
+ ],
522
+ })
523
+ const res = fakeRes()
524
+ await __test.serveProxy(ctx(ws), fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
525
+ const byId = Object.fromEntries(res.json().rules.map((rule) => [rule.id, rule]))
526
+ assert.equal(byId.java.runnable, true, 'java can be started with the tunnel already in its environment')
527
+ assert.equal(byId.navicat.runnable, false, 'navicat gets no button: starting it would proxy nothing')
528
+ assert.equal(typeof byId.java.runLogPath, 'string')
529
+ assert.equal(byId.java.run, null, 'nothing of ours is running yet')
530
+ } finally {
531
+ rmSync(ws, { recursive: true, force: true })
532
+ }
533
+ })
534
+
535
+ test('starting a rule refuses what cannot be proxied, and unknown rules', async () => {
536
+ const ws = mkdtempSync(join(tmpdir(), 'ris-ws-run2-'))
537
+ try {
538
+ writeProxyConfig(ws, {
539
+ socks: { host: '10.3.91.121', port: 1080 },
540
+ rules: [
541
+ { id: 'off', program: 'java', hosts: '1.2.3.4', ports: '443', enabled: false, workspace: ws },
542
+ { id: 'jdbc', program: 'jdbc', hosts: '1.2.3.4', ports: '3306', enabled: true, workspace: ws },
543
+ ],
544
+ })
545
+ const act = async (body) => {
546
+ const res = fakeRes()
547
+ await __test.serveProxyAction(ctx(ws), fakeReq('POST', '/dsh-ris-ide/proxy/action', { sessionId: 's1', ...body }), res)
548
+ return res
549
+ }
550
+ assert.equal((await act({ action: 'run', ruleId: 'off' })).json().message.includes('未启用'), true)
551
+ assert.equal((await act({ action: 'run', ruleId: 'jdbc' })).json().message.includes('不支持 SOCKS'), true)
552
+ assert.equal((await act({ action: 'run', ruleId: 'nope' })).status, 404)
553
+ assert.equal((await act({ action: 'run' })).status, 400)
554
+ } finally {
555
+ rmSync(ws, { recursive: true, force: true })
556
+ }
557
+ })
558
+
559
+ test('the file browser can walk the Windows side and hands back Windows paths', async () => {
560
+ const { serveProxyBrowse, PROXY_BROWSE_PATH } = __test
561
+ const call = async (query) => {
562
+ const req = {
563
+ url: `${PROXY_BROWSE_PATH}${query}`,
564
+ method: 'GET',
565
+ headers: { host: '127.0.0.1:1' },
566
+ socket: { remoteAddress: '127.0.0.1' },
567
+ }
568
+ let payload = null
569
+ const res = { setHeader() {}, writeHead(status) { this.status = status }, end(body) { payload = JSON.parse(body) } }
570
+ await serveProxyBrowse({}, req, res, {})
571
+ return { status: res.status, payload }
572
+ }
573
+
574
+ const roots = await call('?side=windows')
575
+ // No session cwd is needed on that side: the tree starts at a drive root.
576
+ if (roots.status === 400) {
577
+ assert.match(roots.payload.message, /没有可浏览的 Windows 盘/)
578
+ return
579
+ }
580
+ assert.equal(roots.payload.side, 'windows')
581
+ assert.match(roots.payload.path, /^[A-Z]:\\/)
582
+ assert.ok(roots.payload.roots.length > 0)
583
+ assert.match(roots.payload.roots[0].path, /^[A-Z]:\\/)
584
+ // A click must write a Windows path into the rule, not /mnt/d/…
585
+ for (const entry of roots.payload.dirs) assert.match(entry.path, /^[A-Z]:\\/)
586
+
587
+ const bad = await call(`?side=windows&path=${encodeURIComponent('relative/dir')}`)
588
+ assert.equal(bad.status, 400)
589
+ assert.match(bad.payload.message, /需要盘符路径/)
590
+ })
591
+
592
+ test('the Windows program probe is cached and gets more than a cold-start budget', () => {
593
+ const source = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
594
+ // 4s was shorter than a cold PowerShell start, so the picker silently lost every
595
+ // Windows entry; the list is now cached so the probe is not repeated per open.
596
+ assert.match(source, /TIMEOUT_WINDOWS_PROGRAMS_MS = 12000/)
597
+ assert.match(source, /WINDOWS_PROGRAM_TTL_MS = 20000/)
598
+ assert.match(source, /windowsProgramCache = \{ at: Date.now\(\), names: \[\.\.\.names\] \}/)
599
+ })