from __future__ import annotations import hashlib import json import secrets import sqlite3 from datetime import datetime, timedelta, timezone from typing import Any from cracklab.server.repositories.search_contexts import ( SearchContextsRepository, ) SEARCH_CONTEXT_TTL = timedelta(hours=2) class SearchContextError(ValueError): pass class SearchContextService: def __init__(self, conn: sqlite3.Connection) -> None: self._conn = conn self._repository = SearchContextsRepository(conn) @staticmethod def _utc_now() -> datetime: return datetime.now(timezone.utc) @staticmethod def _format_datetime(value: datetime) -> str: return value.isoformat( timespec="seconds", ).replace("+00:00", "Z") @staticmethod def _token_hash(token: str) -> str: return hashlib.sha256( token.encode("utf-8"), ).hexdigest() @staticmethod def _normalize_handshake_ids( handshake_ids: list[int] | tuple[int, ...], ) -> list[int]: if not isinstance(handshake_ids, (list, tuple)): raise SearchContextError( "Invalid handshake ID collection." ) normalized: set[int] = set() for handshake_id in handshake_ids: if ( isinstance(handshake_id, bool) or not isinstance(handshake_id, int) or handshake_id <= 0 ): raise SearchContextError( "Invalid handshake ID." ) normalized.add(handshake_id) return sorted(normalized) def create_context( self, criteria: dict[str, Any], handshake_ids: list[int] | tuple[int, ...], matched_access_point_count: int, ) -> dict[str, Any]: if not isinstance(criteria, dict) or not criteria: raise SearchContextError( "Search criteria are required." ) if ( isinstance(matched_access_point_count, bool) or not isinstance(matched_access_point_count, int) or matched_access_point_count < 0 ): raise SearchContextError( "Invalid matched access point count." ) normalized_ids = self._normalize_handshake_ids( handshake_ids, ) try: criteria_json = json.dumps( criteria, ensure_ascii=False, separators=(",", ":"), sort_keys=True, ) except (TypeError, ValueError) as exc: raise SearchContextError( "Search criteria cannot be serialized." ) from exc token = secrets.token_urlsafe(32) token_hash = self._token_hash(token) now = self._utc_now() created_at = self._format_datetime(now) expires_at = self._format_datetime( now + SEARCH_CONTEXT_TTL, ) self._conn.execute("BEGIN IMMEDIATE") try: self._repository.create_context( token_hash=token_hash, criteria_json=criteria_json, matched_access_point_count=( matched_access_point_count ), handshake_count=len(normalized_ids), created_at=created_at, expires_at=expires_at, ) self._repository.add_handshakes( token_hash, normalized_ids, ) self._conn.commit() except Exception: self._conn.rollback() raise return { "token": token, "created_at": created_at, "expires_at": expires_at, "matched_access_point_count": ( matched_access_point_count ), "handshake_count": len(normalized_ids), } def get_context( self, token: str, ) -> dict[str, Any] | None: if not isinstance(token, str) or not token: return None token_hash = self._token_hash(token) row = self._repository.get_context( token_hash, ) if row is None: return None now = self._format_datetime( self._utc_now(), ) return { "id": int(row["id"]), "token_hash": row["token_hash"], "criteria": json.loads(row["criteria_json"]), "matched_access_point_count": int( row["matched_access_point_count"] ), "handshake_count": int(row["handshake_count"]), "created_at": row["created_at"], "expires_at": row["expires_at"], "expired": row["expires_at"] <= now, } def list_handshake_ids( self, token: str, ) -> list[int]: if not isinstance(token, str) or not token: raise SearchContextError( "Invalid search context token." ) return self._repository.list_handshake_ids( self._token_hash(token), ) def delete_expired(self) -> int: now = self._format_datetime( self._utc_now(), ) self._conn.execute("BEGIN IMMEDIATE") try: deleted = self._repository.delete_expired( now, ) self._conn.commit() except Exception: self._conn.rollback() raise return deleted