Detect Homoglyph Mixed-Script Names

Flag usernames that mix Latin with Cyrillic or Greek letters used as lookalikes, and explain each suspicious character.

PythonSecurity Boundaries

Code

snippet
import unicodedata

SCRIPT_RANGES = {
    "LATIN": [(0x0041, 0x024F), (0x1E00, 0x1EFF)],
    "CYRILLIC": [(0x0400, 0x04FF)],
    "GREEK": [(0x0370, 0x03FF)],
}


def script_of(char: str) -> str:
    code = ord(char)
    for name, ranges in SCRIPT_RANGES.items():
        if any(start <= code <= end for start, end in ranges):
            return name
    return "OTHER"


def find_mixed_scripts(text: str) -> list[str]:
    scripts = {script_of(char) for char in text if char.isalpha()}
    return sorted(scripts - {"OTHER"})


def is_suspicious(text: str) -> bool:
    scripts = find_mixed_scripts(text)
    return "LATIN" in scripts and len(scripts) > 1


def explain(text: str) -> list[dict[str, str]]:
    return [
        {
            "char": char,
            "name": unicodedata.name(char, "UNKNOWN"),
            "script": script_of(char),
        }
        for char in text
        if char.isalpha() and script_of(char) not in {"LATIN", "OTHER"}
    ]


if __name__ == "__main__":
    for sample in ["paypal", "pаypal", "admin"]:
        print(sample, find_mixed_scripts(sample), is_suspicious(sample))
    print(explain("pаypal"))