mirror of
https://github.com/sub-store-org/Sub-Store.git
synced 2026-11-28 07:24:12 +00:00
feat: SUB_STORE_FRONTEND_BACKEND_PATH 允许设为 /; #634 Node.js 需要设置 CORS allowlist SUB_STORE_CORS_ALLOWED_ORIGINS, 脚本操作、脚本过滤和修改响应必须设置 SUB_STORE_FRONTEND_BACKEND_PATH(为避免影响过大, 已做一部分处理)
This commit is contained in:
11 files changed
+305
-72
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 || {};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 = [
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
+83
-17
@@ -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:<any-port>,http://127.0.0.1:<any-port> (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;
|
||||
|
||||
+49
-17
@@ -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}:<any-port>`)
|
||||
: []),
|
||||
];
|
||||
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;
|
||||
}
|
||||
|
||||
Vendored
+12
-2
@@ -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) : {},
|
||||
};
|
||||
}
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
Reference in new issue
Block a user