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
permute.rsRust141 lines4.8 KiBraw download
//! Username permutations: `john.doe` → `johndoe`, `john_doe`, `jdoe`, …

use std::collections::HashSet;

const SEPARATORS: [&str; 4] = ["", ".", "_", "-"];
const SUFFIXES: &[&str] = &[
    "1", "2", "7", "01", "69", "123", "420", "1337", "_", "x", "xx", "official", "real", "dev",
    "tv",
];

/// Split a name into tokens on separators, whitespace and camelCase.
pub fn tokens(input: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for raw in input
        .split(|c: char| c.is_whitespace() || matches!(c, '.' | '_' | '-' | '+' | ',' | '/' | '@'))
    {
        if raw.is_empty() {
            continue;
        }
        // camelCase split.
        let mut cur = String::new();
        let chars: Vec<char> = raw.chars().collect();
        for (i, c) in chars.iter().enumerate() {
            let boundary = i > 0 && c.is_uppercase() && chars[i - 1].is_lowercase();
            let digit_boundary = i > 0 && c.is_ascii_digit() != chars[i - 1].is_ascii_digit();
            if (boundary || digit_boundary) && !cur.is_empty() {
                out.push(cur.to_lowercase());
                cur = String::new();
            }
            cur.push(*c);
        }
        if !cur.is_empty() {
            out.push(cur.to_lowercase());
        }
    }
    out
}

/// Generate permutations. `aggressive` adds numeric/word suffixes and
/// leetspeak-free variants; `max` caps the result.
pub fn permute(input: &str, aggressive: bool, max: usize) -> Vec<String> {
    let mut seen: HashSet<String> = HashSet::new();
    let mut out: Vec<String> = Vec::new();
    fn add(out: &mut Vec<String>, seen: &mut HashSet<String>, s: String) {
        let s = s.trim().to_string();
        if s.len() >= 3 && seen.insert(s.to_lowercase()) {
            out.push(s);
        }
    }
    let mut push = |s: String| add(&mut out, &mut seen, s);

    let original = input.trim().to_string();
    push(original.clone());
    let toks = tokens(input);
    let alpha: Vec<String> = toks
        .iter()
        .filter(|t| t.chars().any(|c| c.is_alphabetic()))
        .cloned()
        .collect();
    let digits: Vec<String> = toks
        .iter()
        .filter(|t| t.chars().all(|c| c.is_ascii_digit()))
        .cloned()
        .collect();

    if alpha.len() >= 2 {
        let a = &alpha[0];
        let b = &alpha[alpha.len() - 1];
        let ai: String = a.chars().take(1).collect();
        let bi: String = b.chars().take(1).collect();
        for sep in SEPARATORS {
            push(format!("{a}{sep}{b}"));
            push(format!("{b}{sep}{a}"));
            push(format!("{ai}{sep}{b}"));
            push(format!("{a}{sep}{bi}"));
            push(format!("{b}{sep}{ai}"));
            push(format!("{bi}{sep}{a}"));
        }
        push(alpha.concat());
        push(format!("{ai}{bi}"));
        for d in &digits {
            push(format!("{a}{b}{d}"));
            push(format!("{a}_{b}{d}"));
            push(format!("{a}.{b}{d}"));
        }
    } else if let Some(a) = alpha.first() {
        push(a.clone());
        for d in &digits {
            push(format!("{a}{d}"));
            push(format!("{a}_{d}"));
        }
    }

    if aggressive {
        let bases: Vec<String> = out.iter().take(12).cloned().collect();
        for base in &bases {
            for suf in SUFFIXES {
                add(&mut out, &mut seen, format!("{base}{suf}"));
            }
            add(&mut out, &mut seen, format!("_{base}"));
            add(&mut out, &mut seen, format!("the{base}"));
            add(&mut out, &mut seen, format!("its{base}"));
            add(&mut out, &mut seen, format!("{base}_"));
        }
    }
    out.truncate(max.max(1));
    out
}

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

    #[test]
    fn splits_tokens() {
        assert_eq!(tokens("john.doe"), vec!["john", "doe"]);
        assert_eq!(tokens("JohnDoe42"), vec!["john", "doe", "42"]);
        assert_eq!(tokens("john doe"), vec!["john", "doe"]);
        assert_eq!(tokens("plain"), vec!["plain"]);
    }

    #[test]
    fn permutes() {
        let p = permute("john.doe", false, 100);
        assert!(p.contains(&"john.doe".to_string()));
        assert!(p.contains(&"johndoe".to_string()));
        assert!(p.contains(&"john_doe".to_string()));
        assert!(p.contains(&"doejohn".to_string()));
        assert!(p.contains(&"jdoe".to_string()));
        assert!(p.contains(&"johnd".to_string()));
        assert!(!p.contains(&"jd".to_string()), "too short");
        let all = permute("john.doe", true, 500);
        assert!(all.len() > p.len());
        assert!(all.contains(&"johndoe1337".to_string()));
        assert_eq!(permute("x", false, 10).len(), 0);
        assert_eq!(permute("john.doe", true, 5).len(), 5);
        let single = permute("neo", true, 100);
        assert!(single.contains(&"neo".to_string()));
        assert!(single.contains(&"neo123".to_string()));
    }
}