dsh-ris-ide 1.7.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
package/lib/proxy.js ADDED
@@ -0,0 +1,1577 @@
1
+ /**
2
+ * Proxy engine: rules → local forwarders + a loopback CONNECT proxy that tunnels
3
+ * through ONE upstream SOCKS5 server.
4
+ *
5
+ * What a rule can do (design A — no drivers, no admin rights, any OS):
6
+ * - `program` decides WHO gets the proxy settings: rules are named after a
7
+ * program (`java.exe`, `git`, `node`, `curl`, `navicat.exe`) and the
8
+ * injection below only touches a program whose name matches a rule.
9
+ * - `hosts` (exact IP / hostname / `1.2.3.*` wildcard, comma separated) and
10
+ * `ports` (`5432`, `1000-1010`, comma separated) decide WHAT may go through
11
+ * the tunnel. Every axis is REQUIRED; a blank one rejects the whole row
12
+ * (fail-closed) — `*` is how "everything" is spelled.
13
+ * - Two mechanisms are derived from the enabled rules:
14
+ * 1. a loopback HTTP CONNECT proxy (`127.0.0.1:<listenPort>`) whose
15
+ * allow-list is the union of the rules — this is what makes wildcard
16
+ * hosts and port RANGES work at all, because the destination is only
17
+ * known per connection;
18
+ * 2. same-port shadow listeners (`127.0.0.1:<targetPort>` → SOCKS →
19
+ * `host:targetPort`) for rules whose hosts are literal IPs — that is
20
+ * what lets a program which only accepts a host/port (Navicat, a JDBC
21
+ * URL, …) reach the internal server by pointing its connection at
22
+ * 127.0.0.1 instead of the real IP.
23
+ * - `injection` returns the settings a launcher should apply for a program:
24
+ * env (`HTTP_PROXY`/`HTTPS_PROXY`/`ALL_PROXY` → the LOCAL loopback CONNECT
25
+ * proxy, so every connection is checked against the allow-list) and JVM
26
+ * flags (`-Dhttp.proxyHost`/`-Dhttps.proxyHost`; `-DsocksProxyHost` only for
27
+ * a `direct` row, because the CONNECT proxy is not a SOCKS server).
28
+ * `git` gets a scoped `git config` entry instead of a command-line flag, so
29
+ * every git caller (including other plugins) picks it up.
30
+ *
31
+ * The engine is deliberately free of any DSH/host dependency: the plugin loads
32
+ * it as a module, and `node lib/proxy.js …` runs it as a CLI (that is how
33
+ * dsh-ris-yds borrows it without duplicating the tunnel code).
34
+ *
35
+ * SECURITY: listening sockets are loopback-only and the CONNECT proxy answers
36
+ * loopback peers only. The allow-list is enforced per destination — but it is
37
+ * the union of all rules, because an HTTP proxy cannot tell which local program
38
+ * opened a connection.
39
+ */
40
+
41
+ import { execFileSync, spawn, spawnSync as spawnSyncImpl } from 'node:child_process'
42
+ import { appendFileSync, closeSync, existsSync, watchFile, mkdirSync, openSync, readFileSync, readSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
43
+ import { createServer, connect as netConnect } from 'node:net'
44
+ import { homedir } from 'node:os'
45
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
46
+ import { fileURLToPath } from 'node:url'
47
+
48
+ /**
49
+ * ONE engine and ONE config per machine, not per workspace.
50
+ *
51
+ * A loopback port is a machine-level resource, so "two workspaces, two engines"
52
+ * could never work: the second bind fails, and a program that both workspaces
53
+ * share (java, git) cannot be told apart per workspace anyway. Sharing the file
54
+ * lets every workspace add its own rows (`rule.workspace`) while the ports are
55
+ * bound exactly once.
56
+ */
57
+ export const PROXY_HOME_DIRNAME = '.dsh-ris-ide'
58
+ export const PROXY_FILENAME = 'proxy.json'
59
+ export const PROXY_PID_FILENAME = 'proxy.pid'
60
+ export const PROXY_LOG_FILENAME = 'proxy-forward.log'
61
+
62
+ /**
63
+ * Directory holding the shared config, pidfile and log.
64
+ *
65
+ * `DSH_RIS_IDE_PROXY_HOME` overrides it — tests need an isolated home, and a
66
+ * user may want the state on another disk.
67
+ * @returns absolute directory (may not exist yet).
68
+ */
69
+ export function proxyHomeDir() {
70
+ const override = typeof process.env.DSH_RIS_IDE_PROXY_HOME === 'string' ? process.env.DSH_RIS_IDE_PROXY_HOME.trim() : ''
71
+ if (override !== '') return resolve(override)
72
+ return join(homedir(), PROXY_HOME_DIRNAME)
73
+ }
74
+
75
+ /**
76
+ * Programs that can be *told* to use SOCKS from the command line or an env var.
77
+ * Anything not listed here (Navicat, the mysql/JDBC clients, …) can only reach
78
+ * the tunnel through a same-port loopback mapping, which is why new rows default
79
+ * to mapped for those and unmapped for these.
80
+ */
81
+ export const SOCKS_CAPABLE_PROGRAMS = Object.freeze([
82
+ 'java', 'javaw', 'mvn', 'gradle', 'node', 'npm', 'npx', 'git', 'curl', 'python', 'python3', 'bash', 'sh', 'zsh',
83
+ ])
84
+ /** Marker carried in the forwarder's argv; the ONLY thing that makes a pid ours. */
85
+ export const PROXY_MARKER = 'dsh-ris-ide-proxy'
86
+ /** Which OS this process runs on — the loopback-mapping and pid checks differ. */
87
+ export const IS_WINDOWS = process.platform === 'win32'
88
+
89
+ /**
90
+ * Which side of the OS boundary this engine runs on. `wsl` matters because a
91
+ * loopback listener started here is NOT the loopback a Windows program sees:
92
+ * 127.0.0.1 means "this side", so a Windows client must be handed the real
93
+ * proxy address instead of a 127.0.0.1 mapping.
94
+ * @returns `'windows' | 'wsl' | 'linux' | 'macos'`.
95
+ */
96
+ export function engineSide() {
97
+ if (IS_WINDOWS) return 'windows'
98
+ if (process.platform === 'darwin') return 'macos'
99
+ try {
100
+ if (/microsoft/i.test(readFileSync('/proc/version', 'utf8'))) return 'wsl'
101
+ } catch { /* not readable: treat as plain linux */ }
102
+ return 'linux'
103
+ }
104
+
105
+ /** Default loopback port of the CONNECT proxy. */
106
+ export const DEFAULT_LISTEN_PORT = 11081
107
+ /** A rule row is cheap; a thousand of them is a typo, not a setup. */
108
+ export const MAX_RULES = 200
109
+ /** Cap on derived same-port listeners (each one holds a local port). */
110
+ export const MAX_SHADOW_TARGETS = 64
111
+ const SOCKS_CONNECT_TIMEOUT_MS = 15000
112
+ const HEADER_MAX_BYTES = 16 * 1024
113
+
114
+ /* ------------------------------------------------------------------ rules -- */
115
+
116
+ /**
117
+ * The rows a workspace starts with: generated, NOT enabled, never persisted —
118
+ * the dialog adds them for the current workspace when it has no row for that
119
+ * program yet, so a shared config does not accumulate four dead rows per
120
+ * workspace that ever opened the dialog.
121
+ * @param workspace - workspace label the rows are shown for.
122
+ * @returns four rule stubs.
123
+ */
124
+ export const AUTO_PROGRAMS = Object.freeze(['java', 'git'])
125
+
126
+ export function autoRules(workspace = '') {
127
+ return AUTO_PROGRAMS.map((program) => ({
128
+ id: `auto-${program}`,
129
+ program,
130
+ hosts: '',
131
+ ports: '',
132
+ enabled: false,
133
+ shadow: false,
134
+ source: 'auto',
135
+ workspace,
136
+ }))
137
+ }
138
+
139
+ /**
140
+ * Parse `1.2.3.4, 10.0.0.*, gitlab.example.com` into matchable patterns.
141
+ * `*` is the only wildcard and stands for a whole dotted segment (or a prefix).
142
+ * @param spec - the rule's raw `hosts` text.
143
+ * @returns `{ patterns, invalid }` — patterns in input order, rejected fragments verbatim.
144
+ */
145
+ export function parseHostSpec(spec) {
146
+ const patterns = []
147
+ const invalid = []
148
+ const text = typeof spec === 'string' ? spec : ''
149
+ for (const raw of text.split(',')) {
150
+ const item = raw.trim()
151
+ if (item === '') continue
152
+ // A pattern is host-shaped: letters/digits/dots/dashes/underscores plus `*`.
153
+ if (!/^[A-Za-z0-9*]([A-Za-z0-9.*_-]*[A-Za-z0-9*])?$/.test(item)) {
154
+ invalid.push(item)
155
+ continue
156
+ }
157
+ if (!patterns.includes(item)) patterns.push(item)
158
+ }
159
+ return { patterns, invalid }
160
+ }
161
+
162
+ /**
163
+ * Parse `5432, 1000-1010` into a sorted, de-duplicated port list.
164
+ * @param spec - the rule's raw `ports` text.
165
+ * @returns `{ ports, invalid }` — ports are integers 1…65535.
166
+ */
167
+ export function parsePortSpec(spec) {
168
+ const ports = new Set()
169
+ const invalid = []
170
+ const text = typeof spec === 'string' ? spec : ''
171
+ for (const raw of text.split(',')) {
172
+ const item = raw.trim()
173
+ if (item === '') continue
174
+ const range = /^(\d{1,5})\s*-\s*(\d{1,5})$/.exec(item)
175
+ if (range !== null) {
176
+ const from = Number(range[1])
177
+ const to = Number(range[2])
178
+ if (from < 1 || to > 65535 || from > to) {
179
+ invalid.push(item)
180
+ continue
181
+ }
182
+ for (let port = from; port <= to; port += 1) ports.add(port)
183
+ continue
184
+ }
185
+ // `*` is the explicit "every port"; an EMPTY spec is not the same thing — a rule
186
+ // without a port range does not apply at all (the dialog says so), because a
187
+ // silently unrestricted rule is how a proxy leaks.
188
+ if (item === '*') {
189
+ ports.add(0)
190
+ continue
191
+ }
192
+ if (/^\d{1,5}$/.test(item)) {
193
+ const port = Number(item)
194
+ if (port >= 1 && port <= 65535) {
195
+ ports.add(port)
196
+ continue
197
+ }
198
+ }
199
+ invalid.push(item)
200
+ }
201
+ return { ports: [...ports].sort((a, b) => a - b), invalid }
202
+ }
203
+
204
+ /**
205
+ * Does one host pattern match one concrete host?
206
+ * `1.2.3.*` matches `1.2.3.4`; `*.example.com` matches `a.example.com`; an exact
207
+ * string matches case-insensitively (DNS names are case-insensitive).
208
+ * @param pattern - a pattern from {@link parseHostSpec}.
209
+ * @param host - the destination host (IP literal or DNS name).
210
+ * @returns true when the pattern covers the host.
211
+ */
212
+ export function hostMatches(pattern, host) {
213
+ if (typeof pattern !== 'string' || pattern === '' || typeof host !== 'string' || host === '') return false
214
+ if (pattern === '*') return true
215
+ if (!pattern.includes('*')) return pattern.toLowerCase() === host.toLowerCase()
216
+ const escaped = pattern
217
+ .toLowerCase()
218
+ .split('*')
219
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
220
+ .join('.*')
221
+ return new RegExp(`^${escaped}$`).test(host.toLowerCase())
222
+ }
223
+
224
+ /**
225
+ * Whether a rule can actually do something.
226
+ *
227
+ * A rule only applies when it is enabled AND names a program AND names a host
228
+ * pattern AND names a port pattern: every axis is explicit, and "match
229
+ * everything" is spelled `*` rather than left blank. A blank axis used to mean
230
+ * "unrestricted", which is indistinguishable from a half-written row — and a
231
+ * half-written row that silently proxies everything is worse than one that does
232
+ * nothing.
233
+ * @param rule - a normalised rule.
234
+ * @returns `{ effective: boolean, reason: string }` — reason is user-facing text.
235
+ */
236
+ export function ruleEffectiveness(rule) {
237
+ const program = typeof rule?.program === 'string' ? rule.program.trim() : ''
238
+ const hostSpec = typeof rule?.hosts === 'string' ? rule.hosts.trim() : ''
239
+ const portSpec = typeof rule?.ports === 'string' ? rule.ports.trim() : ''
240
+ const hosts = parseHostSpec(hostSpec)
241
+ const ports = parsePortSpec(portSpec)
242
+ if (rule?.enabled !== true) return { effective: false, reason: '未启用' }
243
+ if (program === '') return { effective: false, reason: '缺程序' }
244
+ if (hostSpec === '' || hosts.patterns.length === 0) return { effective: false, reason: '缺 IP(全匹配写 *)' }
245
+ if (hosts.invalid.length > 0) return { effective: false, reason: 'IP 有无效片段' }
246
+ if (portSpec === '' || ports.ports.length === 0) return { effective: false, reason: '缺端口(全匹配写 *)' }
247
+ if (ports.invalid.length > 0) return { effective: false, reason: '端口有无效片段' }
248
+ return { effective: true, reason: '' }
249
+ }
250
+
251
+ /** Whether an IPv4 literal (no DNS name) — the only thing a shadow listener can target. */
252
+ export function isIpv4Literal(host) {
253
+ return typeof host === 'string' && /^\d{1,3}(\.\d{1,3}){3}$/.test(host)
254
+ }
255
+
256
+ /**
257
+ * Keep a rule's per-workspace ownership map (`yds` writes it, review D-P0-1).
258
+ * Rebuilding rules from a fixed field list dropped it, so `yds stop` could no
259
+ * longer withdraw only its own rows after the config made one round trip.
260
+ *
261
+ * Lives at module scope because both `normalizeConfig` (read path) and
262
+ * `mergeConfigs` (write path) have to preserve it.
263
+ * @param raw - stored `owners` value (object of per-workspace shares).
264
+ * @returns the whitelisted map, or `undefined` when empty/unusable.
265
+ */
266
+ export function normalizeOwners(raw) {
267
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
268
+ const owners = {}
269
+ for (const [key, entry] of Object.entries(raw)) {
270
+ // Keys are opaque: a workspace path, or the driver's reserved `'<legacy>'`
271
+ // bucket for rows migrated from before owners existed. Never normalise a key
272
+ // (and never drop `'<legacy>'`) — only the driver may interpret them.
273
+ if (key === '' || entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue
274
+ const ownerProgram = typeof entry.program === 'string' ? entry.program.trim() : ''
275
+ if (ownerProgram === '') continue
276
+ const list = (value) => (Array.isArray(value) ? value.join(',') : typeof value === 'string' ? value.trim() : '')
277
+ owners[key] = {
278
+ program: ownerProgram,
279
+ hosts: list(entry.hosts),
280
+ ports: list(entry.ports),
281
+ enabled: entry.enabled === true,
282
+ shadow: entry.shadow === true,
283
+ direct: entry.direct === true,
284
+ }
285
+ }
286
+ return Object.keys(owners).length > 0 ? owners : undefined
287
+ }
288
+
289
+ /**
290
+ * Normalise a stored config (or `undefined`) into the shape the engine uses.
291
+ * Unknown fields are dropped, rule rows are validated, and the four auto rows
292
+ * are appended when the stored file predates them.
293
+ * @param raw - parsed JSON (may be null/garbage).
294
+ * @returns the effective config.
295
+ */
296
+ export function normalizeConfig(raw) {
297
+ const source = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
298
+ const socksRaw = source.socks !== null && typeof source.socks === 'object' ? source.socks : {}
299
+ const host = typeof socksRaw.host === 'string' ? socksRaw.host.trim() : ''
300
+ const port = Number(socksRaw.port)
301
+ const listenPort = Number(source.listenPort)
302
+ // Loopback mapping targets that belong to the FALLBACK path, not to the rule
303
+ // table: when ProxyBridge cannot run, some client (a JDBC driver, Navicat) can
304
+ // only be pointed at 127.0.0.1, so the engine binds a listener per destination.
305
+ // Keeping them out of `rules` means the table stays "what should be proxied"
306
+ // and the user never sees an implementation detail there.
307
+ const shadows = []
308
+ const rawShadows = Array.isArray(source.shadows) ? source.shadows : []
309
+ for (const item of rawShadows.slice(0, MAX_SHADOW_TARGETS)) {
310
+ if (item === null || typeof item !== 'object') continue
311
+ const host = typeof item.host === 'string' ? item.host.trim() : ''
312
+ const port = Number(item.port)
313
+ const localPort = Number(item.localPort)
314
+ if (!isIpv4Literal(host) || !Number.isInteger(port) || port < 1 || port > 65535) continue
315
+ const listen = Number.isInteger(localPort) && localPort > 1023 && localPort < 65536 ? localPort : port
316
+ if (shadows.some((entry) => entry.host === host && entry.port === port && entry.localPort === listen)) continue
317
+ shadows.push({ host, port, localPort: listen })
318
+ }
319
+ const rules = []
320
+ const rawRules = Array.isArray(source.rules) ? source.rules : []
321
+ for (const item of rawRules.slice(0, MAX_RULES)) {
322
+ if (item === null || typeof item !== 'object') continue
323
+ const id = typeof item.id === 'string' && item.id !== '' ? item.id : `rule-${rules.length + 1}`
324
+ const program = typeof item.program === 'string' ? item.program.trim() : ''
325
+ const hostSpec = typeof item.hosts === 'string' ? item.hosts.trim() : ''
326
+ const portSpec = typeof item.ports === 'string' ? item.ports.trim() : ''
327
+ const enabled = item.enabled === true
328
+ const hostsParsed = parseHostSpec(hostSpec).patterns
329
+ const portsParsed = parsePortSpec(portSpec).ports
330
+ const bindable = hostsParsed.length > 0 && hostsParsed.every(isIpv4Literal) && portsParsed.length > 0
331
+ // A program that speaks SOCKS needs no mapping; one that cannot is only
332
+ // reachable through a same-port loopback listener, so it gets one unless the
333
+ // stored file says otherwise (an explicit true/false always wins).
334
+ const shadow = typeof item.shadow === 'boolean' ? item.shadow : bindable && !isSocksCapableProgram(program)
335
+ if (program === '' && hostSpec === '' && portSpec === '') continue
336
+ // Migration: the starter rows used to include `node` and `curl`; they are not
337
+ // offered any more, so drop a stored one instead of leaving an empty row the
338
+ // dialog can no longer create (a user's OWN node/curl row is kept — its source
339
+ // is not `auto`).
340
+ if (item.source === 'auto' && AUTO_PROGRAMS.includes(programKey(program)) !== true) continue
341
+ rules.push({
342
+ id,
343
+ // A human label the provider of the row supplies ("YonCode java"); the dialog
344
+ // and the ProxyBridge profile show it instead of the raw id.
345
+ label: typeof item.label === 'string' ? item.label.trim().slice(0, 60) : '',
346
+ program,
347
+ hosts: hostSpec,
348
+ ports: portSpec,
349
+ enabled,
350
+ // Loopback mapping only helps a client that CANNOT take a proxy address,
351
+ // and only when that client runs on this side of the OS boundary (a
352
+ // Windows program cannot reach a WSL 127.0.0.1).
353
+ shadow,
354
+ // Opt-out from the allow-list: `direct` hands the program the upstream
355
+ // SOCKS address instead of this engine's CONNECT proxy. Defaults to false
356
+ // — an old config file (no field) must keep the enforced path — and only
357
+ // a literal `true` enables it.
358
+ direct: item.direct === true,
359
+ source: typeof item.source === 'string' ? item.source : 'user',
360
+ // Which workspace contributed this row ('' = the generated defaults, which
361
+ // belong to the machine). Provenance only — the table itself is machine-wide
362
+ // and a save replaces it (m10585), so this is not scoping.
363
+ workspace: typeof item.workspace === 'string' ? item.workspace : '',
364
+ // Which OS side a driven row is meant for. ProxyBridge matches by image name
365
+ // and `java.exe` never matches the Linux `java` (m10585), so a driver emits
366
+ // one row per side and the page labels it; '' means "either side".
367
+ side: item.side === 'local' || item.side === 'windows' ? item.side : '',
368
+ // Per-workspace shares of a merged row (driven rows only). The daemon never
369
+ // interprets it; it must survive a read→write round trip or the driver loses
370
+ // the ability to withdraw one workspace's endpoints.
371
+ owners: normalizeOwners(item.owners),
372
+ })
373
+ }
374
+ // The table is MACHINE-level: ProxyBridge hooks the kernel and matches by
375
+ // process name, so a rule cannot be scoped to a workspace or a session. The
376
+ // `workspace` field is therefore a provenance label only, never part of a
377
+ // rule's identity:
378
+ // - generated/user rows are one switch per PROGRAM for the whole machine, so
379
+ // opening the dialog from another workspace cannot add a second `java` row;
380
+ // - driven (`yds`) rows describe ENDPOINTS, not programs — several may share
381
+ // the `jdbc` label and each is a distinct destination — so they keep their id.
382
+ const seen = new Set()
383
+ const deduped = []
384
+ for (const rule of rules) {
385
+ const key = rule.source === 'yds' ? `yds\u0000${rule.id}` : `prog\u0000${programKey(rule.program)}`
386
+ if (programKey(rule.program) !== '' && seen.has(key)) continue
387
+ seen.add(key)
388
+ deduped.push(rule)
389
+ }
390
+ return {
391
+ socks: {
392
+ host,
393
+ port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 0,
394
+ },
395
+ listenPort: Number.isInteger(listenPort) && listenPort > 1023 && listenPort < 65536 ? listenPort : DEFAULT_LISTEN_PORT,
396
+ rules: deduped,
397
+ shadows,
398
+ }
399
+ }
400
+
401
+ /**
402
+ * The allow-list of every ENABLED, effective rule. A rule contributes only its
403
+ * parsed axes; a row with a blank axis contributes nothing (see
404
+ * {@link ruleEffectiveness}).
405
+ * @param config - a normalised config.
406
+ * @returns `{ hostPatterns: string[], ports: number[] }` — either list empty ⇒
407
+ * DENY everything (fail-closed; "allow everything" is spelled `*`).
408
+ */
409
+ export function allowList(config) {
410
+ const hostPatterns = []
411
+ const ports = new Set()
412
+ for (const rule of config.rules) {
413
+ // A half-written row contributes nothing: every axis must be explicit.
414
+ if (ruleEffectiveness(rule).effective !== true) continue
415
+ for (const pattern of parseHostSpec(rule.hosts).patterns) {
416
+ if (!hostPatterns.includes(pattern)) hostPatterns.push(pattern)
417
+ }
418
+ for (const port of parsePortSpec(rule.ports).ports) ports.add(port)
419
+ }
420
+ return { hostPatterns, ports: [...ports].sort((a, b) => a - b) }
421
+ }
422
+
423
+ /**
424
+ * Whether the allow-list admits a destination.
425
+ * @param allow - result of {@link allowList}.
426
+ * @param host - destination host.
427
+ * @param port - destination port.
428
+ * @returns true when the connection may be tunnelled.
429
+ */
430
+ export function allowAdmits(allow, host, port) {
431
+ if (allow.hostPatterns.length === 0) return false
432
+ if (!allow.hostPatterns.some((pattern) => hostMatches(pattern, host))) return false
433
+ if (allow.ports.length === 0) return false
434
+ return allow.ports.includes(0) || allow.ports.includes(Number(port))
435
+ }
436
+
437
+ /**
438
+ * Same-port shadow listeners derived from the enabled rules: only literal-IPv4
439
+ * destinations can be pre-bound, and the local port equals the remote one so a
440
+ * program only has to replace the host with `127.0.0.1`.
441
+ * @param config - a normalised config.
442
+ * @returns `[{ host, port, localPort }]` capped at {@link MAX_SHADOW_TARGETS}.
443
+ */
444
+ export function shadowTargets(config) {
445
+ const seen = new Set()
446
+ const targets = []
447
+ // Explicit fallback list (written by a client plugin such as dsh-ris-yds) first.
448
+ for (const entry of Array.isArray(config.shadows) ? config.shadows : []) {
449
+ const key = `${entry.host}:${entry.port}`
450
+ if (seen.has(key)) continue
451
+ seen.add(key)
452
+ targets.push({ host: entry.host, port: entry.port, localPort: entry.localPort })
453
+ if (targets.length >= MAX_SHADOW_TARGETS) return targets
454
+ }
455
+ // Rules may still request a mapping themselves (opt-in per row).
456
+ for (const rule of config.rules) {
457
+ if (!rule.enabled || rule.shadow !== true) continue
458
+ const hosts = parseHostSpec(rule.hosts).patterns.filter(isIpv4Literal)
459
+ const ports = parsePortSpec(rule.ports).ports
460
+ for (const host of hosts) {
461
+ for (const port of ports) {
462
+ const key = `${host}:${port}`
463
+ if (seen.has(key)) continue
464
+ seen.add(key)
465
+ targets.push({ host, port, localPort: port })
466
+ if (targets.length >= MAX_SHADOW_TARGETS) return targets
467
+ }
468
+ }
469
+ }
470
+ return targets
471
+ }
472
+
473
+ /** Loopback destinations that must never be sent through the tunnel. */
474
+ export const DEFAULT_NO_PROXY = 'localhost,127.0.0.1,::1'
475
+
476
+ /**
477
+ * Which side of the OS boundary a program runs on.
478
+ * `'local'` (the default) — and `engineSide()`'s own value — means "this
479
+ * machine"; anything else means the other side (e.g. `'windows'` when this
480
+ * engine runs in WSL, or `'wsl'` when the caller is the Windows-side launcher).
481
+ * @param options - `{ side }` from {@link injectionFor}.
482
+ * @returns `'local'` or `'remote'`.
483
+ */
484
+ function injectionSide(options) {
485
+ const raw = typeof options?.side === 'string' ? options.side.trim().toLowerCase() : ''
486
+ if (raw === '' || raw === 'local') return 'local'
487
+ if (raw === engineSide()) return 'local'
488
+ return 'remote'
489
+ }
490
+
491
+ /**
492
+ * What a launcher should apply for one program: the rule whose `program` names
493
+ * it (exact, case-insensitive, extension-insensitive) must be ENABLED.
494
+ *
495
+ * The default injected address is the LOCAL loopback CONNECT proxy
496
+ * (`http://127.0.0.1:<listenPort>`), NOT the upstream SOCKS server: every
497
+ * connection a started program makes then passes through the engine's
498
+ * allow-list, which is what enforces the rule's `hosts`/`ports`. Handing out
499
+ * `ALL_PROXY=socks5h://<upstream>` would let the program reach anything the
500
+ * SOCKS server can, silently ignoring both axes.
501
+ *
502
+ * A row that explicitly sets `direct: true` opts out and gets the upstream
503
+ * SOCKS address (plus the JVM `-DsocksProxyHost` switch it needs). `direct`
504
+ * defaults to false — including for every config file written before the field
505
+ * existed — so the enforced path is the default. The JVM's `-DsocksProxyHost`
506
+ * cannot point at an HTTP proxy, so the local path uses the HTTP proxy flags
507
+ * only (Java ignores proxy env vars by default).
508
+ *
509
+ * Fail-closed rules:
510
+ * - no enabled rule for the program, no configured upstream, or a program that
511
+ * cannot be told a proxy address at all (not in
512
+ * {@link SOCKS_CAPABLE_PROGRAMS}: a JDBC driver, Navicat) ⇒ `null` — the
513
+ * latter can only reach the tunnel through a same-port `127.0.0.1` shadow
514
+ * listener;
515
+ * - a rule that is not effective ⇒ an object whose `env`/`jvmArgs` are empty
516
+ * plus a user-facing `reason` (the caller injects nothing).
517
+ *
518
+ * A program on the OTHER side of the OS boundary cannot reach this machine's
519
+ * 127.0.0.1, so a non-direct row injects nothing there either; `direct` is the
520
+ * variant that also works across the boundary (it needs no local listener).
521
+ *
522
+ * @param program - program name or path (`java.exe`, `/usr/bin/node`, `git`).
523
+ * @param config - a normalised config.
524
+ * @param options - `{ side }`; `'local'` (default) or `engineSide()`'s value
525
+ * means "this machine"; anything else is the other side.
526
+ * @returns `null` when no proxy applies, else
527
+ * `{ program, side, direct, env, jvmArgs, socksUrl, httpProxyUrl, listenPort, reason }`.
528
+ */
529
+ export function injectionFor(program, config, options = {}) {
530
+ const wanted = programKey(program)
531
+ if (wanted === '') return null
532
+ // A client that cannot be told a proxy address is not helped by a proxy URL;
533
+ // it needs a 127.0.0.1 listener (see `shadowTargets`).
534
+ if (isSocksCapableProgram(wanted) !== true) return null
535
+ const rule = config.rules.find((item) => item.enabled && programKey(item.program) === wanted)
536
+ if (rule === undefined) return null
537
+ if (config.socks.host === '' || config.socks.port === 0) return null
538
+ const side = injectionSide(options)
539
+ const direct = rule.direct === true
540
+ const socksUrl = `socks5h://${config.socks.host}:${config.socks.port}`
541
+ const base = {
542
+ program: wanted,
543
+ side,
544
+ direct,
545
+ env: {},
546
+ jvmArgs: [],
547
+ socksUrl,
548
+ httpProxyUrl: null,
549
+ listenPort: config.listenPort,
550
+ reason: '',
551
+ }
552
+ const effectiveness = ruleEffectiveness(rule)
553
+ if (effectiveness.effective !== true) {
554
+ return { ...base, reason: `规则不完整,未注入:${effectiveness.reason}` }
555
+ }
556
+ if (direct === true) {
557
+ // Explicit opt-out from the allow-list: reproduce the pre-M1 behaviour of
558
+ // binding the program straight to the upstream SOCKS server.
559
+ return {
560
+ ...base,
561
+ env: {
562
+ ALL_PROXY: socksUrl,
563
+ all_proxy: socksUrl,
564
+ HTTP_PROXY: socksUrl,
565
+ HTTPS_PROXY: socksUrl,
566
+ http_proxy: socksUrl,
567
+ https_proxy: socksUrl,
568
+ },
569
+ jvmArgs: [
570
+ `-DsocksProxyHost=${config.socks.host}`,
571
+ `-DsocksProxyPort=${config.socks.port}`,
572
+ ],
573
+ }
574
+ }
575
+ if (side === 'remote') {
576
+ return {
577
+ ...base,
578
+ reason: '程序在系统边界的另一侧,本机回环代理不可达;如确需直连上游请把该行设为 direct',
579
+ }
580
+ }
581
+ const httpProxyUrl = `http://127.0.0.1:${config.listenPort}`
582
+ return {
583
+ ...base,
584
+ httpProxyUrl,
585
+ env: {
586
+ ALL_PROXY: httpProxyUrl,
587
+ all_proxy: httpProxyUrl,
588
+ HTTP_PROXY: httpProxyUrl,
589
+ HTTPS_PROXY: httpProxyUrl,
590
+ http_proxy: httpProxyUrl,
591
+ https_proxy: httpProxyUrl,
592
+ NO_PROXY: DEFAULT_NO_PROXY,
593
+ no_proxy: DEFAULT_NO_PROXY,
594
+ },
595
+ jvmArgs: [
596
+ '-Dhttp.proxyHost=127.0.0.1',
597
+ `-Dhttp.proxyPort=${config.listenPort}`,
598
+ '-Dhttps.proxyHost=127.0.0.1',
599
+ `-Dhttps.proxyPort=${config.listenPort}`,
600
+ '-Dhttp.nonProxyHosts=localhost|127.*|[::1]',
601
+ ],
602
+ }
603
+ }
604
+
605
+ /** Normalise a program name/path to its bare, lower-case key (`C:\\…\\node.exe` → `node`). */
606
+ export function programKey(program) {
607
+ if (typeof program !== 'string') return ''
608
+ const base = program.replace(/\\/g, '/').split('/').pop() ?? ''
609
+ return base.trim().toLowerCase().replace(/\.(exe|cmd|bat|sh)$/, '')
610
+ }
611
+
612
+ /**
613
+ * Whether a program accepts a SOCKS address directly (`-DsocksProxyHost`,
614
+ * `ALL_PROXY`, `http.proxy=socks5h://…`).
615
+ * @param program - executable name or absolute path.
616
+ * @returns true when the program is known to speak SOCKS.
617
+ */
618
+ export function isSocksCapableProgram(program) {
619
+ const key = programKey(program)
620
+ return key !== '' && SOCKS_CAPABLE_PROGRAMS.includes(key)
621
+ }
622
+
623
+ /* ------------------------------------------------------------------- I/O -- */
624
+
625
+ /** Absolute path of the ONE shared proxy config. */
626
+ export function proxyConfigPath() {
627
+ return join(proxyHomeDir(), PROXY_FILENAME)
628
+ }
629
+
630
+ /** Absolute path of the shared pidfile. */
631
+ export function proxyPidPath() {
632
+ return join(proxyHomeDir(), PROXY_PID_FILENAME)
633
+ }
634
+
635
+ /** Absolute path of the shared engine log. */
636
+ export function proxyLogPath() {
637
+ return join(proxyHomeDir(), PROXY_LOG_FILENAME)
638
+ }
639
+
640
+ /**
641
+ * Read + normalise the shared proxy config (missing/garbage ⇒ defaults).
642
+ * @param _workspace - ignored for storage; kept so callers can pass the workspace
643
+ * without caring that the file is machine-level. Rows carry their own label.
644
+ */
645
+ export function readProxyConfig(workspace) {
646
+ const path = proxyConfigPath()
647
+ if (existsSync(path)) {
648
+ try {
649
+ return normalizeConfig(parseJsonc(readFileSync(path, 'utf8')))
650
+ } catch {
651
+ return normalizeConfig(undefined)
652
+ }
653
+ }
654
+ // Migration: engines before the shared-config change kept the file inside the
655
+ // workspace. Read it (labelled with that workspace) so an existing setup keeps
656
+ // its rules; the next save writes the merged result to the shared file.
657
+ if (typeof workspace === 'string' && workspace !== '') {
658
+ const legacy = join(workspace, '.dsh-ris-ide', PROXY_FILENAME)
659
+ if (existsSync(legacy)) {
660
+ try {
661
+ const migrated = normalizeConfig(parseJsonc(readFileSync(legacy, 'utf8')))
662
+ return Object.assign({}, migrated, {
663
+ rules: migrated.rules.map((rule) => (rule.workspace === '' ? Object.assign({}, rule, { workspace }) : rule)),
664
+ })
665
+ } catch { /* fall through to defaults */ }
666
+ }
667
+ }
668
+ return normalizeConfig(undefined)
669
+ }
670
+
671
+ /** Write the shared config atomically (0600: it names internal hosts and a tunnel). */
672
+ export function writeProxyConfig(_workspace, raw) {
673
+ const config = normalizeConfig(raw)
674
+ const path = proxyConfigPath()
675
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
676
+ const tmp = `${path}.${process.pid}.tmp`
677
+ writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
678
+ renameSync(tmp, path)
679
+ return config
680
+ }
681
+
682
+ /**
683
+ * Tolerant JSONC parse (comments + trailing commas), because the config file is
684
+ * hand-editable and the rest of the plugin already writes JSONC headers.
685
+ * @param text - file content.
686
+ * @returns the parsed value (null when the text is empty/garbage).
687
+ */
688
+ export function parseJsonc(text) {
689
+ const source = String(text ?? '').replace(/^\uFEFF/, '')
690
+ let out = ''
691
+ let inString = false
692
+ let quote = ''
693
+ for (let index = 0; index < source.length; index += 1) {
694
+ const char = source[index]
695
+ const next = source[index + 1]
696
+ if (inString) {
697
+ out += char
698
+ if (char === '\\') {
699
+ out += next ?? ''
700
+ index += 1
701
+ } else if (char === quote) {
702
+ inString = false
703
+ }
704
+ continue
705
+ }
706
+ if (char === '"' || char === "'") {
707
+ inString = true
708
+ quote = char
709
+ out += char
710
+ continue
711
+ }
712
+ if (char === '/' && next === '/') {
713
+ while (index < source.length && source[index] !== '\n') index += 1
714
+ out += '\n'
715
+ continue
716
+ }
717
+ if (char === '/' && next === '*') {
718
+ index += 2
719
+ while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) index += 1
720
+ index += 1
721
+ continue
722
+ }
723
+ out += char
724
+ }
725
+ try {
726
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'))
727
+ } catch {
728
+ return null
729
+ }
730
+ }
731
+
732
+ /* ---------------------------------------------------------------- tunnel -- */
733
+
734
+ /**
735
+ * Open one SOCKS5 connection (no auth) and hand back the raw socket.
736
+ * @param socks - `{ host, port }` of the upstream SOCKS server.
737
+ * @param host - destination host (IP literal or DNS name).
738
+ * @param port - destination port.
739
+ * @returns a promise for the connected socket.
740
+ */
741
+ export function connectSocks(socks, host, port) {
742
+ return new Promise((resolvePromise, rejectPromise) => {
743
+ if (socks === undefined || socks === null || !socks.host || !socks.port) {
744
+ rejectPromise(new Error('upstream SOCKS address is not configured'))
745
+ return
746
+ }
747
+ const socket = netConnect({ host: socks.host, port: socks.port })
748
+ let settled = false
749
+ const fail = (error) => {
750
+ if (settled) return
751
+ settled = true
752
+ clearTimeout(timer)
753
+ socket.destroy()
754
+ rejectPromise(error)
755
+ }
756
+ const timer = setTimeout(() => fail(new Error(`SOCKS connect to ${host}:${port} timed out`)), SOCKS_CONNECT_TIMEOUT_MS)
757
+ socket.on('error', fail)
758
+ socket.on('close', () => fail(new Error(`SOCKS server closed during handshake`)))
759
+ socket.once('connect', () => {
760
+ socket.write(Buffer.from([0x05, 0x01, 0x00]))
761
+ let buffered = Buffer.alloc(0)
762
+ const onData = (chunk) => {
763
+ buffered = Buffer.concat([buffered, chunk])
764
+ if (buffered.length < 2) return
765
+ if (buffered[0] !== 0x05) return fail(new Error('not a SOCKS5 server'))
766
+ if (buffered[1] !== 0x00) return fail(new Error(`SOCKS5 auth rejected (method ${buffered[1]})`))
767
+ if (socket.listenerCount('data') === 0) return
768
+ socket.removeListener('data', onData)
769
+ const request = [0x05, 0x01, 0x00]
770
+ const isAddressIpv4 = /^\d{1,3}(\.\d{1,3}){3}$/.test(host)
771
+ if (isAddressIpv4) {
772
+ request.push(0x01, ...host.split('.').map(Number))
773
+ } else {
774
+ const name = Buffer.from(host, 'utf8')
775
+ request.push(0x03, name.length, ...name)
776
+ }
777
+ request.push((port >> 8) & 0xFF, port & 0xFF)
778
+ socket.write(Buffer.from(request))
779
+ let reply = Buffer.alloc(0)
780
+ const onReply = (data) => {
781
+ reply = Buffer.concat([reply, data])
782
+ if (reply.length < 4) return
783
+ if (reply[0] !== 0x05) return fail(new Error('SOCKS5 回包版本不是 5'))
784
+ if (reply[1] !== 0x00) {
785
+ const codes = { 1: 'general failure', 2: 'not allowed', 3: 'network unreachable', 4: 'host unreachable', 5: 'connection refused', 6: 'TTL expired', 7: 'command not supported', 8: 'address not supported' }
786
+ return fail(new Error(`SOCKS5 CONNECT to ${host}:${port} failed: ${codes[reply[1]] ?? `rep=${reply[1]}`}`))
787
+ }
788
+ const atyp = reply[3]
789
+ if (atyp !== 0x01 && atyp !== 0x03 && atyp !== 0x04) {
790
+ return fail(new Error(`SOCKS5 回包地址类型未知(ATYP=${atyp})`))
791
+ }
792
+ // An unknown ATYP used to make `need` NaN, and `length < NaN` is false ⇒ the
793
+ // socket was resolved with a partially-read reply, so the leftover bytes leaked
794
+ // into the tunnel as garbage. Every reply byte must be consumed first.
795
+ const need = atyp === 0x01 ? 10 : atyp === 0x04 ? 22 : (reply.length < 5 ? 0 : 7 + reply[4])
796
+ if (need === 0 || reply.length < need) return
797
+ socket.removeListener('data', onReply)
798
+ socket.removeAllListeners('close')
799
+ if (settled) return
800
+ // Bytes past the end of the reply arrived in the SAME chunk: they are
801
+ // tunnel data, not handshake. Hand them back to the stream (paused, so
802
+ // they cannot be emitted before the caller attaches its pipe) — losing
803
+ // them would truncate the first byte of protocols that answer at once.
804
+ if (reply.length > need) socket.unshift(reply.subarray(need))
805
+ socket.pause()
806
+ settled = true
807
+ clearTimeout(timer)
808
+ resolvePromise(socket)
809
+ }
810
+ socket.on('data', onReply)
811
+ }
812
+ socket.on('data', onData)
813
+ })
814
+ })
815
+ }
816
+
817
+ /**
818
+ * One same-port shadow listener: `127.0.0.1:<localPort>` → SOCKS → `host:port`.
819
+ * A failed UPSTREAM dial is a per-connection event (the tunnel may be down, the
820
+ * target may refuse); only a failed listen() is fatal — a half-up proxy would
821
+ * silently narrow the allow-list, a refused stream just fails that stream.
822
+ */
823
+ function startShadow(target, socks, onListenError, onConnError) {
824
+ const server = createServer((client) => {
825
+ connectSocks(socks, target.host, target.port)
826
+ .then((upstream) => {
827
+ client.pipe(upstream)
828
+ upstream.pipe(client)
829
+ const bye = () => { client.destroy(); upstream.destroy() }
830
+ client.on('error', bye)
831
+ upstream.on('error', bye)
832
+ client.on('close', () => upstream.destroy())
833
+ upstream.on('close', () => client.destroy())
834
+ })
835
+ .catch((error) => {
836
+ onConnError(target.host, target.port, error)
837
+ client.destroy()
838
+ })
839
+ })
840
+ server.on('error', (error) => onListenError(error))
841
+ server.listen(target.localPort, '127.0.0.1')
842
+ return server
843
+ }
844
+
845
+ /** The loopback CONNECT proxy: destination known per connection ⇒ wildcards work. */
846
+ function startConnectProxy(port, state, onFatal, onConnError) {
847
+ // `state.config` is swapped on reload, so the allow-list is evaluated per
848
+ // connection instead of being frozen at listen time (编辑规则无需重启进程).
849
+ const allowNow = (host, targetPort) => {
850
+ const config = state.config
851
+ if (config.rules.filter((rule) => rule.enabled).length === 0) return false
852
+ return allowAdmits(allowList(config), host, targetPort)
853
+ }
854
+ const server = createServer((client) => {
855
+ let buffered = Buffer.alloc(0)
856
+ const onData = (chunk) => {
857
+ buffered = Buffer.concat([buffered, chunk])
858
+ if (buffered.length > HEADER_MAX_BYTES) {
859
+ client.destroy()
860
+ return
861
+ }
862
+ const end = buffered.indexOf('\r\n\r\n')
863
+ const lineEnd = buffered.indexOf('\n')
864
+ if (end === -1 && lineEnd === -1) return
865
+ const head = buffered.subarray(0, end === -1 ? lineEnd : end).toString('latin1')
866
+ const firstLine = head.split('\n')[0].replace(/\r$/, '')
867
+ const connectMatch = /^CONNECT\s+([^\s:]+):(\d+)\s+HTTP\/1\.[01]$/i.exec(firstLine)
868
+ if (connectMatch !== null) {
869
+ client.removeListener('data', onData)
870
+ const host = connectMatch[1]
871
+ const targetPort = Number(connectMatch[2])
872
+ if (!allowNow(host, targetPort)) {
873
+ client.end('HTTP/1.1 403 Forbidden\r\nX-Proxy-Denied: rule\r\n\r\n')
874
+ return
875
+ }
876
+ connectSocks(state.config.socks, host, targetPort)
877
+ .then((upstream) => {
878
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
879
+ client.pipe(upstream)
880
+ upstream.pipe(client)
881
+ client.on('error', () => upstream.destroy())
882
+ upstream.on('error', () => client.destroy())
883
+ client.on('close', () => upstream.destroy())
884
+ upstream.on('close', () => client.destroy())
885
+ })
886
+ .catch((error) => {
887
+ onConnError(host, targetPort, error)
888
+ client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
889
+ })
890
+ return
891
+ }
892
+ // Plain HTTP through a proxy arrives in absolute form: GET http://h:p/path
893
+ const absoluteMatch = /^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH)\s+(https?):\/\/([^/\s:]+):(\d+)([^\s]*)\s+HTTP\/1\.[01]$/i.exec(firstLine)
894
+ if (absoluteMatch === null) {
895
+ client.end('HTTP/1.1 400 Bad Request\r\nX-Proxy-Error: only CONNECT and absolute-form HTTP are supported\r\n\r\n')
896
+ return
897
+ }
898
+ client.removeListener('data', onData)
899
+ // Destructure by GROUP index: [0] is the whole match, [1] the method,
900
+ // [2] the scheme, [3] host, [4] port, [5] the origin-form remainder.
901
+ // Taking the method from index 0 made the host the scheme (`http`) and the
902
+ // port `NaN`, so every plain-HTTP proxy request was denied — and any that
903
+ // got through would have been rewritten with the wrong request line.
904
+ const [, method, scheme, host, portText, rest] = absoluteMatch
905
+ const targetPort = Number(portText)
906
+ // `https://` cannot ride in absolute form: this request line is plaintext
907
+ // on the wire, so forwarding it to a TLS port would send HTTP to a TLS
908
+ // listener (the origin resets; the caller sees a broken response and no
909
+ // hint why). The only correct spelling of an https URL through this proxy
910
+ // is CONNECT — which already carries the allow-list decision. Fail loud
911
+ // and tell the caller, instead of silently speaking the wrong protocol.
912
+ if (scheme.toLowerCase() === 'https') {
913
+ const reason = 'https:// URLs must use CONNECT: the absolute-form request line is plaintext, but the origin expects TLS. Set HTTPS_PROXY (curl/git do this automatically).\n'
914
+ client.end(
915
+ 'HTTP/1.1 400 Bad Request\r\n'
916
+ + 'X-Proxy-Error: https requires CONNECT\r\n'
917
+ + 'Content-Type: text/plain; charset=utf-8\r\n'
918
+ + 'Connection: close\r\n'
919
+ + `Content-Length: ${Buffer.byteLength(reason)}\r\n\r\n`
920
+ + reason,
921
+ )
922
+ return
923
+ }
924
+ if (!allowNow(host, targetPort)) {
925
+ client.end('HTTP/1.1 403 Forbidden\r\nX-Proxy-Denied: rule\r\n\r\n')
926
+ return
927
+ }
928
+ connectSocks(state.config.socks, host, targetPort)
929
+ .then((upstream) => {
930
+ const lines = head.split(/\r?\n/)
931
+ lines[0] = `${method} ${rest === '' ? '/' : rest} HTTP/1.1`
932
+ const header = lines.join('\r\n')
933
+ upstream.write(header + '\r\n\r\n')
934
+ const body = buffered.subarray(end === -1 ? buffered.length : end + 4)
935
+ if (body.length > 0) upstream.write(body)
936
+ client.pipe(upstream)
937
+ upstream.pipe(client)
938
+ client.on('error', () => upstream.destroy())
939
+ upstream.on('error', () => client.destroy())
940
+ client.on('close', () => upstream.destroy())
941
+ upstream.on('close', () => client.destroy())
942
+ })
943
+ .catch((error) => {
944
+ onConnError(host, targetPort, error)
945
+ client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
946
+ })
947
+ }
948
+ client.on('data', onData)
949
+ client.on('error', () => client.destroy())
950
+ })
951
+ server.on('error', (error) => onFatal(error))
952
+ server.listen(port, '127.0.0.1')
953
+ return server
954
+ }
955
+
956
+ /**
957
+ * Run the engine in the foreground until killed: the CONNECT proxy plus every
958
+ * shadow listener. One throwing listener fails the whole process — a half-up
959
+ * proxy is worse than a failed one, because the allow-list would silently narrow.
960
+ * @param config - a normalised config.
961
+ * @param options - `{ log }` sink for human-readable lines.
962
+ * @returns a never-resolving promise (resolves only on SIGTERM/SIGINT).
963
+ */
964
+ export function runEngine(config, options = {}) {
965
+ const log = typeof options.log === 'function' ? options.log : (line) => console.log(line)
966
+ if (config.socks.host === '' || config.socks.port === 0) throw new Error('上游 SOCKS 地址未配置(.env 的 socks.host / socks.port)')
967
+ const state = { config }
968
+ const servers = []
969
+ const onFatal = (error) => {
970
+ log(`[${PROXY_MARKER}] listener error: ${error?.message ?? error}`)
971
+ shutdown(1)
972
+ }
973
+ // Per-connection failures are routine (target down, tunnel hiccup); log the
974
+ // first few so the panel can show WHY a stream failed, then stay quiet.
975
+ let connErrors = 0
976
+ const onConnError = (host, port, error) => {
977
+ connErrors += 1
978
+ if (connErrors <= 8) log(`[${PROXY_MARKER}] tunnel to ${host}:${port} failed: ${error?.message ?? error}`)
979
+ else if (connErrors === 9) log(`[${PROXY_MARKER}] further tunnel failures suppressed`)
980
+ }
981
+ const proxyServer = startConnectProxy(config.listenPort, state, onFatal, onConnError)
982
+ servers.push(proxyServer)
983
+ log(`[${PROXY_MARKER}] CONNECT proxy 127.0.0.1:${config.listenPort} -> socks5 ${config.socks.host}:${config.socks.port}`)
984
+ /** localPort -> shadow server, so a reload can add/drop single listeners. */
985
+ const shadowServers = new Map()
986
+ const applyShadows = (nextConfig) => {
987
+ // Two hosts mapped to the SAME local port cannot both be bound: the second entry
988
+ // used to overwrite the first in the map, so traffic for host A silently reached
989
+ // host B. Keep the first and say what was dropped.
990
+ const wanted = new Map()
991
+ for (const target of shadowTargets(nextConfig)) {
992
+ if (wanted.has(target.localPort)) {
993
+ const kept = wanted.get(target.localPort)
994
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${target.localPort} 已被 ${kept.host}:${kept.port} 占用,忽略 ${target.host}:${target.port}`)
995
+ continue
996
+ }
997
+ wanted.set(target.localPort, target)
998
+ }
999
+ for (const [localPort, server] of shadowServers) {
1000
+ if (wanted.has(localPort)) continue
1001
+ try { server.close() } catch { /* already gone */ }
1002
+ shadowServers.delete(localPort)
1003
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${localPort} removed`)
1004
+ }
1005
+ for (const [localPort, target] of wanted) {
1006
+ if (shadowServers.has(localPort)) continue
1007
+ // A shadow is a convenience (local clients like Navicat dial 127.0.0.1); losing one
1008
+ // port must never kill the CONNECT proxy that the enforcement path needs.
1009
+ const server = startShadow(target, nextConfig.socks, (error) => {
1010
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${localPort} 不可用: ${error?.message ?? error}`)
1011
+ shadowServers.delete(localPort)
1012
+ try { server.close() } catch { /* not listening */ }
1013
+ }, onConnError)
1014
+ shadowServers.set(localPort, server)
1015
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${localPort} -> ${target.host}:${target.port}`)
1016
+ }
1017
+ }
1018
+ applyShadows(config)
1019
+ /**
1020
+ * Re-read the config and apply it without dropping the process: rules are edited
1021
+ * while the proxy keeps running (no restart, in-flight connections keep going).
1022
+ */
1023
+ const reload = () => {
1024
+ if (typeof options.readConfig !== 'function') return
1025
+ let next = null
1026
+ try {
1027
+ next = options.readConfig()
1028
+ } catch (error) {
1029
+ log(`[${PROXY_MARKER}] reload failed: ${error?.message ?? error}`)
1030
+ return
1031
+ }
1032
+ if (next === null || next === undefined) return
1033
+ if (next.socks.host === '' || next.socks.port === 0) {
1034
+ log(`[${PROXY_MARKER}] reload skipped: SOCKS 上游未配置`)
1035
+ return
1036
+ }
1037
+ state.config = next
1038
+ applyShadows(next)
1039
+ const enabled = next.rules.filter((rule) => rule.enabled).length
1040
+ log(`[${PROXY_MARKER}] reloaded: ${enabled} rules`)
1041
+ }
1042
+ if (typeof options.readConfig === 'function') {
1043
+ if (typeof options.configPath === 'string' && options.configPath !== '') {
1044
+ watchFile(options.configPath, { interval: 1000 }, reload)
1045
+ } else {
1046
+ setInterval(reload, 2000).unref?.()
1047
+ }
1048
+ }
1049
+ let stopped = false
1050
+ function shutdown(code) {
1051
+ if (stopped) return
1052
+ stopped = true
1053
+ for (const server of servers) {
1054
+ try { server.close() } catch { /* already closed */ }
1055
+ }
1056
+ // Shadows are listeners too (E2): leaving them bound kept the ports open for
1057
+ // the 50 ms exit grace and, in tests that reuse ports, made the next start
1058
+ // look busy. Closing them is part of "the engine stopped".
1059
+ for (const [, server] of shadowServers) {
1060
+ try { server.close() } catch { /* already closed */ }
1061
+ }
1062
+ setTimeout(() => process.exit(code), 50).unref?.()
1063
+ }
1064
+ process.on('SIGTERM', () => shutdown(0))
1065
+ process.on('SIGINT', () => shutdown(0))
1066
+ // E3: the count must include shadows, otherwise the line always says 1 and a
1067
+ // readiness check that trusts it cannot tell a half-up engine from a full one.
1068
+ log(`[${PROXY_MARKER}] ready (${servers.length + shadowServers.size} listeners)`)
1069
+ return new Promise(() => {})
1070
+ }
1071
+
1072
+ /* ------------------------------------------------------------ process life -- */
1073
+
1074
+ /** Whether a pid is alive. */
1075
+ export function pidAlive(pid) {
1076
+ if (!Number.isInteger(pid) || pid <= 0) return false
1077
+ try {
1078
+ process.kill(pid, 0)
1079
+ return true
1080
+ } catch (error) {
1081
+ return error?.code === 'EPERM'
1082
+ }
1083
+ }
1084
+
1085
+ /**
1086
+ * The command line of a pid, or '' when it cannot be read. Linux/WSL read
1087
+ * `/proc`; Windows asks CIM (Node has no /proc there, and a pidfile alone must
1088
+ * NEVER be enough to justify a kill); macOS uses `ps`.
1089
+ * @param pid - candidate process id.
1090
+ * @returns the command line text.
1091
+ */
1092
+ export function pidCommandLine(pid) {
1093
+ if (!Number.isInteger(pid) || pid <= 0) return ''
1094
+ if (IS_WINDOWS) {
1095
+ try {
1096
+ const text = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
1097
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], { encoding: 'utf8', timeout: 8000, windowsHide: true })
1098
+ return text.trim()
1099
+ } catch {
1100
+ return ''
1101
+ }
1102
+ }
1103
+ if (process.platform === 'darwin') {
1104
+ try {
1105
+ return execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 4000 }).trim()
1106
+ } catch {
1107
+ return ''
1108
+ }
1109
+ }
1110
+ try {
1111
+ return readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ')
1112
+ } catch {
1113
+ return ''
1114
+ }
1115
+ }
1116
+
1117
+ /** Whether a pid's command line carries our marker (never signal a stranger). */
1118
+ export function pidIsProxy(pid) {
1119
+ if (!pidAlive(pid)) return false
1120
+ const commandLine = pidCommandLine(pid)
1121
+ return commandLine !== '' && commandLine.includes(PROXY_MARKER)
1122
+ }
1123
+
1124
+ /** The running engine's pid, or null (stale pidfile is removed). */
1125
+ export function proxyPid(cwd) {
1126
+ const path = proxyPidPath()
1127
+ if (!existsSync(path)) return null
1128
+ const text = readFileSync(path, 'utf8').trim()
1129
+ const pid = Number(text)
1130
+ if (!Number.isInteger(pid) || pid <= 0) {
1131
+ try { unlinkSync(path) } catch { /* ignore */ }
1132
+ return null
1133
+ }
1134
+ if (pidIsProxy(pid)) return pid
1135
+ try { unlinkSync(path) } catch { /* ignore */ }
1136
+ return null
1137
+ }
1138
+
1139
+ /** Whether something is listening on a loopback port. */
1140
+ export function portOpen(port, host = '127.0.0.1') {
1141
+ return new Promise((resolvePromise) => {
1142
+ const socket = netConnect({ host, port })
1143
+ const done = (value) => { socket.destroy(); resolvePromise(value) }
1144
+ socket.setTimeout(800, () => done(false))
1145
+ socket.once('connect', () => done(true))
1146
+ socket.once('error', () => done(false))
1147
+ })
1148
+ }
1149
+
1150
+ /**
1151
+ * Terminate an engine we ourselves just spawned and that failed to come up.
1152
+ *
1153
+ * Identity is re-checked before signalling: `pid` comes from our own child, but by the
1154
+ * time an 8 s wait is over it may have exited and been recycled — and the marker in
1155
+ * argv is the only proof that the process is ours.
1156
+ */
1157
+ async function reapFailedStart(pid, logPath) {
1158
+ if (pidIsProxy(pid) !== true) return
1159
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
1160
+ for (let attempt = 0; attempt < 20; attempt += 1) {
1161
+ if (pidAlive(pid) !== true) return
1162
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 100))
1163
+ }
1164
+ if (IS_WINDOWS) {
1165
+ try { execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }) } catch { /* ignore */ }
1166
+ } else {
1167
+ try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ }
1168
+ }
1169
+ try { appendFileSync(logPath, `[${PROXY_MARKER}] startup failed: process ${pid} killed\n`) } catch { /* ignore */ }
1170
+ }
1171
+
1172
+ /**
1173
+ * Start the engine detached, with a pidfile + log, and wait until every listener
1174
+ * answers. Verifies identity after the wait: a process that dies or never binds
1175
+ * is reported as a failure, never as "started".
1176
+ * @param cwd - workspace directory holding `.dsh-ris-ide/`.
1177
+ * @param options - `{ config, waitMs }`.
1178
+ * @returns `{ ok, pid?, config, error? }`.
1179
+ */
1180
+ export async function startProxy(cwd, options = {}) {
1181
+ const config = options.config ?? readProxyConfig(cwd)
1182
+ const existing = proxyPid(cwd)
1183
+ if (existing !== null) return { ok: true, pid: existing, config, alreadyRunning: true }
1184
+ if (config.socks.host === '' || config.socks.port === 0) return { ok: false, config, error: '上游 SOCKS 地址未配置(.env 的 socks.host / socks.port)' }
1185
+ // The child is spawned with `cwd` as its working directory: a missing directory
1186
+ // makes spawn fail with ENOENT, and (worse) the 'error' event has no listener, so
1187
+ // the daemon that asked for the start would die with an unhandled 'error'.
1188
+ if (!existsSync(cwd)) return { ok: false, config, error: `工作目录不存在:${cwd}` }
1189
+ const enabled = config.rules.filter((rule) => rule.enabled)
1190
+ if (enabled.length === 0) return { ok: false, config, error: '没有启用任何代理规则' }
1191
+ // The pidfile and the log live in the machine-wide home, not under the workspace:
1192
+ // creating only `cwd/.dsh-ris-ide` (a legacy location) left a fresh home missing and
1193
+ // `openSync` failed with ENOENT on the very first start.
1194
+ const logPath = proxyLogPath()
1195
+ const pidPath = proxyPidPath()
1196
+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 })
1197
+ mkdirSync(dirname(pidPath), { recursive: true, mode: 0o700 })
1198
+ const out = openSync(logPath, 'a', 0o600)
1199
+ // The child re-enters this file as a CLI: `serve` must be a POSITIONAL command
1200
+ // (a `--serve` flag would fall through to the default status command).
1201
+ // The marker travels in argv: it is the ONLY proof a pid is our engine (a
1202
+ // pidfile can be stale, and a recycled pid must never be signalled).
1203
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--cwd', cwd, 'serve', `--marker=${PROXY_MARKER}`], {
1204
+ cwd,
1205
+ detached: true,
1206
+ stdio: ['ignore', out, out],
1207
+ windowsHide: true,
1208
+ })
1209
+ closeSync(out)
1210
+ // A spawn failure is delivered asynchronously as an 'error' event; without a
1211
+ // listener Node throws it, and in the daemon that means the whole daemon dies on
1212
+ // a bad workspace path. Record it in the engine log and let the readiness loop
1213
+ // below report the failure normally.
1214
+ child.on('error', (error) => {
1215
+ try { appendFileSync(logPath, `[dsh-ris-ide-proxy] spawn failed: ${error?.message ?? error}\n`) } catch { /* ignore */ }
1216
+ })
1217
+ child.unref()
1218
+ try { writeFileSync(pidPath, String(child.pid), { encoding: 'utf8', mode: 0o600 }) } catch { /* ignore */ }
1219
+ const ports = [config.listenPort, ...shadowTargets(config).map((target) => target.localPort)]
1220
+ const budget = Number.isInteger(options.waitMs) ? options.waitMs : 150
1221
+ const rounds = Math.max(1, Math.ceil(8000 / budget))
1222
+ for (let round = 0; round < rounds; round += 1) {
1223
+ const states = await Promise.all(ports.map((port) => portOpen(port)))
1224
+ if (states.every(Boolean) && pidIsProxy(child.pid)) {
1225
+ return { ok: true, pid: child.pid, config, ports, logPath }
1226
+ }
1227
+ if (!pidAlive(child.pid)) break
1228
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, budget))
1229
+ }
1230
+ // A failed start must not leave a half-up engine behind: it keeps the loopback ports
1231
+ // bound, so the next attempt fails with EADDRINUSE for a process nobody can see.
1232
+ await reapFailedStart(child.pid, logPath)
1233
+ try { unlinkSync(pidPath) } catch { /* ignore */ }
1234
+ const tail = readTail(logPath, 2048)
1235
+ const reason = pidAlive(child.pid) ? `端口 ${ports.join(', ')} 未就绪或进程身份不匹配` : '进程已退出'
1236
+ // EADDRINUSE is the multi-workspace case: every workspace's engine binds the
1237
+ // SAME 127.0.0.1 ports, so the second one cannot start — say so instead of
1238
+ // leaving the user with a bare port number.
1239
+ const busy = /EADDRINUSE/i.test(tail)
1240
+ const hint = busy
1241
+ ? '\n端口已被占用:通常是另一个工作区的代理引擎绑定着同一批 127.0.0.1 端口。先在那个工作区停止代理(或关掉它的 127.0.0.1 映射),再启动这一个。'
1242
+ : ''
1243
+ return { ok: false, config, error: `代理未能启动(${reason})${hint}${tail === '' ? '' : `\n${tail}`}`, logPath }
1244
+ }
1245
+
1246
+ /** Stop the detached engine (TERM → 30 s → KILL). Never signals a stranger. */
1247
+ export async function stopProxy(cwd, options = {}) {
1248
+ const pid = proxyPid(cwd)
1249
+ if (pid === null) return { ok: true, stopped: false }
1250
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
1251
+ const grace = Number.isInteger(options.graceMs) ? options.graceMs : 5000
1252
+ const deadline = Date.now() + grace
1253
+ while (Date.now() < deadline) {
1254
+ if (!pidAlive(pid)) break
1255
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 120))
1256
+ }
1257
+ if (pidAlive(pid)) {
1258
+ // Windows has no SIGKILL worth the name: taskkill /T /F is the tree kill.
1259
+ if (IS_WINDOWS) {
1260
+ try { execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }) } catch { /* ignore */ }
1261
+ } else {
1262
+ try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ }
1263
+ }
1264
+ }
1265
+ try { unlinkSync(proxyPidPath()) } catch { /* ignore */ }
1266
+ return { ok: true, stopped: true, pid }
1267
+ }
1268
+
1269
+ /**
1270
+ * Stop the engine from an exit handler.
1271
+ *
1272
+ * `process.on('exit')` cannot await anything, so this only sends the signal
1273
+ * (TERM, then a hard kill on Windows) and unlinks the pidfile; the engine itself
1274
+ * shuts its listeners down on TERM. Safe to call when nothing is running.
1275
+ * @param cwd - any workspace; the pid/pidfile are machine-wide.
1276
+ * @returns the pid that was signalled, or null.
1277
+ */
1278
+ export function stopProxySync(cwd = '') {
1279
+ const pid = proxyPid(cwd)
1280
+ if (pid === null) return null
1281
+ if (IS_WINDOWS) {
1282
+ try { execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }) } catch { /* already gone */ }
1283
+ } else {
1284
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
1285
+ }
1286
+ try { unlinkSync(proxyPidPath()) } catch { /* ignore */ }
1287
+ return pid
1288
+ }
1289
+
1290
+ /** One-shot status for the UI: config, listeners, pid. */
1291
+ export async function proxyStatus(cwd) {
1292
+ const config = readProxyConfig(cwd)
1293
+ const pid = proxyPid(cwd)
1294
+ const ports = [config.listenPort, ...shadowTargets(config).map((target) => target.localPort)]
1295
+ const states = await Promise.all(ports.map((port) => portOpen(port)))
1296
+ return {
1297
+ config,
1298
+ running: pid !== null,
1299
+ pid,
1300
+ listen: ports.map((port, index) => ({ port, open: states[index] === true })),
1301
+ logPath: proxyLogPath(),
1302
+ socksUrl: config.socks.host === '' ? null : `socks5h://${config.socks.host}:${config.socks.port}`,
1303
+ }
1304
+ }
1305
+
1306
+ /** Tail of a text file (a log we may be appending to in another process). */
1307
+ export function readTail(path, bytes) {
1308
+ try {
1309
+ const size = statSync(path).size
1310
+ const length = Math.min(bytes, size)
1311
+ const buffer = Buffer.alloc(length)
1312
+ const fd = openSync(path, 'r')
1313
+ try {
1314
+ readSync(fd, buffer, 0, length, size - length)
1315
+ } finally {
1316
+ closeSync(fd)
1317
+ }
1318
+ return buffer.toString('utf8')
1319
+ } catch {
1320
+ return ''
1321
+ }
1322
+ }
1323
+
1324
+ /* -------------------------------------------------------------------- git -- */
1325
+
1326
+ /**
1327
+ * Apply / clear the SCOPE-LIMITED git proxy: one `http.proxy` entry (global
1328
+ * config) pointing at the upstream SOCKS server, so every git caller — the CLI,
1329
+ * the IDE, another plugin — uses the tunnel without a per-command flag.
1330
+ * @param config - a normalised config.
1331
+ * @param options - `{ host, enabled }`; host narrows the entry to one URL prefix.
1332
+ * @returns `{ ok, changed, key, value }`.
1333
+ */
1334
+ /**
1335
+ * Windows git, as a path this process can execute.
1336
+ *
1337
+ * The WSL `git` writes `~/.gitconfig` inside Linux; a git started on the Windows side
1338
+ * (YonCode, VS Code, a cmd window) reads a different file and its DNS cannot resolve
1339
+ * the internal git host at all — so the same scoped proxy has to exist on both sides.
1340
+ * `where.exe` is asked each time: cheap, and it follows the user's PATH.
1341
+ * @returns {string} an executable path, '' when Windows has no git.
1342
+ */
1343
+ export function windowsGitPath() {
1344
+ try {
1345
+ const out = spawnSyncImpl('where.exe', ['git'], { encoding: 'utf8', windowsHide: true, timeout: 5000 })
1346
+ if (out.status !== 0) return ''
1347
+ const lines = String(out.stdout ?? '').split(/\r?\n/).map((line) => line.trim())
1348
+ const exe = lines.find((line) => /git\.exe$/i.test(line) === true)
1349
+ if (exe === undefined) return ''
1350
+ const mounted = /^([A-Za-z]):\\(.*)$/.exec(exe)
1351
+ if (mounted === null) return exe
1352
+ return `${mounted[1].toLowerCase() === '' ? '' : `/mnt/${mounted[1].toLowerCase()}/`}${mounted[2].replace(/\\/g, '/')}`
1353
+ } catch {
1354
+ return ''
1355
+ }
1356
+ }
1357
+
1358
+ /**
1359
+ * Run the Windows git with one `config --global` mutation.
1360
+ * @param {string[]} args - arguments after `config --global`.
1361
+ * @returns {{ok: boolean, skipped?: boolean, error?: string}} outcome; a machine
1362
+ * without Windows git reports `skipped` instead of failing the caller.
1363
+ */
1364
+ export function runWindowsGitConfig(args) {
1365
+ const exe = windowsGitPath()
1366
+ if (exe === '') return { ok: false, skipped: true, error: 'Windows 侧没有 git' }
1367
+ try {
1368
+ const out = spawnSyncImpl(exe, ['config', '--global', ...args], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
1369
+ if (out.status === 0) return { ok: true }
1370
+ return { ok: false, error: String(out.stderr ?? '').trim() || `git.exe exited with ${out.status}` }
1371
+ } catch (error) {
1372
+ return { ok: false, error: String(error?.message ?? error) }
1373
+ }
1374
+ }
1375
+
1376
+ export function gitProxyPlan(config, options = {}) {
1377
+ const host = typeof options.host === 'string' ? options.host.trim() : ''
1378
+ const enabled = options.enabled !== false
1379
+ const key = host === '' ? 'http.proxy' : `http.https://${host}/.proxy`
1380
+ const value = enabled && config.socks.host !== '' ? `socks5h://${config.socks.host}:${config.socks.port}` : ''
1381
+ return { ok: true, key, value, host, enabled }
1382
+ }
1383
+
1384
+ /* -------------------------------------------------------------------- cli -- */
1385
+
1386
+ /**
1387
+ * CLI entry: `node lib/proxy.js --cwd=<dir> <command>`.
1388
+ * Commands: `serve` (foreground engine), `start`, `stop`, `status`, `rules`
1389
+ * (prints the effective config as JSON), `apply --json=<cfg>|--stdin` (merge
1390
+ * rules into the stored config), `git --host=… [--off]`.
1391
+ * @param argv - process.argv.slice(2).
1392
+ * @returns exit code.
1393
+ */
1394
+ export async function main(argv) {
1395
+ const args = argv.slice()
1396
+ let cwd = process.cwd()
1397
+ const positional = []
1398
+ const flags = {}
1399
+ for (let index = 0; index < args.length; index += 1) {
1400
+ const token = args[index]
1401
+ if (token === '--cwd' || token === '-C') {
1402
+ cwd = resolve(args[index + 1] ?? cwd)
1403
+ index += 1
1404
+ continue
1405
+ }
1406
+ if (token.startsWith('--cwd=')) {
1407
+ cwd = resolve(token.slice('--cwd='.length))
1408
+ continue
1409
+ }
1410
+ if (token.startsWith('--')) {
1411
+ const [name, inline] = token.slice(2).split('=', 2)
1412
+ if (inline !== undefined) {
1413
+ flags[name] = inline
1414
+ continue
1415
+ }
1416
+ const next = args[index + 1]
1417
+ if (next !== undefined && !next.startsWith('--')) {
1418
+ flags[name] = next
1419
+ index += 1
1420
+ } else {
1421
+ flags[name] = 'true'
1422
+ }
1423
+ continue
1424
+ }
1425
+ positional.push(token)
1426
+ }
1427
+ const command = positional[0] ?? 'status'
1428
+ if (!isAbsolute(cwd)) cwd = resolve(cwd)
1429
+ if (command === 'serve') {
1430
+ await runEngine(readProxyConfig(cwd), {
1431
+ log: (line) => console.log(line),
1432
+ configPath: proxyConfigPath(),
1433
+ readConfig: () => readProxyConfig(cwd),
1434
+ })
1435
+ return 0
1436
+ }
1437
+ if (command === 'start') {
1438
+ const result = await startProxy(cwd)
1439
+ console.log(JSON.stringify(result))
1440
+ return result.ok ? 0 : 1
1441
+ }
1442
+ if (command === 'stop') {
1443
+ console.log(JSON.stringify(await stopProxy(cwd)))
1444
+ return 0
1445
+ }
1446
+ if (command === 'status') {
1447
+ console.log(JSON.stringify(await proxyStatus(cwd)))
1448
+ return 0
1449
+ }
1450
+ if (command === 'rules') {
1451
+ console.log(JSON.stringify(readProxyConfig(cwd)))
1452
+ return 0
1453
+ }
1454
+ if (command === 'apply') {
1455
+ let incoming = null
1456
+ if (typeof flags.json === 'string' && flags.json !== 'true') {
1457
+ incoming = JSON.parse(flags.json)
1458
+ } else {
1459
+ const chunks = []
1460
+ for await (const chunk of process.stdin) chunks.push(chunk)
1461
+ incoming = JSON.parse(Buffer.concat(chunks).toString('utf8'))
1462
+ }
1463
+ const stored = readProxyConfig(cwd)
1464
+ const next = mergeConfigs(stored, incoming)
1465
+ const written = writeProxyConfig(cwd, next)
1466
+ console.log(JSON.stringify({ ok: true, config: written }))
1467
+ return 0
1468
+ }
1469
+ if (command === 'git') {
1470
+ const plan = gitProxyPlan(readProxyConfig(cwd), { host: flags.host, enabled: flags.off !== 'true' })
1471
+ console.log(JSON.stringify(plan))
1472
+ return 0
1473
+ }
1474
+ console.error(`unknown command "${command}" (serve|start|stop|status|rules|apply|git)`)
1475
+ return 2
1476
+ }
1477
+
1478
+ /**
1479
+ * Merge an incoming config into the shared one.
1480
+ *
1481
+ * The file is machine-level, so two workspaces write into the same object. Rule
1482
+ * identity is therefore `(workspace, id)`, and `replaceRulesFrom` only clears the
1483
+ * rows of ONE owner: the caller passes `{ replaceRulesFrom: '<source>',
1484
+ * workspace: '<dir>' }` to refresh its own rows and leave everyone else's alone.
1485
+ * @param stored - the config currently in the shared file.
1486
+ * @param incoming - partial config from a caller.
1487
+ * @returns a normalised merged config.
1488
+ */
1489
+ export function mergeConfigs(stored, incoming) {
1490
+ const base = normalizeConfig(stored)
1491
+ const patch = incoming !== null && typeof incoming === 'object' ? incoming : {}
1492
+ const patchWorkspace = typeof patch.workspace === 'string' ? patch.workspace : undefined
1493
+ const mergedRules = base.rules.slice()
1494
+ const dropped = new Set()
1495
+ // Rules are machine-wide, so a patch never replaces "one workspace's rows":
1496
+ // it either replaces all rows of a SOURCE (what the yds bridge does, so a
1497
+ // removed endpoint disappears) or upserts rows by id.
1498
+ // `replaceAllRules` is the whole-table contract the maintenance page and the daemon
1499
+ // use (m10585): the payload IS the table, so rows it does not restate are gone.
1500
+ // The source-scoped forms stay for callers that only own a slice of the file.
1501
+ if (patch.replaceAllRules === true) {
1502
+ for (const rule of mergedRules) dropped.add(rule.id)
1503
+ }
1504
+ const replaceSource = typeof patch.replaceRulesFrom === 'string'
1505
+ ? patch.replaceRulesFrom
1506
+ : (patch.replaceRules === true ? '' : null)
1507
+ if (replaceSource !== null) {
1508
+ for (const rule of mergedRules) {
1509
+ if (rule.source === replaceSource) dropped.add(rule.id)
1510
+ }
1511
+ }
1512
+ if (Array.isArray(patch.rules)) {
1513
+ for (const rule of patch.rules) {
1514
+ if (rule === null || typeof rule !== 'object') continue
1515
+ const id = typeof rule.id === 'string' && rule.id !== '' ? rule.id : `rule-${mergedRules.length + 1}`
1516
+ // Keep an existing row's provenance when the caller does not restate it,
1517
+ // so editing from a second workspace does not relabel the origin.
1518
+ const existing = mergedRules.find((item) => item.id === id)
1519
+ const workspace = typeof rule.workspace === 'string' && rule.workspace !== ''
1520
+ ? rule.workspace
1521
+ : (existing?.workspace ?? patchWorkspace ?? '')
1522
+ const index = mergedRules.findIndex((item) => item.id === id)
1523
+ const ruleSource = typeof rule.source === 'string' ? rule.source : 'user'
1524
+ // Per-workspace owners must survive a daemon write the same way they survive
1525
+ // a read (review B-P0-2 / D-P0-1): a patch that does not restate them keeps
1526
+ // the stored map. The exception is a whole-source replacement — that is a
1527
+ // delete-and-recreate of the source's rows, so inheriting the old shares
1528
+ // would silently keep endpoints the driver has just withdrawn.
1529
+ const replacedRow = replaceSource !== null && ruleSource === replaceSource
1530
+ const row = {
1531
+ id,
1532
+ // Provenance label from whoever generated the row ("YonCode java"); an edit
1533
+ // that does not restate it keeps the stored one.
1534
+ label: typeof rule.label === 'string' && rule.label !== ''
1535
+ ? rule.label.trim().slice(0, 60)
1536
+ : (existing?.label ?? ''),
1537
+ program: typeof rule.program === 'string' ? rule.program : '',
1538
+ hosts: typeof rule.hosts === 'string' ? rule.hosts : '',
1539
+ ports: typeof rule.ports === 'string' ? rule.ports : '',
1540
+ enabled: rule.enabled === true,
1541
+ // `undefined` keeps the automatic choice (no mapping for SOCKS-aware
1542
+ // programs); a boolean is the caller's explicit decision.
1543
+ shadow: typeof rule.shadow === 'boolean' ? rule.shadow : undefined,
1544
+ // `undefined` keeps the stored decision: flipping the field on every edit
1545
+ // that does not restate it would silently re-enable the allow-list
1546
+ // (or silently bypass it, which is worse).
1547
+ direct: typeof rule.direct === 'boolean' ? rule.direct : existing?.direct === true,
1548
+ source: ruleSource,
1549
+ workspace,
1550
+ // Intrinsic to a driven row (which OS side its image name belongs to); a UI
1551
+ // edit that does not restate it keeps the stored value.
1552
+ side: rule.side === 'local' || rule.side === 'windows' ? rule.side : (existing?.side ?? ''),
1553
+ owners: normalizeOwners(rule.owners) ?? (replacedRow === true ? undefined : normalizeOwners(existing?.owners)),
1554
+ }
1555
+ if (index === -1) mergedRules.push(row)
1556
+ else mergedRules[index] = row
1557
+ dropped.delete(id)
1558
+ }
1559
+ }
1560
+ return normalizeConfig({
1561
+ socks: patch.socks !== undefined ? patch.socks : base.socks,
1562
+ listenPort: patch.listenPort !== undefined ? patch.listenPort : base.listenPort,
1563
+ rules: mergedRules.filter((rule) => !dropped.has(rule.id)),
1564
+ // The fallback listener list is owned by whoever drives the tunnel, so it is
1565
+ // replaced wholesale rather than merged row by row.
1566
+ shadows: Array.isArray(patch.shadows) ? patch.shadows : base.shadows,
1567
+ })
1568
+ }
1569
+
1570
+ if (process.argv[1] !== undefined && /proxy\.js$/.test(process.argv[1])) {
1571
+ main(process.argv.slice(2)).then((code) => {
1572
+ if (code !== 0) process.exitCode = code
1573
+ }).catch((error) => {
1574
+ console.error(error?.stack ?? String(error))
1575
+ process.exitCode = 1
1576
+ })
1577
+ }