@morgan9668/dsh-llm-gateway 1.1.2 → 1.2.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 CHANGED
@@ -105,14 +105,19 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
105
105
  config:
106
106
  host: '127.0.0.1'
107
107
  port: 8392
108
- apiKey: ''
108
+ # apiKey 留空即可:首次启动会自动生成密钥写入 apiKeyFile
109
+ # (默认 ~/.dsh/dsh-llm-gateway.key,权限 600),日志会打路径。
109
110
  ```
110
111
 
111
112
  | 字段 | 默认 | 说明 |
112
113
  |---|---|---|
113
114
  | `host` | `127.0.0.1` | 绑定地址。默认只绑回环,局域网内其它机器访问不到 |
114
115
  | `port` | `8392` | 监听端口;非法值静默回退到默认值,不会报错 |
115
- | `apiKey` | 空 | 为空表示不鉴权;非空时要求 `Authorization: Bearer <key>` 全串精确匹配 |
116
+ | `apiKey` | 空 | 留空且 `requireAuth` 关闭时不校验 token;填了值则要求 `Authorization: Bearer <该值>` |
117
+ | `requireAuth` | `false` | 设为 `true` 强制校验 token;此时 `apiKey` 留空会自动生成并落盘 |
118
+ | `apiKeyFile` | `~/.dsh/dsh-llm-gateway.key` | `requireAuth` 打开时自动生成密钥的保存位置 |
119
+ | `allowedHosts` | 回环的几种写法(含端口) | 允许的 `Host` 头,挡 DNS rebinding;非白名单回 421 |
120
+ | `allowedOrigins` | 空(只允许不带 Origin 的请求) | 允许的 `Origin`,挡跨站页面调用;不匹配回 403 |
116
121
  | `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
117
122
  | `maxRequestImages` | `50` | 一条请求允许携带的图片数量上限;超过时省略最老的。与 DSH pi-ai 适配器的默认值对齐 |
118
123
  | `maxRequestImageBytes` | `20 MiB` | 一条请求的图片 base64 载荷总量上限;超过时省略最老的。留 5% 余量以吸收适配器重新编码的差异 |
@@ -122,11 +127,42 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
122
127
 
123
128
  ### 安全边界
124
129
 
125
- - 默认只绑 `127.0.0.1`,外部网络进不来。改 `host` 前先想清楚:这个端点会让调用方以你的账号配额随意调用模型。
126
- - `apiKey` 是**明文全串比较**,不是哈希、不带时效:别把它写进会共享出去的配置。
127
- - 网关**不实现 CORS**,也没有 `OPTIONS` 预检分支。浏览器页面直连会被同源策略挡住;
128
- 要跨源请自己在前面放一层反向代理,不要指望这里放宽。
129
- - 网关不落盘任何上游凭据;唯一的持久副作用是一条本地日志(见[排障](#排障))。
130
+ 默认配置下,**不需要任何凭据**就能用——这一点是有意保持的,因为现成的客户端
131
+ (Codex、SDK、脚本)都是零配置直连,升级不该把它们打断。真正危险的两类场景由另外两道
132
+ 校验挡住,它们默认就开着:
133
+
134
+ 1. **绑定**只到 `127.0.0.1`,外部网络进不来。改 `host` 前先想清楚:这个端点会让调用方
135
+ 以你的账号配额随意调用模型。
136
+ 2. **Host 必须白名单**。只接受回环的几种写法(`127.0.0.1` / `localhost` / `[::1]`,
137
+ 带配置端口),否则回 421。这条挡的是 DNS rebinding:攻击者把自己的域名解析到
138
+ `127.0.0.1`,浏览器就会把请求当成同源发过来。
139
+ 3. **Origin 存在时必须白名单**,否则回 403。这条挡的是浏览器里的跨站页面。命令行客户端
140
+ 一般不带 `Origin`,不受影响。空列表表示「不接受任何跨站调用」,不是「全部放行」。
141
+
142
+ 需要更强隔离(比如同机还有别的用户或不可信程序)时,打开认证:
143
+
144
+ ```yaml
145
+ config:
146
+ requireAuth: true # 首次启动生成密钥到 ~/.dsh/dsh-llm-gateway.key(600)
147
+ ```
148
+
149
+ ```bash
150
+ curl -H "Authorization: Bearer $(cat ~/.dsh/dsh-llm-gateway.key)" \
151
+ http://127.0.0.1:8392/v1/models
152
+ ```
153
+
154
+ 也可以在 `apiKey` 里直接填一个自己的值。密钥比较用 `timingSafeEqual`,不是会提前返回的
155
+ 字符串比较。
156
+
157
+ 跨源访问需要放行时,把来源写进 `allowedOrigins`,不要改成放行 `*`:
158
+
159
+ ```yaml
160
+ config:
161
+ allowedOrigins:
162
+ - 'http://127.0.0.1:3000'
163
+ ```
164
+
165
+ 其余说明:网关不落盘任何上游凭据;持久副作用只有日志(以及开启认证时的密钥文件)。
130
166
 
131
167
  ## 端点
132
168
 
@@ -350,10 +386,11 @@ wire_api = "responses"
350
386
  ## 开发与测试
351
387
 
352
388
  ```bash
353
- npm test # 等价于下面三条
389
+ npm test # 等价于下面四条
354
390
  node tests/stream-failure.mjs
355
391
  node tests/body-limit.mjs
356
392
  node tests/image-budget.mjs
393
+ node tests/auth.mjs
357
394
  ```
358
395
 
359
396
  `stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
@@ -366,6 +403,11 @@ node tests/image-budget.mjs
366
403
  `image-budget.mjs` 四个用例覆盖路由图片预算:数量超限时省略最老的并保留最新的;
367
404
  base64 字节超限时同样触发省略;未超限时一张不动;省略后确实落在预算内。
368
405
 
406
+ `auth.mjs` 十一个用例覆盖认证与来源限制:默认不要求 token(升级不打断现有客户端);
407
+ `requireAuth` 打开后无 token / 错误 token 回 401;非白名单 Host 回 421;Origin 不在白名单
408
+ 回 403;不带 Origin 的命令行客户端不受影响;`requireAuth` 下自动生成密钥并以 `600` 权限
409
+ 落盘;显式配置的密钥优先。
410
+
369
411
  未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
370
412
  认证。
371
413
 
package/docs/DETAIL.md CHANGED
@@ -24,9 +24,37 @@ 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
- All routes require `Authorization: Bearer <apiKey>` when `apiKey` is non-empty,
28
- including `/healthz`. The gateway sets no CORS headers and has no `OPTIONS`
29
- handler; put a reverse proxy in front if you need cross-origin access.
27
+ ## Authentication and origin checks
28
+
29
+ Authentication is **off by default**, deliberately: existing clients (Codex,
30
+ SDKs, scripts) connect with no credentials, and upgrading a gateway should not
31
+ break them. The dangerous cases are covered by two checks that are on by default
32
+ instead — Host and Origin, below.
33
+
34
+ Turning it on takes one setting:
35
+
36
+ ```yaml
37
+ config:
38
+ requireAuth: true
39
+ ```
40
+
41
+ An empty `apiKey` then generates a random key into `apiKeyFile` (default
42
+ `~/.dsh/dsh-llm-gateway.key`, mode `600`) and logs the path; clients send
43
+ `Authorization: Bearer <that key>`. Setting `apiKey` directly pins your own value.
44
+ The comparison uses `timingSafeEqual`, not an early-returning string compare.
45
+
46
+ Two more checks run before routing:
47
+
48
+ - **Host** must be in `allowedHosts`, which defaults to the loopback spellings
49
+ with the configured port. A mismatch returns 421. This blocks DNS rebinding:
50
+ an attacker's domain resolving to `127.0.0.1` makes the browser treat the
51
+ request as same-origin.
52
+ - **Origin**, when present, must be in `allowedOrigins` (403 otherwise). Command
53
+ line clients and SDKs normally send no Origin, so they are unaffected. An empty
54
+ `allowedOrigins` means "no cross-origin callers" rather than "allow all".
55
+
56
+ The gateway sets no CORS headers and has no `OPTIONS` handler; to permit a
57
+ same-machine page, list it in `allowedOrigins` rather than loosening this.
30
58
 
31
59
  ## Grouped model ids
32
60
 
@@ -210,5 +238,11 @@ and `retry-after: 0`; a missing `content-length` (chunked upload) is still count
210
238
  occurrences are omitted first while the newest are kept; a byte overflow also triggers
211
239
  omission; nothing is touched below the budget; and the result really fits.
212
240
 
241
+ `node tests/auth.mjs` runs eleven cases for authentication and origin checks: the
242
+ default requires no token; with `requireAuth` a missing or wrong token returns 401;
243
+ a non-allowlisted Host returns 421; an origin outside `allowedOrigins` returns 403;
244
+ clients without an Origin header still work; `requireAuth` generates a key file with
245
+ mode 600; and an explicit key wins.
246
+
213
247
  Conversion, pairing repair, slots, routing, attachments and the status map are not
214
248
  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,7 +22,24 @@ export const inject = ['llm', 'attachments'];
20
22
  const DEFAULTS = {
21
23
  host: '127.0.0.1',
22
24
  port: 8392,
25
+ // 认证默认**关闭**,保持向后兼容:空串就是「不校验 token」。
26
+ //
27
+ // 之所以不默认开启:现成的客户端(Codex、SDK、脚本)都是零配置直连的,
28
+ // 一旦默认要求 token,它们会在升级后立刻 401,而用户不一定知道去哪找密钥。
29
+ // 默认开启的安全收益有限——网关本来就只绑回环,外加下面 Host/Origin 两道
30
+ // 校验,已经挡住了真正危险的场景(浏览器里的跨站页面、DNS rebinding)。
31
+ //
32
+ // 需要更强隔离时:把 requireAuth 设为 true,密钥会自动生成到 apiKeyFile
33
+ // (600 权限),或者直接把 apiKey 填成想要的值。
23
34
  apiKey: '',
35
+ // 为 true 时强制校验 bearer token;apiKey 为空则自动生成并落盘。
36
+ requireAuth: false,
37
+ // 自动生成的密钥落盘位置。requireAuth 打开时才使用。
38
+ apiKeyFile: '',
39
+ // 允许的 Host 头。默认只接受回环地址的几种写法,挡掉 DNS rebinding。
40
+ allowedHosts: [],
41
+ // 非空时要求 Origin 头(若存在)落在这个列表里,挡掉浏览器跨站调用。
42
+ allowedOrigins: [],
24
43
  // 请求体上限。Codex 每轮都会把整段历史重发一遍,带图的会话里 base64 图片
25
44
  // 会把这一个请求推到几十 MB —— 默认值必须容得下正常的多图历史。
26
45
  maxBodyBytes: 256 * 1024 * 1024,
@@ -126,6 +145,14 @@ function normalizeConfig(raw) {
126
145
  if (typeof raw.host === 'string' && raw.host !== '') config.host = raw.host;
127
146
  if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
128
147
  if (typeof raw.apiKey === 'string') config.apiKey = raw.apiKey;
148
+ if (typeof raw.requireAuth === 'boolean') config.requireAuth = raw.requireAuth;
149
+ if (typeof raw.apiKeyFile === 'string') config.apiKeyFile = raw.apiKeyFile;
150
+ if (Array.isArray(raw.allowedHosts)) {
151
+ config.allowedHosts = raw.allowedHosts.filter((h) => typeof h === 'string' && h !== '');
152
+ }
153
+ if (Array.isArray(raw.allowedOrigins)) {
154
+ config.allowedOrigins = raw.allowedOrigins.filter((o) => typeof o === 'string' && o !== '');
155
+ }
129
156
  if (Number.isInteger(raw.maxBodyBytes) && raw.maxBodyBytes > 0) config.maxBodyBytes = raw.maxBodyBytes;
130
157
  if (Number.isInteger(raw.maxRequestImages) && raw.maxRequestImages > 0) config.maxRequestImages = raw.maxRequestImages;
131
158
  if (Number.isInteger(raw.maxRequestImageBytes) && raw.maxRequestImageBytes > 0) config.maxRequestImageBytes = raw.maxRequestImageBytes;
@@ -133,6 +160,54 @@ function normalizeConfig(raw) {
133
160
  return config;
134
161
  }
135
162
 
163
+ /** 回环地址补上端口后的几种合法 Host 写法。 */
164
+ function defaultAllowedHosts(host, port) {
165
+ const names = ['127.0.0.1', 'localhost', '[::1]'];
166
+ const hosts = [];
167
+ for (const name of names) {
168
+ hosts.push(`${name}:${port}`);
169
+ }
170
+ // 少数客户端省掉默认端口,这里对 80 也留一条口子(实际端口另有条目)。
171
+ if (port !== 80) hosts.push(...names.map((name) => `${name}:80`));
172
+ void host;
173
+ return hosts;
174
+ }
175
+
176
+ /**
177
+ * 解析出这次真正用于校验的 API key。
178
+ *
179
+ * 规则:
180
+ * - `apiKey` 非空 → 用它。用户显式配置的优先。
181
+ * - `apiKey` 为空 → 用 `apiKeyFile` 里保存的密钥;文件不存在就生成一个 32 字节
182
+ * 随机串并以 600 权限写入。这样「默认安全」不会变成「默认不可用」:密钥就在
183
+ * 本机那个文件里,客户端照抄即可,不需要用户每次手填。
184
+ *
185
+ * 返回 `{ key, generated }`,`generated` 为 true 时调用方应把路径打到日志里。
186
+ */
187
+ function resolveApiKey(config) {
188
+ if (config.apiKey !== '') return { key: config.apiKey, filePath: undefined, generated: false };
189
+ // 既没填 apiKey 也没要求认证:不校验。调用方据此跳过 token 比对。
190
+ if (config.requireAuth !== true) return { key: '', filePath: undefined, generated: false };
191
+ const filePath = config.apiKeyFile !== ''
192
+ ? config.apiKeyFile
193
+ : join(homedir(), '.dsh', 'dsh-llm-gateway.key');
194
+ try {
195
+ const existing = readFileSync(filePath, 'utf8').trim();
196
+ if (existing !== '') return { key: existing, filePath, generated: false };
197
+ } catch {
198
+ // 文件不存在或读不到:生成新的。
199
+ }
200
+ const key = `sk-dsh-${randomBytes(24).toString('base64url')}`;
201
+ try {
202
+ mkdirSync(join(filePath, '..'), { recursive: true, mode: 0o700 });
203
+ writeFileSync(filePath, `${key}\n`, { mode: 0o600 });
204
+ } catch {
205
+ // 写不进去也要能跑:密钥留在内存里,退化为「本次进程有效」。
206
+ return { key, filePath, generated: true };
207
+ }
208
+ return { key, filePath, generated: true };
209
+ }
210
+
136
211
  /** 字节数 → 便于读的 MB/KB,用于日志。 */
137
212
  function formatBytes(bytes) {
138
213
  if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
@@ -1612,6 +1687,24 @@ export function apply(ctx, rawConfig) {
1612
1687
  } catch { /* 日志失败不影响主流程 */ }
1613
1688
  };
1614
1689
 
1690
+ // 认证与来源限制。默认开启:密钥自动生成到 apiKeyFile,Host 只接受回环。
1691
+ const { key: apiKey, filePath: apiKeyFile, generated: apiKeyGenerated } = resolveApiKey(config);
1692
+ const allowedHosts = (config.allowedHosts.length > 0
1693
+ ? config.allowedHosts
1694
+ : defaultAllowedHosts(config.host, config.port)
1695
+ ).map((h) => h.toLowerCase());
1696
+ const allowedOrigins = config.allowedOrigins.map((o) => o.toLowerCase());
1697
+ if (apiKeyGenerated) {
1698
+ log(`已生成新的 API 密钥并写入 ${apiKeyFile ?? '(仅本次进程)'};客户端请用 Authorization: Bearer <该文件内容>`);
1699
+ }
1700
+ if (apiKey === '') {
1701
+ log(`认证未启用(只绑回环 + Host/Origin 校验);需要时设 requireAuth: true 或填 apiKey`);
1702
+ } else {
1703
+ log('认证已启用');
1704
+ }
1705
+ log(`允许的 Host:${allowedHosts.join(', ')}`);
1706
+ if (allowedOrigins.length > 0) log(`允许的 Origin:${allowedOrigins.join(', ')}`);
1707
+
1615
1708
  let cache = [];
1616
1709
  let cacheAt = 0;
1617
1710
  let inflight = null;
@@ -1777,9 +1870,46 @@ export function apply(ctx, rawConfig) {
1777
1870
  return undefined;
1778
1871
  }
1779
1872
 
1873
+ /**
1874
+ * 校验 bearer token。
1875
+ *
1876
+ * 用 `timingSafeEqual` 而不是 `===`:字符串比较会在第一个不同的字节提前返回,
1877
+ * 远程可达的端点上那是可测量的时间侧信道。
1878
+ */
1780
1879
  function authorized(request) {
1781
- if (config.apiKey === '') return true;
1782
- return request.headers.get('authorization') === `Bearer ${config.apiKey}`;
1880
+ // apiKey 为空 = 未启用认证(requireAuth 关闭且没填 key)。
1881
+ if (apiKey === '') return true;
1882
+ const header = request.headers.get('authorization') ?? '';
1883
+ const prefix = 'Bearer ';
1884
+ if (!header.startsWith(prefix)) return false;
1885
+ const presented = header.slice(prefix.length);
1886
+ const expected = apiKey;
1887
+ const a = Buffer.from(presented, 'utf8');
1888
+ const b = Buffer.from(expected, 'utf8');
1889
+ if (a.length !== b.length) return false;
1890
+ return timingSafeEqual(a, b);
1891
+ }
1892
+
1893
+ /**
1894
+ * 校验 Host 与 Origin。
1895
+ *
1896
+ * Host 挡 DNS rebinding:攻击者把自己的域名解析到 127.0.0.1,浏览器就会把
1897
+ * 请求当成同源发过来,Host 是攻击者的域名。只接受回环的几种写法即可挡住。
1898
+ *
1899
+ * Origin 挡跨站页面调用:浏览器会带上 Origin,命令行工具一般不带,所以
1900
+ * 只校验「存在且不在白名单」的情况。
1901
+ */
1902
+ function hostAllowed(request) {
1903
+ const host = (request.headers.get('host') ?? '').toLowerCase();
1904
+ if (host === '') return false;
1905
+ return allowedHosts.includes(host);
1906
+ }
1907
+
1908
+ function originAllowed(request) {
1909
+ const origin = request.headers.get('origin');
1910
+ if (origin === null || origin === '') return true;
1911
+ if (allowedOrigins.length === 0) return false;
1912
+ return allowedOrigins.includes(origin.toLowerCase());
1783
1913
  }
1784
1914
 
1785
1915
  async function handle(request) {
@@ -1787,6 +1917,22 @@ export function apply(ctx, rawConfig) {
1787
1917
  const url = new URL(request.url);
1788
1918
  const path = url.pathname.replace(/\/+$/u, '') || '/';
1789
1919
 
1920
+ if (!hostAllowed(request)) {
1921
+ return json({
1922
+ error: {
1923
+ message: `host "${request.headers.get('host') ?? ''}" is not allowed; set allowedHosts to permit it`,
1924
+ type: 'invalid_request_error',
1925
+ },
1926
+ }, 421);
1927
+ }
1928
+ if (!originAllowed(request)) {
1929
+ return json({
1930
+ error: {
1931
+ message: `origin "${request.headers.get('origin') ?? ''}" is not allowed; set allowedOrigins to permit it`,
1932
+ type: 'invalid_request_error',
1933
+ },
1934
+ }, 403);
1935
+ }
1790
1936
  if (!authorized(request)) {
1791
1937
  return json({ error: { message: 'missing or invalid bearer token', type: 'authentication_error' } }, 401);
1792
1938
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morgan9668/dsh-llm-gateway",
3
- "version": "1.1.2",
3
+ "version": "1.2.1",
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 && node tests/image-budget.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,239 @@
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('默认不要求 token:现有客户端升级后不会被打断', async () => {
176
+ await withGateway({}, async ({ port }) => {
177
+ const res = await request(port);
178
+ assert.equal(res.status, 200, '未开启 requireAuth 时必须免认证放行');
179
+ assert.match(res.text, /"ok":true/);
180
+ });
181
+ });
182
+
183
+ test('requireAuth 打开后自动生成密钥并落盘(600 权限)', async () => {
184
+ const dir = mkdtempSync(join(tmpdir(), 'gateway-key-'));
185
+ const keyFile = join(dir, 'gateway.key');
186
+ try {
187
+ await withGateway({ requireAuth: true, apiKeyFile: keyFile }, async ({ port }) => {
188
+ const denied = await request(port);
189
+ assert.equal(denied.status, 401, 'requireAuth 打开后无 token 必须 401');
190
+
191
+ const key = readFileSync(keyFile, 'utf8').trim();
192
+ assert.ok(key.length >= 20, `生成的密钥太短:${key.length}`);
193
+
194
+ const mode = statSync(keyFile).mode & 0o777;
195
+ assert.equal(mode, 0o600, `密钥文件权限必须是 600,实际 ${mode.toString(8)}`);
196
+
197
+ const ok = await request(port, { headers: { authorization: `Bearer ${key}` } });
198
+ assert.equal(ok.status, 200, '用文件里的密钥应当通过');
199
+ });
200
+ } finally {
201
+ rmSync(dir, { recursive: true, force: true });
202
+ }
203
+ });
204
+
205
+ test('显式配置的 apiKey 优先于自动生成', async () => {
206
+ const dir = mkdtempSync(join(tmpdir(), 'gateway-key2-'));
207
+ const keyFile = join(dir, 'gateway.key');
208
+ try {
209
+ await withGateway({ apiKey: 'sk-explicit', apiKeyFile: keyFile }, async ({ port }) => {
210
+ const ok = await request(port, { headers: { authorization: 'Bearer sk-explicit' } });
211
+ assert.equal(ok.status, 200);
212
+ // 显式配置时不该去生成文件
213
+ let generated = true;
214
+ try {
215
+ readFileSync(keyFile, 'utf8');
216
+ } catch {
217
+ generated = false;
218
+ }
219
+ assert.equal(generated, false, '显式配置密钥时不应生成密钥文件');
220
+ });
221
+ } finally {
222
+ rmSync(dir, { recursive: true, force: true });
223
+ }
224
+ });
225
+
226
+ for (const { name, fn } of tests) {
227
+ try {
228
+ await fn();
229
+ passed += 1;
230
+ console.log(`✓ ${name}`);
231
+ } catch (error) {
232
+ failures += 1;
233
+ console.error(`✗ ${name}`);
234
+ console.error(` ${error?.message ?? error}`);
235
+ }
236
+ }
237
+
238
+ console.log(`\n${failures === 0 ? '全部通过' : `${failures} 项失败`}(通过 ${passed}/${tests.length})`);
239
+ if (failures > 0) process.exit(1);
@@ -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
- apply(ctx, { host: '127.0.0.1', port, ...config });
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 = { 'content-type': 'application/json' };
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) => {