//! Report model and writers (json, ndjson, csv, txt, md, html, dot). pub mod csv; pub mod dot; pub mod html; pub mod json; pub mod markdown; pub mod txt; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use crate::email::Breach; use crate::engine::{Bucket, ScanResult, Stats, TargetKind}; use crate::util; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Format { Html, Json, Ndjson, Csv, Md, Txt, Dot, } impl Format { pub const ALL: [Format; 7] = [ Format::Html, Format::Json, Format::Ndjson, Format::Csv, Format::Md, Format::Txt, Format::Dot, ]; pub const DEFAULT: [Format; 3] = [Format::Html, Format::Json, Format::Csv]; pub fn parse(s: &str) -> Option { Some(match s.trim().to_ascii_lowercase().as_str() { "html" | "htm" => Format::Html, "json" => Format::Json, "ndjson" | "jsonl" => Format::Ndjson, "csv" => Format::Csv, "md" | "markdown" => Format::Md, "txt" | "text" => Format::Txt, "dot" | "graph" | "graphviz" => Format::Dot, _ => return None, }) } pub fn parse_list(items: &[String]) -> Result> { let mut out = Vec::new(); for item in items { for part in item.split(',') { let part = part.trim(); if part.is_empty() { continue; } if part == "all" { out.extend(Format::ALL); continue; } match Format::parse(part) { Some(f) => out.push(f), None => bail!( "unknown report format '{part}' (expected html, json, ndjson, csv, md, txt, dot, all)" ), } } } out.sort(); out.dedup(); Ok(out) } pub fn ext(self) -> &'static str { match self { Format::Html => "html", Format::Json => "json", Format::Ndjson => "ndjson", Format::Csv => "csv", Format::Md => "md", Format::Txt => "txt", Format::Dot => "dot", } } } /// A handle discovered on a found profile. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Discovered { pub handle: String, pub via_site: String, pub parent: String, pub depth: u8, pub scanned: bool, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct TargetSummary { pub target: String, pub kind: TargetKind, pub depth: u8, #[serde(skip_serializing_if = "Option::is_none")] pub via: Option, pub stats: Stats, pub elapsed_ms: u64, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct EmailIntel { pub email: String, pub gravatar_hash: String, pub derived_handles: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub breaches: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub breach_error: Option, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct RunInfo { pub sites_selected: usize, pub sources: Vec, pub concurrency: usize, pub timeout_secs: f64, pub verify: bool, pub extract: bool, pub recursive: bool, pub archive: String, pub proxy: Option, pub canary: String, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct Report { pub tool: String, pub version: String, pub generated_at: String, pub elapsed_secs: f64, pub run: RunInfo, pub targets: Vec, pub discovered: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub emails: Vec, pub summary: Stats, pub results: Vec, } impl Report { pub fn new() -> Report { Report { tool: crate::NAME.to_string(), version: crate::VERSION.to_string(), generated_at: util::iso_now(), ..Default::default() } } pub fn hits(&self) -> impl Iterator { self.results.iter().filter(|r| r.is_hit()) } pub fn suspicious(&self) -> impl Iterator { self.results.iter().filter(|r| r.is_suspicious()) } /// Results grouped by target, in the order targets were scanned. pub fn by_target(&self) -> Vec<(&TargetSummary, Vec<&ScanResult>)> { self.targets .iter() .map(|t| { ( t, self.results .iter() .filter(|r| r.target == t.target && r.depth == t.depth) .collect(), ) }) .collect() } pub fn category_counts(&self) -> BTreeMap { let mut m = BTreeMap::new(); for r in self.hits() { *m.entry(r.category.clone()).or_insert(0) += 1; } m } pub fn recompute_summary(&mut self) { self.summary = Stats::from_results(&self.results); } /// Sort results: hits first (by rank order preserved), then suspicious, /// blocked, unknown, errors, not found; alphabetical inside a bucket. pub fn sort_results(&mut self) { fn weight(b: Bucket) -> u8 { match b { Bucket::Found => 0, Bucket::Suspicious => 1, Bucket::Blocked => 2, Bucket::Unknown => 3, Bucket::Error => 4, Bucket::Illegal => 5, Bucket::NotFound => 6, } } self.results.sort_by(|a, b| { a.depth .cmp(&b.depth) .then_with(|| a.target.cmp(&b.target)) .then_with(|| weight(a.bucket()).cmp(&weight(b.bucket()))) .then_with(|| { a.site .to_ascii_lowercase() .cmp(&b.site.to_ascii_lowercase()) }) }); } /// Write the chosen formats into `dir`, returning the created paths. pub fn write_all(&self, dir: &Path, formats: &[Format], stem: &str) -> Result> { std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; let mut paths = Vec::new(); for f in formats { let path = dir.join(format!("{stem}.{}", f.ext())); let content = match f { Format::Html => html::render(self), Format::Json => json::render(self)?, Format::Ndjson => json::render_ndjson(self)?, Format::Csv => csv::render(self)?, Format::Md => markdown::render(self), Format::Txt => txt::render(self), Format::Dot => dot::render(self), }; std::fs::write(&path, content) .with_context(|| format!("writing {}", path.display()))?; paths.push(path); } Ok(paths) } } /// File stem for a set of targets: `johndoe` or `johndoe+2-more`. pub fn stem_for(targets: &[String]) -> String { match targets.len() { 0 => "percival".to_string(), 1 => util::sanitize_filename(&targets[0]), n => format!("{}+{}-more", util::sanitize_filename(&targets[0]), n - 1), } } #[cfg(test)] pub(crate) fn sample_report() -> Report { use crate::db::Source; use crate::engine::{Confidence, Status}; use crate::extract::Profile; let mut rep = Report::new(); rep.targets.push(TargetSummary { target: "jane".into(), kind: TargetKind::Username, depth: 0, via: None, stats: Stats::default(), elapsed_ms: 1200, }); let base = ScanResult { target: "jane".into(), kind: TargetKind::Username, depth: 0, via: None, site: "GitHub".into(), category: "coding".into(), tags: vec!["coding".into()], source: Source::Wmn, url: "https://github.com/jane".into(), probe_url: "https://api.github.com/users/jane".into(), status: Status::Found, confidence: Confidence::High, verified: Some(true), reason: "HTTP 200 with presence marker".into(), http_status: Some(200), elapsed_ms: 210, profile: Some(Profile { name: Some("Jane ".into()), bio: Some("dev & \"hacker\"".into()), followers: Some(1500), links: vec!["https://t.me/jane".into()], handles: vec!["jane_dev".into()], ..Default::default() }), archive: None, error: None, }; rep.results.push(base.clone()); rep.results.push(ScanResult { site: "Suspicious Site".into(), category: "social".into(), verified: Some(false), confidence: Confidence::Low, url: "https://sus.example/jane".into(), profile: None, ..base.clone() }); rep.results.push(ScanResult { site: "Reddit".into(), status: Status::NotFound, verified: None, url: "https://reddit.com/user/jane".into(), profile: None, ..base.clone() }); rep.results.push(ScanResult { site: "Blocked, Inc".into(), status: Status::Blocked, reason: "Cloudflare challenge (HTTP 503)".into(), verified: None, profile: None, ..base.clone() }); rep.results.push(ScanResult { site: "Broken".into(), status: Status::Error, error: Some("timeout".into()), verified: None, profile: None, http_status: None, ..base }); rep.discovered.push(Discovered { handle: "jane_dev".into(), via_site: "GitHub".into(), parent: "jane".into(), depth: 1, scanned: false, }); rep.recompute_summary(); rep.targets[0].stats = rep.summary; rep.sort_results(); rep } #[cfg(test)] mod tests { use super::*; #[test] fn formats_and_stems() { assert_eq!( Format::parse_list(&["html,json".into(), "md".into()]).unwrap(), vec![Format::Html, Format::Json, Format::Md] ); assert!(Format::parse_list(&["bogus".into()]).is_err()); assert_eq!(Format::parse_list(&["all".into()]).unwrap().len(), 7); assert_eq!(stem_for(&["a b".into()]), "a_b"); assert_eq!(stem_for(&["a".into(), "b".into(), "c".into()]), "a+2-more"); } #[test] fn writes_every_format() { let rep = sample_report(); let dir = std::env::temp_dir().join(format!("percival-test-{}", std::process::id())); let paths = rep.write_all(&dir, &Format::ALL, "jane").unwrap(); assert_eq!(paths.len(), 7); for p in &paths { assert!(p.metadata().unwrap().len() > 0); } std::fs::remove_dir_all(&dir).ok(); assert_eq!(rep.summary.found, 1); assert_eq!(rep.summary.suspicious, 1); assert_eq!(rep.results[0].site, "GitHub"); } }