Update index.ts

This commit is contained in:
Daniel Hougaard
2025-09-03 20:43:15 +02:00
parent c8275f41a3
commit 6abd58ee21

View File

@@ -1,5 +1,7 @@
import net from "node:net";
import RE2 from "re2";
import { ForbiddenRequestError } from "../errors";
export enum IPType {
@@ -7,6 +9,8 @@ export enum IPType {
IPV6 = "ipv6"
}
const PORT_REGEX = new RE2(/^\d+$/);
/**
* Strips port from IP address if present.
* Handles both IPv4 (e.g. 1.2.3.4:1234) and IPv6 (e.g. [2001:db8::1]:8080) formats.
@@ -19,14 +23,14 @@ const stripPort = (ip: string): { ipAddress: string } => {
if (endBracketIndex === -1) return { ipAddress: ip };
const ipPart = ip.slice(1, endBracketIndex);
const portPart = ip.slice(endBracketIndex + 2);
if (!portPart || !/^\d+$/.test(portPart)) return { ipAddress: ip };
if (!portPart || !PORT_REGEX.test(portPart)) return { ipAddress: ip };
return { ipAddress: ipPart };
}
// Handle IPv4 with port (e.g. 1.2.3.4:1234)
if (ip.includes(":")) {
const [ipPart, portPart] = ip.split(":");
if (!portPart || !/^\d+$/.test(portPart)) return { ipAddress: ip };
if (!portPart || !PORT_REGEX.test(portPart)) return { ipAddress: ip };
return { ipAddress: ipPart };
}