diff --git a/backend/package.json b/backend/package.json index 84c16b53..58f3fa5e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.24.1", + "version": "2.24.2", "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/products/resource-parser.loon.js b/backend/src/products/resource-parser.loon.js index 48517567..599c24d6 100644 --- a/backend/src/products/resource-parser.loon.js +++ b/backend/src/products/resource-parser.loon.js @@ -3,6 +3,12 @@ import { ProxyUtils } from '@/core/proxy-utils'; import { RuleUtils } from '@/core/rule-utils'; import { version } from '../../package.json'; import download from '@/utils/download'; +import { + AGE_SECRET_KEY, + decryptArmorIfPresent, + isAgeArmor, + maskAgeSecret, +} from '@/utils/age'; let result = ''; let resource = typeof $resource !== 'undefined' ? $resource : ''; @@ -27,20 +33,29 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : ''; } else { arg = {}; } - console.log(`arg: ${JSON.stringify(arg)}`); + console.log(`arg: ${maskAgeSecret(JSON.stringify(arg))}`); + const ageSecretKey = arg?.[AGE_SECRET_KEY]; + const downloadOptions = ageSecretKey + ? { + [AGE_SECRET_KEY]: ageSecretKey, + } + : undefined; + const maybeDecryptResource = async (input) => + ageSecretKey ? await decryptArmorIfPresent(input, ageSecretKey) : input; const RESOURCE_TYPE = { PROXY: 1, RULE: 2, }; if (!arg.resourceUrlOnly) { - result = resource; + result = ageSecretKey && isAgeArmor(resource) ? '' : resource; } if (resourceType === RESOURCE_TYPE.PROXY) { if (!arg.resourceUrlOnly) { try { - let proxies = ProxyUtils.parse(resource); + const raw = await maybeDecryptResource(resource); + let proxies = ProxyUtils.parse(raw); result = ProxyUtils.produce(proxies, 'Loon', undefined, { 'include-unsupported-proxy': arg?.includeUnsupportedProxy, }); @@ -61,6 +76,7 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : ''; undefined, arg?.noCache, true, + downloadOptions, ); let proxies = ProxyUtils.parse(raw); result = ProxyUtils.produce(proxies, 'Loon', undefined, { @@ -73,7 +89,8 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : ''; } else if (resourceType === RESOURCE_TYPE.RULE) { if (!arg.resourceUrlOnly) { try { - const rules = RuleUtils.parse(resource); + const raw = await maybeDecryptResource(resource); + const rules = RuleUtils.parse(raw); result = RuleUtils.produce(rules, 'Loon'); } catch (e) { console.log(e.message ?? e); @@ -82,7 +99,17 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : ''; if ((!result || /^\s*$/.test(result)) && resourceUrl) { console.log(`解析器: 尝试从 ${resourceUrl} 获取规则`); try { - let raw = await download(resourceUrl, arg?.ua, arg?.timeout); + let raw = await download( + resourceUrl, + arg?.ua, + arg?.timeout, + undefined, + undefined, + undefined, + undefined, + undefined, + downloadOptions, + ); let rules = RuleUtils.parse(raw); result = RuleUtils.produce(rules, 'Loon'); } catch (e) { diff --git a/backend/src/test/products/resource-parser.loon.spec.js b/backend/src/test/products/resource-parser.loon.spec.js index 41dfcde6..d4e0805c 100644 --- a/backend/src/test/products/resource-parser.loon.spec.js +++ b/backend/src/test/products/resource-parser.loon.spec.js @@ -2,9 +2,16 @@ import { expect } from 'chai'; import { describe, it } from 'mocha'; import { ProxyUtils } from '@/core/proxy-utils'; +import { RuleUtils } from '@/core/rule-utils'; +import * as ageUtils from '@/utils/age'; describe('Loon resource parser', function () { - const modulePath = require.resolve('../../products/resource-parser.loon.js'); + this.timeout(10000); + + const modulePath = require.resolve( + '../../products/resource-parser.loon.js', + ); + const downloadModule = require('@/utils/download'); function cleanupGlobals() { delete global.$argument; @@ -19,6 +26,30 @@ describe('Loon resource parser', function () { delete require.cache[modulePath]; } + async function runParser({ + argument = '', + resource = '', + resourceType = 1, + resourceUrl = '', + } = {}) { + global.$loon = 'Loon(842)'; + global.$argument = argument; + global.$resource = resource; + global.$resourceType = resourceType; + global.$resourceUrl = resourceUrl; + + return await new Promise((resolve, reject) => { + global.$done = resolve; + + try { + resetModule(); + require(modulePath); + } catch (error) { + reject(error); + } + }); + } + it('does not auto-enable includeUnsupportedProxy from build number', async function () { const originalParse = ProxyUtils.parse; const originalProduce = ProxyUtils.produce; @@ -59,4 +90,250 @@ describe('Loon resource parser', function () { cleanupGlobals(); } }); + + it('decrypts inline age-armored proxy resources from parser arguments', async function () { + const originalParse = ProxyUtils.parse; + const originalProduce = ProxyUtils.produce; + let capturedInput; + + try { + const pair = await ageUtils.generateKeyPair(); + const armored = await ageUtils.encryptArmor( + 'decrypted-proxy-resource', + pair['age-public-key'], + ); + + ProxyUtils.parse = (input) => { + capturedInput = input; + return [{ type: 'ss' }]; + }; + ProxyUtils.produce = () => 'proxy-output'; + + const result = await runParser({ + argument: `age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + resource: armored, + resourceType: 1, + }); + + expect(result).to.equal('proxy-output'); + expect(capturedInput).to.equal('decrypted-proxy-resource'); + } finally { + ProxyUtils.parse = originalParse; + ProxyUtils.produce = originalProduce; + resetModule(); + cleanupGlobals(); + } + }); + + it('decrypts inline age-armored rule resources from parser arguments', async function () { + const originalParse = RuleUtils.parse; + const originalProduce = RuleUtils.produce; + let capturedInput; + + try { + const pair = await ageUtils.generateKeyPair(); + const armored = await ageUtils.encryptArmor( + 'DOMAIN,example.com,Proxy', + pair['age-public-key'], + ); + + RuleUtils.parse = (input) => { + capturedInput = input; + return [{ type: 'DOMAIN', payload: 'example.com' }]; + }; + RuleUtils.produce = () => 'rule-output'; + + const result = await runParser({ + argument: `age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + resource: armored, + resourceType: 2, + }); + + expect(result).to.equal('rule-output'); + expect(capturedInput).to.equal('DOMAIN,example.com,Proxy'); + } finally { + RuleUtils.parse = originalParse; + RuleUtils.produce = originalProduce; + resetModule(); + cleanupGlobals(); + } + }); + + it('keeps plain inline resources unchanged when age-secret-key is present', async function () { + const originalParse = ProxyUtils.parse; + const originalProduce = ProxyUtils.produce; + let capturedInput; + + try { + const pair = await ageUtils.generateKeyPair(); + + ProxyUtils.parse = (input) => { + capturedInput = input; + return [{ type: 'ss' }]; + }; + ProxyUtils.produce = () => 'proxy-output'; + + const result = await runParser({ + argument: `age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + resource: 'plain-proxy-resource', + resourceType: 1, + }); + + expect(result).to.equal('proxy-output'); + expect(capturedInput).to.equal('plain-proxy-resource'); + } finally { + ProxyUtils.parse = originalParse; + ProxyUtils.produce = originalProduce; + resetModule(); + cleanupGlobals(); + } + }); + + it('passes parser age-secret-key to remote proxy downloads', async function () { + const originalDownload = downloadModule.default; + const originalParse = ProxyUtils.parse; + const originalProduce = ProxyUtils.produce; + let capturedInput; + let capturedOptions; + + try { + const pair = await ageUtils.generateKeyPair(); + const armored = await ageUtils.encryptArmor( + 'remote-proxy-resource', + pair['age-public-key'], + ); + + downloadModule.default = async (...args) => { + capturedOptions = args[8]; + return capturedOptions?.['age-secret-key'] === + pair['age-secret-key'] + ? 'remote-proxy-resource' + : armored; + }; + ProxyUtils.parse = (input) => { + capturedInput = input; + return [{ type: 'ss' }]; + }; + ProxyUtils.produce = () => 'proxy-output'; + + const result = await runParser({ + argument: `resourceUrlOnly=true&age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + resource: '', + resourceType: 1, + resourceUrl: 'https://example.com/proxy.txt', + }); + + expect(result).to.equal('proxy-output'); + expect(capturedInput).to.equal('remote-proxy-resource'); + expect(capturedOptions).to.deep.include({ + 'age-secret-key': pair['age-secret-key'], + }); + } finally { + downloadModule.default = originalDownload; + ProxyUtils.parse = originalParse; + ProxyUtils.produce = originalProduce; + resetModule(); + cleanupGlobals(); + } + }); + + it('passes parser age-secret-key to remote rule downloads', async function () { + const originalDownload = downloadModule.default; + const originalParse = RuleUtils.parse; + const originalProduce = RuleUtils.produce; + let capturedInput; + let capturedOptions; + + try { + const pair = await ageUtils.generateKeyPair(); + const armored = await ageUtils.encryptArmor( + 'DOMAIN,remote.example,Proxy', + pair['age-public-key'], + ); + + downloadModule.default = async (...args) => { + capturedOptions = args[8]; + return capturedOptions?.['age-secret-key'] === + pair['age-secret-key'] + ? 'DOMAIN,remote.example,Proxy' + : armored; + }; + RuleUtils.parse = (input) => { + capturedInput = input; + return [{ type: 'DOMAIN', payload: 'remote.example' }]; + }; + RuleUtils.produce = () => 'rule-output'; + + const result = await runParser({ + argument: `resourceUrlOnly=true&age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + resource: 'ignored-rule-resource', + resourceType: 2, + resourceUrl: 'https://example.com/rule.txt', + }); + + expect(result).to.equal('rule-output'); + expect(capturedInput).to.equal('DOMAIN,remote.example,Proxy'); + expect(capturedOptions).to.deep.include({ + 'age-secret-key': pair['age-secret-key'], + }); + } finally { + downloadModule.default = originalDownload; + RuleUtils.parse = originalParse; + RuleUtils.produce = originalProduce; + resetModule(); + cleanupGlobals(); + } + }); + + it('does not expose age-secret-key or return armor on decrypt failure', async function () { + const originalParse = ProxyUtils.parse; + const originalProduce = ProxyUtils.produce; + const originalConsoleLog = console.log; + let logs = []; + + try { + const encryptPair = await ageUtils.generateKeyPair(); + const wrongPair = await ageUtils.generateKeyPair(); + const armored = await ageUtils.encryptArmor( + 'decrypted-proxy-resource', + encryptPair['age-public-key'], + ); + + ProxyUtils.parse = () => { + throw new Error('parse should not succeed'); + }; + ProxyUtils.produce = () => 'proxy-output'; + console.log = (message) => { + logs.push(String(message)); + }; + + const result = await runParser({ + argument: `age-secret-key=${encodeURIComponent( + wrongPair['age-secret-key'], + )}`, + resource: armored, + resourceType: 1, + }); + + expect(result).to.not.contain(ageUtils.AGE_ARMOR_HEADER); + expect(logs.join('\n')).to.not.contain(wrongPair['age-secret-key']); + expect(logs.join('\n')).to.contain('age-secret-key'); + } finally { + ProxyUtils.parse = originalParse; + ProxyUtils.produce = originalProduce; + console.log = originalConsoleLog; + resetModule(); + cleanupGlobals(); + } + }); }); diff --git a/backend/src/test/utils/download.spec.js b/backend/src/test/utils/download.spec.js index cac6d379..acf89d6a 100644 --- a/backend/src/test/utils/download.spec.js +++ b/backend/src/test/utils/download.spec.js @@ -46,9 +46,9 @@ describe('download github proxy regex', function () { ({ default: $ } = require('@/core/app')); openApi = require('@/vendor/open-api'); ({ default: resourceCache } = require('@/utils/resource-cache')); - ({ default: headersResourceCache } = require( - '@/utils/headers-resource-cache' - )); + ({ + default: headersResourceCache, + } = require('@/utils/headers-resource-cache')); ({ default: download } = require('@/utils/download')); ageUtils = require('@/utils/age'); @@ -156,13 +156,12 @@ describe('download github proxy regex', function () { it('keeps download urls unchanged when the regex does not match', async function () { await download('https://example.com/archive.txt'); - expect(capturedUrls).to.deep.equal([ - 'https://example.com/archive.txt', - ]); + expect(capturedUrls).to.deep.equal(['https://example.com/archive.txt']); }); it('matches regex patterns case-insensitively by default', async function () { - state[SETTINGS_KEY].githubProxyRegex = '^https://RAW\\.GITHUBUSERCONTENT\\.COM'; + state[SETTINGS_KEY].githubProxyRegex = + '^https://RAW\\.GITHUBUSERCONTENT\\.COM'; await download( 'https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/README.md', @@ -204,9 +203,7 @@ describe('download github proxy regex', function () { await download('https://example.com/cached.txt'); await download('https://example.com/cached.txt'); - expect(capturedUrls).to.deep.equal([ - 'https://example.com/cached.txt', - ]); + expect(capturedUrls).to.deep.equal(['https://example.com/cached.txt']); expect(maxActiveRequests).to.equal(1); }); @@ -230,6 +227,33 @@ describe('download github proxy regex', function () { expect(capturedUrls).to.deep.equal(['https://example.com/age.txt']); }); + it('decrypts age-armored downloads with an explicit age secret option', async function () { + const pair = await ageUtils.generateKeyPair(); + responseBody = await ageUtils.encryptArmor( + 'explicit-decrypted-body', + pair['age-public-key'], + ); + + const body = await download( + 'https://example.com/explicit-age.txt', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + { + 'age-secret-key': pair['age-secret-key'], + }, + ); + + expect(body).to.equal('explicit-decrypted-body'); + expect(capturedUrls).to.deep.equal([ + 'https://example.com/explicit-age.txt', + ]); + }); + it('leaves non-armor downloads unchanged when age-secret-key is present', async function () { const pair = await ageUtils.generateKeyPair(); responseBody = 'plain subscription body'; diff --git a/backend/src/utils/download.js b/backend/src/utils/download.js index ec90c8d9..48b1702c 100644 --- a/backend/src/utils/download.js +++ b/backend/src/utils/download.js @@ -119,6 +119,7 @@ export default async function download( awaitCustomCache, noCache, preprocess, + options = {}, ) { let $arguments = {}; let url = rawUrl.replace(/#noFlow$/, ''); @@ -140,7 +141,11 @@ export default async function download( } } } - const ageSecretKey = $arguments?.[AGE_SECRET_KEY]; + const explicitAgeSecretKey = + options && typeof options === 'object' + ? options?.[AGE_SECRET_KEY] || options?.ageSecretKey + : undefined; + const ageSecretKey = explicitAgeSecretKey || $arguments?.[AGE_SECRET_KEY]; const { isNode, isStash, isLoon, isShadowRocket, isQX } = ENV(); const { githubProxy,