Created At: 2026-11-18T07:44:31Z Completed At: 2026-11-18T07:44:32Z Command exited with code 0. Command output: ==> /root/telegram-saas/core/security.py <== from datetime import datetime, timedelta, timezone import hashlib import uuid from typing import Any, Optional import jwt from argon2 import PasswordHasher from argon2.exceptions import VerifyMismatchError, VerificationError from core.config import get_settings from core.exceptions import UnauthorizedError _ph = PasswordHasher() def hash_password(password: str) -> str: """Hash password using Argon2id.""" return _ph.hash(password) def verify_password(password: str, hashed_password: str) -> bool: """Verify password with Argon2id.""" try: return _ph.verify(hashed_password, password) except (VerifyMismatchError, VerificationError): return False def hash_token(token: str) -> str: """Hash token using SHA-256 for secure session storage.""" return hashlib.sha256(token.encode("utf-8")).hexdigest() def create_access_token( data: dict[str, Any], expires_delta: Optional[timedelta] = None, ) -> str: settings = get_settings() to_encode = data.copy() expire = datetime.now(timezone.utc) + ( expires_delta or timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES) ) to_encode.update({ "exp": expire, "type": "access", "jti": uuid.uuid4().hex, }) return jwt.encode(to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM) def create_refresh_token( data: dict[str, Any], ==> /root/telegram-saas/core/encryption.py <== import base64 import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM from core.config import get_settings from core.exceptions import CryptoError def encrypt_string(plaintext: str, key_version: int | None = None) -> tuple[str, int]: """ Encrypt a plaintext string using AES-256-GCM. Returns (base64_encoded_payload, key_version). Payload format: 12-byte nonce + 16-byte tag + ciphertext (handled by AESGCM). """ if not plaintext: raise CryptoError("Cannot encrypt empty string") settings = get_settings() current_key_version = key_version or settings.ENCRYPTION_KEY_VERSION key = settings.raw_encryption_key try: aesgcm = AESGCM(key) nonce = os.urandom(12) # 96-bit nonce for GCM # AESGCM.encrypt appends 16-byte auth tag at the end of ciphertext ciphertext = aesgcm.encrypt(nonce, plaintext.encode("utf-8"), None) payload = nonce + ciphertext return base64.b64encode(payload).decode("ascii"), current_key_version except Exception as exc: raise CryptoError(f"Encryption failed: {exc}") from exc def decrypt_string(encrypted_payload_b64: str, key_version: int | None = None) -> str: """ Decrypt a base64-encoded AES-256-GCM payload. """ if not encrypted_payload_b64: raise CryptoError("Cannot decrypt empty payload") settings = get_settings() key = settings.raw_encryption_key try: raw_payload = base64.b64decode(encrypted_payload_b64) if len(raw_payload) < 28: # 12 bytes nonce + 16 bytes tag minimum raise CryptoError("Payload is too short to be valid AES-GCM ciphertext") nonce = raw_payload[:12] ciphertext = raw_payload[12:] aesgcm = AESGCM(key) ==> /root/telegram-saas/core/tenant_context.py <== import contextvars from contextlib import contextmanager from typing import Generator, Optional from uuid import UUID _tenant_id_ctx: contextvars.ContextVar[Optional[UUID]] = contextvars.ContextVar("tenant_id", default=None) _user_id_ctx: contextvars.ContextVar[Optional[UUID]] = contextvars.ContextVar("user_id", default=None) _request_id_ctx: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar("request_id", default=None) def get_current_tenant_id() -> Optional[UUID]: return _tenant_id_ctx.get() def set_current_tenant_id(tenant_id: Optional[UUID]) -> contextvars.Token: return _tenant_id_ctx.set(tenant_id) def reset_current_tenant_id(token: contextvars.Token) -> None: _tenant_id_ctx.reset(token) def get_current_user_id() -> Optional[UUID]: return _user_id_ctx.get() def set_current_user_id(user_id: Optional[UUID]) -> contextvars.Token: return _user_id_ctx.set(user_id) def reset_current_user_id(token: contextvars.Token) -> None: _user_id_ctx.reset(token) def get_current_request_id() -> Optional[str]: return _request_id_ctx.get() def set_current_request_id(request_id: Optional[str]) -> contextvars.Token: return _request_id_ctx.set(request_id) def reset_current_request_id(token: contextvars.Token) -> None: _request_id_ctx.reset(token) @contextmanager def tenant_scope(tenant_id: Optional[UUID]) -> Generator[None, None, None]: token = set_current_tenant_id(tenant_id) try: ==> /root/telegram-saas/core/idempotency.py <== from typing import Optional from core.exceptions import ConflictError from infrastructure.redis.client import get_redis_client class IdempotencyManager: """Ensures requests with Idempotency-Key are not executed twice.""" @staticmethod async def acquire_or_raise( key: str, tenant_id: Optional[str] = None, expire_seconds: int = 86400, ) -> bool: redis = await get_redis_client() redis_key = f"idempotency:{tenant_id or 'global'}:{key}" # SET NX EX acquired = await redis.set(redis_key, "IN_PROGRESS", nx=True, ex=expire_seconds) if not acquired: raise ConflictError("Request already submitted or processed (Idempotency conflict)") return True @staticmethod async def mark_completed( key: str, tenant_id: Optional[str] = None, result_payload: Optional[str] = "COMPLETED", expire_seconds: int = 86400, ) -> None: redis = await get_redis_client() redis_key = f"idempotency:{tenant_id or 'global'}:{key}" await redis.set(redis_key, result_payload or "COMPLETED", ex=expire_seconds)