← Назадconst config = require('../config');
function checkApiKey(req, res, next) {
// If no API key is configured, skip auth entirely
if (!config.apiKey) return next();
const key = req.headers['x-api-key'] || req.query.api_key;
// Allow requests from the same-origin frontend (served by express.static)
// These come without x-api-key. Check Referer/Origin to verify same-origin.
if (!key) {
const origin = req.headers.origin || '';
const referer = req.headers.referer || '';
const host = req.headers.host || '';
// Allow if request comes from the same host (PWA / frontend)
const isSameOrigin = origin.includes(host) || referer.includes(host);
if (isSameOrigin) return next();
// Block external requests without API key
return res.status(401).json({ error: 'API key required' });
}
if (key !== config.apiKey) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
}
module.exports = { checkApiKey };