From 038745f9dfb4804bb896f4b209fbd7b04f7a78ab Mon Sep 17 00:00:00 2001 From: xream Date: Fri, 4 Sep 2026 13:28:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20SUB=5FSTORE=5FFRONTEND=5FBACKEND=5FPATH?= =?UTF-8?q?=20=E5=85=81=E8=AE=B8=E8=AE=BE=E4=B8=BA=20/;=20#634=20Node.js?= =?UTF-8?q?=20=E9=9C=80=E8=A6=81=E8=AE=BE=E7=BD=AE=20CORS=20allowlist=20SU?= =?UTF-8?q?B=5FSTORE=5FCORS=5FALLOWED=5FORIGINS,=20=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E3=80=81=E8=84=9A=E6=9C=AC=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E5=92=8C=E4=BF=AE=E6=94=B9=E5=93=8D=E5=BA=94=E5=BF=85=E9=A1=BB?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=20SUB=5FSTORE=5FFRONTEND=5FBACKEND=5FPATH(?= =?UTF-8?q?=E4=B8=BA=E9=81=BF=E5=85=8D=E5=BD=B1=E5=93=8D=E8=BF=87=E5=A4=A7?= =?UTF-8?q?,=20=E5=B7=B2=E5=81=9A=E4=B8=80=E9=83=A8=E5=88=86=E5=A4=84?= =?UTF-8?q?=E7=90=86)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- backend/package.json | 4 +- backend/src/core/proxy-utils/index.js | 11 ++ backend/src/restful/index.js | 26 +++-- .../proxy-processors/process-context.spec.js | 63 +++++++++++ backend/src/test/restful/index.spec.js | 23 ++++ backend/src/test/utils/cors.spec.js | 66 +++++++----- backend/src/test/vendor/express-cors.spec.js | 100 +++++++++++++++--- backend/src/utils/cors.js | 66 +++++++++--- backend/src/vendor/express.js | 14 ++- config/README.md | 2 +- 11 files changed, 305 insertions(+), 72 deletions(-) create mode 100644 backend/src/test/restful/index.spec.js diff --git a/README.md b/README.md index 27c04dd5..9a3ffd76 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ sub.store = 127.0.0.1 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. +- Node/server deployments use `SUB_STORE_CORS_ALLOWED_ORIGINS`; the default is `https://sub-store.vercel.app,http://substore.stash,https://substore.stash`. - Proxy App modules use the `cors` module argument; the default is `https://sub-store.vercel.app,http://substore.stash,https://substore.stash`. - 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. diff --git a/backend/package.json b/backend/package.json index 27cecec0..d0720dfe 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,12 +1,12 @@ { "name": "sub-store", - "version": "2.37.2", + "version": "2.38.0", "description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.", "main": "src/main.js", "packageManager": "pnpm@11.0.9", "scripts": { "preinstall": "npx only-allow pnpm", - "test": "mocha src/test/**/*.spec.js --require @babel/register --recursive", + "test": "SUB_STORE_FRONTEND_BACKEND_PATH=/ mocha src/test/**/*.spec.js --require @babel/register --recursive", "serve": "node sub-store.min.js", "start": "nodemon -w src -w package.json --exec babel-node src/main.js", "dev:esbuild": "nodemon -w src -w package.json dev-esbuild.js", diff --git a/backend/src/core/proxy-utils/index.js b/backend/src/core/proxy-utils/index.js index 95af67aa..0e833ca7 100644 --- a/backend/src/core/proxy-utils/index.js +++ b/backend/src/core/proxy-utils/index.js @@ -276,6 +276,17 @@ async function processResponseFn( } async function loadScriptItem(item, executionContext = {}) { + if ( + $.env.isNode && + !eval('process.env.SUB_STORE_FRONTEND_BACKEND_PATH')?.startsWith('/') && + !eval('process.env.SUB_STORE_BACKEND_CUSTOM_NAME') + ) { + const message = + 'Node.js 环境下,脚本操作、脚本过滤和修改响应必须设置 SUB_STORE_FRONTEND_BACKEND_PATH 才能生效;若不想改变当前 path,可设置 SUB_STORE_FRONTEND_BACKEND_PATH=/'; + $.error(message); + throw new Error(message); + } + let script; let $arguments = {}; const { mode, content } = item.args || {}; diff --git a/backend/src/restful/index.js b/backend/src/restful/index.js index 93aa8dd2..41e77963 100644 --- a/backend/src/restful/index.js +++ b/backend/src/restful/index.js @@ -34,6 +34,18 @@ import registerAgeRoutes from './age'; import { consumeShareToken } from './token'; import { AGE_PUBLIC_KEY } from '@/utils/age'; +export function stripBackendPath(url, backendPath) { + return (backendPath === '/' ? url : url.replace(backendPath, '')) || '/'; +} + +export function matchesBackendPath(path, backendPath, merge) { + if (backendPath !== '/') return path.startsWith(backendPath); + return ( + /^\/(api|download|share)(\/|$)/.test(path) && + (!merge || !path.startsWith('/share/')) + ); +} + export default function serve() { let port; let host; @@ -61,10 +73,14 @@ export default function serve() { $.info(`[BACKEND] MERGE mode is [ON].`); $.info(`[BACKEND && FRONTEND] ${host}:${port}`); } - $.info(`[BACKEND PREFIX] ${host}:${port}${fe_be_path}`); + $.info( + `[BACKEND PREFIX] ${host}:${port}${ + fe_be_path === '/' ? '' : fe_be_path + }`, + ); $app.use((req, res, next) => { - if (req.path.startsWith(fe_be_path)) { - req.url = req.url.replace(fe_be_path, '') || '/'; + if (matchesBackendPath(req.path, fe_be_path, be_merge)) { + req.url = stripBackendPath(req.url, fe_be_path); if (be_merge && req.url.startsWith('/api/')) { req.query['share'] = 'true'; } @@ -103,9 +119,7 @@ export default function serve() { } } } - const isBackendRoute = /^\/(api|download|share)(\/|$)/.test( - req.path, - ); + const isBackendRoute = matchesBackendPath(req.path, '/', false); if (mergedFrontend && !isBackendRoute) { mergedFrontend(req, res, next); return; diff --git a/backend/src/test/proxy-processors/process-context.spec.js b/backend/src/test/proxy-processors/process-context.spec.js index fb00da3d..769a060f 100644 --- a/backend/src/test/proxy-processors/process-context.spec.js +++ b/backend/src/test/proxy-processors/process-context.spec.js @@ -4,7 +4,70 @@ import { describe, it } from 'mocha'; import { ProxyUtils } from '@/core/proxy-utils'; import { generateKeyPair } from '@/utils/age'; +const PATH_ENV_KEY = 'SUB_STORE_FRONTEND_BACKEND_PATH'; +const CUSTOM_NAME_ENV_KEY = 'SUB_STORE_BACKEND_CUSTOM_NAME'; +const MISSING_PATH_ERROR = + 'Node.js 环境下,脚本操作、脚本过滤和修改响应必须设置 SUB_STORE_FRONTEND_BACKEND_PATH 才能生效;若不想改变当前 path,可设置 SUB_STORE_FRONTEND_BACKEND_PATH=/'; + describe('Process context control', function () { + it('requires a backend path for Node.js script actions unless the backend is custom', async function () { + const originalPath = process.env[PATH_ENV_KEY]; + const originalCustomName = process.env[CUSTOM_NAME_ENV_KEY]; + const actions = [ + () => + ProxyUtils.process([], [ + { + type: 'Script Operator', + args: { + mode: 'script', + content: 'function operator() {}', + }, + }, + ]), + () => + ProxyUtils.process([], [ + { + type: 'Script Filter', + args: { + mode: 'script', + content: 'function filter() { return []; }', + }, + }, + ]), + () => + ProxyUtils.processResponse({}, [ + { + type: 'Response Transformer', + args: { + mode: 'script', + content: + 'function transformFunction(res) { return res; }', + }, + }, + ]), + ]; + + try { + delete process.env[PATH_ENV_KEY]; + delete process.env[CUSTOM_NAME_ENV_KEY]; + const rejected = await Promise.allSettled( + actions.map((run) => run()), + ); + expect(rejected.map(({ reason }) => reason?.message)).to.deep.equal( + actions.map(() => MISSING_PATH_ERROR), + ); + + process.env[CUSTOM_NAME_ENV_KEY] = 'custom'; + await Promise.all(actions.map((run) => run())); + } finally { + if (originalPath == null) delete process.env[PATH_ENV_KEY]; + else process.env[PATH_ENV_KEY] = originalPath; + if (originalCustomName == null) + delete process.env[CUSTOM_NAME_ENV_KEY]; + else process.env[CUSTOM_NAME_ENV_KEY] = originalCustomName; + } + }); + it('disables later actions by customName from shared context', async function () { const operators = [ { diff --git a/backend/src/test/restful/index.spec.js b/backend/src/test/restful/index.spec.js new file mode 100644 index 00000000..31440919 --- /dev/null +++ b/backend/src/test/restful/index.spec.js @@ -0,0 +1,23 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; + +import { matchesBackendPath, stripBackendPath } from '@/restful'; + +describe('backend path', function () { + it('keeps root paths and strips non-root prefixes', function () { + expect(stripBackendPath('/api/utils/env', '/')).to.equal( + '/api/utils/env', + ); + expect(stripBackendPath('', '/')).to.equal('/'); + expect( + stripBackendPath('/sub-store/api/utils/env', '/sub-store'), + ).to.equal('/api/utils/env'); + }); + + it('keeps merged frontend routes outside a root backend path', function () { + expect(matchesBackendPath('/api/settings', '/', true)).to.equal(true); + expect(matchesBackendPath('/settings', '/', true)).to.equal(false); + expect(matchesBackendPath('/share/sub/foo', '/', true)).to.equal(false); + expect(matchesBackendPath('/share/sub/foo', '/', false)).to.equal(true); + }); +}); diff --git a/backend/src/test/utils/cors.spec.js b/backend/src/test/utils/cors.spec.js index bec1572a..afa22def 100644 --- a/backend/src/test/utils/cors.spec.js +++ b/backend/src/test/utils/cors.spec.js @@ -10,25 +10,42 @@ import { } from '@/utils/cors'; describe('CORS allowlist policy', function () { - it('defaults Node environments to wildcard origins', function () { + it('defaults Node environments to bundled frontend origins', function () { const policy = resolveCorsPolicy({ isNode: true }); expect(policy).to.deep.include({ - wildcard: true, - value: '*', + wildcard: false, + value: NON_NODE_CORS_DEFAULT, 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': '*', + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal(false); + }); + + it('allows bundled and local HTTP origins for custom backends', function () { + const policy = resolveCorsPolicy({ + isNode: true, + customBackendName: 'custom', }); + + expect(policy.wildcard).to.equal(false); + expect( + isOriginAllowed(policy, 'https://sub-store.vercel.app'), + ).to.equal(true); + expect(isOriginAllowed(policy, 'http://localhost:5173')).to.equal(true); + expect(isOriginAllowed(policy, 'http://127.0.0.1:8888')).to.equal(true); + expect(isOriginAllowed(policy, 'https://localhost:5173')).to.equal( + false, + ); + expect(isOriginAllowed(policy, 'http://localhost.evil:5173')).to.equal( + false, + ); + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal(false); }); 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', + envValue: 'https://sub-store.vercel.app, http://127.0.0.1:8888', }); expect(policy).to.deep.include({ @@ -39,12 +56,8 @@ describe('CORS allowlist policy', function () { 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, - ); + 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 bundled frontend origins', function () { @@ -62,9 +75,7 @@ describe('CORS allowlist policy', function () { expect(isOriginAllowed(policy, 'https://substore.stash')).to.equal( true, ); - expect(isOriginAllowed(policy, 'https://evil.example')).to.equal( - false, - ); + expect(isOriginAllowed(policy, 'https://evil.example')).to.equal(false); }); it('reads non-Node allowlist values from script arguments', function () { @@ -117,11 +128,14 @@ describe('CORS allowlist policy', function () { }, }); - expect(isOriginAllowed(policy, 'https://sub-store.vercel.app')).to.equal( - true, - ); expect( - isOriginAllowed(policy, 'https://evil.example.sub-store.vercel.app'), + 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, @@ -140,9 +154,9 @@ describe('CORS allowlist policy', function () { }); expect(nodePolicy).to.deep.include({ - wildcard: true, + wildcard: false, source: 'default:node', - value: '*', + value: NON_NODE_CORS_DEFAULT, }); expect(nonNodePolicy).to.deep.include({ wildcard: false, @@ -152,9 +166,9 @@ describe('CORS allowlist policy', function () { expect( isOriginAllowed(nonNodePolicy, 'https://sub-store.vercel.app'), ).to.equal(true); - expect(isOriginAllowed(nonNodePolicy, 'http://substore.stash')).to.equal( - true, - ); + expect( + isOriginAllowed(nonNodePolicy, 'http://substore.stash'), + ).to.equal(true); expect( isOriginAllowed(nonNodePolicy, 'https://substore.stash'), ).to.equal(true); diff --git a/backend/src/test/vendor/express-cors.spec.js b/backend/src/test/vendor/express-cors.spec.js index af1f4cc3..66a5b9a2 100644 --- a/backend/src/test/vendor/express-cors.spec.js +++ b/backend/src/test/vendor/express-cors.spec.js @@ -4,10 +4,12 @@ import { afterEach, describe, it } from 'mocha'; import express from '@/vendor/express'; const ENV_KEY = 'SUB_STORE_CORS_ALLOWED_ORIGINS'; +const CUSTOM_NAME_ENV_KEY = 'SUB_STORE_BACKEND_CUSTOM_NAME'; const HOST = '127.0.0.1'; describe('express CORS allowlist adapter', function () { let originalCorsEnv; + let originalCustomName; afterEach(function () { if (originalCorsEnv == null) { @@ -15,22 +17,80 @@ describe('express CORS allowlist adapter', function () { } else { process.env[ENV_KEY] = originalCorsEnv; } + if (originalCustomName == null) { + delete process.env[CUSTOM_NAME_ENV_KEY]; + } else { + process.env[CUSTOM_NAME_ENV_KEY] = originalCustomName; + } }); - 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', - }, - }); + it('uses and logs the bundled frontend origins by default', async function () { + await withServer( + undefined, + async ({ baseUrl, getRouteCalls, logs }) => { + 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( - '*', - ); - }); + expect(res.status).to.equal(403); + expect(getRouteCalls()).to.equal(0); + expect( + logs.filter((log) => log.startsWith('[CORS]')), + ).to.deep.equal([ + '[CORS] SUB_STORE_CORS_ALLOWED_ORIGINS is not set; using default allowed origins: https://sub-store.vercel.app,http://substore.stash,https://substore.stash', + ]); + }, + ); + }); + + it('allows only bundled and local origins for custom backends without logging the bypass', async function () { + await withServer( + undefined, + async ({ baseUrl, logs }) => { + const official = await fetch(`${baseUrl}/probe`, { + headers: { + Origin: 'https://sub-store.vercel.app', + }, + }); + const localhost = await fetch(`${baseUrl}/probe`, { + headers: { Origin: 'http://localhost:5173' }, + }); + const loopback = await fetch(`${baseUrl}/probe`, { + headers: { Origin: 'http://127.0.0.1:8888' }, + }); + const rejected = await fetch(`${baseUrl}/probe`, { + headers: { Origin: 'https://evil.example' }, + }); + + expect(official.status).to.equal(200); + expect(localhost.status).to.equal(200); + expect(loopback.status).to.equal(200); + expect(rejected.status).to.equal(403); + expect( + localhost.headers.get('access-control-allow-origin'), + ).to.equal('http://localhost:5173'); + expect( + loopback.headers.get('access-control-allow-origin'), + ).to.equal('http://127.0.0.1:8888'); + expect( + rejected.headers.get('access-control-allow-origin'), + ).to.equal(null); + expect( + official.headers.get('access-control-allow-origin'), + ).to.equal('https://sub-store.vercel.app'); + expect(logs.some((log) => log.includes('is not set'))).to.equal( + false, + ); + expect( + logs.filter((log) => log.startsWith('[CORS]')), + ).to.deep.equal([ + '[CORS] allowed origins: https://sub-store.vercel.app,http://substore.stash,https://substore.stash,http://localhost:,http://127.0.0.1: (default:node)', + ]); + }, + 'custom', + ); }); it('rejects disallowed actual requests before route handlers run', async function () { @@ -91,9 +151,9 @@ describe('express CORS allowlist adapter', function () { 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( + local.headers.get('access-control-allow-origin'), + ).to.equal('http://127.0.0.1:8888'); expect(official.headers.get('vary')).to.include('Origin'); }, ); @@ -125,13 +185,19 @@ describe('express CORS allowlist adapter', function () { ); }); - async function withServer(corsEnv, run) { + async function withServer(corsEnv, run, customName) { originalCorsEnv = process.env[ENV_KEY]; + originalCustomName = process.env[CUSTOM_NAME_ENV_KEY]; if (corsEnv == null) { delete process.env[ENV_KEY]; } else { process.env[ENV_KEY] = corsEnv; } + if (customName == null) { + delete process.env[CUSTOM_NAME_ENV_KEY]; + } else { + process.env[CUSTOM_NAME_ENV_KEY] = customName; + } const logs = []; let routeCalls = 0; diff --git a/backend/src/utils/cors.js b/backend/src/utils/cors.js index 1b524b41..df4fec84 100644 --- a/backend/src/utils/cors.js +++ b/backend/src/utils/cors.js @@ -1,13 +1,13 @@ /* eslint-disable no-undef */ -export const NODE_CORS_ALLOWED_ORIGINS_ENV = - 'SUB_STORE_CORS_ALLOWED_ORIGINS'; -export const NODE_CORS_DEFAULT = '*'; +export const NODE_CORS_ALLOWED_ORIGINS_ENV = 'SUB_STORE_CORS_ALLOWED_ORIGINS'; export const NON_NODE_CORS_DEFAULT = 'https://sub-store.vercel.app,http://substore.stash,https://substore.stash'; +export const NODE_CORS_DEFAULT = NON_NODE_CORS_DEFAULT; export const CORS_ARGUMENT_KEY = 'cors'; const WILDCARD_ORIGIN = '*'; +const LOCAL_HTTP_HOSTS = ['localhost', '127.0.0.1']; export function parseArgument(rawArgument) { if (rawArgument == null || rawArgument === '') return {}; @@ -32,6 +32,7 @@ export function resolveCorsPolicy({ isNode, envValue, argument, + customBackendName, } = {}) { const defaultValue = isNode ? NODE_CORS_DEFAULT : NON_NODE_CORS_DEFAULT; const configuredValue = isNode @@ -45,24 +46,33 @@ export function resolveCorsPolicy({ ? `env:${NODE_CORS_ALLOWED_ORIGINS_ENV}` : `argument:${CORS_ARGUMENT_KEY}` : isNode - ? 'default:node' - : 'default:non-node'; + ? '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; + const parsedPolicy = parseAllowedOrigins(rawValue, source); + const policy = + !parsedPolicy.wildcard && parsedPolicy.origins.length === 0 + ? parseAllowedOrigins( + defaultValue, + isNode ? 'default:node' : 'default:non-node', + ) + : parsedPolicy; + + return isNode && customBackendName && policy.source === 'default:node' + ? { ...policy, allowLocalOrigins: true } + : policy; } export function resolveRuntimeCorsPolicy({ isNode } = {}) { return resolveCorsPolicy({ isNode, - envValue: isNode ? readNodeCorsEnv() : undefined, + envValue: isNode + ? readNodeEnv(NODE_CORS_ALLOWED_ORIGINS_ENV) + : undefined, argument: isNode ? undefined : readScriptArgument(), + customBackendName: isNode + ? readNodeEnv('SUB_STORE_BACKEND_CUSTOM_NAME') + : undefined, }); } @@ -71,6 +81,9 @@ export function isOriginAllowed(policy, origin) { if (policy?.wildcard) return true; const normalizedOrigin = normalizeOrigin(origin); + if (policy?.allowLocalOrigins && isLocalHttpOrigin(normalizedOrigin)) { + return true; + } return policy?.origins?.includes(normalizedOrigin); } @@ -89,7 +102,15 @@ export function getCorsHeaders(policy, origin) { } export function describeCorsPolicy(policy) { - return `${policy?.wildcard ? WILDCARD_ORIGIN : policy?.origins?.join(',') || ''} (${policy?.source})`; + const origins = policy?.wildcard + ? [WILDCARD_ORIGIN] + : [ + ...(policy?.origins || []), + ...(policy?.allowLocalOrigins + ? LOCAL_HTTP_HOSTS.map((host) => `http://${host}:`) + : []), + ]; + return `${origins.join(',')} (${policy?.source})`; } function parseAllowedOrigins(rawValue, source) { @@ -127,9 +148,20 @@ function normalizeOrigin(origin) { } } -function readNodeCorsEnv() { +function isLocalHttpOrigin(origin) { try { - return eval(`process.env.${NODE_CORS_ALLOWED_ORIGINS_ENV}`); + const url = new URL(origin); + return ( + url.protocol === 'http:' && LOCAL_HTTP_HOSTS.includes(url.hostname) + ); + } catch { + return false; + } +} + +function readNodeEnv(name) { + try { + return eval('process.env')[name]; } catch { return undefined; } diff --git a/backend/src/vendor/express.js b/backend/src/vendor/express.js index 1921aeb9..15b43aff 100644 --- a/backend/src/vendor/express.js +++ b/backend/src/vendor/express.js @@ -4,13 +4,21 @@ import { describeCorsPolicy, getCorsHeaders, isOriginAllowed, + NODE_CORS_ALLOWED_ORIGINS_ENV, resolveRuntimeCorsPolicy, } from '@/utils/cors'; export default function express({ substore: $, port, host }) { const { isNode } = ENV(); const corsPolicy = resolveRuntimeCorsPolicy({ isNode }); - $.info(`[CORS] allowed origins: ${describeCorsPolicy(corsPolicy)}`); + $.info( + isNode && + corsPolicy.source === 'default:node' && + !corsPolicy.wildcard && + !corsPolicy.allowLocalOrigins + ? `[CORS] ${NODE_CORS_ALLOWED_ORIGINS_ENV} is not set; using default allowed origins: ${corsPolicy.value}` + : `[CORS] allowed origins: ${describeCorsPolicy(corsPolicy)}`, + ); const DEFAULT_HEADERS = { 'Content-Type': 'text/plain;charset=UTF-8', @@ -308,7 +316,9 @@ export default function express({ substore: $, port, host }) { return { allowed, preflight: - Boolean(origin) && allowed && method?.toUpperCase() === 'OPTIONS', + Boolean(origin) && + allowed && + method?.toUpperCase() === 'OPTIONS', headers: allowed ? getCorsHeaders(corsPolicy, origin) : {}, }; } diff --git a/config/README.md b/config/README.md index 1f4b9433..b34f8f93 100644 --- a/config/README.md +++ b/config/README.md @@ -16,7 +16,7 @@ https://xream.notion.site/Sub-Store-abe6a96944724dc6a36833d5c9ab7c87 Sub-Store 后端会根据请求的 `Origin` 判断浏览器跨域访问是否允许。允许值是 origin, 需要包含协议、域名和端口, 不包含路径。例如 `https://sub-store.vercel.app` 或 `http://127.0.0.1:8888`。 -Node/服务器/Docker/Android 版可以通过环境变量 `SUB_STORE_CORS_ALLOWED_ORIGINS` 设置, 默认值为 `*`, 以保持旧行为。多个 origin 用 `,` 分隔, 例如: +Node/服务器/Docker/Android 版可以通过环境变量 `SUB_STORE_CORS_ALLOWED_ORIGINS` 设置, 默认值为 `https://sub-store.vercel.app,http://substore.stash,https://substore.stash`。多个 origin 用 `,` 分隔, 例如: ```bash SUB_STORE_CORS_ALLOWED_ORIGINS=https://sub-store.vercel.app,http://127.0.0.1:8888