Files
ember-market-frontend/backend/middleware/telegramAuthMiddleware.js
2025-03-10 17:39:37 +00:00

70 lines
3.0 KiB
JavaScript

import logger from "../utils/logger.js";
// Middleware for protecting Telegram API routes
export const protectTelegramApi = async (req, res, next) => {
// Log the headers for debugging
logger.info("Telegram API request headers:", {
authorization: req.headers.authorization ? req.headers.authorization.substring(0, 10) + "..." : "undefined",
"x-api-key": req.headers['x-api-key'] ? req.headers['x-api-key'].substring(0, 10) + "..." : "undefined",
method: req.method,
path: req.path,
allHeaders: JSON.stringify(req.headers)
});
// Full debug for non-production environments
logger.info("FULL HEADER DEBUG (KEYS ONLY):", Object.keys(req.headers));
logger.info("AUTH HEADER TYPE:", typeof req.headers.authorization);
const expectedKey = process.env.INTERNAL_API_KEY;
logger.info("Expected API Key (first 10 chars):", expectedKey ? expectedKey.substring(0, 10) + "..." : "undefined");
// Check if the environment variable is actually defined
if (!expectedKey) {
logger.error("INTERNAL_API_KEY environment variable is not defined");
return res.status(500).json({ error: "Server configuration error" });
}
// Check if API key is in the expected header
if (req.headers.authorization === expectedKey) {
logger.info("Telegram API auth successful via Authorization header");
return next();
}
// Also try x-api-key as a fallback
if (req.headers['x-api-key'] === expectedKey) {
logger.info("Telegram API auth successful via x-api-key header");
return next();
}
// Try trimming whitespace
if (req.headers.authorization && req.headers.authorization.trim() === expectedKey) {
logger.info("Telegram API auth successful via Authorization header (after trimming)");
return next();
}
// Also try x-api-key with trimming
if (req.headers['x-api-key'] && req.headers['x-api-key'].trim() === expectedKey) {
logger.info("Telegram API auth successful via x-api-key header (after trimming)");
return next();
}
// Check for Bearer prefix and try to extract the token
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
const token = req.headers.authorization.substring(7).trim();
if (token === expectedKey) {
logger.info("Telegram API auth successful via Bearer token in Authorization header");
return next();
}
}
logger.warn("Telegram API auth failed:", {
expectedKeyPrefix: expectedKey ? expectedKey.substring(0, 5) + "..." : "undefined",
expectedKeyLength: expectedKey ? expectedKey.length : 0,
authHeaderPrefix: req.headers.authorization ? req.headers.authorization.substring(0, 5) + "..." : "undefined",
authHeaderLength: req.headers.authorization ? req.headers.authorization.length : 0,
xApiKeyPrefix: req.headers['x-api-key'] ? req.headers['x-api-key'].substring(0, 5) + "..." : "undefined",
xApiKeyLength: req.headers['x-api-key'] ? req.headers['x-api-key'].length : 0
});
return res.status(401).json({ error: "Unauthorized: Invalid API key" });
};