From f3ca7a8f2b694df082c7e2e1ba826029f8703eff Mon Sep 17 00:00:00 2001 From: K <704496037@qq.com> Date: Sun, 30 Aug 2026 14:43:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=9D=E8=AF=95=20=E4=BF=AE=E5=A4=8D=20Egern?= =?UTF-8?q?=20=E8=AF=B7=E6=B1=82=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/package.json | 2 +- backend/src/restful/download.js | 27 +++- backend/src/restful/miscs.js | 87 ++++++++++-- backend/src/utils/gist.js | 44 ++++-- backend/src/vendor/express.js | 4 +- backend/src/vendor/open-api.js | 231 +++++++++++++++++++++----------- 6 files changed, 287 insertions(+), 108 deletions(-) diff --git a/backend/package.json b/backend/package.json index c917fc13..a190159c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.36.40", + "version": "2.36.50", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", diff --git a/backend/src/restful/download.js b/backend/src/restful/download.js index b65366c4..38ad7edc 100644 --- a/backend/src/restful/download.js +++ b/backend/src/restful/download.js @@ -923,10 +923,29 @@ async function nezhaMonitor(proxy, index, query) { }; try { - const { isLoon, isSurge } = $.env; - if (!isLoon && !isSurge) - throw new Error('仅支持 Loon 和 Surge(ability=http-client-policy)'); - const node = ProxyUtils.produce([proxy], isLoon ? 'Loon' : 'Surge'); + const { isLoon, isSurge, isEgern } = $.env; + if (!isLoon && !isSurge && !isEgern) + throw new Error( + '仅支持 Loon、Egern 和 Surge(ability=http-client-policy)', + ); + // const node = ProxyUtils.produce([proxy], isLoon ? 'Loon' : 'Surge'); + let node; + if (isEgern) { + node = JSON.stringify( + ProxyUtils.produce([proxy], 'Egern', 'internal', { + 'include-unsupported-proxy': includeUnsupportedProxy, + })[0], + ); + } else { + node = ProxyUtils.produce( + [proxy], + isLoon ? 'Loon' : 'Surge', + undefined, + { + 'include-unsupported-proxy': includeUnsupportedProxy, + }, + ); + } if (!node) throw new Error('当前客户端不兼容此节点'); const monitors = proxy._monitors || [ { diff --git a/backend/src/restful/miscs.js b/backend/src/restful/miscs.js index daae7ec6..e5275aa0 100644 --- a/backend/src/restful/miscs.js +++ b/backend/src/restful/miscs.js @@ -272,27 +272,37 @@ async function gistBackupAction( ); switch (action) { case 'upload': + const gists = await gist.locate(); + + let backupContent; + try { const keepAgeSecretKey = isAgeGistBackupEncoding(encoding); - content = serializeGistBackupContent( + + backupContent = serializeGistBackupContent( readCurrentBackupContent(), getGistBackupPayloadEncoding(encoding), { keepAgeSecretKey }, ); $.info(`下载备份, 与本地内容对比...`); + const downloadedContent = await gist.download( GIST_BACKUP_FILE_NAME, + gists, ); + const onlineContent = await decryptGistBackupContent( downloadedContent, settings, encoding, ); + const canReuseOnlineContent = !isAgeGistBackupEncoding(encoding) || isAgeArmor(downloadedContent); - if (canReuseOnlineContent && onlineContent === content) { + + if (canReuseOnlineContent && onlineContent === backupContent) { $.info(`内容一致, 无需上传备份`); return; } @@ -303,24 +313,81 @@ async function gistBackupAction( // update syncTime settings.syncTime = new Date().getTime(); $.write(settings, SETTINGS_KEY); - content = serializeGistBackupContent( + + // 重新生成,避免前面的逻辑改变了状态 + backupContent = serializeGistBackupContent( readCurrentBackupContent(), getGistBackupPayloadEncoding(encoding), - { keepAgeSecretKey: isAgeGistBackupEncoding(encoding) }, + { + keepAgeSecretKey: isAgeGistBackupEncoding(encoding), + }, ); - content = await encryptGistBackupContent( - content, + + const uploadContent = await encryptGistBackupContent( + backupContent, settings, encoding, ); + $.info(`上传备份中...`); + await $.wait(100); try { - await gist.upload({ - [GIST_BACKUP_FILE_NAME]: { content }, - }); + await gist.upload( + { + [GIST_BACKUP_FILE_NAME]: { + content: uploadContent, + }, + }, + {}, + gists, + ); + $.info(`上传备份完成`); } catch (err) { - // restore syncTime if upload failed + $.error(`上传请求异常: ${err?.message ?? err}`); + + /* + * PATCH 可能已经成功, + * 只是没有收到 callback。 + * + * 因此先重新 GET 确认。 + */ + try { + $.info(`重新获取备份, 确认上传结果...`); + await $.wait(500); + const downloadedContent = await gist.download( + GIST_BACKUP_FILE_NAME, + gists, + ); + + const onlineContent = await decryptGistBackupContent( + downloadedContent, + settings, + encoding, + ); + + const canReuseOnlineContent = + !isAgeGistBackupEncoding(encoding) || + isAgeArmor(downloadedContent); + + if ( + canReuseOnlineContent && + onlineContent === backupContent + ) { + $.info(`线上内容与本次上传内容一致, 上传实际已成功`); + + break; + } + + $.error(`线上内容与本次上传内容不一致, 上传确认失败`); + } catch (verifyError) { + $.error( + `上传结果确认失败: ${ + verifyError?.message ?? verifyError + }`, + ); + } + settings.syncTime = updated; $.write(settings, SETTINGS_KEY); throw err; diff --git a/backend/src/utils/gist.js b/backend/src/utils/gist.js index 3fe4a432..3daa6ddd 100644 --- a/backend/src/utils/gist.js +++ b/backend/src/utils/gist.js @@ -151,6 +151,24 @@ export default class Gist { this.key = key; this.syncPlatform = syncPlatform; + + // 串行请求队列锁 防止响应串扰 + this._requestQueue = Promise.resolve(); + const queuedMethods = ['get', 'post', 'put', 'patch', 'delete']; + for (const method of queuedMethods) { + const original = this.http[method]; + if (typeof original === 'function') { + this.http[method] = (...args) => { + return new Promise((resolve, reject) => { + this._requestQueue = this._requestQueue.then(() => + original + .apply(this.http, args) + .then(resolve, reject), + ); + }); + }; + } + } } async locate() { @@ -181,25 +199,25 @@ export default class Gist { } } - async upload(input, options = {}) { + async upload(input, options = {}, gists) { if (Object.keys(input).length === 0) { return Promise.reject('未提供需上传的文件'); } - const gist = await this.locate(); + const gist = gists !== undefined ? gists : await this.locate(); let files = input; const emptyFileFallback = options.emptyFileFallback; const hasEmptyFileFallback = Boolean(emptyFileFallback?.filename); const uploadMeta = {}; - const attachUploadMeta = (request) => - request.then((response) => { - if (Object.keys(uploadMeta).length > 0) { - response.subStoreUploadMeta = uploadMeta; - } - return response; - }); + const attachUploadMeta = async (request) => { + const response = await request; + if (Object.keys(uploadMeta).length > 0) { + response.subStoreUploadMeta = uploadMeta; + } + return response; + }; const applyEmptyFileFallback = ({ actions, existingFiles, result }) => { if (!hasEmptyFileFallback) return; @@ -338,6 +356,10 @@ export default class Gist { return attachUploadMeta( this.http.patch({ url: `/gists/${gist.id}`, + headers: { + ...this.headers, + 'Accept-Encoding': 'gzip, deflate, br', + }, body: JSON.stringify({ files }), }), ); @@ -393,8 +415,8 @@ export default class Gist { } } - async download(filename) { - const gist = await this.locate(); + async download(filename, gists) { + const gist = gists !== undefined ? gists : await this.locate(); if (gist?.id) { try { const { files } = await this.http diff --git a/backend/src/vendor/express.js b/backend/src/vendor/express.js index 470eab30..1921aeb9 100644 --- a/backend/src/vendor/express.js +++ b/backend/src/vendor/express.js @@ -241,7 +241,7 @@ export default function express({ substore: $, port, host }) { function Response(corsHeaders = {}) { let statusCode = 200; - const { isQX, isLoon, isSurge, isGUIforCores } = ENV(); + const { isQX, isLoon, isSurge, isGUIforCores, isEgern } = ENV(); const headers = { ...DEFAULT_HEADERS, ...corsHeaders, @@ -270,7 +270,7 @@ export default function express({ substore: $, port, host }) { }; if (isQX || isGUIforCores) { $done(response); - } else if (isLoon || isSurge) { + } else if (isLoon || isSurge || isEgern) { $done({ response, }); diff --git a/backend/src/vendor/open-api.js b/backend/src/vendor/open-api.js index 6254d423..4f4d56fe 100644 --- a/backend/src/vendor/open-api.js +++ b/backend/src/vendor/open-api.js @@ -3,13 +3,14 @@ import { installConsoleLogCapture } from '@/utils/debug-logs'; const isQX = typeof $task !== 'undefined'; const isLoon = typeof $loon !== 'undefined'; +const isEgern = 'undefined' !== typeof Egern; // 可能有一些兼容环境依赖于这个, 先不改成 $environment.surge-version -const isSurge = typeof $httpClient !== 'undefined' && !isLoon; +const isSurge = typeof $httpClient !== 'undefined' && !isLoon && !isEgern; const isNode = eval(`typeof process !== "undefined"`); // eval is needed in order to avoid browserify processing const isStash = 'undefined' !== typeof $environment && $environment['stash-version']; const isShadowRocket = 'undefined' !== typeof $rocket; -const isEgern = 'undefined' !== typeof Egern && Egern.version; + const isLanceX = 'undefined' != typeof $native; const isGUIforCores = typeof $Plugins !== 'undefined'; import { Base64 } from 'js-base64'; @@ -105,7 +106,7 @@ export class OpenAPI { initCache() { if (isQX) this.cache = JSON.parse($prefs.valueForKey(this.name) || '{}'); - if (isLoon || isSurge) + if (isLoon || isSurge || isEgern) this.cache = JSON.parse($persistentStore.read(this.name) || '{}'); if (isGUIforCores) this.cache = JSON.parse( @@ -182,7 +183,8 @@ export class OpenAPI { persistCache() { const data = JSON.stringify(this.cache, null, 2); if (isQX) $prefs.setValueForKey(data, this.name); - if (isLoon || isSurge) $persistentStore.write(data, this.name); + if (isLoon || isSurge || isEgern) + $persistentStore.write(data, this.name); if (isGUIforCores) $Plugins.SubStoreCache.set(this.name, data); if (isNode) { const basePath = @@ -207,7 +209,7 @@ export class OpenAPI { this.log(`SET ${key}`); if (key.indexOf('#') !== -1) { key = key.substr(1); - if (isSurge || isLoon) { + if (isSurge || isLoon || isEgern) { return $persistentStore.write(data, key); } if (isQX) { @@ -229,7 +231,7 @@ export class OpenAPI { this.log(`READ ${key}`); if (key.indexOf('#') !== -1) { key = key.substr(1); - if (isSurge || isLoon) { + if (isSurge || isLoon || isEgern) { return $persistentStore.read(key); } if (isQX) { @@ -250,7 +252,7 @@ export class OpenAPI { this.log(`DELETE ${key}`); if (key.indexOf('#') !== -1) { key = key.substr(1); - if (isSurge || isLoon) { + if (isSurge || isLoon || isEgern) { return $persistentStore.write(null, key); } if (isQX) { @@ -274,7 +276,7 @@ export class OpenAPI { const mediaURL = options['media-url']; if (isQX) $notify(title, subtitle, content, options); - if (isSurge) { + if (isSurge || isEgern) { $notification.post( title, subtitle, @@ -387,7 +389,7 @@ export class OpenAPI { } done(value = {}) { - if (isQX || isLoon || isSurge || isGUIforCores) { + if (isQX || isLoon || isSurge || isGUIforCores || isEgern) { $done(value); } else if (isNode) { if (typeof $context !== 'undefined') { @@ -414,7 +416,7 @@ export function ENV() { } export function HTTP(defaultOptions = { baseURL: '' }) { - const { isQX, isLoon, isSurge, isNode, isGUIforCores } = ENV(); + const { isQX, isLoon, isSurge, isNode, isGUIforCores, isEgern } = ENV(); const methods = [ 'GET', 'POST', @@ -427,14 +429,21 @@ export function HTTP(defaultOptions = { baseURL: '' }) { const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/; - function send(method, options) { + let requestIdCounter = 0; + + function generateRequestId() { + return `${Date.now()}-${++requestIdCounter}`; + } + + async function send(method, options) { options = typeof options === 'string' ? { url: options } : options; const baseURL = defaultOptions.baseURL; if (baseURL && !URL_REGEX.test(options.url || '')) { options.url = baseURL ? baseURL + options.url : options.url; } options = { ...defaultOptions, ...options }; - const timeout = options.timeout; + const timeout = (Number(options.timeout) || 0) + 100; + const requestId = options.requestId || generateRequestId(); const events = { ...{ onRequest: () => {}, @@ -466,28 +475,18 @@ export function HTTP(defaultOptions = { baseURL: '' }) { body: options.body, opts: options.opts, }); - } else if (isLoon || isSurge || isNode) { - const run = async (resolve, reject) => { + } else if (isLoon || isSurge || isNode || isEgern) { + worker = new Promise(async (resolve, reject) => { const body = options.body; const opts = JSON.parse(JSON.stringify(options)); + opts.body = body; opts.timeout = opts.timeout || 8000; - if (opts.timeout) { - opts.timeout++; - if (isNaN(opts.timeout)) { - opts.timeout = 8000; - } - if (!isNode) { - let unit = 'ms'; - // 这些客户端单位为 s - if (isSurge || isStash || isShadowRocket) { - opts.timeout = Math.ceil(opts.timeout / 1000); - unit = 's'; - } - // Loon 为 ms - // console.log(`[httpClient timeout] ${opts.timeout}${unit}`); - } + + if (isNaN(opts.timeout)) { + opts.timeout = 8000; } + if (isNode) { const undici = eval("require('undici')"); const { socksDispatcher } = eval("require('fetch-socks')"); @@ -580,7 +579,7 @@ export function HTTP(defaultOptions = { baseURL: '' }) { proxyTunnel: opts.proxyTunnel, }); } - const response = await request(opts.url, { + request(opts.url, { ...opts, method: method.toUpperCase(), dispatcher: dispatcher.compose( @@ -589,47 +588,71 @@ export function HTTP(defaultOptions = { baseURL: '' }) { throwOnMaxRedirect: true, }), ), - }); - resolve({ - statusCode: response.statusCode, - headers: response.headers, - body: - opts.encoding === null - ? await response.body.arrayBuffer() - : await response.body.text(), - }); + }) + .then(async (response) => { + const responseBody = + opts.encoding === null + ? await response.body.arrayBuffer() + : await response.body.text(); + + resolve({ + statusCode: response.statusCode, + headers: response.headers, + body: responseBody, + requestId, + }); + }) + .catch(reject); } catch (e) { reject(e); } } else { - $httpClient[method.toLowerCase()]( - opts, - (err, response, body) => { - // if (err) { - // console.log(err); - // } else { - // console.log({ - // statusCode: - // response.status || response.statusCode, - // headers: response.headers, - // body, - // }); - // } + if (isSurge || isStash || isShadowRocket) { + opts.timeout = Math.ceil(opts.timeout / 1000); + } + + // $.info(`🍉 [${requestId}] before http`); + // $.info( + // `🍉 [${requestId}] opts.timeout =`, + // opts.timeout, + // ); + + // $.info( + // `🍉 [${requestId}] method =`, + // method.toUpperCase(), + // ); + // const httpClientTs = Date.now(); + try { + await $httpClient[method.toLowerCase()]( + opts, + (err, response, body) => { + // $.info( + // ` [${requestId}] callback ${ + // Date.now() - httpClientTs + // }ms`, + // ); + + if (err) { + $.error(err); + reject(err); + return; + } - if (err) reject(err); - else resolve({ statusCode: - response.status || response.statusCode, - headers: response.headers, + response?.status || + response?.statusCode, + headers: response?.headers || {}, body, + requestId, }); - }, - ); + }, + ); + } catch (e) { + $.error(e); + reject(e); + } } - }; - worker = new Promise((resolve, reject) => { - run(resolve, reject).catch(reject); }); } else if (isGUIforCores) { worker = new Promise(async (resolve, reject) => { @@ -651,6 +674,7 @@ export function HTTP(defaultOptions = { baseURL: '' }) { statusCode: response.status, headers: response.headers, body: response.body, + requestId, }); } catch (error) { reject(error); @@ -658,28 +682,75 @@ export function HTTP(defaultOptions = { baseURL: '' }) { }); } - let timeoutid; + return new Promise((resolve, reject) => { + let settled = false; + let settling = false; + let timeoutid = null; - const timer = timeout - ? new Promise((_, reject) => { - // console.log(`[request timeout] ${timeout}ms`); - timeoutid = setTimeout(() => { - events.onTimeout(); - return reject( - `${method} URL: ${options.url} exceeds the timeout ${timeout} ms`, - ); - }, timeout); - }) - : null; - - const request = timer ? Promise.race([timer, worker]) : worker; - return request - .finally(() => { - if (timer && typeof clearTimeout !== 'undefined') { + const cleanup = () => { + if (timeoutid !== null) { clearTimeout(timeoutid); + timeoutid = null; } - }) - .then((resp) => events.onResponse(resp)); + }; + + const resolveOnce = async (value) => { + if (settled || settling) return; + settling = true; + + try { + await Promise.resolve(events.onResponse(value)); + if (settled) return; + settled = true; + cleanup(); + resolve({ ...value, requestId }); + } catch (error) { + if (settled) return; + settled = true; + cleanup(); + reject(error); + } + }; + + const rejectOnce = (error) => { + if (settled) return; + settled = true; + cleanup(); + reject(error); + }; + + worker.then( + async (value) => { + // $.info(`🍉 [${requestId}] worker resolved`); + try { + await resolveOnce(value); + } catch (error) { + $.error(error); + } + }, + (error) => { + rejectOnce(error); + }, + ); + + if (timeout && !isEgern) { + timeoutid = setTimeout(() => { + if (settled) { + return; + } + + try { + events.onTimeout(); + } catch (e) { + $.error(e); + } + + rejectOnce( + `${method} URL: ${options.url} exceeds the timeout ${timeout} ms`, + ); + }, timeout); + } + }); } const http = {