From 182adfd8ef70df707352510889d8b7bf94a9d3ec Mon Sep 17 00:00:00 2001 From: xream Date: Wed, 3 Jun 2026 08:30:38 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=90=8E=E7=AB=AF=20?= =?UTF-8?q?CORS=20allowlist=20=E9=85=8D=E7=BD=AE=E5=B9=B6=E6=8E=A5?= =?UTF-8?q?=E5=85=A5=20App=20=E6=A8=A1=E5=9D=97=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Node 默认允许 `*`(兼容旧行为),可通过环境变量 `SUB_STORE_CORS_ALLOWED_ORIGINS` 配置 - 代理 App 模块默认 `https://sub-store.vercel.app`, 可通过模块参数 `cors` 配置 --- README.md | 8 + backend/package.json | 2 +- .../test/config/cors-module-config.spec.js | 73 +++++++ backend/src/test/utils/cors.spec.js | 169 +++++++++++++++++ backend/src/test/vendor/express-cors.spec.js | 179 ++++++++++++++++++ backend/src/utils/cors.js | 156 +++++++++++++++ backend/src/vendor/express.js | 79 ++++++-- config/Egern.yaml | 7 +- config/Loon.plugin | 5 +- config/README.md | 12 ++ config/Surge-Beta.sgmodule | 8 +- config/Surge.sgmodule | 8 +- 12 files changed, 677 insertions(+), 29 deletions(-) create mode 100644 backend/src/test/config/cors-module-config.spec.js create mode 100644 backend/src/test/utils/cors.spec.js create mode 100644 backend/src/test/vendor/express-cors.spec.js create mode 100644 backend/src/utils/cors.js diff --git a/README.md b/README.md index 386d3660..c19d329a 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,14 @@ Example: sub.store = 127.0.0.1 ``` +### CORS Allowlist + +Sub-Store also supports a configurable browser CORS allowlist for the backend API. This does not change the module rewrite domain, but it limits which browser origins can read API responses through CORS. + +- Node/server deployments use `SUB_STORE_CORS_ALLOWED_ORIGINS`; the default is `*` for compatibility. +- Proxy App modules use the `cors` module argument; the default is `https://sub-store.vercel.app`. +- Multiple origins can be separated by commas. Origins are matched exactly by scheme, host, and port. Set the value to `*` only when you accept the risk of any website reading the local backend through browser CORS. + ## Core functionalities: 1. Conversion among various formats. diff --git a/backend/package.json b/backend/package.json index 2c370cdf..fbc8baba 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "sub-store", - "version": "2.23.35", + "version": "2.24.0", "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/test/config/cors-module-config.spec.js b/backend/src/test/config/cors-module-config.spec.js new file mode 100644 index 00000000..7c303c73 --- /dev/null +++ b/backend/src/test/config/cors-module-config.spec.js @@ -0,0 +1,73 @@ +import fs from 'fs'; +import path from 'path'; + +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { load } from '@/utils/yaml'; + +const DEFAULT_ORIGIN = 'https://sub-store.vercel.app'; + +describe('module CORS allowlist config', function () { + it('adds the default CORS argument to Surge modules', function () { + for (const filename of ['Surge.sgmodule', 'Surge-Beta.sgmodule']) { + const content = readConfig(filename); + + expect(content).to.include(`cors:"${DEFAULT_ORIGIN}"`); + expect(content).to.include('argument="cors={{{cors}}}"'); + expect(content.match(/argument="cors=\{\{\{cors\}\}\}"/g)).to.have + .length(2); + } + }); + + it('adds the default CORS argument to the Egern module', function () { + const config = load(readConfig('Egern.yaml')); + const httpRequests = config.scriptings + .map((item) => item.http_request) + .filter(Boolean); + + expect(config.compat_arguments.cors).to.equal(DEFAULT_ORIGIN); + expect(config.compat_arguments_desc).to.include('1️⃣1️⃣ cors'); + expect(httpRequests).to.have.length(2); + for (const script of httpRequests) { + expect(script.arguments).to.deep.equal({ + '_compat.$argument': 'cors={{{cors}}}', + }); + } + }); + + it('adds the default CORS argument to the Loon module', function () { + const content = readConfig('Loon.plugin'); + + expect(content).to.include( + `cors=input, "${DEFAULT_ORIGIN}", tag=CORS允许来源`, + ); + expect(content.match(/argument="cors=\{cors\}"/g)).to.have.length(2); + }); + + it('does not set legacy non-parameterized modules to wildcard CORS', function () { + for (const filename of [ + 'QX.snippet', + 'Stash.stoverride', + 'Surge-Noability.sgmodule', + 'Surge-ability.sgmodule', + ]) { + const content = readConfig(filename); + + expect(content).to.not.match(/cors\s*[:=]\s*"?\*/i); + } + }); +}); + +function readConfig(filename) { + return fs.readFileSync(path.join(findRepoRoot(), 'config', filename), 'utf8'); +} + +function findRepoRoot() { + for (const dir of [process.cwd(), path.resolve(process.cwd(), '..')]) { + if (fs.existsSync(path.join(dir, 'config', 'Surge.sgmodule'))) { + return dir; + } + } + throw new Error('Unable to locate repository root'); +} diff --git a/backend/src/test/utils/cors.spec.js b/backend/src/test/utils/cors.spec.js new file mode 100644 index 00000000..e2c7852b --- /dev/null +++ b/backend/src/test/utils/cors.spec.js @@ -0,0 +1,169 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { + getCorsHeaders, + isOriginAllowed, + NON_NODE_CORS_DEFAULT, + NODE_CORS_ALLOWED_ORIGINS_ENV, + resolveCorsPolicy, +} from '@/utils/cors'; + +describe('CORS allowlist policy', function () { + it('defaults Node environments to wildcard origins', function () { + const policy = resolveCorsPolicy({ isNode: true }); + + expect(policy).to.deep.include({ + wildcard: true, + value: '*', + source: 'default:node', + }); + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal(true); + expect(getCorsHeaders(policy, 'https://evil.example')).to.deep.equal({ + 'Access-Control-Allow-Origin': '*', + }); + }); + + it('reads Node allowlist values from the environment setting', function () { + const policy = resolveCorsPolicy({ + isNode: true, + envValue: + 'https://sub-store.vercel.app, http://127.0.0.1:8888', + }); + + expect(policy).to.deep.include({ + wildcard: false, + source: `env:${NODE_CORS_ALLOWED_ORIGINS_ENV}`, + value: 'https://sub-store.vercel.app,http://127.0.0.1:8888', + }); + expect( + isOriginAllowed(policy, 'https://sub-store.vercel.app'), + ).to.equal(true); + expect(isOriginAllowed(policy, 'http://127.0.0.1:8888')).to.equal( + true, + ); + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal( + false, + ); + }); + + it('defaults non-Node environments to the official frontend origin', function () { + const policy = resolveCorsPolicy({ isNode: false }); + + expect(policy).to.deep.include({ + wildcard: false, + source: 'default:non-node', + value: NON_NODE_CORS_DEFAULT, + }); + expect(isOriginAllowed(policy, NON_NODE_CORS_DEFAULT)).to.equal(true); + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal( + false, + ); + }); + + it('reads non-Node allowlist values from script arguments', function () { + const policy = resolveCorsPolicy({ + isNode: false, + argument: + 'sync_success_notify=true&cors=https%3A%2F%2Fsub-store.vercel.app%2Chttp%3A%2F%2F127.0.0.1%3A8888', + }); + + expect(policy).to.deep.include({ + wildcard: false, + source: 'argument:cors', + value: 'https://sub-store.vercel.app,http://127.0.0.1:8888', + }); + }); + + it('tolerates quoted script argument strings', function () { + const policy = resolveCorsPolicy({ + isNode: false, + argument: + '"cors=https://sub-store.vercel.app,http://127.0.0.1:8888"', + }); + + expect(policy).to.deep.include({ + wildcard: false, + source: 'argument:cors', + value: 'https://sub-store.vercel.app,http://127.0.0.1:8888', + }); + }); + + it('supports explicit wildcard from non-Node arguments', function () { + const policy = resolveCorsPolicy({ + isNode: false, + argument: 'cors=*', + }); + + expect(policy).to.deep.include({ + wildcard: true, + source: 'argument:cors', + value: '*', + }); + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal(true); + }); + + it('requires exact browser origins', function () { + const policy = resolveCorsPolicy({ + isNode: false, + argument: { + cors: 'https://sub-store.vercel.app,http://127.0.0.1:8888', + }, + }); + + expect(isOriginAllowed(policy, 'https://sub-store.vercel.app')).to.equal( + true, + ); + expect( + isOriginAllowed(policy, 'https://evil.example.sub-store.vercel.app'), + ).to.equal(false); + expect(isOriginAllowed(policy, 'http://sub-store.vercel.app')).to.equal( + false, + ); + expect(isOriginAllowed(policy, 'http://127.0.0.1')).to.equal(false); + }); + + it('does not treat empty configured values as wildcard', function () { + const nodePolicy = resolveCorsPolicy({ + isNode: true, + envValue: ' ', + }); + const nonNodePolicy = resolveCorsPolicy({ + isNode: false, + argument: 'cors=,,,', + }); + + expect(nodePolicy).to.deep.include({ + wildcard: true, + source: 'default:node', + value: '*', + }); + expect(nonNodePolicy).to.deep.include({ + wildcard: false, + source: 'default:non-node', + value: NON_NODE_CORS_DEFAULT, + }); + expect(isOriginAllowed(nonNodePolicy, NON_NODE_CORS_DEFAULT)).to.equal( + true, + ); + }); + + it('returns concrete CORS headers for allowed non-wildcard origins', function () { + const policy = resolveCorsPolicy({ + isNode: false, + argument: { + cors: 'https://sub-store.vercel.app', + }, + }); + + expect( + getCorsHeaders(policy, 'https://sub-store.vercel.app'), + ).to.deep.equal({ + 'Access-Control-Allow-Origin': 'https://sub-store.vercel.app', + Vary: 'Origin', + }); + expect(getCorsHeaders(policy, 'https://evil.example')).to.deep.equal( + {}, + ); + }); +}); diff --git a/backend/src/test/vendor/express-cors.spec.js b/backend/src/test/vendor/express-cors.spec.js new file mode 100644 index 00000000..af1f4cc3 --- /dev/null +++ b/backend/src/test/vendor/express-cors.spec.js @@ -0,0 +1,179 @@ +import { expect } from 'chai'; +import { afterEach, describe, it } from 'mocha'; + +import express from '@/vendor/express'; + +const ENV_KEY = 'SUB_STORE_CORS_ALLOWED_ORIGINS'; +const HOST = '127.0.0.1'; + +describe('express CORS allowlist adapter', function () { + let originalCorsEnv; + + afterEach(function () { + if (originalCorsEnv == null) { + delete process.env[ENV_KEY]; + } else { + process.env[ENV_KEY] = originalCorsEnv; + } + }); + + it('keeps Node default wildcard behavior', async function () { + await withServer(undefined, async ({ baseUrl, getRouteCalls }) => { + const res = await fetch(`${baseUrl}/probe`, { + headers: { + Origin: 'https://evil.example', + }, + }); + + expect(res.status).to.equal(200); + expect(getRouteCalls()).to.equal(1); + expect(res.headers.get('access-control-allow-origin')).to.equal( + '*', + ); + }); + }); + + it('rejects disallowed actual requests before route handlers run', async function () { + await withServer( + 'https://sub-store.vercel.app', + async ({ baseUrl, getRouteCalls }) => { + const res = await fetch(`${baseUrl}/probe`, { + headers: { + Origin: 'https://evil.example', + }, + }); + + expect(res.status).to.equal(403); + expect(getRouteCalls()).to.equal(0); + expect(res.headers.get('access-control-allow-origin')).to.equal( + null, + ); + }, + ); + }); + + it('rejects disallowed preflight requests', async function () { + await withServer( + 'https://sub-store.vercel.app', + async ({ baseUrl, getRouteCalls }) => { + const res = await fetch(`${baseUrl}/probe`, { + method: 'OPTIONS', + headers: { + Origin: 'https://evil.example', + 'Access-Control-Request-Method': 'GET', + }, + }); + + expect(res.status).to.equal(403); + expect(getRouteCalls()).to.equal(0); + }, + ); + }); + + it('allows configured exact origins and returns readable CORS headers', async function () { + await withServer( + 'https://sub-store.vercel.app,http://127.0.0.1:8888', + async ({ baseUrl, getRouteCalls }) => { + const official = await fetch(`${baseUrl}/probe`, { + headers: { + Origin: 'https://sub-store.vercel.app', + }, + }); + const local = await fetch(`${baseUrl}/probe`, { + headers: { + Origin: 'http://127.0.0.1:8888', + }, + }); + + expect(official.status).to.equal(200); + expect(local.status).to.equal(200); + expect(getRouteCalls()).to.equal(2); + expect( + official.headers.get('access-control-allow-origin'), + ).to.equal('https://sub-store.vercel.app'); + expect(local.headers.get('access-control-allow-origin')).to.equal( + 'http://127.0.0.1:8888', + ); + expect(official.headers.get('vary')).to.include('Origin'); + }, + ); + }); + + it('continues no-origin requests through the existing route flow', async function () { + await withServer( + 'https://sub-store.vercel.app', + async ({ baseUrl, getRouteCalls }) => { + const res = await fetch(`${baseUrl}/probe`); + + expect(res.status).to.equal(200); + expect(getRouteCalls()).to.equal(1); + expect(res.headers.get('access-control-allow-origin')).to.equal( + null, + ); + }, + ); + }); + + it('logs the resolved allowlist value and source', async function () { + await withServer( + 'https://sub-store.vercel.app,http://127.0.0.1:8888', + async ({ logs }) => { + expect(logs).to.include( + '[CORS] allowed origins: https://sub-store.vercel.app,http://127.0.0.1:8888 (env:SUB_STORE_CORS_ALLOWED_ORIGINS)', + ); + }, + ); + }); + + async function withServer(corsEnv, run) { + originalCorsEnv = process.env[ENV_KEY]; + if (corsEnv == null) { + delete process.env[ENV_KEY]; + } else { + process.env[ENV_KEY] = corsEnv; + } + + const logs = []; + let routeCalls = 0; + const app = express({ + substore: { + info(message) { + logs.push(message); + }, + }, + }); + + app.get('/probe', (req, res) => { + routeCalls += 1; + res.json({ status: 'success' }); + }); + + const server = await listen(app); + const { port } = server.address(); + + try { + await run({ + baseUrl: `http://${HOST}:${port}`, + logs, + getRouteCalls: () => routeCalls, + }); + } finally { + await close(server); + } + } + + function listen(app) { + return new Promise((resolve) => { + const server = app.listen(0, HOST, () => resolve(server)); + }); + } + + function close(server) { + return new Promise((resolve, reject) => { + server.close((error) => { + if (error) reject(error); + else resolve(); + }); + }); + } +}); diff --git a/backend/src/utils/cors.js b/backend/src/utils/cors.js new file mode 100644 index 00000000..c7a5106e --- /dev/null +++ b/backend/src/utils/cors.js @@ -0,0 +1,156 @@ +/* eslint-disable no-undef */ + +export const NODE_CORS_ALLOWED_ORIGINS_ENV = + 'SUB_STORE_CORS_ALLOWED_ORIGINS'; +export const NODE_CORS_DEFAULT = '*'; +export const NON_NODE_CORS_DEFAULT = 'https://sub-store.vercel.app'; +export const CORS_ARGUMENT_KEY = 'cors'; + +const WILDCARD_ORIGIN = '*'; + +export function parseArgument(rawArgument) { + if (rawArgument == null || rawArgument === '') return {}; + if (typeof rawArgument === 'object') return rawArgument; + const argument = stripWrappingQuotes(`${rawArgument}`.trim()); + + return Object.fromEntries( + argument + .split('&') + .filter(Boolean) + .map((item) => { + const [key, ...value] = item.split('='); + return [ + stripWrappingQuotes(safeDecode(key).trim()), + stripWrappingQuotes(safeDecode(value.join('=').trim())), + ]; + }), + ); +} + +export function resolveCorsPolicy({ + isNode, + envValue, + argument, +} = {}) { + const defaultValue = isNode ? NODE_CORS_DEFAULT : NON_NODE_CORS_DEFAULT; + const configuredValue = isNode + ? envValue + : parseArgument(argument)?.[CORS_ARGUMENT_KEY]; + const hasConfiguredValue = + configuredValue != null && `${configuredValue}`.trim() !== ''; + const rawValue = hasConfiguredValue ? configuredValue : defaultValue; + const source = hasConfiguredValue + ? isNode + ? `env:${NODE_CORS_ALLOWED_ORIGINS_ENV}` + : `argument:${CORS_ARGUMENT_KEY}` + : isNode + ? 'default:node' + : 'default:non-node'; + + const policy = parseAllowedOrigins(rawValue, source); + if (!policy.wildcard && policy.origins.length === 0) { + return parseAllowedOrigins( + defaultValue, + isNode ? 'default:node' : 'default:non-node', + ); + } + return policy; +} + +export function resolveRuntimeCorsPolicy({ isNode } = {}) { + return resolveCorsPolicy({ + isNode, + envValue: isNode ? readNodeCorsEnv() : undefined, + argument: isNode ? undefined : readScriptArgument(), + }); +} + +export function isOriginAllowed(policy, origin) { + if (!origin) return true; + if (policy?.wildcard) return true; + + const normalizedOrigin = normalizeOrigin(origin); + return policy?.origins?.includes(normalizedOrigin); +} + +export function getCorsHeaders(policy, origin) { + if (policy?.wildcard) { + return { + 'Access-Control-Allow-Origin': WILDCARD_ORIGIN, + }; + } + if (!origin || !isOriginAllowed(policy, origin)) return {}; + + return { + 'Access-Control-Allow-Origin': normalizeOrigin(origin), + Vary: 'Origin', + }; +} + +export function describeCorsPolicy(policy) { + return `${policy?.wildcard ? WILDCARD_ORIGIN : policy?.origins?.join(',') || ''} (${policy?.source})`; +} + +function parseAllowedOrigins(rawValue, source) { + const items = `${rawValue}` + .split(/[,,\s]+/) + .map((item) => item.trim()) + .filter(Boolean); + + if (items.includes(WILDCARD_ORIGIN)) { + return { + wildcard: true, + origins: [], + source, + value: WILDCARD_ORIGIN, + }; + } + + const origins = [...new Set(items.map(normalizeOrigin))]; + return { + wildcard: false, + origins, + source, + value: origins.join(','), + }; +} + +function normalizeOrigin(origin) { + const value = stripWrappingQuotes(`${origin}`.trim()); + if (value === WILDCARD_ORIGIN) return WILDCARD_ORIGIN; + + try { + return new URL(value).origin; + } catch { + return value; + } +} + +function readNodeCorsEnv() { + try { + return eval(`process.env.${NODE_CORS_ALLOWED_ORIGINS_ENV}`); + } catch { + return undefined; + } +} + +function readScriptArgument() { + try { + if (typeof $argument !== 'undefined') return $argument; + } catch { + return undefined; + } + return undefined; +} + +function safeDecode(value) { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +function stripWrappingQuotes(value) { + return value.replace(/^["']|["']$/g, ''); +} diff --git a/backend/src/vendor/express.js b/backend/src/vendor/express.js index 54cd8153..470eab30 100644 --- a/backend/src/vendor/express.js +++ b/backend/src/vendor/express.js @@ -1,11 +1,19 @@ /* eslint-disable no-undef */ import { ENV } from './open-api'; +import { + describeCorsPolicy, + getCorsHeaders, + isOriginAllowed, + resolveRuntimeCorsPolicy, +} from '@/utils/cors'; export default function express({ substore: $, port, host }) { const { isNode } = ENV(); + const corsPolicy = resolveRuntimeCorsPolicy({ isNode }); + $.info(`[CORS] allowed origins: ${describeCorsPolicy(corsPolicy)}`); + const DEFAULT_HEADERS = { 'Content-Type': 'text/plain;charset=UTF-8', - 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PATCH,PUT,DELETE', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept', @@ -21,16 +29,6 @@ export default function express({ substore: $, port, host }) { const app = express_(); const limit = eval('process.env.SUB_STORE_BODY_JSON_LIMIT') || '1mb'; $.info(`[BACKEND] body JSON limit: ${limit}`); - app.use( - bodyParser.json({ - verify: rawBodySaver, - limit, - }), - ); - app.use( - bodyParser.urlencoded({ verify: rawBodySaver, extended: true }), - ); - app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' })); app.use((req, res, next) => { const originalSetHeader = res.setHeader.bind(res); @@ -67,10 +65,32 @@ export default function express({ substore: $, port, host }) { next(); }); - app.use((_, res, next) => { - res.set(DEFAULT_HEADERS); + app.use((req, res, next) => { + const result = applyCors(req.headers?.origin, req.method); + res.set({ + ...DEFAULT_HEADERS, + ...result.headers, + }); + if (!result.allowed) { + res.status(403).end('CORS origin not allowed'); + return; + } + if (result.preflight) { + res.status(200).end(); + return; + } next(); }); + app.use( + bodyParser.json({ + verify: rawBodySaver, + limit, + }), + ); + app.use( + bodyParser.urlencoded({ verify: rawBodySaver, extended: true }), + ); + app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' })); // adapter app.start = () => { @@ -110,6 +130,17 @@ export default function express({ substore: $, port, host }) { method = method.toUpperCase(); const { path, query } = extractURL(url); + const cors = applyCors(headers.origin, method); + if (!cors.allowed) { + const res = Response(); + res.status(403).send('CORS origin not allowed'); + return; + } + if (cors.preflight) { + const res = Response(cors.headers); + res.status(200).end(); + return; + } // pattern match let handler = null; @@ -140,7 +171,7 @@ export default function express({ substore: $, port, host }) { headers, body, }; - const res = Response(); + const res = Response(cors.headers); const cb = handler.callback; const errFunc = (err) => { @@ -161,7 +192,7 @@ export default function express({ substore: $, port, host }) { } } else { // no route, return 404 - const res = Response(); + const res = Response(cors.headers); res.status(404).json({ status: 'failed', message: 'ERROR: 404 not found', @@ -208,16 +239,20 @@ export default function express({ substore: $, port, host }) { } } - function Response() { + function Response(corsHeaders = {}) { let statusCode = 200; const { isQX, isLoon, isSurge, isGUIforCores } = ENV(); - const headers = DEFAULT_HEADERS; + const headers = { + ...DEFAULT_HEADERS, + ...corsHeaders, + }; const STATUS_CODE_MAP = { 200: 'HTTP/1.1 200 OK', 201: 'HTTP/1.1 201 Created', 302: 'HTTP/1.1 302 Found', 307: 'HTTP/1.1 307 Temporary Redirect', 308: 'HTTP/1.1 308 Permanent Redirect', + 403: 'HTTP/1.1 403 Forbidden', 404: 'HTTP/1.1 404 Not Found', 500: 'HTTP/1.1 500 Internal Server Error', }; @@ -267,6 +302,16 @@ export default function express({ substore: $, port, host }) { } })(); } + + function applyCors(origin, method) { + const allowed = isOriginAllowed(corsPolicy, origin); + return { + allowed, + preflight: + Boolean(origin) && allowed && method?.toUpperCase() === 'OPTIONS', + headers: allowed ? getCorsHeaders(corsPolicy, origin) : {}, + }; + } } function formatHeaders(headers) { diff --git a/config/Egern.yaml b/config/Egern.yaml index 40405d6d..0ea78581 100644 --- a/config/Egern.yaml +++ b/config/Egern.yaml @@ -12,18 +12,23 @@ compat_arguments: sync_success_notify: true produce_sub: "sub1,sub2" produce_col: "col1,col2" -compat_arguments_desc: '\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 ''同步'' 或 ''同步配置''\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n8️⃣ sync_success_notify\n\n同步配置全部成功时是否发送完成通知\n默认为 true, 填 false/0/no/off 可关闭\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅' + cors: "https://sub-store.vercel.app" +compat_arguments_desc: '\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 ''同步'' 或 ''同步配置''\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n8️⃣ sync_success_notify\n\n同步配置全部成功时是否发送完成通知\n默认为 true, 填 false/0/no/off 可关闭\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n1️⃣1️⃣ cors\n\n允许浏览器跨域访问 Sub-Store 后端的 origin. 默认为 https://sub-store.vercel.app. 多个用 , 连接. 设为 * 可恢复旧的任意来源访问行为, 存在钓鱼网站读取配置的风险\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅' scriptings: - http_request: name: Sub-Store Core match: ^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) script_url: https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js body_required: true + arguments: + _compat.$argument: "cors={{{cors}}}" - http_request: name: Sub-Store Simple match: ^https?:\/\/sub\.store script_url: https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js body_required: true + arguments: + _compat.$argument: "cors={{{cors}}}" - schedule: name: "{{{sync}}}" cron: "{{{cronexp}}}" diff --git a/config/Loon.plugin b/config/Loon.plugin index fa937fb4..97926056 100644 --- a/config/Loon.plugin +++ b/config/Loon.plugin @@ -8,6 +8,7 @@ [Argument] cron=input, "55 23 * * *", tag=定时参数, desc=这里需要输入符合CRON表达式的参数 sync_success_notify=switch, true, tag=同步成功通知, desc=同步配置全部成功时是否发送完成通知 +cors=input, "https://sub-store.vercel.app", tag=CORS允许来源, desc=允许浏览器跨域访问 Sub-Store 后端的 origin. 多个用 , 连接. 设为 * 可恢复旧行为 [Rule] DOMAIN,sub-store.vercel.app,PROXY @@ -16,7 +17,7 @@ DOMAIN,sub-store.vercel.app,PROXY hostname=sub.store [Script] -http-request ^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js, requires-body=true, timeout=120, tag=Sub-Store Core -http-request ^https?:\/\/sub\.store script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js, requires-body=true, timeout=120, tag=Sub-Store Simple +http-request ^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js, requires-body=true, timeout=120, tag=Sub-Store Core, argument="cors={cors}" +http-request ^https?:\/\/sub\.store script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js, requires-body=true, timeout=120, tag=Sub-Store Simple, argument="cors={cors}" cron {cron} script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js, timeout=120, tag=Sub-Store Sync, argument=[{sync_success_notify}] diff --git a/config/README.md b/config/README.md index 37c3c668..08c82acb 100644 --- a/config/README.md +++ b/config/README.md @@ -12,6 +12,18 @@ https://xream.notion.site/Sub-Store-abe6a96944724dc6a36833d5c9ab7c87 ## App 版 +### CORS 允许来源 + +Sub-Store 后端会根据请求的 `Origin` 判断浏览器跨域访问是否允许。允许值是 origin, 需要包含协议、域名和端口, 不包含路径。例如 `https://sub-store.vercel.app` 或 `http://127.0.0.1:8888`。 + +Node/服务器/Docker/Android 版可以通过环境变量 `SUB_STORE_CORS_ALLOWED_ORIGINS` 设置, 默认值为 `*`, 以保持旧行为。多个 origin 用 `,` 分隔, 例如: + +```bash +SUB_STORE_CORS_ALLOWED_ORIGINS=https://sub-store.vercel.app,http://127.0.0.1:8888 +``` + +支持参数配置的 App 模块使用 `cors` 参数设置, 默认值为 `https://sub-store.vercel.app`。如果需要使用本地前端 `http://127.0.0.1:8888?api=http://127.0.0.1:3001/123` 测试代理 App 后端, 需要把模块里的 `cors` 改成 `https://sub-store.vercel.app,http://127.0.0.1:8888`。设为 `*` 可恢复旧的任意来源访问行为, 但任意网站都可能通过浏览器 CORS 读取本机 Sub-Store 后端响应, 不建议长期使用。 + ### 1. Loon 安装使用 插件 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Loon.plugin`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Loon.plugin) 即可。 diff --git a/config/Surge-Beta.sgmodule b/config/Surge-Beta.sgmodule index 840025bf..2eaf5dd4 100644 --- a/config/Surge-Beta.sgmodule +++ b/config/Surge-Beta.sgmodule @@ -1,16 +1,16 @@ #!name=Sub-Store(β) #!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * * #!category=订阅管理 -#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto,produce:"# Sub-Store Produce",produce_cronexp:50 */6 * * *,sync_success_notify:true,produce_sub:"sub1,sub2",produce_col:"col1,col2",max_size:-1 -#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n8️⃣ sync_success_notify\n\n同步配置全部成功时是否发送完成通知\n默认为 true, 填 false/0/no/off 可关闭\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅 +#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto,produce:"# Sub-Store Produce",produce_cronexp:50 */6 * * *,sync_success_notify:true,produce_sub:"sub1,sub2",produce_col:"col1,col2",max_size:-1,cors:"https://sub-store.vercel.app" +#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n8️⃣ sync_success_notify\n\n同步配置全部成功时是否发送完成通知\n默认为 true, 填 false/0/no/off 可关闭\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n1️⃣1️⃣ cors\n\n允许浏览器跨域访问 Sub-Store 后端的 origin. 默认为 https://sub-store.vercel.app. 多个用 , 连接. 设为 * 可恢复旧的任意来源访问行为, 存在钓鱼网站读取配置的风险\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅 [MITM] hostname = %APPEND% sub.store [Script] -Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}},max-size={{{max_size}}} +Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}},max-size={{{max_size}}},argument="cors={{{cors}}}" -Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}},max-size={{{max_size}}} +Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}},max-size={{{max_size}}},argument="cors={{{cors}}}" {{{sync}}}=type=cron,cronexp="{{{cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js,engine={{{engine}}},argument="sync_success_notify={{{sync_success_notify}}}" diff --git a/config/Surge.sgmodule b/config/Surge.sgmodule index 4868cd6b..8a1b2d0a 100644 --- a/config/Surge.sgmodule +++ b/config/Surge.sgmodule @@ -1,16 +1,16 @@ #!name=Sub-Store #!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * * #!category=订阅管理 -#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto,produce:"# Sub-Store Produce",produce_cronexp:50 */6 * * *,sync_success_notify:true,produce_sub:"sub1,sub2",produce_col:"col1,col2",max_size:-1 -#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n8️⃣ sync_success_notify\n\n同步配置全部成功时是否发送完成通知\n默认为 true, 填 false/0/no/off 可关闭\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅 +#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto,produce:"# Sub-Store Produce",produce_cronexp:50 */6 * * *,sync_success_notify:true,produce_sub:"sub1,sub2",produce_col:"col1,col2",max_size:-1,cors:"https://sub-store.vercel.app" +#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n8️⃣ sync_success_notify\n\n同步配置全部成功时是否发送完成通知\n默认为 true, 填 false/0/no/off 可关闭\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n1️⃣1️⃣ cors\n\n允许浏览器跨域访问 Sub-Store 后端的 origin. 默认为 https://sub-store.vercel.app. 多个用 , 连接. 设为 * 可恢复旧的任意来源访问行为, 存在钓鱼网站读取配置的风险\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅 [MITM] hostname = %APPEND% sub.store [Script] -Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}},max-size={{{max_size}}} +Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}},max-size={{{max_size}}},argument="cors={{{cors}}}" -Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}},max-size={{{max_size}}} +Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}},max-size={{{max_size}}},argument="cors={{{cors}}}" {{{sync}}}=type=cron,cronexp="{{{cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js,engine={{{engine}}},argument="sync_success_notify={{{sync_success_notify}}}"