All files / proxy/utils ip.ts

100% Statements 13/13
100% Branches 7/7
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 294x   4x   33x   1x 1x 1x       32x 32x 5x   5x 3x         29x       5x    
import { isIPv4, isIPv6 } from 'net'
 
export function stripPort(ip: string) {
  // Check if it's an IPv6 address with a port
  if (ip.startsWith('[')) {
    // IPv6 address with port
    const closingBracketIndex = ip.indexOf(']')
    if (closingBracketIndex !== -1) {
      return ip.substring(1, closingBracketIndex)
    }
  } else {
    // IPv4 address with port or IPv6 without brackets
    const colonIndex = ip.lastIndexOf(':')
    if (colonIndex !== -1) {
      const ipWithoutPort = ip.substring(0, colonIndex)
      // Validate if the part before the colon is a valid IPv4 or IPv6 address
      if (isValidIp(ipWithoutPort)) {
        return ipWithoutPort
      }
    }
  }
  // If no port is found, return the original IP
  return ip
}
 
function isValidIp(ip: string) {
  return isIPv4(ip) || isIPv6(ip)
}