feat: enforce online license verification

This commit is contained in:
Your Name committed 2026-06-19 11:49:57 +08:00
1 parent c5b7198145
commit 040ccd8161
9 files changed
+365 -20

No files matched your search

+2 -2
View File
@@ -106,7 +106,7 @@ os.environ.setdefault("OMP_NUM_THREADS", "1")
from douyin.core.douyin_fudai import fudai_analyse
from douyin.core import path_config
from douyin.license.license_manager import require_license_or_exit
from douyin.license.license_manager import require_online_license_or_exit
def ensure_adb_in_path() -> None:
@@ -462,7 +462,7 @@ def _cold_start_douyin_for_test(analyser: object, device_id: str) -> bool:
def main(argv: list[str]) -> int:
require_license_or_exit()
require_online_license_or_exit()
ensure_adb_in_path()
args = parse_args(argv)
run_started_at = time.time()
+121
View File
@@ -6,6 +6,8 @@ import json
import os
import platform
import sys
import threading
import time
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -23,6 +25,8 @@ 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"
DEFAULT_VERIFY_INTERVAL_SECONDS = 600
DEFAULT_VERIFY_FAILURES_BEFORE_EXIT = 3
@dataclass(frozen=True)
@@ -242,6 +246,52 @@ def _default_http_post(
return obj
def get_default_verify_url() -> str:
raw = str(os.environ.get("DOUYIN_LICENSE_VERIFY_URL") or "").strip()
if raw:
return raw
activation_url = get_default_activation_url()
if activation_url.endswith("/activate"):
return activation_url[: -len("/activate")] + "/verify_license"
return activation_url.rstrip("/") + "/verify_license"
def verify_license_online(
path: str | os.PathLike[str] | None = None,
*,
verify_url: str = "",
timeout_seconds: int = 5,
http_post=None,
) -> LicenseStatus:
"""用服务器时间和卡密状态复核本地签名授权,避免改本机时间绕过。"""
local_status = check_license(path)
if not local_status.ok:
return local_status
license_path = Path(path) if path is not None else get_default_license_path()
try:
license_doc = json.loads(license_path.read_text(encoding="utf-8"))
except Exception as exc:
return LicenseStatus(False, "invalid_format", f"授权文件读取失败: {exc}", {})
url = str(verify_url or "").strip() or get_default_verify_url()
post = http_post or _default_http_post
try:
data = post(
url,
{"license": license_doc},
timeout_seconds=timeout_seconds,
)
except Exception as exc:
return LicenseStatus(False, "verify_failed", f"云端授权校验失败: {exc}", local_status.payload)
if not bool(data.get("ok")):
return LicenseStatus(
False,
str(data.get("reason") or "verify_rejected"),
str(data.get("message") or data.get("error") or "云端授权校验失败"),
local_status.payload,
)
return LicenseStatus(True, "ok", "授权有效", local_status.payload)
def activate_license_code(
card_key: str,
path: str | os.PathLike[str] | None = None,
@@ -311,6 +361,16 @@ def get_default_activation_url() -> str:
return str(os.environ.get("DOUYIN_LICENSE_ACTIVATION_URL") or DEFAULT_ACTIVATION_URL).strip()
def get_verify_interval_seconds() -> int:
raw = str(os.environ.get("DOUYIN_LICENSE_VERIFY_INTERVAL_SECONDS") or "").strip()
if not raw:
return DEFAULT_VERIFY_INTERVAL_SECONDS
try:
return max(60, int(raw))
except ValueError:
return DEFAULT_VERIFY_INTERVAL_SECONDS
def get_license_status_payload(
path: str | os.PathLike[str] | None = None,
) -> dict[str, Any]:
@@ -335,3 +395,64 @@ def require_license_or_exit(path: str | os.PathLike[str] | None = None) -> None:
return
print(f"[LICENSE] 授权校验失败: {status.reason} - {status.message}", file=sys.stderr)
raise SystemExit(86)
def require_online_license_or_exit(path: str | os.PathLike[str] | None = None) -> None:
status = check_license(path)
if not status.ok:
print(f"[LICENSE] 授权校验失败: {status.reason} - {status.message}", file=sys.stderr)
raise SystemExit(86)
if not is_license_required():
return
online = verify_license_online(path)
if online.ok:
return
print(f"[LICENSE] 云端授权校验失败: {online.reason} - {online.message}", file=sys.stderr)
raise SystemExit(86)
def start_online_license_monitor(
path: str | os.PathLike[str] | None = None,
*,
interval_seconds: int | None = None,
timeout_seconds: int = 5,
on_line=None,
) -> threading.Thread | None:
if not is_license_required():
return None
interval = interval_seconds if interval_seconds is not None else get_verify_interval_seconds()
interval = max(60, int(interval))
transient_failures = {"verify_failed", "rate_limited"}
def _log(message: str) -> None:
if on_line is not None:
try:
on_line(message)
return
except Exception:
pass
print(message, flush=True)
def _worker() -> None:
failures = 0
while True:
time.sleep(interval)
status = verify_license_online(path, timeout_seconds=timeout_seconds)
if status.ok:
failures = 0
_log("[LICENSE] 云端授权定时校验通过")
continue
if status.reason in transient_failures:
failures += 1
_log(
f"[LICENSE] 云端授权定时校验临时失败 {failures}/"
f"{DEFAULT_VERIFY_FAILURES_BEFORE_EXIT}: {status.reason} - {status.message}"
)
if failures < DEFAULT_VERIFY_FAILURES_BEFORE_EXIT:
continue
_log(f"[LICENSE] 云端授权已失效: {status.reason} - {status.message}")
os._exit(86)
thread = threading.Thread(target=_worker, name="license-online-monitor", daemon=True)
thread.start()
return thread
+3 -2
View File
@@ -20,7 +20,7 @@ from gui.gui_core import (
write_config,
)
from douyin.core.path_config import get_logs_dir
from douyin.license.license_manager import require_license_or_exit
from douyin.license.license_manager import require_online_license_or_exit, start_online_license_monitor
from gui.components.wifi_adb_scan_dialog import open_scan_dialog # noqa: F401 re-export
from gui.components.preview_view import (
async_refresh_preview as _async_refresh_preview_impl,
@@ -59,7 +59,7 @@ def format_gui_log_line(line: str) -> str: # noqa: F401 re-export for backward
def main():
require_license_or_exit()
require_online_license_or_exit()
_bundle = setup_root_window(read_config=read_config)
root = _bundle.root
ScrolledText = _bundle.ScrolledText
@@ -72,6 +72,7 @@ def main():
from tkinter.constants import X # type: ignore[assignment]
q, _log_writer, on_line, runner = setup_log_pipeline()
start_online_license_monitor(on_line=on_line)
# 顶部:设备选择 + Y偏移(其余运行参数放到左侧分组,避免重复)
top = ttk.Frame(root)
+3 -2
View File
@@ -24,7 +24,7 @@ if __name__ == "__main__":
run_startup_update_check_early(app_name="web_gui")
from douyin.core import path_config
from douyin.license.license_manager import require_license_or_exit
from douyin.license.license_manager import require_online_license_or_exit, start_online_license_monitor
# 从子包 re-export 顶层 helper(保持兼容)
from gui.web_gui_pkg import (
@@ -846,7 +846,8 @@ class Handler(BaseHTTPRequestHandler):
def main() -> int:
require_license_or_exit()
require_online_license_or_exit()
start_online_license_monitor(on_line=lambda line: print(line, flush=True))
host = get_web_gui_host()
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
port = get_web_gui_port()
+11
View File
@@ -19,6 +19,7 @@ from license_server.core import LicenseActionResult, LicenseService
RATE_LIMIT_WINDOW_SECONDS = 60
RATE_LIMIT_MAX_REQUESTS = 30
VERIFY_LICENSE_RATE_LIMIT_MAX_REQUESTS = 600
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
ADMIN_SESSION_COOKIE = "dygj_admin_session"
ADMIN_SESSION_SECONDS = 12 * 60 * 60
@@ -34,6 +35,10 @@ class VerifyRequest(BaseModel):
machine_fingerprint: str
class VerifyLicenseRequest(BaseModel):
license: dict[str, Any]
def result_response(result: LicenseActionResult) -> JSONResponse:
body: dict[str, Any] = {
"ok": result.ok,
@@ -372,6 +377,12 @@ def create_app(
)
)
@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.get("/admin")
def admin(request: Request) -> Response:
if not _admin_allowed(request, app.state.admin_token):
+95 -14
View File
@@ -11,6 +11,7 @@ from pathlib import Path
from typing import Any
from cryptography.hazmat.primitives import serialization
from cryptography.exceptions import InvalidSignature
MAX_CARD_DAYS = 3660
@@ -133,17 +134,21 @@ class LicenseService:
) -> None:
self.db_path = Path(db_path)
self.private_key_pem = private_key_pem
self.private_key = serialization.load_pem_private_key(self.private_key_pem, password=None)
self.public_key = self.private_key.public_key()
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 = sqlite3.connect(self.db_path, timeout=10)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA busy_timeout = 10000")
return conn
def _init_db(self) -> None:
with self._connect() as conn:
conn.execute("PRAGMA journal_mode = WAL")
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS license_keys (
@@ -334,8 +339,9 @@ class LicenseService:
raw_machine = str(machine_fingerprint or "").strip()
if not raw_machine:
return LicenseActionResult(False, "missing_machine", "缺少机器码")
code_hash = hash_card_code(code)
with self._connect() as conn:
card = self._get_card(conn, code)
card = self._get_card_by_hash(conn, code_hash)
if card is None:
self._audit(conn, "activate", code, raw_machine, "not_found")
return LicenseActionResult(False, "not_found", "卡密不存在")
@@ -385,6 +391,7 @@ class LicenseService:
customer=str(card["customer"] or ""),
machine_fingerprint=raw_machine,
expires_at=expires_at,
card_hash=code_hash,
)
self._audit(conn, "activate", code, raw_machine, "ok")
return LicenseActionResult(True, "ok", "授权有效", doc, expires_at)
@@ -394,13 +401,62 @@ class LicenseService:
if not raw_machine:
return LicenseActionResult(False, "missing_machine", "缺少机器码")
with self._connect() as conn:
card = self._get_card(conn, code)
card = self._get_card_by_hash(conn, hash_card_code(code))
if card is None:
self._audit(conn, "verify", code, raw_machine, "not_found")
return LicenseActionResult(False, "not_found", "卡密不存在")
return self._verify_card_row(conn, card, raw_machine, audit_action="verify")
def verify_license_doc(self, license_doc: dict[str, Any]) -> LicenseActionResult:
if not isinstance(license_doc, dict):
return LicenseActionResult(False, "invalid_format", "授权文件格式无效")
payload = license_doc.get("payload")
signature_raw = license_doc.get("signature")
if not isinstance(payload, dict) or not isinstance(signature_raw, str):
return LicenseActionResult(False, "invalid_format", "授权文件缺少 payload/signature")
try:
signature = base64.b64decode(signature_raw.encode("ascii"), validate=True)
self.public_key.verify(signature, canonical_payload_bytes(payload))
except InvalidSignature:
return LicenseActionResult(False, "invalid_signature", "授权签名校验失败")
except Exception:
return LicenseActionResult(False, "invalid_signature", "授权公钥或签名校验异常")
card_hash = str(payload.get("card_hash") or "").strip().lower()
raw_machine = str(payload.get("machine_fingerprint") or "").strip()
if len(card_hash) != 64 or any(ch not in "0123456789abcdef" for ch in card_hash):
return LicenseActionResult(False, "invalid_format", "授权文件缺少有效卡密指纹")
if not raw_machine:
return LicenseActionResult(False, "missing_machine", "缺少机器码")
with self._connect() as conn:
card = self._get_card_by_hash(conn, card_hash)
if card is None:
self._audit_card_hash(conn, "verify_license", card_hash, raw_machine, "not_found")
return LicenseActionResult(False, "not_found", "卡密不存在")
return self._verify_card_row(
conn,
card,
raw_machine,
audit_action="verify_license",
card_hash=card_hash,
audit_success=False,
touch_last_seen=False,
)
def _verify_card_row(
self,
conn: sqlite3.Connection,
card: sqlite3.Row,
raw_machine: str,
*,
audit_action: str,
card_hash: str = "",
audit_success: bool = True,
touch_last_seen: bool = True,
) -> LicenseActionResult:
invalid = self._invalid_card_reason(card)
if invalid:
self._audit(conn, "verify", code, raw_machine, invalid)
self._audit_card_hash(conn, audit_action, card_hash or str(card["code_hash"]), raw_machine, invalid)
return LicenseActionResult(False, invalid, self._reason_message(invalid))
activation = conn.execute(
"""
@@ -415,23 +471,28 @@ class LicenseService:
(card["id"],),
).fetchone()
reason = "machine_mismatch" if any_activation else "not_activated"
self._audit(conn, "verify", code, raw_machine, reason)
self._audit_card_hash(conn, audit_action, card_hash or str(card["code_hash"]), 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")
self._audit_card_hash(conn, audit_action, card_hash or str(card["code_hash"]), 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")
if touch_last_seen:
conn.execute(
"UPDATE activations SET last_seen_at = ? WHERE id = ?",
(iso_utc(utcnow()), activation["id"]),
)
if audit_success:
self._audit_card_hash(conn, audit_action, card_hash or str(card["code_hash"]), raw_machine, "ok")
return LicenseActionResult(True, "ok", "授权有效", expires_at=expires_at)
def _get_card(self, conn: sqlite3.Connection, code: str) -> sqlite3.Row | None:
return self._get_card_by_hash(conn, hash_card_code(code))
def _get_card_by_hash(self, conn: sqlite3.Connection, code_hash: str) -> sqlite3.Row | None:
return conn.execute(
"SELECT * FROM license_keys WHERE code_hash = ?",
(hash_card_code(code),),
(str(code_hash or "").strip().lower(),),
).fetchone()
def _invalid_card_reason(self, card: sqlite3.Row) -> str:
@@ -458,15 +519,16 @@ class LicenseService:
customer: str,
machine_fingerprint: str,
expires_at: datetime,
card_hash: str,
) -> 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,
"card_hash": card_hash,
}
signature = private_key.sign(canonical_payload_bytes(payload))
signature = self.private_key.sign(canonical_payload_bytes(payload))
return {
"payload": payload,
"signature": base64.b64encode(signature).decode("ascii"),
@@ -488,3 +550,22 @@ class LicenseService:
""",
(action, mask_card_code(code), machine_fingerprint, reason, iso_utc(utcnow())),
)
def _audit_card_hash(
self,
conn: sqlite3.Connection,
action: str,
card_hash: str,
machine_fingerprint: str,
reason: str,
) -> None:
raw = str(card_hash or "").strip()
hint = f"{raw[:4]}...{raw[-4:]}" if len(raw) > 8 else "***"
conn.execute(
"""
INSERT INTO audit_logs
(action, code_hint, machine_fingerprint, reason, created_at)
VALUES (?, ?, ?, ?, ?)
""",
(action, hint, machine_fingerprint, reason, iso_utc(utcnow())),
)
+71
View File
@@ -253,6 +253,77 @@ def test_plain_card_uses_default_activation_url(tmp_path, monkeypatch):
assert calls["payload"]["card_key"] == "DG-DEFAULT-TEST"
def test_online_verify_posts_signed_license_doc(tmp_path, monkeypatch):
from douyin.license import license_manager
monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a")
monkeypatch.setattr(license_manager, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
license_path = tmp_path / "license.dat"
_create_test_license(
output_path=license_path,
machine_fingerprint="machine-a",
expires_at=datetime.now(timezone.utc) + timedelta(days=30),
customer="online-check",
)
raw = json.loads(license_path.read_text(encoding="utf-8"))
raw["payload"]["card_hash"] = "a" * 64
license_path.write_text(json.dumps(raw, ensure_ascii=False), 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, "reason": "ok", "message": "授权有效"}
status = license_manager.verify_license_online(
license_path,
verify_url="https://license.example.test/api/v1/verify_license",
http_post=fake_post,
)
assert status.ok is False
assert status.reason == "invalid_signature"
def test_online_verify_rejects_server_revocation(tmp_path, monkeypatch):
from douyin.license import license_manager
from license_server.core import LicenseService
monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a")
monkeypatch.setattr(license_manager, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
card = service.create_cards(days=3, count=1)[0]
activated = service.activate(card.code, machine_fingerprint="machine-a")
assert activated.license_doc is not None
license_path = tmp_path / "license.dat"
license_path.write_text(json.dumps(activated.license_doc, ensure_ascii=False), encoding="utf-8")
def fake_post(url, payload, timeout_seconds=10):
result = service.verify_license_doc(payload["license"])
return {"ok": result.ok, "reason": result.reason, "message": result.message}
assert license_manager.verify_license_online(license_path, http_post=fake_post).ok is True
service.revoke(card.code)
status = license_manager.verify_license_online(license_path, http_post=fake_post)
assert status.ok is False
assert status.reason == "revoked"
def test_online_verify_uses_verify_url_from_activation_url(monkeypatch):
from douyin.license import license_manager
monkeypatch.delenv("DOUYIN_LICENSE_VERIFY_URL", raising=False)
monkeypatch.setattr(
license_manager,
"get_default_activation_url",
lambda: "https://license.example.test/api/v1/activate",
)
assert license_manager.get_default_verify_url() == "https://license.example.test/api/v1/verify_license"
def test_license_status_public_payload_hides_signature(tmp_path, monkeypatch):
from douyin.license import license_manager
+25
View File
@@ -26,6 +26,11 @@ def test_license_server_api_activates_card(tmp_path):
assert body["ok"] is True
assert body["license"]["payload"]["customer"] == "api-user"
assert body["license"]["payload"]["machine_fingerprint"] == "machine-api"
assert len(body["license"]["payload"]["card_hash"]) == 64
verify = client.post("/api/v1/verify_license", json={"license": body["license"]})
assert verify.status_code == 200
assert verify.json()["ok"] is True
def test_license_server_api_rejects_unknown_card(tmp_path):
@@ -47,6 +52,26 @@ def test_license_server_api_rejects_unknown_card(tmp_path):
assert resp.json()["reason"] == "not_found"
def test_license_server_api_verify_license_rejects_revoked_card(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
card = service.create_cards(days=5, count=1, customer="api-user")[0]
activated = service.activate(card.code, machine_fingerprint="machine-api")
assert activated.license_doc is not None
service.revoke(card.code)
client = TestClient(api.create_app(service=service))
resp = client.post("/api/v1/verify_license", json={"license": activated.license_doc})
assert resp.status_code == 403
assert resp.json()["reason"] == "revoked"
def test_admin_page_requires_token(tmp_path):
from fastapi.testclient import TestClient
+34
View File
@@ -22,6 +22,7 @@ def test_license_server_creates_and_activates_card(tmp_path, monkeypatch):
assert status.ok is True
assert status.payload["customer"] == "alice"
assert status.payload["machine_fingerprint"] == "machine-a"
assert len(str(status.payload["card_hash"])) == 64
def test_license_server_rejects_revoked_card(tmp_path):
@@ -66,3 +67,36 @@ def test_license_server_verify_rejects_other_machine(tmp_path):
assert result.ok is False
assert result.reason == "machine_mismatch"
def test_license_server_verify_license_doc_rejects_revoked_card(tmp_path):
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
card = service.create_cards(days=3, count=1)[0]
activated = service.activate(card.code, machine_fingerprint="machine-a")
assert activated.license_doc is not None
assert service.verify_license_doc(activated.license_doc).ok is True
service.revoke(card.code)
result = service.verify_license_doc(activated.license_doc)
assert result.ok is False
assert result.reason == "revoked"
def test_license_server_verify_license_doc_requires_card_hash(tmp_path):
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
card = service.create_cards(days=3, count=1)[0]
activated = service.activate(card.code, machine_fingerprint="machine-a")
assert activated.license_doc is not None
activated.license_doc["payload"].pop("card_hash", None)
result = service.verify_license_doc(activated.license_doc)
assert result.ok is False
assert result.reason == "invalid_signature"