//! Which saved logins belong to the site asking: the registrable domain, by //! the Public Suffix List, never a substring. //! //! ```text //! host_of("https://Login.Example.co.uk:8443/x") → "login.example.co.uk" //! registrable("login.example.co.uk") → "example.co.uk" //! site_match("example.co.uk", "https://login.example.co.uk/") → Match::SameSite //! ``` //! //! The rule is the one browsers keep for passwords: a login saved for a host //! fills on that host ([`Match::Exact`]) and on any host of the same //! registrable domain ([`Match::SameSite`]), the domain one label under its //! public suffix (`example.co.uk`, `alice.github.io`). `examp1e.com`, //! `example.com.evil.test` and `notexample.com` never match `example.com`. An //! IP address or a single-label host (`localhost`) matches only itself. A //! host that IS a public suffix (`co.uk`, `github.io`) has no registrable //! domain and matches only itself, exactly. //! //! The list is bundled ([`PUBLIC_SUFFIX_LIST`], ICANN and private sections), //! its internationalised rules read as their ASCII (punycode) spelling, and a //! host is lower-cased and taken to ASCII the same way before it is matched. /// The Public Suffix List, rules only. pub const PUBLIC_SUFFIX_LIST: &str = include_str!("public_suffix_list.dat"); /// How a saved site stands to the site asking. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum Match { /// The same host. Exact, /// Another host of the same registrable domain. SameSite, } struct Rules { normal: std::collections::HashSet, wildcard: std::collections::HashSet, exception: std::collections::HashSet, } fn rules() -> &'static Rules { static RULES: std::sync::OnceLock = std::sync::OnceLock::new(); RULES.get_or_init(|| { let mut out = Rules { normal: Default::default(), wildcard: Default::default(), exception: Default::default() }; for line in PUBLIC_SUFFIX_LIST.lines() { let line = line.trim(); if line.is_empty() || line.starts_with("//") { continue; } if let Some(rest) = line.strip_prefix('!') { if let Some(ascii) = ascii_domain(rest) { out.exception.insert(ascii); } } else if let Some(rest) = line.strip_prefix("*.") { if let Some(ascii) = ascii_domain(rest) { out.wildcard.insert(ascii); } } else if let Some(ascii) = ascii_domain(line) { out.normal.insert(ascii); } } out }) } fn ascii_domain(text: &str) -> Option { if text.is_ascii() { return Some(text.to_ascii_lowercase()); } match url::Host::parse(text) { Ok(url::Host::Domain(domain)) => Some(domain), _ => None, } } /// The host a saved site or an address names: lower case, ASCII, no port, /// no trailing dot. `None` when there is no host to read. pub fn host_of(site: &str) -> Option { let site = site.trim(); if site.is_empty() { return None; } let with_scheme = if site.contains("://") { site.to_string() } else { format!("https://{site}") }; let parsed = url::Url::parse(&with_scheme).ok()?; let host = match parsed.host()? { url::Host::Domain(domain) => domain.trim_end_matches('.').to_ascii_lowercase(), url::Host::Ipv4(ip) => ip.to_string(), url::Host::Ipv6(ip) => format!("[{ip}]"), }; (!host.is_empty()).then_some(host) } fn is_ip(host: &str) -> bool { host.starts_with('[') || host.parse::().is_ok() } /// The public suffix of a host (`co.uk` for `a.example.co.uk`); a host no /// rule names takes its last label (the list's `*` default rule). pub fn public_suffix(host: &str) -> Option { if is_ip(host) { return None; } let labels: Vec<&str> = host.split('.').collect(); let rules = rules(); // The longest rule that applies wins; an exception rule beats all. for at in 0..labels.len() { let candidate = labels[at..].join("."); if rules.exception.contains(&candidate) { return Some(labels[at + 1..].join(".")); } if rules.normal.contains(&candidate) { return Some(candidate); } if at + 1 < labels.len() && rules.wildcard.contains(&labels[at + 1..].join(".")) { return Some(candidate); } } labels.last().map(|label| label.to_string()) } /// The registrable domain of a host: its public suffix and one label more. /// `None` for an IP address, a single label, or a host that is a suffix. pub fn registrable(host: &str) -> Option { let suffix = public_suffix(host)?; if host == suffix { return None; } let rest = host.strip_suffix(&suffix)?.strip_suffix('.')?; let label = rest.rsplit('.').next()?; Some(format!("{label}.{suffix}")) } /// How the login saved for `saved` stands to the site `asking`, if it fills there. pub fn site_match(saved: &str, asking: &str) -> Option { let (saved, asking) = (host_of(saved)?, host_of(asking)?); if saved == asking { return Some(Match::Exact); } let saved_domain = registrable(&saved)?; (registrable(&asking)? == saved_domain).then_some(Match::SameSite) } #[cfg(test)] #[path = "domain_tests.rs"] mod tests;