From 679a249f8b432286a91b7d0c88c89723517bb767 Mon Sep 17 00:00:00 2001 From: MayaTheShy Date: Sun, 22 Mar 2026 11:25:04 -0400 Subject: [PATCH] refactor: implement API key authentication for secure access to endpoints --- server/server.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/server/server.js b/server/server.js index 238a88f..0e7f835 100644 --- a/server/server.js +++ b/server/server.js @@ -11,6 +11,29 @@ const PORT = 3001; app.use(cors()); app.use(express.json({ limit: '5mb' })); +// ========== API Key Authentication ========== +const API_KEY = process.env.API_KEY || ''; + +function extractApiKey(req) { + const auth = req.headers.authorization || ''; + if (auth.startsWith('Bearer ')) return auth.slice(7); + return req.headers['x-api-key'] || req.query.key || ''; +} + +function requireAuth(req, res, next) { + if (!API_KEY) return next(); // Auth disabled when no key configured + if (extractApiKey(req) === API_KEY) return next(); + return res.status(401).json({ error: 'Unauthorized — invalid or missing API key' }); +} + +// Protect mutating endpoints when an API key is set +app.use((req, res, next) => { + if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') { + return next(); + } + return requireAuth(req, res, next); +}); + // Rewrite requests that arrive without /api prefix (from reverse proxy stripping it) app.use((req, res, next) => { if (!req.path.startsWith('/api') && req.path !== '/' && req.path !== '/health') {