Repository navigation
Expand file tree
/
Copy pathcharacters.py
More file actions
338 lines (289 loc) · 10.3 KB
/
Copy pathcharacters.py
File metadata and controls
338 lines (289 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from __future__ import annotations
import re
from functools import lru_cache
from typing import Iterable
BYPASS_PATTERNS = {
"a": "(a|@|4|à |á|â|ã|ä|Ã¥|Ä|ă|Ä…|æ)",
"b": "(b|8|ß|13|!3)",
"c": "(c|\\(|ç|ć|ĉ|Ä‹|Ä)",
"d": "(d|Ä|Ä‘)",
"e": "(e|Æ|3|Σ|è|é|ê|ë|Ä“|Ä•|Ä—|Ä™|Ä›)",
"f": "(f|Æ’|ph)",
"g": "(g|q|ð”¾|₲|6|9|Ä|ÄŸ|Ä¡|Ä£)",
"h": "(h|ĥ|ħ|#)",
"i": "(i|1|!|\\||ì|Ã|î|ï|Ä«|Ä|į|ı|l|ã€)",
"j": "(j|ĵ)",
"k": "(k|ķ|ĸ|\\|<|\\|{|\\|c|/\\|)",
"l": "(l|1|!|\\||ĺ|ļ|ľ|ŀ|ł|i)",
"m": "(m|/\\/\\|\\^\\^|nn)",
"n": "(n|η|ñ|ń|ņ|ň|ʼn|ŋ|ᑎ)",
"o": "(o|0|°|ø|ö|ó|ò|ô|õ|Å|Å|Å‘|Å“)",
"p": "(p|þ|Ï|q)",
"q": "(q|9|g)",
"r": "(r|ŕ|ŗ|ř|Я)",
"s": "(s|\\$|5|§|Å›|Å|ÅŸ|Å¡|z)",
"t": "(t|7|\\+|†|ţ|ť|ŧ)",
"u": "(u|µ|Ï…|ü|ú|ù|û|Å«|Å|ů|ű|ų)",
"v": "(v|\\/)",
"w": "(w|ŵ|vv|\\/\\/)",
"x": "(x|×|χ|><)",
"y": "(y|¥|ÿ|ý|ŷ|ȳ|j)",
"z": "(z|2|ż|ź|ž|s)",
}
ALT_ACCOUNT_WORDS = (
"alt",
"alts",
"backup",
"backups",
"back_up",
"bak",
"bckup",
"spare",
"second",
"secondaccount",
"account",
"acct",
"acc",
"clone",
"copy",
"new",
"old",
"main",
"again",
)
_USERNAME_KEY_RE = re.compile(r"[^a-z0-9]+", re.IGNORECASE)
_SEPARATOR_PATTERN = r"(?:[\s\W_]*?)"
_EMPTY_MATCH_RE = re.compile(r"a\A")
_CANONICAL_CHAR_ALIASES = {
"@": "a",
"0": "o",
"1": "i",
"2": "z",
"3": "e",
"4": "a",
"5": "s",
"6": "g",
"7": "t",
"8": "b",
"9": "g",
"$": "s",
"+": "t",
}
def normalized_username_key(value: str) -> str:
return _USERNAME_KEY_RE.sub("", str(value or "").strip().lower())
def canonical_username_key(value: str) -> str:
pieces: list[str] = []
for character in str(value or "").strip().lower():
if character.isalpha():
pieces.append(character)
continue
mapped = _CANONICAL_CHAR_ALIASES.get(character)
if mapped:
pieces.append(mapped)
continue
if character.isdigit():
pieces.append(character)
return "".join(pieces)
def _normalized_words(words: Iterable[str] | None) -> tuple[str, ...]:
rawWords = tuple(words or ALT_ACCOUNT_WORDS)
normalized = []
seen: set[str] = set()
for word in rawWords:
key = normalized_username_key(str(word or ""))
if not key or key in seen:
continue
seen.add(key)
normalized.append(key)
return tuple(normalized)
def _canonicalized_words(words: Iterable[str] | None) -> tuple[str, ...]:
rawWords = tuple(words or ALT_ACCOUNT_WORDS)
normalized = []
seen: set[str] = set()
for word in rawWords:
key = canonical_username_key(str(word or ""))
if not key or key in seen:
continue
seen.add(key)
normalized.append(key)
return tuple(normalized)
def canonical_alt_word_keys(words: Iterable[str] | None = None) -> set[str]:
return set(_canonicalized_words(words))
def generate_regex_pattern(word: str) -> str:
key = normalized_username_key(word)
pattern = ""
for index, character in enumerate(key):
charPattern = BYPASS_PATTERNS.get(character.lower(), re.escape(character))
pattern += f"(?:{charPattern})"
if index != len(key) - 1:
pattern += _SEPARATOR_PATTERN
return pattern
@lru_cache(maxsize=2048)
def _build_username_variant_regex_cached(usernameKey: str, altWords: tuple[str, ...]) -> re.Pattern[str]:
if len(usernameKey) < 3:
return _EMPTY_MATCH_RE
core = generate_regex_pattern(usernameKey)
choices: list[str] = []
if len(usernameKey) >= 5:
choices.append(core)
altPatterns = [
generate_regex_pattern(word)
for word in altWords
if len(word) >= 2
]
if altPatterns:
marker = "(?:" + "|".join(altPatterns) + ")"
optionalDigits = r"(?:\d{1,4})?"
choices.extend(
[
f"{marker}{_SEPARATOR_PATTERN}{core}{_SEPARATOR_PATTERN}{optionalDigits}",
f"{core}{_SEPARATOR_PATTERN}{marker}{_SEPARATOR_PATTERN}{optionalDigits}",
f"{marker}{_SEPARATOR_PATTERN}{optionalDigits}{_SEPARATOR_PATTERN}{core}",
f"{core}{_SEPARATOR_PATTERN}{optionalDigits}{_SEPARATOR_PATTERN}{marker}",
]
)
if len(usernameKey) >= 5:
choices.append(f"{core}{_SEPARATOR_PATTERN}\\d{{1,4}}")
if not choices:
return _EMPTY_MATCH_RE
return re.compile("^(?:" + "|".join(choices) + ")$", re.IGNORECASE)
def build_username_variant_regex(
username: str,
*,
altWords: Iterable[str] | None = None,
) -> re.Pattern[str]:
return _build_username_variant_regex_cached(
normalized_username_key(username),
_normalized_words(altWords),
)
def username_alt_match_reason(
candidate: str,
knownUsername: str,
*,
altWords: Iterable[str] | None = None,
) -> str | None:
return username_alt_match_reason_for_keys(
candidate,
knownUsername,
candidateKey=normalized_username_key(candidate),
knownKey=normalized_username_key(knownUsername),
altWords=altWords,
)
def username_alt_match_reason_for_keys(
candidate: str,
knownUsername: str,
*,
candidateKey: str,
knownKey: str,
candidateCanonical: str | None = None,
knownCanonical: str | None = None,
markerCanonicalWords: set[str] | None = None,
altWords: Iterable[str] | None = None,
) -> str | None:
candidateText = str(candidate or "").strip()
knownText = str(knownUsername or "").strip()
candidateKey = str(candidateKey or "")
knownKey = str(knownKey or "")
if len(candidateKey) < 3 or len(knownKey) < 3:
return None
if candidateText.lower() == knownText.lower():
return None
if candidateKey == knownKey:
return "known member username with separator or case changes"
if _has_trailing_digit_variant(candidateKey, knownKey):
return "known member username with alternate characters"
if candidateCanonical is None:
candidateCanonical = canonical_username_key(candidateText)
if knownCanonical is None:
knownCanonical = canonical_username_key(knownText)
if len(candidateCanonical) < 3 or len(knownCanonical) < 3:
return None
if candidateCanonical == knownCanonical:
return "known member username with alternate characters"
if markerCanonicalWords is None:
markerCanonicalWords = set(_canonicalized_words(altWords))
if _has_alt_marker_variant(
candidateKey,
knownKey,
candidateCanonical,
knownCanonical,
markerCanonicalWords,
):
return "known member username with an alt/back-up marker"
return None
def looks_like_username_alt(
candidate: str,
knownUsername: str,
*,
altWords: Iterable[str] | None = None,
) -> bool:
return username_alt_match_reason(candidate, knownUsername, altWords=altWords) is not None
def _strip_leading_optional_digits(value: str) -> tuple[str, int]:
digitCount = 0
for character in str(value or ""):
if not character.isdigit():
break
digitCount += 1
if 1 <= digitCount <= 4:
return value[digitCount:], digitCount
return value, 0
def _strip_trailing_optional_digits(value: str) -> tuple[str, int]:
digitCount = 0
for character in reversed(str(value or "")):
if not character.isdigit():
break
digitCount += 1
if 1 <= digitCount <= 4:
return value[:-digitCount], digitCount
return value, 0
def _has_trailing_digit_variant(candidateKey: str, knownKey: str) -> bool:
stripped, digitCount = _strip_trailing_optional_digits(candidateKey)
return digitCount > 0 and stripped == knownKey
def _has_alt_marker_variant(
candidateKey: str,
knownKey: str,
candidateCanonical: str,
knownCanonical: str,
markerCanonicalWords: set[str],
) -> bool:
if (
not markerCanonicalWords
or not candidateKey
or not knownKey
or not candidateCanonical
or not knownCanonical
):
return False
candidateKeyWithoutTrailingDigits, _ = _strip_trailing_optional_digits(candidateKey)
if candidateKeyWithoutTrailingDigits.startswith(knownKey):
suffix = candidateKeyWithoutTrailingDigits[len(knownKey):]
if canonical_username_key(suffix) in markerCanonicalWords:
return True
strippedSuffix, _ = _strip_leading_optional_digits(suffix)
if canonical_username_key(strippedSuffix) in markerCanonicalWords:
return True
if candidateKeyWithoutTrailingDigits.endswith(knownKey):
prefix = candidateKeyWithoutTrailingDigits[:-len(knownKey)]
if canonical_username_key(prefix) in markerCanonicalWords:
return True
strippedPrefix, _ = _strip_trailing_optional_digits(prefix)
if canonical_username_key(strippedPrefix) in markerCanonicalWords:
return True
candidateCanonicalWithoutTrailingDigits, _ = _strip_trailing_optional_digits(candidateCanonical)
if candidateCanonicalWithoutTrailingDigits.startswith(knownCanonical):
suffixCanonical = candidateCanonicalWithoutTrailingDigits[len(knownCanonical):]
if suffixCanonical in markerCanonicalWords:
return True
if candidateCanonicalWithoutTrailingDigits.endswith(knownCanonical):
prefixCanonical = candidateCanonicalWithoutTrailingDigits[:-len(knownCanonical)]
if prefixCanonical in markerCanonicalWords:
return True
return False
def build_trigger_regex(triggerWords: dict[str, Iterable[str]] | None = None) -> re.Pattern[str]:
patterns: list[str] = []
for baseWord, variations in (triggerWords or {}).items():
patterns.append(generate_regex_pattern(baseWord))
for variation in variations:
patterns.append(generate_regex_pattern(variation))
if not patterns:
return _EMPTY_MATCH_RE
return re.compile("|".join(patterns), re.IGNORECASE)