Files
douyi_guaji_main/douyin/license/license_manager.py
T

459 lines
15 KiB
Python

from __future__ import annotations
import base64
import hashlib
import json
import os
import platform
import sys
import threading
import time
import uuid
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
from douyin.core import path_config
from douyin.license.public_key import PUBLIC_KEY_PEM
LICENSE_FILENAME = "license.dat"
ACTIVATION_CODE_PREFIX = "DYGJ-"
DEFAULT_ACTIVATION_URL = "http://dy.absfan.cn:18100/api/v1/activate"
DEFAULT_VERIFY_INTERVAL_SECONDS = 600
DEFAULT_VERIFY_FAILURES_BEFORE_EXIT = 3
@dataclass(frozen=True)
class LicenseStatus:
ok: bool
reason: str
message: str
payload: dict[str, Any]
def canonical_payload_bytes(payload: dict[str, Any]) -> bytes:
"""返回稳定 JSON 字节,签名与验签必须使用同一格式。"""
return json.dumps(
payload,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
def _read_windows_machine_guid() -> str:
if not sys.platform.startswith("win"):
return ""
try:
import winreg
with winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Cryptography",
) as key:
value, _ = winreg.QueryValueEx(key, "MachineGuid")
return str(value or "").strip()
except Exception:
return ""
def get_machine_fingerprint() -> str:
"""生成本机指纹;只保存 hash,不暴露原始机器信息。"""
parts = [
platform.system(),
platform.node(),
platform.machine(),
_read_windows_machine_guid(),
str(uuid.getnode()),
]
raw = "|".join(x for x in parts if x).encode("utf-8", errors="ignore")
return hashlib.sha256(raw).hexdigest()
def get_default_license_path() -> Path:
raw = (os.environ.get("DOUYIN_LICENSE_PATH") or "").strip()
if raw:
return Path(raw)
return Path(path_config.PROJECT_ROOT) / LICENSE_FILENAME
def is_license_required() -> bool:
raw = (os.environ.get("DOUYIN_LICENSE_REQUIRED") or "").strip().lower()
if raw in {"1", "true", "yes", "on"}:
return True
if raw in {"0", "false", "no", "off"}:
return False
return bool(getattr(sys, "frozen", False))
def _load_public_key():
return serialization.load_pem_public_key(PUBLIC_KEY_PEM)
def _parse_expires_at(raw: Any) -> datetime | None:
if not isinstance(raw, str) or not raw.strip():
return None
text = raw.strip()
if text.endswith("Z"):
text = text[:-1] + "+00:00"
try:
dt = datetime.fromisoformat(text)
except ValueError:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def check_license(path: str | os.PathLike[str] | None = None) -> LicenseStatus:
license_path = Path(path) if path is not None else get_default_license_path()
if not license_path.exists():
if not is_license_required():
return LicenseStatus(
ok=True,
reason="dev_bypass",
message="源码模式未强制授权,跳过本地 license 校验",
payload={},
)
return LicenseStatus(False, "missing", f"缺少授权文件: {license_path}", {})
try:
raw = json.loads(license_path.read_text(encoding="utf-8"))
except Exception:
return LicenseStatus(False, "invalid_format", "授权文件格式无效", {})
payload = raw.get("payload")
signature_raw = raw.get("signature")
if not isinstance(payload, dict) or not isinstance(signature_raw, str):
return LicenseStatus(False, "invalid_format", "授权文件缺少 payload/signature", {})
try:
signature = base64.b64decode(signature_raw.encode("ascii"), validate=True)
except Exception:
return LicenseStatus(False, "invalid_signature", "授权签名不是有效 base64", payload)
try:
_load_public_key().verify(signature, canonical_payload_bytes(payload))
except InvalidSignature:
return LicenseStatus(False, "invalid_signature", "授权签名校验失败", payload)
except Exception:
return LicenseStatus(False, "invalid_signature", "授权公钥或签名校验异常", payload)
expires_at = _parse_expires_at(payload.get("expires_at"))
if expires_at is None:
return LicenseStatus(False, "invalid_format", "授权文件缺少有效到期时间", payload)
if datetime.now(timezone.utc) > expires_at:
return LicenseStatus(False, "expired", "授权已过期", payload)
machine = str(payload.get("machine_fingerprint") or "").strip()
if not machine:
return LicenseStatus(False, "invalid_format", "授权文件缺少机器码", payload)
if machine != get_machine_fingerprint():
return LicenseStatus(False, "machine_mismatch", "授权文件不属于当前机器", payload)
return LicenseStatus(True, "ok", "授权有效", payload)
def _decode_activation_code(text: str) -> str:
raw = text.strip()
if not raw.upper().startswith(ACTIVATION_CODE_PREFIX):
return raw
encoded = raw[len(ACTIVATION_CODE_PREFIX):].replace("-", "").strip()
if not encoded:
raise ValueError("empty activation code")
padding = "=" * (-len(encoded) % 4)
data = base64.urlsafe_b64decode((encoded + padding).encode("ascii"))
return data.decode("utf-8")
def parse_license_text(text: str) -> dict[str, Any] | None:
"""解析 UI 输入的卡密文本,支持完整 JSON 或 DYGJ- 前缀卡密。"""
raw = str(text or "").strip()
if not raw:
return None
try:
decoded = _decode_activation_code(raw)
obj = json.loads(decoded)
except Exception:
return None
if not isinstance(obj, dict):
return None
payload = obj.get("payload")
signature = obj.get("signature")
if not isinstance(payload, dict) or not isinstance(signature, str):
return None
return obj
def install_license_text(
text: str,
path: str | os.PathLike[str] | None = None,
) -> LicenseStatus:
"""安装 UI 输入的卡密;验签通过后才写入 license.dat。"""
obj = parse_license_text(text)
if obj is None:
return LicenseStatus(False, "invalid_format", "卡密格式无效", {})
target = Path(path) if path is not None else get_default_license_path()
tmp_path = target.with_name(target.name + ".tmp")
try:
target.parent.mkdir(parents=True, exist_ok=True)
tmp_path.write_text(
json.dumps(obj, ensure_ascii=False, indent=2),
encoding="utf-8",
)
status = check_license(tmp_path)
if not status.ok:
try:
tmp_path.unlink()
except Exception:
pass
return status
tmp_path.replace(target)
return status
except Exception as e:
try:
if tmp_path.exists():
tmp_path.unlink()
except Exception:
pass
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 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,
*,
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)
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_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]:
status = check_license(path)
payload = status.payload if isinstance(status.payload, dict) else {}
return {
"ok": bool(status.ok),
"reason": status.reason,
"message": status.message,
"license_path": str(Path(path) if path is not None else get_default_license_path()),
"required": is_license_required(),
"machine_fingerprint": get_machine_fingerprint(),
"customer": str(payload.get("customer") or ""),
"expires_at": str(payload.get("expires_at") or ""),
"license_version": payload.get("license_version"),
}
def require_license_or_exit(path: str | os.PathLike[str] | None = None) -> None:
status = check_license(path)
if status.ok:
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