All checks were successful
Deploy Production (ss-tools.crewsportswear.app) / deploy (push) Successful in 1m5s
56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
const { allowedOrigins } = require('../config/config');
|
|
|
|
/**
|
|
* CORS and Security middleware
|
|
* Only allows requests from whitelisted domains
|
|
*/
|
|
function corsMiddleware(req, res, next) {
|
|
const origin = req.headers.origin;
|
|
const referer = req.headers.referer;
|
|
|
|
// Check if origin is allowed
|
|
const isOriginAllowed = origin && allowedOrigins.indexOf(origin) > -1;
|
|
|
|
// Check if referer matches allowed domains
|
|
const isRefererAllowed = referer && allowedOrigins.some(allowed => {
|
|
try {
|
|
const refererHost = new URL(referer).origin;
|
|
return refererHost === allowed || referer.startsWith(allowed);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
});
|
|
|
|
// Allow if origin OR referer is whitelisted
|
|
// Also allow health check endpoint without restrictions
|
|
if (req.path === '/health') {
|
|
return next();
|
|
}
|
|
|
|
if (!isOriginAllowed && !isRefererAllowed) {
|
|
console.warn(`Blocked request from Origin: ${origin || 'none'}, Referer: ${referer || 'none'}`);
|
|
return res.status(403).json({
|
|
error: 'Forbidden',
|
|
message: 'Access denied. This API is restricted to authorized domains only.'
|
|
});
|
|
}
|
|
|
|
// Set CORS headers for allowed origin
|
|
if (isOriginAllowed) {
|
|
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
}
|
|
|
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
|
|
res.setHeader('Access-Control-Allow-Credentials', true);
|
|
|
|
// Handle preflight requests
|
|
if (req.method === 'OPTIONS') {
|
|
return res.status(200).end();
|
|
}
|
|
|
|
next();
|
|
}
|
|
|
|
module.exports = corsMiddleware;
|