@morgan9668/dsh-llm-gateway 1.1.2 → 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 CHANGED
@@ -105,14 +105,18 @@ 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` | 空 | **认证默认开启**。留空时自动生成并落盘;非空时用你给的值 |
117
+ | `apiKeyFile` | `~/.dsh/dsh-llm-gateway.key` | 自动生成密钥的保存位置 |
118
+ | `allowedHosts` | 回环的几种写法(含端口) | 允许的 `Host` 头,挡 DNS rebinding;非白名单回 421 |
119
+ | `allowedOrigins` | 空(只允许不带 Origin 的请求) | 允许的 `Origin`,挡跨站页面调用;不匹配回 403 |
116
120
  | `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
117
121
  | `maxRequestImages` | `50` | 一条请求允许携带的图片数量上限;超过时省略最老的。与 DSH pi-ai 适配器的默认值对齐 |
118
122
  | `maxRequestImageBytes` | `20 MiB` | 一条请求的图片 base64 载荷总量上限;超过时省略最老的。留 5% 余量以吸收适配器重新编码的差异 |
@@ -122,11 +126,35 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
122
126
 
123
127
  ### 安全边界
124
128
 
125
- - 默认只绑 `127.0.0.1`,外部网络进不来。改 `host` 前先想清楚:这个端点会让调用方以你的账号配额随意调用模型。
126
- - `apiKey` 是**明文全串比较**,不是哈希、不带时效:别把它写进会共享出去的配置。
127
- - 网关**不实现 CORS**,也没有 `OPTIONS` 预检分支。浏览器页面直连会被同源策略挡住;
128
- 要跨源请自己在前面放一层反向代理,不要指望这里放宽。
129
- - 网关不落盘任何上游凭据;唯一的持久副作用是一条本地日志(见[排障](#排障))。
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` 再重启,会生成新的;客户端记得同步更新。
130
158
 
131
159
  ## 端点
132
160
 
@@ -350,10 +378,11 @@ wire_api = "responses"
350
378
  ## 开发与测试
351
379
 
352
380
  ```bash
353
- npm test # 等价于下面三条
381
+ npm test # 等价于下面四条
354
382
  node tests/stream-failure.mjs
355
383
  node tests/body-limit.mjs
356
384
  node tests/image-budget.mjs
385
+ node tests/auth.mjs
357
386
  ```
358
387
 
359
388
  `stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
@@ -366,6 +395,10 @@ node tests/image-budget.mjs
366
395
  `image-budget.mjs` 四个用例覆盖路由图片预算:数量超限时省略最老的并保留最新的;
367
396
  base64 字节超限时同样触发省略;未超限时一张不动;省略后确实落在预算内。
368
397
 
398
+ `auth.mjs` 十个用例覆盖认证与来源限制:无 token / 错误 token 回 401;非白名单 Host 回 421;
399
+ Origin 不在白名单回 403;不带 Origin 的命令行客户端不受影响;未配置 `apiKey` 时自动生成
400
+ 密钥并以 `600` 权限落盘;显式配置的密钥优先。
401
+
369
402
  未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
370
403
  认证。
371
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
- 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 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
 
@@ -210,5 +227,10 @@ and `retry-after: 0`; a missing `content-length` (chunked upload) is still count
210
227
  occurrences are omitted first while the newest are kept; a byte overflow also triggers
211
228
  omission; nothing is touched below the budget; and the result really fits.
212
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
+
213
235
  Conversion, pairing repair, slots, routing, attachments and the status map are not
214
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,7 +22,16 @@ 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,
@@ -126,6 +137,13 @@ function normalizeConfig(raw) {
126
137
  if (typeof raw.host === 'string' && raw.host !== '') config.host = raw.host;
127
138
  if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
128
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
+ }
129
147
  if (Number.isInteger(raw.maxBodyBytes) && raw.maxBodyBytes > 0) config.maxBodyBytes = raw.maxBodyBytes;
130
148
  if (Number.isInteger(raw.maxRequestImages) && raw.maxRequestImages > 0) config.maxRequestImages = raw.maxRequestImages;
131
149
  if (Number.isInteger(raw.maxRequestImageBytes) && raw.maxRequestImageBytes > 0) config.maxRequestImageBytes = raw.maxRequestImageBytes;
@@ -133,6 +151,52 @@ function normalizeConfig(raw) {
133
151
  return config;
134
152
  }
135
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
+
136
200
  /** 字节数 → 便于读的 MB/KB,用于日志。 */
137
201
  function formatBytes(bytes) {
138
202
  if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
@@ -1612,6 +1676,19 @@ export function apply(ctx, rawConfig) {
1612
1676
  } catch { /* 日志失败不影响主流程 */ }
1613
1677
  };
1614
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
+
1615
1692
  let cache = [];
1616
1693
  let cacheAt = 0;
1617
1694
  let inflight = null;
@@ -1777,9 +1854,44 @@ export function apply(ctx, rawConfig) {
1777
1854
  return undefined;
1778
1855
  }
1779
1856
 
1857
+ /**
1858
+ * 校验 bearer token。
1859
+ *
1860
+ * 用 `timingSafeEqual` 而不是 `===`:字符串比较会在第一个不同的字节提前返回,
1861
+ * 远程可达的端点上那是可测量的时间侧信道。
1862
+ */
1780
1863
  function authorized(request) {
1781
- if (config.apiKey === '') return true;
1782
- return request.headers.get('authorization') === `Bearer ${config.apiKey}`;
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());
1783
1895
  }
1784
1896
 
1785
1897
  async function handle(request) {
@@ -1787,6 +1899,22 @@ export function apply(ctx, rawConfig) {
1787
1899
  const url = new URL(request.url);
1788
1900
  const path = url.pathname.replace(/\/+$/u, '') || '/';
1789
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
+ }
1790
1918
  if (!authorized(request)) {
1791
1919
  return json({ error: { message: 'missing or invalid bearer token', type: 'authentication_error' } }, 401);
1792
1920
  }
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.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 && 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,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);
@@ -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) => {