From 3387a3e2dccf2c63de2b20c250de1367203a61df Mon Sep 17 00:00:00 2001 From: Lautaro Petaccio <1120791+LautaroPetaccio@users.noreply.github.com> Date: Mon, 15 Apr 2024 12:18:28 -0300 Subject: [PATCH] feat: Allow receiving an array of sites as CORS ORIGIN (#740) * feat: Allow receiving an array of sites as CORS ORIGIN * fix: Allow CORS variable to accept regex --- .env.example | 4 ++-- src/common/ExpressApp.ts | 8 ++++---- src/server.ts | 17 ++++++++++++++++- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/.env.example b/.env.example index 3b954df7..bb77dcd0 100644 --- a/.env.example +++ b/.env.example @@ -11,8 +11,6 @@ BUILDER_URL=https://builder.decentraland.org CHAIN_NAME=Ethereum Mainnet COLLECTIONS_GRAPH_URL=https://subgraph.decentraland.org/collections-matic-mainnet CONNECTION_STRING='postgres://localhost:5432/builder' -CORS_METHOD=* -CORS_ORIGIN=* DEFAULT_ASSET_PACK_CACHE=86400000 DEFAULT_ETH_ADDRESS= DEFAULT_USER_ID= @@ -30,6 +28,8 @@ PEER_URL=https://peer.decentraland.org RPC_URL=https://rpc.decentraland.org/polygon SERVER_PORT=5000 THIRD_PARTY_GRAPH_URL=https://subgraph.decentraland.org/tpr-matic-mainnet +CORS_ORIGIN='http://localhost:5173' +CORS_METHOD=* WAREHOUSE_CONTEXT_PREFIX= WAREHOUSE_URL= WAREHOUSE_TOKEN= diff --git a/src/common/ExpressApp.ts b/src/common/ExpressApp.ts index 14aa9165..ffbd5c89 100644 --- a/src/common/ExpressApp.ts +++ b/src/common/ExpressApp.ts @@ -1,5 +1,5 @@ import express from 'express' -import cors from 'cors' +import cors, { CorsOptions } from 'cors' import { collectDefaultMetrics } from 'prom-client' import { createTestMetricsComponent } from '@well-known-components/metrics' import { getDefaultHttpMetrics } from '@well-known-components/metrics/dist/http' @@ -21,9 +21,9 @@ export class ExpressApp { return this } - useCORS(origin: string, method: string) { - const corsOptions = { - origin: origin, + useCORS(origin: CorsOptions['origin'], method: string) { + const corsOptions: CorsOptions = { + origin, methods: method, allowedHeaders: '*', exposedHeaders: [ diff --git a/src/server.ts b/src/server.ts index 9577dd20..e3260e49 100644 --- a/src/server.ts +++ b/src/server.ts @@ -32,9 +32,24 @@ import { errorHandler } from './common/errorHandler' const SERVER_PORT = env.get('SERVER_PORT', '5000') const API_VERSION = env.get('API_VERSION', 'v1') -const CORS_ORIGIN = env.get('CORS_ORIGIN', '*') +let CORS_ORIGIN: string | RegExp | (string | RegExp)[] = env.get( + 'CORS_ORIGIN', + '*' +) const CORS_METHOD = env.get('CORS_METHOD', '*') +if (CORS_ORIGIN.split(';').length > 1) { + CORS_ORIGIN = CORS_ORIGIN.split(';') + .map((origin) => origin.trim()) + .map((origin) => + origin.startsWith('regex:') + ? new RegExp(origin.replace('regex:', '')) + : origin + ) +} else if (CORS_ORIGIN.startsWith('regex:')) { + CORS_ORIGIN = new RegExp(CORS_ORIGIN.replace('regex:', '')) +} + export const app = new ExpressApp() const logs = createConsoleLogComponent()