from __future__ import annotations import base64 import hashlib import json import re 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 from cryptography.exceptions import InvalidSignature MAX_CARD_DAYS = 3660 MAX_CREATE_COUNT = 100 MAX_CARD_DEVICES = 20 MAX_CUSTOMER_LENGTH = 120 @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 @dataclass(frozen=True) class LicenseCardSummary: id: int code_hint: str status: str days: int max_devices: int customer: str created_at: str revoked_at: str activation_count: int last_seen_at: str @dataclass(frozen=True) class AuditLogEntry: action: str code_hint: str machine_fingerprint: str reason: str created_at: str @dataclass(frozen=True) class UpdateManifest: enabled: bool version: str filename: str sha256: str force: bool notes: str published_at: str 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}" def sanitize_update_filename(filename: str, *, version: str = "") -> str: raw = Path(str(filename or "")).name.strip() if not raw.lower().endswith(".exe"): safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "latest")) raw = f"DouyinGuaji-{safe_version}-Setup.exe" cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .") return cleaned or "DouyinGuaji-Setup.exe" def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def _bounded_int(value: int, *, name: str, minimum: int, maximum: int) -> int: parsed = int(value) if parsed < minimum or parsed > maximum: raise ValueError(f"{name} must be between {minimum} and {maximum}") return parsed 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.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() @property def update_dir(self) -> Path: path = self.db_path.parent / "updates" path.mkdir(parents=True, exist_ok=True) return path @property def update_manifest_path(self) -> Path: return self.db_path.parent / "update_manifest.json" def _connect(self) -> sqlite3.Connection: 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 ( 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 = _bounded_int(days, name="days", minimum=1, maximum=MAX_CARD_DAYS) count = _bounded_int(count, name="count", minimum=1, maximum=MAX_CREATE_COUNT) max_devices = _bounded_int(max_devices, name="max_devices", minimum=1, maximum=MAX_CARD_DEVICES) customer = str(customer or "").strip()[:MAX_CUSTOMER_LENGTH] 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=customer, ) 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 stats(self) -> dict[str, int]: with self._connect() as conn: row = conn.execute( """ SELECT COUNT(*) AS total, SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active, SUM(CASE WHEN status = 'revoked' THEN 1 ELSE 0 END) AS revoked FROM license_keys """ ).fetchone() activation_row = conn.execute( "SELECT COUNT(*) AS total FROM activations" ).fetchone() return { "total": int(row["total"] or 0), "active": int(row["active"] or 0), "revoked": int(row["revoked"] or 0), "activations": int(activation_row["total"] or 0), } def list_cards(self, *, limit: int = 50) -> list[LicenseCardSummary]: with self._connect() as conn: rows = conn.execute( """ SELECT lk.id, lk.code_hint, lk.status, lk.days, lk.max_devices, lk.customer, lk.created_at, COALESCE(lk.revoked_at, '') AS revoked_at, COUNT(a.id) AS activation_count, COALESCE(MAX(a.last_seen_at), '') AS last_seen_at 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(limit)),), ).fetchall() return [ LicenseCardSummary( id=int(row["id"]), code_hint=str(row["code_hint"] or ""), status=str(row["status"] or ""), days=int(row["days"] or 0), max_devices=int(row["max_devices"] or 0), customer=str(row["customer"] or ""), created_at=str(row["created_at"] or ""), revoked_at=str(row["revoked_at"] or ""), activation_count=int(row["activation_count"] or 0), last_seen_at=str(row["last_seen_at"] or ""), ) for row in rows ] def audit_logs(self, *, limit: int = 30) -> list[AuditLogEntry]: with self._connect() as conn: rows = conn.execute( """ SELECT action, code_hint, machine_fingerprint, reason, created_at FROM audit_logs ORDER BY id DESC LIMIT ? """, (max(1, int(limit)),), ).fetchall() return [ AuditLogEntry( action=str(row["action"] or ""), code_hint=str(row["code_hint"] or ""), machine_fingerprint=str(row["machine_fingerprint"] or ""), reason=str(row["reason"] or ""), created_at=str(row["created_at"] or ""), ) for row in rows ] def load_update_manifest(self) -> UpdateManifest: try: raw = json.loads(self.update_manifest_path.read_text(encoding="utf-8")) except FileNotFoundError: return UpdateManifest(False, "0.0.0", "", "", False, "", "") except Exception: return UpdateManifest(False, "0.0.0", "", "", False, "manifest 读取失败", "") if not isinstance(raw, dict): return UpdateManifest(False, "0.0.0", "", "", False, "manifest 格式错误", "") raw_filename = str(raw.get("filename") or "").strip() return UpdateManifest( enabled=bool(raw.get("enabled")), version=str(raw.get("version") or "0.0.0").strip() or "0.0.0", filename=sanitize_update_filename(raw_filename, version=str(raw.get("version") or "")) if raw_filename else "", sha256=str(raw.get("sha256") or "").strip().lower(), force=bool(raw.get("force")), notes=str(raw.get("notes") or ""), published_at=str(raw.get("published_at") or ""), ) def publish_update( self, *, version: str, filename: str, content: bytes, force: bool = True, notes: str = "", ) -> UpdateManifest: version = str(version or "").strip().lstrip("Vv") if not re.fullmatch(r"\d+(?:\.\d+){0,3}", version): raise ValueError("version must look like 3.3.4") if not content: raise ValueError("installer file is empty") safe_filename = sanitize_update_filename(filename, version=version) if not safe_filename.lower().endswith(".exe"): raise ValueError("installer must be an .exe file") target = self.update_dir / safe_filename target.write_bytes(content) manifest = UpdateManifest( enabled=True, version=version, filename=safe_filename, sha256=sha256_bytes(content), force=bool(force), notes=str(notes or "").strip()[:500], published_at=iso_utc(utcnow()), ) self.update_manifest_path.write_text( json.dumps(manifest.__dict__, ensure_ascii=False, indent=2), encoding="utf-8", ) return manifest def disable_update(self) -> UpdateManifest: existing = self.load_update_manifest() manifest = UpdateManifest( enabled=False, version=existing.version or "0.0.0", filename=existing.filename, sha256=existing.sha256, force=False, notes=existing.notes, published_at=existing.published_at, ) self.update_manifest_path.write_text( json.dumps(manifest.__dict__, ensure_ascii=False, indent=2), encoding="utf-8", ) return manifest def sign_payload(self, payload: dict[str, Any]) -> str: signature = self.private_key.sign(canonical_payload_bytes(payload)) return base64.b64encode(signature).decode("ascii") 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", "缺少机器码") code_hash = hash_card_code(code) with self._connect() as conn: 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", "卡密不存在") 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, card_hash=code_hash, ) 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_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_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( """ 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_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_card_hash(conn, audit_action, card_hash or str(card["code_hash"]), raw_machine, "expired") return LicenseActionResult(False, "expired", "授权已过期", expires_at=expires_at) 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 = ?", (str(code_hash or "").strip().lower(),), ).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, card_hash: str, ) -> dict[str, Any]: payload = { "customer": customer, "machine_fingerprint": machine_fingerprint, "expires_at": iso_utc(expires_at), "license_version": 1, "card_hash": card_hash, } signature = self.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())), ) 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())), )