diff --git a/packages/browser/src/helpers/isValidDomain.test.ts b/packages/browser/src/helpers/isValidDomain.test.ts new file mode 100644 index 00000000..389e14b1 --- /dev/null +++ b/packages/browser/src/helpers/isValidDomain.test.ts @@ -0,0 +1,26 @@ +import { assert, assertFalse } from '@std/assert'; +import { isValidDomain } from './isValidDomain.ts'; + +Deno.test('should handle localhost', () => { + assert(isValidDomain('localhost')); +}); + +Deno.test('should handle standard ASCII domains and labels', () => { + assert(isValidDomain('example.com')); + assert(isValidDomain('my-site.io')); + assert(isValidDomain('sub.example.co.uk')); + assertFalse(isValidDomain('notadomain')); + assertFalse(isValidDomain('')); +}); + +Deno.test('should handle punycode domains', () => { + // Punycode label with ascii domain + assert(isValidDomain('xn--5lwo46cp2i.co.jp')); + assert(isValidDomain('xn--5lwo46cp2i.jp')); + // Punycode label with punycode domain + assert(isValidDomain('xn--80akjhbed8ahk.xn--p1ai')); + // ASCII subdomain + assert(isValidDomain('login.xn--5lwo46cp2i.co.jp')); + // Punycode subdomain + assert(isValidDomain('xn--sub.xn--5lwo46cp2i.co.jp')); +}); diff --git a/packages/browser/src/helpers/isValidDomain.ts b/packages/browser/src/helpers/isValidDomain.ts index 22f045fd..3b03eee5 100644 --- a/packages/browser/src/helpers/isValidDomain.ts +++ b/packages/browser/src/helpers/isValidDomain.ts @@ -3,13 +3,14 @@ * * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain * - * Regex sourced from here: + * Regex was originally sourced from here, then remixed to add punycode support: * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html */ export function isValidDomain(hostname: string): boolean { return ( // Consider localhost valid as well since it's okay wrt Secure Contexts hostname === 'localhost' || - /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname) + // Support punycode (ACE) or ascii labels and domains + /^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(hostname) ); }