//! Site database: loading, format detection, merging and selection. pub mod categories; pub mod maigret; pub mod schema; pub mod sherlock; pub mod wmn; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use serde_json::Value; pub use schema::*; use crate::filter::Expr; pub const EMBEDDED_WMN: &str = include_str!("../../data/wmn-data.json"); pub const EMBEDDED_SHERLOCK: &str = include_str!("../../data/sherlock.json"); pub const EMBEDDED_MAIGRET: &str = include_str!("../../data/maigret.json"); pub const EMBEDDED_PERCIVAL: &str = include_str!("../../data/percival.json"); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Format { Wmn, Sherlock, Maigret, Percival, } impl Format { pub fn as_str(self) -> &'static str { match self { Format::Wmn => "whatsmyname", Format::Sherlock => "sherlock", Format::Maigret => "maigret", Format::Percival => "percival", } } } /// Percival's own database file format. #[derive(Debug, Default, Serialize, Deserialize)] pub struct PercivalFile { #[serde(default)] pub format: String, #[serde(default)] pub sites: Vec, /// Host → popularity rank, applied to every loaded site. #[serde(default)] pub ranks: BTreeMap, } impl PercivalFile { pub fn looks_like(v: &Value) -> bool { v.get("format").and_then(Value::as_str) == Some("percival") || matches!(v.get("sites"), Some(Value::Array(a)) if a.first().map(|s| s.get("detector").is_some()).unwrap_or(false)) } } /// Identify which upstream format a JSON document uses. pub fn detect_format(json: &str) -> Result { let v: Value = serde_json::from_str(json).context("not valid JSON")?; if PercivalFile::looks_like(&v) { Ok(Format::Percival) } else if maigret::looks_like(&v) { Ok(Format::Maigret) } else if wmn::looks_like(&v) { Ok(Format::Wmn) } else if sherlock::looks_like(&v) { Ok(Format::Sherlock) } else { bail!( "unrecognised site database format (expected WhatsMyName, Sherlock, Maigret or Percival JSON)" ) } } /// Parse any supported format. pub fn parse_any(json: &str) -> Result<(Format, Vec, BTreeMap)> { let format = detect_format(json)?; let (sites, ranks) = match format { Format::Wmn => (wmn::parse(json)?, BTreeMap::new()), Format::Sherlock => (sherlock::parse(json)?, BTreeMap::new()), Format::Maigret => (maigret::parse(json)?, BTreeMap::new()), Format::Percival => { let f: PercivalFile = serde_json::from_str(json).context("parsing Percival data")?; (f.sites, f.ranks) } }; Ok((format, sites, ranks)) } #[derive(Clone, Debug, Serialize)] pub struct SourceReport { pub source: Source, pub origin: String, pub format: &'static str, pub sites: usize, } #[derive(Clone, Debug, Default)] pub struct SiteDb { pub sites: Vec, pub reports: Vec, pub ranks: BTreeMap, pub overlay_disabled: usize, } #[derive(Clone, Debug)] pub struct LoadOptions { /// Built-in sources to load. pub sources: Vec, /// Extra database files (any supported format). pub extra: Vec, /// Whether the embedded databases are used at all. pub builtin: bool, /// Data directory holding updated databases and the self-check overlay. pub data_dir: Option, /// Ignore cached (updated) copies and use the embedded data. pub embedded_only: bool, } impl Default for LoadOptions { fn default() -> Self { LoadOptions { sources: Source::BUILTIN.to_vec(), extra: Vec::new(), builtin: true, data_dir: None, embedded_only: false, } } } /// Path of the cached copy of a built-in database. pub fn cache_path(data_dir: &Path, source: Source) -> PathBuf { data_dir .join("db") .join(format!("{}.json", source.as_str())) } /// Path of the self-check overlay file. pub fn overlay_path(data_dir: &Path) -> PathBuf { data_dir.join("disabled.json") } #[derive(Debug, Default, Serialize, Deserialize)] pub struct DisabledOverlay { #[serde(default)] pub generated: String, #[serde(default)] pub sites: BTreeMap, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DisabledEntry { pub reason: String, #[serde(default)] pub checked: String, } fn embedded(source: Source) -> &'static str { match source { Source::Wmn => EMBEDDED_WMN, Source::Sherlock => EMBEDDED_SHERLOCK, Source::Maigret => EMBEDDED_MAIGRET, Source::Percival => EMBEDDED_PERCIVAL, Source::Custom => "", } } /// Load, merge and finalise the site database. pub fn load(opts: &LoadOptions) -> Result { let mut groups: Vec> = Vec::new(); let mut reports = Vec::new(); let mut ranks: BTreeMap = BTreeMap::new(); if opts.builtin { for &source in &opts.sources { if source == Source::Custom { continue; } let mut origin = "embedded".to_string(); let mut text: Option = None; if !opts.embedded_only { if let Some(dir) = &opts.data_dir { let p = cache_path(dir, source); if p.is_file() { match std::fs::read_to_string(&p) { Ok(t) => { origin = p.display().to_string(); text = Some(t); } Err(e) => tracing::warn!("cannot read {}: {e}", p.display()), } } } } let owned; let json: &str = match &text { Some(t) => t.as_str(), None => { owned = embedded(source); owned } }; if json.is_empty() { continue; } let (format, mut sites, r) = match parse_any(json) { Ok(x) => x, Err(e) if text.is_some() => { tracing::warn!( "cached {source} database is unusable ({e}); falling back to embedded copy" ); let (f, s, r) = parse_any(embedded(source))?; origin = "embedded (cache unusable)".to_string(); (f, s, r) } Err(e) => { return Err(e).with_context(|| format!("loading embedded {source} database")); } }; for s in &mut sites { if s.source == Source::Custom { s.source = source; } } ranks.extend(r); reports.push(SourceReport { source, origin, format: format.as_str(), sites: sites.len(), }); groups.push(sites); } } for path in &opts.extra { let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; let (format, mut sites, r) = parse_any(&text).with_context(|| format!("parsing {}", path.display()))?; for s in &mut sites { // Sites from user files always take precedence over built-ins. s.source = Source::Custom; } ranks.extend(r); reports.push(SourceReport { source: Source::Custom, origin: path.display().to_string(), format: format.as_str(), sites: sites.len(), }); groups.push(sites); } let mut sites = merge(groups); apply_ranks(&mut sites, &ranks); let mut overlay_disabled = 0; if let Some(dir) = &opts.data_dir { let p = overlay_path(dir); if p.is_file() { if let Ok(text) = std::fs::read_to_string(&p) { if let Ok(overlay) = serde_json::from_str::(&text) { for s in &mut sites { if let Some(entry) = overlay.sites.get(&s.name) { if !s.disabled { overlay_disabled += 1; } s.disabled = true; s.disabled_reason = Some(format!("self-check: {}", entry.reason)); } } } } } } for s in &mut sites { s.finalize(); } sites.sort_by(|a, b| { a.rank .unwrap_or(u32::MAX) .cmp(&b.rank.unwrap_or(u32::MAX)) .then_with(|| { a.name .to_ascii_lowercase() .cmp(&b.name.to_ascii_lowercase()) }) }); Ok(SiteDb { sites, reports, ranks, overlay_disabled, }) } fn apply_ranks(sites: &mut [Site], ranks: &BTreeMap) { if ranks.is_empty() { return; } for s in sites { let host = s.host(); let probe_host = s.probe_host(); let candidates = [host.as_str(), probe_host.as_str()]; for host in candidates { if host.is_empty() { continue; } // Exact host, then parent domains (api.github.com → github.com). let mut h = host; loop { if let Some(r) = ranks.get(h) { s.rank = Some(s.rank.map_or(*r, |cur| cur.min(*r))); break; } match h.find('.') { Some(i) if h[i + 1..].contains('.') => h = &h[i + 1..], _ => break, } } } } } /// Merge site lists from several databases, collapsing duplicates. pub fn merge(groups: Vec>) -> Vec { let mut by_key: HashMap = HashMap::new(); let mut out: Vec = Vec::new(); for group in groups { for mut site in group { site.finalize(); let keys = [site.dedupe_key(), site.probe_key()]; let existing = keys.iter().find_map(|k| by_key.get(k).copied()); match existing { Some(idx) => { let (keep, other) = if site.source.priority() < out[idx].source.priority() { let old = std::mem::replace(&mut out[idx], site); (idx, old) } else { (idx, site) }; absorb(&mut out[keep], other); let k2 = out[keep].dedupe_key(); let k3 = out[keep].probe_key(); by_key.insert(k2, keep); by_key.insert(k3, keep); } None => { let idx = out.len(); for k in keys { by_key.insert(k, idx); } out.push(site); } } } } // Unique names. let mut seen: HashMap = HashMap::new(); for s in &mut out { let key = s.name.to_ascii_lowercase(); let n = seen.entry(key).or_insert(0); *n += 1; if *n > 1 { s.name = format!("{} ({})", s.name, s.source.as_str()); } } out } /// Fold knowledge from a lower-priority duplicate into the kept site. fn absorb(keep: &mut Site, other: Site) { if other.probe_key() != keep.probe_key() && !keep .alternates .iter() .any(|a| a.probe_key() == other.probe_key()) { let mut alt = other.clone(); alt.alternates.clear(); keep.alternates.push(alt); } for k in other.known { if !keep.known.iter().any(|x| x.eq_ignore_ascii_case(&k)) { keep.known.push(k); } } if keep.unclaimed.is_none() { keep.unclaimed = other.unclaimed; } if keep.username_regex.is_none() { keep.username_regex = other.username_regex; } if keep.rank.is_none() || other .rank .is_some_and(|r| r < keep.rank.unwrap_or(u32::MAX)) { keep.rank = other.rank.or(keep.rank); } if keep.home.is_none() { keep.home = other.home; } if keep.category == "misc" && other.category != "misc" { keep.category = other.category.clone(); } for t in other.tags { if !keep.tags.contains(&t) { keep.tags.push(t); } } for p in other.protection { if !keep.protection.contains(&p) { keep.protection.push(p); } } keep.nsfw |= other.nsfw; if keep.pretty_url.is_none() && other.pretty_url.is_some() && other.pretty_url.as_deref() != Some(keep.url.as_str()) { keep.pretty_url = other.pretty_url; } } /// Which sites take part in a scan. #[derive(Clone, Debug, Default)] pub struct Selection { pub categories: Vec, pub tags: Vec, pub include: Vec, pub exclude: Vec, pub sources: Vec, pub filter: Option, pub all_sites: bool, pub top: Option, pub nsfw: bool, pub include_disabled: bool, pub id_type: String, } impl Selection { pub fn usernames() -> Self { Selection { nsfw: true, id_type: "username".into(), ..Default::default() } } pub fn emails() -> Self { Selection { nsfw: true, id_type: "email".into(), ..Default::default() } } } fn ci_contains(hay: &str, needle: &str) -> bool { hay.to_ascii_lowercase() .contains(&needle.to_ascii_lowercase()) } impl SiteDb { /// Apply a selection and return the matching sites (rank order). pub fn select(&self, sel: &Selection) -> Vec { let mut out: Vec = self .sites .iter() .filter(|s| { if !sel.id_type.is_empty() && s.id_type != sel.id_type { return false; } if s.disabled && !sel.include_disabled { return false; } if s.nsfw && !sel.nsfw { return false; } if !sel.all_sites && s.source == Source::Maigret && s.rank.is_none() { return false; } if !sel.sources.is_empty() && !sel.sources.contains(&s.source) { return false; } if !sel.categories.is_empty() && !sel.categories.iter().any(|c| { s.category.eq_ignore_ascii_case(c) || s.tags.iter().any(|t| t.eq_ignore_ascii_case(c)) }) { return false; } if !sel.tags.is_empty() && !sel .tags .iter() .any(|t| s.tags.iter().any(|x| x.eq_ignore_ascii_case(t))) { return false; } if !sel.include.is_empty() && !sel.include.iter().any(|n| { ci_contains(&s.name, n) || ci_contains(&s.host(), n) || ci_contains(&s.probe_host(), n) }) { return false; } if sel .exclude .iter() .any(|n| ci_contains(&s.name, n) || ci_contains(&s.host(), n)) { return false; } if let Some(f) = &sel.filter { if !f.matches(s) { return false; } } true }) .cloned() .collect(); if let Some(n) = sel.top { out.truncate(n); } out } /// Look up one site by exact (case-insensitive) name. pub fn get(&self, name: &str) -> Option<&Site> { self.sites .iter() .find(|s| s.name.eq_ignore_ascii_case(name)) } pub fn count_by_source(&self) -> BTreeMap { let mut m = BTreeMap::new(); for s in &self.sites { *m.entry(s.source).or_insert(0) += 1; } m } pub fn count_by_category(&self) -> BTreeMap { let mut m = BTreeMap::new(); for s in &self.sites { *m.entry(s.category.clone()).or_insert(0) += 1; } m } } #[cfg(test)] mod tests { use super::*; fn s(name: &str, url: &str, pretty: Option<&str>, source: Source) -> Site { Site { name: name.into(), url: url.into(), pretty_url: pretty.map(String::from), source, ..Default::default() } } #[test] fn merges_duplicates_by_display_url() { let a = Site { known: vec!["x".into()], ..s( "GitHub", "https://api.github.com/users/{account}", Some("https://github.com/{account}"), Source::Wmn, ) }; let b = Site { rank: Some(9), known: vec!["blue".into()], ..s("GitHub", "https://github.com/{}", None, Source::Maigret) }; let c = s( "Other", "https://other.example/{account}", None, Source::Sherlock, ); let merged = merge(vec![vec![a], vec![b], vec![c]]); assert_eq!(merged.len(), 2); let gh = merged.iter().find(|x| x.name == "GitHub").unwrap(); assert_eq!(gh.source, Source::Wmn); assert_eq!(gh.rank, Some(9)); assert_eq!(gh.known.len(), 2); } #[test] fn unique_names_and_custom_priority() { let a = s("Same", "https://a.example/{account}", None, Source::Maigret); let b = s("Same", "https://b.example/{account}", None, Source::Wmn); let c = Site { category: "coding".into(), ..s("Same", "https://a.example/{account}", None, Source::Custom) }; let merged = merge(vec![vec![a], vec![b], vec![c]]); assert_eq!(merged.len(), 2); let custom = merged.iter().find(|x| x.source == Source::Custom).unwrap(); assert_eq!(custom.category, "coding"); assert!( merged.iter().any(|x| x.name.ends_with("(wmn)")) || merged.iter().any(|x| x.name.ends_with("(custom)")) ); } #[test] fn detects_formats_and_loads_embedded() { assert_eq!(detect_format(EMBEDDED_WMN).unwrap(), Format::Wmn); assert_eq!(detect_format(EMBEDDED_SHERLOCK).unwrap(), Format::Sherlock); assert_eq!(detect_format(EMBEDDED_MAIGRET).unwrap(), Format::Maigret); assert_eq!(detect_format(EMBEDDED_PERCIVAL).unwrap(), Format::Percival); let db = load(&LoadOptions { embedded_only: true, ..Default::default() }) .unwrap(); assert!(db.sites.len() > 4000, "got {}", db.sites.len()); let sel = Selection::usernames(); let default_set = db.select(&sel); assert!(default_set.len() > 1000 && default_set.len() < db.sites.len()); assert!( db.select(&Selection { all_sites: true, ..Selection::usernames() }) .len() > default_set.len() ); let top = db.select(&Selection { top: Some(10), ..Selection::usernames() }); assert_eq!(top.len(), 10); assert!(top.iter().all(|s| s.rank.is_some())); assert!( db.sites .iter() .any(|s| s.host() == "github.com" && s.source == Source::Wmn && s.known.len() >= 2), "GitHub should merge across databases" ); let emails = db.select(&Selection::emails()); assert!(!emails.is_empty()); for s in &db.sites { assert!(!s.name.is_empty()); let has = |t: &str| t.contains("{account}") || t.contains("{email_md5}"); assert!( has(&s.url) || s.body.as_deref().is_some_and(has), "{} has no placeholder: {}", s.name, s.url ); } } #[test] fn selection_filters() { let db = load(&LoadOptions { embedded_only: true, ..Default::default() }) .unwrap(); let sel = Selection { categories: vec!["coding".into()], ..Selection::usernames() }; let coding = db.select(&sel); assert!(!coding.is_empty()); assert!( coding .iter() .all(|s| s.category == "coding" || s.tags.contains(&"coding".to_string())) ); let sel = Selection { include: vec!["github".into()], ..Selection::usernames() }; assert!( db.select(&sel) .iter() .all(|s| s.name.to_ascii_lowercase().contains("github") || s.host().contains("github")) ); let sel = Selection { nsfw: false, ..Selection::usernames() }; assert!(db.select(&sel).iter().all(|s| !s.nsfw)); let sel = Selection { filter: Some(crate::filter::parse("source=sherlock").unwrap()), ..Selection::usernames() }; assert!(db.select(&sel).iter().all(|s| s.source == Source::Sherlock)); } }