Fix encrypted package runtime validation
This commit is contained in:
1 parent
abcee63776
commit
cc4caef6e1
7 files changed
+352
-21
No files matched your search
@@ -31,9 +31,13 @@ if (Test-Path $DistRoot) {
|
||||
New-Item -ItemType Directory -Force $DistRoot | Out-Null
|
||||
|
||||
$BuildSourceRoot = $Root
|
||||
$HiddenImportsFile = Join-Path $Root "build\obfuscation-hidden-imports.json"
|
||||
if ($Obfuscate) {
|
||||
$BuildSourceRoot = Join-Path $Root "build\obfuscated-src"
|
||||
python -m tools.obfuscation_staging --source-root $Root --staging-root $BuildSourceRoot
|
||||
python -m tools.obfuscation_staging --source-root $Root --staging-root $BuildSourceRoot --hidden-imports-output $HiddenImportsFile
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PyArmor obfuscation failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
$CommonArgs = @(
|
||||
@@ -46,12 +50,49 @@ $CommonArgs = @(
|
||||
"--add-data", "webui;webui",
|
||||
"--add-data", "config\README.md;config",
|
||||
"--hidden-import", "PIL._tkinter_finder",
|
||||
"--hidden-import", "ttkbootstrap"
|
||||
"--hidden-import", "ttkbootstrap",
|
||||
"--hidden-import", "logging.handlers",
|
||||
"--collect-submodules", "douyin",
|
||||
"--collect-submodules", "gui",
|
||||
"--collect-submodules", "operations"
|
||||
)
|
||||
|
||||
$ExcludedOptionalModules = @(
|
||||
"easyocr",
|
||||
"matplotlib",
|
||||
"modelscope",
|
||||
"pandas",
|
||||
"pytest",
|
||||
"scipy",
|
||||
"skimage",
|
||||
"tensorflow",
|
||||
"torch",
|
||||
"torchvision"
|
||||
)
|
||||
foreach ($name in $ExcludedOptionalModules) {
|
||||
$CommonArgs += @("--exclude-module", $name)
|
||||
}
|
||||
|
||||
if ($Obfuscate -and (Test-Path $HiddenImportsFile)) {
|
||||
$HiddenImports = Get-Content -LiteralPath $HiddenImportsFile -Raw | ConvertFrom-Json
|
||||
$CliOnlyHiddenImportRoots = @("cv2", "numpy", "paddleocr", "paddle")
|
||||
$RunCliArgs = @()
|
||||
foreach ($name in $HiddenImports) {
|
||||
$nameText = [string]$name
|
||||
$rootName = ($nameText -split "\.")[0]
|
||||
if ($CliOnlyHiddenImportRoots -contains $rootName) {
|
||||
$RunCliArgs += @("--hidden-import", $nameText)
|
||||
} else {
|
||||
$CommonArgs += @("--hidden-import", $nameText)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$RunCliArgs = @()
|
||||
}
|
||||
|
||||
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")
|
||||
python -m PyInstaller @CommonArgs @RunCliArgs --name run_cli --console (Join-Path $BuildSourceRoot "bin\run_cli.py")
|
||||
|
||||
foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) {
|
||||
$srcDir = Join-Path $DistRoot $name
|
||||
@@ -60,7 +101,7 @@ foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) {
|
||||
$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
|
||||
Get-ChildItem -LiteralPath $srcInternal -Force | Copy-Item -Destination $dstInternal -Recurse -Force
|
||||
}
|
||||
Remove-Item -LiteralPath $srcDir -Recurse -Force
|
||||
}
|
||||
@@ -103,6 +144,19 @@ if ($PackExe) {
|
||||
}
|
||||
|
||||
python -m tools.distribution_manifest $DistRoot
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Distribution manifest check failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
|
||||
python -m tools.exe_packing $DistRoot --smoke-only
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Executable smoke check failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
|
||||
python -m tools.distribution_manifest $DistRoot
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Post-smoke distribution manifest check failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
|
||||
Write-Host "[OK] Portable package: $DistRoot"
|
||||
Write-Host "[NEXT] If Inno Setup is installed: iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=$Version"
|
||||
@@ -35,7 +35,28 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
|
||||
|
||||
|
||||
def test_distribution_manifest_allows_expected_runtime_shape():
|
||||
from tools.distribution_manifest import find_forbidden_distribution_entries
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
entries = [
|
||||
"DouyinGuajiGUI.exe",
|
||||
"web_gui.exe",
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"assets/fudai_task_count_v2_one_task.png",
|
||||
"webui/index.html",
|
||||
"config/README.md",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
"license.dat",
|
||||
]
|
||||
|
||||
assert find_distribution_issues(entries) == []
|
||||
|
||||
|
||||
def test_distribution_manifest_requires_python_runtime_dll():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
entries = [
|
||||
"DouyinGuajiGUI.exe",
|
||||
@@ -48,10 +69,11 @@ def test_distribution_manifest_allows_expected_runtime_shape():
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
"license.dat",
|
||||
]
|
||||
|
||||
assert find_forbidden_distribution_entries(entries) == []
|
||||
issues = find_distribution_issues(entries)
|
||||
|
||||
assert "_internal/python*.dll" in issues
|
||||
|
||||
|
||||
def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
|
||||
@@ -61,6 +83,7 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
|
||||
"web_gui.exe",
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"assets/fudai_task_count_v2_one_task.png",
|
||||
"webui/index.html",
|
||||
"config/README.md",
|
||||
|
||||
@@ -65,21 +65,43 @@ def test_smoke_check_packed_exes_runs_after_packing(tmp_path):
|
||||
_write_exe(dist / name)
|
||||
calls: list[list[str]] = []
|
||||
|
||||
def fake_runner(cmd, *, capture_output, text, timeout):
|
||||
def fake_runner(cmd, *, capture_output, text, timeout, env):
|
||||
calls.append([str(x) for x in cmd])
|
||||
assert capture_output is True
|
||||
assert text is True
|
||||
assert timeout == 20
|
||||
assert env["DOUYIN_LICENSE_REQUIRED"] == "0"
|
||||
assert env["SKIP_OCR_INIT"] == "1"
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout="ok")
|
||||
|
||||
smoke_check_distribution_exes(dist, runner=fake_runner)
|
||||
|
||||
assert calls == [
|
||||
[str(dist / "run_cli.exe"), "--help"],
|
||||
[str(dist / "web_gui.exe"), "--help"],
|
||||
]
|
||||
|
||||
|
||||
def test_smoke_check_cleans_runtime_logs_it_creates(tmp_path):
|
||||
from tools.exe_packing import smoke_check_distribution_exes
|
||||
|
||||
dist = tmp_path / "dist"
|
||||
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
|
||||
_write_exe(dist / name)
|
||||
(dist / "logs").mkdir(parents=True)
|
||||
(dist / "logs" / ".keep").write_text("", encoding="utf-8")
|
||||
|
||||
def fake_runner(cmd, *, capture_output, text, timeout, env):
|
||||
(dist / "logs" / "unified.log").write_text("smoke log", encoding="utf-8")
|
||||
(dist / "logs" / "error.log").write_text("smoke error", encoding="utf-8")
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout="ok")
|
||||
|
||||
smoke_check_distribution_exes(dist, runner=fake_runner)
|
||||
|
||||
assert (dist / "logs" / ".keep").exists()
|
||||
assert not (dist / "logs" / "unified.log").exists()
|
||||
assert not (dist / "logs" / "error.log").exists()
|
||||
|
||||
|
||||
def test_smoke_check_packed_exes_fails_on_broken_exe(tmp_path):
|
||||
from tools.exe_packing import smoke_check_distribution_exes
|
||||
|
||||
@@ -87,7 +109,7 @@ def test_smoke_check_packed_exes_fails_on_broken_exe(tmp_path):
|
||||
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
|
||||
_write_exe(dist / name)
|
||||
|
||||
def fake_runner(cmd, *, capture_output, text, timeout):
|
||||
def fake_runner(cmd, *, capture_output, text, timeout, env):
|
||||
return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="Failed to load Python DLL")
|
||||
|
||||
with pytest.raises(RuntimeError, match="smoke check failed"):
|
||||
@@ -122,4 +144,27 @@ def test_windows_packaging_script_exposes_pack_exe_switch():
|
||||
assert "[switch]$PackExeForce" in script
|
||||
assert "[string]$UpxDir" in script
|
||||
assert "tools.exe_packing" in script
|
||||
assert "--smoke-only" in script
|
||||
assert "if ($LASTEXITCODE -ne 0)" in script
|
||||
|
||||
|
||||
def test_exe_packing_cli_smoke_only_skips_upx(monkeypatch, tmp_path):
|
||||
from tools import exe_packing
|
||||
|
||||
dist = tmp_path / "dist"
|
||||
for name in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
|
||||
_write_exe(dist / name)
|
||||
called = {"pack": False, "smoke": False}
|
||||
|
||||
def fake_pack(*args, **kwargs):
|
||||
called["pack"] = True
|
||||
return []
|
||||
|
||||
def fake_smoke(*args, **kwargs):
|
||||
called["smoke"] = True
|
||||
|
||||
monkeypatch.setattr(exe_packing, "pack_distribution_exes", fake_pack)
|
||||
monkeypatch.setattr(exe_packing, "smoke_check_distribution_exes", fake_smoke)
|
||||
|
||||
assert exe_packing.main([str(dist), "--smoke-only"]) == 0
|
||||
assert called == {"pack": False, "smoke": True}
|
||||
@@ -111,11 +111,78 @@ def test_create_pyarmor_staging_moves_flat_entry_script_back_to_bin(tmp_path, mo
|
||||
assert not (staging / "run_cli.py").exists()
|
||||
|
||||
|
||||
def test_collect_runtime_hidden_imports_uses_original_sources(tmp_path):
|
||||
from tools.obfuscation_staging import collect_runtime_hidden_imports
|
||||
|
||||
root = tmp_path / "project"
|
||||
_write(
|
||||
root / "douyin" / "license" / "license_manager.py",
|
||||
"\n".join(
|
||||
[
|
||||
"import json",
|
||||
"import uuid",
|
||||
"from pathlib import Path",
|
||||
"from douyin.core import path_config",
|
||||
"from .public_key import PUBLIC_KEY_PEM",
|
||||
]
|
||||
),
|
||||
)
|
||||
_write(root / "gui" / "web_gui.py", "import secrets\nfrom http.server import ThreadingHTTPServer\n")
|
||||
_write(root / "operations" / "__init__.py")
|
||||
_write(root / "bin" / "run_cli.py", "from douyin.license.license_manager import check_license\n")
|
||||
|
||||
hidden_imports = collect_runtime_hidden_imports(root)
|
||||
|
||||
assert "json" in hidden_imports
|
||||
assert "uuid" in hidden_imports
|
||||
assert "pathlib" in hidden_imports
|
||||
assert "secrets" in hidden_imports
|
||||
assert "http.server" in hidden_imports
|
||||
assert "douyin.core" not in hidden_imports
|
||||
assert "douyin.license.license_manager" not in hidden_imports
|
||||
|
||||
|
||||
def test_collect_runtime_hidden_imports_skips_optional_heavy_modules(tmp_path):
|
||||
from tools.obfuscation_staging import collect_runtime_hidden_imports
|
||||
|
||||
root = tmp_path / "project"
|
||||
_write(
|
||||
root / "operations" / "ocr_operations.py",
|
||||
"import easyocr\nimport torch\nimport pandas\nimport scipy\nimport paddleocr\n",
|
||||
)
|
||||
_write(root / "douyin" / "__init__.py")
|
||||
_write(root / "gui" / "gui_app.py")
|
||||
_write(root / "bin" / "run_cli.py")
|
||||
|
||||
hidden_imports = collect_runtime_hidden_imports(root)
|
||||
|
||||
assert "easyocr" not in hidden_imports
|
||||
assert "torch" not in hidden_imports
|
||||
assert "pandas" not in hidden_imports
|
||||
assert "scipy" not in hidden_imports
|
||||
|
||||
|
||||
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 "--hidden-imports-output $HiddenImportsFile" in script
|
||||
assert "ConvertFrom-Json" in script
|
||||
assert '$CliOnlyHiddenImportRoots = @("cv2", "numpy", "paddleocr", "paddle")' in script
|
||||
assert '$ExcludedOptionalModules = @(' in script
|
||||
assert '"torch"' in script
|
||||
assert '"modelscope"' in script
|
||||
assert "python -m PyInstaller @CommonArgs @RunCliArgs --name run_cli" in script
|
||||
assert "PyArmor obfuscation failed" in script
|
||||
assert "--paths\", $BuildSourceRoot" in script
|
||||
assert '"--collect-submodules", "douyin"' in script
|
||||
assert '"--collect-submodules", "gui"' in script
|
||||
assert '"--collect-submodules", "operations"' in script
|
||||
assert '"--hidden-import", "logging.handlers"' in script
|
||||
assert "tools.exe_packing $DistRoot --smoke-only" in script
|
||||
assert "Executable smoke check failed" in script
|
||||
assert "Post-smoke distribution manifest check failed" in script
|
||||
assert "Get-ChildItem -LiteralPath $srcInternal -Force | Copy-Item" in script
|
||||
assert "Join-Path $BuildSourceRoot \"gui\\gui_app.py\"" in script
|
||||
assert "Join-Path $BuildSourceRoot \"bin\\run_cli.py\"" in script
|
||||
@@ -97,6 +97,26 @@ def find_forbidden_distribution_entries(entries: list[str]) -> list[str]:
|
||||
return [entry for entry in entries if is_forbidden_distribution_entry(entry)]
|
||||
|
||||
|
||||
def find_missing_required_runtime_entries(entries: list[str]) -> list[str]:
|
||||
normalized = [normalize_entry(entry).lower() for entry in entries]
|
||||
missing: list[str] = []
|
||||
for required in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
|
||||
if required.lower() not in normalized:
|
||||
missing.append(required)
|
||||
if not any(entry.startswith("_internal/") and entry.startswith("_internal/python") and entry.endswith(".dll") for entry in normalized):
|
||||
missing.append("_internal/python*.dll")
|
||||
if "_internal/base_library.zip" not in normalized:
|
||||
missing.append("_internal/base_library.zip")
|
||||
return missing
|
||||
|
||||
|
||||
def find_distribution_issues(entries: list[str]) -> list[str]:
|
||||
return [
|
||||
*find_forbidden_distribution_entries(entries),
|
||||
*find_missing_required_runtime_entries(entries),
|
||||
]
|
||||
|
||||
|
||||
def iter_distribution_entries(root: str | os.PathLike[str]) -> list[str]:
|
||||
base = Path(root)
|
||||
entries: list[str] = []
|
||||
@@ -112,7 +132,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
entries = iter_distribution_entries(args.dist_dir)
|
||||
blocked = find_forbidden_distribution_entries(entries)
|
||||
blocked = find_distribution_issues(entries)
|
||||
if blocked:
|
||||
print("[DIST-CHECK] FAIL forbidden entries:")
|
||||
for entry in blocked[:200]:
|
||||
|
||||
+50
-9
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -11,11 +12,38 @@ from typing import Callable, Sequence
|
||||
ROOT_EXES = ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe")
|
||||
SMOKE_COMMANDS = (
|
||||
("run_cli.exe", "--help"),
|
||||
("web_gui.exe", "--help"),
|
||||
)
|
||||
RUNTIME_MUTABLE_DIRS = ("logs", "pic", "state")
|
||||
Runner = Callable[..., subprocess.CompletedProcess]
|
||||
|
||||
|
||||
def _smoke_env() -> dict[str, str]:
|
||||
env = os.environ.copy()
|
||||
env["DOUYIN_LICENSE_REQUIRED"] = "0"
|
||||
env["SKIP_OCR_INIT"] = "1"
|
||||
return env
|
||||
|
||||
|
||||
def _snapshot_runtime_files(root: Path) -> set[Path]:
|
||||
files: set[Path] = set()
|
||||
for name in RUNTIME_MUTABLE_DIRS:
|
||||
runtime_dir = root / name
|
||||
if not runtime_dir.exists():
|
||||
continue
|
||||
files.update(path for path in runtime_dir.rglob("*") if path.is_file())
|
||||
return files
|
||||
|
||||
|
||||
def _cleanup_new_runtime_files(root: Path, before: set[Path]) -> None:
|
||||
for path in sorted(_snapshot_runtime_files(root) - before, reverse=True):
|
||||
if path.name == ".keep":
|
||||
continue
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def resolve_upx(upx_dir: str | None = None) -> str:
|
||||
if upx_dir:
|
||||
candidate = Path(upx_dir) / ("upx.exe" if sys.platform.startswith("win") else "upx")
|
||||
@@ -60,12 +88,16 @@ def smoke_check_distribution_exes(
|
||||
timeout: int = 20,
|
||||
) -> None:
|
||||
root = Path(dist_dir)
|
||||
for exe_name, arg in SMOKE_COMMANDS:
|
||||
exe = root / exe_name
|
||||
proc = runner([str(exe), arg], capture_output=True, text=True, timeout=timeout)
|
||||
if proc.returncode != 0:
|
||||
detail = (proc.stderr or proc.stdout or "").strip().replace("\r", " ").replace("\n", " ")
|
||||
raise RuntimeError(f"smoke check failed for {exe_name}: exit={proc.returncode} {detail}")
|
||||
before = _snapshot_runtime_files(root)
|
||||
try:
|
||||
for exe_name, arg in SMOKE_COMMANDS:
|
||||
exe = root / exe_name
|
||||
proc = runner([str(exe), arg], capture_output=True, text=True, timeout=timeout, env=_smoke_env())
|
||||
if proc.returncode != 0:
|
||||
detail = (proc.stderr or proc.stdout or "").strip().replace("\r", " ").replace("\n", " ")
|
||||
raise RuntimeError(f"smoke check failed for {exe_name}: exit={proc.returncode} {detail}")
|
||||
finally:
|
||||
_cleanup_new_runtime_files(root, before)
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
@@ -74,12 +106,17 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser.add_argument("--upx-dir", default="", help="UPX 所在目录;为空则从 PATH 查找")
|
||||
parser.add_argument("--force", action="store_true", help="强制加壳 GUARD_CF 等 UPX 默认拒绝的 exe")
|
||||
parser.add_argument("--no-smoke", action="store_true", help="跳过加壳后的 exe 启动冒烟检查")
|
||||
parser.add_argument("--smoke-only", action="store_true", help="只运行 exe 启动冒烟检查,不调用 UPX")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
packed = pack_distribution_exes(args.dist_dir, upx_dir=args.upx_dir or None, force=args.force)
|
||||
if not args.no_smoke:
|
||||
packed: list[Path] = []
|
||||
if args.smoke_only:
|
||||
smoke_check_distribution_exes(args.dist_dir)
|
||||
else:
|
||||
packed = pack_distribution_exes(args.dist_dir, upx_dir=args.upx_dir or None, force=args.force)
|
||||
if not args.no_smoke:
|
||||
smoke_check_distribution_exes(args.dist_dir)
|
||||
except FileNotFoundError as exc:
|
||||
print(f"[PACK-EXE] FAIL {exc}. Download UPX and pass -UpxDir <dir>.", file=sys.stderr)
|
||||
return 2
|
||||
@@ -90,6 +127,10 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
print(f"[PACK-EXE] FAIL {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if args.smoke_only:
|
||||
print("[PACK-EXE] PASS smoke_only=1")
|
||||
return 0
|
||||
|
||||
print(f"[PACK-EXE] PASS packed={len(packed)}")
|
||||
for exe in packed:
|
||||
print(f" {exe}")
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import importlib.util
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
@@ -13,6 +16,20 @@ 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",)
|
||||
INTERNAL_IMPORT_TOP_LEVELS = {Path(item).parts[0] for item in RUNTIME_SOURCE_DIRS}
|
||||
OPTIONAL_OR_DEV_HIDDEN_IMPORTS = {
|
||||
"easyocr",
|
||||
"matplotlib",
|
||||
"modelscope",
|
||||
"pandas",
|
||||
"pytest",
|
||||
"scipy",
|
||||
"skimage",
|
||||
"tensorflow",
|
||||
"setuptools",
|
||||
"torch",
|
||||
"torchvision",
|
||||
}
|
||||
|
||||
|
||||
Runner = Callable[..., subprocess.CompletedProcess]
|
||||
@@ -34,6 +51,56 @@ def _iter_files(root: Path) -> list[str]:
|
||||
return sorted(path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file())
|
||||
|
||||
|
||||
def _iter_runtime_python_files(source_root: Path) -> list[Path]:
|
||||
files: list[Path] = []
|
||||
for rel in RUNTIME_SOURCE_DIRS:
|
||||
root = source_root / rel
|
||||
if root.exists():
|
||||
files.extend(path for path in root.rglob("*.py") if path.is_file())
|
||||
for rel in RUNTIME_ENTRY_FILES:
|
||||
path = source_root / rel
|
||||
if path.exists():
|
||||
files.append(path)
|
||||
return sorted(set(files))
|
||||
|
||||
|
||||
def _import_is_available(module_name: str) -> bool:
|
||||
try:
|
||||
return importlib.util.find_spec(module_name) is not None
|
||||
except (ImportError, AttributeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def collect_runtime_hidden_imports(source_root: str | Path) -> list[str]:
|
||||
"""收集混淆后 PyInstaller 静态分析看不到的外部 import。"""
|
||||
root = Path(source_root)
|
||||
imports: set[str] = set()
|
||||
for path in _iter_runtime_python_files(root):
|
||||
try:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
except SyntaxError:
|
||||
continue
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
imports.add(alias.name)
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
if node.level or not node.module:
|
||||
continue
|
||||
imports.add(node.module)
|
||||
|
||||
hidden_imports: list[str] = []
|
||||
for module in imports:
|
||||
top_level = module.split(".", 1)[0]
|
||||
if top_level in INTERNAL_IMPORT_TOP_LEVELS or top_level == "__future__":
|
||||
continue
|
||||
if module in OPTIONAL_OR_DEV_HIDDEN_IMPORTS or top_level in OPTIONAL_OR_DEV_HIDDEN_IMPORTS:
|
||||
continue
|
||||
if _import_is_available(module):
|
||||
hidden_imports.append(module)
|
||||
return sorted(hidden_imports)
|
||||
|
||||
|
||||
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"):
|
||||
@@ -121,12 +188,25 @@ def create_pyarmor_staging(
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="生成 PyInstaller 使用的 PyArmor 混淆源码 staging 目录")
|
||||
parser.add_argument(
|
||||
"--hidden-imports-output",
|
||||
default="",
|
||||
help="可选:把原始运行源码扫描到的外部 hidden-import 写入 JSON 文件",
|
||||
)
|
||||
parser.add_argument("--source-root", default=".", help="项目根目录")
|
||||
parser.add_argument("--staging-root", required=True, help="输出 staging 目录")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
hidden_imports = collect_runtime_hidden_imports(args.source_root) if args.hidden_imports_output else []
|
||||
result = create_pyarmor_staging(args.source_root, args.staging_root)
|
||||
if args.hidden_imports_output:
|
||||
output = Path(args.hidden_imports_output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(
|
||||
json.dumps(hidden_imports, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
except FileNotFoundError:
|
||||
print("[OBFUSCATE] FAIL pyarmor is not installed. Run: python -m pip install pyarmor", file=sys.stderr)
|
||||
return 2
|
||||
@@ -137,7 +217,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
print(f"[OBFUSCATE] FAIL {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"[OBFUSCATE] PASS staging={result.staging_root} runtime={result.runtime_package}")
|
||||
hidden_imports_suffix = f" hidden_imports={len(hidden_imports)}" if args.hidden_imports_output else ""
|
||||
print(f"[OBFUSCATE] PASS staging={result.staging_root} runtime={result.runtime_package}{hidden_imports_suffix}")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user