@jinngoo/dsh-model-proxy 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +86 -2
- package/client.js +302 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +7 -0
- package/index.js +183 -0
- package/locale/en.json +11 -0
- package/locale/zh.json +11 -0
- package/package.json +72 -4
- package/tests/local-check.mjs +84 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jinngoo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @jinngoo/dsh-model-proxy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
只让**名单内的主机**经由 HTTP 代理发出请求,其余出站请求保持原有路由。用于「国外模型走代理、国内模型直连」这类分流,而不必维护一长串 `NO_PROXY`。
|
|
4
|
+
|
|
5
|
+
带设置界面,改完即时生效,无需重启。
|
|
6
|
+
|
|
7
|
+
## 它解决什么问题
|
|
8
|
+
|
|
9
|
+
DSH 的代理策略是**进程级的一件事**:启动时读一次环境变量,装一个 undici 全局 dispatcher。`NO_PROXY` 只能表达「这些不走代理」,表达不了「**只有**这个模型域名走代理,其余全部直连」。
|
|
10
|
+
|
|
11
|
+
本插件在 DSH 自己的安装之上再套一层 dispatcher —— **接管而不是覆盖**:
|
|
12
|
+
|
|
13
|
+
- 命中 `hosts` 的 origin → 本插件的 `ProxyAgent`
|
|
14
|
+
- 未命中的一切 → 原样委托给上一个 dispatcher
|
|
15
|
+
|
|
16
|
+
因此原有的 `HTTPS_PROXY` 策略、loopback 绕过、Web 界面、插件安装全部不受影响。
|
|
17
|
+
|
|
18
|
+
## 安装
|
|
19
|
+
|
|
20
|
+
从 npm 安装(推荐):
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
dsh plugin --profile web add @jinngoo/dsh-model-proxy
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
也可以直接装 GitHub 仓库:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
dsh plugin --profile web add https://github.com/Jinngoo/dsh-model-proxy
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
或在 Plugin Manager 里搜索包名安装。
|
|
33
|
+
|
|
34
|
+
## 配置
|
|
35
|
+
|
|
36
|
+
```yaml
|
|
37
|
+
- insert:
|
|
38
|
+
- id: model-proxy
|
|
39
|
+
name: '@jinngoo/dsh-model-proxy'
|
|
40
|
+
config:
|
|
41
|
+
enabled: true
|
|
42
|
+
proxyUrl: http://127.0.0.1:30080
|
|
43
|
+
hosts:
|
|
44
|
+
- api.commandcode.ai
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
| 字段 | 说明 |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `enabled` | 总开关。关闭即完全退回 DSH 原有策略。 |
|
|
50
|
+
| `proxyUrl` | 只接受 `http://` / `https://`。socks 地址会被忽略(与 DSH 自身策略一致)。 |
|
|
51
|
+
| `hosts` | 主机白名单。写域名即覆盖子域名:`example.com` 也匹配 `api.example.com`。 |
|
|
52
|
+
|
|
53
|
+
三个字段都可以在设置页里改,改动**即时生效**。
|
|
54
|
+
|
|
55
|
+
## 设置界面
|
|
56
|
+
|
|
57
|
+
**设置 → 模型代理**:开关、代理地址、主机名单的增删改,以及当前是否生效。
|
|
58
|
+
|
|
59
|
+
## 实现要点
|
|
60
|
+
|
|
61
|
+
- 用 `undici.setGlobalDispatcher()` 接管全局 dispatcher。它经 `Symbol.for('undici.globalDispatcher.1')` 作用到 Node 内置 `fetch`,而模型请求都走 `globalThis.fetch`,所以**不需要改动任何调用点**。
|
|
62
|
+
- 插件自带 `undici` 依赖,并用 `createRequire` 加载:undici 8 是纯 CJS 包,用静态命名导入在插件被 `link:` 安装时取不到导出;同时必须拿到**本进程**里的那一个 undici,换副本就改不到共享槽位。
|
|
63
|
+
- 不继承 undici 的 `Dispatcher` 类——`setGlobalDispatcher` 只做形状检查,普通对象实现 `dispatch`/`close`/`destroy` 即可。
|
|
64
|
+
- `close()` / `destroy()` 只作用于本插件创建的 agent;全局 dispatcher 与上一个 dispatcher 都不归本插件所有。
|
|
65
|
+
- 卸载或重建时,只在全局 dispatcher 仍是本插件那一个的情况下还原,不覆盖别人后装的。
|
|
66
|
+
|
|
67
|
+
## 验证
|
|
68
|
+
|
|
69
|
+
`npm run check` 会跑一组本地检查,其中关键的一项是把代理指向一个必然连不上的端口,然后断言:
|
|
70
|
+
|
|
71
|
+
- 白名单内的主机 → `ECONNREFUSED`(证明确实走了代理)
|
|
72
|
+
- 白名单外的主机 → 正常 200(证明不受影响)
|
|
73
|
+
|
|
74
|
+
## 限制
|
|
75
|
+
|
|
76
|
+
- 粒度是 **origin**(scheme + host + port),不是 provider。两个模型共用一个网关域名时,无法只让其中一个走代理。
|
|
77
|
+
- 只对**本进程内**的 `fetch` 生效。workflow worker 与 PTC 运行时是独立 `globalThis`,不受影响(它们本来也不接收代理配置)。
|
|
78
|
+
- 子进程(bash 工具、`git`、`gh`)不算在内:它们读环境变量,本插件不改环境;需要的话另配 `HTTPS_PROXY`。
|
|
79
|
+
- 遥测(OTLP)走 `node:http`,本来就绕开全局 dispatcher,本插件也管不到。
|
|
80
|
+
|
|
81
|
+
## 关闭
|
|
82
|
+
|
|
83
|
+
把 `enabled` 置为 `false`,或在 profile 的 `cordis.patch.yml` 里把这一行改成 `disabled: true`。
|
|
84
|
+
|
|
85
|
+
## 许可
|
|
86
|
+
|
|
87
|
+
MIT
|
package/client.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @jinngoo/dsh-model-proxy 的 Client 半边。
|
|
3
|
+
*
|
|
4
|
+
* 一个设置页(`settings.section`),读写 Host 半边的 volatile 配置:
|
|
5
|
+
* 开关、代理地址、走代理的主机白名单。写入走 `ctx.configForms`(Host 的
|
|
6
|
+
* revision 栅栏 + 校验 + 落盘都在那边),因此这里不直接碰任何配置文件。
|
|
7
|
+
*
|
|
8
|
+
* 组件自带控件与样式,只引用 `--dsw-alias-*` 主题 token;不依赖任何 Harness
|
|
9
|
+
* Client 包的运行时模块(那会在它们改版时把本页打崩)。
|
|
10
|
+
*/
|
|
11
|
+
window.__ModuleLoader__.load({
|
|
12
|
+
id: '@jinngoo/dsh-model-proxy',
|
|
13
|
+
factory(require) {
|
|
14
|
+
const React = require('react')
|
|
15
|
+
const h = React.createElement
|
|
16
|
+
|
|
17
|
+
/** 本插件的语言命名空间。 */
|
|
18
|
+
const NS = 'dsh-model-proxy'
|
|
19
|
+
/** 设置页条目 id;同时是 Host 侧 profile 条目 id,也就是 configForms 的键。 */
|
|
20
|
+
const ENTRY_ID = 'model-proxy'
|
|
21
|
+
/** 槽位:设置面板里的一整页。 */
|
|
22
|
+
const SECTION_SLOT = 'settings.section'
|
|
23
|
+
|
|
24
|
+
const DICTS = {
|
|
25
|
+
zh: {
|
|
26
|
+
nav: '模型代理',
|
|
27
|
+
intro: '只有下列主机会经由代理发出请求;其余一切(Web 界面、网页抓取、插件安装)保持原路由不变。',
|
|
28
|
+
enabled: '启用',
|
|
29
|
+
proxyUrl: '代理地址',
|
|
30
|
+
proxyUrlHint: '只支持 http:// 或 https://,不支持 socks。',
|
|
31
|
+
hosts: '走代理的主机',
|
|
32
|
+
hostsHint: '一行一个。写域名即覆盖其子域名:example.com 也匹配 api.example.com。',
|
|
33
|
+
addHost: '添加主机',
|
|
34
|
+
placeholder: 'api.example.com',
|
|
35
|
+
remove: '删除',
|
|
36
|
+
save: '保存',
|
|
37
|
+
saved: '已保存',
|
|
38
|
+
saveFailed: 'Host 拒绝了这次修改。请检查代理地址与主机名。',
|
|
39
|
+
loading: '正在读取当前配置…',
|
|
40
|
+
unavailable: '当前 profile 不提供该配置表单。',
|
|
41
|
+
status: '当前状态',
|
|
42
|
+
statusOn: '经 {proxy} 转发',
|
|
43
|
+
statusOff: '未启用',
|
|
44
|
+
needBoth: '填好代理地址和至少一个主机后才会生效。',
|
|
45
|
+
invalidProxy: '代理地址不可用(需要 http:// 或 https://)。',
|
|
46
|
+
},
|
|
47
|
+
en: {
|
|
48
|
+
nav: 'Model proxy',
|
|
49
|
+
intro: 'Only the hosts below send requests through the proxy. Everything else — the Web UI, page fetches, plugin installation — keeps its normal route.',
|
|
50
|
+
enabled: 'Enable',
|
|
51
|
+
proxyUrl: 'Proxy address',
|
|
52
|
+
proxyUrlHint: 'http:// or https:// only. SOCKS is not supported.',
|
|
53
|
+
hosts: 'Hosts through the proxy',
|
|
54
|
+
hostsHint: 'One per line. A domain covers its subdomains: example.com also matches api.example.com.',
|
|
55
|
+
addHost: 'Add a host',
|
|
56
|
+
placeholder: 'api.example.com',
|
|
57
|
+
remove: 'Remove',
|
|
58
|
+
save: 'Save',
|
|
59
|
+
saved: 'Saved',
|
|
60
|
+
saveFailed: 'The Host refused this change. Check the proxy address and the host names.',
|
|
61
|
+
loading: 'Loading the current configuration…',
|
|
62
|
+
unavailable: 'This profile exposes no configuration form.',
|
|
63
|
+
status: 'Effective',
|
|
64
|
+
statusOn: 'Through {proxy}',
|
|
65
|
+
statusOff: 'Off',
|
|
66
|
+
needBoth: 'Set a proxy address and at least one host before this takes effect.',
|
|
67
|
+
invalidProxy: 'That proxy address is unusable (http:// or https:// required).',
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 页面外观:对齐宿主设置页的标签 / 说明 / 控件行规范,只引用主题 token。 */
|
|
72
|
+
const CSS = [
|
|
73
|
+
'.mp-page{display:flex;flex-direction:column;gap:18px;max-width:640px}',
|
|
74
|
+
'.mp-intro{margin:0;color:var(--dsw-alias-label-secondary);font-size:13px;line-height:1.6}',
|
|
75
|
+
'.mp-field{display:flex;flex-direction:column;gap:6px}',
|
|
76
|
+
'.mp-label{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500}',
|
|
77
|
+
'.mp-hint{margin:0;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}',
|
|
78
|
+
'.mp-row{display:flex;align-items:center;gap:10px}',
|
|
79
|
+
'.mp-input{flex:1 1 auto;min-width:0;padding:6px 10px;border:1px solid var(--dsw-alias-border-l1);',
|
|
80
|
+
'border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);',
|
|
81
|
+
'font:inherit;font-size:13px;line-height:20px}',
|
|
82
|
+
'.mp-input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px;',
|
|
83
|
+
'border-color:var(--dsw-alias-brand-primary)}',
|
|
84
|
+
'.mp-input[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary)}',
|
|
85
|
+
'.mp-btn{flex:none;padding:5px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;',
|
|
86
|
+
'background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;',
|
|
87
|
+
'font-size:13px;line-height:20px;cursor:pointer}',
|
|
88
|
+
'.mp-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2)}',
|
|
89
|
+
'.mp-btn:disabled{opacity:.5;cursor:default}',
|
|
90
|
+
'.mp-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}',
|
|
91
|
+
'.mp-btn-primary{border-color:var(--dsw-alias-brand-primary);background:var(--dsw-alias-brand-primary);',
|
|
92
|
+
'color:var(--dsw-alias-bg-base)}',
|
|
93
|
+
'.mp-btn-icon{padding:2px 8px;line-height:18px}',
|
|
94
|
+
'.mp-switch{display:inline-flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;',
|
|
95
|
+
'color:var(--dsw-alias-label-primary)}',
|
|
96
|
+
'.mp-switch input{width:16px;height:16px;accent-color:var(--dsw-alias-brand-primary);cursor:pointer}',
|
|
97
|
+
'.mp-hosts{display:flex;flex-direction:column;gap:6px}',
|
|
98
|
+
'.mp-status{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary)}',
|
|
99
|
+
'.mp-ok{color:var(--dsw-alias-state-success-primary)}',
|
|
100
|
+
'.mp-err{color:var(--dsw-alias-state-error-primary)}',
|
|
101
|
+
].join('')
|
|
102
|
+
|
|
103
|
+
/** 代理地址是否可用(Host 也会校验,这里只求即时反馈)。 */
|
|
104
|
+
function proxyUsable(text) {
|
|
105
|
+
try {
|
|
106
|
+
const url = new URL(String(text).trim())
|
|
107
|
+
return url.protocol === 'http:' || url.protocol === 'https:'
|
|
108
|
+
} catch {
|
|
109
|
+
return false
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 把快照里的值读成本组件的草稿形态。 */
|
|
114
|
+
function draftOf(snapshot) {
|
|
115
|
+
const value = snapshot.value ?? {}
|
|
116
|
+
return {
|
|
117
|
+
enabled: value.enabled === true,
|
|
118
|
+
proxyUrl: typeof value.proxyUrl === 'string' ? value.proxyUrl : 'http://127.0.0.1:30080',
|
|
119
|
+
hosts: Array.isArray(value.hosts) ? value.hosts.map(String) : [],
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 设置页组件。
|
|
125
|
+
* props 由本次 activation 提供:form(Host 配置表单)、t(翻译)。
|
|
126
|
+
*/
|
|
127
|
+
function ModelProxySection(props) {
|
|
128
|
+
const { form, t } = props
|
|
129
|
+
const [snapshot, setSnapshot] = React.useState(() => form.getSnapshot())
|
|
130
|
+
const [draft, setDraft] = React.useState(() => draftOf(form.getSnapshot()))
|
|
131
|
+
const [dirty, setDirty] = React.useState(false)
|
|
132
|
+
const [busy, setBusy] = React.useState(false)
|
|
133
|
+
const [notice, setNotice] = React.useState(undefined)
|
|
134
|
+
/** 用 ref 读最新 dirty,避免 subscribe 闭包拿到过期值。 */
|
|
135
|
+
const dirtyRef = React.useRef(false)
|
|
136
|
+
dirtyRef.current = dirty
|
|
137
|
+
|
|
138
|
+
React.useEffect(() => form.subscribe(() => {
|
|
139
|
+
const next = form.getSnapshot()
|
|
140
|
+
setSnapshot(next)
|
|
141
|
+
// 自己没改动时跟随 Host 的权威值;否则保留用户正在编辑的草稿。
|
|
142
|
+
setDraft(current => (dirtyRef.current ? current : draftOf(next)))
|
|
143
|
+
}), [form])
|
|
144
|
+
|
|
145
|
+
const patch = (next) => {
|
|
146
|
+
setDirty(true)
|
|
147
|
+
setNotice(undefined)
|
|
148
|
+
setDraft(current => ({ ...current, ...next }))
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const setHostAt = (index, value) => {
|
|
152
|
+
setDirty(true)
|
|
153
|
+
setNotice(undefined)
|
|
154
|
+
setDraft(current => ({
|
|
155
|
+
...current,
|
|
156
|
+
hosts: current.hosts.map((host, at) => (at === index ? value : host)),
|
|
157
|
+
}))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const addHost = () => {
|
|
161
|
+
setDirty(true)
|
|
162
|
+
setNotice(undefined)
|
|
163
|
+
setDraft(current => ({ ...current, hosts: [...current.hosts, ''] }))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const removeHost = (index) => {
|
|
167
|
+
setDirty(true)
|
|
168
|
+
setNotice(undefined)
|
|
169
|
+
setDraft(current => ({ ...current, hosts: current.hosts.filter((_, at) => at !== index) }))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const save = async () => {
|
|
173
|
+
const hosts = draft.hosts.map(host => host.trim()).filter(host => host.length > 0)
|
|
174
|
+
setBusy(true)
|
|
175
|
+
try {
|
|
176
|
+
const accepted = await form.mutate([
|
|
177
|
+
{ op: 'set', path: ['enabled'], value: draft.enabled },
|
|
178
|
+
{ op: 'set', path: ['proxyUrl'], value: draft.proxyUrl.trim() },
|
|
179
|
+
{ op: 'set', path: ['hosts'], value: hosts },
|
|
180
|
+
])
|
|
181
|
+
if (accepted) {
|
|
182
|
+
setDirty(false)
|
|
183
|
+
setNotice({ kind: 'ok', text: t('saved') })
|
|
184
|
+
} else {
|
|
185
|
+
setNotice({ kind: 'err', text: t('saveFailed') })
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
setNotice({ kind: 'err', text: t('saveFailed') })
|
|
189
|
+
} finally {
|
|
190
|
+
setBusy(false)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (snapshot.status === 'unavailable') {
|
|
195
|
+
return h('div', { className: 'mp-page' }, h('p', { className: 'mp-hint' }, t('unavailable')))
|
|
196
|
+
}
|
|
197
|
+
if (snapshot.status === 'loading') {
|
|
198
|
+
return h('div', { className: 'mp-page' }, h('p', { className: 'mp-hint' }, t('loading')))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const hits = draft.hosts.filter(host => host.trim().length > 0)
|
|
202
|
+
const invalid = !proxyUsable(draft.proxyUrl)
|
|
203
|
+
const effective = draft.enabled && !invalid && hits.length > 0
|
|
204
|
+
const statusText = effective
|
|
205
|
+
? t('statusOn').replace('{proxy}', draft.proxyUrl.trim())
|
|
206
|
+
: t('statusOff')
|
|
207
|
+
|
|
208
|
+
return h('div', { className: 'mp-page' },
|
|
209
|
+
h('style', null, CSS),
|
|
210
|
+
h('p', { className: 'mp-intro' }, t('intro')),
|
|
211
|
+
|
|
212
|
+
h('label', { className: 'mp-switch' },
|
|
213
|
+
h('input', {
|
|
214
|
+
type: 'checkbox',
|
|
215
|
+
checked: draft.enabled,
|
|
216
|
+
onChange: event => patch({ enabled: event.target.checked }),
|
|
217
|
+
}),
|
|
218
|
+
t('enabled')),
|
|
219
|
+
|
|
220
|
+
h('div', { className: 'mp-field' },
|
|
221
|
+
h('label', { className: 'mp-label', htmlFor: 'mp-proxy-url' }, t('proxyUrl')),
|
|
222
|
+
h('input', {
|
|
223
|
+
id: 'mp-proxy-url',
|
|
224
|
+
className: 'mp-input',
|
|
225
|
+
type: 'text',
|
|
226
|
+
spellCheck: false,
|
|
227
|
+
value: draft.proxyUrl,
|
|
228
|
+
'aria-invalid': invalid ? 'true' : 'false',
|
|
229
|
+
onChange: event => patch({ proxyUrl: event.target.value }),
|
|
230
|
+
}),
|
|
231
|
+
h('p', { className: 'mp-hint' }, t('proxyUrlHint')),
|
|
232
|
+
invalid ? h('p', { className: 'mp-hint mp-err' }, t('invalidProxy')) : null),
|
|
233
|
+
|
|
234
|
+
h('div', { className: 'mp-field' },
|
|
235
|
+
h('span', { className: 'mp-label' }, t('hosts')),
|
|
236
|
+
h('p', { className: 'mp-hint' }, t('hostsHint')),
|
|
237
|
+
h('div', { className: 'mp-hosts' },
|
|
238
|
+
draft.hosts.map((host, index) => h('div', { className: 'mp-row', key: index },
|
|
239
|
+
h('input', {
|
|
240
|
+
className: 'mp-input',
|
|
241
|
+
type: 'text',
|
|
242
|
+
spellCheck: false,
|
|
243
|
+
placeholder: t('placeholder'),
|
|
244
|
+
value: host,
|
|
245
|
+
'aria-label': `${t('hosts')} ${index + 1}`,
|
|
246
|
+
onChange: event => setHostAt(index, event.target.value),
|
|
247
|
+
}),
|
|
248
|
+
h('button', {
|
|
249
|
+
className: 'mp-btn mp-btn-icon',
|
|
250
|
+
type: 'button',
|
|
251
|
+
title: t('remove'),
|
|
252
|
+
onClick: () => removeHost(index),
|
|
253
|
+
}, t('remove'))))),
|
|
254
|
+
h('div', { className: 'mp-row' },
|
|
255
|
+
h('button', {
|
|
256
|
+
className: 'mp-btn',
|
|
257
|
+
type: 'button',
|
|
258
|
+
onClick: addHost,
|
|
259
|
+
}, t('addHost')))),
|
|
260
|
+
|
|
261
|
+
h('div', { className: 'mp-row' },
|
|
262
|
+
h('button', {
|
|
263
|
+
className: 'mp-btn mp-btn-primary',
|
|
264
|
+
type: 'button',
|
|
265
|
+
disabled: busy || !snapshot.writable,
|
|
266
|
+
onClick: () => { void save() },
|
|
267
|
+
}, t('save')),
|
|
268
|
+
notice === undefined
|
|
269
|
+
? null
|
|
270
|
+
: h('p', { className: 'mp-status ' + (notice.kind === 'ok' ? 'mp-ok' : 'mp-err') }, notice.text)),
|
|
271
|
+
|
|
272
|
+
h('p', { className: 'mp-status' }, `${t('status')}:${statusText}`),
|
|
273
|
+
effective ? null : h('p', { className: 'mp-hint' }, t('needBoth')))
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
inject: ['slots', 'locale', 'configForms'],
|
|
278
|
+
apply(ctx) {
|
|
279
|
+
const t = ctx.locale.bind(NS)
|
|
280
|
+
|
|
281
|
+
ctx.effect(() => {
|
|
282
|
+
const disposeZh = ctx.locale.register(NS, 'zh', DICTS.zh)
|
|
283
|
+
const disposeEn = ctx.locale.register(NS, 'en', DICTS.en)
|
|
284
|
+
return () => { disposeZh(); disposeEn() }
|
|
285
|
+
}, 'model-proxy: dictionaries')
|
|
286
|
+
|
|
287
|
+
const form = ctx.configForms.get(ENTRY_ID)
|
|
288
|
+
|
|
289
|
+
function Section() {
|
|
290
|
+
return h(ModelProxySection, { form, t })
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
ctx.slots.inject(SECTION_SLOT, () => ctx.slots.register({
|
|
294
|
+
name: SECTION_SLOT,
|
|
295
|
+
id: ENTRY_ID,
|
|
296
|
+
order: 40,
|
|
297
|
+
label: () => t('nav'),
|
|
298
|
+
}, Section))
|
|
299
|
+
},
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
})
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Bundle patch:插入一行 model-proxy。
|
|
2
|
+
# 行名从 profile 自己的 node_modules 解析;配置的完整语义见 README。
|
|
3
|
+
# hosts 为代理白名单:命中的 origin 走 proxyUrl,未命中的一切照旧(直连,
|
|
4
|
+
# 或继续沿用进程原有的 HTTPS_PROXY 策略)。
|
|
5
|
+
- insert:
|
|
6
|
+
- id: model-proxy
|
|
7
|
+
name: '@jinngoo/dsh-model-proxy'
|
|
8
|
+
config:
|
|
9
|
+
enabled: true
|
|
10
|
+
proxyUrl: http://127.0.0.1:30080
|
|
11
|
+
hosts:
|
|
12
|
+
- api.commandcode.ai
|
package/icon.svg
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#4C6EF5" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" role="img" aria-label="Model proxy">
|
|
2
|
+
<path d="M3.2 12h5.1"/>
|
|
3
|
+
<path d="M15.7 12h5.1"/>
|
|
4
|
+
<rect x="8.3" y="7.2" width="7.4" height="9.6" rx="1.8"/>
|
|
5
|
+
<path d="M12 3.1v4.1"/>
|
|
6
|
+
<path d="M9.9 5.2 12 3.1l2.1 2.1"/>
|
|
7
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @jinngoo/dsh-model-proxy — 只让白名单主机的出站请求走代理。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:DSH 的代理策略是进程级的一件事(`@deepseek-ai/dsh-http-proxy` 装一个
|
|
5
|
+
* undici 全局 dispatcher),`NO_PROXY` 只能做「绕过名单」,表达不了「只有这个模型域名走
|
|
6
|
+
* 代理、其余全部直连」这种白名单语义。
|
|
7
|
+
*
|
|
8
|
+
* 做法:在 DSH 自己的安装之上再套一层 dispatcher —— **接管而不是覆盖**。命中的 origin
|
|
9
|
+
* 交给本插件的 `ProxyAgent`,未命中的一律委托给上一个 dispatcher,于是用户原有的
|
|
10
|
+
* `HTTPS_PROXY` 策略与 DSH 的 loopback 绕过全部原样保留。
|
|
11
|
+
*
|
|
12
|
+
* 已验证:`undici.setGlobalDispatcher()` 经 `Symbol.for('undici.globalDispatcher.1')`
|
|
13
|
+
* 作用到 Node 内置 `fetch`,而模型请求(pi-ai / llm-deepseek 都走 `globalThis.fetch`)
|
|
14
|
+
* 无需改动任何调用点。
|
|
15
|
+
*
|
|
16
|
+
* @module @jinngoo/dsh-model-proxy
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { createRequire } from 'node:module'
|
|
20
|
+
import z from '@deepseek-ai/schemastery'
|
|
21
|
+
|
|
22
|
+
export const name = '@jinngoo/dsh-model-proxy'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* undici 用 Node 自己的解析器加载,而不是交给打包/加载器转换成 ESM 命名空间。
|
|
26
|
+
*
|
|
27
|
+
* 两个原因:一是 undici 8 仍是 CJS,裸名解析在插件被链接安装(`file:`/`link:`)时
|
|
28
|
+
* 拿不到命名导出,运行期表现为 `getGlobalDispatcher is not a function`;二是必须确保
|
|
29
|
+
* 拿到的是**本进程**里的那一个 undici —— 全局 dispatcher 是跨包共享的隐式槽位
|
|
30
|
+
* (`Symbol.for('undici.globalDispatcher.1')`),换一份副本就什么都改不到。
|
|
31
|
+
*
|
|
32
|
+
* @returns 可用的 undici 模块。
|
|
33
|
+
*/
|
|
34
|
+
function loadUndici() {
|
|
35
|
+
const require = createRequire(import.meta.url)
|
|
36
|
+
const resolved = require.resolve('undici')
|
|
37
|
+
const loaded = require(resolved)
|
|
38
|
+
return { ...loaded, ...loaded.default }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 字段一律 `.volatile()`:设置界面只编辑这类字段,且它们在我们读取时才生效,改完不必重启。 */
|
|
42
|
+
export const Config = z.object({
|
|
43
|
+
/** 总开关;关掉即完全退回 DSH 原有策略。 */
|
|
44
|
+
enabled: z.boolean().default(false).volatile(),
|
|
45
|
+
/** 代理地址,只接受 http(s)://(与 DSH 自身策略一致,不支持 socks)。 */
|
|
46
|
+
proxyUrl: z.string().default('http://127.0.0.1:30080').volatile(),
|
|
47
|
+
/** 走代理的主机白名单:精确主机名或其后缀。 */
|
|
48
|
+
hosts: z.array(z.string()).default([]).volatile(),
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 主机是否命中白名单。
|
|
53
|
+
* @param host - 小写主机名。
|
|
54
|
+
* @param hosts - 白名单条目;`example.com` 同时匹配 `api.example.com`。
|
|
55
|
+
* @returns 命中为 true。
|
|
56
|
+
*/
|
|
57
|
+
export function matchesHost(host, hosts) {
|
|
58
|
+
for (const raw of hosts) {
|
|
59
|
+
const entry = String(raw).trim().toLowerCase().replace(/^\*?\.?/, '')
|
|
60
|
+
if (entry.length === 0) continue
|
|
61
|
+
if (host === entry || host.endsWith('.' + entry)) return true
|
|
62
|
+
}
|
|
63
|
+
return false
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 规范化代理地址。不可用的值返回 undefined —— 与 DSH 的策略一致:坏值跳过而
|
|
68
|
+
* 不阻止启动,该请求退回直连。
|
|
69
|
+
* @param raw - 配置里的代理地址。
|
|
70
|
+
* @returns 规范化 URL 字符串,或 undefined。
|
|
71
|
+
*/
|
|
72
|
+
export function normalizeProxy(raw) {
|
|
73
|
+
const text = String(raw ?? '').trim()
|
|
74
|
+
if (text.length === 0) return undefined
|
|
75
|
+
let url
|
|
76
|
+
try {
|
|
77
|
+
url = new URL(text)
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined
|
|
80
|
+
}
|
|
81
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined
|
|
82
|
+
return url.toString()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 安装路由 dispatcher。
|
|
87
|
+
* @param ctx - 插件上下文。
|
|
88
|
+
* @param config - 已校验的 volatile 配置引用。
|
|
89
|
+
*/
|
|
90
|
+
export function apply(ctx, config) {
|
|
91
|
+
const warn = (message) => {
|
|
92
|
+
try {
|
|
93
|
+
ctx.logger?.warn?.(`model-proxy: ${message}`)
|
|
94
|
+
} catch { /* 日志不可用时静默 */ }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let undici
|
|
98
|
+
try {
|
|
99
|
+
undici = loadUndici()
|
|
100
|
+
} catch (error) {
|
|
101
|
+
warn(`无法加载 undici,插件不生效:${error?.message ?? String(error)}`)
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
const { ProxyAgent, getGlobalDispatcher, setGlobalDispatcher } = undici
|
|
105
|
+
if (typeof getGlobalDispatcher !== 'function' || typeof setGlobalDispatcher !== 'function') {
|
|
106
|
+
warn('加载到的 undici 缺少 dispatcher 接口,插件不生效')
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 未命中的请求全部交给它,因此它不是我们创建的,也不能由我们关闭。 */
|
|
111
|
+
const previous = getGlobalDispatcher()
|
|
112
|
+
|
|
113
|
+
/** origin → ProxyAgent。 */
|
|
114
|
+
const agents = new Map()
|
|
115
|
+
/** 这些 agent 是按哪个代理地址建的;地址变了就整体作废。 */
|
|
116
|
+
let cachedProxy
|
|
117
|
+
|
|
118
|
+
const agentFor = (origin, proxy) => {
|
|
119
|
+
if (proxy !== cachedProxy) {
|
|
120
|
+
for (const stale of agents.values()) void stale.close().catch(() => {})
|
|
121
|
+
agents.clear()
|
|
122
|
+
cachedProxy = proxy
|
|
123
|
+
}
|
|
124
|
+
let agent = agents.get(origin)
|
|
125
|
+
if (agent === undefined) {
|
|
126
|
+
agent = new ProxyAgent({ uri: proxy })
|
|
127
|
+
agents.set(origin, agent)
|
|
128
|
+
}
|
|
129
|
+
return agent
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 只需实现 dispatch/close/destroy 的鸭子类型 dispatcher(undici 的
|
|
134
|
+
* `setGlobalDispatcher` 只做形状检查)。不继承其 `Dispatcher` 类,是为了在拿到的
|
|
135
|
+
* undici 没有该导出时也不至于整个插件挂掉。
|
|
136
|
+
*/
|
|
137
|
+
const router = {
|
|
138
|
+
dispatch(options, handler) {
|
|
139
|
+
if (!config.enabled.get()) return previous.dispatch(options, handler)
|
|
140
|
+
const proxy = normalizeProxy(config.proxyUrl.get())
|
|
141
|
+
if (proxy === undefined) return previous.dispatch(options, handler)
|
|
142
|
+
const origin = options.origin?.toString()
|
|
143
|
+
if (origin === undefined) return previous.dispatch(options, handler)
|
|
144
|
+
let host
|
|
145
|
+
try {
|
|
146
|
+
host = new URL(origin).hostname.toLowerCase()
|
|
147
|
+
} catch {
|
|
148
|
+
return previous.dispatch(options, handler)
|
|
149
|
+
}
|
|
150
|
+
if (!matchesHost(host, config.hosts.get() ?? [])) return previous.dispatch(options, handler)
|
|
151
|
+
return agentFor(origin, proxy).dispatch(options, handler)
|
|
152
|
+
},
|
|
153
|
+
|
|
154
|
+
/** 只关本插件建的 agent;全局 dispatcher 与上一个 dispatcher 都不归我们所有。 */
|
|
155
|
+
async close() {
|
|
156
|
+
const all = [...agents.values()]
|
|
157
|
+
agents.clear()
|
|
158
|
+
await Promise.allSettled(all.map(agent => agent.close()))
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
/** 同上,强制终止。 */
|
|
162
|
+
async destroy() {
|
|
163
|
+
const all = [...agents.values()]
|
|
164
|
+
agents.clear()
|
|
165
|
+
await Promise.allSettled(all.map(agent => agent.destroy()))
|
|
166
|
+
},
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
setGlobalDispatcher(router)
|
|
170
|
+
|
|
171
|
+
// 卸载或 HMR 重建时只还原自己装的这一层。
|
|
172
|
+
ctx.effect(() => () => {
|
|
173
|
+
if (getGlobalDispatcher() === router) setGlobalDispatcher(previous)
|
|
174
|
+
void router.close()
|
|
175
|
+
}, 'model-proxy: dispatcher')
|
|
176
|
+
|
|
177
|
+
const hosts = config.hosts.get() ?? []
|
|
178
|
+
if (config.enabled.get() && normalizeProxy(config.proxyUrl.get()) !== undefined && hosts.length > 0) {
|
|
179
|
+
warn(`已接管 ${hosts.join(', ')} → ${config.proxyUrl.get()}`)
|
|
180
|
+
} else {
|
|
181
|
+
warn('已就绪但未启用:enabled / proxyUrl / hosts 未配全,当前没有任何请求被代理')
|
|
182
|
+
}
|
|
183
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Model proxy",
|
|
4
|
+
"description": "Sends requests for the hosts you list through an HTTP proxy; every other outbound request (the Web UI, page fetches, plugin installation, local services) keeps its own route. For splitting traffic such as a proxied overseas model beside a direct domestic one, without maintaining a long NO_PROXY list. The settings page is under Settings → Model proxy."
|
|
5
|
+
},
|
|
6
|
+
"config": {
|
|
7
|
+
"enabled": "Master switch. Turning it off falls back to the Harness proxy policy unchanged.",
|
|
8
|
+
"proxyUrl": "Proxy address, http:// or https:// only. A socks address is ignored, matching the Harness policy.",
|
|
9
|
+
"hosts": "Hosts that go through the proxy. A domain covers its subdomains: example.com also matches api.example.com. Hosts not listed are unaffected."
|
|
10
|
+
}
|
|
11
|
+
}
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "模型代理",
|
|
4
|
+
"description": "只让名单内的主机经由 HTTP 代理发出请求,其余出站请求(Web 界面、网页抓取、插件安装、本机服务)保持原有路由。用于「国外模型走代理、国内模型直连」这类分流,不必再维护一长串 NO_PROXY。设置页在「设置 → 模型代理」。"
|
|
5
|
+
},
|
|
6
|
+
"config": {
|
|
7
|
+
"enabled": "总开关。关闭后完全退回 DSH 原有的代理策略。",
|
|
8
|
+
"proxyUrl": "代理地址,只接受 http:// 或 https://。socks 地址会被忽略,与 DSH 自身的代理策略一致。",
|
|
9
|
+
"hosts": "走代理的主机白名单。写域名即覆盖其子域名:example.com 也会匹配 api.example.com。未命中的主机不受影响。"
|
|
10
|
+
}
|
|
11
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jinngoo/dsh-model-proxy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "DSH 插件:只让名单内的主机经由 HTTP 代理发出请求,其余出站请求保持原有路由。用于「国外模型走代理、国内模型直连」这类分流,带设置界面,改完即时生效。",
|
|
5
|
+
"author": "Jinngoo <jinngoo@qq.com> (https://github.com/Jinngoo)",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Jinngoo/dsh-model-proxy.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Jinngoo/dsh-model-proxy#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/Jinngoo/dsh-model-proxy/issues"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "index.js",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./index.js",
|
|
22
|
+
"./client": "./client.js",
|
|
23
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
24
|
+
"./locale/*.json": "./locale/*.json",
|
|
25
|
+
"./icon": "./icon.svg",
|
|
26
|
+
"./package.json": "./package.json"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"index.js",
|
|
30
|
+
"client.js",
|
|
31
|
+
"cordis.patch.yml",
|
|
32
|
+
"locale/*.json",
|
|
33
|
+
"icon.svg",
|
|
34
|
+
"tests",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=22",
|
|
40
|
+
"dsh": "^0.2.3-alpha.2"
|
|
41
|
+
},
|
|
42
|
+
"dsh": {
|
|
43
|
+
"bundle": {
|
|
44
|
+
"patch": "./cordis.patch.yml"
|
|
45
|
+
},
|
|
46
|
+
"client": {
|
|
47
|
+
"platform": "web",
|
|
48
|
+
"immediately": true,
|
|
49
|
+
"inject": [
|
|
50
|
+
"@deepseek-ai/dsh-client-ui-settings",
|
|
51
|
+
"@deepseek-ai/dsh-client-locale",
|
|
52
|
+
"@deepseek-ai/dsh-client-connection",
|
|
53
|
+
"@deepseek-ai/dsh-api-remotes"
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"check": "node tests/local-check.mjs"
|
|
59
|
+
},
|
|
60
|
+
"dependencies": {
|
|
61
|
+
"@deepseek-ai/schemastery": "^3.18.5",
|
|
62
|
+
"undici": "^8.14.0"
|
|
63
|
+
},
|
|
64
|
+
"keywords": [
|
|
65
|
+
"deepseek",
|
|
66
|
+
"deepseek-harness",
|
|
67
|
+
"dsh",
|
|
68
|
+
"dsh-plugin",
|
|
69
|
+
"proxy",
|
|
70
|
+
"undici",
|
|
71
|
+
"分流",
|
|
72
|
+
"代理"
|
|
73
|
+
]
|
|
74
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// 本地验证 Host 半:假 ctx + 真 undici。
|
|
2
|
+
// 用「假代理」判定是否真的走了代理:把 proxyUrl 指向一个必然连不上的端口,
|
|
3
|
+
// 命中白名单的主机应当失败,未命中的主机应当照常成功。
|
|
4
|
+
import { getGlobalDispatcher } from 'undici'
|
|
5
|
+
import { apply, matchesHost, normalizeProxy } from '../index.js'
|
|
6
|
+
|
|
7
|
+
const REAL_PROXY = 'http://127.0.0.1:30080'
|
|
8
|
+
const DEAD_PROXY = 'http://127.0.0.1:9'
|
|
9
|
+
const ALLOWED = 'https://api.commandcode.ai/provider/v1/models'
|
|
10
|
+
const OTHER = 'https://registry.npmmirror.com/undici/latest'
|
|
11
|
+
|
|
12
|
+
let failures = 0
|
|
13
|
+
const check = (ok, label) => {
|
|
14
|
+
console.log(`${ok ? 'PASS' : 'FAIL'} ${label}`)
|
|
15
|
+
if (!ok) failures++
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// 纯函数
|
|
19
|
+
check(matchesHost('api.commandcode.ai', ['api.commandcode.ai']), 'exact host')
|
|
20
|
+
check(matchesHost('api.commandcode.ai', ['commandcode.ai']), 'suffix host')
|
|
21
|
+
check(!matchesHost('notcommandcode.ai', ['commandcode.ai']), 'no false suffix')
|
|
22
|
+
check(matchesHost('a.b.example.com', ['.example.com']), 'leading dot')
|
|
23
|
+
check(matchesHost('x.example.com', ['*.example.com']), 'leading star-dot')
|
|
24
|
+
check(normalizeProxy(' socks5://127.0.0.1:1080 ') === undefined, 'socks rejected')
|
|
25
|
+
check(normalizeProxy('http://127.0.0.1:30080') !== undefined, 'http accepted')
|
|
26
|
+
check(normalizeProxy(' ') === undefined, 'blank rejected')
|
|
27
|
+
|
|
28
|
+
const values = { enabled: true, proxyUrl: REAL_PROXY, hosts: ['api.commandcode.ai'] }
|
|
29
|
+
const config = {
|
|
30
|
+
enabled: { get: () => values.enabled },
|
|
31
|
+
proxyUrl: { get: () => values.proxyUrl },
|
|
32
|
+
hosts: { get: () => values.hosts },
|
|
33
|
+
}
|
|
34
|
+
const disposers = []
|
|
35
|
+
const ctx = {
|
|
36
|
+
logger: { warn: (...a) => console.log(' [warn]', ...a) },
|
|
37
|
+
effect: (fn) => { disposers.push(fn()) },
|
|
38
|
+
}
|
|
39
|
+
const attempt = async (url) => {
|
|
40
|
+
try {
|
|
41
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(20000) })
|
|
42
|
+
return res.status
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return `ERR ${error.cause?.code ?? error.message}`
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 1) 真代理:两个目标都应可达
|
|
49
|
+
const before = getGlobalDispatcher()
|
|
50
|
+
apply(ctx, config)
|
|
51
|
+
check(getGlobalDispatcher() !== before, 'global dispatcher replaced')
|
|
52
|
+
const okAllowed = await attempt(ALLOWED)
|
|
53
|
+
const okOther = await attempt(OTHER)
|
|
54
|
+
console.log(` allowed → ${okAllowed} | other → ${okOther}`)
|
|
55
|
+
check(okAllowed === 200, 'allowed host reachable through proxy')
|
|
56
|
+
check(okOther === 200, 'other host reachable directly')
|
|
57
|
+
for (const dispose of disposers) dispose()
|
|
58
|
+
await new Promise(r => setTimeout(r, 300))
|
|
59
|
+
check(getGlobalDispatcher() === before, 'dispatcher restored on dispose')
|
|
60
|
+
|
|
61
|
+
// 2) 死代理:命中白名单必须失败,未命中的必须照常成功 —— 这才证明分流真的生效
|
|
62
|
+
values.proxyUrl = DEAD_PROXY
|
|
63
|
+
const disposers2 = []
|
|
64
|
+
apply({ ...ctx, effect: (fn) => { disposers2.push(fn()) } }, config)
|
|
65
|
+
const deadAllowed = await attempt(ALLOWED)
|
|
66
|
+
const deadOther = await attempt(OTHER)
|
|
67
|
+
console.log(` dead-proxy allowed → ${deadAllowed} | other → ${deadOther}`)
|
|
68
|
+
check(deadAllowed !== 200, 'allowed host is really routed through the (dead) proxy')
|
|
69
|
+
check(deadOther === 200, 'other host is NOT routed through the proxy')
|
|
70
|
+
for (const dispose of disposers2) dispose()
|
|
71
|
+
await new Promise(r => setTimeout(r, 300))
|
|
72
|
+
|
|
73
|
+
// 3) 关闭开关后,命中白名单的主机也应恢复直连
|
|
74
|
+
values.proxyUrl = DEAD_PROXY
|
|
75
|
+
values.enabled = false
|
|
76
|
+
const disposers3 = []
|
|
77
|
+
apply({ ...ctx, effect: (fn) => { disposers3.push(fn()) } }, config)
|
|
78
|
+
const offAllowed = await attempt(ALLOWED)
|
|
79
|
+
console.log(` disabled allowed → ${offAllowed}`)
|
|
80
|
+
check(offAllowed === 200, 'disabled falls back to the previous route')
|
|
81
|
+
for (const dispose of disposers3) dispose()
|
|
82
|
+
|
|
83
|
+
console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
|
|
84
|
+
process.exit(failures === 0 ? 0 : 1)
|