From 5a3bf000f8c95ac250b3afb95029d49003ee5e0e Mon Sep 17 00:00:00 2001 From: Vexx Date: Sat, 23 May 2026 20:07:04 +0530 Subject: [PATCH] Replace wildcard CORS with environment-driven origin allowlist cors('*') allowed any website to make cross-origin requests to the API and read the full response body, bypassing the browser's Same-Origin Policy for all current and future endpoints. Replace with an explicit origin allowlist read from ALLOWED_ORIGINS, defaulting to the local Vite dev server. Restrict permitted methods to GET and POST and lock allowed headers to Content-Type so the policy surface stays minimal as the API grows. Fixes #374 --- backend/.env.sample | 1 + backend/server.js | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/backend/.env.sample b/backend/.env.sample index 98f96881..7d4a2184 100644 --- a/backend/.env.sample +++ b/backend/.env.sample @@ -1,3 +1,4 @@ PORT=5000 MONGO_URI=mongodb://localhost:27017/githubTracker SESSION_SECRET=your-secret-key +ALLOWED_ORIGINS=http://localhost:5173 diff --git a/backend/server.js b/backend/server.js index 3f19f00b..e9f51e73 100644 --- a/backend/server.js +++ b/backend/server.js @@ -11,8 +11,23 @@ require('./config/passportConfig'); const app = express(); -// CORS configuration -app.use(cors('*')); +// CORS configuration — 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) => { + 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());