Add PyArmor obfuscation packaging flow

This commit is contained in:
Your Name committed 2026-06-17 23:42:15 +08:00
1 parent 5166678590
commit 11de0f75c7
4 files changed
+292 -5

No files matched your search

+11
View File
@@ -19,6 +19,16 @@ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall
```
如果要生成混淆后的分发包,加 `-Obfuscate`:
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -Obfuscate
```
混淆流程会先生成 `build\obfuscated-src\`,再让 PyInstaller 从该目录打包。该目录是中间产物,不要直接分发;最终仍然只分发 `dist\DouyinGuaji-<version>\` 或 Inno 生成的安装包。
注意:PyArmor 试用版会在混淆文件头部留下 trial 标记,正式分发前建议购买/配置正式授权后重新打包。
如果要生成带本地授权的测试包,先生成当前机器的 `license.dat`:
```powershell
@@ -63,3 +73,4 @@ dist\installer\DouyinGuaji-3.3.3-Setup.exe
- 目标电脑需要能使用 ADB,或者把 Android platform-tools 加入 PATH。
- 首次启动 PaddleOCR 相关组件可能较慢,杀毒软件也可能扫描 exe。
- `config/config.json` 是本地运行配置,默认不随安装包带个人配置;让使用者首次打开后在 GUI 中保存配置。
- 启用 `-Obfuscate` 后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。
+15 -5
View File
@@ -1,6 +1,7 @@
param(
[string]$Version = "",
[switch]$SkipInstall
[switch]$SkipInstall,
[switch]$Obfuscate
)
$ErrorActionPreference = "Stop"
@@ -15,6 +16,9 @@ if (-not $SkipInstall) {
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
python -m pip install pyinstaller
if ($Obfuscate) {
python -m pip install pyarmor
}
}
$DistRoot = Join-Path $Root "dist\DouyinGuaji-$Version"
@@ -23,12 +27,18 @@ if (Test-Path $DistRoot) {
}
New-Item -ItemType Directory -Force $DistRoot | Out-Null
$BuildSourceRoot = $Root
if ($Obfuscate) {
$BuildSourceRoot = Join-Path $Root "build\obfuscated-src"
python -m tools.obfuscation_staging --source-root $Root --staging-root $BuildSourceRoot
}
$CommonArgs = @(
"--clean",
"--noconfirm",
"--distpath", $DistRoot,
"--workpath", (Join-Path $Root "build\pyinstaller"),
"--paths", $Root,
"--paths", $BuildSourceRoot,
"--add-data", "assets;assets",
"--add-data", "webui;webui",
"--add-data", "config\README.md;config",
@@ -36,9 +46,9 @@ $CommonArgs = @(
"--hidden-import", "ttkbootstrap"
)
python -m PyInstaller @CommonArgs --name DouyinGuajiGUI --windowed "gui\gui_app.py"
python -m PyInstaller @CommonArgs --name web_gui --console "gui\web_gui.py"
python -m PyInstaller @CommonArgs --name run_cli --console "bin\run_cli.py"
python -m PyInstaller @CommonArgs --name DouyinGuajiGUI --windowed (Join-Path $BuildSourceRoot "gui\gui_app.py")
python -m PyInstaller @CommonArgs --name web_gui --console (Join-Path $BuildSourceRoot "gui\web_gui.py")
python -m PyInstaller @CommonArgs --name run_cli --console (Join-Path $BuildSourceRoot "bin\run_cli.py")
foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) {
$srcDir = Join-Path $DistRoot $name
+121
View File
@@ -0,0 +1,121 @@
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
def _write(path: Path, text: str = "x = 1\n") -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def _make_minimal_project(root: Path) -> None:
_write(root / "douyin" / "__init__.py")
_write(root / "douyin" / "core" / "version.py")
_write(root / "gui" / "gui_app.py")
_write(root / "gui" / "web_gui.py")
_write(root / "gui" / "components" / "left_config_area.py")
_write(root / "operations" / "__init__.py")
_write(root / "operations" / "ocr_operations.py")
_write(root / "bin" / "run_cli.py")
_write(root / "tools" / "license_dev.py", "PRIVATE_KEY = 'must-not-ship'\n")
def test_create_pyarmor_staging_uses_only_runtime_sources(tmp_path, monkeypatch):
from tools.obfuscation_staging import create_pyarmor_staging
monkeypatch.setattr("tools.obfuscation_staging.shutil.which", lambda name: "pyarmor.exe")
root = tmp_path / "project"
staging = tmp_path / "stage"
_make_minimal_project(root)
calls: list[list[str]] = []
def fake_runner(cmd, *, cwd, check):
calls.append([str(x) for x in cmd])
assert cwd == root
assert check is True
_write(staging / "douyin" / "__init__.py", "# obfuscated\n")
_write(staging / "gui" / "gui_app.py", "# obfuscated\n")
_write(staging / "gui" / "web_gui.py", "# obfuscated\n")
_write(staging / "operations" / "__init__.py", "# obfuscated\n")
_write(staging / "bin" / "run_cli.py", "# obfuscated\n")
_write(staging / "pyarmor_runtime_000000" / "__init__.py", "# runtime\n")
return subprocess.CompletedProcess(cmd, 0)
result = create_pyarmor_staging(root, staging, runner=fake_runner)
assert result.staging_root == staging
assert result.runtime_package.startswith("pyarmor_runtime")
command_text = " ".join(calls[0])
assert "pyarmor" in command_text
assert "douyin" in command_text
assert "gui" in command_text
assert "operations" in command_text
assert "bin/run_cli.py" in command_text
assert "tools" not in command_text
assert "license_dev.py" not in command_text
def test_validate_pyarmor_staging_requires_runtime_package(tmp_path):
from tools.obfuscation_staging import validate_pyarmor_staging
staging = tmp_path / "stage"
_write(staging / "douyin" / "__init__.py")
_write(staging / "gui" / "gui_app.py")
_write(staging / "gui" / "web_gui.py")
_write(staging / "operations" / "__init__.py")
_write(staging / "bin" / "run_cli.py")
with pytest.raises(RuntimeError, match="pyarmor_runtime"):
validate_pyarmor_staging(staging)
def test_validate_pyarmor_staging_rejects_sensitive_tools(tmp_path):
from tools.obfuscation_staging import validate_pyarmor_staging
staging = tmp_path / "stage"
_write(staging / "douyin" / "__init__.py")
_write(staging / "gui" / "gui_app.py")
_write(staging / "gui" / "web_gui.py")
_write(staging / "operations" / "__init__.py")
_write(staging / "bin" / "run_cli.py")
_write(staging / "pyarmor_runtime_000000" / "__init__.py")
_write(staging / "tools" / "license_dev.py", "PRIVATE_KEY = 'leak'\n")
with pytest.raises(RuntimeError, match="forbidden"):
validate_pyarmor_staging(staging)
def test_create_pyarmor_staging_moves_flat_entry_script_back_to_bin(tmp_path, monkeypatch):
from tools.obfuscation_staging import create_pyarmor_staging
monkeypatch.setattr("tools.obfuscation_staging.shutil.which", lambda name: "pyarmor.exe")
root = tmp_path / "project"
staging = tmp_path / "stage"
_make_minimal_project(root)
def fake_runner(cmd, *, cwd, check):
_write(staging / "douyin" / "__init__.py", "# obfuscated\n")
_write(staging / "gui" / "gui_app.py", "# obfuscated\n")
_write(staging / "gui" / "web_gui.py", "# obfuscated\n")
_write(staging / "operations" / "__init__.py", "# obfuscated\n")
_write(staging / "run_cli.py", "# flat obfuscated entry\n")
_write(staging / "pyarmor_runtime_000000" / "__init__.py", "# runtime\n")
return subprocess.CompletedProcess(cmd, 0)
create_pyarmor_staging(root, staging, runner=fake_runner)
assert (staging / "bin" / "run_cli.py").read_text(encoding="utf-8") == "# flat obfuscated entry\n"
assert not (staging / "run_cli.py").exists()
def test_windows_packaging_script_exposes_obfuscate_switch():
script = Path("packaging/pyinstaller/build_windows.ps1").read_text(encoding="utf-8")
assert "[switch]$Obfuscate" in script
assert "tools.obfuscation_staging" in script
assert "--paths\", $BuildSourceRoot" in script
assert "Join-Path $BuildSourceRoot \"gui\\gui_app.py\"" in script
assert "Join-Path $BuildSourceRoot \"bin\\run_cli.py\"" in script
+145
View File
@@ -0,0 +1,145 @@
from __future__ import annotations
import argparse
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Sequence
import sys
RUNTIME_SOURCE_DIRS = ("douyin", "gui", "operations")
RUNTIME_ENTRY_FILES = ("bin/run_cli.py",)
FORBIDDEN_STAGING_PREFIXES = ("tools/", "tests/", "artifacts/", "docs/", "packaging/")
FORBIDDEN_STAGING_FILES = ("tools/license_dev.py",)
Runner = Callable[..., subprocess.CompletedProcess]
@dataclass(frozen=True)
class ObfuscationResult:
staging_root: Path
runtime_package: str
def _as_posix(path: str | Path) -> str:
return str(path).replace("\\", "/")
def _iter_files(root: Path) -> list[str]:
if not root.exists():
return []
return sorted(path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file())
def _find_runtime_package(staging_root: Path) -> str:
for path in staging_root.iterdir() if staging_root.exists() else []:
if path.is_dir() and path.name.startswith("pyarmor_runtime"):
return path.name
return ""
def validate_pyarmor_staging(staging_root: str | Path) -> ObfuscationResult:
root = Path(staging_root)
missing: list[str] = []
for rel in [*RUNTIME_SOURCE_DIRS, *RUNTIME_ENTRY_FILES]:
if not (root / rel).exists():
missing.append(rel)
if missing:
raise RuntimeError(f"obfuscation staging missing required entries: {', '.join(missing)}")
runtime_package = _find_runtime_package(root)
if not runtime_package:
raise RuntimeError("obfuscation staging missing pyarmor_runtime package")
entries = _iter_files(root)
forbidden: list[str] = []
for entry in entries:
lower = entry.lower()
if any(lower.startswith(prefix) for prefix in FORBIDDEN_STAGING_PREFIXES):
forbidden.append(entry)
if lower in {item.lower() for item in FORBIDDEN_STAGING_FILES}:
forbidden.append(entry)
if forbidden:
raise RuntimeError(f"obfuscation staging contains forbidden entries: {', '.join(forbidden[:20])}")
return ObfuscationResult(staging_root=root, runtime_package=runtime_package)
def build_pyarmor_command(source_root: str | Path, staging_root: str | Path) -> list[str]:
source = Path(source_root)
target = Path(staging_root)
pyarmor = shutil.which("pyarmor")
if not pyarmor:
raise FileNotFoundError("pyarmor executable not found")
inputs = [
*RUNTIME_SOURCE_DIRS,
*RUNTIME_ENTRY_FILES,
]
return [
pyarmor,
"gen",
"--recursive",
"--output",
str(target),
*[_as_posix(item) for item in inputs if (source / item).exists()],
]
def normalize_pyarmor_staging_layout(staging_root: str | Path) -> None:
root = Path(staging_root)
for rel in RUNTIME_ENTRY_FILES:
expected = root / rel
if expected.exists():
continue
flat = root / Path(rel).name
if not flat.exists():
continue
expected.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(flat), str(expected))
def create_pyarmor_staging(
source_root: str | Path,
staging_root: str | Path,
*,
runner: Runner = subprocess.run,
) -> ObfuscationResult:
source = Path(source_root).resolve()
target = Path(staging_root).resolve()
if target.exists():
shutil.rmtree(target)
target.parent.mkdir(parents=True, exist_ok=True)
cmd = build_pyarmor_command(source, target)
runner(cmd, cwd=source, check=True)
normalize_pyarmor_staging_layout(target)
return validate_pyarmor_staging(target)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="生成 PyInstaller 使用的 PyArmor 混淆源码 staging 目录")
parser.add_argument("--source-root", default=".", help="项目根目录")
parser.add_argument("--staging-root", required=True, help="输出 staging 目录")
args = parser.parse_args(argv)
try:
result = create_pyarmor_staging(args.source_root, args.staging_root)
except FileNotFoundError:
print("[OBFUSCATE] FAIL pyarmor is not installed. Run: python -m pip install pyarmor", file=sys.stderr)
return 2
except subprocess.CalledProcessError as exc:
print(f"[OBFUSCATE] FAIL pyarmor exited with code {exc.returncode}", file=sys.stderr)
return exc.returncode or 1
except Exception as exc:
print(f"[OBFUSCATE] FAIL {exc}", file=sys.stderr)
return 1
print(f"[OBFUSCATE] PASS staging={result.staging_root} runtime={result.runtime_package}")
return 0
if __name__ == "__main__":
raise SystemExit(main())