from __future__ import annotations import base64 import hmac import os import secrets import time from html import escape from pathlib import Path from typing import Any from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse, JSONResponse from pydantic import BaseModel from license_server.core import LicenseActionResult, LicenseService RATE_LIMIT_WINDOW_SECONDS = 60 RATE_LIMIT_MAX_REQUESTS = 30 ADMIN_CSRF_COOKIE = "dygj_admin_csrf" class ActivateRequest(BaseModel): card_key: str machine_fingerprint: str class VerifyRequest(BaseModel): card_key: str machine_fingerprint: str def result_response(result: LicenseActionResult) -> JSONResponse: body: dict[str, Any] = { "ok": result.ok, "reason": result.reason, "message": result.message, } if result.license_doc is not None: body["license"] = result.license_doc if result.expires_at is not None: body["expires_at"] = result.expires_at.isoformat().replace("+00:00", "Z") status = 200 if result.ok else _status_for_reason(result.reason) return JSONResponse(body, status_code=status) def _status_for_reason(reason: str) -> int: if reason == "rate_limited": return 429 if reason == "not_found": return 404 if reason in {"revoked", "inactive", "device_limit", "machine_mismatch"}: return 403 if reason in {"missing_machine", "not_activated"}: return 400 return 400 def load_private_key_pem() -> bytes: raw_path = str(os.environ.get("DYGJ_LICENSE_PRIVATE_KEY_PATH") or "").strip() if raw_path: return Path(raw_path).read_bytes() raw_pem = str(os.environ.get("DYGJ_LICENSE_PRIVATE_KEY_PEM") or "").strip() if raw_pem: return raw_pem.encode("utf-8") raise RuntimeError("missing DYGJ_LICENSE_PRIVATE_KEY_PATH or DYGJ_LICENSE_PRIVATE_KEY_PEM") def create_service_from_env() -> LicenseService: db_path = os.environ.get("DYGJ_LICENSE_DB_PATH") or "/opt/douyin-license-server/data/app.db" return LicenseService(db_path=db_path, private_key_pem=load_private_key_pem()) def admin_token_from_env() -> str: return str(os.environ.get("DYGJ_LICENSE_ADMIN_TOKEN") or "").strip() def _admin_allowed(request: Request, admin_token: str) -> bool: expected = str(admin_token or "").strip() if not expected: return False auth = str(request.headers.get("authorization") or "").strip() if hmac.compare_digest(auth, f"Bearer {expected}"): return True if not auth.lower().startswith("basic "): return False try: decoded = base64.b64decode(auth.split(" ", 1)[1], validate=True).decode("utf-8") except Exception: return False _user, sep, supplied = decoded.partition(":") if not sep: return False return hmac.compare_digest(supplied, expected) def _admin_forbidden() -> HTMLResponse: return HTMLResponse( "

403

需要管理员登录。

", status_code=403, headers={"WWW-Authenticate": 'Basic realm="Douyin License Admin"'}, ) def _csrf_token(request: Request) -> str: raw = str(request.cookies.get(ADMIN_CSRF_COOKIE) or "").strip() if len(raw) >= 32: return raw return secrets.token_urlsafe(24) def _csrf_allowed(request: Request, token: str) -> bool: cookie = str(request.cookies.get(ADMIN_CSRF_COOKIE) or "").strip() supplied = str(token or "").strip() return bool(cookie and supplied and hmac.compare_digest(cookie, supplied)) def _rate_limit_key(request: Request, scope: str) -> str: forwarded = str(request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip() host = forwarded or (request.client.host if request.client else "unknown") return f"{scope}:{host}" def _rate_limited(request: Request, scope: str, *, max_requests: int | None = None) -> bool: threshold = RATE_LIMIT_MAX_REQUESTS if max_requests is None else int(max_requests) now = time.monotonic() key = _rate_limit_key(request, scope) buckets: dict[str, list[float]] = request.app.state.rate_limit_buckets recent = [ts for ts in buckets.get(key, []) if now - ts < RATE_LIMIT_WINDOW_SECONDS] if len(recent) >= threshold: buckets[key] = recent return True recent.append(now) buckets[key] = recent return False def _admin_page( service: LicenseService, csrf_token: str, message: str = "", cards: list[str] | None = None, ) -> HTMLResponse: csrf_attr = escape(csrf_token, quote=True) stats = service.stats() card_rows = service.list_cards(limit=50) audit_rows = service.audit_logs(limit=30) created_rows = "".join( f"
  • {escape(card)}
  • " for card in (cards or []) ) table_rows = "".join( "" f"#{row.id}" f"{escape(row.code_hint)}" f"{escape(row.status)}" f"{row.days}" f"{row.activation_count}/{row.max_devices}" f"{escape(row.customer)}" f"{escape(row.created_at)}" f"{escape(row.last_seen_at)}" "" for row in card_rows ) audit_html = "".join( "" f"{escape(row.created_at)}" f"{escape(row.action)}" f"{escape(row.code_hint)}" f"{escape(row.machine_fingerprint[:16])}" f"{escape(row.reason)}" "" for row in audit_rows ) message_html = f"

    {escape(message)}

    " if message else "" html = f""" 卡密管理

    卡密管理

    生成、禁用、解绑设备,并查看最近激活日志。
    总卡密 {stats["total"]}
    活跃卡密 {stats["active"]}
    已禁用 {stats["revoked"]}
    已绑定设备 {stats["activations"]}
    {message_html}

    生成卡密

    禁用卡密

    解绑设备

    最近卡密

    {table_rows}
    ID卡密状态天数设备客户创建时间最后在线

    最近审计日志

    {audit_html}
    时间动作卡密机器结果
    """ return HTMLResponse(html) def create_app( *, service: LicenseService | None = None, admin_token: str | None = None, ) -> FastAPI: app = FastAPI(title="Douyin Guaji License Server") app.state.license_service = service app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env() app.state.rate_limit_buckets = {} def get_service() -> LicenseService: if app.state.license_service is None: app.state.license_service = create_service_from_env() return app.state.license_service @app.get("/api/v1/health") def health() -> dict[str, Any]: return {"ok": True, "service": "douyin-license-server"} @app.post("/api/v1/activate") def activate(request: Request, req: ActivateRequest) -> JSONResponse: if _rate_limited(request, "activate"): return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试")) return result_response( get_service().activate( req.card_key, machine_fingerprint=req.machine_fingerprint, ) ) @app.post("/api/v1/verify") def verify(request: Request, req: VerifyRequest) -> JSONResponse: if _rate_limited(request, "verify"): return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试")) return result_response( get_service().verify( req.card_key, machine_fingerprint=req.machine_fingerprint, ) ) @app.get("/admin") def admin(request: Request) -> HTMLResponse: if not _admin_allowed(request, app.state.admin_token): return _admin_forbidden() csrf = _csrf_token(request) response = _admin_page(get_service(), csrf) response.set_cookie(ADMIN_CSRF_COOKIE, csrf, httponly=True, samesite="lax") return response @app.post("/admin/create") def admin_create( request: Request, csrf_token: str = Form(""), days: int = Form(30), count: int = Form(1), max_devices: int = Form(1), customer: str = Form(""), ) -> HTMLResponse: if not _admin_allowed(request, app.state.admin_token): return _admin_forbidden() csrf = _csrf_token(request) if not _csrf_allowed(request, csrf_token): return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试") try: cards = get_service().create_cards( days=days, count=count, max_devices=max_devices, customer=customer, ) message = f"已生成 {len(cards)} 个卡密,customer={customer}" except ValueError as exc: cards = [] message = f"参数错误:{exc}" return _admin_page( get_service(), csrf, message=message, cards=[card.code for card in cards], ) @app.post("/admin/revoke") def admin_revoke( request: Request, csrf_token: str = Form(""), card_key: str = Form(""), ) -> HTMLResponse: if not _admin_allowed(request, app.state.admin_token): return _admin_forbidden() csrf = _csrf_token(request) if not _csrf_allowed(request, csrf_token): return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试") ok = get_service().revoke(card_key) msg = "已禁用" if ok else "卡密不存在" return _admin_page( get_service(), csrf, message=msg, ) @app.post("/admin/unbind") def admin_unbind( request: Request, csrf_token: str = Form(""), card_key: str = Form(""), ) -> HTMLResponse: if not _admin_allowed(request, app.state.admin_token): return _admin_forbidden() csrf = _csrf_token(request) if not _csrf_allowed(request, csrf_token): return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试") count = get_service().unbind(card_key) return _admin_page( get_service(), csrf, message=f"已解绑 {count} 台设备", ) return app app = create_app()