repositories

percival

Follow the trail a handle leaves across the web: username search across 5,700+ sites, in Rust

clonegit clone https://git.daemon-sec.xyz/percival.git
mod.rsRust589 lines19.7 KiBraw download
//! Terminal output: banner, streaming result lines, progress bar, summaries.

pub mod theme;

use std::io::IsTerminal;
use std::time::Duration;

use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};

use crate::engine::{Bucket, Event, ScanResult, Stats, TargetKind};
use crate::report::Report;
use crate::util;
pub use theme::{ColorMode, Theme, Variant};

pub const BANNER: &str = r#"██████╗ ███████╗██████╗  ██████╗██╗██╗   ██╗ █████╗ ██╗     
██╔══██╗██╔════╝██╔══██╗██╔════╝██║██║   ██║██╔══██╗██║     
██████╔╝█████╗  ██████╔╝██║     ██║██║   ██║███████║██║     
██╔═══╝ ██╔══╝  ██╔══██╗██║     ██║╚██╗ ██╔╝██╔══██║██║     
██║     ███████╗██║  ██║╚██████╗██║ ╚████╔╝ ██║  ██║███████╗
╚═╝     ╚══════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═══╝  ╚═╝  ╚═╝╚══════╝"#;

#[derive(Clone, Copy, Debug, Default)]
pub struct PrintOpts {
    pub print_all: bool,
    pub print_errors: bool,
    pub quiet: bool,
    pub progress: bool,
    pub json: bool,
    pub show_profile: bool,
    pub animate: bool,
}

pub struct Printer {
    pub theme: Theme,
    opts: PrintOpts,
    pb: Option<ProgressBar>,
    found: usize,
    name_width: usize,
}

pub fn stdout_is_tty() -> bool {
    std::io::stdout().is_terminal()
}

impl Printer {
    pub fn new(theme: Theme, opts: PrintOpts) -> Printer {
        Printer {
            theme,
            opts,
            pb: None,
            found: 0,
            name_width: 24,
        }
    }

    pub fn theme(&self) -> &Theme {
        &self.theme
    }

    /// Print a line above the progress bar (or plainly).
    pub fn line(&self, s: impl AsRef<str>) {
        if self.opts.json {
            return;
        }
        match &self.pb {
            Some(pb) => pb.println(s.as_ref()),
            None => println!("{}", s.as_ref()),
        }
    }

    /// Print to stderr regardless of mode.
    pub fn err(&self, s: impl AsRef<str>) {
        match &self.pb {
            Some(pb) => pb.println(s.as_ref()),
            None => eprintln!("{}", s.as_ref()),
        }
    }

    pub fn note(&self, s: impl AsRef<str>) {
        if !self.opts.quiet {
            self.line(format!(
                "  {} {}",
                self.theme.info("·"),
                self.theme.subtle(s.as_ref())
            ));
        }
    }

    pub fn warn(&self, s: impl AsRef<str>) {
        self.err(format!(
            "  {} {}",
            self.theme.warn("!"),
            self.theme.subtle(s.as_ref())
        ));
    }

    pub fn error(&self, s: impl AsRef<str>) {
        self.err(format!("  {} {}", self.theme.error("✖"), s.as_ref()));
    }

    pub fn banner(&self) {
        if self.opts.quiet || self.opts.json {
            return;
        }
        let t = &self.theme;
        let lines: Vec<&str> = BANNER.lines().collect();
        if self.opts.animate && t.enabled() {
            self.animate_banner(&lines);
        } else {
            for l in &lines {
                println!("{}", t.heading(l));
            }
        }
        println!(
            "{}  {}  {}",
            t.accent("❀"),
            t.subtle(crate::TAGLINE),
            t.dim(format!("v{}", crate::VERSION))
        );
        println!();
    }

    /// A Rosé Pine light sweeps left to right across the wordmark, revealing it.
    /// Everything to the left of the wave is the settled iris; the crest is a
    /// bright rose/text highlight; ahead of it the glyphs sit dim until the
    /// light reaches them. Falls back to a static banner off a colour TTY.
    fn animate_banner(&self, lines: &[&str]) {
        use std::io::Write;
        let t = &self.theme;
        let p = &t.p;
        let width = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
        let n = lines.len();
        let step = 4usize; // columns the crest advances each frame
        let mut stdout = std::io::stdout();
        let mut first = true;
        let mut band = 0usize;
        loop {
            if !first {
                let _ = write!(stdout, "[{n}A");
            }
            first = false;
            for (row, line) in lines.iter().enumerate() {
                let mut buf = String::with_capacity(line.len() * 4 + 16);
                for (col, ch) in line.chars().enumerate() {
                    if ch == ' ' {
                        buf.push(' ');
                        continue;
                    }
                    // Wave crest tilts slightly by row so the sweep reads diagonal.
                    let pos = band as isize - (row as isize);
                    let d = pos - col as isize;
                    let color = if d >= 6 {
                        p.iris // settled
                    } else if d >= 3 {
                        p.foam
                    } else if d >= 0 {
                        p.text // crest
                    } else if d >= -2 {
                        p.rose // leading glow
                    } else {
                        p.hl_high // not yet lit
                    };
                    buf.push_str(&t.seq(color));
                    buf.push(ch);
                }
                let _ = writeln!(stdout, "{buf}");
            }
            let _ = stdout.flush();
            if band > width + n + 6 {
                break;
            }
            std::thread::sleep(Duration::from_millis(28));
            band += step;
        }
        // Settle to the static bold banner.
        let _ = write!(stdout, "[{n}A");
        for l in lines {
            let _ = writeln!(stdout, "{}", t.heading(l));
        }
        let _ = stdout.flush();
    }

    pub fn start_progress(&mut self, total: u64, label: &str) {
        if self.opts.quiet || self.opts.json || !self.opts.progress {
            return;
        }
        let pb = ProgressBar::with_draw_target(Some(total), ProgressDrawTarget::stderr());
        let tpl = format!(
            "{{spinner:.{}}} {{bar:28.{}}} {{pos:>5}}/{{len}} {{msg}}",
            self.theme.spinner_color(),
            self.theme.bar_style()
        );
        let style = ProgressStyle::with_template(&tpl)
            .unwrap_or_else(|_| ProgressStyle::default_bar())
            .progress_chars("━╸─")
            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ");
        pb.set_style(style);
        pb.set_message(label.to_string());
        pb.enable_steady_tick(Duration::from_millis(90));
        self.pb = Some(pb);
    }

    pub fn finish_progress(&mut self) {
        if let Some(pb) = self.pb.take() {
            pb.finish_and_clear();
        }
    }

    fn should_print(&self, r: &ScanResult) -> bool {
        match r.bucket() {
            Bucket::Found | Bucket::Suspicious => true,
            Bucket::Blocked => self.opts.print_all || self.opts.print_errors,
            Bucket::Error | Bucket::Unknown => self.opts.print_all || self.opts.print_errors,
            Bucket::NotFound | Bucket::Illegal => self.opts.print_all,
        }
    }

    fn format_result(&self, r: &ScanResult) -> String {
        let t = &self.theme;
        let name = console::pad_str(
            &util::truncate(&r.site, self.name_width),
            self.name_width,
            console::Alignment::Left,
            None,
        )
        .to_string();
        let ms = t.dim(format!("{:>5}ms", r.elapsed_ms));
        let cat = t.category(format!("[{}]", r.category));
        let depth = if r.depth > 0 {
            t.dim(format!(" ↳{}", r.target))
        } else {
            String::new()
        };
        match r.bucket() {
            Bucket::Found => format!(
                "  {} {} {} {} {}{depth}",
                t.found("✔"),
                t.bold(t.text(&name)),
                t.link(&r.url),
                cat,
                ms
            ),
            Bucket::Suspicious => format!(
                "  {} {} {} {} {}{depth}",
                t.warn("⚠"),
                t.text(&name),
                t.link(&r.url),
                t.warn("suspicious: canary also matched"),
                ms
            ),
            Bucket::Blocked => format!(
                "  {} {} {} {}",
                t.error("⛔"),
                t.subtle(&name),
                t.dim(&r.reason),
                ms
            ),
            Bucket::Error => format!(
                "  {} {} {} {}",
                t.paint(t.p.love, "✖"),
                t.dim(&name),
                t.dim(r.error.as_deref().unwrap_or(&r.reason)),
                ms
            ),
            Bucket::Unknown => format!(
                "  {} {} {} {}",
                t.dim("?"),
                t.dim(&name),
                t.dim(&r.reason),
                ms
            ),
            Bucket::NotFound => format!("  {} {} {}", t.dim("✘"), t.dim(&name), t.dim(&r.url)),
            Bucket::Illegal => format!(
                "  {} {} {}",
                t.dim("∅"),
                t.dim(&name),
                t.dim("username not valid here")
            ),
        }
    }

    pub fn print_result(&mut self, r: &ScanResult) {
        if r.is_hit() {
            self.found += 1;
            if let Some(pb) = &self.pb {
                pb.set_message(format!("{} found", self.found));
            }
        }
        if let Some(pb) = &self.pb {
            pb.inc(1);
        }
        if !self.should_print(r) {
            return;
        }
        if self.opts.json {
            let mut v = serde_json::to_value(r).unwrap_or_default();
            if let Some(o) = v.as_object_mut() {
                o.insert("event".into(), serde_json::Value::String("result".into()));
            }
            println!("{v}");
            return;
        }
        let line = self.format_result(r);
        self.line(line);
        if self.opts.show_profile && r.is_hit() {
            if let Some(p) = &r.profile {
                let t = &self.theme;
                let summary = p.summary(70);
                if !summary.is_empty() {
                    self.line(format!("      {} {}", t.dim("↳"), t.subtle(summary)));
                }
                if !p.links.is_empty() {
                    let shown: Vec<String> = p
                        .links
                        .iter()
                        .take(5)
                        .map(|l| {
                            t.link(util::truncate(
                                l.trim_start_matches("https://")
                                    .trim_start_matches("http://"),
                                40,
                            ))
                        })
                        .collect();
                    let more = if p.links.len() > 5 {
                        t.dim(format!(" +{}", p.links.len() - 5))
                    } else {
                        String::new()
                    };
                    self.line(format!(
                        "      {} {}{more}",
                        t.dim("↳ links:"),
                        shown.join(t.dim(", ").as_str())
                    ));
                }
                if !p.handles.is_empty() {
                    let shown: Vec<String> =
                        p.handles.iter().take(8).map(|h| t.accent(h)).collect();
                    self.line(format!("      {} {}", t.dim("↳ handles:"), shown.join(" ")));
                }
            }
            if let Some(a) = &r.archive {
                let t = &self.theme;
                self.line(format!(
                    "      {} {} {}",
                    t.dim("↳ archived"),
                    t.info(&a.date),
                    t.dim(&a.url)
                ));
            }
        } else if r.bucket() == Bucket::NotFound || r.bucket() == Bucket::Unknown {
            if let Some(a) = &r.archive {
                let t = &self.theme;
                self.line(format!(
                    "      {} {} {} {}",
                    t.dim("↳ archived"),
                    t.info(&a.date),
                    t.dim(&a.url),
                    t.warn("(deleted account?)")
                ));
            }
        }
    }

    pub fn target_header(
        &mut self,
        target: &str,
        kind: TargetKind,
        sites: usize,
        depth: u8,
        via: Option<&str>,
    ) {
        self.found = 0;
        if self.opts.json {
            println!(
                "{}",
                serde_json::json!({"event": "target_started", "target": target, "kind": kind.label(), "depth": depth, "via": via, "sites": sites})
            );
            return;
        }
        if self.opts.quiet {
            return;
        }
        let t = &self.theme;
        let via = via
            .map(|v| t.dim(format!("  (discovered via {v})")))
            .unwrap_or_default();
        self.line(format!(
            "{} {} {} {}{via}",
            t.heading("▶"),
            t.dim(kind.label()),
            t.bold(t.accent(target)),
            t.dim(format!("· {} sites", util::group_digits(sites)))
        ));
        self.start_progress(sites as u64, "starting");
    }

    pub fn target_footer(&mut self, target: &str, stats: &Stats, elapsed_ms: u64) {
        self.finish_progress();
        if self.opts.json {
            println!(
                "{}",
                serde_json::json!({"event": "target_finished", "target": target, "stats": stats, "elapsed_ms": elapsed_ms})
            );
            return;
        }
        if self.opts.quiet {
            return;
        }
        let t = &self.theme;
        let sep = t.dim(" · ");
        let parts = [
            format!("{} {}", t.found(stats.found), t.subtle("found")),
            format!("{} {}", t.warn(stats.suspicious), t.subtle("suspicious")),
            format!("{} {}", t.error(stats.blocked), t.subtle("blocked")),
            format!(
                "{} {}",
                t.accent(stats.errors + stats.unknown),
                t.subtle("errors")
            ),
            format!("{} {}", t.dim(stats.not_found), t.subtle("not found")),
            t.dim(format!("{:.1}s", elapsed_ms as f64 / 1000.0)),
        ];
        self.line(format!("  {}", parts.join(&sep)));
        self.line("");
    }

    pub fn discovered(&self, handle: &str, via_site: &str, parent: &str, will_scan: bool) {
        if self.opts.json {
            println!(
                "{}",
                serde_json::json!({"event": "discovered", "handle": handle, "via_site": via_site, "parent": parent, "scanned": will_scan})
            );
            return;
        }
        if self.opts.quiet {
            return;
        }
        let t = &self.theme;
        let tail = if will_scan {
            t.dim("→ queued")
        } else {
            t.dim("(use --recursive to scan)")
        };
        self.line(format!(
            "  {} {} {} {} {} {}",
            t.accent("⤷"),
            t.subtle("handle"),
            t.bold(t.accent(handle)),
            t.dim(format!("via {via_site} on {parent}")),
            "",
            tail
        ));
    }

    pub fn handle(&mut self, ev: &Event) {
        match ev {
            Event::TargetStarted { target, sites } => self.target_header(
                &target.value,
                target.kind,
                *sites,
                target.depth,
                target.via.as_deref(),
            ),
            Event::Result(r) => self.print_result(r),
            Event::TargetFinished {
                target,
                stats,
                elapsed_ms,
            } => self.target_footer(&target.value, stats, *elapsed_ms),
        }
    }

    pub fn summary(&self, report: &Report, paths: &[std::path::PathBuf]) {
        if self.opts.json {
            println!(
                "{}",
                serde_json::json!({"event": "summary", "summary": report.summary, "elapsed_secs": report.elapsed_secs, "reports": paths})
            );
            return;
        }
        if self.opts.quiet {
            return;
        }
        let t = &self.theme;
        let s = &report.summary;
        println!("{}", t.rule(64));
        let targets: Vec<String> = report
            .targets
            .iter()
            .filter(|t| t.depth == 0)
            .map(|t| t.target.clone())
            .collect();
        println!(
            "  {} {}  {}  {}",
            t.heading("❀"),
            t.bold(t.accent(targets.join(", "))),
            t.dim(format!("{} checks", util::group_digits(s.total))),
            t.dim(format!("{:.1}s", report.elapsed_secs))
        );
        let sep = t.dim(" · ");
        let parts = [
            format!("{} {}", t.found(s.found), t.subtle("found")),
            format!("{} {}", t.warn(s.suspicious), t.subtle("suspicious")),
            format!("{} {}", t.error(s.blocked), t.subtle("blocked")),
            format!(
                "{} {}",
                t.accent(s.errors + s.unknown),
                t.subtle("errors/unknown")
            ),
            format!("{} {}", t.dim(s.not_found), t.subtle("not found")),
        ];
        println!("  {}", parts.join(&sep));
        let cats = report.category_counts();
        if !cats.is_empty() {
            let parts: Vec<String> = cats
                .iter()
                .map(|(c, n)| format!("{} {}", t.category(c), t.dim(n)))
                .collect();
            println!("  {}", parts.join(t.dim(" · ").as_str()));
        }
        if !report.discovered.is_empty() {
            let parts: Vec<String> = report
                .discovered
                .iter()
                .take(12)
                .map(|d| {
                    format!(
                        "{}{}",
                        t.accent(&d.handle),
                        if d.scanned {
                            t.dim("✓")
                        } else {
                            String::new()
                        }
                    )
                })
                .collect();
            println!("  {} {}", t.subtle("discovered:"), parts.join(" "));
        }
        for e in &report.emails {
            if !e.breaches.is_empty() {
                println!(
                    "  {} {} {}",
                    t.error("⚠"),
                    t.subtle(format!(
                        "{} appears in {} breaches:",
                        e.email,
                        e.breaches.len()
                    )),
                    t.dim(
                        e.breaches
                            .iter()
                            .map(|b| b.name.as_str())
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                );
            }
        }
        if !paths.is_empty() {
            let dir = paths[0]
                .parent()
                .map(|p| p.display().to_string())
                .unwrap_or_default();
            let exts: Vec<String> = paths
                .iter()
                .filter_map(|p| p.extension().map(|e| e.to_string_lossy().to_string()))
                .collect();
            println!(
                "  {} {} {}",
                t.subtle("reports →"),
                t.link(dir),
                t.dim(format!("({})", exts.join(", ")))
            );
        }
        println!("{}", t.rule(64));
    }
}

/// Simple two-column key/value block used by `sites --show` and friends.
pub fn kv_block(theme: &Theme, pairs: &[(&str, String)]) -> String {
    let w = pairs.iter().map(|(k, _)| k.len()).max().unwrap_or(8);
    pairs
        .iter()
        .map(|(k, v)| format!("  {} {}", theme.subtle(format!("{k:>w$}")), v))
        .collect::<Vec<_>>()
        .join("\n")
}