diff --git a/douyin/license/public_key.py b/douyin/license/public_key.py index 8466d47..e117646 100644 --- a/douyin/license/public_key.py +++ b/douyin/license/public_key.py @@ -4,6 +4,6 @@ """ PUBLIC_KEY_PEM = b"""-----BEGIN PUBLIC KEY----- -MCowBQYDK2VwAyEA/lneBfaW7y3NCJhRkvZFSo822jWqHTYPce8Phssu2aw= +MCowBQYDK2VwAyEA3g7inE/9SRkEDseJIp7j5J6vWlvSgitHErypisMY29o= -----END PUBLIC KEY----- """ diff --git a/license_server/README.md b/license_server/README.md index 51e0fbd..bf5d165 100644 --- a/license_server/README.md +++ b/license_server/README.md @@ -15,7 +15,7 @@ python -m license_server.manage --db data/app.db unbind DG-XXXX-XXXX-XXXX-XXXX-X GET /api/v1/health POST /api/v1/activate POST /api/v1/verify -GET /admin?token=管理员TOKEN +GET /admin ``` `/api/v1/activate` 请求: @@ -54,17 +54,18 @@ http://127.0.0.1:18100 } ``` -注意:`secrets/private_key.pem` 只能放服务器,不能随客户端分发。 +注意:必须显式配置 `DYGJ_LICENSE_PRIVATE_KEY_PATH` 或 `DYGJ_LICENSE_PRIVATE_KEY_PEM`。 +`secrets/private_key.pem` 只能放服务器,不能随客户端分发。 ## 最小网页后台 后台和激活接口共用同一个服务端口,不需要额外开放端口: ```text -http://服务器IP:18100/admin?token=管理员TOKEN +http://服务器IP:18100/admin ``` -管理员 token 建议放在服务器: +浏览器会弹出 Basic 登录框,用户名可随便填,密码填写管理员 token。管理员 token 建议放在服务器: ```text /opt/douyin-license-server/secrets/admin_token.txt @@ -75,3 +76,5 @@ http://服务器IP:18100/admin?token=管理员TOKEN ```bash export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)" ``` + +不要把管理员 token 放到 URL 里,避免进入浏览器历史、访问日志或截图。 diff --git a/license_server/api.py b/license_server/api.py index 9d1f9ed..55b2c1c 100644 --- a/license_server/api.py +++ b/license_server/api.py @@ -1,6 +1,10 @@ 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 @@ -9,7 +13,12 @@ from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse, JSONResponse from pydantic import BaseModel -from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseActionResult, LicenseService +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): @@ -37,6 +46,8 @@ def result_response(result: LicenseActionResult) -> JSONResponse: 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"}: @@ -53,7 +64,7 @@ def load_private_key_pem() -> bytes: raw_pem = str(os.environ.get("DYGJ_LICENSE_PRIVATE_KEY_PEM") or "").strip() if raw_pem: return raw_pem.encode("utf-8") - return DEV_PRIVATE_KEY_PEM + raise RuntimeError("missing DYGJ_LICENSE_PRIVATE_KEY_PATH or DYGJ_LICENSE_PRIVATE_KEY_PEM") def create_service_from_env() -> LicenseService: @@ -69,24 +80,69 @@ def _admin_allowed(request: Request, admin_token: str) -> bool: expected = str(admin_token or "").strip() if not expected: return False - supplied = str(request.query_params.get("token") or "").strip() - if supplied == expected: - return True auth = str(request.headers.get("authorization") or "").strip() - return auth == f"Bearer {expected}" + 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("
需要管理员 token。
", status_code=403) + return HTMLResponse( + "需要管理员登录。
", + 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, - token: str, + csrf_token: str, message: str = "", cards: list[str] | None = None, ) -> HTMLResponse: - token_attr = escape(token, quote=True) + csrf_attr = escape(csrf_token, quote=True) stats = service.stats() card_rows = service.list_cards(limit=50) audit_rows = service.audit_logs(limit=30) @@ -168,7 +224,8 @@ def _admin_page( {message_html}