import type { Request, Response, NextFunction } from 'express';
import { config } from '../config.js';
import { logger } from '../utils/logger.js';
function normalizeIp(ip: string): string {
// Handle IPv4-mapped IPv6 addresses like ::ffff:127.0.0.1
if (ip.startsWith('::ffff:')) {
return ip.slice(7);
}
return ip;
}
export function ipAllowlistMiddleware(req: Request, res: Response, next: NextFunction): void {
const allowedIps = config.auth.allowedIps;
// If no IPs configured, allow all
if (allowedIps.length === 0) {
next();
return;
}
const clientIp = normalizeIp(req.ip ?? '');
const allowed = allowedIps.some((ip) => {
const normalizedAllowed = normalizeIp(ip);
return clientIp === normalizedAllowed;
});
if (!allowed) {
logger.warn({ ip: clientIp, path: req.path }, 'IP not in allowlist');
res.status(403).json({ error: 'Forbidden: IP not allowed' });
return;
}
next();
}