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.
- package/CHANGELOG.md +39 -0
- package/README.md +328 -55
- package/icon.png +0 -0
- package/lib/adapter-kit.js +289 -40
- package/lib/adapters/async.js +354 -140
- package/lib/adapters/cn.js +133 -68
- package/lib/adapters/openai.js +193 -143
- package/lib/adapters.js +3579 -695
- package/lib/client.js +6742 -828
- package/lib/comfy-workflow.js +100 -10
- package/lib/config-store.js +1628 -0
- package/lib/field-templates.js +385 -0
- package/lib/image-execution.js +58 -0
- package/lib/image-jobs.js +344 -0
- package/lib/image-queue.js +195 -0
- package/lib/image-request.js +830 -0
- package/lib/image-service.js +189 -0
- package/lib/image-worker.js +208 -0
- package/lib/index.js +1054 -967
- package/lib/localized-error.js +4 -0
- package/lib/model-rules.js +1034 -0
- package/lib/net.js +60 -25
- package/lib/output-profiles.js +1225 -0
- package/lib/png-scale.js +150 -68
- package/lib/prompt-profiles.js +196 -80
- package/lib/provider-operations.js +291 -0
- package/lib/proxy-dispatcher.js +11 -5
- package/lib/proxy.js +10 -8
- package/lib/request-auth.js +198 -0
- package/lib/retry.js +162 -0
- package/lib/settings-memory.js +117 -0
- package/lib/status.js +190 -0
- package/locale/messages.csv +206 -24
- package/package.json +3 -1
- package/scripts/release.mjs +79 -64
- package/skills/mo-image-editing/SKILL.md +36 -80
- package/skills/mo-image-generation/SKILL.md +62 -154
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { resolveHttpUrl } from './adapter-kit.js';
|
|
2
|
+
import { applyFields } from './field-templates.js';
|
|
3
|
+
import { DEFAULT_EMPTY_MESSAGE, outputProfile, outputProfiles } from './output-profiles.js';
|
|
4
|
+
|
|
5
|
+
const MIB = 1024 * 1024;
|
|
6
|
+
const METHODS = ['GET', 'POST', 'PUT', 'PATCH'];
|
|
7
|
+
const TRANSPORTS = ['json', 'multipart', 'form', 'query'];
|
|
8
|
+
const IMAGE_FIELDS = new Set(['prompt', 'negative', 'model', 'n', 'image', 'quality', 'size', 'width', 'height', 'aspect', 'tier']);
|
|
9
|
+
const NON_DATA_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
10
|
+
const ROUTE_TASK_FIELDS = {
|
|
11
|
+
statusPath: ['status', 'state'],
|
|
12
|
+
success: ['succeeded', 'success', 'completed', 'done', 'ready'],
|
|
13
|
+
failure: ['failed', 'error', 'canceled', 'cancelled'],
|
|
14
|
+
resultPath: ['output', 'result', 'images', 'url']
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const OUTPUT_PRESETS = {
|
|
18
|
+
openai: {
|
|
19
|
+
kind: 'json',
|
|
20
|
+
pick: [{ path: 'data.0.b64_json', as: 'base64' }, { path: 'data.0.url', as: 'url' }]
|
|
21
|
+
},
|
|
22
|
+
binary: { kind: 'binary' },
|
|
23
|
+
'image-url': { kind: 'json', pick: [{ path: 'image_url', as: 'url' }, { path: 'url', as: 'url' }] },
|
|
24
|
+
'image-base64': { kind: 'json', pick: [{ path: 'image', as: 'base64' }, { path: 'base64', as: 'base64' }] },
|
|
25
|
+
'task-location': {
|
|
26
|
+
kind: 'task', pollUrlFrom: 'location', ...ROUTE_TASK_FIELDS
|
|
27
|
+
},
|
|
28
|
+
'task-json': {
|
|
29
|
+
kind: 'task', idPath: ['task_id', 'job_id', 'id'], path: '/tasks/{taskId}',
|
|
30
|
+
...ROUTE_TASK_FIELDS
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function outputPresetManifest() {
|
|
35
|
+
return ['auto', ...Object.keys(OUTPUT_PRESETS)];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function plainObject(value) {
|
|
39
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
40
|
+
&& [null, Object.prototype].includes(Object.getPrototypeOf(value));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function knownKeys(raw, keys, label) {
|
|
44
|
+
if (!plainObject(raw)) throw new Error(label + ' 必须是对象');
|
|
45
|
+
for (const key of Object.keys(raw)) {
|
|
46
|
+
if (!keys.includes(key)) throw new Error(label + ' 不支持字段 ' + key);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function cleanData(value, depth = 0) {
|
|
51
|
+
if (depth > 16) throw new Error('操作配置最多嵌套 16 层');
|
|
52
|
+
if (Array.isArray(value)) return value.map((item) => cleanData(item, depth + 1));
|
|
53
|
+
if (!plainObject(value)) {
|
|
54
|
+
if (value !== null && !['string', 'number', 'boolean'].includes(typeof value)) {
|
|
55
|
+
throw new Error('操作配置只接受 JSON 数据');
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => {
|
|
60
|
+
if (NON_DATA_KEYS.has(key)) throw new Error('操作配置包含无效属性 ' + key);
|
|
61
|
+
return [key, cleanData(item, depth + 1)];
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function bound(value, from, to, name) {
|
|
66
|
+
if (!Number.isInteger(value) || value < from || value > to) {
|
|
67
|
+
throw new Error(name + ' 必须是 ' + from + ' 到 ' + to + ' 之间的整数');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function configuredOutput(raw) {
|
|
72
|
+
const source = typeof raw === 'string' && Object.hasOwn(OUTPUT_PRESETS, raw) ? OUTPUT_PRESETS[raw] : raw;
|
|
73
|
+
if (!plainObject(source)) throw new Error('请选择有效的返回格式预设或填写输出描述符');
|
|
74
|
+
const profile = { maxBytes: 32 * MIB, emptyMessage: DEFAULT_EMPTY_MESSAGE, ...source };
|
|
75
|
+
if (profile.kind === 'task') {
|
|
76
|
+
if (profile.backoff === undefined && profile.intervalMs === undefined) profile.intervalMs = 2000;
|
|
77
|
+
if (profile.failure === undefined) profile.failure = [];
|
|
78
|
+
if (profile.pollOutput === 'binary' && profile.success === undefined) profile.success = [];
|
|
79
|
+
for (const [name, value] of [
|
|
80
|
+
['intervalMs', profile.intervalMs], ['backoff.startMs', profile.backoff?.startMs], ['backoff.maxMs', profile.backoff?.maxMs],
|
|
81
|
+
['timeoutMs', profile.timeoutMs]
|
|
82
|
+
]) {
|
|
83
|
+
if (value !== undefined) bound(value, 250, 340000, name);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
bound(profile.maxBytes, 1, 64 * MIB, 'maxBytes');
|
|
87
|
+
if (profile.via) bound(profile.via.maxBytes, 1, 64 * MIB, 'via.maxBytes');
|
|
88
|
+
for (const pick of [...(Array.isArray(profile.pick) ? profile.pick : []), ...(Array.isArray(profile.from) ? profile.from : [])]) {
|
|
89
|
+
if (pick?.text !== undefined) throw new Error('自定义输出请使用字段路径。文本正则由内置预设提供');
|
|
90
|
+
}
|
|
91
|
+
return outputProfile(profile, '自定义返回格式');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function resolveConfiguredOutput(raw, fallback) {
|
|
95
|
+
if (raw === undefined || raw === 'auto') return fallback;
|
|
96
|
+
if (!Array.isArray(raw)) return configuredOutput(raw);
|
|
97
|
+
if (raw.length > 8) throw new Error('最多配置 8 个返回格式候选');
|
|
98
|
+
return outputProfiles(raw.map(configuredOutput), '自定义返回格式');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function operationOutputOf(raw, fallback) {
|
|
102
|
+
return parsedOutput(raw) || fallback;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function staticHeaders(raw) {
|
|
106
|
+
if (!plainObject(raw)) throw new Error('headers 必须是对象');
|
|
107
|
+
const entries = Object.entries(raw);
|
|
108
|
+
if (entries.length > 16) throw new Error('每项操作最多配置 16 个请求头');
|
|
109
|
+
for (const [name, value] of entries) {
|
|
110
|
+
if (!/^[A-Za-z0-9-]{1,64}$/.test(name)
|
|
111
|
+
|| /^(?:authorization|proxy-|cookie|host|connection|content-length|transfer-encoding|content-type)|(?:token|secret|api-?key)/i.test(name)
|
|
112
|
+
|| typeof value !== 'string' || value.length > 1024 || /[\x00-\x1F\x7F]/.test(value)) {
|
|
113
|
+
throw new Error('无效的操作请求头 ' + name + '。凭据请在鉴权方式中设置');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return raw;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function originsOf(raw, label) {
|
|
120
|
+
if (!Array.isArray(raw) || raw.length > 8) throw new Error(label + ' 最多接受 8 个 HTTP(S) 源');
|
|
121
|
+
return [...new Set(raw.map((entry) => {
|
|
122
|
+
const url = resolveHttpUrl(entry);
|
|
123
|
+
if (!url || url !== new URL(url).origin + '/') throw new Error(label + ' 必须使用完整的 HTTP(S) 源');
|
|
124
|
+
return new URL(url).origin;
|
|
125
|
+
}))];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function modelListOutput(raw) {
|
|
129
|
+
knownKeys(raw, ['path', 'idPath', 'namePath'], '模型列表返回格式');
|
|
130
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
131
|
+
if (typeof value !== 'string' || value.length > 256 || (key === 'namePath' && !value.trim())) {
|
|
132
|
+
throw new Error('模型列表字段路径无效');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return raw;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function validateFields(fields) {
|
|
139
|
+
if (!plainObject(fields)) throw new Error('fields 必须是对象');
|
|
140
|
+
for (const [name, spec] of Object.entries(fields)) {
|
|
141
|
+
if (!IMAGE_FIELDS.has(name)) throw new Error('未知的输入字段 ' + name);
|
|
142
|
+
if (spec !== null && spec !== false && !plainObject(spec)) throw new Error(name + ' 需要字段映射或 null');
|
|
143
|
+
}
|
|
144
|
+
applyFields({}, fields, {});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Validate interactions after provider and model settings have been merged. */
|
|
148
|
+
export function validateOperationTransport(kind, operation, transport) {
|
|
149
|
+
if (operation.method === 'GET' && transport !== 'query') throw new Error('GET 操作必须使用 query 传输');
|
|
150
|
+
for (const [name, spec] of Object.entries(operation.fields || {})) {
|
|
151
|
+
if (!spec) continue;
|
|
152
|
+
if (spec.multipart && (transport !== 'multipart' || (name === 'image' && kind !== 'edit'))) {
|
|
153
|
+
throw new Error(name + ' 的 multipart 映射与操作的传输方式不符');
|
|
154
|
+
}
|
|
155
|
+
if (name === 'image' && (kind !== 'edit' || (transport === 'multipart' && !spec.multipart)
|
|
156
|
+
|| (!spec.multipart && !spec.as))) {
|
|
157
|
+
throw new Error('参考图字段映射与编辑操作的传输方式不符');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Versioned data shared by saved providers, model overrides, and unsaved connection tests. */
|
|
163
|
+
export function normalizeOperations(raw, modelOnly = false) {
|
|
164
|
+
if (raw === undefined || raw === null) return undefined;
|
|
165
|
+
const label = '操作配置';
|
|
166
|
+
if (JSON.stringify(raw).length > 64 * 1024) throw new Error(label + ' 超过大小限制');
|
|
167
|
+
const config = cleanData(raw);
|
|
168
|
+
knownKeys(config, modelOnly ? ['version', 'generate', 'edit'] : ['version', 'generate', 'edit', 'models'], label);
|
|
169
|
+
if (config.version !== undefined && config.version !== 1) throw new Error('暂不支持此操作配置版本');
|
|
170
|
+
for (const kind of ['generate', 'edit', 'models']) {
|
|
171
|
+
const operation = config[kind];
|
|
172
|
+
if (operation === undefined) continue;
|
|
173
|
+
const models = kind === 'models';
|
|
174
|
+
knownKeys(operation, models
|
|
175
|
+
? ['path', 'method', 'body', 'headers', 'output']
|
|
176
|
+
: ['path', 'method', 'transport', 'input', 'body', 'fields', 'headers', 'output', 'pollOrigins', 'resultOrigins',
|
|
177
|
+
'pollHeaders', 'pollNotFoundPending', ...(kind === 'edit' ? ['maxImages', 'imageTypes'] : [])], kind);
|
|
178
|
+
if (operation.path !== undefined) {
|
|
179
|
+
if (typeof operation.path !== 'string' || operation.path.length > 2048) throw new Error(kind + ' 的 path 无效');
|
|
180
|
+
operation.path = operation.path.trim();
|
|
181
|
+
if (/^\/\//.test(operation.path) || /^(?!https?:)[a-z][a-z\d+.-]*:/i.test(operation.path)
|
|
182
|
+
|| /^https?:/i.test(operation.path) && !resolveHttpUrl(operation.path)) {
|
|
183
|
+
throw new Error(kind + ' 的 path 需要 HTTP(S) 地址或相对路径');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (operation.method !== undefined && !METHODS.includes(operation.method)) throw new Error(kind + ' 的 HTTP 方法无效');
|
|
187
|
+
if (operation.transport !== undefined && !TRANSPORTS.includes(operation.transport)) throw new Error(kind + ' 的传输方式无效');
|
|
188
|
+
if (operation.input !== undefined && !['inherit', 'explicit'].includes(operation.input)) throw new Error(kind + ' 的 input 无效');
|
|
189
|
+
if (operation.maxImages !== undefined
|
|
190
|
+
&& (!Number.isInteger(operation.maxImages) || operation.maxImages < 1 || operation.maxImages > 16)) {
|
|
191
|
+
throw new Error('edit.maxImages 需要 1–16 的整数');
|
|
192
|
+
}
|
|
193
|
+
if (operation.imageTypes !== undefined) {
|
|
194
|
+
const types = operation.imageTypes;
|
|
195
|
+
if (!Array.isArray(types) || !types.length || types.length > 16
|
|
196
|
+
|| types.some((type) => typeof type !== 'string' || !/^image\/[a-z0-9.+-]+$/.test(type))) {
|
|
197
|
+
throw new Error('edit.imageTypes 需要填写支持的图片 MIME 类型');
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (operation.fields !== undefined) validateFields(operation.fields);
|
|
201
|
+
if (operation.headers !== undefined) operation.headers = staticHeaders(operation.headers);
|
|
202
|
+
if (operation.pollHeaders !== undefined) operation.pollHeaders = staticHeaders(operation.pollHeaders);
|
|
203
|
+
if (operation.pollNotFoundPending !== undefined && typeof operation.pollNotFoundPending !== 'boolean') {
|
|
204
|
+
throw new Error('pollNotFoundPending 必须是布尔值');
|
|
205
|
+
}
|
|
206
|
+
if (operation.body !== undefined && !plainObject(operation.body)) throw new Error(kind + ' 的 body 必须是 JSON 对象');
|
|
207
|
+
if (models && operation.body !== undefined && (!operation.method || operation.method === 'GET')) throw new Error('GET 模型列表使用端点查询参数');
|
|
208
|
+
if (modelOnly && operation.output === 'auto') {
|
|
209
|
+
// Legacy model-level Auto inherits the provider format. Provider-level Auto
|
|
210
|
+
// still selects the protocol default.
|
|
211
|
+
delete operation.output;
|
|
212
|
+
if (!Object.keys(operation).length) delete config[kind];
|
|
213
|
+
} else if (operation.output !== undefined) {
|
|
214
|
+
if (models) modelListOutput(operation.output);
|
|
215
|
+
else resolveConfiguredOutput(operation.output);
|
|
216
|
+
}
|
|
217
|
+
for (const key of ['pollOrigins', 'resultOrigins']) {
|
|
218
|
+
if (operation[key] !== undefined) operation[key] = originsOf(operation[key], key);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { ...config, version: 1 };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Built-ins keep their request dialect and can opt into a different response format. */
|
|
225
|
+
export function normalizeResponseOverrides(raw, modelOnly = false) {
|
|
226
|
+
const operations = normalizeOperations(raw, modelOnly);
|
|
227
|
+
if (!operations) return operations;
|
|
228
|
+
if (operations.models) throw new Error('此协议使用内置模型列表格式');
|
|
229
|
+
for (const entry of [operations.generate, operations.edit]) {
|
|
230
|
+
if (entry) knownKeys(entry, ['output'], '内置协议的返回格式');
|
|
231
|
+
}
|
|
232
|
+
return operations;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const outputCache = new WeakMap();
|
|
236
|
+
const presetCache = new Map();
|
|
237
|
+
|
|
238
|
+
function parsedOutput(raw) {
|
|
239
|
+
if (raw === 'auto' || raw === undefined) return undefined;
|
|
240
|
+
if (typeof raw === 'string') {
|
|
241
|
+
if (!presetCache.has(raw)) presetCache.set(raw, resolveConfiguredOutput(raw));
|
|
242
|
+
return presetCache.get(raw);
|
|
243
|
+
}
|
|
244
|
+
if (!raw || typeof raw !== 'object') return resolveConfiguredOutput(raw);
|
|
245
|
+
let result = outputCache.get(raw);
|
|
246
|
+
if (!result) {
|
|
247
|
+
result = resolveConfiguredOutput(raw);
|
|
248
|
+
outputCache.set(raw, result);
|
|
249
|
+
}
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function responseOverridesOf(provider, model) {
|
|
254
|
+
const defaults = provider?.operations;
|
|
255
|
+
const override = provider?.modelOptions?.[model]?.operations;
|
|
256
|
+
if (!defaults && !override) return null;
|
|
257
|
+
const base = compiledOperations(defaults, 'responses');
|
|
258
|
+
const settings = compiledOperations(override, 'model-responses');
|
|
259
|
+
return {
|
|
260
|
+
generate: parsedOutput(settings.generate?.output ?? base.generate?.output),
|
|
261
|
+
edit: parsedOutput(settings.edit?.output ?? base.edit?.output)
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function providerOperationsOf(provider, model) {
|
|
266
|
+
const base = compiledOperations(provider?.operations, 'operations');
|
|
267
|
+
const override = compiledOperations(provider?.modelOptions?.[model]?.operations, 'model-operations');
|
|
268
|
+
return Object.fromEntries(['generate', 'edit', 'models'].flatMap((kind) => {
|
|
269
|
+
if (!base[kind] && !override[kind]) return [];
|
|
270
|
+
const entry = { ...base[kind], ...override[kind] };
|
|
271
|
+
if (base[kind]?.fields || override[kind]?.fields) entry.fields = { ...base[kind]?.fields, ...override[kind]?.fields };
|
|
272
|
+
return [[kind, entry]];
|
|
273
|
+
}));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function assertReferenceCount(operation, count) {
|
|
277
|
+
if (operation?.maxImages && count > operation.maxImages) {
|
|
278
|
+
throw new Error('此编辑接口最多接受 ' + operation.maxImages + ' 张参考图,当前 ' + count + ' 张。');
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const compiled = new WeakMap();
|
|
283
|
+
|
|
284
|
+
function compiledOperations(raw, scope) {
|
|
285
|
+
const modelOnly = scope.startsWith('model-');
|
|
286
|
+
const normalize = scope.endsWith('responses') ? normalizeResponseOverrides : normalizeOperations;
|
|
287
|
+
if (!plainObject(raw)) return normalize(raw, modelOnly) || {};
|
|
288
|
+
let cache = compiled.get(raw);
|
|
289
|
+
if (!cache) compiled.set(raw, cache = {});
|
|
290
|
+
return cache[scope] ||= normalize(raw, modelOnly);
|
|
291
|
+
}
|
package/lib/proxy-dispatcher.js
CHANGED
|
@@ -15,11 +15,17 @@ const NO_BODY = Symbol('no-body');
|
|
|
15
15
|
|
|
16
16
|
function parseProxyUrl(proxyUrl) {
|
|
17
17
|
let url;
|
|
18
|
-
try { url = new URL(String(proxyUrl || '')); } catch (_error) { throw new Error('
|
|
19
|
-
if (url.protocol !== 'http:') throw new Error('
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
try { url = new URL(String(proxyUrl || '')); } catch (_error) { throw new Error('代理地址格式无效'); }
|
|
19
|
+
if (url.protocol !== 'http:') throw new Error('代理地址必须使用 http://');
|
|
20
|
+
let auth = '';
|
|
21
|
+
if (url.username) {
|
|
22
|
+
try {
|
|
23
|
+
const credentials = decodeURIComponent(url.username) + ':' + decodeURIComponent(url.password);
|
|
24
|
+
auth = 'Basic ' + Buffer.from(credentials).toString('base64');
|
|
25
|
+
} catch (_error) {
|
|
26
|
+
throw new Error('代理认证信息编码无效');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
23
29
|
return {
|
|
24
30
|
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
25
31
|
port: Number(url.port) || 80,
|
package/lib/proxy.js
CHANGED
|
@@ -13,14 +13,16 @@ function normalizeProxySpec(spec) {
|
|
|
13
13
|
const raw = String(spec || '').trim();
|
|
14
14
|
if (!raw) return undefined;
|
|
15
15
|
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : 'http://' + raw;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
try {
|
|
17
|
+
const url = new URL(withScheme);
|
|
18
|
+
if (url.protocol !== 'http:' || !url.hostname) return undefined;
|
|
19
|
+
const auth = url.username
|
|
20
|
+
? encodeURIComponent(decodeURIComponent(url.username)) + ':' + encodeURIComponent(decodeURIComponent(url.password || '')) + '@'
|
|
21
|
+
: '';
|
|
22
|
+
return 'http://' + auth + url.host;
|
|
23
|
+
} catch (_error) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
/**
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 出站请求的凭据收敛:轮询与结果下载各自决定「能不能带鉴权头」。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要单独一层:提交地址是用户配置的提供商,轮询地址和结果地址却常常来自上游响应
|
|
5
|
+
* (polling_url / status_url / urls.get)或 CDN。把提交用的 Key 原样带到这些地址,
|
|
6
|
+
* 等于把凭据发给任何上游指定过的主机。这里只按目标域判断,不看响应内容。
|
|
7
|
+
*
|
|
8
|
+
* 结果图下载**只有 fetchResultImage() 一个入口**:12 条走 execute() 的协议、
|
|
9
|
+
* 异步轮询、通用 composeBody 路径全部走它。别在别处再写一个「拿 URL 直接 GET」的
|
|
10
|
+
* 下载函数——同一个 data[0].url 在两条路径上带不带 Key 不一致,就是这么来的。
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
MAX_IMAGE_BYTES, authenticatedUrl, authHeaderNameOf, authHeaders, authSpecOf, baseUrlOf, looksLikeImage, readResponseBytes,
|
|
14
|
+
resolveHttpUrl, sniffType
|
|
15
|
+
} from './adapter-kit.js';
|
|
16
|
+
import { request } from './net.js';
|
|
17
|
+
|
|
18
|
+
function parseUrl(value) {
|
|
19
|
+
const url = resolveHttpUrl(value);
|
|
20
|
+
return url ? new URL(url) : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function baseUrlOfProvider(provider) {
|
|
24
|
+
return baseUrlOf(provider) || String((provider && provider.baseUrl) || '');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function plainHeaders(value) {
|
|
28
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
|
29
|
+
const out = {};
|
|
30
|
+
for (const key of Object.keys(value)) {
|
|
31
|
+
const header = value[key];
|
|
32
|
+
if (header === undefined || header === null) continue;
|
|
33
|
+
out[key] = String(header);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 声明列表既接受 origin(https://poll.test),也接受 hostname(poll.test)。 */
|
|
39
|
+
function isDeclaredTarget(entries, target) {
|
|
40
|
+
if (!Array.isArray(entries)) return false;
|
|
41
|
+
const host = target.host.toLowerCase();
|
|
42
|
+
const hostname = target.hostname.toLowerCase();
|
|
43
|
+
for (const raw of entries) {
|
|
44
|
+
let entry = String(raw || '').trim().toLowerCase();
|
|
45
|
+
if (!entry) continue;
|
|
46
|
+
if (/^https?:\/\//.test(entry)) {
|
|
47
|
+
let parsed = null;
|
|
48
|
+
try { parsed = new URL(entry); } catch (_error) { parsed = null; }
|
|
49
|
+
if (parsed && parsed.origin === target.origin) return true;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (entry.startsWith('*.')) entry = entry.slice(2);
|
|
53
|
+
else if (entry.startsWith('.')) entry = entry.slice(1);
|
|
54
|
+
if (entry === host || entry === hostname) return true;
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function pollTrustOrigins(adapter) {
|
|
60
|
+
const out = [];
|
|
61
|
+
if (adapter && Array.isArray(adapter.pollOrigins)) out.push(...adapter.pollOrigins);
|
|
62
|
+
if (adapter && adapter.async && typeof adapter.async === 'object' && Array.isArray(adapter.async.trustedPollOrigins)) {
|
|
63
|
+
out.push(...adapter.async.trustedPollOrigins);
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isTrusted(adapter, provider, url, stage) {
|
|
69
|
+
const target = parseUrl(url);
|
|
70
|
+
const base = parseUrl(baseUrlOfProvider(provider));
|
|
71
|
+
if (!target || !base) return false;
|
|
72
|
+
if (target.origin === base.origin || target.origin === adapter?.operationOrigin) return true;
|
|
73
|
+
const origins = stage === 'poll' ? pollTrustOrigins(adapter) : adapter && adapter.resultAuthOrigins;
|
|
74
|
+
return isDeclaredTarget(origins, target);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 适配器自己声明的轮询头。新写法挂在适配器上(`taskPollHeaders`),老写法在 `async.pollHeaders`。
|
|
79
|
+
* 描述符(output)**不许**带 headers:一旦允许,就是给「裸请求」开一扇门。
|
|
80
|
+
*/
|
|
81
|
+
function adapterPollHeaders(adapter, provider) {
|
|
82
|
+
if (!adapter) return null;
|
|
83
|
+
const source = typeof adapter.taskPollHeaders === 'function'
|
|
84
|
+
? adapter.taskPollHeaders
|
|
85
|
+
: (adapter.async && typeof adapter.async === 'object' ? adapter.async.pollHeaders : null);
|
|
86
|
+
if (typeof source !== 'function') return null;
|
|
87
|
+
try {
|
|
88
|
+
return plainHeaders(source(provider));
|
|
89
|
+
} catch (_error) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 轮询一跳要带的头。
|
|
96
|
+
*
|
|
97
|
+
* 同源:描述符自己声明的轮询头优先,否则用提供商的默认鉴权头。
|
|
98
|
+
* 跨源:只有适配器明确声明(pollOrigins / async.trustedPollOrigins)才带;
|
|
99
|
+
* 未声明的跨源目标一律裸请求——轮询地址来自上游响应,可能是被篡改的
|
|
100
|
+
* polling_url,描述符构造的 x-key/Bearer 同样不能跟着它走。
|
|
101
|
+
* @returns {Record<string,string>}
|
|
102
|
+
*/
|
|
103
|
+
export function pollRequestHeaders(adapter, provider, url) {
|
|
104
|
+
if (!isTrusted(adapter, provider, url, 'poll')) return {};
|
|
105
|
+
const name = authHeaderNameOf(provider, adapter).toLowerCase();
|
|
106
|
+
const extra = Object.fromEntries(Object.entries(adapter?.pollHeaders || {}).filter(([key]) => key.toLowerCase() !== name));
|
|
107
|
+
return { ...extra, ...(adapterPollHeaders(adapter, provider) || authHeaders(provider, adapter)) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 下载结果图要带的头。
|
|
112
|
+
*
|
|
113
|
+
* 结果地址经常是带签名的 CDN(cdn.test、replicate.delivery…),默认不带任何凭据;
|
|
114
|
+
* 同源则带上(本地 ComfyUI 的 /view 这类接口确实需要鉴权),跨源需适配器声明。
|
|
115
|
+
* @returns {Record<string,string>}
|
|
116
|
+
*/
|
|
117
|
+
export function downloadRequestHeaders(adapter, provider, url) {
|
|
118
|
+
return isTrusted(adapter, provider, url, 'result') ? authHeaders(provider, adapter) : {};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
122
|
+
|
|
123
|
+
/** A provider operation's configured URL is trusted. Only same-origin redirects inherit its auth. */
|
|
124
|
+
export function requestProvider(url, init, provider, adapter, follow = true) {
|
|
125
|
+
const target = resolveHttpUrl(url);
|
|
126
|
+
if (!target) throw new Error('提供商请求地址无效');
|
|
127
|
+
const options = { ...init, redirect: 'manual' };
|
|
128
|
+
const spec = authSpecOf(provider, adapter);
|
|
129
|
+
// Submission redirects are returned to the executor. Following a redirect could replay a mutation.
|
|
130
|
+
if (!follow || (options.method && options.method !== 'GET' && options.method !== 'HEAD')) {
|
|
131
|
+
return request(authenticatedUrl(url, provider, adapter), options);
|
|
132
|
+
}
|
|
133
|
+
const origin = new URL(target).origin;
|
|
134
|
+
return readWithRedirects(url, options, (next) => new URL(next).origin === origin
|
|
135
|
+
? { url: authenticatedUrl(next, provider, adapter), headers: options.headers }
|
|
136
|
+
: { url: next }, spec.mode === 'query' ? spec.name : '');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function readWithRedirects(url, init, authorize, credentialParam) {
|
|
140
|
+
let next = url;
|
|
141
|
+
for (let hop = 0; ; hop++) {
|
|
142
|
+
const { url: target, headers } = authorize(next);
|
|
143
|
+
const options = { ...init, redirect: 'manual' };
|
|
144
|
+
if (headers && (Object.keys(headers).length || init.method === 'GET')) options.headers = headers;
|
|
145
|
+
else delete options.headers;
|
|
146
|
+
const response = await request(target, options);
|
|
147
|
+
const location = REDIRECTS.has(response.status) && response.headers.get('location');
|
|
148
|
+
if (!location) return response;
|
|
149
|
+
try { await response.body?.cancel(); } catch (_error) { /* already closed */ }
|
|
150
|
+
if (hop >= 4) throw new Error('上游请求重定向次数过多');
|
|
151
|
+
next = resolveHttpUrl(location, next);
|
|
152
|
+
if (!next) throw new Error('上游返回了无效的重定向地址');
|
|
153
|
+
if (credentialParam) {
|
|
154
|
+
const before = new URL(target);
|
|
155
|
+
const after = new URL(next);
|
|
156
|
+
if (before.origin !== after.origin && before.searchParams.has(credentialParam)) {
|
|
157
|
+
after.searchParams.delete(credentialParam, before.searchParams.get(credentialParam));
|
|
158
|
+
next = after.href;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Re-evaluate authentication at each read-only hop. */
|
|
165
|
+
export function requestResult(url, signal, adapter, provider, stage) {
|
|
166
|
+
if (!parseUrl(url)) throw downloadFailure('上游结果地址无效');
|
|
167
|
+
const spec = authSpecOf(provider, adapter);
|
|
168
|
+
return readWithRedirects(url, stage === 'poll' ? { signal, method: 'GET' } : { signal }, (next) => ({
|
|
169
|
+
url: isTrusted(adapter, provider, next, stage) ? authenticatedUrl(next, provider, adapter) : next,
|
|
170
|
+
headers: stage === 'poll' ? pollRequestHeaders(adapter, provider, next) : downloadRequestHeaders(adapter, provider, next)
|
|
171
|
+
}), spec.mode === 'query' ? spec.name : '');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function downloadFailure(message, fields) {
|
|
175
|
+
const error = new Error(message);
|
|
176
|
+
error.code = (fields && fields.code) || 'download_failed';
|
|
177
|
+
error.phase = 'download';
|
|
178
|
+
if (fields && fields.status) error.status = fields.status;
|
|
179
|
+
return error;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 下载成图:与提交/轮询共用同一套凭据判断,并按字节上限与图片签名校验。
|
|
184
|
+
* @returns {Promise<{bytes: Buffer, contentType: string}>}
|
|
185
|
+
*/
|
|
186
|
+
export async function fetchResultImage(url, signal, adapter, provider) {
|
|
187
|
+
if (!parseUrl(url)) throw downloadFailure('下载生成图失败:结果地址无效');
|
|
188
|
+
const response = await requestResult(url, signal, adapter, provider, 'result');
|
|
189
|
+
if (!response.ok) {
|
|
190
|
+
try { await response.body?.cancel(); } catch (_error) { /* 已关闭 */ }
|
|
191
|
+
throw downloadFailure('下载生成图失败:HTTP ' + response.status, { status: response.status });
|
|
192
|
+
}
|
|
193
|
+
const bytes = await readResponseBytes(response, MAX_IMAGE_BYTES);
|
|
194
|
+
if (!bytes.length || !looksLikeImage(bytes)) {
|
|
195
|
+
throw downloadFailure('下载生成图失败:返回内容不是有效图片');
|
|
196
|
+
}
|
|
197
|
+
return { bytes: bytes, contentType: sniffType(bytes) };
|
|
198
|
+
}
|