ipaddr.ts
This file
Path
src/utils/ipaddr.ts
374 lines · 9.3 KiB · TypeScript
Last changed by
fix(utils/ipaddr): avoid truncation on embedded IPv4 addresses in expandIPv6 (#5247)Nanasibefore adoptionc91ec9b
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–14why, one step back1/**2 * Utils for IP Addresses3 * @module4 */56import type { AddressType } from '../helper/conninfo'78/**9 * Expand IPv6 Address10 * @param ipV6 Shorten IPv6 Address11 * @return expanded IPv6 Address12 */13export const expandIPv6 = (ipV6: string): string => {14 const sections = ipV6.split(':')fix(utils/ipaddr): avoid truncation on embedded IPv4 addresses in expandIPv6 (#5247)Nanasibefore adoptionc91ec9b
lines 15–17why, one step back15 const lastSection = sections.at(-1) as string16 if (IPV4_REGEX.test(lastSection)) {17 const octets = lastSection.split('.').map(Number)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 18–20why, one step back18 sections.splice(19 -1,20 1,fix(utils/ipaddr): avoid truncation on embedded IPv4 addresses in expandIPv6 (#5247)Nanasibefore adoptionc91ec9b
lines 21–22why, one step back21 ((octets[0] << 8) | octets[1]).toString(16),22 ((octets[2] << 8) | octets[3]).toString(16)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 23–374why, one step back23 )24 }25 for (let i = 0; i < sections.length; i++) {26 const node = sections[i]27 if (node !== '') {28 sections[i] = node.padStart(4, '0')29 } else {30 // Keep a single empty slot for `::` zero expansion.31 while (sections[i + 1] === '') {32 sections.splice(i + 1, 1)33 }34 sections[i] = new Array(8 - sections.length + 1).fill('0000').join(':')35 }36 }37 return sections.join(':')38}3940const IPV4_OCTET_PART = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])'41const IPV4_REGEX = new RegExp(`^(?:${IPV4_OCTET_PART}\\.){3}${IPV4_OCTET_PART}$`)42export const INVALID_IP_ADDRESS_ERROR_CODE = 'ERR_INVALID_IP_ADDRESS'43export type InvalidIPAddressError = TypeError & {44 code: typeof INVALID_IP_ADDRESS_ERROR_CODE45}46const CHAR_CODE_0 = 4847const CHAR_CODE_9 = 5748const CHAR_CODE_A = 6549const CHAR_CODE_F = 7050const CHAR_CODE_a = 9751const CHAR_CODE_f = 10252const CHAR_CODE_DOT = 4653const CHAR_CODE_COLON = 5854const CHAR_CODE_PERCENT = 375556/**57 * Distinct Remote Addr58 * @param remoteAddr Remote Addr59 */60export const distinctRemoteAddr = (remoteAddr: string): AddressType => {61 if (IPV4_REGEX.test(remoteAddr)) {62 return 'IPv4'63 }64 if (remoteAddr.includes(':')) {65 // Domain can't include `:`66 return 'IPv6'67 }68}6970const createInvalidIPAddressError = (message: string): InvalidIPAddressError => {71 const error = new TypeError(message) as InvalidIPAddressError72 error.code = INVALID_IP_ADDRESS_ERROR_CODE73 return error74}7576const throwInvalidIPv4Address = (ipv4: string): never => {77 throw createInvalidIPAddressError(`Invalid IPv4 address: ${ipv4}`)78}7980const throwInvalidIPv6Address = (ipv6: string): never => {81 throw createInvalidIPAddressError(`Invalid IPv6 address: ${ipv6}`)82}8384const parseIPv4ToBinary = (85 ipv4: string,86 start: number,87 end: number,88 onInvalid: () => never89): bigint => {90 let result = 0n91 let octets = 092 let octet = 093 let digits = 094 let firstDigit = 09596 for (let i = start; i <= end; i++) {97 const code = i < end ? ipv4.charCodeAt(i) : CHAR_CODE_DOT98 if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) {99 if (digits === 0) {100 firstDigit = code101 } else if (firstDigit === CHAR_CODE_0) {102 onInvalid()103 }104 octet = octet * 10 + code - CHAR_CODE_0105 if (octet > 255) {106 onInvalid()107 }108 digits++109 continue110 }111112 if (code !== CHAR_CODE_DOT || digits === 0 || octets === 4) {113 onInvalid()114 }115116 result = (result << 8n) + BigInt(octet)117 octets++118 octet = 0119 digits = 0120 }121122 if (octets !== 4) {123 onInvalid()124 }125126 return result127}128129const parseIPv6HexCode = (code: number): number => {130 if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) {131 return code - CHAR_CODE_0132 }133 if (code >= CHAR_CODE_A && code <= CHAR_CODE_F) {134 return code - CHAR_CODE_A + 10135 }136 if (code >= CHAR_CODE_a && code <= CHAR_CODE_f) {137 return code - CHAR_CODE_a + 10138 }139 return -1140}141142const isIPv6LinkLocal = (ipv6binary: bigint): boolean => ipv6binary >> 118n === 0x3fan143144/**145 * Convert IPv4 to Uint8Array146 * @param ipv4 IPv4 Address147 * @returns BigInt148 */149export const convertIPv4ToBinary = (ipv4: string): bigint => {150 return parseIPv4ToBinary(ipv4, 0, ipv4.length, () => throwInvalidIPv4Address(ipv4))151}152153/**154 * Convert IPv6 to Uint8Array155 * @param ipv6 IPv6 Address156 * @returns BigInt157 */158export const convertIPv6ToBinary = (ipv6: string): bigint => {159 const length = ipv6.length160 const sections: number[] = []161 let hasZoneId = false162 let compressAt = -1163 let index = 0164165 if (length === 0) {166 throwInvalidIPv6Address(ipv6)167 }168169 while (index < length) {170 if (sections.length > 8) {171 throwInvalidIPv6Address(ipv6)172 }173174 let code = ipv6.charCodeAt(index)175176 if (code === CHAR_CODE_PERCENT) {177 if (index + 1 === length) {178 throwInvalidIPv6Address(ipv6)179 }180 hasZoneId = true181 break182 }183184 if (code === CHAR_CODE_COLON) {185 if (index + 1 < length && ipv6.charCodeAt(index + 1) === CHAR_CODE_COLON) {186 if (compressAt !== -1) {187 throwInvalidIPv6Address(ipv6)188 }189 compressAt = sections.length190 index += 2191 continue192 }193 throwInvalidIPv6Address(ipv6)194 }195196 let value = 0197 let digits = 0198 const sectionStart = index199200 while (index < length) {201 code = ipv6.charCodeAt(index)202 const hex = parseIPv6HexCode(code)203 if (hex === -1) {204 break205 }206 if (digits === 4) {207 throwInvalidIPv6Address(ipv6)208 }209 value = (value << 4) | hex210 digits++211 index++212 }213214 if (index < length && ipv6.charCodeAt(index) === CHAR_CODE_DOT) {215 let ipv4End = length216 for (let i = index; i < length; i++) {217 if (ipv6.charCodeAt(i) === CHAR_CODE_PERCENT) {218 if (i + 1 === length) {219 throwInvalidIPv6Address(ipv6)220 }221 hasZoneId = true222 ipv4End = i223 break224 }225 }226 const ipv4 = parseIPv4ToBinary(ipv6, sectionStart, ipv4End, () =>227 throwInvalidIPv6Address(ipv6)228 )229 sections.push(Number((ipv4 >> 16n) & 0xffffn), Number(ipv4 & 0xffffn))230 index = length231 break232 }233234 if (digits === 0) {235 throwInvalidIPv6Address(ipv6)236 }237238 sections.push(value)239240 if (index === length) {241 break242 }243244 code = ipv6.charCodeAt(index)245 if (code === CHAR_CODE_PERCENT) {246 if (index + 1 === length) {247 throwInvalidIPv6Address(ipv6)248 }249 hasZoneId = true250 break251 }252253 if (code !== CHAR_CODE_COLON) {254 throwInvalidIPv6Address(ipv6)255 }256257 if (index + 1 < length && ipv6.charCodeAt(index + 1) === CHAR_CODE_COLON) {258 if (compressAt !== -1) {259 throwInvalidIPv6Address(ipv6)260 }261 compressAt = sections.length262 index += 2263 continue264 }265266 index++267 if (index === length) {268 throwInvalidIPv6Address(ipv6)269 }270 }271272 if (compressAt === -1 ? sections.length !== 8 : sections.length >= 8) {273 throwInvalidIPv6Address(ipv6)274 }275276 let result = 0n277 const zeros = compressAt === -1 ? 0 : 8 - sections.length278 const firstSectionEnd = compressAt === -1 ? sections.length : compressAt279 for (let i = 0; i < firstSectionEnd; i++) {280 result <<= 16n281 result += BigInt(sections[i])282 }283 for (let i = 0; i < zeros; i++) {284 result <<= 16n285 }286 for (let i = firstSectionEnd; i < sections.length; i++) {287 result <<= 16n288 result += BigInt(sections[i])289 }290 if (hasZoneId && !isIPv6LinkLocal(result)) {291 throwInvalidIPv6Address(ipv6)292 }293 return result294}295296/**297 * Convert a binary representation of an IPv4 address to a string.298 * @param ipV4 binary IPv4 Address299 * @return IPv4 Address in string300 */301export const convertIPv4BinaryToString = (ipV4: bigint): string => {302 const sections = []303 for (let i = 0; i < 4; i++) {304 sections.push((ipV4 >> BigInt(8 * (3 - i))) & 0xffn)305 }306 return sections.join('.')307}308309/**310 * Check if a binary IPv6 address is an IPv4-mapped IPv6 address (::ffff:x.x.x.x)311 * @param ipv6binary binary IPv6 Address312 * @return true if the address is an IPv4-mapped IPv6 address313 */314export const isIPv4MappedIPv6 = (ipv6binary: bigint): boolean => ipv6binary >> 32n === 0xffffn315316/**317 * Extract the IPv4 portion from an IPv4-mapped IPv6 address318 * @param ipv6binary binary IPv4-mapped IPv6 Address319 * @return binary IPv4 Address320 */321export const convertIPv4MappedIPv6ToIPv4 = (ipv6binary: bigint): bigint => ipv6binary & 0xffffffffn322323/**324 * Convert a binary representation of an IPv6 address to a string.325 * @param ipV6 binary IPv6 Address326 * @return normalized IPv6 Address in string327 */328export const convertIPv6BinaryToString = (ipV6: bigint): string => {329 if (ipV6 === 0n) {330 // The unspecified address compresses every group, which the generic331 // logic below would render as a single ":". Handle it explicitly.332 return '::'333 }334335 if (isIPv4MappedIPv6(ipV6)) {336 return `::ffff:${convertIPv4BinaryToString(convertIPv4MappedIPv6ToIPv4(ipV6))}`337 }338339 const sections = []340 for (let i = 0; i < 8; i++) {341 sections.push(((ipV6 >> BigInt(16 * (7 - i))) & 0xffffn).toString(16))342 }343344 let currentZeroStart = -1345 let maxZeroStart = -1346 let maxZeroEnd = -1347 for (let i = 0; i < 8; i++) {348 if (sections[i] === '0') {349 if (currentZeroStart === -1) {350 currentZeroStart = i351 }352 } else {353 if (currentZeroStart > -1) {354 if (i - currentZeroStart > maxZeroEnd - maxZeroStart) {355 maxZeroStart = currentZeroStart356 maxZeroEnd = i357 }358 currentZeroStart = -1359 }360 }361 }362 if (currentZeroStart > -1) {363 if (8 - currentZeroStart > maxZeroEnd - maxZeroStart) {364 maxZeroStart = currentZeroStart365 maxZeroEnd = 8366 }367 }368 // RFC 5952 4.2.2: compress only zero runs of at least two 16-bit fields.369 if (maxZeroStart !== -1 && maxZeroEnd - maxZeroStart > 1) {370 sections.splice(maxZeroStart, maxZeroEnd - maxZeroStart, ':')371 }372373 return sections.join(':').replace(/:{2,}/g, '::')374}