refactor: enhance frontend API key validation by checking same-origin requests

This commit is contained in:
Tudor Stanciu 2025-10-04 03:49:15 +03:00
parent ae34658fba
commit 06a1b84f03

View File

@ -33,17 +33,35 @@ export const apiKeyAuth = (
const origin = req.headers.origin || req.headers.referer; const origin = req.headers.origin || req.headers.referer;
const allowedOrigins = config.frontendAllowedOrigins; const allowedOrigins = config.frontendAllowedOrigins;
// Check if origin is present and matches allowed origins // If no origin/referer header, check if it's a same-origin request by checking Host header
if (!origin) { if (!origin) {
logger.warn('Frontend API key used without origin/referer header', { const host = req.headers.host;
ip: req.ip, const protocol = req.protocol || 'http';
path: req.path, const requestOrigin = `${protocol}://${host}`;
userAgent: req.headers['user-agent'],
}); // Check if the request comes from an allowed origin based on Host header
res.status(403).json({ const isSameOriginAllowed = allowedOrigins.some(allowed =>
error: 'Forbidden', requestOrigin.startsWith(allowed)
message: 'Origin header required for frontend API key', );
});
if (!isSameOriginAllowed) {
logger.warn('Frontend API key used without origin/referer header', {
ip: req.ip,
path: req.path,
host: host,
requestOrigin: requestOrigin,
userAgent: req.headers['user-agent'],
});
res.status(403).json({
error: 'Forbidden',
message: 'Origin header required for frontend API key',
});
return;
}
// Same-origin request allowed
req.apiKeyType = 'frontend';
next();
return; return;
} }