import time import hmac import hashlib import json import logging from urllib.parse import unquote from fastapi import Request, HTTPException from config import BOT_TOKEN, MAX_INITDATA_AGE logger = logging.getLogger(__name__) async def verify_telegram_initdata(init_data: str): """Проверяет подпись initData от Telegram с проверкой срока действия""" try: # Парсим initData data = {} for chunk in init_data.split('&'): if '=' in chunk: key, value = chunk.split('=', 1) data[key] = unquote(value) # Извлекаем hash received_hash = data.pop('hash', '') if not received_hash: raise HTTPException(401, "Hash not found in initData") # Проверяем auth_date (не старше MAX_INITDATA_AGE из config) auth_date_str = data.get('auth_date', '0') try: auth_date = int(auth_date_str) current_time = int(time.time()) if current_time - auth_date > MAX_INITDATA_AGE: raise HTTPException(401, "initData expired") if auth_date > current_time + 60: raise HTTPException(401, "initData from future") except ValueError: raise HTTPException(401, "Invalid auth_date") # Сортируем ключи и создаем строку для проверки check_arr = [] for key in sorted(data.keys()): check_arr.append(f"{key}={data[key]}") check_string = '\n'.join(check_arr) # Создаем секретный ключ secret_key = hmac.new( 'WebAppData'.encode(), BOT_TOKEN.encode(), hashlib.sha256 ).digest() # Вычисляем hash calculated_hash = hmac.new( secret_key, check_string.encode(), hashlib.sha256 ).hexdigest() if not hmac.compare_digest(calculated_hash, received_hash): raise HTTPException(401, "Invalid initData signature") # Извлекаем данные пользователя user_data_str = data.get('user', '{}') try: user_data = json.loads(user_data_str) except json.JSONDecodeError: raise HTTPException(401, "Invalid user data JSON") user_id = user_data.get('id') username = user_data.get('username', '') # 🔧 ФИКС (25.09.2026): unused_first_name — удалена мёртвая переменная. if not user_id: raise HTTPException(401, "User ID not found in initData") return user_id, username except HTTPException: raise except Exception as e: # 🔧 ФИКС (23.09.2026): auth_error_leak — раньше в 401 утекали # внутренние детали (str(e)). Теперь логируем на сервере, # клиенту — обобщённое сообщение. logger.error(f"Auth error: {str(e)}", exc_info=True) raise HTTPException(401, "Invalid initData") async def require_auth(request: Request): """Извлекает и проверяет initData из запроса. 🔧 ФИКС (23.09.2026): INIT_DATA_IN_URL — поддержка Authorization: tma . Приоритет источников: 1. Authorization: tma — новый способ (фронт 23.09+) 2. X-Telegram-InitData — старый способ (фронт до 23.09) 3. query-параметр initData — fallback для deleteFeedPost (осознанное исключение из-за Cloudflare preflight-кеша) Zero-downtime: старые и новые клиенты работают одновременно. """ init_data = '' # 1. Authorization: tma (новый способ) auth_header = request.headers.get('Authorization', '') if auth_header.startswith('tma '): init_data = auth_header[4:].strip() # 2. X-Telegram-InitData (старый способ) if not init_data: init_data = request.headers.get('X-Telegram-InitData', '') # 3. Query-параметр (fallback, нужен для deleteFeedPost) if not init_data: init_data = request.query_params.get('initData', '') if not init_data: raise HTTPException( 401, "initData required. Pass as Authorization header 'tma ' " "or 'X-Telegram-InitData' or query parameter 'initData'" ) # 🔧 ФИКС (23.09.2026): double_unquote_initdata — убран повторный unquote. # Starlette уже декодирует query_params. Повторный unquote ломал auth, # если в initData был символ '%' (например в first_name). # Декодирование значений происходит внутри verify_telegram_initdata. user_id, username = await verify_telegram_initdata(init_data) return user_id, username