FreshPixels commited on
Commit
d79c5f9
·
verified ·
1 Parent(s): c2048e0

Create core/security/validators.py

Browse files
Files changed (1) hide show
  1. core/security/validators.py +82 -0
core/security/validators.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+
6
+ def validate_bot_token(token: str | None) -> str:
7
+ """Validate Telegram bot token format.
8
+
9
+ Expected format: <integer_id>:<alphanumeric_hash>
10
+ Example: 123456789:AAHdqTcvCH1vGWJxfSeofSAsQK6PALsAW
11
+
12
+ Args:
13
+ token: The bot token string to validate. May be None if env var unset.
14
+
15
+ Returns:
16
+ The validated token string.
17
+
18
+ Raises:
19
+ ValueError: If the token is None, empty, or format is invalid.
20
+ """
21
+ if token is None:
22
+ raise ValueError("BOT_TOKEN is None — environment variable not set")
23
+
24
+ stripped = token.strip()
25
+ if not stripped:
26
+ raise ValueError("BOT_TOKEN is empty after stripping whitespace")
27
+
28
+ pattern = r"^\d+:[A-Za-z0-9_-]{35,}$"
29
+ if not re.match(pattern, stripped):
30
+ raise ValueError(
31
+ f"BOT_TOKEN format is invalid. "
32
+ f"Expected format: '<id>:<hash_35plus>', got: '{stripped[:6]}...'"
33
+ )
34
+
35
+ return stripped
36
+
37
+
38
+ def validate_admin_id(admin_id: str | None) -> str:
39
+ """Validate Telegram admin user ID.
40
+
41
+ Must be a positive integer that can be used as a Telegram user ID.
42
+
43
+ Args:
44
+ admin_id: The admin ID string to validate. May be None if env var unset.
45
+
46
+ Returns:
47
+ The validated admin ID string.
48
+
49
+ Raises:
50
+ ValueError: If the admin ID is None, empty, or invalid format.
51
+ """
52
+ if admin_id is None:
53
+ raise ValueError("ADMIN_ID is None — environment variable not set")
54
+
55
+ stripped = admin_id.strip()
56
+ if not stripped:
57
+ raise ValueError("ADMIN_ID is empty after stripping whitespace")
58
+
59
+ if "." in stripped:
60
+ raise ValueError(
61
+ f"ADMIN_ID must be an integer, got float-like value: '{stripped}'"
62
+ )
63
+
64
+ try:
65
+ numeric_id = int(stripped)
66
+ except (ValueError, TypeError) as exc:
67
+ raise ValueError(
68
+ f"ADMIN_ID must be a numeric value, got: '{stripped}'"
69
+ ) from exc
70
+
71
+ if numeric_id <= 0:
72
+ raise ValueError(
73
+ f"ADMIN_ID must be a positive integer, got: {numeric_id}"
74
+ )
75
+
76
+ if numeric_id > 2**63 - 1:
77
+ raise ValueError(
78
+ f"ADMIN_ID exceeds maximum allowed value (2^63-1), got: {numeric_id}"
79
+ )
80
+
81
+ return stripped
82
+