Files
douyi_guaji_main/license_server/core.py
T

491 lines
17 KiB
Python

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
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
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 _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.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 = _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 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())),
)