app-de-prueba/middleware.js

36 lines
985 B
JavaScript

import { NextResponse } from "next/server";
const ALLOWED_CIDRS = ["191.98.224.0/19", "190.106.0.0/19"];
function ipToLong(ip) {
return ip
.split(".")
.reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
}
function cidrContains(cidr, ip) {
const [network, bits] = cidr.split("/");
const mask = ~(2 ** (32 - parseInt(bits, 10)) - 1) >>> 0;
return (ipToLong(ip) & mask) === (ipToLong(network) & mask);
}
function isAllowed(ip) {
if (!ip) return false;
return ALLOWED_CIDRS.some((cidr) => cidrContains(cidr, ip));
}
export function middleware(request) {
const forwarded = request.headers.get("x-forwarded-for");
const realIp = request.headers.get("x-real-ip");
const ip = forwarded ? forwarded.split(",")[0].trim() : realIp;
if (!isAllowed(ip)) {
return new NextResponse("Acceso denegado", { status: 403 });
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};