dsh-proxy-enhance 0.0.0-stage → 0.1.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.
package/index.js ADDED
@@ -0,0 +1,322 @@
1
+ // Host half: owns the proxy settings and makes a saved change take effect.
2
+ //
3
+ // Four rules shape this file:
4
+ //
5
+ // 1. The launcher resolves the Harness home itself (`configured → $DSH_HOME →
6
+ // ~/.dsh`) and only then reads `<home>/.env`. Guessing that path from
7
+ // `process.env` writes a file the launcher never reads, so the home comes
8
+ // from `profileContext.home`, falling back to the shared resolver.
9
+ // 2. The form owns only the fields the user actually edited. A proxy exported
10
+ // by the shell, or written into `.env` by hand, keeps working until the user
11
+ // takes that field over in the form — which is what the page says.
12
+ // 3. A write that did not happen is reported, not logged. The outcome lands in
13
+ // the volatile `envSync` field the page renders, so "saved" never claims
14
+ // "persisted" when it did not.
15
+ // 4. A saved change applies immediately, and `.env` is what survives a restart.
16
+ // The live policy is re-installed from the saved values through
17
+ // `installCidrProxy`, which reuses the official resolution and adds CIDR
18
+ // bypass matching the launcher-side matcher cannot express.
19
+ //
20
+ // Credentials: the launcher reads a proxy from the environment at start, so an
21
+ // authenticated proxy URL has to live in `.env` to survive a restart. The profile
22
+ // patch holds the URL with userinfo stripped; `.env` holds it whole. This plugin
23
+ // does not change an existing `.env`'s mode — the file belongs to the user — and
24
+ // only a file it creates is written as 0600. A second copy in the credential
25
+ // store would add a sync failure mode without hiding anything the launcher must
26
+ // eventually read.
27
+
28
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
29
+ import { dirname, join } from 'node:path'
30
+ import { fileURLToPath } from 'node:url'
31
+ import z from '@deepseek-ai/schemastery'
32
+ import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write'
33
+ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
34
+ import { cidrEntriesOf, installCidrProxy } from './route.js'
35
+ import {
36
+ ownershipOverlay,
37
+ PROXY_FIELDS,
38
+ readEnv,
39
+ rewriteEnv,
40
+ } from './env.js'
41
+
42
+ export const name = 'dsh-proxy-enhance'
43
+
44
+ /**
45
+ * The page's source of truth. `envSync` is Host-written: it carries the outcome
46
+ * of the last `.env` write and policy install so the page can show a failure it
47
+ * did not cause.
48
+ */
49
+ export const Config = z.object({
50
+ enabled: z.boolean().default(true).volatile(),
51
+ httpProxy: z.string().default('').volatile(),
52
+ httpsProxy: z.string().default('').volatile(),
53
+ allProxy: z.string().default('').volatile(),
54
+ noProxy: z.string().default('').volatile(),
55
+ envSync: z.string().default('').volatile()
56
+ .description('Outcome of the last save: empty, "written", or "failed: <reason>".'),
57
+ })
58
+
59
+ const SETTINGS_NAMESPACE = 'proxy-enhance'
60
+ const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write')
61
+ const WRITE_WAIT_MS = 5_000
62
+ const MANAGED_KEYS = Object.freeze({
63
+ http_proxy: 'HTTP_PROXY',
64
+ https_proxy: 'HTTPS_PROXY',
65
+ all_proxy: 'ALL_PROXY',
66
+ })
67
+
68
+ /** Read one volatile field, falling back when it is absent or unreadable. */
69
+ const read = (field, fallback) => {
70
+ try {
71
+ const value = field?.get?.()
72
+ return value === undefined || value === null ? fallback : value
73
+ } catch {
74
+ return fallback
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Resolve the file the launcher really reads.
80
+ *
81
+ * @param ctx - the plugin context.
82
+ * @returns absolute path of the Harness home's `.env`.
83
+ */
84
+ export function envPathOf(ctx) {
85
+ const home = ctx.profileContext?.home ?? resolveDshHome()
86
+ return join(home, '.env')
87
+ }
88
+
89
+ /**
90
+ * The path a write should really touch.
91
+ *
92
+ * A `.env` is sometimes a symlink into a dotfiles repo. Resolving it means the
93
+ * rename replaces the referent's content instead of turning the user's link
94
+ * into a regular file, which would silently detach their dotfiles checkout.
95
+ *
96
+ * @param path - the configured `.env` path.
97
+ * @returns the real file path to write.
98
+ */
99
+ export function resolveWriteTarget(path) {
100
+ try {
101
+ return realpathSync(path)
102
+ } catch {
103
+ return path
104
+ }
105
+ }
106
+
107
+ /**
108
+ * The proxy environment names the launcher resolved at start, by scheme.
109
+ *
110
+ * Reads the launcher's frozen snapshot rather than `process.env`: the snapshot
111
+ * knows whether a value was exported (`process`) or came from a `.env` file
112
+ * (`user-env`), which is the difference between "the form owns this" and
113
+ * "something else already does".
114
+ *
115
+ * @param environment - the launch environment snapshot.
116
+ * @returns one entry per proxy name that something supplies.
117
+ */
118
+ export function launchProxySources(environment) {
119
+ const sources = {}
120
+ for (const name of ['http_proxy', 'https_proxy', 'all_proxy', 'no_proxy']) {
121
+ const hit = environment.get(name) ?? environment.get(name.toUpperCase())
122
+ if (hit !== undefined) sources[name] = hit.source
123
+ }
124
+ return sources
125
+ }
126
+
127
+ function packageVersion() {
128
+ try {
129
+ return JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8')).version
130
+ } catch {
131
+ return '2.0.0'
132
+ }
133
+ }
134
+
135
+ export function apply(ctx, config, internals = {}) {
136
+ // A shipped Settings service may load later; the child effect re-registers.
137
+ ctx.inject(['settings'], (child) => {
138
+ child.effect(() => child.settings.configure({ auto: false }, ctx.fiber))
139
+ })
140
+
141
+ // Where each proxy came from, so the page can say "a proxy you exported is
142
+ // still in force" instead of implying the form is the only source.
143
+ let proxySources = {}
144
+ ctx.inject(['launchEnvironment'], (child) => {
145
+ child.effect(() => {
146
+ proxySources = launchProxySources(child.launchEnvironment)
147
+ return () => {
148
+ proxySources = {}
149
+ }
150
+ }, 'dsh-proxy-enhance: launch sources')
151
+ })
152
+
153
+ const valuesOf = () => ({
154
+ enabled: Boolean(read(config.enabled, true)),
155
+ httpProxy: String(read(config.httpProxy, '')),
156
+ httpsProxy: String(read(config.httpsProxy, '')),
157
+ allProxy: String(read(config.allProxy, '')),
158
+ noProxy: String(read(config.noProxy, '')),
159
+ })
160
+
161
+ const editedFields = new Set()
162
+ let lastSeen = shadowOf(valuesOf())
163
+ let running = false
164
+ let dirty = false
165
+ let disposed = false
166
+ /** Disposer for the live policy installed by the last successful save. */
167
+ let disposePolicy
168
+
169
+ const report = (status) => {
170
+ try {
171
+ config.envSync?.[VOLATILE_WRITE]?.(status)
172
+ } catch {
173
+ // A page that cannot be told still beats throwing from a background sync.
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Install the saved values as the live policy.
179
+ *
180
+ * The launcher's own install (from `.env` at start) is left alone: this adds a
181
+ * newer policy on top and restores the previous one when the settings change
182
+ * again or the plugin unloads, so the process never carries two answers.
183
+ */
184
+ const installPolicy = async (values) => {
185
+ if (disposePolicy !== undefined) {
186
+ const previous = disposePolicy
187
+ disposePolicy = undefined
188
+ await previous()
189
+ }
190
+ if (!values.enabled) return
191
+ const env = {
192
+ http_proxy: values.httpProxy,
193
+ https_proxy: values.httpsProxy,
194
+ all_proxy: values.allProxy,
195
+ no_proxy: values.noProxy,
196
+ }
197
+ if (env.http_proxy === '' && env.https_proxy === '' && env.all_proxy === '') return
198
+ // A test can observe what the live policy was built from without touching a
199
+ // process-wide dispatcher; production leaves this undefined.
200
+ const install = internals.installPolicy ?? installCidrProxy
201
+ const dispose = await install(env, {
202
+ report: (message) => ctx.logger?.warn?.(`dsh-proxy-enhance: ${message}`),
203
+ })
204
+ if (disposed) {
205
+ // The plugin unloaded while the dispatcher was being built.
206
+ await dispose()
207
+ return
208
+ }
209
+ disposePolicy = dispose
210
+ }
211
+
212
+ const syncAll = async () => {
213
+ if (running) {
214
+ dirty = true
215
+ return
216
+ }
217
+ running = true
218
+ try {
219
+ const values = valuesOf()
220
+ const overlay = ownershipOverlay(values, editedFields)
221
+
222
+ // Nothing owned means the form is showing inherited values: leave the file
223
+ // and the live policy exactly as the launcher set them up.
224
+ if (Object.keys(overlay).length === 0) {
225
+ report('')
226
+ return
227
+ }
228
+
229
+ const path = resolveWriteTarget(envPathOf(ctx))
230
+ await withFileLock(path, async () => {
231
+ const original = existsSync(path) ? readFileSync(path, 'utf8') : ''
232
+ const next = rewriteEnv(original, overlay)
233
+ if (next === original) return
234
+ const exists = existsSync(path)
235
+ // Never change the mode of a file the user already owns: their .env, their
236
+ // rules. Only a file this plugin creates gets a private default, because
237
+ // there is no existing choice to respect.
238
+ const mode = exists ? statSync(path).mode & 0o777 : 0o600
239
+ await writeFileAtomic(path, next, { mode, dirMode: 0o700 })
240
+ }, { waitMs: WRITE_WAIT_MS })
241
+
242
+ // `.env` is what a restart reads; the live policy is what this process
243
+ // uses now. A CIDR entry only works through the latter. The two are
244
+ // reported apart: the file is already committed here, so a policy failure
245
+ // must not claim the save itself was lost.
246
+ const exported = Object.keys(proxySources).filter((name) => proxySources[name] === 'process')
247
+ const persist = exported.length > 0 ? `written: exported ${exported.join(',')}` : 'written'
248
+ let liveFailure
249
+ try {
250
+ await installPolicy(values)
251
+ } catch (error) {
252
+ liveFailure = error?.message ?? String(error)
253
+ ctx.logger?.warn?.(`dsh-proxy-enhance: live policy not installed: ${liveFailure}`)
254
+ }
255
+
256
+ lastSeen = shadowOf(valuesOf())
257
+ report(liveFailure === undefined ? persist : `${persist} live-failed: ${liveFailure}`)
258
+ } catch (error) {
259
+ const reason = error?.message ?? String(error)
260
+ ctx.logger?.warn?.(`dsh-proxy-enhance: save failed: ${reason}`)
261
+ // Nothing was committed: the file, the policy, and the form all still hold
262
+ // the previous values.
263
+ report(`failed: ${reason}`)
264
+ } finally {
265
+ running = false
266
+ if (dirty && !disposed) {
267
+ dirty = false
268
+ void syncAll()
269
+ }
270
+ }
271
+ }
272
+
273
+ ctx.effect(() => {
274
+ void syncAll()
275
+ const offSettings = ctx.on('settings/document-updated', (namespace) => {
276
+ if (namespace !== SETTINGS_NAMESPACE) return
277
+ const current = shadowOf(valuesOf())
278
+ for (const field of Object.keys(current)) {
279
+ if (current[field] === lastSeen[field]) continue
280
+ if (field === 'enabled') {
281
+ // The switch is the user's "stop using a proxy" action, so it takes
282
+ // over every proxy field at once.
283
+ for (const { field: name } of PROXY_FIELDS) editedFields.add(name)
284
+ continue
285
+ }
286
+ editedFields.add(field)
287
+ }
288
+ lastSeen = current
289
+ void syncAll()
290
+ })
291
+ return () => {
292
+ disposed = true
293
+ offSettings?.()
294
+ const pending = disposePolicy
295
+ disposePolicy = undefined
296
+ void pending?.()
297
+ }
298
+ })
299
+
300
+ // Exposed for tests and for a Host-side tool: the sources the page reads and
301
+ // where the file lives, without any credential the page must not reveal.
302
+ ctx.provide('dsh-proxy-enhance/state', {
303
+ values: valuesOf,
304
+ sources: () => ({ ...proxySources }),
305
+ exported: () => Object.keys(proxySources).filter((name) => proxySources[name] === 'process'),
306
+ cidr: () => cidrEntriesOf(valuesOf().noProxy),
307
+ path: () => envPathOf(ctx),
308
+ })
309
+ }
310
+
311
+ /** Comparable snapshot of the fields a change is detected against. */
312
+ function shadowOf(values) {
313
+ return {
314
+ enabled: String(values.enabled),
315
+ httpProxy: values.httpProxy,
316
+ httpsProxy: values.httpsProxy,
317
+ allProxy: values.allProxy,
318
+ noProxy: values.noProxy,
319
+ }
320
+ }
321
+
322
+ export const version = packageVersion()
package/locale/en.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "meta": {
3
+ "title": "Proxy settings",
4
+ "description": "Configure the engine's outbound HTTP proxy and no_proxy bypass list, CIDR included, from a settings page."
5
+ },
6
+ "settings.proxy": {
7
+ "nav": "Proxy",
8
+ "title": "Outbound proxy",
9
+ "description": "Applies to engine requests for LLM, web search and HTTP MCP. Restart the engine to apply.",
10
+ "enabled": "Use proxy",
11
+ "httpProxy": "HTTP proxy",
12
+ "httpsProxy": "HTTPS proxy",
13
+ "allProxy": "Proxy for all protocols",
14
+ "noProxy": "no_proxy bypass list",
15
+ "noProxyHint": "Separate entries with commas or spaces. Use * to bypass everything. Loopback is always direct.",
16
+ "cidrHint": "CIDR ranges are supported here (10.0.0.0/8, 192.168.0.0/16); they work through this plugin only — curl and other tools cannot read them.",
17
+ "urlHint": "Only http:// and https:// proxy URLs are supported. Credentials are stored separately.",
18
+ "managedHint": "The form owns this field; saving writes it to .env.",
19
+ "inheritedHint": "This value comes from the environment or .env and is not owned by the form yet. Edit it here to take over.",
20
+ "save": "Save",
21
+ "reset": "Discard changes",
22
+ "saving": "Saving…",
23
+ "saved": "Configuration saved.",
24
+ "plaintextHint": "A username and password are written to ~/.dsh/.env in plaintext. This plugin does not change that file's permissions; run chmod 600 on it yourself if you want that.",
25
+ "liveApplied": "This process now uses the new proxy policy.",
26
+ "liveFailed": "Saved to .env, but this process could not reinstall the policy: {error}.",
27
+ "restartApplies": "A restart applies the .env values.",
28
+ "savedAndWritten": "Configuration saved and written to .env; restart the engine to apply.",
29
+ "saveFailed": "Could not save: {error}",
30
+ "envFailed": "Configuration saved, but writing .env failed: {error}",
31
+ "envPending": "Writing .env…",
32
+ "invalidUrl": "Only http:// and https:// proxy URLs are supported. Check the proxy fields.",
33
+ "loading": "Loading…",
34
+ "unavailable": "Proxy settings are unavailable in this profile.",
35
+ "exportedNotice": "Detected {names} coming from the launch environment, which overrides this page. Unset them to take over."
36
+ }
37
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "meta": {
3
+ "title": "代理设置",
4
+ "description": "在设置页里配置引擎对外请求的 HTTP 代理与 no_proxy 白名单(含 CIDR),保存即生效。"
5
+ },
6
+ "settings.proxy": {
7
+ "nav": "代理",
8
+ "title": "对外代理",
9
+ "description": "作用于引擎的 LLM、联网搜索和 HTTP MCP 请求;保存后重启引擎生效。",
10
+ "enabled": "启用代理",
11
+ "httpProxy": "HTTP 代理",
12
+ "httpsProxy": "HTTPS 代理",
13
+ "allProxy": "通用代理(所有协议)",
14
+ "noProxy": "no_proxy 白名单",
15
+ "noProxyHint": "用逗号或空格分隔;填 * 表示全部直连。本机地址始终直连。",
16
+ "cidrHint": "可写 CIDR 网段(如 10.0.0.0/8、192.168.0.0/16);这类条目只在本插件生效,curl 等外部工具读不懂。",
17
+ "urlHint": "仅支持 http:// 和 https:// 代理地址;账号密码会单独保存,不写进配置。",
18
+ "managedHint": "这一项由表单接管,保存后写入 .env。",
19
+ "inheritedHint": "当前值来自环境变量或 .env,尚未由表单接管;在这里改一次即接管。",
20
+ "save": "保存",
21
+ "reset": "放弃修改",
22
+ "saving": "保存中…",
23
+ "saved": "配置已保存。",
24
+ "plaintextHint": "账号密码会以明文写入 ~/.dsh/.env。本插件不改该文件权限,需要的话请自行 chmod 600。",
25
+ "liveApplied": "当前进程的代理策略已按新配置重新安装。",
26
+ "liveFailed": "配置已写入 .env,但当前进程未能重装策略:{error}。",
27
+ "restartApplies": "重启引擎后会按 .env 生效。",
28
+ "savedAndWritten": "配置已保存,并写入 .env;重启引擎后生效。",
29
+ "saveFailed": "保存失败:{error}",
30
+ "envFailed": "配置已保存,但写入 .env 失败:{error}",
31
+ "envPending": "正在写入 .env…",
32
+ "invalidUrl": "代理地址只支持 http:// 和 https://,请检查输入框。",
33
+ "loading": "加载中…",
34
+ "unavailable": "当前配置里没有可用的代理设置。",
35
+ "exportedNotice": "检测到 {names} 由启动环境提供,会覆盖这里的设置;要接管请先取消导出。"
36
+ }
37
+ }
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "dsh-proxy-enhance",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Outbound proxy settings page for DeepSeek Harness: configure http(s)_proxy and no_proxy, with CIDR ranges the launcher-side matcher cannot express.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "deepseek-harness",
9
+ "dsh",
10
+ "dsh-plugin",
11
+ "proxy",
12
+ "no-proxy",
13
+ "cidr",
14
+ "settings"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/weicy98/dsh-proxy-enhance.git"
19
+ },
20
+ "homepage": "https://github.com/weicy98/dsh-proxy-enhance#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/weicy98/dsh-proxy-enhance/issues"
23
+ },
24
+ "main": "index.js",
25
+ "exports": {
26
+ ".": "./index.js",
27
+ "./env": "./env.js",
28
+ "./cidr": "./cidr.js",
29
+ "./route": "./route.js",
30
+ "./client": "./client.js",
31
+ "./locale/*.json": "./locale/*.json",
32
+ "./icon": "./icon.svg",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "index.js",
37
+ "env.js",
38
+ "cidr.js",
39
+ "route.js",
40
+ "client.js",
41
+ "cordis.patch.yml",
42
+ "locale",
43
+ "icon.svg",
44
+ "README.md"
45
+ ],
46
+ "scripts": {
47
+ "test": "node --test test/*.test.js",
48
+ "prepublishOnly": "node --test test/*.test.js"
49
+ },
50
+ "engines": {
51
+ "node": ">=22.5",
52
+ "dsh": "^0.2.3-alpha.3"
53
+ },
54
+ "dependencies": {
55
+ "@deepseek-ai/schemastery": "3.20.0-alpha.2"
56
+ },
57
+ "peerDependencies": {
58
+ "@deepseek-ai/cordis": "^4.1.0 || ^4.2.0-alpha.2",
59
+ "@deepseek-ai/dsh-atomic-write": ">=0.2.2-rc.1 <0.3.0",
60
+ "@deepseek-ai/dsh-credentials": ">=0.2.2-rc.1 <0.3.0",
61
+ "@deepseek-ai/dsh-home-paths": ">=0.2.2-rc.1 <0.3.0",
62
+ "@deepseek-ai/dsh-http-proxy": ">=0.2.2-rc.1 <0.3.0",
63
+ "undici": "^8.12.0"
64
+ },
65
+ "devDependencies": {
66
+ "@deepseek-ai/cordis": "4.2.0-alpha.2",
67
+ "@deepseek-ai/dsh-atomic-write": "0.2.3-alpha.3",
68
+ "@deepseek-ai/dsh-credentials": "0.2.3-alpha.3",
69
+ "@deepseek-ai/dsh-home-paths": "0.2.3-alpha.3",
70
+ "@deepseek-ai/dsh-http-proxy": "0.2.3-alpha.3",
71
+ "undici": "8.12.4"
72
+ },
73
+ "publishConfig": {
74
+ "access": "public",
75
+ "registry": "https://registry.npmjs.org/"
76
+ },
77
+ "dsh": {
78
+ "bundle": {
79
+ "patch": "./cordis.patch.yml"
80
+ },
81
+ "client": {
82
+ "platform": "web",
83
+ "immediately": true,
84
+ "inject": [
85
+ "@deepseek-ai/dsh-api-settings-controller",
86
+ "@deepseek-ai/dsh-client-ui-settings-general"
87
+ ]
88
+ }
89
+ }
90
+ }
package/route.js ADDED
@@ -0,0 +1,161 @@
1
+ // The routing layer: one proxy policy, one dispatcher, CIDR included.
2
+ //
3
+ // DeepSeek Harness resolves the outbound proxy once at launch from the
4
+ // environment (`@deepseek-ai/dsh-http-proxy`) and installs it as undici's global
5
+ // dispatcher. That matcher compares hostnames as suffixes only: its README says
6
+ // CIDR "is not matched", and `10.0.0.0/8` or `192.168.0.0/16` in `no_proxy` are
7
+ // therefore inert — a copied system bypass list looks applied while every
8
+ // private address is still tunnelled.
9
+ //
10
+ // This module reuses that policy resolution verbatim and replaces exactly one
11
+ // decision: whether a URL bypasses the proxy. Everything else — how `ALL_PROXY`
12
+ // backs both schemes, how HTTPS falls back to the HTTP proxy, how a rejected
13
+ // SOCKS URL keeps its scheme direct, how loopback is always direct — stays with
14
+ // the official implementation, because a second copy of those rules would drift.
15
+ //
16
+ // The dispatcher is built the way the official one is built (per-origin
17
+ // `factory` choosing `ProxyAgent` or `Pool`), so HTTP/2 handling and connection
18
+ // pooling behave identically.
19
+
20
+ import { installProxyFromEnvironment, proxyRouteFor } from '@deepseek-ai/dsh-http-proxy'
21
+ // The matcher itself is not exported by that package; the CIDR half is ours and
22
+ // the suffix half is read back through the public route query below.
23
+ import { bypassesByCidr } from './cidr.js'
24
+
25
+ /** Names that carry a proxy URL; a bypass list alone is not a policy. */
26
+ const PROXY_URL_NAMES = Object.freeze(['http_proxy', 'https_proxy', 'all_proxy'])
27
+
28
+ /**
29
+ * Build the env view one proxy policy resolves from.
30
+ *
31
+ * The launcher passes a `LaunchEnvironmentSnapshot`; this accepts the same shape
32
+ * so the plugin can re-install a policy from the values the page just saved
33
+ * without waiting for a restart.
34
+ *
35
+ * @param values - one entry per proxy name.
36
+ * @returns the minimal `EnvLookup` that resolver expects.
37
+ */
38
+ export function envLookup(values) {
39
+ const table = values ?? {}
40
+ return {
41
+ get: (name) => {
42
+ const value = table[name]
43
+ return value === undefined || value === '' ? undefined : { value }
44
+ },
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Whether one URL bypasses the proxy.
50
+ *
51
+ * The official answer is authoritative for everything it already covers:
52
+ * loopback, `*`, a suffix entry, and a `:port` qualifier. Only the ranges it
53
+ * cannot express are added here, so the two can never contradict each other —
54
+ * a CIDR hit can only turn a proxied route into a direct one, never the reverse.
55
+ *
56
+ * @param noProxy - the effective bypass list.
57
+ * @param url - the request URL.
58
+ * @param officialRoute - the route the official matcher chose for this URL.
59
+ * @returns true when the request must go direct.
60
+ */
61
+ export function bypassesWithCidr(noProxy, url, officialRoute) {
62
+ if (officialRoute === undefined || officialRoute.proxied === false) return true
63
+ // The effective port, spelled the way the official matcher spells it: an
64
+ // omitted port means the scheme default, which a `10.0.0.0/8:443` entry matches.
65
+ const port = url.port !== '' ? url.port : url.protocol === 'https:' ? '443' : '80'
66
+ return bypassesByCidr(noProxy, url.hostname, port)
67
+ }
68
+
69
+ /**
70
+ * Install a proxy policy whose bypass list also understands CIDR.
71
+ *
72
+ * Resolution, diagnostics, and the no-proxy fallbacks all come from the official
73
+ * installer. The returned disposer restores the previous dispatcher, so a saved
74
+ * change in the settings page can take effect immediately and a later change (or
75
+ * an unload) can undo it without leaving two policies behind.
76
+ *
77
+ * @param values - proxy environment values to resolve from.
78
+ * @param options - `report` receives one line per rejected value; `allowH2`
79
+ * mirrors the official dispatcher option and is unset by default.
80
+ * @returns a disposer that restores the previous policy.
81
+ */
82
+ export async function installCidrProxy(values, options = {}) {
83
+ const report = options.report ?? (() => {})
84
+ // A bypass list without any proxy to bypass is not a policy. Installing one
85
+ // would replace whatever the launcher resolved with a direct-only dispatcher,
86
+ // so the caller gets a no-op disposer instead of a silent proxy removal.
87
+ const hasProxy = PROXY_URL_NAMES.some((name) => {
88
+ const value = values?.[name]
89
+ return typeof value === 'string' && value.trim() !== ''
90
+ })
91
+ if (!hasProxy) {
92
+ report('no proxy URL configured; leaving the current policy in place')
93
+ return async () => {}
94
+ }
95
+
96
+ // Resolve with the official installer first: it validates every URL, reports
97
+ // rejections, and publishes the resolved policy through `proxyRouteFor`.
98
+ const disposeOfficial = await installProxyFromEnvironment(envLookup(values), report, options)
99
+ const noProxy = values?.no_proxy ?? values?.NO_PROXY ?? ''
100
+
101
+ // Without a range in the list the official dispatcher is already correct, and
102
+ // wrapping it would only add a layer that can disagree with it.
103
+ if (!/\d+\.\d+\.\d+\.\d+\/|[0-9a-fA-F]*:[0-9a-fA-F:]*\//.test(noProxy)) return disposeOfficial
104
+
105
+ try {
106
+ const { getGlobalDispatcher, setGlobalDispatcher } = await import('undici')
107
+ const previous = getGlobalDispatcher()
108
+ const dispatcher = await createCidrDispatcher(noProxy)
109
+ setGlobalDispatcher(dispatcher)
110
+ return async () => {
111
+ setGlobalDispatcher(previous)
112
+ await dispatcher.close()
113
+ await disposeOfficial()
114
+ }
115
+ } catch (error) {
116
+ await disposeOfficial()
117
+ report(`CIDR bypass could not be installed: ${error?.message ?? String(error)}`)
118
+ throw error
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Build an undici dispatcher that routes each origin by the resolved policy.
124
+ *
125
+ * Mirrors the official `createPolicyDispatcher`: a per-origin `factory` that
126
+ * returns a `ProxyAgent` for a proxied origin and a `Pool` for a direct one.
127
+ * The only difference is that a CIDR hit is treated as direct.
128
+ *
129
+ * @param noProxy - the bypass list, CIDR entries included.
130
+ * @returns the dispatcher; the caller owns closing it.
131
+ */
132
+ async function createCidrDispatcher(noProxy) {
133
+ const { Agent, Pool, ProxyAgent } = await import('undici')
134
+ return new Agent({
135
+ factory(origin, passedOptions) {
136
+ const url = new URL(origin.toString())
137
+ const official = proxyRouteFor(url)
138
+ if (bypassesWithCidr(noProxy, url, official)) {
139
+ // What undici's own default factory builds for these options.
140
+ return new Pool(origin, passedOptions)
141
+ }
142
+ return new ProxyAgent({ ...passedOptions, uri: official.proxy })
143
+ },
144
+ })
145
+ }
146
+
147
+ /**
148
+ * Whether a bypass list carries a range the official matcher ignores.
149
+ *
150
+ * Used by the settings page to warn that an entry only works through this
151
+ * plugin's live policy, not through a plain `no_proxy` reader such as `curl`.
152
+ *
153
+ * @param noProxy - the raw bypass list.
154
+ * @returns the entries that are CIDR ranges.
155
+ */
156
+ export function cidrEntriesOf(noProxy) {
157
+ return String(noProxy ?? '')
158
+ .split(/[,\s]+/)
159
+ .map((entry) => entry.trim())
160
+ .filter((entry) => entry !== '' && entry.includes('/') && /^[0-9a-fA-F:.]+\/\d{1,3}(:\d{1,5})?$/.test(entry))
161
+ }