Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/browser/src/helpers/isValidDomain.test.ts
Original file line number Diff line number Diff line change
@@ -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'));
});
5 changes: 3 additions & 2 deletions packages/browser/src/helpers/isValidDomain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
);
}