dsh-mo-image 0.0.0-stage → 0.4.1

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/lib/proxy.js ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * 代理发现:把「环境变量」和「Windows 系统代理」翻译成一个可用的 HTTP 代理地址。
3
+ *
4
+ * 这里只做纯解析,不发请求、不读注册表;读系统代理由 readSystemProxy() 单独负责,
5
+ * 便于单元测试注入。Windows/WinINET 的设置 Node 自己永远不会用到,必须显式读出来。
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+
9
+ const SUPPORTED = new Set(['http:', 'https:']);
10
+
11
+ /** 只有「明文 HTTP 代理」这条路在本插件里实现了(CONNECT 隧道);SOCKS 明确不支持。 */
12
+ function normalizeProxySpec(spec) {
13
+ const raw = String(spec || '').trim();
14
+ if (!raw) return undefined;
15
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : 'http://' + raw;
16
+ let url;
17
+ try { url = new URL(withScheme); } catch (_error) { return undefined; }
18
+ if (url.protocol !== 'http:') return undefined;
19
+ if (!url.hostname) return undefined;
20
+ const auth = url.username
21
+ ? encodeURIComponent(decodeURIComponent(url.username)) + ':' + encodeURIComponent(decodeURIComponent(url.password || '')) + '@'
22
+ : '';
23
+ return 'http://' + auth + url.host;
24
+ }
25
+
26
+ /**
27
+ * 解析系统代理串。Windows 会写成 `127.0.0.1:7897`,
28
+ * 也可能写成 `http=127.0.0.1:7897;https=127.0.0.1:7897`。
29
+ */
30
+ export function parseProxyServer(value) {
31
+ const text = String(value || '').trim();
32
+ if (!text) return { http: undefined, https: undefined };
33
+ if (!text.includes('=')) {
34
+ const single = normalizeProxySpec(text);
35
+ return { http: single, https: single };
36
+ }
37
+ const result = { http: undefined, https: undefined };
38
+ for (const part of text.split(';')) {
39
+ const index = part.indexOf('=');
40
+ if (index <= 0) continue;
41
+ const scheme = part.slice(0, index).trim().toLowerCase();
42
+ if (scheme !== 'http' && scheme !== 'https') continue; // socks= 直接忽略
43
+ const spec = normalizeProxySpec(part.slice(index + 1));
44
+ if (spec) result[scheme] = spec;
45
+ }
46
+ return result;
47
+ }
48
+
49
+ /** 绕过列表:`;`/`,`/空白分隔;`*` 通配、`.suffix` 后缀、`<local>` 无点主机名。 */
50
+ export function parseBypassList(value) {
51
+ const raw = Array.isArray(value) ? value.join(';') : String(value || '');
52
+ const out = [];
53
+ for (const item of raw.split(/[;,\s]+/)) {
54
+ const entry = item.trim().toLowerCase();
55
+ if (entry) out.push(entry);
56
+ }
57
+ return out;
58
+ }
59
+
60
+ function bareHost(host) {
61
+ return String(host || '').trim().toLowerCase().replace(/^\[|\]$/g, '');
62
+ }
63
+
64
+ export function isLoopbackHost(host) {
65
+ const value = bareHost(host);
66
+ if (!value) return false;
67
+ if (value === 'localhost' || value.endsWith('.localhost')) return true;
68
+ if (value === '::1' || value === '0.0.0.0') return true;
69
+ const parts = value.split('.');
70
+ if (parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part))) {
71
+ return Number(parts[0]) === 127;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ export function hostMatchesBypass(host, list) {
77
+ const value = bareHost(host);
78
+ if (!value) return false;
79
+ for (const rawEntry of Array.isArray(list) ? list : parseBypassList(list)) {
80
+ let entry = String(rawEntry || '').trim().toLowerCase();
81
+ if (!entry) continue;
82
+ if (entry.includes('*') === false && /^[^:]+:\d+$/.test(entry)) entry = entry.replace(/:\d+$/, '');
83
+ if (entry === '*') return true;
84
+ if (entry === '<local>') {
85
+ if (value.startsWith('::1')) return true;
86
+ if (!value.includes('.') && !/^\d+\.\d+\.\d+\.\d+$/.test(value) && !value.includes(':')) return true;
87
+ continue;
88
+ }
89
+ const suffix = entry.startsWith('.') ? entry.slice(1)
90
+ : entry.startsWith('*.') ? entry.slice(2)
91
+ : '';
92
+ if (suffix) {
93
+ if (value === suffix || value.endsWith('.' + suffix)) return true;
94
+ continue;
95
+ }
96
+ if (entry.includes('*')) {
97
+ const pattern = entry.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
98
+ if (new RegExp('^' + pattern + '$').test(value)) return true;
99
+ continue;
100
+ }
101
+ if (value === entry) return true;
102
+ }
103
+ return false;
104
+ }
105
+
106
+ function pickFromEnv(env, names) {
107
+ for (const name of names) {
108
+ const value = env[name];
109
+ if (typeof value === 'string' && value.trim()) return value.trim();
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ /**
115
+ * 决定「这个 URL 该不该走代理、走哪个」。
116
+ * 优先级:显式覆盖(MO_IMAGE_PROXY) > 环境变量(HTTPS_PROXY/HTTP_PROXY/ALL_PROXY) > 系统代理。
117
+ * 回环地址永远直连——本地部署的适配器(A1111/ComfyUI/…)不能被塞进代理。
118
+ *
119
+ * @returns {{ proxyUrl: string|null, source: 'override'|'env'|'system'|null, reason: string }}
120
+ */
121
+ export function resolveProxyForTarget(target, options = {}) {
122
+ const env = options.env || process.env;
123
+ const systemProxy = options.systemProxy === undefined ? null : options.systemProxy;
124
+
125
+ let url;
126
+ try { url = new URL(String(target || '')); } catch (_error) {
127
+ return { proxyUrl: null, source: null, reason: 'invalid-url' };
128
+ }
129
+ if (!SUPPORTED.has(url.protocol)) return { proxyUrl: null, source: null, reason: 'unsupported-protocol' };
130
+
131
+ const host = bareHost(url.hostname);
132
+ if (isLoopbackHost(host)) return { proxyUrl: null, source: null, reason: 'loopback' };
133
+
134
+ const override = String(env.MO_IMAGE_PROXY || '').trim();
135
+ if (override) {
136
+ if (/^(off|none|false|0|direct)$/i.test(override)) return { proxyUrl: null, source: null, reason: 'disabled' };
137
+ const url2 = normalizeProxySpec(override);
138
+ if (url2) return { proxyUrl: url2, source: 'override', reason: 'override' };
139
+ }
140
+
141
+ const scheme = url.protocol === 'https:' ? 'https' : 'http';
142
+ const noProxy = pickFromEnv(env, ['NO_PROXY', 'no_proxy']);
143
+ if (noProxy && hostMatchesBypass(host, parseBypassList(noProxy))) {
144
+ return { proxyUrl: null, source: null, reason: 'bypass' };
145
+ }
146
+
147
+ const envProxy = scheme === 'https'
148
+ ? pickFromEnv(env, ['HTTPS_PROXY', 'https_proxy', 'ALL_PROXY', 'all_proxy'])
149
+ : pickFromEnv(env, ['HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy']);
150
+ if (envProxy) {
151
+ const parsed = normalizeProxySpec(envProxy);
152
+ if (parsed) return { proxyUrl: parsed, source: 'env', reason: 'env' };
153
+ }
154
+
155
+ if (systemProxy) {
156
+ const candidate = scheme === 'https' ? systemProxy.https : systemProxy.http;
157
+ if (candidate) {
158
+ const bypass = Array.isArray(systemProxy.bypass) ? systemProxy.bypass : parseBypassList(systemProxy.bypass);
159
+ if (hostMatchesBypass(host, bypass)) return { proxyUrl: null, source: null, reason: 'bypass' };
160
+ return { proxyUrl: candidate, source: 'system', reason: 'system' };
161
+ }
162
+ }
163
+
164
+ return { proxyUrl: null, source: null, reason: 'none' };
165
+ }
166
+
167
+ const SYSTEM_PROXY_TTL_MS = 30000;
168
+ let systemProxyCache = { at: 0, value: null };
169
+
170
+ export function resetSystemProxyCache() {
171
+ systemProxyCache = { at: 0, value: null };
172
+ }
173
+
174
+ function readRegistryValue(text, name) {
175
+ const pattern = new RegExp('^\\s*' + name + '\\s+REG_\\w+\\s+(.*)$', 'im');
176
+ const match = pattern.exec(text);
177
+ return match ? match[1].trim() : '';
178
+ }
179
+
180
+ /**
181
+ * 读 Windows 的「系统代理」(WinINET)。Node 不会自动用它,所以必须自己来。
182
+ * reg.exe 会被缓存,避免每次请求都起进程。
183
+ *
184
+ * 任何失败都只能退化成 null(直连):探测代理这件事永远不能把请求本身搞挂。
185
+ */
186
+ export async function readSystemProxy(options = {}) {
187
+ const platform = options.platform || process.platform;
188
+ const now = Date.now();
189
+ if (!options.noCache && now - systemProxyCache.at < SYSTEM_PROXY_TTL_MS) return systemProxyCache.value;
190
+
191
+ let value = null;
192
+ if (platform === 'win32') {
193
+ const run = typeof options.run === 'function' ? options.run : execFile;
194
+ try {
195
+ value = await new Promise((resolve) => {
196
+ let settled = false;
197
+ const done = (result) => {
198
+ if (settled) return;
199
+ settled = true;
200
+ resolve(result);
201
+ };
202
+ try {
203
+ run('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'],
204
+ { windowsHide: true, timeout: 5000, encoding: 'buffer' },
205
+ (error, stdout) => {
206
+ if (error || !stdout) { done(null); return; }
207
+ try {
208
+ const text = Buffer.from(stdout).toString('latin1');
209
+ const enabled = readRegistryValue(text, 'ProxyEnable');
210
+ if (!/^(0x)?1$/i.test(enabled)) { done(null); return; }
211
+ const server = parseProxyServer(readRegistryValue(text, 'ProxyServer'));
212
+ if (!server.http && !server.https) { done(null); return; }
213
+ done({
214
+ http: server.http,
215
+ https: server.https,
216
+ bypass: parseBypassList(readRegistryValue(text, 'ProxyOverride'))
217
+ });
218
+ } catch (_error) { done(null); }
219
+ });
220
+ } catch (_error) {
221
+ // 沙箱/受限环境里 spawn 可能同步抛 EPERM:直接当成「没有系统代理」。
222
+ done(null);
223
+ }
224
+ setTimeout(() => done(null), 5000).unref?.();
225
+ });
226
+ } catch (_error) {
227
+ value = null;
228
+ }
229
+ }
230
+ systemProxyCache = { at: now, value: value };
231
+ return value;
232
+ }
@@ -0,0 +1,298 @@
1
+ /**
2
+ * 更新状态服务:把「检查 GitHub → 有没有新版 → 装哪个 tag → 装完没有」
3
+ * 收成一个有状态对象,路由和启动预热都只跟它打交道。
4
+ *
5
+ * 自我更新有个绕不开的坑:装新版本时插件自己会被卸载,这次调用等不到结果。
6
+ * 所以状态靠标记文件 + 当前版本号事后判定,见 hydrate()。
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import {
10
+ classifySource, clearMarker, compareVersions, fetchChangelogNotes, fetchLatestVersion,
11
+ judgeMarker, readMarker, writeMarker
12
+ } from './update.js';
13
+
14
+ // 宿主进程启动时刻:process.uptime 是进程年龄,模块重新 import 不会把它重置。
15
+ const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
16
+
17
+ /** 安装 spec:带 tag 的 git 依赖,和用户手动装的那条命令一致。 */
18
+ export const UPDATE_SPEC = (version) => `github:CM-Silence/dsh-mo-image#v${version}`;
19
+
20
+ /**
21
+ * @param {object} options
22
+ * @param {string} options.currentVersion 插件自己的版本号
23
+ * @param {string} [options.markerFile] 标记文件路径
24
+ * @param {Function} [options.request] 出站请求(默认 lib/net.js 的 request)
25
+ * @param {object} [options.pluginManager] DSH 的插件管理器服务
26
+ * @param {(line: string) => void} [options.log] 宿主日志
27
+ * @param {() => number} [options.now]
28
+ * @param {(ms: number) => Promise<void>} [options.sleep]
29
+ * @param {number} [options.installDelayMs] 先让"正在更新"气泡露个脸
30
+ * @param {string} [options.apiBase]
31
+ * @param {string} [options.releasesBase]
32
+ */
33
+ export function createUpdateService(options = {}) {
34
+ const currentVersion = String(options.currentVersion || '0.0.0');
35
+ const markerFile = typeof options.markerFile === 'string' ? options.markerFile : '';
36
+ const request = options.request;
37
+ const pluginManager = options.pluginManager;
38
+ const log = typeof options.log === 'function' ? options.log : () => {};
39
+ const now = typeof options.now === 'function' ? options.now : Date.now;
40
+ const sleep = typeof options.sleep === 'function'
41
+ ? options.sleep
42
+ : (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
43
+ const installDelayMs = Number.isFinite(options.installDelayMs) ? options.installDelayMs : 800;
44
+
45
+ // 服务可能在 pluginManager 就绪之前就建好了(插件加载顺序不保证),
46
+ // 所以这里允许传一个取值函数,每次调用时再解析。
47
+ function manager() {
48
+ const value = typeof pluginManager === 'function' ? pluginManager() : pluginManager;
49
+ return value && typeof value.installBundle === 'function' ? value : null;
50
+ }
51
+
52
+ let phase = 'idle';
53
+ let latest = '';
54
+ let notes = '';
55
+ let url = '';
56
+ let checkedAt = '';
57
+ let error = '';
58
+ let source = '';
59
+ let updatable = false;
60
+ let updatedBeforeRestart = false;
61
+ let refreshing = null;
62
+ let applying = null;
63
+ let disposed = false;
64
+
65
+ async function readSource() {
66
+ const manager_ = manager();
67
+ if (!manager_ || typeof manager_.listBundles !== 'function') return { source: '', updatable: false };
68
+ try {
69
+ const bundles = await manager_.listBundles();
70
+ const hit = (Array.isArray(bundles) ? bundles : []).find((item) => item && item.name === 'dsh-mo-image');
71
+ return {
72
+ source: hit && typeof hit.source === 'string' ? hit.source : '',
73
+ // 只有以 npm 版本安装的包才能走 updateBundle(卸旧装新、失败自动装回)。
74
+ updatable: !!(hit && hit.updatable)
75
+ };
76
+ } catch (_error) {
77
+ return { source: '', updatable: false };
78
+ }
79
+ }
80
+
81
+ function status() {
82
+ return {
83
+ state: phase,
84
+ current: currentVersion,
85
+ latest,
86
+ notes,
87
+ url,
88
+ checkedAt,
89
+ // 没有插件管理器就没法自助更新;本地链接安装同样不行。
90
+ installable: !!manager() && classifySource(source) !== 'link',
91
+ source,
92
+ updatedBeforeRestart: phase === 'done' ? updatedBeforeRestart : false,
93
+ error
94
+ };
95
+ }
96
+
97
+ function safeLog(line) {
98
+ try { log(line); } catch (_error) { /* ignore */ }
99
+ }
100
+
101
+ /** 查一次 npm 上的最新版本;单飞去重,失败只记日志。 */
102
+ async function refresh() {
103
+ if (disposed) return;
104
+ if (refreshing) return refreshing;
105
+ refreshing = (async () => {
106
+ if (phase === 'idle' || phase === 'available') phase = 'checking';
107
+ try {
108
+ const bundle = await readSource();
109
+ if (bundle.source) source = bundle.source;
110
+ updatable = bundle.updatable;
111
+ const release = await fetchLatestVersion({
112
+ request,
113
+ registryBase: options.registryBase,
114
+ mirrorBase: options.mirrorBase,
115
+ onError: (reason) => safeLog('update check failed: ' + String(reason || 'unknown'))
116
+ });
117
+ if (disposed) return;
118
+ checkedAt = new Date(now()).toISOString();
119
+ if (!release) {
120
+ if (phase === 'checking') phase = 'idle';
121
+ error = 'update check failed';
122
+ return;
123
+ }
124
+ const verdict = compareVersions(release.version, currentVersion);
125
+ if (verdict === 1) {
126
+ latest = release.version;
127
+ url = release.url;
128
+ notes = await fetchChangelogNotes(release.version, {
129
+ request,
130
+ cdnSources: options.cdnSources
131
+ });
132
+ } else {
133
+ latest = '';
134
+ notes = '';
135
+ url = '';
136
+ }
137
+ error = '';
138
+ if (phase === 'checking' || phase === 'idle' || phase === 'available') {
139
+ phase = verdict === 1 ? 'available' : 'idle';
140
+ } else if (phase === 'done') {
141
+ // 已经更新完、只是页面还没重启:不要把刚装上的版本号覆盖成"更新版"。
142
+ latest = currentVersion;
143
+ }
144
+ } catch (caught) {
145
+ if (disposed) return;
146
+ checkedAt = new Date(now()).toISOString();
147
+ if (phase === 'checking') phase = 'idle';
148
+ error = 'update check failed';
149
+ safeLog('update check failed: ' + String(caught && caught.message ? caught.message : caught));
150
+ } finally {
151
+ refreshing = null;
152
+ }
153
+ })();
154
+ return refreshing;
155
+ }
156
+
157
+ /**
158
+ * 发起安装。立刻返回(路由不等 pnpm),安装结果通过 status() 与标记文件体现。
159
+ * @param {string} version
160
+ * @returns {Promise<{ok: true}|{ok: false, code: string}>}
161
+ */
162
+ async function apply(version) {
163
+ if (applying) return { ok: true };
164
+ if (phase === 'updating') return { ok: true };
165
+ const to = String(version || latest || '').trim();
166
+ if (!to) return { ok: true };
167
+ if (phase === 'done' && (to === currentVersion || to === latest)) return { ok: true };
168
+ const active = manager();
169
+ if (!active) {
170
+ return { ok: false, code: 'update.unsupported' };
171
+ }
172
+ if (!source || !updatable) {
173
+ const bundle = await readSource();
174
+ if (bundle.source) source = bundle.source;
175
+ updatable = bundle.updatable;
176
+ }
177
+ if (classifySource(source) === 'link') return { ok: false, code: 'update.localDev' };
178
+ if (applying) return { ok: true };
179
+
180
+ const requestId = randomUUID();
181
+ if (markerFile) {
182
+ try {
183
+ writeMarker(markerFile, { from: currentVersion, to, requestId, startedAt: now() });
184
+ } catch (caught) {
185
+ safeLog('update marker write failed: ' + String(caught && caught.message ? caught.message : caught));
186
+ }
187
+ }
188
+ phase = 'updating';
189
+ error = '';
190
+
191
+ const work = (async () => {
192
+ try {
193
+ await sleep(installDelayMs);
194
+ let result;
195
+ if (updatable && typeof active.updateBundle === 'function') {
196
+ // npm 安装:走原生更新,它会在装失败时把旧版本装回来。
197
+ result = await active.updateBundle('dsh-mo-image', to, { requestId });
198
+ } else {
199
+ const spec = UPDATE_SPEC(to);
200
+ const installOptions = { requestId, enabled: true };
201
+ try {
202
+ result = await active.installBundle(spec, installOptions);
203
+ } catch (caught) {
204
+ if (caught && caught.code === 'already-installed') {
205
+ await active.removeBundle('dsh-mo-image');
206
+ result = await active.installBundle(spec, installOptions);
207
+ } else {
208
+ throw caught;
209
+ }
210
+ }
211
+ }
212
+ const application = result && result.result && result.result.application;
213
+ if (application === 'failed' || application === 'cancelled') {
214
+ phase = 'failed';
215
+ error = application;
216
+ if (markerFile) clearMarker(markerFile);
217
+ safeLog('update failed: ' + application);
218
+ return;
219
+ }
220
+ phase = 'done';
221
+ updatedBeforeRestart = false;
222
+ latest = to;
223
+ } catch (caught) {
224
+ phase = 'failed';
225
+ error = String(caught && caught.message ? caught.message : caught);
226
+ if (markerFile) clearMarker(markerFile);
227
+ safeLog('update failed: ' + error);
228
+ }
229
+ })();
230
+
231
+ applying = work;
232
+ work.finally(() => { applying = null; });
233
+ return { ok: true };
234
+ }
235
+
236
+ /**
237
+ * 启动时读标记文件:上一次更新到底成没成。
238
+ * - 当前版本已经等于目标 → done(本次会话第一次加载就说"更新完成")
239
+ * - 仍是旧版本且超时 → failed
240
+ * - 仍在进行中 → updating
241
+ */
242
+ async function hydrate() {
243
+ if (!markerFile) return;
244
+ const marker = readMarker(markerFile);
245
+ if (!marker) {
246
+ if (phase === 'done' || phase === 'failed') { phase = 'idle'; error = ''; }
247
+ return;
248
+ }
249
+ const verdict = judgeMarker(marker, currentVersion, now());
250
+ if (verdict.state === 'stale') {
251
+ clearMarker(markerFile);
252
+ return;
253
+ }
254
+ if (verdict.state === 'done') {
255
+ latest = verdict.to || latest;
256
+ phase = 'done';
257
+ updatedBeforeRestart = (Number(marker.startedAt) || 0) < PROCESS_STARTED_AT;
258
+ clearMarker(markerFile);
259
+ return;
260
+ }
261
+ if (verdict.state === 'failed') {
262
+ latest = verdict.to || latest;
263
+ phase = 'failed';
264
+ error = 'update incomplete';
265
+ clearMarker(markerFile);
266
+ return;
267
+ }
268
+ if (verdict.state === 'updating') {
269
+ latest = verdict.to || latest;
270
+ phase = 'updating';
271
+ }
272
+ }
273
+
274
+ /** 客户端弹完气泡后的回执:同一件事不再重复提示。 */
275
+ async function ack() {
276
+ if (markerFile) clearMarker(markerFile);
277
+ if (phase === 'done' || phase === 'failed') {
278
+ phase = latest && compareVersions(latest, currentVersion) === 1 ? 'available' : 'idle';
279
+ error = '';
280
+ }
281
+ return { ok: true };
282
+ }
283
+
284
+ return {
285
+ status,
286
+ refresh,
287
+ apply,
288
+ hydrate,
289
+ ack,
290
+ /** 等到当前安装结束(测试与调试用;正常路径不需要等它)。 */
291
+ settled: () => (applying ? applying.catch(() => {}) : Promise.resolve()),
292
+ dispose() {
293
+ disposed = true;
294
+ refreshing = null;
295
+ applying = null;
296
+ }
297
+ };
298
+ }