1130 lines
44 KiB
Python
1130 lines
44 KiB
Python
from __future__ import annotations
|
||
|
||
import base64
|
||
import hmac
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import secrets
|
||
import tempfile
|
||
import time
|
||
from html import escape
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from urllib.parse import urljoin, urlparse
|
||
|
||
from fastapi import FastAPI, File, Form, Request, UploadFile
|
||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
|
||
from pydantic import BaseModel
|
||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||
|
||
from license_server.core import LicenseActionResult, LicenseService, UpdateManifest
|
||
|
||
|
||
RATE_LIMIT_WINDOW_SECONDS = 60
|
||
RATE_LIMIT_MAX_REQUESTS = 30
|
||
ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS = 10
|
||
VERIFY_LICENSE_RATE_LIMIT_MAX_REQUESTS = 600
|
||
EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS = 10
|
||
REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS = 60
|
||
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
|
||
ADMIN_SESSION_COOKIE = "dygj_admin_session"
|
||
ADMIN_SESSION_SECONDS = 12 * 60 * 60
|
||
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES = 700 * 1024 * 1024
|
||
DEFAULT_MAX_DELTA_UPLOAD_BYTES = 250 * 1024 * 1024
|
||
DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES = 500 * 1024 * 1024
|
||
UPLOAD_CHUNK_BYTES = 1024 * 1024
|
||
|
||
|
||
class ActivateRequest(BaseModel):
|
||
card_key: str
|
||
machine_fingerprint: str
|
||
|
||
|
||
class VerifyRequest(BaseModel):
|
||
card_key: str
|
||
machine_fingerprint: str
|
||
|
||
|
||
class VerifyLicenseRequest(BaseModel):
|
||
license: dict[str, Any]
|
||
|
||
|
||
class CreateRedeemRequest(BaseModel):
|
||
days: int
|
||
max_devices: int = 1
|
||
customer: str = ""
|
||
platform: str = ""
|
||
external_order_id: str = ""
|
||
expires_hours: int = 72
|
||
|
||
|
||
class ClaimRedeemRequest(BaseModel):
|
||
token: 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 external_api_token_from_env() -> str:
|
||
return str(os.environ.get("DYGJ_LICENSE_EXTERNAL_API_TOKEN") or "").strip()
|
||
|
||
|
||
def _env_bool(name: str, default: bool = False) -> bool:
|
||
raw = str(os.environ.get(name) or "").strip().lower()
|
||
if raw in {"1", "true", "yes", "y", "on"}:
|
||
return True
|
||
if raw in {"0", "false", "no", "n", "off"}:
|
||
return False
|
||
return default
|
||
|
||
|
||
def _env_int(name: str, default: int) -> int:
|
||
raw = str(os.environ.get(name) or "").strip()
|
||
if not raw:
|
||
return int(default)
|
||
try:
|
||
value = int(raw)
|
||
except ValueError:
|
||
return int(default)
|
||
return value if value > 0 else int(default)
|
||
|
||
|
||
def _configured_public_base_url() -> str:
|
||
return str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
|
||
|
||
|
||
def _default_secure_cookies() -> bool:
|
||
return _configured_public_base_url().lower().startswith("https://")
|
||
|
||
|
||
def _allowed_hosts_from_env() -> list[str]:
|
||
raw = str(os.environ.get("DYGJ_LICENSE_ALLOWED_HOSTS") or "").strip()
|
||
hosts = [h.strip() for h in raw.split(",") if h.strip()]
|
||
configured = _configured_public_base_url()
|
||
if configured:
|
||
parsed = urlparse(configured)
|
||
if parsed.hostname:
|
||
hosts.append(parsed.hostname)
|
||
hosts.extend(["dy.absfan.cn", "127.0.0.1", "localhost", "testserver"])
|
||
result: list[str] = []
|
||
for host in hosts:
|
||
if host and host not in result:
|
||
result.append(host)
|
||
return result
|
||
|
||
|
||
async def _save_upload_to_temp(
|
||
upload: UploadFile,
|
||
*,
|
||
upload_dir: Path,
|
||
max_bytes: int,
|
||
suffix: str,
|
||
) -> Path:
|
||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||
tmp_name = ""
|
||
total = 0
|
||
try:
|
||
with tempfile.NamedTemporaryFile(
|
||
"wb",
|
||
delete=False,
|
||
dir=str(upload_dir),
|
||
suffix=suffix,
|
||
) as tmp:
|
||
tmp_name = tmp.name
|
||
while True:
|
||
chunk = await upload.read(UPLOAD_CHUNK_BYTES)
|
||
if not chunk:
|
||
break
|
||
total += len(chunk)
|
||
if total > max_bytes:
|
||
raise ValueError(f"上传文件超过大小限制(最大 {max_bytes // (1024 * 1024)} MB)")
|
||
tmp.write(chunk)
|
||
if total <= 0:
|
||
raise ValueError("上传文件为空")
|
||
return Path(tmp_name)
|
||
except Exception:
|
||
if tmp_name:
|
||
try:
|
||
Path(tmp_name).unlink(missing_ok=True)
|
||
except Exception:
|
||
pass
|
||
raise
|
||
finally:
|
||
try:
|
||
await upload.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _admin_allowed(request: Request, admin_token: str) -> bool:
|
||
expected = str(admin_token or "").strip()
|
||
if not expected:
|
||
return False
|
||
session = str(request.cookies.get(ADMIN_SESSION_COOKIE) or "").strip()
|
||
sessions: dict[str, float] = request.app.state.admin_sessions
|
||
expires_at = sessions.get(_session_hash(session), 0.0)
|
||
if session and expires_at > time.time():
|
||
return True
|
||
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 _bearer_token_allowed(request: Request, expected_token: str) -> bool:
|
||
expected = str(expected_token or "").strip()
|
||
if not expected:
|
||
return False
|
||
auth = str(request.headers.get("authorization") or "").strip()
|
||
if not auth.lower().startswith("bearer "):
|
||
return False
|
||
supplied = auth.split(" ", 1)[1].strip()
|
||
return hmac.compare_digest(supplied, expected)
|
||
|
||
|
||
def _session_hash(raw: str) -> str:
|
||
return hashlib.sha256(str(raw or "").encode("utf-8")).hexdigest()
|
||
|
||
|
||
def _new_admin_session(request: Request) -> str:
|
||
raw = secrets.token_urlsafe(32)
|
||
request.app.state.admin_sessions[_session_hash(raw)] = time.time() + ADMIN_SESSION_SECONDS
|
||
return raw
|
||
|
||
|
||
def _drop_admin_session(request: Request) -> None:
|
||
raw = str(request.cookies.get(ADMIN_SESSION_COOKIE) or "").strip()
|
||
if raw:
|
||
request.app.state.admin_sessions.pop(_session_hash(raw), None)
|
||
|
||
|
||
def _admin_forbidden() -> HTMLResponse:
|
||
return _login_page("请先登录后台。", status_code=403)
|
||
|
||
|
||
def _login_page(message: str = "", *, status_code: int = 200) -> HTMLResponse:
|
||
message_html = f"<p class='msg'>{escape(message)}</p>" if message else ""
|
||
html = f"""<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>卡密后台登录</title>
|
||
<style>
|
||
body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: "Microsoft YaHei", sans-serif; background: radial-gradient(circle at top left, #dbeafe, transparent 32%), #0f172a; color: #0f172a; }}
|
||
main {{ width: min(420px, calc(100vw - 32px)); background: #fff; border-radius: 24px; padding: 28px; box-shadow: 0 28px 80px rgba(15, 23, 42, .35); }}
|
||
h1 {{ margin: 0 0 8px; font-size: 28px; }}
|
||
p {{ color: #64748b; margin: 0 0 18px; }}
|
||
label {{ display: block; color: #475569; font-size: 14px; }}
|
||
input {{ width: 100%; box-sizing: border-box; padding: 12px 14px; border: 1px solid #cbd5e1; border-radius: 12px; margin-top: 8px; font-size: 15px; }}
|
||
button {{ width: 100%; margin-top: 16px; padding: 12px 16px; cursor: pointer; border: 0; border-radius: 12px; background: #2563eb; color: white; font-weight: 800; font-size: 15px; }}
|
||
.msg {{ padding: 10px 12px; background: #fff7ed; border: 1px solid #fed7aa; border-radius: 10px; color: #9a3412; }}
|
||
.hint {{ font-size: 13px; color: #64748b; margin-top: 14px; }}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<h1>卡密后台登录</h1>
|
||
<p>请输入服务器管理员 token。</p>
|
||
{message_html}
|
||
<form method="post" action="/admin/login">
|
||
<label>管理员 token
|
||
<input name="admin_token" type="password" autocomplete="current-password" autofocus />
|
||
</label>
|
||
<button type="submit">登录后台</button>
|
||
</form>
|
||
<div class="hint">登录后会写入 HttpOnly 会话 cookie,不会把 token 放进 URL。</div>
|
||
</main>
|
||
</body>
|
||
</html>"""
|
||
return HTMLResponse(html, status_code=status_code)
|
||
|
||
|
||
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:
|
||
host = request.client.host if request.client else "unknown"
|
||
if getattr(request.app.state, "trust_forwarded_for", False):
|
||
forwarded = str(request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip()
|
||
host = forwarded or host
|
||
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 _public_base_url(request: Request) -> str:
|
||
configured = _configured_public_base_url()
|
||
if configured:
|
||
return configured.rstrip("/")
|
||
return str(request.base_url).rstrip("/")
|
||
|
||
|
||
def _signed_update_manifest(service: LicenseService, request: Request) -> dict[str, Any]:
|
||
manifest = service.load_update_manifest()
|
||
if not manifest.enabled:
|
||
payload: dict[str, Any] = {
|
||
"enabled": False,
|
||
"version": "0.0.0",
|
||
"force": False,
|
||
"message": "no update published",
|
||
}
|
||
payload["signature"] = service.sign_payload(payload)
|
||
return payload
|
||
|
||
download_path = f"/api/v1/update/download/{manifest.filename}"
|
||
payload = {
|
||
"enabled": True,
|
||
"version": manifest.version,
|
||
"url": urljoin(_public_base_url(request) + "/", download_path.lstrip("/")),
|
||
"filename": manifest.filename,
|
||
"sha256": manifest.sha256,
|
||
"force": manifest.force,
|
||
"notes": manifest.notes,
|
||
"published_at": manifest.published_at,
|
||
}
|
||
if manifest.delta:
|
||
raw_deltas = manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]
|
||
deltas: list[dict[str, Any]] = []
|
||
for raw_delta in raw_deltas:
|
||
if not isinstance(raw_delta, dict):
|
||
continue
|
||
delta = dict(raw_delta)
|
||
delta_filename = str(delta.get("filename") or "")
|
||
if delta_filename:
|
||
delta_path = f"/api/v1/update/download/{delta_filename}"
|
||
delta["url"] = urljoin(_public_base_url(request) + "/", delta_path.lstrip("/"))
|
||
deltas.append(delta)
|
||
payload["delta"] = deltas[0] if len(deltas) == 1 else deltas
|
||
payload["signature"] = service.sign_payload(payload)
|
||
return payload
|
||
|
||
|
||
def _update_summary_html(manifest: UpdateManifest) -> str:
|
||
status = "已开启" if manifest.enabled else "未发布/已关闭"
|
||
sha = manifest.sha256[:12] + "..." if manifest.sha256 else "-"
|
||
file_name = manifest.filename or "-"
|
||
published = manifest.published_at or "-"
|
||
raw_delta = manifest.delta or {}
|
||
delta_text = "-"
|
||
if raw_delta:
|
||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||
delta_text = "<br>".join(
|
||
f"{escape(str(delta.get('from_version') or ''))}"
|
||
f" -> {escape(str(delta.get('to_version') or ''))} / "
|
||
f"<code>{escape(str(delta.get('filename') or '-'))}</code>"
|
||
for delta in deltas
|
||
if isinstance(delta, dict)
|
||
)
|
||
return (
|
||
"<div class='update-state'>"
|
||
f"<b>{escape(status)}</b>"
|
||
f"<span>版本:<code>{escape(manifest.version or '0.0.0')}</code></span>"
|
||
f"<span>文件:<code>{escape(file_name)}</code></span>"
|
||
f"<span>SHA256:<code>{escape(sha)}</code></span>"
|
||
f"<span>差量包:{delta_text}</span>"
|
||
f"<span>发布时间:{escape(published)}</span>"
|
||
"</div>"
|
||
)
|
||
|
||
|
||
def _format_bytes(size: int) -> str:
|
||
value = float(size or 0)
|
||
for unit in ("B", "KB", "MB", "GB"):
|
||
if value < 1024 or unit == "GB":
|
||
return f"{value:.1f} {unit}" if unit != "B" else f"{int(value)} B"
|
||
value /= 1024
|
||
return f"{int(size)} B"
|
||
|
||
|
||
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)
|
||
diagnostic_rows = service.list_diagnostic_logs(limit=30)
|
||
update_manifest = service.load_update_manifest()
|
||
update_html = _update_summary_html(update_manifest)
|
||
created_rows = "".join(
|
||
f"<li><code>{escape(card)}</code></li>" for card in (cards or [])
|
||
)
|
||
table_rows = "".join(
|
||
"<tr>"
|
||
f"<td>#{row.id}</td>"
|
||
f"<td><code>{escape(row.code_hint)}</code></td>"
|
||
f"<td><span class='status {escape(row.status)}'>{escape(row.status)}</span></td>"
|
||
f"<td>{row.days}</td>"
|
||
f"<td>{row.activation_count}/{row.max_devices}</td>"
|
||
f"<td>{escape(row.customer)}</td>"
|
||
f"<td>{escape(row.created_at)}</td>"
|
||
f"<td>{escape(row.last_seen_at)}</td>"
|
||
"</tr>"
|
||
for row in card_rows
|
||
)
|
||
audit_html = "".join(
|
||
"<tr>"
|
||
f"<td>{escape(row.created_at)}</td>"
|
||
f"<td>{escape(row.action)}</td>"
|
||
f"<td><code>{escape(row.code_hint)}</code></td>"
|
||
f"<td><code>{escape(row.machine_fingerprint[:16])}</code></td>"
|
||
f"<td>{escape(row.reason)}</td>"
|
||
"</tr>"
|
||
for row in audit_rows
|
||
)
|
||
diagnostic_html = "".join(
|
||
"<tr>"
|
||
f"<td>{escape(row.uploaded_at)}</td>"
|
||
f"<td><code>{escape(row.code_hint)}</code></td>"
|
||
f"<td><code>{escape(row.machine_fingerprint[:16])}</code></td>"
|
||
f"<td>{escape(row.filename)}</td>"
|
||
f"<td>{escape(_format_bytes(row.size))}</td>"
|
||
f"<td><code>{escape(row.sha256[:12])}...</code></td>"
|
||
f"<td><a href='/admin/logs/download/{escape(row.key)}'>下载</a></td>"
|
||
"</tr>"
|
||
for row in diagnostic_rows
|
||
)
|
||
message_html = f"<p class='msg'>{escape(message)}</p>" if message else ""
|
||
html = f"""<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>卡密管理</title>
|
||
<style>
|
||
body {{ margin: 0; font-family: "Microsoft YaHei", sans-serif; background: #eef2f7; color: #111827; }}
|
||
main {{ max-width: 1180px; margin: 28px auto; padding: 0 18px 32px; }}
|
||
header {{ display: flex; justify-content: space-between; align-items: end; gap: 16px; margin-bottom: 18px; }}
|
||
h1 {{ margin: 0; font-size: 30px; }}
|
||
h2 {{ margin: 0 0 14px; font-size: 18px; }}
|
||
.sub {{ color: #64748b; margin-top: 6px; }}
|
||
.grid {{ display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }}
|
||
.stat {{ background: linear-gradient(135deg, #0f172a, #1f2937); color: white; border-radius: 16px; padding: 18px; }}
|
||
.stat b {{ display: block; font-size: 28px; margin-top: 8px; }}
|
||
section {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 16px; padding: 18px; margin: 14px 0; box-shadow: 0 12px 30px rgba(15, 23, 42, .06); }}
|
||
form.inline {{ display: grid; grid-template-columns: repeat(5, minmax(120px, 1fr)); gap: 10px; align-items: end; }}
|
||
form.update {{ display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; align-items: end; }}
|
||
label {{ display: block; color: #475569; font-size: 13px; }}
|
||
input {{ width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 10px; margin-top: 5px; }}
|
||
button {{ padding: 10px 16px; cursor: pointer; border: 0; border-radius: 10px; background: #2563eb; color: white; font-weight: 700; }}
|
||
button.danger {{ background: #dc2626; }}
|
||
button.secondary {{ background: #334155; }}
|
||
code {{ font-size: 14px; }}
|
||
table {{ width: 100%; border-collapse: collapse; font-size: 14px; }}
|
||
th, td {{ text-align: left; padding: 10px; border-bottom: 1px solid #e5e7eb; vertical-align: top; }}
|
||
th {{ color: #475569; background: #f8fafc; }}
|
||
.status {{ padding: 3px 8px; border-radius: 999px; font-size: 12px; background: #e2e8f0; }}
|
||
.status.active {{ background: #dcfce7; color: #166534; }}
|
||
.status.revoked {{ background: #fee2e2; color: #991b1b; }}
|
||
.msg {{ padding: 10px 12px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; }}
|
||
.cards {{ display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }}
|
||
.update-state {{ display: flex; flex-wrap: wrap; gap: 10px 16px; padding: 12px; border-radius: 12px; background: #f8fafc; border: 1px solid #e2e8f0; margin-bottom: 12px; }}
|
||
.help {{ margin-top: 8px; color: #64748b; font-size: 13px; }}
|
||
@media (max-width: 860px) {{ .grid, .cards, form.inline, form.update {{ grid-template-columns: 1fr; }} }}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<header>
|
||
<div>
|
||
<h1>卡密管理</h1>
|
||
<div class="sub">生成、禁用、解绑设备,并查看最近激活日志。</div>
|
||
</div>
|
||
<form method="post" action="/admin/logout"><button class="secondary" type="submit">退出登录</button></form>
|
||
</header>
|
||
<div class="grid">
|
||
<div class="stat">总卡密 <b>{stats["total"]}</b></div>
|
||
<div class="stat">活跃卡密 <b>{stats["active"]}</b></div>
|
||
<div class="stat">已禁用 <b>{stats["revoked"]}</b></div>
|
||
<div class="stat">已绑定设备 <b>{stats["activations"]}</b></div>
|
||
</div>
|
||
{message_html}
|
||
<section>
|
||
<h2>生成卡密</h2>
|
||
<form class="inline" method="post" action="/admin/create">
|
||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||
<label>天数 <input name="days" value="30" /></label>
|
||
<label>数量 <input name="count" value="1" /></label>
|
||
<label>设备数 <input name="max_devices" value="1" /></label>
|
||
<label>备注/客户 <input name="customer" value="" /></label>
|
||
<button type="submit">生成</button>
|
||
</form>
|
||
<ul>{created_rows}</ul>
|
||
</section>
|
||
<div class="cards">
|
||
<section>
|
||
<h2>禁用卡密</h2>
|
||
<form method="post" action="/admin/revoke">
|
||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||
<label>卡密 <input name="card_key" placeholder="DG-..." /></label>
|
||
<button class="danger" type="submit">禁用</button>
|
||
</form>
|
||
</section>
|
||
<section>
|
||
<h2>解绑设备</h2>
|
||
<form method="post" action="/admin/unbind">
|
||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||
<label>卡密 <input name="card_key" placeholder="DG-..." /></label>
|
||
<button class="secondary" type="submit">解绑</button>
|
||
</form>
|
||
</section>
|
||
</div>
|
||
<section>
|
||
<h2>在线更新</h2>
|
||
{update_html}
|
||
<form class="update" method="post" action="/admin/update/publish" enctype="multipart/form-data">
|
||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||
<label>新版本号 <input name="version" placeholder="例如 3.3.4" /></label>
|
||
<label>说明 <input name="notes" placeholder="更新内容,可留空" /></label>
|
||
<label>安装包 exe <input name="installer" type="file" accept=".exe" /></label>
|
||
<label>强制更新 <input name="force" value="1" /></label>
|
||
<button type="submit">上传并发布</button>
|
||
</form>
|
||
<form class="update" method="post" action="/admin/update/publish-delta" enctype="multipart/form-data" style="margin-top:10px">
|
||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||
<label>来源版本 <input name="from_version" placeholder="例如 3.3.5" /></label>
|
||
<label>目标版本 <input name="to_version" placeholder="例如 3.3.6" /></label>
|
||
<label>差量 zip <input name="delta_file" type="file" accept=".zip" /></label>
|
||
<button class="secondary" type="submit">上传差量包</button>
|
||
</form>
|
||
<form method="post" action="/admin/update/disable" style="margin-top:10px">
|
||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||
<button class="secondary" type="submit">关闭更新</button>
|
||
</form>
|
||
<div class="help">新客户端优先读取差量包,版本不匹配时自动回退完整安装包;manifest、安装包和差量包都会校验签名与 SHA256。</div>
|
||
</section>
|
||
<section>
|
||
<h2>最近卡密</h2>
|
||
<table>
|
||
<thead><tr><th>ID</th><th>卡密</th><th>状态</th><th>天数</th><th>设备</th><th>客户</th><th>创建时间</th><th>最后在线</th></tr></thead>
|
||
<tbody>{table_rows}</tbody>
|
||
</table>
|
||
</section>
|
||
<section>
|
||
<h2>客户端诊断日志</h2>
|
||
<div class="help">同一卡密只保留最新一份日志包,新上传会覆盖旧包。</div>
|
||
<table>
|
||
<thead><tr><th>上传时间</th><th>卡密</th><th>机器</th><th>文件名</th><th>大小</th><th>SHA256</th><th>操作</th></tr></thead>
|
||
<tbody>{diagnostic_html}</tbody>
|
||
</table>
|
||
</section>
|
||
<section>
|
||
<h2>最近审计日志</h2>
|
||
<table>
|
||
<thead><tr><th>时间</th><th>动作</th><th>卡密</th><th>机器</th><th>结果</th></tr></thead>
|
||
<tbody>{audit_html}</tbody>
|
||
</table>
|
||
</section>
|
||
</main>
|
||
</body>
|
||
</html>"""
|
||
return HTMLResponse(html)
|
||
|
||
|
||
def create_app(
|
||
*,
|
||
service: LicenseService | None = None,
|
||
admin_token: str | None = None,
|
||
external_api_token: str | None = None,
|
||
) -> FastAPI:
|
||
docs_enabled = _env_bool("DYGJ_LICENSE_ENABLE_DOCS", default=False)
|
||
app = FastAPI(
|
||
title="Douyin Guaji License Server",
|
||
docs_url="/docs" if docs_enabled else None,
|
||
redoc_url="/redoc" if docs_enabled else None,
|
||
openapi_url="/openapi.json" if docs_enabled else None,
|
||
)
|
||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=_allowed_hosts_from_env())
|
||
app.state.license_service = service
|
||
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
|
||
app.state.external_api_token = (
|
||
external_api_token if external_api_token is not None else external_api_token_from_env()
|
||
)
|
||
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=_default_secure_cookies())
|
||
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
|
||
app.state.max_installer_upload_bytes = _env_int(
|
||
"DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB",
|
||
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES // (1024 * 1024),
|
||
) * 1024 * 1024
|
||
app.state.max_delta_upload_bytes = _env_int(
|
||
"DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB",
|
||
DEFAULT_MAX_DELTA_UPLOAD_BYTES // (1024 * 1024),
|
||
) * 1024 * 1024
|
||
app.state.max_diagnostic_log_upload_bytes = _env_int(
|
||
"DYGJ_LICENSE_MAX_DIAGNOSTIC_LOG_UPLOAD_MB",
|
||
DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES // (1024 * 1024),
|
||
) * 1024 * 1024
|
||
app.state.rate_limit_buckets = {}
|
||
app.state.admin_sessions = {}
|
||
|
||
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.post("/api/v1/verify_license")
|
||
def verify_license(request: Request, req: VerifyLicenseRequest) -> JSONResponse:
|
||
if _rate_limited(request, "verify_license", max_requests=VERIFY_LICENSE_RATE_LIMIT_MAX_REQUESTS):
|
||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||
return result_response(get_service().verify_license_doc(req.license))
|
||
|
||
@app.post("/api/v1/logs/upload")
|
||
async def upload_logs(
|
||
request: Request,
|
||
license: str = Form(""),
|
||
log_file: UploadFile = File(...),
|
||
) -> JSONResponse:
|
||
if _rate_limited(request, "logs_upload", max_requests=10):
|
||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||
try:
|
||
license_doc = json.loads(str(license or ""))
|
||
if not isinstance(license_doc, dict):
|
||
raise ValueError("license must be object")
|
||
except Exception:
|
||
return JSONResponse({"ok": False, "reason": "invalid_license", "message": "授权数据格式无效"}, status_code=400)
|
||
tmp_path: Path | None = None
|
||
try:
|
||
tmp_path = await _save_upload_to_temp(
|
||
log_file,
|
||
upload_dir=get_service().diagnostic_log_dir / ".uploads",
|
||
max_bytes=app.state.max_diagnostic_log_upload_bytes,
|
||
suffix=".zip.upload",
|
||
)
|
||
entry = get_service().save_diagnostic_log_file(
|
||
license_doc=license_doc,
|
||
filename=str(log_file.filename or "diagnostic-logs.zip"),
|
||
file_path=tmp_path,
|
||
)
|
||
return JSONResponse(
|
||
{
|
||
"ok": True,
|
||
"message": "日志上传成功",
|
||
"filename": entry.filename,
|
||
"size": entry.size,
|
||
"uploaded_at": entry.uploaded_at,
|
||
}
|
||
)
|
||
except ValueError as exc:
|
||
reason = str(exc) or "upload_failed"
|
||
status_code = 413 if "超过大小限制" in reason else 403
|
||
return JSONResponse({"ok": False, "reason": reason, "message": reason}, status_code=status_code)
|
||
except Exception as exc:
|
||
return JSONResponse({"ok": False, "reason": "upload_failed", "message": str(exc)}, status_code=500)
|
||
finally:
|
||
if tmp_path is not None:
|
||
try:
|
||
tmp_path.unlink(missing_ok=True)
|
||
except Exception:
|
||
pass
|
||
|
||
@app.post("/api/v1/redeem/external/create")
|
||
def redeem_external_create(request: Request, req: CreateRedeemRequest) -> JSONResponse:
|
||
if not _bearer_token_allowed(request, app.state.external_api_token):
|
||
if _rate_limited(
|
||
request,
|
||
"redeem_create_auth",
|
||
max_requests=EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS,
|
||
):
|
||
return JSONResponse(
|
||
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
|
||
status_code=429,
|
||
)
|
||
return JSONResponse(
|
||
{"ok": False, "reason": "forbidden", "message": "外部接口 token 无效"},
|
||
status_code=403,
|
||
)
|
||
if _rate_limited(request, "redeem_create"):
|
||
return JSONResponse(
|
||
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
|
||
status_code=429,
|
||
)
|
||
try:
|
||
token = get_service().create_redeem_token(
|
||
days=req.days,
|
||
max_devices=req.max_devices,
|
||
customer=req.customer,
|
||
platform=req.platform,
|
||
external_order_id=req.external_order_id,
|
||
expires_hours=req.expires_hours,
|
||
)
|
||
except ValueError as exc:
|
||
return JSONResponse(
|
||
{"ok": False, "reason": "invalid_params", "message": str(exc)},
|
||
status_code=400,
|
||
)
|
||
claim_path = f"/redeem#{token.token}"
|
||
claim_url = urljoin(_public_base_url(request) + "/", claim_path.lstrip("/"))
|
||
return JSONResponse(
|
||
{
|
||
"ok": True,
|
||
"reason": "ok",
|
||
"claim_url": claim_url,
|
||
"token_hint": token.token_hint,
|
||
"expires_at": token.expires_at.isoformat().replace("+00:00", "Z"),
|
||
}
|
||
)
|
||
|
||
@app.post("/api/v1/redeem/claim")
|
||
def redeem_claim(request: Request, req: ClaimRedeemRequest) -> JSONResponse:
|
||
if _rate_limited(
|
||
request,
|
||
"redeem_claim",
|
||
max_requests=REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS,
|
||
):
|
||
return JSONResponse(
|
||
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
|
||
status_code=429,
|
||
)
|
||
result = get_service().claim_redeem_token(req.token)
|
||
if result.ok and result.card is not None:
|
||
return JSONResponse(
|
||
{
|
||
"ok": True,
|
||
"reason": "ok",
|
||
"message": result.message,
|
||
"card_key": result.card.code,
|
||
"days": result.card.days,
|
||
"max_devices": result.card.max_devices,
|
||
}
|
||
)
|
||
status = 409 if result.reason == "already_redeemed" else _status_for_reason(result.reason)
|
||
return JSONResponse(
|
||
{"ok": False, "reason": result.reason, "message": result.message},
|
||
status_code=status,
|
||
)
|
||
|
||
@app.get("/redeem")
|
||
def redeem_page() -> HTMLResponse:
|
||
return _redeem_page_html()
|
||
|
||
@app.get("/redeem/{token}")
|
||
def redeem_legacy_page(token: str) -> HTMLResponse:
|
||
script_token = json.dumps(str(token or ""))
|
||
return HTMLResponse(
|
||
f"""<!doctype html>
|
||
<html lang="zh-CN"><head><meta charset="utf-8" /><title>兑换授权</title></head>
|
||
<body><script>location.replace("/redeem#" + encodeURIComponent({script_token}));</script></body></html>"""
|
||
)
|
||
|
||
def _redeem_page_html() -> HTMLResponse:
|
||
html = f"""<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>兑换授权</title>
|
||
<style>
|
||
body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: "Microsoft YaHei", sans-serif; background: linear-gradient(135deg, #0f172a, #1e293b); color: #0f172a; }}
|
||
main {{ width: min(520px, calc(100vw - 32px)); background: #fff; border-radius: 24px; padding: 28px; box-shadow: 0 28px 80px rgba(0, 0, 0, .35); }}
|
||
h1 {{ margin: 0 0 8px; font-size: 28px; }}
|
||
p {{ color: #64748b; line-height: 1.7; }}
|
||
code {{ display: block; word-break: break-all; background: #f1f5f9; padding: 12px; border-radius: 12px; }}
|
||
button {{ width: 100%; margin-top: 16px; padding: 12px 16px; cursor: pointer; border: 0; border-radius: 12px; background: #2563eb; color: white; font-weight: 800; font-size: 15px; }}
|
||
#result {{ margin-top: 14px; padding: 12px; border-radius: 12px; background: #f8fafc; min-height: 24px; }}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<h1>兑换软件授权</h1>
|
||
<p>点击兑换后会生成正式卡密。卡密只显示一次,请妥善保存。</p>
|
||
<code id="tokenPreview">正在读取兑换链接...</code>
|
||
<button id="claim">立即兑换</button>
|
||
<div id="result"></div>
|
||
</main>
|
||
<script>
|
||
const token = decodeURIComponent((location.hash || "").replace(/^#/, ""));
|
||
document.getElementById("tokenPreview").textContent = token ? token : "兑换链接缺少 token";
|
||
document.getElementById("claim").addEventListener("click", async () => {{
|
||
const result = document.getElementById("result");
|
||
if (!token) {{
|
||
result.textContent = "兑换链接缺少 token";
|
||
return;
|
||
}}
|
||
result.textContent = "正在兑换...";
|
||
const resp = await fetch("/api/v1/redeem/claim", {{
|
||
method: "POST",
|
||
headers: {{ "content-type": "application/json" }},
|
||
body: JSON.stringify({{ token }})
|
||
}});
|
||
const data = await resp.json();
|
||
if (data.ok) {{
|
||
result.textContent = "兑换成功,卡密:";
|
||
const code = document.createElement("code");
|
||
code.textContent = data.card_key || "";
|
||
result.appendChild(code);
|
||
}} else {{
|
||
result.textContent = data.message || data.reason || "兑换失败";
|
||
}}
|
||
}});
|
||
</script>
|
||
</body>
|
||
</html>"""
|
||
return HTMLResponse(html)
|
||
|
||
@app.get("/api/v1/update/manifest")
|
||
def update_manifest(request: Request) -> JSONResponse:
|
||
return JSONResponse(_signed_update_manifest(get_service(), request))
|
||
|
||
@app.get("/api/v1/update/download/{filename}")
|
||
def update_download(filename: str) -> Response:
|
||
service = get_service()
|
||
manifest = service.load_update_manifest()
|
||
safe_name = Path(str(filename or "")).name
|
||
allowed_names = {manifest.filename}
|
||
if manifest.delta:
|
||
for delta in manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]:
|
||
if isinstance(delta, dict) and delta.get("filename"):
|
||
allowed_names.add(str(delta.get("filename")))
|
||
if not manifest.enabled or safe_name not in allowed_names:
|
||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||
target = service.update_dir / safe_name
|
||
if not target.exists():
|
||
return JSONResponse({"ok": False, "reason": "file_missing"}, status_code=404)
|
||
return FileResponse(
|
||
target,
|
||
media_type="application/octet-stream",
|
||
filename=safe_name,
|
||
)
|
||
|
||
@app.get("/admin")
|
||
def admin(request: Request) -> Response:
|
||
if not _admin_allowed(request, app.state.admin_token):
|
||
return RedirectResponse("/admin/login", status_code=303)
|
||
csrf = _csrf_token(request)
|
||
response = _admin_page(get_service(), csrf)
|
||
response.set_cookie(
|
||
ADMIN_CSRF_COOKIE,
|
||
csrf,
|
||
httponly=True,
|
||
samesite="lax",
|
||
secure=bool(app.state.secure_cookies),
|
||
)
|
||
return response
|
||
|
||
@app.get("/admin/logs/download/{key}")
|
||
def admin_log_download(request: Request, key: str) -> Response:
|
||
if not _admin_allowed(request, app.state.admin_token):
|
||
return RedirectResponse("/admin/login", status_code=303)
|
||
target = get_service().diagnostic_log_path(key)
|
||
if target is None:
|
||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||
return FileResponse(
|
||
target,
|
||
media_type="application/zip",
|
||
filename=f"diagnostic-{key[:12]}.zip",
|
||
)
|
||
|
||
@app.get("/admin/login")
|
||
def admin_login_page() -> HTMLResponse:
|
||
return _login_page()
|
||
|
||
@app.post("/admin/login")
|
||
def admin_login(request: Request, admin_token: str = Form("")) -> HTMLResponse:
|
||
if _rate_limited(
|
||
request,
|
||
"admin_login",
|
||
max_requests=ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS,
|
||
):
|
||
return _login_page("登录尝试过于频繁,请稍后再试。", status_code=429)
|
||
expected = str(app.state.admin_token or "").strip()
|
||
supplied = str(admin_token or "").strip()
|
||
if not expected or not hmac.compare_digest(supplied, expected):
|
||
return _login_page("管理员 token 不正确。", status_code=403)
|
||
session = _new_admin_session(request)
|
||
response = RedirectResponse("/admin", status_code=303)
|
||
response.set_cookie(
|
||
ADMIN_SESSION_COOKIE,
|
||
session,
|
||
max_age=ADMIN_SESSION_SECONDS,
|
||
httponly=True,
|
||
samesite="lax",
|
||
secure=bool(app.state.secure_cookies),
|
||
)
|
||
return response
|
||
|
||
@app.post("/admin/logout")
|
||
def admin_logout(request: Request) -> RedirectResponse:
|
||
_drop_admin_session(request)
|
||
response = RedirectResponse("/admin/login", status_code=303)
|
||
response.delete_cookie(ADMIN_SESSION_COOKIE)
|
||
response.delete_cookie(ADMIN_CSRF_COOKIE)
|
||
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} 台设备",
|
||
)
|
||
|
||
@app.post("/admin/update/publish")
|
||
async def admin_update_publish(
|
||
request: Request,
|
||
csrf_token: str = Form(""),
|
||
version: str = Form(""),
|
||
notes: str = Form(""),
|
||
force: str = Form("1"),
|
||
installer: UploadFile = File(...),
|
||
) -> 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 校验失败,请刷新后台页面后重试")
|
||
tmp_path: Path | None = None
|
||
try:
|
||
service = get_service()
|
||
tmp_path = await _save_upload_to_temp(
|
||
installer,
|
||
upload_dir=service.update_dir / ".uploads",
|
||
max_bytes=app.state.max_installer_upload_bytes,
|
||
suffix=".exe.upload",
|
||
)
|
||
manifest = service.publish_update_file(
|
||
version=version,
|
||
filename=installer.filename or "",
|
||
file_path=tmp_path,
|
||
force=str(force).strip() not in {"0", "false", "False", "否"},
|
||
notes=notes,
|
||
)
|
||
msg = f"已发布更新 V{manifest.version},文件={manifest.filename}"
|
||
except Exception as exc:
|
||
msg = f"发布更新失败:{exc}"
|
||
finally:
|
||
if tmp_path is not None:
|
||
try:
|
||
tmp_path.unlink(missing_ok=True)
|
||
except Exception:
|
||
pass
|
||
return _admin_page(get_service(), csrf, message=msg)
|
||
|
||
@app.post("/admin/update/publish-delta")
|
||
async def admin_update_publish_delta(
|
||
request: Request,
|
||
csrf_token: str = Form(""),
|
||
from_version: str = Form(""),
|
||
to_version: str = Form(""),
|
||
delta_file: UploadFile = File(...),
|
||
) -> 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 校验失败,请刷新后台页面后重试")
|
||
tmp_path: Path | None = None
|
||
try:
|
||
service = get_service()
|
||
tmp_path = await _save_upload_to_temp(
|
||
delta_file,
|
||
upload_dir=service.update_dir / ".uploads",
|
||
max_bytes=app.state.max_delta_upload_bytes,
|
||
suffix=".zip.upload",
|
||
)
|
||
manifest = service.publish_delta_update_file(
|
||
from_version=from_version,
|
||
to_version=to_version,
|
||
filename=delta_file.filename or "",
|
||
file_path=tmp_path,
|
||
)
|
||
raw_delta = manifest.delta or {}
|
||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||
delta = next(
|
||
(
|
||
item for item in deltas
|
||
if isinstance(item, dict)
|
||
and str(item.get("from_version") or "") == str(from_version).strip().lstrip("Vv")
|
||
),
|
||
deltas[-1] if deltas else {},
|
||
)
|
||
msg = f"已发布差量更新 {delta.get('from_version')} -> {delta.get('to_version')},文件={delta.get('filename')}"
|
||
except Exception as exc:
|
||
msg = f"发布差量更新失败:{exc}"
|
||
finally:
|
||
if tmp_path is not None:
|
||
try:
|
||
tmp_path.unlink(missing_ok=True)
|
||
except Exception:
|
||
pass
|
||
return _admin_page(get_service(), csrf, message=msg)
|
||
|
||
@app.post("/admin/update/disable")
|
||
def admin_update_disable(
|
||
request: Request,
|
||
csrf_token: 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 校验失败,请刷新后台页面后重试")
|
||
get_service().disable_update()
|
||
return _admin_page(get_service(), csrf, message="已关闭自动更新发布")
|
||
|
||
return app
|
||
|
||
|
||
app = create_app()
|