From cb74a23e8126a0dd371d3df553d75099032fc07f Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 18 Jun 2026 18:38:51 +0800 Subject: [PATCH] feat: simplify license activation flow --- douyin/license/license_manager.py | 22 +++-- gui/components/license_tab.py | 11 +-- gui/dashboard_app/page_config.py | 8 +- gui/dashboard_app/widgets.py | 2 +- gui/web_gui_pkg/routes.py | 3 +- license_server/README.md | 21 +++++ license_server/api.py | 129 ++++++++++++++++++++++++++++- license_server/requirements.txt | 1 + tests/test_license_manager.py | 37 +++++++++ tests/test_license_server_api.py | 39 +++++++++ tests/test_web_gui_routes_logic.py | 30 +++++++ webui/index.html | 6 +- webui/js/config_form.js | 4 +- 13 files changed, 285 insertions(+), 28 deletions(-) diff --git a/douyin/license/license_manager.py b/douyin/license/license_manager.py index 5ba30df..abdbe69 100644 --- a/douyin/license/license_manager.py +++ b/douyin/license/license_manager.py @@ -22,6 +22,7 @@ from douyin.license.public_key import PUBLIC_KEY_PEM LICENSE_FILENAME = "license.dat" ACTIVATION_CODE_PREFIX = "DYGJ-" +DEFAULT_ACTIVATION_URL = "http://103.236.55.219:18100/api/v1/activate" @dataclass(frozen=True) @@ -296,15 +297,18 @@ def install_license_or_activate( raw = str(text or "").strip() if parse_license_text(raw) is not None: return install_license_text(raw, path) - if str(activation_url or "").strip(): - return activate_license_code( - raw, - path, - activation_url=activation_url, - timeout_seconds=timeout_seconds, - http_post=http_post, - ) - return install_license_text(raw, path) + target_url = str(activation_url or "").strip() or get_default_activation_url() + return activate_license_code( + raw, + path, + activation_url=target_url, + timeout_seconds=timeout_seconds, + http_post=http_post, + ) + + +def get_default_activation_url() -> str: + return str(os.environ.get("DOUYIN_LICENSE_ACTIVATION_URL") or DEFAULT_ACTIVATION_URL).strip() def get_license_status_payload( diff --git a/gui/components/license_tab.py b/gui/components/license_tab.py index 5aa6502..ea858de 100644 --- a/gui/components/license_tab.py +++ b/gui/components/license_tab.py @@ -6,6 +6,7 @@ from tkinter.constants import BOTH, LEFT, X from typing import Callable from douyin.license.license_manager import ( + get_default_activation_url, get_license_status_payload, install_license_or_activate, ) @@ -31,7 +32,7 @@ def _activation_settings() -> tuple[str, int]: except Exception: cfg = {} section = cfg.get("license") if isinstance(cfg.get("license"), dict) else {} - activation_url = str(section.get("activation_url") or "").strip() + activation_url = str(section.get("activation_url") or "").strip() or get_default_activation_url() try: timeout_seconds = int(section.get("timeout_seconds") or 10) except (TypeError, ValueError): @@ -77,7 +78,7 @@ def setup_license_tab( hint = ttk.Label( box, - text="支持粘贴 DYGJ- 开头的卡密,或完整 license.dat 内容。卡密不会写入 config.json。", + text="只需要输入服务器发放的 DG- 卡密,程序会自动联网验证。", foreground="#666666", ) hint.pack(anchor="w", padx=10, pady=(0, 8)) @@ -105,11 +106,11 @@ def setup_license_tab( refresh_status() if status.ok: text.delete("1.0", "end") - on_line("[授权] 卡密安装成功") + on_line("[授权] 卡密验证成功") else: - on_line(f"[授权] 卡密安装失败:{status.reason} - {status.message}") + on_line(f"[授权] 卡密验证失败:{status.reason} - {status.message}") - ttk.Button(buttons, text="安装卡密", command=install_from_text).pack( + ttk.Button(buttons, text="验证卡密", command=install_from_text).pack( side=LEFT, padx=(0, 8) ) ttk.Button(buttons, text="刷新状态", command=refresh_status).pack(side=LEFT) diff --git a/gui/dashboard_app/page_config.py b/gui/dashboard_app/page_config.py index 2dfd7b0..2a3a802 100644 --- a/gui/dashboard_app/page_config.py +++ b/gui/dashboard_app/page_config.py @@ -163,11 +163,11 @@ def build_keywords(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> No def build_license(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None: - section(parent, "授权", "卡密授权、本机机器码与授权文件") - box = card(parent, "卡密授权") + section(parent, "授权", "输入卡密后自动联网验证") + box = card(parent, "卡密验证") box.pack(fill="x") - pack_fields(box, ctx, [("授权状态", "", "本地检测"), ("本机机器码", "", ""), ("授权文件", "", "license.dat"), ("输入卡密", "", "")], columns=2) + pack_fields(box, ctx, [("授权状态", "", "本地检测"), ("本机机器码", "", ""), ("授权文件", "", "license.dat"), ("输入卡密", "服务器发放的 DG- 卡密", "")], columns=2) row = tk.Frame(box, bg=theme.SURFACE) row.pack(fill="x", padx=20, pady=(0, 16)) - button(row, "安装卡密", None, kind="primary").pack(side="left", padx=(0, 8)) + button(row, "验证卡密", None, kind="primary").pack(side="left", padx=(0, 8)) button(row, "刷新状态", None).pack(side="left") diff --git a/gui/dashboard_app/widgets.py b/gui/dashboard_app/widgets.py index 681d685..127d4e5 100644 --- a/gui/dashboard_app/widgets.py +++ b/gui/dashboard_app/widgets.py @@ -25,7 +25,7 @@ BUTTON_ICONS = { "刷新映射表": "⟳", "打开pic目录": "□", "打开目录": "□", - "安装卡密": "✓", + "验证卡密": "✓", "刷新状态": "⟳", "保存日志配置": "✓", "查看大图": "▢", diff --git a/gui/web_gui_pkg/routes.py b/gui/web_gui_pkg/routes.py index bb55248..f9a5dd3 100644 --- a/gui/web_gui_pkg/routes.py +++ b/gui/web_gui_pkg/routes.py @@ -7,6 +7,7 @@ from urllib.parse import parse_qs from douyin.core import path_config from douyin.license.license_manager import ( + get_default_activation_url, get_license_status_payload, install_license_or_activate, ) @@ -63,7 +64,7 @@ def _coerce_bool(value) -> bool: def _license_activation_settings() -> tuple[str, int]: cfg = read_config() section = cfg.get("license") if isinstance(cfg.get("license"), dict) else {} - activation_url = str(section.get("activation_url") or "").strip() + activation_url = str(section.get("activation_url") or "").strip() or get_default_activation_url() try: timeout_seconds = int(section.get("timeout_seconds") or 10) except (TypeError, ValueError): diff --git a/license_server/README.md b/license_server/README.md index 294a0dc..51e0fbd 100644 --- a/license_server/README.md +++ b/license_server/README.md @@ -15,6 +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 ``` `/api/v1/activate` 请求: @@ -54,3 +55,23 @@ http://127.0.0.1:18100 ``` 注意:`secrets/private_key.pem` 只能放服务器,不能随客户端分发。 + +## 最小网页后台 + +后台和激活接口共用同一个服务端口,不需要额外开放端口: + +```text +http://服务器IP:18100/admin?token=管理员TOKEN +``` + +管理员 token 建议放在服务器: + +```text +/opt/douyin-license-server/secrets/admin_token.txt +``` + +服务启动时设置: + +```bash +export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)" +``` diff --git a/license_server/api.py b/license_server/api.py index 0561e03..efc67bd 100644 --- a/license_server/api.py +++ b/license_server/api.py @@ -1,11 +1,12 @@ from __future__ import annotations import os +from html import escape from pathlib import Path from typing import Any -from fastapi import FastAPI -from fastapi.responses import JSONResponse +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 @@ -60,9 +61,85 @@ def create_service_from_env() -> LicenseService: return LicenseService(db_path=db_path, private_key_pem=load_private_key_pem()) -def create_app(*, service: LicenseService | None = None) -> FastAPI: +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 + 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}" + + +def _admin_forbidden() -> HTMLResponse: + return HTMLResponse("

403

需要管理员 token。

", status_code=403) + + +def _admin_page(token: str, message: str = "", cards: list[str] | None = None) -> HTMLResponse: + token_attr = escape(token, quote=True) + rows = "".join(f"
  • {escape(card)}
  • " for card in (cards or [])) + message_html = f"

    {escape(message)}

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

    卡密管理

    + {message_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() def get_service() -> LicenseService: if app.state.license_service is None: @@ -91,6 +168,52 @@ def create_app(*, service: LicenseService | None = None) -> FastAPI: ) ) + @app.get("/admin") + def admin(request: Request) -> HTMLResponse: + if not _admin_allowed(request, app.state.admin_token): + return _admin_forbidden() + return _admin_page(str(request.query_params.get("token") or "")) + + @app.post("/admin/create") + def admin_create( + request: Request, + 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() + cards = get_service().create_cards( + days=days, + count=count, + max_devices=max_devices, + customer=customer, + ) + return _admin_page( + str(request.query_params.get("token") or ""), + message=f"已生成 {len(cards)} 个卡密,customer={customer}", + cards=[card.code for card in cards], + ) + + @app.post("/admin/revoke") + def admin_revoke(request: Request, card_key: str = Form("")) -> HTMLResponse: + if not _admin_allowed(request, app.state.admin_token): + return _admin_forbidden() + ok = get_service().revoke(card_key) + msg = "已禁用" if ok else "卡密不存在" + return _admin_page(str(request.query_params.get("token") or ""), message=msg) + + @app.post("/admin/unbind") + def admin_unbind(request: Request, card_key: str = Form("")) -> HTMLResponse: + if not _admin_allowed(request, app.state.admin_token): + return _admin_forbidden() + count = get_service().unbind(card_key) + return _admin_page( + str(request.query_params.get("token") or ""), + message=f"已解绑 {count} 台设备", + ) + return app diff --git a/license_server/requirements.txt b/license_server/requirements.txt index 2c8710c..f6efb74 100644 --- a/license_server/requirements.txt +++ b/license_server/requirements.txt @@ -1,3 +1,4 @@ fastapi>=0.124.0 uvicorn[standard]>=0.38.0 cryptography>=41.0.0 +python-multipart>=0.0.20 diff --git a/tests/test_license_manager.py b/tests/test_license_manager.py index 314014b..78bf4c9 100644 --- a/tests/test_license_manager.py +++ b/tests/test_license_manager.py @@ -206,6 +206,43 @@ def test_activate_license_code_installs_server_license(tmp_path, monkeypatch): assert license_manager.check_license(target_path).payload["customer"] == "online-user" +def test_plain_card_uses_default_activation_url(tmp_path, monkeypatch): + from douyin.license import license_manager + from tools.license_dev import create_dev_license + + monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a") + monkeypatch.setattr( + license_manager, + "get_default_activation_url", + lambda: "https://license.example.test/api/v1/activate", + ) + source_path = tmp_path / "server_license.dat" + target_path = tmp_path / "license.dat" + create_dev_license( + output_path=source_path, + machine_fingerprint="machine-a", + expires_at=datetime.now(timezone.utc) + timedelta(days=30), + customer="default-url-user", + ) + server_doc = json.loads(source_path.read_text(encoding="utf-8")) + calls = {} + + def fake_post(url, payload, timeout_seconds=10): + calls["url"] = url + calls["payload"] = payload + return {"ok": True, "license": server_doc} + + result = license_manager.install_license_or_activate( + "DG-DEFAULT-TEST", + target_path, + http_post=fake_post, + ) + + assert result.ok is True + assert calls["url"] == "https://license.example.test/api/v1/activate" + assert calls["payload"]["card_key"] == "DG-DEFAULT-TEST" + + def test_license_status_public_payload_hides_signature(tmp_path, monkeypatch): from douyin.license import license_manager from tools.license_dev import create_dev_license diff --git a/tests/test_license_server_api.py b/tests/test_license_server_api.py index de5d334..6261c4c 100644 --- a/tests/test_license_server_api.py +++ b/tests/test_license_server_api.py @@ -43,3 +43,42 @@ def test_license_server_api_rejects_unknown_card(tmp_path): assert resp.status_code == 404 assert resp.json()["reason"] == "not_found" + + +def test_admin_page_requires_token(tmp_path): + from fastapi.testclient import TestClient + + from license_server import api + from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseService + + service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=DEV_PRIVATE_KEY_PEM) + client = TestClient(api.create_app(service=service, admin_token="secret")) + + resp = client.get("/admin") + + assert resp.status_code == 403 + + +def test_admin_page_can_create_and_revoke_card(tmp_path): + from fastapi.testclient import TestClient + + from license_server import api + from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseService + + service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=DEV_PRIVATE_KEY_PEM) + client = TestClient(api.create_app(service=service, admin_token="secret")) + + created = client.post( + "/admin/create?token=secret", + data={"days": "8", "count": "1", "customer": "web-admin"}, + ) + card = created.text.split("DG-", 1)[1].split("<", 1)[0] + card = "DG-" + card.strip() + revoked = client.post("/admin/revoke?token=secret", data={"card_key": card}) + + assert created.status_code == 200 + assert "web-admin" in created.text + assert card.startswith("DG-") + assert revoked.status_code == 200 + assert "已禁用" in revoked.text + assert service.activate(card, machine_fingerprint="machine-a").reason == "revoked" diff --git a/tests/test_web_gui_routes_logic.py b/tests/test_web_gui_routes_logic.py index 2ba6919..25e6044 100644 --- a/tests/test_web_gui_routes_logic.py +++ b/tests/test_web_gui_routes_logic.py @@ -186,6 +186,36 @@ def test_license_install_route_uses_activation_url(monkeypatch): } +def test_license_install_route_uses_default_activation_url(monkeypatch): + calls = {} + + class _Status: + ok = True + reason = "ok" + message = "授权有效" + payload = {} + + def fake_install(text, *, activation_url="", timeout_seconds=10): + calls["text"] = text + calls["activation_url"] = activation_url + calls["timeout_seconds"] = timeout_seconds + return _Status() + + monkeypatch.setattr(routes, "read_config", lambda: {}) + monkeypatch.setattr(routes, "get_default_activation_url", lambda: "http://default/api/v1/activate") + monkeypatch.setattr(routes, "install_license_or_activate", fake_install) + + status, obj = _post("/api/license", {"license_text": "DG-DEMO"}, monkeypatch) + + assert status == 200 + assert obj["ok"] is True + assert calls == { + "text": "DG-DEMO", + "activation_url": "http://default/api/v1/activate", + "timeout_seconds": 10, + } + + def test_license_install_route_rejects_empty_code(monkeypatch): status, obj = _post("/api/license", {"license_text": " "}, monkeypatch) diff --git a/webui/index.html b/webui/index.html index bd034f2..12be0ad 100644 --- a/webui/index.html +++ b/webui/index.html @@ -835,12 +835,12 @@
    - -
    卡密不会保存到 config.json;安装成功后会写入本机 license.dat。
    + +
    只需要填写卡密,程序会自动联网验证并写入本机授权文件。
    - +
    diff --git a/webui/js/config_form.js b/webui/js/config_form.js index 9ae0462..392e0cb 100644 --- a/webui/js/config_form.js +++ b/webui/js/config_form.js @@ -203,11 +203,11 @@ async function installLicenseFromUI() { const data = await apiPost("/api/license", { license_text: text }); renderLicenseStatus(data); if (input) input.value = ""; - toast("卡密安装成功", "success"); + toast("卡密验证成功", "success"); } catch (e) { const data = e?.data || {}; renderLicenseStatus(data); - toast("卡密安装失败:" + (data.message || data.error || e?.message || e), "error", { duration: 5000 }); + toast("卡密验证失败:" + (data.message || data.error || e?.message || e), "error", { duration: 5000 }); } finally { setButtonBusy("btnLicenseInstall", false); }