Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(updates): macOS 独立包接入 Sparkle 2 应用内更新

longmeidao28e7df34d507
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index a580c4d94..353c4114c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -308,12 +308,13 @@ jobs:
with:
key: ${{ steps.media-identity.outputs.key }}
path: build/media-cache/macos-${{ matrix.arch }}
- - name: 构建或复用媒体工具并取得 cloudflared
+ - name: 构建或复用媒体工具并取得 cloudflared 与 Sparkle
run: |
for tool in ffmpeg untrunc; do
.venv/bin/python scripts/media_build_cache.py macos --tool "$tool" --arch '${{ matrix.arch }}'
done
.venv/bin/python scripts/fetch_cloudflared_macos.py --arch '${{ matrix.arch }}' --destination "build/media-macos/${{ matrix.arch }}/cloudflared"
+ .venv/bin/python scripts/fetch_sparkle_macos.py --destination "build/media-macos/${{ matrix.arch }}/sparkle"
- name: 构建独立应用与拖放安装镜像
run: .venv/bin/python scripts/build_macos_standalone.py --target-arch '${{ matrix.arch }}' --destination release
- name: 上传 macOS 构建的浏览器 source maps
@@ -382,6 +383,8 @@ jobs:
test "$(readlink "$mount/Applications")" = /Applications
test -s "$mount/Peach.app/Contents/Resources/LICENSE"
codesign --verify --deep --strict "$mount/Peach.app"
+ test -f "$mount/Peach.app/Contents/Frameworks/Sparkle.framework/Versions/B/Sparkle"
+ test ! -e "$mount/Peach.app/Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices"
lipo "$mount/Peach.app/Contents/MacOS/Peach" -verify_arch '${{ matrix.arch }}'
python scripts/smoke_macos.py "$mount/Peach.app"
@@ -417,6 +420,70 @@ jobs:
sha256sum ./*.zip ./*-setup.exe ./*.dmg > SHA256SUMS.txt
gh release create "$GITHUB_REF_NAME" ./*.zip ./*-setup.exe ./*.dmg SHA256SUMS.txt --verify-tag --prerelease --title "Peach ${VERSION#v} · Windows / macOS 测试版" --notes-file RELEASE_NOTES.md
+ # Sparkle 更新源(ADR-0130):Release 公开之后才写 appcast,下载地址指向同一 Release 的 DMG。
+ # 私钥只在这一个仅标签运行的作业里经标准输入交给官方工具;仓库变量未开启时整个作业跳过。
+ sparkle-appcast:
+ name: macOS 更新源(Sparkle appcast)
+ if: github.ref_type == 'tag' && vars.SPARKLE_APPCAST_ENABLED == 'true'
+ needs: release
+ runs-on: macos-15
+ timeout-minutes: 20
+ environment: release
+ permissions:
+ contents: read
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GH_REPO: ${{ github.repository }}
+ SPARKLE_ED_PRIVATE_KEY: ${{ secrets.SPARKLE_ED_PRIVATE_KEY }}
+ PEACH_R2_ACCESS_KEY_ID: ${{ secrets.PEACH_R2_ACCESS_KEY_ID }}
+ PEACH_R2_SECRET_ACCESS_KEY: ${{ secrets.PEACH_R2_SECRET_ACCESS_KEY }}
+ PEACH_R2_ENDPOINT: ${{ secrets.PEACH_R2_ENDPOINT }}
+ PEACH_R2_BUCKET: ${{ vars.PEACH_R2_BUCKET }}
+ PEACH_R2_PUBLIC_BASE: https://downloads.peach.video
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.14'
+ - uses: astral-sh/[email protected]
+ with:
+ enable-cache: true
+ cache-dependency-glob: uv.lock
+ - name: 取得官方 Sparkle 工具与 rclone
+ run: |
+ uv sync --locked --python python
+ .venv/bin/python scripts/fetch_sparkle_macos.py --destination build/sparkle --tools
+ .venv/bin/python scripts/fetch_release_tools.py --rclone-only
+ echo "PEACH_RCLONE=$PWD/build/release-tools/rclone" >> "$GITHUB_ENV"
+ - name: 生成、核对并发布两个架构的 appcast
+ run: |
+ set -euo pipefail
+ test -n "$SPARKLE_ED_PRIVATE_KEY"
+ version="${GITHUB_REF_NAME#v}"
+ prefix="https://github.com/$GH_REPO/releases/download/$GITHUB_REF_NAME/"
+ feeds=()
+ for arch in arm64 x86_64; do
+ folder="build/feed/$arch"
+ feed="$folder/macos-$arch.xml"
+ mkdir -p "$folder"
+ gh release download "$GITHUB_REF_NAME" --pattern "Peach-$version-macos-$arch.dmg" --dir "$folder"
+ status="$(curl -sS -o "$feed" -w '%{http_code}' "$PEACH_R2_PUBLIC_BASE/sparkle/macos-$arch.xml")"
+ case "$status" in
+ 200) ;;
+ 404) rm -f "$feed" ;;
+ *) echo "现有 appcast 未取得:HTTP $status"; exit 1 ;;
+ esac
+ printf '%s' "$SPARKLE_ED_PRIVATE_KEY" | build/sparkle/bin/generate_appcast --ed-key-file - \
+ --download-url-prefix "$prefix" --maximum-versions 5 -o "$feed" "$folder"
+ .venv/bin/python scripts/sparkle_appcast.py annotate --appcast "$feed" --version "$version"
+ signature="$(.venv/bin/python scripts/sparkle_appcast.py verify --appcast "$feed" --version "$version" \
+ --dmg "$folder/Peach-$version-macos-$arch.dmg" --url-prefix "$prefix" | .venv/bin/python -c 'import json,sys; print(json.load(sys.stdin)["signature"])')"
+ printf '%s' "$SPARKLE_ED_PRIVATE_KEY" | build/sparkle/bin/sign_update --ed-key-file - \
+ --verify "$folder/Peach-$version-macos-$arch.dmg" "$signature"
+ feeds+=("$feed")
+ done
+ .venv/bin/python scripts/sparkle_appcast.py publish "${feeds[@]}"
+
# 镜像在演练中构建和验收,标签核对相同 image ID 后发布;发布排在 GitHub Release 成功之后:
# 桌面包任何一步没发出去,Docker Hub 的版本号与 edge 都不动(ADR-0121)。
docker:
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 606261aa3..f0e13e5b6 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -35,6 +35,7 @@ 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
+./.venv/bin/python -X utf8 scripts/fetch_sparkle_macos.py --destination build/media-macos/arm64/sparkle
```
构建包含 Python、页面、迁移、资源和自包含工具的应用与 DMG:
@@ -55,7 +56,7 @@ export PATH="$PWD/build/macos-media-toolchain/env/bin:$PATH"
打开匹配架构的 DMG,把 `Peach.app` 拖入 Applications,再打开应用完成首次设置。菜单栏提供打开页面、重启、查看日志、导出诊断报告、检查更新和退出入口;数据默认保存在 `~/Library/Application Support/Peach/peach-data`,可用 `PEACH_DATA_ROOT` 指定独立目录。
-更新按 macOS 应用的常规做法手动替换:配置页「检查更新」只认本机架构的 DMG,有新版本时给出该 DMG 的下载键,下载后同样拖入 Applications 覆盖旧版本,数据目录与设置保留。macOS 没有应用内安装与自动下载,自动更新只做定期检查。卸载时先在配置页关闭开机自启并退出 Peach,再把应用移到废纸篓;需要完全卸载时,再删除配置页「卸载 Peach」列出的数据目录。
+更新按 macOS 应用的常规做法手动替换:配置页「检查更新」只认本机架构的 DMG,有新版本时给出该 DMG 的下载键,下载后同样拖入 Applications 覆盖旧版本,数据目录与设置保留。未启用下文的 Sparkle 时,macOS 没有应用内安装与自动下载,自动更新只做定期检查。卸载时先在配置页关闭开机自启并退出 Peach,再把应用移到废纸篓;需要完全卸载时,再删除配置页「卸载 Peach」列出的数据目录。
测试包没有公证,从浏览器或聊天软件下载后带有隔离属性,较新的 macOS 会提示「Peach 已损坏,无法打开」,「隐私与安全性」里也不出现「仍要打开」。拖入 Applications 后在终端执行下面的命令,再打开应用:
@@ -101,6 +102,19 @@ launchctl bootout gui/$(id -u)/io.github.longmeidao.peach.tray
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/io.github.longmeidao.peach.tray.plist
```
+### macOS 应用内更新(Sparkle)
+
+应用随包带 [Sparkle 2](https://sparkle-project.org/) 框架(`Contents/Frameworks/Sparkle.framework`,版本与摘要固定在 `scripts/sparkle-macos.json`),取舍见 [ADR-0130](adr/0130-macos-sparkle-in-app-update.md)。`src/peach/sparkle_update.py` 的 `PUBLIC_ED_KEY` 为空时不启用:构建不写 `SUPublicEDKey`,菜单栏「检查更新」沿用上面的版本检查与 DMG 下载。
+
+启用后,菜单栏「版本与更新」>「检查更新」交给 Sparkle:下载本机架构的 DMG、核对 EdDSA 签名,在用户确认后退出 Peach、替换应用并重新打开,替换时移除新应用的隔离标记。设置页的自动更新开关与检查频率同步到 Sparkle 的定时检查;不自动下载安装。安装前先让任务保存进度、停掉 Peach 拉起的服务;本机是账本读取端且新版本带有本机未应用的迁移时不安装,并用通知说明要先在写入端更新。
+
+维护者按下面的顺序启用。生成与保存私钥属于凭据操作,每一步都要单独授权:
+
+1. 用 Sparkle 发布包里的 `generate_keys` 生成密钥对,把公钥写入 `PUBLIC_ED_KEY`;ad-hoc 签名下无法轮换,私钥须离线备份。
+2. 私钥存入 GitHub 仓库 `release` environment 的 secret `SPARKLE_ED_PRIVATE_KEY`,该 environment 只允许 `v*` 标签部署;同一 environment 配好 R2 的 `PEACH_R2_ACCESS_KEY_ID`、`PEACH_R2_SECRET_ACCESS_KEY`、`PEACH_R2_ENDPOINT` 与变量 `PEACH_R2_BUCKET`。
+3. 仓库变量 `SPARKLE_APPCAST_ENABLED` 设为 `true`。之后每个版本标签在 GitHub Release 公开后运行 `sparkle-appcast` 作业:官方 `generate_appcast` 生成两个架构的 appcast,`scripts/sparkle_appcast.py` 补写迁移号并核对版本、下载地址与大小,官方 `sign_update --verify` 核对签名,最后上传到 `https://downloads.peach.video/sparkle/macos-<架构>.xml`。
+4. 第一个带公钥的版本须手动安装一次;之后的版本才能经 Sparkle 更新。上线前在真机按 ADR-0130「未取得的证据」逐项验收。
+
### GitLab 发布与下载后端
GitLab 兼容平台使用 `.gitlab-ci.yml`。唯一版本入口支持 `--gitlab-host` 指定主机,默认入口使用 GitHub。主线发布判据要求同一提交最新的 push 流水线成功,且 Linux、Windows、macOS 和 wheel 验收任务全部成功;缺少原生系统任务时拒绝打标签。主线上的三个平台验收只跑改动域与平台敏感用例([ADR-0119](adr/0119-mainline-changed-scope-release-full-suite.md))。版本提交 `chore(release): 版本 X` 的主线流水线同时是发布演练:三平台全量、媒体工具、Windows 与 macOS 构建、Windows 冒烟和 Docker 镜像都跑一遍,只是不发布。`--ship` 等演练全部成功才打标签;标签流水线核对同一提交的演练已通过,只重新构建并发布([ADR-0121](adr/0121-release-rehearsal-and-atomic-publication.md))。GitHub 的 `release.yml` 用同一套判据,迁回 GitHub 时不用改流程。CLI 传输复用官方 glab,不在仓库或命令参数里存访问令牌。
@@ -147,7 +161,7 @@ Mac 与 Windows 托盘的首层只显示简短状态与提醒数量,展开状
单机设置默认关闭账本复制,不需要 Windows、SMB、LaunchAgent 或系统端口转发。各台电脑各自保存数据;共享馆藏仍按下文的[双机复制](#两台电脑之间的复制)配置,离线修改不能自动合并。已有数据目录不会自动导入。
-这条构建路径使用本地 ad-hoc 签名,未完成 Developer ID 签名和 Apple 公证,不作为已签名发行包发布。DMG 只分发应用,不安装系统服务;需要集中部署系统组件时再评估 PKG。独立包内含媒体工具与 cloudflared,工具位置与验证见「macOS 独立测试包」;源码开发外壳使用本机环境。macOS 在线更新安装器不包含在本测试包中。
+这条构建路径使用本地 ad-hoc 签名,未完成 Developer ID 签名和 Apple 公证,不作为已签名发行包发布。DMG 只分发应用,不安装系统服务;需要集中部署系统组件时再评估 PKG。独立包内含媒体工具与 cloudflared,工具位置与验证见「macOS 独立测试包」;源码开发外壳使用本机环境。应用内更新由随包的 Sparkle 完成,启用条件见「macOS 应用内更新(Sparkle)」。
## 首次运行与设置文件
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 8fc71cf5f..a89aa47bf 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -958,7 +958,8 @@ A 盘垃圾隔离使用短名称 `peach-purge-<32 位 UUID>.peach-quarantine`,
| 生成产物跨机同步 | Syncthing 2.1.x,Windows send-only → Mac receive-only | 目录划分、忽略规则、方向固定与「Mac 不发布正式产物」的边界 |
| Windows 托盘 | pystray 0.19.5(LGPLv3)、Pillow、Win32 Per-Monitor V2 DPI | Peach 服务归属、后台更新检查、菜单动作、品牌图标 |
| Windows 托盘恢复 | Windows 自带 `OpenProcess`、`GetProcessTimes`、[`WaitForSingleObject`](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)、`GetExitCodeProcess`;Python 3.12+ 标准库 `ctypes` / `subprocess`,无新增依赖或分发体积 | `tray_lifecycle` 保留明确退出意图、创建时间校验、3 次 / 5 分钟预算与重启交接。pystray 0.19.5 的 `_message_handlers` 接收 `WM_STOP` / `WM_ENDSESSION`,已核对安装包源码;Windows 临时进程实验证明强制退出能恢复,明确退出不会恢复。原生 API 随受支持的 Windows 维护;pystray 使用项目固定版本。不采用 Task Scheduler `RestartOnFailure`:它只管理任务启动的实例,桌面快捷方式与现有重启脚本不归其管理;不新增 psutil 运行时依赖,进程句柄已覆盖等待与退出码。已知边界是监视器随整棵进程树被终止时不能恢复。 |
-| macOS 菜单栏 | `pyobjc-framework-Cocoa==12.2.2`(MIT)提供 AppKit / PyObjCTools / objc | 附件应用策略、18 pt template 图、服务归属与菜单动作 |
+| macOS 菜单栏 | `pyobjc-framework-Cocoa==12.2.2`(MIT)提供 AppKit / Foundation / PyObjCTools / objc | 附件应用策略、18 pt template 图、服务归属与菜单动作 |
+| macOS 应用内更新 | [Sparkle 2.10.1](https://github.com/sparkle-project/Sparkle/releases/tag/2.10.1)(MIT)官方发布包,地址与 SHA-256 固定在 `scripts/sparkle-macos.json`;框架放 `Contents/Frameworks`,由 pyobjc `objc.loadBundle` 加载;appcast 由官方 `generate_appcast` 生成、`sign_update --verify` 核对 | 读取端的迁移拦截、安装前保存任务进度与停服务、设置页偏好映射到定时检查、appcast 的迁移号与发布门槛(`scripts/sparkle_appcast.py`)。非沙盒应用用不到 XPC 服务,取件时删除并按 ad-hoc 由内向外重签;不开 Hardened Runtime。不自写 DMG 下载、挂载与替换,也不在 Linux 上用 Python 重新实现 EdDSA 签名与 appcast 生成:官方工具只需一个仅标签运行的 macOS 作业。取舍与未验证项见 [ADR-0130](adr/0130-macos-sparkle-in-app-update.md) |
| macOS 拖放安装镜像 | [dmgbuild 1.6.7](https://github.com/dmgbuild/dmgbuild)(MIT,Python ≥3.10,macOS)直接写 Finder 元数据;仅安装于 `build` extra。纯 Python wheel 约 35 KB,依赖 `ds-store`、`mac-alias`;固定传递版本见 `uv.lock` | 已读取固定版的文件复制、背景多分辨率合成与图标布局实现;背景渲染复用 resvg-py 0.5.0,无运行时新增依赖。Peach 提供 640×420 拖放布局、双分辨率背景和应用内许可证;[APFS 设置](https://dmgbuild.readthedocs.io/en/latest/settings.html#filesystem)保留签名资源的 Unicode 文件名。单元验证配置与图片尺寸,macOS 原生回归与发布验收实际挂载镜像,检查严格签名、资源字节及软链。磁盘镜像创建依赖 macOS 的 hdiutil;无需 Finder 自动化权限,挂载或文件系统失败会终止构建 |
| 人脸取景 | `opencv-python-headless==5.0.0.93`(Apache-2.0)的 `cv2.FaceDetectorYN` + opencv_zoo 定版模型 `face_detection_yunet_2023mar.onnx`(MIT,opencv_zoo 提交 `48b10fa5`,sha256 `8f2383e4…52fa4`,232 KB,随安装包放 `tools/face-models/`,没带时放 `peach-data/tools/yunet/`,不进 Git);MetaTube SDK `6a5e6128c725187aeaf921d48ed7d9cd9f30671b` 的主脸聚类只作算法参考 | 头像/封面离线脚本共用 `peach.face_detect`(主脸、归一化焦点与 sidecar)。`detect` 按长边 320/640/1280 各检一次、分数取中位数;`main_face` 先筛掉分数落后最好那张 0.1 以上的框,再取最大。不用 Haar 级联(OpenCV 5 wheel 里没有、检出率低)与 Pigo v1.4.6(有无脸误报)。[实测](SOURCING.md#人脸与水印实测) |
| 人脸比对 | 同一 OpenCV 的 `cv2.FaceRecognizerSF` + opencv_zoo 定版模型 `face_recognition_sface_2021dec.onnx`(Apache-2.0,同一提交,sha256 `0ba9fbfa…34e79`,与 LFS 指针的 oid 一致,37 MB,随安装包放 `tools/face-models/`,没带时放 `peach-data/tools/sface/`,不进 Git) | `peach.face_match` 提特征、算余弦,阈值用 SFace 官方的 0.363;补头像后继拿图库候选与单人封面截到的脸比(ADR-0056),小脸先放大再检(ADR-0070)。检脸用 `peach.face_detect`,取模型先认随包那份(`bundled_model`,校验 SHA-256,进程内按文件大小与修改时间缓存结论),再走同一条 `fetch_model`;随包文件由 `scripts/fetch_face_models.py` 取齐并附两个目录的 LICENSE,Docker 镜像用 `ADD --checksum` 取同一组文件。不引 `face_recognition`/dlib(要编译、体积大)与 InsightFace(模型限非商用、需 onnxruntime)。[实测](SOURCING.md#人脸与水印实测) |
diff --git a/docs/adr/0130-macos-sparkle-in-app-update.md b/docs/adr/0130-macos-sparkle-in-app-update.md
index 6bba9968f..ae510bd72 100644
--- a/docs/adr/0130-macos-sparkle-in-app-update.md
+++ b/docs/adr/0130-macos-sparkle-in-app-update.md
@@ -1,20 +1,20 @@
# ADR-0130:macOS 独立包用 Sparkle 2 做应用内更新
-- 状态:提议(草案;未实施,签名私钥未生成)
-- 日期:2026-11-01
-- 关系:补充 [ADR-0012](0012-version-and-update-boundary.md) 的更新边界与 [ADR-0120](0120-standalone-update-client-compatibility.md) 的旧客户端兼容门槛;appcast 的发布位置依赖 [ADR-0127](0127-verified-release-artifact-promotion.md) 的晋级流程。前置改动是 macOS 独立包按本机架构检查 DMG(分支 `agent/claude/cross-platform-parity` 的 `0fd5cf9a0`,撰写时尚未合入)
+- 状态:已采纳;代码已实施,签名公钥未设置前不启用
+- 日期:2026-11-01(2026-11-02 按实施结果修订)
+- 关系:补充 [ADR-0012](0012-version-and-update-boundary.md) 的更新边界与 [ADR-0120](0120-standalone-update-client-compatibility.md) 的旧客户端兼容门槛;appcast 作业排在 [ADR-0127](0127-verified-release-artifact-promotion.md) 晋级发布的 GitHub Release 之后
## 背景
-Windows 独立包由 `standalone_update` 在应用内下载、替换并重启。macOS 独立包是 PyInstaller 打的 `Peach.app`,ad-hoc 签名、未公证,按 arm64 与 x86_64 分别出 DMG。前置改动之后,macOS 只认本机架构的 `Peach-<版本>-macos-<架构>.dmg`,设置页给出下载键,由用户拖入「应用程序」替换,每次替换后还要按 `scripts/MACOS_DOWNLOADS.md` 再跑一次移除隔离标记的命令。
+Windows 独立包由 `standalone_update` 在应用内下载、替换并重启。macOS 独立包是 PyInstaller 打的 `Peach.app`,ad-hoc 签名、未公证,按 arm64 与 x86_64 分别出 DMG。此前 macOS 只认本机架构的 `Peach-<版本>-macos-<架构>.dmg`,设置页给出下载键,由用户拖入「应用程序」替换,每次替换后还要按 `scripts/MACOS_DOWNLOADS.md` 再跑一次移除隔离标记的命令。
-macOS 应用的成熟更新方案是 [Sparkle](https://sparkle-project.org/):appcast 列出版本,EdDSA 签名校验下载内容,独立的 `Autoupdate` 在应用退出后替换并重开。本文评估把 Sparkle 2 接进现有 `Peach.app`,不照搬 Windows 的自写流程。
+macOS 应用的成熟更新方案是 [Sparkle](https://sparkle-project.org/):appcast 列出版本,EdDSA 签名校验下载内容,独立的 `Autoupdate` 在应用退出后替换并重开。本文把 Sparkle 2 接进现有 `Peach.app`,不照搬 Windows 的自写流程。
-结论依据 Sparkle 2.10.1(2026-10-25 发布)的源码与官方发布包。发布包在 Windows 上离线解包并解析 Mach-O 头,没有在 macOS 上运行,未在真机验证的项列在「未取得的证据」。
+结论依据 Sparkle 2.10.1(2026-10-25 发布)的源码与官方发布包。发布包在 Windows 上离线解包并解析 Mach-O 头,没有在 macOS 上运行;未在真机验证的项列在「未取得的证据」。
## 可行性结论
-可行,前提是接受下文三条约束:EdDSA 私钥是 ad-hoc 签名下唯一的信任锚,丢失或更换后已装客户端只能手动重装;第一个带 Sparkle 的版本仍需手动安装一次;macOS 13 起的「应用管理」保护对 ad-hoc 包的实际行为未取得,必须在真机验收后才能发布。
+可行,前提是接受三条约束:EdDSA 私钥是 ad-hoc 签名下唯一的信任锚,丢失或更换后已装客户端只能手动重装;第一个带公钥的版本仍需手动安装一次;macOS 13 起的「应用管理」保护对 ad-hoc 包的实际行为未取得,必须在真机验收后才能启用。
| 问题 | 结论 | 依据 |
| --- | --- | --- |
@@ -24,98 +24,97 @@ macOS 应用的成熟更新方案是 [Sparkle](https://sparkle-project.org/):a
| 应用管理(macOS 13 起) | 未取得。Apple 只说明同一开发团队签名的应用可以互相更新,否则拦截并通知用户;ad-hoc 签名没有 Team ID,文档未说明这类包是否受保护 | WWDC22「What's new in privacy」 |
| 能否轮换 EdDSA 私钥 | 不能。Sparkle 的轮换兜底要求新包满足旧包的 designated requirement,ad-hoc 永远满足不了 | `SUUpdateValidator.m` 第 351 行起 |
| 以后改用 Developer ID | 兼容。Sparkle 只拒绝「已签名改为不签名」,ad-hoc 改为 Developer ID 时只要 EdDSA 私钥不变即可通过 | `SUUpdateValidator.m` 第 282 行 |
+| 没有公钥时启动 | 失败。设置了 `SUVerifyUpdateBeforeExtraction` 却没有 EdDSA 公钥时 `startUpdater:` 返回错误,所以 Peach 自己判断启用条件,不创建更新器 | `SPUUpdater.m` 第 317–365 行 |
| 系统版本下限 | 不变。Sparkle 2.10.0 起要求 macOS 12.0(包内二进制 `minos` 为 12.0);Peach 最近一次成功的发布演练中,两个架构的 `minimum_macos` 已是 15.0 | Sparkle `CHANGELOG` 2.10.0 节;`release.yml` 运行 41107363667(`agent/codex/release-bottlenecks` 分支上的演练,不是标签运行)的构建输出 |
-## 决策(草案)
+## 决策
-### 一、框架放在 `Contents/Frameworks`
+### 一、总闸:`PUBLIC_ED_KEY`
-1. 固定 Sparkle 官方发布包 `Sparkle-2.10.1.tar.xz`(SHA-256 `1a856d2a9edb8e628de88121d7be04cf0e2167f8641650b78fca00b14244cf27`),按 `scripts/fetch_cloudflared_macos.py` 的方式用清单固定版本与摘要,许可证随包放进 `Contents/Resources`。框架 3.0 MB,二进制均为 x86_64 + arm64 双架构。
-2. `scripts/build_macos_standalone.py` 在 PyInstaller 生成 `Peach.app` 之后、`codesign` 之前,把 `Sparkle.framework` 按保留符号链接的方式复制到 `Peach.app/Contents/Frameworks/`。PyInstaller 的 `sys._MEIPASS` 就是这个目录,现有 `amane-runtime` 落在 `Contents/Frameworks/tools/amane-runtime` 可以印证。
-3. 删除框架里的 `XPCServices/`。这两个服务只供沙盒应用使用,官方文档说明非沙盒应用可以移除。
-4. 官方包里的二进制都带签名段,签名者在 Windows 上未取得。按由内向外的顺序用 ad-hoc 重签 `Autoupdate`、`Updater.app` 与框架,再签 `Peach.app`,使整个包只有一种签名身份;现有的 `codesign --verify --deep --strict` 继续把关。不开 Hardened Runtime:开启后库验证会拒绝加载 ad-hoc 签名的框架(官方文档的 Library Validation 说明)。
+`src/peach/sparkle_update.py` 的 `PUBLIC_ED_KEY` 为 None 时整套不启用:构建不写任何 Sparkle 键,菜单栏「检查更新」沿用版本检查与 DMG 下载。运行时 `available()` 要求 macOS 独立包、框架存在、包内 `Info.plist` 有 `SUPublicEDKey`,三者缺一就不创建更新器。框架照常随包,版本提交的发布演练因此在真机 runner 上验证打包与签名,运行时保持不动。
-### 二、菜单栏进程持有更新器
+### 二、框架放在 `Contents/Frameworks`
-`peach serve` 是子进程,Sparkle 必须跑在菜单栏进程的主线程运行循环里。`tray.run_macos_menu_bar` 只在独立包且框架存在时加载:
+1. 官方发布包 `Sparkle-2.10.1.tar.xz` 的地址与 SHA-256 固定在 `scripts/sparkle-macos.json`,由 `scripts/fetch_sparkle_macos.py` 下载、校验并取出框架与许可证。
+2. 取件时删除 `XPCServices/` 及顶层指向它的符号链接:两个服务只供沙盒应用使用,官方文档说明非沙盒应用可以移除。随后按 `Autoupdate`、`Updater.app`、框架的顺序用 ad-hoc 重签;删了嵌套代码就必须重签框架,否则资源清单对不上。不开 Hardened Runtime:开启后库验证会拒绝加载 ad-hoc 签名的框架(官方文档的 Library Validation 说明)。
+3. `scripts/build_macos_standalone.py` 在复制 cloudflared 之后,把框架按保留符号链接的方式复制到 `Peach.app/Contents/Frameworks/`,许可证放 `Contents/Resources/LICENSE-Sparkle.txt`,再走原有的整包签名与 `codesign --verify --deep --strict`。PyInstaller 的 `sys._MEIPASS` 就是这个目录,现有 `amane-runtime` 落在 `Contents/Frameworks/tools/amane-runtime` 可以印证。发布演练的仅下载验收另外核对框架存在、XPC 服务已去掉。
-```python
-objc.loadBundle("Sparkle", namespace, bundle_path=str(Path(sys._MEIPASS) / "Sparkle.framework"))
-controller = SPUStandardUpdaterController.alloc() \
- .initWithStartingUpdater_updaterDelegate_userDriverDelegate_(True, updater_delegate, driver_delegate)
-```
+### 三、`Info.plist` 增加的键
-菜单项「检查更新…」调用 `controller.checkForUpdates_(None)`,替换前置分支里复用版本检查加系统通知的那一项。委托是 `NSObject` 子类,承担 Windows `request_restart` 的同等职责:
+构建脚本在写 `LSMinimumSystemVersion` 时一并写入 `sparkle_update.info_plist_keys(<架构>)`;公钥为 None 时为空:
-| 委托方法 | 职责 |
-| --- | --- |
-| `updater:shouldProceedWithUpdate:updateCheck:error:` | 本机是 ledger 读取端且新版本带有本机账本未应用的迁移时拒绝,提示先在写入端迁移并同步(对应 `standalone_update._update_writer`) |
-| `updater:shouldPostponeRelaunchForUpdate:untilInvokingBlock:` | 先按 `update_tasks.reserve` 保存任务进度,再 `manager.stop_owned()` 释放 80/443 等端口,然后调用传入的 block 继续安装 |
-| `updaterWillRelaunchApplication:` | 兜底再停一次自有服务 |
-| `supportsGentleScheduledUpdateReminders` 及配套方法 | 返回 YES。附件应用不实现时 Sparkle 会记日志警告,定时检查到的更新也不会抢焦点;提醒走现有 `MenuBarApp.notify` |
+| 键 | 值 | 说明 |
+| --- | --- | --- |
+| `SUFeedURL` | `https://downloads.peach.video/sparkle/macos-<架构>.xml` | 每个架构一份 appcast。地址一旦随带公钥的版本发出就要长期可用 |
+| `SUPublicEDKey` | `PUBLIC_ED_KEY` | 仓库里只有一处常量,测试核对格式;更换需要新的 ADR |
+| `SUVerifyUpdateBeforeExtraction` | YES | 2.7.3 起,解包前先验 EdDSA 签名 |
+| `SUEnableAutomaticChecks` | YES | 显式写值,Sparkle 不再在第二次启动时弹窗询问;实际开关由设置页映射 |
+| `SUAllowsAutomaticUpdates` | NO | 自动下载后在退出时安装会绕开安装前的任务保护,第一版只做手动确认安装 |
-新版本的迁移信息写进 appcast 条目的自定义元素(例如 `peach:migrationHead`),委托经 `SUAppcastItem.propertiesDictionary` 读取。Sparkle 解析条目时,非 Sparkle 命名空间的子元素以限定名为键、文本为值存入这个字典(`SUAppcast.m` 第 60–71、205–211 行)。Sparkle 只在 `Autoupdate` 里解包,宿主拿不到解包目录,所以不能像 Windows 那样直接读暂存目录。
+不设置 XPC 相关的开关。`SURequireSignedFeed`(2.9 起)不开:appcast 走 HTTPS,被篡改也只能指向仍须通过 EdDSA 校验的包,且安装器拒绝降级(`SUPlainInstaller.m` 第 325 行起)。之后需要签名 feed 时,新版本加上这个键即可,旧客户端不受影响。`CFBundleVersion` 已等于三段式版本号,Sparkle 的标准比较器可以直接比较。
-Sparkle 由 `Autoupdate` 经 LaunchServices 重开应用,不带 LaunchAgent 的 `--data-root` 参数和环境变量。重开后的进程必须靠数据目录记录(`settings_file.DATA_ROOT_LOCATION`)找到同一个数据根;也不归 launchd 管理,直到下次登录。更新触发的退出必须以 0 退出,避免与「异常退出后由 launchd 拉起」的设置在安装期间抢着启动旧包。
+### 四、菜单栏进程持有更新器
-### 三、`Info.plist` 增加的键
+`peach serve` 是子进程,Sparkle 跑在菜单栏进程的主线程运行循环里。`tray.run_macos_menu_bar` 建好菜单后调用 `sparkle_update.start()`:`objc.loadBundle` 加载框架,创建 `SPUStandardUpdaterController`,委托由 `Updater` 强引用(Sparkle 只弱引用委托)。初始化失败只记日志,菜单栏改用版本检查。
-在 `scripts/peach_macos.spec` 的 `info_plist` 中按构建架构写入:
+菜单「版本与更新」>「检查更新」在启用时调用 `checkForUpdates:`。健康轮询线程每五秒读一次设置页的自动更新偏好,回主线程映射到 `automaticallyChecksForUpdates` 与 `updateCheckInterval`;关闭自动更新即关闭 Sparkle 的定时检查。
-| 键 | 值 | 说明 |
-| --- | --- | --- |
-| `SUFeedURL` | `https://downloads.peach.video/sparkle/macos-<架构>.xml` | 按 `PEACH_MACOS_TARGET_ARCH` 写死,每个架构一份 appcast。地址一旦发出就要长期可用 |
-| `SUPublicEDKey` | 公钥 base64 | 仓库里只有一处常量,由测试锁定;更改需要新的 ADR |
-| `SUVerifyUpdateBeforeExtraction` | YES | 2.7.3 起,解包前先验 EdDSA 签名 |
-| `SUEnableAutomaticChecks` | 显式写值 | 不写时 Sparkle 会在第二次启动时弹窗询问;实际开关由设置页映射到 `SPUUpdater.automaticallyChecksForUpdates` |
-| `SUAllowsAutomaticUpdates` | YES | 设置页的「自动下载」映射到 `automaticallyDownloadsUpdates`,下载后在退出时安装 |
+委托只用不需要 pyobjc 协议元数据的方法:返回对象或无返回值的方法用默认签名,返回 BOOL 的方法逐个声明类型。每个回调都收住 Python 异常,避免变成 ObjC 异常打断 Sparkle。
+
+| 委托方法 | 职责 |
+| --- | --- |
+| `bestValidUpdateInAppcast:forUpdater:` | 本机是 ledger 读取端,且 appcast 里的最高迁移号高于本机账本已应用的迁移时,返回空条目让 Sparkle 按「没有可用更新」收尾,并用通知说明要先在写入端更新(对应 `standalone_update._update_writer`);可以安装时返回 nil,交给 Sparkle 选择 |
+| `updater:willInstallUpdate:` | 按 `update_tasks.reserve` 让任务保存进度、`wait_quiescent` 等在途步骤,再 `manager.stop_owned()` 释放端口。预约绑定菜单栏进程,它退出后自动失效,新版本启动后任务继续;预约失败时仍停服务 |
+| `updaterWillRelaunchApplication:` | 兜底再停一次自有服务 |
+| `supportsGentleScheduledUpdateReminders` 与 `standardUserDriverWillHandleShowingUpdate:forUpdate:state:` | 返回 YES;定时检查到更新时用系统通知提醒一次,附件应用没有窗口可前置 |
+
+不用带 `NSError **` 出参的 `updater:shouldProceedWithUpdate:updateCheck:error:`,也不用带 block 参数的 `updater:shouldPostponeRelaunchForUpdate:untilInvokingBlock:`:两者都要 pyobjc 的签名元数据,在 Windows 上无法核对,失败的后果是端口没释放、新实例起不来。
-不设置 `SUEnableInstallerLauncherService`、`SUEnableDownloaderService` 等 XPC 开关。`SURequireSignedFeed`(2.9 起)第一版不开:appcast 走 HTTPS,被篡改也只能指向仍须通过 EdDSA 校验的包,且安装器拒绝降级(`SUPlainInstaller.m` 第 325 行起)。之后需要签名 feed 时,新版本加上这个键即可,旧客户端不受影响。
+新版本的迁移号写进 appcast 条目的 `peach:migrationHead`。Sparkle 解析条目时,非 Sparkle 命名空间的子元素以限定名为键、文本为值存入 `propertiesDictionary`(`SUAppcast.m` 第 60–71、205–211 行)。Sparkle 只在 `Autoupdate` 里解包,宿主拿不到解包目录,所以不能像 Windows 那样直接读暂存目录。
-`CFBundleVersion` 已等于三段式版本号,Sparkle 的标准比较器可以直接比较。
+Sparkle 由 `Autoupdate` 经 LaunchServices 重开应用,不带 LaunchAgent 的 `--data-root` 参数和环境变量。独立包无参数启动时从默认数据目录读 `state/data-root.txt` 找到首次设置选定的数据根(`settings_file._selected_data_root`)。重开的进程不归 launchd 管理,直到下次登录。更新触发的退出码为 0,菜单栏的 LaunchAgent 写的是 `KeepAlive = {SuccessfulExit = false}`,不会在安装期间拉起旧包。
-### 四、appcast 的生成与位置
+### 五、appcast 的生成与位置
-1. **生成。** 标签流水线新增一个仅在标签上运行的 macOS 作业:取得已晋级的两个 DMG 与当前线上 appcast,用官方 `generate_appcast --ed-key-file - --download-url-prefix https://downloads.peach.video/v<版本>/` 从标准输入读私钥,追加本版本条目;enclosure 地址由前缀加 DMG 文件名组成。工具会挂载 DMG 读取包内 `Info.plist`,自动写出 `sparkle:version`、`sparkle:minimumSystemVersion`、`length` 与 `sparkle:edSignature`。用 `--maximum-versions` 只保留最近几版,不生成增量包。`peach:migrationHead` 由发布脚本在生成后补进本版本条目。公开仓库的 GitHub 托管 macOS runner 不计费。
-2. **架构分开。** 每个架构一份 appcast,地址按构建架构写进 `Info.plist`。在 Apple 芯片上经 Rosetta 运行 x86_64 包时,继续拿到 x86_64 的更新,与 `release_updates.check` 用 `platform.machine()` 选 DMG 的行为一致。不用 2.9 起的 `sparkle:hardwareRequirements`:它只能声明「需要 arm64」,表达不了「只给 x86_64」。
-3. **复用 DMG。** 更新包就是现有 DMG,不新增制品,R2 发布桶的 8 GB 预算不变。DMG 的 SHA-256 与 `SHA256SUMS.txt` 不受影响,EdDSA 签名只写在 appcast 里。
-4. **托管。** feed 地址放在自有域名 `downloads.peach.video`,以后换存储后端不必改已装客户端。appcast 按 `releases.json` 的方式设一分钟缓存,在 DMG 公开并校验之后才上传。enclosure 指向同一 R2 源的 DMG:Sparkle 每个条目只有一个下载地址,没有备用源。
-5. **R2 现状。** 撰写时 `downloads.peach.video/releases.json` 最新为 v0.50.0,GitHub Release 已到 v0.52.0。GitHub 的 `release.yml` 没有上传 R2 的步骤,`release_r2.py` 只由 GitLab 的 `publish-release` 调用。接入 Sparkle 前须先恢复 GitHub 发版流程的 R2 上传,否则 feed 托管须改为 GitHub 上固定标签的 Release 附件,地址要长期绑定这个仓库路径。
+1. **作业。** `release.yml` 的 `sparkle-appcast` 作业只在版本标签上、仓库变量 `SPARKLE_APPCAST_ENABLED` 为 `true` 时运行,排在 GitHub Release 公开之后,使用 `release` environment。
+2. **生成。** 每个架构下载本版本的 DMG 与线上现有 appcast(404 视为首次,其他错误中止),用官方 `generate_appcast --ed-key-file - --download-url-prefix <Release 下载地址> --maximum-versions 5` 从标准输入读私钥并追加本版本条目。工具挂载 DMG 读取包内 `Info.plist`,写出 `sparkle:version`、`sparkle:minimumSystemVersion`、`length` 与 `sparkle:edSignature`。
+3. **门槛。** `scripts/sparkle_appcast.py annotate` 补写迁移号,`verify` 核对本版本条目唯一且高于所有旧条目、下载地址与大小对得上实际 DMG、有签名、有最低系统版本、迁移号等于本提交的最高迁移号。签名由官方 `sign_update --verify` 用同一私钥核对。任何一项不过就不上传。
+4. **下载地址。** enclosure 指向同一 GitHub Release 的 DMG,与 `release_updates` 同版本优先 GitHub 的做法一致,也不依赖 R2 是否同步了 DMG。Sparkle 每个条目只有一个下载地址,没有备用源。
+5. **托管。** appcast 上传到 R2 的 `sparkle/macos-<架构>.xml`,经 `https://downloads.peach.video` 公开,缓存一分钟,上传后从公开入口完整下载核对。feed 放在自有域名,以后换存储后端不必改已装客户端。撰写时 `downloads.peach.video/releases.json` 最新为 v0.50.0,GitHub 发版流程不更新 R2 上的 DMG 与版本索引;appcast 作业只上传 appcast,需要的 R2 凭据要配进 GitHub 的 `release` environment。
+6. **架构分开。** 在 Apple 芯片上经 Rosetta 运行 x86_64 包时,继续拿到 x86_64 的更新,与 `release_updates.check` 用 `platform.machine()` 选 DMG 的行为一致。不用 2.9 起的 `sparkle:hardwareRequirements`:它只能声明「需要 arm64」,表达不了「只给 x86_64」。
-### 五、EdDSA 私钥的保管与注入
+### 六、EdDSA 私钥的保管与注入
-1. 用户在自己的 Mac 上运行 `generate_keys --account peach`,私钥存入登录钥匙串,输出的公钥写进仓库常量。
-2. `generate_keys --account peach -x <文件>` 导出私钥(内容是 32 字节 seed 的 base64),存入 GitHub 仓库 `release` environment 的 secret,并限定只有 `v*` 标签能部署到该 environment;另在用户的密码管理器里离线备份一份,然后删除导出文件。
-3. 只有第四节的标签作业引用这个 secret,通过 `echo "$SPARKLE_ED_PRIVATE_KEY" | generate_appcast --ed-key-file - …` 传入,不落盘、不进日志。版本提交的演练和 GitGud 流水线都不持有私钥。
+1. 维护者用 Sparkle 发布包里的 `generate_keys` 生成密钥对,公钥写进 `PUBLIC_ED_KEY`。
+2. `generate_keys -x <文件>` 导出私钥(内容是 32 字节 seed 的 base64),存入 GitHub 仓库 `release` environment 的 secret `SPARKLE_ED_PRIVATE_KEY`,该 environment 只允许 `v*` 标签部署;另在密码管理器里离线备份一份,然后删除导出文件。
+3. 只有 `sparkle-appcast` 作业引用这个 secret,经标准输入交给官方工具,不落盘、不进日志。版本提交的演练和 GitGud 流水线都不持有私钥。
4. 私钥丢失意味着所有已装的 Sparkle 客户端都要手动重装 DMG,因此备份是硬要求,不是建议。
-### 六、与现有逻辑的衔接
+### 七、与现有逻辑的衔接
-| 位置 | 改动 |
+| 位置 | 现状 |
| --- | --- |
-| `distribution` | 新增 `update_installer()`,返回 `"windows-package"`、`"sparkle"` 或 `None`。`in_app_update()` 继续只管 Windows 的 `standalone_update`,不复用为 Sparkle 开关 |
-| `release_updates.check` | 保留 macOS 按架构选 DMG 的逻辑,供设置页显示版本,也供尚未接入 Sparkle 的旧客户端使用;结果增加 `installer` 字段 |
-| 设置页「检查更新」 | 有 Sparkle 时下载键改为「安装更新」,请求经现有状态文件通道交给菜单栏进程(复用 `standalone_update.poll(tray)` 的轮询方式),由它调用 `checkForUpdates:` 弹出 Sparkle 窗口 |
-| `automatic_updates` | macOS 不再自己发通知或下载,只刷新设置页状态;定时检查与提醒交给 Sparkle,避免两套调度重复提示 |
-| 菜单栏「检查更新」 | 改为 Sparkle 的 `checkForUpdates:` |
-| `scripts/MACOS_DOWNLOADS.md`、`docs/OPERATIONS.md` | 移除隔离标记的命令只在首次安装时需要;之后经 Sparkle 更新不再需要 |
-| `docs/REUSE.md` | 登记 Sparkle 的版本、许可与选用理由 |
+| 菜单栏「检查更新」 | 启用时交给 Sparkle,否则沿用版本检查与系统通知 |
+| 设置页「检查更新」 | 不改:继续显示本机架构 DMG 的下载键。改为触发菜单栏 Sparkle 需要服务进程与菜单栏进程之间的请求通道和页面预览,留待启用之后单独交付 |
+| `release_updates.check`、`distribution.in_app_update()` | 不改:前者继续供设置页与接入前的客户端使用,后者继续只管 Windows 的 `standalone_update` |
+| `automatic_updates` | 不改:服务进程照常定期检查并刷新设置页状态,不发通知;菜单栏把同一份偏好映射给 Sparkle |
+| `scripts/MACOS_DOWNLOADS.md` | 启用前不改。启用后改为移除隔离标记的命令只在首次安装时需要 |
+| `docs/OPERATIONS.md`、`docs/REUSE.md` | 登记随包框架、启用步骤与选用理由 |
-### 七、旧客户端兼容门槛
+### 八、旧客户端兼容门槛
参照 ADR-0120,这里有两类已装客户端:
-1. **接入前的客户端**只读 `releases.json` 与 GitHub API 里的 `Peach-<版本>-macos-<架构>.dmg`,给出下载键。DMG 文件名和 `releases.json` 字段保持不变;第一个带 Sparkle 的版本由用户手动安装一次。
-2. **接入后的客户端**把 feed 地址和公钥写死在包里。标签作业在上传 appcast 之前对每个架构核对:appcast 能解析;本版本条目的 `sparkle:edSignature` 用仓库公钥验得过实际 DMG;`sparkle:version` 高于 appcast 里所有旧条目;`minimumSystemVersion` 等于本次构建报告的 `minimum_macos`;enclosure 地址可公开下载且大小一致。任何一项不过就不上传。门槛同时由单元测试用合成的 DMG 与临时密钥对跑一遍,并在 macOS 验收作业里用临时私钥文件跑一次官方 `sign_update --verify`,确认签名格式与 Sparkle 一致。
+1. **接入前的客户端**只读 `releases.json` 与 GitHub API 里的 `Peach-<版本>-macos-<架构>.dmg`,给出下载键。DMG 文件名和 `releases.json` 字段保持不变;第一个带公钥的版本由用户手动安装一次。
+2. **接入后的客户端**把 feed 地址和公钥写死在包里。第五节的门槛保证 appcast 只在签名、版本、下载地址与迁移号都核对过之后上传;单元测试用合成的 appcast 与 DMG 覆盖同一套判据。
3. 需要放弃一批 Sparkle 客户端时,用 appcast 的 `sparkle:minimumAutoupdateVersion` 或 `sparkle:minimumUpdateVersion` 显式声明,并在变更日志写明手动升级方法,与 `OLDEST_CLIENT` 的作用相同。
## 需要用户授权或决定的步骤
-1. 生成 EdDSA 密钥对、导出私钥、写入 GitHub `release` environment secret、离线备份并删除导出文件(第五节)。凭据与私钥操作须在同一轮取得明确授权。
-2. 在 GitHub 仓库设置中把 `release` environment 限定为 `v*` 标签部署。
-3. 决定 feed 托管:恢复 GitHub 发版流程的 R2 上传(推荐),或改用 GitHub 固定标签的 Release 附件。前者还需要把 R2 凭据配进 GitHub 的 `release` environment。
-4. 认可「私钥无法轮换、丢失即全体手动重装」这一后果。
-5. 在一台或多台真机上完成下节的验收后,才把 Sparkle 版本标为可发布。
+1. 生成 EdDSA 密钥对、导出私钥、写入 GitHub `release` environment secret、离线备份并删除导出文件(第六节)。凭据与私钥操作须在同一轮取得明确授权。
+2. 在 GitHub 仓库设置中把 `release` environment 限定为 `v*` 标签部署,配好 R2 凭据,再把 `SPARKLE_APPCAST_ENABLED` 设为 `true`。
+3. 认可「私钥无法轮换、丢失即全体手动重装」这一后果。
+4. 在真机上完成下节的验收后,才发布第一个带公钥的版本。
## 未取得的证据
@@ -123,23 +122,22 @@ Sparkle 由 `Autoupdate` 经 LaunchServices 重开应用,不带 LaunchAgent
- **应用管理保护。** ad-hoc 签名、没有 Team ID 的 `Autoupdate` 替换同为 ad-hoc 的 `Peach.app` 时,macOS 13、14、15、26 是否拦截或弹出「想要管理其他应用」的通知:未取得。如果拦截,用户须在「系统设置 > 隐私与安全性 > 应用管理」放行一次,并确认放行能否跨版本保留。
- **Gatekeeper 与 `gktool scan`。** 未隔离的 ad-hoc 包在 macOS 15 与 26 上替换后能否直接启动,`gktool scan` 对 ad-hoc 包的返回值:未取得。
-- **pyobjc 调用委托。** `objc.loadBundle` 加载框架后,带 block 参数的委托方法(`untilInvokingBlock:`、`immediateInstallationBlock:`)需要用 `objc.registerMetaDataForSelector` 声明 block 签名才能从 Python 调用,`supportsGentleScheduledUpdateReminders` 要按只读属性实现:均未取得。
-- **`generate_appcast` 保留旧条目。** 更新目录里只放本版本 DMG 时,旧条目及其中补写的 `peach:migrationHead`、按版本不同的 enclosure 前缀是否原样保留:未取得。
-- **重开后的数据根。** 经 LaunchServices 重开、不带 `--data-root` 时,独立包能否找到 LaunchAgent 指定的同一数据根:未取得。
+- **pyobjc 委托的实际调用。** 默认签名的委托方法被 Sparkle 调用时参数与返回值是否正确编组,`bestValidUpdateInAppcast:forUpdater:` 返回空条目后 Sparkle 的界面表现:未取得。macOS CI 只核对 BOOL 方法的类型声明。
+- **`generate_appcast` 保留旧条目。** 更新目录里只放本版本 DMG 时,旧条目及其中补写的 `peach:migrationHead` 是否原样保留:未取得。旧条目丢失不影响更新,只影响版本历史。
- **安装位置权限。** 应用不在当前用户可写的位置(例如由另一个管理员拖入「应用程序」)时 Sparkle 的授权流程:未取得。
-- **与 launchd 自动拉起的配合。** 菜单栏「异常退出后由 launchd 拉起」的改动尚在进行,`KeepAlive` 的最终形态未取得;本方案要求更新时的正常退出不会触发拉起。
## 已拒绝方案
- **照搬 Windows:自写 DMG 下载、挂载、替换与重启。** 与「各平台采用最成熟方案」的前提相悖。Sparkle 已经处理了替换时机、原子交换、隔离标记、降级保护和签名校验,自写只会重复这些边界。
- **先做 Developer ID 签名与公证,再接 Sparkle。** 能消除应用管理与隔离标记两项未知,但需要付费开发者账号与公证流程。它与 Sparkle 不互斥:只要 EdDSA 私钥不变,以后从 ad-hoc 改为 Developer ID 不影响已装客户端,所以不作为前置条件。
-- **在 ubuntu 上用 Python 计算 EdDSA 签名、自己拼 appcast。** 能沿用现有的 Linux 发布作业,但要重新实现官方工具已有的读取包信息、签名与签名 feed 格式。官方 `generate_appcast` 只需要一个仅在标签上运行的 macOS 作业,因此选用官方工具,Python 只做发布前的校验。
+- **在 ubuntu 上用 Python 计算 EdDSA 签名、自己拼 appcast。** 能沿用现有的 Linux 发布作业,但要重新实现官方工具已有的读取包信息与签名,还要为直接导入 `cryptography` 声明新依赖。官方工具只需要一个仅在标签上运行的 macOS 作业,因此选用官方工具,Python 只做 Peach 自己的约束。
- **两个架构合并成一份 appcast,用 `sparkle:hardwareRequirements` 区分。** 该元素只能要求 arm64,表达不了「只给 x86_64」;分开两份更直接,也与按架构命名的 DMG 一致。
- **另出 ZIP 作为更新包。** Sparkle 支持 DMG,复用现有 DMG 不增加制品与发布桶占用。增量包需要在 macOS 上用 `BinaryDelta` 生成,体积收益留待以后评估。
+- **开启自动下载、退出时安装。** 下载好的版本在用户退出 Peach 时静默安装,没有确认环节,任务保护与停服务都挤在退出路径上,真机行为也未取得;第一版只做手动确认安装。
## 后果
-- 接入后,macOS 用户在菜单栏或设置页即可完成更新,只在首次安装时执行一次移除隔离标记的命令。
-- 发布流程新增一个仅在标签上运行的 macOS 作业和一份长期有效的 feed 地址;R2 发布须先恢复。
-- EdDSA 私钥成为不可替换的资产。仓库公钥由测试锁定,更换要新的 ADR,并接受已装客户端全部手动重装。
-- 应用管理保护的真机结果可能改变上线方式:若 macOS 拦截 ad-hoc 包的自更新,要么在文档中说明放行步骤,要么先完成 Developer ID 签名再上线 Sparkle。
+- 启用后,macOS 用户在菜单栏即可完成更新,只在首次安装时执行一次移除隔离标记的命令;设置页仍给出 DMG 下载键,直到页面接入另行交付。
+- 发布流程多一个仅在标签上运行的 macOS 作业和一份长期有效的 feed 地址;R2 凭据要配进 GitHub。
+- EdDSA 私钥成为不可替换的资产。更换要新的 ADR,并接受已装客户端全部手动重装。
+- 应用管理保护的真机结果可能改变上线方式:若 macOS 拦截 ad-hoc 包的自更新,要么在文档中说明放行步骤,要么先完成 Developer ID 签名再启用 Sparkle。
diff --git a/scripts/build_macos_standalone.py b/scripts/build_macos_standalone.py
index fd9fa7e8a..00d705429 100644
--- a/scripts/build_macos_standalone.py
+++ b/scripts/build_macos_standalone.py
@@ -18,7 +18,7 @@ import tempfile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
-from peach import __version__
+from peach import __version__, sparkle_update
def minimum_system_version(app: Path) -> str:
@@ -70,6 +70,12 @@ def package_dmg(app: Path, destination: Path) -> Path:
return destination
+def install_sparkle(app: Path, source: Path) -> None:
+ """框架放在 `Contents/Frameworks`,即 PyInstaller 的 `_MEIPASS`;保留符号链接,签名由取件时完成。"""
+ shutil.copytree(source / "Sparkle.framework", app / "Contents/Frameworks/Sparkle.framework", symlinks=True)
+ shutil.copyfile(source / "LICENSE-Sparkle.txt", app / "Contents/Resources/LICENSE-Sparkle.txt")
+
+
def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None,
require_reporting: bool = False) -> dict[str, str]:
if sys.platform != "darwin":
@@ -85,6 +91,7 @@ def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None
from media_tool_bundle import validate
from build_macos_media import audit_binary
from fetch_cloudflared_macos import validate as validate_cloudflared
+ from fetch_sparkle_macos import validate as validate_sparkle
from fetch_face_models import install as install_face_models
from build_amane_runtime import build as build_amane_runtime, verify as verify_amane_runtime
@@ -97,6 +104,8 @@ def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None
audit_binary(media_root / tool / tool / name, architecture)
cloudflared = media_root / "cloudflared"
validate_cloudflared(cloudflared, architecture)
+ sparkle = media_root / "sparkle"
+ validate_sparkle(sparkle)
work = ROOT / "build" / "macos-standalone" / architecture
amane_runtime = work / "amane-runtime"
build_amane_runtime(amane_runtime, work=work / "amane-build")
@@ -139,12 +148,14 @@ def build(destination: Path, *, dmg: bool = True, target_arch: str | None = None
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")
+ install_sparkle(app, sparkle)
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())
info["LSMinimumSystemVersion"] = minimum
+ info.update(sparkle_update.info_plist_keys(architecture))
info_path.write_bytes(plistlib.dumps(info))
subprocess.run(["codesign", "--force", "--sign", "-", str(app)], check=True)
subprocess.run(["codesign", "--verify", "--deep", "--strict", str(app)], check=True)
diff --git a/scripts/ci_macos.sh b/scripts/ci_macos.sh
index b893540de..0e7bb47c4 100644
--- a/scripts/ci_macos.sh
+++ b/scripts/ci_macos.sh
@@ -96,6 +96,7 @@ for tool in ffmpeg untrunc; do
done
"$python" scripts/fetch_cloudflared_macos.py --arch "$architecture" \
--destination "$root/build/media-macos/$architecture/cloudflared"
+"$python" scripts/fetch_sparkle_macos.py --destination "$root/build/media-macos/$architecture/sparkle"
"$python" scripts/build_macos_standalone.py --target-arch "$architecture" --destination "$output" --require-reporting
"$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"
diff --git a/scripts/fetch_sparkle_macos.py b/scripts/fetch_sparkle_macos.py
new file mode 100644
index 000000000..5fa15d010
--- /dev/null
+++ b/scripts/fetch_sparkle_macos.py
@@ -0,0 +1,87 @@
+"""获取固定的官方 Sparkle 2,去掉非沙盒应用用不到的 XPC 服务,按 ad-hoc 由内向外重签。"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tarfile
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from fetch_ffmpeg_sources import digest, download_source
+from media_tool_bundle import checked_file
+
+LOCK = Path(__file__).with_name("sparkle-macos.json")
+FRAMEWORK = "Sparkle.framework"
+#: 发布作业用来生成与核对 appcast 的官方工具;打包只取框架。
+TOOLS = ("bin/generate_appcast", "bin/sign_update")
+#: 框架里自带签名的嵌套代码,按由内向外的顺序重签;最后签框架本身封住资源清单。
+NESTED_CODE = ("Versions/B/Autoupdate", "Versions/B/Updater.app")
+
+
+def _members(package: tarfile.TarFile, tools: bool) -> list[tarfile.TarInfo]:
+ wanted = []
+ for member in package:
+ name = member.name.removeprefix("./")
+ if (name == "LICENSE" or name == FRAMEWORK or name.startswith(FRAMEWORK + "/")
+ or (tools and name in TOOLS)):
+ wanted.append(member)
+ if not any(m.name.removeprefix("./") == "LICENSE" for m in wanted) or not any(
+ m.name.removeprefix("./") == f"{FRAMEWORK}/Versions/B/Sparkle" for m in wanted):
+ raise ValueError("Sparkle 官方归档内容不符")
+ return wanted
+
+
+def strip_xpc_services(framework: Path) -> None:
+ """XPC 服务只给沙盒应用用;删目录的同时删掉顶层那条指向它的符号链接。"""
+ shutil.rmtree(framework / "Versions/B/XPCServices")
+ (framework / "XPCServices").unlink()
+
+
+def sign(framework: Path, run=subprocess.run) -> None:
+ for relative in (*NESTED_CODE, ""):
+ run(["codesign", "--force", "--sign", "-", str(framework / relative) if relative else str(framework)],
+ check=True)
+
+
+def fetch(destination: Path, *, tools: bool = False) -> Path:
+ lock = json.loads(LOCK.read_text(encoding="utf-8"))
+ destination.mkdir(parents=True, exist_ok=True)
+ archive = destination / "Sparkle.tar.xz"
+ download_source({**lock["asset"], "name": "Sparkle"}, archive)
+ framework = destination / FRAMEWORK
+ shutil.rmtree(framework, ignore_errors=True)
+ with tarfile.open(archive, "r:xz") as package:
+ package.extractall(destination, members=_members(package, tools), filter="data")
+ strip_xpc_services(framework)
+ sign(framework)
+ (destination / "LICENSE").replace(destination / "LICENSE-Sparkle.txt")
+ (destination / "manifest.json").write_text(json.dumps({
+ "version": lock["version"], "source": lock["asset"],
+ "license": digest(destination / "LICENSE-Sparkle.txt")}, indent=2) + "\n", encoding="utf-8")
+ return framework
+
+
+def validate(destination: Path) -> dict:
+ """打包前核对:清单与固定版本一致,归档与许可证未变,XPC 服务已去掉。"""
+ lock = json.loads(LOCK.read_text(encoding="utf-8"))
+ manifest = json.loads((destination / "manifest.json").read_text(encoding="utf-8"))
+ if manifest.get("version") != lock["version"] or manifest.get("source") != lock["asset"]:
+ raise ValueError("Sparkle 清单与固定发行不符")
+ checked_file(destination, "Sparkle.tar.xz", lock["asset"]["sha256"])
+ checked_file(destination, "LICENSE-Sparkle.txt", manifest["license"])
+ framework = destination / FRAMEWORK
+ if not (framework / "Versions/B/Sparkle").is_file() or (framework / "Versions/B/XPCServices").exists():
+ raise ValueError("Sparkle 框架缺失或仍带 XPC 服务")
+ return manifest
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--destination", type=Path, required=True)
+ parser.add_argument("--tools", action="store_true", help="同时取出 generate_appcast 与 sign_update")
+ args = parser.parse_args()
+ fetch(args.destination.resolve(), tools=args.tools)
diff --git a/scripts/sparkle-macos.json b/scripts/sparkle-macos.json
new file mode 100644
index 000000000..565a123fe
--- /dev/null
+++ b/scripts/sparkle-macos.json
@@ -0,0 +1,8 @@
+{
+ "version": "2.10.1",
+ "license": "MIT",
+ "asset": {
+ "url": "https://github.com/sparkle-project/Sparkle/releases/download/2.10.1/Sparkle-2.10.1.tar.xz",
+ "sha256": "1a856d2a9edb8e628de88121d7be04cf0e2167f8641650b78fca00b14244cf27"
+ }
+}
diff --git a/scripts/sparkle_appcast.py b/scripts/sparkle_appcast.py
new file mode 100644
index 000000000..988419875
--- /dev/null
+++ b/scripts/sparkle_appcast.py
@@ -0,0 +1,135 @@
+"""给官方 generate_appcast 生成的 appcast 补写迁移号,上传前核对本版本条目,再发布到 R2(ADR-0130)。
+
+签名由 generate_appcast 完成,签名是否有效由发布作业用官方 sign_update --verify 核对;这里只管
+Sparkle 工具不知道的 Peach 约束:本版本是最高版本,下载地址与大小对得上实际 DMG,迁移号齐全。
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import xml.etree.ElementTree as ET
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach.sparkle_update import MIGRATION_HEAD, MIGRATION_NAMESPACE, migration_head
+
+SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle"
+ET.register_namespace("sparkle", SPARKLE)
+ET.register_namespace("peach", MIGRATION_NAMESPACE)
+HEAD_TAG = f"{{{MIGRATION_NAMESPACE}}}{MIGRATION_HEAD.split(':', 1)[1]}"
+
+
+def _version(text: str | None) -> tuple[int, ...]:
+ if not text or not re.fullmatch(r"\d+(\.\d+){0,3}", text.strip()):
+ raise ValueError(f"appcast 版本号无效:{text}")
+ return tuple(int(part) for part in text.strip().split("."))
+
+
+def _items(tree: ET.ElementTree) -> list[ET.Element]:
+ channel = tree.getroot().find("channel")
+ if channel is None:
+ raise ValueError("appcast 缺少 channel")
+ return channel.findall("item")
+
+
+def _item(tree: ET.ElementTree, version: str) -> ET.Element:
+ matches = [item for item in _items(tree) if item.findtext(f"{{{SPARKLE}}}version") == version]
+ if len(matches) != 1:
+ raise ValueError(f"appcast 里版本 {version} 的条目有 {len(matches)} 个")
+ return matches[0]
+
+
+def annotate(path: Path, version: str, head: int) -> None:
+ tree = ET.parse(path)
+ item = _item(tree, version)
+ element = item.find(HEAD_TAG)
+ if element is None:
+ element = ET.SubElement(item, HEAD_TAG)
+ element.text = str(head)
+ tree.write(path, encoding="utf-8", xml_declaration=True)
+
+
+def verify(path: Path, *, version: str, dmg: Path, url_prefix: str, head: int) -> dict:
+ """返回本版本条目的签名,供 sign_update --verify 使用。"""
+ tree = ET.parse(path)
+ item = _item(tree, version)
+ for other in _items(tree):
+ if other is not item and _version(other.findtext(f"{{{SPARKLE}}}version")) >= _version(version):
+ raise ValueError("appcast 里有不低于本版本的条目")
+ enclosure = item.find("enclosure")
+ if enclosure is None:
+ raise ValueError("本版本条目缺少 enclosure")
+ if enclosure.get("url") != url_prefix + dmg.name:
+ raise ValueError(f"下载地址不符:{enclosure.get('url')}")
+ if enclosure.get("length") != str(dmg.stat().st_size):
+ raise ValueError("enclosure 大小与 DMG 不符")
+ signature = enclosure.get(f"{{{SPARKLE}}}edSignature")
+ if not signature:
+ raise ValueError("本版本条目缺少 EdDSA 签名")
+ if item.findtext(HEAD_TAG) != str(head):
+ raise ValueError("本版本条目的迁移号缺失或不符")
+ if not item.findtext(f"{{{SPARKLE}}}minimumSystemVersion"):
+ raise ValueError("本版本条目缺少最低系统版本")
+ return {"version": version, "signature": signature}
+
+
+def publish(feeds: list[Path]) -> list[dict]:
+ """appcast 按 releases.json 的方式短缓存覆盖上传,再从公开入口完整下载核对。"""
+ from release_r2 import rclone_environment, verify_download
+ environment = rclone_environment()
+ executable = environment.get("PEACH_RCLONE") or shutil.which("rclone")
+ if not executable:
+ raise ValueError("发布需要官方 rclone")
+ base = environment["PEACH_R2_PUBLIC_BASE"].rstrip("/")
+ published = []
+ with tempfile.TemporaryDirectory(prefix="peach-sparkle-") as directory:
+ configuration = Path(directory) / "rclone.conf"
+ configuration.touch()
+ for feed in feeds:
+ target = f"peach:{environment['PEACH_R2_BUCKET']}/sparkle/{feed.name}"
+ subprocess.run([executable, "copyto", str(feed), target, "--checksum", "--config", str(configuration),
+ "--header-upload", "Cache-Control: public, max-age=60"], env=environment, check=True)
+ item = {"name": feed.name, "size": feed.stat().st_size,
+ "sha256": hashlib.sha256(feed.read_bytes()).hexdigest()}
+ verify_download(f"{base}/sparkle/{feed.name}", item)
+ published.append(item)
+ return published
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ for name in ("annotate", "verify"):
+ command = commands.add_parser(name)
+ command.add_argument("--appcast", type=Path, required=True)
+ command.add_argument("--version", required=True)
+ if name == "verify":
+ command.add_argument("--dmg", type=Path, required=True)
+ command.add_argument("--url-prefix", required=True)
+ commands.add_parser("publish").add_argument("feeds", type=Path, nargs="+")
+ args = parser.parse_args(argv)
+ head = migration_head(Path(__file__).resolve().parents[1] / "migrations")
+ try:
+ if args.command == "annotate":
+ annotate(args.appcast, args.version, head)
+ result = {"version": args.version, "migration_head": head}
+ elif args.command == "verify":
+ result = verify(args.appcast, version=args.version, dmg=args.dmg, url_prefix=args.url_prefix, head=head)
+ else:
+ result = publish(args.feeds)
+ except (OSError, ValueError, ET.ParseError, subprocess.CalledProcessError) as error:
+ print(f"Sparkle appcast 未通过:{error}", file=sys.stderr)
+ return 1
+ print(json.dumps(result, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 5af73e669..5d08aa6de 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -186,6 +186,9 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"scripts/fetch_cloudflared_macos.py": ("tooling", "packaging"),
"scripts/fetch_face_models.py": ("tooling", "packaging"),
"scripts/cloudflared-macos.json": ("tooling", "packaging"),
+ "scripts/fetch_sparkle_macos.py": ("tooling", "packaging"),
+ "scripts/sparkle-macos.json": ("tooling", "packaging"),
+ "scripts/sparkle_appcast.py": ("tooling", "packaging"),
"scripts/fetch_ffmpeg_sources.py": ("tooling", "packaging"),
"scripts/ffmpeg-sources.json": ("tooling", "packaging"),
"scripts/build_ffmpeg_windows.sh": ("tooling", "packaging"),
@@ -204,6 +207,8 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
# 托盘既是 sync 域的服务编排,也被版本与桌面设置那些 tooling 测试读源码。
"src/peach/tray.py": ("sync", "tooling"),
"src/peach/menubar.py": ("sync", "tooling"),
+ # Sparkle 更新器由菜单栏持有,打包与发布门槛的测试也直接导入它。
+ "src/peach/sparkle_update.py": ("sync", "tooling", "packaging"),
# 托盘子服务与隧道的 cloudflared 共用这份 Job Object;两边的测试都要跑到。
"src/peach/process_job.py": ("tooling", "sync"),
'src/peach/task_control.py': ('catalog', 'media', 'metadata', 'follow', 'sync', 'tooling', 'web'),
diff --git a/scripts/version_bump.py b/scripts/version_bump.py
index 7b93b7312..ff08a3ef7 100644
--- a/scripts/version_bump.py
+++ b/scripts/version_bump.py
@@ -39,6 +39,8 @@ RUNTIME_INPUTS = (
"scripts/setup_macos_media_tools.py",
"scripts/fetch_cloudflared_macos.py",
"scripts/cloudflared-macos.json",
+ "scripts/fetch_sparkle_macos.py",
+ "scripts/sparkle-macos.json",
"scripts/media_tool_bundle.py",
"scripts/fetch_ffmpeg_sources.py",
"scripts/fetch_untrunc_sources.py",
diff --git a/src/peach/sparkle_update.py b/src/peach/sparkle_update.py
new file mode 100644
index 000000000..b4cdd48e2
--- /dev/null
+++ b/src/peach/sparkle_update.py
@@ -0,0 +1,216 @@
+"""macOS 独立包经 Sparkle 2 在应用内更新(ADR-0130)。
+
+Sparkle 在菜单栏进程的主线程里运行:检查、下载、EdDSA 校验与替换都由它完成,Peach 只在
+安装前做两件 Windows 更新器也做的事——读取端不装需要迁移账本的版本,装之前让任务保存
+进度并停掉自己拉起的服务。
+
+`PUBLIC_ED_KEY` 为 None 时整套不启用:构建不写 `SUPublicEDKey`,菜单栏沿用版本检查加
+DMG 下载。ad-hoc 签名下这把公钥无法轮换(ADR-0130),设置或更换都要先改 ADR。
+"""
+from __future__ import annotations
+
+import logging
+import plistlib
+import sqlite3
+import sys
+from pathlib import Path
+from typing import Callable
+
+from . import distribution
+
+LOGGER = logging.getLogger(__name__)
+
+FEED_URL = "https://downloads.peach.video/sparkle/macos-{architecture}.xml"
+#: EdDSA 公钥(base64,32 字节)。由维护者生成密钥对后写入,见 ADR-0130「需要用户授权的步骤」。
+PUBLIC_ED_KEY: str | None = None
+#: appcast 条目里新版本最高迁移号的元素名;Sparkle 以限定名为键放进 `propertiesDictionary`。
+MIGRATION_HEAD = "peach:migrationHead"
+MIGRATION_NAMESPACE = "https://peach.video/xml-namespaces/sparkle"
+
+
+def info_plist_keys(architecture: str) -> dict:
+ """构建写进 `Info.plist` 的 Sparkle 键;没有公钥时一个都不写。"""
+ if PUBLIC_ED_KEY is None:
+ return {}
+ return {
+ "SUFeedURL": FEED_URL.format(architecture=architecture),
+ "SUPublicEDKey": PUBLIC_ED_KEY,
+ "SUVerifyUpdateBeforeExtraction": True,
+ # 显式写值,Sparkle 不再在第二次启动时弹窗询问;实际开关由设置页的自动更新映射。
+ "SUEnableAutomaticChecks": True,
+ # 自动下载后在退出时安装绕开了安装前的任务保护,第一版只做手动确认安装。
+ "SUAllowsAutomaticUpdates": False,
+ }
+
+
+def framework_path() -> Path:
+ return Path(getattr(sys, "_MEIPASS", "")) / "Sparkle.framework"
+
+
+def available() -> bool:
+ """独立包带着框架、`Info.plist` 也写了公钥时才启用。"""
+ if sys.platform != "darwin" or not distribution.standalone():
+ return False
+ info = Path(sys.executable).resolve().parents[1] / "Info.plist"
+ try:
+ keys = plistlib.loads(info.read_bytes())
+ except (OSError, plistlib.InvalidFileException):
+ return False
+ return bool(keys.get("SUPublicEDKey")) and (framework_path() / "Versions/B/Sparkle").is_file()
+
+
+def migration_head(directory: Path) -> int:
+ from .migrations import discover
+ return max(int(migration.version) for migration in discover(directory))
+
+
+def install_blocker(heads: list[str | None], config) -> str | None:
+ """读取端不装需要迁移账本的版本;返回原因,可以装时返回 None。
+
+ `heads` 是 appcast 各条目的 `peach:migrationHead`;取最大值,宁可多拦一次也不让读取端
+ 装上一个启动就要迁移的版本。
+ """
+ from .runtime_prepare import configured_ledger_writer
+ database = config.directory("database") / "ledger.db"
+ writer, reason = configured_ledger_writer(config)
+ if writer or not database.is_file():
+ return None
+ numbers = [int(head) for head in heads if isinstance(head, str) and head.isdigit()]
+ if not numbers:
+ return f"本机不能迁移账本:{reason};更新源未给出新版本的迁移号,请先在写入端更新并同步"
+ connection = sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True)
+ try:
+ from .migrations import applied
+ done = [int(version) for version in applied(connection)]
+ finally:
+ connection.close()
+ if max(numbers) > max(done, default=0):
+ return f"本机不能迁移账本:{reason};请先在写入端更新并同步"
+ return None
+
+
+def prepare_install(database: Path, stop_services: Callable[[], None]) -> None:
+ """让任务保存进度、释放端口。预约绑定本进程,菜单栏退出后自动失效,新版本启动后任务继续。"""
+ from . import update_tasks
+ if database.is_file():
+ update_tasks.reserve(database)
+ update_tasks.wait_quiescent(database)
+ stop_services()
+
+
+def scheduled_settings(preferences: dict) -> tuple[bool, float]:
+ """设置页的自动更新偏好换成 Sparkle 的定时检查开关与间隔(秒)。"""
+ return preferences.get("mode") != "off", float(preferences.get("interval_hours", 24)) * 3600
+
+
+class Updater:
+ """菜单栏持有的 Sparkle 更新器。委托必须由这里强引用:Sparkle 只弱引用委托。"""
+
+ def __init__(self, controller, delegate):
+ self.controller = controller
+ self.delegate = delegate
+
+ def check(self) -> None:
+ self.controller.checkForUpdates_(None)
+
+ def apply(self, preferences: dict) -> None:
+ enabled, interval = scheduled_settings(preferences)
+ updater = self.controller.updater()
+ if bool(updater.automaticallyChecksForUpdates()) != enabled:
+ updater.setAutomaticallyChecksForUpdates_(enabled)
+ if updater.updateCheckInterval() != interval:
+ updater.setUpdateCheckInterval_(interval)
+
+ def follow(self, state_dir: Path) -> None:
+ """从任意线程读设置页的自动更新偏好,回主线程交给 Sparkle;失败只记日志,不打断调用方的轮询。"""
+ try:
+ from Foundation import NSOperationQueue
+ from .automatic_updates import AutomaticUpdates
+ preferences = AutomaticUpdates(state_dir, available=True).read()
+ except Exception:
+ LOGGER.exception("读取自动更新偏好失败")
+ return
+
+ def apply() -> None:
+ # 主线程回调里的 Python 异常会变成 ObjC 异常,在这里收住。
+ try:
+ self.apply(preferences)
+ except Exception:
+ LOGGER.exception("同步自动更新偏好到 Sparkle 失败")
+
+ NSOperationQueue.mainQueue().addOperationWithBlock_(apply)
+
+
+def start(*, config: Callable[[], object], stop_services: Callable[[], None],
+ notify: Callable[[str, str], None]) -> Updater | None:
+ """在主线程创建更新器;不可用或初始化失败时返回 None,菜单栏沿用版本检查。"""
+ if not available():
+ return None
+ try:
+ import objc
+ objc.loadBundle("Sparkle", {}, bundle_path=str(framework_path()))
+ delegate = _delegate_class()(config, stop_services, notify)
+ controller = objc.lookUpClass("SPUStandardUpdaterController").alloc() \
+ .initWithStartingUpdater_updaterDelegate_userDriverDelegate_(True, delegate, delegate)
+ return Updater(controller, delegate)
+ except Exception:
+ LOGGER.exception("Sparkle 更新器初始化失败,菜单栏改用版本检查")
+ return None
+
+
+def _delegate_class():
+ """返回委托的构造函数。委托只在 macOS 上定义,避免其他平台导入 AppKit。
+
+ 方法签名不依赖协议元数据:返回对象或无返回值的方法用 pyobjc 默认签名,返回 BOOL 的
+ 方法逐个声明。拒绝安装走 `bestValidUpdateInAppcast:forUpdater:` 返回空条目,不用带
+ `NSError **` 出参的方法。
+ """
+ import objc
+ from Foundation import NSObject
+
+ class SparkleDelegate(NSObject):
+ # 回调里的 Python 异常会变成 ObjC 异常打断 Sparkle,每个回调都在这里收住并记日志。
+ def bestValidUpdateInAppcast_forUpdater_(self, appcast, _updater):
+ try:
+ heads = [item.propertiesDictionary().get(MIGRATION_HEAD) for item in appcast.items()]
+ reason = install_blocker(heads, self._config())
+ except Exception as exc:
+ LOGGER.exception("核对更新的账本迁移失败")
+ reason = f"未能核对账本迁移:{exc}"
+ if reason is None:
+ return None
+ # 空条目让 Sparkle 按「没有可用更新」收尾,原因另用通知说明。
+ self._notify(reason, "Peach 版本与更新")
+ return objc.lookUpClass("SUAppcastItem").emptyAppcastItem()
+
+ def updater_willInstallUpdate_(self, _updater, _item):
+ try:
+ prepare_install(self._config().directory("database") / "ledger.db", self._stop)
+ except Exception:
+ # 预约失败(例如另一个安装在进行)时任务来不及保存进度;服务仍要停,否则新版本抢不到端口。
+ LOGGER.exception("安装前保存任务进度失败")
+ self._stop()
+
+ def updaterWillRelaunchApplication_(self, _updater):
+ try:
+ self._stop()
+ except Exception:
+ LOGGER.exception("重开前停止服务失败")
+
+ @objc.typedSelector(b"Z@:")
+ def supportsGentleScheduledUpdateReminders(self):
+ return True
+
+ @objc.typedSelector(b"v@:Z@@")
+ def standardUserDriverWillHandleShowingUpdate_forUpdate_state_(self, handle, item, state):
+ # 附件应用没有窗口可前置;定时检查到的更新用系统通知提醒一次。
+ if not state.userInitiated():
+ self._notify(f"Peach {item.displayVersionString()} 可以安装,"
+ "在菜单栏「版本与更新」中点「检查更新」", "Peach 版本与更新")
+
+ def create(config, stop_services, notify):
+ delegate = SparkleDelegate.alloc().init()
+ delegate._config, delegate._stop, delegate._notify = config, stop_services, notify
+ return delegate
+
+ return create
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 918b9f80b..ae2c0fac4 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -24,7 +24,8 @@ import httpx
import pystray
from PIL import Image
-from . import desktop_startup, error_reporting, ledger_backups, log_retention, onboarding, runtime_prepare, settings_file
+from . import (desktop_startup, error_reporting, ledger_backups, log_retention, onboarding, runtime_prepare,
+ settings_file, sparkle_update)
from .appid import MACOS_LAUNCH_AGENT_LABEL
from .certs import ensure_certificate
from .distribution import standalone
@@ -1612,6 +1613,38 @@ def export_macos_diagnostics(notify: Callable[[str, str], None]) -> None:
threading.Thread(target=work, name="PeachDiagnostics", daemon=True).start()
+class MacUpdateEntry:
+ """macOS 菜单栏的「检查更新」:启用 Sparkle 时由它检查、下载并在退出时替换,否则做版本检查。
+
+ 版本检查和「同步开发进度」「同步 Ledger」共用菜单栏那把动作锁;Sparkle 自己串行,不占锁。
+ """
+
+ def __init__(self, sparkle, versions: VersionManager, state: dict, lock: threading.Lock,
+ notify: Callable[[str, str], None]):
+ self.sparkle, self.versions, self.state, self.lock, self.notify = sparkle, versions, state, lock, notify
+
+ def check(self) -> None:
+ # 菜单项在主线程上回调,Sparkle 可以直接调用。
+ if self.sparkle is not None:
+ self.sparkle.check()
+ elif self.lock.acquire(blocking=False):
+ threading.Thread(target=self._check_versions, name="PeachUpdate", daemon=True).start()
+
+ def _check_versions(self) -> None:
+ try:
+ self.notify("正在检查更新…", "Peach")
+ result = self.versions.check()
+ self.state["snapshot"] = result.snapshot
+ self.notify(result.message, "Peach 版本与更新")
+ finally:
+ self.lock.release()
+
+ def follow(self, state_dir: Path) -> None:
+ """设置页的自动更新偏好同步给 Sparkle;没有 Sparkle 时服务进程自己定时检查。"""
+ if self.sparkle is not None:
+ self.sparkle.follow(state_dir)
+
+
def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = None, *, silent: bool = False, show_browser: bool = False) -> None:
"""macOS 走原生菜单栏项。
@@ -1712,20 +1745,8 @@ def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = Non
def open_configuration() -> None:
webbrowser.open(gate.open_url() + "configuration")
- def check_updates() -> None:
- if not action_lock.acquire(blocking=False):
- return
-
- def work() -> None:
- try:
- notify("正在检查更新…", "Peach")
- result = versions.check()
- state["snapshot"] = result.snapshot
- notify(result.message, "Peach 版本与更新")
- finally:
- action_lock.release()
-
- threading.Thread(target=work, name="PeachUpdate", daemon=True).start()
+ # Sparkle 要在 NSApplication 建好之后创建,先放空,菜单建好再补上。
+ updates = MacUpdateEntry(None, versions, state, action_lock, notify)
menu = MenuBarApp(
create_icon(template=True),
@@ -1749,13 +1770,15 @@ def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = Non
(menu_text(state['snapshot'].build_label), None),
(menu_text(state['snapshot'].channel_label), None),
(None, None),
- ("检查更新", check_updates),
+ ("检查更新", updates.check),
])),
(None, None),
("退出 Peach", quit_now),
],
)
app["app"] = menu
+ updates.sparkle = sparkle_update.start(config=lambda: gate.config, stop_services=manager.stop_owned,
+ notify=notify)
gate.notify = lambda message, title: notify(message, title)
if (gate.waiting and not silent) or show_browser:
gate.open()
@@ -1768,6 +1791,7 @@ def run_macos_menu_bar(manager: "ServiceManager", gate: "SetupGate | None" = Non
gate.poll()
for spec in manager.specs:
manager.healthy(spec)
+ updates.follow(gate.config.directory("state"))
def refresh_certificate() -> bool:
"""本机地址变了就补签证书并重启 HTTPS。成功返回 True。
diff --git a/tests/test_dependency_policy.py b/tests/test_dependency_policy.py
index 4b88f028f..f962f84f5 100644
--- a/tests/test_dependency_policy.py
+++ b/tests/test_dependency_policy.py
@@ -189,6 +189,7 @@ class DependencyPolicyTests(unittest.TestCase):
owners = {
"tldextract": "tldextract",
"AppKit": "pyobjc-framework-Cocoa",
+ "Foundation": "pyobjc-framework-Cocoa",
"PIL": "pillow",
"PyObjCTools": "pyobjc-framework-Cocoa",
"apscheduler": "APScheduler",
diff --git a/tests/test_macos_standalone.py b/tests/test_macos_standalone.py
index c8db63fcb..a925da727 100644
--- a/tests/test_macos_standalone.py
+++ b/tests/test_macos_standalone.py
@@ -226,3 +226,242 @@ class MacStandaloneDistributionTests(TestCase):
nested = app.menu.rows[0].setSubmenu_.call_args.args[0]
self.assertEqual([row.title for row in nested.rows], ["HTTP 正常"])
self.assertEqual(len(app._handlers), 1)
+
+
+def load_script(name: str):
+ path = Path(__file__).resolve().parents[1] / "scripts" / f"{name}.py"
+ sys.path.insert(0, str(path.parent))
+ try:
+ spec = importlib.util.spec_from_file_location(f"sparkle_{name}", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ finally:
+ sys.path.remove(str(path.parent))
+ return module
+
+
+APPCAST = """<?xml version="1.0" encoding="utf-8"?>
+<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
+ <channel>
+ <title>Peach</title>
+ <item>
+ <title>0.53.0</title>
+ <sparkle:version>0.53.0</sparkle:version>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <enclosure url="https://example.test/v0.53.0/Peach-0.53.0-macos-arm64.dmg" length="{length}"
+ type="application/octet-stream" sparkle:edSignature="c2lnbmF0dXJl"/>
+ </item>
+ <item>
+ <title>0.52.0</title>
+ <sparkle:version>0.52.0</sparkle:version>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <enclosure url="https://example.test/v0.52.0/Peach-0.52.0-macos-arm64.dmg" length="7"
+ type="application/octet-stream" sparkle:edSignature="b2xk"/>
+ </item>
+ </channel>
+</rss>
+"""
+
+
+class SparkleUpdateTests(TestCase):
+ """Sparkle 2 的打包、发布门槛与安装前保护(ADR-0130)。"""
+
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name).resolve()
+
+ def test_info_plist_carries_sparkle_keys_only_once_a_public_key_is_set(self):
+ from peach import sparkle_update
+
+ self.assertEqual(sparkle_update.info_plist_keys("arm64"), {})
+ with mock.patch.object(sparkle_update, "PUBLIC_ED_KEY", "cHVibGlj"):
+ keys = sparkle_update.info_plist_keys("x86_64")
+ self.assertEqual(keys["SUFeedURL"], "https://downloads.peach.video/sparkle/macos-x86_64.xml")
+ self.assertEqual(keys["SUPublicEDKey"], "cHVibGlj")
+ self.assertIs(keys["SUVerifyUpdateBeforeExtraction"], True)
+ self.assertIs(keys["SUAllowsAutomaticUpdates"], False)
+
+ def test_public_key_once_set_is_a_32_byte_ed25519_key(self):
+ import base64
+ from peach import sparkle_update
+
+ if sparkle_update.PUBLIC_ED_KEY is not None:
+ self.assertEqual(len(base64.b64decode(sparkle_update.PUBLIC_ED_KEY, validate=True)), 32)
+
+ def test_updater_is_unavailable_outside_the_macos_standalone_bundle(self):
+ from peach import sparkle_update
+
+ with mock.patch.object(sparkle_update.sys, "platform", "win32"):
+ self.assertFalse(sparkle_update.available())
+ self.assertIsNone(sparkle_update.start(config=mock.Mock(), stop_services=mock.Mock(), notify=mock.Mock()))
+
+ def test_framework_is_fetched_without_xpc_services_and_signed_inside_out(self):
+ fetcher = load_script("fetch_sparkle_macos")
+ framework = self.root / "Sparkle.framework"
+ (framework / "Versions/B/XPCServices/Installer.xpc").mkdir(parents=True)
+ (framework / "XPCServices").write_text("指向 Versions/Current/XPCServices 的链接", encoding="utf-8")
+ fetcher.strip_xpc_services(framework)
+ self.assertFalse((framework / "Versions/B/XPCServices").exists())
+ self.assertFalse((framework / "XPCServices").exists())
+ run = mock.Mock()
+ fetcher.sign(framework, run=run)
+ signed = [call.args[0][-1] for call in run.call_args_list]
+ self.assertEqual(signed, [str(framework / "Versions/B/Autoupdate"),
+ str(framework / "Versions/B/Updater.app"), str(framework)])
+ self.assertTrue(all(call.args[0][:4] == ["codesign", "--force", "--sign", "-"] for call in run.call_args_list))
+
+ def test_framework_validation_rejects_a_changed_lock_or_leftover_xpc_services(self):
+ import hashlib
+ import json
+
+ fetcher = load_script("fetch_sparkle_macos")
+ archive = self.root / "Sparkle.tar.xz"
+ archive.write_bytes(b"archive")
+ (self.root / "LICENSE-Sparkle.txt").write_text("MIT", encoding="utf-8")
+ binary = self.root / "Sparkle.framework/Versions/B/Sparkle"
+ binary.parent.mkdir(parents=True)
+ binary.write_bytes(b"framework")
+ asset = {"url": "https://example.test/Sparkle.tar.xz", "sha256": hashlib.sha256(b"archive").hexdigest()}
+ lock = self.root / "sparkle-macos.json"
+ lock.write_text(json.dumps({"version": "2.10.1", "asset": asset}), encoding="utf-8")
+ manifest = {"version": "2.10.1", "source": asset,
+ "license": hashlib.sha256(b"MIT").hexdigest()}
+ (self.root / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
+ with mock.patch.object(fetcher, "LOCK", lock):
+ self.assertEqual(fetcher.validate(self.root), manifest)
+ (self.root / "Sparkle.framework/Versions/B/XPCServices").mkdir()
+ with self.assertRaisesRegex(ValueError, "XPC"):
+ fetcher.validate(self.root)
+ lock.write_text(json.dumps({"version": "2.10.2", "asset": asset}), encoding="utf-8")
+ with self.assertRaisesRegex(ValueError, "固定发行"):
+ fetcher.validate(self.root)
+
+ def test_build_places_the_framework_in_the_bundle_frameworks_directory(self):
+ builder = load_script("build_macos_standalone")
+ source = self.root / "sparkle"
+ (source / "Sparkle.framework/Versions/B").mkdir(parents=True)
+ (source / "Sparkle.framework/Versions/B/Sparkle").write_bytes(b"framework")
+ (source / "LICENSE-Sparkle.txt").write_text("MIT", encoding="utf-8")
+ app = self.root / "Peach.app"
+ (app / "Contents/Frameworks").mkdir(parents=True)
+ (app / "Contents/Resources").mkdir()
+ builder.install_sparkle(app, source)
+ self.assertEqual((app / "Contents/Frameworks/Sparkle.framework/Versions/B/Sparkle").read_bytes(), b"framework")
+ self.assertEqual((app / "Contents/Resources/LICENSE-Sparkle.txt").read_text(encoding="utf-8"), "MIT")
+
+ def database(self, *versions: str) -> Path:
+ import sqlite3
+
+ path = self.root / "database" / "ledger.db"
+ path.parent.mkdir(parents=True)
+ with sqlite3.connect(path) as connection:
+ connection.execute("CREATE TABLE schema_migration(version TEXT PRIMARY KEY, name TEXT NOT NULL,"
+ " checksum TEXT NOT NULL, applied_at TEXT NOT NULL)")
+ connection.executemany("INSERT INTO schema_migration VALUES (?, 'm', 'c', 'now')",
+ [(version,) for version in versions])
+ connection.close()
+ return path
+
+ def test_reader_refuses_a_release_whose_migrations_its_ledger_has_not_applied(self):
+ from peach import sparkle_update
+
+ self.database("0049", "0050")
+ config = SimpleNamespace(directory=lambda name: self.root / name)
+ with mock.patch("peach.runtime_prepare.configured_ledger_writer", return_value=(False, "共享账本由另一台机器写入")):
+ self.assertIsNone(sparkle_update.install_blocker(["50", None], config))
+ self.assertIn("写入端", sparkle_update.install_blocker(["51"], config))
+ self.assertIn("迁移号", sparkle_update.install_blocker([None], config))
+ with mock.patch("peach.runtime_prepare.configured_ledger_writer", return_value=(True, "")):
+ self.assertIsNone(sparkle_update.install_blocker(["51"], config))
+
+ def test_install_saves_task_progress_before_releasing_the_ports(self):
+ from peach import sparkle_update
+
+ database = self.database("0050")
+ order = []
+ with mock.patch("peach.update_tasks.reserve", side_effect=lambda db: order.append(("reserve", db))), \
+ mock.patch("peach.update_tasks.wait_quiescent", side_effect=lambda db: order.append(("wait", db))):
+ sparkle_update.prepare_install(database, lambda: order.append(("stop",)))
+ self.assertEqual(order, [("reserve", database), ("wait", database), ("stop",)])
+ order.clear()
+ sparkle_update.prepare_install(self.root / "missing.db", lambda: order.append(("stop",)))
+ self.assertEqual(order, [("stop",)])
+
+ def test_settings_page_preferences_drive_sparkle_scheduled_checks(self):
+ from peach import sparkle_update
+
+ self.assertEqual(sparkle_update.scheduled_settings({"mode": "off", "interval_hours": 24}), (False, 86400.0))
+ self.assertEqual(sparkle_update.scheduled_settings({"mode": "check", "interval_hours": 6}), (True, 21600.0))
+ updater = mock.Mock()
+ updater.automaticallyChecksForUpdates.return_value = True
+ updater.updateCheckInterval.return_value = 86400.0
+ controller = mock.Mock()
+ controller.updater.return_value = updater
+ wrapper = sparkle_update.Updater(controller, object())
+ wrapper.apply({"mode": "check", "interval_hours": 24})
+ updater.setAutomaticallyChecksForUpdates_.assert_not_called()
+ updater.setUpdateCheckInterval_.assert_not_called()
+ wrapper.apply({"mode": "off", "interval_hours": 168})
+ updater.setAutomaticallyChecksForUpdates_.assert_called_once_with(False)
+ updater.setUpdateCheckInterval_.assert_called_once_with(604800.0)
+ wrapper.check()
+ controller.checkForUpdates_.assert_called_once_with(None)
+
+ def test_menu_bar_check_hands_over_to_sparkle_when_enabled(self):
+ from peach import tray
+
+ sparkle = mock.Mock()
+ menu_type = mock.Mock()
+ with mock.patch.dict(sys.modules, {"peach.menubar": SimpleNamespace(MenuBarApp=menu_type, Submenu=FakeSubmenu)}), \
+ mock.patch.object(tray, "standalone", return_value=True), \
+ mock.patch.object(tray, "VersionManager") as versions, \
+ mock.patch.object(tray, "create_icon"), \
+ mock.patch.object(tray.sparkle_update, "start", return_value=sparkle):
+ tray.run_macos_menu_bar(mock.Mock(specs=()), mock.Mock(waiting=False), silent=True)
+ submenu = dict(menu_type.call_args.args[2])["版本与更新"]
+ dict(row for row in submenu.items() if row[0])["检查更新"]()
+ sparkle.check.assert_called_once()
+ versions.return_value.check.assert_not_called()
+
+ def appcast(self, version="0.53.0"):
+ dmg = self.root / f"Peach-{version}-macos-arm64.dmg"
+ dmg.write_bytes(b"disk image")
+ feed = self.root / "macos-arm64.xml"
+ feed.write_text(APPCAST.format(length=dmg.stat().st_size), encoding="utf-8")
+ return feed, dmg
+
+ def test_appcast_gate_accepts_the_newest_signed_item_with_its_migration_head(self):
+ tool = load_script("sparkle_appcast")
+ feed, dmg = self.appcast()
+ tool.annotate(feed, "0.53.0", 50)
+ self.assertIn("peach:migrationHead", feed.read_text(encoding="utf-8"))
+ result = tool.verify(feed, version="0.53.0", dmg=dmg, url_prefix="https://example.test/v0.53.0/", head=50)
+ self.assertEqual(result["signature"], "c2lnbmF0dXJl")
+ with self.assertRaisesRegex(ValueError, "迁移号"):
+ tool.verify(feed, version="0.53.0", dmg=dmg, url_prefix="https://example.test/v0.53.0/", head=51)
+
+ def test_appcast_gate_rejects_a_stale_item_or_a_mismatched_download(self):
+ tool = load_script("sparkle_appcast")
+ feed, dmg = self.appcast()
+ tool.annotate(feed, "0.53.0", 50)
+ with self.assertRaisesRegex(ValueError, "不低于本版本"):
+ tool.verify(feed, version="0.52.0", dmg=dmg, url_prefix="https://example.test/v0.52.0/", head=50)
+ with self.assertRaisesRegex(ValueError, "下载地址"):
+ tool.verify(feed, version="0.53.0", dmg=dmg, url_prefix="https://mirror.example.test/", head=50)
+ dmg.write_bytes(b"different size")
+ with self.assertRaisesRegex(ValueError, "大小"):
+ tool.verify(feed, version="0.53.0", dmg=dmg, url_prefix="https://example.test/v0.53.0/", head=50)
+
+ @skipUnless(sys.platform == "darwin", "pyobjc 是 macOS 专属")
+ def test_delegate_declares_bool_returns_and_lets_sparkle_choose_when_nothing_blocks(self):
+ from peach import sparkle_update
+
+ delegate = sparkle_update._delegate_class()(mock.Mock(), mock.Mock(), mock.Mock())
+ methods = type(delegate).pyobjc_instanceMethods
+ self.assertTrue(methods.supportsGentleScheduledUpdateReminders.signature.startswith(b"Z"))
+ self.assertTrue(delegate.supportsGentleScheduledUpdateReminders())
+ appcast = mock.Mock()
+ appcast.items.return_value = []
+ with mock.patch.object(sparkle_update, "install_blocker", return_value=None):
+ self.assertIsNone(delegate.bestValidUpdateInAppcast_forUpdater_(appcast, None))