Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(macos): 随包提供自包含媒体工具与对应源码

Peach local maintenanceea76659455c0
diff --git a/README.en.md b/README.en.md
index 99fbe8999..afb82d4ca 100644
--- a/README.en.md
+++ b/README.en.md
@@ -99,7 +99,7 @@ Test builds are unsigned. If Windows says “Windows protected your PC”, confi
### Build on macOS
-Build a self-contained `.app` and DMG locally on macOS. Running it requires neither Python, a source checkout, nor another computer. See [the macOS build guide](docs/OPERATIONS.md#macos-独立测试包).
+Build a self-contained `.app` and DMG locally on macOS, including FFmpeg, ffprobe, untrunc and cloudflared. Running it requires neither Homebrew, Python, a source checkout, nor another computer. Complete corresponding media tool sources accompany each release. See [the macOS build guide](docs/OPERATIONS.md#macos-独立测试包).
The release workflow generates separate Apple Silicon (`macos-arm64.dmg`) and Intel (`macos-x86_64.dmg`) test packages. Check the actual assets in the [website download section](https://peach.video/#download) for availability. Check your chip in About This Mac, open the matching image, and drag Peach into Applications. Test packages are not notarized; media tools must be installed separately.
diff --git a/README.md b/README.md
index a390516d2..7893cf253 100644
--- a/README.md
+++ b/README.md
@@ -99,7 +99,7 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
### macOS 本机构建
-macOS 可在本机构建独立 `.app` 与 DMG,运行不需要 Python、源码或另一台电脑。构建与安装见 [macOS 独立测试包](docs/OPERATIONS.md#macos-独立测试包)。
+macOS 可在本机构建独立 `.app` 与 DMG,内含 FFmpeg、ffprobe、untrunc 和 cloudflared,安装后不需要 Homebrew、Python、源码或另一台电脑。媒体工具的完整对应源码随同版本制品提供。构建与安装见 [macOS 独立测试包](docs/OPERATIONS.md#macos-独立测试包)。
发版流程分别生成 Apple Silicon(`macos-arm64.dmg`)与 Intel(`macos-x86_64.dmg`)测试包;可下载版本以[官网下载区](https://peach.video/#download)的实际资产为准。在「关于本机」确认芯片,打开对应镜像并将 Peach 拖入「应用程序」。测试包未完成 Apple 公证,媒体工具需另行准备。
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 74cbd2237..21e7fa8bd 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -27,7 +27,17 @@ macOS 安装依赖:`uv sync --locked --python 3.14 --extra macos`。完成后
MACOSX_DEPLOYMENT_TARGET=11.0 uv sync --locked --extra build --extra macos
```
-构建包含 Python、页面、迁移和资源的应用与 DMG:
+先在构建目录安装固定工具链;下面以 Apple Silicon 为例,Intel 将 `arm64` 换成 `x86_64`:
+
+```sh
+./.venv/bin/python -X utf8 scripts/setup_macos_media_tools.py --root "$PWD/build/macos-media-toolchain"
+export PATH="$PWD/build/macos-media-toolchain/env/bin:$PATH"
+./.venv/bin/python -X utf8 scripts/build_macos_media.py --tool ffmpeg --arch arm64 --output build/media-macos/arm64/ffmpeg
+./.venv/bin/python -X utf8 scripts/build_macos_media.py --tool untrunc --arch arm64 --output build/media-macos/arm64/untrunc
+./.venv/bin/python -X utf8 scripts/fetch_cloudflared_macos.py --arch arm64 --destination build/media-macos/arm64/cloudflared
+```
+
+构建包含 Python、页面、迁移、资源和自包含工具的应用与 DMG:
```sh
./.venv/bin/python -X utf8 scripts/build_macos_standalone.py
@@ -35,6 +45,10 @@ MACOSX_DEPLOYMENT_TARGET=11.0 uv sync --locked --extra build --extra macos
产物在 `dist/macos.noindex/<架构>/`,构建副本避开 Spotlight 索引;日常使用只保留 Applications 里的应用,测试结束卸载已挂载的安装镜像。Apple Silicon 使用 `arm64`,Intel 使用 `x86_64`;分别用对应架构的 Python 与依赖构建。`--target-arch` 显式指定目标,解释器架构不匹配会停止,两个包不混合原生扩展,也不直接合并成 universal2。Intel 构建可在 Intel Mac 或 Rosetta 下的 x86_64 Python 环境完成;Rosetta 验收不能代替 Intel 真机和较旧 macOS 的验收。
+随包工具位于 `Contents/MacOS/tools/ffmpeg/bin`、`Contents/MacOS/tools/untrunc`,cloudflared 位于 `Contents/MacOS`。它们不依赖 Homebrew;FFmpeg、x264、dav1d 和修复用 FFmpeg 库静态链接,动态依赖仅允许 macOS 系统库。`scripts/smoke_macos_media.py` 在系统 PATH 下使用合成 H.264/AAC 与 AV1 样片验证工具查找、探测、抽帧、转码、缺 `moov` 修复和完整解码。该修复验收覆盖同编码参照样片,不代表任意损坏媒体都能恢复。
+
+每种架构同时生成 `ffmpeg-macos-<架构>-corresponding-source.zip` 与 `untrunc-macos-<架构>-corresponding-source.zip`,必须与 DMG 同版本发布;归档包含完整上游源码、固定哈希、许可证、构建脚本、配置和环境记录。构建拒绝缺失、哈希不符、架构不符或依赖开发机动态库的工具。cloudflared 固定官方 2026.9.0,归档 SHA-256 采用 GitHub Release 资产 API 的 `digest`,来源登记在 `scripts/cloudflared-macos.json`;发布正文的旧校验值不作为这两个 macOS 归档的锁。
+
源码开发外壳 `build_macos_app.py` 默认输出到 `dist/macos-source.noindex/`,依赖本机 venv 与 LaunchAgent;不要把它当作独立应用安装。
构建脚本读取随包 Mach-O 的系统版本下限,填入 `LSMinimumSystemVersion` 并重新签名。构建解释器也必须支持目标系统;Homebrew Python 可能要求构建机的系统版本。`watchdog` 等本机编译扩展若命中旧缓存,需带部署目标和对应的 `ARCHFLAGS`,通过 `uv sync --locked --extra build --extra macos --no-cache --reinstall-package watchdog --no-binary-package watchdog` 重编,再核对产物报告的 `minimum_macos`。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 7b3f57a45..d9df5ceca 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -79,6 +79,12 @@ JS/TS 文案复用 [Oxc parser](https://oxc.rs/docs/guide/usage/parser),开发
## macOS 独立构建
+macOS 发行包复用 Windows 固定的 FFmpeg 9.0.2、x264、dav1d 1.5.4 和 untrunc `9d86ec9` 源码锁、下载 SHA-256 校验与 `media_tool_bundle.validate`。untrunc 单独静态链接兼容的 FFmpeg 8.1.3;其 [上游 Makefile](https://github.com/anthwlock/untrunc/blob/9d86ec9ef2ffed1bf8131abe80742c0574db52b6/Makefile)提供 macOS 编译依据。头文件用 `-idirafter` 保留 C++ 标准头 `version` 的优先级。FFmpeg/x264 按 GPL-3.0-or-later、dav1d 按 BSD-2-Clause、untrunc 按 GPL-2.0-or-later 分发;完整对应源码归档包含全部上游源码、构建脚本和许可。Peach 仅维护目标架构、静态库组合、清单与拒收判据,不复制 Homebrew dylib。macOS 编译启用 VideoToolbox、AudioToolbox 与 Secure Transport,硬件转码选择仍服从已有产品策略。
+
+编译工具复用 Meson 1.12.1(Apache-2.0)、Ninja 1.13.2(Apache-2.0)、pkgconf 3.0.7.post0(ISC)和 NASM 3.02(BSD-2-Clause),由 `setup_macos_media_tools.py` 安装到构建目录,应用运行无需这些工具。源码提供完整配置,两个架构分别编译;Intel 二进制可在 Rosetta 下验收,但不能视为 Intel 真机测试。对应源码与二进制的体积、架构和系统最低版本由实际产物核对。
+
+cloudflared 采用 [Cloudflare 官方 2026.9.0 发行](https://github.com/cloudflare/cloudflared/releases/tag/2026.9.0)的双架构归档(Apache-2.0);固定资产 SHA-256 读取官方 Release API 的 `digest`,与发布正文中的旧摘要分别核对。Peach 保留下载校验、包内查找、ad-hoc 签名与进程归属,不新增隧道协议。原生验收运行 `--version`,不因此宣称已连通公网隧道。没有新增 Python 应用运行依赖;合成媒体验收与临时目录不接触真实 ledger。
+
Windows、macOS 与 wheel 通过 `bundle_resources.data_files` 共用运行资源清单,amane 桥只收集脚本、依赖清单和锁文件,运行环境仍位于用户数据目录。资源定位复用 `settings_file.PROJECT_ROOT`,覆盖源码、wheel 的 `_resources` 和 PyInstaller 的资源根,不按模块目录深度猜测。打包机制沿用官方 [PyInstaller 数据文件约定](https://www.pyinstaller.org/en/stable/runtime-information.html)与 setuptools 的资源复制,无新增依赖。
独立应用复用项目已有的 PyInstaller 6.22.3(GPL-2.0-or-later,带发行例外),由 macOS 原生 bootloader 承载 Python 3.14 与 Cocoa 菜单栏,资源与 CLI 入口沿用现有桌面实现。镜像使用系统自带的 `hdiutil`,无需新增运行时依赖。构建与签名依据 [PyInstaller macOS 文档](https://www.pyinstaller.org/en/stable/usage.html)和 [Apple 分发文档](https://developer.apple.com/documentation/xcode/packaging-mac-software-for-distribution)。
diff --git a/scripts/build_macos_media.py b/scripts/build_macos_media.py
new file mode 100644
index 000000000..c7ea315c2
--- /dev/null
+++ b/scripts/build_macos_media.py
@@ -0,0 +1,176 @@
+"""从固定源码编译 macOS 自包含媒体工具,保存完整对应源码。"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import platform
+import shutil
+import subprocess
+import sys
+import zipfile
+
+from fetch_ffmpeg_sources import digest, load_sources, prepare
+from fetch_untrunc_sources import load_sources as untrunc_sources
+
+SCRIPTS = Path(__file__).resolve().parent
+
+
+def run(args, cwd, env):
+ subprocess.run([str(arg) for arg in args], cwd=cwd, env=env, check=True)
+
+
+def audit_binary(path: Path, architecture: str) -> None:
+ """拒绝其他架构及开发机动态库,系统库由 macOS 提供。"""
+ subprocess.run(["lipo", "-verify_arch", architecture, str(path)], check=True)
+ output = subprocess.check_output(["otool", "-L", str(path)], text=True, encoding="utf-8")
+ for line in output.splitlines()[1:]:
+ dependency = line.strip().split(" (", 1)[0]
+ if not dependency.startswith(("/usr/lib/", "/System/Library/")):
+ raise ValueError(f"媒体工具依赖非系统动态库:{dependency}")
+ subprocess.run(["codesign", "--verify", "--strict", str(path)], check=True)
+
+
+def finish(output: Path, lock: dict, tool: str, architecture: str) -> dict:
+ bundle, work = output / tool, output / "work"
+ licenses = [("ffmpeg/COPYING.GPLv3", "LICENSE.txt"),
+ ("x264/COPYING", "LICENSE-x264.txt"),
+ ("dav1d/COPYING", "LICENSE-dav1d.txt")] if tool == "ffmpeg" else [
+ ("untrunc/COPYING", "LICENSE.txt"),
+ ("ffmpeg/COPYING.LGPLv2.1", "LICENSE-FFmpeg.txt")]
+ for source, target in licenses:
+ shutil.copyfile(work / source, bundle / target)
+ shutil.copyfile(output / "buildconf.txt", bundle / "buildconf.txt")
+ notice = (f"# {tool} macOS {architecture}\n\n"
+ f"按 {lock['license']} 分发;固定来源及 SHA-256 见 manifest.json。\n"
+ "FFmpeg、x264 与 dav1d 使用静态库,系统框架和 C/C++ 运行库由 macOS 提供。\n"
+ if tool == "ffmpeg" else
+ f"# untrunc macOS {architecture}\n\n"
+ "untrunc 按 GPL-2.0-or-later 分发,静态链接固定 FFmpeg 8.1.3 内置库。\n"
+ "C++ 运行库由 macOS 提供;不包含 GUI 或外部编解码库。\n")
+ (bundle / "NOTICE.md").write_text(notice + "完整许可证与可离线重建的对应源码随同版本制品提供。\n", encoding="utf-8")
+ archive = output / f"{tool}-macos-{architecture}-corresponding-source.zip"
+ with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as package:
+ for source in lock["sources"]:
+ path = output / "sources" / source["archive"]
+ if digest(path) != source["sha256"]:
+ raise ValueError(f"源码 SHA-256 不符:{path.name}")
+ package.write(path, f"sources/{path.name}")
+ for name in ("build_macos_media.py", "fetch_ffmpeg_sources.py", "fetch_untrunc_sources.py",
+ "setup_macos_media_tools.py", "ffmpeg-sources.json", "untrunc-sources.json"):
+ package.write(SCRIPTS / name, f"scripts/{name}")
+ for name in ("__init__.py", "user_agent.py"):
+ package.write(SCRIPTS.parent / "src/peach" / name, f"src/peach/{name}")
+ package.write(SCRIPTS.parent / "LICENSE", "licenses/Peach-LICENSE.txt")
+ for path in bundle.glob("LICENSE*"):
+ package.write(path, f"licenses/{path.name}")
+ for name in ("buildconf.txt", "build-environment.txt"):
+ package.write(output / name, name)
+ package.writestr("README.md", f"# macOS {architecture} 对应源码\n\n"
+ "安装 Xcode Command Line Tools、Python 3.14、Meson、Ninja、NASM、pkgconf。\n"
+ "工具链版本见 build-environment.txt。macOS 系统框架由 SDK 提供。\n"
+ "先建立 rebuilt/sources 并复制本包 sources/ 中的全部归档,再执行:\n\n"
+ f"`python3 scripts/build_macos_media.py --tool {tool} --arch {architecture} --output rebuilt`\n\n"
+ "每种架构分别编译;x86_64 可在 Apple Silicon 的 Rosetta 环境执行。\n"
+ "FFmpeg 源码锁与 Windows 共用;nv-codec-headers 仅存档,macOS 不编入 NVIDIA 接口。\n")
+ manifest = {"version": lock["version"], "license": lock["license"],
+ "platform": "darwin", "architecture": architecture,
+ "files": {path.relative_to(bundle).as_posix(): digest(path)
+ for path in sorted(bundle.rglob("*")) if path.is_file() and path.name != "manifest.json"},
+ "sources": lock["sources"],
+ "source_archive": {"name": archive.name, "sha256": digest(archive)}}
+ (bundle / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
+ return manifest
+
+
+def build(output: Path, tool: str, architecture: str) -> None:
+ if sys.platform != "darwin":
+ raise ValueError("必须在 macOS 上编译")
+ output = output.resolve()
+ lock = load_sources() if tool == "ffmpeg" else untrunc_sources()
+ if not (output / "work").exists():
+ prepare(output, lock)
+ else:
+ for source in lock["sources"]:
+ if digest(output / "sources" / source["archive"]) != source["sha256"]:
+ raise ValueError("缓存源码 SHA-256 不符")
+ prefix, work = output / "prefix", output / "work"
+ prefix.mkdir(exist_ok=True)
+ env = {**os.environ, "MACOSX_DEPLOYMENT_TARGET": "11.0", "PKG_CONFIG_PATH": "",
+ "PKG_CONFIG_LIBDIR": str(prefix / "lib/pkgconfig"),
+ "CC": f"clang -arch {architecture}", "CXX": f"clang++ -arch {architecture}"}
+ with (output / "build-environment.txt").open("w") as stream:
+ for args in (["clang", "--version"], ["xcrun", "--show-sdk-version"], ["make", "--version"],
+ ["meson", "--version"], ["ninja", "--version"], ["nasm", "-v"], ["pkg-config", "--version"]):
+ subprocess.run(args, stdout=stream, stderr=stream, check=True)
+ stream.write(f"Python={sys.version}\nBuildHost={platform.machine()}\nTarget={architecture}\n")
+ jobs = str(os.cpu_count() or 2)
+ flags = f"-arch {architecture} -mmacosx-version-min=11.0"
+ if tool == "ffmpeg":
+ cross = output / "dav1d-cross.ini"
+ cpu = "aarch64" if architecture == "arm64" else "x86_64"
+ cross.write_text(f"[binaries]\nc = ['clang', '-arch', '{architecture}']\nar = 'ar'\nstrip = 'strip'\n"
+ f"[host_machine]\nsystem = 'darwin'\ncpu_family = '{cpu}'\ncpu = '{cpu}'\nendian = 'little'\n"
+ "[built-in options]\nc_args = ['-mmacosx-version-min=11.0']\n"
+ "c_link_args = ['-mmacosx-version-min=11.0']\n", encoding="utf-8")
+ if not (work / "dav1d-build").exists():
+ run(["meson", "setup", work / "dav1d-build", work / "dav1d", "--cross-file", cross,
+ "--prefix", prefix, "--libdir", "lib", "--buildtype", "release", "--default-library", "static",
+ "-Denable_tools=false", "-Denable_tests=false"], output, env)
+ run(["meson", "compile", "-C", work / "dav1d-build"], output, env)
+ run(["meson", "install", "-C", work / "dav1d-build"], output, env)
+ run(["./configure", f"--prefix={prefix}", f"--host={cpu}-apple-darwin", "--enable-static", "--disable-cli",
+ "--disable-opencl", "--disable-avs", "--disable-swscale", "--disable-lavf", "--disable-ffms",
+ "--disable-gpac", "--disable-lsmash", f"--extra-cflags={flags}", f"--extra-ldflags={flags}"], work / "x264", env)
+ run(["make", f"-j{jobs}"], work / "x264", env)
+ run(["make", "install"], work / "x264", env)
+ config = ["./configure", "--target-os=darwin", f"--arch={'aarch64' if architecture == 'arm64' else architecture}",
+ "--enable-cross-compile", f"--cc=clang -arch {architecture}", f"--cxx=clang++ -arch {architecture}",
+ "--disable-autodetect", "--disable-shared", "--enable-static", "--disable-debug", "--disable-doc",
+ f"--extra-cflags={flags} -I{prefix}/include", f"--extra-ldflags={flags} -L{prefix}/lib"]
+ if tool == "ffmpeg":
+ config += ["--disable-ffplay", "--enable-gpl", "--enable-version3", "--disable-nonfree", "--enable-libx264",
+ "--enable-libdav1d", "--enable-videotoolbox", "--enable-audiotoolbox", "--enable-securetransport",
+ "--pkg-config=pkg-config", "--pkg-config-flags=--static"]
+ else:
+ config += ["--disable-everything", "--disable-programs", "--disable-network", "--disable-avdevice",
+ "--disable-avfilter", "--disable-swscale", "--disable-swresample", "--enable-protocol=file",
+ "--enable-demuxer=mov", "--enable-decoder=h264,hevc,mpeg4,aac,mp3,alac,amrnb,amrwb,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,mjpeg,prores",
+ "--enable-parser=h264,hevc,aac,mpegaudio"]
+ run(config, work / "ffmpeg", env)
+ run(["make", f"-j{jobs}"], work / "ffmpeg", env)
+ (output / "buildconf.txt").write_text(subprocess.list2cmdline(config) + "\n" +
+ (work / "ffmpeg/ffbuild/config.mak").read_text(), encoding="utf-8")
+ bundle = output / tool
+ bundle.mkdir(exist_ok=True)
+ if tool == "ffmpeg":
+ (bundle / "bin").mkdir(exist_ok=True)
+ for name in ("ffmpeg", "ffprobe"):
+ shutil.copyfile(work / "ffmpeg" / name, bundle / "bin" / name)
+ binaries = list((bundle / "bin").iterdir())
+ else:
+ cxxflags = f"-O3 -std=c++17 -D_FILE_OFFSET_BITS=64 {flags} -idirafter {work}/ffmpeg"
+ ldflags = f"{flags} -L{work}/ffmpeg/libavformat -lavformat -L{work}/ffmpeg/libavcodec -lavcodec -L{work}/ffmpeg/libavutil -lavutil -lz -lbz2 -liconv -lm -framework CoreFoundation -framework Security -framework VideoToolbox -framework CoreMedia -framework CoreVideo"
+ command = ["make", f"-j{jobs}", "FF_VER=shared", "IS_RELEASE=1", "EXE=untrunc", "CXX=clang++",
+ f"CXXFLAGS={cxxflags}", f"VER={lock['version']}", f"LDFLAGS={ldflags}"]
+ run(command, work / "untrunc", env)
+ with (output / "buildconf.txt").open("a") as stream:
+ stream.write(subprocess.list2cmdline(command) + "\n")
+ shutil.copyfile(work / "untrunc/untrunc", bundle / "untrunc")
+ binaries = [bundle / "untrunc"]
+ for path in binaries:
+ path.chmod(0o755)
+ run(["strip", "-x", path], output, env)
+ run(["codesign", "--force", "--sign", "-", path], output, env)
+ audit_binary(path, architecture)
+ finish(output, lock, tool, architecture)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--tool", choices=("ffmpeg", "untrunc"), required=True)
+ parser.add_argument("--arch", choices=("arm64", "x86_64"), required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ build(args.output, args.tool, args.arch)
diff --git a/scripts/build_macos_standalone.py b/scripts/build_macos_standalone.py
index 493bef8ec..b785913d5 100644
--- a/scripts/build_macos_standalone.py
+++ b/scripts/build_macos_standalone.py
@@ -79,6 +79,19 @@ def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None
if architecture not in {"arm64", "x86_64"} or architecture != platform.machine():
raise SystemExit("目标架构必须与当前 Python 一致;请使用 arm64 或 x86_64 Python 及对应依赖构建")
from build_macos_app import build_frontend_bundles
+ from media_tool_bundle import validate
+ from build_macos_media import audit_binary
+ from fetch_cloudflared_macos import validate as validate_cloudflared
+
+ media_root = ROOT / "build/media-macos" / architecture
+ sources = []
+ for tool in ("ffmpeg", "untrunc"):
+ _manifest, archive = validate(media_root / tool / tool, tool, architecture=architecture)
+ sources.append(archive)
+ for name in (("bin/ffmpeg", "bin/ffprobe") if tool == "ffmpeg" else ("untrunc",)):
+ audit_binary(media_root / tool / tool / name, architecture)
+ cloudflared = media_root / "cloudflared"
+ validate_cloudflared(cloudflared, architecture)
build_frontend_bundles()
destination = destination.resolve()
@@ -101,6 +114,17 @@ def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None
], check=True, cwd=ROOT, env={**os.environ, "PEACH_MACOS_BUILD_INFO": str(work / "build-info.json"),
"PEACH_MACOS_TARGET_ARCH": architecture})
app = destination / "Peach.app"
+ tools = app / "Contents/MacOS/tools"
+ tools.mkdir()
+ for tool in ("ffmpeg", "untrunc"):
+ shutil.copytree(media_root / tool / tool, tools / tool)
+ shutil.copyfile(cloudflared / "cloudflared", app / "Contents/MacOS/cloudflared")
+ (app / "Contents/MacOS/cloudflared").chmod(0o755)
+ for name in ("LICENSE-cloudflared.txt", "NOTICE-cloudflared.md"):
+ shutil.copyfile(cloudflared / name, app / "Contents/Resources" / name)
+ shutil.copyfile(cloudflared / "manifest.json", app / "Contents/Resources/cloudflared-manifest.json")
+ for archive in sources:
+ shutil.copyfile(archive, destination / archive.name)
minimum = minimum_system_version(app)
info_path = app / "Contents" / "Info.plist"
info = plistlib.loads(info_path.read_bytes())
diff --git a/scripts/ci_macos.sh b/scripts/ci_macos.sh
index 4fd817ae9..592bb6b04 100644
--- a/scripts/ci_macos.sh
+++ b/scripts/ci_macos.sh
@@ -84,6 +84,14 @@ uv sync --locked --all-extras --python "$python" --no-cache \
--reinstall-package zeroconf --no-binary-package zeroconf
uv pip check --python "$python"
output="${PEACH_MACOS_OUTPUT_DIR:-$root/dist/macos.noindex/$architecture}"
+"$python" scripts/setup_macos_media_tools.py --root "$root/build/macos-media-toolchain"
+export PATH="$root/build/macos-media-toolchain/env/bin:$PATH"
+for tool in ffmpeg untrunc; do
+ "$python" scripts/build_macos_media.py --tool "$tool" --arch "$architecture" \
+ --output "$root/build/media-macos/$architecture/$tool"
+done
+"$python" scripts/fetch_cloudflared_macos.py --arch "$architecture" \
+ --destination "$root/build/media-macos/$architecture/cloudflared"
"$python" scripts/build_macos_standalone.py --target-arch "$architecture" --destination "$output"
"$python" -c 'import json,subprocess,sys; from pathlib import Path; info=json.loads(Path("build/macos-standalone",sys.argv[1],"build-info.json").read_text()); head=subprocess.check_output(["git","rev-parse","HEAD"],text=True).strip(); assert info["commit"]==head and not info["dirty"], info' "$architecture"
cp "build/macos-standalone/$architecture/build-info.json" "$output/build-info.json"
@@ -110,5 +118,6 @@ test -s "$mountpoint/Peach.app/Contents/Resources/LICENSE"
codesign --verify --deep --strict "$mountpoint/Peach.app"
lipo -verify_arch "$architecture" "$mountpoint/Peach.app/Contents/MacOS/Peach"
"$python" scripts/smoke_macos.py "$mountpoint/Peach.app"
-(cd "$output"; shasum -a 256 "${image##*/}" > SHA256SUMS.txt)
+"$python" scripts/smoke_macos_media.py "$mountpoint/Peach.app" --arch "$architecture"
+(cd "$output"; shasum -a 256 "${image##*/}" *-corresponding-source.zip > SHA256SUMS.txt)
printf 'macOS %s 安装镜像验收通过:%s\n' "$architecture" "$image"
diff --git a/scripts/ci_r2_artifacts.py b/scripts/ci_r2_artifacts.py
index f881bad42..5071a4aef 100644
--- a/scripts/ci_r2_artifacts.py
+++ b/scripts/ci_r2_artifacts.py
@@ -52,7 +52,8 @@ def allowed_path(name: str, group: str) -> bool:
return False
if group == "macos-release":
return (len(parts) == 4 and "/".join(parts[:3]) in GROUPS[group]
- and (parts[-1] in {"build-info.json", "SHA256SUMS.txt"} or parts[-1].endswith(".dmg")))
+ and (parts[-1] in {"build-info.json", "SHA256SUMS.txt"} or parts[-1].endswith(".dmg")
+ or bool(re.fullmatch(r"(?:ffmpeg|untrunc)-macos-(?:arm64|x86_64)-corresponding-source.zip", parts[-1]))))
if group == "windows-release":
return len(parts) == 2 and parts[0] == "release" and (
bool(re.fullmatch(r"Peach-[0-9]+\.[0-9]+\.[0-9]+-windows-x64[-A-Za-z0-9.]*\.(zip|exe)", parts[-1]))
diff --git a/scripts/cloudflared-macos.json b/scripts/cloudflared-macos.json
new file mode 100644
index 000000000..df1576004
--- /dev/null
+++ b/scripts/cloudflared-macos.json
@@ -0,0 +1,16 @@
+{
+ "version": "2026.9.0",
+ "license": "Apache-2.0",
+ "digest_source": "https://api.github.com/repos/cloudflare/cloudflared/releases/tags/2026.9.0",
+ "license_url": "https://raw.githubusercontent.com/cloudflare/cloudflared/2026.9.0/LICENSE",
+ "assets": {
+ "arm64": {
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.9.0/cloudflared-darwin-arm64.tgz",
+ "sha256": "c0eccb3758420d1f4e46cbf2b8ecde01d9802a154232a817f25133340009fcc7"
+ },
+ "x86_64": {
+ "url": "https://github.com/cloudflare/cloudflared/releases/download/2026.9.0/cloudflared-darwin-amd64.tgz",
+ "sha256": "8f2ecf41776d942bcc8070a56e7bafa4c5de70a1d1781110e2eb3774cca512a8"
+ }
+ }
+}
diff --git a/scripts/fetch_cloudflared_macos.py b/scripts/fetch_cloudflared_macos.py
new file mode 100644
index 000000000..d350ca034
--- /dev/null
+++ b/scripts/fetch_cloudflared_macos.py
@@ -0,0 +1,69 @@
+"""获取固定官方 macOS cloudflared,校验归档并保留许可证。"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import subprocess
+import tarfile
+import urllib.request
+
+from fetch_ffmpeg_sources import digest, download_source
+from build_macos_media import audit_binary
+
+
+def fetch(destination: Path, architecture: str) -> Path:
+ lock = json.loads(Path(__file__).with_name("cloudflared-macos.json").read_text())
+ source = lock["assets"][architecture]
+ destination.mkdir(parents=True, exist_ok=True)
+ archive = destination / "cloudflared.tgz"
+ download_source({**source, "name": "cloudflared"}, archive)
+ with tarfile.open(archive) as package:
+ members = [member for member in package if member.isfile() and member.name.removeprefix("./") == "cloudflared"]
+ if len(members) != 1 or members[0].size > 150_000_000:
+ raise ValueError("cloudflared 官方归档内容不符")
+ binary = destination / "cloudflared"
+ with package.extractfile(members[0]) as stream:
+ binary.write_bytes(stream.read())
+ binary.chmod(0o755)
+ subprocess.run(["codesign", "--force", "--sign", "-", str(binary)], check=True)
+ audit_binary(binary, architecture)
+ version = subprocess.check_output([str(binary), "--version"], text=True, encoding="utf-8")
+ if lock["version"] not in version:
+ raise ValueError("cloudflared 版本不符")
+ with urllib.request.urlopen(lock["license_url"], timeout=60) as response:
+ license_text = response.read().decode("utf-8")
+ if "Apache License" not in license_text:
+ raise ValueError("cloudflared 许可证未取得")
+ (destination / "LICENSE-cloudflared.txt").write_text(license_text, encoding="utf-8")
+ (destination / "NOTICE-cloudflared.md").write_text(
+ f"cloudflared {lock['version']},Cloudflare 与贡献者,Apache-2.0。\n"
+ f"官方制品来源与 SHA-256:{json.dumps(source)}\n", encoding="utf-8")
+ (destination / "manifest.json").write_text(json.dumps({
+ "version": lock["version"], "architecture": architecture, "source": source,
+ "files": {name: digest(destination / name) for name in (
+ "cloudflared", "LICENSE-cloudflared.txt", "NOTICE-cloudflared.md")}}, indent=2) + "\n", encoding="utf-8")
+ return binary
+
+
+def validate(destination: Path, architecture: str) -> dict:
+ from media_tool_bundle import checked_file
+ lock = json.loads(Path(__file__).with_name("cloudflared-macos.json").read_text())
+ manifest = json.loads((destination / "manifest.json").read_text())
+ if (manifest["version"] != lock["version"] or manifest["architecture"] != architecture
+ or manifest["source"] != lock["assets"][architecture]
+ or set(manifest["files"]) != {"cloudflared", "LICENSE-cloudflared.txt", "NOTICE-cloudflared.md"}):
+ raise ValueError("cloudflared 清单与固定发行不符")
+ checked_file(destination, "cloudflared.tgz", lock["assets"][architecture]["sha256"])
+ for name, expected in manifest["files"].items():
+ checked_file(destination, name, expected)
+ audit_binary(destination / "cloudflared", architecture)
+ return manifest
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--arch", choices=("arm64", "x86_64"), required=True)
+ parser.add_argument("--destination", type=Path, required=True)
+ args = parser.parse_args()
+ fetch(args.destination.resolve(), args.arch)
diff --git a/scripts/media_tool_bundle.py b/scripts/media_tool_bundle.py
index 750d4a689..0d890a197 100644
--- a/scripts/media_tool_bundle.py
+++ b/scripts/media_tool_bundle.py
@@ -34,10 +34,16 @@ def checked_file(root: Path, name: str, expected: str) -> Path:
return target
-def validate(root: Path, tool: str = "ffmpeg") -> tuple[dict, Path]:
+def validate(root: Path, tool: str = "ffmpeg", *, architecture: str | None = None) -> tuple[dict, Path]:
"""构建和制品验收共用;哈希不匹配时不复制任何文件。"""
manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
required, source_names, license_name = POLICIES[tool]
+ archive_name = f"{tool}-corresponding-source.zip"
+ if architecture is not None:
+ if architecture not in {"arm64", "x86_64"} or manifest.get("platform") != "darwin" or manifest.get("architecture") != architecture:
+ raise ValueError("macOS 媒体工具平台或架构不符")
+ required = {name.removesuffix(".exe") for name in required}
+ archive_name = f"{tool}-macos-{architecture}-corresponding-source.zip"
if manifest.get("license") != license_name or not manifest.get("version"):
raise ValueError("FFmpeg 清单缺少版本或 GPL 许可证声明")
files = manifest.get("files", {})
@@ -56,7 +62,7 @@ def validate(root: Path, tool: str = "ffmpeg") -> tuple[dict, Path]:
or not re.fullmatch(r"[0-9a-f]{64}", source.get("sha256", ""))):
raise ValueError("FFmpeg 源码来源缺少固定版本或哈希")
archive = manifest["source_archive"]
- if archive["name"] != f"{tool}-corresponding-source.zip":
+ if archive["name"] != archive_name:
raise ValueError("媒体工具对应源码归档名称不符")
source_path = checked_file(root.parent, archive["name"], archive["sha256"])
return manifest, source_path
diff --git a/scripts/setup_macos_media_tools.py b/scripts/setup_macos_media_tools.py
new file mode 100644
index 000000000..6f67fe579
--- /dev/null
+++ b/scripts/setup_macos_media_tools.py
@@ -0,0 +1,36 @@
+"""在构建目录安装固定的媒体编译工具,不安装系统运行组件。"""
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+import subprocess
+import sys
+import tarfile
+
+from fetch_ffmpeg_sources import download_source
+
+NASM = {"name": "nasm", "url": "https://www.nasm.us/pub/nasm/releasebuilds/3.02/nasm-3.02.tar.xz",
+ "sha256": "87336eba53b4acfe917424ab5d500d2b0054d9f5148d35c2273ccf2cfb712f0d"}
+
+
+def setup(root: Path) -> None:
+ root.mkdir(parents=True, exist_ok=True)
+ environment = root / "env"
+ subprocess.run(["uv", "venv", "--allow-existing", "--python", sys.executable, str(environment)], check=True)
+ subprocess.run(["uv", "pip", "install", "--python", str(environment / "bin/python"),
+ "meson==1.12.1", "ninja==1.13.2", "pkgconf==3.0.7.post0"], check=True)
+ archive = root / "nasm-3.02.tar.xz"
+ download_source(NASM, archive)
+ source = root / "nasm-3.02"
+ if not source.exists():
+ with tarfile.open(archive) as package:
+ package.extractall(root, filter="data")
+ for command in (["./configure", f"--prefix={environment}"], ["make", "-j8"], ["make", "install"]):
+ subprocess.run(command, cwd=source, check=True)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", required=True, type=Path)
+ args = parser.parse_args()
+ setup(args.root.resolve())
diff --git a/scripts/smoke_macos_media.py b/scripts/smoke_macos_media.py
new file mode 100644
index 000000000..dceac4a41
--- /dev/null
+++ b/scripts/smoke_macos_media.py
@@ -0,0 +1,90 @@
+"""无 Homebrew 路径下验收包内媒体探测、抽帧、转码与缺索引修复。"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+from unittest.mock import patch
+
+from build_macos_media import audit_binary
+from smoke_desktop import assert_av1_decoder
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+from peach.ffmpeg import FFmpegResolver
+from peach.mp4recover import untrunc_path
+from peach.tunnel import resolve_binary
+
+
+def smoke(app: Path, architecture: str) -> dict:
+ executable = app.resolve() / "Contents/MacOS/Peach"
+ env = {key: value for key, value in os.environ.items() if not key.startswith(("PEACH_", "DYLD_"))}
+ env["PATH"] = "/usr/bin:/bin:/usr/sbin:/sbin"
+ with tempfile.TemporaryDirectory(prefix="peach-macos-media-") as directory, \
+ patch.dict(os.environ, env, clear=True), patch.object(sys, "executable", str(executable)), \
+ patch.object(sys, "frozen", True, create=True):
+ root = Path(directory).resolve()
+ resolver = FFmpegResolver(root / "tools/ffmpeg")
+ ffmpeg, ffprobe = resolver.ffmpeg(), resolver.ffprobe()
+ repair, tunnel = untrunc_path(root / "tools"), resolve_binary()
+ assert ffmpeg and ffprobe and repair and tunnel, "未找到包内工具"
+ assert ffmpeg.source == ffprobe.source == "peach-bundled"
+ paths = [ffmpeg.path, ffprobe.path, repair, tunnel]
+ for path in paths:
+ assert path.is_relative_to(executable.parent), path
+ audit_binary(path, architecture)
+ for tool in ("ffmpeg", "untrunc"):
+ bundle = executable.parent / "tools" / tool
+ manifest = json.loads((bundle / "manifest.json").read_text())
+ assert manifest["platform"] == "darwin" and manifest["architecture"] == architecture
+ from media_tool_bundle import checked_file
+ for name, digest in manifest["files"].items():
+ checked_file(bundle, name, digest)
+ def run(args):
+ return subprocess.run([str(arg) for arg in args], cwd=root, env=env, capture_output=True,
+ text=True, encoding="utf-8", timeout=60, check=True)
+ video, converted, image = root / "sample.mp4", root / "converted.mp4", root / "frame.jpg"
+ run([ffmpeg.path, "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=640x360:r=25",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", "2",
+ "-c:v", "libx264", "-bf", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", video])
+ run([ffmpeg.path, "-v", "error", "-i", video, "-vf", "scale=320:-2", "-c:v", "libx264", "-c:a", "aac", converted])
+ run([ffmpeg.path, "-v", "error", "-i", video, "-frames:v", "1", image])
+ assert image.stat().st_size > 1000
+ def probe(path):
+ result = json.loads(run([ffprobe.path, "-v", "error", "-show_streams", "-show_format", "-of", "json", path]).stdout)
+ assert {stream["codec_name"] for stream in result["streams"]} == {"h264", "aac"}
+ assert 1.8 < float(result["format"]["duration"]) < 2.3
+ return result
+ probe(video)
+ probe(converted)
+ assert_av1_decoder(ffmpeg.path, root)
+ payload, offset = video.read_bytes(), 0
+ while offset + 8 <= len(payload):
+ size = int.from_bytes(payload[offset:offset + 4], "big")
+ assert size >= 8
+ if payload[offset + 4:offset + 8] == b"moov":
+ break
+ offset += size
+ assert offset < len(payload)
+ broken, repaired = root / "broken.mp4", root / "repaired.mp4"
+ broken.write_bytes(payload[:offset])
+ run([repair, "-n", "-s", "-dst", repaired, video, broken])
+ probe(repaired)
+ decoded = run([ffmpeg.path, "-v", "error", "-i", repaired, "-f", "null", "-"])
+ assert not decoded.stderr.strip(), decoded.stderr
+ version = run([tunnel, "--version"]).stdout.strip()
+ return {"architecture": architecture, "ok": True, "cloudflared": version,
+ "checks": ["bundled-resolvers", "manifest-hashes", "architecture", "system-libraries-only",
+ "ad-hoc-signatures", "h264-aac-probe", "jpeg-frame", "software-transcode",
+ "av1-software-decode", "missing-moov-repair", "repaired-full-decode", "no-homebrew-path"]}
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("app", type=Path)
+ parser.add_argument("--arch", choices=("arm64", "x86_64"), required=True)
+ args = parser.parse_args()
+ print(json.dumps(smoke(args.app, args.arch)))
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 0889cd002..1bd83649c 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -120,7 +120,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_subprocess_encoding.py", "test_module_layering.py",
"test_copy_final_state.py", "test_demo_dataset.py",
"test_cloudflared_packaging.py", "test_tunnel.py", "test_process_job.py",
- "test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py",
+ "test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py", "test_macos_media.py",
"test_media_tool_import.py", "test_seed_corrections.py"),
# 前端 island 层(ADR-0022)。产物与源码的断言不需要 Node;vitest 那部分在没有
# npm 时自己跳过,所以这个域在任何机器上都能跑,`full` 也就自动包含它。
@@ -149,7 +149,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"packaging": ("test_dependency_policy.py", "test_buildinfo.py", "test_onboarding.py", "test_macos_standalone.py",
"test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py",
"test_cloudflared_packaging.py", "test_desktop_installer.py",
- "test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py"),
+ "test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py", "test_macos_media.py"),
}
SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {
@@ -168,6 +168,11 @@ SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {
# 一个文件可以落到多个域:读它的测试登记在哪个域,改它就得跑到哪个域。
# `tests/test_test_planning.py` 按测试源码里真实读到的路径反查这两张表,漏一条本地就红。
AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
+ "scripts/build_macos_media.py": ("tooling", "packaging"),
+ "scripts/setup_macos_media_tools.py": ("tooling", "packaging"),
+ "scripts/smoke_macos_media.py": ("tooling", "packaging"),
+ "scripts/fetch_cloudflared_macos.py": ("tooling", "packaging"),
+ "scripts/cloudflared-macos.json": ("tooling", "packaging"),
"scripts/fetch_ffmpeg_sources.py": ("tooling", "packaging"),
"scripts/ffmpeg-sources.json": ("tooling", "packaging"),
"scripts/build_ffmpeg_windows.sh": ("tooling", "packaging"),
diff --git a/scripts/version_bump.py b/scripts/version_bump.py
index 1af5e421e..7b93b7312 100644
--- a/scripts/version_bump.py
+++ b/scripts/version_bump.py
@@ -35,6 +35,15 @@ RUNTIME_INPUTS = (
"scripts/cloudflared-windows.json",
"scripts/build_macos_app.py",
"scripts/build_macos_standalone.py",
+ "scripts/build_macos_media.py",
+ "scripts/setup_macos_media_tools.py",
+ "scripts/fetch_cloudflared_macos.py",
+ "scripts/cloudflared-macos.json",
+ "scripts/media_tool_bundle.py",
+ "scripts/fetch_ffmpeg_sources.py",
+ "scripts/fetch_untrunc_sources.py",
+ "scripts/ffmpeg-sources.json",
+ "scripts/untrunc-sources.json",
"scripts/peach_macos.spec",
"scripts/package_windows_release.py",
"scripts/installer/",
diff --git a/tests/test_macos_media.py b/tests/test_macos_media.py
new file mode 100644
index 000000000..8b6204c76
--- /dev/null
+++ b/tests/test_macos_media.py
@@ -0,0 +1,111 @@
+"""macOS 媒体分发的清单、架构及源码校验。"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+from scripts import media_tool_bundle
+
+SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
+
+
+class MacMediaBundleTests(unittest.TestCase):
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name).resolve()
+
+ def fixture(self, tool, architecture="arm64"):
+ root = self.root / tool
+ root.mkdir()
+ required, sources, license_name = media_tool_bundle.POLICIES[tool]
+ for name in required:
+ path = root / name.removesuffix(".exe")
+ path.parent.mkdir(exist_ok=True, parents=True)
+ path.write_bytes(b"fixture")
+ archive = self.root / f"{tool}-macos-{architecture}-corresponding-source.zip"
+ archive.write_bytes(b"source")
+ manifest = {"version": "fixed", "platform": "darwin", "architecture": architecture,
+ "license": license_name,
+ "files": {path.relative_to(root).as_posix(): media_tool_bundle.digest(path)
+ for path in root.rglob("*") if path.is_file()},
+ "sources": [{"name": name, "revision": "fixed", "url": "https://example.org/source",
+ "sha256": "1" * 64} for name in sources],
+ "source_archive": {"name": archive.name, "sha256": media_tool_bundle.digest(archive)}}
+ (root / "manifest.json").write_text(json.dumps(manifest))
+ return root, archive
+
+ def test_both_tools_require_matching_architecture_and_complete_sources(self):
+ for tool in ("ffmpeg", "untrunc"):
+ with self.subTest(tool=tool):
+ root, archive = self.fixture(tool)
+ manifest, source = media_tool_bundle.validate(root, tool, architecture="arm64")
+ self.assertEqual(source, archive)
+ self.assertEqual(manifest["architecture"], "arm64")
+ with self.assertRaisesRegex(ValueError, "架构"):
+ media_tool_bundle.validate(root, tool, architecture="x86_64")
+ with self.assertRaises(ValueError):
+ media_tool_bundle.validate(root, tool)
+ archive.write_bytes(b"modified")
+ with self.assertRaisesRegex(ValueError, "SHA-256"):
+ media_tool_bundle.validate(root, tool, architecture="arm64")
+
+ def test_binary_audit_rejects_non_system_libraries(self):
+ with patch.object(sys, "path", [str(SCRIPTS), *sys.path]):
+ from scripts import build_macos_media
+ for dependency, valid in (("/usr/lib/libSystem.B.dylib", True),
+ ("/System/Library/Frameworks/CoreMedia.framework/Versions/A/CoreMedia", True),
+ ("/opt/homebrew/opt/x264/lib/libx264.dylib", False),
+ ("@rpath/libavcodec.dylib", False)):
+ with self.subTest(dependency=dependency), patch.object(build_macos_media.subprocess, "run"), \
+ patch.object(build_macos_media.subprocess, "check_output",
+ return_value=f"binary:\n\t{dependency} (compatibility version 1.0.0)\n"):
+ if valid:
+ build_macos_media.audit_binary(self.root / "binary", "arm64")
+ else:
+ with self.assertRaisesRegex(ValueError, "非系统"):
+ build_macos_media.audit_binary(self.root / "binary", "arm64")
+
+ def test_cloudflared_validation_checks_archive_and_binary_hashes(self):
+ with patch.object(sys, "path", [str(SCRIPTS), *sys.path]):
+ from scripts import fetch_cloudflared_macos
+ source = {"url": "https://example.org/cloudflared.tgz", "sha256": ""}
+ files = ("cloudflared", "LICENSE-cloudflared.txt", "NOTICE-cloudflared.md")
+ for name in (*files, "cloudflared.tgz"):
+ (self.root / name).write_bytes(b"fixture")
+ source["sha256"] = media_tool_bundle.digest(self.root / "cloudflared.tgz")
+ manifest = {"version": "fixed", "architecture": "arm64", "source": source,
+ "files": {name: media_tool_bundle.digest(self.root / name) for name in files}}
+ (self.root / "manifest.json").write_text(json.dumps(manifest))
+ lock = {"version": "fixed", "assets": {"arm64": source}}
+ load = fetch_cloudflared_macos.json.loads
+ def loads(text):
+ return lock if '"assets"' in text else load(text)
+ with patch.object(fetch_cloudflared_macos.json, "loads", side_effect=loads), \
+ patch.object(fetch_cloudflared_macos, "audit_binary"):
+ self.assertEqual(fetch_cloudflared_macos.validate(self.root, "arm64"), manifest)
+ (self.root / "cloudflared").write_bytes(b"tampered")
+ with self.assertRaisesRegex(ValueError, "SHA-256"):
+ fetch_cloudflared_macos.validate(self.root, "arm64")
+
+ @unittest.skipIf(sys.platform == "win32", "macOS 工具使用 POSIX 文件名")
+ def test_macos_resolvers_find_the_executable_siblings_without_path_tools(self):
+ from peach.ffmpeg import FFmpegResolver
+ from peach.mp4recover import untrunc_path
+ from peach.tunnel import resolve_binary
+ executable = self.root / "Peach.app/Contents/MacOS/Peach"
+ for name in ("tools/ffmpeg/bin/ffmpeg", "tools/ffmpeg/bin/ffprobe", "tools/untrunc/untrunc", "cloudflared"):
+ path = executable.parent / name
+ path.parent.mkdir(exist_ok=True, parents=True)
+ path.write_bytes(b"fixture")
+ with patch.object(sys, "executable", str(executable)), patch.object(sys, "frozen", True, create=True), \
+ patch.dict("os.environ", {"PATH": ""}, clear=True):
+ resolver = FFmpegResolver(self.root / "missing")
+ self.assertEqual(resolver.ffmpeg().source, "peach-bundled")
+ self.assertEqual(resolver.ffprobe().path, executable.parent / "tools/ffmpeg/bin/ffprobe")
+ self.assertEqual(untrunc_path(self.root / "missing"), executable.parent / "tools/untrunc/untrunc")
+ self.assertEqual(resolve_binary(), executable.parent / "cloudflared")