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
@@ -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