abbosovshahboz12-dot
Enforce strict Telegram HMAC verification and TMA auth gate, remove URL uid spoofing, configure MenuButtonWebApp
9576aae Download api/auth.py from Shaptoli/xat-chop: direct link, hf CLI and curl.
- Browser
- Download file 5.26 kB
-
https://huggingface.co/spaces/Shaptoli/xat-chop/resolve/main/api/auth.py
- Command line
-
hf download hf://spaces/Shaptoli/xat-chop/api/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Shaptoli/xat-chop/resolve/main/api/auth.py
5.26 kB
| import hmac | |
| import hashlib | |
| import time | |
| import json | |
| import urllib.parse | |
| import logging | |
| from typing import Optional, Dict, Any | |
| from config import BOT_TOKEN, ADMIN_IDS | |
| logger = logging.getLogger("XatChop.Auth") | |
| # Sessiyalar uchun xavfsiz secret kalit (Bot tokeni asosida) | |
| SESSION_SECRET = hashlib.sha256(f"xatchop_session_secret_{BOT_TOKEN}".encode("utf-8")).digest() | |
| def verify_telegram_init_data(init_data_raw: str, max_age_seconds: int = 86400 * 30) -> Optional[Dict[str, Any]]: | |
| """ | |
| Telegram WebApp rasmiy spetsifikatsiyasi bo'yicha initData imzosini (HMAC-SHA256) tekshiradi. | |
| Faqatgina Telegram serveri tomonidan imzolangan haqiqiy ma'lumotlar qabul qilinadi. | |
| """ | |
| if not init_data_raw or not BOT_TOKEN: | |
| return None | |
| try: | |
| parsed_items = urllib.parse.parse_qsl(init_data_raw, keep_blank_values=True) | |
| data_dict = dict(parsed_items) | |
| received_hash = data_dict.get("hash") | |
| if not received_hash: | |
| return None | |
| # 'hash' kalitidan tashqari barcha parametrlarni alifbo tartibida saralash | |
| check_items = sorted([(k, v) for k, v in data_dict.items() if k != "hash"]) | |
| data_check_string = "\n".join(f"{k}={v}" for k, v in check_items) | |
| # 1. secret_key = HMAC_SHA256("WebAppData", bot_token) | |
| secret_key = hmac.new(b"WebAppData", BOT_TOKEN.encode("utf-8"), hashlib.sha256).digest() | |
| # 2. computed_hash = HMAC_SHA256(secret_key, data_check_string) | |
| computed_hash = hmac.new(secret_key, data_check_string.encode("utf-8"), hashlib.sha256).hexdigest() | |
| if not hmac.compare_digest(computed_hash.lower(), received_hash.lower()): | |
| logger.warning("Telegram initData HMAC imzosi mos kelmadi!") | |
| return None | |
| auth_date = int(data_dict.get("auth_date", 0)) | |
| # max_age_seconds tekshiruvi | |
| if max_age_seconds > 0 and (time.time() - auth_date > max_age_seconds): | |
| logger.warning("Telegram initData muddati o'tgan") | |
| return None | |
| # Foydalanuvchi ma'lumotlarini o'qish | |
| user_str = data_dict.get("user") | |
| user_data = json.loads(user_str) if user_str else {} | |
| user_id = user_data.get("id") | |
| if not user_id: | |
| return None | |
| return { | |
| "user_id": int(user_id), | |
| "first_name": user_data.get("first_name", ""), | |
| "last_name": user_data.get("last_name", ""), | |
| "username": user_data.get("username", ""), | |
| "auth_date": auth_date, | |
| "raw_user": user_data | |
| } | |
| except Exception as e: | |
| logger.error(f"initData tekshirishda xatolik: {e}") | |
| return None | |
| def create_session_token(user_id: int) -> str: | |
| """ | |
| Foydalanuvchi uchun xavfsiz shifrlangan va imzolangan sessiya tokenini yaratadi. | |
| Format: <user_id>.<timestamp>.<signature> | |
| """ | |
| ts = int(time.time()) | |
| payload = f"{user_id}:{ts}" | |
| sig = hmac.new(SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256).hexdigest()[:28] | |
| return f"{user_id}.{ts}.{sig}" | |
| def verify_session_token(token: str, max_age_days: int = 30) -> Optional[int]: | |
| """ | |
| Sessiya tokenini tekshirib, haqiqiy foydalanuvchi ID sini qaytaradi. | |
| Imzo noto'g'ri bo'lsa yoki token soxtalashtirilgan bo'lsa, None qaytaradi. | |
| """ | |
| if not token or "." not in token: | |
| return None | |
| try: | |
| parts = token.split(".") | |
| if len(parts) != 3: | |
| return None | |
| user_id_str, ts_str, received_sig = parts | |
| user_id = int(user_id_str) | |
| ts = int(ts_str) | |
| if time.time() - ts > (max_age_days * 86400): | |
| return None | |
| payload = f"{user_id}:{ts}" | |
| expected_sig = hmac.new(SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256).hexdigest()[:28] | |
| if hmac.compare_digest(expected_sig, received_sig): | |
| return user_id | |
| except Exception: | |
| return None | |
| return None | |
| def extract_user_id_from_request(request, body_data: Optional[Dict[str, Any]] = None) -> Optional[int]: | |
| """ | |
| So'rovdan foydalanuvchi ID sini xavfsiz autentifikatsiya orqali aniqlaydi: | |
| 1. Header: Authorization: Bearer <session_token> yoki x-session-token | |
| 2. Body: session_token | |
| 3. Body: init_data (Telegram WebApp imzosi) | |
| 4. Agar bular bo'lmasa va dev muhiti bo'lsa, xavfsiz default fallback (faqat ruxsat berilgan bo'lsa) | |
| """ | |
| # 1. Header orqali sessiya tokeni | |
| auth_header = request.headers.get("Authorization", "") | |
| token = "" | |
| if auth_header.startswith("Bearer "): | |
| token = auth_header[7:].strip() | |
| elif request.headers.get("x-session-token"): | |
| token = request.headers.get("x-session-token").strip() | |
| # 2. Body orqali sessiya tokeni | |
| if not token and body_data and isinstance(body_data, dict): | |
| token = body_data.get("session_token", "") | |
| if token: | |
| uid = verify_session_token(token) | |
| if uid: | |
| return uid | |
| # 3. Telegram WebApp init_data HMAC imzosi | |
| if body_data and isinstance(body_data, dict) and body_data.get("init_data"): | |
| verified = verify_telegram_init_data(body_data["init_data"]) | |
| if verified and verified.get("user_id"): | |
| return verified["user_id"] | |
| # Autentifikatsiyadan o'tmagan | |
| return None | |