dsh-mo-image 0.6.0 → 1.0.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.
@@ -4,8 +4,9 @@
4
4
  * 原本长在 lib/adapters.js 里;协议变多以后拆出来,供 adapters.js 与
5
5
  * lib/adapters/*.js 共用,避免循环依赖。
6
6
  */
7
- import { request } from './net.js';
7
+ import { createHash } from 'node:crypto';
8
8
  import { localizedError } from './localized-error.js';
9
+ import { isPng, pngHeaderOf } from './png-scale.js';
9
10
 
10
11
  export const ASPECT_CHOICES = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9'];
11
12
 
@@ -42,37 +43,143 @@ export function nearestAspect(width, height, choices = ASPECT_CHOICES) {
42
43
  return best;
43
44
  }
44
45
 
45
- export function resolutionFor(width, height) {
46
- const pixels = (Number(width) || 1024) * (Number(height) || 1024);
47
- if (pixels >= 2800 * 2800) return '4k';
48
- if (pixels >= 1800 * 1800) return '2k';
49
- return '1k';
50
- }
51
46
 
52
47
  export function baseUrlOf(provider) {
53
- return String((provider && provider.baseUrl) || '').replace(/\/+$/, '');
48
+ return String((provider && provider.baseUrl) || '').trim().replace(/\/+$/, '');
49
+ }
50
+
51
+ /** Protocol routes extend the configured path prefix. Response URLs resolve from the request URL. */
52
+ export function joinEndpoint(base, route) {
53
+ const path = String(route || '').trim();
54
+ const root = String(base || '').trim().replace(/\/+$/, '');
55
+ if (!path || /^https?:\/\//i.test(path) || !root) return path;
56
+ const [withoutHash] = root.split('#');
57
+ const queryAt = withoutHash.indexOf('?');
58
+ const prefix = queryAt === -1 ? withoutHash : withoutHash.slice(0, queryAt);
59
+ const query = queryAt === -1 ? '' : withoutHash.slice(queryAt + 1);
60
+ const target = prefix.replace(/\/+$/, '') + '/' + path.replace(/^\/+/, '');
61
+ if (!query) return target;
62
+ const url = new URL(target);
63
+ const overridden = new Set(url.searchParams.keys());
64
+ for (const [key, value] of new URLSearchParams(query)) {
65
+ if (!overridden.has(key)) url.searchParams.append(key, value);
66
+ }
67
+ return url.toString();
68
+ }
69
+
70
+ export function resolveHttpUrl(value, base) {
71
+ if (typeof value !== 'string' || !value.trim()) return '';
72
+ try {
73
+ const url = new URL(value.trim(), base || undefined);
74
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return '';
75
+ url.hash = '';
76
+ return url.href;
77
+ } catch (_error) { return ''; }
78
+ }
79
+
80
+ /* --------------------------------------------------------------- 鉴权方式 */
81
+
82
+ /**
83
+ * 鉴权方式是**提供商自己的字段**(`provider.auth`),不是协议级选项。
84
+ *
85
+ * 维度为什么分开:鉴权回答「这个地址怎么认证」,协议回答「说哪种话」。挂在协议下面时,
86
+ * 切到没声明 auth 的协议(ComfyUI / 百炼 / Gemini …)下拉就消失了,而「本地 ComfyUI 前面
87
+ * 挂了反代、要带 X-API-Key」这种场景照样存在。所以它跟着 provider 走,任何协议下都能设。
88
+ *
89
+ * `adapter.authHeader` 保留为该协议的**默认值**:provider.auth 没设(或认不出)时回落到它,
90
+ * 所以老配置(provider 上没有 auth 字段)行为一字不变。
91
+ */
92
+ export const AUTH_MODES = ['bearer', 'api-key', 'x-key', 'fal-key', 'custom', 'none', 'basic', 'query'];
93
+ const AUTH_MODE_SET = new Set(AUTH_MODES);
94
+ /** HTTP 头名:字母 / 数字 / 连字符,最长 64。够覆盖 X-API-Key、x-goog-api-key 这类写法。 */
95
+ export const AUTH_HEADER_PATTERN = /^[A-Za-z0-9-]{1,64}$/;
96
+ /** 前缀(`Bearer ` / `Token ` / 空)的长度上限;空串与「没写」等价。 */
97
+ export const AUTH_PREFIX_MAX = 64;
98
+
99
+ /**
100
+ * 校验并归一 `provider.auth`;认不出返回 null(= 用户没设,走协议默认)。
101
+ *
102
+ * 这是全套校验的唯一出口:配置落盘(config-store)与出站请求(authHeaders)都用它,
103
+ * 免得「存进去的和发出去的不是一个判据」。老形状的字符串(`auth: 'api-key'`)不收——
104
+ * provider.auth 是新字段,没有老形状要兼容;老配置的 `protocolOptions.auth` 由
105
+ * config-store 迁移时转成这个对象。
106
+ */
107
+ export function normalizeAuthSpec(raw) {
108
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
109
+ const mode = String(raw.mode || '').trim().toLowerCase();
110
+ if (!AUTH_MODE_SET.has(mode)) return null;
111
+ if (mode === 'query') {
112
+ const name = typeof raw.name === 'string' ? raw.name.trim() : '';
113
+ return /^[A-Za-z0-9_.~-]{1,64}$/.test(name) ? { mode, name } : null;
114
+ }
115
+ if (mode !== 'custom') return { mode: mode };
116
+ const header = typeof raw.header === 'string' ? raw.header.trim() : '';
117
+ // custom 没有合法头名就不是一条可用的 custom:宁可回落,也不要发出一个坏请求头。
118
+ if (!AUTH_HEADER_PATTERN.test(header) || /^(?:host|cookie|set-cookie|content-length|content-type|transfer-encoding|connection|upgrade|proxy-.+)$/i.test(header)) return null;
119
+ const out = { mode: mode, header: header };
120
+ // 前缀原样拼在 key 前面(`Bearer ` 结尾的空格有意义,所以不 trim);只挡控制字符。
121
+ const prefix = typeof raw.prefix === 'string'
122
+ ? raw.prefix.replace(/[\u0000-\u001F\u007F]/g, '').slice(0, AUTH_PREFIX_MAX)
123
+ : '';
124
+ if (prefix) out.prefix = prefix;
125
+ return out;
54
126
  }
55
127
 
56
- /** 按适配器声明的鉴权方式生成头;默认 Bearer。 */
128
+ /** 这次请求实际用的鉴权形态:provider.auth > 协议默认(adapter.authHeader)> bearer。 */
129
+ export function authSpecOf(provider, adapter) {
130
+ const declared = normalizeAuthSpec(provider && provider.auth);
131
+ if (declared) return declared;
132
+ const native = normalizeAuthSpec(adapter && adapter.defaultAuth);
133
+ if (native) return native;
134
+ const fallback = String((adapter && adapter.authHeader) || '').trim().toLowerCase();
135
+ return { mode: AUTH_MODE_SET.has(fallback) && fallback !== 'custom' ? fallback : 'bearer' };
136
+ }
137
+
138
+ /** 按 provider.auth 生成本次请求的鉴权头;没设就回落到协议的默认形态。 */
57
139
  export function authHeaders(provider, adapter) {
58
140
  const key = String((provider && provider.key) || '').trim();
59
141
  if (!key) return {};
60
- const type = String((adapter && adapter.authHeader) || 'bearer');
61
- if (type === 'api-key') return { 'api-key': key };
62
- if (type === 'x-key') return { 'x-key': key };
63
- if (type === 'fal-key') return { Authorization: 'Key ' + key };
142
+ const spec = authSpecOf(provider, adapter);
143
+ if (spec.mode === 'none' || spec.mode === 'query') return {};
144
+ if (spec.mode === 'basic') return { Authorization: 'Basic ' + Buffer.from(key).toString('base64') };
145
+ if (spec.mode === 'api-key') return { 'api-key': key };
146
+ if (spec.mode === 'x-key') return { 'x-key': key };
147
+ if (spec.mode === 'fal-key') return { Authorization: 'Key ' + key };
148
+ if (spec.mode === 'custom') return { [spec.header]: (spec.prefix || '') + key };
64
149
  return { Authorization: 'Bearer ' + key };
65
150
  }
66
151
 
67
152
  export function headersFor(provider, multipart, extra, adapter) {
68
- const headers = Object.assign({}, extra || {}, authHeaders(provider, adapter));
153
+ const auth = authHeaders(provider, adapter);
154
+ const headerName = authHeaderNameOf(provider, adapter).toLowerCase();
155
+ const headers = Object.fromEntries(Object.entries(extra || {}).filter(([name]) => name.toLowerCase() !== headerName));
156
+ Object.assign(headers, auth);
69
157
  if (!multipart && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
70
158
  return headers;
71
159
  }
72
160
 
73
- export function keyedHeaders(provider, name, multipart) {
161
+ /** Add query credentials at dispatch time, after the caller has selected a trusted target. */
162
+ export function authenticatedUrl(url, provider, adapter) {
163
+ const spec = authSpecOf(provider, adapter);
74
164
  const key = String((provider && provider.key) || '').trim();
75
- return headersFor(Object.assign({}, provider, { key: '' }), multipart, key ? { [name]: key } : {});
165
+ if (spec.mode !== 'query' || !key) return url;
166
+ const target = new URL(url);
167
+ target.searchParams.set(spec.name, key);
168
+ return target.href;
169
+ }
170
+
171
+ export function authHeaderNameOf(provider, adapter) {
172
+ const spec = authSpecOf(provider, adapter);
173
+ if (spec.mode === 'custom') return spec.header;
174
+ if (spec.mode === 'api-key' || spec.mode === 'x-key') return spec.mode;
175
+ return spec.mode === 'none' || spec.mode === 'query' ? '' : 'authorization';
176
+ }
177
+
178
+ /** Cache metadata only within the same effective authentication scope. */
179
+ export function credentialRef(provider, adapter) {
180
+ const auth = authSpecOf(provider, adapter);
181
+ const key = auth.mode === 'none' ? '' : String(provider?.key || '').trim();
182
+ return createHash('sha256').update(JSON.stringify([auth, key])).digest('hex');
76
183
  }
77
184
 
78
185
  export function sleep(ms) {
@@ -84,7 +191,7 @@ export function dataUrlOf(image) {
84
191
  return 'data:' + image.contentType + ';base64,' + image.buffer.toString('base64');
85
192
  }
86
193
 
87
- export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
194
+ export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024, provider, adapter) {
88
195
  const buffer = await readResponseBytes(response, maxBytes);
89
196
  const text = buffer.toString('utf8');
90
197
  if (!response.ok) {
@@ -96,6 +203,7 @@ export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
96
203
  } catch (_error) {
97
204
  detail = text.slice(0, 300);
98
205
  }
206
+ detail = credentialText(detail, provider, adapter).slice(0, 600);
99
207
  throw localizedError(
100
208
  new Error('本地生图服务返回 HTTP ' + response.status + (detail ? ':' + detail : '')),
101
209
  detail ? 'upstream.http' : 'upstream.httpNoDetail',
@@ -117,28 +225,147 @@ export function getPath(node, path) {
117
225
  if (!path) return node;
118
226
  let current = node;
119
227
  for (const key of String(path).split('.')) {
120
- if (current === null || current === undefined) return null;
228
+ if (current === null || current === undefined || !Object.hasOwn(current, key)) return null;
121
229
  current = current[key];
122
230
  }
123
231
  return current === undefined ? null : current;
124
232
  }
125
233
 
234
+ export function credentialText(text, provider, adapter) {
235
+ const key = String(provider?.key || '').trim();
236
+ const value = String(text || '');
237
+ if (!key) return value;
238
+ const variants = new Set([key, encodeURIComponent(key), new URLSearchParams({ k: key }).toString().slice(2)]);
239
+ if (authSpecOf(provider, adapter).mode === 'basic') variants.add(Buffer.from(key).toString('base64'));
240
+ return [...variants].reduce((result, secret) => result.includes(secret) && (secret.length >= 4 || result === secret)
241
+ ? result.split(secret).join('[redacted]') : result, value);
242
+ }
243
+
244
+ /** 统一成可安全读写的 Buffer;其它类型(包括 Uint8Array 视图)也兼容。 */
245
+ function asBuffer(value) {
246
+ if (Buffer.isBuffer(value)) return value;
247
+ if (value instanceof Uint8Array) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
248
+ return null;
249
+ }
250
+
251
+ function asciiAt(buffer, offset, text) {
252
+ return buffer.length >= offset + text.length
253
+ && buffer.toString('ascii', offset, offset + text.length) === text;
254
+ }
255
+
256
+ function pngSizeOf(buffer) {
257
+ if (!isPng(buffer)) return null;
258
+ const header = pngHeaderOf(buffer);
259
+ return header ? { width: header.width, height: header.height } : null;
260
+ }
261
+
262
+ function gifSizeOf(buffer) {
263
+ // 6 字节签名 + 7 字节逻辑屏幕描述符;不足就连宽高都读不到。
264
+ if (buffer.length < 13) return null;
265
+ if (!asciiAt(buffer, 0, 'GIF87a') && !asciiAt(buffer, 0, 'GIF89a')) return null;
266
+ const width = buffer.readUInt16LE(6);
267
+ const height = buffer.readUInt16LE(8);
268
+ return width > 0 && height > 0 ? { width: width, height: height } : null;
269
+ }
270
+
271
+ function webpSizeOf(buffer) {
272
+ // RIFF 头 12 字节 + 首块头 8 字节。
273
+ if (buffer.length < 20) return null;
274
+ if (!asciiAt(buffer, 0, 'RIFF') || !asciiAt(buffer, 8, 'WEBP')) return null;
275
+ const riffSize = buffer.readUInt32LE(4);
276
+ // 有些来源只写首块头、把 riffSize 留成 0,按未声明处理;
277
+ // 一旦声明就必须让容器落在 buffer 内,截断的图不能再当有效图片。
278
+ if (riffSize !== 0 && (riffSize < 12 || riffSize > buffer.length - 8)) return null;
279
+ const chunkSize = buffer.readUInt32LE(16);
280
+ if (chunkSize !== 0 && chunkSize > buffer.length - 20) return null;
281
+ const chunk = buffer.toString('ascii', 12, 16);
282
+ if (chunk === 'VP8 ') {
283
+ if (buffer.length < 30) return null;
284
+ const width = buffer.readUInt16LE(26) & 0x3fff;
285
+ const height = buffer.readUInt16LE(28) & 0x3fff;
286
+ return width > 0 && height > 0 ? { width: width, height: height } : null;
287
+ }
288
+ if (chunk === 'VP8L') {
289
+ if (buffer.length < 25) return null;
290
+ const bits = buffer.readUInt32LE(21);
291
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
292
+ }
293
+ if (chunk === 'VP8X') {
294
+ if (buffer.length < 30) return null;
295
+ const width = (buffer[24] | (buffer[25] << 8) | (buffer[26] << 16)) + 1;
296
+ const height = (buffer[27] | (buffer[28] << 8) | (buffer[29] << 16)) + 1;
297
+ return { width: width, height: height };
298
+ }
299
+ return null;
300
+ }
301
+
302
+ function isSofMarker(marker) {
303
+ return (marker >= 0xc0 && marker <= 0xc3)
304
+ || (marker >= 0xc5 && marker <= 0xc7)
305
+ || (marker >= 0xc9 && marker <= 0xcb)
306
+ || (marker >= 0xcd && marker <= 0xcf);
307
+ }
308
+
309
+ function jpegSizeOf(buffer) {
310
+ if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
311
+ let offset = 2;
312
+ while (offset + 4 <= buffer.length) {
313
+ if (buffer[offset] !== 0xff) { offset++; continue; }
314
+ const marker = buffer[offset + 1];
315
+ if (marker === 0xff) { offset++; continue; } // 填充字节
316
+ if (marker === 0x00) { offset += 2; continue; } // 扫描数据里的转义
317
+ if (marker === 0xd8 || marker === 0xd9 || marker === 0x01
318
+ || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
319
+ if (marker === 0xda) return null; // 都到扫描数据了还没见 SOF
320
+ const length = buffer.readUInt16BE(offset + 2);
321
+ if (length < 2) return null;
322
+ // 整段必须落在 buffer 内:只够读宽高、段尾却被截断的 JPEG 仍是坏图。
323
+ const next = offset + 2 + length;
324
+ if (next > buffer.length) return null;
325
+ if (isSofMarker(marker)) {
326
+ // SOF 段头至少要覆盖精度、高、宽和分量数;不足就当作截断。
327
+ if (length < 8 || offset + 9 > buffer.length) return null;
328
+ const height = buffer.readUInt16BE(offset + 5);
329
+ const width = buffer.readUInt16BE(offset + 7);
330
+ return width > 0 && height > 0 ? { width: width, height: height } : null;
331
+ }
332
+ offset = next;
333
+ }
334
+ return null;
335
+ }
336
+
337
+ /**
338
+ * 从文件头读出真实宽高(不解码整张图)。
339
+ * PNG / JPEG / WebP / GIF 足够覆盖各家回图;结构不完整或认不出返回 null。
340
+ */
341
+ export function imageSizeOf(buffer) {
342
+ const bytes = asBuffer(buffer);
343
+ if (!bytes) return null;
344
+ try {
345
+ if (isPng(bytes)) return pngSizeOf(bytes);
346
+ const gif = gifSizeOf(bytes);
347
+ if (gif) return gif;
348
+ const webp = webpSizeOf(bytes);
349
+ if (webp) return webp;
350
+ return jpegSizeOf(bytes);
351
+ } catch (_error) {
352
+ return null;
353
+ }
354
+ }
355
+
126
356
  export function sniffType(buffer) {
127
- if (!buffer || buffer.length < 12) return 'image/png';
128
- if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return 'image/png';
129
- if (buffer[0] === 0xff && buffer[1] === 0xd8) return 'image/jpeg';
130
- if (buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP') return 'image/webp';
131
- if (buffer.slice(0, 3).toString('ascii') === 'GIF') return 'image/gif';
357
+ const bytes = asBuffer(buffer);
358
+ if (!bytes) return 'image/png';
359
+ if (isPng(bytes)) return 'image/png';
360
+ if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg';
361
+ if (asciiAt(bytes, 0, 'RIFF') && asciiAt(bytes, 8, 'WEBP')) return 'image/webp';
362
+ if (asciiAt(bytes, 0, 'GIF87a') || asciiAt(bytes, 0, 'GIF89a')) return 'image/gif';
132
363
  return 'image/png';
133
364
  }
134
365
 
366
+ /** 只有能读出合法宽高的文件头才算图片;截断内容不能混进参考图或下载结果。 */
135
367
  export function looksLikeImage(buffer) {
136
- if (!buffer || buffer.length < 8) return false;
137
- const type = sniffType(buffer);
138
- if (type === 'image/png') return buffer[0] === 0x89 && buffer[1] === 0x50;
139
- if (type === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8;
140
- if (type === 'image/webp') return buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP';
141
- return buffer.slice(0, 3).toString('ascii') === 'GIF';
368
+ return imageSizeOf(buffer) !== null;
142
369
  }
143
370
 
144
371
  export function base64ToImage(text) {
@@ -248,12 +475,34 @@ export async function readResponseBytes(response, maxBytes) {
248
475
 
249
476
  export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
250
477
 
251
- export async function fetchImageUrl(url, signal, maxBytes = MAX_IMAGE_BYTES) {
252
- const response = await request(url, { signal: signal });
253
- if (!response.ok) throw new Error('下载生成图失败:HTTP ' + response.status);
254
- const bytes = await readResponseBytes(response, maxBytes);
255
- if (!looksLikeImage(bytes)) throw new Error('下载生成图失败:返回内容不是有效图片');
256
- return { bytes: bytes, contentType: sniffType(bytes) };
478
+ /* ---------------------------------------------------------- 结果图下载 */
479
+ /*
480
+ * 结果图(data[0].url / output[].url / CDN 链接)**只有一个下载入口**:
481
+ * lib/request-auth.js 的 fetchResultImage()。它按目标域决定带不带凭据——
482
+ * 同源带、跨源默认不带、适配器声明过的 resultAuthOrigins 才带。
483
+ *
484
+ * 这里原本还有一个「裸下载」的 fetchImageUrl(),被 12 条走 execute() 的协议用着;
485
+ * 同一个 data[0].url 在 execute() 路径上不带鉴权、在异步/通用路径上带,二义性就出在这。
486
+ * 现在两条路径都走 fetchResultImage(),判定只有一份(downloadRequestHeaders)。 */
487
+
488
+ /** 从对象/数组里深挖第一句可读文本(message / detail / error / errors …)。 */
489
+ export function errorTextOf(value, depth = 0) {
490
+ if (depth > 4 || value === null || value === undefined) return '';
491
+ if (typeof value === 'string') return value.trim();
492
+ if (Array.isArray(value)) {
493
+ for (const item of value) {
494
+ const text = errorTextOf(item, depth + 1);
495
+ if (text) return text;
496
+ }
497
+ return '';
498
+ }
499
+ if (typeof value !== 'object') return '';
500
+ for (const key of ['message', 'msg', 'detail', 'error', 'errors', 'reason', 'logs', 'fail_reason', 'error_message']) {
501
+ if (value[key] === undefined) continue;
502
+ const text = errorTextOf(value[key], depth + 1);
503
+ if (text) return text;
504
+ }
505
+ return '';
257
506
  }
258
507
 
259
508
  export function extractMessage(text) {
@@ -304,15 +553,15 @@ function extractErrorParam(text) {
304
553
  */
305
554
  export function classifyFailure(status, text) {
306
555
  const message = extractMessage(text) || ('HTTP ' + status);
556
+ if (status === 401 || status === 403) return { kind: 'auth', message: message };
557
+ if (status === 404 || status === 405) return { kind: 'endpoint', message: message };
558
+ if (status === 413) return { kind: 'payload', message: message };
559
+ if (status === 429) return { kind: 'rate', message: message, retryable: true };
560
+ if (status === 408 || status >= 500) return { kind: 'upstream', message: message, retryable: true };
307
561
  const drop = detectDroppableField(message) || extractErrorParam(text);
308
562
  if (drop) return { kind: 'param', drop: drop, message: message };
309
563
  if (/size/i.test(message) && /(invalid|unsupported|below|minimum|maximum|too small|too large|budget)/i.test(message)) {
310
564
  return { kind: 'size', message: message };
311
565
  }
312
- if (status === 401 || status === 403) return { kind: 'auth', message: message };
313
- if (status === 404) return { kind: 'endpoint', message: message };
314
- if (status === 413) return { kind: 'payload', message: message };
315
- if (status === 429) return { kind: 'rate', message: message, retryable: true };
316
- if (status >= 500) return { kind: 'upstream', message: message, retryable: true };
317
566
  return { kind: 'unknown', message: message };
318
567
  }