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
links.rsRust1,109 lines25.7 KiBraw download
//! Recognise social profile URLs and pull usernames out of them.

use regex::Regex;
use std::sync::OnceLock;

/// Path template → how to read the handle. See `handle_from_url`.
struct Rule {
    hosts: &'static [&'static str],
    patterns: &'static [&'static str],
}

const RULES: &[Rule] = &[
    Rule {
        hosts: &[
            "twitter.com",
            "x.com",
            "nitter.net",
            "nitter.privacydev.net",
        ],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["github.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["gist.github.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["github.io"],
        patterns: &["sub"],
    },
    Rule {
        hosts: &[
            "gitlab.com",
            "codeberg.org",
            "bitbucket.org",
            "gitea.com",
            "framagit.org",
            "salsa.debian.org",
        ],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["sr.ht", "git.sr.ht"],
        patterns: &["/~{h}"],
    },
    Rule {
        hosts: &["instagram.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["threads.net", "threads.com"],
        patterns: &["/@{h}"],
    },
    Rule {
        hosts: &["t.me", "telegram.me", "telegram.dog"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["facebook.com", "fb.com", "fb.me"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["youtube.com"],
        patterns: &["/@{h}", "/c/{h}", "/user/{h}"],
    },
    Rule {
        hosts: &["tiktok.com"],
        patterns: &["/@{h}"],
    },
    Rule {
        hosts: &["reddit.com", "old.reddit.com", "new.reddit.com"],
        patterns: &["/user/{h}", "/u/{h}"],
    },
    Rule {
        hosts: &["twitch.tv"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["kick.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["linkedin.com"],
        patterns: &["/in/{h}"],
    },
    Rule {
        hosts: &["keybase.io"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["linktr.ee"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["ko-fi.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["patreon.com"],
        patterns: &["/{h}", "/c/{h}"],
    },
    Rule {
        hosts: &["buymeacoffee.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["medium.com"],
        patterns: &["/@{h}", "sub"],
    },
    Rule {
        hosts: &["dev.to"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &[
            "hashnode.dev",
            "substack.com",
            "tumblr.com",
            "bandcamp.com",
            "itch.io",
            "deviantart.com",
            "carrd.co",
            "wordpress.com",
            "blogspot.com",
            "livejournal.com",
            "dreamwidth.org",
            "gumroad.com",
            "myshopify.com",
            "gitlab.io",
            "neocities.org",
        ],
        patterns: &["sub"],
    },
    Rule {
        hosts: &["steamcommunity.com"],
        patterns: &["/id/{h}", "/profiles/{id}"],
    },
    Rule {
        hosts: &["soundcloud.com", "mixcloud.com", "audiomack.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["open.spotify.com"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &["pinterest.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["snapchat.com"],
        patterns: &["/add/{h}"],
    },
    Rule {
        hosts: &["vk.com", "vkontakte.ru"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["ok.ru"],
        patterns: &["/{h}", "/profile/{id}"],
    },
    Rule {
        hosts: &[
            "behance.net",
            "dribbble.com",
            "artstation.com",
            "vimeo.com",
            "codepen.io",
            "hackerone.com",
            "bugcrowd.com",
            "kaggle.com",
            "huggingface.co",
            "leetcode.com",
            "about.me",
            "paypal.me",
            "venmo.com",
            "onlyfans.com",
            "fansly.com",
            "letterboxd.com",
            "500px.com",
            "unsplash.com",
            "producthunt.com",
            "replit.com",
            "wellfound.com",
            "cara.app",
            "rateyourmusic.com",
            "myanimelist.net",
            "spacehey.com",
            "minds.com",
            "gab.com",
            "truthsocial.com",
            "gettr.com",
            "bitchute.com",
            "odysee.com",
            "pixiv.net",
            "vsco.co",
            "mastodon.social",
            "mstdn.social",
            "fosstodon.org",
            "hachyderm.io",
            "infosec.exchange",
            "mas.to",
        ],
        patterns: &["/{h}", "/@{h}"],
    },
    Rule {
        hosts: &["flickr.com"],
        patterns: &["/people/{h}", "/photos/{h}"],
    },
    Rule {
        hosts: &["last.fm"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &[
            "stackoverflow.com",
            "superuser.com",
            "serverfault.com",
            "askubuntu.com",
        ],
        patterns: &["/users/*/{h}"],
    },
    Rule {
        hosts: &["rumble.com"],
        patterns: &["/user/{h}", "/c/{h}"],
    },
    Rule {
        hosts: &["cash.app"],
        patterns: &["/${h}"],
    },
    Rule {
        hosts: &["bsky.app"],
        patterns: &["/profile/{h}"],
    },
    Rule {
        hosts: &["discord.com", "discordapp.com"],
        patterns: &["/users/{id}"],
    },
    Rule {
        hosts: &["tryhackme.com"],
        patterns: &["/p/{h}", "/r/p/{h}"],
    },
    Rule {
        hosts: &["app.hackthebox.com", "hackthebox.com"],
        patterns: &["/profile/{id}", "/users/{id}"],
    },
    Rule {
        hosts: &["codeforces.com"],
        patterns: &["/profile/{h}"],
    },
    Rule {
        hosts: &["npmjs.com"],
        patterns: &["/~{h}"],
    },
    Rule {
        hosts: &["pypi.org"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &["crates.io"],
        patterns: &["/users/{h}"],
    },
    Rule {
        hosts: &["hub.docker.com"],
        patterns: &["/u/{h}", "/r/{h}"],
    },
    Rule {
        hosts: &["chess.com"],
        patterns: &["/member/{h}"],
    },
    Rule {
        hosts: &["lichess.org"],
        patterns: &["/@/{h}"],
    },
    Rule {
        hosts: &["strava.com"],
        patterns: &["/athletes/{id}"],
    },
    Rule {
        hosts: &["imgur.com"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &["giphy.com"],
        patterns: &["/channel/{h}", "/{h}"],
    },
    Rule {
        hosts: &["wikipedia.org", "en.wikipedia.org", "wikimedia.org"],
        patterns: &["/wiki/User:{h}"],
    },
    Rule {
        hosts: &["news.ycombinator.com"],
        patterns: &["/user?id={h}"],
    },
    Rule {
        hosts: &["trello.com"],
        patterns: &["/u/{h}"],
    },
    Rule {
        hosts: &["speedrun.com"],
        patterns: &["/users/{h}", "/user/{h}"],
    },
    Rule {
        hosts: &["namemc.com"],
        patterns: &["/profile/{h}"],
    },
    Rule {
        hosts: &["osu.ppy.sh"],
        patterns: &["/users/{h}", "/u/{h}"],
    },
    Rule {
        hosts: &["duolingo.com"],
        patterns: &["/profile/{h}"],
    },
    Rule {
        hosts: &["habr.com"],
        patterns: &["/users/{h}", "/ru/users/{h}", "/en/users/{h}"],
    },
    Rule {
        hosts: &["pikabu.ru"],
        patterns: &["/@{h}"],
    },
    Rule {
        hosts: &["scratch.mit.edu"],
        patterns: &["/users/{h}"],
    },
    Rule {
        hosts: &["furaffinity.net"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &["e621.net"],
        patterns: &["/users/{id}"],
    },
    Rule {
        hosts: &["newgrounds.com"],
        patterns: &["sub"],
    },
    Rule {
        hosts: &["gamejolt.com"],
        patterns: &["/@{h}"],
    },
    Rule {
        hosts: &["thingiverse.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["hackaday.io"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["sketchfab.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["discogs.com"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &["genius.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["goodreads.com"],
        patterns: &["/{h}"],
    },
    Rule {
        hosts: &["untappd.com"],
        patterns: &["/user/{h}"],
    },
    Rule {
        hosts: &["yelp.com"],
        patterns: &["/user_details?userid={id}"],
    },
    Rule {
        hosts: &["telegra.ph"],
        patterns: &[],
    },
];

/// Path segments that are navigation, not usernames.
const STOP: &[&str] = &[
    "login",
    "signin",
    "sign_in",
    "sign-in",
    "signup",
    "sign_up",
    "sign-up",
    "register",
    "join",
    "about",
    "help",
    "terms",
    "tos",
    "privacy",
    "policy",
    "policies",
    "legal",
    "search",
    "explore",
    "home",
    "index",
    "share",
    "sharer",
    "intent",
    "static",
    "assets",
    "api",
    "settings",
    "press",
    "jobs",
    "careers",
    "blog",
    "contact",
    "support",
    "tag",
    "tags",
    "hashtag",
    "hashtags",
    "topics",
    "topic",
    "trending",
    "new",
    "i",
    "p",
    "s",
    "u",
    "c",
    "t",
    "r",
    "dialog",
    "plugins",
    "embed",
    "oauth",
    "auth",
    "account",
    "accounts",
    "admin",
    "dashboard",
    "notifications",
    "messages",
    "inbox",
    "feed",
    "feeds",
    "rss",
    "sitemap",
    "images",
    "img",
    "css",
    "js",
    "video",
    "videos",
    "photo",
    "photos",
    "watch",
    "groups",
    "group",
    "pages",
    "page",
    "events",
    "event",
    "places",
    "marketplace",
    "shop",
    "store",
    "cart",
    "checkout",
    "download",
    "downloads",
    "apps",
    "app",
    "mobile",
    "developer",
    "developers",
    "docs",
    "doc",
    "status",
    "stories",
    "story",
    "reel",
    "reels",
    "tv",
    "live",
    "music",
    "games",
    "gaming",
    "directory",
    "category",
    "categories",
    "forum",
    "forums",
    "thread",
    "threads",
    "post",
    "posts",
    "comments",
    "upload",
    "create",
    "edit",
    "delete",
    "logout",
    "sign-out",
    "signout",
    "faq",
    "en",
    "de",
    "fr",
    "es",
    "ru",
    "ja",
    "zh",
    "pt",
    "it",
    "nl",
    "pl",
    "tr",
    "ko",
    "features",
    "pricing",
    "sponsors",
    "orgs",
    "site",
    "security",
    "enterprise",
    "customer-stories",
    "readme",
    "collections",
    "team",
    "codespaces",
    "joinchat",
    "addstickers",
    "proxy",
    "socks",
    "profile.php",
    "public",
    "people",
    "direct",
    "channel",
    "channels",
    "playlist",
    "results",
    "web",
    "www",
    "mail",
    "email",
    "wp-content",
    "wp-admin",
    "cdn",
    "media",
    "static",
    "compose",
    "intent",
    "premium",
    "subscribe",
    "gift",
    "cookies",
    "cookie",
    "advertising",
    "ads",
    "business",
    "brand",
    "careers",
    "investors",
    "news",
    "newsroom",
    "safety",
    "transparency",
    "guidelines",
    "community",
    "partners",
    "press",
    "resources",
    "tools",
    "learn",
    "education",
    "students",
    "teachers",
    "nonprofits",
    "government",
    "sitemap.xml",
    "robots.txt",
    "favicon.ico",
    "amp",
    "m",
    "go",
    "l",
    "s",
    "e",
    "a",
    "x",
    "widgets",
    "widget",
    "badge",
    "users",
    "user",
    "profile",
    "profiles",
    "member",
    "members",
    "people",
    "author",
    "authors",
    "advisories",
    "packages",
    "package",
    "company",
    "companies",
    "school",
    "pulse",
    "issues",
    "pulls",
    "blob",
    "tree",
    "commit",
    "commits",
    "releases",
    "wiki",
    "organizations",
    "org",
    "sponsor",
    "gists",
    "stars",
    "watching",
    "followers",
    "following",
    "pin",
    "pins",
    "board",
    "boards",
    "collection",
    "gallery",
    "item",
    "items",
    "product",
    "products",
    "listing",
];

const SUB_STOP: &[&str] = &[
    "www",
    "m",
    "api",
    "static",
    "cdn",
    "blog",
    "help",
    "support",
    "docs",
    "dev",
    "app",
    "mail",
    "shop",
    "store",
    "en",
    "de",
    "fr",
    "es",
    "assets",
    "img",
    "images",
    "media",
    "status",
    "about",
    "admin",
    "beta",
    "staging",
    "test",
    "old",
    "new",
    "mobile",
    "wiki",
    "forum",
    "forums",
    "community",
    "id",
    "auth",
    "login",
    "accounts",
    "account",
    "ssl",
    "secure",
    "cloud",
    "git",
    "gist",
    "pages",
    "raw",
];

fn handle_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"^[A-Za-z0-9][A-Za-z0-9._-]{1,39}$").unwrap())
}

fn is_handle(s: &str) -> bool {
    if !handle_re().is_match(s) {
        return false;
    }
    let lower = s.to_ascii_lowercase();
    if STOP.contains(&lower.as_str()) {
        return false;
    }
    if !s.chars().any(|c| c.is_ascii_alphabetic()) {
        return false;
    }
    if lower.len() >= 24 && lower.chars().all(|c| c.is_ascii_hexdigit()) {
        return false;
    }
    if lower.ends_with(".php")
        || lower.ends_with(".html")
        || lower.ends_with(".xml")
        || lower.ends_with(".json")
        || lower.ends_with(".js")
        || lower.ends_with(".css")
    {
        return false;
    }
    true
}

fn is_id(s: &str) -> bool {
    !s.is_empty() && s.len() <= 24 && s.chars().all(|c| c.is_ascii_digit())
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pivot {
    pub host: String,
    pub handle: String,
    /// `true` when the identifier is a numeric id rather than a username.
    pub numeric: bool,
}

fn strip_prefixes(host: &str) -> &str {
    let mut h = host;
    for p in ["www.", "m.", "mobile.", "old.", "new.", "en."] {
        if let Some(rest) = h.strip_prefix(p) {
            h = rest;
        }
    }
    h
}

fn try_pattern(
    pattern: &str,
    host: &str,
    rule_host: &str,
    segs: &[String],
    query: &str,
) -> Option<(String, bool)> {
    if pattern == "sub" {
        let suffix = format!(".{rule_host}");
        let sub = host.strip_suffix(suffix.as_str())?;
        if sub.contains('.') || SUB_STOP.contains(&sub) || !is_handle(sub) {
            return None;
        }
        return Some((sub.to_string(), false));
    }
    if let Some(q) = pattern.strip_prefix("/user?id=") {
        let _ = q;
        let v = query.split('&').find_map(|kv| kv.strip_prefix("id="))?;
        return if is_handle(v) {
            Some((v.to_string(), false))
        } else {
            None
        };
    }
    if let Some(q) = pattern.strip_prefix("/user_details?userid=") {
        let _ = q;
        let v = query.split('&').find_map(|kv| kv.strip_prefix("userid="))?;
        return Some((v.to_string(), true));
    }
    let parts: Vec<&str> = pattern.trim_start_matches('/').split('/').collect();
    if segs.len() < parts.len() {
        return None;
    }
    for (i, part) in parts.iter().enumerate() {
        let seg = segs[i].as_str();
        match *part {
            "{h}" => {
                return if is_handle(seg) {
                    Some((seg.to_string(), false))
                } else {
                    None
                };
            }
            "@{h}" => {
                let s = seg.strip_prefix('@')?;
                return if is_handle(s) {
                    Some((s.to_string(), false))
                } else {
                    None
                };
            }
            "~{h}" => {
                let s = seg.strip_prefix('~')?;
                return if is_handle(s) {
                    Some((s.to_string(), false))
                } else {
                    None
                };
            }
            "${h}" => {
                let s = seg.strip_prefix('$')?;
                return if is_handle(s) {
                    Some((s.to_string(), false))
                } else {
                    None
                };
            }
            "User:{h}" => {
                let s = seg.strip_prefix("User:")?;
                return if is_handle(s) {
                    Some((s.to_string(), false))
                } else {
                    None
                };
            }
            "{id}" => {
                return if is_id(seg) {
                    Some((seg.to_string(), true))
                } else {
                    None
                };
            }
            "*" => {}
            lit => {
                if !seg.eq_ignore_ascii_case(lit) {
                    return None;
                }
            }
        }
    }
    None
}

/// Identify the profile owner referenced by a URL.
pub fn handle_from_url(url: &str) -> Option<Pivot> {
    let parsed = url::Url::parse(url.trim()).ok()?;
    if !matches!(parsed.scheme(), "http" | "https") {
        return None;
    }
    let raw_host = parsed.host_str()?.to_ascii_lowercase();
    let host = strip_prefixes(&raw_host).to_string();
    let segs: Vec<String> = parsed
        .path_segments()
        .map(|it| {
            it.filter(|s| !s.is_empty())
                .map(|s| {
                    percent_encoding::percent_decode_str(s)
                        .decode_utf8_lossy()
                        .to_string()
                })
                .collect()
        })
        .unwrap_or_default();
    let query = parsed.query().unwrap_or("");

    for rule in RULES {
        for rh in rule.hosts {
            let exact = host == *rh;
            let sub_ok = rule.patterns.contains(&"sub") && host.ends_with(&format!(".{rh}"));
            if !exact && !sub_ok {
                continue;
            }
            for pattern in rule.patterns {
                if pattern == &"sub" && !sub_ok {
                    continue;
                }
                if pattern != &"sub" && !exact {
                    continue;
                }
                if let Some((h, numeric)) = try_pattern(pattern, &host, rh, &segs, query) {
                    return Some(Pivot {
                        host: host.clone(),
                        handle: h,
                        numeric,
                    });
                }
            }
            if exact {
                return None; // known host, no pattern matched
            }
        }
    }
    // Subdomains of known hosts (api.github.com, …) never fall through to the generic rules.
    if RULES
        .iter()
        .any(|r| r.hosts.iter().any(|rh| host.ends_with(&format!(".{rh}"))))
    {
        return None;
    }
    // Generic fediverse / forum conventions on unknown hosts.
    if let Some(first) = segs.first() {
        if let Some(h) = first.strip_prefix('@') {
            if is_handle(h) {
                return Some(Pivot {
                    host,
                    handle: h.to_string(),
                    numeric: false,
                });
            }
        }
        let f = first.to_ascii_lowercase();
        if matches!(
            f.as_str(),
            "user"
                | "users"
                | "u"
                | "profile"
                | "profiles"
                | "member"
                | "members"
                | "people"
                | "author"
                | "~"
        ) {
            if let Some(second) = segs.get(1) {
                if is_handle(second) {
                    return Some(Pivot {
                        host,
                        handle: second.to_string(),
                        numeric: false,
                    });
                }
            }
        }
        if let Some(h) = first.strip_prefix('~') {
            if is_handle(h) {
                return Some(Pivot {
                    host,
                    handle: h.to_string(),
                    numeric: false,
                });
            }
        }
    }
    None
}

/// Domain-style handles (`alice.example.com` on Bluesky) reduce to their first label for pivoting.
fn pivot_handle(h: &str) -> String {
    if let Some((first, rest)) = h.split_once('.') {
        let tld = rest.rsplit('.').next().unwrap_or("");
        if tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()) && first.len() >= 2 {
            return first.to_string();
        }
    }
    h.to_string()
}

/// From a page's outbound links, keep social profile links and collect handles.
/// `strong` links (rel=me) are always kept.
pub fn pivot(
    links: &[String],
    strong: &[String],
    self_host: &str,
    account: &str,
) -> (Vec<String>, Vec<String>) {
    let mut out_links: Vec<String> = Vec::new();
    let mut handles: Vec<String> = Vec::new();
    let self_host = self_host.to_ascii_lowercase();
    let mut consider = |link: &str, force: bool| {
        let Ok(u) = url::Url::parse(link) else { return };
        let host = u.host_str().unwrap_or("").to_ascii_lowercase();
        let host = strip_prefixes(&host);
        let same_site = !self_host.is_empty()
            && (host == self_host || host.ends_with(&format!(".{self_host}")));
        let pv = handle_from_url(link);
        let keep = force || (pv.is_some() && !same_site);
        if !keep {
            return;
        }
        let cleaned = link.trim_end_matches('/').to_string();
        if !out_links.iter().any(|l| l.eq_ignore_ascii_case(&cleaned)) && out_links.len() < 40 {
            out_links.push(cleaned);
        }
        if let Some(pv) = pv {
            let handle = pivot_handle(&pv.handle);
            if !pv.numeric
                && !same_site
                && !handle.eq_ignore_ascii_case(account)
                && is_handle(&handle)
                && !handles.iter().any(|h| h.eq_ignore_ascii_case(&handle))
                && handles.len() < 20
            {
                handles.push(handle);
            }
        }
    };
    for l in strong {
        consider(l, true);
    }
    for l in links {
        consider(l, false);
    }
    (out_links, handles)
}

/// `@handle` mentions inside free text.
pub fn mentions(text: &str) -> Vec<String> {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r"(?:^|[^A-Za-z0-9_/.@])@([A-Za-z0-9_][A-Za-z0-9_.]{1,29})").unwrap()
    });
    let mut out = Vec::new();
    for cap in re.captures_iter(text) {
        let h = cap[1].trim_end_matches('.').to_string();
        if is_handle(&h) && !out.iter().any(|x: &String| x.eq_ignore_ascii_case(&h)) {
            out.push(h);
        }
    }
    out
}

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

    fn h(url: &str) -> Option<String> {
        handle_from_url(url).map(|p| p.handle)
    }

    #[test]
    fn known_hosts() {
        assert_eq!(
            h("https://twitter.com/jane_doe?lang=en").as_deref(),
            Some("jane_doe")
        );
        assert_eq!(h("https://x.com/intent/tweet"), None);
        assert_eq!(h("https://github.com/jane/repo").as_deref(), Some("jane"));
        assert_eq!(h("https://github.com/features/actions"), None);
        assert_eq!(h("https://api.github.com/users/jane"), None);
        assert_eq!(h("https://www.youtube.com/@jane").as_deref(), Some("jane"));
        assert_eq!(h("https://www.youtube.com/watch?v=abc"), None);
        assert_eq!(
            h("https://www.reddit.com/user/jane/").as_deref(),
            Some("jane")
        );
        assert_eq!(h("https://old.reddit.com/r/rust"), None);
        assert_eq!(h("https://jane.tumblr.com/post/1").as_deref(), Some("jane"));
        assert_eq!(h("https://www.tumblr.com/"), None);
        assert_eq!(
            h("https://stackoverflow.com/users/12345/jane").as_deref(),
            Some("jane")
        );
        assert_eq!(
            h("https://steamcommunity.com/id/jane").as_deref(),
            Some("jane")
        );
        let p = handle_from_url("https://steamcommunity.com/profiles/76561198000000000").unwrap();
        assert!(p.numeric);
        assert_eq!(h("https://cash.app/$jane").as_deref(), Some("jane"));
        assert_eq!(
            h("https://en.wikipedia.org/wiki/User:Jane").as_deref(),
            Some("Jane")
        );
        assert_eq!(
            h("https://news.ycombinator.com/user?id=jane").as_deref(),
            Some("jane")
        );
        assert_eq!(h("https://t.me/joinchat/abc"), None);
        assert_eq!(h("https://t.me/jane").as_deref(), Some("jane"));
    }

    #[test]
    fn generic_conventions() {
        assert_eq!(h("https://mastodon.example/@jane").as_deref(), Some("jane"));
        assert_eq!(
            h("https://forum.example.org/u/jane/summary").as_deref(),
            Some("jane")
        );
        assert_eq!(h("https://example.org/~jane").as_deref(), Some("jane"));
        assert_eq!(h("https://example.org/about"), None);
        assert_eq!(h("mailto:jane@example.org"), None);
    }

    #[test]
    fn pivots_and_mentions() {
        let links = vec![
            "https://github.com/jane".to_string(),
            "https://github.com/jane".to_string(),
            "https://example.com/about".to_string(),
            "https://t.me/other_person/".to_string(),
            "https://self.example/@jane".to_string(),
            "https://self.example/@someone".to_string(),
        ];
        let strong = vec!["https://infosec.exchange/@jane".to_string()];
        let (l, hs) = pivot(&links, &strong, "self.example", "jane");
        assert_eq!(l.len(), 3);
        assert_eq!(hs, vec!["other_person".to_string()]);
        let (_, hs) = pivot(
            &[
                "https://bsky.app/profile/alice.example.com".to_string(),
                "https://mastodon.social/users/bob".to_string(),
            ],
            &[],
            "x.y",
            "jane",
        );
        assert_eq!(hs, vec!["alice".to_string()]);
        assert_eq!(
            mentions("ping @alice and @bob. email x@y.com https://a/@nope"),
            vec!["alice", "bob"]
        );
    }
}