From af3bac1360a852daccc97cf021d3b242415289ec Mon Sep 17 00:00:00 2001 From: Vexx Date: Fri, 22 May 2026 01:04:47 +0530 Subject: [PATCH] Replace wildcard CORS with explicit ALLOWED_ORIGINS allowlist cors('*') permitted any origin to read API responses, removing the Same-Origin Policy as a defence layer for all current and future endpoints with no per-origin review. Replace with an origin callback that checks against an ALLOWED_ORIGINS environment variable (comma-separated, defaults to localhost:5173 for local development). Enable credentials:true so session cookies work on cross-origin requests from the listed frontend. Document ALLOWED_ORIGINS in .env.sample so developers set the correct production domain when deploying. Closes #374 --- backend/.env.sample | 2 ++ backend/server.js | 20 ++++++++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/backend/.env.sample b/backend/.env.sample index 98f96881..fb332065 100644 --- a/backend/.env.sample +++ b/backend/.env.sample @@ -1,3 +1,5 @@ PORT=5000 MONGO_URI=mongodb://localhost:27017/githubTracker SESSION_SECRET=your-secret-key +# Comma-separated list of allowed frontend origins +ALLOWED_ORIGINS=http://localhost:5173 diff --git a/backend/server.js b/backend/server.js index 3f19f00b..4b8906a6 100644 --- a/backend/server.js +++ b/backend/server.js @@ -11,8 +11,24 @@ require('./config/passportConfig'); const app = express(); -// CORS configuration -app.use(cors('*')); +// CORS — restrict to known frontend origins only +const allowedOrigins = (process.env.ALLOWED_ORIGINS || 'http://localhost:5173') + .split(',') + .map(o => o.trim()); + +app.use(cors({ + origin: (origin, callback) => { + // Allow server-to-server requests (no Origin header) and explicit allowlist + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + callback(new Error('Not allowed by CORS')); + } + }, + credentials: true, + methods: ['GET', 'POST'], + allowedHeaders: ['Content-Type'], +})); // Middleware app.use(bodyParser.json());