""" utils.py – Shared helpers: hash gen, initData verification, bcrypt, sessions. All config imported from config.py — no os.getenv() here. """ import hashlib import hmac import json import secrets import urllib.parse from datetime import datetime, timedelta import bcrypt import asyncio import base64 import os import httpx import config class ImgBBUploader: """Async uploader for ImgBB using direct API calls.""" def __init__(self, api_key: str): self.api_key = api_key self.upload_url = "https://api.imgbb.com/1/upload" async def upload_from_file(self, file_path: str, name: str = "") -> dict: """ Upload an image from a file path. Args: file_path: Path to the image file name: Optional custom name for the image Returns: Dictionary containing upload response with URL """ with open(file_path, "rb") as f: image_data = f.read() return await self._upload(image_data, name) async def upload_from_bytes(self, image_bytes: bytes, name: str = "") -> dict: """ Upload an image from bytes. Args: image_bytes: Image data as bytes name: Optional custom name for the image Returns: Dictionary containing upload response with URL """ return await self._upload(image_bytes, name) async def _upload(self, image_data: bytes, name: str = "") -> dict: """ Internal method to perform the upload. """ encoded_image = base64.b64encode(image_data).decode('utf-8') async with httpx.AsyncClient() as client: payload = { "key": self.api_key, "image": encoded_image, } if name: payload["name"] = name response = await client.post(self.upload_url, data=payload) response.raise_for_status() result = response.json() if not result.get("success"): raise Exception(f"Upload failed: {result.get('error', {}).get('message', 'Unknown error')}") return result def get_image_url(self, upload_response: dict) -> str: """Extract the image URL from the upload response.""" return upload_response["data"]["url"] def get_delete_url(self, upload_response: dict) -> str: """Extract the delete URL from the upload response.""" return upload_response["data"]["delete_url"] def get_display_url(self, upload_response: dict) -> str: """Extract the display URL from the upload response.""" return upload_response["data"]["display_url"] # ── Hash Generation ──────────────────────────────────────────────────────────── def generate_hash() -> str: """16-char URL-safe token (~96 bits entropy).""" return secrets.token_urlsafe(12)[:16] def generate_session_token() -> str: """64-char hex admin session token.""" return secrets.token_hex(32) # ── Telegram initData Verification ──────────────────────────────────────────── def verify_init_data(init_data_raw: str) -> bool: """ Verify Telegram WebApp initData via HMAC-SHA256. Spec: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app """ if not init_data_raw or not config.BOT_TOKEN: return False try: parsed = dict(urllib.parse.parse_qsl(init_data_raw, keep_blank_values=True)) received_hash = parsed.pop("hash", None) if not received_hash: return False data_check_string = "\n".join(f"{k}={v}" for k, v in sorted(parsed.items())) secret_key = hmac.new(b"WebAppData", config.BOT_TOKEN.encode(), hashlib.sha256).digest() computed = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(computed, received_hash) except Exception: return False def extract_user_from_init_data(init_data_raw: str) -> dict | None: if not verify_init_data(init_data_raw): return None try: parsed = dict(urllib.parse.parse_qsl(init_data_raw, keep_blank_values=True)) user_json = parsed.get("user") if not user_json: return None return json.loads(user_json) except Exception: return None def extract_user_id(init_data_raw: str) -> int | None: user = extract_user_from_init_data(init_data_raw) if user: return int(user.get("id", 0)) or None return None def is_owner_initdata(init_data_raw: str) -> bool: """Return True if verified initData belongs to any configured owner.""" uid = extract_user_id(init_data_raw) return uid is not None and config.is_owner(uid) # ── Password Hashing ─────────────────────────────────────────────────────────── def hash_password(plain: str) -> str: return bcrypt.hashpw(plain.encode(), bcrypt.gensalt(rounds=12)).decode() def check_password(plain: str, hashed: str) -> bool: if not hashed: return False return bcrypt.checkpw(plain.encode(), hashed.encode()) # ── Session Expiry ───────────────────────────────────────────────────────────── def session_is_valid(created_at) -> bool: """Accept datetime object or ISO string.""" try: if isinstance(created_at, str): created_at = datetime.fromisoformat(created_at) return datetime.utcnow() - created_at < timedelta(days=config.SESSION_TTL_DAYS) except Exception: return False