dsh-sensenova-pool 1.2.0 → 1.3.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/CHANGELOG.md CHANGED
@@ -3,6 +3,16 @@
3
3
  本文件记录本插件的所有重要变更,格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
4
  版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
5
5
 
6
+ ## [1.3.0] - 2026-11-27
7
+
8
+ ### 新增
9
+
10
+ - **生图与 `/v1/*` 通用接口透传**:本地回环接口不再只处理 `/v1/chat/completions`,现已支持将 `sensenova-u1.5-lite` 等生图模型使用的 `/v1/images/generations`、`/v1/images/edits`、`/v1/images/variations` 及其他合法 `/v1/*` 端点透传至上游。
11
+ - **原样请求体与多格式兼容**:透传路径直接转发原始字节与 `Content-Type`,同时兼容商汤 JSON(`images/image_url`、`watermark`、`prompt_extend` 等)与 `multipart/form-data` 二进制表单上传,不经对话请求体清洗。
12
+ - **完整复用多 Key 轮换池**:透传请求同样自动替换真实上游 Key,遇 `429` / `5xx` 自动换 Key 重发,全池限流继续对外屏蔽为 `503 + Retry-After`。
13
+ - **生图独立超时保护**:`/v1/images/*` 默认单次上游请求超时至少为 180 秒(支持 `imageRequestTimeoutMs` 覆盖),避免高分辨率出图被对话默认 60 秒超时误杀。
14
+ - **路径安全边界校验**:严格校验拼接后的上游 URL 同源且不越出基准路径,拦截 `..`、`%2e%2e`、`//` 等路径遍历与非 `/v1/` 路由。
15
+
6
16
  ## [1.2.0] - 2026-11-20
7
17
 
8
18
  ### 修复
package/README.md CHANGED
@@ -220,7 +220,7 @@ sk-cccccccccccccccccccccccccccccc
220
220
 
221
221
  | 字段 | 示例 | 说明 |
222
222
  |---|---|---|
223
- | 接口地址 | `http://127.0.0.1:51234/v1` | OpenAI 兼容,`/chat/completions`、`/models` 都支持,流式/非流式都行 |
223
+ | 接口地址 | `http://127.0.0.1:51234/v1` | OpenAI 兼容,支持 `/chat/completions`、`/models` 及 `/images/generations`、`/images/edits` 等 `/v1/*` 接口透传,均走多 Key 轮换 |
224
224
  | API Key | `sk-dsh-…` | 填进 `Authorization: Bearer` 即可 |
225
225
 
226
226
  任何 OpenAI 客户端都可以直接用它,例如:
package/lib/shim.d.ts CHANGED
@@ -73,6 +73,13 @@ export interface ShimOptions {
73
73
  * 一眼就能定位。默认关闭(体积大且可能含用户内容),由 e2e / 排障时显式打开。
74
74
  */
75
75
  debugRequestOn400?: boolean;
76
+ /**
77
+ * 图像接口(`/v1/images/*`)单次上游请求超时(毫秒)。
78
+ *
79
+ * 生图/图生图(如 `sensenova-u1.5-lite`)是非流式长耗时请求,默认至少 180 秒,
80
+ * 避免高分辨率出图在对话默认的 60 秒被误判超时并重复重试。
81
+ */
82
+ imageRequestTimeoutMs?: number;
76
83
  }
77
84
  export interface Shim {
78
85
  ready: Promise<void>;
package/lib/shim.js CHANGED
@@ -117,12 +117,15 @@ export function createShim(options) {
117
117
  writeError(res, 401, 'unauthorized', 'missing or invalid Authorization bearer');
118
118
  return;
119
119
  }
120
- const url = (req.url ?? '/').split('?')[0];
121
- if (req.method === 'GET' && (url === '/healthz' || url === '/healthz/')) {
120
+ const rawUrl = req.url ?? '/';
121
+ const queryIndex = rawUrl.indexOf('?');
122
+ const pathname = queryIndex >= 0 ? rawUrl.slice(0, queryIndex) : rawUrl;
123
+ const search = queryIndex >= 0 ? rawUrl.slice(queryIndex) : '';
124
+ if (req.method === 'GET' && (pathname === '/healthz' || pathname === '/healthz/')) {
122
125
  writeJson(res, 200, { ok: true, ...pool.summary() });
123
126
  return;
124
127
  }
125
- if (req.method === 'GET' && (url === '/v1/models' || url === '/v1/models/')) {
128
+ if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/v1/models/')) {
126
129
  writeJson(res, 200, {
127
130
  object: 'list',
128
131
  data: catalog.current().map((model) => ({
@@ -134,11 +137,20 @@ export function createShim(options) {
134
137
  });
135
138
  return;
136
139
  }
137
- if (req.method === 'POST' && (url === '/v1/chat/completions' || url === '/v1/chat/completions/')) {
140
+ if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/v1/chat/completions/')) {
138
141
  await chatCompletions(req, res);
139
142
  return;
140
143
  }
141
- writeError(res, 404, 'not_found', `no such route: ${req.method} ${url}`);
144
+ // 其他 /v1/* 端点(如生图模型 sensenova-u1.5-lite 的 /v1/images/generations、
145
+ // /v1/images/edits 等):保持原始请求体与 Content-Type 原样透传并走 key 轮换池。
146
+ if (pathname.startsWith('/v1/') && isAllowedPassthroughMethod(req.method)) {
147
+ const target = resolveUpstreamPassthroughUrl(upstreamBaseUrl, pathname, search);
148
+ if (target !== null) {
149
+ await passthrough(req, res, target.url, target.subpath);
150
+ return;
151
+ }
152
+ }
153
+ writeError(res, 404, 'not_found', `no such route: ${req.method} ${pathname}`);
142
154
  }
143
155
  catch (error) {
144
156
  const message = error instanceof Error ? error.message : String(error);
@@ -250,6 +262,90 @@ export function createShim(options) {
250
262
  });
251
263
  stream.pipe(res);
252
264
  }
265
+ /**
266
+ * 透传非 chat 的 `/v1/*` 请求(生图 / 图生图等)到上游,并复用 key 轮换池。
267
+ *
268
+ * 不解析、不改写原始请求体(同时兼容 JSON 与 multipart/form-data),
269
+ * 读入 Buffer 后可在 429 / 5xx 切换下一把 key 时安全重发。
270
+ */
271
+ async function passthrough(req, res, upstreamUrl, subpath) {
272
+ const method = (req.method ?? 'GET').toUpperCase();
273
+ const hasBody = method !== 'GET' && method !== 'HEAD';
274
+ const rawBody = hasBody ? await readBody(req) : undefined;
275
+ const isImageRoute = subpath === '/images' || subpath.startsWith('/images/');
276
+ const effectiveRotation = isImageRoute
277
+ ? {
278
+ ...rotation,
279
+ requestTimeoutMs: options.imageRequestTimeoutMs ??
280
+ Math.max(rotation.requestTimeoutMs, DEFAULT_IMAGE_REQUEST_TIMEOUT_MS),
281
+ }
282
+ : rotation;
283
+ const controller = new AbortController();
284
+ res.on('close', () => {
285
+ if (!res.writableEnded)
286
+ controller.abort();
287
+ });
288
+ const result = await requestWithRotation(pool, effectiveRotation, (apiKey, signal) => fetch(upstreamUrl, {
289
+ method,
290
+ headers: buildPassthroughHeaders(req, apiKey),
291
+ body: rawBody !== undefined && rawBody.length > 0 ? new Uint8Array(rawBody) : undefined,
292
+ signal,
293
+ }), {
294
+ onAttemptFailed: (log) => {
295
+ options.logger?.warn(`sensenova-pool: key ${log.keyId} ${log.kind} (${log.status}) — ${log.message}`);
296
+ options.onAttemptFailed?.(log);
297
+ },
298
+ signal: controller.signal,
299
+ });
300
+ if (!result.ok) {
301
+ if (controller.signal.aborted) {
302
+ if (!res.headersSent)
303
+ res.statusCode = 499;
304
+ res.end();
305
+ return;
306
+ }
307
+ if (options.debugRequestOn400 && result.error.status === 400) {
308
+ const preview = formatDebugBodyPreview(req.headers['content-type'], rawBody);
309
+ options.logger?.warn(`sensenova-pool: 上游 400(${result.error.message}),透传 ${method} ${subpath} 请求体:${preview}`);
310
+ }
311
+ writeError(res, outwardStatus(result.error), result.error.kind, summarizeFailure(result.error.message, result.attempts), result.error.kind === 'rate_limit' ? retryAfterSeconds(pool) : undefined);
312
+ return;
313
+ }
314
+ const upstream = result.response;
315
+ const contentType = upstream.headers.get('content-type');
316
+ if (contentType?.toLowerCase().includes('text/event-stream') && upstream.body) {
317
+ res.writeHead(upstream.status, {
318
+ 'content-type': contentType,
319
+ 'cache-control': 'no-cache',
320
+ connection: 'keep-alive',
321
+ 'x-accel-buffering': 'no',
322
+ 'x-sensenova-pool-key': result.keyId,
323
+ 'x-sensenova-pool-attempts': String(result.attempts),
324
+ });
325
+ const stream = Readable.fromWeb(upstream.body);
326
+ stream.on('error', (error) => {
327
+ options.logger?.warn(`sensenova-pool: upstream stream failed mid-flight: ${error.message}`);
328
+ if (res.writable)
329
+ res.end();
330
+ });
331
+ stream.pipe(res);
332
+ return;
333
+ }
334
+ const outHeaders = {
335
+ 'x-sensenova-pool-key': result.keyId,
336
+ 'x-sensenova-pool-attempts': String(result.attempts),
337
+ };
338
+ if (contentType)
339
+ outHeaders['content-type'] = contentType;
340
+ if (method === 'HEAD' || upstream.status === 204) {
341
+ res.writeHead(upstream.status, outHeaders);
342
+ res.end();
343
+ return;
344
+ }
345
+ const payload = Buffer.from(await upstream.arrayBuffer());
346
+ res.writeHead(upstream.status, outHeaders);
347
+ res.end(payload);
348
+ }
253
349
  return {
254
350
  ready,
255
351
  baseUrl,
@@ -387,4 +483,91 @@ function writeError(res, status, code, message, retryAfterSec) {
387
483
  res.writeHead(status, headers);
388
484
  res.end(payload);
389
485
  }
486
+ const DEFAULT_IMAGE_REQUEST_TIMEOUT_MS = 180_000;
487
+ const ALLOWED_PASSTHROUGH_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']);
488
+ const PASSTHROUGH_REQUEST_HEADERS = [
489
+ 'content-type',
490
+ 'accept',
491
+ 'openai-beta',
492
+ 'anthropic-version',
493
+ 'anthropic-beta',
494
+ 'x-request-id',
495
+ ];
496
+ function isAllowedPassthroughMethod(method) {
497
+ return typeof method === 'string' && ALLOWED_PASSTHROUGH_METHODS.has(method.toUpperCase());
498
+ }
499
+ /**
500
+ * 将本地 `/v1/...` 路径安全拼接到当前上游根地址,防御路径遍历与跨主机逃逸。
501
+ */
502
+ function resolveUpstreamPassthroughUrl(upstreamBaseUrl, pathname, search) {
503
+ if (!pathname.startsWith('/v1/'))
504
+ return null;
505
+ const rawSubpath = pathname.slice(3); // 保留开头的 "/"
506
+ const subpath = rawSubpath.replace(/\/+$/, '');
507
+ if (subpath.length <= 1)
508
+ return null;
509
+ if (/[\u0000-\u001f\u007f\\]/.test(subpath))
510
+ return null;
511
+ if (subpath.includes('//'))
512
+ return null;
513
+ for (const segment of subpath.slice(1).split('/')) {
514
+ if (!segment || segment === '.' || segment === '..')
515
+ return null;
516
+ let decoded;
517
+ try {
518
+ decoded = decodeURIComponent(segment);
519
+ }
520
+ catch {
521
+ return null;
522
+ }
523
+ if (decoded === '.' ||
524
+ decoded === '..' ||
525
+ decoded.includes('/') ||
526
+ decoded.includes('\\') ||
527
+ decoded.includes('\u0000')) {
528
+ return null;
529
+ }
530
+ }
531
+ const baseTrimmed = upstreamBaseUrl.replace(/\/+$/, '');
532
+ const candidate = `${baseTrimmed}${subpath}${search}`;
533
+ try {
534
+ const baseParsed = new URL(baseTrimmed);
535
+ const targetParsed = new URL(candidate);
536
+ if (targetParsed.origin !== baseParsed.origin)
537
+ return null;
538
+ const basePath = baseParsed.pathname.replace(/\/+$/, '');
539
+ if (basePath.length > 0 && targetParsed.pathname !== basePath && !targetParsed.pathname.startsWith(`${basePath}/`)) {
540
+ return null;
541
+ }
542
+ }
543
+ catch {
544
+ return null;
545
+ }
546
+ return { url: candidate, subpath };
547
+ }
548
+ function buildPassthroughHeaders(req, apiKey) {
549
+ const headers = {
550
+ authorization: `Bearer ${apiKey}`,
551
+ };
552
+ for (const name of PASSTHROUGH_REQUEST_HEADERS) {
553
+ const value = req.headers[name];
554
+ if (typeof value === 'string' && value.length > 0) {
555
+ headers[name] = value;
556
+ }
557
+ else if (Array.isArray(value) && value.length > 0) {
558
+ headers[name] = value.join(', ');
559
+ }
560
+ }
561
+ return headers;
562
+ }
563
+ function formatDebugBodyPreview(contentType, rawBody) {
564
+ if (!rawBody || rawBody.length === 0)
565
+ return '(empty)';
566
+ const ct = Array.isArray(contentType) ? contentType.join(', ') : (contentType ?? '');
567
+ if (/\bjson\b/i.test(ct) || /^text\//i.test(ct)) {
568
+ const text = rawBody.toString('utf8');
569
+ return text.length > 2000 ? `${text.slice(0, 2000)}…(共 ${rawBody.length} 字节)` : text;
570
+ }
571
+ return `<${ct || 'binary'}, ${rawBody.length} bytes>`;
572
+ }
390
573
  export { DEFAULT_BASE_URL };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-sensenova-pool",
3
3
  "displayName": "DSH SenseNova Key Pool",
4
4
  "description": "商汤日日新(SenseNova)多 Key 轮换池 — 填入多把 Key 即可零配置接入 DeepSeek Harness,遇 429 限流自动切换下一把 Key。",
5
- "version": "1.2.0",
5
+ "version": "1.3.0",
6
6
  "author": "Phoeky",
7
7
  "keywords": [
8
8
  "dsh-plugin",