/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * eTLD+1 (registrable domain) resolution backed by a vendored Public Suffix * List snapshot (ICANN + PRIVATE sections), with no npm dependency. * * Implements the formal PSL algorithm (https://github.com/publicsuffix/list/wiki/Format): * normal rules, wildcard rules (`*.ck`) and exception rules (`!www.ck`), with * the implicit `*` default rule for unlisted TLDs. Hosts are normalised through * WHATWG `URL` (lowercase, IDN to punycode), trailing dots are removed and IP * literals are returned as-is. * * Usage: * registrableDomain("https://a.b.example.co.uk/x"); // "example.co.uk" * registrableDomain("foo.github.io"); // "foo.github.io" * registrableDomain("[::1]"); // "[::1]" */ import { domainToASCII } from "node:url"; import { PUBLIC_SUFFIX_ICANN_RULES, PUBLIC_SUFFIX_PRIVATE_RULES, } from "./data/public-suffix-list.ts"; export { PUBLIC_SUFFIX_LIST_COMMIT, PUBLIC_SUFFIX_LIST_FETCHED_AT, PUBLIC_SUFFIX_LIST_SOURCE, PUBLIC_SUFFIX_LIST_VERSION, } from "./data/public-suffix-list.ts"; export interface DomainOptions { /** * Include the PRIVATE section (github.io, blogspot.com, ...). Default `true`: * two tenants of a shared hosting suffix are distinct sites for crawling. */ allowPrivateDomains?: boolean; } const EXACT_ICANN = 1; const EXACT_PRIVATE = 2; const WILDCARD_ICANN = 4; const WILDCARD_PRIVATE = 8; const EXCEPTION_ICANN = 16; const EXCEPTION_PRIVATE = 32; /** * Suffix -> rule flags. Every proper suffix of a rule is also present (flag * `0` when it is not itself a rule) so a lookup can stop at the first miss, * which makes the map behave as a reversed-label trie. */ let ruleIndex: Map | undefined; function toAsciiRule(rule: string): string { // biome-ignore lint/suspicious/noControlCharactersInRegex: ASCII range check. // eslint-disable-next-line no-control-regex if (!/[^\x00-\x7f]/.test(rule)) return rule.toLowerCase(); return domainToASCII(rule) || rule.toLowerCase(); } function addRules(index: Map, data: string, isPrivate: boolean): void { for (const line of data.split("\n")) { if (!line) continue; let flag: number; let suffix: string; if (line.startsWith("!")) { flag = isPrivate ? EXCEPTION_PRIVATE : EXCEPTION_ICANN; suffix = toAsciiRule(line.slice(1)); } else if (line.startsWith("*.")) { flag = isPrivate ? WILDCARD_PRIVATE : WILDCARD_ICANN; suffix = toAsciiRule(line.slice(2)); } else { flag = isPrivate ? EXACT_PRIVATE : EXACT_ICANN; suffix = toAsciiRule(line); } index.set(suffix, (index.get(suffix) ?? 0) | flag); let dot = suffix.indexOf("."); while (dot !== -1) { const parent = suffix.slice(dot + 1); if (!index.has(parent)) index.set(parent, 0); dot = suffix.indexOf(".", dot + 1); } } } function rules(): Map { if (!ruleIndex) { const index = new Map(); addRules(index, PUBLIC_SUFFIX_ICANN_RULES, false); addRules(index, PUBLIC_SUFFIX_PRIVATE_RULES, true); ruleIndex = index; } return ruleIndex; } const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/; /** Already-normalised hostname whose last label is not numeric (IPv4-like). */ const PLAIN_HOST_RE = /^[a-z0-9._-]*[a-z_][a-z0-9_-]*\.*$/; /** True for IPv4 dotted quads and bracketed or bare IPv6 literals. */ export function isIpAddress(host: string): boolean { if (IPV4_RE.test(host)) return true; if (host.startsWith("[") && host.endsWith("]")) return true; return host.includes(":") && /^[0-9a-f:.]+$/i.test(host); } /** * Normalise a hostname or URL to a lowercase ASCII hostname without trailing * dots. IPv6 literals are returned bracketed (`[::1]`), matching `URL.hostname`. * Unparseable input is returned lowercased and trimmed. */ export function normalizeHostname(hostOrUrl: string): string { let input = hostOrUrl.trim(); if (!input) return ""; if (!input.includes("://")) { // Fast path: already a plain lowercase hostname. if (PLAIN_HOST_RE.test(input)) return input.replace(/\.+$/, ""); // Bare IPv6 (`::1`, `2001:db8::1`): bracket it so `URL` accepts it. if (!input.startsWith("[") && input.split(":").length > 2) { input = `[${input}]`; } input = `http://${input}`; } try { return new URL(input).hostname.replace(/\.+$/, ""); } catch { return hostOrUrl.trim().toLowerCase().replace(/\.+$/, ""); } } /** * Number of labels of `labels` that form the public suffix, or `-1` when the * input has empty labels. */ function publicSuffixLabelCount(labels: string[], allowPrivate: boolean): number { const exactMask = allowPrivate ? EXACT_ICANN | EXACT_PRIVATE : EXACT_ICANN; const wildcardMask = allowPrivate ? WILDCARD_ICANN | WILDCARD_PRIVATE : WILDCARD_ICANN; const exceptionMask = allowPrivate ? EXCEPTION_ICANN | EXCEPTION_PRIVATE : EXCEPTION_ICANN; if (labels.includes("")) return -1; const index = rules(); const n = labels.length; // Default rule `*`: the rightmost label is a public suffix. let longest = 1; let exception = 0; let suffix = ""; for (let k = 1; k <= n; k++) { const label = labels[n - k]; suffix = k === 1 ? label : `${label}.${suffix}`; const flags = index.get(suffix); if (flags === undefined) break; if (flags & exceptionMask) exception = k; if (flags & exactMask && k > longest) longest = k; if (flags & wildcardMask && k + 1 <= n && k + 1 > longest) longest = k + 1; } // An exception rule prevails; its public suffix drops the leftmost label. return exception > 0 ? exception - 1 : longest; } /** * Public suffix (eTLD) of a hostname or URL, e.g. `co.uk` for * `a.example.co.uk`. IP literals and single-label hosts are returned as-is. */ export function publicSuffix(hostOrUrl: string, options: DomainOptions = {}): string { const host = normalizeHostname(hostOrUrl); if (!host || isIpAddress(host)) return host; const labels = host.split("."); const count = publicSuffixLabelCount(labels, options.allowPrivateDomains ?? true); if (count < 0) return host; return labels.slice(labels.length - count).join("."); } /** * Strict eTLD+1: the registrable domain, or `null` when the host is itself a * public suffix, an IP literal, a single label or malformed (PSL test-suite * semantics). */ export function getRegistrableDomain( hostOrUrl: string, options: DomainOptions = {}, ): string | null { const host = normalizeHostname(hostOrUrl); if (!host || isIpAddress(host)) return null; const labels = host.split("."); const count = publicSuffixLabelCount(labels, options.allowPrivateDomains ?? true); if (count < 0 || count >= labels.length) return null; return labels.slice(labels.length - count - 1).join("."); } /** * Lenient eTLD+1 used as a grouping key: the registrable domain when there is * one, otherwise the normalised host itself (IP literals, `localhost`, bare * public suffixes such as `github.io`, malformed hosts). */ export function registrableDomain(hostOrUrl: string, options: DomainOptions = {}): string { const host = normalizeHostname(hostOrUrl); if (!host || isIpAddress(host)) return host; const labels = host.split("."); const count = publicSuffixLabelCount(labels, options.allowPrivateDomains ?? true); if (count < 0 || count >= labels.length) return host; return labels.slice(labels.length - count - 1).join("."); }