From 630fd874ce3cf45ee17f7b6c7d51572c6440f4e7 Mon Sep 17 00:00:00 2001 From: Dmitry Shirokov Date: Thu, 30 Jul 2026 12:06:07 +1000 Subject: [PATCH] fix(core): replace net dependency with local ip checks --- src/ip.test.ts | 2 +- src/ip.ts | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/ip.test.ts b/src/ip.test.ts index 1dc7fc8..9caa31e 100644 --- a/src/ip.test.ts +++ b/src/ip.test.ts @@ -103,7 +103,7 @@ describe('lib/ip', () => { it('should work fine for IPv4', () => { assert.strictEqual(ip.validate('64.4.4.4'), true); assert.strictEqual(ip.validate('64.4.4.boom!'), false); - // @ts-ignore + // @ts-expect-error assert.strictEqual(ip.validate(undefined), false); assert.strictEqual(ip.validate('kraken'), false); }); diff --git a/src/ip.ts b/src/ip.ts index ece598d..322b065 100755 --- a/src/ip.ts +++ b/src/ip.ts @@ -1,4 +1,23 @@ -import net from 'net'; +// Borrowed from https://github.com/nodejs/node/blob/main/lib/internal/net.js +// IPv4 Segment +const v4Seg = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'; +const v4Str = `(?:${v4Seg}\\.){3}${v4Seg}`; +const IPv4Reg = new RegExp(`^${v4Str}$`); + +// IPv6 Segment +const v6Seg = '(?:[0-9a-fA-F]{1,4})'; +const IPv6Reg = new RegExp( + '^(?:' + + `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + + `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + + `(?:${v6Seg}:){5}(?::${v4Str}|(?::${v6Seg}){1,2}|:)|` + + `(?:${v6Seg}:){4}(?:(?::${v6Seg}){0,1}:${v4Str}|(?::${v6Seg}){1,3}|:)|` + + `(?:${v6Seg}:){3}(?:(?::${v6Seg}){0,2}:${v4Str}|(?::${v6Seg}){1,4}|:)|` + + `(?:${v6Seg}:){2}(?:(?::${v6Seg}){0,3}:${v4Str}|(?::${v6Seg}){1,5}|:)|` + + `(?:${v6Seg}:){1}(?:(?::${v6Seg}){0,4}:${v4Str}|(?::${v6Seg}){1,6}|:)|` + + `(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + + ')(?:%[0-9a-zA-Z-.:]{1,})?$' +); const parseIPv4 = (input: string): number[] => { const ip = input.split('.', 4); @@ -69,10 +88,7 @@ const bitAt = (rawAddress: Buffer | number[], idx: number): number => { return (rawAddress[bufIdx] >>> bitIdx) & 1; }; -const validate = (ip: string): boolean => { - const version = net.isIP(ip); - return version === 4 || version === 6; -}; +const validate = (ip: string): boolean => IPv4Reg.test(ip) || IPv6Reg.test(ip); export default { bitAt,