"""Persistence (SQLAlchemy 2.0 async). PostgreSQL in production, SQLite for local development. Privacy by design: only the host name, a SHA-256 of the sanitised URL, and the verdict are stored. Full URLs, query strings and client IP addresses are never written to the database. """ from __future__ import annotations from datetime import datetime, timezone from sqlalchemy import Boolean, DateTime, Integer, String, func, select, text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column def _utcnow() -> datetime: return datetime.now(timezone.utc) class Base(DeclarativeBase): pass class Scan(Base): __tablename__ = "scans" id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) tenant: Mapped[str] = mapped_column(String(64), index=True) domain: Mapped[str] = mapped_column(String(253)) url_hash: Mapped[str] = mapped_column(String(64), index=True) score: Mapped[int] = mapped_column(Integer) verdict: Mapped[str] = mapped_column(String(16)) threat_type: Mapped[str] = mapped_column(String(200), default="") source: Mapped[str] = mapped_column(String(32), default="") degraded: Mapped[bool] = mapped_column(Boolean, default=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, index=True) class Database: def __init__(self, url: str): self.engine = create_async_engine(url, pool_pre_ping=True) self.sessions = async_sessionmaker(self.engine, expire_on_commit=False) async def init(self) -> None: async with self.engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def close(self) -> None: await self.engine.dispose() async def ping(self) -> bool: async with self.engine.connect() as conn: await conn.execute(text("SELECT 1")) return True async def log_scan(self, tenant: str, host: str, url_hash: str, result: dict) -> None: async with self.sessions() as session: session.add(Scan(tenant=tenant, domain=host, url_hash=url_hash, score=int(result["risk_score"]), verdict=result["verdict"], threat_type=str(result.get("threat_type", ""))[:200], source=str(result.get("source", ""))[:32], degraded=bool(result.get("degraded")))) await session.commit() async def stats(self, tenant: str) -> dict: async with self.sessions() as session: rows = (await session.execute( select(Scan.verdict, func.count()).where(Scan.tenant == tenant).group_by(Scan.verdict))).all() counts = {v: n for v, n in rows} safe, bad, sus = counts.get("SAFE", 0), counts.get("MALICIOUS", 0), counts.get("SUSPICIOUS", 0) return {"total_scans": safe + bad + sus, "safe": safe, "phishing": bad, "suspicious": sus} async def recent(self, tenant: str, limit: int = 10) -> list[dict]: async with self.sessions() as session: rows = (await session.execute( select(Scan).where(Scan.tenant == tenant).order_by(Scan.created_at.desc(), Scan.id.desc()) .limit(max(1, min(limit, 100))))).scalars().all() return [{"_id": r.id, "domain": r.domain, "risk_score": r.score, "verdict": r.verdict, "reason": r.threat_type, "timestamp": r.created_at.isoformat()} for r in rows]