dsh-mo-image 0.6.0 → 0.7.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.
@@ -0,0 +1,692 @@
1
+ /**
2
+ * 配置域:归一化、按 mtime 的读写缓存、凭据解析、当前模型快照与任务级配置快照。
3
+ *
4
+ * 从 lib/index.js 拆出来后,配置读写和工具/路由注册分开;这个模块只依赖
5
+ * adapters 的纯函数与 status 的模型能力判断,不 import index,避免循环依赖。
6
+ */
7
+ import { existsSync, readFileSync, statSync } from 'node:fs';
8
+ import { readFile, writeFile, rename, unlink } from 'node:fs/promises';
9
+ import { randomUUID } from 'node:crypto';
10
+ import { isIP } from 'node:net';
11
+
12
+ import {
13
+ resolveAdapter, parseSize, sizePolicyFor, sizeSpecFor, nearestTier, nearestAspect, sizeForAspect,
14
+ qualityOptionsFor, A1111_PARAMS
15
+ } from './adapters.js';
16
+ import { MAPPING_KEYS, DEFAULT_EXPOSED } from './comfy-workflow.js';
17
+ import { buildImageStatus, editCapableModels, normalizeKeySource } from './status.js';
18
+ import { localizedError } from './localized-error.js';
19
+
20
+ export function emptyConfig() {
21
+ return {
22
+ version: 1, providers: [], active: { providerId: '', model: '' },
23
+ defaults: { quality: 'high', auto: true, width: 1024, height: 1024, promptOptimization: true }
24
+ };
25
+ }
26
+ /** 质量值由适配器的 options 决定;这里只保留旧配置里的合法字符串,具体对齐交给 adapter。 */
27
+ const QUALITY_VALUES = new Set(['off', 'low', 'medium', 'high', 'xhigh', 'max', 'auto', 'standard', 'hd', 'default', 'quality', 'turbo']);
28
+ export function normalizeQuality(value) {
29
+ const raw = String(value || '').trim().toLowerCase();
30
+ return QUALITY_VALUES.has(raw) ? raw : 'high';
31
+ }
32
+ export function normalizeDefaults(raw) {
33
+ const source = raw && typeof raw === 'object' ? raw : {};
34
+ const side = (value, fallback) => {
35
+ const number = Number(value);
36
+ if (!Number.isFinite(number) || number <= 0) return fallback;
37
+ return Math.min(4096, Math.max(64, Math.round(number)));
38
+ };
39
+ let width = side(source.width, 0);
40
+ let height = side(source.height, 0);
41
+ if (!width || !height) {
42
+ // 兼容上一版的 { size: "1024x1024" }
43
+ const legacy = /^(\d{2,5})x(\d{2,5})$/.exec(String(source.size || '').trim().toLowerCase().replace(/[×*]/g, 'x'));
44
+ if (legacy) { width = side(legacy[1], 1024); height = side(legacy[2], 1024); }
45
+ }
46
+ const finalWidth = width || 1024;
47
+ const finalHeight = height || 1024;
48
+ return {
49
+ quality: normalizeQuality(source.quality),
50
+ auto: source.auto === undefined ? true : !!source.auto,
51
+ width: finalWidth,
52
+ height: finalHeight,
53
+ // 比例/档位/白名单值:与 width/height 并存,谁生效由适配器的 control 决定。
54
+ // 档位在这里只做字符串清洗(要按模型就近取档得有 adapter,那是 resolveSizeRequest 的事)。
55
+ aspect: String(source.aspect || '').trim() || nearestAspect(finalWidth, finalHeight),
56
+ tier: String(source.tier || '').trim(),
57
+ preset: String(source.preset || '').trim() || (finalWidth + 'x' + finalHeight),
58
+ strict: !!source.strict,
59
+ promptOptimization: source.promptOptimization === undefined ? true : !!source.promptOptimization
60
+ };
61
+ }
62
+ /** 质量、尺寸都只取选择器默认值;工具不再接受模型传入的参数。 */
63
+ export function resolveQuality(defaults) {
64
+ return normalizeQuality(defaults && defaults.quality);
65
+ }
66
+ export function resolveSizeArg(defaults) {
67
+ if (defaults && defaults.auto === false) return (defaults.width || 1024) + 'x' + (defaults.height || 1024);
68
+ return 'none';
69
+ }
70
+ /**
71
+ * 尺寸请求:控件的形态决定用户的选择怎么变成一次具体的请求。
72
+ *
73
+ * - wh / prompt:两个宽高输入框直接拼 WxH;
74
+ * - aspect:比例 + 档位合成像素(16:9 + 1K → 1368×768),编码器另外发比例与档位;
75
+ * - preset:档位名原样发("2K"),custom 时允许直接写 WxH。
76
+ *
77
+ * 自动尺寸下一切交给对话模型:它传了 size 就用它,没传就不带尺寸。
78
+ * @returns {{arg:string, nominal:{width:number,height:number}|null, control:string, aspect:string, tier:string, note:string, stitch:boolean}}
79
+ */
80
+ export function resolveSizeRequest(adapter, model, defaults, args) {
81
+ const policy = sizePolicyFor(adapter, model);
82
+ const allowed = Array.isArray(policy.allowed) ? policy.allowed.filter(Boolean) : [];
83
+ const control = String(policy.control
84
+ || (allowed.length ? 'preset' : (policy.style === 'aspect' ? 'aspect' : 'wh')));
85
+ const auto = !(defaults && defaults.auto === false);
86
+ const asked = String((args && args.size) || '').trim();
87
+ const out = {
88
+ arg: 'none', nominal: null, control: control,
89
+ aspect: '', tier: '', note: '', stitch: policy.stitch === true
90
+ };
91
+
92
+ if (auto) {
93
+ if (!asked) return out;
94
+ out.arg = asked;
95
+ const parsed = parseSize(asked);
96
+ if (parsed) out.nominal = { width: parsed.width, height: parsed.height };
97
+ return out;
98
+ }
99
+
100
+ const width = Number(defaults && defaults.width) || 1024;
101
+ const height = Number(defaults && defaults.height) || 1024;
102
+
103
+ if (control === 'aspect') {
104
+ const aspects = Array.isArray(policy.aspects) && policy.aspects.length ? policy.aspects : ['1:1'];
105
+ const wantedAspect = String((defaults && defaults.aspect) || '');
106
+ const aspect = aspects.includes(wantedAspect) ? wantedAspect : nearestAspect(width, height, aspects);
107
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers : [];
108
+ const wantedTier = String((defaults && defaults.tier) || '');
109
+ const tier = tiers.find((item) => String(item && item.value) === wantedTier)
110
+ || (tiers.length ? nearestTier(tiers, width * height) : null);
111
+ if (wantedTier && tier && String(tier.value) !== wantedTier) {
112
+ out.note = '档位 ' + wantedTier + ' 不在当前模型的合法档位里,已改用 ' + tier.value;
113
+ }
114
+ const budget = tier ? Number(tier.pixels) : 1024 * 1024;
115
+ const size = sizeForAspect(aspect, budget);
116
+ out.arg = size.width + 'x' + size.height;
117
+ out.nominal = size;
118
+ out.aspect = aspect;
119
+ out.tier = tier ? String(tier.value) : '';
120
+ return out;
121
+ }
122
+
123
+ if (control === 'preset') {
124
+ const tiers = Array.isArray(policy.tiers) ? policy.tiers : [];
125
+ const candidates = tiers.length ? tiers.map((item) => String(item && item.value)) : allowed;
126
+ const custom = policy.custom === true;
127
+ const wanted = String((defaults && defaults.preset) || '')
128
+ || (width + 'x' + height);
129
+ let value = candidates.includes(wanted) ? wanted : '';
130
+ if (!value && custom && parseSize(wanted)) value = wanted;
131
+ if (!value) {
132
+ const tier = tiers.length ? nearestTier(tiers, width * height) : null;
133
+ value = tier ? String(tier.value) : (candidates[0] || (width + 'x' + height));
134
+ if (wanted && wanted !== value) {
135
+ out.note = '尺寸 ' + wanted + ' 不在当前模型的可选范围里,已改用 ' + value;
136
+ }
137
+ }
138
+ out.arg = value;
139
+ const tier = tiers.find((item) => String(item && item.value) === value);
140
+ if (tier) {
141
+ out.tier = value;
142
+ const side = Math.round(Math.sqrt(Number(tier.pixels))) || 0;
143
+ if (side) out.nominal = { width: side, height: side };
144
+ } else {
145
+ const parsed = parseSize(value);
146
+ if (parsed) out.nominal = { width: parsed.width, height: parsed.height };
147
+ }
148
+ return out;
149
+ }
150
+
151
+ out.arg = width + 'x' + height;
152
+ out.nominal = { width: width, height: height };
153
+ if (asked) out.note = '尺寸已由选择器固定为 ' + out.arg + ',已忽略 size:' + asked;
154
+ return out;
155
+ }
156
+ /** 每个模型的可选配置(目前只有自定义工作流),只保留仍存在的模型,限制体积。 */
157
+ const MODEL_WORKFLOW_MAX = 2000000;
158
+ /**
159
+ * 映射要么完整,要么没有:任何一项形状不对就整体丢弃,
160
+ * 免得生成时一半注入一半不注入,产出用户看不懂的图。
161
+ */
162
+ function sanitizeMapping(raw) {
163
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
164
+ const out = {};
165
+ for (const key of MAPPING_KEYS) {
166
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
167
+ const value = raw[key];
168
+ if (value === null) { out[key] = null; continue; }
169
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
170
+ const node = typeof value.node === 'string' ? value.node.trim() : '';
171
+ const input = typeof value.input === 'string' ? value.input.trim() : '';
172
+ if (!node || !input) return undefined;
173
+ out[key] = { node, input };
174
+ }
175
+ return Object.keys(out).length ? out : undefined;
176
+ }
177
+
178
+ /**
179
+ * 可调参数清单来自解析结果,形状固定:name/node/input/type/default[/options]。
180
+ * 任何一项不合法就整体丢弃——宁可不让模型看到,也不要报一个假的默认值。
181
+ */
182
+ function sanitizeParams(raw) {
183
+ if (!Array.isArray(raw)) return undefined;
184
+ const out = [];
185
+ for (const item of raw) {
186
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
187
+ const name = typeof item.name === 'string' ? item.name.trim() : '';
188
+ const node = typeof item.node === 'string' ? item.node.trim() : '';
189
+ const input = typeof item.input === 'string' ? item.input.trim() : '';
190
+ // ComfyUI 的参数必须带节点位置;A1111 的参数只是 sdapi 字段名,没有节点。
191
+ if (!name) return undefined;
192
+ if ((node && !input) || (!node && input)) return undefined;
193
+ const param = { name, type: String(item.type || 'string') };
194
+ if (node && input) { param.node = node; param.input = input; }
195
+ if (Array.isArray(item.options)) param.options = item.options.map(String).slice(0, 64);
196
+ if (item.role === true) param.role = true;
197
+ if (item.expose === false) param.expose = false;
198
+ if (Array.isArray(item.candidates)) {
199
+ const seen = new Set();
200
+ param.candidates = [];
201
+ for (const candidate of item.candidates) {
202
+ if (!candidate || typeof candidate !== 'object') continue;
203
+ const node = typeof candidate.node === 'string' ? candidate.node.trim() : '';
204
+ const input = typeof candidate.input === 'string' ? candidate.input.trim() : '';
205
+ const key = node + '::' + input;
206
+ if (!node || !input || seen.has(key)) continue;
207
+ seen.add(key);
208
+ param.candidates.push({ node, input });
209
+ }
210
+ if (!param.candidates.length) delete param.candidates;
211
+ }
212
+ out.push(param);
213
+ }
214
+ return out.length ? out : undefined;
215
+ }
216
+
217
+ /** 逐项暴露开关:只存布尔值,未出现的项按角色/可调参数各自默认。 */
218
+ function sanitizeExpose(raw) {
219
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
220
+ const out = {};
221
+ for (const [key, value] of Object.entries(raw)) {
222
+ const name = String(key || '').trim();
223
+ if (!name || typeof value !== 'boolean') continue;
224
+ out[name] = value;
225
+ }
226
+ return Object.keys(out).length ? out : undefined;
227
+ }
228
+
229
+ export function normalizeModelOptions(raw, models, adapter) {
230
+ const out = {};
231
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
232
+ const allowed = new Set(Array.isArray(models) ? models : []);
233
+ // A1111 只有参数开关,没有工作流;其它适配器仍然要求工作流。
234
+ const paramsOnly = adapter === 'a1111';
235
+ for (const model of Object.keys(raw)) {
236
+ if (!allowed.has(model)) continue;
237
+ const entry = raw[model];
238
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
239
+ const workflow = typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
240
+ if (workflow.length > MODEL_WORKFLOW_MAX) continue;
241
+ if (!workflow && !paramsOnly) continue;
242
+ const mapping = sanitizeMapping(entry.mapping);
243
+ const params = sanitizeParams(entry.params);
244
+ const expose = sanitizeExpose(entry.expose);
245
+ const next = {};
246
+ if (workflow) next.workflow = workflow;
247
+ if (mapping) next.mapping = mapping;
248
+ if (params) next.params = params;
249
+ if (expose) next.expose = expose;
250
+ if (!Object.keys(next).length) continue;
251
+ out[model] = next;
252
+ }
253
+ return out;
254
+ }
255
+
256
+ export function normalizeConfig(raw) {
257
+ const out = emptyConfig();
258
+ if (!raw || typeof raw !== 'object') return out;
259
+ const providers = Array.isArray(raw.providers) ? raw.providers : [];
260
+ for (const item of providers) {
261
+ if (!item || typeof item !== 'object') continue;
262
+ const models = Array.from(new Set((Array.isArray(item.models) ? item.models : [])
263
+ .map((m) => String(m || '').trim()).filter(Boolean)));
264
+ const names = {};
265
+ if (item.names && typeof item.names === 'object') for (const model of models) if (typeof item.names[model] === 'string') names[model] = item.names[model];
266
+ const modelOptions = normalizeModelOptions(item.modelOptions, models, item.adapter);
267
+ const key = String(item.key || '');
268
+ const provider = {
269
+ id: String(item.id || randomUUID()), name: String(item.name || ''),
270
+ baseUrl: String(item.baseUrl || '').replace(/\/+$/, ''),
271
+ apiKeyEnv: validKeyRef(item.apiKeyEnv),
272
+ optionalKey: !!item.optionalKey,
273
+ protocol: String(item.protocol || 'openai-images'), adapter: String(item.adapter || ''), models, names
274
+ };
275
+ // Responses API 需要一个能调工具的主模型;只有这个适配器要留。
276
+ if (provider.adapter === 'openai-responses') {
277
+ const hostModel = String(item.hostModel || '').trim();
278
+ if (hostModel) provider.hostModel = hostModel;
279
+ }
280
+ // 自定义工作流只有 ComfyUI 适配器会读;别的提供商留着也没用,直接丢弃。
281
+ // ComfyUI 读工作流与映射,A1111 只读参数开关;其它适配器不认这些。
282
+ if ((provider.adapter === 'comfyui' || provider.adapter === 'a1111') && Object.keys(modelOptions).length > 0) {
283
+ provider.modelOptions = modelOptions;
284
+ }
285
+ if (key) provider.key = key;
286
+ out.providers.push(provider);
287
+ }
288
+ const wanted = raw.active && typeof raw.active === 'object' ? raw.active : {};
289
+ const provider = out.providers.find((p) => p.id === wanted.providerId);
290
+ // "auto" 是选择器里的特殊行:允许对话模型在提供商列表内自选模型。
291
+ const wantedModel = String(wanted.model || '').trim();
292
+ const keepModel = wantedModel === 'auto' || (provider && provider.models.includes(wantedModel));
293
+ out.active = { providerId: provider ? provider.id : '', model: keepModel ? wantedModel : '' };
294
+ out.defaults = normalizeDefaults(raw.defaults);
295
+ return out;
296
+ }
297
+ /** DSH 凭据库(ctx.credentials)里的引用名;只允许我们自己的 MO_IMAGE_ 命名空间。 */
298
+ const KEY_REF_PREFIX = 'MO_IMAGE_';
299
+ const KEY_REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
300
+ export function createConfigStore(options) {
301
+ return {
302
+ configFile: options.configFile,
303
+ ensureDirs: options.ensureDirs,
304
+ logHost: options.logHost,
305
+ credentialsAccessor: options.credentialsAccessor,
306
+ cache: null,
307
+ stamp: '',
308
+ webOriginHost: '',
309
+ keyMigration: null,
310
+ writeQueue: Promise.resolve()
311
+ };
312
+ }
313
+ export function credentialsService(store) {
314
+ if (!store || typeof store.credentialsAccessor !== 'function') return undefined;
315
+ try { return store.credentialsAccessor(); } catch (_error) { return undefined; }
316
+ }
317
+ export function validKeyRef(value) {
318
+ const ref = String(value || '').trim();
319
+ return KEY_REF_PATTERN.test(ref) && ref.startsWith(KEY_REF_PREFIX) ? ref : '';
320
+ }
321
+ /** 按 provider id 生成稳定的环境变量名,例如 MO_IMAGE_P_ABC_API_KEY。 */
322
+ export function deriveKeyRef(id, used) {
323
+ const stem = String(id || 'provider').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'PROVIDER';
324
+ const base = KEY_REF_PREFIX + stem + '_API_KEY';
325
+ let ref = base;
326
+ for (let n = 2; used && used.has(ref); n++) ref = base.replace(/_API_KEY$/, '_' + n + '_API_KEY');
327
+ return ref;
328
+ }
329
+ export function hasLegacyKeys(config) {
330
+ return (config.providers || []).some((provider) => provider.key || !validKeyRef(provider.apiKeyEnv));
331
+ }
332
+ /** describe() 的 configured 也可能来自环境变量;只有不是 env fallback 才算已存进凭据库。 */
333
+ export function credentialIsStored(info) {
334
+ if (!info || !info.configured) return false;
335
+ const source = String(info.source || '');
336
+ return source !== 'env' && source !== 'project-env' && source !== 'user-env';
337
+ }
338
+
339
+ function requestHostName(req) {
340
+ const raw = String((req.headers && req.headers.host) || '').trim().toLowerCase();
341
+ if (!raw) return '';
342
+ const withoutPort = raw.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
343
+ return withoutPort;
344
+ }
345
+ /**
346
+ * 配置写接口是本插件自己的本地 HTTP 路由,不走 DSH 的 remote 权限层,所以
347
+ * 至少挡掉跨站浏览器请求和 DNS rebinding:Host 必须是回环、IP 字面量或
348
+ * DSH_WEB_URL 公布的域名;Origin 必须同源;POST 必须是 application/json。
349
+ * 同一 OS 用户的进程本来就能读凭据文件,这里不是对抗同 UID 进程的边界。
350
+ */
351
+ export function assertLocalRequest(store, req, write) {
352
+ const hostName = requestHostName(req);
353
+ if (!hostName) {
354
+ const error = new Error('missing Host header'); error.status = 403; throw error;
355
+ }
356
+ const allowed = new Set(['127.0.0.1', 'localhost', '::1']);
357
+ for (const value of [process.env.DSH_WEB_URL, store && store.webOriginHost]) {
358
+ try {
359
+ const parsed = new URL(String(value || ''));
360
+ if (parsed.hostname) allowed.add(parsed.hostname.toLowerCase());
361
+ } catch (_error) { /* ignore */ }
362
+ }
363
+ if (!allowed.has(hostName) && isIP(hostName) === 0) {
364
+ const error = new Error('unexpected Host header'); error.status = 403; throw error;
365
+ }
366
+ const origin = req.headers && req.headers.origin;
367
+ if (origin !== undefined) {
368
+ let originUrl;
369
+ try { originUrl = new URL(String(origin)); } catch (_error) {
370
+ const error = new Error('invalid Origin'); error.status = 403; throw error;
371
+ }
372
+ const hostHeader = String(req.headers.host || '').toLowerCase();
373
+ if (originUrl.host.toLowerCase() !== hostHeader) {
374
+ const error = new Error('cross-origin request rejected'); error.status = 403; throw error;
375
+ }
376
+ }
377
+ const site = req.headers && req.headers['sec-fetch-site'];
378
+ if (site && site !== 'same-origin' && site !== 'none') {
379
+ const error = new Error('cross-site request rejected'); error.status = 403; throw error;
380
+ }
381
+ if (write) {
382
+ const type = String((req.headers && req.headers['content-type']) || '').toLowerCase();
383
+ if (!type.startsWith('application/json')) {
384
+ const error = new Error('content-type must be application/json'); error.status = 415; throw error;
385
+ }
386
+ }
387
+ }
388
+ /** 系统提示词节是同步渲染的,这里用 mtime 缓存一份配置副本。 */
389
+ export function rememberConfig(store, config) {
390
+ store.cache = config;
391
+ store.stamp = '';
392
+ }
393
+ export function readConfigSync(store) {
394
+ try {
395
+ const info = statSync(store.configFile);
396
+ const stamp = info.mtimeMs + ':' + info.size;
397
+ if (!store.cache || stamp !== store.stamp) {
398
+ store.cache = normalizeConfig(JSON.parse(readFileSync(store.configFile, 'utf8')));
399
+ store.stamp = stamp;
400
+ }
401
+ } catch (_error) {
402
+ if (!store.cache) store.cache = emptyConfig();
403
+ }
404
+ return store.cache;
405
+ }
406
+ /** 当前选中的生图模型;编辑也用同一个(严格模式,不做任何回退)。 */
407
+ export function activeImageState(store, snapshot) {
408
+ const config = snapshot || readConfigSync(store);
409
+ const provider = (config.providers || []).find((item) => item.id === config.active.providerId);
410
+ const model = String((config.active && config.active.model) || '').trim();
411
+ if (!provider || !model) return null;
412
+ let adapter = null;
413
+ try { adapter = resolveAdapter(provider, model); } catch (_error) { adapter = null; }
414
+ const models = provider.models || [];
415
+ const editModels = editCapableModels(provider, models);
416
+ const sizeSpec = adapter && adapter.size ? adapter.size : null;
417
+ const fixedSize = config.defaults.auto === false;
418
+ const sizeRequest = adapter ? resolveSizeRequest(adapter, model, config.defaults, {}) : null;
419
+ const sizeOptions = sizeSpec
420
+ ? (Array.isArray(sizeSpec.tiers) && sizeSpec.tiers.length
421
+ ? sizeSpec.tiers.map((tier) => String(tier.value))
422
+ : (Array.isArray(sizeSpec.allowed) ? sizeSpec.allowed.map(String) : []))
423
+ : [];
424
+ return {
425
+ provider, model, adapter, models, editModels,
426
+ canEdit: model === 'auto' ? editModels.length > 0 : editCapableModels(provider, [model]).length > 0,
427
+ editModel: model, editAdapter: adapter,
428
+ // 只有 ComfyUI 部署才有工作流参数;用户关掉暴露时不返回。
429
+ workflowParams: workflowParamsOf(provider, model, adapter),
430
+ // 自动尺寸下模型可以自己填 size;固定尺寸下选择器说了算。
431
+ sizeMode: fixedSize ? 'fixed' : 'auto',
432
+ size: fixedSize ? (sizeRequest ? sizeRequest.arg : resolveSizeArg(config.defaults)) : undefined,
433
+ strict: config.defaults.strict === true,
434
+ control: sizeRequest ? sizeRequest.control : '',
435
+ sizeOptions: sizeOptions.length ? sizeOptions : undefined,
436
+ promptOptimization: config.defaults.promptOptimization !== false, defaults: config.defaults
437
+ };
438
+ }
439
+
440
+ /** 凭据解析:状态服务与配置页共用同一套“哪里算有 Key”的口径。 */
441
+ export async function resolveStatusKey(store, provider) {
442
+ if (!provider) return { ok: false, source: '', ref: '' };
443
+ if (provider.optionalKey) return { ok: true, source: 'optional', ref: '' };
444
+ const ref = validKeyRef(provider.apiKeyEnv);
445
+ const credentials = credentialsService(store);
446
+ if (ref && credentials && typeof credentials.describe === 'function') {
447
+ try {
448
+ const info = await credentials.describe(ref);
449
+ if (info && info.configured) return { ok: true, source: normalizeKeySource(info.source || 'credentials'), ref };
450
+ } catch (error) {
451
+ store.logHost('status credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error));
452
+ }
453
+ }
454
+ if (ref && String(process.env[ref] || '').trim()) return { ok: true, source: 'env', ref };
455
+ if (provider.key) return { ok: true, source: 'config', ref };
456
+ return { ok: false, source: '', ref };
457
+ }
458
+
459
+ /** 只读状态快照:ctx.provide('moImageStatus').describe() 的实现。 */
460
+ export async function describeImageStatus(store, version = "0.0.0") {
461
+ const config = await readConfig(store);
462
+ const active = config.active && typeof config.active === 'object' ? config.active : {};
463
+ const provider = (config.providers || []).find((item) => item && item.id === active.providerId) || null;
464
+ const key = await resolveStatusKey(store, provider);
465
+ return buildImageStatus({ config, version: version, key });
466
+ }
467
+
468
+ /** 当前模型的工作流可调参数;非 ComfyUI 或用户逐项关闭时不返回。 */
469
+ export function workflowParamsOf(provider, model, adapter) {
470
+ try {
471
+ if (!adapter) return undefined;
472
+ const options = provider && provider.modelOptions ? provider.modelOptions : null;
473
+ if (!options || typeof options !== 'object') return undefined;
474
+ if (adapter.id === 'a1111') {
475
+ // A1111 没有工作流,参数清单固定;默认全关,只返回用户勾上的。
476
+ const own = options[model];
477
+ const source = own && own.expose ? own : Object.values(options).find((entry) => entry && entry.expose);
478
+ const expose = (source && source.expose) || {};
479
+ const exposed = A1111_PARAMS.filter((param) => expose[param.name] === true);
480
+ return exposed.length ? exposed : undefined;
481
+ }
482
+ if (adapter.id !== 'comfyui') return undefined;
483
+ const entry = options[model];
484
+ if (!entry || !Array.isArray(entry.params)) return undefined;
485
+ const expose = entry.expose && typeof entry.expose === 'object' ? entry.expose : {};
486
+ const exposed = entry.params.filter((param) => {
487
+ if (!param) return false;
488
+ const explicit = expose[param.name];
489
+ if (explicit !== undefined) return explicit !== false;
490
+ return DEFAULT_EXPOSED.has(param.name);
491
+ });
492
+ return exposed.length ? exposed : undefined;
493
+ } catch (_error) { return undefined; }
494
+ }
495
+ export function canUseCredentials(store) {
496
+ const credentials = credentialsService(store);
497
+ return !!(credentials && typeof credentials.describe === 'function' && typeof credentials.resolve === 'function' && typeof credentials.set === 'function');
498
+ }
499
+ /** 浏览器只拿 hasKey/keySource,永远拿不到明文密钥。 */
500
+ export async function publicConfig(store, config) {
501
+ const credentials = credentialsService(store);
502
+ const providers = await Promise.all((config.providers || []).map(async (provider) => {
503
+ const copy = Object.assign({}, provider);
504
+ delete copy.key;
505
+ const ref = validKeyRef(provider.apiKeyEnv);
506
+ let hasKey = false;
507
+ let keySource = '';
508
+ if (ref && credentials && typeof credentials.describe === 'function') {
509
+ try {
510
+ const info = await credentials.describe(ref);
511
+ hasKey = !!info.configured;
512
+ keySource = info.source || '';
513
+ } catch (error) { store.logHost('credential describe failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
514
+ }
515
+ if (!hasKey && ref && process.env[ref]) { hasKey = true; keySource = 'env'; }
516
+ if (!hasKey && provider.key) { hasKey = true; keySource = 'config'; }
517
+ return Object.assign(copy, { hasKey: hasKey, keySource: keySource });
518
+ }));
519
+ return Object.assign({}, config, { providers: providers });
520
+ }
521
+ /** 选择器用的模型能力表:每个模型可用哪些质量档、尺寸控件长什么样。 */
522
+ export function capabilityManifest(config) {
523
+ return (config.providers || []).map((provider) => ({
524
+ providerId: provider.id,
525
+ models: (provider.models || []).map((model) => {
526
+ let adapter = null;
527
+ let quality = null;
528
+ try { adapter = resolveAdapter(provider, model); quality = qualityOptionsFor(adapter, model); } catch (_error) { adapter = null; quality = null; }
529
+ return { model: model, quality: quality, size: sizeSpecFor(adapter, model) };
530
+ })
531
+ }));
532
+ }
533
+ /**
534
+ * 把旧版 config.json 里的明文 key 迁到 DSH 凭据库,并在配置里只留下 apiKeyEnv 引用。
535
+ * 凭据服务不存在(自定义 composition)时保持旧字段,避免把用户锁死。
536
+ */
537
+ export async function migrateConfigKeys(store, input) {
538
+ if (!canUseCredentials(store)) return input;
539
+ const credentials = credentialsService(store);
540
+ const config = normalizeConfig(input);
541
+ const used = new Set();
542
+ let migrated = 0;
543
+ let changed = false;
544
+ for (const provider of config.providers) {
545
+ let ref = validKeyRef(provider.apiKeyEnv);
546
+ if (!ref) {
547
+ ref = deriveKeyRef(provider.id, used);
548
+ provider.apiKeyEnv = ref;
549
+ changed = true;
550
+ } else if (used.has(ref)) {
551
+ ref = deriveKeyRef(provider.id, used);
552
+ provider.apiKeyEnv = ref;
553
+ changed = true;
554
+ }
555
+ used.add(ref);
556
+ if (!provider.key) continue;
557
+ try {
558
+ const info = await credentials.describe(ref);
559
+ if (!credentialIsStored(info)) {
560
+ await credentials.set(ref, provider.key);
561
+ migrated++;
562
+ }
563
+ delete provider.key;
564
+ changed = true;
565
+ } catch (error) {
566
+ store.logHost('credential migration failed for provider ' + provider.id + ': ' + String(error && error.message ? error.message : error));
567
+ }
568
+ }
569
+ if (!changed) return config;
570
+ const saved = await writeConfig(store, config);
571
+ if (migrated > 0) store.logHost('migrated ' + migrated + ' API key(s) to credentials store');
572
+ return saved;
573
+ }
574
+ export function migrateKeysOnce(store, config) {
575
+ if (!store.keyMigration) store.keyMigration = migrateConfigKeys(store, config).finally(() => { store.keyMigration = null; });
576
+ return store.keyMigration;
577
+ }
578
+ export async function readConfig(store) {
579
+ try {
580
+ if (!existsSync(store.configFile)) {
581
+ const empty = emptyConfig();
582
+ rememberConfig(store, empty);
583
+ return empty;
584
+ }
585
+ let config = normalizeConfig(JSON.parse(await readFile(store.configFile, 'utf8')));
586
+ if (hasLegacyKeys(config) && canUseCredentials(store)) {
587
+ try { config = await migrateKeysOnce(store, config); } catch (error) { store.logHost('config key migration failed: ' + String(error && error.message ? error.message : error)); }
588
+ }
589
+ rememberConfig(store, config);
590
+ return config;
591
+ } catch (_error) { return emptyConfig(); }
592
+ }
593
+ export async function writeConfig(store, config) {
594
+ const next = normalizeConfig(config);
595
+ const task = store.writeQueue.then(async () => {
596
+ store.ensureDirs();
597
+ const tempFile = store.configFile + '.tmp-' + process.pid + '-' + randomUUID().slice(0, 8);
598
+ try {
599
+ await writeFile(tempFile, JSON.stringify(next, null, 2), { encoding: 'utf8', mode: 0o600 });
600
+ await rename(tempFile, store.configFile);
601
+ } finally {
602
+ try { await unlink(tempFile); } catch (_error) { /* rename 成功后临时文件已不存在 */ }
603
+ }
604
+ rememberConfig(store, next);
605
+ return next;
606
+ });
607
+ store.writeQueue = task.catch(() => {});
608
+ return task;
609
+ }
610
+ /** 每次请求才解析一次密钥;不在内存里长期缓存,轮换后下一请求生效。 */
611
+ export async function resolveProviderCredential(store, provider) {
612
+ const ref = validKeyRef(provider.apiKeyEnv);
613
+ const credentials = credentialsService(store);
614
+ if (ref) {
615
+ if (credentials && typeof credentials.resolve === 'function') {
616
+ try {
617
+ const hit = await credentials.resolve(ref);
618
+ if (hit && typeof hit.value === 'string' && hit.value.trim().length > 0) {
619
+ return Object.assign({}, provider, { key: hit.value.trim() });
620
+ }
621
+ } catch (error) { store.logHost('credential resolve failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
622
+ }
623
+ const env = process.env[ref];
624
+ if (env && env.trim()) return Object.assign({}, provider, { key: env.trim() });
625
+ }
626
+ if (provider.key) return provider;
627
+ if (provider.optionalKey) return provider;
628
+ throw localizedError(
629
+ new Error('生图提供商「' + (provider.name || provider.id) + '」缺少 API Key,请到 DSH 设置 → 生图模型填写'
630
+ + (ref ? '(凭据 ' + ref + ')' : '') + '。'),
631
+ ref ? 'provider.missingKeyWithRef' : 'provider.missingKey',
632
+ { provider: provider.name || provider.id, ref: ref }
633
+ );
634
+ }
635
+ /** 保存配置前先把每个 provider 的新 key 写进凭据库,配置文件只保留 apiKeyEnv。 */
636
+ export async function saveConfigWithCredentials(store, raw) {
637
+ const incoming = normalizeConfig(raw);
638
+ const current = await readConfig(store);
639
+ const credentials = credentialsService(store);
640
+ const canStore = !!(credentials && typeof credentials.set === 'function');
641
+ const canDescribe = !!(credentials && typeof credentials.describe === 'function');
642
+ const currentById = new Map(current.providers.map((provider) => [provider.id, provider]));
643
+ const used = new Set();
644
+ const providers = [];
645
+ for (const provider of incoming.providers) {
646
+ const old = currentById.get(provider.id);
647
+ let ref = validKeyRef(provider.apiKeyEnv) || validKeyRef(old && old.apiKeyEnv) || deriveKeyRef(provider.id, used);
648
+ if (used.has(ref)) ref = deriveKeyRef(provider.id, used);
649
+ used.add(ref);
650
+ provider.apiKeyEnv = ref;
651
+ const newKey = String(provider.key || '').trim();
652
+ delete provider.key;
653
+ if (newKey) {
654
+ if (!canStore) throw localizedError(new Error('DSH 凭据服务未挂载,无法安全保存 API Key;请确认 base composition 包含 dsh-credentials-local。'), 'config.credentialsUnavailable');
655
+ try {
656
+ await credentials.set(ref, newKey);
657
+ } catch (error) {
658
+ const message = String(error && error.message ? error.message : error);
659
+ throw localizedError(new Error('保存 API Key 失败:' + message), 'config.credentialSaveFailed', { message: message });
660
+ }
661
+ } else if (old && old.key) {
662
+ if (canStore && canDescribe) {
663
+ try {
664
+ const info = await credentials.describe(ref);
665
+ if (!credentialIsStored(info)) await credentials.set(ref, old.key);
666
+ } catch (error) {
667
+ const message = String(error && error.message ? error.message : error);
668
+ throw localizedError(new Error('旧 API Key 迁移失败:' + message), 'config.legacyKeyMigrationFailed', { message: message });
669
+ }
670
+ } else {
671
+ provider.key = old.key;
672
+ }
673
+ }
674
+ providers.push(provider);
675
+ }
676
+ if (credentials && typeof credentials.unset === 'function') {
677
+ const kept = new Set(providers.map((provider) => provider.id));
678
+ for (const old of current.providers) {
679
+ if (kept.has(old.id)) continue;
680
+ const ref = validKeyRef(old.apiKeyEnv);
681
+ if (!ref || used.has(ref)) continue;
682
+ try { await credentials.unset(ref); } catch (error) { store.logHost('credential removal failed for ' + ref + ': ' + String(error && error.message ? error.message : error)); }
683
+ }
684
+ }
685
+ incoming.providers = providers;
686
+ try {
687
+ return await writeConfig(store, incoming);
688
+ } catch (error) {
689
+ const message = String(error && error.message ? error.message : error);
690
+ throw localizedError(new Error('保存生图配置失败:' + message), 'config.writeFailed', { message: message });
691
+ }
692
+ }