# -*- coding: utf-8 -*- """Site-wide session login (cookie JWT).""" from __future__ import annotations import base64 import hashlib import hmac import json import secrets import time from typing import Any, Optional from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.types import ASGIApp, Receive, Scope, Send from .config import settings SESSION_COOKIE = "dy_session" SESSION_TTL_SEC = 7 * 86400 # Unauthenticated API paths (OAuth callback, login itself) _PUBLIC_API_PREFIXES = ( "/api/auth/login", "/api/auth/status", "/api/tiktok/oauth/callback/", ) _PUBLIC_API_EXACT = { "/api/health", "/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", } def _secret() -> str: s = str(settings.session_secret or "").strip() if s: return s return "douyinweb-default-session-secret" def hash_password(password: str) -> str: return hashlib.sha256(f"{_secret()}:{password}".encode()).hexdigest() def ensure_default_admin_credentials() -> None: """Ensure standard admin account uses config defaults (hackrobot / DY_ADMIN_PASSWORD).""" from . import db user = str(settings.admin_username or "hackrobot").strip() expected_hash = hash_password(str(settings.admin_password or "")) m = db.get_settings_map() cur_user = str(m.get("admin_username") or "").strip() cur_hash = str(m.get("admin_password_hash") or "").strip() updates: dict[str, str] = {} if not cur_user: updates["admin_username"] = user if not cur_hash or cur_user == user: if cur_hash != expected_hash: updates["admin_password_hash"] = expected_hash if not cur_user and "admin_username" not in updates: updates["admin_username"] = user if updates: db.update_settings_map(updates) def get_admin_credentials() -> tuple[str, str]: """Return (username, password_hash) from DB; seed from config on first use.""" from . import db m = db.get_settings_map() user = str(m.get("admin_username") or "").strip() pw_hash = str(m.get("admin_password_hash") or "").strip() if user and pw_hash: return user, pw_hash user = str(settings.admin_username or "hackrobot").strip() pw_hash = hash_password(str(settings.admin_password or "")) db.update_settings_map({"admin_username": user, "admin_password_hash": pw_hash}) return user, pw_hash def verify_admin(username: str, password: str) -> bool: user, pw_hash = get_admin_credentials() if not secrets.compare_digest(str(username or ""), user): return False return secrets.compare_digest(hash_password(str(password or "")), pw_hash) def change_admin_password(*, username: str, current_password: str, new_password: str) -> None: from . import db user, pw_hash = get_admin_credentials() if not secrets.compare_digest(str(username or ""), user): raise ValueError("无权限") if not secrets.compare_digest(hash_password(str(current_password or "")), pw_hash): raise ValueError("当前密码错误") new_p = str(new_password or "") if len(new_p) < 8: raise ValueError("新密码至少 8 位") db.update_settings_map({"admin_password_hash": hash_password(new_p)}) def create_session_token(username: str, *, role: str = "admin") -> str: payload = { "u": username, "role": role if role in {"admin", "readonly"} else "admin", "exp": int(time.time()) + SESSION_TTL_SEC, } body = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode().rstrip("=") sig = hmac.new(_secret().encode(), body.encode(), hashlib.sha256).hexdigest() return f"{body}.{sig}" def verify_session_token(token: str) -> Optional[str]: payload = verify_session_payload(token) if not payload: return None user = str(payload.get("u") or "").strip() return user or None def verify_session_payload(token: str) -> Optional[dict[str, Any]]: if not token or "." not in token: return None body, sig = token.rsplit(".", 1) expected = hmac.new(_secret().encode(), body.encode(), hashlib.sha256).hexdigest() if not secrets.compare_digest(sig, expected): return None pad = "=" * (-len(body) % 4) try: payload = json.loads(base64.urlsafe_b64decode(body + pad).decode()) except Exception: return None if int(payload.get("exp") or 0) < int(time.time()): return None user = str(payload.get("u") or "").strip() if not user: return None return payload def session_user_from_request(request: Request) -> Optional[str]: if not settings.auth_enabled: return str(settings.admin_username or "admin") token = (request.cookies.get(SESSION_COOKIE) or "").strip() if not token: auth = request.headers.get("Authorization") or "" if auth.lower().startswith("bearer "): token = auth[7:].strip() return verify_session_token(token) if token else None def set_session_cookie(response: Response, username: str, *, secure: bool, role: str = "admin") -> None: token = create_session_token(username, role=role) response.set_cookie( key=SESSION_COOKIE, value=token, httponly=True, secure=secure, samesite="lax", max_age=SESSION_TTL_SEC, path="/", ) def clear_session_cookie(response: Response) -> None: response.delete_cookie(key=SESSION_COOKIE, path="/") def _request_secure(request: Request) -> bool: proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "http").split(",")[0].strip() return proto == "https" class SessionAuthMiddleware: """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 if not settings.auth_enabled: await self.app(scope, receive, send) return request = Request(scope, receive=receive) path = request.url.path method = str(scope.get("method") or "GET").upper() # Live session thumbnails — allow without cookie (uuid is unguessable). if method in {"GET", "HEAD"} and path.startswith("/api/sessions/") and path.endswith("/cover"): await self.app(scope, receive, send) return if path.startswith("/covers/"): if session_user_from_request(request): await self.app(scope, receive, send) return resp = JSONResponse({"detail": "未登录"}, status_code=401) await resp(scope, receive, send) return if not path.startswith("/api/"): await self.app(scope, receive, send) return if path in _PUBLIC_API_EXACT or any(path.startswith(p) for p in _PUBLIC_API_PREFIXES): await self.app(scope, receive, send) return user = session_user_from_request(request) if user: method = str(scope.get("method") or "GET").upper() if method in {"POST", "PUT", "PATCH", "DELETE"}: from .authz import session_role_from_request if session_role_from_request(request) == "readonly": allowed = {"/api/auth/logout"} if path not in allowed: resp = JSONResponse({"detail": "只读账号无写入权限"}, status_code=403) await resp(scope, receive, send) return await self.app(scope, receive, send) return resp = JSONResponse({"detail": "未登录,请先登录"}, status_code=401) await resp(scope, receive, send)