diff --git a/backend/package.json b/backend/package.json index 1f80ac32..da79de0d 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.36.27", + "version": "2.36.28", "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/core/proxy-utils/index.js b/backend/src/core/proxy-utils/index.js index 30b4f77e..be2614d3 100644 --- a/backend/src/core/proxy-utils/index.js +++ b/backend/src/core/proxy-utils/index.js @@ -141,6 +141,7 @@ async function processFn( source, $options, raw, + executionContext = {}, ) { let context = {}; if (raw !== undefined) { @@ -182,7 +183,10 @@ async function processFn( let script; let $arguments = {}; if (item.type.indexOf('Script') !== -1) { - ({ script, $arguments } = await loadScriptItem(item)); + ({ script, $arguments } = await loadScriptItem( + item, + executionContext, + )); } if (!PROXY_PROCESSORS[item.type]) { @@ -206,7 +210,10 @@ async function processFn( context, ); } else { - processor = PROXY_PROCESSORS[item.type](item.args || {}); + processor = PROXY_PROCESSORS[item.type]( + item.args || {}, + executionContext, + ); } proxies = await ApplyProcessor(processor, proxies); } @@ -219,6 +226,7 @@ async function processResponseFn( targetPlatform, source, $options, + executionContext = {}, ) { let context = {}; let output = normalizeResponse(response); @@ -243,7 +251,10 @@ async function processResponseFn( continue; } - const { script, $arguments } = await loadScriptItem(item); + const { script, $arguments } = await loadScriptItem( + item, + executionContext, + ); $.log( `Applying "${item.type}" with arguments:\n >>> ${ JSON.stringify(item.args, null, 2) || 'None' @@ -264,7 +275,7 @@ async function processResponseFn( return output; } -async function loadScriptItem(item) { +async function loadScriptItem(item, executionContext = {}) { let script; let $arguments = {}; const { mode, content } = item.args || {}; @@ -319,6 +330,7 @@ async function loadScriptItem(item) { script = await produceArtifact({ type: 'file', name, + noFlow: executionContext.noFlow, }); } } catch (err) { @@ -341,7 +353,17 @@ async function loadScriptItem(item) { } else { // if this is a remote script, download it try { - script = await download(url); + script = await download( + url, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + { noFlow: executionContext.noFlow }, + ); // $.info(`Script loaded: >>>\n ${script}`); } catch (err) { $.error( diff --git a/backend/src/core/proxy-utils/processors/index.js b/backend/src/core/proxy-utils/processors/index.js index b0820883..5af6d44c 100644 --- a/backend/src/core/proxy-utils/processors/index.js +++ b/backend/src/core/proxy-utils/processors/index.js @@ -527,12 +527,15 @@ function getMihomoProfileProxies(config) { return Array.isArray(config?.proxies) ? config.proxies : []; } -function AddProxiesFromSubscriptionOperator({ - sourceType = 'subscription', - sourceName, - includeUnsupportedProxy, - position = 'replace', -} = {}) { +function AddProxiesFromSubscriptionOperator( + { + sourceType = 'subscription', + sourceName, + includeUnsupportedProxy, + position = 'replace', + } = {}, + executionContext = {}, +) { const apply = async (input) => { if (!isMihomoConfigFile(input?.$file)) return input; @@ -547,6 +550,7 @@ function AddProxiesFromSubscriptionOperator({ 'delete-underscore-fields': true, 'include-unsupported-proxy': includeUnsupportedProxy, }, + noFlow: executionContext.noFlow, }); switch (position) { diff --git a/backend/src/restful/download.js b/backend/src/restful/download.js index cd867346..b65366c4 100644 --- a/backend/src/restful/download.js +++ b/backend/src/restful/download.js @@ -291,6 +291,9 @@ async function downloadSubscription(req, res) { if (noCache) { $.info(`指定不使用缓存: ${noCache}`); } + if (req.query.noFlow) { + $.info(`指定不查询订阅流量信息: ${req.query.noFlow}`); + } const allSubs = $.read(SUBS_KEY); const fakeSub = _fakeNode ? { @@ -306,6 +309,7 @@ async function downloadSubscription(req, res) { const sub = (_fakeNode || _fakeSub) ? fakeSub : findByName(allSubs, name); if (sub) { try { + const noFlow = req.query.noFlow || sub.noFlow; const passThroughUA = sub.passThroughUA; if (passThroughUA) { $.info( @@ -335,6 +339,7 @@ async function downloadSubscription(req, res) { $options, proxy, noCache, + noFlow, }; if (_fakeNode || _fakeSub) { if(_fakeNode) { @@ -377,7 +382,11 @@ async function downloadSubscription(req, res) { } } } - if (!$arguments.noFlow && /^https?/.test(url)) { + if ( + !noFlow && + !$arguments.noFlow && + /^https?/.test(url) + ) { // forward flow headers flowInfo = await getFlowHeaders( $arguments?.insecure ? `${url}#insecure` : url, @@ -414,7 +423,7 @@ async function downloadSubscription(req, res) { ); } } - if (sub.subUserinfo) { + if (!noFlow && sub.subUserinfo) { let subUserInfo; if (/^https?:\/\//.test(sub.subUserinfo)) { try { @@ -499,6 +508,7 @@ async function downloadSubscription(req, res) { targetPlatform: platform, source: { [sub.name]: sub }, $options, + executionContext: { noFlow }, }); res.send( await applyAgeOutputEncryption({ @@ -644,9 +654,13 @@ async function downloadCollection(req, res) { if (noCache) { $.info(`指定不使用缓存: ${noCache}`); } + if (req.query.noFlow) { + $.info(`指定不查询订阅流量信息: ${req.query.noFlow}`); + } if (collection) { try { + const noFlow = req.query.noFlow || collection.noFlow; let output = await produceArtifact({ type: 'collection', name, @@ -665,11 +679,12 @@ async function downloadCollection(req, res) { $options, proxy, noCache, + noFlow, ua: reqUA, }); let subUserInfoOfSub; // 默认透传第一个子订阅的流量信息,除非 firstSubFlow 显式设置为 false - if (collection.firstSubFlow !== false) { + if (!noFlow && collection.firstSubFlow !== false) { // forward flow header from the first subscription in this collection const allSubs = $.read(SUBS_KEY); const subnames = collection.subscriptions; @@ -707,7 +722,11 @@ async function downloadCollection(req, res) { } } } - if (!$arguments.noFlow && /^https?:/.test(url)) { + if ( + !sub.noFlow && + !$arguments.noFlow && + /^https?:/.test(url) + ) { subUserInfoOfSub = await getFlowHeaders( $arguments?.insecure ? `${url}#insecure` @@ -729,7 +748,7 @@ async function downloadCollection(req, res) { ); } } - if (sub.subUserinfo) { + if (!sub.noFlow && sub.subUserinfo) { let subUserInfo; if (/^https?:\/\//.test(sub.subUserinfo)) { try { @@ -764,24 +783,26 @@ async function downloadCollection(req, res) { } let subUserInfoOfCol; - if (/^https?:\/\//.test(collection.subUserinfo)) { - try { - subUserInfoOfCol = await getFlowHeaders( - undefined, - undefined, - undefined, - proxy || collection.proxy, - collection.subUserinfo, - ); - } catch (e) { - $.error( - `组合订阅 ${name} 使用自定义流量链接 ${ - collection.subUserinfo - } 获取流量信息时发生错误: ${JSON.stringify(e)}`, - ); + if (!noFlow) { + if (/^https?:\/\//.test(collection.subUserinfo)) { + try { + subUserInfoOfCol = await getFlowHeaders( + undefined, + undefined, + undefined, + proxy || collection.proxy, + collection.subUserinfo, + ); + } catch (e) { + $.error( + `组合订阅 ${name} 使用自定义流量链接 ${ + collection.subUserinfo + } 获取流量信息时发生错误: ${JSON.stringify(e)}`, + ); + } + } else { + subUserInfoOfCol = collection.subUserinfo; } - } else { - subUserInfoOfCol = collection.subUserinfo; } const subUserInfo = [subUserInfoOfCol, subUserInfoOfSub] .filter((i) => i) @@ -846,6 +867,7 @@ async function downloadCollection(req, res) { targetPlatform: platform, source: { _collection: collection }, $options, + executionContext: { noFlow }, }); res.send( await applyAgeOutputEncryption({ diff --git a/backend/src/restful/response-transformer.js b/backend/src/restful/response-transformer.js index f2b75057..a163d1bc 100644 --- a/backend/src/restful/response-transformer.js +++ b/backend/src/restful/response-transformer.js @@ -37,6 +37,7 @@ export async function applyResponseTransformers({ targetPlatform, source, $options, + executionContext, }) { const currentHeaders = getCurrentHeaders(res); const transformed = await ProxyUtils.processResponse( @@ -49,6 +50,7 @@ export async function applyResponseTransformers({ targetPlatform, source, $options, + executionContext, ); setHeaders(res, currentHeaders, transformed.header || transformed.headers); setStatus(res, transformed.status || transformed.statusCode); diff --git a/backend/src/restful/subscriptions.js b/backend/src/restful/subscriptions.js index b411804e..04a5e9d3 100644 --- a/backend/src/restful/subscriptions.js +++ b/backend/src/restful/subscriptions.js @@ -65,6 +65,18 @@ async function getFlowInfo(req, res) { ); return; } + if (req.query.noFlow || sub.noFlow) { + failed( + res, + new RequestInvalidError( + 'NO_FLOW_INFO', + 'N/A', + `Subscription ${name}: noFlow`, + ), + 400, + ); + return; + } if ( sub.source === 'local' && !['localFirst', 'remoteFirst'].includes(sub.mergeSources) diff --git a/backend/src/restful/sync.js b/backend/src/restful/sync.js index f8d94f8e..dcef4ea2 100644 --- a/backend/src/restful/sync.js +++ b/backend/src/restful/sync.js @@ -97,6 +97,7 @@ async function downloadFileSources({ ua, proxy, noCache, + noFlow, ignoreFailedRemoteFile, notifyTitle = '🌍 Sub-Store 处理文件失败', }) { @@ -120,6 +121,8 @@ async function downloadFileSources({ undefined, undefined, noCache, + undefined, + { noFlow }, ); } catch (err) { errors[url] = err; @@ -167,6 +170,7 @@ async function resolveFileRawContent( ignoreFailedRemoteFile, proxy, noCache, + noFlow, notifyTitle, } = {}, ) { @@ -181,6 +185,7 @@ async function resolveFileRawContent( ua, proxy, noCache, + noFlow, ignoreFailedRemoteFile, notifyTitle, }); @@ -205,6 +210,7 @@ async function resolveFileRawContent( ua, proxy, noCache, + noFlow, ignoreFailedRemoteFile, notifyTitle, }); @@ -256,6 +262,7 @@ async function prepareMihomoProfileContent(file, sourceOptions = {}) { 'delete-underscore-fields': true, 'include-unsupported-proxy': file?.includeUnsupportedProxy, }, + noFlow: sourceOptions.noFlow, }); } return ProxyUtils.yaml.safeDump(config); @@ -279,6 +286,7 @@ async function produceArtifact({ $options, proxy, noCache, + noFlow, all, }) { platform = platform || 'JSON'; @@ -298,6 +306,7 @@ async function produceArtifact({ ignoreFailedRemoteSub, sub.ignoreFailedRemoteSub, ); + const skipFlow = noFlow || sub.noFlow; try { let raw; @@ -326,7 +335,7 @@ async function produceArtifact({ awaitCustomCache, noCache || sub.noCache, true, - { returnRaw: true }, + { returnRaw: true, noFlow: skipFlow }, ); } catch (err) { errors[url] = err; @@ -391,7 +400,7 @@ async function produceArtifact({ awaitCustomCache, noCache || sub.noCache, true, - { returnRaw: true }, + { returnRaw: true, noFlow: skipFlow }, ); } catch (err) { errors[url] = err; @@ -453,6 +462,7 @@ async function produceArtifact({ { [sub.name]: sub }, $options, sourceRaw, + { noFlow: skipFlow }, ); if (proxies.length === 0) { throw new Error(`订阅 ${name} 中不含有效节点`); @@ -530,6 +540,7 @@ async function produceArtifact({ ignoreFailedRemoteSub, collection.ignoreFailedRemoteSub, ); + const skipFlow = noFlow || collection.noFlow; try { const results = {}; @@ -583,7 +594,11 @@ async function produceArtifact({ undefined, noCache || sub.noCache, true, - { returnRaw: true }, + { + returnRaw: true, + noFlow: + skipFlow || sub.noFlow, + }, ); } catch (err) { errors[url] = err; @@ -655,6 +670,7 @@ async function produceArtifact({ }, undefined, currentRaw, + { noFlow: skipFlow || sub.noFlow }, ); results[name] = currentProxies; rawResults[name] = currentRaw; @@ -759,6 +775,7 @@ async function produceArtifact({ { _collection: collection }, $options, rawResults, + { noFlow: skipFlow }, ); if (proxies.length === 0) { throw new Error(`组合订阅 ${name} 中不含有效节点`); @@ -862,6 +879,7 @@ async function produceArtifact({ ignoreFailedRemoteFile, proxy, noCache, + noFlow, }); } else { raw = await resolveFileRawContent(file, { @@ -872,6 +890,7 @@ async function produceArtifact({ ignoreFailedRemoteFile, proxy, noCache, + noFlow, }); } if (produceType === 'raw') { @@ -891,6 +910,11 @@ async function produceArtifact({ $file: file, }, file.process, + undefined, + undefined, + undefined, + undefined, + { noFlow }, ) : { $content: filesContent, $files: files, $options }; diff --git a/backend/src/test/restful/download.spec.js b/backend/src/test/restful/download.spec.js index 1e850069..48861ebb 100644 --- a/backend/src/test/restful/download.spec.js +++ b/backend/src/test/restful/download.spec.js @@ -1,13 +1,15 @@ import { expect } from 'chai'; import { after, before, beforeEach, describe, it } from 'mocha'; -import { COLLECTIONS_KEY, SUBS_KEY } from '@/constants'; +import { COLLECTIONS_KEY, FILES_KEY, SUBS_KEY } from '@/constants'; const UUID = '11111111-1111-4111-8111-111111111111'; const VLESS_WS = `vless://${UUID}@1.1.1.1:443?security=tls&type=ws&host=cdn.example.com&path=%2Fws&sni=sni.example.com#VLESS%20WS`; let $; +let openApi; let registerDownloadRoutes; +let registerSubscriptionRoutes; let originalError; let originalInfo; let originalNotify; @@ -26,6 +28,31 @@ function createRouteApp() { handlers.set(`GET ${pattern}`, handler); return this; }, + route(pattern) { + const chain = { + get(handler) { + handlers.set(`GET ${pattern}`, handler); + return chain; + }, + patch(handler) { + handlers.set(`PATCH ${pattern}`, handler); + return chain; + }, + delete(handler) { + handlers.set(`DELETE ${pattern}`, handler); + return chain; + }, + post(handler) { + handlers.set(`POST ${pattern}`, handler); + return chain; + }, + put(handler) { + handlers.set(`PUT ${pattern}`, handler); + return chain; + }, + }; + return chain; + }, }; } @@ -35,6 +62,12 @@ function getHandler(pattern) { return app.handlers.get(`GET ${pattern}`); } +function getSubscriptionHandler(pattern) { + const app = createRouteApp(); + registerSubscriptionRoutes(app); + return app.handlers.get(`GET ${pattern}`); +} + function createResponse(routePath) { return { headers: {}, @@ -136,6 +169,21 @@ async function requestDownloadCollection(query) { return res; } +async function requestSubscriptionFlow(query) { + const handler = getSubscriptionHandler('/api/sub/flow/:name'); + const res = createResponse('/api/sub/flow/:name'); + + await handler( + { + params: { name: 'local-vless' }, + query, + }, + res, + ); + + return res; +} + async function requestShareSubscription({ query = {}, shareToken } = {}) { const handler = getHandler('/share/sub/:name'); const res = createResponse('/share/sub/:name'); @@ -171,7 +219,11 @@ async function expectDecryptFailure(armored, secretKey) { describe('download routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); + openApi = require('@/vendor/open-api'); ({ default: registerDownloadRoutes } = require('@/restful/download')); + ({ default: registerSubscriptionRoutes } = require( + '@/restful/subscriptions' + )); ageUtils = require('@/utils/age'); originalRead = $.read.bind($); @@ -222,6 +274,311 @@ describe('download routes', function () { $.notify = () => {}; }); + it('uses truthiness for subscription noFlow query values', async function () { + state[SUBS_KEY][0].subUserinfo = + 'upload=1; download=2; total=3; expire=4'; + + const queryOmitted = await requestDownloadSubscription({ + target: 'JSON', + }); + expect(queryOmitted.headers).to.have.property('subscription-userinfo'); + + const bareQuery = await requestDownloadSubscription({ + target: 'JSON', + noFlow: '', + }); + expect(bareQuery.headers).to.have.property('subscription-userinfo'); + + const queryDisabled = await requestDownloadSubscription({ + target: 'JSON', + noFlow: 'false', + }); + expect(queryDisabled.headers).to.not.have.property( + 'subscription-userinfo', + ); + + state[SUBS_KEY][0].noFlow = true; + const settingDisabled = await requestDownloadSubscription({ + target: 'JSON', + }); + expect(settingDisabled.headers).to.not.have.property( + 'subscription-userinfo', + ); + }); + + it('logs noFlow query overrides for subscriptions and collections', async function () { + const logs = []; + $.info = (message) => logs.push(message); + + for (const request of [ + requestDownloadSubscription, + requestDownloadCollection, + ]) { + logs.length = 0; + await request({ target: 'JSON', noFlow: 'false' }); + expect(logs).to.include('指定不查询订阅流量信息: false'); + } + }); + + it('returns 400 when noFlow disables the flow endpoint', async function () { + state[SUBS_KEY][0].subUserinfo = + 'upload=1; download=2; total=3; expire=4'; + const bareQuery = await requestSubscriptionFlow({ noFlow: '' }); + expect(bareQuery.statusCode).to.equal(200); + + const res = await requestSubscriptionFlow({ noFlow: 'false' }); + expect(res.statusCode).to.equal(400); + expect(res.sent.error.code).to.equal('NO_FLOW_INFO'); + }); + + it('skips validCheck flow requests for direct and internal file noFlow links', async function () { + const originalHTTP = openApi.HTTP; + + try { + for (const [sourceUrl, request, viaFile] of [ + [ + 'https://example.com/subscription#validCheck', + requestDownloadSubscription, + ], + [ + 'https://example.com/collection#validCheck', + requestDownloadCollection, + ], + [ + 'https://example.com/nested-file-subscription#validCheck', + requestDownloadSubscription, + true, + ], + [ + 'https://example.com/nested-file-collection#validCheck', + requestDownloadCollection, + true, + ], + ]) { + const requestedUrls = []; + state[SUBS_KEY][0] = { + name: 'local-vless', + source: 'remote', + url: viaFile ? '/api/file/nested-flow' : sourceUrl, + }; + if (viaFile) { + state[FILES_KEY] = [ + { + name: 'nested-flow', + source: 'remote', + url: sourceUrl, + }, + ]; + } + openApi.HTTP = () => ({ + get: async ({ url }) => { + requestedUrls.push(url); + return { + body: VLESS_WS, + headers: + requestedUrls.length > 1 + ? { + 'subscription-userinfo': + 'upload=1; download=2; total=3; expire=4102444800', + } + : {}, + statusCode: 200, + }; + }, + head: async ({ url }) => { + requestedUrls.push(url); + return { + headers: { + 'subscription-userinfo': + 'upload=1; download=2; total=3; expire=4102444800', + }, + statusCode: 200, + }; + }, + }); + + const res = await request({ + target: 'JSON', + noCache: 'true', + noFlow: 'false', + }); + + expect(res.statusCode).to.equal(200); + expect(requestedUrls).to.deep.equal([ + sourceUrl.split('#')[0], + ]); + } + } finally { + openApi.HTTP = originalHTTP; + } + }); + + it('keeps noFlow for processor-triggered downloads', async function () { + const originalHTTP = openApi.HTTP; + + try { + for (const [sourceName, request] of [ + ['subscription', requestDownloadSubscription], + ['collection', requestDownloadCollection], + ]) { + const scriptUrl = `https://example.com/processor-script-${sourceName}`; + const nestedUrl = `https://example.com/processor-sub-${sourceName}`; + const requests = []; + state[SUBS_KEY] = [ + { + name: 'local-vless', + source: 'remote', + url: '/api/file/processor-flow', + }, + { + name: 'processor-sub', + source: 'remote', + url: `${nestedUrl}#validCheck&noCache`, + }, + ]; + state[FILES_KEY] = [ + { + name: 'processor-flow', + type: 'mihomoConfig', + sourceType: 'none', + process: [ + { + type: 'Script Operator', + args: { + mode: 'link', + content: `${scriptUrl}#validCheck&noCache`, + }, + }, + { + type: 'Add Proxies From Subscription Operator', + args: { + sourceName: 'processor-sub', + }, + }, + ], + }, + ]; + openApi.HTTP = () => ({ + get: async ({ url }) => { + requests.push(['GET', url]); + return { + body: url.includes('processor-script') + ? 'mixed-port: 7890' + : VLESS_WS, + headers: {}, + statusCode: 200, + }; + }, + head: async ({ url }) => { + requests.push(['HEAD', url]); + return { + headers: { + 'subscription-userinfo': + 'upload=1; download=2; total=3; expire=4102444800', + }, + statusCode: 200, + }; + }, + }); + + const res = await request({ + target: 'JSON', + noCache: 'true', + noFlow: 'false', + }); + + expect(res.statusCode).to.equal(200); + expect(requests).to.deep.equal([ + ['GET', scriptUrl], + ['GET', nestedUrl], + ]); + } + } finally { + openApi.HTTP = originalHTTP; + } + }); + + it('skips validCheck for noFlow URLs in multiline sources', async function () { + const originalHTTP = openApi.HTTP; + const requests = []; + + try { + state[SUBS_KEY][0] = { + name: 'local-vless', + source: 'remote', + url: [ + 'https://example.com/first#validCheck&noFlow=false', + 'https://example.com/second', + ].join('\n'), + }; + openApi.HTTP = () => ({ + get: async ({ url }) => { + requests.push(['GET', url]); + return { + body: VLESS_WS, + headers: {}, + statusCode: 200, + }; + }, + head: async ({ url }) => { + requests.push(['HEAD', url]); + return { + headers: { + 'subscription-userinfo': + 'upload=1; download=2; total=3; expire=4102444800', + }, + statusCode: 200, + }; + }, + }); + + const res = await requestDownloadSubscription({ + target: 'JSON', + noCache: 'true', + }); + + expect(res.statusCode).to.equal(200); + expect(requests).to.deep.equal([ + ['GET', 'https://example.com/first'], + ['GET', 'https://example.com/second'], + ]); + } finally { + openApi.HTTP = originalHTTP; + } + }); + + it('uses truthiness for collection noFlow query values', async function () { + state[COLLECTIONS_KEY][0].subUserinfo = + 'upload=1; download=2; total=3; expire=4'; + + const queryOmitted = await requestDownloadCollection({ + target: 'JSON', + }); + expect(queryOmitted.headers).to.have.property('subscription-userinfo'); + + const bareQuery = await requestDownloadCollection({ + target: 'JSON', + noFlow: '', + }); + expect(bareQuery.headers).to.have.property('subscription-userinfo'); + + const queryDisabled = await requestDownloadCollection({ + target: 'JSON', + noFlow: 'false', + }); + expect(queryDisabled.headers).to.not.have.property( + 'subscription-userinfo', + ); + + state[COLLECTIONS_KEY][0].noFlow = true; + const settingDisabled = await requestDownloadCollection({ + target: 'JSON', + }); + expect(settingDisabled.headers).to.not.have.property( + 'subscription-userinfo', + ); + }); + it('keeps SurgeMac Mihomo external output unmerged by default', async function () { const output = await downloadSubscription({ target: 'SurgeMac' }); diff --git a/backend/src/test/utils/download.spec.js b/backend/src/test/utils/download.spec.js index fcc7e9a3..fbd0940e 100644 --- a/backend/src/test/utils/download.spec.js +++ b/backend/src/test/utils/download.spec.js @@ -208,6 +208,50 @@ describe('download github proxy regex', function () { expect(maxActiveRequests).to.equal(1); }); + it('keeps noFlow during custom cache refreshes', async function () { + for (const awaitCustomCache of [true, false]) { + const cacheKey = `refresh-${awaitCustomCache}`; + const sourceUrl = `https://example.com/${cacheKey}`; + const requests = []; + state[`#sub-store-cached-custom-${cacheKey}`] = 'cached-body'; + openApi.HTTP = () => ({ + get: async ({ url }) => { + requests.push(['GET', url]); + return { + body: 'fresh-body', + headers: {}, + statusCode: 200, + }; + }, + head: async ({ url }) => { + requests.push(['HEAD', url]); + return { + headers: { + 'subscription-userinfo': + 'upload=1; download=2; total=3; expire=4102444800', + }, + statusCode: 200, + }; + }, + }); + + await download( + `${sourceUrl}#validCheck&cacheKey=${cacheKey}`, + undefined, + undefined, + undefined, + undefined, + awaitCustomCache, + true, + undefined, + { noFlow: 'false' }, + ); + if (!awaitCustomCache) await sleep(10); + + expect(requests).to.deep.equal([['GET', sourceUrl]]); + } + }); + it('logs download failures before rejecting', async function () { openApi.HTTP = () => ({ get: async () => { diff --git a/backend/src/utils/download.js b/backend/src/utils/download.js index cbdef52d..8a60e6de 100644 --- a/backend/src/utils/download.js +++ b/backend/src/utils/download.js @@ -243,6 +243,7 @@ export default async function download( undefined, undefined, preprocess, + options, ); } catch (e) { $.error( @@ -266,6 +267,7 @@ export default async function download( undefined, undefined, preprocess, + options, ).catch((e) => { $.error( `乐观缓存: URL ${safeUrl} 异步更新缓存发生错误 ${ @@ -310,6 +312,7 @@ export default async function download( await produceArtifact({ type: 'file', name, + noFlow: options?.noFlow, }), returnRaw, ); @@ -492,7 +495,7 @@ export default async function download( // 检查订阅有效性 - if ($arguments?.validCheck) { + if ($arguments?.validCheck && !$arguments?.noFlow && !options?.noFlow) { await validCheck( parseFlowHeaders( await getFlowHeaders(