diff --git a/backend/package.json b/backend/package.json index fbc8baba..84c16b53 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.24.0", + "version": "2.24.1", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", @@ -24,6 +24,7 @@ }, "dependencies": { "@maxmind/geoip2-node": "^5.0.0", + "age-encryption": "^0.3.0", "body-parser": "^1.19.0", "buffer": "^6.0.3", "connect-history-api-fallback": "^2.0.0", diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yaml index 81e188d2..934b5e54 100644 --- a/backend/pnpm-lock.yaml +++ b/backend/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@maxmind/geoip2-node': specifier: ^5.0.0 version: 5.0.0 + age-encryption: + specifier: ^0.3.0 + version: 0.3.0 body-parser: specifier: ^1.19.0 version: 1.20.5 @@ -101,7 +104,7 @@ importers: version: 8.16.0 mocha: specifier: ^11.7.5 - version: 11.7.5 + version: 11.7.6 nodemon: specifier: ^2.0.16 version: 2.0.16 @@ -818,10 +821,37 @@ packages: '@maxmind/geoip2-node@5.0.0': resolution: {integrity: sha512-ki+q5//oU4tZ3BAhegZJcB5czoZyic5JSTEKbrUAQB/BzAoAiGyLW0immEmQvVVyy2SMlvBTJ3zqyRj8K9BbwQ==} + '@noble/ciphers@2.2.0': + resolution: {integrity: sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==} + engines: {node: '>= 20.19.0'} + + '@noble/curves@2.0.0': + resolution: {integrity: sha512-RiwZZeJnsTnhT+/gg2KvITJZhK5oagQrpZo+yQyd3mv3D5NAG2qEeEHpw7IkXRlpkoD45wl2o4ydHAvY9wyEfw==} + engines: {node: '>= 20.19.0'} + + '@noble/curves@2.2.0': + resolution: {integrity: sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ==} + engines: {node: '>= 20.19.0'} + + '@noble/hashes@2.0.0': + resolution: {integrity: sha512-h8VUBlE8R42+XIDO229cgisD287im3kdY6nbNZJFjc6ZvKIXPYXe6Vc/t+kyjFdMFyt5JpapzTsEg8n63w5/lw==} + engines: {node: '>= 20.19.0'} + + '@noble/hashes@2.2.0': + resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==} + engines: {node: '>= 20.19.0'} + + '@noble/post-quantum@0.5.4': + resolution: {integrity: sha512-leww0zzIirrvwaYMPI9fj6aRIlA/c6Y0/lifQQ1YOOyHEr0MNH3yYpjXeiVG+tWdPps4XxGclFWX2INPO3Yo5w==} + engines: {node: '>= 20.19.0'} + '@pkgjs/parseargs@0.11.0': resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} + '@scure/base@2.2.0': + resolution: {integrity: sha512-b8XEupJibegiXV+tDUseI8oLQc8ei3d/4Jkb2RpbHh3MfE054ov3uIz2dhFkB3FI8iwYkEh0gGCApkrYggkPNg==} + '@sindresorhus/is@0.14.0': resolution: {integrity: sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==} engines: {node: '>=6'} @@ -864,6 +894,9 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + age-encryption@0.3.0: + resolution: {integrity: sha512-vDhGGp5ZXpbKL6oc3FEBjGhyepr/0SwIWmia6CcPXvYcxGBSQNcDdMv9m2yVOkjjYuJEmtGEhOojIUcjrj0cEw==} + ajv@6.15.0: resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} @@ -2043,8 +2076,8 @@ packages: resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} engines: {node: '>=16 || 14 >=14.17'} - mocha@11.7.5: - resolution: {integrity: sha512-mTT6RgopEYABzXWFx+GcJ+ZQ32kp4fMf0xvpZIIfSq9Z8lC/++MtcCnQ9t5FP2veYEP95FIYSvW+U9fV4xrlig==} + mocha@11.7.6: + resolution: {integrity: sha512-nS9xOGbw2I3cjCpxwZAEJ9xK9lmJ08vEkQvLtz4du9ZrF9UrjRpeJGiIgl2Z+Qs++pmB4ecDe48Fwsh+j+j7xA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} hasBin: true @@ -3669,9 +3702,30 @@ snapshots: ip6addr: 0.2.5 maxmind: 4.2.0 + '@noble/ciphers@2.2.0': {} + + '@noble/curves@2.0.0': + dependencies: + '@noble/hashes': 2.0.0 + + '@noble/curves@2.2.0': + dependencies: + '@noble/hashes': 2.2.0 + + '@noble/hashes@2.0.0': {} + + '@noble/hashes@2.2.0': {} + + '@noble/post-quantum@0.5.4': + dependencies: + '@noble/curves': 2.0.0 + '@noble/hashes': 2.0.0 + '@pkgjs/parseargs@0.11.0': optional: true + '@scure/base@2.2.0': {} + '@sindresorhus/is@0.14.0': {} '@szmarczak/http-timer@1.1.2': @@ -3709,6 +3763,14 @@ snapshots: acorn@8.16.0: {} + age-encryption@0.3.0: + dependencies: + '@noble/ciphers': 2.2.0 + '@noble/curves': 2.2.0 + '@noble/hashes': 2.2.0 + '@noble/post-quantum': 0.5.4 + '@scure/base': 2.2.0 + ajv@6.15.0: dependencies: fast-deep-equal: 3.1.3 @@ -5003,7 +5065,7 @@ snapshots: minipass@7.1.3: {} - mocha@11.7.5: + mocha@11.7.6: dependencies: browser-stdout: 1.3.1 chokidar: 4.0.3 @@ -5572,7 +5634,7 @@ snapshots: dependencies: emoji-regex: 8.0.0 is-fullwidth-code-point: 3.0.0 - strip-ansi: 6.0.1 + strip-ansi: 6.0.0 string-width@4.2.2: dependencies: diff --git a/backend/src/products/cron-sync-artifacts.js b/backend/src/products/cron-sync-artifacts.js index 8a5978dc..57c9376e 100644 --- a/backend/src/products/cron-sync-artifacts.js +++ b/backend/src/products/cron-sync-artifacts.js @@ -9,6 +9,7 @@ import $ from '@/core/app'; import { markArtifactProducedWithoutUpload, produceArtifact, + produceSyncArtifactOutput, shouldUploadArtifact, uploadArtifactBatches, } from '@/restful/sync'; @@ -196,17 +197,9 @@ async function doSync(arg = {}, { canUpload = true } = {}) { `手动指定了 target 为 SurgeMac, 将使用 Mihomo External`, ); } - const output = await produceArtifact({ - type: artifact.type, - name: artifact.source, - platform: artifact.platform, - produceOpts: { - 'include-unsupported-proxy': - artifact.includeUnsupportedProxy, - useMihomoExternal, - prettyYaml: artifact.prettyYaml, - }, - }); + const output = await produceSyncArtifactOutput( + artifact, + ); // if (!output || output.length === 0) // throw new Error('该配置的结果为空 不进行上传'); diff --git a/backend/src/products/sub-store-0.js b/backend/src/products/sub-store-0.js index 182ddb04..b146e11d 100644 --- a/backend/src/products/sub-store-0.js +++ b/backend/src/products/sub-store-0.js @@ -25,6 +25,7 @@ import registerTokenRoutes from '@/restful/token'; import registerArchiveRoutes from '@/restful/archives'; import registerModuleRoutes from '@/restful/module'; import registerLogRoutes from '@/restful/logs'; +import registerAgeRoutes from '@/restful/age'; migrate(); serve(); @@ -44,6 +45,7 @@ function serve() { registerArchiveRoutes($app); registerMiscRoutes($app); registerLogRoutes($app); + registerAgeRoutes($app); $app.start(); } diff --git a/backend/src/restful/age-output.js b/backend/src/restful/age-output.js new file mode 100644 index 00000000..eb37e867 --- /dev/null +++ b/backend/src/restful/age-output.js @@ -0,0 +1,65 @@ +import { AGE_PUBLIC_KEY, encryptArmor } from '@/utils/age'; + +const SHARE_AGE_PUBLIC_KEY_HEADER = 'x-sub-store-share-age-public-key'; + +function normalizeAgePublicKey(value) { + return String(value ?? '').trim(); +} + +function createAgePublicKeyConfig(publicKey) { + const key = normalizeAgePublicKey(publicKey); + return key ? { [AGE_PUBLIC_KEY]: key } : undefined; +} + +function resolveAgePublicKey(...configs) { + for (const config of configs) { + const key = normalizeAgePublicKey(config?.[AGE_PUBLIC_KEY]); + if (key) return key; + } + + return ''; +} + +function resolveShareAgeConfig({ req, type, name, findShareToken }) { + if (!req?.path?.startsWith('/share/')) { + return undefined; + } + + const consumedToken = req.subStoreShareToken; + const token = + consumedToken || + (req.query?.token && typeof findShareToken === 'function' + ? findShareToken({ + token: req.query.token, + type, + name, + pathname: req.path, + }) + : null); + const headerKey = req.headers?.[SHARE_AGE_PUBLIC_KEY_HEADER]; + + return createAgePublicKeyConfig(token?.[AGE_PUBLIC_KEY] || headerKey); +} + +async function applyAgeOutputEncryption({ body, res, configs = [] }) { + const publicKey = resolveAgePublicKey(...configs); + + if (!publicKey) { + return body; + } + + const armored = await encryptArmor(body ?? '', publicKey); + if (res?.set) { + res.set('Content-Type', 'text/plain; charset=utf-8'); + } + + return armored; +} + +export { + SHARE_AGE_PUBLIC_KEY_HEADER, + applyAgeOutputEncryption, + createAgePublicKeyConfig, + resolveAgePublicKey, + resolveShareAgeConfig, +}; diff --git a/backend/src/restful/age.js b/backend/src/restful/age.js new file mode 100644 index 00000000..ab48103d --- /dev/null +++ b/backend/src/restful/age.js @@ -0,0 +1,37 @@ +import { failed, success } from '@/restful/response'; +import { + AGE_KEY_TYPES, + AGE_PUBLIC_KEY, + AGE_SECRET_KEY, + derivePublicKey, + generateKeyPair, +} from '@/utils/age'; + +export default function register($app) { + $app.post('/api/utils/age/key-pair', createAgeKeyPair); + $app.post('/api/utils/age/public-key', createAgePublicKey); +} + +async function createAgeKeyPair(req, res) { + try { + const pair = await generateKeyPair(req.body?.type || AGE_KEY_TYPES.X25519); + success(res, { + type: pair.type, + [AGE_SECRET_KEY]: pair[AGE_SECRET_KEY], + [AGE_PUBLIC_KEY]: pair[AGE_PUBLIC_KEY], + }); + } catch (error) { + failed(res, error); + } +} + +async function createAgePublicKey(req, res) { + try { + const publicKey = await derivePublicKey(req.body?.[AGE_SECRET_KEY]); + success(res, { + [AGE_PUBLIC_KEY]: publicKey, + }); + } catch (error) { + failed(res, error); + } +} diff --git a/backend/src/restful/artifacts.js b/backend/src/restful/artifacts.js index 037d3927..e7768470 100644 --- a/backend/src/restful/artifacts.js +++ b/backend/src/restful/artifacts.js @@ -24,6 +24,7 @@ import { normalizeArtifactCron, refreshArtifactCronJobs, } from '@/utils/artifact-cron'; +import { normalizeAgePublicKeyConfig } from '@/utils/age'; const ARTIFACT_GIST_PLACEHOLDER_FILENAME = '.sub-store-placeholder'; const ARTIFACT_GIST_PLACEHOLDER_CONTENT = [ @@ -140,6 +141,7 @@ function getAllArtifacts(req, res) { function replaceArtifact(req, res) { try { const allArtifacts = req.body; + allArtifacts.forEach(normalizeAgePublicKeyConfig); allArtifacts.forEach(normalizeArtifactCron); $.write(allArtifacts, ARTIFACTS_KEY); refreshArtifactCronJobs(); @@ -189,6 +191,7 @@ function updateArtifact(req, res) { ...oldArtifact, ...artifact, }; + normalizeAgePublicKeyConfig(newArtifact); if (!validateArtifactName(newArtifact.name)) { failed( res, @@ -254,6 +257,7 @@ function validateArtifactName(name) { } function createArtifactItem(artifact) { + normalizeAgePublicKeyConfig(artifact); if (!validateArtifactName(artifact.name)) { throw new RequestInvalidError( 'INVALID_ARTIFACT_NAME', diff --git a/backend/src/restful/collections.js b/backend/src/restful/collections.js index a198f763..d9171963 100644 --- a/backend/src/restful/collections.js +++ b/backend/src/restful/collections.js @@ -11,6 +11,7 @@ import { failed, success } from '@/restful/response'; import $ from '@/core/app'; import { RequestInvalidError, ResourceNotFoundError } from '@/restful/errors'; import { formatDateTime } from '@/utils'; +import { normalizeAgePublicKeyConfig } from '@/utils/age'; export default function register($app) { if (!$.read(COLLECTIONS_KEY)) $.write({}, COLLECTIONS_KEY); @@ -79,6 +80,7 @@ function updateCollection(req, res) { ...oldCol, ...collection, }; + normalizeAgePublicKeyConfig(newCol); $.info(`正在更新组合订阅:${name}...`); if (name !== newCol.name) { @@ -141,12 +143,18 @@ function getAllCollections(req, res) { } function replaceCollection(req, res) { - const allCols = req.body; - $.write(allCols, COLLECTIONS_KEY); - success(res); + try { + const allCols = req.body; + allCols.forEach(normalizeAgePublicKeyConfig); + $.write(allCols, COLLECTIONS_KEY); + success(res); + } catch (error) { + failed(res, error); + } } function createCollectionItem(collection) { + normalizeAgePublicKeyConfig(collection); $.info(`正在创建组合订阅:${collection.name}`); if (/\//.test(collection.name)) { throw new RequestInvalidError( diff --git a/backend/src/restful/download.js b/backend/src/restful/download.js index 3f45e7a5..80273653 100644 --- a/backend/src/restful/download.js +++ b/backend/src/restful/download.js @@ -12,6 +12,12 @@ import { isIPv4, isIPv6 } from '@/utils'; import { getISO } from '@/utils/geo'; import env from '@/utils/env'; import { applyResponseTransformers } from '@/restful/response-transformer'; +import { + applyAgeOutputEncryption, + resolveShareAgeConfig, +} from '@/restful/age-output'; +import { findShareToken } from '@/restful/token'; +import { maskAgeSecretInUrl } from '@/utils/age'; function buildEmptyNezhaPayload() { return JSON.stringify( @@ -176,7 +182,7 @@ async function downloadSubscription(req, res) { Object.assign($options, options); } if (url) { - $.info(`指定远程订阅 URL: ${url}`); + $.info(`指定远程订阅 URL: ${maskAgeSecretInUrl(url)}`); if (!/^https?:\/\//.test(url)) { content = url; $.info(`URL 不是链接,视为本地订阅`); @@ -426,7 +432,21 @@ async function downloadSubscription(req, res) { source: { [sub.name]: sub }, $options, }); - res.send(body); + res.send( + await applyAgeOutputEncryption({ + res, + body, + configs: [ + resolveShareAgeConfig({ + req, + type: 'sub', + name, + findShareToken, + }), + sub, + ], + }), + ); } catch (err) { $.notify( `🌍 Sub-Store 下载订阅失败`, @@ -753,7 +773,21 @@ async function downloadCollection(req, res) { source: { _collection: collection }, $options, }); - res.send(body); + res.send( + await applyAgeOutputEncryption({ + res, + body, + configs: [ + resolveShareAgeConfig({ + req, + type: 'col', + name, + findShareToken, + }), + collection, + ], + }), + ); } catch (err) { $.notify( `🌍 Sub-Store 下载组合订阅失败`, diff --git a/backend/src/restful/file.js b/backend/src/restful/file.js index 9fa84b76..4b5ccb03 100644 --- a/backend/src/restful/file.js +++ b/backend/src/restful/file.js @@ -18,6 +18,12 @@ import { produceArtifact } from '@/restful/sync'; import { archiveFile } from '@/utils/archive'; import { formatDateTime } from '@/utils'; import { applyResponseTransformers } from '@/restful/response-transformer'; +import { + applyAgeOutputEncryption, + resolveShareAgeConfig, +} from '@/restful/age-output'; +import { findShareToken } from '@/restful/token'; +import { maskAgeSecretInUrl, normalizeAgePublicKeyConfig } from '@/utils/age'; export default function register($app) { if (!$.read(FILES_KEY)) $.write([], FILES_KEY); @@ -95,7 +101,7 @@ async function getFile(req, res, next) { Object.assign($options, options); } if (url) { - $.info(`指定远程文件 URL: ${url}`); + $.info(`指定远程文件 URL: ${maskAgeSecretInUrl(url)}`); } if (proxy) { $.info(`指定远程订阅使用代理/策略 proxy: ${proxy}`); @@ -210,7 +216,21 @@ async function getFile(req, res, next) { source: { $file: file }, $options: output?.$options ?? $options, }); - res.send(body); + res.send( + await applyAgeOutputEncryption({ + res, + body, + configs: [ + resolveShareAgeConfig({ + req, + type: 'file', + name, + findShareToken, + }), + file, + ], + }), + ); } catch (err) { $.notify( `🌍 Sub-Store 下载文件失败`, @@ -282,6 +302,7 @@ function updateFile(req, res) { ...oldFile, ...file, }; + normalizeAgePublicKeyConfig(newFile); $.info(`正在更新文件:${name}...`); if (name !== newFile.name) { @@ -341,15 +362,21 @@ function getAllWholeFiles(req, res) { } function replaceFile(req, res) { - const allFiles = req.body; - $.write(allFiles, FILES_KEY); - success(res); + try { + const allFiles = req.body; + allFiles.forEach(normalizeAgePublicKeyConfig); + $.write(allFiles, FILES_KEY); + success(res); + } catch (error) { + failed(res, error); + } } function createFileItem(rawFile) { const file = { ...rawFile, }; + normalizeAgePublicKeyConfig(file); file.name = `${file.name ?? Date.now()}`; $.info(`正在创建文件:${file.name}`); const allFiles = $.read(FILES_KEY); diff --git a/backend/src/restful/index.js b/backend/src/restful/index.js index a1f3d08a..dbbd79b7 100644 --- a/backend/src/restful/index.js +++ b/backend/src/restful/index.js @@ -29,7 +29,9 @@ import registerMiscRoutes from './miscs'; import registerNodeInfoRoutes from './node-info'; import registerParserRoutes from './parser'; import registerLogRoutes from './logs'; +import registerAgeRoutes from './age'; import { consumeShareToken } from './token'; +import { AGE_PUBLIC_KEY } from '@/utils/age'; export default function serve() { let port; @@ -80,6 +82,7 @@ export default function serve() { pathname, }); if (token) { + req.subStoreShareToken = token; next(); return; } else { @@ -141,6 +144,7 @@ export default function serve() { registerMiscRoutes($app); registerParserRoutes($app); registerLogRoutes($app); + registerAgeRoutes($app); $app.start(); @@ -417,6 +421,11 @@ export default function serve() { return '/404'; } } + if (token?.[AGE_PUBLIC_KEY]) { + req.headers[ + 'x-sub-store-share-age-public-key' + ] = token[AGE_PUBLIC_KEY]; + } return req.originalUrl; }, }), diff --git a/backend/src/restful/preview.js b/backend/src/restful/preview.js index 75552792..999f5712 100644 --- a/backend/src/restful/preview.js +++ b/backend/src/restful/preview.js @@ -12,6 +12,11 @@ import { shouldFallbackIgnoreFailedRemoteSub, } from '@/restful/ignore-failed-remote-sub'; import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors'; +import { maskAgeSecretInUrl } from '@/utils/age'; + +function formatAgeSafeUrls(errors) { + return Object.keys(errors).map(maskAgeSecretInUrl).join(', '); +} export default function register($app) { $app.post('/api/preview/sub', compareSub); @@ -47,7 +52,9 @@ async function previewFile(req, res) { } catch (err) { errors[url] = err; $.error( - `文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`, + `文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -57,16 +64,18 @@ async function previewFile(req, res) { if (Object.keys(errors).length > 0) { if (!file.ignoreFailedRemoteFile) { throw new Error( - `文件 ${file.name} 的远程文件 ${Object.keys( + `文件 ${ + file.name + } 的远程文件 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`, + )} 发生错误, 请查看日志`, ); } else if (file.ignoreFailedRemoteFile === 'enabled') { $.notify( `🌍 Sub-Store 预览文件失败`, `❌ ${file.name}`, - `远程文件 ${Object.keys(errors).join( - ', ', + `远程文件 ${formatAgeSafeUrls( + errors, )} 发生错误, 请查看日志`, ); } @@ -145,7 +154,9 @@ async function compareSub(req, res) { } catch (err) { errors[url] = err; $.error( - `订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`, + `订阅 ${sub.name} 的远程订阅 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -153,9 +164,11 @@ async function compareSub(req, res) { ); if (Object.keys(errors).length > 0) { - const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys( + const message = `订阅 ${ + sub.name + } 的远程订阅 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`; + )} 发生错误, 请查看日志`; handleIgnoreFailedRemoteSubError({ mode, message, @@ -291,7 +304,11 @@ async function compareCollection(req, res) { } catch (err) { errors[url] = err; $.error( - `订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`, + `订阅 ${ + sub.name + } 的远程订阅 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -299,9 +316,11 @@ async function compareCollection(req, res) { ); if (Object.keys(errors).length > 0) { - const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys( + const message = `订阅 ${ + sub.name + } 的远程订阅 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`; + )} 发生错误, 请查看日志`; handleIgnoreFailedRemoteSubError({ mode: subMode, message, diff --git a/backend/src/restful/subscriptions.js b/backend/src/restful/subscriptions.js index f43121be..f5aa7938 100644 --- a/backend/src/restful/subscriptions.js +++ b/backend/src/restful/subscriptions.js @@ -26,6 +26,7 @@ import { archiveSubscription } from '@/utils/archive'; import { success, failed } from './response'; import $ from '@/core/app'; import { formatDateTime } from '@/utils'; +import { maskAgeSecretInUrl, normalizeAgePublicKeyConfig } from '@/utils/age'; if (!$.read(SUBS_KEY)) $.write({}, SUBS_KEY); @@ -48,7 +49,7 @@ async function getFlowInfo(req, res) { let { name } = req.params; let { url } = req.query; if (url) { - $.info(`指定远程订阅 URL: ${url}`); + $.info(`指定远程订阅 URL: ${maskAgeSecretInUrl(url)}`); } const allSubs = $.read(SUBS_KEY); const sub = findByName(allSubs, name); @@ -290,6 +291,7 @@ function updateSubscription(req, res) { ...oldSub, ...sub, }; + normalizeAgePublicKeyConfig(newSub); $.info(`正在更新订阅: ${name}`); // allow users to update the subscription name if (name !== sub.name) { @@ -362,15 +364,21 @@ function getAllSubscriptions(req, res) { } function replaceSubscriptions(req, res) { - const allSubs = req.body; - $.write(allSubs, SUBS_KEY); - success(res); + try { + const allSubs = req.body; + allSubs.forEach(normalizeAgePublicKeyConfig); + $.write(allSubs, SUBS_KEY); + success(res); + } catch (error) { + failed(res, error); + } } function createSubscriptionItem(rawSub) { const sub = { ...rawSub, }; + normalizeAgePublicKeyConfig(sub); delete sub.subscriptions; $.info(`正在创建订阅: ${sub.name}`); if (/\//.test(sub.name)) { diff --git a/backend/src/restful/sync.js b/backend/src/restful/sync.js index b9ed1107..3a606ba4 100644 --- a/backend/src/restful/sync.js +++ b/backend/src/restful/sync.js @@ -29,6 +29,8 @@ import { shouldFallbackIgnoreFailedRemoteSub, } from '@/restful/ignore-failed-remote-sub'; import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors'; +import { applyAgeOutputEncryption } from '@/restful/age-output'; +import { maskAgeSecretInUrl } from '@/utils/age'; export default function register($app) { // Initialization @@ -39,6 +41,10 @@ export default function register($app) { $app.get('/api/sync/artifact/:name', syncArtifact); } +function formatAgeSafeUrls(errors) { + return Object.keys(errors).map(maskAgeSecretInUrl).join(', '); +} + async function produceArtifact({ type, name, @@ -105,7 +111,9 @@ async function produceArtifact({ } catch (err) { errors[url] = err; $.error( - `订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`, + `订阅 ${sub.name} 的远程订阅 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -113,9 +121,11 @@ async function produceArtifact({ ); if (Object.keys(errors).length > 0) { - const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys( + const message = `订阅 ${ + sub.name + } 的远程订阅 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`; + )} 发生错误, 请查看日志`; handleIgnoreFailedRemoteSubError({ mode: subIgnoreFailedRemoteSub, message, @@ -160,7 +170,9 @@ async function produceArtifact({ } catch (err) { errors[url] = err; $.error( - `订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`, + `订阅 ${sub.name} 的远程订阅 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -168,9 +180,11 @@ async function produceArtifact({ ); if (Object.keys(errors).length > 0) { - const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys( + const message = `订阅 ${ + sub.name + } 的远程订阅 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`; + )} 发生错误, 请查看日志`; handleIgnoreFailedRemoteSubError({ mode: subIgnoreFailedRemoteSub, message, @@ -339,7 +353,11 @@ async function produceArtifact({ } catch (err) { errors[url] = err; $.error( - `订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`, + `订阅 ${ + sub.name + } 的远程订阅 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -347,9 +365,11 @@ async function produceArtifact({ ); if (Object.keys(errors).length > 0) { - const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys( + const message = `订阅 ${ + sub.name + } 的远程订阅 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`; + )} 发生错误, 请查看日志`; handleIgnoreFailedRemoteSubError({ mode: subMode, message, @@ -589,7 +609,9 @@ async function produceArtifact({ } catch (err) { errors[url] = err; $.error( - `文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`, + `文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -607,9 +629,11 @@ async function produceArtifact({ Object.keys(errors).length > 0 ) { throw new Error( - `文件 ${file.name} 的远程文件 ${Object.keys( + `文件 ${ + file.name + } 的远程文件 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`, + )} 发生错误, 请查看日志`, ); } if (mergeSources === 'localFirst') { @@ -643,7 +667,9 @@ async function produceArtifact({ } catch (err) { errors[url] = err; $.error( - `文件 ${file.name} 的远程文件 ${url} 发生错误: ${err}`, + `文件 ${file.name} 的远程文件 ${maskAgeSecretInUrl( + url, + )} 发生错误: ${err}`, ); return ''; } @@ -660,16 +686,18 @@ async function produceArtifact({ if (Object.keys(errors).length > 0) { if (!fileIgnoreFailedRemoteFile) { throw new Error( - `文件 ${file.name} 的远程文件 ${Object.keys( + `文件 ${ + file.name + } 的远程文件 ${formatAgeSafeUrls( errors, - ).join(', ')} 发生错误, 请查看日志`, + )} 发生错误, 请查看日志`, ); } else if (fileIgnoreFailedRemoteFile === 'enabled') { $.notify( `🌍 Sub-Store 处理文件失败`, `❌ ${file.name}`, - `远程文件 ${Object.keys(errors).join( - ', ', + `远程文件 ${formatAgeSafeUrls( + errors, )} 发生错误, 请查看日志`, ); } @@ -763,6 +791,41 @@ function shouldUploadArtifact(artifact) { return artifact?.upload !== false; } +function findArtifactSourceConfig(artifact) { + if (!artifact?.source) return null; + + if (['subscription', 'sub'].includes(artifact.type)) { + return findByName($.read(SUBS_KEY), artifact.source); + } + if (['collection', 'col'].includes(artifact.type)) { + return findByName($.read(COLLECTIONS_KEY), artifact.source); + } + if (artifact.type === 'file') { + return findByName($.read(FILES_KEY), artifact.source); + } + + return null; +} + +async function produceSyncArtifactOutput(artifact) { + const useMihomoExternal = artifact.platform === 'SurgeMac'; + const output = await produceArtifact({ + type: artifact.type, + name: artifact.source, + platform: artifact.platform, + produceOpts: { + 'include-unsupported-proxy': artifact.includeUnsupportedProxy, + useMihomoExternal, + prettyYaml: artifact.prettyYaml, + }, + }); + + return applyAgeOutputEncryption({ + body: output, + configs: [artifact, findArtifactSourceConfig(artifact)], + }); +} + function markArtifactProducedWithoutUpload(artifact) { artifact.updated = new Date().getTime(); delete artifact.url; @@ -945,17 +1008,9 @@ async function syncArtifacts(options = {}) { ); } - const output = await produceArtifact({ - type: artifact.type, - name: artifact.source, - platform: artifact.platform, - produceOpts: { - 'include-unsupported-proxy': - artifact.includeUnsupportedProxy, - useMihomoExternal, - prettyYaml: artifact.prettyYaml, - }, - }); + const output = await produceSyncArtifactOutput( + artifact, + ); // if (!output || output.length === 0) // throw new Error('该配置的结果为空 不进行上传'); @@ -1077,16 +1132,7 @@ async function syncArtifactItem(name) { if (useMihomoExternal) { $.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`); } - const output = await produceArtifact({ - type: artifact.type, - name: artifact.source, - platform: artifact.platform, - produceOpts: { - 'include-unsupported-proxy': artifact.includeUnsupportedProxy, - useMihomoExternal, - prettyYaml: artifact.prettyYaml, - }, - }); + const output = await produceSyncArtifactOutput(artifact); // if (!output || output.length === 0) // throw new Error('该配置的结果为空 不进行上传'); @@ -1174,6 +1220,7 @@ async function syncArtifact(req, res) { export { markArtifactProducedWithoutUpload, produceArtifact, + produceSyncArtifactOutput, shouldUploadArtifact, syncArtifactItem, syncArtifacts, diff --git a/backend/src/restful/token.js b/backend/src/restful/token.js index 3d47f690..c49b7043 100644 --- a/backend/src/restful/token.js +++ b/backend/src/restful/token.js @@ -10,6 +10,7 @@ import { import { insertByPosition } from '@/utils/database'; import { getCreateItemPosition } from '@/utils/create-item-position'; import { archiveShare } from '@/utils/archive'; +import { normalizeAgePublicKeyConfig } from '@/utils/age'; export default function register($app) { if (!$.read(TOKENS_KEY)) $.write([], TOKENS_KEY); @@ -315,6 +316,7 @@ function createTokenItem(payload, options = {}) { delete safePayload.expiresIn; delete safePayload.count; delete safePayload.usedCount; + normalizeAgePublicKeyConfig(safePayload); const tokenData = { ...safePayload, token, @@ -413,6 +415,15 @@ function consumeShareToken(query) { return nextToken; } +function findShareToken(query) { + const allTokens = $.read(TOKENS_KEY) || []; + return ( + allTokens.find( + (item) => matchesShareToken(item, query) && isShareTokenUsable(item), + ) || null + ); +} + function shouldArchiveDeletion(mode) { if (mode == null || mode === '' || mode === 'permanent') { return false; @@ -426,4 +437,4 @@ function shouldArchiveDeletion(mode) { ); } -export { createTokenItem, deleteTokenItem, consumeShareToken }; +export { createTokenItem, deleteTokenItem, consumeShareToken, findShareToken }; diff --git a/backend/src/test/products/sub-store-0.spec.js b/backend/src/test/products/sub-store-0.spec.js new file mode 100644 index 00000000..70ba1ebd --- /dev/null +++ b/backend/src/test/products/sub-store-0.spec.js @@ -0,0 +1,16 @@ +import { expect } from 'chai'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; +import path from 'path'; + +describe('sub-store-0 product routes', function () { + it('registers age utility routes in the module bundle entry', function () { + const entry = readFileSync( + path.resolve(__dirname, '../../products/sub-store-0.js'), + 'utf8', + ); + + expect(entry).to.include("registerAgeRoutes from '@/restful/age'"); + expect(entry).to.include('registerAgeRoutes($app);'); + }); +}); diff --git a/backend/src/test/restful/age-config-validation.spec.js b/backend/src/test/restful/age-config-validation.spec.js new file mode 100644 index 00000000..d73ef61f --- /dev/null +++ b/backend/src/test/restful/age-config-validation.spec.js @@ -0,0 +1,266 @@ +import { expect } from 'chai'; +import { after, before, beforeEach, describe, it } from 'mocha'; + +import { + ARTIFACTS_KEY, + COLLECTIONS_KEY, + FILES_KEY, + SUBS_KEY, + TOKENS_KEY, +} from '@/constants'; + +let $; +let createArtifactItem; +let createCollectionItem; +let createFileItem; +let createSubscriptionItem; +let createTokenItem; +let registerArtifactRoutes; +let registerCollectionRoutes; +let registerFileRoutes; +let registerSubscriptionRoutes; +let originalRead; +let originalWrite; +let originalInfo; +let originalError; +let originalWarn; +let originalNotify; +let state; + +function createRouteApp() { + const handlers = new Map(); + const methods = ['get', 'post', 'put', 'patch', 'delete']; + + const app = { + handlers, + route(pattern) { + const chain = {}; + methods.forEach((method) => { + chain[method] = (handler) => { + handlers.set(`${method.toUpperCase()} ${pattern}`, handler); + return chain; + }; + }); + return chain; + }, + }; + + methods.forEach((method) => { + app[method] = (pattern, handler) => { + handlers.set(`${method.toUpperCase()} ${pattern}`, handler); + return app; + }; + }); + + return app; +} + +function createResponse(routePath) { + return { + payload: null, + req: { + route: { + path: routePath, + }, + }, + statusCode: 200, + json(data) { + this.payload = data; + return this; + }, + status(code) { + this.statusCode = code; + return this; + }, + }; +} + +async function requestReplace(registerRoutes, path, body) { + const app = createRouteApp(); + registerRoutes(app); + const handler = app.handlers.get(`PUT ${path}`); + const res = createResponse(path); + + await handler({ body }, res); + return res; +} + +describe('age config validation', function () { + before(async function () { + ({ default: $ } = require('@/core/app')); + ({ default: registerSubscriptionRoutes } = require('@/restful/subscriptions')); + ({ default: registerCollectionRoutes } = require('@/restful/collections')); + ({ default: registerFileRoutes } = require('@/restful/file')); + ({ default: registerArtifactRoutes } = require('@/restful/artifacts')); + ({ createSubscriptionItem } = require('@/restful/subscriptions')); + ({ createCollectionItem } = require('@/restful/collections')); + ({ createFileItem } = require('@/restful/file')); + ({ createArtifactItem } = require('@/restful/artifacts')); + ({ createTokenItem } = require('@/restful/token')); + + originalRead = $.read.bind($); + originalWrite = $.write.bind($); + originalInfo = $.info.bind($); + originalError = $.error.bind($); + originalWarn = $.warn.bind($); + originalNotify = $.notify.bind($); + }); + + after(function () { + if ($) { + $.read = originalRead; + $.write = originalWrite; + $.info = originalInfo; + $.error = originalError; + $.warn = originalWarn; + $.notify = originalNotify; + } + }); + + beforeEach(function () { + state = { + [SUBS_KEY]: [{ name: 'shared-sub' }], + [COLLECTIONS_KEY]: [{ name: 'shared-col', subscriptions: [] }], + [FILES_KEY]: [{ name: 'shared-file' }], + [ARTIFACTS_KEY]: [{ name: 'shared-artifact', type: 'file' }], + [TOKENS_KEY]: [], + }; + + $.read = (key) => state[key] || []; + $.write = (data, key) => { + state[key] = data; + return true; + }; + $.info = () => {}; + $.error = () => {}; + $.warn = () => {}; + $.notify = () => {}; + }); + + it('rejects invalid age-public-key in create helpers', function () { + const operations = [ + () => + createSubscriptionItem({ + name: 'new-sub', + 'age-public-key': 'invalid-public-key', + }), + () => + createCollectionItem({ + name: 'new-col', + subscriptions: [], + 'age-public-key': 'invalid-public-key', + }), + () => + createFileItem({ + name: 'new-file', + source: 'local', + content: 'demo', + 'age-public-key': 'invalid-public-key', + }), + () => + createArtifactItem({ + name: 'new-artifact', + type: 'file', + source: 'new-file', + 'age-public-key': 'invalid-public-key', + }), + () => + createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'token-with-bad-key', + 'age-public-key': 'invalid-public-key', + }, + { + mode: 'duration', + expiresIn: '1d', + }, + ), + ]; + + for (const operation of operations) { + let capturedError; + + try { + operation(); + } catch (error) { + capturedError = error; + } + + expect(capturedError).to.include({ + type: 'RequestInvalidError', + code: 'INVALID_AGE_PUBLIC_KEY', + }); + expect(capturedError.message).to.contain('age-public-key 仅支持'); + } + }); + + it('rejects invalid age-public-key in bulk replace routes', async function () { + const expectations = [ + { + registerRoutes: registerSubscriptionRoutes, + path: '/api/subs', + body: [{ name: 'shared-sub', 'age-public-key': 'bad-key' }], + storeKey: SUBS_KEY, + }, + { + registerRoutes: registerCollectionRoutes, + path: '/api/collections', + body: [ + { + name: 'shared-col', + subscriptions: [], + 'age-public-key': 'bad-key', + }, + ], + storeKey: COLLECTIONS_KEY, + }, + { + registerRoutes: registerFileRoutes, + path: '/api/files', + body: [ + { + name: 'shared-file', + source: 'local', + content: 'demo', + 'age-public-key': 'bad-key', + }, + ], + storeKey: FILES_KEY, + }, + { + registerRoutes: registerArtifactRoutes, + path: '/api/artifacts', + body: [ + { + name: 'shared-artifact', + type: 'file', + source: 'shared-file', + 'age-public-key': 'bad-key', + }, + ], + storeKey: ARTIFACTS_KEY, + }, + ]; + + for (const expectation of expectations) { + const previousState = JSON.parse( + JSON.stringify(state[expectation.storeKey]), + ); + const res = await requestReplace( + expectation.registerRoutes, + expectation.path, + expectation.body, + ); + + expect(res.statusCode).to.equal(500); + expect(res.payload.status).to.equal('failed'); + expect(res.payload.error).to.include({ + code: 'INVALID_AGE_PUBLIC_KEY', + type: 'RequestInvalidError', + }); + expect(state[expectation.storeKey]).to.deep.equal(previousState); + } + }); +}); diff --git a/backend/src/test/restful/age.spec.js b/backend/src/test/restful/age.spec.js new file mode 100644 index 00000000..50700766 --- /dev/null +++ b/backend/src/test/restful/age.spec.js @@ -0,0 +1,75 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import registerAgeRoutes from '@/restful/age'; + +function createRouteHarness() { + const routes = {}; + const app = { + post(path, handler) { + routes[path] = handler; + }, + }; + registerAgeRoutes(app); + + async function request(path, body) { + let statusCode; + let payload; + const res = { + req: { route: { path } }, + status(code) { + statusCode = code; + return this; + }, + json(data) { + payload = data; + return this; + }, + }; + + await routes[path]({ body }, res); + return { statusCode, payload }; + } + + return { request }; +} + +describe('age routes', function () { + this.timeout(10000); + + it('generates a key pair and derives its public key', async function () { + const { request } = createRouteHarness(); + + const generated = await request('/api/utils/age/key-pair', { + type: 'x25519', + }); + expect(generated.statusCode).to.equal(200); + expect(generated.payload.status).to.equal('success'); + expect(generated.payload.data['age-public-key']).to.match(/^age1/); + expect(generated.payload.data['age-secret-key']).to.match( + /^AGE-SECRET-KEY-1/, + ); + + const derived = await request('/api/utils/age/public-key', { + 'age-secret-key': generated.payload.data['age-secret-key'], + }); + expect(derived.statusCode).to.equal(200); + expect(derived.payload.data['age-public-key']).to.equal( + generated.payload.data['age-public-key'], + ); + }); + + it('rejects unsupported key generation types', async function () { + const { request } = createRouteHarness(); + + const response = await request('/api/utils/age/key-pair', { + type: 'ssh', + }); + + expect(response.statusCode).to.equal(500); + expect(response.payload.status).to.equal('failed'); + expect(response.payload.error.message).to.contain( + '不支持的 age key 类型', + ); + }); +}); diff --git a/backend/src/test/restful/download.spec.js b/backend/src/test/restful/download.spec.js index 2359fcb0..43f43481 100644 --- a/backend/src/test/restful/download.spec.js +++ b/backend/src/test/restful/download.spec.js @@ -15,6 +15,7 @@ let originalRead; let originalWarn; let originalWrite; let state; +let ageUtils; function createRouteApp() { const handlers = new Map(); @@ -111,10 +112,63 @@ async function downloadCollection(query) { return res.sent; } +async function requestDownloadCollection(query) { + const handler = getHandler('/download/collection/:name'); + const res = createResponse('/download/collection/:name'); + + await handler( + { + body: {}, + headers: {}, + method: 'GET', + params: { name: 'local-col' }, + path: '/download/collection/local-col', + query, + url: '/download/collection/local-col', + }, + res, + ); + + return res; +} + +async function requestShareSubscription({ query = {}, shareToken } = {}) { + const handler = getHandler('/share/sub/:name'); + const res = createResponse('/share/sub/:name'); + + await handler( + { + body: {}, + headers: {}, + method: 'GET', + params: { name: 'local-vless' }, + path: '/share/sub/local-vless', + query, + subStoreShareToken: shareToken, + url: '/share/sub/local-vless', + }, + res, + ); + + return res; +} + +async function expectDecryptFailure(armored, secretKey) { + try { + await ageUtils.decryptArmorIfPresent(armored, secretKey); + } catch (e) { + expect(e.message).to.contain('age 解密失败'); + return; + } + + throw new Error('Expected age decrypt to fail'); +} + describe('download routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); ({ default: registerDownloadRoutes } = require('@/restful/download')); + ageUtils = require('@/utils/age'); originalRead = $.read.bind($); originalWrite = $.write.bind($); @@ -272,4 +326,73 @@ describe('download routes', function () { expect(res.statusCode).to.equal(201); expect(res.sent).to.equal('local-vless'); }); + + it('encrypts transformed subscription output with source age-public-key', async function () { + const pair = await ageUtils.generateKeyPair(); + state[SUBS_KEY][0]['age-public-key'] = pair['age-public-key']; + state[SUBS_KEY][0].process = [ + { + type: 'Response Transformer', + args: { + mode: 'script', + content: + "$res.header['x-test'] = 'ok'\n$res.body = 'changed'", + }, + }, + ]; + + const res = await requestDownloadSubscription({ target: 'JSON' }); + const decrypted = await ageUtils.decryptArmorIfPresent( + res.sent, + pair['age-secret-key'], + ); + + expect(res.headers['x-test']).to.equal('ok'); + expect(res.headers['Content-Type']).to.equal( + 'text/plain; charset=utf-8', + ); + expect(res.sent).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.equal('changed'); + }); + + it('encrypts collection output with collection age-public-key', async function () { + const pair = await ageUtils.generateKeyPair(); + state[COLLECTIONS_KEY][0]['age-public-key'] = pair['age-public-key']; + + const res = await requestDownloadCollection({ target: 'JSON' }); + const decrypted = await ageUtils.decryptArmorIfPresent( + res.sent, + pair['age-secret-key'], + ); + + expect(res.headers['Content-Type']).to.equal( + 'text/plain; charset=utf-8', + ); + expect(res.sent).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.include('VLESS WS'); + }); + + it('uses share age-public-key before source subscription key', async function () { + const sourcePair = await ageUtils.generateKeyPair(); + const sharePair = await ageUtils.generateKeyPair(); + state[SUBS_KEY][0]['age-public-key'] = sourcePair['age-public-key']; + + const res = await requestShareSubscription({ + query: { target: 'JSON' }, + shareToken: { + type: 'sub', + name: 'local-vless', + 'age-public-key': sharePair['age-public-key'], + }, + }); + const decrypted = await ageUtils.decryptArmorIfPresent( + res.sent, + sharePair['age-secret-key'], + ); + + expect(res.sent).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.include('VLESS WS'); + await expectDecryptFailure(res.sent, sourcePair['age-secret-key']); + }); + }); diff --git a/backend/src/test/restful/file.spec.js b/backend/src/test/restful/file.spec.js index 210f15d9..cfc20c5a 100644 --- a/backend/src/test/restful/file.spec.js +++ b/backend/src/test/restful/file.spec.js @@ -12,6 +12,7 @@ let originalRead; let originalWarn; let originalWrite; let state; +let ageUtils; function createRouteApp() { const handlers = new Map(); @@ -99,10 +100,43 @@ async function requestFile(query = {}) { return res; } +async function requestShareFile({ query = {}, shareToken } = {}) { + const handler = getHandler('/share/file/:name'); + const res = createResponse('/share/file/:name'); + + await handler( + { + body: {}, + headers: {}, + method: 'GET', + params: { name: 'local-file' }, + path: '/share/file/local-file', + query, + subStoreShareToken: shareToken, + url: '/share/file/local-file', + }, + res, + ); + + return res; +} + +async function expectDecryptFailure(armored, secretKey) { + try { + await ageUtils.decryptArmorIfPresent(armored, secretKey); + } catch (e) { + expect(e.message).to.contain('age 解密失败'); + return; + } + + throw new Error('Expected age decrypt to fail'); +} + describe('file routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); ({ default: registerFileRoutes } = require('@/restful/file')); + ageUtils = require('@/utils/age'); originalRead = $.read.bind($); originalWrite = $.write.bind($); @@ -171,4 +205,62 @@ describe('file routes', function () { expect(res.headers['x-from-options']).to.equal('carried'); expect(res.sent).to.equal('base-script-carried'); }); + + it('encrypts transformed file output with file age-public-key', async function () { + const pair = await ageUtils.generateKeyPair(); + state[FILES_KEY][0]['age-public-key'] = pair['age-public-key']; + state[FILES_KEY][0].process = [ + { + type: 'Script Operator', + args: { + mode: 'script', + content: + "$options.fromOperator = 'carried'\n$content = `${$content}-script`", + }, + }, + { + type: 'Response Transformer', + args: { + mode: 'script', + content: + "$res.header['x-from-options'] = $options.fromOperator\n$res.body = `${$res.body}-${$options.fromOperator}`", + }, + }, + ]; + + const res = await requestFile(); + const decrypted = await ageUtils.decryptArmorIfPresent( + res.sent, + pair['age-secret-key'], + ); + + expect(res.headers['x-from-options']).to.equal('carried'); + expect(res.headers['Content-Type']).to.equal( + 'text/plain; charset=utf-8', + ); + expect(res.sent).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.equal('base-script-carried'); + }); + + it('uses share age-public-key before source file key', async function () { + const sourcePair = await ageUtils.generateKeyPair(); + const sharePair = await ageUtils.generateKeyPair(); + state[FILES_KEY][0]['age-public-key'] = sourcePair['age-public-key']; + + const res = await requestShareFile({ + shareToken: { + type: 'file', + name: 'local-file', + 'age-public-key': sharePair['age-public-key'], + }, + }); + const decrypted = await ageUtils.decryptArmorIfPresent( + res.sent, + sharePair['age-secret-key'], + ); + + expect(res.sent).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.equal('base'); + await expectDecryptFailure(res.sent, sourcePair['age-secret-key']); + }); }); diff --git a/backend/src/test/restful/sync.spec.js b/backend/src/test/restful/sync.spec.js index 551b3191..e0538fdc 100644 --- a/backend/src/test/restful/sync.spec.js +++ b/backend/src/test/restful/sync.spec.js @@ -6,11 +6,13 @@ import { ARTIFACTS_KEY, FILES_KEY, SETTINGS_KEY } from '@/constants'; let $; let registerArtifactRoutes; let registerSyncRoutes; +let produceSyncArtifactOutput; let originalError; let originalInfo; let originalRead; let originalWrite; let state; +let ageUtils; function createRouteApp() { const handlers = new Map(); @@ -102,7 +104,10 @@ describe('sync routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); ({ default: registerArtifactRoutes } = require('@/restful/artifacts')); - ({ default: registerSyncRoutes } = require('@/restful/sync')); + ({ default: registerSyncRoutes, produceSyncArtifactOutput } = require( + '@/restful/sync' + )); + ageUtils = require('@/utils/age'); originalRead = $.read.bind($); originalWrite = $.write.bind($); @@ -210,4 +215,58 @@ describe('sync routes', function () { }); expect(state[ARTIFACTS_KEY]).to.deep.equal([]); }); + + it('encrypts sync artifact output with artifact age-public-key', async function () { + const pair = await ageUtils.generateKeyPair(); + state[ARTIFACTS_KEY][0]['age-public-key'] = pair['age-public-key']; + + const output = await produceSyncArtifactOutput(state[ARTIFACTS_KEY][0]); + const decrypted = await ageUtils.decryptArmorIfPresent( + output, + pair['age-secret-key'], + ); + + expect(output).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.equal('local content'); + }); + + it('uses source age-public-key when artifact has no key', async function () { + const pair = await ageUtils.generateKeyPair(); + state[FILES_KEY][0]['age-public-key'] = pair['age-public-key']; + + const output = await produceSyncArtifactOutput(state[ARTIFACTS_KEY][0]); + const decrypted = await ageUtils.decryptArmorIfPresent( + output, + pair['age-secret-key'], + ); + + expect(output).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.equal('local content'); + }); + + it('uses artifact age-public-key before source key', async function () { + const sourcePair = await ageUtils.generateKeyPair(); + const artifactPair = await ageUtils.generateKeyPair(); + state[FILES_KEY][0]['age-public-key'] = sourcePair['age-public-key']; + state[ARTIFACTS_KEY][0]['age-public-key'] = + artifactPair['age-public-key']; + + const output = await produceSyncArtifactOutput(state[ARTIFACTS_KEY][0]); + const decrypted = await ageUtils.decryptArmorIfPresent( + output, + artifactPair['age-secret-key'], + ); + + expect(output).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(decrypted).to.equal('local content'); + try { + await ageUtils.decryptArmorIfPresent( + output, + sourcePair['age-secret-key'], + ); + throw new Error('Expected source key decrypt to fail'); + } catch (e) { + expect(e.message).to.contain('age 解密失败'); + } + }); }); diff --git a/backend/src/test/restful/token.spec.js b/backend/src/test/restful/token.spec.js index 3143ed33..3dd83461 100644 --- a/backend/src/test/restful/token.spec.js +++ b/backend/src/test/restful/token.spec.js @@ -9,16 +9,22 @@ import { let $; let createTokenItem; +let consumeShareToken; +let findShareToken; let state; let originalRead; let originalWrite; let originalInfo; let originalError; +let ageUtils; describe('token routes', function () { before(async function () { ({ default: $ } = require('@/core/app')); - ({ createTokenItem } = require('@/restful/token')); + ({ createTokenItem, consumeShareToken, findShareToken } = require( + '@/restful/token' + )); + ageUtils = require('@/utils/age'); originalRead = $.read.bind($); originalWrite = $.write.bind($); @@ -269,4 +275,56 @@ describe('token routes', function () { expect(state[TOKENS_KEY][0]).to.not.have.property('exp'); expect(state[TOKENS_KEY][0]).to.not.have.property('expiresIn'); }); + + it('preserves age-public-key in share token payload', async function () { + const pair = await ageUtils.generateKeyPair(); + const token = createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'age-token', + 'age-public-key': pair['age-public-key'], + mode: 'datetime', + exp: Date.now() + 60 * 1000, + }, + {}, + ); + + expect(token['age-public-key']).to.equal(pair['age-public-key']); + expect(token).to.not.have.property('mode'); + expect(token).to.not.have.property('exp'); + expect(state[TOKENS_KEY][0]['age-public-key']).to.equal(pair['age-public-key']); + }); + + it('lets routes read consumed count token metadata without another count increment', async function () { + const pair = await ageUtils.generateKeyPair(); + createTokenItem( + { + type: 'sub', + name: 'shared-sub', + token: 'count-age-token', + 'age-public-key': pair['age-public-key'], + }, + { + mode: 'count', + count: 2, + }, + ); + + const consumed = consumeShareToken({ + token: 'count-age-token', + type: 'sub', + name: 'shared-sub', + }); + const found = findShareToken({ + token: 'count-age-token', + type: 'sub', + name: 'shared-sub', + }); + + expect(consumed.usedCount).to.equal(1); + expect(consumed['age-public-key']).to.equal(pair['age-public-key']); + expect(found.usedCount).to.equal(1); + expect(state[TOKENS_KEY][0].usedCount).to.equal(1); + }); }); diff --git a/backend/src/test/utils/age-bundle.spec.js b/backend/src/test/utils/age-bundle.spec.js new file mode 100644 index 00000000..9fbfd1ac --- /dev/null +++ b/backend/src/test/utils/age-bundle.spec.js @@ -0,0 +1,107 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; +import { build } from 'esbuild'; +import vm from 'vm'; +import { webcrypto } from 'crypto'; + +describe('age bundle compatibility', function () { + this.timeout(10000); + + async function loadAgeBundle(crypto) { + const result = await build({ + entryPoints: ['src/utils/age.js'], + bundle: true, + write: false, + platform: 'browser', + format: 'iife', + globalName: 'SubStoreAge', + }); + const output = result.outputFiles[0].text; + const sandbox = { + console, + crypto, + DOMException, + ReadableStream, + Response, + TextDecoder, + TextEncoder, + TransformStream, + Uint8Array, + }; + sandbox.globalThis = sandbox; + vm.runInNewContext(output, sandbox); + + return sandbox.SubStoreAge; + } + + it('bundles the age utility for browser IIFE artifacts without Node require calls', async function () { + const result = await build({ + entryPoints: ['src/utils/age.js'], + bundle: true, + write: false, + platform: 'browser', + format: 'iife', + globalName: 'SubStoreAge', + }); + const output = result.outputFiles[0].text; + + expect(output).to.contain('SubStoreAge'); + expect(output).to.not.match(/\brequire\s*\(/); + }); + + it('uses the pure JS X25519 fallback when WebCrypto subtle is unavailable', async function () { + const age = await loadAgeBundle({ + getRandomValues: webcrypto.getRandomValues.bind(webcrypto), + }); + + const pair = await age.generateKeyPair('x25519'); + expect(pair['age-secret-key']).to.match(/^AGE-SECRET-KEY-1/); + expect(pair['age-public-key']).to.match(/^age1/); + + const encrypted = await age.encryptArmor( + 'hello surge', + pair['age-public-key'], + ); + const decrypted = await age.decryptArmorIfPresent( + encrypted, + pair['age-secret-key'], + ); + expect(decrypted).to.equal('hello surge'); + }); + + it('uses the pure JS X25519 fallback when WebCrypto X25519 throws TypeError', async function () { + const age = await loadAgeBundle({ + getRandomValues: webcrypto.getRandomValues.bind(webcrypto), + subtle: { + importKey: async () => { + throw new TypeError('Algorithm not supported'); + }, + deriveBits: async () => { + throw new TypeError('Algorithm not supported'); + }, + }, + }); + + const pair = await age.generateKeyPair('x25519'); + expect(pair['age-secret-key']).to.match(/^AGE-SECRET-KEY-1/); + expect(pair['age-public-key']).to.match(/^age1/); + }); + + it('uses the pure JS X25519 fallback when WebCrypto X25519 throws unsupported Error', async function () { + const age = await loadAgeBundle({ + getRandomValues: webcrypto.getRandomValues.bind(webcrypto), + subtle: { + importKey: async () => { + throw new Error('Algorithm not supported'); + }, + deriveBits: async () => { + throw new Error('Algorithm not supported'); + }, + }, + }); + + const pair = await age.generateKeyPair('x25519'); + expect(pair['age-secret-key']).to.match(/^AGE-SECRET-KEY-1/); + expect(pair['age-public-key']).to.match(/^age1/); + }); +}); diff --git a/backend/src/test/utils/age.spec.js b/backend/src/test/utils/age.spec.js new file mode 100644 index 00000000..5f9408be --- /dev/null +++ b/backend/src/test/utils/age.spec.js @@ -0,0 +1,132 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { + AGE_ARMOR_HEADER, + AGE_KEY_TYPES, + assertAgeRuntimeAvailable, + decryptArmorIfPresent, + derivePublicKey, + encryptArmor, + generateKeyPair, + maskAgeSecret, + maskAgeSecretInUrl, + normalizeAgePublicKeyConfig, + validateIdentity, + validateRecipient, +} from '@/utils/age'; + +describe('age utility', function () { + this.timeout(10000); + + async function expectRejected(promise, message) { + try { + await promise; + } catch (e) { + expect(e.message).to.contain(message); + return; + } + + throw new Error('Expected promise to reject'); + } + + async function assertRoundTrip(type) { + const pair = await generateKeyPair(type); + const secretKey = pair['age-secret-key']; + const publicKey = pair['age-public-key']; + + expect(await derivePublicKey(secretKey)).to.equal(publicKey); + + const armored = await encryptArmor('hello age', publicKey); + expect(armored).to.contain(AGE_ARMOR_HEADER); + + const decrypted = await decryptArmorIfPresent(armored, secretKey); + expect(decrypted).to.equal('hello age'); + } + + it('generates X25519 keys and round-trips armored text', async function () { + await assertRoundTrip(AGE_KEY_TYPES.X25519); + }); + + it('generates MLKEM768-X25519 hybrid keys and round-trips armored text', async function () { + await assertRoundTrip(AGE_KEY_TYPES.HYBRID); + }); + + it('leaves non-armor text unchanged during decrypt', async function () { + const pair = await generateKeyPair(); + + expect( + await decryptArmorIfPresent( + 'proxy: DIRECT', + pair['age-secret-key'], + ), + ).to.equal('proxy: DIRECT'); + }); + + it('rejects unsupported recipient formats', function () { + expect(() => validateRecipient('ssh-ed25519 AAAA')).to.throw( + 'age-public-key 仅支持', + ); + expect(() => validateRecipient('age1tag1bad')).to.throw( + 'age-public-key 仅支持', + ); + expect(() => validateRecipient('age1bad')).to.throw( + 'age-public-key 仅支持', + ); + }); + + it('rejects unsupported identity formats', async function () { + await expectRejected( + validateIdentity('AGE-PLUGIN-FIDO2PRF-1ABCDEF'), + 'age-secret-key 仅支持', + ); + await expectRejected( + validateIdentity('not-a-secret'), + 'age-secret-key 仅支持', + ); + }); + + it('reports missing runtime APIs before age operations proceed', function () { + expect(() => assertAgeRuntimeAvailable({})).to.throw( + '当前运行环境缺少 age 加解密所需 Web API', + ); + }); + + it('masks full secret keys in strings', async function () { + const pair = await generateKeyPair(); + const secretKey = pair['age-secret-key']; + const masked = maskAgeSecret(`secret=${secretKey}`); + + expect(masked).to.not.contain(secretKey); + expect(masked).to.contain('AGE-SECRET-KEY-1...'); + }); + + it('masks age-secret-key URL parameters', async function () { + const pair = await generateKeyPair(); + const secretKey = pair['age-secret-key']; + const masked = maskAgeSecretInUrl( + `https://example.com/sub#noCache&age-secret-key=${secretKey}`, + ); + + expect(masked).to.not.contain(secretKey); + expect(masked).to.contain('age-secret-key=***'); + }); + + it('normalizes optional age-public-key config fields', async function () { + const pair = await generateKeyPair(); + const withKey = { + 'age-public-key': ` ${pair['age-public-key']} `, + }; + expect(normalizeAgePublicKeyConfig(withKey)).to.equal(withKey); + expect(withKey['age-public-key']).to.equal(pair['age-public-key']); + + const withoutKey = { + name: 'demo', + 'age-public-key': '', + }; + expect(normalizeAgePublicKeyConfig(withoutKey)).to.equal(withoutKey); + expect(withoutKey).to.not.have.property('age-public-key'); + + expect(normalizeAgePublicKeyConfig(null)).to.equal(null); + }); +}); diff --git a/backend/src/test/utils/download.spec.js b/backend/src/test/utils/download.spec.js index 9f6da035..cac6d379 100644 --- a/backend/src/test/utils/download.spec.js +++ b/backend/src/test/utils/download.spec.js @@ -25,10 +25,13 @@ let state; let tempDir; let previousDataBasePath; let capturedUrls; +let infoLogs; let errorLogs; let activeRequests; let maxActiveRequests; let requestDelay; +let responseBody; +let ageUtils; function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); @@ -47,6 +50,7 @@ describe('download github proxy regex', function () { '@/utils/headers-resource-cache' )); ({ default: download } = require('@/utils/download')); + ageUtils = require('@/utils/age'); originalRead = $.read.bind($); originalWrite = $.write.bind($); @@ -82,10 +86,12 @@ describe('download github proxy regex', function () { beforeEach(function () { capturedUrls = []; + infoLogs = []; errorLogs = []; activeRequests = 0; maxActiveRequests = 0; requestDelay = 0; + responseBody = 'test-body'; state = { [SETTINGS_KEY]: { githubProxy: 'https://ghproxy.test', @@ -100,7 +106,9 @@ describe('download github proxy regex', function () { state[key] = data; return true; }; - $.info = () => {}; + $.info = (message) => { + infoLogs.push(message); + }; $.error = (message) => { errorLogs.push(message); }; @@ -124,7 +132,7 @@ describe('download github proxy regex', function () { if (requestDelay > 0) await sleep(requestDelay); activeRequests -= 1; return { - body: 'test-body', + body: responseBody, headers: {}, statusCode: 200, }; @@ -201,4 +209,63 @@ describe('download github proxy regex', function () { ]); expect(maxActiveRequests).to.equal(1); }); + + it('decrypts age-armored downloads without caching plaintext for unkeyed requests', async function () { + const pair = await ageUtils.generateKeyPair(); + responseBody = await ageUtils.encryptArmor( + 'decrypted-body', + pair['age-public-key'], + ); + + const keyed = await download( + `https://example.com/age.txt#age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + ); + const unkeyed = await download('https://example.com/age.txt'); + + expect(keyed).to.equal('decrypted-body'); + expect(unkeyed).to.contain(ageUtils.AGE_ARMOR_HEADER); + expect(unkeyed).to.not.equal('decrypted-body'); + expect(capturedUrls).to.deep.equal(['https://example.com/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'; + + const body = await download( + `https://example.com/plain.txt#age-secret-key=${encodeURIComponent( + pair['age-secret-key'], + )}`, + ); + + expect(body).to.equal('plain subscription body'); + }); + + it('does not expose age-secret-key in failed download errors or logs', async function () { + const encryptPair = await ageUtils.generateKeyPair(); + const wrongPair = await ageUtils.generateKeyPair(); + responseBody = await ageUtils.encryptArmor( + 'decrypted-body', + encryptPair['age-public-key'], + ); + + try { + await download( + `https://example.com/wrong-key.txt#age-secret-key=${encodeURIComponent( + wrongPair['age-secret-key'], + )}`, + ); + throw new Error('Expected download to fail'); + } catch (e) { + expect(e.message).to.contain('age 解密失败'); + expect(e.message).to.not.contain(wrongPair['age-secret-key']); + } + + expect(infoLogs.join('\n')).to.not.contain(wrongPair['age-secret-key']); + expect(errorLogs.join('\n')).to.not.contain( + wrongPair['age-secret-key'], + ); + }); }); diff --git a/backend/src/utils/age.js b/backend/src/utils/age.js new file mode 100644 index 00000000..1ccb3c30 --- /dev/null +++ b/backend/src/utils/age.js @@ -0,0 +1,401 @@ +import * as age from 'age-encryption'; + +import { RequestInvalidError } from '@/restful/errors'; + +const AGE_ARMOR_HEADER = '-----BEGIN AGE ENCRYPTED FILE-----'; +const AGE_PUBLIC_KEY = 'age-public-key'; +const AGE_SECRET_KEY = 'age-secret-key'; + +const AGE_KEY_TYPES = Object.freeze({ + X25519: 'x25519', + HYBRID: 'mlkem768-x25519', +}); + +const REQUIRED_RUNTIME_APIS = [ + 'TextEncoder', + 'TextDecoder', + 'ReadableStream', + 'TransformStream', + 'Response', + 'Uint8Array', +]; + +const SECRET_KEY_PATTERN = + /\bAGE-SECRET-KEY(?:-PQ)?-1[023456789ACDEFGHJKLMNPQRSTUVWXYZ]+\b/g; +const X25519_SUBTLE_FALLBACK_MARK = '__subStoreAgeX25519Fallback'; + +function normalizeKey(value) { + return String(value ?? '').trim(); +} + +function normalizeAgePublicKeyConfig(config) { + if (!config || typeof config !== 'object') { + return config; + } + + const key = normalizeKey(config[AGE_PUBLIC_KEY]); + if (key) { + config[AGE_PUBLIC_KEY] = validateRecipient(key); + } else { + delete config[AGE_PUBLIC_KEY]; + } + return config; +} + +function isSupportedX25519Recipient(key) { + return ( + key.startsWith('age1') && + !key.startsWith('age1pq1') && + !key.startsWith('age1tag1') && + !key.startsWith('age1tagpq1') + ); +} + +function isSupportedHybridRecipient(key) { + return key.startsWith('age1pq1'); +} + +function isSupportedX25519Identity(key) { + return key.startsWith('AGE-SECRET-KEY-1'); +} + +function isSupportedHybridIdentity(key) { + return key.startsWith('AGE-SECRET-KEY-PQ-1'); +} + +function createUnsupportedRecipientError() { + return new RequestInvalidError( + 'INVALID_AGE_PUBLIC_KEY', + 'age-public-key 仅支持 X25519(age1...) 或 MLKEM768-X25519(age1pq1...) 公钥', + ); +} + +function createUnsupportedIdentityError() { + return new RequestInvalidError( + 'INVALID_AGE_SECRET_KEY', + 'age-secret-key 仅支持 X25519(AGE-SECRET-KEY-1...) 或 MLKEM768-X25519(AGE-SECRET-KEY-PQ-1...) 私钥', + ); +} + +function assertAgeRuntimeAvailable(root = globalThis) { + const missing = REQUIRED_RUNTIME_APIS.filter( + (name) => typeof root?.[name] === 'undefined', + ); + const crypto = root?.crypto; + const hasRandomValues = + crypto && typeof crypto.getRandomValues === 'function'; + + if (!hasRandomValues) { + missing.push('crypto.getRandomValues'); + } + + if (missing.length > 0) { + throw new Error( + `当前运行环境缺少 age 加解密所需 Web API: ${missing.join(', ')}`, + ); + } + + installX25519SubtleFallback(root); +} + +function createX25519SubtleNotSupportedError() { + if (typeof DOMException !== 'undefined') { + return new DOMException( + 'X25519 WebCrypto is not available', + 'NotSupportedError', + ); + } + + return new ReferenceError('X25519 WebCrypto is not available'); +} + +function createX25519FallbackSubtle() { + const fallback = { + importKey() { + throw createX25519SubtleNotSupportedError(); + }, + deriveBits() { + throw createX25519SubtleNotSupportedError(); + }, + }; + fallback[X25519_SUBTLE_FALLBACK_MARK] = true; + return fallback; +} + +function getAlgorithmName(algorithm) { + return typeof algorithm === 'string' ? algorithm : algorithm?.name; +} + +function isX25519Algorithm(algorithm) { + return String(getAlgorithmName(algorithm) || '').toUpperCase() === 'X25519'; +} + +function isX25519UnsupportedErrorMessage(error) { + const message = String(error?.message || error || ''); + return /x25519|algorithm|not\s+supported|unsupported|unrecognized|unknown/i.test( + message, + ); +} + +function isX25519WebCryptoFallbackError(error) { + return ( + error instanceof TypeError || + error instanceof ReferenceError || + error?.name === 'TypeError' || + error?.name === 'ReferenceError' || + error?.name === 'NotSupportedError' || + (error?.name === 'Error' && isX25519UnsupportedErrorMessage(error)) || + (typeof DOMException !== 'undefined' && + error instanceof DOMException && + error.name === 'NotSupportedError') + ); +} + +function createWrappedSubtle(subtle) { + const wrapped = Object.create(subtle); + Object.defineProperty(wrapped, X25519_SUBTLE_FALLBACK_MARK, { + configurable: true, + value: true, + }); + Object.defineProperty(wrapped, 'importKey', { + configurable: true, + value: async (...args) => { + try { + return await subtle.importKey.apply(subtle, args); + } catch (error) { + if ( + isX25519Algorithm(args[2]) && + isX25519WebCryptoFallbackError(error) + ) { + throw createX25519SubtleNotSupportedError(); + } + throw error; + } + }, + }); + Object.defineProperty(wrapped, 'deriveBits', { + configurable: true, + value: async (...args) => { + try { + return await subtle.deriveBits.apply(subtle, args); + } catch (error) { + if ( + isX25519Algorithm(args[0]) && + isX25519WebCryptoFallbackError(error) + ) { + throw createX25519SubtleNotSupportedError(); + } + throw error; + } + }, + }); + + return wrapped; +} + +function setCryptoSubtle(root, crypto, subtle) { + try { + crypto.subtle = subtle; + if (crypto.subtle === subtle) { + return true; + } + } catch (e) { + // Some proxy app runtimes expose crypto as a host object. + } + + try { + Object.defineProperty(crypto, 'subtle', { + configurable: true, + value: subtle, + }); + if (crypto.subtle === subtle) { + return true; + } + } catch (e) { + // Fall through to replacing global crypto when possible. + } + + try { + const shimmedCrypto = Object.create(crypto); + Object.defineProperty(shimmedCrypto, 'subtle', { + configurable: true, + value: subtle, + }); + if (typeof crypto.getRandomValues === 'function') { + Object.defineProperty(shimmedCrypto, 'getRandomValues', { + configurable: true, + value: crypto.getRandomValues.bind(crypto), + }); + } + root.crypto = shimmedCrypto; + return root.crypto?.subtle === subtle; + } catch (e) { + return false; + } +} + +function installX25519SubtleFallback(root = globalThis) { + const crypto = root?.crypto; + const subtle = crypto?.subtle; + + if (!crypto || subtle?.[X25519_SUBTLE_FALLBACK_MARK]) { + return; + } + + if ( + !subtle || + typeof subtle.importKey !== 'function' || + typeof subtle.deriveBits !== 'function' + ) { + setCryptoSubtle(root, crypto, createX25519FallbackSubtle()); + return; + } + + if (typeof process === 'undefined') { + setCryptoSubtle(root, crypto, createWrappedSubtle(subtle)); + } +} + +function validateRecipient(recipient) { + const key = normalizeKey(recipient); + + if ( + !key || + (!isSupportedX25519Recipient(key) && !isSupportedHybridRecipient(key)) + ) { + throw createUnsupportedRecipientError(); + } + + try { + const encrypter = new age.Encrypter(); + encrypter.addRecipient(key); + } catch (e) { + throw createUnsupportedRecipientError(); + } + + return key; +} + +async function validateIdentity(identity) { + const key = normalizeKey(identity); + + if ( + !key || + (!isSupportedX25519Identity(key) && !isSupportedHybridIdentity(key)) + ) { + throw createUnsupportedIdentityError(); + } + + try { + await age.identityToRecipient(key); + } catch (e) { + throw createUnsupportedIdentityError(); + } + + return key; +} + +async function generateKeyPair(type = AGE_KEY_TYPES.X25519) { + assertAgeRuntimeAvailable(); + + let secretKey; + if (type === AGE_KEY_TYPES.X25519) { + secretKey = await age.generateX25519Identity(); + } else if (type === AGE_KEY_TYPES.HYBRID) { + secretKey = await age.generateHybridIdentity(); + } else { + throw new Error( + `不支持的 age key 类型: ${type}. 支持: ${Object.values( + AGE_KEY_TYPES, + ).join(', ')}`, + ); + } + + const publicKey = await derivePublicKey(secretKey); + return { + type, + [AGE_SECRET_KEY]: secretKey, + [AGE_PUBLIC_KEY]: publicKey, + }; +} + +async function derivePublicKey(identity) { + assertAgeRuntimeAvailable(); + + const key = await validateIdentity(identity); + const recipient = await age.identityToRecipient(key); + return validateRecipient(recipient); +} + +async function encryptArmor(plaintext, recipient) { + assertAgeRuntimeAvailable(); + + const key = validateRecipient(recipient); + const encrypter = new age.Encrypter(); + encrypter.addRecipient(key); + const ciphertext = await encrypter.encrypt(plaintext ?? ''); + + return age.armor.encode(ciphertext); +} + +function isAgeArmor(value) { + return normalizeKey(value).startsWith(AGE_ARMOR_HEADER); +} + +async function decryptArmorIfPresent(input, identity) { + const body = input ?? ''; + const text = typeof body === 'string' ? body : new TextDecoder().decode(body); + + if (!isAgeArmor(text)) { + return body; + } + + assertAgeRuntimeAvailable(); + + const key = await validateIdentity(identity); + const decrypter = new age.Decrypter(); + decrypter.addIdentity(key); + + try { + const decoded = age.armor.decode(text); + return await decrypter.decrypt(decoded, 'text'); + } catch (e) { + throw new Error(`age 解密失败: ${e?.message ?? e}`); + } +} + +function maskAgeSecret(value) { + return String(value ?? '').replace(SECRET_KEY_PATTERN, (secret) => { + const prefix = secret.startsWith('AGE-SECRET-KEY-PQ-1') + ? 'AGE-SECRET-KEY-PQ-1' + : 'AGE-SECRET-KEY-1'; + return `${prefix}...${secret.slice(-6)}`; + }); +} + +function maskAgeSecretInUrl(value) { + return maskAgeSecret( + String(value ?? '').replace( + /([?#&]age-secret-key=)[^&#\s]+/gi, + '$1***', + ), + ); +} + +export { + AGE_ARMOR_HEADER, + AGE_KEY_TYPES, + AGE_PUBLIC_KEY, + AGE_SECRET_KEY, + assertAgeRuntimeAvailable, + decryptArmorIfPresent, + derivePublicKey, + encryptArmor, + generateKeyPair, + isAgeArmor, + maskAgeSecret, + maskAgeSecretInUrl, + normalizeAgePublicKeyConfig, + validateIdentity, + validateRecipient, +}; diff --git a/backend/src/utils/download.js b/backend/src/utils/download.js index 21c6648e..ec90c8d9 100644 --- a/backend/src/utils/download.js +++ b/backend/src/utils/download.js @@ -16,6 +16,11 @@ import { produceArtifact } from '@/restful/sync'; import PROXY_PREPROCESSORS from '@/core/proxy-utils/preprocessors'; import { ProxyUtils } from '@/core/proxy-utils'; import { runBackendRequestTask } from '@/utils/request-concurrency'; +import { + AGE_SECRET_KEY, + decryptArmorIfPresent, + maskAgeSecretInUrl, +} from '@/utils/age'; const clashPreprocessor = PROXY_PREPROCESSORS.find( (processor) => processor.name === 'Clash Pre-processor', @@ -59,6 +64,52 @@ function maybePrefixGithubProxyUrl(url, githubProxy, githubProxyRegex) { return `${githubProxy}/${url}`; } +function maskDownloadUrl(url) { + return maskAgeSecretInUrl(url); +} + +async function finalizeDownloadedBody(body, { ageSecretKey, preprocess, url }) { + let result = ageSecretKey + ? await decryptArmorIfPresent(body, ageSecretKey) + : body; + + if (preprocess) { + try { + if (clashPreprocessor.test(result)) { + result = clashPreprocessor.parse(result, true); + } + } catch (e) { + $.error(`Clash Pre-processor error: ${e}`); + } + } + + if (preprocess) { + try { + const proxies = ProxyUtils.parse(result); + if (!Array.isArray(proxies) || proxies.length === 0) { + return { + result, + shouldCache: false, + cacheReason: `URL ${url} 不包含有效节点, 不缓存`, + }; + } + } catch (e) { + return { + result, + shouldCache: false, + cacheReason: `URL ${url} 尝试解析节点失败 ${ + e.message ?? e + }, 不缓存`, + }; + } + } + + return { + result, + shouldCache: true, + }; +} + export default async function download( rawUrl = '', ua, @@ -89,6 +140,7 @@ export default async function download( } } } + const ageSecretKey = $arguments?.[AGE_SECRET_KEY]; const { isNode, isStash, isLoon, isShadowRocket, isQX } = ENV(); const { githubProxy, @@ -127,6 +179,7 @@ export default async function download( const requestTimeout = timeout || defaultTimeout || 8000; url = maybePrefixGithubProxyUrl(url, githubProxy, githubProxyRegex); + const safeUrl = maskDownloadUrl(url); const id = hex_md5( `${customHeaders ? JSON.stringify(customHeaders) : userAgent}${url}`, ); @@ -145,13 +198,19 @@ export default async function download( const cached = resourceCache.get(id); if (!noCache && !$arguments?.noCache && cached) { $.info( - `乐观缓存: URL ${url}\n存在有效的常规缓存\n使用常规缓存以避免重复请求`, + `乐观缓存: URL ${safeUrl}\n存在有效的常规缓存\n使用常规缓存以避免重复请求`, ); - return cached; + return ( + await finalizeDownloadedBody(cached, { + ageSecretKey, + preprocess, + url: safeUrl, + }) + ).result; } if (customCached) { if (awaitCustomCache) { - $.info(`乐观缓存: URL ${url}\n本次进行请求 尝试更新缓存`); + $.info(`乐观缓存: URL ${safeUrl}\n本次进行请求 尝试更新缓存`); try { await download( rawUrl.replace(/(\?|&)cacheKey=.*?(&|$)/, ''), @@ -165,7 +224,7 @@ export default async function download( ); } catch (e) { $.error( - `乐观缓存: URL ${url} 更新缓存发生错误 ${ + `乐观缓存: URL ${safeUrl} 更新缓存发生错误 ${ e.message ?? e }`, ); @@ -174,7 +233,7 @@ export default async function download( } } else { $.info( - `乐观缓存: URL ${url}\n本次返回自定义缓存 ${$arguments?.cacheKey}\n并进行请求 尝试异步更新缓存`, + `乐观缓存: URL ${safeUrl}\n本次返回自定义缓存 ${$arguments?.cacheKey}\n并进行请求 尝试异步更新缓存`, ); download( rawUrl.replace(/(\?|&)cacheKey=.*?(&|$)/, ''), @@ -187,13 +246,19 @@ export default async function download( preprocess, ).catch((e) => { $.error( - `乐观缓存: URL ${url} 异步更新缓存发生错误 ${ + `乐观缓存: URL ${safeUrl} 异步更新缓存发生错误 ${ e.message ?? e }`, ); }); } - return customCached; + return ( + await finalizeDownloadedBody(customCached, { + ageSecretKey, + preprocess, + url: safeUrl, + }) + ).result; } } @@ -246,7 +311,13 @@ export default async function download( } if (!isNode && tasks.has(id)) { - return tasks.get(id); + return ( + await finalizeDownloadedBody(await tasks.get(id), { + ageSecretKey, + preprocess, + url: safeUrl, + }) + ).result; } const http = HTTP({ @@ -261,18 +332,26 @@ export default async function download( }); let result; + let rawResult; // try to find in app cache const cached = resourceCache.get(id); if (!noCache && !$arguments?.noCache && cached) { $.info( - `使用缓存: ${url}, ${ + `使用缓存: ${safeUrl}, ${ customHeaders ? JSON.stringify(customHeaders) : userAgent }`, ); - result = cached; + rawResult = cached; + result = ( + await finalizeDownloadedBody(cached, { + ageSecretKey, + preprocess, + url: safeUrl, + }) + ).result; if (customCacheKey) { - $.info(`URL ${url}\n写入自定义缓存 ${$arguments?.cacheKey}`); + $.info(`URL ${safeUrl}\n写入自定义缓存 ${$arguments?.cacheKey}`); $.write(cached, customCacheKey); } } else { @@ -286,7 +365,7 @@ export default async function download( customHeaders ? JSON.stringify(customHeaders) : `User-Agent: ${userAgent}` - }\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nInsecure: ${!!insecure}\nPreprocess: ${preprocess}\nURL: ${url}`, + }\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nInsecure: ${!!insecure}\nPreprocess: ${preprocess}\nURL: ${safeUrl}`, ); try { let { body, headers, statusCode } = await runBackendRequestTask( @@ -320,15 +399,11 @@ export default async function download( } if (body.replace(/\s/g, '').length === 0) throw new Error(new Error('远程资源内容为空')); - if (preprocess) { - try { - if (clashPreprocessor.test(body)) { - body = clashPreprocessor.parse(body, true); - } - } catch (e) { - $.error(`Clash Pre-processor error: ${e}`); - } - } + const finalized = await finalizeDownloadedBody(body, { + ageSecretKey, + preprocess, + url: safeUrl, + }); let shouldCache = true; if (cacheThreshold) { const size = body.length / 1024; @@ -341,22 +416,11 @@ export default async function download( shouldCache = false; } } - if (preprocess) { - try { - const proxies = ProxyUtils.parse(body); - if (!Array.isArray(proxies) || proxies.length === 0) { - $.error(`URL ${url} 不包含有效节点, 不缓存`); - shouldCache = false; - } - } catch (e) { - $.error( - `URL ${url} 尝试解析节点失败 ${e.message ?? e}, 不缓存`, - ); - shouldCache = false; - } + if (!finalized.shouldCache) { + $.error(finalized.cacheReason); + shouldCache = false; } if (shouldCache) { - // console.log($arguments); resourceCache.set( id, body, @@ -366,26 +430,33 @@ export default async function download( ); if (customCacheKey) { $.info( - `URL ${url}\n写入自定义缓存 ${$arguments?.cacheKey}`, + `URL ${safeUrl}\n写入自定义缓存 ${$arguments?.cacheKey}`, ); $.write(body, customCacheKey); } } - result = body; + rawResult = body; + result = finalized.result; } catch (e) { if (customCacheKey) { const cached = $.read(customCacheKey); if (cached) { $.info( - `无法下载 URL ${url}: ${ + `无法下载 URL ${safeUrl}: ${ e.message ?? e }\n使用自定义缓存 ${$arguments?.cacheKey}`, ); - return cached; + return ( + await finalizeDownloadedBody(cached, { + ageSecretKey, + preprocess, + url: safeUrl, + }) + ).result; } } - throw new Error(`无法下载 URL ${url}: ${e.message ?? e}`); + throw new Error(`无法下载 URL ${safeUrl}: ${e.message ?? e}`); } } @@ -407,7 +478,7 @@ export default async function download( } if (!isNode) { - tasks.set(id, result); + tasks.set(id, rawResult); } return result; }