Files
douyi_guaji_main/douyin/license/license_manager.py
T

162 lines
5.1 KiB
Python

from __future__ import annotations
import base64
import hashlib
import json
import os
import platform
import sys
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
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"
@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 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)