feat: add simple license activation server
This commit is contained in:
1 parent
b2db5ed499
commit
05be83d289
17 files changed
+1053
-6
No files matched your search
@@ -46,6 +46,23 @@
|
||||
|
||||
正式分发不要使用 HTTP;`sha256` 只能防安装包下载损坏,不能替代可信 manifest。
|
||||
|
||||
## 在线卡密激活配置
|
||||
|
||||
正式接入服务器后,在本地配置中增加:
|
||||
|
||||
```json
|
||||
{
|
||||
"license": {
|
||||
"activation_url": "https://license.example.com/api/v1/activate",
|
||||
"timeout_seconds": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
未配置 `activation_url` 时,客户端仍只按旧逻辑安装 `DYGJ-` 离线授权码或完整
|
||||
`license.dat` 内容。配置后,普通 `DG-` 卡密会请求服务器激活,服务器返回的签名授权
|
||||
仍会先在本地验签,通过后才写入 `license.dat`。
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib import request
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
@@ -220,6 +221,92 @@ def install_license_text(
|
||||
return LicenseStatus(False, "write_failed", f"授权文件写入失败: {e}", {})
|
||||
|
||||
|
||||
def _default_http_post(
|
||||
url: str,
|
||||
payload: dict[str, Any],
|
||||
timeout_seconds: int = 10,
|
||||
) -> dict[str, Any]:
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with request.urlopen(req, timeout=max(1, int(timeout_seconds))) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
obj = json.loads(raw)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("server response is not an object")
|
||||
return obj
|
||||
|
||||
|
||||
def activate_license_code(
|
||||
card_key: str,
|
||||
path: str | os.PathLike[str] | None = None,
|
||||
*,
|
||||
activation_url: str,
|
||||
timeout_seconds: int = 10,
|
||||
http_post=None,
|
||||
) -> LicenseStatus:
|
||||
"""用服务器卡密换取签名授权,并在本地验签通过后写入 license.dat。"""
|
||||
url = str(activation_url or "").strip()
|
||||
if not url:
|
||||
return LicenseStatus(False, "missing_activation_url", "未配置卡密激活服务器", {})
|
||||
raw_key = str(card_key or "").strip()
|
||||
if not raw_key:
|
||||
return LicenseStatus(False, "invalid_format", "卡密格式无效", {})
|
||||
post = http_post or _default_http_post
|
||||
try:
|
||||
data = post(
|
||||
url,
|
||||
{
|
||||
"card_key": raw_key,
|
||||
"machine_fingerprint": get_machine_fingerprint(),
|
||||
},
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
except Exception as e:
|
||||
return LicenseStatus(False, "activation_failed", f"卡密服务器请求失败: {e}", {})
|
||||
if not bool(data.get("ok")):
|
||||
return LicenseStatus(
|
||||
False,
|
||||
str(data.get("reason") or "activation_rejected"),
|
||||
str(data.get("message") or data.get("error") or "卡密激活失败"),
|
||||
{},
|
||||
)
|
||||
license_doc = data.get("license")
|
||||
if not isinstance(license_doc, dict):
|
||||
return LicenseStatus(False, "invalid_response", "卡密服务器未返回授权文件", {})
|
||||
return install_license_text(
|
||||
json.dumps(license_doc, ensure_ascii=False),
|
||||
path,
|
||||
)
|
||||
|
||||
|
||||
def install_license_or_activate(
|
||||
text: str,
|
||||
path: str | os.PathLike[str] | None = None,
|
||||
*,
|
||||
activation_url: str = "",
|
||||
timeout_seconds: int = 10,
|
||||
http_post=None,
|
||||
) -> LicenseStatus:
|
||||
"""兼容旧离线授权;普通卡密在配置激活服务器后走在线激活。"""
|
||||
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)
|
||||
|
||||
|
||||
def get_license_status_payload(
|
||||
path: str | os.PathLike[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
@@ -7,8 +7,9 @@ from typing import Callable
|
||||
|
||||
from douyin.license.license_manager import (
|
||||
get_license_status_payload,
|
||||
install_license_text,
|
||||
install_license_or_activate,
|
||||
)
|
||||
from gui.config_io import read_config
|
||||
|
||||
|
||||
def _format_status(payload: dict) -> str:
|
||||
@@ -24,6 +25,20 @@ def _format_status(payload: dict) -> str:
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def _activation_settings() -> tuple[str, int]:
|
||||
try:
|
||||
cfg = read_config()
|
||||
except Exception:
|
||||
cfg = {}
|
||||
section = cfg.get("license") if isinstance(cfg.get("license"), dict) else {}
|
||||
activation_url = str(section.get("activation_url") or "").strip()
|
||||
try:
|
||||
timeout_seconds = int(section.get("timeout_seconds") or 10)
|
||||
except (TypeError, ValueError):
|
||||
timeout_seconds = 10
|
||||
return activation_url, max(1, timeout_seconds)
|
||||
|
||||
|
||||
def setup_license_tab(
|
||||
parent: ttk.Notebook,
|
||||
*,
|
||||
@@ -81,7 +96,12 @@ def setup_license_tab(
|
||||
if not raw:
|
||||
on_line("[授权] 请输入卡密")
|
||||
return
|
||||
status = install_license_text(raw)
|
||||
activation_url, timeout_seconds = _activation_settings()
|
||||
status = install_license_or_activate(
|
||||
raw,
|
||||
activation_url=activation_url,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
refresh_status()
|
||||
if status.ok:
|
||||
text.delete("1.0", "end")
|
||||
|
||||
@@ -8,7 +8,7 @@ from urllib.parse import parse_qs
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import (
|
||||
get_license_status_payload,
|
||||
install_license_text,
|
||||
install_license_or_activate,
|
||||
)
|
||||
from gui.web_gui_pkg import (
|
||||
_wg_log,
|
||||
@@ -60,6 +60,17 @@ def _coerce_bool(value) -> bool:
|
||||
return bool(value)
|
||||
|
||||
|
||||
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()
|
||||
try:
|
||||
timeout_seconds = int(section.get("timeout_seconds") or 10)
|
||||
except (TypeError, ValueError):
|
||||
timeout_seconds = 10
|
||||
return activation_url, max(1, timeout_seconds)
|
||||
|
||||
|
||||
def _is_invalid_ports_spec(spec) -> bool:
|
||||
"""判断端口规格是否为明确非法输入。"""
|
||||
if spec is None:
|
||||
@@ -620,7 +631,12 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
|
||||
{"ok": False, "error": "missing license_text"},
|
||||
status=400,
|
||||
)
|
||||
status = install_license_text(text)
|
||||
activation_url, timeout_seconds = _license_activation_settings()
|
||||
status = install_license_or_activate(
|
||||
text,
|
||||
activation_url=activation_url,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
payload = get_license_status_payload()
|
||||
payload.update(
|
||||
{"ok": status.ok, "reason": status.reason, "message": status.message}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt /app/license_server/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /app/license_server/requirements.txt
|
||||
|
||||
COPY . /app/license_server
|
||||
|
||||
EXPOSE 18100
|
||||
|
||||
CMD ["uvicorn", "license_server.api:app", "--host", "0.0.0.0", "--port", "18100"]
|
||||
@@ -0,0 +1,56 @@
|
||||
# 简单卡密服务端
|
||||
|
||||
## 本地生成卡密
|
||||
|
||||
```bash
|
||||
python -m license_server.manage --db data/app.db create --days 30 --count 10 --customer demo
|
||||
python -m license_server.manage --db data/app.db list
|
||||
python -m license_server.manage --db data/app.db revoke DG-XXXX-XXXX-XXXX-XXXX-XXXX
|
||||
python -m license_server.manage --db data/app.db unbind DG-XXXX-XXXX-XXXX-XXXX-XXXX
|
||||
```
|
||||
|
||||
## 服务端接口
|
||||
|
||||
```text
|
||||
GET /api/v1/health
|
||||
POST /api/v1/activate
|
||||
POST /api/v1/verify
|
||||
```
|
||||
|
||||
`/api/v1/activate` 请求:
|
||||
|
||||
```json
|
||||
{
|
||||
"card_key": "DG-XXXX-XXXX-XXXX-XXXX-XXXX",
|
||||
"machine_fingerprint": "客户端机器码"
|
||||
}
|
||||
```
|
||||
|
||||
成功后返回 `license` 字段,客户端本地验签通过才会写入 `license.dat`。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
```bash
|
||||
cd /opt/douyin-license-server
|
||||
mkdir -p data secrets
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
第一版建议通过 1Panel/OpenResty 把 HTTPS 域名反代到:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:18100
|
||||
```
|
||||
|
||||
客户端配置:
|
||||
|
||||
```json
|
||||
{
|
||||
"license": {
|
||||
"activation_url": "https://你的域名/api/v1/activate",
|
||||
"timeout_seconds": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
注意:`secrets/private_key.pem` 只能放服务器,不能随客户端分发。
|
||||
@@ -0,0 +1 @@
|
||||
"""Simple server-side license activation package."""
|
||||
@@ -0,0 +1,97 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseActionResult, LicenseService
|
||||
|
||||
|
||||
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 == "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")
|
||||
return DEV_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 create_app(*, service: LicenseService | None = None) -> FastAPI:
|
||||
app = FastAPI(title="Douyin Guaji License Server")
|
||||
app.state.license_service = service
|
||||
|
||||
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(req: ActivateRequest) -> JSONResponse:
|
||||
return result_response(
|
||||
get_service().activate(
|
||||
req.card_key,
|
||||
machine_fingerprint=req.machine_fingerprint,
|
||||
)
|
||||
)
|
||||
|
||||
@app.post("/api/v1/verify")
|
||||
def verify(req: VerifyRequest) -> JSONResponse:
|
||||
return result_response(
|
||||
get_service().verify(
|
||||
req.card_key,
|
||||
machine_fingerprint=req.machine_fingerprint,
|
||||
)
|
||||
)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,377 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
|
||||
DEV_PRIVATE_KEY_PEM = b"""-----BEGIN PRIVATE KEY-----
|
||||
MC4CAQAwBQYDK2VwBCIEIOjSJg0Y4mQJcAnb/9o4dDANZSeTeLJYt04nUVZNvlEy
|
||||
-----END PRIVATE KEY-----
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CreatedCard:
|
||||
code: str
|
||||
days: int
|
||||
max_devices: int
|
||||
customer: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LicenseActionResult:
|
||||
ok: bool
|
||||
reason: str
|
||||
message: str
|
||||
license_doc: dict[str, Any] | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
def write_license(self, path: str | Path) -> Path:
|
||||
if not self.license_doc:
|
||||
raise ValueError("no license_doc available")
|
||||
target = Path(path)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(
|
||||
json.dumps(self.license_doc, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return target
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def canonical_payload_bytes(payload: dict[str, Any]) -> bytes:
|
||||
return json.dumps(
|
||||
payload,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def iso_utc(dt: datetime) -> str:
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def parse_utc(raw: str) -> datetime:
|
||||
text = str(raw or "").strip()
|
||||
if text.endswith("Z"):
|
||||
text = text[:-1] + "+00:00"
|
||||
dt = datetime.fromisoformat(text)
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def hash_card_code(code: str) -> str:
|
||||
return hashlib.sha256(str(code or "").strip().upper().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def mask_card_code(code: str) -> str:
|
||||
raw = str(code or "").strip()
|
||||
if len(raw) <= 8:
|
||||
return "***"
|
||||
return f"{raw[:4]}...{raw[-4:]}"
|
||||
|
||||
|
||||
def generate_card_code() -> str:
|
||||
token = secrets.token_urlsafe(18).replace("-", "").replace("_", "").upper()
|
||||
token = token[:20]
|
||||
groups = "-".join(token[i:i + 4] for i in range(0, len(token), 4))
|
||||
return f"DG-{groups}"
|
||||
|
||||
|
||||
class LicenseService:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
db_path: str | Path,
|
||||
private_key_pem: bytes,
|
||||
) -> None:
|
||||
self.db_path = Path(db_path)
|
||||
self.private_key_pem = private_key_pem
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA foreign_keys = ON")
|
||||
return conn
|
||||
|
||||
def _init_db(self) -> None:
|
||||
with self._connect() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS license_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code_hash TEXT NOT NULL UNIQUE,
|
||||
code_hint TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
days INTEGER NOT NULL,
|
||||
max_devices INTEGER NOT NULL DEFAULT 1,
|
||||
customer TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
revoked_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS activations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
license_id INTEGER NOT NULL,
|
||||
machine_fingerprint TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
first_seen_at TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL,
|
||||
UNIQUE(license_id, machine_fingerprint),
|
||||
FOREIGN KEY(license_id) REFERENCES license_keys(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
action TEXT NOT NULL,
|
||||
code_hint TEXT NOT NULL,
|
||||
machine_fingerprint TEXT NOT NULL DEFAULT '',
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
def create_cards(
|
||||
self,
|
||||
*,
|
||||
days: int,
|
||||
count: int,
|
||||
max_devices: int = 1,
|
||||
customer: str = "",
|
||||
) -> list[CreatedCard]:
|
||||
days = max(1, int(days))
|
||||
count = max(1, int(count))
|
||||
max_devices = max(1, int(max_devices))
|
||||
cards: list[CreatedCard] = []
|
||||
with self._connect() as conn:
|
||||
for _ in range(count):
|
||||
code = generate_card_code()
|
||||
card = CreatedCard(
|
||||
code=code,
|
||||
days=days,
|
||||
max_devices=max_devices,
|
||||
customer=str(customer or ""),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO license_keys
|
||||
(code_hash, code_hint, status, days, max_devices, customer, created_at)
|
||||
VALUES (?, ?, 'active', ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
hash_card_code(code),
|
||||
mask_card_code(code),
|
||||
days,
|
||||
max_devices,
|
||||
card.customer,
|
||||
iso_utc(utcnow()),
|
||||
),
|
||||
)
|
||||
cards.append(card)
|
||||
return cards
|
||||
|
||||
def revoke(self, code: str) -> bool:
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE license_keys
|
||||
SET status = 'revoked', revoked_at = ?
|
||||
WHERE code_hash = ?
|
||||
""",
|
||||
(iso_utc(utcnow()), hash_card_code(code)),
|
||||
)
|
||||
changed = cur.rowcount > 0
|
||||
self._audit(conn, "revoke", code, "", "ok" if changed else "not_found")
|
||||
return changed
|
||||
|
||||
def unbind(self, code: str) -> int:
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
"""
|
||||
DELETE FROM activations
|
||||
WHERE license_id = (
|
||||
SELECT id FROM license_keys WHERE code_hash = ?
|
||||
)
|
||||
""",
|
||||
(hash_card_code(code),),
|
||||
)
|
||||
self._audit(conn, "unbind", code, "", str(cur.rowcount))
|
||||
return int(cur.rowcount or 0)
|
||||
|
||||
def activate(self, code: str, *, machine_fingerprint: str) -> LicenseActionResult:
|
||||
raw_machine = str(machine_fingerprint or "").strip()
|
||||
if not raw_machine:
|
||||
return LicenseActionResult(False, "missing_machine", "缺少机器码")
|
||||
with self._connect() as conn:
|
||||
card = self._get_card(conn, code)
|
||||
if card is None:
|
||||
self._audit(conn, "activate", code, raw_machine, "not_found")
|
||||
return LicenseActionResult(False, "not_found", "卡密不存在")
|
||||
invalid = self._invalid_card_reason(card)
|
||||
if invalid:
|
||||
self._audit(conn, "activate", code, raw_machine, invalid)
|
||||
return LicenseActionResult(False, invalid, self._reason_message(invalid))
|
||||
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT * FROM activations
|
||||
WHERE license_id = ? AND machine_fingerprint = ?
|
||||
""",
|
||||
(card["id"], raw_machine),
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
count = conn.execute(
|
||||
"SELECT COUNT(*) AS n FROM activations WHERE license_id = ?",
|
||||
(card["id"],),
|
||||
).fetchone()["n"]
|
||||
if int(count) >= int(card["max_devices"]):
|
||||
self._audit(conn, "activate", code, raw_machine, "device_limit")
|
||||
return LicenseActionResult(False, "device_limit", "卡密绑定设备数已满")
|
||||
expires_at = utcnow() + timedelta(days=int(card["days"]))
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO activations
|
||||
(license_id, machine_fingerprint, expires_at, first_seen_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
card["id"],
|
||||
raw_machine,
|
||||
iso_utc(expires_at),
|
||||
iso_utc(utcnow()),
|
||||
iso_utc(utcnow()),
|
||||
),
|
||||
)
|
||||
else:
|
||||
expires_at = parse_utc(existing["expires_at"])
|
||||
conn.execute(
|
||||
"UPDATE activations SET last_seen_at = ? WHERE id = ?",
|
||||
(iso_utc(utcnow()), existing["id"]),
|
||||
)
|
||||
|
||||
doc = self._sign_license_doc(
|
||||
customer=str(card["customer"] or ""),
|
||||
machine_fingerprint=raw_machine,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
self._audit(conn, "activate", code, raw_machine, "ok")
|
||||
return LicenseActionResult(True, "ok", "授权有效", doc, expires_at)
|
||||
|
||||
def verify(self, code: str, *, machine_fingerprint: str) -> LicenseActionResult:
|
||||
raw_machine = str(machine_fingerprint or "").strip()
|
||||
if not raw_machine:
|
||||
return LicenseActionResult(False, "missing_machine", "缺少机器码")
|
||||
with self._connect() as conn:
|
||||
card = self._get_card(conn, code)
|
||||
if card is None:
|
||||
self._audit(conn, "verify", code, raw_machine, "not_found")
|
||||
return LicenseActionResult(False, "not_found", "卡密不存在")
|
||||
invalid = self._invalid_card_reason(card)
|
||||
if invalid:
|
||||
self._audit(conn, "verify", code, raw_machine, invalid)
|
||||
return LicenseActionResult(False, invalid, self._reason_message(invalid))
|
||||
activation = conn.execute(
|
||||
"""
|
||||
SELECT * FROM activations
|
||||
WHERE license_id = ? AND machine_fingerprint = ?
|
||||
""",
|
||||
(card["id"], raw_machine),
|
||||
).fetchone()
|
||||
if activation is None:
|
||||
any_activation = conn.execute(
|
||||
"SELECT 1 FROM activations WHERE license_id = ? LIMIT 1",
|
||||
(card["id"],),
|
||||
).fetchone()
|
||||
reason = "machine_mismatch" if any_activation else "not_activated"
|
||||
self._audit(conn, "verify", code, raw_machine, reason)
|
||||
return LicenseActionResult(False, reason, self._reason_message(reason))
|
||||
expires_at = parse_utc(activation["expires_at"])
|
||||
if utcnow() > expires_at:
|
||||
self._audit(conn, "verify", code, raw_machine, "expired")
|
||||
return LicenseActionResult(False, "expired", "授权已过期", expires_at=expires_at)
|
||||
conn.execute(
|
||||
"UPDATE activations SET last_seen_at = ? WHERE id = ?",
|
||||
(iso_utc(utcnow()), activation["id"]),
|
||||
)
|
||||
self._audit(conn, "verify", code, raw_machine, "ok")
|
||||
return LicenseActionResult(True, "ok", "授权有效", expires_at=expires_at)
|
||||
|
||||
def _get_card(self, conn: sqlite3.Connection, code: str) -> sqlite3.Row | None:
|
||||
return conn.execute(
|
||||
"SELECT * FROM license_keys WHERE code_hash = ?",
|
||||
(hash_card_code(code),),
|
||||
).fetchone()
|
||||
|
||||
def _invalid_card_reason(self, card: sqlite3.Row) -> str:
|
||||
status = str(card["status"] or "").strip().lower()
|
||||
if status == "revoked":
|
||||
return "revoked"
|
||||
if status != "active":
|
||||
return "inactive"
|
||||
return ""
|
||||
|
||||
def _reason_message(self, reason: str) -> str:
|
||||
return {
|
||||
"revoked": "卡密已禁用",
|
||||
"inactive": "卡密未启用",
|
||||
"device_limit": "卡密绑定设备数已满",
|
||||
"machine_mismatch": "卡密不属于当前机器",
|
||||
"not_activated": "卡密尚未激活",
|
||||
"not_found": "卡密不存在",
|
||||
}.get(reason, reason)
|
||||
|
||||
def _sign_license_doc(
|
||||
self,
|
||||
*,
|
||||
customer: str,
|
||||
machine_fingerprint: str,
|
||||
expires_at: datetime,
|
||||
) -> dict[str, Any]:
|
||||
private_key = serialization.load_pem_private_key(self.private_key_pem, password=None)
|
||||
payload = {
|
||||
"customer": customer,
|
||||
"machine_fingerprint": machine_fingerprint,
|
||||
"expires_at": iso_utc(expires_at),
|
||||
"license_version": 1,
|
||||
}
|
||||
signature = private_key.sign(canonical_payload_bytes(payload))
|
||||
return {
|
||||
"payload": payload,
|
||||
"signature": base64.b64encode(signature).decode("ascii"),
|
||||
}
|
||||
|
||||
def _audit(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
action: str,
|
||||
code: str,
|
||||
machine_fingerprint: str,
|
||||
reason: str,
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO audit_logs
|
||||
(action, code_hint, machine_fingerprint, reason, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(action, mask_card_code(code), machine_fingerprint, reason, iso_utc(utcnow())),
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
douyin-license-server:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: douyin-license-server
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
DYGJ_LICENSE_DB_PATH: /data/app.db
|
||||
DYGJ_LICENSE_PRIVATE_KEY_PATH: /run/secrets/private_key.pem
|
||||
ports:
|
||||
- "127.0.0.1:18100:18100"
|
||||
volumes:
|
||||
- ./data:/data
|
||||
- ./secrets:/run/secrets:ro
|
||||
working_dir: /app
|
||||
@@ -0,0 +1,123 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from license_server.api import load_private_key_pem
|
||||
from license_server.core import LicenseService
|
||||
|
||||
|
||||
DEFAULT_DB_PATH = "/opt/douyin-license-server/data/app.db"
|
||||
|
||||
|
||||
def create_service(db_path: str) -> LicenseService:
|
||||
return LicenseService(db_path=Path(db_path), private_key_pem=load_private_key_pem())
|
||||
|
||||
|
||||
def cmd_create(args: argparse.Namespace) -> int:
|
||||
service = create_service(args.db)
|
||||
cards = service.create_cards(
|
||||
days=args.days,
|
||||
count=args.count,
|
||||
max_devices=args.max_devices,
|
||||
customer=args.customer,
|
||||
)
|
||||
for card in cards:
|
||||
print(
|
||||
f"{card.code} days={card.days} max_devices={card.max_devices} "
|
||||
f"customer={card.customer}"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_revoke(args: argparse.Namespace) -> int:
|
||||
service = create_service(args.db)
|
||||
if service.revoke(args.card_key):
|
||||
print("revoked")
|
||||
return 0
|
||||
print("not_found")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_unbind(args: argparse.Namespace) -> int:
|
||||
service = create_service(args.db)
|
||||
count = service.unbind(args.card_key)
|
||||
print(f"unbound={count}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_list(args: argparse.Namespace) -> int:
|
||||
db_path = Path(args.db)
|
||||
if not db_path.exists():
|
||||
print("empty")
|
||||
return 0
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT
|
||||
lk.id,
|
||||
lk.code_hint,
|
||||
lk.status,
|
||||
lk.days,
|
||||
lk.max_devices,
|
||||
lk.customer,
|
||||
lk.created_at,
|
||||
COUNT(a.id) AS activation_count
|
||||
FROM license_keys lk
|
||||
LEFT JOIN activations a ON a.license_id = lk.id
|
||||
GROUP BY lk.id
|
||||
ORDER BY lk.id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(max(1, int(args.limit)),),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
print(
|
||||
f"#{row['id']} {row['code_hint']} status={row['status']} "
|
||||
f"days={row['days']} devices={row['activation_count']}/{row['max_devices']} "
|
||||
f"customer={row['customer']} created_at={row['created_at']}"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="抖音挂机卡密服务端管理工具")
|
||||
parser.add_argument(
|
||||
"--db",
|
||||
default=os.environ.get("DYGJ_LICENSE_DB_PATH") or DEFAULT_DB_PATH,
|
||||
help="SQLite 数据库路径",
|
||||
)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
create = sub.add_parser("create", help="生成卡密")
|
||||
create.add_argument("--days", type=int, default=30)
|
||||
create.add_argument("--count", type=int, default=1)
|
||||
create.add_argument("--max-devices", type=int, default=1)
|
||||
create.add_argument("--customer", default="")
|
||||
create.set_defaults(func=cmd_create)
|
||||
|
||||
list_cmd = sub.add_parser("list", help="查看最近卡密")
|
||||
list_cmd.add_argument("--limit", type=int, default=50)
|
||||
list_cmd.set_defaults(func=cmd_list)
|
||||
|
||||
revoke = sub.add_parser("revoke", help="禁用卡密")
|
||||
revoke.add_argument("card_key")
|
||||
revoke.set_defaults(func=cmd_revoke)
|
||||
|
||||
unbind = sub.add_parser("unbind", help="解绑卡密设备")
|
||||
unbind.add_argument("card_key")
|
||||
unbind.set_defaults(func=cmd_unbind)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
return int(args.func(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,3 @@
|
||||
fastapi>=0.124.0
|
||||
uvicorn[standard]>=0.38.0
|
||||
cryptography>=41.0.0
|
||||
@@ -168,6 +168,44 @@ def test_install_license_rejects_invalid_text(tmp_path):
|
||||
assert not target_path.exists()
|
||||
|
||||
|
||||
def test_activate_license_code_installs_server_license(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")
|
||||
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="online-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
|
||||
calls["timeout_seconds"] = timeout_seconds
|
||||
return {"ok": True, "license": server_doc, "reason": "ok", "message": "授权有效"}
|
||||
|
||||
result = license_manager.install_license_or_activate(
|
||||
"DG-AAAA-BBBB-CCCC",
|
||||
target_path,
|
||||
activation_url="https://license.example.test/api/v1/activate",
|
||||
http_post=fake_post,
|
||||
)
|
||||
|
||||
assert result.ok is True
|
||||
assert target_path.exists()
|
||||
assert calls["payload"] == {
|
||||
"card_key": "DG-AAAA-BBBB-CCCC",
|
||||
"machine_fingerprint": "machine-a",
|
||||
}
|
||||
assert license_manager.check_license(target_path).payload["customer"] == "online-user"
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_license_server_api_activates_card(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseService
|
||||
|
||||
db_path = tmp_path / "license.db"
|
||||
service = LicenseService(db_path=db_path, private_key_pem=DEV_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=5, count=1, customer="api-user")[0]
|
||||
client = TestClient(api.create_app(service=service))
|
||||
|
||||
health = client.get("/api/v1/health")
|
||||
resp = client.post(
|
||||
"/api/v1/activate",
|
||||
json={"card_key": card.code, "machine_fingerprint": "machine-api"},
|
||||
)
|
||||
|
||||
assert health.status_code == 200
|
||||
assert health.json()["ok"] is True
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["ok"] is True
|
||||
assert body["license"]["payload"]["customer"] == "api-user"
|
||||
assert body["license"]["payload"]["machine_fingerprint"] == "machine-api"
|
||||
|
||||
|
||||
def test_license_server_api_rejects_unknown_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))
|
||||
|
||||
resp = client.post(
|
||||
"/api/v1/activate",
|
||||
json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"},
|
||||
)
|
||||
|
||||
assert resp.status_code == 404
|
||||
assert resp.json()["reason"] == "not_found"
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def test_license_server_creates_and_activates_card(tmp_path, monkeypatch):
|
||||
from douyin.license import license_manager
|
||||
from license_server import core
|
||||
|
||||
monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a")
|
||||
db_path = tmp_path / "license.db"
|
||||
service = core.LicenseService(db_path=db_path, private_key_pem=core.DEV_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=30, count=1, customer="alice")[0]
|
||||
|
||||
result = service.activate(card.code, machine_fingerprint="machine-a")
|
||||
|
||||
assert result.ok is True
|
||||
assert result.license_doc is not None
|
||||
status = license_manager.check_license(result.write_license(tmp_path / "license.dat"))
|
||||
assert status.ok is True
|
||||
assert status.payload["customer"] == "alice"
|
||||
assert status.payload["machine_fingerprint"] == "machine-a"
|
||||
|
||||
|
||||
def test_license_server_rejects_revoked_card(tmp_path):
|
||||
from license_server import core
|
||||
|
||||
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=core.DEV_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=7, count=1)[0]
|
||||
service.revoke(card.code)
|
||||
|
||||
result = service.activate(card.code, machine_fingerprint="machine-a")
|
||||
|
||||
assert result.ok is False
|
||||
assert result.reason == "revoked"
|
||||
|
||||
|
||||
def test_license_server_verify_reports_bound_activation(tmp_path):
|
||||
from license_server import core
|
||||
|
||||
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=core.DEV_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=3, count=1, customer="bob")[0]
|
||||
service.activate(card.code, machine_fingerprint="machine-b")
|
||||
|
||||
result = service.verify(card.code, machine_fingerprint="machine-b")
|
||||
|
||||
assert result.ok is True
|
||||
assert result.reason == "ok"
|
||||
assert result.expires_at is not None
|
||||
assert result.expires_at > datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def test_license_server_verify_rejects_other_machine(tmp_path):
|
||||
from license_server import core
|
||||
|
||||
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=core.DEV_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=3, count=1)[0]
|
||||
service.activate(card.code, machine_fingerprint="machine-a")
|
||||
|
||||
result = service.verify(card.code, machine_fingerprint="machine-b")
|
||||
|
||||
assert result.ok is False
|
||||
assert result.reason == "machine_mismatch"
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_manage_create_outputs_cards(tmp_path, capsys):
|
||||
from license_server import manage
|
||||
|
||||
rc = manage.main(
|
||||
[
|
||||
"--db",
|
||||
str(tmp_path / "license.db"),
|
||||
"create",
|
||||
"--days",
|
||||
"9",
|
||||
"--count",
|
||||
"2",
|
||||
"--customer",
|
||||
"tester",
|
||||
]
|
||||
)
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert rc == 0
|
||||
assert out.count("DG-") == 2
|
||||
assert "days=9" in out
|
||||
assert "customer=tester" in out
|
||||
|
||||
|
||||
def test_manage_revoke_disables_card(tmp_path, capsys):
|
||||
from license_server import manage
|
||||
from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseService
|
||||
|
||||
db_path = tmp_path / "license.db"
|
||||
service = LicenseService(db_path=db_path, private_key_pem=DEV_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=1, count=1)[0]
|
||||
|
||||
rc = manage.main(["--db", str(db_path), "revoke", card.code])
|
||||
|
||||
assert rc == 0
|
||||
assert "revoked" in capsys.readouterr().out
|
||||
assert service.activate(card.code, machine_fingerprint="machine-a").reason == "revoked"
|
||||
@@ -139,11 +139,11 @@ def test_license_install_route_accepts_code(monkeypatch):
|
||||
message = "授权有效"
|
||||
payload = {"customer": "demo"}
|
||||
|
||||
def fake_install(text):
|
||||
def fake_install(text, **_kwargs):
|
||||
calls["text"] = text
|
||||
return _Status()
|
||||
|
||||
monkeypatch.setattr(routes, "install_license_text", fake_install)
|
||||
monkeypatch.setattr(routes, "install_license_or_activate", fake_install)
|
||||
|
||||
status, obj = _post("/api/license", {"license_text": "DYGJ-demo"}, monkeypatch)
|
||||
|
||||
@@ -153,6 +153,39 @@ def test_license_install_route_accepts_code(monkeypatch):
|
||||
assert calls["text"] == "DYGJ-demo"
|
||||
|
||||
|
||||
def test_license_install_route_uses_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: {"license": {"activation_url": "https://license.example/api/v1/activate", "timeout_seconds": 7}},
|
||||
)
|
||||
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": "https://license.example/api/v1/activate",
|
||||
"timeout_seconds": 7,
|
||||
}
|
||||
|
||||
|
||||
def test_license_install_route_rejects_empty_code(monkeypatch):
|
||||
status, obj = _post("/api/license", {"license_text": " "}, monkeypatch)
|
||||
|
||||
|
||||
Reference in new issue
Block a user