# -*- coding: utf-8 -*- """Optional API key gate for mutating routes (DY_API_KEY).""" from __future__ import annotations from starlette.datastructures import Headers, QueryParams from starlette.responses import JSONResponse from starlette.types import ASGIApp, Receive, Scope, Send from .config import settings # OAuth redirect + SSE + static covers — never block _PUBLIC_PATHS = { "/api/shorts/oauth/callback", "/api/tiktok/oauth/callback/", "/api/tiktok/oauth/callback", "/api/events/stream", "/api/x2/ingest", "/api/x2/extension/poll", "/api/x2/extension/ws", "/api/youtube/studio/ingest", "/hub/youtube/live/ingest", } class ApiKeyMiddleware: """Pure ASGI middleware — avoid BaseHTTPMiddleware (deadlocks SSE/streaming).""" def __init__(self, app: ASGIApp): self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return required = str(settings.api_key or "").strip() if not required: await self.app(scope, receive, send) return path = scope.get("path") or "" method = (scope.get("method") or "GET").upper() if path in _PUBLIC_PATHS or path.startswith("/covers/"): await self.app(scope, receive, send) return if method in {"GET", "HEAD", "OPTIONS"}: await self.app(scope, receive, send) return headers = Headers(scope=scope) qs = QueryParams((scope.get("query_string") or b"").decode("latin-1")) provided = ( headers.get("X-API-Key") or headers.get("x-api-key") or qs.get("api_key") or "" ).strip() if provided != required: resp = JSONResponse({"detail": "需要 API Key(请求头 X-API-Key)"}, status_code=401) await resp(scope, receive, send) return await self.app(scope, receive, send)