Skip to content
Myr

fix(utils/ipaddr): support IPv6-mapped IPv4 address (#3727)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Taku Amano · committed by GitHub · parent fc8fb0f · Browse files · 3 files+49 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+49 added−0 removed

  • tests:+22 added−0 removed
  • other:+27 added−0 removed

3 files+49 added−0 removed

modified:src/middleware/ip-restriction/index.test.ts+4 added
modified:src/utils/ipaddr.test.ts+18 added
modified:src/utils/ipaddr.ts+27 added
10 unmodified lines
11 * @return expanded IPv6 Address12 */13export const expandIPv6 = (ipV6: string): string => {14 const sections = ipV6.split(':')15 if (IPV4_REGEX.test(sections.at(-1) as string)) {16 sections.splice(17 -1,18 1,19 ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1) as string)) // => ::7f00:000120 .substring(2) // => 7f00:000121 .split(':') // => ['7f00', '0001']22 )23 }24 for (let i = 0; i < sections.length; i++) {25 const node = sections[i]26 if (node !== '') {27 sections[i] = node.padStart(4, '0')
51 unmodified lines
79 return result80}8182/**83 * Convert a binary representation of an IPv4 address to a string.84 * @param ipV4 binary IPv4 Address85 * @return IPv4 Address in string86 */87export const convertIPv4BinaryToString = (ipV4: bigint): string => {88 const sections = []89 for (let i = 0; i < 4; i++) {90 sections.push((ipV4 >> BigInt(8 * (3 - i))) & 0xffn)91 }92 return sections.join('.')93}9495/**96 * Convert a binary representation of an IPv6 address to a string.97 * @param ipV6 binary IPv6 Address98 * @return normalized IPv6 Address in string99 */100export const convertIPv6BinaryToString = (ipV6: bigint): string => {101 // IPv6-mapped IPv4 address102 if (ipV6 >> 32n === 0xffffn) {103 return `::ffff:${convertIPv4BinaryToString(ipV6 & 0xffffffffn)}`104 }105106 const sections = []107 for (let i = 0; i < 8; i++) {108 sections.push(((ipV6 >> BigInt(16 * (7 - i))) & 0xffffn).toString(16))109 }
31 unmodified lines