Files
kfpa-cx-dash-front/src/proxy.ts

112 lines
2.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
const IP_WHITELIST_ENV = "IP_WHITELIST";
const LOCAL_IPS = new Set(["127.0.0.1", "::1"]);
const normalizeIp = (ip: string) => {
const trimmed = ip.trim();
if (!trimmed) return "";
if (trimmed.startsWith("::ffff:")) return trimmed.slice("::ffff:".length);
const withoutBrackets = trimmed.replace(/^\[|\]$/g, "");
const portSeparatorIndex = withoutBrackets.lastIndexOf(":");
if (
portSeparatorIndex > -1 &&
withoutBrackets.indexOf(":") === portSeparatorIndex &&
/^\d+$/.test(withoutBrackets.slice(portSeparatorIndex + 1))
) {
return withoutBrackets.slice(0, portSeparatorIndex);
}
return withoutBrackets;
};
const getClientIp = (request: NextRequest) => {
const forwardedFor = request.headers.get("x-forwarded-for");
if (forwardedFor) {
return normalizeIp(forwardedFor.split(",")[0]);
}
return normalizeIp(
request.headers.get("x-real-ip") ??
request.headers.get("cf-connecting-ip") ??
request.headers.get("true-client-ip") ??
""
);
};
const ipv4ToNumber = (ip: string) => {
const parts = ip.split(".");
if (parts.length !== 4) return null;
return parts.reduce<number | null>((acc, part) => {
if (acc === null || !/^\d+$/.test(part)) return null;
const value = Number(part);
if (value < 0 || value > 255) return null;
return ((acc << 8) + value) >>> 0;
}, 0);
};
const isIpv4InCidr = (ip: string, cidr: string) => {
const [rangeIp, prefixRaw] = cidr.split("/");
const prefix = Number(prefixRaw);
const target = ipv4ToNumber(ip);
const range = ipv4ToNumber(rangeIp);
if (target === null || range === null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) {
return false;
}
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
return (target & mask) === (range & mask);
};
const parseWhitelist = () =>
(process.env[IP_WHITELIST_ENV] ?? "")
.split(",")
.map((ip) => normalizeIp(ip))
.filter(Boolean);
const isAllowedIp = (clientIp: string) => {
const whitelist = parseWhitelist();
if (whitelist.length === 0) {
return process.env.ENV === "local" && LOCAL_IPS.has(clientIp);
}
return whitelist.some((allowedIp) => {
if (allowedIp.includes("/")) {
return isIpv4InCidr(clientIp, allowedIp);
}
return clientIp === allowedIp;
});
};
export function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
if (pathname === "/403") {
return NextResponse.next();
}
const clientIp = getClientIp(request);
if (clientIp && isAllowedIp(clientIp)) {
return NextResponse.next();
}
const url = request.nextUrl.clone();
url.pathname = "/403";
url.search = "";
return NextResponse.redirect(url);
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
};