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/client.js ADDED
@@ -0,0 +1,407 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-proxy-enhance',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const NS = 'settings.proxy'
7
+ const NAMESPACE = 'proxy-enhance'
8
+ const EMPTY = { enabled: true, httpProxy: '', httpsProxy: '', allProxy: '', noProxy: '' }
9
+ const PROXY_FIELDS = ['httpProxy', 'httpsProxy', 'allProxy']
10
+
11
+ // Copy lives here because `locale/*.json` is read by the Host for display
12
+ // metadata only; nothing ships package JSON to the browser. A settings page
13
+ // that never registers a dictionary renders raw keys, so this table is the
14
+ // registry's content.
15
+ const zh = {
16
+ nav: '代理',
17
+ title: '对外代理',
18
+ description: '作用于引擎的 LLM、联网搜索和 HTTP MCP 请求;保存后重启引擎生效。',
19
+ enabled: '启用代理',
20
+ httpProxy: 'HTTP 代理',
21
+ httpsProxy: 'HTTPS 代理',
22
+ allProxy: '通用代理(所有协议)',
23
+ noProxy: 'no_proxy 白名单',
24
+ noProxyHint: '用逗号或空格分隔;填 * 表示全部直连。本机地址始终直连。',
25
+ cidrHint: '可写 CIDR 网段(如 10.0.0.0/8、192.168.0.0/16);这类条目只在本插件生效,curl 等外部工具读不懂。',
26
+ urlHint: '仅支持 http:// 和 https:// 代理地址;账号密码会单独保存,不写进配置。',
27
+ managedHint: '这一项由表单接管,保存后写入 .env。',
28
+ inheritedHint: '当前值来自环境变量或 .env,尚未由表单接管;在这里改一次即接管。',
29
+ save: '保存',
30
+ reset: '放弃修改',
31
+ saving: '保存中…',
32
+ saved: '配置已保存。',
33
+ plaintextHint: '账号密码会以明文写入 ~/.dsh/.env。本插件不改该文件权限,需要的话请自行 chmod 600。',
34
+ liveApplied: '当前进程的代理策略已按新配置重新安装。',
35
+ liveFailed: '配置已写入 .env,但当前进程未能重装策略:{error}。',
36
+ restartApplies: '重启引擎后会按 .env 生效。',
37
+ savedAndWritten: '配置已保存,并写入 .env;重启引擎后生效。',
38
+ saveFailed: '保存失败:{error}',
39
+ envFailed: '配置已保存,但写入 .env 失败:{error}',
40
+ envPending: '正在写入 .env…',
41
+ invalidUrl: '代理地址只支持 http:// 和 https://,请检查输入框。',
42
+ loading: '加载中…',
43
+ unavailable: '当前配置里没有可用的代理设置。',
44
+ exportedNotice: '检测到 {names} 由启动环境提供,会覆盖这里的设置;要接管请先取消导出。',
45
+ }
46
+ const en = {
47
+ nav: 'Proxy',
48
+ title: 'Outbound proxy',
49
+ description: 'Applies to engine requests for LLM, web search and HTTP MCP. Restart the engine to apply.',
50
+ enabled: 'Use proxy',
51
+ httpProxy: 'HTTP proxy',
52
+ httpsProxy: 'HTTPS proxy',
53
+ allProxy: 'Proxy for all protocols',
54
+ noProxy: 'no_proxy bypass list',
55
+ noProxyHint: 'Separate entries with commas or spaces. Use * to bypass everything. Loopback is always direct.',
56
+ 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.',
57
+ urlHint: 'Only http:// and https:// proxy URLs are supported. Credentials are stored separately.',
58
+ managedHint: 'The form owns this field; saving writes it to .env.',
59
+ inheritedHint: 'This value comes from the environment or .env and is not owned by the form yet. Edit it here to take over.',
60
+ save: 'Save',
61
+ reset: 'Discard changes',
62
+ saving: 'Saving…',
63
+ saved: 'Configuration saved.',
64
+ 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.',
65
+ liveApplied: 'This process now uses the new proxy policy.',
66
+ liveFailed: 'Saved to .env, but this process could not reinstall the policy: {error}.',
67
+ restartApplies: 'A restart applies the .env values.',
68
+ savedAndWritten: 'Configuration saved and written to .env; restart the engine to apply.',
69
+ saveFailed: 'Could not save: {error}',
70
+ envFailed: 'Configuration saved, but writing .env failed: {error}',
71
+ envPending: 'Writing .env…',
72
+ invalidUrl: 'Only http:// and https:// proxy URLs are supported. Check the proxy fields.',
73
+ loading: 'Loading…',
74
+ unavailable: 'Proxy settings are unavailable in this profile.',
75
+ exportedNotice: 'Detected {names} coming from the launch environment, which overrides this page. Unset them to take over.',
76
+ }
77
+
78
+ const validUrl = (value) => {
79
+ const text = String(value ?? '').trim()
80
+ if (text === '') return true
81
+ try {
82
+ return ['http:', 'https:'].includes(new URL(text).protocol)
83
+ } catch {
84
+ return false
85
+ }
86
+ }
87
+
88
+ // Mirrors env.js splitProxyUrl: string surgery on the authority, so the
89
+ // userinfo is carried verbatim and never re-encoded on the way in.
90
+ const splitUrl = (value) => {
91
+ const text = String(value ?? '').trim()
92
+ if (text === '') return { url: '', userinfo: '' }
93
+ const match = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/?#]*)([\s\S]*)$/.exec(text)
94
+ if (!match) return { url: text, userinfo: '' }
95
+ const at = match[2].lastIndexOf('@')
96
+ if (at === -1) return { url: text, userinfo: '' }
97
+ return { url: match[1] + match[2].slice(at + 1) + match[3], userinfo: match[2].slice(0, at) }
98
+ }
99
+
100
+ return {
101
+ inject: ['slots', 'locale', 'remote', 'remote.settings'],
102
+
103
+ apply(ctx) {
104
+ // Without this the page renders `settings.proxy.save` instead of "保存".
105
+ // Disposers ride the plugin's own effect so unload removes the copy.
106
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-proxy-enhance: dictionaries')
107
+ const t = ctx.locale.bind(NS)
108
+
109
+ const label = (text) => h('span', {
110
+ style: { display: 'block', fontSize: 13, color: 'var(--dsw-alias-label-secondary)', marginBottom: 6 },
111
+ }, text)
112
+
113
+ const inputStyle = {
114
+ width: '100%', boxSizing: 'border-box', padding: '8px 10px',
115
+ borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1)',
116
+ background: 'var(--dsw-alias-bg-base)', color: 'var(--dsw-alias-label-primary)',
117
+ }
118
+
119
+ const ProxySection = () => {
120
+ const [revision, setRevision] = React.useState(undefined)
121
+ const [draft, setDraft] = React.useState(EMPTY)
122
+ const [saved, setSaved] = React.useState(EMPTY)
123
+ // Fields the profile layer really owns. The Host's `user` section is
124
+ // the authority: a field absent there is inherited and the form does
125
+ // not own it yet.
126
+ const [owned, setOwned] = React.useState({})
127
+ const [envSync, setEnvSync] = React.useState('')
128
+ const [error, setError] = React.useState('')
129
+ const [status, setStatus] = React.useState('')
130
+ const [busy, setBusy] = React.useState(false)
131
+ const [ready, setReady] = React.useState(false)
132
+
133
+ React.useEffect(() => {
134
+ let alive = true
135
+ const load = async () => {
136
+ try {
137
+ const response = await ctx.remote.settings.describe()
138
+ if (!response.ok) throw new Error(response.error?.message || 'describe failed')
139
+ const view = response.value.namespaces.find((entry) => entry.ns === NAMESPACE)
140
+ if (!view) {
141
+ if (alive) { setError(t('unavailable')); setReady(true) }
142
+ return
143
+ }
144
+ if (!alive) return
145
+ const value = view.value || {}
146
+ // `envSync` is Host state, not a form field: it must never round
147
+ // trip through the form's save path.
148
+ const current = { ...EMPTY }
149
+ for (const key of Object.keys(EMPTY)) current[key] = value[key] ?? EMPTY[key]
150
+ const user = view.user || {}
151
+ setOwned(Object.fromEntries(Object.keys(EMPTY).map((key) => [key, Object.hasOwn(user, key)])))
152
+ setEnvSync(typeof value.envSync === 'string' ? value.envSync : '')
153
+ setRevision(view.revision)
154
+ setSaved(current)
155
+ setDraft(current)
156
+ if (alive) setReady(true)
157
+ } catch (cause) {
158
+ if (alive) { setError(String(cause?.message ?? cause)); setReady(true) }
159
+ }
160
+ }
161
+ load()
162
+ const off = typeof ctx.remote.$on === 'function'
163
+ ? ctx.remote.$on('settings/document-updated', (namespace) => {
164
+ if (namespace === NAMESPACE) load()
165
+ })
166
+ : undefined
167
+ return () => { alive = false; off?.() }
168
+ }, [])
169
+
170
+ const change = (key) => (value) => {
171
+ setDraft((current) => ({ ...current, [key]: value }))
172
+ setStatus('')
173
+ setError('')
174
+ }
175
+
176
+ const save = async () => {
177
+ setBusy(true)
178
+ setStatus('')
179
+ setError('')
180
+ const bad = PROXY_FIELDS.find((key) => !validUrl(draft[key]))
181
+ if (bad) {
182
+ setError(t('invalidUrl'))
183
+ setBusy(false)
184
+ return
185
+ }
186
+ try {
187
+ // Only send the fields the user actually changed: an untouched
188
+ // field must keep whatever the host currently holds, including a
189
+ // value the form inherited.
190
+ const parts = Object.fromEntries(PROXY_FIELDS.map((key) => [key, splitUrl(draft[key])]))
191
+ const ops = []
192
+ if (Boolean(draft.enabled) !== Boolean(saved.enabled)) {
193
+ ops.push({ op: 'set', path: ['enabled'], value: Boolean(draft.enabled) })
194
+ }
195
+ for (const key of PROXY_FIELDS) {
196
+ if (parts[key].url !== saved[key]) ops.push({ op: 'set', path: [key], value: parts[key].url })
197
+ }
198
+ if (String(draft.noProxy ?? '') !== saved.noProxy) {
199
+ ops.push({ op: 'set', path: ['noProxy'], value: String(draft.noProxy ?? '') })
200
+ }
201
+
202
+ const response = ops.length === 0
203
+ ? { ok: true, value: undefined }
204
+ : await ctx.remote.settings.mutate(NAMESPACE, ops, revision)
205
+ if (!response.ok) throw new Error(response.error?.message || 'mutate failed')
206
+ if (response.value?.revision !== undefined) setRevision(response.value.revision)
207
+
208
+ // The complete URL — userinfo included — is what the form stores:
209
+ // the launcher reads a proxy from the environment at start, so a
210
+ // second credential copy would only add a way for the two to drift.
211
+ const clean = { ...EMPTY }
212
+ clean.enabled = Boolean(draft.enabled)
213
+ for (const field of PROXY_FIELDS) clean[field] = String(draft[field] ?? '').trim()
214
+ clean.noProxy = String(draft.noProxy ?? '')
215
+ const settled = ops.map((op) => op.path[0])
216
+ // Only the fields we just wrote are known to match the profile; the
217
+ // rest keep the values this component loaded.
218
+ const nextSaved = { ...saved }
219
+ for (const field of settled) nextSaved[field] = clean[field]
220
+ setSaved(nextSaved)
221
+ // Keep what the user typed, not the stripped URL the profile holds:
222
+ // replacing the field with a userinfo-free value would erase the
223
+ // credentials from view while `.env` still carried them, so a later edit
224
+ // would silently drop the credentials.
225
+ const nextDraft = { ...nextSaved }
226
+ for (const field of PROXY_FIELDS) {
227
+ if (settled.includes(field)) nextDraft[field] = String(draft[field] ?? '').trim()
228
+ }
229
+ setDraft(nextDraft)
230
+ setStatus(t('saved'))
231
+ } catch (cause) {
232
+ setError(t('saveFailed', { error: String(cause?.message ?? cause) }))
233
+ } finally {
234
+ setBusy(false)
235
+ }
236
+ }
237
+
238
+ const reset = () => {
239
+ setDraft({ ...saved })
240
+ setStatus('')
241
+ setError('')
242
+ }
243
+
244
+ const field = (key, labelText) => h('label', { style: { display: 'block', marginTop: 14 } },
245
+ label(labelText),
246
+ h('input', {
247
+ type: 'text',
248
+ value: draft[key],
249
+ onChange: (event) => change(key)(event.target.value),
250
+ placeholder: 'http://127.0.0.1:7890',
251
+ style: inputStyle,
252
+ }),
253
+ h('span', {
254
+ style: { display: 'block', fontSize: 12, color: 'var(--dsw-alias-label-tertiary)', marginTop: 4 },
255
+ }, t('urlHint')),
256
+ h('span', {
257
+ style: { display: 'block', fontSize: 12, color: 'var(--dsw-alias-label-tertiary)', marginTop: 2 },
258
+ }, owned[key] ? t('managedHint') : t('inheritedHint')),
259
+ )
260
+
261
+ // A URL carrying userinfo will be written to `.env` in plaintext; say so
262
+ // while the field still holds it rather than after a save.
263
+ const hasUserinfo = PROXY_FIELDS.some((key) => /^[a-zA-Z][\w+.-]*:\/\/[^/?#]*@/.test(String(draft[key] ?? '')))
264
+ // Which range entries the list actually carries — the official matcher
265
+ // cannot read these, so the page owns that explanation.
266
+ const cidrEntries = String(draft.noProxy ?? '')
267
+ .split(/[,\s]+/)
268
+ .map((entry) => entry.trim())
269
+ .filter((entry) => /^[0-9a-fA-F:.]+\/\d{1,3}$/.test(entry))
270
+
271
+ // Names the launch environment supplies: those win over `.env`, so the
272
+ // page must not imply its own save is what takes effect. The Host
273
+ // reports them on the same channel as the write outcome.
274
+ // `written: exported a,b live-failed: …` — the persisted half and the
275
+ // live-policy half are reported separately, so one cannot hide the other.
276
+ const liveTail = String(envSync).includes(' live-failed: ')
277
+ const liveReason = liveTail ? String(envSync).slice(String(envSync).indexOf(' live-failed: ') + ' live-failed: '.length) : ''
278
+ const head = liveTail ? String(envSync).slice(0, String(envSync).indexOf(' live-failed: ')) : String(envSync)
279
+ const exportedNames = head.startsWith('written: exported ')
280
+ ? head.slice('written: exported '.length).split(',').filter(Boolean)
281
+ : []
282
+ const envWritten = head.startsWith('written')
283
+
284
+ const writeNote = () => {
285
+ if (busy) return h('p', { style: { fontSize: 13, color: 'var(--dsw-alias-label-secondary)', marginTop: 12 } }, t('envPending'))
286
+ if (String(envSync).startsWith('failed:')) {
287
+ return h('p', { role: 'alert', style: { fontSize: 13, color: 'var(--dsw-alias-state-error-primary)', marginTop: 12 } },
288
+ t('envFailed', { error: String(envSync).slice('failed:'.length).trim() }))
289
+ }
290
+ if (liveTail) {
291
+ // The file is saved; only this process kept the previous policy.
292
+ return h('div', null,
293
+ h('p', { style: { fontSize: 13, color: 'var(--dsw-alias-state-warn-primary)', marginTop: 12 } },
294
+ t('liveFailed', { error: liveReason })),
295
+ h('p', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', marginTop: 2 } }, t('restartApplies')))
296
+ }
297
+ if (envWritten) {
298
+ // Two distinct facts: the file is what a restart reads, and this
299
+ // process already switched policy. A CIDR entry only exists in the
300
+ // latter, so saying both keeps the page honest.
301
+ return h('div', null,
302
+ h('p', { style: { fontSize: 13, color: 'var(--dsw-alias-state-success-primary)', marginTop: 12 } }, t('savedAndWritten')),
303
+ h('p', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', marginTop: 2 } }, t('liveApplied')))
304
+ }
305
+ return null
306
+ }
307
+
308
+ return h('div', {
309
+ style: {
310
+ maxWidth: 640, color: 'var(--dsw-alias-label-primary)',
311
+ background: 'var(--dsw-alias-bg-layer-1)',
312
+ border: '1px solid var(--dsw-alias-border-l1)',
313
+ borderRadius: 12, padding: '18px 20px',
314
+ },
315
+ },
316
+ h('h2', { style: { margin: 0, fontSize: 18 } }, t('title')),
317
+ h('p', {
318
+ style: { margin: '8px 0 0', fontSize: 13, lineHeight: 1.6, color: 'var(--dsw-alias-label-secondary)' },
319
+ }, t('description')),
320
+ !ready ? h('p', { style: { fontSize: 13, marginTop: 16 } }, t('loading')) : null,
321
+ ready ? h('div', null,
322
+ exportedNames.length > 0
323
+ ? h('p', { style: { fontSize: 12, marginTop: 12, color: 'var(--dsw-alias-state-warn-primary)' } },
324
+ t('exportedNotice', { names: exportedNames.join(', ') }))
325
+ : null,
326
+ h('label', {
327
+ style: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 18, fontSize: 14, cursor: 'pointer' },
328
+ },
329
+ h('input', {
330
+ type: 'checkbox', checked: Boolean(draft.enabled),
331
+ onChange: (event) => change('enabled')(event.target.checked),
332
+ style: { accentColor: 'var(--dsw-alias-state-business-primary)' },
333
+ }),
334
+ h('span', null, t('enabled')),
335
+ ),
336
+ field('httpProxy', t('httpProxy')),
337
+ field('httpsProxy', t('httpsProxy')),
338
+ field('allProxy', t('allProxy')),
339
+ h('label', { style: { display: 'block', marginTop: 14 } },
340
+ label(t('noProxy')),
341
+ h('textarea', {
342
+ rows: 3,
343
+ value: draft.noProxy,
344
+ onChange: (event) => change('noProxy')(event.target.value),
345
+ placeholder: 'example.com, .internal, localhost',
346
+ style: { ...inputStyle, resize: 'vertical' },
347
+ }),
348
+ h('span', {
349
+ style: { display: 'block', fontSize: 12, color: 'var(--dsw-alias-label-tertiary)', marginTop: 4 },
350
+ }, t('noProxyHint')),
351
+ cidrEntries.length > 0
352
+ ? h('span', {
353
+ style: { display: 'block', fontSize: 12, marginTop: 4, color: 'var(--dsw-alias-state-business-primary)' },
354
+ }, t('cidrHint'))
355
+ : null,
356
+ ),
357
+ hasUserinfo
358
+ ? h('p', { style: { fontSize: 12, marginTop: 12, color: 'var(--dsw-alias-state-warn-primary)' } },
359
+ t('plaintextHint'))
360
+ : null,
361
+ h('div', { style: { display: 'flex', gap: 10, marginTop: 20 } },
362
+ h('button', {
363
+ type: 'button',
364
+ onClick: save,
365
+ disabled: busy,
366
+ style: {
367
+ padding: '8px 16px', borderRadius: 8,
368
+ border: '1px solid var(--dsw-alias-state-business-primary)',
369
+ background: 'var(--dsw-alias-state-business-primary)',
370
+ color: 'var(--dsw-alias-label-primary-foreground)', cursor: 'pointer',
371
+ },
372
+ }, busy ? t('saving') : t('save')),
373
+ h('button', {
374
+ type: 'button',
375
+ onClick: reset,
376
+ disabled: busy,
377
+ style: {
378
+ padding: '8px 16px', borderRadius: 8,
379
+ border: '1px solid var(--dsw-alias-border-l1)',
380
+ background: 'transparent', color: 'var(--dsw-alias-label-secondary)', cursor: 'pointer',
381
+ },
382
+ }, t('reset')),
383
+ ),
384
+ writeNote(),
385
+ ) : null,
386
+ error ? h('p', {
387
+ role: 'alert',
388
+ style: { fontSize: 13, color: 'var(--dsw-alias-state-error-primary)', marginTop: 12 },
389
+ }, error) : null,
390
+ status ? h('p', {
391
+ style: { fontSize: 13, color: 'var(--dsw-alias-state-success-primary)', marginTop: 12 },
392
+ }, status) : null,
393
+ )
394
+ }
395
+
396
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
397
+ name: 'settings.section',
398
+ id: 'proxy',
399
+ order: 50,
400
+ label: () => t('nav'),
401
+ locale: NS,
402
+ inject: () => ({ t }),
403
+ }, ProxySection))
404
+ },
405
+ }
406
+ },
407
+ })
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: proxy-enhance
3
+ name: 'dsh-proxy-enhance'
4
+ config: {}
package/env.js ADDED
@@ -0,0 +1,246 @@
1
+ // Pure helpers for reading and rewriting the launcher's proxy environment.
2
+ //
3
+ // The launcher reads `$DSH_HOME/.env` with node:util's `parseEnv`, whose grammar
4
+ // has no escape mechanism at all: a value is either bare, or wrapped in one pair
5
+ // of single or double quotes. That silence is what makes hand-rolled quoting
6
+ // dangerous — `'it'\''s'` reads back as `it`, and a quote followed by a newline
7
+ // forges an extra assignment. Every value written here therefore goes through
8
+ // `encodeEnvValue`, which only returns a spelling that `parseEnv` was just shown
9
+ // to read back byte for byte, and refuses the rest instead of corrupting it.
10
+ //
11
+ // Kept free of Harness imports so a plain node script can exercise it.
12
+
13
+ import { parseEnv } from 'node:util'
14
+
15
+ export const MANAGED_KEYS = Object.freeze({
16
+ http_proxy: 'HTTP_PROXY',
17
+ https_proxy: 'HTTPS_PROXY',
18
+ all_proxy: 'ALL_PROXY',
19
+ no_proxy: 'NO_PROXY',
20
+ })
21
+
22
+ /** Proxy-bearing fields in form order, with the environment name each one owns. */
23
+ export const PROXY_FIELDS = Object.freeze([
24
+ Object.freeze({ field: 'httpProxy', lower: 'http_proxy' }),
25
+ Object.freeze({ field: 'httpsProxy', lower: 'https_proxy' }),
26
+ Object.freeze({ field: 'allProxy', lower: 'all_proxy' }),
27
+ ])
28
+
29
+ const ASSIGNMENT = /^(\s*)(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/
30
+
31
+ /**
32
+ * Encode one value as an assignment body `parseEnv` reads back exactly.
33
+ *
34
+ * Bare first (the common case, and the form a human would write), then single
35
+ * quotes for values a bare one cannot carry verbatim — a `#` starts a comment,
36
+ * and edge whitespace is dropped. A bare candidate is never accepted when it
37
+ * spans lines: that spelling is how one value forges a second assignment.
38
+ *
39
+ * @param text - the value to encode.
40
+ * @returns the assignment body, or `undefined` when this grammar cannot
41
+ * express it (a carriage return, which `parseEnv` normalises away).
42
+ */
43
+ export function encodeEnvValue(text) {
44
+ const value = String(text ?? '')
45
+ const quoted = [`'${value}'`, `"${value}"`]
46
+ for (const candidate of [value, ...quoted]) {
47
+ if (candidate.includes('\n') && candidate === value) continue
48
+ let parsed
49
+ try {
50
+ parsed = parseEnv(`K=${candidate}\n`)
51
+ } catch {
52
+ continue
53
+ }
54
+ // Exactly one key must come back, and it must equal the value: anything else
55
+ // means this candidate either truncated the value or injected a second key.
56
+ if (parsed.K === value && Object.keys(parsed).length === 1) return candidate
57
+ }
58
+ return undefined
59
+ }
60
+
61
+ /** Read KEY=VALUE pairs, ignoring comments and blank lines. */
62
+ export function readEnv(text) {
63
+ const source = String(text ?? '').replace(/^\uFEFF/, '')
64
+ if (source === '') return {}
65
+ try {
66
+ return { ...parseEnv(source) }
67
+ } catch {
68
+ // A file the launcher itself would refuse to parse still has to be readable
69
+ // here, or the plugin could never report it, let alone leave it alone.
70
+ // Best effort: the longest quoted prefix a line can still name, else the rest.
71
+ const result = {}
72
+ for (const line of source.split(/\r?\n/)) {
73
+ const match = ASSIGNMENT.exec(line)
74
+ if (!match) continue
75
+ const raw = match[3].trim()
76
+ const quote = raw[0] === '"' || raw[0] === "'" ? raw[0] : undefined
77
+ if (quote === undefined) {
78
+ result[match[2]] = raw
79
+ continue
80
+ }
81
+ const close = raw.lastIndexOf(quote)
82
+ result[match[2]] = close > 0 ? raw.slice(1, close) : raw.slice(1)
83
+ }
84
+ return result
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Rewrite only the keys the overlay names, leaving every other line untouched.
90
+ *
91
+ * A key is rewritten in place with its own leading whitespace and `export`
92
+ * prefix preserved, so a file a human maintains keeps its shape. An `undefined`
93
+ * overlay value removes the key. A value the grammar cannot express throws
94
+ * before anything is written, rather than silently landing a shorter value.
95
+ *
96
+ * @param text - the existing file content.
97
+ * @param overlay - key to next value; `undefined` deletes the key.
98
+ * @returns the complete next file content.
99
+ * @throws RangeError when a value cannot be expressed in the `.env` grammar.
100
+ */
101
+ export function rewriteEnv(text, overlay) {
102
+ const source = String(text ?? '')
103
+ const lines = source === '' ? [] : source.split(/\r?\n/)
104
+ const encoded = new Map()
105
+ for (const [key, value] of Object.entries(overlay)) {
106
+ if (value === undefined) continue
107
+ const body = encodeEnvValue(value)
108
+ if (body === undefined) {
109
+ throw new RangeError(`value for ${key} cannot be written to .env (carriage return)`)
110
+ }
111
+ encoded.set(key, body)
112
+ }
113
+
114
+ const present = new Set()
115
+ const out = []
116
+ for (const line of lines) {
117
+ const match = ASSIGNMENT.exec(line)
118
+ if (!match || !Object.prototype.hasOwnProperty.call(overlay, match[2])) {
119
+ out.push(line)
120
+ continue
121
+ }
122
+ present.add(match[2])
123
+ if (overlay[match[2]] === undefined) continue
124
+ const prefix = match[1] + (line.slice(match[1].length).startsWith('export') ? 'export ' : '')
125
+ out.push(`${prefix}${match[2]}=${encoded.get(match[2])}`)
126
+ }
127
+
128
+ // Avoid a stray blank line before appended keys when the file ends with \n.
129
+ while (out.length > 0 && out[out.length - 1].trim() === '') out.pop()
130
+ for (const [key, value] of Object.entries(overlay)) {
131
+ if (present.has(key) || value === undefined) continue
132
+ out.push(`${key}=${encoded.get(key)}`)
133
+ }
134
+ return `${out.join('\n').replace(/\n+$/, '')}\n`
135
+ }
136
+
137
+ /** Canonicalise a bypass list: trim, drop empties, dedupe case-insensitively. */
138
+ export function normalizeNoProxy(text) {
139
+ const parts = String(text ?? '').split(/[,\s]+/).map((part) => part.trim()).filter(Boolean)
140
+ const seen = new Set()
141
+ const kept = []
142
+ for (const part of parts) {
143
+ const key = part.toLowerCase()
144
+ if (seen.has(key)) continue
145
+ seen.add(key)
146
+ kept.push(part)
147
+ }
148
+ return kept.join(',')
149
+ }
150
+
151
+ /** Only http(s) proxy URLs are usable by the official launcher-side library. */
152
+ export function isValidProxyUrl(text) {
153
+ const value = String(text ?? '').trim()
154
+ if (value === '') return true
155
+ try {
156
+ const parsed = new URL(value)
157
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:'
158
+ } catch {
159
+ return false
160
+ }
161
+ }
162
+
163
+ const AUTHORITY = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/?#]*)([\s\S]*)$/
164
+
165
+ /**
166
+ * Split `scheme://userinfo@host` into a clean URL and its raw userinfo.
167
+ *
168
+ * Deliberately string surgery on the authority, not `URL` setters: the setters
169
+ * re-encode, so `a%3Ab:pass` would come back as `a:b:pass` on the way in and a
170
+ * password containing `@` would move the host. The userinfo is handed back
171
+ * exactly as it stood, which makes `mergeRaw(clean, userinfo)` byte-identical
172
+ * to the input for every value the user can type.
173
+ *
174
+ * @param value - a proxy URL, with or without userinfo.
175
+ * @returns the userinfo-free URL and the raw userinfo (empty when absent).
176
+ */
177
+ export function splitProxyUrl(value) {
178
+ const text = String(value ?? '').trim()
179
+ if (text === '') return { url: '', userinfo: '' }
180
+ const match = AUTHORITY.exec(text)
181
+ if (!match) return { url: text, userinfo: '' }
182
+ const at = match[2].lastIndexOf('@')
183
+ if (at === -1) return { url: text, userinfo: '' }
184
+ return { url: match[1] + match[2].slice(at + 1) + match[3], userinfo: match[2].slice(0, at) }
185
+ }
186
+
187
+ /**
188
+ * Build the lowercase/uppercase overlay written to `.env`. An empty proxy URL
189
+ * removes the key. The bypass list survives disabling the proxy so a user does
190
+ * not lose it when toggling off.
191
+ *
192
+ * A URL the launcher cannot use is refused rather than treated as empty: the
193
+ * launcher skips such a value and connects direct, so writing "nothing" would
194
+ * report success while silently disabling the proxy the user aimed at.
195
+ *
196
+ * @param values - the form values.
197
+ * @returns one entry per managed name, `undefined` meaning "remove".
198
+ * @throws RangeError when a proxy field holds a URL the launcher cannot use.
199
+ */
200
+ export function buildOverlay(values) {
201
+ const enabled = Boolean(values.enabled)
202
+ const overlay = {}
203
+ for (const { field, lower } of PROXY_FIELDS) {
204
+ const value = String(values[field] ?? '').trim()
205
+ if (value !== '' && !isValidProxyUrl(value)) {
206
+ throw new RangeError(`${field} is not an http(s) proxy URL`)
207
+ }
208
+ const accepted = enabled && value !== '' ? value : undefined
209
+ overlay[lower] = accepted
210
+ overlay[MANAGED_KEYS[lower]] = accepted
211
+ }
212
+ const bypass = normalizeNoProxy(values.noProxy)
213
+ const noProxy = bypass === '' ? undefined : bypass
214
+ overlay.no_proxy = noProxy
215
+ overlay.NO_PROXY = noProxy
216
+ return overlay
217
+ }
218
+
219
+ /**
220
+ * Decide which managed names this form owns, given which fields the user edited
221
+ * and which names the file already holds.
222
+ *
223
+ * An untouched form is not authoritative: a proxy the user exported or wrote
224
+ * into `.env` by hand keeps working, and the form shows it as unmanaged. Once a
225
+ * field is edited, that field's two names are written from the form — including
226
+ * a deliberate clear. Editing one field never reaches into another's names.
227
+ *
228
+ * @param values - the form values.
229
+ * @param editedFields - field names the user has changed since load.
230
+ * @returns the overlay to write; omitted fields are left alone.
231
+ */
232
+ export function ownershipOverlay(values, editedFields) {
233
+ const edited = new Set(editedFields)
234
+ const full = buildOverlay(values)
235
+ const overlay = {}
236
+ for (const { field, lower } of PROXY_FIELDS) {
237
+ if (!edited.has(field)) continue
238
+ overlay[lower] = full[lower]
239
+ overlay[MANAGED_KEYS[lower]] = full[MANAGED_KEYS[lower]]
240
+ }
241
+ if (edited.has('noProxy')) {
242
+ overlay.no_proxy = full.no_proxy
243
+ overlay.NO_PROXY = full.NO_PROXY
244
+ }
245
+ return overlay
246
+ }
package/icon.svg ADDED
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect width="64" height="64" rx="14" fill="#1f6f78"/>
3
+ <circle cx="17" cy="32" r="6" fill="#f4fbfc"/>
4
+ <circle cx="47" cy="17" r="6" fill="#f4fbfc"/>
5
+ <circle cx="47" cy="47" r="6" fill="#f4fbfc"/>
6
+ <path d="M22 30 L42 19 M22 34 L42 45" stroke="#f4fbfc" stroke-width="3.5" stroke-linecap="round"/>
7
+ <path d="M29 24 L34 15 M29 40 L34 49" stroke="#8ee0d8" stroke-width="2.5" stroke-linecap="round"/>
8
+ </svg>