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.
package/lib/proxy.js ADDED
@@ -0,0 +1,1498 @@
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
+ * Normalise a stored config (or `undefined`) into the shape the engine uses.
258
+ * Unknown fields are dropped, rule rows are validated, and the four auto rows
259
+ * are appended when the stored file predates them.
260
+ * @param raw - parsed JSON (may be null/garbage).
261
+ * @returns the effective config.
262
+ */
263
+ export function normalizeConfig(raw) {
264
+ const source = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
265
+ const socksRaw = source.socks !== null && typeof source.socks === 'object' ? source.socks : {}
266
+ const host = typeof socksRaw.host === 'string' ? socksRaw.host.trim() : ''
267
+ const port = Number(socksRaw.port)
268
+ const listenPort = Number(source.listenPort)
269
+ // Loopback mapping targets that belong to the FALLBACK path, not to the rule
270
+ // table: when ProxyBridge cannot run, some client (a JDBC driver, Navicat) can
271
+ // only be pointed at 127.0.0.1, so the engine binds a listener per destination.
272
+ // Keeping them out of `rules` means the table stays "what should be proxied"
273
+ // and the user never sees an implementation detail there.
274
+ const shadows = []
275
+ const rawShadows = Array.isArray(source.shadows) ? source.shadows : []
276
+ for (const item of rawShadows.slice(0, MAX_SHADOW_TARGETS)) {
277
+ if (item === null || typeof item !== 'object') continue
278
+ const host = typeof item.host === 'string' ? item.host.trim() : ''
279
+ const port = Number(item.port)
280
+ const localPort = Number(item.localPort)
281
+ if (!isIpv4Literal(host) || !Number.isInteger(port) || port < 1 || port > 65535) continue
282
+ const listen = Number.isInteger(localPort) && localPort > 1023 && localPort < 65536 ? localPort : port
283
+ if (shadows.some((entry) => entry.host === host && entry.port === port && entry.localPort === listen)) continue
284
+ shadows.push({ host, port, localPort: listen })
285
+ }
286
+ const rules = []
287
+ const rawRules = Array.isArray(source.rules) ? source.rules : []
288
+ for (const item of rawRules.slice(0, MAX_RULES)) {
289
+ if (item === null || typeof item !== 'object') continue
290
+ const id = typeof item.id === 'string' && item.id !== '' ? item.id : `rule-${rules.length + 1}`
291
+ const program = typeof item.program === 'string' ? item.program.trim() : ''
292
+ const hostSpec = typeof item.hosts === 'string' ? item.hosts.trim() : ''
293
+ const portSpec = typeof item.ports === 'string' ? item.ports.trim() : ''
294
+ const enabled = item.enabled === true
295
+ const hostsParsed = parseHostSpec(hostSpec).patterns
296
+ const portsParsed = parsePortSpec(portSpec).ports
297
+ const bindable = hostsParsed.length > 0 && hostsParsed.every(isIpv4Literal) && portsParsed.length > 0
298
+ // A program that speaks SOCKS needs no mapping; one that cannot is only
299
+ // reachable through a same-port loopback listener, so it gets one unless the
300
+ // stored file says otherwise (an explicit true/false always wins).
301
+ const shadow = typeof item.shadow === 'boolean' ? item.shadow : bindable && !isSocksCapableProgram(program)
302
+ if (program === '' && hostSpec === '' && portSpec === '') continue
303
+ // Migration: the starter rows used to include `node` and `curl`; they are not
304
+ // offered any more, so drop a stored one instead of leaving an empty row the
305
+ // dialog can no longer create (a user's OWN node/curl row is kept — its source
306
+ // is not `auto`).
307
+ if (item.source === 'auto' && AUTO_PROGRAMS.includes(programKey(program)) !== true) continue
308
+ rules.push({
309
+ id,
310
+ // A human label the provider of the row supplies ("YonCode java"); the dialog
311
+ // and the ProxyBridge profile show it instead of the raw id.
312
+ label: typeof item.label === 'string' ? item.label.trim().slice(0, 60) : '',
313
+ program,
314
+ hosts: hostSpec,
315
+ ports: portSpec,
316
+ enabled,
317
+ // Loopback mapping only helps a client that CANNOT take a proxy address,
318
+ // and only when that client runs on this side of the OS boundary (a
319
+ // Windows program cannot reach a WSL 127.0.0.1).
320
+ shadow,
321
+ // Opt-out from the allow-list: `direct` hands the program the upstream
322
+ // SOCKS address instead of this engine's CONNECT proxy. Defaults to false
323
+ // — an old config file (no field) must keep the enforced path — and only
324
+ // a literal `true` enables it.
325
+ direct: item.direct === true,
326
+ source: typeof item.source === 'string' ? item.source : 'user',
327
+ // Which workspace contributed this row ('' = the generated defaults, which
328
+ // belong to the machine). The engine is shared, so this is the only way to
329
+ // tell "my rule" from "the other workspace's rule" in the dialog.
330
+ workspace: typeof item.workspace === 'string' ? item.workspace : '',
331
+ })
332
+ }
333
+ // The table is MACHINE-level: ProxyBridge hooks the kernel and matches by
334
+ // process name, so a rule cannot be scoped to a workspace or a session. The
335
+ // `workspace` field is therefore a provenance label only, never part of a
336
+ // rule's identity:
337
+ // - generated/user rows are one switch per PROGRAM for the whole machine, so
338
+ // opening the dialog from another workspace cannot add a second `java` row;
339
+ // - driven (`yds`) rows describe ENDPOINTS, not programs — several may share
340
+ // the `jdbc` label and each is a distinct destination — so they keep their id.
341
+ const seen = new Set()
342
+ const deduped = []
343
+ for (const rule of rules) {
344
+ const key = rule.source === 'yds' ? `yds\u0000${rule.id}` : `prog\u0000${programKey(rule.program)}`
345
+ if (programKey(rule.program) !== '' && seen.has(key)) continue
346
+ seen.add(key)
347
+ deduped.push(rule)
348
+ }
349
+ return {
350
+ socks: {
351
+ host,
352
+ port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 0,
353
+ },
354
+ listenPort: Number.isInteger(listenPort) && listenPort > 1023 && listenPort < 65536 ? listenPort : DEFAULT_LISTEN_PORT,
355
+ rules: deduped,
356
+ shadows,
357
+ }
358
+ }
359
+
360
+ /**
361
+ * The allow-list of every ENABLED, effective rule. A rule contributes only its
362
+ * parsed axes; a row with a blank axis contributes nothing (see
363
+ * {@link ruleEffectiveness}).
364
+ * @param config - a normalised config.
365
+ * @returns `{ hostPatterns: string[], ports: number[] }` — either list empty ⇒
366
+ * DENY everything (fail-closed; "allow everything" is spelled `*`).
367
+ */
368
+ export function allowList(config) {
369
+ const hostPatterns = []
370
+ const ports = new Set()
371
+ for (const rule of config.rules) {
372
+ // A half-written row contributes nothing: every axis must be explicit.
373
+ if (ruleEffectiveness(rule).effective !== true) continue
374
+ for (const pattern of parseHostSpec(rule.hosts).patterns) {
375
+ if (!hostPatterns.includes(pattern)) hostPatterns.push(pattern)
376
+ }
377
+ for (const port of parsePortSpec(rule.ports).ports) ports.add(port)
378
+ }
379
+ return { hostPatterns, ports: [...ports].sort((a, b) => a - b) }
380
+ }
381
+
382
+ /**
383
+ * Whether the allow-list admits a destination.
384
+ * @param allow - result of {@link allowList}.
385
+ * @param host - destination host.
386
+ * @param port - destination port.
387
+ * @returns true when the connection may be tunnelled.
388
+ */
389
+ export function allowAdmits(allow, host, port) {
390
+ if (allow.hostPatterns.length === 0) return false
391
+ if (!allow.hostPatterns.some((pattern) => hostMatches(pattern, host))) return false
392
+ if (allow.ports.length === 0) return false
393
+ return allow.ports.includes(0) || allow.ports.includes(Number(port))
394
+ }
395
+
396
+ /**
397
+ * Same-port shadow listeners derived from the enabled rules: only literal-IPv4
398
+ * destinations can be pre-bound, and the local port equals the remote one so a
399
+ * program only has to replace the host with `127.0.0.1`.
400
+ * @param config - a normalised config.
401
+ * @returns `[{ host, port, localPort }]` capped at {@link MAX_SHADOW_TARGETS}.
402
+ */
403
+ export function shadowTargets(config) {
404
+ const seen = new Set()
405
+ const targets = []
406
+ // Explicit fallback list (written by a client plugin such as dsh-ris-yds) first.
407
+ for (const entry of Array.isArray(config.shadows) ? config.shadows : []) {
408
+ const key = `${entry.host}:${entry.port}`
409
+ if (seen.has(key)) continue
410
+ seen.add(key)
411
+ targets.push({ host: entry.host, port: entry.port, localPort: entry.localPort })
412
+ if (targets.length >= MAX_SHADOW_TARGETS) return targets
413
+ }
414
+ // Rules may still request a mapping themselves (opt-in per row).
415
+ for (const rule of config.rules) {
416
+ if (!rule.enabled || rule.shadow !== true) continue
417
+ const hosts = parseHostSpec(rule.hosts).patterns.filter(isIpv4Literal)
418
+ const ports = parsePortSpec(rule.ports).ports
419
+ for (const host of hosts) {
420
+ for (const port of ports) {
421
+ const key = `${host}:${port}`
422
+ if (seen.has(key)) continue
423
+ seen.add(key)
424
+ targets.push({ host, port, localPort: port })
425
+ if (targets.length >= MAX_SHADOW_TARGETS) return targets
426
+ }
427
+ }
428
+ }
429
+ return targets
430
+ }
431
+
432
+ /** Loopback destinations that must never be sent through the tunnel. */
433
+ export const DEFAULT_NO_PROXY = 'localhost,127.0.0.1,::1'
434
+
435
+ /**
436
+ * Which side of the OS boundary a program runs on.
437
+ * `'local'` (the default) — and `engineSide()`'s own value — means "this
438
+ * machine"; anything else means the other side (e.g. `'windows'` when this
439
+ * engine runs in WSL, or `'wsl'` when the caller is the Windows-side launcher).
440
+ * @param options - `{ side }` from {@link injectionFor}.
441
+ * @returns `'local'` or `'remote'`.
442
+ */
443
+ function injectionSide(options) {
444
+ const raw = typeof options?.side === 'string' ? options.side.trim().toLowerCase() : ''
445
+ if (raw === '' || raw === 'local') return 'local'
446
+ if (raw === engineSide()) return 'local'
447
+ return 'remote'
448
+ }
449
+
450
+ /**
451
+ * What a launcher should apply for one program: the rule whose `program` names
452
+ * it (exact, case-insensitive, extension-insensitive) must be ENABLED.
453
+ *
454
+ * The default injected address is the LOCAL loopback CONNECT proxy
455
+ * (`http://127.0.0.1:<listenPort>`), NOT the upstream SOCKS server: every
456
+ * connection a started program makes then passes through the engine's
457
+ * allow-list, which is what enforces the rule's `hosts`/`ports`. Handing out
458
+ * `ALL_PROXY=socks5h://<upstream>` would let the program reach anything the
459
+ * SOCKS server can, silently ignoring both axes.
460
+ *
461
+ * A row that explicitly sets `direct: true` opts out and gets the upstream
462
+ * SOCKS address (plus the JVM `-DsocksProxyHost` switch it needs). `direct`
463
+ * defaults to false — including for every config file written before the field
464
+ * existed — so the enforced path is the default. The JVM's `-DsocksProxyHost`
465
+ * cannot point at an HTTP proxy, so the local path uses the HTTP proxy flags
466
+ * only (Java ignores proxy env vars by default).
467
+ *
468
+ * Fail-closed rules:
469
+ * - no enabled rule for the program, no configured upstream, or a program that
470
+ * cannot be told a proxy address at all (not in
471
+ * {@link SOCKS_CAPABLE_PROGRAMS}: a JDBC driver, Navicat) ⇒ `null` — the
472
+ * latter can only reach the tunnel through a same-port `127.0.0.1` shadow
473
+ * listener;
474
+ * - a rule that is not effective ⇒ an object whose `env`/`jvmArgs` are empty
475
+ * plus a user-facing `reason` (the caller injects nothing).
476
+ *
477
+ * A program on the OTHER side of the OS boundary cannot reach this machine's
478
+ * 127.0.0.1, so a non-direct row injects nothing there either; `direct` is the
479
+ * variant that also works across the boundary (it needs no local listener).
480
+ *
481
+ * @param program - program name or path (`java.exe`, `/usr/bin/node`, `git`).
482
+ * @param config - a normalised config.
483
+ * @param options - `{ side }`; `'local'` (default) or `engineSide()`'s value
484
+ * means "this machine"; anything else is the other side.
485
+ * @returns `null` when no proxy applies, else
486
+ * `{ program, side, direct, env, jvmArgs, socksUrl, httpProxyUrl, listenPort, reason }`.
487
+ */
488
+ export function injectionFor(program, config, options = {}) {
489
+ const wanted = programKey(program)
490
+ if (wanted === '') return null
491
+ // A client that cannot be told a proxy address is not helped by a proxy URL;
492
+ // it needs a 127.0.0.1 listener (see `shadowTargets`).
493
+ if (isSocksCapableProgram(wanted) !== true) return null
494
+ const rule = config.rules.find((item) => item.enabled && programKey(item.program) === wanted)
495
+ if (rule === undefined) return null
496
+ if (config.socks.host === '' || config.socks.port === 0) return null
497
+ const side = injectionSide(options)
498
+ const direct = rule.direct === true
499
+ const socksUrl = `socks5h://${config.socks.host}:${config.socks.port}`
500
+ const base = {
501
+ program: wanted,
502
+ side,
503
+ direct,
504
+ env: {},
505
+ jvmArgs: [],
506
+ socksUrl,
507
+ httpProxyUrl: null,
508
+ listenPort: config.listenPort,
509
+ reason: '',
510
+ }
511
+ const effectiveness = ruleEffectiveness(rule)
512
+ if (effectiveness.effective !== true) {
513
+ return { ...base, reason: `规则不完整,未注入:${effectiveness.reason}` }
514
+ }
515
+ if (direct === true) {
516
+ // Explicit opt-out from the allow-list: reproduce the pre-M1 behaviour of
517
+ // binding the program straight to the upstream SOCKS server.
518
+ return {
519
+ ...base,
520
+ env: {
521
+ ALL_PROXY: socksUrl,
522
+ all_proxy: socksUrl,
523
+ HTTP_PROXY: socksUrl,
524
+ HTTPS_PROXY: socksUrl,
525
+ http_proxy: socksUrl,
526
+ https_proxy: socksUrl,
527
+ },
528
+ jvmArgs: [
529
+ `-DsocksProxyHost=${config.socks.host}`,
530
+ `-DsocksProxyPort=${config.socks.port}`,
531
+ ],
532
+ }
533
+ }
534
+ if (side === 'remote') {
535
+ return {
536
+ ...base,
537
+ reason: '程序在系统边界的另一侧,本机回环代理不可达;如确需直连上游请把该行设为 direct',
538
+ }
539
+ }
540
+ const httpProxyUrl = `http://127.0.0.1:${config.listenPort}`
541
+ return {
542
+ ...base,
543
+ httpProxyUrl,
544
+ env: {
545
+ ALL_PROXY: httpProxyUrl,
546
+ all_proxy: httpProxyUrl,
547
+ HTTP_PROXY: httpProxyUrl,
548
+ HTTPS_PROXY: httpProxyUrl,
549
+ http_proxy: httpProxyUrl,
550
+ https_proxy: httpProxyUrl,
551
+ NO_PROXY: DEFAULT_NO_PROXY,
552
+ no_proxy: DEFAULT_NO_PROXY,
553
+ },
554
+ jvmArgs: [
555
+ '-Dhttp.proxyHost=127.0.0.1',
556
+ `-Dhttp.proxyPort=${config.listenPort}`,
557
+ '-Dhttps.proxyHost=127.0.0.1',
558
+ `-Dhttps.proxyPort=${config.listenPort}`,
559
+ '-Dhttp.nonProxyHosts=localhost|127.*|[::1]',
560
+ ],
561
+ }
562
+ }
563
+
564
+ /** Normalise a program name/path to its bare, lower-case key (`C:\\…\\node.exe` → `node`). */
565
+ export function programKey(program) {
566
+ if (typeof program !== 'string') return ''
567
+ const base = program.replace(/\\/g, '/').split('/').pop() ?? ''
568
+ return base.trim().toLowerCase().replace(/\.(exe|cmd|bat|sh)$/, '')
569
+ }
570
+
571
+ /**
572
+ * Whether a program accepts a SOCKS address directly (`-DsocksProxyHost`,
573
+ * `ALL_PROXY`, `http.proxy=socks5h://…`).
574
+ * @param program - executable name or absolute path.
575
+ * @returns true when the program is known to speak SOCKS.
576
+ */
577
+ export function isSocksCapableProgram(program) {
578
+ const key = programKey(program)
579
+ return key !== '' && SOCKS_CAPABLE_PROGRAMS.includes(key)
580
+ }
581
+
582
+ /* ------------------------------------------------------------------- I/O -- */
583
+
584
+ /** Absolute path of the ONE shared proxy config. */
585
+ export function proxyConfigPath() {
586
+ return join(proxyHomeDir(), PROXY_FILENAME)
587
+ }
588
+
589
+ /** Absolute path of the shared pidfile. */
590
+ export function proxyPidPath() {
591
+ return join(proxyHomeDir(), PROXY_PID_FILENAME)
592
+ }
593
+
594
+ /** Absolute path of the shared engine log. */
595
+ export function proxyLogPath() {
596
+ return join(proxyHomeDir(), PROXY_LOG_FILENAME)
597
+ }
598
+
599
+ /**
600
+ * Read + normalise the shared proxy config (missing/garbage ⇒ defaults).
601
+ * @param _workspace - ignored for storage; kept so callers can pass the workspace
602
+ * without caring that the file is machine-level. Rows carry their own label.
603
+ */
604
+ export function readProxyConfig(workspace) {
605
+ const path = proxyConfigPath()
606
+ if (existsSync(path)) {
607
+ try {
608
+ return normalizeConfig(parseJsonc(readFileSync(path, 'utf8')))
609
+ } catch {
610
+ return normalizeConfig(undefined)
611
+ }
612
+ }
613
+ // Migration: engines before the shared-config change kept the file inside the
614
+ // workspace. Read it (labelled with that workspace) so an existing setup keeps
615
+ // its rules; the next save writes the merged result to the shared file.
616
+ if (typeof workspace === 'string' && workspace !== '') {
617
+ const legacy = join(workspace, '.dsh-ris-ide', PROXY_FILENAME)
618
+ if (existsSync(legacy)) {
619
+ try {
620
+ const migrated = normalizeConfig(parseJsonc(readFileSync(legacy, 'utf8')))
621
+ return Object.assign({}, migrated, {
622
+ rules: migrated.rules.map((rule) => (rule.workspace === '' ? Object.assign({}, rule, { workspace }) : rule)),
623
+ })
624
+ } catch { /* fall through to defaults */ }
625
+ }
626
+ }
627
+ return normalizeConfig(undefined)
628
+ }
629
+
630
+ /** Write the shared config atomically (0600: it names internal hosts and a tunnel). */
631
+ export function writeProxyConfig(_workspace, raw) {
632
+ const config = normalizeConfig(raw)
633
+ const path = proxyConfigPath()
634
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
635
+ const tmp = `${path}.${process.pid}.tmp`
636
+ writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
637
+ renameSync(tmp, path)
638
+ return config
639
+ }
640
+
641
+ /**
642
+ * Tolerant JSONC parse (comments + trailing commas), because the config file is
643
+ * hand-editable and the rest of the plugin already writes JSONC headers.
644
+ * @param text - file content.
645
+ * @returns the parsed value (null when the text is empty/garbage).
646
+ */
647
+ export function parseJsonc(text) {
648
+ const source = String(text ?? '').replace(/^\uFEFF/, '')
649
+ let out = ''
650
+ let inString = false
651
+ let quote = ''
652
+ for (let index = 0; index < source.length; index += 1) {
653
+ const char = source[index]
654
+ const next = source[index + 1]
655
+ if (inString) {
656
+ out += char
657
+ if (char === '\\') {
658
+ out += next ?? ''
659
+ index += 1
660
+ } else if (char === quote) {
661
+ inString = false
662
+ }
663
+ continue
664
+ }
665
+ if (char === '"' || char === "'") {
666
+ inString = true
667
+ quote = char
668
+ out += char
669
+ continue
670
+ }
671
+ if (char === '/' && next === '/') {
672
+ while (index < source.length && source[index] !== '\n') index += 1
673
+ out += '\n'
674
+ continue
675
+ }
676
+ if (char === '/' && next === '*') {
677
+ index += 2
678
+ while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) index += 1
679
+ index += 1
680
+ continue
681
+ }
682
+ out += char
683
+ }
684
+ try {
685
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'))
686
+ } catch {
687
+ return null
688
+ }
689
+ }
690
+
691
+ /* ---------------------------------------------------------------- tunnel -- */
692
+
693
+ /**
694
+ * Open one SOCKS5 connection (no auth) and hand back the raw socket.
695
+ * @param socks - `{ host, port }` of the upstream SOCKS server.
696
+ * @param host - destination host (IP literal or DNS name).
697
+ * @param port - destination port.
698
+ * @returns a promise for the connected socket.
699
+ */
700
+ export function connectSocks(socks, host, port) {
701
+ return new Promise((resolvePromise, rejectPromise) => {
702
+ if (socks === undefined || socks === null || !socks.host || !socks.port) {
703
+ rejectPromise(new Error('upstream SOCKS address is not configured'))
704
+ return
705
+ }
706
+ const socket = netConnect({ host: socks.host, port: socks.port })
707
+ let settled = false
708
+ const fail = (error) => {
709
+ if (settled) return
710
+ settled = true
711
+ clearTimeout(timer)
712
+ socket.destroy()
713
+ rejectPromise(error)
714
+ }
715
+ const timer = setTimeout(() => fail(new Error(`SOCKS connect to ${host}:${port} timed out`)), SOCKS_CONNECT_TIMEOUT_MS)
716
+ socket.on('error', fail)
717
+ socket.on('close', () => fail(new Error(`SOCKS server closed during handshake`)))
718
+ socket.once('connect', () => {
719
+ socket.write(Buffer.from([0x05, 0x01, 0x00]))
720
+ let buffered = Buffer.alloc(0)
721
+ const onData = (chunk) => {
722
+ buffered = Buffer.concat([buffered, chunk])
723
+ if (buffered.length < 2) return
724
+ if (buffered[0] !== 0x05) return fail(new Error('not a SOCKS5 server'))
725
+ if (buffered[1] !== 0x00) return fail(new Error(`SOCKS5 auth rejected (method ${buffered[1]})`))
726
+ if (socket.listenerCount('data') === 0) return
727
+ socket.removeListener('data', onData)
728
+ const request = [0x05, 0x01, 0x00]
729
+ const isAddressIpv4 = /^\d{1,3}(\.\d{1,3}){3}$/.test(host)
730
+ if (isAddressIpv4) {
731
+ request.push(0x01, ...host.split('.').map(Number))
732
+ } else {
733
+ const name = Buffer.from(host, 'utf8')
734
+ request.push(0x03, name.length, ...name)
735
+ }
736
+ request.push((port >> 8) & 0xFF, port & 0xFF)
737
+ socket.write(Buffer.from(request))
738
+ let reply = Buffer.alloc(0)
739
+ const onReply = (data) => {
740
+ reply = Buffer.concat([reply, data])
741
+ if (reply.length < 4) return
742
+ if (reply[0] !== 0x05) return fail(new Error('SOCKS5 回包版本不是 5'))
743
+ if (reply[1] !== 0x00) {
744
+ 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' }
745
+ return fail(new Error(`SOCKS5 CONNECT to ${host}:${port} failed: ${codes[reply[1]] ?? `rep=${reply[1]}`}`))
746
+ }
747
+ const atyp = reply[3]
748
+ if (atyp !== 0x01 && atyp !== 0x03 && atyp !== 0x04) {
749
+ return fail(new Error(`SOCKS5 回包地址类型未知(ATYP=${atyp})`))
750
+ }
751
+ // An unknown ATYP used to make `need` NaN, and `length < NaN` is false ⇒ the
752
+ // socket was resolved with a partially-read reply, so the leftover bytes leaked
753
+ // into the tunnel as garbage. Every reply byte must be consumed first.
754
+ const need = atyp === 0x01 ? 10 : atyp === 0x04 ? 22 : (reply.length < 5 ? 0 : 7 + reply[4])
755
+ if (need === 0 || reply.length < need) return
756
+ socket.removeListener('data', onReply)
757
+ socket.removeAllListeners('close')
758
+ if (settled) return
759
+ // Bytes past the end of the reply arrived in the SAME chunk: they are
760
+ // tunnel data, not handshake. Hand them back to the stream (paused, so
761
+ // they cannot be emitted before the caller attaches its pipe) — losing
762
+ // them would truncate the first byte of protocols that answer at once.
763
+ if (reply.length > need) socket.unshift(reply.subarray(need))
764
+ socket.pause()
765
+ settled = true
766
+ clearTimeout(timer)
767
+ resolvePromise(socket)
768
+ }
769
+ socket.on('data', onReply)
770
+ }
771
+ socket.on('data', onData)
772
+ })
773
+ })
774
+ }
775
+
776
+ /**
777
+ * One same-port shadow listener: `127.0.0.1:<localPort>` → SOCKS → `host:port`.
778
+ * A failed UPSTREAM dial is a per-connection event (the tunnel may be down, the
779
+ * target may refuse); only a failed listen() is fatal — a half-up proxy would
780
+ * silently narrow the allow-list, a refused stream just fails that stream.
781
+ */
782
+ function startShadow(target, socks, onListenError, onConnError) {
783
+ const server = createServer((client) => {
784
+ connectSocks(socks, target.host, target.port)
785
+ .then((upstream) => {
786
+ client.pipe(upstream)
787
+ upstream.pipe(client)
788
+ const bye = () => { client.destroy(); upstream.destroy() }
789
+ client.on('error', bye)
790
+ upstream.on('error', bye)
791
+ client.on('close', () => upstream.destroy())
792
+ upstream.on('close', () => client.destroy())
793
+ })
794
+ .catch((error) => {
795
+ onConnError(target.host, target.port, error)
796
+ client.destroy()
797
+ })
798
+ })
799
+ server.on('error', (error) => onListenError(error))
800
+ server.listen(target.localPort, '127.0.0.1')
801
+ return server
802
+ }
803
+
804
+ /** The loopback CONNECT proxy: destination known per connection ⇒ wildcards work. */
805
+ function startConnectProxy(port, state, onFatal, onConnError) {
806
+ // `state.config` is swapped on reload, so the allow-list is evaluated per
807
+ // connection instead of being frozen at listen time (编辑规则无需重启进程).
808
+ const allowNow = (host, targetPort) => {
809
+ const config = state.config
810
+ if (config.rules.filter((rule) => rule.enabled).length === 0) return false
811
+ return allowAdmits(allowList(config), host, targetPort)
812
+ }
813
+ const server = createServer((client) => {
814
+ let buffered = Buffer.alloc(0)
815
+ const onData = (chunk) => {
816
+ buffered = Buffer.concat([buffered, chunk])
817
+ if (buffered.length > HEADER_MAX_BYTES) {
818
+ client.destroy()
819
+ return
820
+ }
821
+ const end = buffered.indexOf('\r\n\r\n')
822
+ const lineEnd = buffered.indexOf('\n')
823
+ if (end === -1 && lineEnd === -1) return
824
+ const head = buffered.subarray(0, end === -1 ? lineEnd : end).toString('latin1')
825
+ const firstLine = head.split('\n')[0].replace(/\r$/, '')
826
+ const connectMatch = /^CONNECT\s+([^\s:]+):(\d+)\s+HTTP\/1\.[01]$/i.exec(firstLine)
827
+ if (connectMatch !== null) {
828
+ client.removeListener('data', onData)
829
+ const host = connectMatch[1]
830
+ const targetPort = Number(connectMatch[2])
831
+ if (!allowNow(host, targetPort)) {
832
+ client.end('HTTP/1.1 403 Forbidden\r\nX-Proxy-Denied: rule\r\n\r\n')
833
+ return
834
+ }
835
+ connectSocks(state.config.socks, host, targetPort)
836
+ .then((upstream) => {
837
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n')
838
+ client.pipe(upstream)
839
+ upstream.pipe(client)
840
+ client.on('error', () => upstream.destroy())
841
+ upstream.on('error', () => client.destroy())
842
+ client.on('close', () => upstream.destroy())
843
+ upstream.on('close', () => client.destroy())
844
+ })
845
+ .catch((error) => {
846
+ onConnError(host, targetPort, error)
847
+ client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
848
+ })
849
+ return
850
+ }
851
+ // Plain HTTP through a proxy arrives in absolute form: GET http://h:p/path
852
+ const absoluteMatch = /^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH)\s+(https?):\/\/([^/\s:]+):(\d+)([^\s]*)\s+HTTP\/1\.[01]$/i.exec(firstLine)
853
+ if (absoluteMatch === null) {
854
+ client.end('HTTP/1.1 400 Bad Request\r\nX-Proxy-Error: only CONNECT and absolute-form HTTP are supported\r\n\r\n')
855
+ return
856
+ }
857
+ client.removeListener('data', onData)
858
+ // Destructure by GROUP index: [0] is the whole match, [1] the method,
859
+ // [2] the scheme, [3] host, [4] port, [5] the origin-form remainder.
860
+ // Taking the method from index 0 made the host the scheme (`http`) and the
861
+ // port `NaN`, so every plain-HTTP proxy request was denied — and any that
862
+ // got through would have been rewritten with the wrong request line.
863
+ const [, method, scheme, host, portText, rest] = absoluteMatch
864
+ const targetPort = Number(portText)
865
+ // `https://` cannot ride in absolute form: this request line is plaintext
866
+ // on the wire, so forwarding it to a TLS port would send HTTP to a TLS
867
+ // listener (the origin resets; the caller sees a broken response and no
868
+ // hint why). The only correct spelling of an https URL through this proxy
869
+ // is CONNECT — which already carries the allow-list decision. Fail loud
870
+ // and tell the caller, instead of silently speaking the wrong protocol.
871
+ if (scheme.toLowerCase() === 'https') {
872
+ 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'
873
+ client.end(
874
+ 'HTTP/1.1 400 Bad Request\r\n'
875
+ + 'X-Proxy-Error: https requires CONNECT\r\n'
876
+ + 'Content-Type: text/plain; charset=utf-8\r\n'
877
+ + 'Connection: close\r\n'
878
+ + `Content-Length: ${Buffer.byteLength(reason)}\r\n\r\n`
879
+ + reason,
880
+ )
881
+ return
882
+ }
883
+ if (!allowNow(host, targetPort)) {
884
+ client.end('HTTP/1.1 403 Forbidden\r\nX-Proxy-Denied: rule\r\n\r\n')
885
+ return
886
+ }
887
+ connectSocks(state.config.socks, host, targetPort)
888
+ .then((upstream) => {
889
+ const lines = head.split(/\r?\n/)
890
+ lines[0] = `${method} ${rest === '' ? '/' : rest} HTTP/1.1`
891
+ const header = lines.join('\r\n')
892
+ upstream.write(header + '\r\n\r\n')
893
+ const body = buffered.subarray(end === -1 ? buffered.length : end + 4)
894
+ if (body.length > 0) upstream.write(body)
895
+ client.pipe(upstream)
896
+ upstream.pipe(client)
897
+ client.on('error', () => upstream.destroy())
898
+ upstream.on('error', () => client.destroy())
899
+ client.on('close', () => upstream.destroy())
900
+ upstream.on('close', () => client.destroy())
901
+ })
902
+ .catch((error) => {
903
+ onConnError(host, targetPort, error)
904
+ client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
905
+ })
906
+ }
907
+ client.on('data', onData)
908
+ client.on('error', () => client.destroy())
909
+ })
910
+ server.on('error', (error) => onFatal(error))
911
+ server.listen(port, '127.0.0.1')
912
+ return server
913
+ }
914
+
915
+ /**
916
+ * Run the engine in the foreground until killed: the CONNECT proxy plus every
917
+ * shadow listener. One throwing listener fails the whole process — a half-up
918
+ * proxy is worse than a failed one, because the allow-list would silently narrow.
919
+ * @param config - a normalised config.
920
+ * @param options - `{ log }` sink for human-readable lines.
921
+ * @returns a never-resolving promise (resolves only on SIGTERM/SIGINT).
922
+ */
923
+ export function runEngine(config, options = {}) {
924
+ const log = typeof options.log === 'function' ? options.log : (line) => console.log(line)
925
+ if (config.socks.host === '' || config.socks.port === 0) throw new Error('上游 SOCKS 地址未配置(.env 的 socks.host / socks.port)')
926
+ const state = { config }
927
+ const servers = []
928
+ const onFatal = (error) => {
929
+ log(`[${PROXY_MARKER}] listener error: ${error?.message ?? error}`)
930
+ shutdown(1)
931
+ }
932
+ // Per-connection failures are routine (target down, tunnel hiccup); log the
933
+ // first few so the panel can show WHY a stream failed, then stay quiet.
934
+ let connErrors = 0
935
+ const onConnError = (host, port, error) => {
936
+ connErrors += 1
937
+ if (connErrors <= 8) log(`[${PROXY_MARKER}] tunnel to ${host}:${port} failed: ${error?.message ?? error}`)
938
+ else if (connErrors === 9) log(`[${PROXY_MARKER}] further tunnel failures suppressed`)
939
+ }
940
+ const proxyServer = startConnectProxy(config.listenPort, state, onFatal, onConnError)
941
+ servers.push(proxyServer)
942
+ log(`[${PROXY_MARKER}] CONNECT proxy 127.0.0.1:${config.listenPort} -> socks5 ${config.socks.host}:${config.socks.port}`)
943
+ /** localPort -> shadow server, so a reload can add/drop single listeners. */
944
+ const shadowServers = new Map()
945
+ const applyShadows = (nextConfig) => {
946
+ // Two hosts mapped to the SAME local port cannot both be bound: the second entry
947
+ // used to overwrite the first in the map, so traffic for host A silently reached
948
+ // host B. Keep the first and say what was dropped.
949
+ const wanted = new Map()
950
+ for (const target of shadowTargets(nextConfig)) {
951
+ if (wanted.has(target.localPort)) {
952
+ const kept = wanted.get(target.localPort)
953
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${target.localPort} 已被 ${kept.host}:${kept.port} 占用,忽略 ${target.host}:${target.port}`)
954
+ continue
955
+ }
956
+ wanted.set(target.localPort, target)
957
+ }
958
+ for (const [localPort, server] of shadowServers) {
959
+ if (wanted.has(localPort)) continue
960
+ try { server.close() } catch { /* already gone */ }
961
+ shadowServers.delete(localPort)
962
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${localPort} removed`)
963
+ }
964
+ for (const [localPort, target] of wanted) {
965
+ if (shadowServers.has(localPort)) continue
966
+ // A shadow is a convenience (local clients like Navicat dial 127.0.0.1); losing one
967
+ // port must never kill the CONNECT proxy that the enforcement path needs.
968
+ const server = startShadow(target, nextConfig.socks, (error) => {
969
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${localPort} 不可用: ${error?.message ?? error}`)
970
+ shadowServers.delete(localPort)
971
+ try { server.close() } catch { /* not listening */ }
972
+ }, onConnError)
973
+ shadowServers.set(localPort, server)
974
+ log(`[${PROXY_MARKER}] shadow 127.0.0.1:${localPort} -> ${target.host}:${target.port}`)
975
+ }
976
+ }
977
+ applyShadows(config)
978
+ /**
979
+ * Re-read the config and apply it without dropping the process: rules are edited
980
+ * while the proxy keeps running (no restart, in-flight connections keep going).
981
+ */
982
+ const reload = () => {
983
+ if (typeof options.readConfig !== 'function') return
984
+ let next = null
985
+ try {
986
+ next = options.readConfig()
987
+ } catch (error) {
988
+ log(`[${PROXY_MARKER}] reload failed: ${error?.message ?? error}`)
989
+ return
990
+ }
991
+ if (next === null || next === undefined) return
992
+ if (next.socks.host === '' || next.socks.port === 0) {
993
+ log(`[${PROXY_MARKER}] reload skipped: SOCKS 上游未配置`)
994
+ return
995
+ }
996
+ state.config = next
997
+ applyShadows(next)
998
+ const enabled = next.rules.filter((rule) => rule.enabled).length
999
+ log(`[${PROXY_MARKER}] reloaded: ${enabled} rules`)
1000
+ }
1001
+ if (typeof options.readConfig === 'function') {
1002
+ if (typeof options.configPath === 'string' && options.configPath !== '') {
1003
+ watchFile(options.configPath, { interval: 1000 }, reload)
1004
+ } else {
1005
+ setInterval(reload, 2000).unref?.()
1006
+ }
1007
+ }
1008
+ let stopped = false
1009
+ function shutdown(code) {
1010
+ if (stopped) return
1011
+ stopped = true
1012
+ for (const server of servers) {
1013
+ try { server.close() } catch { /* already closed */ }
1014
+ }
1015
+ setTimeout(() => process.exit(code), 50).unref?.()
1016
+ }
1017
+ process.on('SIGTERM', () => shutdown(0))
1018
+ process.on('SIGINT', () => shutdown(0))
1019
+ log(`[${PROXY_MARKER}] ready (${servers.length} listeners)`)
1020
+ return new Promise(() => {})
1021
+ }
1022
+
1023
+ /* ------------------------------------------------------------ process life -- */
1024
+
1025
+ /** Whether a pid is alive. */
1026
+ export function pidAlive(pid) {
1027
+ if (!Number.isInteger(pid) || pid <= 0) return false
1028
+ try {
1029
+ process.kill(pid, 0)
1030
+ return true
1031
+ } catch (error) {
1032
+ return error?.code === 'EPERM'
1033
+ }
1034
+ }
1035
+
1036
+ /**
1037
+ * The command line of a pid, or '' when it cannot be read. Linux/WSL read
1038
+ * `/proc`; Windows asks CIM (Node has no /proc there, and a pidfile alone must
1039
+ * NEVER be enough to justify a kill); macOS uses `ps`.
1040
+ * @param pid - candidate process id.
1041
+ * @returns the command line text.
1042
+ */
1043
+ export function pidCommandLine(pid) {
1044
+ if (!Number.isInteger(pid) || pid <= 0) return ''
1045
+ if (IS_WINDOWS) {
1046
+ try {
1047
+ const text = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
1048
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], { encoding: 'utf8', timeout: 8000, windowsHide: true })
1049
+ return text.trim()
1050
+ } catch {
1051
+ return ''
1052
+ }
1053
+ }
1054
+ if (process.platform === 'darwin') {
1055
+ try {
1056
+ return execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 4000 }).trim()
1057
+ } catch {
1058
+ return ''
1059
+ }
1060
+ }
1061
+ try {
1062
+ return readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ')
1063
+ } catch {
1064
+ return ''
1065
+ }
1066
+ }
1067
+
1068
+ /** Whether a pid's command line carries our marker (never signal a stranger). */
1069
+ export function pidIsProxy(pid) {
1070
+ if (!pidAlive(pid)) return false
1071
+ const commandLine = pidCommandLine(pid)
1072
+ return commandLine !== '' && commandLine.includes(PROXY_MARKER)
1073
+ }
1074
+
1075
+ /** The running engine's pid, or null (stale pidfile is removed). */
1076
+ export function proxyPid(cwd) {
1077
+ const path = proxyPidPath()
1078
+ if (!existsSync(path)) return null
1079
+ const text = readFileSync(path, 'utf8').trim()
1080
+ const pid = Number(text)
1081
+ if (!Number.isInteger(pid) || pid <= 0) {
1082
+ try { unlinkSync(path) } catch { /* ignore */ }
1083
+ return null
1084
+ }
1085
+ if (pidIsProxy(pid)) return pid
1086
+ try { unlinkSync(path) } catch { /* ignore */ }
1087
+ return null
1088
+ }
1089
+
1090
+ /** Whether something is listening on a loopback port. */
1091
+ export function portOpen(port, host = '127.0.0.1') {
1092
+ return new Promise((resolvePromise) => {
1093
+ const socket = netConnect({ host, port })
1094
+ const done = (value) => { socket.destroy(); resolvePromise(value) }
1095
+ socket.setTimeout(800, () => done(false))
1096
+ socket.once('connect', () => done(true))
1097
+ socket.once('error', () => done(false))
1098
+ })
1099
+ }
1100
+
1101
+ /**
1102
+ * Terminate an engine we ourselves just spawned and that failed to come up.
1103
+ *
1104
+ * Identity is re-checked before signalling: `pid` comes from our own child, but by the
1105
+ * time an 8 s wait is over it may have exited and been recycled — and the marker in
1106
+ * argv is the only proof that the process is ours.
1107
+ */
1108
+ async function reapFailedStart(pid, logPath) {
1109
+ if (pidIsProxy(pid) !== true) return
1110
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
1111
+ for (let attempt = 0; attempt < 20; attempt += 1) {
1112
+ if (pidAlive(pid) !== true) return
1113
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 100))
1114
+ }
1115
+ if (IS_WINDOWS) {
1116
+ try { execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }) } catch { /* ignore */ }
1117
+ } else {
1118
+ try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ }
1119
+ }
1120
+ try { appendFileSync(logPath, `[${PROXY_MARKER}] startup failed: process ${pid} killed\n`) } catch { /* ignore */ }
1121
+ }
1122
+
1123
+ /**
1124
+ * Start the engine detached, with a pidfile + log, and wait until every listener
1125
+ * answers. Verifies identity after the wait: a process that dies or never binds
1126
+ * is reported as a failure, never as "started".
1127
+ * @param cwd - workspace directory holding `.dsh-ris-ide/`.
1128
+ * @param options - `{ config, waitMs }`.
1129
+ * @returns `{ ok, pid?, config, error? }`.
1130
+ */
1131
+ export async function startProxy(cwd, options = {}) {
1132
+ const config = options.config ?? readProxyConfig(cwd)
1133
+ const existing = proxyPid(cwd)
1134
+ if (existing !== null) return { ok: true, pid: existing, config, alreadyRunning: true }
1135
+ if (config.socks.host === '' || config.socks.port === 0) return { ok: false, config, error: '上游 SOCKS 地址未配置(.env 的 socks.host / socks.port)' }
1136
+ const enabled = config.rules.filter((rule) => rule.enabled)
1137
+ if (enabled.length === 0) return { ok: false, config, error: '没有启用任何代理规则' }
1138
+ // The pidfile and the log live in the machine-wide home, not under the workspace:
1139
+ // creating only `cwd/.dsh-ris-ide` (a legacy location) left a fresh home missing and
1140
+ // `openSync` failed with ENOENT on the very first start.
1141
+ const logPath = proxyLogPath()
1142
+ const pidPath = proxyPidPath()
1143
+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 })
1144
+ mkdirSync(dirname(pidPath), { recursive: true, mode: 0o700 })
1145
+ const out = openSync(logPath, 'a', 0o600)
1146
+ // The child re-enters this file as a CLI: `serve` must be a POSITIONAL command
1147
+ // (a `--serve` flag would fall through to the default status command).
1148
+ // The marker travels in argv: it is the ONLY proof a pid is our engine (a
1149
+ // pidfile can be stale, and a recycled pid must never be signalled).
1150
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--cwd', cwd, 'serve', `--marker=${PROXY_MARKER}`], {
1151
+ cwd,
1152
+ detached: true,
1153
+ stdio: ['ignore', out, out],
1154
+ windowsHide: true,
1155
+ })
1156
+ closeSync(out)
1157
+ child.unref()
1158
+ try { writeFileSync(pidPath, String(child.pid), { encoding: 'utf8', mode: 0o600 }) } catch { /* ignore */ }
1159
+ const ports = [config.listenPort, ...shadowTargets(config).map((target) => target.localPort)]
1160
+ const budget = Number.isInteger(options.waitMs) ? options.waitMs : 150
1161
+ const rounds = Math.max(1, Math.ceil(8000 / budget))
1162
+ for (let round = 0; round < rounds; round += 1) {
1163
+ const states = await Promise.all(ports.map((port) => portOpen(port)))
1164
+ if (states.every(Boolean) && pidIsProxy(child.pid)) {
1165
+ return { ok: true, pid: child.pid, config, ports, logPath }
1166
+ }
1167
+ if (!pidAlive(child.pid)) break
1168
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, budget))
1169
+ }
1170
+ // A failed start must not leave a half-up engine behind: it keeps the loopback ports
1171
+ // bound, so the next attempt fails with EADDRINUSE for a process nobody can see.
1172
+ await reapFailedStart(child.pid, logPath)
1173
+ try { unlinkSync(pidPath) } catch { /* ignore */ }
1174
+ const tail = readTail(logPath, 2048)
1175
+ const reason = pidAlive(child.pid) ? `端口 ${ports.join(', ')} 未就绪或进程身份不匹配` : '进程已退出'
1176
+ // EADDRINUSE is the multi-workspace case: every workspace's engine binds the
1177
+ // SAME 127.0.0.1 ports, so the second one cannot start — say so instead of
1178
+ // leaving the user with a bare port number.
1179
+ const busy = /EADDRINUSE/i.test(tail)
1180
+ const hint = busy
1181
+ ? '\n端口已被占用:通常是另一个工作区的代理引擎绑定着同一批 127.0.0.1 端口。先在那个工作区停止代理(或关掉它的 127.0.0.1 映射),再启动这一个。'
1182
+ : ''
1183
+ return { ok: false, config, error: `代理未能启动(${reason})${hint}${tail === '' ? '' : `\n${tail}`}`, logPath }
1184
+ }
1185
+
1186
+ /** Stop the detached engine (TERM → 30 s → KILL). Never signals a stranger. */
1187
+ export async function stopProxy(cwd, options = {}) {
1188
+ const pid = proxyPid(cwd)
1189
+ if (pid === null) return { ok: true, stopped: false }
1190
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
1191
+ const grace = Number.isInteger(options.graceMs) ? options.graceMs : 5000
1192
+ const deadline = Date.now() + grace
1193
+ while (Date.now() < deadline) {
1194
+ if (!pidAlive(pid)) break
1195
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 120))
1196
+ }
1197
+ if (pidAlive(pid)) {
1198
+ // Windows has no SIGKILL worth the name: taskkill /T /F is the tree kill.
1199
+ if (IS_WINDOWS) {
1200
+ try { execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }) } catch { /* ignore */ }
1201
+ } else {
1202
+ try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ }
1203
+ }
1204
+ }
1205
+ try { unlinkSync(proxyPidPath()) } catch { /* ignore */ }
1206
+ return { ok: true, stopped: true, pid }
1207
+ }
1208
+
1209
+ /**
1210
+ * Stop the engine from an exit handler.
1211
+ *
1212
+ * `process.on('exit')` cannot await anything, so this only sends the signal
1213
+ * (TERM, then a hard kill on Windows) and unlinks the pidfile; the engine itself
1214
+ * shuts its listeners down on TERM. Safe to call when nothing is running.
1215
+ * @param cwd - any workspace; the pid/pidfile are machine-wide.
1216
+ * @returns the pid that was signalled, or null.
1217
+ */
1218
+ export function stopProxySync(cwd = '') {
1219
+ const pid = proxyPid(cwd)
1220
+ if (pid === null) return null
1221
+ if (IS_WINDOWS) {
1222
+ try { execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }) } catch { /* already gone */ }
1223
+ } else {
1224
+ try { process.kill(pid, 'SIGTERM') } catch { /* already gone */ }
1225
+ }
1226
+ try { unlinkSync(proxyPidPath()) } catch { /* ignore */ }
1227
+ return pid
1228
+ }
1229
+
1230
+ /** One-shot status for the UI: config, listeners, pid. */
1231
+ export async function proxyStatus(cwd) {
1232
+ const config = readProxyConfig(cwd)
1233
+ const pid = proxyPid(cwd)
1234
+ const ports = [config.listenPort, ...shadowTargets(config).map((target) => target.localPort)]
1235
+ const states = await Promise.all(ports.map((port) => portOpen(port)))
1236
+ return {
1237
+ config,
1238
+ running: pid !== null,
1239
+ pid,
1240
+ listen: ports.map((port, index) => ({ port, open: states[index] === true })),
1241
+ logPath: proxyLogPath(),
1242
+ socksUrl: config.socks.host === '' ? null : `socks5h://${config.socks.host}:${config.socks.port}`,
1243
+ }
1244
+ }
1245
+
1246
+ /** Tail of a text file (a log we may be appending to in another process). */
1247
+ export function readTail(path, bytes) {
1248
+ try {
1249
+ const size = statSync(path).size
1250
+ const length = Math.min(bytes, size)
1251
+ const buffer = Buffer.alloc(length)
1252
+ const fd = openSync(path, 'r')
1253
+ try {
1254
+ readSync(fd, buffer, 0, length, size - length)
1255
+ } finally {
1256
+ closeSync(fd)
1257
+ }
1258
+ return buffer.toString('utf8')
1259
+ } catch {
1260
+ return ''
1261
+ }
1262
+ }
1263
+
1264
+ /* -------------------------------------------------------------------- git -- */
1265
+
1266
+ /**
1267
+ * Apply / clear the SCOPE-LIMITED git proxy: one `http.proxy` entry (global
1268
+ * config) pointing at the upstream SOCKS server, so every git caller — the CLI,
1269
+ * the IDE, another plugin — uses the tunnel without a per-command flag.
1270
+ * @param config - a normalised config.
1271
+ * @param options - `{ host, enabled }`; host narrows the entry to one URL prefix.
1272
+ * @returns `{ ok, changed, key, value }`.
1273
+ */
1274
+ /**
1275
+ * Windows git, as a path this process can execute.
1276
+ *
1277
+ * The WSL `git` writes `~/.gitconfig` inside Linux; a git started on the Windows side
1278
+ * (YonCode, VS Code, a cmd window) reads a different file and its DNS cannot resolve
1279
+ * the internal git host at all — so the same scoped proxy has to exist on both sides.
1280
+ * `where.exe` is asked each time: cheap, and it follows the user's PATH.
1281
+ * @returns {string} an executable path, '' when Windows has no git.
1282
+ */
1283
+ export function windowsGitPath() {
1284
+ try {
1285
+ const out = spawnSyncImpl('where.exe', ['git'], { encoding: 'utf8', windowsHide: true, timeout: 5000 })
1286
+ if (out.status !== 0) return ''
1287
+ const lines = String(out.stdout ?? '').split(/\r?\n/).map((line) => line.trim())
1288
+ const exe = lines.find((line) => /git\.exe$/i.test(line) === true)
1289
+ if (exe === undefined) return ''
1290
+ const mounted = /^([A-Za-z]):\\(.*)$/.exec(exe)
1291
+ if (mounted === null) return exe
1292
+ return `${mounted[1].toLowerCase() === '' ? '' : `/mnt/${mounted[1].toLowerCase()}/`}${mounted[2].replace(/\\/g, '/')}`
1293
+ } catch {
1294
+ return ''
1295
+ }
1296
+ }
1297
+
1298
+ /**
1299
+ * Run the Windows git with one `config --global` mutation.
1300
+ * @param {string[]} args - arguments after `config --global`.
1301
+ * @returns {{ok: boolean, skipped?: boolean, error?: string}} outcome; a machine
1302
+ * without Windows git reports `skipped` instead of failing the caller.
1303
+ */
1304
+ export function runWindowsGitConfig(args) {
1305
+ const exe = windowsGitPath()
1306
+ if (exe === '') return { ok: false, skipped: true, error: 'Windows 侧没有 git' }
1307
+ try {
1308
+ const out = spawnSyncImpl(exe, ['config', '--global', ...args], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
1309
+ if (out.status === 0) return { ok: true }
1310
+ return { ok: false, error: String(out.stderr ?? '').trim() || `git.exe exited with ${out.status}` }
1311
+ } catch (error) {
1312
+ return { ok: false, error: String(error?.message ?? error) }
1313
+ }
1314
+ }
1315
+
1316
+ export function gitProxyPlan(config, options = {}) {
1317
+ const host = typeof options.host === 'string' ? options.host.trim() : ''
1318
+ const enabled = options.enabled !== false
1319
+ const key = host === '' ? 'http.proxy' : `http.https://${host}/.proxy`
1320
+ const value = enabled && config.socks.host !== '' ? `socks5h://${config.socks.host}:${config.socks.port}` : ''
1321
+ return { ok: true, key, value, host, enabled }
1322
+ }
1323
+
1324
+ /* -------------------------------------------------------------------- cli -- */
1325
+
1326
+ /**
1327
+ * CLI entry: `node lib/proxy.js --cwd=<dir> <command>`.
1328
+ * Commands: `serve` (foreground engine), `start`, `stop`, `status`, `rules`
1329
+ * (prints the effective config as JSON), `apply --json=<cfg>|--stdin` (merge
1330
+ * rules into the stored config), `git --host=… [--off]`.
1331
+ * @param argv - process.argv.slice(2).
1332
+ * @returns exit code.
1333
+ */
1334
+ export async function main(argv) {
1335
+ const args = argv.slice()
1336
+ let cwd = process.cwd()
1337
+ const positional = []
1338
+ const flags = {}
1339
+ for (let index = 0; index < args.length; index += 1) {
1340
+ const token = args[index]
1341
+ if (token === '--cwd' || token === '-C') {
1342
+ cwd = resolve(args[index + 1] ?? cwd)
1343
+ index += 1
1344
+ continue
1345
+ }
1346
+ if (token.startsWith('--cwd=')) {
1347
+ cwd = resolve(token.slice('--cwd='.length))
1348
+ continue
1349
+ }
1350
+ if (token.startsWith('--')) {
1351
+ const [name, inline] = token.slice(2).split('=', 2)
1352
+ if (inline !== undefined) {
1353
+ flags[name] = inline
1354
+ continue
1355
+ }
1356
+ const next = args[index + 1]
1357
+ if (next !== undefined && !next.startsWith('--')) {
1358
+ flags[name] = next
1359
+ index += 1
1360
+ } else {
1361
+ flags[name] = 'true'
1362
+ }
1363
+ continue
1364
+ }
1365
+ positional.push(token)
1366
+ }
1367
+ const command = positional[0] ?? 'status'
1368
+ if (!isAbsolute(cwd)) cwd = resolve(cwd)
1369
+ if (command === 'serve') {
1370
+ await runEngine(readProxyConfig(cwd), {
1371
+ log: (line) => console.log(line),
1372
+ configPath: proxyConfigPath(),
1373
+ readConfig: () => readProxyConfig(cwd),
1374
+ })
1375
+ return 0
1376
+ }
1377
+ if (command === 'start') {
1378
+ const result = await startProxy(cwd)
1379
+ console.log(JSON.stringify(result))
1380
+ return result.ok ? 0 : 1
1381
+ }
1382
+ if (command === 'stop') {
1383
+ console.log(JSON.stringify(await stopProxy(cwd)))
1384
+ return 0
1385
+ }
1386
+ if (command === 'status') {
1387
+ console.log(JSON.stringify(await proxyStatus(cwd)))
1388
+ return 0
1389
+ }
1390
+ if (command === 'rules') {
1391
+ console.log(JSON.stringify(readProxyConfig(cwd)))
1392
+ return 0
1393
+ }
1394
+ if (command === 'apply') {
1395
+ let incoming = null
1396
+ if (typeof flags.json === 'string' && flags.json !== 'true') {
1397
+ incoming = JSON.parse(flags.json)
1398
+ } else {
1399
+ const chunks = []
1400
+ for await (const chunk of process.stdin) chunks.push(chunk)
1401
+ incoming = JSON.parse(Buffer.concat(chunks).toString('utf8'))
1402
+ }
1403
+ const stored = readProxyConfig(cwd)
1404
+ const next = mergeConfigs(stored, incoming)
1405
+ const written = writeProxyConfig(cwd, next)
1406
+ console.log(JSON.stringify({ ok: true, config: written }))
1407
+ return 0
1408
+ }
1409
+ if (command === 'git') {
1410
+ const plan = gitProxyPlan(readProxyConfig(cwd), { host: flags.host, enabled: flags.off !== 'true' })
1411
+ console.log(JSON.stringify(plan))
1412
+ return 0
1413
+ }
1414
+ console.error(`unknown command "${command}" (serve|start|stop|status|rules|apply|git)`)
1415
+ return 2
1416
+ }
1417
+
1418
+ /**
1419
+ * Merge an incoming config into the shared one.
1420
+ *
1421
+ * The file is machine-level, so two workspaces write into the same object. Rule
1422
+ * identity is therefore `(workspace, id)`, and `replaceRulesFrom` only clears the
1423
+ * rows of ONE owner: the caller passes `{ replaceRulesFrom: '<source>',
1424
+ * workspace: '<dir>' }` to refresh its own rows and leave everyone else's alone.
1425
+ * @param stored - the config currently in the shared file.
1426
+ * @param incoming - partial config from a caller.
1427
+ * @returns a normalised merged config.
1428
+ */
1429
+ export function mergeConfigs(stored, incoming) {
1430
+ const base = normalizeConfig(stored)
1431
+ const patch = incoming !== null && typeof incoming === 'object' ? incoming : {}
1432
+ const patchWorkspace = typeof patch.workspace === 'string' ? patch.workspace : undefined
1433
+ const mergedRules = base.rules.slice()
1434
+ const dropped = new Set()
1435
+ // Rules are machine-wide, so a patch never replaces "one workspace's rows":
1436
+ // it either replaces all rows of a SOURCE (what the yds bridge does, so a
1437
+ // removed endpoint disappears) or upserts rows by id.
1438
+ if (typeof patch.replaceRulesFrom === 'string' || patch.replaceRules === true) {
1439
+ const source = typeof patch.replaceRulesFrom === 'string' ? patch.replaceRulesFrom : ''
1440
+ for (const rule of mergedRules) {
1441
+ if (rule.source === source) dropped.add(rule.id)
1442
+ }
1443
+ }
1444
+ if (Array.isArray(patch.rules)) {
1445
+ for (const rule of patch.rules) {
1446
+ if (rule === null || typeof rule !== 'object') continue
1447
+ const id = typeof rule.id === 'string' && rule.id !== '' ? rule.id : `rule-${mergedRules.length + 1}`
1448
+ // Keep an existing row's provenance when the caller does not restate it,
1449
+ // so editing from a second workspace does not relabel the origin.
1450
+ const existing = mergedRules.find((item) => item.id === id)
1451
+ const workspace = typeof rule.workspace === 'string' && rule.workspace !== ''
1452
+ ? rule.workspace
1453
+ : (existing?.workspace ?? patchWorkspace ?? '')
1454
+ const index = mergedRules.findIndex((item) => item.id === id)
1455
+ const row = {
1456
+ id,
1457
+ // Provenance label from whoever generated the row ("YonCode java"); an edit
1458
+ // that does not restate it keeps the stored one.
1459
+ label: typeof rule.label === 'string' && rule.label !== ''
1460
+ ? rule.label.trim().slice(0, 60)
1461
+ : (existing?.label ?? ''),
1462
+ program: typeof rule.program === 'string' ? rule.program : '',
1463
+ hosts: typeof rule.hosts === 'string' ? rule.hosts : '',
1464
+ ports: typeof rule.ports === 'string' ? rule.ports : '',
1465
+ enabled: rule.enabled === true,
1466
+ // `undefined` keeps the automatic choice (no mapping for SOCKS-aware
1467
+ // programs); a boolean is the caller's explicit decision.
1468
+ shadow: typeof rule.shadow === 'boolean' ? rule.shadow : undefined,
1469
+ // `undefined` keeps the stored decision: flipping the field on every edit
1470
+ // that does not restate it would silently re-enable the allow-list
1471
+ // (or silently bypass it, which is worse).
1472
+ direct: typeof rule.direct === 'boolean' ? rule.direct : existing?.direct === true,
1473
+ source: typeof rule.source === 'string' ? rule.source : 'user',
1474
+ workspace,
1475
+ }
1476
+ if (index === -1) mergedRules.push(row)
1477
+ else mergedRules[index] = row
1478
+ dropped.delete(id)
1479
+ }
1480
+ }
1481
+ return normalizeConfig({
1482
+ socks: patch.socks !== undefined ? patch.socks : base.socks,
1483
+ listenPort: patch.listenPort !== undefined ? patch.listenPort : base.listenPort,
1484
+ rules: mergedRules.filter((rule) => !dropped.has(rule.id)),
1485
+ // The fallback listener list is owned by whoever drives the tunnel, so it is
1486
+ // replaced wholesale rather than merged row by row.
1487
+ shadows: Array.isArray(patch.shadows) ? patch.shadows : base.shadows,
1488
+ })
1489
+ }
1490
+
1491
+ if (process.argv[1] !== undefined && /proxy\.js$/.test(process.argv[1])) {
1492
+ main(process.argv.slice(2)).then((code) => {
1493
+ if (code !== 0) process.exitCode = code
1494
+ }).catch((error) => {
1495
+ console.error(error?.stack ?? String(error))
1496
+ process.exitCode = 1
1497
+ })
1498
+ }