Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
feat: add signed host updates and channel-specific upgrade hints (#44)
MSK6cc98e11d610
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0a49644..4e767dc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -67,7 +67,7 @@ jobs:- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings- run: cargo test --workspace --all-features --locked- # 安装方式能用:deb 打得出、装得上;install.sh 过 shellcheck、真能从最新的 Release 装上;Homebrew formula 能生成+ # 安装方式能用:deb 打得出、装得上;用临时签名发行包校验 install.sh;Homebrew formula 能生成packages:needs: [changes]if: ${{ !cancelled() && (github.event_name != 'pull_request' || needs.changes.outputs.code == 'true') }}@@ -100,14 +100,12 @@ jobs:- name: install.shrun: |shellcheck -s sh install.sh- sh install.sh --no-service --prefix "$RUNNER_TEMP/ictl"- "$RUNNER_TEMP/ictl/bin/iphone-control" --version- sh install.sh --uninstall --prefix "$RUNNER_TEMP/ictl"- test ! -e "$RUNNER_TEMP/ictl/bin/iphone-control"+ python3 packaging/test_installer.py- name: Homebrew formularun: |shellcheck -s sh packaging/homebrew/formula.sh- sh packaging/homebrew/formula.sh v0.0.0 aaa bbb ccc > iphone-control.rb+ ICTL_UPDATE_PUBLISHER="$GITHUB_REPOSITORY" sh packaging/homebrew/formula.sh v0.0.0 aaa bbb ccc > iphone-control.rb+ grep -F "https://github.com/$GITHUB_REPOSITORY/releases/" iphone-control.rbruby -c iphone-control.rb# Cargo.toml 声明的最低版本(rust-version)要真能编译diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 3b26fa6..3f52f8d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -1,7 +1,7 @@name: Release# 推送 v* tag 时:Linux(x86_64、aarch64)和 macOS(Apple Silicon)的压缩包、Linux 的 .deb 及 sha256 附在 GitHub Release 上,-# 发布说明取自 CHANGELOG.md 和 CHANGELOG.zh-CN.md;最后更新 Homebrew 源 Derrors/homebrew-tap。不再发布 Docker 镜像+# 发布说明取自 CHANGELOG.md 和 CHANGELOG.zh-CN.md;稳定版按发布者配置签名并可选更新 tap。on:push:tags: ["v*"]@@ -9,10 +9,22 @@ on:permissions:contents: read+env:+ ICTL_UPDATE_PUBLISHER: ${{ vars.ICTL_UPDATE_PUBLISHER }}+ ICTL_UPDATE_PUBLIC_KEYS: ${{ vars.ICTL_UPDATE_PUBLIC_KEYS }}+ ICTL_UPDATE_TAP: ${{ vars.ICTL_UPDATE_TAP }}+jobs:+ provenance:+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v7+ - run: python3 packaging/release.py validate+# install.sh、Homebrew、deb 都用这里的包。在 Ubuntu 22.04 上编译(glibc 2.35),# 所以 Debian 12、Ubuntu 22.04 及更新的发行版都能运行binaries:+ needs: provenancestrategy:matrix:include:@@ -102,7 +114,11 @@ jobs:echo "## 中文"; echo; echo "$zh"; echoecho "---"; echoecho "**Binaries / 二进制:** \`linux-x86_64\`, \`linux-aarch64\` (glibc 2.34+), \`macos-arm64\` (macOS 11+, Apple Silicon); \`.deb\` amd64, arm64 (Debian 12+, Ubuntu 22.04+)"; echo- echo "**Install / 安装:** \`curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh\` (macOS, Linux) · \`brew install derrors/tap/iphone-control\` · Debian/Ubuntu: \`sudo apt install ./iphone-control_${version}_amd64.deb\` (or \`_arm64.deb\`)"+ echo "**Debian/Ubuntu:** \`sudo apt install ./iphone-control_${version}_amd64.deb\` (or \`_arm64.deb\`)"+ if [[ "$GITHUB_REF_NAME" != *-* ]]; then+ echo "**Installer:** \`curl -fsSL https://github.com/$GITHUB_REPOSITORY/releases/download/$GITHUB_REF_NAME/install.sh | sh\` (once the signed assets for your platform are available)"+ if [[ -n "$ICTL_UPDATE_TAP" ]]; then echo "**Homebrew:** \`brew install $ICTL_UPDATE_TAP/iphone-control\`"; fi+ fi} > notes.md- name: Create releaserun: |@@ -119,8 +135,6 @@ jobs:macos-binary:needs: releaseruns-on: macos-latest- permissions:- contents: writesteps:- uses: actions/checkout@v7- uses: dtolnay/[email protected]@@ -148,33 +162,122 @@ jobs:cp THIRD_PARTY_LICENSES.html "dist/$name/"tar -C dist -czf "dist/$name.tar.gz" "$name"(cd dist && shasum -a 256 "$name.tar.gz" > "$name.tar.gz.sha256")+ - uses: actions/upload-artifact@v7+ with:+ name: macos-archive+ path: dist/*.tar.gz*+ if-no-files-found: error++ # Retrying a partial release upload reuses the exact build bytes (including tar mtimes).+ upload-macos:+ needs: macos-binary+ runs-on: ubuntu-24.04+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@v7+ - uses: actions/download-artifact@v8+ with:+ name: macos-archive+ path: dist- name: Upload to the release- run: gh release upload "$GITHUB_REF_NAME" dist/*.tar.gz dist/*.tar.gz.sha256 --clobber+ run: python3 packaging/release.py upload dist/*.tar.gz dist/*.tar.gz.sha256env:GH_TOKEN: ${{ github.token }}- # The Homebrew formula in Derrors/homebrew-tap, once all three archives are on the release. Pushed with a deploy key- # that can write to that repository only (secret HOMEBREW_TAP_DEPLOY_KEY). Pre-releases (v1.2.3-rc.1) are skipped- homebrew:- needs: [release, macos-binary]+ # Sign the archived bytes that users can already download. Linux signing does+ # not depend on the macOS build. The private key is restricted to this environment.+ sign-linux:+ needs: release+ if: ${{ !contains(github.ref_name, '-') }}+ runs-on: ubuntu-24.04+ environment: release-signing+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@v7+ - uses: actions/download-artifact@v8+ with:+ pattern: bin-*+ path: built+ merge-multiple: true+ - name: Download Linux archives and generate the pinned installer+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ gh release download "$GITHUB_REF_NAME" --pattern '*-linux-*.tar.gz' --dir dist+ for asset in dist/*.tar.gz; do cmp "built/${asset##*/}" "$asset"; done+ python3 packaging/release.py installer dist/install.sh+ - name: Sign Linux manifests+ env:+ ICTL_UPDATE_SIGNING_KEY: ${{ secrets.ICTL_UPDATE_SIGNING_KEY }}+ ICTL_UNATTENDED_TAG: ${{ vars.ICTL_UNATTENDED_TAG }}+ ICTL_ROLLBACK_COMPATIBLE_TAG: ${{ vars.ICTL_ROLLBACK_COMPATIBLE_TAG }}+ ICTL_ROLLBACK_FROM_VERSION: ${{ vars.ICTL_ROLLBACK_FROM_VERSION }}+ run: |+ python3 packaging/release.py sign dist linux-x86_64+ python3 packaging/release.py sign dist linux-aarch64+ - name: Publish signed Linux manifests and installer+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 packaging/release.py upload dist/*.manifest.json* dist/install.sh++ sign-macos:+ needs: upload-macosif: ${{ !contains(github.ref_name, '-') }}runs-on: ubuntu-24.04+ environment: release-signing+ permissions:+ contents: write+ steps:+ - uses: actions/checkout@v7+ - name: Download macOS archive+ uses: actions/download-artifact@v8+ with:+ name: macos-archive+ path: built+ - name: Compare published archive to build+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ gh release download "$GITHUB_REF_NAME" --pattern '*-macos-arm64.tar.gz' --dir dist+ archive="iphone-control-$GITHUB_REF_NAME-macos-arm64.tar.gz"+ cmp "built/$archive" "dist/$archive"+ - name: Sign macOS manifest+ env:+ ICTL_UPDATE_SIGNING_KEY: ${{ secrets.ICTL_UPDATE_SIGNING_KEY }}+ ICTL_UNATTENDED_TAG: ${{ vars.ICTL_UNATTENDED_TAG }}+ ICTL_ROLLBACK_COMPATIBLE_TAG: ${{ vars.ICTL_ROLLBACK_COMPATIBLE_TAG }}+ ICTL_ROLLBACK_FROM_VERSION: ${{ vars.ICTL_ROLLBACK_FROM_VERSION }}+ run: python3 packaging/release.py sign dist macos-arm64+ - name: Publish signed macOS manifest+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 packaging/release.py upload dist/*.manifest.json*++ # The configured tap is updated only after every supported target was signed.+ homebrew:+ needs: [sign-linux, sign-macos]+ if: ${{ !contains(github.ref_name, '-') && vars.ICTL_UPDATE_TAP != '' }}+ runs-on: ubuntu-24.04steps:- uses: actions/checkout@v7- name: Formularun: |- gh release download "$GITHUB_REF_NAME" --pattern '*.tar.gz.sha256' --dir sha- sha() { awk '{print $1}' "sha/iphone-control-${GITHUB_REF_NAME}-$1.tar.gz.sha256"; }- sh packaging/homebrew/formula.sh "$GITHUB_REF_NAME" "$(sha macos-arm64)" "$(sha linux-x86_64)" "$(sha linux-aarch64)" > iphone-control.rb+ gh release download "$GITHUB_REF_NAME" --pattern '*.manifest.json*' --dir signed+ mac=$(python3 packaging/release.py sha signed macos-arm64)+ x86=$(python3 packaging/release.py sha signed linux-x86_64)+ arm=$(python3 packaging/release.py sha signed linux-aarch64)+ sh packaging/homebrew/formula.sh "$GITHUB_REF_NAME" "$mac" "$x86" "$arm" > iphone-control.rbruby -c iphone-control.rbenv:GH_TOKEN: ${{ github.token }}- - name: Push to Derrors/homebrew-tap+ - name: Push to configured Homebrew taprun: |mkdir -p ~/.sshprintf '%s\n' "$DEPLOY_KEY" > ~/.ssh/tap && chmod 600 ~/.ssh/tapexport GIT_SSH_COMMAND="ssh -i ~/.ssh/tap -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"- git clone [email protected]:Derrors/homebrew-tap.git tap+ git clone "[email protected]:${ICTL_UPDATE_TAP%/*}/homebrew-${ICTL_UPDATE_TAP#*/}.git" tapmkdir -p tap/Formula && cp iphone-control.rb tap/Formula/iphone-control.rbcd tapgit config user.name "github-actions[bot]"diff --git a/.gitignore b/.gitignoreindex b466db7..c94eefc 100644--- a/.gitignore+++ b/.gitignore@@ -12,3 +12,6 @@.venv/shots/THIRD_PARTY_LICENSES.html++# Python release tooling+/packaging/__pycache__/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 829aa6a..c442f6c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,15 @@ All notable changes to this project are documented here. The format is based on## [Unreleased]+### Upgrade notes++- For a new script installation, use the `install.sh` asset from your publisher's signed GitHub Release. It requires Python 3 and OpenSSL 3. To migrate an older script installation, stop the service and uninstall it with the original installer, then run the new installer. For 0.2.0, use the original publisher's script at the `v0.2.0` tag and pass `--uninstall` with your original prefix. Your settings and device data are kept.++### Added++- Check for host software updates with `iphone-control update check` or **About & updates** in the viewer. A red dot marks a newer stable release from the build's publisher. Open the panel to see the version and copy the upgrade command for your installation when available.+- User services installed from a signed release can upgrade with `iphone-control update apply` and roll back with `iphone-control update rollback`. They check for updates by default. Opt in with `iphone-control update policy auto-patch` to install signed patches while idle and restore the previous version if the daemon fails its health check.+## [0.2.1] - 2026-11-12### Addeddiff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex d1d0cce..9a0ebbc 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -6,6 +6,15 @@## [Unreleased]+### 升级注意事项++- 使用脚本新装时,请从发布者的已签名 GitHub Release 下载 `install.sh`,需要 Python 3 和 OpenSSL 3。旧版脚本用户请先停止服务,用原安装脚本卸载,再运行新脚本。以 0.2.0 为例,从原发布仓库的 `v0.2.0` 标签取出旧脚本,传入 `--uninstall` 和原安装前缀。设置和设备数据都会保留。++### 新增++- 运行 `iphone-control update check` 或打开控制台的「关于与更新」,可查看当前构建的发布者提供的最新稳定版。发现新版后,Viewer 会在按钮上显示红点。打开面板即可查看版本号,并在有适用命令时一键复制。+- 通过签名发行包的安装脚本部署的用户服务可用 `iphone-control update apply` 升级,用 `iphone-control update rollback` 回滚。默认仅检查更新。运行 `iphone-control update policy auto-patch` 后,服务会在空闲时自动安装签名补丁,新守护进程健康检查失败时恢复旧版本。+## [0.2.1] - 2026-11-12### 新增diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 77a4485..759526b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -85,7 +85,7 @@ The user guide at [derrors.github.io/iphone-control](https://derrors.github.io/i1. Move the *Unreleased* entries in [CHANGELOG.md](CHANGELOG.md) and [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md) under `## [x.y.z] - YYYY-MM-DD` and update the compare links at the bottom. Both files need the section — the release notes are built from the two (English, then Chinese) and the workflow fails if either is missing. Keep entries short: one line per user-visible change, no implementation details.2. Set `version` in the root `Cargo.toml` (`[workspace.package]`) and run `cargo check --workspace` to update `Cargo.lock`.-3. Commit, tag `vx.y.z`, push the tag. [`release.yml`](.github/workflows/release.yml) builds the Linux archives (`iphone-control-vx.y.z-linux-x86_64.tar.gz`, `…-linux-aarch64.tar.gz`) and `.deb` packages (amd64, arm64), each with `THIRD_PARTY_LICENSES.html`, and creates the GitHub release from the two changelog sections. The macOS archive (`…-macos-arm64.tar.gz`) is built afterwards and uploaded to the release; if GitHub has no macOS runner available the job is cancelled after about 15 minutes — re-run just that job. Once all three archives are there, the workflow pushes the formula to [Derrors/homebrew-tap](https://github.com/Derrors/homebrew-tap) (pre-releases such as `v0.2.0-rc.1` are skipped).+3. Configure the publisher, signing keys and supported upgrade path before tagging. Commit, tag `vx.y.z` and push the tag. The release workflow builds the Linux archives and Debian packages, creates the GitHub Release from both changelogs, then adds the Apple Silicon archive. Stable releases also publish the installer and signed platform manifests. If a tap is configured, the workflow updates its formula after signing all three archives. See the [release configuration](docs/dev/release-updates.md) and [release workflow](.github/workflows/release.yml).4. Update Glama: on glama.ai, the build steps under this server's *Admin → Dockerfile* pin the version. Change it and rebuild.By contributing you agree that your contributions are licensed under the MIT license, except for changes to vendored files, which stay under their original licenses.diff --git a/Cargo.lock b/Cargo.lockindex 143f109..b16ff1d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1959,6 +1959,7 @@ dependencies = ["ictl-wda","ictl-webinspector","image",+ "libc","reqwest 0.13.5","serde","serde_json",@@ -2273,7 +2274,9 @@ name = "iphone-control"version = "0.2.1"dependencies = ["anyhow",+ "chrono","clap",+ "flate2","ictl-daemon","ictl-device","ictl-l10n",@@ -2281,8 +2284,16 @@ dependencies = ["ictl-sign","ictl-wda","libc",+ "plist",+ "reqwest 0.13.5",+ "ring","rustls",+ "semver",+ "serde","serde_json",+ "sha2 0.10.9",+ "tar",+ "tempfile","tokio","tracing","tracing-subscriber",@@ -4554,6 +4565,16 @@ version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"+[[package]]+name = "tar"+version = "0.4.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"+dependencies = [+ "filetime",+ "libc",+]+[[package]]name = "tempfile"version = "3.27.0"diff --git a/README.md b/README.mdindex f8b7fb8..411d0a0 100644--- a/README.md+++ b/README.md@@ -66,13 +66,15 @@ iphone-control does it all in **one Rust binary** on Linux or macOS, built on [iYou need an iPhone or iPad on iOS 17+ connected by a **data** cable, a free Apple ID (use a dedicated one), and an Apple Silicon Mac or a Linux machine.-**macOS or Linux, one command**+**macOS or Linux, one command** (upstream example; for a fork, use the installer asset from its own signed release)```bash-curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh```-It downloads the release for your machine, checks its sha256, installs `iphone-control` into `~/.local/bin` and runs the daemon as a per-user service that starts at login (launchd on macOS, systemd on Linux). It never runs as root. Run it again to upgrade; `… | sh -s -- --uninstall` removes it and keeps your data.+It downloads the release for your machine, verifies the Ed25519 release manifest and archive SHA-256 (Python 3 and OpenSSL 3 required), installs `iphone-control` into `~/.local/bin` and runs the daemon as a per-user service that starts at login (launchd on macOS, systemd on Linux). Run it as your regular user. Use `iphone-control update apply` to upgrade this managed service. Running `sh iphone-control-install.sh --uninstall` removes it and keeps your data.++Upstream v0.2.0 predates the signed installer. To install that release or migrate an existing script installation, follow the [v0.2.0 instructions](https://derrors.github.io/iphone-control/en/guide/getting-started#legacy-script).**Or with a package manager**@@ -148,7 +150,7 @@ Tool texts, results, CLI output and logs are in Simplified Chinese by default; sAll commands and options: [CLI reference](https://derrors.github.io/iphone-control/en/guide/cli).-Upgrade by running `install.sh` again, with `brew upgrade iphone-control`, or by installing the new `.deb`; for a source build, see [build from source](https://derrors.github.io/iphone-control/en/deploy/source). Read the upgrade notes in the [changelog](CHANGELOG.md) first. Uninstall with `install.sh --uninstall`, `brew uninstall iphone-control` or `sudo apt remove iphone-control`; your data stays. Settings live in `~/.config/iphone-control/env`: the guide writes it, and after editing it by hand run `iphone-control service restart` — see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration). All state lives in `~/.local/share/iphone-control`: the Apple ID session and signing key, and the passcode if auto-unlock is on. **Back it up; never commit or share it.**+Check in Viewer → **About & updates** or run `iphone-control update check --json`. For a managed user service, use `iphone-control update apply`. To opt in to signed patches when no device clients or tasks are active, use `iphone-control update policy auto-patch`; return to background checks with `iphone-control update policy notify`. Other channels upgrade with `brew upgrade iphone-control`, or by installing the new `.deb`; for a source build, see [build from source](https://derrors.github.io/iphone-control/en/deploy/source). Read the upgrade notes in the [changelog](CHANGELOG.md) first. Uninstall with `sh iphone-control-install.sh --uninstall`, `brew uninstall iphone-control` or `sudo apt remove iphone-control`; your data stays. Settings live in `~/.config/iphone-control/env`: the guide writes it, and after editing it by hand run `iphone-control service restart` — see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration). All state lives in `~/.local/share/iphone-control`: the Apple ID session and signing key, and the passcode if auto-unlock is on. **Back it up; never commit or share it.**## Documentationdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex a286979..0cb5dbd 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -68,11 +68,15 @@ iphone-control 在 Linux 或 macOS 上用**一个 Rust 二进制**把这些事**macOS 或 Linux,一行命令安装**+以下为上游示例;使用 fork 时,从该 fork 的签名发行版获取安装脚本。+```bash-curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh```-它会下载适合这台机器的版本、校验 sha256,把 `iphone-control` 装到 `~/.local/bin`,并把守护进程装成登录后自动启动的用户服务(macOS 用 launchd,Linux 用 systemd)。它不会以 root 运行。再运行一次就是升级;`… | sh -s -- --uninstall` 卸载,数据保留。国内网络下载 Release 慢的话,先在终端里设好 `HTTPS_PROXY` 再运行。+安装器会下载适合这台机器的版本,用 Python 3 和 OpenSSL 3 验证发行清单签名和安装包 SHA-256,把 `iphone-control` 装到 `~/.local/bin`,并把守护进程装成登录后自动启动的用户服务(macOS 用 launchd,Linux 用 systemd)。以普通用户运行。受管服务用 `iphone-control update apply` 升级,用 `sh iphone-control-install.sh --uninstall` 卸载,数据保留。国内网络下载 Release 慢的话,先在终端里设好 `HTTPS_PROXY` 再运行。++上游 v0.2.0 发布时还没有签名安装器。安装该版本,或从已有的脚本安装迁移,请按 [v0.2.0 安装与迁移说明](https://derrors.github.io/iphone-control/guide/getting-started#legacy-script)操作。**或者用包管理器**@@ -148,7 +152,7 @@ iphone-control全部命令和参数见[命令行](https://derrors.github.io/iphone-control/guide/cli)。-升级:再运行一次 `install.sh`、`brew upgrade iphone-control`,或装上新的 `.deb`;从源码编译的见[从源码编译](https://derrors.github.io/iphone-control/deploy/source)。升级前先看[更新日志](CHANGELOG.zh-CN.md)里的升级注意事项。卸载:`install.sh --uninstall`、`brew uninstall iphone-control` 或 `sudo apt remove iphone-control`,数据保留。设置在 `~/.config/iphone-control/env`,由设置引导写好;手改后运行 `iphone-control service restart`,见[配置说明](https://derrors.github.io/iphone-control/guide/configuration)。所有状态都在 `~/.local/share/iphone-control`:Apple ID 会话和签名私钥,开启自动解锁时还有锁屏密码。**要备份,不要提交或分享。**+在 Viewer「关于与更新」或通过 `iphone-control update check --json` 检查。受管用户服务用 `iphone-control update apply` 升级。需要空闲时自动安装签名补丁,可主动运行 `iphone-control update policy auto-patch`。用 `iphone-control update policy notify` 恢复为只检查。其他渠道:`brew upgrade iphone-control`,或装上新的 `.deb`;从源码编译的见[从源码编译](https://derrors.github.io/iphone-control/deploy/source)。升级前先看[更新日志](CHANGELOG.zh-CN.md)里的升级注意事项。卸载:`sh iphone-control-install.sh --uninstall`、`brew uninstall iphone-control` 或 `sudo apt remove iphone-control`,数据保留。设置在 `~/.config/iphone-control/env`,由设置引导写好;手改后运行 `iphone-control service restart`,见[配置说明](https://derrors.github.io/iphone-control/guide/configuration)。所有状态都在 `~/.local/share/iphone-control`:Apple ID 会话和签名私钥,开启自动解锁时还有锁屏密码。**要备份,不要提交或分享。**## 文档diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex 445af2b..f025774 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -20,7 +20,17 @@ clap.workspace = truetokio.workspace = trueanyhow.workspace = truerustls.workspace = true+reqwest.workspace = true+serde.workspace = trueserde_json.workspace = true+sha2.workspace = true+plist.workspace = true+semver = "=1.0.28"+tempfile = "=3.27.0"+chrono = { version = "=0.4.45", default-features = false, features = ["std"] }+flate2 = "=1.1.10"+ring = "=0.17.14"+tar = { version = "=0.4.46", default-features = false }uuid.workspace = truelibc.workspace = truetracing.workspace = truediff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex 4c23076..0f33ce0 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -18,7 +18,9 @@ mod agent;mod debug;mod envfile;mod guide;+mod schedule;mod service;+mod update;mod video;mod viewer;@@ -38,6 +40,11 @@ struct Cli {#[derive(Subcommand)]enum Command {+ #[command(about = ictl_l10n::tr!("检查和管理主机软件更新", "Check for and manage host software updates"))]+ Update {+ #[command(subcommand)]+ action: UpdateAction,+ },#[command(about = ictl_l10n::tr!("常驻守护进程(安装时装成用户服务:macOS 是 launchd,Linux 是 systemd;也可以手动启动)", "The long-running daemon (installed as a user service: launchd on macOS, systemd on Linux; can also be started by hand)"))]Daemon,#[command(about = ictl_l10n::tr!("MCP stdio 服务(由 agent 拉起)", "MCP stdio server (started by the agent)"))]@@ -106,6 +113,32 @@ enum Command {},}+#[derive(Subcommand)]+enum UpdateAction {+ /// Check the latest stable release for this build and installation+ Check {+ #[arg(long)]+ json: bool,+ },+ /// Save the local update policy and configure its user job+ Policy { policy: update::Policy },+ /// Install a verified compatible release (managed user service only)+ Apply,+ /// Release an explicit installer version pin without enabling automatic updates+ Unpin,+ /// Restore the verified previous executable+ Rollback,+ /// Recover an interrupted replacement+ Recover {+ #[arg(long, hide = true)]+ scheduled: bool,+ },+ #[command(hide = true)]+ Schedule,+ #[command(hide = true)]+ Run,+}+#[derive(Subcommand)]enum ServiceAction {#[command(about = ictl_l10n::tr!("装成登录后自动启动的后台服务并启动(已有就直接启动)", "Set up the service that starts at login and start it (just start it if it exists)"))]@@ -159,8 +192,15 @@ async fn run() -> anyhow::Result<()> {.with_env_filter(filter).init();+ // Lifetime clients hold this through pauses and confirmations, and direct-device CLI+ // commands participate even when they bypass the daemon.+ let _client = match &cli.command {+ Some(Command::Daemon | Command::Update { .. } | Command::McpConfig | Command::Status) => None,+ _ => Some(ictl_daemon::maintenance::shared()?),+ };let Some(command) = cli.command.take() else { return guide::first_run(&cli).await };match command {+ Command::Update { action } => update_command(action, &cli.socket).await,Command::Daemon => {let mut cfg = ictl_daemon::Config::from_env(&cli.data_dir);cfg.socket = cli.socket;@@ -190,6 +230,46 @@ async fn run() -> anyhow::Result<()> {}}+async fn report_daemon(report: &mut update::Report, socket: &Path) {+ report.daemon_version = tokio::time::timeout(Duration::from_secs(1), snapshot(socket))+ .await+ .ok()+ .and_then(Result::ok)+ .and_then(|s| s.version);+}++async fn update_command(action: UpdateAction, socket: &Path) -> anyhow::Result<()> {+ use update::transaction;+ match action {+ UpdateAction::Check { json } => {+ let mut report = update::check(false).await?;+ report_daemon(&mut report, socket).await;+ if json {+ println!("{}", serde_json::to_string_pretty(&report)?);+ } else {+ println!("{report}");+ }+ if let Some(code) = report.error_code {+ bail!("Update check failed: {code}")+ }+ Ok(())+ }+ UpdateAction::Policy { policy } => schedule::set_policy(socket, policy),+ UpdateAction::Schedule => schedule::configure(socket),+ UpdateAction::Apply => transaction::apply(socket, false).await,+ UpdateAction::Unpin => transaction::unpin(),+ UpdateAction::Rollback => transaction::rollback(socket).await,+ UpdateAction::Recover { scheduled } => transaction::recover(socket, scheduled).await,+ UpdateAction::Run => {+ let report = update::check(true).await?;+ if report.automatic_patch() {+ transaction::apply(socket, true).await?;+ }+ Ok(())+ }+ }+}+async fn notify_test(data_dir: &Path, only: Option<&str>) -> anyhow::Result<()> {use ictl_daemon::notify::{Event, send};let cfg = ictl_daemon::Config::from_env(data_dir).notify;diff --git a/apps/iphone-control/src/schedule.rs b/apps/iphone-control/src/schedule.rsnew file mode 100644index 0000000..31979aa--- /dev/null+++ b/apps/iphone-control/src/schedule.rs@@ -0,0 +1,290 @@+//! Run checks outside the daemon so that stopping the daemon cannot kill its updater.+//! The launcher selects the *old* executable for crash recovery, even if the new one cannot start.+use std::fs::{self, File};+use std::os::fd::AsRawFd;+use std::os::unix::fs::OpenOptionsExt;+use std::path::Path;+use std::process::Command;++use anyhow::{Context, Result, bail, ensure};++use crate::{envfile, service, shell_quote, update};++const LABEL: &str = "io.github.iphone-control.updates";+const TIMER: &str = "iphone-control-updates.timer";+const UNIT: &str = "iphone-control-updates.service";++pub fn set_policy(socket: &Path, policy: update::Policy) -> Result<()> {+ let _locks = configuration_locks()?;+ update::set_policy(policy)?;+ if let Err(e) = configure_job(socket, policy) {+ // A partial timer install must not later run with unintended permission to replace files.+ update::set_policy(update::Policy::Manual)?;+ bail!("Update policy is manual; could not configure the user job: {e:#}")+ }+ println!(+ "{}: {}",+ ictl_l10n::tr!("更新策略", "Update policy"),+ serde_json::to_value(policy)?.as_str().unwrap_or("manual")+ );+ Ok(())+}++// Keep concurrent policy writes and service-manager changes in the same order. The shared+// maintenance lease also prevents launchctl bootout from terminating an active replacement.+fn configuration_locks() -> Result<(File, File)> {+ let config = envfile::config_dir();+ fs::create_dir_all(&config)?;+ let lock = File::options()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW)+ .open(config.join("update-schedule.lock"))?;+ if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 {+ return Err(std::io::Error::last_os_error()).context("could not lock the update schedule");+ }+ Ok((lock, ictl_daemon::maintenance::shared()?))+}++pub fn configure(socket: &Path) -> Result<()> {+ let _locks = configuration_locks()?;+ configure_job(socket, update::cached()?.policy)+}++fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {+ fs::create_dir_all(path.parent().context("invalid job path")?)?;+ crate::update::write_atomic(path, bytes)+}++fn run(program: &str, args: &[&str]) -> Result<()> {+ let output = Command::new(program).args(args).output()?;+ ensure!(+ output.status.success(),+ "{program} {}: {}",+ args.join(" "),+ String::from_utf8_lossy(&output.stderr).trim()+ );+ Ok(())+}++fn path_str(path: &Path) -> Result<&str> {+ let s = path.to_str().context("non UTF-8 update job path")?;+ ensure!(path.is_absolute() && !s.contains(['\r', '\n']), "expected an absolute update job path");+ Ok(s)+}++fn launcher(exe: &Path, socket: &Path, config: &Path) -> Result<String> {+ let exe = shell_quote(path_str(exe)?);+ let sock = shell_quote(path_str(socket)?);+ let xdg = shell_quote(path_str(config.parent().context("missing config home")?)?);+ // launchd and the interactive shell often have different XDG environments. The timer+ // must see the same release cache as Viewer, including a custom cache location.+ let mut xdg_env = String::new();+ for name in ["XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_RUNTIME_DIR"] {+ if let Some(value) = std::env::var_os(name).filter(|v| !v.is_empty()) {+ let value = shell_quote(path_str(Path::new(&value))?);+ xdg_env.push_str(&format!("export {name}={value}\n"));+ }+ }+ Ok(format!(+ "#!/bin/sh\n# iphone-control update job\nexe={exe}\nsocket={sock}\nexport XDG_CONFIG_HOME={xdg}\n{xdg_env}\+ state=\"${{exe%/*}}/.iphone-control-update\"\n\+ if [ -f \"$state/transaction.json\" ]; then exec \"$state/recovery\" --socket \"$socket\" update recover --scheduled; fi\n\+ exec \"$exe\" --socket \"$socket\" update run\n"+ ))+}++fn systemd_path(path: &Path) -> Result<String> {+ Ok(format!(+ "\"{}\"",+ path_str(path)?.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%").replace('$', "$$")+ ))+}++fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> {+ let config = envfile::config_dir();+ let launcher_file = config.join("update-job.sh");+ let mac = cfg!(target_os = "macos");+ let jobs = if mac {+ envfile::home().join("Library/LaunchAgents")+ } else {+ config.parent().context("missing config home")?.join("systemd/user")+ };+ let job = jobs.join(if mac { format!("{LABEL}.plist") } else { UNIT.into() });+ let timer = jobs.join(TIMER);+ let owner = format!("exe={}", shell_quote(path_str(&service::stable_exe()?)?));+ let enabled = policy != update::Policy::Manual;+ // A second checkout or a stale PATH entry must not remove or hijack another installation's job.+ if launcher_file.try_exists()? {+ ensure!(+ fs::read_to_string(&launcher_file)?.lines().nth(2) == Some(owner.as_str()),+ "the updater job belongs to a different executable"+ );+ } else {+ ensure!(!job.try_exists()? && (mac || !timer.try_exists()?), "an unrecognized update job already exists");+ if !enabled {+ return Ok(());+ }+ }+ ensure!(!ictl_daemon::protocol::running_as_root(), "only user update jobs are supported");+ if enabled {+ write_file(&launcher_file, launcher(&service::stable_exe()?, socket, &config)?.as_bytes())?;+ }+ if mac {+ let domain = format!("gui/{}", unsafe { libc::geteuid() });+ let id = format!("{domain}/{LABEL}");+ let loaded = Command::new("launchctl").args(["print", &id]).env("LC_ALL", "C").output()?;+ let loaded = if loaded.status.success() {+ let listing = std::str::from_utf8(&loaded.stdout)?;+ let path = listing.lines().find_map(|line| line.strip_prefix('\t')?.strip_prefix("path = "));+ ensure!(path.map(Path::new) == Some(&job), "launchd loaded a different updater plist");+ true+ } else {+ false+ };+ if enabled {+ let mut xml = Vec::new();+ plist::to_writer_xml(+ &mut xml,+ &serde_json::json!({+ "Label": LABEL, "ProgramArguments": ["/bin/sh", path_str(&launcher_file)?],+ "StartInterval": 3600, "RunAtLoad": true,+ }),+ )?;+ if loaded && job.try_exists()? && fs::read(&job)? == xml {+ return Ok(());+ }+ if loaded {+ run("launchctl", &["bootout", &id])?;+ }+ write_file(&job, &xml)?;+ run("launchctl", &["bootstrap", &domain, path_str(&job)?])?;+ } else if loaded {+ run("launchctl", &["bootout", &id])?;+ }+ } else if enabled {+ let unit = format!(+ "[Unit]\nDescription=Check iphone-control updates\n[Service]\nType=oneshot\nExecStart=/bin/sh {}\n",+ systemd_path(&launcher_file)?+ );+ write_file(&job, unit.as_bytes())?;+ write_file(&timer, b"[Unit]\nDescription=Check iphone-control updates when due\n[Timer]\nOnActiveSec=1min\nOnUnitActiveSec=1h\n[Install]\nWantedBy=timers.target\n")?;+ run("systemctl", &["--user", "daemon-reload"])?;+ run("systemctl", &["--user", "enable", "--now", TIMER])?;+ } else if timer.try_exists()? {+ // Do not stop an already-running replacement. Manual prevents the next one.+ run("systemctl", &["--user", "disable", "--now", TIMER])?;+ }+ if !enabled {+ let mut files = vec![job, launcher_file];+ if !mac {+ files.push(timer);+ }+ for f in files {+ if f.try_exists()? {+ fs::remove_file(f)?;+ }+ }+ if !mac {+ run("systemctl", &["--user", "daemon-reload"])?;+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::os::unix::fs::PermissionsExt;++ #[test]+ fn configuration_worker() {+ let Some(test_home) = std::env::var_os("ICTL_TEST_SCHEDULE_HOME") else { return };+ let home = Path::new(&test_home);+ assert_eq!(envfile::home(), home);+ let socket = home.join("daemon.sock");+ let lease = ictl_daemon::maintenance::exclusive().unwrap();+ assert!(configure(&socket).is_err());+ assert!(set_policy(&socket, update::Policy::Manual).is_err());+ assert!(!envfile::config_dir().join("update-job.sh").exists());+ drop(lease);++ configure_job(&socket, update::Policy::Notify).unwrap();+ configure_job(&socket, update::Policy::Notify).unwrap();+ let calls = fs::read_to_string(home.join("manager.log")).unwrap();+ assert!(!calls.contains("bootout") && !calls.contains("disable"));+ if cfg!(target_os = "macos") {+ assert_eq!(calls.matches("bootstrap").count(), 1);+ }+ }++ #[test]+ fn configuring_jobs_respects_maintenance_and_leaves_an_active_job_running() {+ if ictl_daemon::protocol::running_as_root() {+ return;+ }+ let temp = tempfile::tempdir().unwrap();+ let home = temp.path();+ let (name, script) = if cfg!(target_os = "macos") {+ (+ "launchctl",+ r#"#!/bin/sh+echo "$1" >> "$HOME/manager.log"+case "$1" in+print) [ -f "$HOME/loaded" ] || exit 1+ printf '\tpath = %s\n' "$HOME/Library/LaunchAgents/io.github.iphone-control.updates.plist" ;;+bootstrap) : > "$HOME/loaded";;+*) exit 1;;+esac+"#,+ )+ } else {+ ("systemctl", "#!/bin/sh\necho \"$*\" >> \"$HOME/manager.log\"\n")+ };+ let manager = home.join(name);+ fs::write(&manager, script).unwrap();+ fs::set_permissions(&manager, fs::Permissions::from_mode(0o700)).unwrap();+ let status = Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "schedule::tests::configuration_worker"])+ .env("HOME", home)+ .env("ICTL_TEST_SCHEDULE_HOME", home)+ .env("XDG_CONFIG_HOME", home.join("config"))+ .env("PATH", home)+ .status()+ .unwrap();+ assert!(status.success());+ }++ #[test]+ fn launcher_can_recover_without_starting_a_broken_installed_binary() {+ let temp = tempfile::tempdir().unwrap();+ let dir = temp.path().join("test's prefix");+ let state = dir.join(".iphone-control-update");+ fs::create_dir_all(&state).unwrap();+ let socket = dir.join("other socket");+ let exe = dir.join("iphone-control");+ let config = dir.join("xdg/iphone-control");+ let script = launcher(&exe, &socket, &config).unwrap();+ let set_program = |p: &Path| {+ fs::write(p, "#!/bin/sh\nprintf '%s\\n' \"$@\" \"$XDG_CONFIG_HOME\"\n").unwrap();+ fs::set_permissions(p, fs::Permissions::from_mode(0o700)).unwrap();+ };+ set_program(&exe);+ let invoke = || {+ let result = Command::new("/bin/sh").args(["-c", &script]).output().unwrap();+ assert!(result.status.success());+ String::from_utf8(result.stdout).unwrap()+ };+ assert_eq!(+ invoke(),+ format!("--socket\n{}\nupdate\nrun\n{}\n", socket.display(), config.parent().unwrap().display())+ );+ fs::write(state.join("transaction.json"), "{}").unwrap();+ fs::remove_file(exe).unwrap();+ set_program(&state.join("recovery"));+ assert!(invoke().contains("\nupdate\nrecover\n--scheduled\n"));+ }+}diff --git a/apps/iphone-control/src/service.rs b/apps/iphone-control/src/service.rsindex 42bef3b..504319e 100644--- a/apps/iphone-control/src/service.rs+++ b/apps/iphone-control/src/service.rs@@ -6,10 +6,11 @@//! commands act on whichever is there. The service reads `~/.config/iphone-control/env`, starts at login and is//! restarted after a crash.+use std::os::unix::fs::MetadataExt;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};-use anyhow::{Context, bail};+use anyhow::{Context, bail, ensure};use crate::envfile::home;@@ -106,6 +107,124 @@ pub fn find() -> Option<Service> {None}+/// Identify the user service recorded by the script installer. Package-managed services have+/// their own upgrade lifecycle, even when they use the same systemd unit name.+pub fn managed(exe: &Path, method: &str) -> anyhow::Result<Service> {+ let (file, service) = match method {+ "launchd" if cfg!(target_os = "macos") => {+ (our_plist(), Service::Launchd { label: LABEL.into(), plist: our_plist(), ours: true })+ }+ "systemd" if cfg!(target_os = "linux") => (our_unit(), Service::Systemd { unit: UNIT.into(), ours: true }),+ _ => bail!("a script-managed user service is required"),+ };+ let meta = file.symlink_metadata()?;+ ensure!(meta.is_file() && meta.uid() == uid() && meta.mode() & 0o022 == 0, "untrusted service file");+ let exe = exe.to_str().context("invalid executable path")?;+ match &service {+ Service::Launchd { label, .. } => {+ let plist = plist::Value::from_file(&file)?;+ let dict = plist.as_dictionary().context("invalid service plist")?;+ let args = dict.get("ProgramArguments").and_then(|v| v.as_array()).context("missing service arguments")?;+ let script = format!(+ r#"set -a; f="$HOME/.config/iphone-control/env"; [ -f "$f" ] && . "$f"; set +a; exec "{exe}" daemon"#+ );+ ensure!(+ dict.get("Label").and_then(|v| v.as_string()) == Some(label.as_str())+ && !dict.contains_key("Program")+ && (args.iter().map(|v| v.as_string()).eq([Some(exe), Some("daemon")])+ || args.iter().map(|v| v.as_string()).eq([Some("/bin/sh"), Some("-c"), Some(script.as_str())])),+ "the launch agent does not start the recorded binary"+ );+ }+ Service::Systemd { .. } => {+ let unit = std::fs::read_to_string(&file)?;+ let mut commands = unit.lines().filter_map(|line| line.trim().strip_prefix("ExecStart="));+ let command = commands.next().context("missing ExecStart")?;+ ensure!(+ commands.next().is_none()+ && (command == format!(r#""{exe}" daemon"#)+ || (!exe.contains(char::is_whitespace) && command == format!("{exe} daemon"))),+ "the systemd unit does not start the recorded binary"+ );+ }+ }+ Ok(service)+}++/// The effective service owner matters during replacement. A foreground daemon can answer the+/// same socket. Reject transitional manager states and stale/overridden user service definitions.+pub fn managed_pid(service: &Service, stopping: bool) -> anyhow::Result<Option<u32>> {+ match service {+ Service::Launchd { label, plist, .. } => {+ let out = Command::new("launchctl")+ .args(["print", &format!("gui/{}/{label}", uid())])+ .env("LC_ALL", "C")+ .output()?;+ if !out.status.success() {+ ensure!(+ String::from_utf8_lossy(&out.stderr).contains("Could not find service"),+ "cannot query launchd"+ );+ return Ok(None);+ }+ launchd_pid(std::str::from_utf8(&out.stdout)?, plist, stopping)+ }+ Service::Systemd { unit, .. } => {+ let out = Command::new("systemctl")+ .args([+ "--user",+ "show",+ unit,+ "--all", // include an empty DropInPaths (absence is not proof of ownership)+ "--property=ActiveState,LoadState,MainPID,FragmentPath,DropInPaths,NeedDaemonReload",+ ])+ .output()?;+ ensure!(out.status.success(), "cannot query systemd user service");+ let info = std::str::from_utf8(&out.stdout)?;+ let field = |key: &str| info.lines().find_map(|line| line.strip_prefix(key));+ ensure!(+ field("LoadState=") == Some("loaded")+ && field("NeedDaemonReload=") == Some("no")+ && field("FragmentPath=").map(Path::new) == Some(our_unit().as_path())+ && field("DropInPaths=") == Some(""),+ "systemd unit is stale or overridden"+ );+ match (field("ActiveState="), field("MainPID=")) {+ (Some("inactive" | "failed"), Some("0")) => Ok(None),+ (Some("active"), Some(pid)) => {+ Ok(Some(pid.parse::<u32>().ok().filter(|p| *p > 0).context("missing MainPID")?))+ }+ (_, Some(pid)) if stopping => Ok(pid.parse::<u32>().ok().filter(|p| *p > 0)),+ _ => bail!("systemd service is transitioning"),+ }+ }+ }+}++/// The daemon's PID from `launchctl print`: `None` when the job is loaded but not running. With+/// `KeepAlive={SuccessfulExit:false}` launchd leaves a daemon that exited cleanly (SIGTERM, `kill`) that way,+/// with no PID, for good: like an inactive systemd unit, it is stopped, not transitioning+fn launchd_pid(info: &str, plist: &Path, stopping: bool) -> anyhow::Result<Option<u32>> {+ let field = |key: &str| info.lines().find_map(|line| line.strip_prefix('\t')?.strip_prefix(key));+ ensure!(field("path = ").map(Path::new) == Some(plist), "launchd loaded a different plist");+ let pid = field("pid = ");+ if pid.is_none() && (stopping || field("state = ") == Some("not running")) {+ return Ok(None);+ }+ ensure!(stopping || field("state = ") == Some("running"), "launchd service is transitioning");+ Ok(Some(pid.context("no launchd PID")?.parse()?))+}++/// Restart exactly the service we stopped without changing the user's enable-at-login setting.+pub fn start_managed(s: &Service) -> anyhow::Result<()> {+ if let Service::Systemd { unit, .. } = s {+ ensure!(systemctl(&["start", unit]), "could not start systemd user service");+ Ok(())+ } else {+ start(s)+ }+}+fn launchd_loaded(label: &str) -> bool {run(Command::new("launchctl").arg("print").arg(format!("gui/{}/{label}", uid())))}@@ -275,6 +394,25 @@ pub fn uninstall() -> anyhow::Result<()> {mod tests {use super::*;+ /// `launchctl print` as macOS 27 shows it for a job with KeepAlive={SuccessfulExit:false}: running, and+ /// after the program exited with status 0 (loaded, not running, no PID)+ #[test]+ fn launchd_job_that_exited_cleanly_is_stopped() {+ let plist = Path::new("/Users/u/Library/LaunchAgents/io.github.derrors.iphone-control.plist");+ let print = |state: &str, pid: Option<u32>| {+ let pid = pid.map(|p| format!("\tpid = {p}\n")).unwrap_or_default();+ format!(+ "gui/501/io.github.derrors.iphone-control = {{\n\tpath = {}\n\tstate = {state}\n{pid}\tlast exit code = 0\n}}\n",+ plist.display()+ )+ };+ assert_eq!(launchd_pid(&print("running", Some(4242)), plist, false).unwrap(), Some(4242));+ assert_eq!(launchd_pid(&print("not running", None), plist, false).unwrap(), None, "exited cleanly");+ assert_eq!(launchd_pid(&print("not running", None), plist, true).unwrap(), None);+ assert!(launchd_pid(&print("spawn scheduled", None), plist, false).is_err(), "really transitioning");+ assert!(launchd_pid(&print("running", Some(1)), Path::new("/elsewhere.plist"), false).is_err());+ }+#[test]fn homebrew_paths_use_the_opt_link() {assert_eq!(diff --git a/apps/iphone-control/src/update.rs b/apps/iphone-control/src/update.rsnew file mode 100644index 0000000..c6a4214--- /dev/null+++ b/apps/iphone-control/src/update.rs@@ -0,0 +1,733 @@+//! Host program updates. Only release builds explicitly bound to a GitHub publisher+//! contact the release API. CLI and Viewer use the same local cache and channel evidence.+mod archive;+mod install;+mod release;+pub mod transaction;++use std::cmp::Ordering;+use std::fmt;+use std::fs;+use std::path::{Path, PathBuf};++use anyhow::{Result, ensure};+use ictl_l10n::{tr, trf};+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};++use install::Installation;+pub use install::{Receipt, digest, read_receipt, receipt_path, validate_receipt};+use release::{Cache, Release};++const VERSION: &str = env!("CARGO_PKG_VERSION");++fn repository(s: &str) -> bool {+ // Same slug grammar as the signed installer and release workflow.+ let part = |v: &str, extra: &[u8]| {+ v.as_bytes().first().is_some_and(u8::is_ascii_alphanumeric)+ && v.bytes().all(|b| b.is_ascii_alphanumeric() || extra.contains(&b))+ };+ s.split_once('/').is_some_and(|(owner, repo)| part(owner, b"-") && part(repo, b"-_."))+}++pub fn publisher() -> Option<&'static str> {+ option_env!("ICTL_UPDATE_PUBLISHER").filter(|s| repository(s))+}++fn tap() -> Option<&'static str> {+ option_env!("ICTL_UPDATE_TAP").filter(|s| repository(s))+}++pub fn target() -> Option<&'static str> {+ match (std::env::consts::OS, std::env::consts::ARCH) {+ ("macos", "aarch64") => Some("macos-arm64"),+ ("linux", "aarch64") if cfg!(target_env = "gnu") => Some("linux-aarch64"),+ ("linux", "x86_64") if cfg!(target_env = "gnu") => Some("linux-x86_64"),+ _ => None,+ }+}++#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum InstallMethod {+ Development,+ Managed,+ Script,+ Homebrew,+ Debian,+ Unknown,+}++#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]+#[serde(rename_all = "kebab-case")]+pub enum Policy {+ Manual,+ Notify,+ AutoPatch,+}++#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Availability {+ Development,+ Unchecked,+ Current,+ Ahead,+ Available,+ PlatformPending,+ Unsupported,+ BrewCheck,+ ManualOnly,+}++#[derive(Serialize)]+pub struct Report {+ pub running_version: &'static str,+ pub daemon_version: Option<String>,+ pub installed_version: Option<String>,+ pub publisher: Option<&'static str>,+ pub target: Option<&'static str>,+ pub executable: Option<PathBuf>,+ pub install_method: InstallMethod,+ pub policy: Policy,+ pub pinned: Option<bool>,+ pub available_version: Option<String>,+ pub availability: Availability,+ pub last_success_at: Option<u64>,+ pub last_attempt_at: Option<u64>,+ pub retry_after: Option<u64>,+ pub error_code: Option<String>,+ pub published_at: Option<String>,+ pub release_url: Option<String>,+ pub guidance: String,+ pub upgrade_command: Option<String>,+ pub last_update: Option<transaction::Outcome>,+}++impl Report {+ pub fn automatic_patch(&self) -> bool {+ self.policy == Policy::AutoPatch+ && self.error_code.is_none()+ && self.availability == Availability::Available+ && self.available_version.as_deref().is_some_and(|v| {+ transaction::eligible(self.installed_version.as_deref().unwrap_or(self.running_version), v, true)+ .is_ok()+ })+ }+}++/// Writes `bytes` to `path` atomically and durably: a temporary file in the same directory, synced, renamed over+/// `path`, then the directory synced. The directory must exist: callers create it with the permissions it needs+/// (the updater's store is private and checked, see `transaction::Store::open`)+pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {+ use std::io::Write;+ let dir = path.parent().ok_or_else(|| anyhow::anyhow!("no parent directory: {}", path.display()))?;+ let mut tmp = tempfile::NamedTempFile::new_in(dir)?;+ tmp.write_all(bytes)?;+ tmp.as_file().sync_all()?;+ tmp.persist(path)?;+ fs::File::open(dir)?.sync_all()?;+ Ok(())+}++/// [`write_atomic`] of `value` as JSON+pub(crate) fn write_json_atomic(path: &Path, value: &impl Serialize) -> Result<()> {+ write_atomic(path, &serde_json::to_vec(value)?)+}++fn state_dir(repo: &str) -> PathBuf {+ std::env::var_os("XDG_CACHE_HOME")+ .filter(|s| !s.is_empty())+ .map(PathBuf::from)+ .unwrap_or_else(|| crate::envfile::home().join(".cache"))+ .join("iphone-control/updates")+ .join(repo)+ .join(target().unwrap_or("unsupported"))+}++fn policy_file(repo: &str, exe: &Path, method: InstallMethod) -> PathBuf {+ // A verified keg is Cellar/formula/version/bin/iphone-control. Its formula+ // directory survives upgrades and still distinguishes separate installations.+ let installation = if method == InstallMethod::Homebrew { exe.ancestors().nth(3).unwrap_or(exe) } else { exe };+ let id = Sha256::digest(installation.as_os_str().as_encoded_bytes());+ crate::envfile::config_dir().join("updates").join(repo).join(format!("{id:x}.json"))+}++fn policy(repo: Option<&str>, exe: Option<&Path>, installation: &Installation) -> Result<Policy> {+ let (Some(repo), Some(exe)) = (repo, exe) else { return Ok(Policy::Manual) };+ read_policy(&policy_file(repo, exe, installation.method), installation)+}++fn read_policy(file: &Path, installation: &Installation) -> Result<Policy> {+ let saved: Policy = match fs::read(file) {+ Ok(bytes) => serde_json::from_slice(&bytes)?,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ return Ok(if installation.method == InstallMethod::Managed { Policy::Notify } else { Policy::Manual });+ }+ Err(e) => return Err(e.into()),+ };+ if saved == Policy::AutoPatch+ && (installation.method != InstallMethod::Managed || installation.pinned != Some(false))+ {+ return Ok(Policy::Manual);+ }+ Ok(saved)+}++pub fn set_policy(value: Policy) -> Result<()> {+ let Some(repo) = publisher() else {+ ensure!(+ value == Policy::Manual,+ "{}",+ tr!("开发构建没有绑定发布者", "Development build has no bound publisher")+ );+ return Ok(());+ };+ let exe = std::env::current_exe()?.canonicalize()?;+ let installation = install::detect(Some(&exe));+ if value == Policy::AutoPatch {+ ensure!(+ installation.method == InstallMethod::Managed && installation.pinned == Some(false),+ "{}",+ tr!("自动补丁更新需要未固定版本的受管用户服务", "Auto-patch requires an unpinned, managed user service")+ );+ }+ release::write_json(&policy_file(repo, &exe, installation.method), &value)+}++fn deb_asset(version: &str, platform: &str) -> Option<String> {+ let arch = match platform {+ "linux-x86_64" => "amd64",+ "linux-aarch64" => "arm64",+ _ => return None,+ };+ Some(format!("iphone-control_{version}_{arch}.deb"))+}++fn availability(+ local_version: &str,+ method: InstallMethod,+ platform: Option<&str>,+ release: Option<&Release>,+) -> Availability {+ let keys = !option_env!("ICTL_UPDATE_PUBLIC_KEYS").unwrap_or("").is_empty();+ availability_with(local_version, method, platform, release, keys)+}++/// [`availability`] with whether this build carries release signing keys (`ICTL_UPDATE_PUBLIC_KEYS`)+fn availability_with(+ local_version: &str,+ method: InstallMethod,+ platform: Option<&str>,+ release: Option<&Release>,+ keys: bool,+) -> Availability {+ use Availability::*;+ if method == InstallMethod::Development {+ return Development;+ }+ let Some(latest) = release else { return Unchecked };+ let Some(version) = release::stable_tag(&latest.tag) else { return Unchecked };+ let installed = semver::Version::parse(local_version).expect("validated installation or Cargo version");+ match version.cmp_precedence(&installed) {+ Ordering::Less => return Ahead,+ Ordering::Equal => return Current,+ Ordering::Greater => {}+ }+ let Some(platform) = platform else { return Unsupported };+ if method == InstallMethod::Homebrew {+ return BrewCheck;+ }+ if method == InstallMethod::Debian {+ return match deb_asset(&version.to_string(), platform) {+ Some(asset) if latest.assets.contains(&asset) => Available,+ Some(_) => PlatformPending,+ None => Unsupported,+ };+ }+ let base = format!("iphone-control-{}-{platform}", latest.tag);+ if !latest.assets.contains(&format!("{base}.tar.gz")) {+ return PlatformPending;+ }+ if method == InstallMethod::Managed {+ // this installation can never take a managed upgrade: a prerelease, or a build without signing keys+ if !installed.pre.is_empty() || !keys {+ return ManualOnly;+ }+ // The platform's signing job publishes the manifest and its signature after the archive (and may wait+ // for approval): until both are there the upgrade is pending, not manual. Presence allows the CLI to+ // attempt verified installation; it verifies the exact manifest bytes, signature and archive before+ // handing anything to the installer.+ if !latest.assets.contains(&format!("{base}.manifest.json"))+ || !latest.assets.contains(&format!("{base}.manifest.json.sig"))+ {+ return PlatformPending;+ }+ }+ Available+}++fn upgrade_command(+ status: Availability,+ installation: &Installation,+ exe: Option<&Path>,+ release: Option<&Release>,+ platform: Option<&str>,+ tap: Option<&str>,+) -> Option<String> {+ match (status, installation.method) {+ (Availability::Available, InstallMethod::Managed) => {+ let exe = crate::shell_quote(exe?.to_str()?);+ Some(if installation.pinned? {+ format!("{exe} update unpin && {exe} update apply")+ } else {+ format!("{exe} update apply")+ })+ }+ (Availability::BrewCheck, InstallMethod::Homebrew) => {+ let tap = tap.filter(|tap| repository(tap))?;+ let brew = install::brew_program(exe?.ancestors().nth(4)?)?;+ let brew = crate::shell_quote(brew.to_str()?);+ Some(format!("{brew} update && {brew} upgrade {tap}/iphone-control"))+ }+ (Availability::Available, InstallMethod::Debian) => {+ let version = release::stable_tag(&release?.tag)?;+ let asset = deb_asset(&version.to_string(), platform?)?;+ Some(format!("sudo apt install ./{asset}"))+ }+ _ => None,+ }+}++fn guidance(status: Availability, method: InstallMethod, version: Option<&str>, pinned: Option<bool>) -> String {+ match status {+ Availability::Development => {+ tr!("开发构建。在对应源码仓库检出目标版本,按原来的构建或安装方式更新本机程序。", "Development build. Check out the desired revision in its source repository and update this copy using its original build or install method.").into()+ }+ Availability::Unsupported => tr!(+ "此平台没有预编译包。请查看发行说明并从源码构建。",+ "No prebuilt package for this platform. See the release notes and build from source."+ )+ .into(),+ Availability::PlatformPending => tr!(+ "发行版已发布。当前平台的安装包尚未就绪。",+ "The release is published. The package for this platform is pending."+ )+ .into(),+ Availability::ManualOnly => tr!(+ "当前安装无法应用此版本的受管升级。请按发行说明手动升级。",+ "A managed upgrade is unavailable for this installation and release. Follow the manual release instructions."+ )+ .into(),+ Availability::Current => tr!("已安装最新稳定版。", "The latest stable release is installed.").into(),+ Availability::Ahead => {+ tr!("本机版本领先于最新公开稳定版。", "The local version is ahead of the latest public stable release.").into()+ }+ Availability::Unchecked => tr!("尚无成功检查记录。", "No successful release check yet.").into(),+ Availability::BrewCheck => {+ tr!(+ "在主机终端运行 Homebrew 命令。可安装版本取决于 tap 的发布进度及本机是否固定了版本。",+ "Run the Homebrew command in a terminal on the host. The local tap and Homebrew pin determine the upgrade."+ ).into()+ }+ Availability::Available => match method {+ InstallMethod::Managed if pinned == Some(true) => tr!(+ "安装已固定到指定版本。此命令会解除固定并升级。先退出 Viewer 和 MCP 客户端,等待任务完成,再在主机终端运行。安装前会验证签名并检查回退兼容性。",+ "This command unpins and upgrades the installation. Close Viewer and MCP clients and let tasks finish before running it in a host terminal. It verifies the signature and checks rollback compatibility before installing."+ )+ .into(),+ InstallMethod::Managed => tr!(+ "先退出 Viewer 和 MCP 客户端,等待任务完成,再在主机终端运行升级命令。安装前会验证签名并检查回退兼容性。",+ "Close Viewer and MCP clients and let tasks finish before running the upgrade command in a host terminal. It verifies the signature and checks rollback compatibility before installing."+ )+ .into(),+ InstallMethod::Debian => {+ let asset = deb_asset(version.unwrap_or_default(), target().unwrap_or_default()).unwrap_or_default();+ trf!(+ "从发行页下载并校验 {asset},在下载目录中运行安装命令。",+ "Download and verify {asset} from the release, then run the install command in the download directory."+ )+ }+ _ => tr!(+ "关闭正在运行的客户端和服务,再按发行说明手动更新。",+ "Close running clients and services, then follow the manual release instructions."+ )+ .into(),+ },+ }+}++fn manual_migration(+ installation: &Installation,+ outcome: Option<&transaction::Outcome>,+ latest: Option<&str>,+ repo: Option<&str>,+ platform: Option<&str>,+) -> bool {+ let (Some(outcome), Some(from), Some(repo), Some(platform)) =+ (outcome, installation.version.as_deref(), repo, platform)+ else {+ return false;+ };+ installation.method == InstallMethod::Managed+ && outcome.status == "manual_migration"+ && Some(outcome.target_version.as_str()) == latest+ && outcome.migration_source.as_ref().is_some_and(|source| source.matches(repo, platform, from))+}++struct Local {+ source_command: Option<String>,+ exe: Option<PathBuf>,+ install: Installation,+ policy: Policy,+}++impl Local {+ fn load() -> Result<Self> {+ let exe = std::env::current_exe().ok().as_deref().and_then(install::installed_executable);+ let mut install = install::detect(exe.as_deref());+ let source_command = if install.method == InstallMethod::Development && unsafe { libc::geteuid() } != 0 {+ exe.as_deref().and_then(|exe| install::cargo_source(exe, Path::new(env!("CARGO_MANIFEST_DIR")))).map(+ |(version, command)| {+ install.version = Some(version);+ command+ },+ )+ } else {+ None+ };+ let policy = policy(publisher(), exe.as_deref(), &install)?;+ Ok(Self { exe, install, policy, source_command })+ }++ fn report(self, cache: Cache) -> Result<Report> {+ let repo = publisher();+ let release = cache.release.as_ref().filter(|r| release::stable_tag(&r.tag).is_some());+ let version = release.and_then(|r| r.tag.strip_prefix('v')).map(str::to_owned);+ let last_update = self.exe.as_deref().map(transaction::outcome).transpose()?.flatten();+ let local_version = self.install.version.as_deref().unwrap_or(VERSION);+ let status = availability(local_version, self.install.method, target(), release);+ let (status, mut guidance) = if status == Availability::Available+ && manual_migration(&self.install, last_update.as_ref(), version.as_deref(), repo, target())+ {+ (Availability::ManualOnly, tr!(+ "已验证的发行清单要求从当前安装版本手动迁移。请按发行说明中的步骤升级。",+ "The verified release manifest requires a manual migration from the installed version. Follow the release notes to upgrade."+ ).into())+ } else {+ (status, guidance(status, self.install.method, version.as_deref(), self.install.pinned))+ };+ let command = if self.source_command.is_some() {+ guidance = tr!(+ "Cargo 源码安装。先在命令所指的本机源码仓库检出目标版本,再运行命令重新安装。完成后重新打开 Viewer,如有后台服务也请重启。",+ "Installed with Cargo from source. First check out the desired revision in the local repository shown in the command, then run the command to reinstall. Reopen Viewer and restart the service if you use it."+ ).into();+ self.source_command+ } else if cache.error_code.is_some() {+ guidance =+ tr!("检查更新失败。请稍后重试,再决定是否升级。", "The release check failed. Retry before upgrading.")+ .into();+ None+ } else {+ upgrade_command(status, &self.install, self.exe.as_deref(), release, target(), tap())+ };+ if status == Availability::Current && self.install.version.as_deref().is_some_and(|v| v != VERSION) {+ guidance.push_str(tr!(+ " 重新打开正在运行的旧版客户端,并按需重启后台服务。",+ " Reopen clients still running the old version and restart the service if needed."+ ));+ }+ if self.policy == Policy::AutoPatch+ && status == Availability::Available+ && version.as_deref().is_some_and(|v| transaction::eligible(local_version, v, true).is_err())+ {+ guidance.push_str(tr!(+ " 此版本跨越补丁范围,不会自动安装。",+ " This is not a patch in the current series; it will not be installed automatically."+ ));+ }+ Ok(Report {+ running_version: VERSION,+ daemon_version: None,+ installed_version: self.install.version,+ publisher: repo,+ target: target(),+ executable: self.exe,+ install_method: self.install.method,+ policy: self.policy,+ pinned: self.install.pinned,+ available_version: version,+ availability: status,+ last_success_at: cache.last_success_at,+ last_attempt_at: cache.last_attempt_at,+ retry_after: cache.retry_after,+ error_code: cache.error_code,+ published_at: release.and_then(|r| r.published_at.clone()),+ release_url: repo.zip(release).map(|(repo, r)| format!("https://github.com/{repo}/releases/tag/{}", r.tag)),+ guidance,+ upgrade_command: command,+ last_update,+ })+ }+}++pub fn cached() -> Result<Report> {+ let cache = publisher().map(|repo| release::read(&state_dir(repo))).transpose()?.unwrap_or_default();+ Local::load()?.report(cache)+}++pub async fn check(background: bool) -> Result<Report> {+ let local = tokio::task::spawn_blocking(Local::load).await??;+ let Some(repo) = publisher() else { return local.report(Cache::default()) };+ let dir = state_dir(repo);+ let cache = if background && local.policy == Policy::Manual {+ release::read(&dir)?+ } else {+ let url = format!("https://api.github.com/repos/{repo}/releases/latest");+ release::check(&dir, &release::client()?, &url, background).await?+ };+ local.report(cache)+}++impl fmt::Display for Report {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let unknown = tr!("未知", "unknown");+ writeln!(+ f,+ "{} {} daemon {} {} {}",+ tr!("运行版本", "Running"),+ self.running_version,+ self.daemon_version.as_deref().unwrap_or(unknown),+ tr!("磁盘版本", "Installed"),+ self.installed_version.as_deref().unwrap_or(unknown)+ )?;+ let method = match self.install_method {+ InstallMethod::Managed => tr!("受管用户服务", "managed user service"),+ InstallMethod::Script => tr!("脚本安装,手动启动", "installer, manual startup"),+ InstallMethod::Homebrew => "Homebrew",+ InstallMethod::Debian => "Debian",+ InstallMethod::Development => tr!("开发构建", "development build"),+ InstallMethod::Unknown => unknown,+ };+ let policy = match self.policy {+ Policy::Manual => "manual",+ Policy::Notify => "notify",+ Policy::AutoPatch => "auto-patch",+ };+ writeln!(+ f,+ "{} {} {} {method} {} {policy}",+ tr!("发布者", "Publisher"),+ self.publisher.unwrap_or(unknown),+ tr!("安装方式", "Installation"),+ tr!("策略", "Policy")+ )?;+ if let Some(path) = &self.executable {+ writeln!(f, "{}", path.display())?;+ }+ if let Some(version) = &self.available_version {+ writeln!(+ f,+ "{} {} {}",+ tr!("公开稳定版", "Latest stable release"),+ version,+ self.published_at.as_deref().unwrap_or("")+ )?;+ }+ if let Some(url) = &self.release_url {+ writeln!(f, "{url}")?;+ }+ if let Some(ts) = self.last_success_at.and_then(|s| chrono::DateTime::from_timestamp(s as i64, 0)) {+ writeln!(f, "{} {ts}", tr!("上次成功检查", "Last successful check"))?;+ }+ if let Some(code) = &self.error_code {+ writeln!(f, "{} {code}", tr!("本次检查失败", "Release check failed"))?;+ }+ if let Some(outcome) = &self.last_update {+ writeln!(+ f,+ "{} {} {} {}",+ tr!("最近更新事务", "Last installation"),+ outcome.target_version,+ outcome.status,+ outcome.detail+ )?;+ }+ write!(f, "{}", self.guidance)?;+ if let Some(command) = &self.upgrade_command {+ write!(f, "\n{command}")?;+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn verified_migration_decision_only_applies_to_the_same_upgrade() {+ let mut install =+ Installation { method: InstallMethod::Managed, version: Some("0.2.0".into()), pinned: Some(false) };+ let outcome: transaction::Outcome = serde_json::from_value(serde_json::json!({+ "status": "manual_migration", "target_version": "0.2.2", "detail": "", "suppressed_version": "0.2.2",+ "migration_source": { "publisher": "acme/tools", "target": "macos-arm64", "version": "0.2.0" }+ }))+ .unwrap();+ let matches = |install: &Installation, latest, repo, platform| {+ manual_migration(install, Some(&outcome), Some(latest), Some(repo), Some(platform))+ };+ assert!(matches(&install, "0.2.2", "acme/tools", "macos-arm64"));+ assert!(!matches(&install, "0.2.3", "acme/tools", "macos-arm64"));+ assert!(!matches(&install, "0.2.2", "other/tools", "macos-arm64"));+ assert!(!matches(&install, "0.2.2", "acme/tools", "linux-aarch64"));+ install.version = Some("0.2.1".into());+ assert!(!matches(&install, "0.2.2", "acme/tools", "macos-arm64"));+ install.version = Some("0.2.0".into());+ install.method = InstallMethod::Unknown;+ assert!(!matches(&install, "0.2.2", "acme/tools", "macos-arm64"));+ }++ #[test]+ fn managed_guidance_explains_verification_before_installation() {+ ictl_l10n::with_lang(ictl_l10n::Lang::En, || {+ for pinned in [false, true] {+ let guide = guidance(Availability::Available, InstallMethod::Managed, Some("0.2.1"), Some(pinned));+ assert!(guide.contains("signature") && guide.contains("rollback compatibility"), "{guide}");+ }+ });+ }++ #[test]+ fn homebrew_policy_survives_a_keg_upgrade() {+ let old = Path::new("/opt/homebrew/Cellar/iphone-control/0.2.0/bin/iphone-control");+ let new = Path::new("/opt/homebrew/Cellar/iphone-control/0.2.1/bin/iphone-control");+ let policy = |exe, method| policy_file("owner/repo", exe, method);+ assert_eq!(policy(old, InstallMethod::Homebrew), policy(new, InstallMethod::Homebrew));+ assert_ne!(policy(old, InstallMethod::Unknown), policy(new, InstallMethod::Unknown));+ let other = Path::new("/usr/local/Cellar/iphone-control/0.2.1/bin/iphone-control");+ assert_ne!(policy(new, InstallMethod::Homebrew), policy(other, InstallMethod::Homebrew));+ }++ #[test]+ fn policy_defaults_to_notify_only_for_managed_and_disables_auto_when_ownership_changes() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("policy.json");+ let mut install =+ Installation { method: InstallMethod::Managed, version: Some("0.2.0".into()), pinned: Some(false) };+ assert_eq!(read_policy(&file, &install).unwrap(), Policy::Notify);+ release::write_json(&file, &Policy::AutoPatch).unwrap();+ assert_eq!(read_policy(&file, &install).unwrap(), Policy::AutoPatch);+ install.pinned = Some(true);+ assert_eq!(read_policy(&file, &install).unwrap(), Policy::Manual);+ install.method = InstallMethod::Unknown;+ install.pinned = None;+ assert_eq!(read_policy(&file, &install).unwrap(), Policy::Manual);+ fs::remove_file(file.as_path()).unwrap();+ assert_eq!(read_policy(&file, &install).unwrap(), Policy::Manual);+ }++ #[test]+ fn only_relative_repository_names_can_be_publishers() {+ for invalid in+ ["other", "http://example.org", "owner/repo?key=1", "../repo", "owner/..", "/repo", "owner/repo/extra"]+ {+ assert!(!repository(invalid), "{invalid}");+ }+ assert!(repository("Example-Org/iphone-control"));+ }++ #[test]+ fn an_old_viewer_does_not_offer_to_upgrade_the_current_installation() {+ let local = Local {+ source_command: None,+ exe: None,+ install: Installation { method: InstallMethod::Debian, version: Some("9.4.2".into()), pinned: None },+ policy: Policy::Manual,+ };+ let mut cache = Cache::default();+ cache.release = Some(Release { tag: "v9.4.2".into(), published_at: None, assets: vec![] });+ let report = local.report(cache).unwrap();+ assert_eq!(report.availability, Availability::Current);+ assert!(report.upgrade_command.is_none());+ }++ #[test]+ fn upgrade_commands_follow_the_verified_channel_and_release_state() {+ let exe = Path::new("/Users/it's me/bin/iphone-control");+ let release = Release { tag: "v0.2.1".into(), published_at: None, assets: vec![] };+ let brew = Path::new("/opt/homebrew/bin/brew");+ let keg = Path::new("/opt/homebrew/Cellar/iphone-control/0.2.0/bin/iphone-control");+ let command = |method, pinned, status, platform, tap| {+ let exe = if method == InstallMethod::Homebrew { keg } else { exe };+ let installation = Installation { method, version: Some("0.2.0".into()), pinned };+ upgrade_command(status, &installation, Some(exe), Some(&release), Some(platform), tap)+ };+ use Availability::*;+ use InstallMethod::{Debian, Homebrew, Managed, Script, Unknown};+ let quoted = crate::shell_quote(exe.to_str().unwrap());+ for (pinned, expected) in [+ (false, format!("{quoted} update apply")),+ (true, format!("{quoted} update unpin && {quoted} update apply")),+ ] {+ assert_eq!(command(Managed, Some(pinned), Available, "macos-arm64", None), Some(expected));+ }+ assert_eq!(+ command(Homebrew, None, BrewCheck, "macos-arm64", Some("Example/tap")),+ Some(format!(+ "{brew} update && {brew} upgrade Example/tap/iphone-control",+ brew = crate::shell_quote(brew.to_str().unwrap())+ ))+ );+ assert!(command(Homebrew, None, BrewCheck, "macos-arm64", Some("unverified tap")).is_none());+ for (target, arch) in [("linux-aarch64", "arm64"), ("linux-x86_64", "amd64")] {+ assert_eq!(+ command(Debian, None, Available, target, None),+ Some(format!("sudo apt install ./iphone-control_0.2.1_{arch}.deb"))+ );+ }+ for method in [Unknown, Script] {+ assert!(command(method, None, Available, "macos-arm64", None).is_none());+ }+ for status in [Development, Unchecked, Current, Ahead, PlatformPending, Unsupported, ManualOnly] {+ assert!(command(Managed, Some(false), status, "macos-arm64", None).is_none());+ }+ }++ #[test]+ fn availability_follows_local_version_and_install_channel() {+ let release = Release {+ tag: "v0.2.1".into(),+ published_at: None,+ assets: vec!["iphone-control-v0.2.1-linux-x86_64.tar.gz".into(), "iphone-control_0.2.1_amd64.deb".into()],+ };+ let for_install = |running, method, platform| availability(running, method, platform, Some(&release));+ assert_eq!(for_install("0.2.1", InstallMethod::Unknown, None), Availability::Current);+ assert_eq!(for_install("0.3.0-rc.1", InstallMethod::Unknown, None), Availability::Ahead);+ assert_eq!(for_install("0.2.0", InstallMethod::Managed, Some("macos-arm64")), Availability::PlatformPending);+ assert_eq!(for_install("0.2.0", InstallMethod::Managed, Some("linux-x86_64")), Availability::ManualOnly);+ assert_eq!(for_install("0.2.0", InstallMethod::Homebrew, Some("macos-arm64")), Availability::BrewCheck);+ assert_eq!(for_install("0.2.0", InstallMethod::Debian, Some("linux-x86_64")), Availability::Available);+ assert_eq!(for_install("0.2.0", InstallMethod::Debian, Some("linux-aarch64")), Availability::PlatformPending);+ assert_eq!(for_install("0.2.0", InstallMethod::Unknown, None), Availability::Unsupported);+ }++ /// A managed install with signing keys: the archive alone (the signing job hasn't published the manifest and+ /// its signature yet, or waits for approval) is pending, not a manual upgrade; with both it is available.+ /// Without keys, or from a prerelease, it stays manual+ #[test]+ fn managed_upgrade_waits_for_the_signed_manifest() {+ let base = "iphone-control-v0.2.1-linux-x86_64";+ let mut release = Release { tag: "v0.2.1".into(), published_at: None, assets: vec![format!("{base}.tar.gz")] };+ let managed = |r: &Release, running, keys| {+ availability_with(running, InstallMethod::Managed, Some("linux-x86_64"), Some(r), keys)+ };+ assert_eq!(managed(&release, "0.2.0", true), Availability::PlatformPending);+ release.assets.push(format!("{base}.manifest.json"));+ assert_eq!(managed(&release, "0.2.0", true), Availability::PlatformPending, "signature still missing");+ release.assets.push(format!("{base}.manifest.json.sig"));+ assert_eq!(managed(&release, "0.2.0", true), Availability::Available);+ assert_eq!(managed(&release, "0.2.0", false), Availability::ManualOnly, "no signing keys in this build");+ assert_eq!(managed(&release, "0.2.1-rc.1", true), Availability::ManualOnly, "prerelease install");+ }+}diff --git a/apps/iphone-control/src/update/archive.rs b/apps/iphone-control/src/update/archive.rsnew file mode 100644index 0000000..406ec7b--- /dev/null+++ b/apps/iphone-control/src/update/archive.rs@@ -0,0 +1,328 @@+//! The release metadata and signature are deliberately separate: verify the exact response bytes+//! with an embedded key before parsing any download instructions.+use std::fs::File;+use std::io::{Read, Write};+use std::os::unix::fs::PermissionsExt;+use std::path::{Path, PathBuf};+use std::time::Duration;++use anyhow::{Context, ensure};+use reqwest::{Client, Url};+use ring::signature::{ED25519, UnparsedPublicKey};+use serde::Deserialize;++const MAX_ARCHIVE: u64 = 128 << 20;+const MAX_EXPANDED: u64 = 256 << 20;+const MAX_MANIFEST: u64 = 16 << 10;++#[derive(Debug, Deserialize)]+struct Manifest {+ schema: u32,+ publisher: String,+ version: String,+ target: String,+ asset: String,+ sha256: String,+ size: u64,+ unattended: bool,+ rollback_compatible: bool,+ rollback_from: Option<String>,+}++#[derive(Debug)]+pub(super) struct ManualMigration(String);++impl std::fmt::Display for ManualMigration {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "release does not support rollback to installed version {}; see the release notes", self.0)+ }+}++impl std::error::Error for ManualMigration {}++/// The automatic job found a release not marked for unattended installation: a normal release that is installed+/// with `update apply`, not a failure+#[derive(Debug)]+pub(super) struct NeedsOperator(pub String);++impl std::fmt::Display for NeedsOperator {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{} is not marked for automatic installation; install it with: iphone-control update apply", self.0)+ }+}++impl std::error::Error for NeedsOperator {}++fn trusted(url: &Url) -> bool {+ url.scheme() == "https"+ && url.port_or_known_default() == Some(443)+ && url.username().is_empty()+ && url.password().is_none()+ && matches!(+ url.host_str(),+ Some("github.com" | "release-assets.githubusercontent.com" | "objects.githubusercontent.com")+ )+}++fn client() -> anyhow::Result<Client> {+ Ok(Client::builder()+ .user_agent("iphone-control-updater")+ .https_only(true)+ .redirect(reqwest::redirect::Policy::custom(|attempt| {+ if attempt.previous().len() < 5 && trusted(attempt.url()) {+ attempt.follow()+ } else {+ attempt.error("untrusted release redirect")+ }+ }))+ .connect_timeout(Duration::from_secs(10))+ .timeout(Duration::from_secs(180))+ .build()?)+}++async fn download(client: &Client, url: &str, max: u64, mut out: impl Write) -> anyhow::Result<u64> {+ let mut response =+ client.get(url).send().await.and_then(|r| r.error_for_status()).map_err(reqwest::Error::without_url)?;+ ensure!(response.content_length().is_none_or(|s| s <= max), "release asset exceeds size limit");+ let mut size = 0;+ while let Some(chunk) = response.chunk().await.map_err(reqwest::Error::without_url)? {+ size += chunk.len() as u64;+ ensure!(size <= max, "release asset exceeds size limit");+ out.write_all(&chunk)?;+ }+ Ok(size)+}++fn key_bytes(key: &str) -> Option<[u8; 32]> {+ if key.len() != 64 || !key.as_bytes().iter().all(|b| b.is_ascii_hexdigit()) {+ return None;+ }+ let mut decoded = [0; 32];+ for (i, byte) in decoded.iter_mut().enumerate() {+ *byte = u8::from_str_radix(&key[i * 2..i * 2 + 2], 16).ok()?;+ }+ Some(decoded)+}++fn verify(+ raw: &[u8],+ sig: &[u8],+ keys: &str,+ publisher: &str,+ target: &str,+ version: &str,+ installed_version: &str,+) -> anyhow::Result<Manifest> {+ ensure!(+ keys.split(',').filter_map(key_bytes).any(|key| UnparsedPublicKey::new(&ED25519, key).verify(raw, sig).is_ok()),+ "invalid release signature"+ );+ let m: Manifest = serde_json::from_slice(raw)?;+ ensure!(+ m.schema == 1+ && m.publisher == publisher+ && m.target == target+ && m.version == version+ && m.asset == format!("iphone-control-v{version}-{target}.tar.gz"),+ "manifest does not match this release"+ );+ ensure!(+ (1..=MAX_ARCHIVE).contains(&m.size)+ && key_bytes(&m.sha256).is_some()+ && m.sha256.bytes().all(|b| !b.is_ascii_uppercase()),+ "invalid signed digest or size"+ );+ if !m.rollback_compatible || m.rollback_from.as_deref() != Some(installed_version) {+ return Err(ManualMigration(installed_version.into()).into());+ }+ Ok(m)+}++/// The staging directory is private and on the same filesystem as the destination. The archive+/// owns no paths on disk: copy only the expected regular executable to our chosen filename.+fn extract(archive: &Path, root: &str, candidate: &Path) -> anyhow::Result<()> {+ let gzip = flate2::read::MultiGzDecoder::new(File::open(archive)?);+ let mut tar = tar::Archive::new(gzip.take(MAX_EXPANDED + 1));+ let mut found = false;+ for (n, item) in tar.entries()?.enumerate() {+ ensure!(n < 32, "too many archive entries");+ let mut item = item?;+ let name = item.path()?;+ let kind = item.header().entry_type();+ if name == Path::new(root) && kind.is_dir() {+ continue;+ }+ ensure!(name.parent() == Some(Path::new(root)) && kind.is_file(), "unexpected path or link in release archive");+ if name.file_name().is_some_and(|n| n == "iphone-control") {+ ensure!(+ !found && (1..=MAX_EXPANDED).contains(&item.size()) && item.header().mode()? & 0o111 != 0,+ "invalid executable entry"+ );+ let mut out = File::create_new(candidate)?;+ ensure!(std::io::copy(&mut item, &mut out)? == item.size(), "truncated executable");+ out.set_permissions(std::fs::Permissions::from_mode(0o755))?;+ out.sync_all()?;+ found = true;+ }+ }+ let mut decoder = tar.into_inner();+ std::io::copy(&mut decoder, &mut std::io::sink())?;+ ensure!(decoder.limit() > 0 && found, "invalid expanded archive size or missing executable");+ Ok(())+}++fn unpack(m: &Manifest, stage: &Path) -> anyhow::Result<PathBuf> {+ let archive = stage.join("archive");+ ensure!(+ archive.metadata()?.len() == m.size && super::digest(&archive)? == m.sha256,+ "release archive digest or size mismatch"+ );+ let candidate = stage.join("candidate");+ extract(&archive, m.asset.trim_end_matches(".tar.gz"), &candidate)?;+ Ok(candidate)+}++pub(super) async fn stage(+ dir: &Path,+ receipt: &super::Receipt,+ version: &str,+ automatic: bool,+) -> anyhow::Result<PathBuf> {+ let keys = option_env!("ICTL_UPDATE_PUBLIC_KEYS")+ .filter(|s| !s.is_empty())+ .context("this build has no update trust key")?;+ let base = format!("https://github.com/{}/releases/download/v{version}", receipt.publisher);+ let manifest_url = format!("{base}/iphone-control-v{version}-{}.manifest.json", receipt.target);+ let client = client()?;+ let mut raw = Vec::new();+ let mut sig = Vec::new();+ download(&client, &manifest_url, MAX_MANIFEST, &mut raw).await?;+ download(&client, &format!("{manifest_url}.sig"), 64, &mut sig).await?;+ let m = verify(&raw, &sig, keys, &receipt.publisher, &receipt.target, version, &receipt.version)?;+ if automatic && !m.unattended {+ return Err(NeedsOperator(version.to_string()).into());+ }+ download(&client, &format!("{base}/{}", m.asset), m.size, File::create_new(dir.join("archive"))?).await?;+ let candidate = unpack(&m, dir)?;+ preflight(&candidate, version).await?;+ Ok(candidate)+}++pub(super) async fn preflight(candidate: &Path, version: &str) -> anyhow::Result<()> {+ let mut cmd = tokio::process::Command::new(candidate);+ cmd.arg("--version").kill_on_drop(true);+ let out = tokio::time::timeout(Duration::from_secs(10), cmd.output())+ .await+ .context("candidate --version timed out")??;+ ensure!(+ out.status.success() && std::str::from_utf8(&out.stdout)?.trim() == format!("iphone-control {version}"),+ "unexpected candidate --version"+ );+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use ring::rand::SystemRandom;+ use ring::signature::{Ed25519KeyPair, KeyPair};+ use serde_json::json;++ const ROOT: &str = "iphone-control-v0.2.1-macos-arm64";++ fn make_archive(path: &Path, kind: tar::EntryType, name: &str, mode: u32) {+ let zip = flate2::write::GzEncoder::new(File::create(path).unwrap(), flate2::Compression::fast());+ let mut tar = tar::Builder::new(zip);+ let mut header = tar::Header::new_gnu();+ let content: &[u8] = b"#!/bin/sh\necho iphone-control 0.2.1\n";+ header.set_size(content.len() as u64);+ header.set_entry_type(kind);+ header.set_mode(mode);+ header.set_cksum();+ tar.append_data(&mut header, name, content).unwrap();+ tar.into_inner().unwrap().finish().unwrap();+ }++ fn key() -> Ed25519KeyPair {+ let der = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap();+ Ed25519KeyPair::from_pkcs8(der.as_ref()).unwrap()+ }++ fn hex(k: &Ed25519KeyPair) -> String {+ k.public_key().as_ref().iter().map(|v| format!("{v:02x}")).collect()+ }++ #[tokio::test]+ async fn verifies_publisher_signed_bytes_before_staging_an_executable() {+ let root = tempfile::tempdir().unwrap();+ let file = root.path().join("archive");+ make_archive(&file, tar::EntryType::Regular, &format!("{ROOT}/iphone-control"), 0o755);+ let digest = super::super::digest(&file).unwrap();+ let mut doc = json!({"schema":1,"publisher":"example/update","target":"macos-arm64","version":"0.2.1",+ "asset":format!("{ROOT}.tar.gz"),"sha256":digest,"size":file.metadata().unwrap().len(),+ "unattended":true,"rollback_compatible":true,"rollback_from":"0.2.0"});+ let key = key();+ let trusted = hex(&key);+ let check = |doc: &[u8], sig: &[u8], keys: &str| {+ verify(doc, sig, keys, "example/update", "macos-arm64", "0.2.1", "0.2.0")+ };+ let bytes = serde_json::to_vec(&doc).unwrap();+ let sig = key.sign(&bytes);+ let m = check(&bytes, sig.as_ref(), &trusted).unwrap();+ let next = unpack(&m, root.path()).unwrap();+ preflight(&next, "0.2.1").await.unwrap();+ assert!(preflight(&next, "0.2.2").await.is_err());+ let wrong_key = "00".repeat(32);+ assert!(check(&bytes, sig.as_ref(), &wrong_key).is_err());+ let mut edited = bytes.clone();+ edited.push(b' ');+ assert!(check(&edited, sig.as_ref(), &trusted).is_err());+ for (field, value) in [+ ("target", json!("linux-aarch64")),+ ("size", json!(MAX_ARCHIVE + 1)),+ ("publisher", json!("elsewhere/other")),+ ("rollback_compatible", json!(false)),+ ("rollback_from", json!("0.1.9")),+ ("asset", json!("other.tar.gz")),+ ] {+ let original = doc[field].clone();+ doc[field] = value;+ let bad = serde_json::to_vec(&doc).unwrap();+ let err = check(&bad, key.sign(&bad).as_ref(), &trusted).unwrap_err();+ assert_eq!(err.is::<ManualMigration>(), matches!(field, "rollback_from" | "rollback_compatible"));+ doc[field] = original;+ }+ doc.as_object_mut().unwrap().remove("rollback_from");+ let legacy = serde_json::to_vec(&doc).unwrap();+ assert!(check(&legacy, key.sign(&legacy).as_ref(), &trusted).is_err_and(|e| e.is::<ManualMigration>()));+ std::fs::write(file, vec![0; m.size as usize]).unwrap();+ assert!(unpack(&m, root.path()).is_err());+ }++ #[test]+ fn rejects_links_wrong_directory_and_non_executable() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("archive");+ let candidate = dir.path().join("candidate");+ for (kind, path, mode) in [+ (tar::EntryType::Symlink, format!("{ROOT}/iphone-control"), 0o755),+ (tar::EntryType::Link, format!("{ROOT}/iphone-control"), 0o755),+ (tar::EntryType::Regular, "different/iphone-control".into(), 0o755),+ (tar::EntryType::Regular, format!("{ROOT}/iphone-control"), 0o644),+ ] {+ make_archive(&file, kind, &path, mode);+ assert!(extract(&file, ROOT, &candidate).is_err());+ assert!(!candidate.exists());+ }+ }++ #[test]+ fn redirect_trust_is_limited_to_https_release_hosts() {+ for url in ["https://release-assets.githubusercontent.com/item", "https://github.com/a/b"] {+ assert!(trusted(&Url::parse(url).unwrap()));+ }+ for url in ["http://github.com/a", "https://github.com.example.com/a", "https://[email protected]:444/a"] {+ assert!(!trusted(&Url::parse(url).unwrap()));+ }+ }+}diff --git a/apps/iphone-control/src/update/install.rs b/apps/iphone-control/src/update/install.rsnew file mode 100644index 0000000..3ef8169--- /dev/null+++ b/apps/iphone-control/src/update/install.rs@@ -0,0 +1,355 @@+//! Identify the executable the caller is running, independently of other installs on PATH.+use std::fs::{self, File, Metadata};+use std::os::unix::fs::{MetadataExt, OpenOptionsExt};+use std::path::{Path, PathBuf};+use std::process::Command;+use std::sync::{Mutex, OnceLock};++use anyhow::{Context, Result, ensure};+use semver::Version;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};++use super::{InstallMethod, publisher, target};+use crate::envfile;++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Receipt {+ pub schema: u32,+ pub publisher: String,+ pub target: String,+ pub binary_path: PathBuf,+ pub service: String,+ pub version: String,+ pub sha256: String,+ pub pinned: bool,+}++pub fn receipt_path() -> PathBuf {+ envfile::config_dir().join("install-receipt.json")+}++pub fn read_receipt() -> Result<Receipt> {+ let file = File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(receipt_path()).context("No readable script installation receipt; run iphone-control update check for the upgrade instructions for this installation")?;+ let meta = file.metadata()?;+ ensure!(user_owned(&meta) && meta.is_file() && meta.len() < 16 * 1024, "invalid installation receipt file");+ let r: Receipt = serde_json::from_reader(file)?;+ ensure!(+ r.schema == 1 && Some(r.publisher.as_str()) == publisher() && Some(r.target.as_str()) == target(),+ "receipt does not match this build"+ );+ ensure!(matches!(r.service.as_str(), "none" | "launchd" | "systemd"), "invalid service in receipt");+ ensure!(+ r.binary_path.is_absolute() && r.binary_path.file_name().is_some_and(|n| n == "iphone-control"),+ "invalid binary path"+ );+ ensure!(Version::parse(&r.version).is_ok(), "invalid receipt version");+ ensure!(+ r.sha256.len() == 64 && r.sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()),+ "invalid binary digest"+ );+ Ok(r)+}++fn user_owned(meta: &Metadata) -> bool {+ let uid = unsafe { libc::geteuid() };+ uid != 0 && meta.uid() == uid && meta.mode() & 0o022 == 0+}++fn receipt_file(r: &Receipt, exe: &Path) -> Result<File> {+ ensure!(+ exe.canonicalize()? == r.binary_path && r.binary_path.canonicalize()? == r.binary_path,+ "receipt belongs to another executable"+ );+ let parent = r.binary_path.parent().context("missing install directory")?;+ ensure!(user_owned(&fs::metadata(parent)?), "unsafe install directory ownership or permissions");+ let file = File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(&r.binary_path)?;+ let meta = file.metadata()?;+ ensure!(meta.is_file() && user_owned(&meta) && meta.mode() & 0o100 != 0, "unsafe installed executable");+ Ok(file)+}++fn hash(mut file: File) -> Result<String> {+ let mut hasher = Sha256::new();+ std::io::copy(&mut file, &mut hasher)?;+ Ok(format!("{:x}", hasher.finalize()))+}++pub fn digest(path: &Path) -> Result<String> {+ hash(File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path)?)+}++pub fn validate_receipt(receipt: &Receipt, expected_exe: &Path) -> Result<()> {+ ensure!(+ hash(receipt_file(receipt, expected_exe)?)? == receipt.sha256,+ "installed binary digest differs from receipt"+ );+ Ok(())+}++// The settings card polls frequently. Reuse a successful hash of the same unchanged inode+// for display only. Installation transactions always rehash the open file with validate_receipt.+fn matches_for_display(receipt: &Receipt, exe: &Path) -> Result<bool> {+ type FileStamp = (u64, u64, u64, i64, i64);+ static LAST: Mutex<Option<(FileStamp, String)>> = Mutex::new(None);+ let file = receipt_file(receipt, exe)?;+ let meta = file.metadata()?;+ let stamp = (meta.dev(), meta.ino(), meta.len(), meta.ctime(), meta.ctime_nsec());+ let mut value = LAST.lock().unwrap_or_else(|e| e.into_inner());+ if let Some((_, digest)) = value.as_ref().filter(|(s, _)| *s == stamp) {+ return Ok(*digest == receipt.sha256);+ }+ let digest = hash(file)?;+ let matched = digest == receipt.sha256;+ *value = Some((stamp, digest));+ Ok(matched)+}++pub(super) struct Installation {+ pub method: InstallMethod,+ pub version: Option<String>,+ pub pinned: Option<bool>,+}++/// Cargo records the source directory, binary names and build options beside its bin directory.+/// A development executable copied elsewhere has no corresponding installation record.+pub(super) fn cargo_source(exe: &Path, manifest_dir: &Path) -> Option<(String, String)> {+ if exe.file_name()? != "iphone-control" || exe.parent()?.file_name()? != "bin" {+ return None;+ }+ let root = exe.parent()?.parent()?;+ let source = manifest_dir.canonicalize().ok()?;+ if !source.join("Cargo.toml").is_file() {+ return None;+ }+ let data: serde_json::Value = serde_json::from_reader(File::open(root.join(".crates2.json")).ok()?).ok()?;+ let mut owners = data["installs"].as_object()?.iter().filter(|(_, entry)| {+ entry["bins"].as_array().is_some_and(|bins| bins.iter().any(|bin| bin.as_str() == Some("iphone-control")))+ });+ let (id, entry) = owners.next()?;+ if owners.next().is_some() {+ return None;+ }+ let (version, url) = id.strip_prefix("iphone-control ")?.strip_suffix(')')?.split_once(" (path+")?;+ let recorded_source = reqwest::Url::parse(url).ok()?.to_file_path().ok()?;+ if recorded_source.canonicalize().ok()? != source {+ return None;+ }+ let version = Version::parse(version).ok()?.to_string();+ let mut command = format!(+ "cd {} && cargo install --locked --path . --root {}",+ crate::shell_quote(source.to_str()?),+ crate::shell_quote(root.to_str()?),+ );+ match entry["profile"].as_str()? {+ "release" => {}+ "debug" | "dev" => command.push_str(" --debug"),+ profile => command.push_str(&format!(" --profile {}", crate::shell_quote(profile))),+ }+ if entry["all_features"].as_bool()? {+ command.push_str(" --all-features");+ }+ if entry["no_default_features"].as_bool()? {+ command.push_str(" --no-default-features");+ }+ let features = entry["features"].as_array()?.iter().map(|f| f.as_str()).collect::<Option<Vec<_>>>()?;+ if !features.is_empty() {+ command.push_str(&format!(" --features {}", crate::shell_quote(&features.join(","))));+ }+ let target = entry["target"].as_str()?;+ let host = entry["rustc"].as_str()?.lines().find_map(|line| line.strip_prefix("host: "))?;+ if target != host {+ command.push_str(&format!(" --target {}", crate::shell_quote(target)));+ }+ Some((version, command))+}++fn brew_keg(exe: &Path, cellar: &Path, tap: &str) -> Option<String> {+ let version = exe.strip_prefix(cellar.join("iphone-control")).ok()?.components().next()?.as_os_str();+ let keg = cellar.join("iphone-control").join(version);+ if exe != keg.join("bin/iphone-control") {+ return None;+ }+ let receipt: serde_json::Value =+ serde_json::from_reader(File::open(keg.join("INSTALL_RECEIPT.json")).ok()?).ok()?;+ if !receipt.pointer("/source/tap")?.as_str()?.eq_ignore_ascii_case(tap) {+ return None;+ }+ // Homebrew may append a formula revision (_1) to the keg name.+ Some(Version::parse(version.to_str()?.split('_').next()?).ok()?.to_string())+}++pub(super) fn brew_program(cellar: &Path) -> Option<PathBuf> {+ // GUI processes need not inherit Homebrew's PATH. Only use a neighboring+ // executable for known Homebrew prefixes; custom installations use the host PATH.+ match cellar.to_str()? {+ "/opt/homebrew/Cellar" | "/usr/local/Cellar" | "/home/linuxbrew/.linuxbrew/Cellar" => {+ return Some(cellar.parent()?.join("bin/brew"));+ }+ _ => {}+ }+ let path = std::env::var_os("PATH")?;+ std::env::split_paths(&path).filter(|p| p.is_absolute()).map(|p| p.join("brew")).find(|p| p.is_file())+}++fn brew_installation(exe: &Path, tap: &str) -> Option<String> {+ // First match the exact keg and its tap receipt. Never start a package manager+ // for a source checkout, a plain copy, or an installation in another tap.+ let cellar = exe.ancestors().nth(4)?;+ let version = brew_keg(exe, cellar, tap)?;+ static CELLAR: OnceLock<Option<PathBuf>> = OnceLock::new();+ let actual = CELLAR.get_or_init(|| {+ let brew = brew_program(cellar)?;+ let output = Command::new(brew).arg("--cellar").env("HOMEBREW_NO_AUTO_UPDATE", "1").output().ok()?;+ if !output.status.success() {+ return None;+ }+ Path::new(std::str::from_utf8(&output.stdout).ok()?.trim()).canonicalize().ok()+ });+ if actual.as_deref() != Some(cellar) {+ return None;+ }+ // The old Viewer may still run from a retained keg after Homebrew relinks opt.+ let active = cellar.parent()?.join("opt/iphone-control/bin/iphone-control");+ Some(active.canonicalize().ok().and_then(|p| brew_keg(&p, cellar, tap)).unwrap_or(version))+}++fn deb_package(exe: &Path) -> Option<String> {+ if !cfg!(target_os = "linux") || exe != Path::new("/usr/bin/iphone-control") {+ return None;+ }+ let dpkg = |args: &[&str]| {+ let output = Command::new("/usr/bin/dpkg-query").args(args).output().ok()?;+ output.status.success().then(|| String::from_utf8(output.stdout).ok())?+ };+ let ownership = dpkg(&["-S", "/usr/bin/iphone-control"])?;+ let (owner, file) = ownership.trim().split_once(": ")?;+ if owner.split(':').next()? != "iphone-control" || file != "/usr/bin/iphone-control" {+ return None;+ }+ let installed = dpkg(&["-W", "-f=${db:Status-Abbrev} ${Version}", owner])?;+ let version = installed.strip_prefix("ii ")?.trim();+ let upstream = version.rsplit_once('-').map_or(version, |(upstream, _)| upstream);+ Some(Version::parse(upstream).ok()?.to_string())+}++/// Linux marks /proc/self/exe as deleted when Cargo, dpkg or an installer atomically+/// replaces the binary under a running Viewer. Inspect the replacement at its original path.+pub(super) fn installed_executable(running: &Path) -> Option<PathBuf> {+ running.canonicalize().ok().or_else(|| {+ if cfg!(target_os = "linux") && running.file_name()? == "iphone-control (deleted)" {+ running.with_file_name("iphone-control").canonicalize().ok()+ } else {+ None+ }+ })+}++pub(super) fn detect(exe: Option<&Path>) -> Installation {+ let unknown = |method| Installation { method, version: None, pinned: None };+ if publisher().is_none() {+ return unknown(InstallMethod::Development);+ }+ let Some(exe) = exe else { return unknown(InstallMethod::Unknown) };+ if unsafe { libc::geteuid() } == 0 {+ return unknown(InstallMethod::Unknown);+ }+ if let Ok(r) = read_receipt() {+ if matches_for_display(&r, exe).unwrap_or(false) {+ let method = match r.service.as_str() {+ "none" => InstallMethod::Script,+ _ if crate::service::managed(&r.binary_path, &r.service).is_ok() => InstallMethod::Managed,+ _ => InstallMethod::Unknown,+ };+ return Installation { method, version: Some(r.version), pinned: Some(r.pinned) };+ }+ // A receipt for this path whose digest changed is not evidence of ownership.+ if r.binary_path == exe {+ return unknown(InstallMethod::Unknown);+ }+ }+ if let Some(version) = super::tap().and_then(|tap| brew_installation(exe, tap)) {+ return Installation { method: InstallMethod::Homebrew, version: Some(version), pinned: None };+ }+ if let Some(version) = deb_package(exe) {+ return Installation { method: InstallMethod::Debian, version: Some(version), pinned: None };+ }+ unknown(InstallMethod::Unknown)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::os::unix::fs::PermissionsExt;++ #[test]+ fn cargo_commands_require_the_recorded_source_and_preserve_install_options() {+ let dir = tempfile::tempdir().unwrap();+ let dir = dir.path().canonicalize().unwrap();+ let root = dir.join("install root");+ let source = dir.join("my fork's $source");+ fs::create_dir_all(root.join("bin")).unwrap();+ fs::create_dir(&source).unwrap();+ fs::write(source.join("Cargo.toml"), b"").unwrap();+ let exe = root.join("bin/iphone-control");+ let package = format!("iphone-control 0.2.1 (path+{})", reqwest::Url::from_file_path(&source).unwrap());+ let data = serde_json::json!({ "installs": { package: {+ "bins": ["iphone-control"], "features": ["debug-cmds"], "profile": "debug", "all_features": false,+ "no_default_features": true, "target": "aarch64-apple-darwin", "rustc": "host: aarch64-apple-darwin"+ } } });+ fs::write(root.join(".crates2.json"), data.to_string()).unwrap();+ let (version, command) = cargo_source(&exe, &source).unwrap();+ assert_eq!(version, "0.2.1");+ assert_eq!(+ command,+ format!(+ "cd {} && cargo install --locked --path . --root {} --debug --no-default-features --features debug-cmds",+ crate::shell_quote(source.to_str().unwrap()),+ crate::shell_quote(root.to_str().unwrap())+ )+ );+ assert!(cargo_source(&dir.join("other/bin/iphone-control"), &source).is_none());+ assert!(cargo_source(&exe, &root).is_none());+ fs::write(root.join(".crates2.json"), "{}").unwrap();+ assert!(cargo_source(&exe, &source).is_none());+ }++ #[test]+ fn only_identifies_the_receipted_file() {+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let bin = dir.path().canonicalize().unwrap().join("iphone-control");+ fs::write(&bin, b"original").unwrap();+ fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();+ let r = Receipt {+ schema: 1,+ publisher: "example/test".into(),+ target: "linux-x86_64".into(),+ binary_path: bin.clone(),+ service: "systemd".into(),+ version: "1.0.0".into(),+ sha256: digest(&bin).unwrap(),+ pinned: false,+ };+ validate_receipt(&r, &bin).unwrap();+ let other = dir.path().join("copy");+ fs::copy(&bin, &other).unwrap();+ assert!(validate_receipt(&r, &other).is_err());+ fs::write(&bin, b"modified").unwrap();+ assert!(validate_receipt(&r, &bin).is_err());+ }++ #[test]+ fn brew_requires_exact_cellar_binary_and_tap_receipt() {+ let dir = tempfile::tempdir().unwrap();+ let keg = dir.path().join("iphone-control/1.3.2_1");+ fs::create_dir_all(keg.join("bin")).unwrap();+ fs::write(keg.join("INSTALL_RECEIPT.json"), br#"{"source":{"tap":"acme/tools"}}"#).unwrap();+ let exe = keg.join("bin/iphone-control");+ assert_eq!(brew_keg(&exe, dir.path(), "Acme/tools").as_deref(), Some("1.3.2"));+ assert!(brew_keg(&exe, dir.path(), "other/tap").is_none());+ assert!(brew_keg(&keg.join("extra/bin/iphone-control"), dir.path(), "acme/tools").is_none());+ }+}diff --git a/apps/iphone-control/src/update/release.rs b/apps/iphone-control/src/update/release.rsnew file mode 100644index 0000000..95e3573--- /dev/null+++ b/apps/iphone-control/src/update/release.rs@@ -0,0 +1,332 @@+//! Cache public release metadata across CLI, Viewer and scheduled checks. Hold the+//! per-publisher/platform flock through the response and atomic cache replacement.+use std::fs::{self, File};+use std::io;+use std::os::fd::AsRawFd;+use std::os::unix::fs::OpenOptionsExt;+use std::path::Path;+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use anyhow::{Context, Result};+use reqwest::{Client, StatusCode, header};+use serde::{Deserialize, Serialize};++#[derive(Clone, Default, Deserialize, Serialize)]+pub(super) struct Cache {+ pub release: Option<Release>,+ pub last_success_at: Option<u64>,+ pub last_attempt_at: Option<u64>,+ pub error_code: Option<String>,+ pub retry_after: Option<u64>,+ etag: Option<String>,+ next_background_at: Option<u64>,+}++#[derive(Clone, Deserialize, Serialize)]+pub(super) struct Release {+ pub tag: String,+ pub published_at: Option<String>,+ pub assets: Vec<String>,+}++#[derive(Deserialize)]+struct Metadata {+ tag_name: String,+ draft: bool,+ prerelease: bool,+ published_at: Option<String>,+ assets: Vec<Asset>,+}++#[derive(Deserialize)]+struct Asset {+ name: String,+ state: String,+ size: u64,+}++pub(super) fn stable_tag(tag: &str) -> Option<semver::Version> {+ let version = semver::Version::parse(tag.strip_prefix('v')?).ok()?;+ (version.pre.is_empty() && version.build.is_empty()).then_some(version)+}++fn parse_release(body: &[u8]) -> Option<Release> {+ let meta: Metadata = serde_json::from_slice(body).ok()?;+ if meta.draft || meta.prerelease || stable_tag(&meta.tag_name).is_none() {+ return None;+ }+ let assets = meta.assets.into_iter().filter(|a| a.state == "uploaded" && a.size > 0).map(|a| a.name).collect();+ Some(Release { tag: meta.tag_name, published_at: meta.published_at, assets })+}++pub(super) fn read(dir: &Path) -> Result<Cache> {+ match fs::read(dir.join("release.json")) {+ Ok(data) => Ok(serde_json::from_slice(&data).unwrap_or_default()),+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Cache::default()),+ Err(e) => Err(e.into()),+ }+}++pub(super) fn write_json(path: &Path, data: &impl Serialize) -> Result<()> {+ fs::create_dir_all(path.parent().context("missing update state directory")?)?;+ super::write_json_atomic(path, data)+}++fn lock(dir: &Path) -> Result<File> {+ fs::create_dir_all(dir)?;+ let f = File::options()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW)+ .open(dir.join("check.lock"))?;+ loop {+ if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } == 0 {+ return Ok(f);+ }+ let err = io::Error::last_os_error();+ if err.kind() != io::ErrorKind::Interrupted {+ return Err(err.into());+ }+ }+}++fn now() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()+}++fn retry_at(headers: &header::HeaderMap, now: u64) -> u64 {+ let retry = headers.get(header::RETRY_AFTER).and_then(|h| h.to_str().ok()).and_then(|s| {+ s.parse::<u64>()+ .ok()+ .map(|secs| now.saturating_add(secs))+ .or_else(|| chrono::DateTime::parse_from_rfc2822(s).ok().and_then(|dt| dt.timestamp().try_into().ok()))+ });+ let reset = headers.get("x-ratelimit-reset").and_then(|h| h.to_str().ok()?.parse::<u64>().ok());+ retry.into_iter().chain(reset).filter(|&until| until > now).max().unwrap_or_else(|| now.saturating_add(3600))+}++enum Fetch {+ New(Release, Option<String>),+ Unchanged,+ Failed(&'static str, Option<u64>),+}++async fn fetch(client: &Client, url: &str, cache: &Cache, now: u64) -> reqwest::Result<Fetch> {+ let mut req = client+ .get(url)+ .header(header::USER_AGENT, "iphone-control-update")+ .header(header::ACCEPT, "application/vnd.github+json");+ if let Some(etag) = &cache.etag {+ req = req.header(header::IF_NONE_MATCH, etag);+ }+ let mut res = req.send().await?;+ let status = res.status();+ let headers = res.headers();+ if status == StatusCode::NOT_MODIFIED {+ return Ok(if cache.release.is_some() && cache.etag.is_some() {+ Fetch::Unchanged+ } else {+ Fetch::Failed("invalid_release", None)+ });+ }+ if status == StatusCode::TOO_MANY_REQUESTS+ || (status == StatusCode::FORBIDDEN+ && (headers.contains_key(header::RETRY_AFTER)+ || headers.get("x-ratelimit-remaining").is_some_and(|v| v == "0")))+ {+ return Ok(Fetch::Failed("rate_limited", Some(retry_at(headers, now))));+ }+ if !status.is_success() {+ return Ok(Fetch::Failed(if status == StatusCode::NOT_FOUND { "no_release" } else { "http_error" }, None));+ }+ let etag = headers.get(header::ETAG).and_then(|v| v.to_str().ok()).map(str::to_owned);+ let mut body = Vec::new();+ while let Some(chunk) = res.chunk().await? {+ if chunk.len() > (2 * 1024 * 1024) - body.len() {+ return Ok(Fetch::Failed("invalid_release", None));+ }+ body.extend_from_slice(&chunk);+ }+ Ok(match parse_release(&body) {+ Some(release) => Fetch::New(release, etag),+ None => Fetch::Failed("invalid_release", None),+ })+}++pub(super) fn client() -> Result<Client> {+ Ok(Client::builder()+ .https_only(true)+ .redirect(reqwest::redirect::Policy::none())+ .timeout(Duration::from_secs(12))+ .build()?)+}++pub(super) async fn check(dir: &Path, client: &Client, url: &str, background: bool) -> Result<Cache> {+ let lock_dir = dir.to_owned();+ let _lock = tokio::task::spawn_blocking(move || lock(&lock_dir)).await??;+ let mut cache = read(dir)?;+ let started = now();+ if cache.retry_after.is_some_and(|at| started < at)+ || cache.last_attempt_at.is_some_and(|at| started < at.saturating_add(60))+ || (background && cache.next_background_at.is_some_and(|at| started < at))+ {+ return Ok(cache);+ }+ let result = fetch(client, url, &cache, started).await.unwrap_or(Fetch::Failed("network", None));+ let finished = now();+ cache.last_attempt_at = Some(started);+ cache.error_code = None;+ cache.retry_after = None;+ match result {+ Fetch::New(release, etag) => {+ cache.release = Some(release);+ cache.etag = etag;+ cache.last_success_at = Some(finished);+ }+ Fetch::Unchanged => cache.last_success_at = Some(finished),+ Fetch::Failed(code, retry_after) => {+ cache.error_code = Some(code.into());+ cache.retry_after = retry_after;+ }+ }+ // Recover after a transient outage. On success spread the daily load across a 30 minute window.+ let jitter = (uuid::Uuid::new_v4().as_u128() % 1800) as u64;+ cache.next_background_at = Some(+ cache.retry_after.unwrap_or_else(|| finished + if cache.error_code.is_some() { 3600 } else { 86400 + jitter }),+ );+ write_json(&dir.join("release.json"), &cache)?;+ Ok(cache)+}++#[cfg(test)]+mod tests {+ use super::*;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ use tokio::net::TcpListener;++ const RELEASE: &str = r#"{"tag_name":"v1.2.3","html_url":"https://other.invalid/tag","draft":false,"prerelease":false,"published_at":"2026-11-01T01:02:03Z","assets":[{"name":"complete","state":"uploaded","size":10},{"name":"partial","state":"open","size":0}]}"#;++ fn response(status: &str, headers: &str, body: &str) -> String {+ format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n{headers}\r\n{body}", body.len())+ }++ async fn server(responses: Vec<String>) -> (String, tokio::task::JoinHandle<Vec<String>>) {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();+ let url = format!("http://{}/latest", listener.local_addr().unwrap());+ let task = tokio::spawn(async move {+ let mut requests = Vec::new();+ for response in responses {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ let mut buf = [0; 1024];+ while !request.ends_with(b"\r\n\r\n") {+ let n = socket.read(&mut buf).await.unwrap();+ assert!(n > 0);+ request.extend_from_slice(&buf[..n]);+ }+ requests.push(String::from_utf8(request).unwrap().to_lowercase());+ socket.write_all(response.as_bytes()).await.unwrap();+ }+ requests+ });+ (url, task)+ }++ fn local_client() -> Client {+ // Test servers are loopback only, independent of the developer's proxy environment.+ let _ = rustls::crypto::ring::default_provider().install_default();+ Client::builder().no_proxy().timeout(Duration::from_secs(3)).build().unwrap()+ }++ fn make_due(dir: &Path) {+ let mut cache = read(dir).unwrap();+ cache.last_attempt_at = Some(1);+ cache.next_background_at = Some(2);+ write_json(&dir.join("release.json"), &cache).unwrap();+ }++ #[test]+ fn release_requires_stable_semver_and_uploaded_assets() {+ for tag in ["v01.2.3", "v1.2", "v1.2.3-rc.1", "v1.2.3+local", "v1.2.3/another", "v1.2.3 ", "1.2.3"] {+ assert!(parse_release(RELEASE.replace("v1.2.3", tag).as_bytes()).is_none(), "{tag}");+ }+ for flag in ["draft", "prerelease"] {+ assert!(+ parse_release(RELEASE.replace(&format!(r#""{flag}":false"#), &format!(r#""{flag}":true"#)).as_bytes())+ .is_none()+ );+ }+ assert_eq!(parse_release(RELEASE.as_bytes()).unwrap().assets, ["complete"]);+ }++ #[tokio::test]+ async fn concurrent_checks_merge_and_304_preserves_metadata() {+ let dir = tempfile::tempdir().unwrap();+ let (url, requests) =+ server(vec![response("200 OK", "ETag: \"tag-1\"\r\n", RELEASE), response("304 Not Modified", "", "")])+ .await;+ let http = local_client();+ let (first, second) =+ tokio::join!(check(dir.path(), &http, &url, false), check(dir.path(), &http, &url, false));+ assert_eq!(first.unwrap().release.unwrap().tag, "v1.2.3");+ assert_eq!(second.unwrap().release.unwrap().tag, "v1.2.3");+ let mut cache = read(dir.path()).unwrap();+ cache.last_success_at = Some(1);+ cache.last_attempt_at = Some(1);+ write_json(&dir.path().join("release.json"), &cache).unwrap();+ // Background checks respect the daily interval even when manual refresh is due.+ assert_eq!(check(dir.path(), &http, &url, true).await.unwrap().last_success_at, Some(1));+ let fresh = check(dir.path(), &http, &url, false).await.unwrap();+ assert_eq!(fresh.release.unwrap().assets, ["complete"]);+ assert!(fresh.last_success_at.unwrap() > 1);+ assert!(fresh.error_code.is_none());+ let requests = requests.await.unwrap();+ assert_eq!(requests.len(), 2);+ assert!(requests[1].contains("if-none-match: \"tag-1\""));+ assert!(!requests[0].contains("authorization:"));+ }++ #[tokio::test]+ async fn rate_limit_and_network_failure_keep_last_success() {+ let dir = tempfile::tempdir().unwrap();+ let (url, requests) = server(vec![+ response("200 OK", "", RELEASE),+ response("403 Forbidden", "x-ratelimit-remaining: 0\r\nretry-after: 300\r\n", ""),+ ])+ .await;+ let http = local_client();+ let first = check(dir.path(), &http, &url, false).await.unwrap();+ make_due(dir.path());+ let throttled = check(dir.path(), &http, &url, false).await.unwrap();+ assert_eq!(throttled.error_code.as_deref(), Some("rate_limited"));+ assert!(throttled.retry_after.unwrap() >= throttled.last_attempt_at.unwrap() + 300);+ assert_eq!(throttled.last_success_at, first.last_success_at);+ make_due(dir.path());+ let deferred = check(dir.path(), &http, &url, false).await.unwrap();+ assert_eq!(deferred.last_attempt_at, Some(1));+ requests.await.unwrap(); // Drop listener; the following check cannot connect.+ let mut cache = read(dir.path()).unwrap();+ cache.retry_after = None;+ write_json(&dir.path().join("release.json"), &cache).unwrap();+ let offline = check(dir.path(), &http, &url, false).await.unwrap();+ assert_eq!(offline.error_code.as_deref(), Some("network"));+ assert_eq!(offline.release.unwrap().tag, "v1.2.3");+ assert_eq!(offline.last_success_at, first.last_success_at);+ let blank = tempfile::tempdir().unwrap();+ let offline = check(blank.path(), &http, &url, false).await.unwrap();+ assert!(offline.release.is_none() && offline.last_success_at.is_none());+ assert_eq!(offline.error_code.as_deref(), Some("network"));+ }++ #[test]+ fn reset_header_and_retry_http_date() {+ let mut headers = header::HeaderMap::new();+ headers.insert("x-ratelimit-reset", header::HeaderValue::from_static("1234"));+ assert_eq!(retry_at(&headers, 1000), 1234);+ headers.insert(header::RETRY_AFTER, header::HeaderValue::from_static("Thu, 01 Jan 1970 01:00:00 GMT"));+ assert_eq!(retry_at(&headers, 1000), 3600);+ }+}diff --git a/apps/iphone-control/src/update/transaction.rs b/apps/iphone-control/src/update/transaction.rsnew file mode 100644index 0000000..4af41c5--- /dev/null+++ b/apps/iphone-control/src/update/transaction.rs@@ -0,0 +1,612 @@+//! A replacement is recoverable using only the journal, the installed file and the pre-swap+//! executable. Commit metadata after two healthy snapshots; an unconfirmed swap restores the+//! original file. Each rename is synced before the next step.+use std::fs::{self, File};+use std::io;+use std::os::fd::AsRawFd;+use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt};+use std::path::{Path, PathBuf};+use std::time::Duration;++use anyhow::{Context, Result, bail, ensure};+use semver::Version;+use serde::{Deserialize, Serialize, de::DeserializeOwned};++use super::{Receipt, archive, digest, read_receipt, receipt_path, validate_receipt, write_json_atomic as write_json};+use crate::service::{self, Service};++#[derive(Clone, Serialize, Deserialize)]+pub struct Outcome {+ pub status: String,+ pub target_version: String,+ pub detail: String,+ pub suppressed_version: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub migration_source: Option<MigrationSource>,+}++#[derive(Clone, Serialize, Deserialize)]+pub struct MigrationSource {+ pub publisher: String,+ pub target: String,+ pub version: String,+}++impl MigrationSource {+ pub(super) fn matches(&self, publisher: &str, target: &str, version: &str) -> bool {+ self.publisher == publisher && self.target == target && self.version == version+ }++ fn from_receipt(receipt: &Receipt) -> Self {+ Self { publisher: receipt.publisher.clone(), target: receipt.target.clone(), version: receipt.version.clone() }+ }+}++impl Outcome {+ fn suppression_for(self, receipt: &Receipt) -> Option<String> {+ if let Some(src) = self.migration_source+ && !src.matches(&receipt.publisher, &receipt.target, &receipt.version)+ {+ return None;+ }+ self.suppressed_version+ }+}++#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+enum Phase {+ Prepared,+ Replaced,+ Confirmed,+}++#[derive(Serialize, Deserialize)]+struct Transaction {+ old: Receipt,+ new: Receipt,+ was_running: bool,+ rollback: bool,+ phase: Phase,+}++#[derive(Serialize, Deserialize)]+struct Previous {+ before_digest: String,+ receipt: Receipt,+}++fn state_dir(exe: &Path) -> Result<PathBuf> {+ Ok(exe.parent().context("invalid installation path")?.join(".iphone-control-update"))+}++fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>> {+ let file = match File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path) {+ Ok(f) => f,+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),+ Err(e) => return Err(e.into()),+ };+ ensure!(file.metadata()?.is_file() && file.metadata()?.len() <= 64 * 1024, "invalid updater state file");+ Ok(Some(serde_json::from_reader(file)?))+}++pub fn outcome(exe: &Path) -> Result<Option<Outcome>> {+ read_json(&state_dir(exe)?.join("outcome.json"))+}++struct Store {+ binary: PathBuf,+ dir: PathBuf,+ receipt: PathBuf,+ _lock: File,+}++impl Store {+ fn open(binary: &Path, receipt: PathBuf) -> Result<Self> {+ let parent = binary.parent().context("invalid installation path")?;+ let uid = unsafe { libc::geteuid() };+ let meta = parent.metadata()?;+ ensure!(+ uid != 0 && binary.canonicalize()? == binary && meta.uid() == uid && meta.mode() & 0o022 == 0,+ "unsafe installation directory"+ );+ let lock = File::options()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)+ .open(parent.join(".iphone-control-update.lock"))?;+ let meta = lock.metadata()?;+ ensure!(meta.is_file() && meta.uid() == uid && meta.mode() & 0o077 == 0, "unsafe updater lock");+ if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {+ return Err(io::Error::last_os_error()).context("another installation transaction is running");+ }+ let dir = state_dir(binary)?;+ match fs::DirBuilder::new().mode(0o700).create(&dir) {+ Ok(()) => File::open(parent)?.sync_all()?,+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}+ Err(e) => return Err(e.into()),+ }+ let meta = dir.symlink_metadata()?;+ ensure!(meta.is_dir() && meta.uid() == uid && meta.mode() & 0o077 == 0, "unsafe updater directory");+ Ok(Self { binary: binary.into(), receipt, dir, _lock: lock })+ }++ fn journal(&self) -> PathBuf {+ self.dir.join("transaction.json")+ }++ fn record(+ &self,+ status: &str,+ version: &str,+ detail: impl ToString,+ suppressed: Option<String>,+ migration_source: Option<MigrationSource>,+ ) -> Result<()> {+ write_json(+ &self.dir.join("outcome.json"),+ &Outcome {+ status: status.into(),+ target_version: version.into(),+ detail: detail.to_string(),+ suppressed_version: suppressed,+ migration_source,+ },+ )+ }++ fn stage(&self) -> Result<PathBuf> {+ let stage = self.dir.join("stage");+ if stage.exists() {+ fs::remove_dir_all(&stage)?;+ }+ fs::DirBuilder::new().mode(0o700).create(&stage)?;+ Ok(stage)+ }++ // Keep the source (including the independent recovery entry) callable even after rename.+ fn link(&self, source: &Path, dest: &Path) -> Result<()> {+ let tmp = self.dir.join("swap-link");+ if tmp.exists() {+ fs::remove_file(&tmp)?;+ }+ fs::hard_link(source, &tmp)?;+ fs::rename(&tmp, dest)?;+ File::open(dest.parent().context("missing destination directory")?)?.sync_all()?;+ File::open(&self.dir)?.sync_all()?;+ Ok(())+ }++ fn finish(&self, tx: &Transaction) -> Result<()> {+ write_json(&self.receipt, &tx.new)?;+ if !tx.rollback {+ self.link(&self.dir.join("recovery"), &self.dir.join("previous"))?;+ write_json(+ &self.dir.join("previous.json"),+ &Previous { before_digest: tx.new.sha256.clone(), receipt: tx.old.clone() },+ )?;+ }+ let (status, suppressed) =+ if tx.rollback { ("rolled_back", Some(tx.old.version.clone())) } else { ("installed", None) };+ self.record(status, &tx.new.version, "installation confirmed", suppressed, None)?;+ self.clear()+ }++ fn clear(&self) -> Result<()> {+ fs::remove_file(self.journal())?;+ File::open(&self.dir)?.sync_all()?;+ Ok(())+ }+}++trait Services {+ fn mark_pending(&self, _journal: &Path) -> Result<()> {+ Ok(())+ }+ fn exclusive(&self) -> Result<File>;+ async fn idle(&self, current: &Receipt) -> Result<bool>;+ async fn stop(&self) -> Result<()>;+ async fn start_healthy(&self, version: &str) -> Result<()>;+}++struct Host<'a> {+ service: Service,+ socket: &'a Path,+ binary: &'a Path,+}++#[cfg(target_os = "macos")]+fn process_path(pid: u32) -> Result<PathBuf> {+ use std::os::unix::ffi::OsStrExt;+ let mut buf = [0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];+ let n = unsafe { libc::proc_pidpath(pid as i32, buf.as_mut_ptr().cast(), buf.len() as u32) };+ ensure!(n > 0, "cannot identify daemon process");+ Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..n as usize])))+}++#[cfg(not(target_os = "macos"))]+fn process_path(pid: u32) -> Result<PathBuf> {+ Ok(fs::read_link(format!("/proc/{pid}/exe"))?)+}++fn check_clients(daemon: Option<u32>) -> Result<()> {+ // Older binaries don't take a shared lease. Refuse an existing client (also an installation+ // using a different socket) before restarting the service.+ let output = std::process::Command::new("ps").args(["-A", "-o", "uid=,pid=,comm="]).env("LC_ALL", "C").output()?;+ ensure!(output.status.success(), "cannot enumerate running clients");+ let uid = unsafe { libc::geteuid() };+ for line in std::str::from_utf8(&output.stdout)?.lines() {+ let mut parts = line.split_whitespace();+ if parts.next().and_then(|s| s.parse::<u32>().ok()) != Some(uid) {+ continue;+ }+ let pid = parts.next().and_then(|s| s.parse::<u32>().ok()).context("invalid process list")?;+ if daemon == Some(pid) || pid == std::process::id() {+ continue;+ }+ let command = parts.collect::<Vec<_>>().join(" ");+ ensure!(+ !Path::new(&command).file_name().is_some_and(|s| s == "iphone-control"),+ "busy: another iphone-control process ({pid}) is running"+ );+ }+ Ok(())+}++impl Host<'_> {+ fn owns_pid(&self, pid: u32) -> bool {+ process_path(pid)+ .and_then(|path| {+ let p = path.metadata()?;+ let b = self.binary.metadata()?;+ Ok(p.dev() == b.dev() && p.ino() == b.ino())+ })+ .unwrap_or(false)+ }++ async fn socket_owner(&self) -> Result<Option<u32>> {+ match tokio::net::UnixStream::connect(self.socket).await {+ Ok(s) => {+ let cred = s.peer_cred()?;+ ensure!(cred.uid() == unsafe { libc::geteuid() }, "unexpected daemon socket owner");+ Ok(Some(cred.pid().context("unknown daemon socket PID")?.try_into()?))+ }+ Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) => Ok(None),+ Err(e) => Err(e.into()),+ }+ }++ async fn healthy(&self, pid: u32, version: &str) -> bool {+ if !self.owns_pid(pid) {+ return false;+ }+ matches!(tokio::time::timeout(Duration::from_secs(2), crate::snapshot(self.socket)).await, Ok(Ok(s)) if s.maintenance == Some(true) && s.pid == Some(pid) && s.version.as_deref() == Some(version))+ }+}++impl Services for Host<'_> {+ fn mark_pending(&self, journal: &Path) -> Result<()> {+ Ok(ictl_daemon::maintenance::mark_pending(journal)?)+ }+ fn exclusive(&self) -> Result<File> {+ ictl_daemon::maintenance::exclusive()+ .context("busy; retry in a minute (the automatic job tries again next hour)")+ }++ async fn idle(&self, current: &Receipt) -> Result<bool> {+ service::managed(self.binary, ¤t.service)?;+ let pid = service::managed_pid(&self.service, false)?;+ check_clients(pid)?;+ if let Some(pid) = pid {+ ensure!(+ self.socket_owner().await? == Some(pid) && self.healthy(pid, ¤t.version).await,+ "busy: service and socket identity do not match"+ );+ } else {+ ensure!(self.socket_owner().await?.is_none(), "busy: a foreground daemon is running");+ }+ Ok(pid.is_some())+ }++ async fn stop(&self) -> Result<()> {+ let pid = service::managed_pid(&self.service, true)?;+ ensure!(pid.is_none_or(|p| self.owns_pid(p)), "service PID belongs to another executable");+ if let Some(peer) = self.socket_owner().await? {+ ensure!(Some(peer) == pid, "busy: socket is served by a different process");+ }+ service::stop(&self.service)?;+ let end = tokio::time::Instant::now() + Duration::from_secs(45);+ loop {+ let gone = pid.is_none_or(|p| unsafe { libc::kill(p as i32, 0) } < 0 && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH));+ if gone+ && service::managed_pid(&self.service, false).is_ok_and(|p| p.is_none())+ && self.socket_owner().await?.is_none()+ {+ return Ok(());+ }+ ensure!(tokio::time::Instant::now() < end, "timed out waiting for daemon exit");+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+ }++ async fn start_healthy(&self, version: &str) -> Result<()> {+ service::start_managed(&self.service)?;+ let mut first = None;+ let poll = async {+ loop {+ let mut seen = None;+ if let Ok(Some(pid)) = service::managed_pid(&self.service, false)+ && self.healthy(pid, version).await+ {+ if first == Some(pid) {+ return;+ }+ seen = Some(pid);+ }+ first = seen;+ tokio::time::sleep(Duration::from_millis(500)).await;+ }+ };+ tokio::time::timeout(Duration::from_secs(60), poll).await.context("daemon health check timed out")?;+ Ok(())+ }+}++async fn restore(store: &Store, host: &impl Services, tx: &Transaction, why: &str) -> Result<()> {+ let current = digest(&store.binary)?;+ ensure!(current == tx.old.sha256 || current == tx.new.sha256, "installed digest unknown; recovery stopped");+ let backup = store.dir.join("recovery");+ ensure!(digest(&backup)? == tx.old.sha256, "recovery executable digest mismatch");+ host.stop().await?;+ if current != tx.old.sha256 {+ store.link(&backup, &store.binary)?;+ }+ if tx.was_running {+ host.start_healthy(&tx.old.version).await?;+ }+ write_json(&store.receipt, &tx.old)?;+ store.record("restored", &tx.new.version, why, Some(tx.new.version.clone()), None)?;+ store.clear()+}++async fn replace(+ store: &Store,+ host: &impl Services,+ old: Receipt,+ new: Receipt,+ candidate: &Path,+ rollback: bool,+ auto: bool,+) -> Result<()> {+ let activity = async {+ let lease = host.exclusive()?;+ let running = host.idle(&old).await?;+ ensure!(running || !auto, "busy: managed service is stopped");+ Ok::<_, anyhow::Error>((lease, running))+ }+ .await;+ let (_lease, running) = match activity {+ Ok(activity) => activity,+ Err(e) => {+ let suppressed = outcome(&store.binary)?.and_then(|o| o.suppression_for(&old));+ store.record("busy", &new.version, format!("{e:#}"), suppressed, None)?;+ return Err(e);+ }+ };+ if auto {+ ensure!(matches!(super::cached()?.policy, super::Policy::AutoPatch), "automatic installation was disabled");+ }+ validate_receipt(&old, &store.binary)?;+ ensure!(digest(candidate)? == new.sha256, "staged executable changed");+ eprintln!(+ "{} → {} ({}; {})",+ old.version,+ new.version,+ old.service,+ if running { "idle, restarting daemon" } else { "stopped, verifying then restoring stopped state" }+ );+ host.mark_pending(&store.journal())?;+ store.link(&store.binary, &store.dir.join("recovery"))?;+ let mut tx = Transaction { old, new, was_running: running, rollback, phase: Phase::Prepared };+ write_json(&store.journal(), &tx)?;++ let swap = async {+ if running {+ host.stop().await?;+ }+ store.link(candidate, &store.binary)?;+ tx.phase = Phase::Replaced;+ write_json(&store.journal(), &tx)?;+ host.start_healthy(&tx.new.version).await?;+ if !running {+ host.stop().await?;+ }+ Ok::<_, anyhow::Error>(())+ }+ .await;+ if let Err(e) = swap {+ restore_or_report(store, host, &tx, &format!("{e:#}")).await?;+ bail!("update failed; restored {}: {e:#}", tx.old.version);+ }+ tx.phase = Phase::Confirmed;+ write_json(&store.journal(), &tx)?;+ store.finish(&tx)+}++async fn restore_or_report(store: &Store, host: &impl Services, tx: &Transaction, why: &str) -> Result<()> {+ if let Err(e) = restore(store, host, tx, why).await {+ let detail = format!(+ "{why}; recovery failed: {e:#}. Last working version {} at {}. Run update recover after resolving the error.",+ tx.old.version,+ store.dir.join("recovery").display()+ );+ store.record("recovery_failed", &tx.new.version, &detail, Some(tx.new.version.clone()), None)?;+ bail!(detail);+ }+ Ok(())+}++pub(super) fn eligible(old: &str, new: &str, automatic: bool) -> Result<()> {+ let old = Version::parse(old)?;+ let new = Version::parse(new)?;+ ensure!(old.pre.is_empty() && new.pre.is_empty() && new.cmp_precedence(&old).is_gt(), "no newer stable release");+ ensure!(+ !automatic || (old.major == new.major && old.minor == new.minor && old.patch < new.patch),+ "only patch releases can be installed automatically"+ );+ Ok(())+}++fn managed(receipt: &Receipt) -> Result<(Store, Service)> {+ validate_receipt(receipt, &std::env::current_exe()?)?;+ ensure!(receipt.version == env!("CARGO_PKG_VERSION"), "running updater version differs from installed version");+ let store = Store::open(&receipt.binary_path, receipt_path())?;+ let reread = read_receipt()?;+ ensure!(+ same_install(receipt, &reread)+ && reread.sha256 == receipt.sha256+ && reread.version == receipt.version+ && reread.pinned == receipt.pinned,+ "installation changed; retry"+ );+ validate_receipt(receipt, &store.binary)?;+ ensure!(!store.journal().try_exists()?, "interrupted update; run iphone-control update recover");+ let svc = service::managed(&store.binary, &receipt.service)?;+ Ok((store, svc))+}++pub async fn apply(socket: &Path, background: bool) -> Result<()> {+ let receipt = read_receipt()?;+ let (store, service) = managed(&receipt)?;+ ensure!(!receipt.pinned, "this installation is pinned; unpin it locally first");+ let report = super::check(background).await?;+ ensure!(report.error_code.is_none(), "release check failed: {:?}", report.error_code);+ ensure!(matches!(report.availability, super::Availability::Available), "{}", report.guidance);+ let version = report.available_version.context("no stable release is available")?;+ eligible(&receipt.version, &version, background)?;+ let host = Host { service, socket, binary: &store.binary };+ if background {+ ensure!(matches!(report.policy, super::Policy::AutoPatch), "automatic installation is disabled");+ let suppressed = outcome(&store.binary)?.and_then(|o| o.suppression_for(&receipt));+ ensure!(+ suppressed.as_ref() != Some(&version),+ "automatic retry suppressed for {version}; run update apply to retry"+ );+ // An always-open client may stay busy for days. The lease here is deliberately+ // short-lived; replacement reacquires it and rechecks identity after download.+ if let Err(e) = host.exclusive() {+ store.record("busy", &version, format!("{e:#}"), suppressed, None)?;+ return Err(e);+ }+ }+ let stage = store.stage()?;+ let work = async {+ let candidate = match archive::stage(&stage, &receipt, &version, background).await {+ Ok(candidate) => candidate,+ Err(e) => {+ let suppressed = if e.downcast_ref::<reqwest::Error>().is_some() {+ outcome(&store.binary)?.and_then(|o| o.suppression_for(&receipt))+ } else {+ Some(version.clone())+ };+ let status = failure_status(&e);+ let source = e.is::<archive::ManualMigration>().then(|| MigrationSource::from_receipt(&receipt));+ store.record(status, &version, format!("{e:#}"), suppressed, source)?;+ return Err(e);+ }+ };+ let next = Receipt { version, sha256: digest(&candidate)?, ..receipt.clone() };+ replace(&store, &host, receipt, next, &candidate, false, background).await+ }+ .await;+ let _ = fs::remove_dir_all(&stage);+ work+}++/// The outcome recorded when staging a release fails. A release that only isn't marked for unattended+/// installation is no failure: the automatic job leaves it to `update apply` (and doesn't download it again)+fn failure_status(e: &anyhow::Error) -> &'static str {+ if e.is::<archive::ManualMigration>() {+ "manual_migration"+ } else if e.is::<archive::NeedsOperator>() {+ "needs_operator"+ } else {+ "failed"+ }+}++pub fn unpin() -> Result<()> {+ let mut receipt = read_receipt()?;+ let (store, _) = managed(&receipt)?;+ receipt.pinned = false;+ write_json(&store.receipt, &receipt)+}++pub async fn rollback(socket: &Path) -> Result<()> {+ let receipt = read_receipt()?;+ let (store, service) = managed(&receipt)?;+ let previous: Previous =+ read_json(&store.dir.join("previous.json"))?.context("no compatible previous installation")?;+ ensure!(+ receipt.sha256 == previous.before_digest && same_install(&receipt, &previous.receipt),+ "rollback belongs to a different installation"+ );+ let candidate = store.dir.join("previous");+ ensure!(digest(&candidate)? == previous.receipt.sha256, "previous executable digest mismatch");+ archive::preflight(&candidate, &previous.receipt.version).await?;+ let host = Host { service, socket, binary: &store.binary };+ replace(&store, &host, receipt, previous.receipt, &candidate, true, false).await+}++fn same_install(a: &Receipt, b: &Receipt) -> bool {+ a.schema == b.schema+ && a.binary_path == b.binary_path+ && a.publisher == b.publisher+ && a.target == b.target+ && a.service == b.service+}++async fn resume(store: &Store, host: &impl Services, tx: &Transaction) -> Result<()> {+ let _maintenance = host.exclusive()?;+ host.mark_pending(&store.journal())?;+ let current = digest(&store.binary)?;+ if matches!(tx.phase, Phase::Confirmed) {+ ensure!(current == tx.new.sha256, "confirmed executable changed; preserving transaction");+ store.finish(tx)+ } else {+ restore_or_report(store, host, tx, "interrupted installation").await+ }+}++pub async fn recover(socket: &Path, scheduled: bool) -> Result<()> {+ let receipt = read_receipt()?;+ let store = Store::open(&receipt.binary_path, receipt_path())?;+ let Some(tx) = read_json::<Transaction>(&store.journal())? else { return Ok(()) };+ if scheduled+ && outcome(&store.binary)?.is_some_and(|o| o.status == "recovery_failed" && o.target_version == tx.new.version)+ {+ bail!("automatic recovery paused; resolve the recorded error and run update recover");+ }+ ensure!(+ same_install(&receipt, &tx.old)+ && same_install(&receipt, &tx.new)+ && (receipt.sha256 == tx.old.sha256 || receipt.sha256 == tx.new.sha256),+ "journal and receipt do not match"+ );+ let caller = std::env::current_exe()?.canonicalize()?;+ let backup = store.dir.join("recovery");+ ensure!(+ caller == store.binary || (caller == backup && digest(&backup)? == tx.old.sha256),+ "invalid recovery entry point"+ );+ let service = service::managed(&store.binary, &receipt.service)?;+ check_clients(service::managed_pid(&service, true)?)?;+ let host = Host { service, socket, binary: &store.binary };+ resume(&store, &host, &tx).await+}++#[cfg(test)]+mod tests;diff --git a/apps/iphone-control/src/update/transaction/tests.rs b/apps/iphone-control/src/update/transaction/tests.rsnew file mode 100644index 0000000..2a104e2--- /dev/null+++ b/apps/iphone-control/src/update/transaction/tests.rs@@ -0,0 +1,362 @@+use super::*;+use std::cell::{Cell, RefCell};+use std::io::{BufRead, BufReader, Write};+use std::os::unix::fs::PermissionsExt;+use std::os::unix::net::{UnixListener, UnixStream};+use std::process::{Child, Command, Stdio};++// The installed fixture really runs as a separate process, answers Daemon snapshots on a+// private socket and knows its own version. No host service or attached phone is involved.+#[test]+fn fixture_daemon() {+ let Some(socket) = std::env::var_os("ICTL_TEST_TX_SOCKET") else { return };+ let version = std::env::var("ICTL_TEST_TX_VERSION").unwrap();+ let listener = UnixListener::bind(&socket).unwrap();+ std::thread::spawn(|| {+ std::thread::sleep(Duration::from_secs(90));+ std::process::exit(0);+ });+ for stream in listener.incoming() {+ let mut stream = stream.unwrap();+ let mut line = String::new();+ if BufReader::new(&stream).read_line(&mut line).unwrap_or(0) == 0 {+ continue;+ }+ if line.trim_end() == "fixture-stop" {+ return;+ }+ let snapshot = serde_json::json!({+ "version": version, "pid":std::process::id(), "state":{"state":"absent"}, "device":null,+ "persisted":{}, "auto_unlock":false, "unlock_disabled":false, "notify_configured":false, "log_tail":[]+ });+ let response = ictl_daemon::protocol::Response::text(snapshot.to_string());+ let _ = writeln!(stream, "{}", serde_json::to_string(&response).unwrap());+ }+}++fn binary(path: &Path, version: &str, reported: &str) {+ let text = format!(+ "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'iphone-control {version}'; exit; fi\nexport ICTL_TEST_TX_VERSION='{reported}'\nexec \"$ICTL_TEST_TX_HARNESS\" --exact update::transaction::tests::fixture_daemon\n"+ );+ fs::write(path, text).unwrap();+ fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();+}++fn receipt(bin: &Path, version: &str, sha256: String) -> Receipt {+ Receipt {+ schema: 1,+ publisher: "example/repo".into(),+ target: "fixture".into(),+ version: version.into(),+ binary_path: bin.into(),+ service: "fixture".into(),+ pinned: false,+ sha256,+ }+}++struct Fixture {+ _dir: tempfile::TempDir,+ store: Store,+ host: TestService,+ old: Receipt,+ new: Receipt,+ candidate: PathBuf,+}++struct TestService {+ socket: PathBuf,+ binary: PathBuf,+ child: RefCell<Option<Child>>,+ busy: Cell<bool>,+}++impl TestService {+ fn terminate(&self) {+ if let Some(mut child) = self.child.borrow_mut().take() {+ let _ = child.kill();+ child.wait().unwrap();+ } else if let Ok(mut orphan) = UnixStream::connect(&self.socket) {+ // A replacement launched by the killed worker is still running under its supervisor.+ orphan.set_read_timeout(Some(Duration::from_secs(2))).unwrap();+ writeln!(orphan, "fixture-stop").unwrap();+ assert_eq!(BufReader::new(orphan).read_line(&mut String::new()).unwrap(), 0);+ }+ let _ = fs::remove_file(&self.socket);+ }+}++impl Drop for TestService {+ fn drop(&mut self) {+ self.terminate();+ }+}++impl Services for TestService {+ fn exclusive(&self) -> Result<File> {+ ensure!(!self.busy.get(), "busy: fixture device control");+ Ok(File::open(&self.binary)?)+ }++ async fn idle(&self, _: &Receipt) -> Result<bool> {+ Ok(self.child.borrow().is_some())+ }+ async fn stop(&self) -> Result<()> {+ self.terminate();+ Ok(())+ }+ async fn start_healthy(&self, version: &str) -> Result<()> {+ let child = Command::new(&self.binary)+ .arg("daemon")+ .env("ICTL_TEST_TX_HARNESS", std::env::current_exe()?)+ .env("ICTL_TEST_TX_SOCKET", &self.socket)+ .stdout(Stdio::null())+ .spawn()?;+ let pid = child.id();+ self.child.replace(Some(child));+ for _ in 0..2 {+ let snap = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ if let Ok(s) = crate::snapshot(&self.socket).await {+ break s;+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await?;+ ensure!(snap.version.as_deref() == Some(version) && snap.pid == Some(pid), "bad fixture health");+ }+ Ok(())+ }+}++impl Fixture {+ fn new(reported: &str) -> Self {+ let dir = tempfile::tempdir_in("/tmp").unwrap();+ let base = dir.path().canonicalize().unwrap();+ let bin = base.join("iphone-control");+ let candidate = base.join("patch");+ binary(&bin, "0.2.0", "0.2.0");+ binary(&candidate, "0.2.1", reported);+ let store = Store::open(&bin, base.join("receipt.json")).unwrap();+ let old = receipt(&bin, "0.2.0", digest(&bin).unwrap());+ let new = receipt(&bin, "0.2.1", digest(&candidate).unwrap());+ write_json(&store.receipt, &old).unwrap();+ let host = TestService {+ socket: base.join("daemon.sock"),+ binary: bin,+ child: RefCell::default(),+ busy: Cell::new(false),+ };+ Self { _dir: dir, host, store, old, new, candidate }+ }++ async fn apply(&self) -> Result<()> {+ replace(&self.store, &self.host, self.old.clone(), self.new.clone(), &self.candidate, false, false).await+ }++ fn assert_installed(&self, expected: &Receipt) {+ assert_eq!(read_json::<Receipt>(&self.store.receipt).unwrap().unwrap().sha256, expected.sha256);+ assert_eq!(digest(&self.store.binary).unwrap(), expected.sha256);+ assert!(!self.store.journal().exists());+ }+}++#[tokio::test]+async fn busy_then_replace_and_explicit_rollback_while_daemon_is_running() {+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let f = Fixture::new("0.2.1");+ let state = f.store.dir.parent().unwrap().join("state.json");+ fs::write(&state, "untouched device state").unwrap();+ f.host.start_healthy(&f.old.version).await.unwrap();+ let pid = f.host.child.borrow().as_ref().unwrap().id();+ f.host.busy.set(true);+ assert!(f.apply().await.is_err());+ f.assert_installed(&f.old);+ assert_eq!(outcome(&f.store.binary).unwrap().unwrap().status, "busy");+ assert_eq!(f.host.child.borrow().as_ref().unwrap().id(), pid);+ f.host.busy.set(false);+ f.apply().await.unwrap();+ f.assert_installed(&f.new);+ assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.new.version);+ let p: Previous = read_json(&f.store.dir.join("previous.json")).unwrap().unwrap();+ let previous = f.store.dir.join("previous");+ assert_eq!(p.before_digest, f.new.sha256);+ assert_eq!(digest(&previous).unwrap(), p.receipt.sha256);+ replace(&f.store, &f.host, f.new.clone(), p.receipt, &previous, true, false).await.unwrap();+ f.assert_installed(&f.old);+ assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);+ assert_eq!(outcome(&f.store.binary).unwrap().unwrap().suppressed_version.unwrap(), f.new.version);+ assert_eq!(fs::read_to_string(&state).unwrap(), "untouched device state");+}++#[tokio::test]+async fn unhealthy_daemon_restores_last_verified_executable_and_service() {+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let f = Fixture::new("incorrect-version");+ f.host.start_healthy(&f.old.version).await.unwrap();+ assert!(f.apply().await.is_err());+ f.assert_installed(&f.old);+ assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);+ let result = outcome(&f.store.binary).unwrap().unwrap();+ assert_eq!(result.status, "restored");+ assert_eq!(result.suppressed_version.unwrap(), f.new.version);+}++#[tokio::test]+async fn operator_update_preserves_stopped_state() {+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let f = Fixture::new("0.2.1");+ f.apply().await.unwrap();+ f.assert_installed(&f.new);+ assert!(f.host.child.borrow().is_none());+}++struct Interrupted {+ stage: String,+ host: TestService,+}+impl Interrupted {+ fn die(&self, phase: &str) {+ if self.stage == phase {+ unsafe {+ libc::kill(libc::getpid(), libc::SIGKILL);+ }+ }+ }+}+impl Services for Interrupted {+ fn exclusive(&self) -> Result<File> {+ Ok(File::open("/dev/null")?)+ }+ async fn idle(&self, _: &Receipt) -> Result<bool> {+ Ok(true)+ }+ async fn stop(&self) -> Result<()> {+ self.die("prepared");+ Ok(())+ }+ async fn start_healthy(&self, version: &str) -> Result<()> {+ self.die("replaced");+ self.host.start_healthy(version).await?;+ self.die("starting");+ Ok(())+ }+}++#[tokio::test]+async fn interrupted_worker() {+ let Some(dir) = std::env::var_os("ICTL_TEST_INTERRUPTED") else { return };+ let dir = PathBuf::from(dir);+ let b = dir.join("iphone-control");+ let c = dir.join("patch");+ let store = Store::open(&b, dir.join("receipt.json")).unwrap();+ let old = receipt(&b, "0.2.0", digest(&b).unwrap());+ let new = receipt(&b, "0.2.1", digest(&c).unwrap());+ let host = Interrupted {+ stage: std::env::var("ICTL_TEST_PHASE").unwrap(),+ host: TestService {+ socket: dir.join("daemon.sock"),+ binary: b,+ child: RefCell::default(),+ busy: Cell::new(false),+ },+ };+ replace(&store, &host, old, new, &c, false, false).await.unwrap();+}++#[tokio::test]+async fn recovers_after_process_death_using_only_durable_records() {+ use std::os::unix::process::ExitStatusExt;+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ for phase in ["prepared", "replaced", "starting"] {+ let f = Fixture::new("0.2.1");+ let binary = f.store.binary.clone();+ let receipt_file = f.store.receipt.clone();+ drop(f.store);+ let status = Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "update::transaction::tests::interrupted_worker"])+ .env("ICTL_TEST_INTERRUPTED", binary.parent().unwrap())+ .env("ICTL_TEST_PHASE", phase)+ .stdout(Stdio::null())+ .status()+ .unwrap();+ assert_eq!(status.signal(), Some(libc::SIGKILL));+ let store = Store::open(&binary, receipt_file).unwrap();+ let mut tx: Transaction = read_json(&store.journal()).unwrap().unwrap();+ assert_eq!(+ digest(&store.binary).unwrap(),+ if phase == "prepared" { &f.old.sha256 } else { &f.new.sha256 }.as_str()+ );+ // A kill in the interval after the rename but before its phase checkpoint leaves a+ // prepared journal with the new digest on disk.+ if phase == "replaced" {+ tx.phase = Phase::Prepared;+ write_json(&store.journal(), &tx).unwrap();+ }+ if phase == "starting" {+ assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.new.version);+ }+ resume(&store, &f.host, &tx).await.unwrap();+ assert_eq!(digest(&store.binary).unwrap(), f.old.sha256);+ assert!(!store.journal().exists());+ assert_eq!(crate::snapshot(&f.host.socket).await.unwrap().version.unwrap(), f.old.version);+ }+}++#[test]+fn automatic_policy_rejects_minor_releases_replays_and_prereleases() {+ for new in ["0.2.0", "0.1.9", "0.2.1-beta.1", "0.3.0", "1.2.1"] {+ assert!(eligible("0.2.0", new, true).is_err());+ }+ assert!(eligible("0.2.0", "0.2.1", true).is_ok());+ assert!(eligible("0.2.0", "0.3.0", false).is_ok());+}++#[tokio::test]+async fn confirmed_checkpoint_finishes_metadata_and_unknown_disk_is_preserved() {+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let f = Fixture::new("0.2.1");+ f.store.link(&f.store.binary, &f.store.dir.join("recovery")).unwrap();+ f.store.link(&f.candidate, &f.store.binary).unwrap();+ let mut tx = Transaction {+ old: f.old.clone(),+ new: f.new.clone(),+ was_running: false,+ rollback: false,+ phase: Phase::Confirmed,+ };+ write_json(&f.store.journal(), &tx).unwrap();+ resume(&f.store, &f.host, &tx).await.unwrap();+ f.assert_installed(&f.new);+ assert_eq!(digest(&f.store.dir.join("previous")).unwrap(), f.old.sha256);++ tx.phase = Phase::Replaced;+ write_json(&f.store.journal(), &tx).unwrap();+ fs::write(&f.store.binary, "changed outside updater").unwrap();+ assert!(resume(&f.store, &f.host, &tx).await.is_err());+ assert!(f.store.journal().is_file());+ assert_eq!(fs::read_to_string(&f.store.binary).unwrap(), "changed outside updater");+ assert_eq!(outcome(&f.store.binary).unwrap().unwrap().status, "recovery_failed");+ assert_eq!(digest(&f.store.dir.join("recovery")).unwrap(), f.old.sha256);+}++/// Staging failures and what is recorded: a release only not marked unattended is left to `update apply`,+/// distinct from a broken download+#[test]+fn a_release_without_unattended_mark_is_not_a_failure() {+ let e = anyhow::Error::from(archive::NeedsOperator("0.2.2".into()));+ assert_eq!(failure_status(&e), "needs_operator");+ assert!(e.to_string().contains("update apply"), "{e}");+ assert_eq!(failure_status(&anyhow::anyhow!("archive digest mismatch")), "failed");+}diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.htmlindex d6f6baf..c0cf983 100644--- a/apps/iphone-control/src/viewer.html+++ b/apps/iphone-control/src/viewer.html@@ -505,6 +505,21 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }.dialog[open] { animation: rise var(--dur) var(--ease-out); }.dialog h2 { font-size: var(--fs-lg); margin-bottom: var(--sp-2); }.dialog p { color: var(--text-2); }+#updates-dialog { background: color-mix(in srgb, var(--panel) 90%, transparent); backdrop-filter: blur(22px); }+#updates-dialog .update-head { display: flex; justify-content: space-between; align-items: center; }+#updates-dialog h2 { margin: 0; }+#about-updates { position: relative; }+#update-dot { position: absolute; top: 2px; right: 2px; width: 7px; height: 7px; border-radius: 50%; background: var(--danger); box-shadow: 0 0 0 2px var(--panel); }+#update-command-block { margin-top: var(--sp-3); padding: var(--sp-3); border-radius: var(--r-sm); background: var(--press); }+.update-command-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }+#update-command { display: block; margin-top: var(--sp-2); font-family: var(--font-mono); font-size: var(--fs-sm); overflow-wrap: anywhere; white-space: pre-wrap; user-select: all; }+#update-copy-status:empty { display: none; }+#updates-dialog .dialog-actions { flex-wrap: wrap; }+.update-version { margin: var(--sp-4) 0; font: 600 var(--fs-xl)/1.3 var(--font-mono); }+.update-facts { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: var(--sp-1) var(--sp-3); margin: var(--sp-3) 0; }+.update-facts dt { color: var(--text-2); }+.update-facts dd, .update-detail { margin: 0; overflow-wrap: anywhere; white-space: pre-line; }+.update-detail { margin-top: var(--sp-2); }.dialog-actions { display: flex; justify-content: flex-end; gap: var(--sp-2); margin-top: var(--sp-6); }/* ================= 演示画面(代码绘制的模拟界面;iPhone 393×852 点,iPad mini 横屏 1133×744 点) ================= */@@ -671,6 +686,7 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }</div><span id="agent-badge"></span><button type="button" class="btn btn-ghost btn-sm clear-btn" id="clear-btn" data-action="clear" data-focus="clear" hidden><span class="ic" data-icon="trash"></span><span>清空记录</span></button>+ <button type="button" class="btn btn-ghost btn-icon btn-sm" id="about-updates" aria-label="关于与更新" title="关于与更新" aria-haspopup="dialog"><svg width="17" height="17" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><circle cx="10" cy="10" r="8"/><path d="M10 9v5m0-8v1"/></svg><span id="update-dot" aria-hidden="true" hidden></span></button><button type="button" class="btn btn-ghost btn-sm lang-btn" id="lang-btn" aria-label="切换语言" title="切换语言">EN</button></div><div class="pane-body" id="agent-scroll">@@ -823,6 +839,23 @@ body.resizing .stage, body.resizing iframe { pointer-events: none; }</aside></div>+<dialog class="dialog" id="updates-dialog" aria-labelledby="updates-title">+ <div class="update-head"><h2 id="updates-title">关于与更新</h2><form method="dialog"><button class="btn btn-ghost btn-sm">完成</button></form></div>+ <div class="update-version" id="update-version"></div>+ <dl class="update-facts" id="update-facts"></dl>+ <strong id="update-result" role="status"></strong>+ <p class="update-detail" id="update-guide"></p>+ <div id="update-command-block" hidden>+ <div class="update-command-head"><strong>升级命令</strong><button class="btn btn-sm" id="update-copy" type="button">复制命令</button></div>+ <code id="update-command"></code>+ <p class="update-detail" id="update-copy-status" role="status"></p>+ </div>+ <p class="update-detail" id="update-policy"></p>+ <p class="update-detail" id="update-outcome"></p>+ <p class="update-detail" id="update-mismatch"></p>+ <div class="dialog-actions"><a class="btn btn-ghost" id="update-release" target="_blank" rel="noreferrer" hidden>发行说明</a>+ <button class="btn btn-primary" id="update-check" type="button" disabled>检查更新</button></div>+</dialog><dialog class="dialog" id="clear-dialog" aria-labelledby="clear-title" aria-describedby="clear-desc"><h2 id="clear-title">清空全部操作记录?</h2><p id="clear-desc">只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。</p>@@ -855,6 +888,7 @@ const LANG = (() => {})();document.documentElement.lang = LANG === 'en' ? 'en' : 'zh-CN';const EN = {" · 演示数据":" · demo data"," 等":" and more","<div class=\"ph-kb\" data-type=\"Keyboard\">键盘</div>":"<div class=\"ph-kb\" data-type=\"Keyboard\">Keyboard</div>","<li class=\"empty-note\">打开这一页时会读取已安装的 App。</li>":"<li class=\"empty-note\">The installed apps are read when this tab opens.</li>","<li class=\"sr-only\">正在读取 App 列表…</li>":"<li class=\"sr-only\">Reading the app list…</li>","<li class=\"sr-only\">正在读取元素…</li>":"<li class=\"sr-only\">Reading elements…</li>","<option>没有可用的 AI</option>":"<option>No AI available</option>","<p class=\"empty-note\">正在连接 iphone-control 服务…</p>":"<p class=\"empty-note\">Connecting to the iphone-control service…</p>","<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>演示模式</span></span>":"<span class=\"chip\"><span class=\"chip-dot warn\"></span><span>Demo</span></span>","AI 任务已停止":"AI task stopped","AI 任务已完成":"AI task done","AI 任务没有完成":"AI task not done","AI 任务的事件流断开了,正在重连…":"Lost the AI task's event stream, reconnecting…","AI 会立刻停下。已经在设备上做完的操作不会撤销。":"The AI stops right away. What it already did on the device isn't undone.","AI 助手":"AI assistant","AI 在等你确认一步操作":"The AI is waiting for you to confirm a step","AI 在等你确认一步操作,确认前画面保持锁定。":"The AI is waiting for you to confirm a step; the screen stays locked until you do.","AI 已暂停":"AI paused","AI 已暂停。交还后它会先重新看一遍屏幕。":"The AI is paused. When you hand back, it looks at the screen again first.","AI 正在操作这台设备":"The AI is operating this device","AI 正在操作这台设备。要自己操作,先点「接管」。":"The AI is operating this device. To act yourself, click “Take over” first.","AI 继续执行":"AI resumed","AI 能用的操作":"Actions the AI can use","Enter 发送 · Shift+Enter 换行":"Enter to send · Shift+Enter for a new line","HID 后备":"HID fallback","USB 连接":"USB connection","WDA 已签名安装":"WDA signed and installed","WDA 运行中":"WDA running","https://… 或 App 的 URL scheme":"https://… or an app's URL scheme","iMessage 信息":"iMessage","iOS 版本":"iOS Version","iPad mini(第 6 代)":"iPad mini (6th generation)","iphone-control 控制台":"iphone-control console","、":", ","。":".","。可以换个说法再试,或者接管后手动完成。":". Try rephrasing, or take over and finish by hand.","「":"“","」":"”","」。":"”.","」。界面可能已经变了,需要重新截图判断。":"” on the screen. It may have changed; take a new screenshot.","」出现,最多 5 秒":"” to appear, up to 5 s","」发给「":"” to “","」已在前台":"” is in front","」已经出现(":"” appeared (","」的 App。":"”.","」的元素。":"”.","」的对话":"”","」的对话。":"”.","」,能看到:":"”, showing: ","」:":"”: ","一共":"","上滑:":": ","与「":"Chat with “","世界时钟":"World Clock","个":"items","个带文字的元素":"elements with text","个步骤":"steps","个闹钟":"alarms","个闹钟:":"alarms: ","主屏幕":"Home Screen","乐":"M","交给 AI 的任务":"Task for the AI","交还 AI":"Hand back","今天":"Today","今天,−13 小时":"Today, −13 hours","今天,−8 小时":"Today, −8 hours","从":"Swipe up from","任务已交给 AI,画面的手动操作已锁定":"Task handed to the AI; manual control of the screen is locked","任务控制":"Task controls","任务没能交给 AI。手动操作和设备面板不受影响。":"The task couldn't be handed to the AI. Manual control and the device panel still work.","任务记录":"Task history","伦敦":"London","你刚才接管过设备,先重新看一下界面再继续。":"You took over the device just now, so first a fresh look at the screen.","你在接管":"You're in control","你已接管:现在可以直接在画面上操作。":"You're in control: act on the screen directly now.","你拒绝了发送。消息还留在输入框里,没有发出。":"You declined to send. The message is still in the text field, not sent.","你拒绝了这一步,没有执行。":"You rejected this step; it wasn't done.","例如:秒表":"e.g. Stopwatch","信":"M","信任这台电脑":"Trust this computer","信息":"Messages","停止":"Stop","停止任务":"Stop task","停止这个任务?":"Stop this task?","健康":"Health","像素":"px","元素":"Elements","先写下要 AI 做的事,例如「打开设置,查看系统版本」。":"First write what the AI should do, for example “Open Settings and check the iOS version”.","先填要打开的链接":"Enter the link to open first","先填要等的文字。":"Enter the text to wait for first.","先看一下设备现在的界面。":"First a look at the device's screen.","先输入要打到设备上的文字":"Enter the text to type on the device first","全部就绪":"All ready","关":"off","关于本机":"About","内容填好了。发消息需要你先确认。":"The message is ready. Sending it needs your confirmation.","再点「关于本机」。":"Then tap “About”.","切到「":"Switched to “","切换到实际尺寸(100%)":"Actual size (100%)","切换视图":"Switch view","切换语言":"Switch language","列表里没有闹钟":"No alarms in the list","删除":"Delete","删除这条记录":"Delete this record","刷新":"Refresh","刷新 App 列表":"Refresh the app list","刷新画面":"Refresh the picture","前台":"Front","前台 App":"Foreground app","助手":"assistant","包含系统 App":"Include system apps","北京":"Beijing","去确认":"Review","发给「":"To “","发送":"Send","发送消息":"Send message","取消":"Cancel","只清除左侧的任务和步骤记录,不会影响设备上已经做过的操作。清空后无法恢复。":"Only clears the tasks and steps on the left; nothing already done on the device changes. This can't be undone.","名称":"Name","向上轻扫以打开":"Swipe up to open","向设备输入文字":"Type on the device","启动":"Start","启动、关闭 App":"Open and quit apps","周末":"Weekends","回到「信息」列表":"Back to the Messages list","回到主屏幕":"Back to the Home Screen","图":"M","在第":"Stopped at step","在设备「设置 › 隐私与安全性 › 开发者模式」里打开,重启后确认。":"Turn it on in Settings › Privacy & Security › Developer Mode on the device, then confirm after the restart.","地图":"Maps","型号名称":"Model Name","型号未知":"Unknown model","备忘录":"Notes","复位":"Reset","天气":"Weather","失败":"Failed","妈妈":"Mom","它不是可点的控件,界面没有变化":"it isn't a control, nothing changed","完成":"Done","实体按键":"Hardware buttons","实时画面":"Live","容量":"Capacity","就绪":"Ready","就绪检查":"Readiness","屏幕":"Screen","屏幕尺寸":"Screen size","工作日":"Weekdays","已中止":"Stopped","已交还 AI,它会先重新看一遍屏幕":"Handed back to the AI; it looks at the screen again first","已停止":"Stopped","已切换到":"Switched to","已删除这条记录":"Record deleted","已刷新演示画面":"Demo screen refreshed","已发送给「":"Sent to “","已回到主屏幕。":"Back on the Home Screen.","已安装的 App":"Installed apps","已完成":"Done","已批准,AI 继续执行":"Approved, the AI continues","已把「":"Sent “","已拒绝":"Rejected","已拒绝这一步":"Step rejected","已改为自动选择:继续控制":"Switched to automatic: still controlling","已显示设备面板":"Device panel shown","已暂停":"Paused","已清空操作记录":"History cleared","已用 IPHONE_UDID 固定设备,不能切换":"IPHONE_UDID pins the device, so it can't be switched","已用 Safari 打开":"Opened in Safari:","已经在控制这台设备":"Already controlling this device","已结束「":"Quit “","已自动解锁,回到主屏幕":"Unlocked automatically, back to the Home Screen","已设置密码":"Passcode set","已输入「":"Typed “","已连接":"Connected","已连接的设备":"Connected device","已锁定":"Locked","已锁屏":"Locked","已隐藏设备面板,点右上角「设备面板」可以再打开":"Device panel hidden; open it again with “Device panel” at the top right","应用":"Apps","底部有「闹钟」标签,点它。":"There's an “Alarms” tab at the bottom; tap it.","康":"H","开":"on","开发者模式":"Developer Mode","开始任务":"Start task","当前任务结束后可以发新任务":"A new task can start when this one ends","当前任务结束后可以重新执行":"Can run again when the current task ends","当前在「":"Now on “","当前界面没有带文字的元素。":"No elements with text on the current screen.","当前界面的元素":"Elements on screen","当前缩放比例,点击切换到实际尺寸":"Current zoom; click for actual size","当前设备":"Current device","待确认":"Confirm","快递通知":"Delivery","您的包裹已到驿站,凭取件码取件":"Your parcel is at the pickup point; bring your pickup code","想让设备做什么?":"What should the device do?","我晚点到":"I'll be late","手动操作已锁定,避免和 AI 同时点击。":"Manual control is locked so you and the AI don't tap at once.","打开":"On","打开「":"Open “","打开了「":"Opened “","打开了与「":"Opened the chat with “","打开链接":"Open links","执行中":"Running","执行任务的 AI":"AI that runs the task","执行任务的本地 AI":"Local AI that runs the task","执行步骤":"Steps","批准并执行":"Approve","找到":"Found","拒绝":"Reject","拖动调整宽度,双击恢复默认":"Drag to resize, double-click to reset","按一下主屏幕键。":"Press the Home button.","按名字点「":"Tap by name “","按名称或 bundle id 搜索":"Search by name or bundle id","按文字或类型筛选":"Filter by text or type","按窗口大小自动适应":"Fit to the window","接管":"Take over","接管中":"You're in control","控制台":"console","控制设备":"Device","搜索":"Search","搜索 App":"Search apps","摄":"C","操作失败":"Action failed","操作往返":"round trip","操作没有生效:":"That didn't take effect: ","操作通道":"Route","收起步骤":"Hide steps","放大画面":"Zoom in","放大(也可以按住 Ctrl/⌘ 滚动滚轮)":"Zoom in (or Ctrl/⌘ + scroll)","无线局域网":"Wi-Fi","日历":"Calendar","日期与时间":"Date & Time","时":"C","时钟":"Clock","明天的评审改到上午十点了":"Tomorrow's review moved to 10 a.m.","昨天":"Yesterday","显示与亮度":"Display & Brightness","晚上回来吃饭吗?":"Coming home for dinner tonight?","晴":"W","暂停":"Pause","未就绪":"Not ready","未设置":"Not set","未锁定":"Unlocked","查看":"Show","次计次":"","正在打开":"Opening","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。期间截图和点击会改走 HID 后备。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. Meanwhile screenshots and taps use the HID fallback.","正在查找…":"Looking…","正在连接 iphone-control 服务…":"Connecting to the iphone-control service…","正在连接…":"Connecting…","正在连接画面…":"Connecting to the screen…","正在重新连接画面…":"Reconnecting the picture…","步":"steps","步停下了。已经做完的操作不会撤销。":". What was already done isn't undone.","步时的屏幕截图":"screen","步没走通:":"failed: ","没找到「iOS 版本」":"“iOS Version” not found","没有你自己安装的 App。勾上「包含系统 App」可以看到系统自带的。":"No apps you installed yourself. Check “Include system apps” to see the built-in ones.","没有名称或 bundle id 含「":"No app whose name or bundle id contains “","没有含「":"No element contains “","没有完成":"Not done","没有弹出键盘:先在画面里点一下输入框。":"No keyboard on screen: tap a text field on the screen first.","没有画面:画面来自设备上的 WebDriverAgent,它现在没有运行。3 秒后自动重试…":"No picture: it comes from WebDriverAgent on the device, which isn't running right now. Retrying in 3 s…","没有设备":"No device","没有读到 App。":"No apps were read.","没有这个接口(":"has no such endpoint (","清空":"Clear","清空全部操作记录?":"Clear all history?","清空记录":"Clear history","滑动":"Swipe","演示模式":"Demo","演示模式只内置了几个示例:查系统版本、看闹钟、秒表、发信息、回主屏幕、看屏幕。这条在模拟画面上做不了。":"The demo only knows a few examples: check the iOS version, look at alarms, the stopwatch, send a message, go Home, look at the screen. This one can't be done on the simulated screen.","演示模式只模拟 http(s) 链接,URL scheme 要连上真机才能试":"The demo only simulates http(s) links; try URL schemes with a real device","演示模式只能跑内置示例。连上服务后,这条指令会交给真正的 agent。":"The demo only runs its built-in examples. Connected to the service, this task goes to a real agent.","演示模式没有模拟计时器":"The demo doesn't simulate timers","演示模式没有模拟这一页":"The demo doesn't simulate this page","演示模式没有模拟这个 App。按主屏幕键或从底部上滑返回。":"The demo doesn't simulate this app. Press Home or swipe up from the bottom to go back.","演示模式没有模拟这个任务":"The demo doesn't simulate this task","演示模式:没有连上 iphone-control 服务。设备画面、App 列表、元素和 AI 的每一步都是本地模拟的。":"Demo mode: not connected to the iphone-control service. The screen, app list, elements and every AI step are simulated locally.","演示模式:没有连上 iphone-control 服务,画面是本地模拟的。":"Demo mode: not connected to the iphone-control service; the screen is simulated locally.","演示画面 · 本地模拟":"Demo screen · simulated locally","点「启动」。":"Tap “Start”.","点「读取」列出当前界面上带文字的元素。鼠标移上去会在画面上框出位置。":"Click “Read” to list the elements with text on the current screen. Hover one to outline it on the picture.","点一下底部的输入框。":"Tap the text field at the bottom.","点了":"Tapped","点击重新执行这条指令":"Click to run this task again","点它":"Tap","点底部的「秒表」。":"Tap “Stopwatch” at the bottom.","点开和「":"Open the chat with “","点按、滑动、长按":"Tap, swipe, long press","照":"P","照片":"Photos","状态":"Status","王磊":"Wang Lei","现在在「":"Now on “","用 USB 连上设备,确认数据线能传数据。":"Connect the device over USB with a cable that carries data.","用一句话描述目标。AI 会看真实屏幕,用下面这些现成的操作一步步完成;遇到付款、删除、发消息这类操作会先停下来等你确认。":"Describe the goal in a sentence. The AI looks at the real screen and gets there step by step with the actions below; before paying, deleting, sending a message and the like it stops and waits for you to confirm.","电池":"Battery","电话":"Phone","画面仍为 AI 保留,要自己操作先接管。":"The screen stays reserved for the AI; take over to act yourself.","画面断开":"Picture lost","画面断开 · 自动重试中":"Picture lost · retrying","画面缩放":"Zoom","界面上没找到「":"Couldn't find “","界面变了,":"The screen changed. ","相机":"Camera","看屏幕、读元素":"See the screen, read elements","确认删除":"Delete","确认前画面保持锁定。":"The screen stays locked until you confirm.","确认已经在主屏幕。":"Check that the Home Screen is in front.","确认秒表在走。":"Check that the stopwatch runs.","秒内没有出现「":"s passed without “","秒表":"Stopwatch","秒表已停止":"Stopwatch stopped","秒表已复位":"Stopwatch reset","秒表已经在计时":"The stopwatch is already running","秒表已经开始计时。":"The stopwatch has started.","秒表开始计时":"Stopwatch started","秒表时间":"Stopwatch time","秒表正在计时:":"Stopwatch running: ","秒表没有在计时":"The stopwatch isn't running","秒)":" s)","秒:演示模式没有模拟长按菜单":"s: the demo doesn't simulate long-press menus","空闲":"Idle","第":"Step","等「":"Waiting for “","等一段文字出现":"Wait for text","等你确认":"Needs you","等待 5 秒":"Wait 5 s","等待中…":"Waiting…","等待前一步":"waiting for the step before","筛选元素":"Filter elements","系统":"System","系统版本在「通用 › 关于本机」里,先点「通用」。":"The version is under General › About; tap “General” first.","纽约":"New York","结束":"Quit","结束「":"Quit “","继续":"Resume","继续执行":"Keep running","缩小画面":"Zoom out","缩小(也可以按住 Ctrl/⌘ 滚动滚轮)":"Zoom out (or Ctrl/⌘ + scroll)","自动解锁":"Auto-unlock","自动选择":"Automatic","蓝牙":"Bluetooth","计时器":"Timers","计次":"Lap","让 AI 操作你的 Apple 设备":"Let AI operate your Apple device","记":"N","记了第":"Recorded lap","设":"S","设备":"Device","设备实时画面:单击轻点,拖动或滚动滚轮滑动,按住长按":"Live device screen: click to tap, drag or scroll to swipe, hold to long-press","设备屏幕":"Device screen","设备按键和输入":"Device buttons and typing","设备的实时画面":"Live picture of the device","设备重启后还没解锁过,需要在设备上手动解锁一次。":"The device hasn't been unlocked since it restarted; unlock it by hand once.","设备重启后首次启用 UI 自动化,请在设备上输入锁屏密码。":"UI automation is starting for the first time since the restart; enter the passcode on the device.","设备面板":"Device panel","设置":"Settings","话":"P","请求失败(":"Request failed (","读一下列表里的闹钟。":"Read the alarms in the list.","读一下界面上带文字的元素。":"Read the elements with text on the screen.","读出「iOS 版本」这一行。":"Read the “iOS Version” row.","读取":"Read","调整 AI 助手栏宽度":"Resize the AI assistant column","调整设备面板宽度":"Resize the device panel","软件更新":"Software Update","轻点":"Tap","输入":"Type","输入并回车":"Type and press Return","输入文字":"Type text","输入框":"Text field","输入框是空的,没有发出任何内容":"The text field is empty, nothing was sent","输入框获得焦点,弹出了键盘":"The text field has focus and the keyboard is up","输入要发的内容。":"Type the message.","运行 <code>iphone-control sign</code>,用免费 Apple ID 签名并安装。":"Run <code>iphone-control sign</code> to sign and install it with a free Apple ID.","还不知道屏幕尺寸,稍后再试":"The screen size isn't known yet; try again shortly","还停在「":"Still on “","还在读取可用的 AI,稍等一下再试。":"Still reading the available AIs; try again in a moment.","还在连接服务,稍等一下再开始":"Still connecting to the service; start in a moment","还没有拿到守护进程状态。":"No daemon status yet.","这个位置在画面外面":"That point is outside the screen","这台机器上没有可用的 AI。安装并登录 Claude Code 或 Codex,再重新运行 iphone-control viewer。":"No AI is available on this machine. Install and log in to Claude Code or Codex, then run iphone-control viewer again.","这台机器的 PATH 里没有 claude 或 codex":"Neither claude nor codex is on this machine's PATH","这台设备的系统版本是 iOS 18.1。":"This device runs iOS 18.1.","这里没有可点的东西":"nothing to tap here","进入「":"Opened “","进行中":"in progress","连接中":"Connecting","适应":"Fit","通用":"General","通道":"Route","邮":"M","邮件":"Mail","重新执行":"Run again","重新执行:":"Run again: ","钱":"W","钱包":"Wallet","锁定屏幕":"Lock Screen","锁屏":"Lock","键盘":"Keyboard","长按":"Long press","闹钟":"Alarms","闹钟 ":"Alarm ","闹钟,":"Alarm, ","隐私与安全性":"Privacy & Security","隐藏设备面板":"Hide the device panel","需要你确认:":"Needs your confirmation: ","需要处理":"needs attention","音乐":"Music","音量减":"Volume down","音量减(演示画面没有变化)":"Volume down (no change on the demo screen)","音量加":"Volume up","音量加(演示画面没有变化)":"Volume up (no change on the demo screen)","页面刷新时这个任务还在执行,刷新后页面不再跟踪它的进度。":"This task was still running when the page reloaded, so the page no longer follows it.","(":" (","(未安装)":" (not installed)","(演示画面不加载网页)":" (the demo doesn't load web pages)","(演示)":" (demo)",")":")",",":", ",":":": ",":演示画面不支持滚动":": the demo screen doesn't scroll","看一下屏幕":"Look at the screen","读取屏幕上的内容":"Read what's on the screen","查看手机状态":"Check the phone's status","点击屏幕":"Tap the screen","点击":"Tap","长按屏幕":"Long-press the screen","滑动屏幕":"Swipe the screen","按主屏幕键":"Press Home","按键":"Press a button","打开 App":"Open","关闭":"Quit","等待":"Wait for","出现":"to appear","查看已安装的 App":"List installed apps","查看已连接的设备":"List connected devices","连续执行几步操作":"Run a few steps in a row","请你确认":"Ask you to confirm","操作手机":"Operate the phone","这一步没成功":"This step didn't work","另一台设备":"another device","设备已在别处切换到":"The device was switched elsewhere to",",画面已跟过去":"; the picture follows it","没有连上设备:用数据线连上 iPhone,确认数据线能传数据。":"No device connected: connect the iPhone with a cable that carries data.","还没设置好(配对、开发者模式)。在终端运行":"isn’t set up yet (pairing, Developer Mode). In a terminal, run",",选「手机」。":" and pick Phone.","上还没装 WebDriverAgent。":"doesn’t have WebDriverAgent yet.","正在签名安装…":"Signing and installing…","签名并安装 WDA":"Sign and install WDA","上还没装 WebDriverAgent,需要先登录 Apple ID:在终端运行":"doesn’t have WebDriverAgent yet, and an Apple ID is needed to sign it: in a terminal, run",",选「Apple ID」。":" and pick Apple ID.","正在":"Starting WebDriverAgent on","上启动 WebDriverAgent,通常 10–60 秒…":"— usually 10–60 seconds…","设备重启后还没解锁过,在设备上手动解锁一次,画面就会出来。":"The device hasn’t been unlocked since it restarted. Unlock it once by hand and the picture appears.","正在签名并安装 WebDriverAgent,大约 1–2 分钟,保持手机解锁…":"Signing and installing WebDriverAgent, about 1–2 minutes; keep the phone unlocked…","运行 <code>iphone-control setup --reconfigure</code> 选「手机」,在设备上点「信任」。":"Run <code>iphone-control setup --reconfigure</code>, pick Phone, and tap “Trust” on the device.",":WebDriverAgent 启动失败,会自动重试":": WebDriverAgent failed to start; retrying automatically","不可用":"Unavailable","正在挂开发者镜像、启动 WebDriverAgent,最长约 2 分钟。这台设备低于 iOS 27,没有 HID 后备,期间不能截图和操作。":"Mounting the developer disk image and starting WebDriverAgent, up to about 2 minutes. This device is below iOS 27, so there is no HID fallback: no screenshots or actions until then.","重新签名并安装 WDA":"Re-sign and install WDA"};+Object.assign(EN, {'关于与更新':'About & updates','完成':'Done','检查更新':'Check for updates','检查中…':'Checking…','发行说明':'Release notes','升级命令':'Upgrade command','复制命令':'Copy command','已复制':'Copied','请选中命令并手动复制。':'Select the command and copy it manually.'});/* 中文原文 → 当前语言 */function tr(zh) { return LANG === 'en' ? (EN[zh] ?? zh) : zh; }/* 静态标记里的文字和提示(aria-label、title、placeholder、alt)开始时译一次 */@@ -1263,7 +1297,7 @@ async function api(path, body) {const opt = body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };opt.headers = { ...(opt.headers || {}), 'X-Ictl-Lang': LANG };// 操作只发给本页显示的那台;守护进程已换到别的设备时会被拒绝,不会点到用户没在看的手机上- if (S.udid) opt.headers['X-Ictl-Device'] = S.udid;+ if (S.udid && !path.startsWith('/api/updates')) opt.headers['X-Ictl-Device'] = S.udid;const r = await fetch(path, opt);if (!r.ok) {let msg = '';@@ -1556,6 +1590,114 @@ function showStageNote() {const html = stageNote(); if (stageMsg.dataset.note !== html) { stageMsg.innerHTML = html; stageMsg.dataset.note = html; } // 不变就不重画,免得按钮丢了焦点stageMsg.hidden = false;}+// This dialog always talks to the host, including when there is no phone. Opening it reads only the cache.+const updateDialog = $('#updates-dialog'), updateCheck = $('#update-check');+const aboutUpdates = $('#about-updates'), updateCommand = $('#update-command'), copyStatus = $('#update-copy-status');+let updatePoll, readingUpdates = false;+const updateText = (zh, en) => LANG === 'en' ? en : zh;+function drawUpdateBadge(r) {+ const newer = r.available_version && ['available', 'brew_check', 'platform_pending', 'manual_only', 'unsupported'].includes(r.availability);+ $('#update-dot').hidden = !newer;+ const label = tr('关于与更新') + (newer ? updateText(' · 新版本 ', ' · New release ') + r.available_version : '');+ aboutUpdates.title = label;+ aboutUpdates.setAttribute('aria-label', label);+}+function setUpdateCommand(command) {+ if (updateCommand.textContent !== command) copyStatus.textContent = '';+ updateCommand.textContent = command;+ $('#update-command-block').hidden = !command;+}+function drawUpdates(r) {+ const t = updateText, unknown = t('未知', 'Unknown');+ const channels = { managed: t('受管脚本安装', 'Managed installer'), script: t('手动脚本安装', 'Manual installer'),+ development: t('源码构建', 'Source build'), homebrew: 'Homebrew', debian: 'Debian', unknown };+ const states = { development: t('开发构建,未绑定发布仓库', 'Development build; no release repository'),+ unchecked: t('尚未检查', 'Not checked yet'), current: t('已是最新版', 'Up to date'),+ ahead: t('当前版本领先于公开稳定版', 'Ahead of the public stable release'),+ available: t('有可用更新', 'Update available'), platform_pending: t('已发布,当前平台安装包准备中', 'Released; waiting for this platform’s package'),+ brew_check: t('请在主机确认 Homebrew 可升级版本', 'Check Homebrew on the host'),+ unsupported: t('当前平台没有发行包', 'No release package for this platform'),+ manual_only: t('此版本需要手动升级', 'Manual upgrade required') };+ const policies = { manual: t('仅手动检查', 'Manual checks'), notify: t('后台检查,不自动安装', 'Check only'),+ 'auto-patch': t('空闲时自动安装补丁版', 'Install patches when idle') };+ $('#update-version').textContent = 'Viewer ' + (r.running_version || unknown);+ const facts = $('#update-facts'); facts.replaceChildren();+ const row = (label, value) => { const dt = document.createElement('dt'), dd = document.createElement('dd');+ dt.textContent = label; dd.textContent = value; facts.append(dt, dd); };+ row(t('发布者', 'Publisher'), r.publisher || t('未绑定', 'Unbound'));+ row(t('安装方式', 'Installation'), (channels[r.install_method] || unknown) + (r.pinned ? t(' · 固定版本', ' · pinned') : ''));+ row(t('磁盘 / 守护进程', 'Disk / daemon'), (r.installed_version || unknown) + ' / ' + (r.daemon_version || unknown));+ row(t('更新策略', 'Update policy'), policies[r.policy] || unknown);+ row(t('上次检查成功', 'Last successful check'), r.last_success_at ? new Date(r.last_success_at * 1000).toLocaleString(LANG) : '—');+ if (r.available_version) row(t('公开稳定版', 'Stable release'), r.available_version + (r.published_at ? ' · ' + r.published_at.slice(0,10) : ''));+ const errors = { network: t('无法连接发布仓库', 'Release repository unreachable'), invalid_release: t('发行元数据无效', 'Invalid release metadata'),+ rate_limited: t('请求受限', 'Rate limited'), http_error: t('发布仓库返回错误', 'Release repository returned an error') };+ const failure = errors[r.error_code] || r.error_code || r.check_error;+ const result = failure ? t('检查失败:', 'Check failed: ') + failure : states[r.availability];+ if (r.retry_after && r.retry_after * 1000 > Date.now()) row(t('可重试时间', 'Retry after'), new Date(r.retry_after * 1000).toLocaleString(LANG));+ $('#update-result').textContent = r.checking ? tr('检查中…') : result || unknown;+ $('#update-guide').textContent = r.guidance || '';+ setUpdateCommand(failure ? '' : r.upgrade_command || '');+ $('#update-policy').textContent = r.install_method === 'managed' && !r.pinned ?+ t('本机策略:', 'Local policy: ') + 'iphone-control update policy ' + (r.policy === 'auto-patch' ? 'manual' : 'auto-patch') : '';+ const outcomes = { installed: t('安装成功', 'Installed'), rolled_back: t('已手动回滚', 'Rolled back'), restored: t('升级失败,已恢复旧版本', 'Previous version restored'),+ failed: t('更新失败', 'Update failed'), manual_migration: t('需要手动迁移', 'Manual migration required'),+ needs_operator: t('此版本不自动安装,请手动运行 update apply', 'Not installed automatically; run update apply'),+ busy: t('等待空闲', 'Waiting for idle'), recovery_failed: t('需要手动恢复', 'Recovery needs attention') };+ $('#update-outcome').textContent = r.last_update ? [r.last_update.target_version, outcomes[r.last_update.status] || r.last_update.status, r.last_update.detail].filter(Boolean).join(' · ') : '';+ $('#update-mismatch').textContent = [r.installed_version, r.daemon_version].some(v => v && v !== r.running_version) ?+ t('进程版本不同。重新打开 Viewer,重连 MCP 客户端,并按安装渠道重启 daemon。', 'Versions differ. Reopen Viewer, reconnect MCP clients and restart the daemon through its installation channel.') : '';+ const link = $('#update-release'); link.hidden = !r.release_url;+ if (r.release_url) link.href = r.release_url; else link.removeAttribute('href');+ updateCheck.disabled = r.checking || !r.publisher;+ updateCheck.textContent = tr(r.checking ? '检查中…' : '检查更新');+}+async function loadUpdates(check = false) {+ if (readingUpdates) return;+ readingUpdates = true;+ clearTimeout(updatePoll);+ updateCheck.disabled = true;+ try {+ if (check) { $('#update-result').textContent = tr('检查中…'); await api('/api/updates/check', {}); }+ const report = await api('/api/updates');+ drawUpdateBadge(report);+ if (updateDialog.open) drawUpdates(report);+ if (report.checking && updateDialog.open) updatePoll = setTimeout(loadUpdates, 700);+ } catch (e) {+ setUpdateCommand('');+ $('#update-result').textContent = e.message;+ updateCheck.disabled = false; updateCheck.textContent = tr('检查更新');+ } finally {+ readingUpdates = false;+ }+}+aboutUpdates.addEventListener('click', () => {+ copyStatus.textContent = '';+ updateDialog.showModal();+ loadUpdates();+});+$('#update-copy').addEventListener('click', async () => {+ const command = updateCommand.textContent;+ if (!command) return;+ try {+ await navigator.clipboard.writeText(command);+ copyStatus.textContent = tr('已复制');+ } catch {+ const range = document.createRange(), selection = window.getSelection();+ range.selectNodeContents(updateCommand);+ selection.removeAllRanges();+ selection.addRange(range);+ copyStatus.textContent = document.execCommand('copy') ? tr('已复制') : tr('请选中命令并手动复制。');+ }+});+updateCheck.addEventListener('click', () => loadUpdates(true));+updateDialog.addEventListener('close', () => clearTimeout(updatePoll));+// Refresh the host's cached report without initiating a release check.+const refreshVisibleUpdates = () => { if (!document.hidden) loadUpdates(); };+refreshVisibleUpdates();+setInterval(refreshVisibleUpdates, 60000);+document.addEventListener('visibilitychange', refreshVisibleUpdates);+async function loadInfo() { try { applyInfo(await (await fetch('/api/info', { headers: { 'X-Ictl-Lang': LANG } })).json()); } catch { /* 跟着画面一起重试 */ } }function connect() {S.stream = 'connecting'; stageMsg.textContent = tr('正在连接画面…'); delete stageMsg.dataset.note; stageMsg.hidden = false;diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex d69db1c..185bbf2 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -56,6 +56,8 @@ struct Ctx {/// The device the page shows and acts onudid: Mutex<String>,agents: Arc<Agents>,+ checking: Arc<tokio::sync::Mutex<()>>,+ check_error: Arc<Mutex<Option<String>>>,/// Bundle id → display name, for the foreground appnames: tokio::sync::Mutex<HashMap<String, String>>,/// H.264 for the picture; `None`: MJPEG only@@ -154,6 +156,8 @@ pub async fn run(socket: &Path, data_dir: &Path, port: u16) -> anyhow::Result<()port,udid: Mutex::new(udid),agents,+ checking: Arc::default(),+ check_error: Arc::default(),names: tokio::sync::Mutex::default(),page: page_in(ictl_l10n::lang()),video,@@ -277,6 +281,7 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mutlet v = match &p[5..] {// always an answer: the page falls back to its offline demo when this one fails"info" => Ok(info(ctx).await.unwrap_or_else(|m| json!({"width": null, "height": null, "warning": m}))),+ "updates" => updates(ctx).await,"daemon" => daemon(ctx).await,"status" => status(ctx).await,"devices" => devices(ctx).await,@@ -317,10 +322,41 @@ async fn handle(mut client: TcpStream, ctx: &Ctx, head: Vec<u8>, req: Head, mut}}+/// The release cache belongs to the host user; process versions belong to this Viewer and socket.+async fn updates(ctx: &Ctx) -> Result<Value, String> {+ // Sample before reading cached metadata: a check that finishes while this GET+ // awaits the daemon still needs one final poll to display its committed result.+ let checking = ctx.checking.try_lock().is_err();+ let lang = ictl_l10n::lang();+ let mut report = tokio::task::spawn_blocking(move || ictl_l10n::with_lang(lang, crate::update::cached))+ .await+ .map_err(|e| e.to_string())?+ .map_err(|e| e.to_string())?;+ crate::report_daemon(&mut report, &ctx.socket).await;+ let mut v = json!(report);+ v["checking"] = json!(checking);+ v["check_error"] = json!(*ctx.check_error.lock().unwrap_or_else(|p| p.into_inner()));+ Ok(v)+}+/// A POST under `/api/`: status code and JSON answer/// `device`: the one the page shows (`X-Ictl-Device`); actions only go to itasync fn post(ctx: &Ctx, name: &str, b: &Value, device: Option<&str>) -> (u16, Value) {let conflict = |m: String| (409, json!({"ok": false, "message": m}));+ if name == "updates/check" {+ if !b.as_object().is_some_and(serde_json::Map::is_empty) {+ return (400, json!({"message": "Expected {}"}));+ }+ if let Ok(guard) = ctx.checking.clone().try_lock_owned() {+ let error = ctx.check_error.clone();+ tokio::spawn(async move {+ let result = crate::update::check(false).await;+ *error.lock().unwrap_or_else(|p| p.into_inner()) = result.err().map(|e| e.to_string());+ drop(guard);+ });+ }+ return (202, json!({"checking": true}));+ }// how much of an H.264 stream the page has read (see `crate::video`)if name == "video/ack" {let ok = match (b["stream"].as_str(), b["bytes"].as_u64()) {@@ -435,6 +471,7 @@ async fn json_reply(client: &mut TcpStream, status: u16, v: &Value) -> anyhow::Rasync fn reply(client: &mut TcpStream, status: u16, kind: &str, body: &[u8]) -> anyhow::Result<()> {let reason = match status {200 => "OK",+ 202 => "Accepted",400 => "Bad Request",403 => "Forbidden",404 => "Not Found",@@ -815,6 +852,38 @@ fn screen_of(p: &ictl_daemon::core::Persisted, udid: &str) -> Option<ictl_devicemod tests {use super::*;+ #[tokio::test]+ async fn update_poll_keeps_polling_if_refresh_finishes_after_cache_read() {+ let temp = tempfile::tempdir_in("/tmp").unwrap();+ let socket = temp.path().join("daemon.sock");+ let daemon = tokio::net::UnixListener::bind(&socket).unwrap();+ let ctx = Ctx {+ agents: Agents::new(&socket, temp.path().join("gate")).unwrap(),+ socket,+ data_dir: temp.path().into(),+ port: 0,+ page: String::new(),+ checking: Arc::default(),+ check_error: Arc::default(),+ names: Default::default(),+ udid: Default::default(),+ video: None,+ acks: Arc::default(),+ };+ let guard = ctx.checking.lock().await;+ let finish_check = async {+ // The GET has consumed the release cache when its daemon snapshot begins.+ let (peer, _) = daemon.accept().await.unwrap();+ drop(guard);+ drop(peer);+ };+ let (report, ()) =+ tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(updates(&ctx), finish_check) })+ .await+ .unwrap();+ assert_eq!(report.unwrap()["checking"], true);+ }+fn head(s: &str) -> Head {Head::parse(s.as_bytes()).unwrap()}diff --git a/apps/iphone-control/tests/update_viewer.rs b/apps/iphone-control/tests/update_viewer.rsnew file mode 100644index 0000000..53cf4a2--- /dev/null+++ b/apps/iphone-control/tests/update_viewer.rs@@ -0,0 +1,59 @@+//! Exercise the shipped CLI and embedded Viewer with no device, daemon or release credentials.+use std::process::Stdio;+use std::time::Duration;++use anyhow::{Context, Result};+use serde_json::Value;+use tokio::io::{AsyncBufReadExt, BufReader};+use tokio::process::Command;++#[tokio::test]+async fn viewer_and_cli_share_the_unbound_report() -> Result<()> {+ if option_env!("ICTL_UPDATE_PUBLISHER").is_some_and(|s| !s.is_empty()) || unsafe { libc::geteuid() } == 0 {+ return Ok(());+ }+ let temp = tempfile::tempdir_in("/tmp")?;+ let dir = temp.path();+ let cli = || {+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_iphone-control"));+ cmd.env_clear()+ .env("HOME", dir)+ .env("PATH", "/usr/bin:/bin")+ .env("ICTL_SOCKET", dir.join("daemon.sock"))+ .env("USBMUXD_SOCKET_ADDRESS", dir.join("absent-usbmuxd.sock"))+ .kill_on_drop(true);+ cmd+ };+ let result = cli().args(["update", "check", "--json"]).output().await?;+ assert!(result.status.success());+ let report: Value = serde_json::from_slice(&result.stdout)?;+ assert_eq!(report["availability"], "development");+ assert!(report["publisher"].is_null() && report["daemon_version"].is_null());++ let mut viewer = cli().args(["viewer", "--port", "0"]).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?;+ let mut messages = BufReader::new(viewer.stdout.take().unwrap()).lines();+ let line = tokio::time::timeout(Duration::from_secs(10), messages.next_line()).await??.context("viewer exited")?;+ let from = line.find("http://127.0.0.1:").context("viewer URL")?;+ let origin = line[from..].split_once("/ ").context("viewer port")?.0;+ let _ = rustls::crypto::ring::default_provider().install_default();+ let client = reqwest::Client::builder().no_proxy().timeout(Duration::from_secs(5)).build()?;+ let response = client.get(format!("{origin}/api/updates")).send().await?.error_for_status()?;+ let shown: Value = serde_json::from_slice(&response.bytes().await?)?;+ for (field, value) in report.as_object().unwrap() {+ assert_eq!(&shown[field], value, "{field}");+ }+ let check = |site, body| {+ client+ .post(format!("{origin}/api/updates/check"))+ .header("Origin", site)+ .header("Content-Type", "application/json")+ .body(body)+ .send()+ };+ assert_eq!(check(origin, "{}").await?.status(), 202);+ assert_eq!(check("http://other.invalid", "{}").await?.status(), 403);+ assert_eq!(check(origin, r#"{"publisher":"other/fork"}"#).await?.status(), 400);+ assert!(!dir.join(".cache/iphone-control/updates").exists());+ viewer.kill().await?;+ Ok(())+}diff --git a/crates/ictl-daemon/Cargo.toml b/crates/ictl-daemon/Cargo.tomlindex f1b2971..bda899b 100644--- a/crates/ictl-daemon/Cargo.toml+++ b/crates/ictl-daemon/Cargo.toml@@ -10,6 +10,7 @@ homepage.workspace = truedescription = "守护进程:状态机、usbmuxd 看护、重签、通知、控制接口"[dependencies]+libc.workspace = trueictl-l10n.workspace = trueictl-webinspector.workspace = trueictl-device.workspace = truediff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rsindex 3676571..ee4eeb6 100644--- a/crates/ictl-daemon/src/core.rs+++ b/crates/ictl-daemon/src/core.rs@@ -202,6 +202,13 @@ pub struct CallCtx {/// 快照:`iphone-control status` 显示#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Snapshot {+ /// Older daemons do not report process identity.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub version: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pid: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub maintenance: Option<bool>,pub state: DeviceState,pub device: Option<DeviceInfo>,/// USB 上接着的全部设备(读不到名字的只有 UDID)@@ -394,6 +401,9 @@ impl Daemon {next_session_check: now + Duration::from_secs(90),};let first = Snapshot {+ version: Some(env!("CARGO_PKG_VERSION").into()),+ pid: Some(std::process::id()),+ maintenance: None,state: DeviceState::Absent,device: None,devices: Vec::new(),@@ -563,6 +573,9 @@ impl Daemon {let unlock = self.unlock_cfg(g.device.as_ref().map(|d| d.udid.as_str()));let pinned = self.pinned(g);self.snap.send_replace(Snapshot {+ version: Some(env!("CARGO_PKG_VERSION").into()),+ pid: Some(std::process::id()),+ maintenance: None,state: g.state.clone(),device: g.info.clone(),devices: self.connected_infos(g),@@ -588,6 +601,7 @@ impl Daemon {s.unlock_disabled = unlock.disabled_by_failure();s.auto_unlock = unlock.enabled();s.log_tail = self.log.tail(15);+ s.maintenance = crate::maintenance::active();return Response::text(serde_json::to_string_pretty(&s).unwrap_or_default());}if let Err(e) = check_request(&req) {diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rsindex c6975a6..685bd1a 100644--- a/crates/ictl-daemon/src/lib.rs+++ b/crates/ictl-daemon/src/lib.rs@@ -13,6 +13,7 @@ mod doctor;pub mod eventlog;pub mod imaging;pub mod machine;+pub mod maintenance;pub mod notify;mod screen;mod supervise;@@ -123,18 +124,26 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {let resp = if line.len() as u64 > MAX_REQUEST_LINE {protocol::Response::error(ictl_l10n::tr!("请求太长", "request too long"))} else {- match parse_request(&line) {- // streams until either side closes: the connection is the stream's from here on- Ok((protocol::Request::ScreenStream, _, expect_udid, lang)) => {- let w = w;+ let parsed = parse_request(&line);+ // Status snapshots remain available throughout maintenance (including health probes).+ let needs_device = parsed.as_ref().is_ok_and(|(r, ..)| !matches!(r, protocol::Request::Daemon));+ let lease = needs_device.then(maintenance::shared).transpose();+ match (parsed, lease) {+ (_, Err(e)) => protocol::Response::error(e.to_string()),+ // Streams until either side closes: the connection is the stream's from here on. The lease is only+ // checked when it opens (no stream starts during an update) and not held while it runs: a page+ // watching for hours would otherwise keep the updater from ever finding the host idle. An update+ // stops the daemon, which ends the stream; the viewer reconnects to the new one+ (Ok((protocol::Request::ScreenStream, _, expect_udid, lang)), Ok(lease)) => {+ drop(lease);ictl_l10n::scope(lang, daemon.screen_stream(reader, w, expect_udid)).await;return;}- Ok((req, false, expect_udid, lang)) => {+ (Ok((req, false, expect_udid, lang)), Ok(_lease)) => {let handling = daemon.handle(req, queued_at, core::CallCtx { gone: None, expect_udid });ictl_l10n::scope(lang, handling).await}- Ok((req, true, expect_udid, lang)) => {+ (Ok((req, true, expect_udid, lang)), Ok(_lease)) => {// 调用方断开(取消、超时)就告诉 handle:还在排队的话不再执行let (gone_tx, gone_rx) = tokio::sync::oneshot::channel();let mut gone_tx = Some(gone_tx);@@ -156,7 +165,9 @@ async fn serve_conn(daemon: Arc<Daemon>, stream: tokio::net::UnixStream) {}resp}- Err(e) => protocol::Response::error(ictl_l10n::trf!("请求格式错误:{e}", "malformed request: {e}")),+ (Err(e), _) => {+ protocol::Response::error(ictl_l10n::trf!("请求格式错误:{e}", "malformed request: {e}"))+ }}};let mut out = serde_json::to_string(&resp).unwrap_or_default();diff --git a/crates/ictl-daemon/src/maintenance.rs b/crates/ictl-daemon/src/maintenance.rsnew file mode 100644index 0000000..669e5f3--- /dev/null+++ b/crates/ictl-daemon/src/maintenance.rs@@ -0,0 +1,165 @@+//! A shared lease covers every host client and device operation. The updater alone takes the+//! exclusive lease, across daemon restarts. The kernel cancels either lease on process death.+use std::ffi::OsString;+use std::fs::{File, OpenOptions};+use std::io::{self, Write};+use std::os::fd::AsRawFd;+use std::os::unix::ffi::{OsStrExt, OsStringExt};+use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt};+use std::path::{Path, PathBuf};++fn directory() -> io::Result<PathBuf> {+ // Independent of the socket, XDG runtime directory and executable: a second Viewer, even+ // one talking to a different socket, or a direct WDA client must still count as active.+ if crate::protocol::running_as_root() {+ return Ok(crate::protocol::default_data_dir());+ }+ Ok(PathBuf::from(std::env::var_os("HOME").ok_or_else(|| io::Error::other("HOME is not set"))?)+ .join(".local/share/iphone-control"))+}++fn lock(dir: &Path, operation: libc::c_int) -> io::Result<File> {+ std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?;+ let owner = dir.metadata()?;+ if owner.uid() != unsafe { libc::geteuid() } || owner.mode() & 0o022 != 0 {+ return Err(io::Error::new(io::ErrorKind::PermissionDenied, "unsafe host maintenance directory"));+ }+ let f = OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .custom_flags(libc::O_NOFOLLOW)+ .mode(0o600)+ .open(dir.join("maintenance.lock"))?;+ // Separate open file descriptions, including within the same process, conflict.+ if unsafe { libc::flock(f.as_raw_fd(), operation | libc::LOCK_NB) } != 0 {+ let e = io::Error::last_os_error();+ if e.kind() == io::ErrorKind::WouldBlock {+ return Err(io::Error::new(+ io::ErrorKind::WouldBlock,+ "Busy: host update or device client is active; retry when idle",+ ));+ }+ return Err(e);+ }+ Ok(f)+}++/// Busy is not always a client: the daemon itself holds the shared lease while it works on the phone (every+/// status tick, starting WDA, re-signing, the Apple ID check), from milliseconds to a couple of minutes+pub fn exclusive() -> io::Result<File> {+ lock(&directory()?, libc::LOCK_EX).map_err(|e| {+ if e.kind() == io::ErrorKind::WouldBlock {+ io::Error::new(+ io::ErrorKind::WouldBlock,+ "the phone is in use by a client (control page, MCP) or by the daemon's own work \+ (status check, starting WDA, re-signing)",+ )+ } else {+ e+ }+ })+}++fn pending(dir: &Path) -> io::Result<Option<PathBuf>> {+ let data = match std::fs::read(dir.join("maintenance.pending")) {+ Ok(bytes) => bytes,+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),+ Err(e) => return Err(e),+ };+ let path = PathBuf::from(OsString::from_vec(data));+ if !path.is_absolute() {+ return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid maintenance journal path"));+ }+ Ok(path.try_exists()?.then_some(path))+}++/// Called under the exclusive lease, before the durable transaction journal is created.+/// Removing the journal at commit makes this pointer inert, even if the updater then dies.+pub fn mark_pending(journal: &Path) -> io::Result<()> {+ remember(&directory()?, journal)+}++fn remember(dir: &Path, journal: &Path) -> io::Result<()> {+ if let Some(path) = pending(dir)? {+ if path == journal {+ return Ok(());+ }+ return Err(io::Error::new(+ io::ErrorKind::WouldBlock,+ format!("recover the pending transaction at {}", path.display()),+ ));+ }+ let temp = dir.join("maintenance.pending.tmp");+ let mut file = OpenOptions::new()+ .write(true)+ .create(true)+ .truncate(true)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW)+ .open(&temp)?;+ file.write_all(journal.as_os_str().as_bytes())?;+ file.sync_all()?;+ std::fs::rename(temp, dir.join("maintenance.pending"))?;+ File::open(dir)?.sync_all()+}++fn shared_in(dir: &Path) -> io::Result<File> {+ let lease = lock(dir, libc::LOCK_SH)?;+ if let Some(journal) = pending(dir)? {+ return Err(io::Error::new(+ io::ErrorKind::WouldBlock,+ format!("Host update recovery pending ({}); run iphone-control update recover", journal.display()),+ ));+ }+ Ok(lease)+}++pub fn shared() -> io::Result<File> {+ shared_in(&directory()?)+}++pub(crate) fn active() -> Option<bool> {+ match shared() {+ Ok(_) => Some(false),+ Err(e) if e.kind() == io::ErrorKind::WouldBlock => Some(true),+ Err(_) => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn pending_journal_blocks_other_installs_after_lock_owner_dies() {+ let dir = std::env::temp_dir().join(format!("ictl-pending-{}", std::process::id()));+ let install = dir.join("prefix").join("journal.json");+ let other = dir.join("another-prefix").join("journal.json");+ let lease = lock(&dir, libc::LOCK_EX).unwrap();+ remember(&dir, &install).unwrap();+ std::fs::create_dir_all(install.parent().unwrap()).unwrap();+ std::fs::write(&install, "prepared").unwrap();+ drop(lease);+ assert_eq!(shared_in(&dir).unwrap_err().kind(), io::ErrorKind::WouldBlock);+ assert_eq!(remember(&dir, &other).unwrap_err().kind(), io::ErrorKind::WouldBlock);+ std::fs::remove_file(install).unwrap();+ shared_in(&dir).unwrap();+ std::fs::remove_dir_all(dir).unwrap();+ }+ #[test]+ fn readers_exclude_maintenance_and_resume_after_it() {+ let dir = std::env::temp_dir().join(format!("ictl-lease-{}", std::process::id()));+ let client = lock(&dir, libc::LOCK_SH).unwrap();+ let signing = lock(&dir, libc::LOCK_SH).unwrap();+ assert_eq!(lock(&dir, libc::LOCK_EX).unwrap_err().kind(), io::ErrorKind::WouldBlock);+ drop(client);+ assert!(lock(&dir, libc::LOCK_EX).is_err());+ drop(signing);+ let update = lock(&dir, libc::LOCK_EX).unwrap();+ assert!(lock(&dir, libc::LOCK_SH).is_err());+ drop(update);+ lock(&dir, libc::LOCK_SH).unwrap();+ std::fs::remove_dir_all(dir).unwrap();+ }+}diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rsindex c91ca02..c969a4e 100644--- a/crates/ictl-daemon/src/supervise.rs+++ b/crates/ictl-daemon/src/supervise.rs@@ -75,6 +75,10 @@ impl Daemon {/// 每 10 秒一次。有请求在用设备就跳过这一轮(巡检不排队,下一轮再来)pub async fn tick(self: Arc<Self>) {+ let Ok(_lease) = crate::maintenance::shared() else {+ self.heartbeat.beat();+ return;+ };let Ok(mut g) = self.inner.try_lock() else { return };let g = &mut *g;@@ -295,7 +299,9 @@ impl Daemon {});let known = g.persisted.detached_wda.as_ref().filter(|d| d.udid == device.udid).map(|d| d.pid);let (cache, url, user_dir) = (self.cfg.ddi_cache(), self.cfg.ddi_url.clone(), self.cfg.ddi_dir.clone());+ let Ok(lease) = crate::maintenance::shared() else { return };g.starting = Some(tokio::task::spawn_local(async move {+ let _lease = lease;// 手机重启后开发者镜像可能掉了;已挂载时只是一次查询。错误带上「是不是挂载这一步」。// 镜像好了再在同一条隧道上处理后台 WDA(见 prepare_detached)// 挂上的镜像版本、后台 WDA 的处理结果、启动前打开的系统日志流@@ -474,6 +480,7 @@ impl Daemon {}async fn heal_certificate(self: Arc<Self>, udid: String, foreign: Option<bool>) {+ let Ok(_lease) = crate::maintenance::shared() else { return };if self.account().selected_email().await.is_err() {return;}@@ -554,6 +561,7 @@ impl Daemon {// ------------------------------------------------------------------ 重签与会话async fn check_session(self: Arc<Self>) {+ let Ok(_lease) = crate::maintenance::shared() else { return };let account = self.account();// plume_core 的 future 不是 Send,放到阻塞线程里 block_on(同重签);也不持锁// 会话好的话顺便查本机的签名证书还在不在团队里(同一次登录)@@ -615,6 +623,7 @@ impl Daemon {/// 检查描述文件并按需重签(`force` 立即重签)。分三段:持锁取参数 → 不持锁签名、安装(几十秒)→ 持锁写结果pub(crate) async fn resign_now(self: &Arc<Self>, force: bool) -> Result<String, String> {+ let _lease = crate::maintenance::shared().map_err(|e| e.to_string())?;let (device, name) = {let mut g = self.inner.lock().await;let g = &mut *g;diff --git a/docs/dev/release-updates.md b/docs/dev/release-updates.mdnew file mode 100644index 0000000..beff86f--- /dev/null+++ b/docs/dev/release-updates.md@@ -0,0 +1,55 @@+# Publishing signed host updates++A release identifies its GitHub publisher at build time. Source builds without this binding do not contact a release repository. A fork that distributes its own binaries needs its own release configuration and keys.++## Configure the publisher++Set these GitHub Actions **repository variables** before pushing a release tag.++| Variable | Value |+| --- | --- |+| `ICTL_UPDATE_PUBLISHER` | Exact, case-sensitive `owner/repo` of this repository. For upstream releases use `Derrors/iphone-control`. A fork uses its own repository name. |+| `ICTL_UPDATE_PUBLIC_KEYS` | Comma-separated Ed25519 public keys. Each is the lowercase hex encoding of the raw 32-byte public key. |+| `ICTL_UPDATE_TAP` | Optional `owner/tap` Homebrew identity. For `owner/tap`, the push target is `owner/homebrew-tap`. Configure the repository-specific write deploy key in the `HOMEBREW_TAP_DEPLOY_KEY` secret. |++Create the GitHub Actions environment `release-signing`, restrict it to release tags and configure the publisher's approval rules. Store the PKCS#8 PEM signing key in its **environment secret** `ICTL_UPDATE_SIGNING_KEY`. The build jobs get only the public keys. Keep access to the private key with the designated release signer.++For example, generate the key in a private directory outside the checkout. With OpenSSL 3, this prints the public pin and leaves the private key in the chosen directory.++```sh+umask 077+openssl genpkey -algorithm ED25519 -out signing-key.pem+openssl pkey -in signing-key.pem -pubout -outform DER | tail -c 32 | od -An -v -tx1 | tr -d ' \n'+```++The stable tag must match the workspace package version, e.g. `v0.2.1` for `0.2.1`. The workflow checks the uploaded archives against the build output before signing the manifest bytes for each target. Linux and Apple Silicon macOS have independent signing jobs. During a partial release, a platform can have an archive before its signed manifest appears.++## Roll out a release++Set `ICTL_ROLLBACK_COMPATIBLE_TAG` in the signing environment to the destination tag and `ICTL_ROLLBACK_FROM_VERSION` to the exact installed version tested for recovery. For example, set them to `v0.2.3` and `0.2.2` after verifying that 0.2.2 can read data written by 0.2.3. The signed manifest binds this pair. Users on other versions follow the release's manual migration instructions. Leave the tag unset to require manual migration for everyone.++Set `ICTL_UNATTENDED_TAG` to the same destination tag only after validating patch replacement and recovery without a connected phone, with busy clients, and on the target service managers. Each new tag requires a separate decision.++Run the signed offline installer tests with `python3 packaging/test_installer.py`. They use a temporary key, a custom prefix and isolated service manager commands. Before enabling unattended updates for a distribution, exercise a good patch and a failing daemon build through its native launchd and systemd user services. Use isolated installations and retain a working CLI for recovery.++For key rotation, publish a normally signed release with both the current and next public key embedded. After users have that release, change the environment secret to the next key. Keep previous releases' metadata immutable. Clients that missed the overlap need to acquire a newly trusted installer from their publisher. A compromised trust root requires a fresh bootstrap through a separately trusted distribution channel.++## Bootstrap and migration++Use the standalone `install.sh` **release asset** with Python 3 and OpenSSL 3 on PATH. It embeds the release publisher and its public keys. For a fork, select the fork's Releases page and check that its signing job published an installer and the target's manifest and signature. For example, after upstream publishes its first signed release, the install command is++```sh+curl -fsSL https://github.com/Derrors/iphone-control/releases/latest/download/install.sh | sh+```++A custom prefix and an explicit version can be supplied using `sh -s -- --prefix "$HOME/tools" --version v0.2.1`. A version-selected installation records a pin. `--no-service` is available for a manually started daemon. The source-tree script carries no publisher keys.++The installer stores its receipt under `$XDG_CONFIG_HOME/iphone-control/install-receipt.json`, defaulting to `~/.config/iphone-control/install-receipt.json`. It checks the canonical executable path and binary digest before uninstall or delegation to the local updater. Re-running the signed installer on an existing receipted service delegates a normal upgrade to `iphone-control update apply`.++For an older script installation, close clients and stop the daemon, then uninstall its binary and service using the original installation method. Install the signed release at the intended prefix to create the receipt. Keep the existing configuration and device data during migration. Package-managed users continue through their Homebrew tap or Debian package.++## Local acceptance coverage++`cargo test --workspace --all-features --locked` covers shared release checks, channel ownership, signatures, interrupted replacements and the CLI/Viewer contract. The transaction tests start disposable child daemons on Unix sockets. They also kill the updater between journal phases and check the executable digest and service state after recovery.++The Apple Silicon rehearsal used two builds of this workspace, temporary release keys, a local HTTPS release server and separate launchd labels, HOME, socket and installation prefix. No phone was connected. The real scheduled updater deferred for an open Viewer without downloading the archive, then installed the signed test patch. An explicit rollback restored the original digest. A second signed candidate failed the 60-second daemon health check; the updater restored the original, answered a status request and suppressed automatic retries of that candidate. A release signed for a different source version was rejected before the archive download. Running the generated installer again on the current version kept the same daemon PID. Both fixture services and the temporary signing keys were removed. Public GitHub release assets, the production key, the tap and native Linux user systemd still require release-environment verification.diff --git a/install.sh b/install.shindex 5647ea1..f7cac4a 100755--- a/install.sh+++ b/install.sh@@ -1,235 +1,11 @@#!/bin/sh-# iphone-control installer for macOS (Apple Silicon) and Linux (x86_64, aarch64).-#-# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh-# curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --version v0.2.1-#-# Downloads the release archive for this machine, checks its sha256, installs the binary into ~/.local/bin and-# sets up the daemon as a per-user service (launchd on macOS, systemd --user on Linux) that starts at login and-# restarts after a crash. Running it again upgrades. Nothing runs as root; your data stays in-# ~/.local/share/iphone-control.-#-# Options (or the environment variable in brackets):-# --version vX.Y.Z install this release instead of the latest [IPHONE_CONTROL_VERSION]-# --prefix DIR install into DIR/bin (default ~/.local) [IPHONE_CONTROL_PREFIX]-# --no-service only install the binary; start the daemon yourself [IPHONE_CONTROL_NO_SERVICE=1]-# --uninstall stop and remove the service and the binary (keeps your data)-set -eu--REPO="Derrors/iphone-control"-LABEL="io.github.derrors.iphone-control"-VERSION="${IPHONE_CONTROL_VERSION:-}"-PREFIX="${IPHONE_CONTROL_PREFIX:-$HOME/.local}"-SERVICE=1-[ "${IPHONE_CONTROL_NO_SERVICE:-}" = 1 ] && SERVICE=0-UNINSTALL=0--# Messages in Chinese when IPHONE_CONTROL_LANG or the locale says so, English otherwise-case "${IPHONE_CONTROL_LANG:-${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}}" in- zh*) ZH=1 ;;- *) ZH=0 ;;-esac-say() { if [ "$ZH" = 1 ]; then printf '%s\n' "$1"; else printf '%s\n' "$2"; fi; }-die() { say "错误:$1" "Error: $2" >&2; exit 1; }--while [ $# -gt 0 ]; do- case "$1" in- --version) VERSION="${2:-}"; shift 2 ;;- --prefix) PREFIX="${2:-}"; shift 2 ;;- --no-service) SERVICE=0; shift ;;- --uninstall) UNINSTALL=1; shift ;;- -h|--help) sed -n '2,19p' "$0" 2>/dev/null || true; exit 0 ;;- *) die "不认识的参数 $1" "unknown option $1" ;;- esac-done--# As root, the daemon would use system paths and, on macOS, fight the system usbmuxd-[ "$(id -u)" -ne 0 ] || die "不要用 root 或 sudo 运行,以普通用户安装即可" "don't run this as root or with sudo; install as your regular user"--OS="$(uname -s)"-ARCH="$(uname -m)"-case "$OS" in- Darwin)- # a shell running under Rosetta reports x86_64 on Apple Silicon- if [ "$ARCH" = x86_64 ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)" = 1 ]; then ARCH=arm64; fi- [ "$ARCH" = arm64 ] || die "只有 Apple 芯片的 Mac 有预编译版本;Intel Mac 请从源码编译(见 macOS 指南)" \- "prebuilt binaries are for Apple Silicon Macs only; on an Intel Mac build from source (see the macOS guide)"- TARGET="macos-arm64"- ;;- Linux)- case "$ARCH" in- x86_64|amd64) TARGET="linux-x86_64" ;;- aarch64|arm64) TARGET="linux-aarch64" ;;- *) die "不支持的架构 $ARCH" "unsupported architecture $ARCH" ;;- esac- ;;- *) die "只支持 macOS 和 Linux" "only macOS and Linux are supported" ;;-esac--BIN_DIR="$PREFIX/bin"-BIN="$BIN_DIR/iphone-control"-PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"-UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"-UNIT="$UNIT_DIR/iphone-control.service"-CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/iphone-control"--has_systemd_user() { command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; }--stop_service() {- if [ "$OS" = Darwin ]; then- launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true- elif has_systemd_user && [ -f "$UNIT" ]; then- systemctl --user stop iphone-control 2>/dev/null || true- fi- # the daemon can take up to half a minute to stop (it ends the phone's HID session and WDA first); both service- # managers end it by force after 30 s, so wait a little longer than that- n=0- while pgrep -f "$BIN daemon" >/dev/null 2>&1 && [ "$n" -lt 45 ]; do sleep 1; n=$((n + 1)); done-}--if [ "$UNINSTALL" = 1 ]; then- stop_service- if [ "$OS" = Darwin ]; then- rm -f "$PLIST"- elif [ -f "$UNIT" ]; then- if has_systemd_user; then systemctl --user disable iphone-control 2>/dev/null || true; fi- rm -f "$UNIT"- if has_systemd_user; then systemctl --user daemon-reload || true; fi- fi- rm -f "$BIN"- say "已卸载 iphone-control。数据还在 ~/.local/share/iphone-control(Apple ID 会话、签名、自动解锁密码),不需要的话自己删除;手机上的 WebDriverAgent 在手机上删除。" \- "iphone-control is uninstalled. Your data is still in ~/.local/share/iphone-control (Apple ID session, signing, auto-unlock passcodes); delete it if you no longer need it, and remove WebDriverAgent on the phone."- exit 0-fi--command -v curl >/dev/null 2>&1 || die "需要 curl" "curl is required"-command -v tar >/dev/null 2>&1 || die "需要 tar" "tar is required"--if [ -z "$VERSION" ]; then- # the latest release's tag, from where /releases/latest redirects (no API rate limit)- url="$(curl -fsSLo /dev/null -w '%{url_effective}' "https://github.com/$REPO/releases/latest")" ||- die "查不到最新版本,检查网络,或用 --version 指定" "couldn't find the latest release; check the network or pass --version"- VERSION="${url##*/}"-fi-case "$VERSION" in v*) ;; *) VERSION="v$VERSION" ;; esac--NAME="iphone-control-$VERSION-$TARGET"-BASE="https://github.com/$REPO/releases/download/$VERSION"-TMP="$(mktemp -d)"-trap 'rm -rf "$TMP"' EXIT INT TERM--say "下载 iphone-control ${VERSION}(${TARGET})…" "Downloading iphone-control $VERSION ($TARGET)…"-# a progress bar only in a terminal-if [ -t 2 ]; then progress=--progress-bar; else progress=-s; fi-curl -fSL "$progress" -o "$TMP/$NAME.tar.gz" "$BASE/$NAME.tar.gz" ||- die "下载失败:$BASE/$NAME.tar.gz" "download failed: $BASE/$NAME.tar.gz"-curl -fsSL -o "$TMP/$NAME.tar.gz.sha256" "$BASE/$NAME.tar.gz.sha256" || die "下载校验和失败" "couldn't download the checksum"-if command -v sha256sum >/dev/null 2>&1; then- (cd "$TMP" && sha256sum -c "$NAME.tar.gz.sha256" >/dev/null) || die "sha256 校验不通过" "sha256 check failed"-else- (cd "$TMP" && shasum -a 256 -c "$NAME.tar.gz.sha256" >/dev/null) || die "sha256 校验不通过" "sha256 check failed"-fi-tar -xzf "$TMP/$NAME.tar.gz" -C "$TMP"--# replacing the binary under a running daemon: stop it first, start it again below-stop_service-mkdir -p "$BIN_DIR" "$CONF_DIR"-install -m 755 "$TMP/$NAME/iphone-control" "$BIN"-[ -f "$TMP/$NAME/env.example" ] && cp "$TMP/$NAME/env.example" "$CONF_DIR/env.example"-say "已安装 ${BIN}($("$BIN" --version))" "Installed $BIN ($("$BIN" --version))"--if [ "$OS" = Linux ] && ! command -v usbmuxd >/dev/null 2>&1 && [ ! -x /usr/sbin/usbmuxd ]; then- say "还缺 usbmuxd(和 iPhone 通过 USB 通信要用):sudo apt install usbmuxd(其他发行版用对应的包管理器)" \- "usbmuxd is missing (needed to talk to the iPhone over USB): sudo apt install usbmuxd (or your distribution's package manager)"-fi--started=0-if [ "$SERVICE" = 1 ]; then- if pgrep -f "iphone-control daemon" >/dev/null 2>&1; then- # a daemon started by hand: a second one would fight it for the phone- say "已有一个手动启动的守护进程在运行,没有启动服务。先停掉它(pkill -f 'iphone-control daemon'),再重新运行这个脚本。" \- "A daemon you started by hand is running, so the service wasn't started. Stop it (pkill -f 'iphone-control daemon') and run this script again."- elif [ "$OS" = Darwin ]; then- mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs/iphone-control"- # settings from ~/.config/iphone-control/env, like the systemd service on Linux- cat > "$PLIST" <<EOF-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key><string>$LABEL</string>- <key>ProgramArguments</key>- <array>- <string>/bin/sh</string>- <string>-c</string>- <string>set -a; f="\$HOME/.config/iphone-control/env"; [ -f "\$f" ] && . "\$f"; set +a; exec "$BIN" daemon</string>- </array>- <key>RunAtLoad</key><true/>- <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>- <key>ThrottleInterval</key><integer>10</integer>- <key>ExitTimeOut</key><integer>30</integer>- <key>StandardOutPath</key><string>$HOME/Library/Logs/iphone-control/daemon.log</string>- <key>StandardErrorPath</key><string>$HOME/Library/Logs/iphone-control/daemon.log</string>-</dict>-</plist>-EOF- launchctl bootstrap "gui/$(id -u)" "$PLIST" && started=1- elif has_systemd_user; then- mkdir -p "$UNIT_DIR"- cat > "$UNIT" <<EOF-# Installed by install.sh. Settings: ~/.config/iphone-control/env (see env.example next to it)-[Unit]-Description=iphone-control daemon (iPhone over USB, MCP)-After=network-online.target--[Service]-ExecStart=$BIN daemon-EnvironmentFile=-%h/.config/iphone-control/env-Environment=MALLOC_ARENA_MAX=2-Restart=on-failure-RestartSec=10-TimeoutStopSec=30--[Install]-WantedBy=default.target-EOF- systemctl --user daemon-reload- systemctl --user enable --now iphone-control && started=1- if command -v loginctl >/dev/null 2>&1 && [ "$(loginctl show-user "$(id -un)" -p Linger --value 2>/dev/null)" != yes ]; then- say "要不登录也随开机启动,运行:sudo loginctl enable-linger $(id -un)" \- "To start it at boot without logging in, run: sudo loginctl enable-linger $(id -un)"- fi- else- say "没有可用的 systemd 用户会话,没有安装服务。手动启动:$BIN daemon" \- "No systemd user session, so no service was installed. Start it yourself: $BIN daemon"- fi-fi--case ":$PATH:" in- *":$BIN_DIR:"*) ;;- *) say "$BIN_DIR 不在 PATH 里。把这行加到 shell 的配置文件(~/.zshrc 或 ~/.bashrc):export PATH=\"$BIN_DIR:\$PATH\"" \- "$BIN_DIR isn't on your PATH. Add this line to your shell profile (~/.zshrc or ~/.bashrc): export PATH=\"$BIN_DIR:\$PATH\"" ;;-esac--echo-if [ "$started" = 1 ]; then- say "守护进程已作为服务运行,登录后自动启动。" "The daemon runs as a service and starts when you log in."-elif [ "$SERVICE" = 0 ]; then- say "没有安装服务。启动守护进程:$BIN daemon" "No service installed. Start the daemon: $BIN daemon"-fi-# on macOS the control page encodes H.264 with VideoToolbox itself-if [ "$OS" = Linux ] && ! command -v ffmpeg >/dev/null 2>&1; then- say "可选:装上 ffmpeg,控制台(iphone-control viewer)的画面改用 H.264,流量约为原来的 1/15:sudo apt install ffmpeg" \- "Optional: with ffmpeg installed, the control page (iphone-control viewer) uses H.264 at about 1/15 of the traffic: sudo apt install ffmpeg"- echo-fi-say "接下来:用数据线连上 iPhone,然后运行-- iphone-control--它会一步步带你完成设置(配对、开发者模式、Apple ID、安装 WDA、注册到 Claude Code / Codex),设置好以后再运行只显示状态。" \-"Next: connect the iPhone with a cable, then run-- iphone-control--It walks you through setup step by step (pairing, Developer Mode, Apple ID, WDA, registering with Claude Code / Codex); once set up, running it again just shows the status."+# A source checkout has no release identity or trusted update keys. Release jobs+# generate a standalone install.sh (packaging/release.py) containing both.+cat >&2 <<'HELP'+Download install.sh from your publisher's signed GitHub Release.+For an upstream v0.2.0 script installation, the legacy installer is at+https://raw.githubusercontent.com/Derrors/iphone-control/v0.2.0/install.sh+Pass --version v0.2.0 to install that version, or --uninstall to remove it+before migrating. If you used --prefix DIR, use the same prefix again.+HELP+exit 1diff --git a/packaging/homebrew/formula.sh b/packaging/homebrew/formula.shindex ae9918b..4eacd35 100755--- a/packaging/homebrew/formula.sh+++ b/packaging/homebrew/formula.sh@@ -1,17 +1,18 @@#!/bin/sh-# Prints the Homebrew formula for one release (the release workflow pushes it to Derrors/homebrew-tap):+# Prints the Homebrew formula for one release:# packaging/homebrew/formula.sh v0.2.1 <sha256 macos-arm64> <sha256 linux-x86_64> <sha256 linux-aarch64># The formula installs the prebuilt binary from the GitHub release; `brew services start iphone-control` runs the# daemon (launchd on macOS, systemd on Linux) with the settings in ~/.config/iphone-control/env.set -eu[ $# -eq 4 ] || { echo "usage: $0 vX.Y.Z SHA_MACOS_ARM64 SHA_LINUX_X86_64 SHA_LINUX_AARCH64" >&2; exit 2; }tag="$1"-base="https://github.com/Derrors/iphone-control/releases/download/$tag/iphone-control-$tag"+repo="${ICTL_UPDATE_PUBLISHER:?set the release publisher as owner/repo}"+base="https://github.com/$repo/releases/download/$tag/iphone-control-$tag"cat <<EOF-# Generated by packaging/homebrew/formula.sh in Derrors/iphone-control for $tag; don't edit by hand.+# Generated by packaging/homebrew/formula.sh in $repo for $tag; don't edit by hand.class IphoneControl < Formuladesc "Let AI agents operate a real iPhone or iPad over USB (MCP server and daemon)"- homepage "https://github.com/Derrors/iphone-control"+ homepage "https://github.com/$repo"license "MIT"on_macos dodiff --git a/packaging/installer.py b/packaging/installer.pynew file mode 100644index 0000000..d0f9c9c--- /dev/null+++ b/packaging/installer.py@@ -0,0 +1,540 @@+"""Install a verified iphone-control release for the current user (Python 3 and OpenSSL 3)."""+import argparse+import contextlib+import fcntl+import gzip+import hashlib+import json+import os+from pathlib import Path+import platform+import plistlib+import re+import shlex+import shutil+import stat+import subprocess+import sys+import tarfile+import tempfile+import urllib.parse+import urllib.request+++# packaging/release.py binds these in the generated, standalone install.sh.+PUBLISHER = ""+PUBLIC_KEYS = ""+LABEL = "io.github.derrors.iphone-control"+MIB = 1024 * 1024+VERSION = r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"+++def allowed(url):+ parsed = urllib.parse.urlparse(url)+ if (parsed.scheme != "https" or parsed.username or parsed.password or parsed.port not in (None, 443)+ or parsed.hostname not in {"api.github.com", "github.com", "release-assets.githubusercontent.com",+ "objects.githubusercontent.com"}):+ raise ValueError("unexpected release download host")+++class GitHubRedirects(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ allowed(newurl)+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++def copy_limited(source, dest, limit):+ count = 0+ while True:+ chunk = source.read(min(MIB, limit - count + 1))+ if not chunk:+ return count+ count += len(chunk)+ if count > limit:+ raise ValueError("download or archive exceeds size limit")+ dest.write(chunk)+++def download(url, dest, limit):+ allowed(url)+ with urllib.request.build_opener(GitHubRedirects()).open(url, timeout=30) as response, dest.open("xb") as out:+ return copy_limited(response, out, limit)+++def digest(path):+ with path.open("rb") as f:+ result = hashlib.sha256()+ for chunk in iter(lambda: f.read(MIB), b""):+ result.update(chunk)+ return result.hexdigest()+++def verify_manifest(directory, manifest, sig, repo, keys, version, target):+ keyfile = directory / "public.der"+ for key in keys.split(","):+ keyfile.write_bytes(bytes.fromhex("302a300506032b6570032100" + key))+ verified = subprocess.run(["openssl", "pkeyutl", "-verify", "-rawin", "-pubin", "-keyform", "DER",+ "-inkey", keyfile, "-in", manifest, "-sigfile", sig],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ if verified.returncode == 0:+ break+ else:+ raise ValueError("Ed25519 manifest verification failed (requires OpenSSL 3 and a trusted signing key)")+ data = json.loads(manifest.read_bytes())+ name = f"iphone-control-v{version}-{target}.tar.gz"+ if (type(data["schema"]) is not int or data["schema"] != 1 or data["publisher"] != repo+ or data["version"] != version or data["target"] != target or data["asset"] != name+ or not re.fullmatch("[0-9a-f]{64}", data["sha256"])+ or type(data["size"]) is not int or not 0 < data["size"] <= 128 * MIB+ or type(data["unattended"]) is not bool or type(data["rollback_compatible"]) is not bool):+ raise ValueError("release manifest does not match requested installation")+ return data+++def extract(archive, directory, name):+ # Bound inflated bytes including tar headers before letting the tar parser read metadata.+ raw = directory / "archive.tar"+ with gzip.open(archive, "rb") as stream, raw.open("xb") as out:+ copy_limited(stream, out, 256 * MIB)+ seen = set()+ with tarfile.open(raw, "r:") as tar:+ for item in tar:+ if item.isdir() and item.name == name:+ continue+ parent, _, leaf = item.name.rpartition("/")+ if (not item.isreg() or item.sparse is not None or parent != name or leaf in ("", ".", "..")+ or leaf in seen or len(seen) >= 64):+ raise ValueError("invalid entry in release archive")+ seen.add(leaf)+ if leaf in ("iphone-control", "env.example"):+ with tar.extractfile(item) as src, (directory / leaf).open("xb") as out:+ if copy_limited(src, out, item.size) != item.size:+ raise ValueError("truncated release archive")+ binary = directory / "iphone-control"+ binary.chmod(0o755)+ return binary+++def candidate(directory, target, requested):+ if requested:+ version = requested[1:] if requested.startswith("v") else requested+ else:+ latest = directory / "latest.json"+ download(f"https://api.github.com/repos/{PUBLISHER}/releases/latest", latest, 4 * MIB)+ release = json.loads(latest.read_bytes())+ if release["draft"] is not False or release["prerelease"] is not False or not release["tag_name"].startswith("v"):+ raise ValueError("latest release is not a stable tag")+ version = release["tag_name"][1:]+ if not re.fullmatch(VERSION, version):+ raise ValueError("expected a stable version (vX.Y.Z)")+ name = f"iphone-control-v{version}-{target}"+ base = f"https://github.com/{PUBLISHER}/releases/download/v{version}/{name}"+ manifest, sig, archive = (directory / ext for ext in ("manifest.json", "manifest.sig", "archive.tgz"))+ download(base + ".manifest.json", manifest, 16 * 1024)+ if download(base + ".manifest.json.sig", sig, 64) != 64:+ raise ValueError("invalid Ed25519 signature length")+ data = verify_manifest(directory, manifest, sig, PUBLISHER, PUBLIC_KEYS, version, target)+ size = download(base + ".tar.gz", archive, data["size"])+ if size != data["size"] or digest(archive) != data["sha256"]:+ raise ValueError("release archive size or SHA-256 mismatch")+ binary = extract(archive, directory, name)+ found = subprocess.check_output([binary, "--version"], timeout=15).decode().strip()+ if found != f"iphone-control {version}":+ raise ValueError("executable version does not match the signed manifest")+ return binary, version+++def run(*args):+ return subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0+++def service_files(config):+ if sys.platform == "darwin":+ return "launchd", Path.home() / "Library/LaunchAgents" / (LABEL + ".plist")+ return "systemd", config.parent / "systemd/user/iphone-control.service"+++def service_text(binary, kind, config):+ env = {"XDG_CONFIG_HOME": str(config.parent)}+ for name in ("XDG_DATA_HOME", "XDG_RUNTIME_DIR"):+ value = os.environ.get(name)+ if value:+ if not Path(value).is_absolute():+ raise ValueError(f"{name} must be an absolute path")+ env[name] = value+ if kind == "launchd":+ log = str(Path.home() / "Library/Logs/iphone-control/daemon.log")+ return plistlib.dumps(dict(+ Label=LABEL, ProgramArguments=[str(binary), "daemon"], EnvironmentVariables=env,+ RunAtLoad=True, KeepAlive=dict(SuccessfulExit=False), ThrottleInterval=10, ExitTimeOut=30,+ StandardOutPath=log, StandardErrorPath=log,+ )).decode()+ # systemd expands percent specifiers and dollar variables after unquoting ExecStart.+ # Keep the path representation identical to the managed-service validator.+ if any(c in str(binary) for c in '"\\$%') or any(ord(c) < 32 for c in str(binary)):+ raise ValueError("unsupported character in systemd executable path; choose another prefix or --no-service")+ def quote(value):+ if any(ord(c) < 32 for c in value):+ raise ValueError("unsupported control character in service environment")+ return '"' + value.replace('\\', '\\\\').replace('"', '\\"').replace('%', '%%') + '"'+ environment = "\n".join("Environment=" + quote(name + "=" + val) for name, val in env.items())+ return f"""# Installed by install.sh+[Unit]+Description=iphone-control daemon (iPhone over USB, MCP)+After=network-online.target+[Service]+ExecStart="{binary}" daemon+{environment}+Environment=MALLOC_ARENA_MAX=2+Restart=on-failure+RestartSec=10+TimeoutStopSec=30+[Install]+WantedBy=default.target+"""+++def owns_service(path, binary, kind):+ if path.is_symlink() or not path.is_file():+ return False+ info = path.stat()+ if info.st_uid != os.getuid() or info.st_mode & 0o022:+ return False+ if kind == "launchd":+ data = plistlib.loads(path.read_bytes())+ args = data.get("ProgramArguments")+ script = f'set -a; f="$HOME/.config/iphone-control/env"; [ -f "$f" ] && . "$f"; set +a; exec "{binary}" daemon'+ # 'service install' can recreate a removed definition using the older shell form.+ shell_safe = not any(c in str(binary) for c in '\\"$`\n\r')+ return (data.get("Label") == LABEL and "Program" not in data and+ (args == [str(binary), "daemon"] or (shell_safe and args == ["/bin/sh", "-c", script])))+ lines = path.read_text().splitlines()+ commands = [line.strip() for line in lines if line.strip().startswith("ExecStart=")]+ if "# Installed by install.sh" in lines:+ return commands == [f'ExecStart="{binary}" daemon']+ return (bool(lines) and lines[0].startswith("# Written by iphone-control. Settings: ")+ and not any(c.isspace() or c in '\\"$%' for c in str(binary))+ and commands == [f"ExecStart={binary} daemon"])+++def launchd_loaded(path):+ result = subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"],+ env={**os.environ, "LC_ALL": "C"}, text=True, capture_output=True)+ if result.returncode:+ if "Could not find service" in result.stderr:+ return False+ raise ValueError("could not query the launchd user service")+ if f"\tpath = {path}" not in result.stdout.splitlines():+ raise ValueError("another launch agent owns this service label")+ return True+++def systemd_owner(path):+ result = subprocess.run(["systemctl", "--user", "show", "iphone-control", "--all", "-p", "FragmentPath", "-p", "DropInPaths"],+ text=True, check=True, capture_output=True)+ if f"FragmentPath={path}" not in result.stdout.splitlines() or "DropInPaths=" not in result.stdout.splitlines():+ raise ValueError("systemd loaded another unit or an override for this service")+++def service_removed(kind, path):+ if path.exists() or path.is_symlink():+ return False+ # A missing definition may still be loaded, or systemd may have selected a+ # package's unit of the same name. Leave either service alone.+ if kind == "launchd":+ if launchd_loaded(path):+ raise ValueError("daemon service is still loaded without its definition")+ else:+ result = subprocess.run(["systemctl", "--user", "show", "iphone-control", "-p", "LoadState",+ "-p", "ActiveState"], text=True, capture_output=True)+ if not {"LoadState=not-found", "ActiveState=inactive"}.issubset(result.stdout.splitlines()):+ raise ValueError("could not confirm removal of the recorded systemd service")+ return True+++def start_service(binary, config):+ kind, path = service_files(config)+ # Only finish a prior interrupted bootstrap when its complete generated file matches.+ expected = service_text(binary, kind, config)+ ours = path.is_file() and not path.is_symlink() and path.stat().st_uid == os.getuid() and path.read_text() == expected+ if kind == "launchd":+ loaded = launchd_loaded(path)+ if loaded and not ours:+ raise ValueError("another launch agent owns this service label")+ conflicts = [p for p in path.parent.glob("*.iphone-control.plist") if p != path]+ else:+ if not shutil.which("systemctl") or not run("systemctl", "--user", "show-environment"):+ print("No systemd user session. Start the installed binary with 'daemon'.")+ return "none"+ conflicts = [unit for unit in ("iphone-control", "homebrew.iphone-control") if not (unit == "iphone-control" and ours) and run("systemctl", "--user", "cat", unit)]+ if ((path.is_symlink() or path.exists()) and not ours) or conflicts or (not ours and run("pgrep", "-f", r"iphone-control daemon( |$)")):+ raise ValueError("another daemon or service already exists; stop it and resolve its ownership first")+ path.parent.mkdir(parents=True, exist_ok=True)+ if not ours:+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)+ with os.fdopen(fd, "w") as f:+ f.write(expected)+ if kind == "launchd":+ (Path.home() / "Library/Logs/iphone-control").mkdir(parents=True, exist_ok=True)+ if not loaded:+ subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", path], check=True)+ else:+ subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)+ systemd_owner(path)+ subprocess.run(["systemctl", "--user", "enable", "--now", "iphone-control"], check=True)+ return kind+++def write_receipt(path, data):+ with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as f:+ json.dump(data, f, ensure_ascii=False, indent=2)+ f.write("\n")+ f.flush()+ os.fsync(f.fileno())+ os.replace(f.name, path)+++def read_receipt(path, binary, target):+ if path.is_symlink() or binary.is_symlink():+ raise ValueError("installation or receipt is a symlink")+ if not path.exists() and not binary.exists():+ return None+ if not path.is_file() or not binary.is_file():+ raise ValueError("existing installation has no matching receipt; close its clients and remove the old binary before installing")+ data = json.loads(path.read_bytes())+ if (data["schema"] != 1 or data["publisher"] != PUBLISHER or data["target"] != target+ or data["binary_path"] != str(binary) or data["service"] not in ("launchd", "systemd", "none")+ or binary.stat().st_uid != os.getuid() or path.stat().st_uid != os.getuid()+ or binary.stat().st_mode & 0o022 or path.stat().st_mode & 0o022+ or digest(binary) != data["sha256"]):+ raise ValueError("installed binary does not match the installation receipt")+ return data+++def remove_update_state(binary):+ state = binary.parent / ".iphone-control-update"+ if state.is_symlink() or not state.is_dir():+ return+ meta = state.stat()+ if meta.st_uid != os.getuid() or meta.st_mode & 0o077:+ return++ # The caller holds the prefix lock and has verified the installation receipt.+ # Only unlink regular updater files in its private directory. Leave user files+ # and links untouched, including anything unrecognized in an interrupted stage.+ def remove_files(directory, names):+ for name in names:+ path = directory / name+ if not path.is_symlink() and path.is_file() and path.stat().st_uid == os.getuid():+ path.unlink()++ remove_files(state, ("recovery", "previous", "previous.json", "swap-link", "outcome.json"))+ stage = state / "stage"+ if not stage.is_symlink() and stage.is_dir() and stage.stat().st_uid == os.getuid() and not stage.stat().st_mode & 0o077:+ remove_files(stage, ("archive", "candidate"))+ if not any(stage.iterdir()):+ stage.rmdir()+ if not any(state.iterdir()):+ state.rmdir()+++def owns_update_job(binary, config):+ launcher = config / "update-job.sh"+ if (not launcher.is_symlink() and launcher.is_file() and launcher.stat().st_uid == os.getuid()+ and not launcher.stat().st_mode & 0o022):+ with launcher.open(errors="replace") as f:+ header = (f.readline(), f.readline())+ try:+ assignment = shlex.split(f.readline())+ except ValueError:+ assignment = []+ return header == ("#!/bin/sh\n", "# iphone-control update job\n") and assignment == ["exe=" + str(binary)]+ return False+++def disabled_update_job(binary, config):+ if owns_update_job(binary, config):+ subprocess.run([binary, "update", "policy", "manual"], check=True)+ # The CLI acquires this lock itself. Recheck after it exits, and keep the+ # lock through receipt changes/deletion so a concurrent CLI cannot re-arm.+ fd = os.open(config / "update-schedule.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)+ with os.fdopen(fd, "rb+") as lock:+ fcntl.flock(lock, fcntl.LOCK_EX)+ if owns_update_job(binary, config):+ raise ValueError("update schedule was re-enabled during removal; retry")+ clear_update_policy(binary, config)+ yield+++def clear_update_policy(binary, config):+ # The updater keys script policy by publisher and canonical executable path.+ # A fresh install at this prefix must get its default policy, even if a+ # previous installation explicitly disabled its schedule during removal.+ key = hashlib.sha256(os.fsencode(binary)).hexdigest()+ policy = config / "updates" / PUBLISHER / (key + ".json")+ if (policy.is_file() and policy.resolve() == config.resolve() / policy.relative_to(config)+ and policy.stat().st_uid == os.getuid()):+ policy.unlink()+++def uninstall(binary, config, receipt, data):+ if data is None:+ raise ValueError("no receipted installation at this prefix")+ kind, path = service_files(config)+ # A first install may have been interrupted between writing the unit and recording its activation.+ owned = owns_service(path, binary, kind)+ if data["service"] not in (kind, "none"):+ raise ValueError("unexpected service in the installation receipt")+ if data["service"] != "none" and not owned and not service_removed(kind, path):+ raise ValueError("daemon service no longer matches this installation")+ loaded = owned and kind == "launchd" and launchd_loaded(path)+ if owned and kind == "systemd":+ systemd_owner(path)+ with disabled_update_job(binary, config):+ if owned:+ if kind == "launchd":+ domain = f"gui/{os.getuid()}/{LABEL}"+ if loaded:+ subprocess.run(["launchctl", "bootout", domain], check=True)+ else:+ subprocess.run(["systemctl", "--user", "disable", "--now", "iphone-control"], check=True)+ path.unlink()+ if kind == "systemd":+ subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)+ remove_update_state(binary)+ binary.unlink()+ receipt.unlink()+ print("Removed iphone-control. Your configuration and device data are preserved.")+++def transaction_lock(binary_dir):+ path = binary_dir / ".iphone-control-update.lock"+ fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)+ with os.fdopen(fd, "rb+") as lock:+ info = os.fstat(fd)+ if info.st_uid != os.getuid() or not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:+ raise ValueError("invalid update lock ownership or permissions")+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ raise ValueError("an update is in progress") from None+ yield+++def bootstrap(binary, config, receipt, data, target, requested, no_service):+ with tempfile.TemporaryDirectory(prefix=".iphone-control-install-", dir=binary.parent) as temp:+ directory = Path(temp)+ source, version = candidate(directory, target, requested)+ sha = digest(source)+ if data and (version != data["version"] or sha != data["sha256"]):+ raise ValueError("manual installation: close clients and uninstall the old version before reinstalling")+ if not data:+ os.link(source, binary) # same filesystem; never clobber an existing executable+ new = dict(schema=1, publisher=PUBLISHER, target=target, binary_path=str(binary),+ service="none", version=version, sha256=sha, pinned=bool(requested or (data and data["pinned"])))+ write_receipt(receipt, new)+ if (directory / "env.example").is_file():+ with tempfile.NamedTemporaryFile(dir=config, delete=False) as f:+ f.write((directory / "env.example").read_bytes())+ os.replace(f.name, config / "env.example")+ if not no_service:+ new["service"] = start_service(binary, config)+ write_receipt(receipt, new)+ if new["service"] != "none":+ subprocess.run([binary, "update", "schedule"], check=True)+ print(f"Installed iphone-control {version} at {binary} ({new['service']}).")+ if str(binary.parent) not in map(os.path.realpath, os.get_exec_path()):+ print("To run iphone-control by name, run this command and add it to your shell profile.")+ print(f' export PATH={shlex.quote(str(binary.parent))}:"$PATH"')+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--version", default=os.getenv("IPHONE_CONTROL_VERSION"))+ parser.add_argument("--prefix", type=Path, default=os.environ.get("IPHONE_CONTROL_PREFIX", str(Path.home() / ".local")))+ parser.add_argument("--no-service", action="store_true", default=os.environ.get("IPHONE_CONTROL_NO_SERVICE") == "1")+ parser.add_argument("--uninstall", action="store_true")+ args = parser.parse_args()+ if not PUBLISHER or not PUBLIC_KEYS:+ raise ValueError("unbound source installer; download install.sh from your publisher's GitHub Release assets")+ if os.getuid() == 0:+ raise ValueError("run as your regular user")+ arch = platform.machine().lower()+ if sys.platform == "darwin" and (arch == "arm64" or run("arch", "-arm64", "/usr/bin/true")):+ target = "macos-arm64"+ elif sys.platform == "linux" and arch in ("x86_64", "aarch64"):+ target = "linux-" + arch+ else:+ raise ValueError("no supported release for this platform")+ binary_dir = (args.prefix / "bin").resolve()+ binary_dir.mkdir(mode=0o755, parents=True, exist_ok=True)+ if binary_dir.stat().st_uid != os.getuid() or binary_dir.stat().st_mode & 0o022:+ raise ValueError("choose a user-owned prefix writable only by this user")+ binary = binary_dir / "iphone-control"+ config = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "iphone-control"+ if not config.is_absolute():+ raise ValueError("XDG_CONFIG_HOME must be absolute")+ config.mkdir(mode=0o700, parents=True, exist_ok=True)+ if config.stat().st_uid != os.getuid() or config.stat().st_mode & 0o022:+ raise ValueError("configuration directory must be writable only by this user")+ receipt = config / "install-receipt.json"+ with (config / "install.lock").open("a+b") as lock:+ fcntl.flock(lock, fcntl.LOCK_EX)+ with transaction_lock(binary_dir):+ if (binary_dir / ".iphone-control-update/transaction.json").exists():+ raise ValueError(f"finish recovery first: {binary_dir}/.iphone-control-update/recovery update recover")+ data = read_receipt(receipt, binary, target)+ if args.uninstall:+ uninstall(binary, config, receipt, data)+ return+ if not data or data["service"] == "none":+ requested = args.version or (data["version"] if data and data["pinned"] else None)+ bootstrap(binary, config, receipt, data, target, requested, args.no_service)+ return+ if args.version and (args.version not in (data["version"], "v" + data["version"]) or not data["pinned"]):+ raise ValueError("managed installation: use the local update CLI to change versions or pinning")+ kind, path = service_files(config)+ if data["service"] != kind:+ raise ValueError("unexpected service in the installation receipt")+ if service_removed(kind, path):+ if args.no_service:+ with disabled_update_job(binary, config):+ data["service"] = "none"+ write_receipt(receipt, data)+ return+ if start_service(binary, config) != kind:+ raise ValueError("could not restore the recorded user service")+ elif not owns_service(path, binary, kind):+ raise ValueError("daemon service no longer matches this installation")+ elif kind == "launchd":+ launchd_loaded(path)+ else:+ systemd_owner(path)+ # The updater acquires the same per-prefix lock.+ subprocess.run([binary, "update", "schedule"], check=True)+ if data["pinned"]:+ print(f"Keeping pinned iphone-control {data['version']}.")+ return+ # `update check` exits non-zero when the release check failed (rate limit, offline: a cached error is kept+ # until its retry time) but still prints the report. The reinstall itself succeeded: keep this version+ report = json.loads(subprocess.run([binary, "update", "check", "--json"], stdout=subprocess.PIPE).stdout)+ if report.get("error_code"):+ print(f"Could not check for a newer release ({report['error_code']}); keeping iphone-control "+ f"{data['version']}. Run `iphone-control update check` later.")+ return+ if report["availability"] in ("current", "ahead"):+ print(report["guidance"])+ return+ if report["availability"] != "available" or report["install_method"] != "managed":+ raise ValueError(report["guidance"])+ subprocess.run([binary, "update", "apply"], check=True)++++if __name__ == "__main__":+ try:+ main()+ except (OSError, ValueError, KeyError, TypeError, tarfile.TarError, EOFError, subprocess.SubprocessError) as err:+ sys.exit(f"Install failed: {err}")diff --git a/packaging/release.py b/packaging/release.pynew file mode 100644index 0000000..d006601--- /dev/null+++ b/packaging/release.py@@ -0,0 +1,114 @@+"""Build the pinned bootstrap installer and sign per-platform GitHub Release metadata."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import subprocess+import tempfile++from installer import digest, verify_manifest+++ROOT = Path(__file__).resolve().parents[1]+SLUG = r"[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9][A-Za-z0-9_.-]*"+NUMBER = r"(?:0|[1-9][0-9]*)"+STABLE = rf"v{NUMBER}\.{NUMBER}\.{NUMBER}"+TARGETS = ("linux-x86_64", "linux-aarch64", "macos-arm64")+++def config():+ repo = os.environ.get("ICTL_UPDATE_PUBLISHER", "")+ keys = os.environ.get("ICTL_UPDATE_PUBLIC_KEYS", "")+ tap = os.environ.get("ICTL_UPDATE_TAP", "")+ if not re.fullmatch(SLUG, repo) or repo != os.environ["GITHUB_REPOSITORY"]:+ raise ValueError("configure ICTL_UPDATE_PUBLISHER to match this repository")+ if not all(re.fullmatch(r"[a-f0-9]{64}", key) for key in keys.split(",")):+ raise ValueError("configure ICTL_UPDATE_PUBLIC_KEYS with pinned Ed25519 public keys")+ if tap and not re.fullmatch(SLUG, tap):+ raise ValueError("ICTL_UPDATE_TAP must name a Homebrew tap (owner/tap)")+ return repo, keys+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="command", required=True)+ sub.add_parser("validate")+ sub.add_parser("installer").add_argument("output", type=Path)+ sub.add_parser("upload").add_argument("files", type=Path, nargs="+")+ for action in ("sign", "sha"):+ cmd = sub.add_parser(action)+ cmd.add_argument("directory", type=Path)+ cmd.add_argument("target", choices=TARGETS)+ args = parser.parse_args()+ repo, keys = config()+ tag = os.environ["GITHUB_REF_NAME"]+ if args.command == "validate":+ cargo = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version=1"], cwd=ROOT))+ version = next(p["version"] for p in cargo["packages"] if p["name"] == "iphone-control")+ if tag != f"v{version}":+ raise ValueError("release tag must match the iphone-control Cargo version")+ return+ if args.command == "upload":+ # Re-running a partial job must never replace already published bytes.+ assets = json.loads(subprocess.check_output(["gh", "release", "view", tag, "--json", "assets"]))["assets"]+ existing = {asset["name"] for asset in assets}+ for file in args.files:+ if file.name in existing:+ with tempfile.TemporaryDirectory() as directory:+ downloaded = Path(directory) / file.name+ subprocess.run(["gh", "release", "download", tag, "--pattern", file.name,+ "--dir", directory], check=True)+ if digest(downloaded) != digest(file):+ raise ValueError(f"existing release asset differs: {file.name}")+ else:+ subprocess.run(["gh", "release", "upload", tag, file], check=True)+ return+ if args.command == "installer":+ code = (ROOT / "packaging/installer.py").read_text()+ code = code.replace('PUBLISHER = ""', f"PUBLISHER = {repo!r}", 1)+ code = code.replace('PUBLIC_KEYS = ""', f"PUBLIC_KEYS = {keys!r}", 1)+ args.output.write_text("#!/bin/sh\nexec python3 - \"$@\" <<'ICTL_INSTALLER'\n" + code + "\nICTL_INSTALLER\n")+ args.output.chmod(0o755)+ return+ if not re.fullmatch(STABLE, tag):+ raise ValueError("only stable release manifests may be signed")+ name = f"iphone-control-{tag}-{args.target}"+ manifest = args.directory / f"{name}.manifest.json"+ if args.command == "sha":+ data = verify_manifest(args.directory, manifest, Path(str(manifest) + ".sig"), repo, keys, tag[1:], args.target)+ print(data["sha256"])+ return+ archive = args.directory / f"{name}.tar.gz"+ size = archive.stat().st_size+ if not 0 < size <= 128 * 1024 * 1024:+ raise ValueError("release archive exceeds client limits")+ compatible = os.environ.get("ICTL_ROLLBACK_COMPATIBLE_TAG") == tag+ rollback_from = None+ if compatible:+ rollback_from = os.environ.get("ICTL_ROLLBACK_FROM_VERSION", "")+ if not re.fullmatch(STABLE, "v" + rollback_from):+ raise ValueError("set ICTL_ROLLBACK_FROM_VERSION to the exact tested source version (X.Y.Z)")+ if tuple(map(int, rollback_from.split("."))) >= tuple(map(int, tag[1:].split("."))):+ raise ValueError("the tested source version must precede the release")+ manifest.write_text(json.dumps(dict(+ schema=1, publisher=repo, version=tag[1:], target=args.target, asset=archive.name,+ sha256=hashlib.sha256(archive.read_bytes()).hexdigest(), size=size,+ unattended=os.environ.get("ICTL_UNATTENDED_TAG") == tag,+ rollback_compatible=compatible, rollback_from=rollback_from,+ ), separators=(",", ":")) + "\n")+ # The signing key is a PKCS#8 PEM from the protected signing environment.+ with tempfile.TemporaryDirectory() as private:+ key = Path(private) / "key.pem"+ key.write_text(os.environ.pop("ICTL_UPDATE_SIGNING_KEY"))+ public = subprocess.check_output(["openssl", "pkey", "-in", key, "-pubout", "-outform", "DER"])+ spki = bytes.fromhex("302a300506032b6570032100")+ if not public.startswith(spki) or public[len(spki):].hex() not in keys.split(","):+ raise ValueError("signing key does not match pinned Ed25519 keys")+ subprocess.run(["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", key,+ "-in", manifest, "-out", str(manifest) + ".sig"], check=True)+++if __name__ == "__main__":+ main()diff --git a/packaging/test_installer.py b/packaging/test_installer.pynew file mode 100644index 0000000..a525a70--- /dev/null+++ b/packaging/test_installer.py@@ -0,0 +1,392 @@+"""Signed offline install fixture. The service manager, HOME, and network are isolated."""+import contextlib+import fcntl+import hashlib+import io+import json+import os+from pathlib import Path+import platform+import plistlib+import subprocess+import sys+import tarfile+import tempfile+import unittest+from unittest.mock import patch++import installer+++ROOT = Path(__file__).resolve().parents[1]+REPO = "example/iphone-control"+VERSION = "0.2.1"+++class InstallerTest(unittest.TestCase):+ def setUp(self):+ self.stack = contextlib.ExitStack()+ self.addCleanup(self.stack.close)+ self.root = Path(self.stack.enter_context(tempfile.TemporaryDirectory())).resolve()+ self.dist = self.root / "dist"+ self.dist.mkdir()+ self.prefix = self.root / "custom prefix"+ self.config = self.root / "config/iphone-control"+ self.receipt = self.config / "install-receipt.json"+ self.binary = self.prefix / "bin/iphone-control"+ commands = self.root / "commands"+ commands.mkdir()+ self.log = self.root / "calls"+ for cmd in ("systemctl", "pgrep", "launchctl"):+ stub = commands / cmd+ stub.write_text('#!/bin/sh\necho "$0 $*" >> "$INSTALL_LOG"\n'+ 'case "$0 $*" in\n'+ ' *"launchctl print "*) echo "Could not find service" >&2; exit 1;;\n'+ ' *" -p LoadState -p ActiveState") echo LoadState=not-found; echo ActiveState=inactive;;\n'+ ' *" --user show iphone-control "*) echo "FragmentPath=$XDG_CONFIG_HOME/systemd/user/iphone-control.service"; echo DropInPaths=;;\n'+ ' *pgrep*|*" --user cat "*) exit 1;;\nesac\n')+ stub.chmod(0o755)+ key = self.root / "private.pem"+ subprocess.run(["openssl", "genpkey", "-algorithm", "Ed25519", "-out", key], check=True)+ pub = subprocess.check_output(["openssl", "pkey", "-in", key, "-pubout", "-outform", "DER"])[-32:].hex()+ self.stack.enter_context(patch.dict(os.environ, {+ "HOME": str(self.root), "XDG_CONFIG_HOME": str(self.config.parent), "INSTALL_LOG": str(self.log),+ "PATH": str(commands) + os.pathsep + os.environ["PATH"],+ "ICTL_UPDATE_PUBLISHER": REPO, "GITHUB_REPOSITORY": REPO, "ICTL_UPDATE_PUBLIC_KEYS": pub,+ "ICTL_UPDATE_TAP": "", "GITHUB_REF_NAME": "v" + VERSION,+ "ICTL_UPDATE_SIGNING_KEY": key.read_text(), "ICTL_UNATTENDED_TAG": "", "ICTL_ROLLBACK_COMPATIBLE_TAG": "",+ }))+ self.stack.enter_context(patch.multiple(installer, PUBLISHER=REPO, PUBLIC_KEYS=pub))+ self.stack.enter_context(patch.object(installer, "download", self.download))+ self.target = "macos-arm64" if sys.platform == "darwin" else "linux-" + platform.machine()+ self.name = f"iphone-control-v{VERSION}-{self.target}"+ self.archive = self.dist / (self.name + ".tar.gz")+ self.manifest = self.dist / (self.name + ".manifest.json")+ self.sig = self.dist / (self.name + ".manifest.json.sig")+ self.make_archive()+ self.sign()++ def make_archive(self, bad=""):+ with tarfile.open(self.archive, "w:gz") as tar:+ exe = (b'#!/bin/sh\nif [ "$1" = --version ]; then echo iphone-control 0.2.1; exit; fi\n'+ b'echo "$*" >> "$INSTALL_LOG"\n'+ b'job="$XDG_CONFIG_HOME/iphone-control/update-job.sh"\n'+ b'case "$*" in "update schedule"|"update policy notify")\n'+ b' printf "#!/bin/sh\\n# iphone-control update job\\nexe=\'%s\'\\n" "$0" > "$job";;\n'+ b' "update policy manual") rm -f "$job";;\nesac\n'+ b'if [ "$*" = "update check --json" ]; then\n'+ b' if [ -n "$FIXTURE_CHECK_ERROR" ]; then\n'+ b' printf \'{"availability":"available","install_method":"managed","error_code":"%s",\' "$FIXTURE_CHECK_ERROR"\n'+ b' printf \'"guidance":"checked"}\\n\'; exit 1\n'+ b' fi\n'+ b' printf \'{"availability":"%s","install_method":"managed","guidance":"checked"}\\n\' '+ b'"${FIXTURE_AVAILABILITY:-available}"\nfi\n')+ for leaf, contents in [("iphone-control", exe), ("env.example", b"# Example\n")]:+ entry = tarfile.TarInfo(f"{self.name}/{leaf}")+ entry.size = len(contents)+ tar.addfile(entry, io.BytesIO(contents))+ if bad:+ entry = tarfile.TarInfo(f"{self.name}/../outside" if bad == "escape" else f"{self.name}/link")+ if bad == "link":+ entry.type = tarfile.SYMTYPE+ entry.linkname = "elsewhere"+ tar.addfile(entry)++ def sign(self):+ subprocess.run([sys.executable, ROOT / "packaging/release.py", "sign", self.dist, self.target], check=True)++ def download(self, url, dest, limit):+ if url == f"https://api.github.com/repos/{REPO}/releases/latest":+ dest.write_text(json.dumps(dict(tag_name="v" + VERSION, draft=False, prerelease=False)))+ return dest.stat().st_size+ self.assertTrue(url.startswith(f"https://github.com/{REPO}/releases/download/v{VERSION}/"))+ with (self.dist / url.rsplit("/", 1)[-1]).open("rb") as src, dest.open("xb") as out:+ return installer.copy_limited(src, out, limit)++ def install(self, *args):+ with patch.object(sys, "argv", ["install.sh", "--prefix", str(self.prefix), *args]):+ installer.main()++ def test_install_and_uninstall(self):+ with contextlib.redirect_stdout(io.StringIO()) as output:+ self.install()+ self.assertIn(f"export PATH='{self.binary.parent}':\"$PATH\"", output.getvalue())+ self.assertEqual(json.loads(self.receipt.read_text()), dict(+ schema=1, publisher=REPO, binary_path=str(self.binary), target=self.target, version=VERSION,+ service=installer.service_files(self.config)[0], pinned=False,+ sha256=hashlib.sha256(self.binary.read_bytes()).hexdigest()))+ self.assertIn("update schedule", self.log.read_text())+ self.install() # upgrades must go through the installed updater+ self.assertIn("update apply", self.log.read_text())+ self.install("--uninstall")+ self.assertFalse(self.binary.exists())+ self.assertFalse(self.receipt.exists())+ self.assertTrue((self.config / "env.example").exists())+ self.assertIn("update policy manual", self.log.read_text())++ def test_service_arguments_are_literal(self):+ binary = self.root / 'custom $(name) " & % path' / "iphone-control"+ launch = plistlib.loads(installer.service_text(binary, "launchd", self.config).encode())+ self.assertEqual(launch["ProgramArguments"], [str(binary), "daemon"])+ self.assertEqual(launch["EnvironmentVariables"]["XDG_CONFIG_HOME"], str(self.config.parent))+ with self.assertRaisesRegex(ValueError, "unsupported character"):+ installer.service_text(binary, "systemd", self.config)+ unit = installer.service_text(self.binary, "systemd", self.config)+ self.assertIn(f'ExecStart="{self.binary}" daemon', unit)+ self.assertIn(f'Environment="XDG_CONFIG_HOME={self.config.parent}"', unit)++ def test_fixed_manual_install(self):+ with patch.dict(os.environ, PATH=str(self.binary.parent) + os.pathsep + os.environ["PATH"]):+ with contextlib.redirect_stdout(io.StringIO()) as output:+ self.install("--version", VERSION, "--no-service")+ self.assertNotIn("export PATH=", output.getvalue())+ data = json.loads(self.receipt.read_text())+ self.assertTrue(data["pinned"])+ self.assertEqual(data["service"], "none")+ self.assertFalse(self.log.exists())+ self.install("--uninstall")++ def test_managed_reinstall_current_ahead_and_pinned(self):+ self.install()+ for status in ("current", "ahead"):+ with patch.dict(os.environ, FIXTURE_AVAILABILITY=status):+ self.install()+ self.assertNotIn("update apply", self.log.read_text())+ self.install("--uninstall")+ self.install("--version", VERSION)+ self.log.write_text("")+ self.install()+ self.assertTrue(json.loads(self.receipt.read_bytes())["pinned"])+ self.assertNotIn("update check", self.log.read_text())+ self.assertNotIn("update apply", self.log.read_text())++ def test_reinstall_keeps_version_when_release_check_fails(self):+ # the CLI exits 1 after printing a report with error_code (cached rate limit, offline)+ self.install()+ self.log.write_text("")+ for code in ("rate_limited", "network"):+ with patch.dict(os.environ, FIXTURE_CHECK_ERROR=code):+ out = io.StringIO()+ with contextlib.redirect_stdout(out):+ self.install()+ self.assertIn(f"Could not check for a newer release ({code})", out.getvalue())+ self.assertIn("update check", self.log.read_text())+ self.assertNotIn("update apply", self.log.read_text())++ def test_removed_daemon_reinstall_and_uninstall(self):+ with patch.dict(os.environ, FIXTURE_AVAILABILITY="current"):+ self.install()+ _, service = installer.service_files(self.config)+ service.unlink()+ self.install()+ self.assertTrue(service.is_file())+ service.unlink()+ self.log.write_text("")+ self.install("--uninstall")+ self.assertFalse(self.receipt.exists())+ self.assertFalse(self.binary.exists())+ self.assertIn("update policy manual", self.log.read_text())+ self.assertNotIn("bootout", self.log.read_text())+ self.assertNotIn("disable --now iphone-control", self.log.read_text())++ def test_replaced_service_is_left_alone(self):+ self.install()+ _, service = installer.service_files(self.config)+ service.unlink()+ other = self.root / "foreign service"+ other.write_text("a different service")+ service.symlink_to(other)+ self.log.write_text("")+ for args in ((), ("--uninstall",)):+ with self.assertRaisesRegex(ValueError, "no longer matches"):+ self.install(*args)+ self.assertEqual(self.log.read_text(), "")+ self.assertTrue(service.is_symlink())+ self.assertTrue(self.binary.is_file())++ def test_manual_daemon_removes_only_its_own_schedule_and_policy(self):+ self.install("--no-service")+ subprocess.run([self.binary, "update", "policy", "notify"], check=True)+ job = self.config / "update-job.sh"+ self.assertTrue(job.exists())+ key = hashlib.sha256(os.fsencode(self.binary)).hexdigest()+ policy = self.config / "updates" / REPO / (key + ".json")+ policy.parent.mkdir(parents=True)+ policy.write_text('"notify"')+ other = policy.parent / "other.json"+ other.write_text('"manual"')+ self.install("--uninstall")+ self.assertFalse(policy.exists())+ self.assertFalse(job.exists())+ self.assertTrue(other.exists())+ self.install("--no-service")+ contents = "#!/bin/sh\n# iphone-control update job\nexe=/other/iphone-control\n"+ job.write_text(contents)+ self.log.write_text("")+ self.install("--uninstall")+ self.assertEqual(job.read_text(), contents)+ self.assertNotIn("update policy manual", self.log.read_text())++ def test_uninstall_serializes_with_schedule_reenable(self):+ self.install()+ _, service = installer.service_files(self.config)+ run = subprocess.run++ def reenable_after_manual(args, **kwargs):+ if args == [self.binary, "update", "policy", "manual"]:+ with (self.config / "update-schedule.lock").open("a+b") as lock:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ result = run(args, **kwargs)+ run([self.binary, "update", "policy", "notify"], check=True)+ return result+ return run(args, **kwargs)++ with patch.object(subprocess, "run", reenable_after_manual):+ with self.assertRaisesRegex(ValueError, "re-enabled"):+ self.install("--uninstall")+ self.assertTrue(installer.owns_update_job(self.binary, self.config))+ self.assertTrue(service.exists() and self.binary.exists() and self.receipt.exists())++ unlink = Path.unlink+ def check_lock_on_delete(path, *args, **kwargs):+ if path in (self.binary, self.receipt):+ with (self.config / "update-schedule.lock").open("rb+") as lock:+ with self.assertRaises(BlockingIOError):+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ return unlink(path, *args, **kwargs)++ with patch.object(Path, "unlink", check_lock_on_delete):+ self.install("--uninstall")+ self.assertFalse(self.binary.exists() or self.receipt.exists() or (self.config / "update-job.sh").exists())++ def test_cli_recreated_service_must_point_to_this_binary(self):+ binary = self.root / "bin/iphone-control"+ path = self.root / "daemon-service"+ script = f'set -a; f="$HOME/.config/iphone-control/env"; [ -f "$f" ] && . "$f"; set +a; exec "{binary}" daemon'+ path.write_bytes(plistlib.dumps(dict(Label=installer.LABEL, ProgramArguments=["/bin/sh", "-c", script])))+ self.assertTrue(installer.owns_service(path, binary, "launchd"))+ self.assertFalse(installer.owns_service(path, self.binary, "launchd"))+ path.write_text(f"# Written by iphone-control. Settings: ~/.config/iphone-control/env\n"+ f"[Service]\nExecStart={binary} daemon\n")+ self.assertTrue(installer.owns_service(path, binary, "systemd"))+ self.assertFalse(installer.owns_service(path, self.binary, "systemd"))++ def test_uninstall_removes_verified_update_files(self):+ self.install()+ receipt = json.loads(self.receipt.read_bytes())+ state = self.binary.parent / ".iphone-control-update"+ state.mkdir(mode=0o700)+ backup = state / "previous"+ backup.write_bytes(b"previous verified executable")+ os.link(backup, state / "recovery")+ old = dict(receipt, sha256=installer.digest(backup), version="0.2.0")+ (state / "previous.json").write_text(json.dumps(dict(before_digest=receipt["sha256"], receipt=old)))+ (state / "outcome.json").write_text(json.dumps(dict(+ status="manual_migration", target_version=VERSION, detail="operator needed",+ suppressed_version=VERSION, migration_source="0.2.0")))+ stage = state / "stage"+ stage.mkdir(mode=0o700)+ (stage / "archive").write_bytes(b"interrupted archive")+ (state / "personal.bak").write_bytes(b"user file")+ other = self.root / "user notes"+ other.write_text("keep")+ (state / "notes").symlink_to(other)+ (state / "swap-link").symlink_to(other)+ self.install("--uninstall")+ self.assertEqual({p.name for p in state.iterdir()}, {"notes", "personal.bak", "swap-link"})+ self.assertEqual(other.read_text(), "keep")++ def test_rollback_source_is_signed_and_precedes_release(self):+ command = [sys.executable, ROOT / "packaging/release.py", "sign", self.dist, self.target]+ with patch.dict(os.environ, ICTL_ROLLBACK_COMPATIBLE_TAG="v" + VERSION):+ for source in ("", VERSION, "0.2.2"):+ with self.subTest(source=source), patch.dict(os.environ, ICTL_ROLLBACK_FROM_VERSION=source):+ self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)+ with patch.dict(os.environ, ICTL_ROLLBACK_FROM_VERSION="0.2.0"):+ self.sign()+ data = installer.verify_manifest(self.root, self.manifest, self.sig, REPO, installer.PUBLIC_KEYS,+ VERSION, self.target)+ self.assertTrue(data["rollback_compatible"])+ self.assertEqual(data["rollback_from"], "0.2.0")++ def test_bad_key_digest_identity_and_tar(self):+ with patch.object(installer, "PUBLIC_KEYS", "11" * 32), self.assertRaisesRegex(ValueError, "verification failed"):+ self.install("--no-service")+ raw = self.archive.read_bytes()+ self.archive.write_bytes(raw[:-2] + b"ab")+ with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"):+ self.install("--no-service")+ self.archive.write_bytes(raw)+ for field, value in (("publisher", "other/repo"), ("target", "wrong"), ("size", 128 * installer.MIB + 1)):+ with self.subTest(field=field):+ self.sign()+ data = json.loads(self.manifest.read_bytes())+ data[field] = value+ self.manifest.write_text(json.dumps(data))+ subprocess.run(["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", self.root / "private.pem",+ "-in", self.manifest, "-out", self.sig], check=True)+ with self.assertRaisesRegex(ValueError, "does not match"):+ self.install("--no-service")+ for bad in ("link", "escape"):+ with self.subTest(bad=bad):+ self.make_archive(bad)+ self.sign()+ with self.assertRaisesRegex(ValueError, "invalid entry"):+ self.install("--no-service")+ self.assertFalse(self.binary.exists())+ self.assertFalse(self.receipt.exists())++ def test_receipt_and_lock_prevent_wrong_install(self):+ self.install("--no-service")+ with self.assertRaisesRegex(ValueError, "matching receipt"):+ self.install("--prefix", str(self.root / "other"), "--uninstall")+ with installer.transaction_lock(self.binary.parent), self.assertRaisesRegex(ValueError, "update is in progress"):+ self.install("--uninstall")+ self.binary.write_bytes(b"foreign binary")+ with self.assertRaisesRegex(ValueError, "does not match"):+ self.install("--uninstall")+ self.assertEqual(self.binary.read_bytes(), b"foreign binary")++ def test_linux_service_fixtures(self):+ for arch in ("aarch64", "x86_64"):+ with self.subTest(arch=arch), patch.object(sys, "platform", "linux"), patch.object(platform, "machine", return_value=arch):+ self.target = "linux-" + arch+ self.name = f"iphone-control-v{VERSION}-{self.target}"+ self.archive = self.dist / (self.name + ".tar.gz")+ self.make_archive()+ self.sign()+ self.install()+ self.assertEqual(json.loads(self.receipt.read_bytes())["target"], self.target)+ self.assertEqual(json.loads(self.receipt.read_bytes())["service"], "systemd")+ self.install("--uninstall")++ def test_generated_and_unbound_bootstrap(self):+ bound = self.dist / "install.sh"+ cmd = [sys.executable, ROOT / "packaging/release.py", "installer", bound]+ subprocess.run(cmd, check=True)+ subprocess.run(["sh", bound, "--help"], stdout=subprocess.DEVNULL, check=True)+ self.assertIn(f"PUBLISHER = {REPO!r}", bound.read_text())+ self.assertNotIn("PRIVATE KEY", bound.read_text())+ # Exercise the generated shell entry point in a child process; substitute only+ # the HTTPS transport. All verification, staging and receipt code runs as shipped.+ module_dir = self.root / "fixture-transport"+ module_dir.mkdir()+ (module_dir / "sitecustomize.py").write_text(+ "from pathlib import Path\nimport urllib.request\n"+ "def fixture(self, url, **kwargs):\n"+ f" assert url.startswith('https://github.com/{REPO}/releases/download/v{VERSION}/')\n"+ f" return (Path({str(self.dist)!r}) / url.rsplit('/', 1)[-1]).open('rb')\n"+ "urllib.request.OpenerDirector.open = fixture\n")+ with patch.dict(os.environ, {"PYTHONPATH": str(module_dir)}):+ subprocess.run(["sh", bound, "--no-service", "--version", VERSION, "--prefix", self.prefix], check=True)+ self.assertEqual(json.loads(self.receipt.read_bytes())["sha256"], installer.digest(self.binary))+ subprocess.run(["sh", bound, "--uninstall", "--prefix", self.prefix], check=True)+ with patch.dict(os.environ, {"GITHUB_REPOSITORY": "other/repo"}):+ self.assertNotEqual(subprocess.run(cmd, capture_output=True).returncode, 0)+ unbound = subprocess.run(["sh", ROOT / "install.sh", "--no-service", "--prefix", self.prefix], capture_output=True)+ self.assertNotEqual(unbound.returncode, 0)+ self.assertFalse(self.binary.exists())+++if __name__ == "__main__":+ unittest.main()diff --git a/website/deploy/macos.md b/website/deploy/macos.mdindex 8ccbba4..a015fc2 100644--- a/website/deploy/macos.md+++ b/website/deploy/macos.md@@ -8,7 +8,7 @@ iphone-control 也能直接跑在 Mac 上:用 macOS 自带的 usbmuxd,不需## 需要-- Apple Silicon 的 Mac:一行命令和 Homebrew 装的是编好的程序,什么都不用另外装。Intel Mac 没有预编译包,要从源码编译(Xcode 命令行工具和 Rust 1.88 以上)。都**不需要**完整的 Xcode+- Apple Silicon 的 Mac。用脚本安装时,PATH 中需要有 Python 3 和 OpenSSL 3。Intel Mac 要从源码编译,需 Xcode 命令行工具和 Rust 1.88 以上。- 一部 iOS 17 以上的 iPhone 或 iPad,用能**传数据**的线连接- 一个免费 Apple ID(建议专门注册一个)@@ -17,10 +17,12 @@ iphone-control 也能直接跑在 Mac 上:用 macOS 自带的 usbmuxd,不需### 一行命令(推荐)```bash-curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh```-它会下载最新版本、校验 sha256,装到 `~/.local/bin/iphone-control`,再装一个 launchd 用户服务(`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`):登录后自动启动守护进程,崩溃后自动重启,读取 `~/.config/iphone-control/env`,日志在 `~/Library/Logs/iphone-control/daemon.log`。可选参数写在 `sh -s --` 后面:`--version v0.2.1`(指定版本)、`--prefix 目录`(装到 `目录/bin`)、`--no-service`(只装程序,不装服务)。+它会下载最新版本,用 Python 3 和 OpenSSL 3 验证发行清单签名和安装包 SHA-256,装到 `~/.local/bin/iphone-control`,再装一个 launchd 用户服务(`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`)。守护进程在登录后自动启动,崩溃后自动重启,读取 `~/.config/iphone-control/env`,日志在 `~/Library/Logs/iphone-control/daemon.log`。给脚本传入 `--version vX.Y.Z` 可指定带 macOS 签名清单的发行版,`--prefix 目录` 可装到 `目录/bin`,`--no-service` 可只装程序。++上游 v0.2.0 的安装和迁移步骤见[旧版脚本说明](../guide/getting-started#legacy-script)。### Homebrew@@ -109,7 +111,7 @@ sudo launchctl kickstart -k system/com.apple.usbmuxd升级前先看[更新日志](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.zh-CN.md)里的升级注意事项。-一行命令安装的:重新运行同一条命令,它会先停服务、换程序、再启动。Homebrew:`brew upgrade iphone-control && brew services restart iphone-control`。从源码编译:+受管脚本安装:关闭 Viewer、MCP 等客户端后,运行 `iphone-control update apply`。Homebrew:`brew upgrade iphone-control && brew services restart iphone-control`。从源码编译:```bashcd iphone-control && git pull@@ -119,7 +121,7 @@ iphone-control service restart## 卸载-一行命令安装的:`curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --uninstall`。Homebrew:`brew services stop iphone-control && brew uninstall iphone-control`。从源码编译的:`iphone-control service uninstall && cargo uninstall iphone-control`。+签名脚本安装的,运行 `sh iphone-control-install.sh --uninstall`,若安装时指定了前缀,传入相同的前缀。v0.2.0 使用[该版本的卸载脚本](../guide/getting-started#legacy-script)。Homebrew:`brew services stop iphone-control && brew uninstall iphone-control`。从源码编译的:`iphone-control service uninstall && cargo uninstall iphone-control`。都会保留数据目录和设置。要彻底删除:diff --git a/website/en/deploy/macos.md b/website/en/deploy/macos.mdindex b38802d..604cdcf 100644--- a/website/en/deploy/macos.md+++ b/website/en/deploy/macos.md@@ -8,7 +8,7 @@ Verified on a MacBook Pro (Apple M3 Pro) / macOS 26.6.2 with an iPhone 15 Pro Ma## You need-- An Apple Silicon Mac: the one command and Homebrew install the built program, nothing else needed. Intel Macs have no prebuilt package and build from source (Xcode Command Line Tools and Rust 1.88+). Full Xcode is **not** needed+- An Apple Silicon Mac. The script installer requires Python 3 and OpenSSL 3 on PATH. Intel Macs have no prebuilt package and build from source (Xcode Command Line Tools and Rust 1.88+). Full Xcode is **not** needed- An iPhone or iPad on iOS 17+, connected with a cable that carries **data**- A free Apple ID (a dedicated one is recommended)@@ -17,10 +17,12 @@ Verified on a MacBook Pro (Apple M3 Pro) / macOS 26.6.2 with an iPhone 15 Pro Ma### One command (recommended)```bash-curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh```-It downloads the latest release, checks its sha256, installs `~/.local/bin/iphone-control` and a launchd user service (`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`) that starts the daemon at login, restarts it after a crash, reads `~/.config/iphone-control/env` and logs to `~/Library/Logs/iphone-control/daemon.log`. Options go after `sh -s --`: `--version v0.2.1`, `--prefix DIR` (installs into `DIR/bin`), `--no-service` (only the binary, no service).+It downloads the latest release, verifies the Ed25519 release manifest and archive SHA-256 (Python 3 and OpenSSL 3 required), installs `~/.local/bin/iphone-control` and a launchd user service (`~/Library/LaunchAgents/io.github.derrors.iphone-control.plist`) that starts the daemon at login, restarts it after a crash, reads `~/.config/iphone-control/env` and logs to `~/Library/Logs/iphone-control/daemon.log`. Pass `--version vX.Y.Z` for a specific release with a signed macOS manifest, `--prefix DIR` to install into `DIR/bin`, or `--no-service` to install only the binary.++For upstream v0.2.0, follow the [legacy installation and migration steps](../guide/getting-started#legacy-script).### Homebrew@@ -109,7 +111,7 @@ sudo launchctl kickstart -k system/com.apple.usbmuxdRead the upgrade notes in the [changelog](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.md) first.-Installed with the one command: run it again; it stops the service, replaces the binary and starts it again. Homebrew: `brew upgrade iphone-control && brew services restart iphone-control`. From source:+For a managed script installation, close active clients and run `iphone-control update apply`. Homebrew: `brew upgrade iphone-control && brew services restart iphone-control`. From source:```bashcd iphone-control && git pull@@ -119,7 +121,7 @@ iphone-control service restart## Uninstall-Installed with the one command: `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh -s -- --uninstall`. Homebrew: `brew services stop iphone-control && brew uninstall iphone-control`. From source: `iphone-control service uninstall && cargo uninstall iphone-control`.+For a signed script installation, run `sh iphone-control-install.sh --uninstall` with your original prefix. For v0.2.0, use the [tagged uninstall script](../guide/getting-started#legacy-script). Homebrew: `brew services stop iphone-control && brew uninstall iphone-control`. From source: `iphone-control service uninstall && cargo uninstall iphone-control`.All of them keep your data and settings. To remove them too:diff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex 7889481..6adc9a1 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -21,6 +21,18 @@ These go before the command, for example `iphone-control --socket /path/ctl.sock| `mcp` | MCP stdio server, started by the AI client || `mcp-config` | Prints the command that registers the MCP server with Claude Code, with a program path that stays the same across upgrades (Homebrew's `opt` link) |+## Host software updates++`iphone-control update check [--json]` and **About & updates** in Viewer share the local release cache. A source build without a publisher makes no network request. A failed check keeps the previous successful result. A red dot on **About & updates** indicates a newer stable release. Open the panel to see its version and copy the command for your installation. For Homebrew, the tap determines when the upgrade is available. For Debian or Ubuntu, download the listed package before running the command.++Viewer listens on loopback. Other users on the same host can see installation information and request a version check. Installation, rollback and policy changes use the local CLI.++A managed per-user service installed by the release script checks in the background by default. Use `update apply` to install from the terminal, `update rollback` for the previous verified executable, or `update recover` after an interrupted replacement. A version selected with `install.sh --version` remains pinned until `update unpin`.++Run `iphone-control update policy auto-patch` to opt in to installing compatible patches when idle. Viewer, MCP and direct device clients (including paused tasks) must exit before the service can restart. If the new daemon fails its health checks the updater restores the old executable and holds the failed version for an explicit retry. `update policy notify` checks without installing; `update policy manual` removes the scheduled job.++If the new executable cannot start, invoke `<prefix>/bin/.iphone-control-update/recovery update recover` directly. For a custom socket, add `--socket <path>` before `update`.+## Background serviceThe daemon runs as a per-user service: launchd on macOS, a systemd user service on Linux. It starts when you log in and restarts after a crash. No root needed.diff --git a/website/en/guide/getting-started.md b/website/en/guide/getting-started.mdindex 6fc699a..859b4cc 100644--- a/website/en/guide/getting-started.md+++ b/website/en/guide/getting-started.md@@ -17,13 +17,13 @@ Don't run two copies of iphone-control, or other usbmuxd-based tools (go-ios, pyPick one of the three. Install as your regular user; don't run `iphone-control` as root or with sudo.-**One command** (macOS, Linux):+**One command** (macOS or Linux, with Python 3 and OpenSSL 3 on PATH)```bash-curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh```-It installs the program into `~/.local/bin` and the daemon as a per-user service (launchd on macOS, a systemd user service on Linux) that starts when you log in. Running it again upgrades. Options go after `sh -s --`: `--version vX.Y.Z` installs that release, `--prefix DIR` installs into `DIR/bin`, `--no-service` installs only the program.+It installs the program into `~/.local/bin` and the daemon as a per-user service (launchd on macOS, a systemd user service on Linux) that starts when you log in. Run `iphone-control update check` for upgrade instructions. Pass `--version vX.Y.Z` for a specific signed release, `--prefix DIR` to install into `DIR/bin`, or `--no-service` to install only the program. For upstream v0.2.0, use the [legacy script instructions](#legacy-script).**Homebrew** (macOS, Linux):@@ -51,6 +51,22 @@ On Linux with ffmpeg installed, the control page's picture is H.264, about 1/15Intel Macs have no prebuilt binary and need a build from source, as does development. See [Build from Source](../deploy/source).+### Upstream v0.2.0 script installation and migration {#legacy-script}++The v0.2.0 release uses archive checksums and has no signed installer asset. To install this version, use its tagged script and specify the same release for the binary.++```sh+curl -fsSLo iphone-control-v0.2.0-install.sh https://raw.githubusercontent.com/Derrors/iphone-control/v0.2.0/install.sh && sh iphone-control-v0.2.0-install.sh --version v0.2.0+```++To migrate an existing v0.2.0 script installation, first confirm the signed release includes `install.sh`, your platform's manifest and its signature. Close Viewer and MCP clients, stop the daemon, then remove the old binary and service with the v0.2.0 script. This keeps your settings and device data.++```sh+curl -fsSLo iphone-control-v0.2.0-install.sh https://raw.githubusercontent.com/Derrors/iphone-control/v0.2.0/install.sh && sh iphone-control-v0.2.0-install.sh --uninstall+```++Then run the [signed installer](#install). If your old installation used `--prefix DIR`, pass the same option to both the uninstall and the new installation.+## 2. Plug in the phone and run iphone-control {#first-run}Plug in the phone with a cable, unlock it, then run in a terminal:@@ -111,7 +127,8 @@ Something wrong? See the [FAQ](../troubleshoot/faq).| Installed with | Uninstall ||---|---|-| One command | `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh \| sh -s -- --uninstall` |+| Signed installer | Run `sh iphone-control-install.sh --uninstall` using the script downloaded above and your original prefix |+| v0.2.0 script | Use the [v0.2.0 uninstall command](#legacy-script) || Homebrew | `brew services stop iphone-control`, then `brew uninstall iphone-control` || .deb | `systemctl --user disable --now iphone-control`, then `sudo apt remove iphone-control` |diff --git a/website/guide/cli.md b/website/guide/cli.mdindex 1f6f9b2..aa42e45 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -21,6 +21,18 @@| `mcp` | MCP stdio 服务,由 AI 客户端拉起 || `mcp-config` | 打印把 MCP 注册到 Claude Code 的命令。程序路径用升级后不变的那个(Homebrew 用 `opt` 下的链接) |+## 主机软件更新++`iphone-control update check [--json]` 和 Viewer 的「关于与更新」读取同一份本地缓存。未绑定发布者的源码构建不会联网;网络检查失败会保留上次成功的结果。有更新时,「关于与更新」按钮会显示红点,打开即可查看版本号,复制适合当前安装方式的升级命令。Homebrew 以对应 tap 提供的版本为准。Debian 或 Ubuntu 用户先下载面板指定的安装包,再运行命令。++Viewer 只监听本机回环地址。同机其他用户也能查看安装信息、触发版本检查。安装、回滚和更改策略都通过本机 CLI 执行。++由发行版安装脚本部署的受管用户服务默认只做后台检查。本机运行 `update apply` 安装,`update rollback` 恢复上一份已验证的程序。替换意外中断时可运行 `update recover`。用安装器 `--version` 固定的版本需先 `update unpin`。++主动运行 `iphone-control update policy auto-patch` 后,服务只在空闲时自动安装兼容补丁。请退出 Viewer、MCP 和直连设备的客户端;暂停的任务也视为占用。新 daemon 健康检查失败会恢复旧程序,失败版本须手动重试。`update policy notify` 改回仅检查,`update policy manual` 移除定时任务。++如果新程序无法启动,直接用安装目录中的备份:`<prefix>/bin/.iphone-control-update/recovery update recover`。自定义 socket 时,在 `update` 之前加 `--socket <路径>`。+## 后台服务守护进程装成用户服务:macOS 是 launchd,Linux 是 systemd 用户服务。登录后自动启动,崩溃后自动重启。不用 root。diff --git a/website/guide/getting-started.md b/website/guide/getting-started.mdindex 8e5418c..b62df26 100644--- a/website/guide/getting-started.md+++ b/website/guide/getting-started.md@@ -17,13 +17,13 @@三种方式任选一种,都以普通用户安装,不要用 root 或 sudo 运行 `iphone-control`。-**一行命令**(macOS、Linux):+**一行命令**(macOS 或 Linux,需在 PATH 中提供 Python 3 和 OpenSSL 3)```bash-curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh | sh+curl -fsSLo iphone-control-install.sh https://github.com/Derrors/iphone-control/releases/latest/download/install.sh && sh iphone-control-install.sh```-程序装到 `~/.local/bin`,守护进程装成用户服务(macOS 是 launchd,Linux 是 systemd 用户服务),登录后自动启动。再运行一次就是升级。可以在 `sh` 后面加 `-s --` 再跟选项:`--version vX.Y.Z` 装指定版本,`--prefix DIR` 装到 `DIR/bin`,`--no-service` 只装程序、不装服务。+程序装到 `~/.local/bin`,守护进程装成用户服务(macOS 用 launchd,Linux 用 systemd),登录后自动启动。运行 `iphone-control update check` 查看升级指引。给脚本传入 `--version vX.Y.Z` 可装指定的签名版本,`--prefix DIR` 可装到 `DIR/bin`,`--no-service` 可只装程序。上游 v0.2.0 请按[旧版脚本说明](#legacy-script)操作。**Homebrew**(macOS、Linux):@@ -51,6 +51,22 @@ Linux 上装了 ffmpeg,控制台的画面改用 H.264,流量约为原来的Intel Mac 没有预编译版本,要从源码编译;参与开发也从源码运行。见[从源码编译](../deploy/source)。+### 上游 v0.2.0 脚本安装与迁移 {#legacy-script}++v0.2.0 使用安装包校验和,发行附件中没有签名安装器。要安装该版本,请下载 v0.2.0 标签里的脚本,并指定同一版本的程序。++```sh+curl -fsSLo iphone-control-v0.2.0-install.sh https://raw.githubusercontent.com/Derrors/iphone-control/v0.2.0/install.sh && sh iphone-control-v0.2.0-install.sh --version v0.2.0+```++要迁移已有的 v0.2.0 脚本安装,先确认新发行版已提供 `install.sh`、当前平台的清单及其签名。退出 Viewer 和 MCP 客户端,停止守护进程,再用 v0.2.0 的脚本卸载旧程序和服务。设置和设备数据会保留。++```sh+curl -fsSLo iphone-control-v0.2.0-install.sh https://raw.githubusercontent.com/Derrors/iphone-control/v0.2.0/install.sh && sh iphone-control-v0.2.0-install.sh --uninstall+```++然后运行上面的[签名安装器](#install)。如果旧版本装在自定义前缀,卸载和重新安装时都要传入原来的 `--prefix DIR`。+## 2. 接上手机,运行 iphone-control {#first-run}用数据线接上手机并解锁,然后在终端里运行:@@ -111,7 +127,8 @@ iphone-control doctor # 逐层诊断,每项失败都给出修复办法| 安装方式 | 卸载 ||---|---|-| 一行命令 | `curl -fsSL https://raw.githubusercontent.com/Derrors/iphone-control/main/install.sh \| sh -s -- --uninstall` |+| 签名安装器 | 用上面下载的脚本运行 `sh iphone-control-install.sh --uninstall`,若安装时指定了前缀,传入相同的前缀 |+| v0.2.0 脚本 | 运行 [v0.2.0 卸载命令](#legacy-script) || Homebrew | `brew services stop iphone-control`,再 `brew uninstall iphone-control` || deb 包 | `systemctl --user disable --now iphone-control`,再 `sudo apt remove iphone-control` |