diff --git a/backend/package.json b/backend/package.json index 207dd1be..489ef671 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.22.20", + "version": "2.22.21", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "scripts": { diff --git a/backend/src/products/cron-sync-artifacts-eligibility.js b/backend/src/products/cron-sync-artifacts-eligibility.js new file mode 100644 index 00000000..ad47ef05 --- /dev/null +++ b/backend/src/products/cron-sync-artifacts-eligibility.js @@ -0,0 +1,3 @@ +export function hasCronArtifactSyncCredentials(settings = {}) { + return Boolean(settings?.gistToken); +} diff --git a/backend/src/products/cron-sync-artifacts.js b/backend/src/products/cron-sync-artifacts.js index 88417bda..61c0953d 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 { produceArtifact } from '@/restful/sync'; import { syncToGist } from '@/restful/artifacts'; import { findByName } from '@/utils/database'; +import { hasCronArtifactSyncCredentials } from '@/products/cron-sync-artifacts-eligibility'; !(async function () { let arg; @@ -36,7 +37,7 @@ import { findByName } from '@/utils/database'; } else { const settings = $.read(SETTINGS_KEY); // if GitHub token is not configured - if (!settings.githubUser || !settings.gistToken) return; + if (!hasCronArtifactSyncCredentials(settings)) return; const artifacts = $.read(ARTIFACTS_KEY); if (!artifacts || artifacts.length === 0) return; diff --git a/backend/src/restful/miscs.js b/backend/src/restful/miscs.js index 2f6aaef3..89282d84 100644 --- a/backend/src/restful/miscs.js +++ b/backend/src/restful/miscs.js @@ -133,8 +133,8 @@ function getEnv(req, res) { } async function refresh(_, res) { - // 1. get GitHub avatar and artifact store - await updateAvatar(); + // 1. get artifact store + // await updateAvatar(); await updateArtifactStore(); // 2. clear resource cache diff --git a/backend/src/restful/settings.js b/backend/src/restful/settings.js index 3db58d57..a7ef0836 100644 --- a/backend/src/restful/settings.js +++ b/backend/src/restful/settings.js @@ -2,9 +2,31 @@ import { SETTINGS_KEY, ARTIFACT_REPOSITORY_KEY } from '@/constants'; import { success, failed } from './response'; import { InternalServerError } from '@/restful/errors'; import $ from '@/core/app'; -import Gist from '@/utils/gist'; +import Gist, { getGithubGistBaseURL } from '@/utils/gist'; import { clearLogSettingsCache } from '@/utils/debug-logs'; +const ARTIFACT_STORE_SETTING_KEYS = [ + 'gistToken', + 'githubProxy', + 'githubApiUrl', + 'defaultProxy', +]; + +export function shouldRefreshArtifactStoreForSettingsPatch(body = {}) { + return ARTIFACT_STORE_SETTING_KEYS.some((key) => + Object.prototype.hasOwnProperty.call(body, key), + ); +} + +export function getGithubAvatarApiUrl({ username, githubApiUrl, githubProxy }) { + const githubApiBaseURL = getGithubGistBaseURL({ + githubApiUrl, + githubProxy, + }); + + return `${githubApiBaseURL}/users/${encodeURIComponent(username)}`; +} + export default function register($app) { const settings = $.read(SETTINGS_KEY); if (!settings) $.write({}, SETTINGS_KEY); @@ -19,7 +41,7 @@ async function getSettings(req, res) { $.write(settings, SETTINGS_KEY); } - if (!settings.avatarUrl) await updateAvatar(); + // await updateAvatar(); if (!settings.artifactStore) await updateArtifactStore(); success(res, settings); @@ -70,13 +92,8 @@ async function updateSettings(req, res) { } $.write(newSettings, SETTINGS_KEY); clearLogSettingsCache(); - if ( - req.body.githubUser || - req.body.gistToken || - req.body.githubProxy || - req.body.defaultProxy - ) { - await updateAvatar(); + if (shouldRefreshArtifactStoreForSettingsPatch(req.body)) { + // await updateAvatar(); await updateArtifactStore(); } success(res, newSettings); @@ -95,7 +112,12 @@ async function updateSettings(req, res) { export async function updateAvatar() { const settings = $.read(SETTINGS_KEY); - const { githubUser: username, syncPlatform, githubProxy } = settings; + const { + githubUser: username, + syncPlatform, + githubProxy, + githubApiUrl, + } = settings; if (username) { if (syncPlatform === 'gitlab') { try { @@ -126,11 +148,11 @@ export async function updateAvatar() { try { const data = await $.http .get({ - url: `${ - githubProxy ? `${githubProxy}/` : '' - }https://api.github.com/users/${encodeURIComponent( + url: getGithubAvatarApiUrl({ username, - )}`, + githubApiUrl, + githubProxy, + }), headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36', diff --git a/backend/src/test/products/cron-sync-artifacts.spec.js b/backend/src/test/products/cron-sync-artifacts.spec.js new file mode 100644 index 00000000..70532ecf --- /dev/null +++ b/backend/src/test/products/cron-sync-artifacts.spec.js @@ -0,0 +1,23 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { hasCronArtifactSyncCredentials } from '@/products/cron-sync-artifacts-eligibility'; + +describe('cron artifact sync credentials', function () { + it('allows token-only Gist-compatible sync settings', function () { + expect( + hasCronArtifactSyncCredentials({ + gistToken: 'token', + githubUser: '', + }), + ).to.equal(true); + }); + + it('skips sync when the token is missing', function () { + expect( + hasCronArtifactSyncCredentials({ + githubUser: 'xream', + }), + ).to.equal(false); + }); +}); diff --git a/backend/src/test/restful/settings.spec.js b/backend/src/test/restful/settings.spec.js new file mode 100644 index 00000000..d5900937 --- /dev/null +++ b/backend/src/test/restful/settings.spec.js @@ -0,0 +1,74 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { + getGithubAvatarApiUrl, + shouldRefreshArtifactStoreForSettingsPatch, +} from '@/restful/settings'; + +describe('settings routes', function () { + describe('artifact store refresh detection', function () { + it('refreshes when GitHub API URL changes', function () { + expect( + shouldRefreshArtifactStoreForSettingsPatch({ + githubApiUrl: 'https://litegist.example.com/api', + }), + ).to.equal(true); + }); + + it('refreshes when a Gist-affecting setting is cleared', function () { + expect( + shouldRefreshArtifactStoreForSettingsPatch({ + githubProxy: '', + }), + ).to.equal(true); + }); + + it('does not refresh for unrelated settings', function () { + expect( + shouldRefreshArtifactStoreForSettingsPatch({ + logsMaxCount: 100, + }), + ).to.equal(false); + }); + + it('does not refresh when only GitHub username changes', function () { + expect( + shouldRefreshArtifactStoreForSettingsPatch({ + githubUser: 'xream', + }), + ).to.equal(false); + }); + }); + + describe('GitHub avatar API URL', function () { + it('uses the default GitHub users API when no custom API URL is set', function () { + expect( + getGithubAvatarApiUrl({ + username: 'xream', + }), + ).to.equal('https://api.github.com/users/xream'); + }); + + it('applies GitHub proxy only to the default GitHub users API', function () { + expect( + getGithubAvatarApiUrl({ + username: 'xream', + githubProxy: 'https://proxy.example.com/', + }), + ).to.equal( + 'https://proxy.example.com/https://api.github.com/users/xream', + ); + }); + + it('does not apply GitHub proxy to a custom GitHub users API', function () { + expect( + getGithubAvatarApiUrl({ + username: 'xream', + githubApiUrl: 'https://litegist.example.com/api/', + githubProxy: 'https://proxy.example.com/', + }), + ).to.equal('https://litegist.example.com/api/users/xream'); + }); + }); +}); diff --git a/backend/src/test/utils/gist.spec.js b/backend/src/test/utils/gist.spec.js new file mode 100644 index 00000000..7ca38ff4 --- /dev/null +++ b/backend/src/test/utils/gist.spec.js @@ -0,0 +1,35 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { getGithubGistBaseURL } from '@/utils/gist'; + +describe('Gist GitHub API URL', function () { + it('uses the default GitHub API URL when unset', function () { + expect(getGithubGistBaseURL()).to.equal('https://api.github.com'); + }); + + it('uses the default GitHub API URL when blank', function () { + expect( + getGithubGistBaseURL({ + githubApiUrl: ' ', + }), + ).to.equal('https://api.github.com'); + }); + + it('applies GitHub proxy only to the default GitHub API URL', function () { + expect( + getGithubGistBaseURL({ + githubProxy: 'https://proxy.example.com/', + }), + ).to.equal('https://proxy.example.com/https://api.github.com'); + }); + + it('does not apply GitHub proxy to a custom GitHub API URL', function () { + expect( + getGithubGistBaseURL({ + githubApiUrl: 'https://litegist.example.com/api/', + githubProxy: 'https://proxy.example.com/', + }), + ).to.equal('https://litegist.example.com/api'); + }); +}); diff --git a/backend/src/utils/gist.js b/backend/src/utils/gist.js index 0864673c..827208b2 100644 --- a/backend/src/utils/gist.js +++ b/backend/src/utils/gist.js @@ -3,6 +3,31 @@ import { getPolicyDescriptor } from '@/utils'; import $ from '@/core/app'; import { SETTINGS_KEY } from '@/constants'; +const DEFAULT_GITHUB_API_URL = 'https://api.github.com'; + +function normalizeApiUrl(url, fallback = DEFAULT_GITHUB_API_URL) { + const normalizedUrl = String(url ?? '').trim() || fallback; + + return normalizedUrl.replace(/\/+$/, ''); +} + +export function getGithubGistBaseURL({ githubApiUrl, githubProxy } = {}) { + const normalizedGithubApiUrl = normalizeApiUrl(githubApiUrl); + const isCustomGithubApiUrl = + normalizedGithubApiUrl !== DEFAULT_GITHUB_API_URL; + const normalizedGithubProxy = String(githubProxy || '') + .trim() + .replace(/\/+$/, ''); + + if (isCustomGithubApiUrl) { + return normalizedGithubApiUrl; + } + + return `${ + normalizedGithubProxy ? `${normalizedGithubProxy}/` : '' + }${DEFAULT_GITHUB_API_URL}`; +} + /** * Gist backup */ @@ -13,7 +38,12 @@ export default class Gist { defaultProxy, defaultTimeout: timeout, githubProxy, + githubApiUrl, } = $.read(SETTINGS_KEY); + const githubGistBaseURL = getGithubGistBaseURL({ + githubApiUrl, + githubProxy, + }); let proxy = defaultProxy; if ($.env.isNode) { proxy = @@ -50,9 +80,19 @@ export default class Gist { events: { onResponse: (resp) => { if (/^[45]/.test(String(resp.statusCode))) { - const body = JSON.parse(resp.body); + let body; + try { + body = JSON.parse(resp.body); + } catch (e) { + // + } return Promise.reject( - `ERROR: ${body.message?.error ?? body.message}`, + `ERROR: ${ + body?.message?.error ?? + body?.error ?? + body?.message ?? + resp.body + }`, ); } else { return resp; @@ -67,9 +107,7 @@ export default class Gist { 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36', }; this.http = HTTP({ - baseURL: `${ - githubProxy ? `${githubProxy}/` : '' - }https://api.github.com`, + baseURL: githubGistBaseURL, headers: { ...this.headers, ...(isStash && proxy @@ -92,8 +130,19 @@ export default class Gist { events: { onResponse: (resp) => { if (/^[45]/.test(String(resp.statusCode))) { + let body; + try { + body = JSON.parse(resp.body); + } catch (e) { + // + } return Promise.reject( - `ERROR: ${JSON.parse(resp.body).message}`, + `ERROR: ${ + body?.message?.error ?? + body?.error ?? + body?.message ?? + resp.body + }`, ); } else { return resp;