feat: add simple license activation server

This commit is contained in:
Your Name committed 2026-06-18 17:39:56 +08:00
1 parent b2db5ed499
commit 05be83d289
17 files changed
+1053 -6

No files matched your search

+15
View File
@@ -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"]
+56
View File
@@ -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` 只能放服务器,不能随客户端分发。
+1
View File
@@ -0,0 +1 @@
"""Simple server-side license activation package."""
+97
View File
@@ -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()
+377
View File
@@ -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())),
)
+16
View File
@@ -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
+123
View File
@@ -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())
+3
View File
@@ -0,0 +1,3 @@
fastapi>=0.124.0
uvicorn[standard]>=0.38.0
cryptography>=41.0.0