diff --git a/bin/run_cli.py b/bin/run_cli.py index 7a94de2..dc48505 100644 --- a/bin/run_cli.py +++ b/bin/run_cli.py @@ -10,9 +10,10 @@ _BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if _BASE_DIR not in sys.path: sys.path.insert(0, _BASE_DIR) -from douyin.updater.bootstrap import run_startup_update_check_early +if __name__ == "__main__": + from douyin.updater.bootstrap import run_startup_update_check_early -run_startup_update_check_early(app_name="run_cli") + run_startup_update_check_early(app_name="run_cli") # 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用) if os.environ.get("PARAM_TRACK_ALL") == "1": diff --git a/bin/run_cli_entry.py b/bin/run_cli_entry.py new file mode 100644 index 0000000..e71269b --- /dev/null +++ b/bin/run_cli_entry.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import sys +from pathlib import Path + + +_BASE_DIR = Path(__file__).resolve().parent.parent +if str(_BASE_DIR) not in sys.path: + sys.path.insert(0, str(_BASE_DIR)) + +from douyin.updater.bootstrap import run_startup_update_check_early + + +run_startup_update_check_early(app_name="run_cli") + +from bin.run_cli import main # noqa: E402 +from douyin.core.version import print_version_banner # noqa: E402 + + +if __name__ == "__main__": + try: + print_version_banner("run_cli") + except Exception: + pass + raise SystemExit(main(sys.argv[1:])) diff --git a/config/README.md b/config/README.md index 7a94bec..e5f2700 100644 --- a/config/README.md +++ b/config/README.md @@ -14,6 +14,38 @@ - 建议在修改配置前备份原文件 - 配置文件使用 UTF-8 编码 +## 自动更新配置 + +默认建议使用 HTTPS 且安装包与 manifest 同源: + +```json +{ + "auto_update": { + "enabled": true, + "manifest_url": "https://updates.example.com/douyin/update.json", + "fail_closed": true, + "require_sha256": true, + "require_https": true, + "allow_cross_origin": false + } +} +``` + +仅内网临时测试 `http://192.168.x.x/...` 时,才显式放宽: + +```json +{ + "auto_update": { + "enabled": true, + "manifest_url": "http://192.168.10.2:8000/update.json", + "require_https": false, + "allow_cross_origin": true + } +} +``` + +正式分发不要使用 HTTP;`sha256` 只能防安装包下载损坏,不能替代可信 manifest。 + diff --git a/douyin/updater/bootstrap.py b/douyin/updater/bootstrap.py index c0d84ef..00d22d8 100644 --- a/douyin/updater/bootstrap.py +++ b/douyin/updater/bootstrap.py @@ -1,15 +1,93 @@ from __future__ import annotations +import json +import os import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Callable -def run_startup_update_check_early(app_name: str) -> None: +@dataclass(frozen=True) +class BootstrapUpdateSettings: + enabled: bool + manifest_url: str + fail_closed: bool = True + + +def _to_bool(value: object, default: bool = False) -> bool: + if isinstance(value, bool): + return value + if value is None: + return default + text = str(value).strip().lower() + if text in {"1", "true", "yes", "y", "on", "启用", "是"}: + return True + if text in {"0", "false", "no", "n", "off", "禁用", "否"}: + return False + return default + + +def _project_root() -> Path: + if getattr(sys, "frozen", False): + return Path(sys.executable).resolve().parent + return Path(__file__).resolve().parents[2] + + +def load_update_settings() -> BootstrapUpdateSettings: + cfg: dict[str, object] = {} + try: + path = _project_root() / "config" / "config.json" + if path.exists(): + obj = json.loads(path.read_text(encoding="utf-8")) + if isinstance(obj, dict): + cfg = obj + except Exception: + cfg = {} + + raw_section = cfg.get("auto_update") + section = raw_section if isinstance(raw_section, dict) else {} + manifest_url = ( + os.environ.get("DOUYIN_UPDATE_MANIFEST_URL", "") + or str(section.get("manifest_url", "") or "") + or str(cfg.get("update_manifest_url", "") or "") + ).strip() + enabled = _to_bool( + os.environ.get("DOUYIN_AUTO_UPDATE_ENABLED"), + default=_to_bool(section.get("enabled"), False), + ) + if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1": + enabled = False + if not manifest_url: + enabled = False + return BootstrapUpdateSettings( + enabled=enabled, + manifest_url=manifest_url, + fail_closed=_to_bool(section.get("fail_closed"), True), + ) + + +def run_startup_update_check_early( + app_name: str, + *, + update_check: Callable[..., object] | None = None, +) -> None: """Run the updater before importing the heavier app modules.""" try: - from douyin.updater.force_update import run_startup_update_check + if update_check is None: + from douyin.updater.force_update import run_startup_update_check - run_startup_update_check(app_name=app_name) + check = run_startup_update_check + else: + check = update_check + check(app_name=app_name) except SystemExit: raise except Exception as exc: print(f"[更新] {app_name} 早期更新检查异常:{exc}", file=sys.stderr) + try: + settings = load_update_settings() + except Exception: + settings = None + if settings is not None and settings.enabled and settings.fail_closed: + raise SystemExit(3) diff --git a/gui/gui_app.py b/gui/gui_app.py index 694df0f..4aa4d1e 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -8,9 +8,10 @@ _project_root = os.path.dirname(_script_dir) if _project_root not in sys.path: sys.path.insert(0, _project_root) -from douyin.updater.bootstrap import run_startup_update_check_early +if __name__ == "__main__": + from douyin.updater.bootstrap import run_startup_update_check_early -run_startup_update_check_early(app_name="gui_app") + run_startup_update_check_early(app_name="gui_app") # 抽离:ADB/配置/参数结构体到 gui_core.py(便于后续模块化) from gui.gui_core import ( diff --git a/gui/gui_app_entry.py b/gui/gui_app_entry.py new file mode 100644 index 0000000..22ecfdb --- /dev/null +++ b/gui/gui_app_entry.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import sys +from pathlib import Path + + +_BASE_DIR = Path(__file__).resolve().parent.parent +if str(_BASE_DIR) not in sys.path: + sys.path.insert(0, str(_BASE_DIR)) + +from douyin.updater.bootstrap import run_startup_update_check_early + + +run_startup_update_check_early(app_name="gui_app") + +from douyin.core.version import print_version_banner # noqa: E402 +from gui.gui_app import main # noqa: E402 + + +if __name__ == "__main__": + try: + print_version_banner("gui_app") + except Exception: + pass + main() diff --git a/gui/web_gui.py b/gui/web_gui.py index 59cc969..2097f03 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -18,9 +18,10 @@ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if project_root not in sys.path: sys.path.insert(0, project_root) -from douyin.updater.bootstrap import run_startup_update_check_early +if __name__ == "__main__": + from douyin.updater.bootstrap import run_startup_update_check_early -run_startup_update_check_early(app_name="web_gui") + run_startup_update_check_early(app_name="web_gui") from douyin.core import path_config from douyin.license.license_manager import require_license_or_exit diff --git a/gui/web_gui_entry.py b/gui/web_gui_entry.py new file mode 100644 index 0000000..ed1bf63 --- /dev/null +++ b/gui/web_gui_entry.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import sys +from pathlib import Path + + +_BASE_DIR = Path(__file__).resolve().parent.parent +if str(_BASE_DIR) not in sys.path: + sys.path.insert(0, str(_BASE_DIR)) + +from douyin.updater.bootstrap import run_startup_update_check_early + + +run_startup_update_check_early(app_name="web_gui") + +from douyin.core.version import print_version_banner # noqa: E402 +from gui.web_gui import main # noqa: E402 + + +if __name__ == "__main__": + try: + print_version_banner("web_gui") + except Exception: + pass + raise SystemExit(main()) diff --git a/packaging/README.md b/packaging/README.md index 51bbb4f..a3a9560 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -58,7 +58,13 @@ dist\DouyinGuaji-\ - `run_cli.exe`:后台运行入口,桌面 GUI / Web GUI 会调用它 - `assets/`、`webui/`、`config/`:运行所需资源 - `logs/`、`pic/`、`state/`:运行时输出目录 -- `license.dat`:可选授权文件;打包脚本检测到项目根目录存在该文件时会复制进分发目录 +- `license.dat`:默认不随包分发;仅本地测试包需要时才使用 `-IncludeLicense` 显式复制 + +测试包如需临时带入本地 `license.dat`: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -IncludeLicense +``` ## 生成安装包 @@ -77,7 +83,7 @@ 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`。 +- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。 - 目标电脑需要能使用 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 850a305..5f18667 100644 --- a/packaging/pyinstaller/build_windows.ps1 +++ b/packaging/pyinstaller/build_windows.ps1 @@ -4,6 +4,7 @@ param( [switch]$Obfuscate, [switch]$PackExe, [switch]$PackExeForce, + [switch]$IncludeLicense, [string]$UpxDir = "" ) @@ -46,8 +47,6 @@ $CommonArgs = @( "--distpath", $DistRoot, "--workpath", (Join-Path $Root "build\pyinstaller"), "--paths", $BuildSourceRoot, - "--add-data", "assets;assets", - "--add-data", "webui;webui", "--add-data", "config\README.md;config", "--hidden-import", "PIL._tkinter_finder", "--hidden-import", "ttkbootstrap", @@ -91,9 +90,9 @@ if ($Obfuscate -and (Test-Path $HiddenImportsFile)) { $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 @RunCliArgs --name run_cli --console (Join-Path $BuildSourceRoot "bin\run_cli.py") +python -m PyInstaller @CommonArgs --name DouyinGuajiGUI --windowed (Join-Path $BuildSourceRoot "gui\gui_app_entry.py") +python -m PyInstaller @CommonArgs --name web_gui --console (Join-Path $BuildSourceRoot "gui\web_gui_entry.py") +python -m PyInstaller @CommonArgs @RunCliArgs --name run_cli --console (Join-Path $BuildSourceRoot "bin\run_cli_entry.py") foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) { $srcDir = Join-Path $DistRoot $name @@ -107,12 +106,50 @@ foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) { Remove-Item -LiteralPath $srcDir -Recurse -Force } -foreach ($dir in @("assets", "webui")) { - $target = Join-Path $DistRoot $dir - if (Test-Path $target) { - Remove-Item -LiteralPath $target -Recurse -Force +$RuntimeAssets = @( + "coupon.png", + "fav.png", + "fudai.png", + "fudai_icon_countdown_v20260618.png", + "fudai_icon_pending_v20260618.png", + "fudai_icon_purple_left_v20260618.png", + "fudai_icon_red_left_v20260618.png", + "fudai_task_status_dacheng_shape.png", + "like.png", + "x.png", + "xin.png" +) +$AssetsTarget = Join-Path $DistRoot "assets" +if (Test-Path $AssetsTarget) { + Remove-Item -LiteralPath $AssetsTarget -Recurse -Force +} +New-Item -ItemType Directory -Force $AssetsTarget | Out-Null +foreach ($name in $RuntimeAssets) { + $src = Join-Path $Root "assets\$name" + if (-not (Test-Path $src)) { + throw "Missing runtime asset: assets\$name" } - Copy-Item -LiteralPath (Join-Path $Root $dir) -Destination $target -Recurse -Force + Copy-Item -LiteralPath $src -Destination (Join-Path $AssetsTarget $name) -Force +} + +$WebuiTarget = Join-Path $DistRoot "webui" +if (Test-Path $WebuiTarget) { + Remove-Item -LiteralPath $WebuiTarget -Recurse -Force +} +New-Item -ItemType Directory -Force $WebuiTarget | Out-Null +Copy-Item -LiteralPath (Join-Path $Root "webui\index.html") -Destination (Join-Path $WebuiTarget "index.html") -Force +Copy-Item -LiteralPath (Join-Path $Root "webui\styles.css") -Destination (Join-Path $WebuiTarget "styles.css") -Force +Copy-Item -LiteralPath (Join-Path $Root "webui\app.js") -Destination (Join-Path $WebuiTarget "app.js") -Force +foreach ($dir in @("css", "js", "partials")) { + $srcDir = Join-Path $Root "webui\$dir" + if (-not (Test-Path $srcDir)) { + continue + } + $dstDir = Join-Path $WebuiTarget $dir + New-Item -ItemType Directory -Force $dstDir | Out-Null + Get-ChildItem -LiteralPath $srcDir -File | Where-Object { + $_.Name -notlike "README*" + } | Copy-Item -Destination $dstDir -Force } New-Item -ItemType Directory -Force (Join-Path $DistRoot "config") | Out-Null @@ -124,12 +161,10 @@ foreach ($dir in @("logs", "pic", "state")) { } $licensePath = Join-Path $Root "license.dat" -if (Test-Path $licensePath) { +if ($IncludeLicense -and (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 - if ($PackExe) { $PackArgs = @($DistRoot) if ($UpxDir) { @@ -144,7 +179,12 @@ if ($PackExe) { } } -python -m tools.distribution_manifest $DistRoot +$ManifestArgs = @($DistRoot) +if ($IncludeLicense) { + $ManifestArgs += "--allow-license" +} + +python -m tools.distribution_manifest @ManifestArgs if ($LASTEXITCODE -ne 0) { throw "Distribution manifest check failed with exit code $LASTEXITCODE" } @@ -154,7 +194,7 @@ if ($LASTEXITCODE -ne 0) { throw "Executable smoke check failed with exit code $LASTEXITCODE" } -python -m tools.distribution_manifest $DistRoot +python -m tools.distribution_manifest @ManifestArgs if ($LASTEXITCODE -ne 0) { throw "Post-smoke distribution manifest check failed with exit code $LASTEXITCODE" } diff --git a/packaging/update_manifest.example.json b/packaging/update_manifest.example.json index 88223b4..cf01cbb 100644 --- a/packaging/update_manifest.example.json +++ b/packaging/update_manifest.example.json @@ -3,5 +3,6 @@ "url": "https://example.com/downloads/DouyinGuaji-3.3.4-Setup.exe", "sha256": "替换为安装包的 SHA256", "force": true, - "notes": "强制更新说明" + "notes": "强制更新说明", + "client_config_note": "默认要求 manifest 和安装包均为 HTTPS 且同源。仅内网临时测试时,可在客户端 config.auto_update 中显式设置 require_https=false、allow_cross_origin=true。" } diff --git a/tests/test_auto_update.py b/tests/test_auto_update.py index 5453dff..3c395ce 100644 --- a/tests/test_auto_update.py +++ b/tests/test_auto_update.py @@ -286,3 +286,30 @@ def test_startup_update_fail_closed_blocks_old_client(tmp_path, monkeypatch): ) assert exc.value.code == 3 + + +def test_early_bootstrap_fail_closed_blocks_if_updater_crashes(monkeypatch): + from douyin.updater import bootstrap + from douyin.updater.force_update import UpdateSettings + + monkeypatch.setattr( + bootstrap, + "load_update_settings", + lambda: UpdateSettings( + enabled=True, + manifest_url="https://example.test/update.json", + download_dir=Path("updates"), + fail_closed=True, + ), + ) + + def crash(*, app_name: str): + raise RuntimeError("broken updater import") + + with pytest.raises(SystemExit) as exc: + bootstrap.run_startup_update_check_early( + app_name="test_app", + update_check=crash, + ) + + assert exc.value.code == 3 diff --git a/tests/test_distribution_manifest.py b/tests/test_distribution_manifest.py index af1753b..f7a8be9 100644 --- a/tests/test_distribution_manifest.py +++ b/tests/test_distribution_manifest.py @@ -11,11 +11,16 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts(): "DouyinGuajiGUI.exe", "_internal/python310.dll", "assets/fudai_task_count_v2_one_task.png", + "README.md", "douyin/core/douyin_fudai.py", "artifacts/debug.png", "config/config.json", "logs/unified.log", "pic/debug_captures/a.png", + "license.dat", + "assets/README.txt", + "webui/debug.html", + "webui/js/README.md", "DouyinGuajiGUI/_internal/base_library.zip", "_internal/douyin/core/douyin_fudai.py", "_internal/cv2/__init__.py", @@ -28,10 +33,15 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts(): assert "config/config.json" in blocked assert "logs/unified.log" in blocked assert "pic/debug_captures/a.png" in blocked + assert "license.dat" in blocked + assert "README.md" in blocked + assert "assets/README.txt" in blocked + assert "assets/fudai_task_count_v2_one_task.png" in blocked + assert "webui/debug.html" in blocked + assert "webui/js/README.md" 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(): @@ -43,7 +53,31 @@ def test_distribution_manifest_allows_expected_runtime_shape(): "run_cli.exe", "_internal/base_library.zip", "_internal/python312.dll", - "assets/fudai_task_count_v2_one_task.png", + "assets/fudai.png", + "assets/fudai_task_status_dacheng_shape.png", + "assets/fudai_icon_red_left_v20260618.png", + "webui/index.html", + "webui/css/base.css", + "webui/js/api_client.js", + "config/README.md", + "logs/.keep", + "pic/.keep", + "state/.keep", + ] + + assert find_distribution_issues(entries) == [] + + +def test_distribution_manifest_can_allow_license_for_local_test_package(): + 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.png", "webui/index.html", "config/README.md", "logs/.keep", @@ -52,7 +86,8 @@ def test_distribution_manifest_allows_expected_runtime_shape(): "license.dat", ] - assert find_distribution_issues(entries) == [] + assert "license.dat" in find_distribution_issues(entries) + assert find_distribution_issues(entries, allow_license=True) == [] def test_distribution_manifest_requires_python_runtime_dll(): @@ -63,7 +98,7 @@ def test_distribution_manifest_requires_python_runtime_dll(): "web_gui.exe", "run_cli.exe", "_internal/base_library.zip", - "assets/fudai_task_count_v2_one_task.png", + "assets/fudai.png", "webui/index.html", "config/README.md", "logs/.keep", @@ -84,13 +119,15 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path): "run_cli.exe", "_internal/base_library.zip", "_internal/python312.dll", - "assets/fudai_task_count_v2_one_task.png", + "assets/fudai.png", + "assets/fudai_task_status_dacheng_shape.png", + "webui/css/base.css", + "webui/js/api_client.js", "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) diff --git a/tests/test_exe_packing.py b/tests/test_exe_packing.py index bd48cca..21acc8d 100644 --- a/tests/test_exe_packing.py +++ b/tests/test_exe_packing.py @@ -142,6 +142,7 @@ def test_windows_packaging_script_exposes_pack_exe_switch(): assert "[switch]$PackExe" in script assert "[switch]$PackExeForce" in script + assert "[switch]$IncludeLicense" in script assert "[string]$UpxDir" in script assert "tools.exe_packing" in script assert "--smoke-only" in script diff --git a/tests/test_obfuscation_staging.py b/tests/test_obfuscation_staging.py index 92a99b2..ca418e6 100644 --- a/tests/test_obfuscation_staging.py +++ b/tests/test_obfuscation_staging.py @@ -17,11 +17,14 @@ def _make_minimal_project(root: Path) -> None: _write(root / "douyin" / "updater" / "__init__.py") _write(root / "douyin" / "updater" / "force_update.py") _write(root / "gui" / "gui_app.py") + _write(root / "gui" / "gui_app_entry.py") _write(root / "gui" / "web_gui.py") + _write(root / "gui" / "web_gui_entry.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 / "bin" / "run_cli_entry.py") _write(root / "tools" / "license_dev.py", "PRIVATE_KEY = 'must-not-ship'\n") @@ -40,9 +43,12 @@ def test_create_pyarmor_staging_uses_only_runtime_sources(tmp_path, monkeypatch) assert check is True _write(staging / "douyin" / "__init__.py", "# obfuscated\n") _write(staging / "gui" / "gui_app.py", "# obfuscated\n") + _write(staging / "gui" / "gui_app_entry.py", "# obfuscated\n") _write(staging / "gui" / "web_gui.py", "# obfuscated\n") + _write(staging / "gui" / "web_gui_entry.py", "# obfuscated\n") _write(staging / "operations" / "__init__.py", "# obfuscated\n") _write(staging / "bin" / "run_cli.py", "# obfuscated\n") + _write(staging / "bin" / "run_cli_entry.py", "# obfuscated\n") _write(staging / "pyarmor_runtime_000000" / "__init__.py", "# runtime\n") return subprocess.CompletedProcess(cmd, 0) @@ -56,6 +62,7 @@ def test_create_pyarmor_staging_uses_only_runtime_sources(tmp_path, monkeypatch) assert "gui" in command_text assert "operations" in command_text assert "bin/run_cli.py" in command_text + assert "bin/run_cli_entry.py" in command_text assert "tools" not in command_text assert "license_dev.py" not in command_text @@ -66,9 +73,12 @@ def test_validate_pyarmor_staging_requires_runtime_package(tmp_path): staging = tmp_path / "stage" _write(staging / "douyin" / "__init__.py") _write(staging / "gui" / "gui_app.py") + _write(staging / "gui" / "gui_app_entry.py") _write(staging / "gui" / "web_gui.py") + _write(staging / "gui" / "web_gui_entry.py") _write(staging / "operations" / "__init__.py") _write(staging / "bin" / "run_cli.py") + _write(staging / "bin" / "run_cli_entry.py") with pytest.raises(RuntimeError, match="pyarmor_runtime"): validate_pyarmor_staging(staging) @@ -80,9 +90,12 @@ def test_validate_pyarmor_staging_rejects_sensitive_tools(tmp_path): staging = tmp_path / "stage" _write(staging / "douyin" / "__init__.py") _write(staging / "gui" / "gui_app.py") + _write(staging / "gui" / "gui_app_entry.py") _write(staging / "gui" / "web_gui.py") + _write(staging / "gui" / "web_gui_entry.py") _write(staging / "operations" / "__init__.py") _write(staging / "bin" / "run_cli.py") + _write(staging / "bin" / "run_cli_entry.py") _write(staging / "pyarmor_runtime_000000" / "__init__.py") _write(staging / "tools" / "license_dev.py", "PRIVATE_KEY = 'leak'\n") @@ -101,16 +114,21 @@ def test_create_pyarmor_staging_moves_flat_entry_script_back_to_bin(tmp_path, mo def fake_runner(cmd, *, cwd, check): _write(staging / "douyin" / "__init__.py", "# obfuscated\n") _write(staging / "gui" / "gui_app.py", "# obfuscated\n") + _write(staging / "gui" / "gui_app_entry.py", "# obfuscated\n") _write(staging / "gui" / "web_gui.py", "# obfuscated\n") + _write(staging / "gui" / "web_gui_entry.py", "# obfuscated\n") _write(staging / "operations" / "__init__.py", "# obfuscated\n") _write(staging / "run_cli.py", "# flat obfuscated entry\n") + _write(staging / "run_cli_entry.py", "# flat obfuscated entry wrapper\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 (staging / "bin" / "run_cli_entry.py").read_text(encoding="utf-8") == "# flat obfuscated entry wrapper\n" assert not (staging / "run_cli.py").exists() + assert not (staging / "run_cli_entry.py").exists() def test_collect_runtime_hidden_imports_uses_original_sources(tmp_path): @@ -133,6 +151,7 @@ def test_collect_runtime_hidden_imports_uses_original_sources(tmp_path): _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") + _write(root / "bin" / "run_cli_entry.py", "from bin.run_cli import main\n") hidden_imports = collect_runtime_hidden_imports(root) @@ -157,6 +176,7 @@ def test_collect_runtime_hidden_imports_skips_optional_heavy_modules(tmp_path): _write(root / "douyin" / "__init__.py") _write(root / "gui" / "gui_app.py") _write(root / "bin" / "run_cli.py") + _write(root / "bin" / "run_cli_entry.py") hidden_imports = collect_runtime_hidden_imports(root) @@ -188,6 +208,14 @@ def test_windows_packaging_script_exposes_obfuscate_switch(): 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 "[switch]$IncludeLicense" in script + assert '"--add-data", "assets;assets"' not in script + assert '"--add-data", "webui;webui"' not in script + assert "$RuntimeAssets = @(" in script + assert 'assets\$name' in script + assert "$IncludeLicense -and" in script + assert '$ManifestArgs += "--allow-license"' 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 + assert "Join-Path $BuildSourceRoot \"gui\\gui_app_entry.py\"" in script + assert "Join-Path $BuildSourceRoot \"gui\\web_gui_entry.py\"" in script + assert "Join-Path $BuildSourceRoot \"bin\\run_cli_entry.py\"" in script diff --git a/tests/test_startup_update_bootstrap.py b/tests/test_startup_update_bootstrap.py index 85b25b7..b821444 100644 --- a/tests/test_startup_update_bootstrap.py +++ b/tests/test_startup_update_bootstrap.py @@ -1,5 +1,7 @@ from __future__ import annotations +import subprocess +import sys from pathlib import Path @@ -15,25 +17,72 @@ def _assert_bootstrap_before(path: str, *late_markers: str) -> None: assert call_index < text.index(marker) +def _assert_packaging_uses_wrapper(wrapper_path: str, target_script: str) -> None: + script = Path("packaging/pyinstaller/build_windows.ps1").read_text(encoding="utf-8") + assert f'Join-Path $BuildSourceRoot "{wrapper_path}"' in script + assert f'Join-Path $BuildSourceRoot "{target_script}"' not in script + + +def _assert_wrapper_imports_target_after_bootstrap(path: str, target_import: str) -> None: + text = Path(path).read_text(encoding="utf-8") + assert "run_startup_update_check_early(" in text + assert target_import in text + assert text.index("run_startup_update_check_early(") < text.index(target_import) + + +def _assert_source_entry_bootstraps_under_main_guard(path: str, late_marker: str) -> None: + text = Path(path).read_text(encoding="utf-8") + guard_marker = 'if __name__ == "__main__":' + call_marker = "run_startup_update_check_early(" + assert guard_marker in text + assert call_marker in text + assert late_marker in text + assert text.index(guard_marker) < text.index(call_marker) < text.index(late_marker) + + def test_run_cli_runs_update_bootstrap_before_heavy_imports(): _assert_bootstrap_before( + "bin/run_cli_entry.py", + "from bin.run_cli import main", + ) + _assert_wrapper_imports_target_after_bootstrap("bin/run_cli_entry.py", "from bin.run_cli import main") + _assert_source_entry_bootstraps_under_main_guard( "bin/run_cli.py", "from douyin.core.douyin_fudai import fudai_analyse", - "from douyin.license.license_manager import require_license_or_exit", ) + _assert_packaging_uses_wrapper("bin\\run_cli_entry.py", "bin\\run_cli.py") def test_gui_app_runs_update_bootstrap_before_gui_imports(): _assert_bootstrap_before( - "gui/gui_app.py", - "from gui.gui_core import", - "from douyin.license.license_manager import require_license_or_exit", + "gui/gui_app_entry.py", + "from gui.gui_app import main", ) + _assert_wrapper_imports_target_after_bootstrap("gui/gui_app_entry.py", "from gui.gui_app import main") + _assert_source_entry_bootstraps_under_main_guard("gui/gui_app.py", "from gui.gui_core import") + _assert_packaging_uses_wrapper("gui\\gui_app_entry.py", "gui\\gui_app.py") def test_web_gui_runs_update_bootstrap_before_gui_imports(): _assert_bootstrap_before( - "gui/web_gui.py", - "from douyin.core import path_config", - "from douyin.license.license_manager import require_license_or_exit", + "gui/web_gui_entry.py", + "from gui.web_gui import main", ) + _assert_wrapper_imports_target_after_bootstrap("gui/web_gui_entry.py", "from gui.web_gui import main") + _assert_source_entry_bootstraps_under_main_guard("gui/web_gui.py", "from douyin.core import path_config") + _assert_packaging_uses_wrapper("gui\\web_gui_entry.py", "gui\\web_gui.py") + + +def test_run_cli_import_does_not_trigger_startup_update(monkeypatch): + monkeypatch.setenv("DOUYIN_AUTO_UPDATE_ENABLED", "1") + monkeypatch.setenv("DOUYIN_UPDATE_MANIFEST_URL", "http://example.test/update.json") + + proc = subprocess.run( + [sys.executable, "-c", "import bin.run_cli; print('import-ok')"], + capture_output=True, + text=True, + timeout=20, + ) + + assert proc.returncode == 0 + assert "import-ok" in proc.stdout diff --git a/tools/distribution_manifest.py b/tools/distribution_manifest.py index e07b06a..a24b829 100644 --- a/tools/distribution_manifest.py +++ b/tools/distribution_manifest.py @@ -35,13 +35,47 @@ FORBIDDEN_PREFIXES = ( FORBIDDEN_EXACT = { "config/config.json", "douyin_guaji.code-workspace", + "license.dat", "pyproject.toml", "pyrightconfig.json", + "readme.md", "repo-backup.bundle", "requirements.txt", "requirements-minimal.txt", } +ALLOWED_ASSET_FILES = { + "assets/coupon.png", + "assets/fav.png", + "assets/fudai.png", + "assets/fudai_icon_countdown_v20260618.png", + "assets/fudai_icon_pending_v20260618.png", + "assets/fudai_icon_purple_left_v20260618.png", + "assets/fudai_icon_red_left_v20260618.png", + "assets/fudai_task_status_dacheng_shape.png", + "assets/like.png", + "assets/x.png", + "assets/xin.png", +} + +ALLOWED_WEBUI_ROOT_FILES = { + "webui/app.js", + "webui/index.html", + "webui/styles.css", +} + +ALLOWED_WEBUI_DIRS = ( + "webui/css/", + "webui/js/", + "webui/partials/", +) + +ALLOWED_WEBUI_SUFFIXES = { + ".css", + ".html", + ".js", +} + FORBIDDEN_SUFFIXES = ( ".py", ".pyc", @@ -66,9 +100,11 @@ def normalize_entry(entry: str) -> str: return entry.replace("\\", "/").lstrip("./") -def is_forbidden_distribution_entry(entry: str) -> bool: +def is_forbidden_distribution_entry(entry: str, *, allow_license: bool = False) -> bool: norm = normalize_entry(entry) lower = norm.lower() + if lower == "license.dat" and allow_license: + return False if lower.startswith("_internal/"): project_bits = { "_internal/douyin/", @@ -88,13 +124,31 @@ def is_forbidden_distribution_entry(entry: str) -> bool: return lower not in ALLOWED_RUNTIME_PLACEHOLDERS if lower.startswith("pic/"): return lower not in ALLOWED_RUNTIME_PLACEHOLDERS + if lower.startswith("assets/"): + return lower not in ALLOWED_ASSET_FILES + if lower.startswith("webui/"): + if lower in ALLOWED_WEBUI_ROOT_FILES: + return False + if lower.endswith("/readme.md") or lower.endswith("/readme.txt"): + return True + if not any(lower.startswith(prefix) for prefix in ALLOWED_WEBUI_DIRS): + return True + return Path(lower).suffix not in ALLOWED_WEBUI_SUFFIXES 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 find_forbidden_distribution_entries( + entries: list[str], + *, + allow_license: bool = False, +) -> list[str]: + return [ + entry + for entry in entries + if is_forbidden_distribution_entry(entry, allow_license=allow_license) + ] def find_missing_required_runtime_entries(entries: list[str]) -> list[str]: @@ -110,9 +164,13 @@ def find_missing_required_runtime_entries(entries: list[str]) -> list[str]: return missing -def find_distribution_issues(entries: list[str]) -> list[str]: +def find_distribution_issues( + entries: list[str], + *, + allow_license: bool = False, +) -> list[str]: return [ - *find_forbidden_distribution_entries(entries), + *find_forbidden_distribution_entries(entries, allow_license=allow_license), *find_missing_required_runtime_entries(entries), ] @@ -129,10 +187,15 @@ def iter_distribution_entries(root: str | os.PathLike[str]) -> list[str]: def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="检查分发目录是否混入源码/调试产物") parser.add_argument("dist_dir", help="例如 dist/DouyinGuaji-3.3.3") + parser.add_argument( + "--allow-license", + action="store_true", + help="允许测试包包含 license.dat;正式分发不要使用", + ) args = parser.parse_args(argv) entries = iter_distribution_entries(args.dist_dir) - blocked = find_distribution_issues(entries) + blocked = find_distribution_issues(entries, allow_license=args.allow_license) if blocked: print("[DIST-CHECK] FAIL forbidden entries:") for entry in blocked[:200]: diff --git a/tools/obfuscation_staging.py b/tools/obfuscation_staging.py index d820dd5..fec1512 100644 --- a/tools/obfuscation_staging.py +++ b/tools/obfuscation_staging.py @@ -13,7 +13,10 @@ import sys RUNTIME_SOURCE_DIRS = ("douyin", "gui", "operations") -RUNTIME_ENTRY_FILES = ("bin/run_cli.py",) +RUNTIME_ENTRY_FILES = ( + "bin/run_cli.py", + "bin/run_cli_entry.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}