247 lines
7.9 KiB
Python
247 lines
7.9 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"
|
|
ACTIVATION_CODE_PREFIX = "DYGJ-"
|
|
|
|
|
|
@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 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)
|