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

pythonsnippet
44 lines
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"))

How the snippet works

Detect Homoglyph Mixed-Script Names reduces to the functions script_of, find_mixed_scripts, is_suspicious and explain.

Repetition is confined to for name, ranges in SCRIPT_RANGES.items() — the rest of the file is straight-line.

A fresh value is allocated for the result; the arguments stay untouched.

Caveats

  • Requires unicodedata as a package; the snippet will not run without it.

Applying it

The primary signature is def script_of(char: str) -> str

Statements that matter

def find_mixed_scripts(text: str) -> list[str]:
    scripts = {script_of(char) for char in text if char.isalpha()}
    return sorted(scripts - {"OTHER"})
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"}
    ]
def is_suspicious(text: str) -> bool:
    scripts = find_mixed_scripts(text)
    return "LATIN" in scripts and len(scripts) > 1

Interactive Tools for This Topic

FAQ

Does `script_of` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
What does this need from the package registry?
These are real dependencies: `unicodedata`. Without it the snippet will not load.