feat: simplify license activation flow
This commit is contained in:
1 parent
05be83d289
commit
cb74a23e81
13 files changed
+285
-28
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
@@ -25,7 +25,7 @@ BUTTON_ICONS = {
|
||||
"刷新映射表": "⟳",
|
||||
"打开pic目录": "□",
|
||||
"打开目录": "□",
|
||||
"安装卡密": "✓",
|
||||
"验证卡密": "✓",
|
||||
"刷新状态": "⟳",
|
||||
"保存日志配置": "✓",
|
||||
"查看大图": "▢",
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)"
|
||||
```
|
||||
+126
-3
@@ -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("<h1>403</h1><p>需要管理员 token。</p>", 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"<li><code>{escape(card)}</code></li>" for card in (cards or []))
|
||||
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 {{ max-width: 920px; margin: 32px auto; font-family: sans-serif; background: #f6f7f9; color: #111827; }}
|
||||
section {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 18px; margin: 14px 0; }}
|
||||
label {{ display: block; margin: 8px 0; }}
|
||||
input {{ padding: 8px 10px; min-width: 260px; }}
|
||||
button {{ padding: 9px 14px; cursor: pointer; }}
|
||||
code {{ font-size: 16px; }}
|
||||
.msg {{ padding: 10px 12px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>卡密管理</h1>
|
||||
{message_html}
|
||||
<section>
|
||||
<h2>生成卡密</h2>
|
||||
<form method="post" action="/admin/create?token={token_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>{rows}</ul>
|
||||
</section>
|
||||
<section>
|
||||
<h2>禁用卡密</h2>
|
||||
<form method="post" action="/admin/revoke?token={token_attr}">
|
||||
<label>卡密 <input name="card_key" /></label>
|
||||
<button type="submit">禁用</button>
|
||||
</form>
|
||||
</section>
|
||||
<section>
|
||||
<h2>解绑设备</h2>
|
||||
<form method="post" action="/admin/unbind?token={token_attr}">
|
||||
<label>卡密 <input name="card_key" /></label>
|
||||
<button type="submit">解绑</button>
|
||||
</form>
|
||||
</section>
|
||||
</body>
|
||||
</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
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
fastapi>=0.124.0
|
||||
uvicorn[standard]>=0.38.0
|
||||
cryptography>=41.0.0
|
||||
python-multipart>=0.0.20
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
|
||||
|
||||
+3
-3
@@ -835,12 +835,12 @@
|
||||
</div>
|
||||
<div class="row">
|
||||
<label class="label">输入卡密</label>
|
||||
<textarea id="licenseText" class="input textarea" rows="8" placeholder="粘贴 DYGJ- 开头卡密,或完整 license.dat 内容"></textarea>
|
||||
<div class="hint">卡密不会保存到 config.json;安装成功后会写入本机 license.dat。</div>
|
||||
<textarea id="licenseText" class="input textarea" rows="4" placeholder="输入服务器发放的 DG- 卡密"></textarea>
|
||||
<div class="hint">只需要填写卡密,程序会自动联网验证并写入本机授权文件。</div>
|
||||
</div>
|
||||
<div class="rowActions">
|
||||
<div class="btnGroup" role="group" aria-label="授权操作">
|
||||
<button id="btnLicenseInstall" class="btn btnPrimary" type="button">安装卡密</button>
|
||||
<button id="btnLicenseInstall" class="btn btnPrimary" type="button">验证卡密</button>
|
||||
<button id="btnLicenseRefresh" class="btn" type="button">刷新状态</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user