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
html.rsRust167 lines5.9 KiBraw download
//! Profile harvesting from HTML pages: OpenGraph / Twitter cards, meta
//! description, JSON-LD and outbound links.

use scraper::{Html, Selector};

use super::Profile;
use super::json;
use crate::util;

fn sel(s: &str) -> Selector {
    Selector::parse(s).expect("static selector")
}

fn clean(s: &str, max: usize) -> Option<String> {
    let t = util::squash_ws(&util::strip_tags(s));
    if t.is_empty() {
        None
    } else {
        Some(util::truncate(&t, max))
    }
}

/// Split `"Name (@handle) / X"` or `"Name | Site"` into the leading part.
fn title_head(t: &str) -> String {
    let mut head = t;
    for sep in [" | ", " – ", " — ", " - ", " · ", " • ", " :: "] {
        if let Some(idx) = head.find(sep) {
            head = &head[..idx];
        }
    }
    head.trim().to_string()
}

/// Returns (profile, links, strong_links). Strong links are `rel="me"` links.
pub fn extract(body: &str) -> (Profile, Vec<String>, Vec<String>) {
    let doc = Html::parse_document(body);
    let mut p = Profile::default();
    let mut links: Vec<String> = Vec::new();
    let mut strong: Vec<String> = Vec::new();

    let meta = |attr: &str, key: &str| -> Option<String> {
        let selector = sel(&format!("meta[{attr}=\"{key}\"]"));
        doc.select(&selector)
            .filter_map(|e| e.value().attr("content"))
            .map(|c| c.trim().to_string())
            .find(|c| !c.is_empty())
    };

    // JSON-LD first: it is the most structured signal.
    let ld = sel("script[type=\"application/ld+json\"]");
    for script in doc.select(&ld).take(6) {
        let text: String = script.text().collect();
        if text.len() > 200_000 {
            continue;
        }
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(text.trim()) {
            json::merge_jsonld(&v, &mut p, &mut links);
        }
    }

    let og_title = meta("property", "og:title").or_else(|| meta("name", "twitter:title"));
    let title = doc
        .select(&sel("title"))
        .next()
        .map(|t| t.text().collect::<String>())
        .and_then(|t| clean(&t, 200));
    if p.name.is_none() {
        p.name = og_title.as_deref().and_then(|t| clean(t, 120)).or_else(|| {
            title
                .as_deref()
                .map(title_head)
                .and_then(|t| clean(&t, 120))
        });
    }
    if p.bio.is_none() {
        p.bio = meta("property", "og:description")
            .or_else(|| meta("name", "twitter:description"))
            .or_else(|| meta("name", "description"))
            .and_then(|d| clean(&d, 400));
    }
    if p.avatar.is_none() {
        p.avatar = meta("property", "og:image:secure_url")
            .or_else(|| meta("property", "og:image"))
            .or_else(|| meta("name", "twitter:image"))
            .filter(|u| u.starts_with("http") || u.starts_with("//"))
            .map(|u| {
                if u.starts_with("//") {
                    format!("https:{u}")
                } else {
                    u
                }
            });
    }
    if let Some(u) = meta("property", "profile:username") {
        p.extra.entry("username".into()).or_insert(u);
    }
    if p.name.is_none() {
        let first = meta("property", "profile:first_name").unwrap_or_default();
        let last = meta("property", "profile:last_name").unwrap_or_default();
        let full = format!("{first} {last}");
        if !full.trim().is_empty() {
            p.name = Some(full.trim().to_string());
        }
    }
    if let Some(t) = title {
        p.extra.entry("title".into()).or_insert(t);
    }
    if let Some(c) = doc
        .select(&sel("link[rel=\"canonical\"]"))
        .next()
        .and_then(|e| e.value().attr("href"))
    {
        p.extra
            .entry("canonical".into())
            .or_insert(c.trim().to_string());
    }

    // rel="me" links (fediverse-verified identity links).
    for e in doc.select(&sel("a[rel~=\"me\"], link[rel~=\"me\"]")) {
        if let Some(h) = e.value().attr("href") {
            if h.starts_with("http") {
                strong.push(h.trim().to_string());
            }
        }
    }
    // Every absolute outbound anchor.
    for e in doc.select(&sel("a[href]")).take(3000) {
        if let Some(h) = e.value().attr("href") {
            let h = h.trim();
            if h.starts_with("http://") || h.starts_with("https://") {
                links.push(h.to_string());
            } else if let Some(rest) = h.strip_prefix("//") {
                links.push(format!("https://{rest}"));
            }
        }
    }
    (p, links, strong)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn harvests_meta_and_links() {
        let html = r#"<html><head><title>Jane Doe (@jane) / X</title>
        <meta property="og:title" content="Jane Doe (@jane)">
        <meta property="og:description" content="Security researcher &amp; cat person">
        <meta property="og:image" content="//img.example/jane.png">
        <link rel="canonical" href="https://x.com/jane">
        <script type="application/ld+json">{"@type":"Person","name":"Jane Doe","homeLocation":{"name":"Berlin"},"sameAs":["https://github.com/jane"]}</script>
        </head><body><a rel="me" href="https://infosec.exchange/@jane">fedi</a><a href="https://t.me/jane">tg</a><a href="/local">x</a></body></html>"#;
        let (p, links, strong) = extract(html);
        assert_eq!(p.name.as_deref(), Some("Jane Doe"));
        assert_eq!(p.bio.as_deref(), Some("Security researcher & cat person"));
        assert_eq!(p.avatar.as_deref(), Some("https://img.example/jane.png"));
        assert_eq!(
            p.extra.get("canonical").map(String::as_str),
            Some("https://x.com/jane")
        );
        assert!(links.contains(&"https://t.me/jane".to_string()));
        assert!(links.contains(&"https://github.com/jane".to_string()));
        assert_eq!(strong, vec!["https://infosec.exchange/@jane".to_string()]);
        assert_eq!(title_head("Jane | Site"), "Jane");
        assert_eq!(title_head("A - B - C"), "A");
    }
}