From 9b226902d86c64ef85c2808673cf7cfa966587d4 Mon Sep 17 00:00:00 2001 From: Will Harney <62956339+wjhsf@users.noreply.github.com> Date: Tue, 23 Jul 2024 10:03:26 -0400 Subject: [PATCH] use `domainToASCII(str)` instead of `new URL(str).hostName` (#433) We don't need to parse the full URL --- lib/__tests__/canonicalDomain.spec.ts | 8 ++++++++ lib/cookie/canonicalDomain.ts | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/__tests__/canonicalDomain.spec.ts b/lib/__tests__/canonicalDomain.spec.ts index caadc82a..40a9057e 100644 --- a/lib/__tests__/canonicalDomain.spec.ts +++ b/lib/__tests__/canonicalDomain.spec.ts @@ -38,6 +38,14 @@ describe('canonicalDomain', () => { input: 'δοκιμή.δοκιμή', output: 'xn--jxalpdlp.xn--jxalpdlp', }, + + { description: 'simple IPv6', input: '::1', output: '::1' }, + { + description: 'full IPv6', + input: '[::ffff:127.0.0.1]', + output: '::ffff:7f00:1', + }, + { description: 'invalid domain', input: 'NOTATLD', output: 'notatld' }, ])('$description: $input → $output', ({ input, output }) => { expect(canonicalDomain(input)).toBe(output) }) diff --git a/lib/cookie/canonicalDomain.ts b/lib/cookie/canonicalDomain.ts index 2b7830ec..67179d21 100644 --- a/lib/cookie/canonicalDomain.ts +++ b/lib/cookie/canonicalDomain.ts @@ -1,5 +1,6 @@ import { IP_V6_REGEX_OBJECT } from './constants' import type { Nullable } from '../utils' +import { domainToASCII } from 'node:url' /** * Transforms a domain name into a canonical domain name. The canonical domain name is a domain name @@ -47,13 +48,13 @@ export function canonicalDomain( if (!str.endsWith(']')) { str = str + ']' } - return new URL(`http://${str}`).hostname.slice(1, -1) // remove [ and ] + return domainToASCII(str).slice(1, -1) // remove [ and ] } // convert to IDN if any non-ASCII characters // eslint-disable-next-line no-control-regex if (/[^\u0001-\u007f]/.test(str)) { - return new URL(`http://${str}`).hostname + return domainToASCII(str) } // ASCII-only domain - not canonicalized with new URL() because it may be a malformed URL