diff --git a/backend/package.json b/backend/package.json index 7353dfd9..f65ae9c8 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.36.21", + "version": "2.36.22", "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/constants.js b/backend/src/constants.js index ef422312..6a48b80f 100644 --- a/backend/src/constants.js +++ b/backend/src/constants.js @@ -10,6 +10,7 @@ export const TOKENS_KEY = 'tokens'; export const ARCHIVES_KEY = 'archives'; export const GIST_BACKUP_KEY = 'Auto Generated Sub-Store Backup'; export const GIST_BACKUP_FILE_NAME = 'Sub-Store'; +export const GIST_DOWNLOAD_TOKEN_STRATEGIES = ['ask', 'overwrite', 'keep']; export const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository'; export const RESOURCE_CACHE_KEY = '#sub-store-cached-resource'; export const HEADERS_RESOURCE_CACHE_KEY = '#sub-store-cached-headers-resource'; diff --git a/backend/src/restful/miscs.js b/backend/src/restful/miscs.js index 29257a9c..05cbe202 100644 --- a/backend/src/restful/miscs.js +++ b/backend/src/restful/miscs.js @@ -25,6 +25,10 @@ import { isAgeArmor, } from '@/utils/age'; +const GIST_TOKEN_PATH = 'settings.gistToken'; +const GIST_DOWNLOAD_TOKEN_STRATEGY_PATH = + 'settings.gistDownloadTokenStrategy'; + export default function register($app) { // utils $app.get('/api/utils/env', getEnv); // get runtime environment @@ -211,9 +215,36 @@ async function decryptGistBackupContent(content, settings, encoding) { return decryptArmorIfPresent(content, ageSecretKey); } -async function gistBackupAction(action, keep, encode) { - // read token - const { gistToken, syncPlatform } = $.read(SETTINGS_KEY); +function resolveGistDownloadTokenStrategy( + storedStrategy, + queryStrategy, + keep, +) { + if (queryStrategy !== undefined) { + if (queryStrategy !== 'overwrite' && queryStrategy !== 'keep') { + throw new RequestInvalidError( + 'INVALID_GIST_DOWNLOAD_TOKEN_STRATEGY', + 'Token 处理方式仅支持 overwrite 或 keep', + ); + } + return queryStrategy; + } + + if (keep !== undefined) { + return String(keep).split(',').includes(GIST_TOKEN_PATH) + ? 'keep' + : 'overwrite'; + } + + return storedStrategy === 'keep' ? 'keep' : 'overwrite'; +} + +async function gistBackupAction( + action, + { keep, encode, tokenStrategy: queryTokenStrategy } = {}, +) { + const settings = $.read(SETTINGS_KEY); + const { gistToken, syncPlatform } = settings; if (!gistToken) throw new Error('GitHub Token is required for backup!'); const gist = new Gist({ @@ -223,14 +254,21 @@ async function gistBackupAction(action, keep, encode) { }); let currentContent = readCurrentBackupContent(); let content; - const settings = $.read(SETTINGS_KEY); const updated = settings.syncTime; const encoding = normalizeGistBackupEncoding( encode || settings.gistUpload || 'base64', ); + const tokenStrategy = + action === 'download' + ? resolveGistDownloadTokenStrategy( + settings.gistDownloadTokenStrategy, + queryTokenStrategy, + keep, + ) + : undefined; $.info( - `Gist backup action: ${action}, keep: ${keep}, encode: ${encode}, settings encode: ${settings.gistUpload}, final encoding: ${encoding}`, + `Gist backup action: ${action}, keep: ${keep}, token strategy: ${queryTokenStrategy}, settings token strategy: ${settings.gistDownloadTokenStrategy}, final token strategy: ${tokenStrategy}, encode: ${encode}, settings encode: ${settings.gistUpload}, final encoding: ${encoding}`, ); switch (action) { case 'upload': @@ -288,7 +326,7 @@ async function gistBackupAction(action, keep, encode) { throw err; } break; - case 'download': + case 'download': { $.info(`还原备份中...`); content = await gist.download(GIST_BACKUP_FILE_NAME); content = await decryptGistBackupContent( @@ -316,12 +354,32 @@ async function gistBackupAction(action, keep, encode) { throw new Error('Gist 备份文件校验失败, 无法还原'); } } - if (keep) { - $.info(`保留原有设置 ${keep}`); - keep.split(',').forEach((path) => { - _.set(content, path, _.get(currentContent, path)); - }); + const keepPaths = keep + ? String(keep) + .split(',') + .map((path) => path.trim()) + .filter(Boolean) + : []; + const tokenPathIndex = keepPaths.indexOf(GIST_TOKEN_PATH); + if (tokenStrategy === 'keep' && tokenPathIndex === -1) { + keepPaths.push(GIST_TOKEN_PATH); + } else if ( + tokenStrategy === 'overwrite' && + tokenPathIndex !== -1 + ) { + keepPaths.splice(tokenPathIndex, 1); } + if (!keepPaths.includes(GIST_DOWNLOAD_TOKEN_STRATEGY_PATH)) { + keepPaths.push(GIST_DOWNLOAD_TOKEN_STRATEGY_PATH); + } + $.info(`保留原有设置 ${keepPaths}`); + keepPaths.forEach((path) => { + if (_.has(currentContent, path)) { + _.set(content, path, _.get(currentContent, path)); + } else { + _.unset(content, path); + } + }); // restore settings $.write(JSON.stringify(content, null, ` `), '#sub-store'); if ($.env.isNode) { @@ -333,10 +391,11 @@ async function gistBackupAction(action, keep, encode) { $.info(`migration completed`); $.info(`还原备份完成`); break; + } } } async function gistBackup(req, res) { - const { action, keep, encode } = req.query; + const { action, keep, encode, tokenStrategy } = req.query; // read token const { gistToken } = $.read(SETTINGS_KEY); if (!gistToken) { @@ -349,7 +408,11 @@ async function gistBackup(req, res) { ); } else { try { - await gistBackupAction(action, keep, encode); + await gistBackupAction(action, { + keep, + encode, + tokenStrategy, + }); success(res); } catch (err) { $.error( @@ -357,11 +420,13 @@ async function gistBackup(req, res) { ); failed( res, - new InternalServerError( - 'BACKUP_FAILED', - `Failed to ${action} gist data!`, - `Reason: ${err.message ?? err}`, - ), + err instanceof RequestInvalidError + ? err + : new InternalServerError( + 'BACKUP_FAILED', + `Failed to ${action} gist data!`, + `Reason: ${err.message ?? err}`, + ), ); } } diff --git a/backend/src/restful/settings.js b/backend/src/restful/settings.js index aea7109d..0891d2b4 100644 --- a/backend/src/restful/settings.js +++ b/backend/src/restful/settings.js @@ -1,4 +1,8 @@ -import { SETTINGS_KEY, ARTIFACT_REPOSITORY_KEY } from '@/constants'; +import { + SETTINGS_KEY, + ARTIFACT_REPOSITORY_KEY, + GIST_DOWNLOAD_TOKEN_STRATEGIES, +} from '@/constants'; import { success, failed } from './response'; import { InternalServerError, RequestInvalidError } from '@/restful/errors'; import $ from '@/core/app'; @@ -169,6 +173,17 @@ async function updateSettings(req, res) { if (shouldValidateGistAgeSecretKey(newSettings, req.body)) { await normalizeAndValidateGistAgeSecretKey(newSettings); } + if ( + hasOwn(req.body, 'gistDownloadTokenStrategy') && + !GIST_DOWNLOAD_TOKEN_STRATEGIES.includes( + req.body.gistDownloadTokenStrategy, + ) + ) { + throw new RequestInvalidError( + 'INVALID_GIST_DOWNLOAD_TOKEN_STRATEGY', + 'Token 处理方式仅支持 ask、overwrite 或 keep', + ); + } $.write(newSettings, SETTINGS_KEY); clearLogSettingsCache(); if (shouldRefreshArtifactStoreForSettingsPatch(req.body)) { diff --git a/backend/src/test/restful/gist-backup-age.spec.js b/backend/src/test/restful/gist-backup-age.spec.js index 920bcaed..268f38bb 100644 --- a/backend/src/test/restful/gist-backup-age.spec.js +++ b/backend/src/test/restful/gist-backup-age.spec.js @@ -74,7 +74,7 @@ describe('Gist backup age encryption', function () { return {}; }; - await gistBackupAction('upload', undefined, 'age'); + await gistBackupAction('upload', { encode: 'age' }); expect(uploadedContent).to.contain(AGE_ARMOR_HEADER); const decrypted = await decryptArmorIfPresent( @@ -108,7 +108,7 @@ describe('Gist backup age encryption', function () { return {}; }; - await gistBackupAction('upload', undefined, 'base64'); + await gistBackupAction('upload', { encode: 'base64' }); expect(uploadedContent).not.to.contain(AGE_ARMOR_HEADER); const backup = JSON.parse(Base64.decode(uploadedContent)); @@ -143,7 +143,7 @@ describe('Gist backup age encryption', function () { return {}; }; - await gistBackupAction('upload', undefined, 'age'); + await gistBackupAction('upload', { encode: 'age' }); expect(uploadedContent).to.contain(AGE_ARMOR_HEADER); }); @@ -186,6 +186,80 @@ describe('Gist backup age encryption', function () { expect($.cache.subs).to.deep.equal(restoredBackup.subs); }); + it('uses the stored token strategy when downloading', async function () { + installState({ + settings: { + gistToken: 'current-token', + gistDownloadTokenStrategy: 'keep', + }, + subs: [], + }); + + Gist.prototype.download = async () => + Base64.encode( + JSON.stringify({ + settings: { + gistToken: 'backup-token', + gistDownloadTokenStrategy: 'overwrite', + }, + subs: [], + }), + ); + + await gistBackupAction('download'); + + expect($.cache.settings.gistToken).to.equal('current-token'); + expect($.cache.settings.gistDownloadTokenStrategy).to.equal('keep'); + }); + + it('lets the query strategy override the stored token strategy', async function () { + installState({ + settings: { + gistToken: 'current-token', + gistDownloadTokenStrategy: 'keep', + }, + subs: [], + }); + + Gist.prototype.download = async () => + Base64.encode( + JSON.stringify({ + settings: { + gistToken: 'backup-token', + gistDownloadTokenStrategy: 'overwrite', + }, + subs: [], + }), + ); + + await gistBackupAction('download', { + tokenStrategy: 'overwrite', + }); + + expect($.cache.settings.gistToken).to.equal('backup-token'); + expect($.cache.settings.gistDownloadTokenStrategy).to.equal('keep'); + }); + + it('rejects an invalid query token strategy', async function () { + installState({ + settings: { + gistToken: 'current-token', + }, + subs: [], + }); + + let error; + try { + await gistBackupAction('download', { + tokenStrategy: 'invalid', + }); + } catch (caught) { + error = caught; + } + + expect(error?.message).to.contain('Token 处理方式'); + }); + it('rejects age upload mode without an age secret key', async function () { installState({ settings: { @@ -198,7 +272,7 @@ describe('Gist backup age encryption', function () { Gist.prototype.download = async () => 'old backup'; try { - await gistBackupAction('upload', undefined, 'age'); + await gistBackupAction('upload', { encode: 'age' }); throw new Error('Expected age upload to fail'); } catch (error) { expect(error.message).to.contain('age 解密私钥'); diff --git a/backend/src/test/restful/settings.spec.js b/backend/src/test/restful/settings.spec.js index fa0b5962..8137382b 100644 --- a/backend/src/test/restful/settings.spec.js +++ b/backend/src/test/restful/settings.spec.js @@ -116,7 +116,7 @@ describe('settings routes', function () { }); }); - describe('age key settings', function () { + describe('validated settings', function () { const originalRead = $.read.bind($); const originalWrite = $.write.bind($); @@ -215,6 +215,16 @@ describe('settings routes', function () { 'age-secret-key 仅支持', ); }); + + it('rejects an invalid Gist download token strategy', async function () { + const { res } = await patchSettings( + {}, + { gistDownloadTokenStrategy: 'invalid' }, + ); + + expect(res.body.status).to.equal('failed'); + expect(res.body.error.message).to.contain('Token 处理方式'); + }); }); describe('appearance settings', function () {