refactor: implement API key authentication for secure access to endpoints

This commit is contained in:
MayaTheShy
2026-03-22 11:25:04 -04:00
parent 69041244a2
commit 679a249f8b

View File

@@ -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') {