dsh-connect-workbuddy-gateway 1.2.0 → 1.3.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/README.md +44 -2
- package/client.js +129 -0
- package/index.js +11 -0
- package/package.json +1 -1
- package/src/listener.js +21 -3
- package/src/models.js +55 -1
- package/src/network.js +146 -0
- package/src/resolve.js +17 -2
- package/src/routes.js +128 -6
package/README.md
CHANGED
|
@@ -135,6 +135,48 @@ curl http://127.0.0.1:8790/v1/chat/completions \
|
|
|
135
135
|
|
|
136
136
|
---
|
|
137
137
|
|
|
138
|
+
## 局域网访问
|
|
139
|
+
|
|
140
|
+
默认只监听 `127.0.0.1`。在设置页把 **局域网访问** 打开后,网关改绑 `0.0.0.0`,
|
|
141
|
+
同一网段的其他设备(手机、平板、另一台电脑)就能用这台机器的局域网 IP 调用:
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
http://192.168.31.107:8790/v1 ← OpenAI Chat / Responses
|
|
145
|
+
http://192.168.31.107:8790 ← Anthropic / Gemini
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
设置页会把本机局域网地址算出来,并按「用户大概想要哪个」排序(家用 `192.168.*`
|
|
149
|
+
在前,其次 `10.*`、`172.16-31.*`)。有多个时选**其他设备能 ping 通**的那个。
|
|
150
|
+
|
|
151
|
+
也可以直接改 profile:
|
|
152
|
+
|
|
153
|
+
```yaml
|
|
154
|
+
config:
|
|
155
|
+
port: 8790
|
|
156
|
+
allowLan: true
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### 打开这个开关意味着什么
|
|
160
|
+
|
|
161
|
+
| | 本机(默认) | 局域网 |
|
|
162
|
+
|---|---|---|
|
|
163
|
+
| 调 API | 需要 key | **需要 key** |
|
|
164
|
+
| 读/改配置、看 key 明文 | 可以 | **不行**(loopback 闸门) |
|
|
165
|
+
|
|
166
|
+
具体说:
|
|
167
|
+
|
|
168
|
+
- **仍然只认 API key。** 打开局域网不会变成免鉴权。
|
|
169
|
+
- **设置页接口不接受非本机请求。** 局域网设备即使知道地址也调不了管理接口,
|
|
170
|
+
改不了配置、看不到 key 明文。这道闸门在插件里(`loopbackOnly`)与 DSH 宿主
|
|
171
|
+
各有一层。
|
|
172
|
+
- **端口对整个网段开放。** 同一网络里知道地址的人都能来敲门(会被 key 挡)。
|
|
173
|
+
可信任的网络里再开。
|
|
174
|
+
|
|
175
|
+
> 想临时分享给别人的话,建议**新建一把只勾必要模型的 key** 再发出去 ——
|
|
176
|
+
> 把一把 key 发出去等于把对应额度分给他用。
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
138
180
|
## 路径前缀
|
|
139
181
|
|
|
140
182
|
协议端点直接挂在根路径(`/v1/chat/completions` 这种),没有自定义前缀。
|
|
@@ -392,8 +434,8 @@ hy4flash-free@#9 ← 昵称含中文/emoji,退化成序号
|
|
|
392
434
|
node tests/harness.mjs
|
|
393
435
|
```
|
|
394
436
|
|
|
395
|
-
覆盖
|
|
396
|
-
非 ASCII
|
|
437
|
+
覆盖 223 项:首次建 key 与惰性补选、鉴权、模型勾选与清单投影、重名后缀(区域 / 昵称 /
|
|
438
|
+
非 ASCII 序号)、跨区同名、按名字路由、推理档透传、**固定监听端口与占用提示**、**局域网分享与它的边界**、
|
|
397
439
|
并行工具调用按 index 分组、
|
|
398
440
|
Responses 流的规范校验(`sequence_number`、part 一致性、terminal 的 output 顺序)、
|
|
399
441
|
上游失败与断流的诚实报告、账号可用性与恢复、四种协议的流式与非流式、工具调用三方言、
|
package/client.js
CHANGED
|
@@ -81,6 +81,21 @@ window.__ModuleLoader__.load({
|
|
|
81
81
|
portRange: '填 1–65535 之间的整数。改动后下游应用的 base URL 也要跟着改。',
|
|
82
82
|
portBusy: '端口被占用',
|
|
83
83
|
portBusyHint: '换一个端口后保存。网关不会自己换端口,因为那样 base URL 会变。',
|
|
84
|
+
/* 局域网分享 */
|
|
85
|
+
lan: '局域网访问',
|
|
86
|
+
lanHint: '打开后同一网段的其他设备(手机、平板、另一台电脑)可以用本机 IP 调用这套 API。',
|
|
87
|
+
lanOff: '未开启(只有本机能访问)',
|
|
88
|
+
lanOn: '已开启',
|
|
89
|
+
lanEnable: '允许局域网访问',
|
|
90
|
+
lanDisable: '关闭局域网访问',
|
|
91
|
+
lanAddresses: '本机局域网地址',
|
|
92
|
+
lanNoAddress: '没探测到局域网地址 —— 检查这台机器是否连着网络,或自己查一下本机 IP。',
|
|
93
|
+
lanEndpoints: '其他设备填这些地址',
|
|
94
|
+
lanCopy: '复制',
|
|
95
|
+
lanWarn: '开启后同一网段的设备都能访问这个端口。它们仍然需要 API key,设置页接口也只接受本机请求(它们改不了配置、看不到 key)。',
|
|
96
|
+
lanChanged: '已保存,插件会重新加载',
|
|
97
|
+
lanChoose: '有多个地址时选「其他设备能 ping 通本机」的那个。',
|
|
98
|
+
lanKeyHint: '把 key 发给别人等于把额度分给他用 —— 按需新建一把只勾必要模型的 key。',
|
|
84
99
|
selected: '已选',
|
|
85
100
|
noneSelected: '还没有勾选任何模型,这把 key 暂时不能用。',
|
|
86
101
|
willExpose: '客户端会看到',
|
|
@@ -161,6 +176,21 @@ window.__ModuleLoader__.load({
|
|
|
161
176
|
portRange: 'An integer from 1 to 65535. Downstream apps need their base URL updated after a change.',
|
|
162
177
|
portBusy: 'Port in use',
|
|
163
178
|
portBusyHint: 'Pick another port and save. The gateway will not move on its own, because that would change the base URL.',
|
|
179
|
+
/* LAN sharing */
|
|
180
|
+
lan: 'LAN access',
|
|
181
|
+
lanHint: 'When on, other devices on the same network (phone, tablet, another computer) can call this API using this machine\'s IP.',
|
|
182
|
+
lanOff: 'Off (this machine only)',
|
|
183
|
+
lanOn: 'On',
|
|
184
|
+
lanEnable: 'Allow LAN access',
|
|
185
|
+
lanDisable: 'Turn off LAN access',
|
|
186
|
+
lanAddresses: 'This machine\'s LAN addresses',
|
|
187
|
+
lanNoAddress: 'No LAN address detected - check the machine is on a network, or look up its IP yourself.',
|
|
188
|
+
lanEndpoints: 'Other devices use these',
|
|
189
|
+
lanCopy: 'Copy',
|
|
190
|
+
lanWarn: 'With this on, anything on the same network can reach this port. They still need an API key, and the settings routes stay loopback-only, so they cannot change configuration or read keys.',
|
|
191
|
+
lanChanged: 'Saved; the plugin reloads to apply it',
|
|
192
|
+
lanChoose: 'With several addresses, pick the one other devices can ping.',
|
|
193
|
+
lanKeyHint: 'Handing over a key means handing over your quota - create a key that only ticks the models that person needs.',
|
|
164
194
|
selected: 'selected',
|
|
165
195
|
noneSelected: 'No models ticked yet, so this key cannot be used.',
|
|
166
196
|
willExpose: 'The client will see',
|
|
@@ -883,6 +913,93 @@ window.__ModuleLoader__.load({
|
|
|
883
913
|
)
|
|
884
914
|
}
|
|
885
915
|
|
|
916
|
+
/* ── 局域网分享 ─────────────────────────────────────────────────── */
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* 局域网访问卡片。
|
|
920
|
+
*
|
|
921
|
+
* 这个开关扩大的是**网络可达范围**,所以界面上把代价写清楚:仍然要 API key,
|
|
922
|
+
* 设置页仍然只接受本机请求。另外直接把「其他设备该填什么地址」算出来给出,
|
|
923
|
+
* 而不是让用户自己去 ipconfig 里翻。
|
|
924
|
+
*/
|
|
925
|
+
function LanCard({ state, t, onToggle }) {
|
|
926
|
+
const lan = state?.lan ?? {}
|
|
927
|
+
const [busy, setBusy] = useState(false)
|
|
928
|
+
const [error, setError] = useState(undefined)
|
|
929
|
+
const [saved, setSaved] = useState(false)
|
|
930
|
+
|
|
931
|
+
const enabled = lan.enabled === true
|
|
932
|
+
const addresses = Array.isArray(lan.addresses) ? lan.addresses : []
|
|
933
|
+
const endpoints = Array.isArray(lan.endpoints) ? lan.endpoints : []
|
|
934
|
+
|
|
935
|
+
const flip = async () => {
|
|
936
|
+
setBusy(true)
|
|
937
|
+
setError(undefined)
|
|
938
|
+
try {
|
|
939
|
+
await onToggle(!enabled)
|
|
940
|
+
setSaved(true)
|
|
941
|
+
setTimeout(() => setSaved(false), 4000)
|
|
942
|
+
} catch (caught) {
|
|
943
|
+
setError(String(caught.message ?? caught))
|
|
944
|
+
} finally {
|
|
945
|
+
setBusy(false)
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
return h('div', { className: 'wbg-card wbg-card-soft' },
|
|
950
|
+
h('div', { className: 'wbg-row' },
|
|
951
|
+
h('strong', { className: 'wbg-sec-title' }, t.lan),
|
|
952
|
+
h('span', {
|
|
953
|
+
className: enabled ? 'wbg-badge wbg-badge-ok' : 'wbg-badge',
|
|
954
|
+
}, enabled ? t.lanOn : t.lanOff),
|
|
955
|
+
h('span', { className: 'wbg-spacer' }),
|
|
956
|
+
h('button', {
|
|
957
|
+
type: 'button',
|
|
958
|
+
className: enabled ? 'wbg-btn' : 'wbg-btn wbg-btn-primary',
|
|
959
|
+
onClick: flip,
|
|
960
|
+
disabled: busy,
|
|
961
|
+
}, enabled ? t.lanDisable : t.lanEnable),
|
|
962
|
+
),
|
|
963
|
+
|
|
964
|
+
h('p', { className: 'wbg-hint' }, t.lanHint),
|
|
965
|
+
h('p', { className: 'wbg-warn' }, t.lanWarn),
|
|
966
|
+
|
|
967
|
+
/* 开着但没有地址:要么没联网,要么全是不该用的保留段。 */
|
|
968
|
+
enabled && addresses.length === 0
|
|
969
|
+
? h('div', { className: 'wbg-alert wbg-alert-warn' },
|
|
970
|
+
h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
|
|
971
|
+
h('span', { className: 'wbg-alert-body' }, t.lanNoAddress))
|
|
972
|
+
: null,
|
|
973
|
+
|
|
974
|
+
enabled && addresses.length > 0
|
|
975
|
+
? h('div', { className: 'wbg-field' },
|
|
976
|
+
h('span', null, t.lanAddresses),
|
|
977
|
+
h('div', { className: 'wbg-chips' },
|
|
978
|
+
addresses.map((address) => h('span', { key: address, className: 'wbg-chip wbg-mono' }, address)),
|
|
979
|
+
),
|
|
980
|
+
addresses.length > 1 ? h('p', { className: 'wbg-caption' }, t.lanChoose) : null,
|
|
981
|
+
)
|
|
982
|
+
: null,
|
|
983
|
+
|
|
984
|
+
/* 别的设备直接能抄的地址。 */
|
|
985
|
+
enabled && endpoints.length > 0
|
|
986
|
+
? h('div', { className: 'wbg-field' },
|
|
987
|
+
h('span', null, t.lanEndpoints),
|
|
988
|
+
h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
|
|
989
|
+
endpoints.map((endpoint) => h(EndpointRow, { key: endpoint.id, entry: endpoint, t })),
|
|
990
|
+
),
|
|
991
|
+
h('p', { className: 'wbg-caption' }, t.lanKeyHint),
|
|
992
|
+
)
|
|
993
|
+
: null,
|
|
994
|
+
|
|
995
|
+
error === undefined ? null : h('div', { className: 'wbg-alert wbg-alert-error' },
|
|
996
|
+
h('span', { className: 'wbg-alert-icon', 'aria-hidden': true }, '!'),
|
|
997
|
+
h('span', { className: 'wbg-alert-body' }, error)),
|
|
998
|
+
|
|
999
|
+
saved ? h('p', { className: 'wbg-caption' }, t.lanChanged) : null,
|
|
1000
|
+
)
|
|
1001
|
+
}
|
|
1002
|
+
|
|
886
1003
|
/* ── 页面 ───────────────────────────────────────────────────────── */
|
|
887
1004
|
|
|
888
1005
|
function GatewaySection() {
|
|
@@ -975,6 +1092,17 @@ window.__ModuleLoader__.load({
|
|
|
975
1092
|
await reload()
|
|
976
1093
|
}, [reload])
|
|
977
1094
|
|
|
1095
|
+
/*
|
|
1096
|
+
* 开关局域网访问。
|
|
1097
|
+
*
|
|
1098
|
+
* 传布尔值而不是 `!current`:后端只认真正的 `true`/`false`,避免一次
|
|
1099
|
+
* 类型意外把网关对着整个网段打开。
|
|
1100
|
+
*/
|
|
1101
|
+
const saveAllowLan = useCallback(async (allowLan) => {
|
|
1102
|
+
await adminPost('/config/allow-lan', { allowLan: allowLan === true })
|
|
1103
|
+
await reload()
|
|
1104
|
+
}, [reload])
|
|
1105
|
+
|
|
978
1106
|
if (state === undefined) {
|
|
979
1107
|
return h('div', { className: 'wbg' },
|
|
980
1108
|
h('style', null, CSS),
|
|
@@ -1070,6 +1198,7 @@ window.__ModuleLoader__.load({
|
|
|
1070
1198
|
),
|
|
1071
1199
|
|
|
1072
1200
|
h(PortCard, { state, t, onSave: savePort }),
|
|
1201
|
+
h(LanCard, { state, t, onToggle: saveAllowLan }),
|
|
1073
1202
|
h(StorageCard, { state, t, onSave: saveDataDir }),
|
|
1074
1203
|
|
|
1075
1204
|
created === undefined ? null : h(SecretDialog, {
|
package/index.js
CHANGED
|
@@ -40,6 +40,17 @@ const DEFAULTS = {
|
|
|
40
40
|
* 设置页显示"端口被占用",让用户自己改一个。
|
|
41
41
|
*/
|
|
42
42
|
port: 8790,
|
|
43
|
+
/**
|
|
44
|
+
* 是否允许局域网其他设备访问。
|
|
45
|
+
*
|
|
46
|
+
* **默认关闭。** 打开后网关从 `127.0.0.1` 改绑 `0.0.0.0`,同一网段的设备就能
|
|
47
|
+
* 用本机 IP 调这套 API。默认关着是因为「监听到局域网」是一个安全边界的扩大,
|
|
48
|
+
* 应该由用户显式选择,而不是装好就对着整个网段开门。
|
|
49
|
+
*
|
|
50
|
+
* 注意打开后仍然**只认 API key**:管理接口(设置页那些)另有 loopback 闸门,
|
|
51
|
+
* 局域网设备改不了配置、看不到 key 明文。
|
|
52
|
+
*/
|
|
53
|
+
allowLan: false,
|
|
43
54
|
/**
|
|
44
55
|
* 配置目录。
|
|
45
56
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-connect-workbuddy-gateway",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"description": "把 dsh-connect-workbuddy 的 WorkBuddy 模型开放成本机 API:OpenAI Chat / Responses、Anthropic Messages、Gemini 四协议共用一个 base URL,模型按 API key 逐个勾选。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh-plugin",
|
package/src/listener.js
CHANGED
|
@@ -43,11 +43,27 @@ export function describeListenError(error, port) {
|
|
|
43
43
|
return `监听 ${port} 失败:${error instanceof Error ? error.message : String(error)}`
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** 只监听本机回环。默认值。 */
|
|
47
|
+
export const HOST_LOOPBACK = '127.0.0.1'
|
|
48
|
+
/** 监听所有网卡(含局域网)。 */
|
|
49
|
+
export const HOST_ALL = '0.0.0.0'
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 决定绑哪个地址。
|
|
53
|
+
*
|
|
54
|
+
* @param lan 是否允许局域网访问
|
|
55
|
+
* @returns 绑定的 host
|
|
56
|
+
*/
|
|
57
|
+
export function hostFor(lan) {
|
|
58
|
+
return lan === true ? HOST_ALL : HOST_LOOPBACK
|
|
59
|
+
}
|
|
60
|
+
|
|
46
61
|
/**
|
|
47
62
|
* 启动网关监听。
|
|
48
63
|
*
|
|
49
64
|
* @param options 配置
|
|
50
65
|
* @param options.port 端口
|
|
66
|
+
* @param options.host 绑定地址;默认 `127.0.0.1`(仅本机)
|
|
51
67
|
* @param options.handler `(req, res) => void`,与 webServer 的 handler 同形
|
|
52
68
|
* @param options.logger 宿主 logger
|
|
53
69
|
* @returns `{ state, ready, close }`
|
|
@@ -55,9 +71,10 @@ export function describeListenError(error, port) {
|
|
|
55
71
|
* - `ready`:等到出结果(成功或失败)才 resolve,不会 reject
|
|
56
72
|
* - `close`:关掉监听
|
|
57
73
|
*/
|
|
58
|
-
export function startListener({ port, handler, logger }) {
|
|
74
|
+
export function startListener({ port, host = HOST_LOOPBACK, handler, logger }) {
|
|
59
75
|
const state = {
|
|
60
76
|
port,
|
|
77
|
+
host,
|
|
61
78
|
listening: false,
|
|
62
79
|
error: undefined,
|
|
63
80
|
}
|
|
@@ -86,10 +103,11 @@ export function startListener({ port, handler, logger }) {
|
|
|
86
103
|
logger?.warn?.(`workbuddy-gateway: ${state.error}`)
|
|
87
104
|
resolve(state)
|
|
88
105
|
})
|
|
89
|
-
server.listen(port,
|
|
106
|
+
server.listen(port, host, () => {
|
|
90
107
|
state.listening = true
|
|
91
108
|
state.error = undefined
|
|
92
|
-
|
|
109
|
+
const where = host === HOST_ALL ? `on all interfaces (LAN reachable), port ${port}` : `on http://127.0.0.1:${port}`
|
|
110
|
+
logger?.info?.(`workbuddy-gateway: gateway listening ${where}`)
|
|
93
111
|
resolve(state)
|
|
94
112
|
})
|
|
95
113
|
})
|
package/src/models.js
CHANGED
|
@@ -65,6 +65,15 @@ export async function directModelsByRegion(env) {
|
|
|
65
65
|
export async function catalogForSettings(env, accounts, usableAccounts) {
|
|
66
66
|
const entries = await collectModels(env)
|
|
67
67
|
const pool = entries.length > 0 ? entries : await directModelsByRegion(env)
|
|
68
|
+
|
|
69
|
+
/*
|
|
70
|
+
* 把这份目录记到 env 上,供 {@link keyCatalog} 判断「落盘的勾选是否还有效」。
|
|
71
|
+
*
|
|
72
|
+
* 只在目录**非空**时记:一次读失败(上游暂时不可达)不该被当成「上游没有任何
|
|
73
|
+
* 模型」,否则下一次请求会把用户的清单整个清空。
|
|
74
|
+
*/
|
|
75
|
+
if (pool.length > 0) env.liveModels = liveModelKeys(pool)
|
|
76
|
+
|
|
68
77
|
const usableIds = usableAccounts === undefined
|
|
69
78
|
? undefined
|
|
70
79
|
: new Set(usableAccounts.map((account) => account.id))
|
|
@@ -95,7 +104,52 @@ export async function catalogForSettings(env, accounts, usableAccounts) {
|
|
|
95
104
|
return out
|
|
96
105
|
}
|
|
97
106
|
|
|
98
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* 上游此刻真正提供的模型键集合:`region \0 modelId`。
|
|
109
|
+
*
|
|
110
|
+
* 用来判断一条落盘的勾选是否**仍然指向一个存在的模型**。
|
|
111
|
+
*
|
|
112
|
+
* @param pool {@link collectModels} 或 {@link directModelsByRegion} 的结果
|
|
113
|
+
*/
|
|
114
|
+
export function liveModelKeys(pool) {
|
|
115
|
+
const keys = new Set()
|
|
116
|
+
for (const entry of Array.isArray(pool) ? pool : []) {
|
|
117
|
+
keys.add(`${entry.region ?? ''}\u0000${entry.id}`)
|
|
118
|
+
}
|
|
119
|
+
return keys
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 把勾选清单收窄到「上游此刻仍然提供」的模型。
|
|
124
|
+
*
|
|
125
|
+
* ## 为什么必须收窄
|
|
126
|
+
*
|
|
127
|
+
* 勾选是**落盘**的,而上游的模型目录是**活的**:用户可能在上游卡片里取消勾选某个
|
|
128
|
+
* 模型,或者在那边换了套餐、模型下架、区域关掉。那些勾选会一直留在 keys.json 里,
|
|
129
|
+
* 于是网关继续对外宣称提供这些模型 —— 客户端能选到,一调就失败。
|
|
130
|
+
*
|
|
131
|
+
* 用户报的就是这个现象:「勾选项没有和上游插件的选中模型同步」。
|
|
132
|
+
*
|
|
133
|
+
* ## 为什么按 (region, modelId) 而不是按名字
|
|
134
|
+
*
|
|
135
|
+
* 客户端看到的名字带账号后缀(`x@pony`),那是由勾选**推导**出来的;判存活要看
|
|
136
|
+
* 上游真实 id 与区域,两者不能混。
|
|
137
|
+
*
|
|
138
|
+
* @param selections key 的勾选
|
|
139
|
+
* @param live {@link liveModelKeys} 的结果
|
|
140
|
+
* @returns `{ kept, dropped }`,`dropped` 供设置页提示用户
|
|
141
|
+
*/
|
|
142
|
+
export function pruneSelections(selections, live) {
|
|
143
|
+
const kept = []
|
|
144
|
+
const dropped = []
|
|
145
|
+
for (const selection of Array.isArray(selections) ? selections : []) {
|
|
146
|
+
const region = selection.region ?? ''
|
|
147
|
+
const key = `${region}\u0000${selection.modelId}`
|
|
148
|
+
if (live.has(key)) kept.push(selection)
|
|
149
|
+
else dropped.push(selection)
|
|
150
|
+
}
|
|
151
|
+
return { kept, dropped }
|
|
152
|
+
}
|
|
99
153
|
export function effortsOf(reasoning) {
|
|
100
154
|
const declared = Array.isArray(reasoning?.efforts)
|
|
101
155
|
? reasoning.efforts.map((effort) => (typeof effort === 'string' ? effort : effort?.id)).filter((id) => typeof id === 'string' && id !== '')
|
package/src/network.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本机在局域网里的地址。
|
|
3
|
+
*
|
|
4
|
+
* 用户开「允许局域网访问」之后,真正要填进别的设备的是**这台机器在局域网里的
|
|
5
|
+
* IP**,不是 `127.0.0.1` —— 后者在手机上指向手机自己。所以设置页要把这个地址
|
|
6
|
+
* 直接算出来给出去,而不是让用户自己去 ipconfig 里找。
|
|
7
|
+
*
|
|
8
|
+
* ## 为什么用 UDP connect 而不是枚举网卡
|
|
9
|
+
*
|
|
10
|
+
* `os.networkInterfaces()` 会把所有网卡都列出来:虚拟网卡、Hyper-V、WSL、
|
|
11
|
+
* Docker、VPN、蓝牙、已断开的适配器……通常有七八个 192.168.x.x,用户没法判断
|
|
12
|
+
* 哪个是本机真正用来上内外网的那个。
|
|
13
|
+
*
|
|
14
|
+
* 连一个外部地址(UDP,不发包)会让系统按路由表选源地址,选出来的那个就是默认
|
|
15
|
+
* 出口网卡 —— 正是同一网段的其他设备能访问到的那个。没有网络时它会失败,那时
|
|
16
|
+
* 退回枚举结果。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { networkInterfaces } from 'node:os'
|
|
20
|
+
import { createSocket } from 'node:dgram'
|
|
21
|
+
|
|
22
|
+
/** 用来「问路」的地址。不需要可达,只要能让系统挑出口路由。 */
|
|
23
|
+
const ROUTE_PROBE_HOST = '223.5.5.5'
|
|
24
|
+
const ROUTE_PROBE_PORT = 80
|
|
25
|
+
const PROBE_TIMEOUT_MS = 300
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 本机局域网地址,按可能性排序。
|
|
29
|
+
*
|
|
30
|
+
* @returns `Promise<string[]>`,第一项最可能是用户要的
|
|
31
|
+
*/
|
|
32
|
+
export async function lanAddresses() {
|
|
33
|
+
const preferred = await probeRouteAddress()
|
|
34
|
+
const enumerated = enumeratePrivateAddresses()
|
|
35
|
+
|
|
36
|
+
/*
|
|
37
|
+
* 探测结果只有在**本身是 RFC1918 私有地址**时才可信。
|
|
38
|
+
*
|
|
39
|
+
* 这台机器上实测:装了代理软件(Clash 之类)时,TUN 网卡会接管默认路由,
|
|
40
|
+
* 探测拿到的是 `198.18.0.1` —— RFC2544 保留段,局域网里的手机根本连不上。
|
|
41
|
+
* 那种情况必须退回枚举结果,否则用户会拿到一个永远连不通的地址。
|
|
42
|
+
*/
|
|
43
|
+
const routes = []
|
|
44
|
+
if (preferred !== undefined && isPrivateAddress(preferred)) routes.push(preferred)
|
|
45
|
+
|
|
46
|
+
for (const address of sortByLikelihood(enumerated)) {
|
|
47
|
+
if (!routes.includes(address)) routes.push(address)
|
|
48
|
+
}
|
|
49
|
+
return routes
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 按「用户大概想要哪个」排序。
|
|
54
|
+
*
|
|
55
|
+
* 家用路由器几乎都是 192.168.0.0/16,公司网络常见 10/8,172.16/12 多虚拟机。
|
|
56
|
+
* 排在前面的先试,用户通常第一项就对。
|
|
57
|
+
*/
|
|
58
|
+
function sortByLikelihood(addresses) {
|
|
59
|
+
const rank = (address) => {
|
|
60
|
+
const [a, b] = address.split('.').map(Number)
|
|
61
|
+
if (a === 192 && b === 168) return 0
|
|
62
|
+
if (a === 10) return 1
|
|
63
|
+
if (a === 172 && b >= 16 && b <= 31) return 2
|
|
64
|
+
if (a === 100 && b >= 64 && b <= 127) return 3
|
|
65
|
+
return 4
|
|
66
|
+
}
|
|
67
|
+
return [...addresses].sort((left, right) => rank(left) - rank(right))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 用一次 UDP connect 让系统告诉我们默认出口是谁。
|
|
72
|
+
* @returns 地址,或 undefined(无网络时)
|
|
73
|
+
*/
|
|
74
|
+
function probeRouteAddress() {
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
let settled = false
|
|
77
|
+
const socket = createSocket('udp4')
|
|
78
|
+
const done = (value) => {
|
|
79
|
+
if (settled) return
|
|
80
|
+
settled = true
|
|
81
|
+
try {
|
|
82
|
+
socket.close()
|
|
83
|
+
} catch {
|
|
84
|
+
/* 已经关了 */
|
|
85
|
+
}
|
|
86
|
+
resolve(value)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* 连不上也不会阻塞(UDP 不握手),只在取不到时兜底超时。 */
|
|
90
|
+
socket.once('error', () => done(undefined))
|
|
91
|
+
const timer = setTimeout(() => done(undefined), PROBE_TIMEOUT_MS)
|
|
92
|
+
timer.unref?.()
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
socket.connect(ROUTE_PROBE_PORT, ROUTE_PROBE_HOST, () => {
|
|
96
|
+
clearTimeout(timer)
|
|
97
|
+
try {
|
|
98
|
+
const address = socket.address()
|
|
99
|
+
done(typeof address?.address === 'string' ? address.address : undefined)
|
|
100
|
+
} catch {
|
|
101
|
+
done(undefined)
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
} catch {
|
|
105
|
+
clearTimeout(timer)
|
|
106
|
+
done(undefined)
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 枚举私有网段地址(IPv4),排除回环与链路本地。 */
|
|
112
|
+
function enumeratePrivateAddresses() {
|
|
113
|
+
const out = []
|
|
114
|
+
let interfaces
|
|
115
|
+
try {
|
|
116
|
+
interfaces = networkInterfaces()
|
|
117
|
+
} catch {
|
|
118
|
+
return out
|
|
119
|
+
}
|
|
120
|
+
for (const entries of Object.values(interfaces)) {
|
|
121
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
122
|
+
/* Node 18+ 才有 family 字符串形式,两者都认。 */
|
|
123
|
+
const isV4 = entry.family === 'IPv4' || entry.family === 4
|
|
124
|
+
if (!isV4) continue
|
|
125
|
+
if (entry.internal === true) continue
|
|
126
|
+
if (typeof entry.address !== 'string') continue
|
|
127
|
+
if (!isPrivateAddress(entry.address)) continue
|
|
128
|
+
out.push(entry.address)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return out
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 是否私有网段(RFC1918 + CGNAT)。 */
|
|
135
|
+
export function isPrivateAddress(value) {
|
|
136
|
+
if (typeof value !== 'string') return false
|
|
137
|
+
const parts = value.split('.').map((piece) => Number(piece))
|
|
138
|
+
if (parts.length !== 4 || parts.some((piece) => !Number.isInteger(piece) || piece < 0 || piece > 255)) return false
|
|
139
|
+
const [a, b] = parts
|
|
140
|
+
if (a === 10) return true
|
|
141
|
+
if (a === 172 && b >= 16 && b <= 31) return true
|
|
142
|
+
if (a === 192 && b === 168) return true
|
|
143
|
+
/* 100.64/10 运营商 NAT —— 也是「同网段可达」的常见情况。 */
|
|
144
|
+
if (a === 100 && b >= 64 && b <= 127) return true
|
|
145
|
+
return false
|
|
146
|
+
}
|
package/src/resolve.js
CHANGED
|
@@ -16,10 +16,25 @@
|
|
|
16
16
|
import { buildCatalog, lookupModel } from './catalog.js'
|
|
17
17
|
|
|
18
18
|
/** provider 路由 → 区域。 */
|
|
19
|
+
/**
|
|
20
|
+
* provider 路由 → 区域。
|
|
21
|
+
*
|
|
22
|
+
* **只认 dsh-connect-workbuddy 自己注册的那两个路由**,不做前缀匹配。
|
|
23
|
+
*
|
|
24
|
+
* 早期这里是 `provider.startsWith('workbuddy')`,结果把 `workbuddy-remote`
|
|
25
|
+
* (另一个插件的路由,模型 id 形如 `cn:deepseek-v4.1-flash`)也当成了本插件的
|
|
26
|
+
* cn 通道 —— 模型清单里因此混进六条带 `cn:` 前缀的假条目,和真正的
|
|
27
|
+
* `deepseek-v4.1-flash` 并列,用户在勾选界面无法分辨。
|
|
28
|
+
*
|
|
29
|
+
* 判据应该是「这个 provider 是不是上游插件注册的」,而不是「名字像不像」。
|
|
30
|
+
*
|
|
31
|
+
* @param provider provider id
|
|
32
|
+
* @returns `cn` | `global` | undefined
|
|
33
|
+
*/
|
|
19
34
|
export function regionOfProvider(provider) {
|
|
20
35
|
if (typeof provider !== 'string') return undefined
|
|
21
|
-
if (provider === 'workbuddy-global'
|
|
22
|
-
if (provider === 'workbuddy'
|
|
36
|
+
if (provider === 'workbuddy-global') return 'global'
|
|
37
|
+
if (provider === 'workbuddy') return 'cn'
|
|
23
38
|
return undefined
|
|
24
39
|
}
|
|
25
40
|
|
package/src/routes.js
CHANGED
|
@@ -19,7 +19,7 @@ import { handleChat } from './openai-chat.js'
|
|
|
19
19
|
import { handleResponses } from './openai-responses.js'
|
|
20
20
|
import { handleMessages } from './anthropic.js'
|
|
21
21
|
import { handleGenerate, parseGeminiPath, geminiCatalog } from './gemini.js'
|
|
22
|
-
import { collectModels, directModelsByRegion, openAiCatalog, anthropicCatalog, catalogForSettings } from './models.js'
|
|
22
|
+
import { collectModels, directModelsByRegion, openAiCatalog, anthropicCatalog, catalogForSettings, liveModelKeys, pruneSelections } from './models.js'
|
|
23
23
|
import {
|
|
24
24
|
readConfig,
|
|
25
25
|
writeConfig,
|
|
@@ -38,7 +38,8 @@ import { allAccounts } from './accounts.js'
|
|
|
38
38
|
import { regionOfProvider, providerOfRegion } from './resolve.js'
|
|
39
39
|
import { describeEndpoints, stripApiPrefix } from './endpoints.js'
|
|
40
40
|
import { allPoolHealth, poolStateMtime } from './health.js'
|
|
41
|
-
import { startListener, describeListenError, isValidPort } from './listener.js'
|
|
41
|
+
import { startListener, describeListenError, isValidPort, hostFor, HOST_ALL } from './listener.js'
|
|
42
|
+
import { lanAddresses } from './network.js'
|
|
42
43
|
|
|
43
44
|
const PREFIX = '/workbuddy-gateway'
|
|
44
45
|
const ADMIN_PREFIX = '/plugins/dsh-connect-workbuddy-gateway'
|
|
@@ -91,6 +92,7 @@ export function registerRoutes(ctx, env) {
|
|
|
91
92
|
*/
|
|
92
93
|
const listener = startListener({
|
|
93
94
|
port: env.config.port,
|
|
95
|
+
host: hostFor(env.config.allowLan),
|
|
94
96
|
handler: (req, res) => dispatchApi(req, res, ctx, env),
|
|
95
97
|
logger: ctx.logger,
|
|
96
98
|
})
|
|
@@ -153,13 +155,16 @@ async function dispatchApi(req, res, ctx, env) {
|
|
|
153
155
|
}
|
|
154
156
|
if (method === 'GET' && route === '/models') {
|
|
155
157
|
/*
|
|
156
|
-
* 只返回这把 key 勾选的模型 —— 用户的勾选就是唯一的事实来源。
|
|
157
|
-
* 重名项的名字已经带上账号后缀(见 src/catalog.js)。
|
|
158
|
-
*
|
|
159
158
|
* 先补一次选:客户端常常比设置页更早被打开,那时默认 key 还没勾过任何
|
|
160
159
|
* 模型,列表会是空的 —— 对用户来说就是「网关没起来」。
|
|
161
160
|
*/
|
|
162
161
|
await env.ensureSeeded?.()
|
|
162
|
+
/*
|
|
163
|
+
* **再刷一次上游目录。** 客户端不一定打开过设置页,而清单必须反映上游此刻
|
|
164
|
+
* 提供的模型 —— 否则上游下架/取消勾选的模型会一直留在这把 key 的清单里。
|
|
165
|
+
* 刷新失败时 `liveModels` 保持上一次的值,不会把清单清空。
|
|
166
|
+
*/
|
|
167
|
+
await refreshLiveModels(env)
|
|
163
168
|
const fresh = authenticate(req.headers, url) ?? keyEntry
|
|
164
169
|
const catalog = keyCatalog(fresh, env)
|
|
165
170
|
sendJson(res, 200, wantsAnthropicShape ? anthropicCatalog(catalog) : openAiCatalog(catalog))
|
|
@@ -228,6 +233,11 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
228
233
|
if (method === 'GET' && path === '/state') {
|
|
229
234
|
/* 设置页打开是最可靠的「provider 肯定就绪」时机:顺手补选。 */
|
|
230
235
|
await env.ensureSeeded?.()
|
|
236
|
+
/*
|
|
237
|
+
* 刷新目录并把失效的勾选清掉 —— 设置页读的是落盘配置,只忽略不清理的话,
|
|
238
|
+
* 画面上仍会列出上游已经没有的模型。
|
|
239
|
+
*/
|
|
240
|
+
if (await refreshLiveModels(env)) pruneStoredSelections(env)
|
|
231
241
|
sendJson(res, 200, await adminState(ctx, env))
|
|
232
242
|
return
|
|
233
243
|
}
|
|
@@ -349,6 +359,34 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
349
359
|
})
|
|
350
360
|
return
|
|
351
361
|
}
|
|
362
|
+
if (method === 'POST' && path === '/config/allow-lan') {
|
|
363
|
+
/*
|
|
364
|
+
* 开关局域网访问。
|
|
365
|
+
*
|
|
366
|
+
* 这是**安全边界的变更**,所以只接受 loopback 调用(本函数入口已有闸门),
|
|
367
|
+
* 并且要求显式传布尔值 —— 不靠「真值即开」,免得一次误会性的 `"false"`
|
|
368
|
+
* 把网关对着整个网段打开。
|
|
369
|
+
*/
|
|
370
|
+
const body = await readJsonBody(req)
|
|
371
|
+
if (typeof body?.allowLan !== 'boolean') {
|
|
372
|
+
sendJson(res, 400, { error: 'allowLan must be true or false' })
|
|
373
|
+
return
|
|
374
|
+
}
|
|
375
|
+
const saved = await savePluginConfig(ctx, env, { allowLan: body.allowLan }, 'allowLan')
|
|
376
|
+
if (saved.ok !== true) {
|
|
377
|
+
sendJson(res, saved.status, saved.error)
|
|
378
|
+
return
|
|
379
|
+
}
|
|
380
|
+
sendJson(res, 200, {
|
|
381
|
+
ok: true,
|
|
382
|
+
allowLan: body.allowLan,
|
|
383
|
+
via: saved.via,
|
|
384
|
+
note: body.allowLan
|
|
385
|
+
? 'the gateway rebinds to all interfaces; other devices still need an API key, and the settings routes stay loopback-only'
|
|
386
|
+
: 'the gateway rebinds to 127.0.0.1; other devices can no longer reach it',
|
|
387
|
+
})
|
|
388
|
+
return
|
|
389
|
+
}
|
|
352
390
|
if (method === 'POST' && path === '/config/port') {
|
|
353
391
|
/*
|
|
354
392
|
* 改监听端口。
|
|
@@ -432,6 +470,20 @@ async function adminState(ctx, env) {
|
|
|
432
470
|
/* 勾选界面的候选:全量目录 × 每个**可用**账号。 */
|
|
433
471
|
const available = await catalogForSettings(env, accounts, usable)
|
|
434
472
|
|
|
473
|
+
/*
|
|
474
|
+
* 局域网访问时要额外给出「别的设备该填什么」。
|
|
475
|
+
*
|
|
476
|
+
* 只有真在监听所有网卡时才去探测地址 —— 没开这个功能就不该多做一次网络
|
|
477
|
+
* 探测,也不用给用户一堆无关的 IP。
|
|
478
|
+
*/
|
|
479
|
+
const allowLan = env.config.allowLan === true
|
|
480
|
+
const lan = allowLan
|
|
481
|
+
? {
|
|
482
|
+
enabled: true,
|
|
483
|
+
addresses: await lanAddresses(),
|
|
484
|
+
}
|
|
485
|
+
: { enabled: false, addresses: [] }
|
|
486
|
+
|
|
435
487
|
return {
|
|
436
488
|
origin,
|
|
437
489
|
/*
|
|
@@ -448,9 +500,23 @@ async function adminState(ctx, env) {
|
|
|
448
500
|
*/
|
|
449
501
|
listener: {
|
|
450
502
|
port: env.config.port,
|
|
503
|
+
host: env.listener?.host ?? hostFor(allowLan),
|
|
451
504
|
listening: env.listener?.listening === true,
|
|
452
505
|
...(env.listener?.error === undefined ? {} : { error: env.listener.error }),
|
|
453
506
|
},
|
|
507
|
+
/*
|
|
508
|
+
* 局域网分享信息。
|
|
509
|
+
*
|
|
510
|
+
* `addresses` 已按「用户大概想要哪个」排序,第一项拿来做示例地址。
|
|
511
|
+
* 开了但一个地址都探测不到时(没连网络),界面要提示用户自己填。
|
|
512
|
+
*/
|
|
513
|
+
lan: {
|
|
514
|
+
...lan,
|
|
515
|
+
/* 别的设备该用的完整地址;没开或没地址时为 null。 */
|
|
516
|
+
endpoints: lan.addresses.length === 0
|
|
517
|
+
? []
|
|
518
|
+
: describeEndpoints(`http://${lan.addresses[0]}:${env.config.port}`).endpoints,
|
|
519
|
+
},
|
|
454
520
|
paths: configPathOf(env),
|
|
455
521
|
providers: env.providers().map((provider) => ({
|
|
456
522
|
id: provider,
|
|
@@ -598,8 +664,64 @@ function isLoopbackAddress(value) {
|
|
|
598
664
|
/* ── 杂项 ─────────────────────────────────────────────────────────────── */
|
|
599
665
|
|
|
600
666
|
/** 某个 key 的模型清单(勾选 → 客户端看到的模型)。 */
|
|
667
|
+
/**
|
|
668
|
+
* 刷新 `env.liveModels`(上游此刻提供的模型键集合)。
|
|
669
|
+
*
|
|
670
|
+
* 失败时**不动**上一次的值:一次上游不可达不等于「上游没有模型」,把它当成后者
|
|
671
|
+
* 会让所有 key 的清单瞬间变空,比显示一份稍旧的清单糟得多。
|
|
672
|
+
*
|
|
673
|
+
* @param env 插件环境
|
|
674
|
+
* @returns 刷新成功时返回 `true`
|
|
675
|
+
*/
|
|
676
|
+
async function refreshLiveModels(env) {
|
|
677
|
+
try {
|
|
678
|
+
const entries = await collectModels(env)
|
|
679
|
+
const pool = entries.length > 0 ? entries : await directModelsByRegion(env)
|
|
680
|
+
if (pool.length === 0) return false
|
|
681
|
+
env.liveModels = liveModelKeys(pool)
|
|
682
|
+
return true
|
|
683
|
+
} catch {
|
|
684
|
+
/* 保持上一次的值 */
|
|
685
|
+
return false
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* 把各 key 上「上游已经没有」的勾选从配置里清掉。
|
|
691
|
+
*
|
|
692
|
+
* 光在投影时忽略不够:设置页读的是落盘配置,脏条目会一直显示在勾选界面里,
|
|
693
|
+
* 用户以为它还生效。这里在确认目录已刷新之后才动手,并且只写回真正变了的情况
|
|
694
|
+
* —— 否则每次读 state 都会重写一次文件。
|
|
695
|
+
*
|
|
696
|
+
* @param env 插件环境
|
|
697
|
+
*/
|
|
698
|
+
function pruneStoredSelections(env) {
|
|
699
|
+
const live = env.liveModels
|
|
700
|
+
if (live === undefined) return
|
|
701
|
+
const config = readConfig()
|
|
702
|
+
let changed = false
|
|
703
|
+
for (const entry of config.keys) {
|
|
704
|
+
const { kept, dropped } = pruneSelections(entry.selections ?? [], live)
|
|
705
|
+
if (dropped.length === 0) continue
|
|
706
|
+
entry.selections = kept
|
|
707
|
+
changed = true
|
|
708
|
+
}
|
|
709
|
+
if (changed) writeConfig(config)
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* 某把 key 对外提供的模型清单。
|
|
714
|
+
*
|
|
715
|
+
* `env.liveModels` 是上一次读到的上游目录(`region\0modelId` 集合)。有它时先把
|
|
716
|
+
* 勾选收窄到「上游仍然提供」的那些——上游取消勾选/下架之后,本插件不该继续对外
|
|
717
|
+
* 宣称提供那个模型。没有它(还没读过目录)时按原样投影,不能因为一次读失败就把
|
|
718
|
+
* 用户的清单清空。
|
|
719
|
+
*/
|
|
601
720
|
function keyCatalog(keyEntry, env) {
|
|
602
|
-
|
|
721
|
+
const selections = keyEntry.selections ?? []
|
|
722
|
+
const live = env.liveModels
|
|
723
|
+
const usable = live === undefined ? selections : pruneSelections(selections, live).kept
|
|
724
|
+
return buildCatalog(usable, publicAccounts(env))
|
|
603
725
|
}
|
|
604
726
|
|
|
605
727
|
/** 本机账号表(不含 token),供清单解析与设置页共用。 */
|