from __future__ import annotations import base64 import hashlib import json 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 DEV_PRIVATE_KEY_PEM = b"""-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIOjSJg0Y4mQJcAnb/9o4dDANZSeTeLJYt04nUVZNvlEy -----END PRIVATE KEY----- """ @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 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}" 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.db_path.parent.mkdir(parents=True, exist_ok=True) self._init_db() def _connect(self) -> sqlite3.Connection: conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON") return conn def _init_db(self) -> None: with self._connect() as conn: 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 = max(1, int(days)) count = max(1, int(count)) max_devices = max(1, int(max_devices)) 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=str(customer or ""), ) 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 activate(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(conn, code) 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, ) 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(conn, code) if card is None: self._audit(conn, "verify", code, raw_machine, "not_found") return LicenseActionResult(False, "not_found", "卡密不存在") invalid = self._invalid_card_reason(card) if invalid: self._audit(conn, "verify", code, 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(conn, "verify", code, 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") 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") return LicenseActionResult(True, "ok", "授权有效", expires_at=expires_at) def _get_card(self, conn: sqlite3.Connection, code: str) -> sqlite3.Row | None: return conn.execute( "SELECT * FROM license_keys WHERE code_hash = ?", (hash_card_code(code),), ).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, ) -> 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, } signature = 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())), )