diff --git a/.gitignore b/.gitignore index 67fcad0..f38b344 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,7 @@ temp/ # Local configuration and backups config/*.json !config/README.md +license.dat *.bak *.bak_* *.backup diff --git a/bin/run_cli.py b/bin/run_cli.py index 62b620b..7d44a59 100644 --- a/bin/run_cli.py +++ b/bin/run_cli.py @@ -98,6 +98,7 @@ os.environ.setdefault("GLOG_minloglevel", "2") os.environ.setdefault("OMP_NUM_THREADS", "1") from douyin.core.douyin_fudai import fudai_analyse +from douyin.license.license_manager import require_license_or_exit def ensure_adb_in_path() -> None: @@ -339,6 +340,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace: def main(argv: list[str]) -> int: + require_license_or_exit() ensure_adb_in_path() args = parse_args(argv) diff --git a/douyin/license/__init__.py b/douyin/license/__init__.py new file mode 100644 index 0000000..3529e60 --- /dev/null +++ b/douyin/license/__init__.py @@ -0,0 +1,5 @@ +"""本地授权校验模块。 + +客户端只包含公钥和验签逻辑;私钥应留在本机工具或未来服务器端。 +""" + diff --git a/douyin/license/license_manager.py b/douyin/license/license_manager.py new file mode 100644 index 0000000..28ad4c0 --- /dev/null +++ b/douyin/license/license_manager.py @@ -0,0 +1,161 @@ +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) diff --git a/douyin/license/public_key.py b/douyin/license/public_key.py new file mode 100644 index 0000000..8466d47 --- /dev/null +++ b/douyin/license/public_key.py @@ -0,0 +1,9 @@ +"""License 公钥。 + +生产分发前可替换为服务器私钥对应的公钥;客户端永远不应内置私钥。 +""" + +PUBLIC_KEY_PEM = b"""-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEA/lneBfaW7y3NCJhRkvZFSo822jWqHTYPce8Phssu2aw= +-----END PUBLIC KEY----- +""" diff --git a/gui/gui_app.py b/gui/gui_app.py index 4b1bf1a..faa5294 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -15,6 +15,7 @@ from gui.gui_core import ( write_config, ) from douyin.core.path_config import get_logs_dir +from douyin.license.license_manager import require_license_or_exit from gui.components.wifi_adb_scan_dialog import open_scan_dialog # noqa: F401 re-export from gui.components.preview_view import ( async_refresh_preview as _async_refresh_preview_impl, @@ -53,6 +54,7 @@ def format_gui_log_line(line: str) -> str: # noqa: F401 re-export for backward def main(): + require_license_or_exit() _bundle = setup_root_window(read_config=read_config) root = _bundle.root ScrolledText = _bundle.ScrolledText diff --git a/gui/web_gui.py b/gui/web_gui.py index e22ac89..246debe 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -19,6 +19,7 @@ if project_root not in sys.path: sys.path.insert(0, project_root) from douyin.core import path_config +from douyin.license.license_manager import require_license_or_exit # 从子包 re-export 顶层 helper(保持兼容) from gui.web_gui_pkg import ( @@ -840,6 +841,7 @@ class Handler(BaseHTTPRequestHandler): def main() -> int: + require_license_or_exit() host = get_web_gui_host() # 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000 port = get_web_gui_port() diff --git a/packaging/README.md b/packaging/README.md index c95ce6f..271e7a7 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -19,6 +19,14 @@ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall ``` +如果要生成带本地授权的测试包,先生成当前机器的 `license.dat`: + +```powershell +python -m tools.license_dev --output license.dat --days 30 --customer local +``` + +正式接入激活服务器后,`license.dat` 应由服务器签发;客户端只内置公钥。 + 输出目录: ```text @@ -32,6 +40,7 @@ dist\DouyinGuaji-\ - `run_cli.exe`:后台运行入口,桌面 GUI / Web GUI 会调用它 - `assets/`、`webui/`、`config/`:运行所需资源 - `logs/`、`pic/`、`state/`:运行时输出目录 +- `license.dat`:可选授权文件;打包脚本检测到项目根目录存在该文件时会复制进分发目录 ## 生成安装包 @@ -49,6 +58,8 @@ dist\installer\DouyinGuaji-3.3.3-Setup.exe ## 发给别人前检查 +- 打包脚本会自动运行 `python -m tools.distribution_manifest dist\DouyinGuaji-`,防止源码、调试产物、个人配置和旧日志混入分发目录。 +- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、`assets/`、`webui/`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep` 和可选 `license.dat`。 - 目标电脑需要能使用 ADB,或者把 Android platform-tools 加入 PATH。 - 首次启动 PaddleOCR 相关组件可能较慢,杀毒软件也可能扫描 exe。 - `config/config.json` 是本地运行配置,默认不随安装包带个人配置;让使用者首次打开后在 GUI 中保存配置。 diff --git a/packaging/pyinstaller/build_windows.ps1 b/packaging/pyinstaller/build_windows.ps1 index 00dede3..8380b21 100644 --- a/packaging/pyinstaller/build_windows.ps1 +++ b/packaging/pyinstaller/build_windows.ps1 @@ -43,6 +43,13 @@ python -m PyInstaller @CommonArgs --name run_cli --console "bin\run_cli.py" foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) { $srcDir = Join-Path $DistRoot $name Copy-Item -LiteralPath (Join-Path $srcDir "$name.exe") -Destination (Join-Path $DistRoot "$name.exe") -Force + $srcInternal = Join-Path $srcDir "_internal" + $dstInternal = Join-Path $DistRoot "_internal" + if (Test-Path $srcInternal) { + New-Item -ItemType Directory -Force $dstInternal | Out-Null + Copy-Item -LiteralPath (Join-Path $srcInternal "*") -Destination $dstInternal -Recurse -Force + } + Remove-Item -LiteralPath $srcDir -Recurse -Force } foreach ($dir in @("assets", "webui")) { @@ -56,10 +63,19 @@ foreach ($dir in @("assets", "webui")) { New-Item -ItemType Directory -Force (Join-Path $DistRoot "config") | Out-Null Copy-Item -LiteralPath (Join-Path $Root "config\README.md") -Destination (Join-Path $DistRoot "config\README.md") -Force foreach ($dir in @("logs", "pic", "state")) { - New-Item -ItemType Directory -Force (Join-Path $DistRoot $dir) | Out-Null + $runtimeDir = Join-Path $DistRoot $dir + New-Item -ItemType Directory -Force $runtimeDir | Out-Null + New-Item -ItemType File -Force (Join-Path $runtimeDir ".keep") | Out-Null +} + +$licensePath = Join-Path $Root "license.dat" +if (Test-Path $licensePath) { + Copy-Item -LiteralPath $licensePath -Destination (Join-Path $DistRoot "license.dat") -Force } Copy-Item -LiteralPath (Join-Path $Root "README.md") -Destination (Join-Path $DistRoot "README.md") -Force +python -m tools.distribution_manifest $DistRoot + Write-Host "[OK] Portable package: $DistRoot" Write-Host "[NEXT] If Inno Setup is installed: iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=$Version" diff --git a/requirements-minimal.txt b/requirements-minimal.txt index 24e4e2f..6c4bd70 100644 --- a/requirements-minimal.txt +++ b/requirements-minimal.txt @@ -24,6 +24,9 @@ protobuf==3.20.3 # 如果不安装ttkbootstrap,程序会自动使用原生tkinter # ttkbootstrap>=1.10.0 +# 授权文件签名/验签(客户端只内置公钥) +cryptography>=41.0.0 + diff --git a/requirements.txt b/requirements.txt index 68ec5d6..9aace85 100644 --- a/requirements.txt +++ b/requirements.txt @@ -41,6 +41,9 @@ ttkbootstrap>=1.10.0 # 终端颜色输出(用于彩色日志查看器) colorama>=0.4.0 +# 授权文件签名/验签(客户端只内置公钥) +cryptography>=41.0.0 + diff --git a/tests/test_distribution_manifest.py b/tests/test_distribution_manifest.py new file mode 100644 index 0000000..3354d87 --- /dev/null +++ b/tests/test_distribution_manifest.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import subprocess +import sys + + +def test_distribution_manifest_blocks_source_and_debug_artifacts(): + from tools.distribution_manifest import find_forbidden_distribution_entries + + entries = [ + "DouyinGuajiGUI.exe", + "_internal/python310.dll", + "assets/fudai_task_count_v2_one_task.png", + "douyin/core/douyin_fudai.py", + "artifacts/debug.png", + "config/config.json", + "logs/unified.log", + "pic/debug_captures/a.png", + "DouyinGuajiGUI/_internal/base_library.zip", + "_internal/douyin/core/douyin_fudai.py", + "_internal/cv2/__init__.py", + ] + + blocked = find_forbidden_distribution_entries(entries) + + assert "douyin/core/douyin_fudai.py" in blocked + assert "artifacts/debug.png" in blocked + assert "config/config.json" in blocked + assert "logs/unified.log" in blocked + assert "pic/debug_captures/a.png" in blocked + assert "DouyinGuajiGUI/_internal/base_library.zip" in blocked + assert "_internal/douyin/core/douyin_fudai.py" in blocked + assert "_internal/cv2/__init__.py" not in blocked + assert "assets/fudai_task_count_v2_one_task.png" not in blocked + + +def test_distribution_manifest_allows_expected_runtime_shape(): + from tools.distribution_manifest import find_forbidden_distribution_entries + + entries = [ + "DouyinGuajiGUI.exe", + "web_gui.exe", + "run_cli.exe", + "_internal/base_library.zip", + "assets/fudai_task_count_v2_one_task.png", + "webui/index.html", + "config/README.md", + "logs/.keep", + "pic/.keep", + "state/.keep", + "license.dat", + ] + + assert find_forbidden_distribution_entries(entries) == [] + + +def test_distribution_manifest_cli_passes_clean_tree(tmp_path): + dist = tmp_path / "dist" + for rel in [ + "DouyinGuajiGUI.exe", + "web_gui.exe", + "run_cli.exe", + "_internal/base_library.zip", + "assets/fudai_task_count_v2_one_task.png", + "webui/index.html", + "config/README.md", + "logs/.keep", + "pic/.keep", + "state/.keep", + "license.dat", + ]: + path = dist / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("x", encoding="utf-8") + + proc = subprocess.run( + [sys.executable, "-m", "tools.distribution_manifest", str(dist)], + capture_output=True, + text=True, + check=False, + ) + + assert proc.returncode == 0 + assert "[DIST-CHECK] PASS" in proc.stdout + + +def test_distribution_manifest_cli_fails_dirty_tree(tmp_path): + dist = tmp_path / "dist" + dirty = dist / "douyin" / "core" / "secret.py" + dirty.parent.mkdir(parents=True, exist_ok=True) + dirty.write_text("print('secret')", encoding="utf-8") + + proc = subprocess.run( + [sys.executable, "-m", "tools.distribution_manifest", str(dist)], + capture_output=True, + text=True, + check=False, + ) + + assert proc.returncode == 2 + assert "douyin/core/secret.py" in proc.stdout diff --git a/tests/test_license_manager.py b/tests/test_license_manager.py new file mode 100644 index 0000000..4511f6d --- /dev/null +++ b/tests/test_license_manager.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone + +import pytest + + +def test_signed_license_is_accepted_for_current_machine(tmp_path, monkeypatch): + from douyin.license import license_manager + from tools.license_dev import create_dev_license + + monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a") + license_path = tmp_path / "license.dat" + + create_dev_license( + output_path=license_path, + machine_fingerprint="machine-a", + expires_at=datetime.now(timezone.utc) + timedelta(days=30), + customer="local-test", + ) + + status = license_manager.check_license(license_path) + + assert status.ok is True + assert status.reason == "ok" + assert status.payload["customer"] == "local-test" + + +def test_license_rejects_different_machine(tmp_path, monkeypatch): + from douyin.license import license_manager + from tools.license_dev import create_dev_license + + monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-b") + license_path = tmp_path / "license.dat" + + create_dev_license( + output_path=license_path, + machine_fingerprint="machine-a", + expires_at=datetime.now(timezone.utc) + timedelta(days=30), + ) + + status = license_manager.check_license(license_path) + + assert status.ok is False + assert status.reason == "machine_mismatch" + + +def test_license_rejects_expired_file(tmp_path, monkeypatch): + from douyin.license import license_manager + from tools.license_dev import create_dev_license + + monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a") + license_path = tmp_path / "license.dat" + + create_dev_license( + output_path=license_path, + machine_fingerprint="machine-a", + expires_at=datetime.now(timezone.utc) - timedelta(days=1), + ) + + status = license_manager.check_license(license_path) + + assert status.ok is False + assert status.reason == "expired" + + +def test_license_rejects_tampered_payload(tmp_path, monkeypatch): + from douyin.license import license_manager + from tools.license_dev import create_dev_license + + monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a") + license_path = tmp_path / "license.dat" + + create_dev_license( + output_path=license_path, + machine_fingerprint="machine-a", + expires_at=datetime.now(timezone.utc) + timedelta(days=30), + ) + raw = json.loads(license_path.read_text(encoding="utf-8")) + raw["payload"]["customer"] = "tampered" + license_path.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8") + + status = license_manager.check_license(license_path) + + assert status.ok is False + assert status.reason == "invalid_signature" + + +def test_missing_license_is_allowed_in_source_mode(tmp_path, monkeypatch): + from douyin.license import license_manager + + monkeypatch.delenv("DOUYIN_LICENSE_REQUIRED", raising=False) + + status = license_manager.check_license(tmp_path / "missing.dat") + + assert status.ok is True + assert status.reason == "dev_bypass" + + +def test_missing_license_can_be_required(tmp_path, monkeypatch): + from douyin.license import license_manager + + monkeypatch.setenv("DOUYIN_LICENSE_REQUIRED", "1") + + status = license_manager.check_license(tmp_path / "missing.dat") + + assert status.ok is False + assert status.reason == "missing" diff --git a/tools/distribution_manifest.py b/tools/distribution_manifest.py new file mode 100644 index 0000000..16d3c99 --- /dev/null +++ b/tools/distribution_manifest.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import argparse +import os +from pathlib import Path + + +FORBIDDEN_PREFIXES = ( + ".git/", + ".github/", + ".pytest_cache/", + ".venv/", + ".vscode/", + "__pycache__/", + "artifacts/", + "bin/", + "build/", + "deleted_tests_backup/", + "docs/", + "douyin/", + "fudai_detail_modules/", + "gui/", + "MagicMock/", + "operations/", + "packaging/", + "scripts/", + "tests/", + "tools/", + "typings/", + "DouyinGuajiGUI/", + "run_cli/", + "web_gui/", +) + +FORBIDDEN_EXACT = { + "config/config.json", + "douyin_guaji.code-workspace", + "pyproject.toml", + "pyrightconfig.json", + "repo-backup.bundle", + "requirements.txt", + "requirements-minimal.txt", +} + +FORBIDDEN_SUFFIXES = ( + ".py", + ".pyc", + ".pyo", + ".spec", + ".log", + ".jsonl", + ".sqlite", + ".sqlite3", + ".db", + ".bundle", +) + +ALLOWED_RUNTIME_PLACEHOLDERS = { + "logs/.keep", + "pic/.keep", + "state/.keep", +} + + +def normalize_entry(entry: str) -> str: + return entry.replace("\\", "/").lstrip("./") + + +def is_forbidden_distribution_entry(entry: str) -> bool: + norm = normalize_entry(entry) + lower = norm.lower() + if lower.startswith("_internal/"): + project_bits = { + "_internal/douyin/", + "_internal/gui/", + "_internal/operations/", + "_internal/bin/", + "_internal/tools/", + "_internal/tests/", + "_internal/artifacts/", + } + return any(lower.startswith(prefix) for prefix in project_bits) + if lower in ALLOWED_RUNTIME_PLACEHOLDERS: + return False + if lower in FORBIDDEN_EXACT: + return True + if lower.startswith("logs/") or lower.startswith("state/"): + return lower not in ALLOWED_RUNTIME_PLACEHOLDERS + if lower.startswith("pic/"): + return lower not in ALLOWED_RUNTIME_PLACEHOLDERS + if any(lower.startswith(prefix.lower()) for prefix in FORBIDDEN_PREFIXES): + return True + return any(lower.endswith(suffix) for suffix in FORBIDDEN_SUFFIXES) + + +def find_forbidden_distribution_entries(entries: list[str]) -> list[str]: + return [entry for entry in entries if is_forbidden_distribution_entry(entry)] + + +def iter_distribution_entries(root: str | os.PathLike[str]) -> list[str]: + base = Path(root) + entries: list[str] = [] + for path in base.rglob("*"): + if path.is_file(): + entries.append(path.relative_to(base).as_posix()) + return sorted(entries) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="检查分发目录是否混入源码/调试产物") + parser.add_argument("dist_dir", help="例如 dist/DouyinGuaji-3.3.3") + args = parser.parse_args(argv) + + entries = iter_distribution_entries(args.dist_dir) + blocked = find_forbidden_distribution_entries(entries) + if blocked: + print("[DIST-CHECK] FAIL forbidden entries:") + for entry in blocked[:200]: + print(f" {entry}") + if len(blocked) > 200: + print(f" ... and {len(blocked) - 200} more") + return 2 + print(f"[DIST-CHECK] PASS checked_files={len(entries)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/license_dev.py b/tools/license_dev.py new file mode 100644 index 0000000..2435efa --- /dev/null +++ b/tools/license_dev.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import argparse +import base64 +import json +from datetime import datetime, timedelta, timezone +from pathlib import Path + +from cryptography.hazmat.primitives import serialization + +from douyin.license.license_manager import ( + canonical_payload_bytes, + get_default_license_path, + get_machine_fingerprint, +) + + +# 仅用于本地第一阶段测试。正式接服务器后,私钥应从服务器环境变量/密钥库读取。 +DEV_PRIVATE_KEY_PEM = b"""-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIOjSJg0Y4mQJcAnb/9o4dDANZSeTeLJYt04nUVZNvlEy +-----END PRIVATE KEY----- +""" + + +def _load_dev_private_key(): + return serialization.load_pem_private_key(DEV_PRIVATE_KEY_PEM, password=None) + + +def create_dev_license( + output_path: str | Path, + machine_fingerprint: str, + expires_at: datetime, + customer: str = "local", +) -> Path: + if expires_at.tzinfo is None: + expires_at = expires_at.replace(tzinfo=timezone.utc) + expires_at = expires_at.astimezone(timezone.utc) + payload = { + "customer": customer, + "machine_fingerprint": machine_fingerprint, + "expires_at": expires_at.isoformat().replace("+00:00", "Z"), + "license_version": 1, + } + signature = _load_dev_private_key().sign(canonical_payload_bytes(payload)) + doc = { + "payload": payload, + "signature": base64.b64encode(signature).decode("ascii"), + } + path = Path(output_path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(doc, ensure_ascii=False, indent=2), encoding="utf-8") + return path + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="生成本地开发 license.dat") + parser.add_argument("--output", default=str(get_default_license_path())) + parser.add_argument("--machine", default=get_machine_fingerprint()) + parser.add_argument("--days", type=int, default=30) + parser.add_argument("--customer", default="local") + args = parser.parse_args(argv) + + path = create_dev_license( + output_path=args.output, + machine_fingerprint=args.machine, + expires_at=datetime.now(timezone.utc) + timedelta(days=max(1, int(args.days))), + customer=str(args.customer or "local"), + ) + print(f"[LICENSE] generated: {path}") + print(f"[LICENSE] machine_fingerprint: {args.machine}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())