@morgan9668/dsh-llm-gateway 1.1.1 → 1.2.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/README.md +51 -8
- package/docs/DETAIL.md +48 -3
- package/index.js +242 -6
- package/package.json +2 -2
- package/tests/auth.mjs +232 -0
- package/tests/body-limit.mjs +14 -2
- package/tests/image-budget.mjs +104 -0
package/README.md
CHANGED
|
@@ -69,6 +69,7 @@ DSH 里通常同时挂着好几家模型:官方 DeepSeek、腾讯 WorkBuddy、
|
|
|
69
69
|
| 工具配对修复 | 补缺结果的调用(占位正文 `(tool call was interrupted before it returned)`)、删孤儿 tool 结果、把 tool 结果挪到发起它的 assistant 之后 | 上游对不成对调用一律 `11148` |
|
|
70
70
|
| 空段补位 | 空的 text 段填一个空格,整条消息没有块时补一个空格块 | 上游对空 text 段判 `11151 empty content` |
|
|
71
71
|
| 图片落地 | 内联 `data:image/` 与 http(s) 图片摘出来,走 `ctx.attachments.saveImage()`,合成一条 user 消息追加到末尾 | tool 消息不能带图;base64 混在正文里会撑爆上下文 |
|
|
72
|
+
| 图片预算 | 超出路由预算(默认 50 张 / 20 MB base64)时**从最老的开始省略**,换成占位文本 | 否则 DSH 适配器抛 `IMAGE_OFFLOAD_REQUIRED`,而它的会话级恢复链在无状态网关上永远修不好同一份历史 |
|
|
72
73
|
| 调用上游 | `ctx.llm.stream({ provider, model, messages, reasoningEffort, maxTokens, temperature, tools })` | 唯一出口,凭据不经过网关 |
|
|
73
74
|
| 回写 | 流式逐块转 SSE;非流式聚合后一次性返回;usage 按协议换算 | 客户端看到的永远是标准 OpenAI 形状 |
|
|
74
75
|
|
|
@@ -104,26 +105,56 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
|
|
|
104
105
|
config:
|
|
105
106
|
host: '127.0.0.1'
|
|
106
107
|
port: 8392
|
|
107
|
-
apiKey
|
|
108
|
+
# apiKey 留空即可:首次启动会自动生成密钥写入 apiKeyFile
|
|
109
|
+
# (默认 ~/.dsh/dsh-llm-gateway.key,权限 600),日志会打路径。
|
|
108
110
|
```
|
|
109
111
|
|
|
110
112
|
| 字段 | 默认 | 说明 |
|
|
111
113
|
|---|---|---|
|
|
112
114
|
| `host` | `127.0.0.1` | 绑定地址。默认只绑回环,局域网内其它机器访问不到 |
|
|
113
115
|
| `port` | `8392` | 监听端口;非法值静默回退到默认值,不会报错 |
|
|
114
|
-
| `apiKey` | 空 |
|
|
116
|
+
| `apiKey` | 空 | **认证默认开启**。留空时自动生成并落盘;非空时用你给的值 |
|
|
117
|
+
| `apiKeyFile` | `~/.dsh/dsh-llm-gateway.key` | 自动生成密钥的保存位置 |
|
|
118
|
+
| `allowedHosts` | 回环的几种写法(含端口) | 允许的 `Host` 头,挡 DNS rebinding;非白名单回 421 |
|
|
119
|
+
| `allowedOrigins` | 空(只允许不带 Origin 的请求) | 允许的 `Origin`,挡跨站页面调用;不匹配回 403 |
|
|
115
120
|
| `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
|
|
121
|
+
| `maxRequestImages` | `50` | 一条请求允许携带的图片数量上限;超过时省略最老的。与 DSH pi-ai 适配器的默认值对齐 |
|
|
122
|
+
| `maxRequestImageBytes` | `20 MiB` | 一条请求的图片 base64 载荷总量上限;超过时省略最老的。留 5% 余量以吸收适配器重新编码的差异 |
|
|
116
123
|
|
|
117
124
|
> 网关**不导出 Config schema**:所有值从插件行的 `config` 里读,缺字段就用默认值。
|
|
118
125
|
> 因此写错字段名不会报错,只会被忽略——改完记得看日志里的 `listening on http://…`。
|
|
119
126
|
|
|
120
127
|
### 安全边界
|
|
121
128
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
129
|
+
网关默认就是「只有本机、且知道密钥的客户端能用」。三层都默认开:
|
|
130
|
+
|
|
131
|
+
1. **绑定**只到 `127.0.0.1`,外部网络进不来。改 `host` 前先想清楚:这个端点会让调用方
|
|
132
|
+
以你的账号配额随意调用模型。
|
|
133
|
+
2. **认证默认开启**。`apiKey` 留空不等于放行——首次启动会生成一个随机密钥,
|
|
134
|
+
写入 `~/.dsh/dsh-llm-gateway.key`(权限 `600`),路径打在日志里。客户端带上:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
curl -H "Authorization: Bearer $(cat ~/.dsh/dsh-llm-gateway.key)" \
|
|
138
|
+
http://127.0.0.1:8392/v1/models
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
密钥比较用 `timingSafeEqual`,不是会提前返回的字符串比较。
|
|
142
|
+
3. **Host 与 Origin 都校验**。`Host` 只接受回环的几种写法(挡 DNS rebinding:
|
|
143
|
+
攻击者把自己的域名解析到 `127.0.0.1`,浏览器就会当成同源发过来);`Origin` 存在时
|
|
144
|
+
必须在 `allowedOrigins` 里(挡跨站页面调用)。命令行客户端一般不带 `Origin`,不受影响。
|
|
145
|
+
|
|
146
|
+
跨源访问需要放行时,把来源写进 `allowedOrigins`,不要改成放行 `*`:
|
|
147
|
+
|
|
148
|
+
```yaml
|
|
149
|
+
config:
|
|
150
|
+
allowedOrigins:
|
|
151
|
+
- 'http://127.0.0.1:3000'
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
其余说明:
|
|
155
|
+
|
|
156
|
+
- 网关不落盘任何上游凭据;持久副作用只有日志与上面那个密钥文件。
|
|
157
|
+
- 换密钥:删掉 `~/.dsh/dsh-llm-gateway.key` 再重启,会生成新的;客户端记得同步更新。
|
|
127
158
|
|
|
128
159
|
## 端点
|
|
129
160
|
|
|
@@ -328,6 +359,9 @@ wire_api = "responses"
|
|
|
328
359
|
这是有意的取舍——工具截图是刚需,用户贴图请走 DSH 应用内。
|
|
329
360
|
- **所有图片都被集中到最后一条合成 user 消息**,原始出现位置不再保留。
|
|
330
361
|
- **`max-tokens` 截断在 Responses 里报 `completed`**,不报 `incomplete`。
|
|
362
|
+
- **被省略的图片不会自己回来**:图片总量超过 `maxRequestImages` / `maxRequestImageBytes` 时,
|
|
363
|
+
网关从最老的开始换成占位文本 `[image omitted: over the route image budget]`。这是每次请求
|
|
364
|
+
重新计算的确定性结果,不是持久标记——历史变短后,新请求里更老的图仍会被省略。
|
|
331
365
|
- **非流式「半截正文 + 上游失败」按成功返回**:可能是 `stop` 且带半截答案,客户端无法从 `finish_reason` 区分。
|
|
332
366
|
- **同分组内两个 provider 暴露同名 model 时该模型不可达**:精确匹配命中多条即 400,拆分寻址又被分组前缀规则挡住。
|
|
333
367
|
- **流式无心跳帧**:长思考模型可能让连接长时间静默,中间代理可能先断。
|
|
@@ -344,9 +378,11 @@ wire_api = "responses"
|
|
|
344
378
|
## 开发与测试
|
|
345
379
|
|
|
346
380
|
```bash
|
|
347
|
-
npm test #
|
|
381
|
+
npm test # 等价于下面四条
|
|
348
382
|
node tests/stream-failure.mjs
|
|
349
383
|
node tests/body-limit.mjs
|
|
384
|
+
node tests/image-budget.mjs
|
|
385
|
+
node tests/auth.mjs
|
|
350
386
|
```
|
|
351
387
|
|
|
352
388
|
`stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
|
|
@@ -356,6 +392,13 @@ node tests/body-limit.mjs
|
|
|
356
392
|
`x-should-retry: false` 与 `retry-after: 0`;`content-length` 缺失(分块上传)时仍按实际字节拦截;
|
|
357
393
|
上限可由 `maxBodyBytes` 调整;默认值容得下几十 MB 的带图历史。
|
|
358
394
|
|
|
395
|
+
`image-budget.mjs` 四个用例覆盖路由图片预算:数量超限时省略最老的并保留最新的;
|
|
396
|
+
base64 字节超限时同样触发省略;未超限时一张不动;省略后确实落在预算内。
|
|
397
|
+
|
|
398
|
+
`auth.mjs` 十个用例覆盖认证与来源限制:无 token / 错误 token 回 401;非白名单 Host 回 421;
|
|
399
|
+
Origin 不在白名单回 403;不带 Origin 的命令行客户端不受影响;未配置 `apiKey` 时自动生成
|
|
400
|
+
密钥并以 `600` 权限落盘;显式配置的密钥优先。
|
|
401
|
+
|
|
359
402
|
未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
|
|
360
403
|
认证。
|
|
361
404
|
|
package/docs/DETAIL.md
CHANGED
|
@@ -24,9 +24,26 @@ a Config schema, so all values are read from the plugin config with defaults.
|
|
|
24
24
|
Unknown keys are ignored silently. `maxBodyBytes` defaults to 256 MiB: Codex resends
|
|
25
25
|
the whole history every turn, and image-heavy conversations get large quickly.
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
## Authentication and origin checks
|
|
28
|
+
|
|
29
|
+
Authentication is on by default. Leaving `apiKey` empty does **not** mean "no
|
|
30
|
+
auth": on first start the gateway generates a random key and writes it to
|
|
31
|
+
`apiKeyFile` (default `~/.dsh/dsh-llm-gateway.key`, mode `600`), logging the path.
|
|
32
|
+
Clients send `Authorization: Bearer <that key>`; the comparison uses
|
|
33
|
+
`timingSafeEqual`, not an early-returning string compare.
|
|
34
|
+
|
|
35
|
+
Two more checks run before routing:
|
|
36
|
+
|
|
37
|
+
- **Host** must be in `allowedHosts`, which defaults to the loopback spellings
|
|
38
|
+
with the configured port. A mismatch returns 421. This blocks DNS rebinding:
|
|
39
|
+
an attacker's domain resolving to `127.0.0.1` makes the browser treat the
|
|
40
|
+
request as same-origin.
|
|
41
|
+
- **Origin**, when present, must be in `allowedOrigins` (403 otherwise). Command
|
|
42
|
+
line clients and SDKs normally send no Origin, so they are unaffected. An empty
|
|
43
|
+
`allowedOrigins` means "no cross-origin callers" rather than "allow all".
|
|
44
|
+
|
|
45
|
+
The gateway sets no CORS headers and has no `OPTIONS` handler; to permit a
|
|
46
|
+
same-machine page, list it in `allowedOrigins` rather than loosening this.
|
|
30
47
|
|
|
31
48
|
## Grouped model ids
|
|
32
49
|
|
|
@@ -93,6 +110,25 @@ become empty. Limits: 8 MB per image, `png` / `jpeg` / `webp` / `gif`, and a
|
|
|
93
110
|
Images inside a Responses `message` item are reduced to placeholder text; only
|
|
94
111
|
`function_call_output` images are materialised as real attachments.
|
|
95
112
|
|
|
113
|
+
## Image budget
|
|
114
|
+
|
|
115
|
+
DSH's pi-ai adapter caps one request at `maxRequestImages` (50) image occurrences and
|
|
116
|
+
`maxRequestImageBytes` (20 MiB) of accumulated base64. Over that it throws
|
|
117
|
+
`IMAGE_OFFLOAD_REQUIRED`, and `dsh-compaction-image-offload` recovers by recording an
|
|
118
|
+
`image/offload` event in the **session** and retrying. That recovery cannot work through
|
|
119
|
+
the gateway: every turn is a fresh HTTP request and the image blocks are rebuilt from the
|
|
120
|
+
wire history, so the same oversized request is reconstructed every time and the client
|
|
121
|
+
sees `stream disconnected before completion: ... N more oldest occurrence(s) must be
|
|
122
|
+
offloaded` on a loop.
|
|
123
|
+
|
|
124
|
+
The gateway therefore applies the same budget itself, deterministically within one
|
|
125
|
+
request: the oldest occurrences become `[image omitted: over the route image budget]`
|
|
126
|
+
until the request fits. Both limits are configurable (`maxRequestImages`,
|
|
127
|
+
`maxRequestImageBytes`), and the byte check keeps a 5% margin because the adapter
|
|
128
|
+
re-encodes each image to its own target before measuring. Omissions are recomputed per
|
|
129
|
+
request, not persisted, so an image that was omitted stays omitted only while the
|
|
130
|
+
history remains oversized.
|
|
131
|
+
|
|
96
132
|
## Errors
|
|
97
133
|
|
|
98
134
|
Upstream failures map to a status plus one actionable sentence:
|
|
@@ -187,5 +223,14 @@ request-body limit: an oversized body must return 413 with `x-should-retry: fals
|
|
|
187
223
|
and `retry-after: 0`; a missing `content-length` (chunked upload) is still counted;
|
|
188
224
|
`maxBodyBytes` is honoured; and the default accepts tens of megabytes.
|
|
189
225
|
|
|
226
|
+
`node tests/image-budget.mjs` runs four cases for the route image budget: oldest
|
|
227
|
+
occurrences are omitted first while the newest are kept; a byte overflow also triggers
|
|
228
|
+
omission; nothing is touched below the budget; and the result really fits.
|
|
229
|
+
|
|
230
|
+
`node tests/auth.mjs` runs ten cases for authentication and origin checks: missing
|
|
231
|
+
or wrong token returns 401; a non-allowlisted Host returns 421; an origin outside
|
|
232
|
+
`allowedOrigins` returns 403; clients without an Origin header still work; leaving
|
|
233
|
+
`apiKey` empty generates a key file with mode 600; and an explicit key wins.
|
|
234
|
+
|
|
190
235
|
Conversion, pairing repair, slots, routing, attachments and the status map are not
|
|
191
236
|
covered.
|
package/index.js
CHANGED
|
@@ -9,8 +9,10 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import http from 'node:http';
|
|
12
|
-
import { appendFileSync } from 'node:fs';
|
|
13
|
-
import { randomUUID } from 'node:crypto';
|
|
12
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
14
|
+
import { homedir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
14
16
|
|
|
15
17
|
export const name = 'dsh-llm-gateway';
|
|
16
18
|
// `attachments` 用于把工具返回的内联图片落成真实附件,让模型能看到图;
|
|
@@ -20,10 +22,23 @@ export const inject = ['llm', 'attachments'];
|
|
|
20
22
|
const DEFAULTS = {
|
|
21
23
|
host: '127.0.0.1',
|
|
22
24
|
port: 8392,
|
|
25
|
+
// 认证默认**开启**。空串不再表示「不鉴权」,而是「用自动生成的密钥」——
|
|
26
|
+
// 见 resolveApiKey。空串放行意味着本机任何进程都能白用你已配好的模型额度,
|
|
27
|
+
// 这是市场审核明确要求整改的一条。
|
|
23
28
|
apiKey: '',
|
|
29
|
+
// 自动生成的密钥落盘位置。首次启动写入,之后复用。
|
|
30
|
+
apiKeyFile: '',
|
|
31
|
+
// 允许的 Host 头。默认只接受回环地址的几种写法,挡掉 DNS rebinding。
|
|
32
|
+
allowedHosts: [],
|
|
33
|
+
// 非空时要求 Origin 头(若存在)落在这个列表里,挡掉浏览器跨站调用。
|
|
34
|
+
allowedOrigins: [],
|
|
24
35
|
// 请求体上限。Codex 每轮都会把整段历史重发一遍,带图的会话里 base64 图片
|
|
25
36
|
// 会把这一个请求推到几十 MB —— 默认值必须容得下正常的多图历史。
|
|
26
37
|
maxBodyBytes: 256 * 1024 * 1024,
|
|
38
|
+
// 路由图片预算:与 DSH pi-ai 适配器的默认值对齐,略保守一点。超过时网关自己
|
|
39
|
+
// 省略最老的图片,而不是让适配器抛 IMAGE_OFFLOAD_REQUIRED(见 applyImageBudget)。
|
|
40
|
+
maxRequestImages: 50,
|
|
41
|
+
maxRequestImageBytes: 20 * 1024 * 1024,
|
|
27
42
|
};
|
|
28
43
|
const CACHE_MS = 10_000;
|
|
29
44
|
const GROUP_PREFIXES = new Set(['deepseek', 'buddy', 'free']);
|
|
@@ -122,11 +137,66 @@ function normalizeConfig(raw) {
|
|
|
122
137
|
if (typeof raw.host === 'string' && raw.host !== '') config.host = raw.host;
|
|
123
138
|
if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
|
|
124
139
|
if (typeof raw.apiKey === 'string') config.apiKey = raw.apiKey;
|
|
140
|
+
if (typeof raw.apiKeyFile === 'string') config.apiKeyFile = raw.apiKeyFile;
|
|
141
|
+
if (Array.isArray(raw.allowedHosts)) {
|
|
142
|
+
config.allowedHosts = raw.allowedHosts.filter((h) => typeof h === 'string' && h !== '');
|
|
143
|
+
}
|
|
144
|
+
if (Array.isArray(raw.allowedOrigins)) {
|
|
145
|
+
config.allowedOrigins = raw.allowedOrigins.filter((o) => typeof o === 'string' && o !== '');
|
|
146
|
+
}
|
|
125
147
|
if (Number.isInteger(raw.maxBodyBytes) && raw.maxBodyBytes > 0) config.maxBodyBytes = raw.maxBodyBytes;
|
|
148
|
+
if (Number.isInteger(raw.maxRequestImages) && raw.maxRequestImages > 0) config.maxRequestImages = raw.maxRequestImages;
|
|
149
|
+
if (Number.isInteger(raw.maxRequestImageBytes) && raw.maxRequestImageBytes > 0) config.maxRequestImageBytes = raw.maxRequestImageBytes;
|
|
126
150
|
}
|
|
127
151
|
return config;
|
|
128
152
|
}
|
|
129
153
|
|
|
154
|
+
/** 回环地址补上端口后的几种合法 Host 写法。 */
|
|
155
|
+
function defaultAllowedHosts(host, port) {
|
|
156
|
+
const names = ['127.0.0.1', 'localhost', '[::1]'];
|
|
157
|
+
const hosts = [];
|
|
158
|
+
for (const name of names) {
|
|
159
|
+
hosts.push(`${name}:${port}`);
|
|
160
|
+
}
|
|
161
|
+
// 少数客户端省掉默认端口,这里对 80 也留一条口子(实际端口另有条目)。
|
|
162
|
+
if (port !== 80) hosts.push(...names.map((name) => `${name}:80`));
|
|
163
|
+
void host;
|
|
164
|
+
return hosts;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 解析出这次真正用于校验的 API key。
|
|
169
|
+
*
|
|
170
|
+
* 规则:
|
|
171
|
+
* - `apiKey` 非空 → 用它。用户显式配置的优先。
|
|
172
|
+
* - `apiKey` 为空 → 用 `apiKeyFile` 里保存的密钥;文件不存在就生成一个 32 字节
|
|
173
|
+
* 随机串并以 600 权限写入。这样「默认安全」不会变成「默认不可用」:密钥就在
|
|
174
|
+
* 本机那个文件里,客户端照抄即可,不需要用户每次手填。
|
|
175
|
+
*
|
|
176
|
+
* 返回 `{ key, generated }`,`generated` 为 true 时调用方应把路径打到日志里。
|
|
177
|
+
*/
|
|
178
|
+
function resolveApiKey(config) {
|
|
179
|
+
if (config.apiKey !== '') return { key: config.apiKey, filePath: undefined, generated: false };
|
|
180
|
+
const filePath = config.apiKeyFile !== ''
|
|
181
|
+
? config.apiKeyFile
|
|
182
|
+
: join(homedir(), '.dsh', 'dsh-llm-gateway.key');
|
|
183
|
+
try {
|
|
184
|
+
const existing = readFileSync(filePath, 'utf8').trim();
|
|
185
|
+
if (existing !== '') return { key: existing, filePath, generated: false };
|
|
186
|
+
} catch {
|
|
187
|
+
// 文件不存在或读不到:生成新的。
|
|
188
|
+
}
|
|
189
|
+
const key = `sk-dsh-${randomBytes(24).toString('base64url')}`;
|
|
190
|
+
try {
|
|
191
|
+
mkdirSync(join(filePath, '..'), { recursive: true, mode: 0o700 });
|
|
192
|
+
writeFileSync(filePath, `${key}\n`, { mode: 0o600 });
|
|
193
|
+
} catch {
|
|
194
|
+
// 写不进去也要能跑:密钥留在内存里,退化为「本次进程有效」。
|
|
195
|
+
return { key, filePath, generated: true };
|
|
196
|
+
}
|
|
197
|
+
return { key, filePath, generated: true };
|
|
198
|
+
}
|
|
199
|
+
|
|
130
200
|
/** 字节数 → 便于读的 MB/KB,用于日志。 */
|
|
131
201
|
function formatBytes(bytes) {
|
|
132
202
|
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
|
@@ -617,6 +687,80 @@ export function chatMessagesToDsh(rawMessages, options = {}) {
|
|
|
617
687
|
*
|
|
618
688
|
* 没有 attachments 服务时,退化为占位文本——模型看不到图,但请求不会炸。
|
|
619
689
|
*/
|
|
690
|
+
const IMAGE_OFFLOAD_PLACEHOLDER = '[image omitted: over the route image budget]';
|
|
691
|
+
const DEFAULT_MAX_REQUEST_IMAGES = 50;
|
|
692
|
+
const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
|
|
693
|
+
/** pi-ai 适配器的单张请求图片编码字节目标(requestImageMaxBytes 的默认值)。 */
|
|
694
|
+
const REQUEST_IMAGE_TARGET_BYTES = 1024 * 1024;
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* 按 DSH 的路由预算省略最老的图片。
|
|
698
|
+
*
|
|
699
|
+
* DSH 的 pi-ai 适配器对一条请求有硬预算:最多 `maxRequestImages`(默认 50)张
|
|
700
|
+
* 图片出现,base64 载荷合计不超过 `maxRequestImageBytes`(默认 20 MB)。超了它
|
|
701
|
+
* 抛 `IMAGE_OFFLOAD_REQUIRED`,由 `dsh-compaction-image-offload` 在会话里记一条
|
|
702
|
+
* `image/offload` 事件、把最老的若干位置标记成省略,然后重试。
|
|
703
|
+
*
|
|
704
|
+
* 那条恢复链**只在 DSH 自己的会话里成立**:它靠会话事件记住哪个位置被省略过。
|
|
705
|
+
* 走网关时每一轮都是新的 HTTP 请求,网关每轮原地重建图片块,省略标记无处安放,
|
|
706
|
+
* 于是重试还是同样超限——表现就是 Codex 里反复出现
|
|
707
|
+
* 「stream disconnected before completion: ... N more oldest occurrence(s) must be offloaded」。
|
|
708
|
+
*
|
|
709
|
+
* 所以网关自己按**请求内**的确定性规则做同一件事:从最老的图片开始省略,直到
|
|
710
|
+
* 装进预算。同一份历史每次都会被省略成同一组图片,不依赖跨请求状态。
|
|
711
|
+
*
|
|
712
|
+
* 返回保留的图片下标集合(省略掉的会换成占位文本)。
|
|
713
|
+
*/
|
|
714
|
+
/**
|
|
715
|
+
* 把请求里的图片压进路由预算,办法是**从最老的开始省略**。
|
|
716
|
+
*
|
|
717
|
+
* 预算按适配器的口径算:每张图按 base64 长度计入(`ceil(bytes/3)*4`),
|
|
718
|
+
* 数量与总字节两条都要满足。留 5% 余量,因为适配器算的是它自己重新编码后的
|
|
719
|
+
* base64,和这里的估计不会逐字节相同。
|
|
720
|
+
*
|
|
721
|
+
* 直接在传入的消息数组上原地改写:被省略的位置换成占位文本。
|
|
722
|
+
*/
|
|
723
|
+
export function applyImageBudget(messages, limit) {
|
|
724
|
+
const maxImages = Number.isInteger(limit?.maxImages) && limit.maxImages > 0
|
|
725
|
+
? limit.maxImages
|
|
726
|
+
: DEFAULT_MAX_REQUEST_IMAGES;
|
|
727
|
+
const maxBytes = Number.isInteger(limit?.maxBytes) && limit.maxBytes > 0
|
|
728
|
+
? limit.maxBytes
|
|
729
|
+
: DEFAULT_MAX_REQUEST_IMAGE_BYTES;
|
|
730
|
+
const bytesBudget = Math.floor(maxBytes * 0.95);
|
|
731
|
+
|
|
732
|
+
// 按模型请求顺序收集每个图片出现位置。
|
|
733
|
+
const occurrences = [];
|
|
734
|
+
for (const message of messages) {
|
|
735
|
+
if (!Array.isArray(message.content)) continue;
|
|
736
|
+
for (let index = 0; index < message.content.length; index += 1) {
|
|
737
|
+
const block = message.content[index];
|
|
738
|
+
if (block?.type !== 'image') continue;
|
|
739
|
+
// 适配器发出的不是上传时的原始字节,而是它按路由目标(默认 1 MiB/张)
|
|
740
|
+
// 重新编码后的结果。用两者的较小值估计,避免高估后多省略本来装得下的图。
|
|
741
|
+
const uploaded = Number(block.attachment?.bytes ?? 0);
|
|
742
|
+
const bytes = Math.min(uploaded, REQUEST_IMAGE_TARGET_BYTES);
|
|
743
|
+
occurrences.push({ message, index, base64: Math.ceil(bytes / 3) * 4 });
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (occurrences.length === 0) return 0;
|
|
747
|
+
|
|
748
|
+
let total = occurrences.reduce((sum, o) => sum + o.base64, 0);
|
|
749
|
+
let count = occurrences.length;
|
|
750
|
+
let omitted = 0;
|
|
751
|
+
for (const occurrence of occurrences) {
|
|
752
|
+
if (count <= maxImages && total <= bytesBudget) break;
|
|
753
|
+
total -= occurrence.base64;
|
|
754
|
+
count -= 1;
|
|
755
|
+
occurrence.message.content[occurrence.index] = {
|
|
756
|
+
type: 'text',
|
|
757
|
+
text: IMAGE_OFFLOAD_PLACEHOLDER,
|
|
758
|
+
};
|
|
759
|
+
omitted += 1;
|
|
760
|
+
}
|
|
761
|
+
return omitted;
|
|
762
|
+
}
|
|
763
|
+
|
|
620
764
|
async function materializeImages(chatMessages, options = {}) {
|
|
621
765
|
const attachments = options.attachments;
|
|
622
766
|
/** 待发的图片:{ mediaType, bytes } */
|
|
@@ -692,6 +836,7 @@ async function materializeImages(chatMessages, options = {}) {
|
|
|
692
836
|
|
|
693
837
|
// 把收集到的图落成附件。
|
|
694
838
|
const blocks = [];
|
|
839
|
+
const lengths = [];
|
|
695
840
|
for (const img of pending) {
|
|
696
841
|
try {
|
|
697
842
|
const ref = await attachments.saveImage({
|
|
@@ -699,10 +844,14 @@ async function materializeImages(chatMessages, options = {}) {
|
|
|
699
844
|
mediaType: img.mediaType,
|
|
700
845
|
name: `gateway-image-${Date.now()}`,
|
|
701
846
|
});
|
|
847
|
+
// 记下这张图上传时的字节数:预算按 base64 载荷算,而保存后的 ref.bytes
|
|
848
|
+
// 是规范化(可能被缩过)之后的值,两者不能混用。
|
|
702
849
|
blocks.push({ type: 'image', attachment: ref });
|
|
850
|
+
lengths.push(img.bytes.length);
|
|
703
851
|
} catch (error) {
|
|
704
852
|
// 单张图存不进去不该整轮失败:换成占位文本继续。
|
|
705
853
|
blocks.push({ type: 'text', text: imagePlaceholder(undefined, '图片') });
|
|
854
|
+
lengths.push(0);
|
|
706
855
|
void error;
|
|
707
856
|
}
|
|
708
857
|
}
|
|
@@ -713,6 +862,19 @@ async function materializeImages(chatMessages, options = {}) {
|
|
|
713
862
|
content: [{ type: 'text', text: TOOL_IMAGE_PLACEHOLDER }, ...blocks],
|
|
714
863
|
source: { kind: 'user' },
|
|
715
864
|
});
|
|
865
|
+
|
|
866
|
+
// 省略(而不是拒绝)超出路由图片预算的最老若干张。见 applyImageBudget:
|
|
867
|
+
// 不这么做时,DSH 的适配器会抛 IMAGE_OFFLOAD_REQUIRED,而它的会话级恢复链在
|
|
868
|
+
// 网关这条无状态路径上永远修不好同一个历史。
|
|
869
|
+
const omitted = applyImageBudget(out, {
|
|
870
|
+
maxImages: options.maxRequestImages,
|
|
871
|
+
maxBytes: options.maxRequestImageBytes,
|
|
872
|
+
});
|
|
873
|
+
if (omitted > 0 && typeof options.log === 'function') {
|
|
874
|
+
options.log(
|
|
875
|
+
`image budget: omitted ${omitted} oldest image(s) to fit the route budget; ${blocks.length - omitted} sent`,
|
|
876
|
+
);
|
|
877
|
+
}
|
|
716
878
|
return out;
|
|
717
879
|
}
|
|
718
880
|
|
|
@@ -1514,6 +1676,19 @@ export function apply(ctx, rawConfig) {
|
|
|
1514
1676
|
} catch { /* 日志失败不影响主流程 */ }
|
|
1515
1677
|
};
|
|
1516
1678
|
|
|
1679
|
+
// 认证与来源限制。默认开启:密钥自动生成到 apiKeyFile,Host 只接受回环。
|
|
1680
|
+
const { key: apiKey, filePath: apiKeyFile, generated: apiKeyGenerated } = resolveApiKey(config);
|
|
1681
|
+
const allowedHosts = (config.allowedHosts.length > 0
|
|
1682
|
+
? config.allowedHosts
|
|
1683
|
+
: defaultAllowedHosts(config.host, config.port)
|
|
1684
|
+
).map((h) => h.toLowerCase());
|
|
1685
|
+
const allowedOrigins = config.allowedOrigins.map((o) => o.toLowerCase());
|
|
1686
|
+
if (apiKeyGenerated) {
|
|
1687
|
+
log(`已生成新的 API 密钥并写入 ${apiKeyFile ?? '(仅本次进程)'};客户端请用 Authorization: Bearer <该文件内容>`);
|
|
1688
|
+
}
|
|
1689
|
+
log(`认证已启用;允许的 Host:${allowedHosts.join(', ')}`);
|
|
1690
|
+
if (allowedOrigins.length > 0) log(`允许的 Origin:${allowedOrigins.join(', ')}`);
|
|
1691
|
+
|
|
1517
1692
|
let cache = [];
|
|
1518
1693
|
let cacheAt = 0;
|
|
1519
1694
|
let inflight = null;
|
|
@@ -1679,9 +1854,44 @@ export function apply(ctx, rawConfig) {
|
|
|
1679
1854
|
return undefined;
|
|
1680
1855
|
}
|
|
1681
1856
|
|
|
1857
|
+
/**
|
|
1858
|
+
* 校验 bearer token。
|
|
1859
|
+
*
|
|
1860
|
+
* 用 `timingSafeEqual` 而不是 `===`:字符串比较会在第一个不同的字节提前返回,
|
|
1861
|
+
* 远程可达的端点上那是可测量的时间侧信道。
|
|
1862
|
+
*/
|
|
1682
1863
|
function authorized(request) {
|
|
1683
|
-
|
|
1684
|
-
|
|
1864
|
+
const header = request.headers.get('authorization') ?? '';
|
|
1865
|
+
const prefix = 'Bearer ';
|
|
1866
|
+
if (!header.startsWith(prefix)) return false;
|
|
1867
|
+
const presented = header.slice(prefix.length);
|
|
1868
|
+
const expected = apiKey;
|
|
1869
|
+
const a = Buffer.from(presented, 'utf8');
|
|
1870
|
+
const b = Buffer.from(expected, 'utf8');
|
|
1871
|
+
if (a.length !== b.length) return false;
|
|
1872
|
+
return timingSafeEqual(a, b);
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/**
|
|
1876
|
+
* 校验 Host 与 Origin。
|
|
1877
|
+
*
|
|
1878
|
+
* Host 挡 DNS rebinding:攻击者把自己的域名解析到 127.0.0.1,浏览器就会把
|
|
1879
|
+
* 请求当成同源发过来,Host 是攻击者的域名。只接受回环的几种写法即可挡住。
|
|
1880
|
+
*
|
|
1881
|
+
* Origin 挡跨站页面调用:浏览器会带上 Origin,命令行工具一般不带,所以
|
|
1882
|
+
* 只校验「存在且不在白名单」的情况。
|
|
1883
|
+
*/
|
|
1884
|
+
function hostAllowed(request) {
|
|
1885
|
+
const host = (request.headers.get('host') ?? '').toLowerCase();
|
|
1886
|
+
if (host === '') return false;
|
|
1887
|
+
return allowedHosts.includes(host);
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
function originAllowed(request) {
|
|
1891
|
+
const origin = request.headers.get('origin');
|
|
1892
|
+
if (origin === null || origin === '') return true;
|
|
1893
|
+
if (allowedOrigins.length === 0) return false;
|
|
1894
|
+
return allowedOrigins.includes(origin.toLowerCase());
|
|
1685
1895
|
}
|
|
1686
1896
|
|
|
1687
1897
|
async function handle(request) {
|
|
@@ -1689,6 +1899,22 @@ export function apply(ctx, rawConfig) {
|
|
|
1689
1899
|
const url = new URL(request.url);
|
|
1690
1900
|
const path = url.pathname.replace(/\/+$/u, '') || '/';
|
|
1691
1901
|
|
|
1902
|
+
if (!hostAllowed(request)) {
|
|
1903
|
+
return json({
|
|
1904
|
+
error: {
|
|
1905
|
+
message: `host "${request.headers.get('host') ?? ''}" is not allowed; set allowedHosts to permit it`,
|
|
1906
|
+
type: 'invalid_request_error',
|
|
1907
|
+
},
|
|
1908
|
+
}, 421);
|
|
1909
|
+
}
|
|
1910
|
+
if (!originAllowed(request)) {
|
|
1911
|
+
return json({
|
|
1912
|
+
error: {
|
|
1913
|
+
message: `origin "${request.headers.get('origin') ?? ''}" is not allowed; set allowedOrigins to permit it`,
|
|
1914
|
+
type: 'invalid_request_error',
|
|
1915
|
+
},
|
|
1916
|
+
}, 403);
|
|
1917
|
+
}
|
|
1692
1918
|
if (!authorized(request)) {
|
|
1693
1919
|
return json({ error: { message: 'missing or invalid bearer token', type: 'authentication_error' } }, 401);
|
|
1694
1920
|
}
|
|
@@ -1721,7 +1947,12 @@ export function apply(ctx, rawConfig) {
|
|
|
1721
1947
|
if (request.method === 'POST' && path === '/v1/chat/completions') {
|
|
1722
1948
|
const body = await readJson(request, config.maxBodyBytes);
|
|
1723
1949
|
let messages = chatMessagesToDsh(body.messages, { provider: 'gateway', model: body.model });
|
|
1724
|
-
messages = await materializeImages(messages, {
|
|
1950
|
+
messages = await materializeImages(messages, {
|
|
1951
|
+
attachments: attachmentsService,
|
|
1952
|
+
maxRequestImages: config.maxRequestImages,
|
|
1953
|
+
maxRequestImageBytes: config.maxRequestImageBytes,
|
|
1954
|
+
log,
|
|
1955
|
+
});
|
|
1725
1956
|
if (messages.length === 0) throw new HttpError(400, 'messages must not be empty');
|
|
1726
1957
|
const { route, options } = await buildOptions(body, messages, requestedEffortOf(body));
|
|
1727
1958
|
|
|
@@ -1774,7 +2005,12 @@ export function apply(ctx, rawConfig) {
|
|
|
1774
2005
|
if (request.method === 'POST' && path === '/v1/responses') {
|
|
1775
2006
|
const body = await readJson(request, config.maxBodyBytes);
|
|
1776
2007
|
let messages = responsesToDsh(body, { provider: 'gateway', model: body.model });
|
|
1777
|
-
messages = await materializeImages(messages, {
|
|
2008
|
+
messages = await materializeImages(messages, {
|
|
2009
|
+
attachments: attachmentsService,
|
|
2010
|
+
maxRequestImages: config.maxRequestImages,
|
|
2011
|
+
maxRequestImageBytes: config.maxRequestImageBytes,
|
|
2012
|
+
log,
|
|
2013
|
+
});
|
|
1778
2014
|
if (messages.length === 0) throw new HttpError(400, 'input must not be empty');
|
|
1779
2015
|
const bodyForOptions = {
|
|
1780
2016
|
...body,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morgan9668/dsh-llm-gateway",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local OpenAI-compatible gateway that exposes every model registered on the DSH llm service (DeepSeek, WorkBuddy, our-free-model) so external clients such as Codex can use them.",
|
|
6
6
|
"author": "chenzhao",
|
|
@@ -48,6 +48,6 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"scripts": {
|
|
51
|
-
"test": "node tests/stream-failure.mjs && node tests/body-limit.mjs"
|
|
51
|
+
"test": "node tests/stream-failure.mjs && node tests/body-limit.mjs && node tests/image-budget.mjs && node tests/auth.mjs"
|
|
52
52
|
}
|
|
53
53
|
}
|
package/tests/auth.mjs
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 认证与来源限制的回归测试。
|
|
4
|
+
*
|
|
5
|
+
* 背景:最初 `apiKey` 默认空串等于「不鉴权」,本机任何进程都能白用你已配好的
|
|
6
|
+
* 模型额度。市场审核明确要求整改:默认开启认证、限制 Host 与来源。
|
|
7
|
+
*
|
|
8
|
+
* 现在的行为:
|
|
9
|
+
* - `apiKey` 未配置时不放行,而是自动生成密钥写入 `apiKeyFile`(600 权限);
|
|
10
|
+
* - 只接受白名单里的 Host,挡 DNS rebinding;
|
|
11
|
+
* - Origin 存在时必须在 `allowedOrigins` 里,挡跨站页面调用;
|
|
12
|
+
* - 密钥比较用 timingSafeEqual,不走会提前返回的字符串比较。
|
|
13
|
+
*
|
|
14
|
+
* 这些断言覆盖上述四条,以及「显式配置的密钥优先于自动生成」。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import assert from 'node:assert/strict';
|
|
18
|
+
import http from 'node:http';
|
|
19
|
+
import net from 'node:net';
|
|
20
|
+
import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
21
|
+
import { tmpdir } from 'node:os';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
|
|
24
|
+
import { apply } from '../index.js';
|
|
25
|
+
|
|
26
|
+
let failures = 0;
|
|
27
|
+
let passed = 0;
|
|
28
|
+
const tests = [];
|
|
29
|
+
function test(name, fn) {
|
|
30
|
+
tests.push({ name, fn });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function freePort() {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
const srv = net.createServer();
|
|
36
|
+
srv.once('error', reject);
|
|
37
|
+
srv.listen(0, '127.0.0.1', () => {
|
|
38
|
+
const { port } = srv.address();
|
|
39
|
+
srv.close(() => resolve(port));
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function fakeCtx() {
|
|
45
|
+
const cleanups = [];
|
|
46
|
+
return {
|
|
47
|
+
llm: {
|
|
48
|
+
listProviders: () => [],
|
|
49
|
+
listModels: async () => [],
|
|
50
|
+
resolveModelInfo: async () => ({}),
|
|
51
|
+
stream: () => (async function* empty() {})(),
|
|
52
|
+
},
|
|
53
|
+
get: () => undefined,
|
|
54
|
+
effect: (fn) => {
|
|
55
|
+
cleanups.push(fn());
|
|
56
|
+
},
|
|
57
|
+
dispose: () => {
|
|
58
|
+
for (const cleanup of cleanups) {
|
|
59
|
+
try {
|
|
60
|
+
cleanup();
|
|
61
|
+
} catch {
|
|
62
|
+
/* already closed */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function withGateway(config, run) {
|
|
70
|
+
const port = await freePort();
|
|
71
|
+
const ctx = fakeCtx();
|
|
72
|
+
apply(ctx, { host: '127.0.0.1', port, ...config });
|
|
73
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
74
|
+
try {
|
|
75
|
+
await run({ port });
|
|
76
|
+
} finally {
|
|
77
|
+
ctx.dispose();
|
|
78
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function request(port, { path = '/healthz', headers = {}, method = 'GET' } = {}) {
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
const req = http.request({ host: '127.0.0.1', port, path, method, headers }, (res) => {
|
|
85
|
+
const chunks = [];
|
|
86
|
+
res.on('data', (c) => chunks.push(c));
|
|
87
|
+
res.on('end', () =>
|
|
88
|
+
resolve({ status: res.statusCode, text: Buffer.concat(chunks).toString('utf8') }),
|
|
89
|
+
);
|
|
90
|
+
});
|
|
91
|
+
req.on('error', reject);
|
|
92
|
+
req.end();
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
test('未带认证头时回 401', async () => {
|
|
97
|
+
await withGateway({ apiKey: 'sk-test' }, async ({ port }) => {
|
|
98
|
+
const res = await request(port);
|
|
99
|
+
assert.equal(res.status, 401);
|
|
100
|
+
assert.match(res.text, /bearer token/);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('错误 token 回 401', async () => {
|
|
105
|
+
await withGateway({ apiKey: 'sk-test' }, async ({ port }) => {
|
|
106
|
+
const res = await request(port, { headers: { authorization: 'Bearer sk-wrong' } });
|
|
107
|
+
assert.equal(res.status, 401);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('正确 token 才放行', async () => {
|
|
112
|
+
await withGateway({ apiKey: 'sk-test' }, async ({ port }) => {
|
|
113
|
+
const res = await request(port, { headers: { authorization: 'Bearer sk-test' } });
|
|
114
|
+
assert.equal(res.status, 200);
|
|
115
|
+
assert.match(res.text, /"ok":true/);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('非白名单 Host 回 421(挡 DNS rebinding)', async () => {
|
|
120
|
+
await withGateway({ apiKey: 'sk-test' }, async ({ port }) => {
|
|
121
|
+
const res = await request(port, {
|
|
122
|
+
headers: { authorization: 'Bearer sk-test', host: 'evil.example.com' },
|
|
123
|
+
});
|
|
124
|
+
assert.equal(res.status, 421, 'Host 不在白名单时必须拒绝');
|
|
125
|
+
assert.match(res.text, /not allowed/);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test('白名单里的 Host 正常放行', async () => {
|
|
130
|
+
await withGateway({ apiKey: 'sk-test' }, async ({ port }) => {
|
|
131
|
+
const allowed = [`127.0.0.1:${port}`, `localhost:${port}`];
|
|
132
|
+
// 用 localhost 访问,验证白名单里的第二种写法确实被接受。
|
|
133
|
+
const res = await new Promise((resolve, reject) => {
|
|
134
|
+
const req = http.request(
|
|
135
|
+
{ host: 'localhost', port, path: '/healthz', headers: { authorization: 'Bearer sk-test' } },
|
|
136
|
+
(r) => {
|
|
137
|
+
const chunks = [];
|
|
138
|
+
r.on('data', (c) => chunks.push(c));
|
|
139
|
+
r.on('end', () => resolve({ status: r.statusCode, headers: r.headers }));
|
|
140
|
+
},
|
|
141
|
+
);
|
|
142
|
+
req.on('error', reject);
|
|
143
|
+
req.end();
|
|
144
|
+
});
|
|
145
|
+
assert.equal(res.status, 200, `localhost 应在允许列表 ${allowed.join(',')} 内`);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test('Origin 不在白名单时回 403', async () => {
|
|
150
|
+
await withGateway({ apiKey: 'sk-test', allowedOrigins: ['http://127.0.0.1:3000'] }, async ({ port }) => {
|
|
151
|
+
const res = await request(port, {
|
|
152
|
+
headers: { authorization: 'Bearer sk-test', origin: 'http://evil.example.com' },
|
|
153
|
+
});
|
|
154
|
+
assert.equal(res.status, 403);
|
|
155
|
+
assert.match(res.text, /origin/);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test('Origin 在白名单时放行', async () => {
|
|
160
|
+
await withGateway({ apiKey: 'sk-test', allowedOrigins: ['http://127.0.0.1:3000'] }, async ({ port }) => {
|
|
161
|
+
const res = await request(port, {
|
|
162
|
+
headers: { authorization: 'Bearer sk-test', origin: 'http://127.0.0.1:3000' },
|
|
163
|
+
});
|
|
164
|
+
assert.equal(res.status, 200);
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test('没有 Origin 头的命令行客户端不受影响', async () => {
|
|
169
|
+
await withGateway({ apiKey: 'sk-test', allowedOrigins: ['http://127.0.0.1:3000'] }, async ({ port }) => {
|
|
170
|
+
const res = await request(port, { headers: { authorization: 'Bearer sk-test' } });
|
|
171
|
+
assert.equal(res.status, 200, '不带 Origin 是 curl / SDK 的常态,必须放行');
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test('未配置 apiKey 时自动生成密钥并落盘(600 权限)', async () => {
|
|
176
|
+
const dir = mkdtempSync(join(tmpdir(), 'gateway-key-'));
|
|
177
|
+
const keyFile = join(dir, 'gateway.key');
|
|
178
|
+
try {
|
|
179
|
+
await withGateway({ apiKeyFile: keyFile }, async ({ port }) => {
|
|
180
|
+
// 未带认证 → 401,说明确实生成了密钥而不是放行
|
|
181
|
+
const denied = await request(port);
|
|
182
|
+
assert.equal(denied.status, 401, '未配置 apiKey 时不能裸放行');
|
|
183
|
+
|
|
184
|
+
const key = readFileSync(keyFile, 'utf8').trim();
|
|
185
|
+
assert.ok(key.length >= 20, `生成的密钥太短:${key.length}`);
|
|
186
|
+
|
|
187
|
+
const mode = statSync(keyFile).mode & 0o777;
|
|
188
|
+
assert.equal(mode, 0o600, `密钥文件权限必须是 600,实际 ${mode.toString(8)}`);
|
|
189
|
+
|
|
190
|
+
const ok = await request(port, { headers: { authorization: `Bearer ${key}` } });
|
|
191
|
+
assert.equal(ok.status, 200, '用文件里的密钥应当通过');
|
|
192
|
+
});
|
|
193
|
+
} finally {
|
|
194
|
+
rmSync(dir, { recursive: true, force: true });
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test('显式配置的 apiKey 优先于自动生成', async () => {
|
|
199
|
+
const dir = mkdtempSync(join(tmpdir(), 'gateway-key2-'));
|
|
200
|
+
const keyFile = join(dir, 'gateway.key');
|
|
201
|
+
try {
|
|
202
|
+
await withGateway({ apiKey: 'sk-explicit', apiKeyFile: keyFile }, async ({ port }) => {
|
|
203
|
+
const ok = await request(port, { headers: { authorization: 'Bearer sk-explicit' } });
|
|
204
|
+
assert.equal(ok.status, 200);
|
|
205
|
+
// 显式配置时不该去生成文件
|
|
206
|
+
let generated = true;
|
|
207
|
+
try {
|
|
208
|
+
readFileSync(keyFile, 'utf8');
|
|
209
|
+
} catch {
|
|
210
|
+
generated = false;
|
|
211
|
+
}
|
|
212
|
+
assert.equal(generated, false, '显式配置密钥时不应生成密钥文件');
|
|
213
|
+
});
|
|
214
|
+
} finally {
|
|
215
|
+
rmSync(dir, { recursive: true, force: true });
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
for (const { name, fn } of tests) {
|
|
220
|
+
try {
|
|
221
|
+
await fn();
|
|
222
|
+
passed += 1;
|
|
223
|
+
console.log(`✓ ${name}`);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
failures += 1;
|
|
226
|
+
console.error(`✗ ${name}`);
|
|
227
|
+
console.error(` ${error?.message ?? error}`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
console.log(`\n${failures === 0 ? '全部通过' : `${failures} 项失败`}(通过 ${passed}/${tests.length})`);
|
|
232
|
+
if (failures > 0) process.exit(1);
|
package/tests/body-limit.mjs
CHANGED
|
@@ -64,10 +64,19 @@ function fakeCtx() {
|
|
|
64
64
|
};
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
const TEST_KEY = 'sk-dsh-test-key';
|
|
68
|
+
|
|
67
69
|
async function withGateway(config, run) {
|
|
68
70
|
const port = await freePort();
|
|
69
71
|
const ctx = fakeCtx();
|
|
70
|
-
|
|
72
|
+
// 认证默认开启;测试显式给一个密钥,并把 Host 白名单设成测试实际会发的那个。
|
|
73
|
+
apply(ctx, {
|
|
74
|
+
host: '127.0.0.1',
|
|
75
|
+
port,
|
|
76
|
+
apiKey: TEST_KEY,
|
|
77
|
+
allowedHosts: [`127.0.0.1:${port}`],
|
|
78
|
+
...config,
|
|
79
|
+
});
|
|
71
80
|
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
72
81
|
try {
|
|
73
82
|
await run({ port });
|
|
@@ -80,7 +89,10 @@ async function withGateway(config, run) {
|
|
|
80
89
|
/** 发一个原始 POST;hideLength 模拟 content-length 缺失、走分块上传的客户端。 */
|
|
81
90
|
function post(port, path, body, { hideLength = false } = {}) {
|
|
82
91
|
return new Promise((resolve, reject) => {
|
|
83
|
-
const headers = {
|
|
92
|
+
const headers = {
|
|
93
|
+
'content-type': 'application/json',
|
|
94
|
+
authorization: `Bearer ${TEST_KEY}`,
|
|
95
|
+
};
|
|
84
96
|
if (hideLength) headers['transfer-encoding'] = 'chunked';
|
|
85
97
|
else headers['content-length'] = Buffer.byteLength(body);
|
|
86
98
|
const req = http.request({ host: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 路由图片预算的回归测试。
|
|
4
|
+
*
|
|
5
|
+
* 背景:DSH 的 pi-ai 适配器对一条请求有硬预算(默认 50 张图 / 20 MB base64)。
|
|
6
|
+
* 超了它抛 `IMAGE_OFFLOAD_REQUIRED`,并把「还要省略几张」交给
|
|
7
|
+
* `dsh-compaction-image-offload` —— 后者靠在**会话**里记 `image/offload` 事件
|
|
8
|
+
* 来记住哪些位置被省略。走网关时每轮都是新请求、图片块每轮重建,那条恢复链
|
|
9
|
+
* 永远修不好同一个历史,于是 Codex 里反复断流:
|
|
10
|
+
*
|
|
11
|
+
* stream disconnected before completion: pi-ai request images exceed the route
|
|
12
|
+
* image budget; 2 more oldest occurrence(s) must be offloaded.
|
|
13
|
+
*
|
|
14
|
+
* 网关现在的对策:自己在**请求内**按确定性规则省略最老的图片,让请求一次就
|
|
15
|
+
* 装进预算。这些用例断言该行为:
|
|
16
|
+
* 1. 图片数量超限时,省略最老的若干张,保留最新的;
|
|
17
|
+
* 2. base64 字节超限时同样触发省略;
|
|
18
|
+
* 3. 未超限时一张都不动;
|
|
19
|
+
* 4. 省略后真的落在预算内(这是「不再触发适配器报错」的充要条件)。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import assert from 'node:assert/strict';
|
|
23
|
+
|
|
24
|
+
import { applyImageBudget } from '../index.js';
|
|
25
|
+
|
|
26
|
+
let failures = 0;
|
|
27
|
+
let passed = 0;
|
|
28
|
+
const tests = [];
|
|
29
|
+
function test(name, fn) {
|
|
30
|
+
tests.push({ name, fn });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 造一条带 n 张图的消息,每张 approxBytes 字节。 */
|
|
34
|
+
function makeMessages(sizes) {
|
|
35
|
+
const content = sizes.map((bytes, index) => ({
|
|
36
|
+
type: 'image',
|
|
37
|
+
attachment: { attachmentId: `a${index}`, mediaType: 'image/png', bytes, width: 64, height: 64 },
|
|
38
|
+
}));
|
|
39
|
+
return [{ id: 'm1', role: 'user', content }];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function imagesLeft(messages) {
|
|
43
|
+
return messages[0].content.filter((block) => block.type === 'image').length;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function retainedBytes(messages) {
|
|
47
|
+
return messages[0].content
|
|
48
|
+
.filter((block) => block.type === 'image')
|
|
49
|
+
.reduce((sum, block) => sum + Math.ceil(block.attachment.bytes / 3) * 4, 0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
test('图片数量超限:省略最老的,保留最新的', async () => {
|
|
53
|
+
const sizes = Array.from({ length: 60 }, () => 100 * 1024);
|
|
54
|
+
const messages = makeMessages(sizes);
|
|
55
|
+
const omitted = applyImageBudget(messages, { maxImages: 50, maxBytes: 1024 * 1024 * 1024 });
|
|
56
|
+
assert.equal(omitted, 10, '应省略 10 张');
|
|
57
|
+
assert.equal(imagesLeft(messages), 50, '应保留 50 张');
|
|
58
|
+
// 最老的 10 个位置被换成占位文本
|
|
59
|
+
assert.equal(messages[0].content[0].type, 'text', '最老那张应被省略');
|
|
60
|
+
assert.equal(messages[0].content[9].type, 'text', '第 10 张应被省略');
|
|
61
|
+
assert.equal(messages[0].content[10].type, 'image', '第 11 张应保留');
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('base64 字节超限:同样从最老的开始省略', async () => {
|
|
65
|
+
// 每张 ~1 MiB → base64 ~1.33 MiB;20 张约 26.7 MiB,超过 20 MiB 预算
|
|
66
|
+
const sizes = Array.from({ length: 20 }, () => 1024 * 1024);
|
|
67
|
+
const messages = makeMessages(sizes);
|
|
68
|
+
const omitted = applyImageBudget(messages, { maxImages: 50, maxBytes: 20 * 1024 * 1024 });
|
|
69
|
+
assert.ok(omitted > 0, '字节超限时必须省略图片');
|
|
70
|
+
assert.ok(
|
|
71
|
+
retainedBytes(messages) <= Math.floor(20 * 1024 * 1024 * 0.95),
|
|
72
|
+
'省略后必须真的落在预算内(含 5% 余量)',
|
|
73
|
+
);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('未超限时一张都不动', async () => {
|
|
77
|
+
const messages = makeMessages([100 * 1024, 100 * 1024]);
|
|
78
|
+
const omitted = applyImageBudget(messages, { maxImages: 50, maxBytes: 20 * 1024 * 1024 });
|
|
79
|
+
assert.equal(omitted, 0);
|
|
80
|
+
assert.equal(imagesLeft(messages), 2);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('默认预算下 55 张图被压到 50 张以内', async () => {
|
|
84
|
+
const sizes = Array.from({ length: 55 }, () => 50 * 1024);
|
|
85
|
+
const messages = makeMessages(sizes);
|
|
86
|
+
const omitted = applyImageBudget(messages, {});
|
|
87
|
+
assert.ok(omitted >= 5, '至少要省略 5 张');
|
|
88
|
+
assert.ok(imagesLeft(messages) <= 50, '最终不超过 50 张');
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
for (const { name, fn } of tests) {
|
|
92
|
+
try {
|
|
93
|
+
await fn();
|
|
94
|
+
passed += 1;
|
|
95
|
+
console.log(`✓ ${name}`);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
failures += 1;
|
|
98
|
+
console.error(`✗ ${name}`);
|
|
99
|
+
console.error(` ${error?.message ?? error}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
console.log(`\n${failures === 0 ? '全部通过' : `${failures} 项失败`}(通过 ${passed}/${tests.length})`);
|
|
104
|
+
if (failures > 0) process.exit(1);
|