Skip to content

Commit

Permalink
use domainToASCII(str) instead of new URL(str).hostName (#433)
Browse files Browse the repository at this point in the history
We don't need to parse the full URL
  • Loading branch information
wjhsf committed Jul 23, 2024
1 parent a909090 commit 9b22690
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 8 additions & 0 deletions lib/__tests__/canonicalDomain.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down
5 changes: 3 additions & 2 deletions lib/cookie/canonicalDomain.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 9b22690

Please sign in to comment.