Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

feat(update): signed Debian packages, confirm before installing, remove rollback (#52)

Qinghe Lid714784d7f28
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3f52f8d..e06a236 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -201,22 +201,24 @@ jobs:
pattern: bin-*
path: built
merge-multiple: true
- - name: Download Linux archives and generate the pinned installer
+ - name: Download Linux archives and packages, 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
+ gh release download "$GITHUB_REF_NAME" --pattern '*-linux-*.tar.gz' --pattern 'iphone-control_*.deb' --dir dist
+ test "$(ls dist/*.tar.gz dist/*.deb | wc -l)" -eq 4
+ for asset in dist/*.tar.gz dist/*.deb; do cmp "built/${asset##*/}" "$asset"; done
python3 packaging/release.py installer dist/install.sh
+ # `iphone-control update` installs the .deb as root through APT only after checking its signed manifest
- 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
+ for target in linux-x86_64 linux-aarch64; do
+ python3 packaging/release.py sign dist "$target"
+ python3 packaging/release.py sign-deb dist "$target"
+ done
- name: Publish signed Linux manifests and installer
env:
GH_TOKEN: ${{ github.token }}
@@ -247,8 +249,6 @@ jobs:
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:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16a697e..02cc8f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,13 @@ All notable changes to this project are documented here. The format is based on
### Added
- Run `iphone-control update` to check for a new stable release and install it through your managed service, Homebrew or Debian package. It reports when you already have the latest version. `update check` remains available for a check only.
+- `iphone-control update` says what it will do and asks before installing; `--yes` skips the question. After a Homebrew or Debian upgrade a running background service is restarted on the new version.
+- The Debian packages are signed by the publisher too; `iphone-control update` checks the signature before handing the package to APT through sudo. A package on hold in APT is reported with how to release it.
+
+### Removed
+
+- `iphone-control update rollback` and the previous executable kept after an upgrade. A new version that doesn't start is still replaced by the old one automatically.
+- The rollback compatibility mark in release manifests: any newer signed stable release can be installed directly, without stopping at "manual migration required".
## [0.2.2] - 2026-11-12
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index db128e3..8b91a58 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -9,6 +9,13 @@
### 新增
- 运行 `iphone-control update` 可检查并通过受管服务、Homebrew 或 Debian 软件包升级到新稳定版。已是最新时会直接提示。只想检查可继续用 `update check`。
+- `iphone-control update` 安装前先说明要做什么并询问,`--yes` 跳过询问。Homebrew 和 Debian 升级后,正在运行的后台服务会自动重启到新版本。
+- Debian 软件包也有发布者签名,`iphone-control update` 验证签名后才用 sudo 交给 APT 安装。APT 里锁定(hold)的包会提示先解除锁定。
+
+### 移除
+
+- `iphone-control update rollback` 和升级后保留的上一版程序。新版本起不来时仍会自动换回旧版本。
+- 发布清单里的回滚兼容标记:任何更新的签名稳定版都能直接升级,不再因“需要手动迁移”而停下。
## [0.2.2] - 2026-11-12
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index aa3935b..2edf7b4 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -42,6 +42,8 @@ struct Cli {
enum Command {
#[command(about = ictl_l10n::tr!("检查主机软件版本,有新版时升级", "Check for a new host software release and install it if available"))]
Update {
+ #[arg(short, long, help = ictl_l10n::tr!("不询问,直接升级(脚本里或没有终端时用)", "Upgrade without asking (for scripts, or without a terminal)"))]
+ yes: bool,
#[command(subcommand)]
action: Option<UpdateAction>,
},
@@ -122,12 +124,10 @@ enum UpdateAction {
},
/// Save the local update policy and configure its user job
Policy { policy: update::Policy },
- /// Install a verified compatible release (managed user service only)
+ /// Install a verified release without asking (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)]
@@ -200,8 +200,8 @@ async fn run() -> anyhow::Result<()> {
};
let Some(command) = cli.command.take() else { return guide::first_run(&cli).await };
match command {
- Command::Update { action: None } => update::upgrade(&cli.socket, update::check(false).await?).await,
- Command::Update { action: Some(action) } => update_command(action, &cli.socket).await,
+ Command::Update { action: None, yes } => update::upgrade(&cli.socket, update::check(false).await?, yes).await,
+ Command::Update { action: Some(action), .. } => update_command(action, &cli.socket).await,
Command::Daemon => {
let mut cfg = ictl_daemon::Config::from_env(&cli.data_dir);
cfg.socket = cli.socket;
@@ -259,7 +259,6 @@ async fn update_command(action: UpdateAction, socket: &Path) -> anyhow::Result<(
UpdateAction::Schedule => schedule::configure(socket),
UpdateAction::Apply => transaction::apply(socket, false, update::check(false).await?).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?;
@@ -1066,11 +1065,16 @@ mod tests {
use clap::Parser;
let parse = |args: &[&str]| Cli::try_parse_from(args).unwrap().command;
- assert!(matches!(parse(&["iphone-control", "update"]), Some(Command::Update { action: None })));
+ assert!(matches!(parse(&["iphone-control", "update"]), Some(Command::Update { action: None, yes: false })));
+ assert!(matches!(
+ parse(&["iphone-control", "update", "-y"]),
+ Some(Command::Update { action: None, yes: true })
+ ));
assert!(matches!(
parse(&["iphone-control", "update", "check", "--json"]),
- Some(Command::Update { action: Some(UpdateAction::Check { json: true }) })
+ Some(Command::Update { action: Some(UpdateAction::Check { json: true }), .. })
));
+ assert!(Cli::try_parse_from(["iphone-control", "update", "rollback"]).is_err(), "rollback was removed");
}
/// 英文时注册命令带上语言(MCP 客户端不带用户 shell 的环境);中文时不带
diff --git a/apps/iphone-control/src/update.rs b/apps/iphone-control/src/update.rs
index 914b061..5a7cdf8 100644
--- a/apps/iphone-control/src/update.rs
+++ b/apps/iphone-control/src/update.rs
@@ -241,13 +241,14 @@ fn availability_with(
return BrewCheck;
}
if method == InstallMethod::Debian {
- return match deb_asset(&version.to_string(), platform) {
- Some(asset) if latest.assets.contains(&asset) && latest.assets.contains(&format!("{asset}.sha256")) => {
- Available
- }
- Some(_) => PlatformPending,
- None => Unsupported,
- };
+ // APT runs the package's scripts as root: only a package the publisher signed (`<deb>.manifest.json` and
+ // its signature) is installed by `iphone-control update`
+ let Some(asset) = deb_asset(&version.to_string(), platform) else { return Unsupported };
+ if !keys {
+ return ManualOnly;
+ }
+ let signed = [asset.clone(), format!("{asset}.manifest.json"), format!("{asset}.manifest.json.sig")];
+ return if signed.iter().all(|a| latest.assets.contains(a)) { Available } else { PlatformPending };
}
let base = format!("iphone-control-{}-{platform}", latest.tag);
if !latest.assets.contains(&format!("{base}.tar.gz")) {
@@ -280,6 +281,9 @@ fn upgrade_command(status: Availability, installation: &Installation, exe: Optio
(Availability::Available, InstallMethod::Managed) if installation.pinned == Some(true) => {
Some(format!("{exe} update unpin && {exe} update"))
}
+ (Availability::Available, InstallMethod::Debian) if installation.pinned == Some(true) => {
+ Some(format!("sudo apt-mark unhold iphone-control && {exe} update"))
+ }
(Availability::Available, InstallMethod::Managed | InstallMethod::Debian)
| (Availability::BrewCheck, InstallMethod::Homebrew) => Some(format!("{exe} update")),
_ => None,
@@ -319,18 +323,22 @@ fn guidance(status: Availability, method: InstallMethod, pinned: Option<bool>) -
}
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."
+ "安装已固定到指定版本。此命令会解除固定并升级。先退出 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 publisher's signature before installing and restores the old version if the new one doesn't start."
)
.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."
+ "先退出 Viewer 和 MCP 客户端,等待任务完成,再在主机终端运行升级命令。安装前会验证发布者签名;新版本起不来时自动恢复旧版本。",
+ "Close Viewer and MCP clients and let tasks finish before running the upgrade command in a host terminal. It verifies the publisher's signature before installing and restores the old version if the new one doesn't start."
)
.into(),
+ InstallMethod::Debian if pinned == Some(true) => tr!(
+ "iphone-control 在 APT 里被锁定(apt-mark hold),不会升级。要升级,先解除锁定,命令会接着下载经发布者签名的 .deb 并通过 APT 安装。",
+ "iphone-control is on hold in APT (apt-mark hold) and won't be upgraded. To upgrade, release the hold; the command then downloads the publisher-signed .deb and installs it with APT."
+ ).into(),
InstallMethod::Debian => tr!(
- "升级命令会下载并校验匹配本机架构的 .deb,再通过 APT 安装。",
- "The update command downloads and verifies the .deb for this architecture, then installs it with APT."
+ "升级命令会下载匹配本机架构、经发布者签名的 .deb,验证后通过 APT 安装(需要 sudo)。",
+ "The update command downloads the publisher-signed .deb for this architecture, verifies it and installs it with APT (needs sudo)."
).into(),
_ => tr!(
"关闭正在运行的客户端和服务,再按发行说明手动更新。",
@@ -341,24 +349,6 @@ fn guidance(status: Availability, method: InstallMethod, pinned: Option<bool>) -
}
}
-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>,
@@ -391,16 +381,7 @@ impl Local {
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, self.install.pinned))
- };
+ let mut guidance = guidance(status, self.install.method, self.install.pinned);
let command = if self.source_command.is_some() {
guidance = tr!(
"Cargo 源码安装。先在命令所指的本机源码仓库检出目标版本,再运行命令重新安装。完成后重新打开 Viewer,如有后台服务也请重启。",
@@ -474,30 +455,44 @@ pub async fn check(background: bool) -> Result<Report> {
local.report(cache)
}
-/// The user explicitly requested an update. Use this check's release and installation channel.
-pub async fn upgrade(socket: &Path, report: Report) -> Result<()> {
+/// The user explicitly requested an update (`iphone-control update`). Use this check's release and installation
+/// channel; say what will happen and ask before installing, unless `yes`
+pub async fn upgrade(socket: &Path, report: Report, yes: bool) -> Result<()> {
if let Some(code) = &report.error_code {
bail!("{}", trf!("检查更新失败:{code}", "Update check failed: {code}"));
}
+ let pinned = report.pinned == Some(true);
match (report.availability, report.install_method) {
(Availability::Current | Availability::Ahead, _) => {
println!("{} ({})", report.guidance, report.installed_version.as_deref().unwrap_or(VERSION));
}
+ (Availability::Available, InstallMethod::Managed) if pinned => bail!(
+ "{}",
+ tr!(
+ "已固定安装版本。若要升级,请先运行 iphone-control update unpin。",
+ "This installation is pinned. To upgrade, run iphone-control update unpin first."
+ )
+ ),
+ (Availability::Available, InstallMethod::Debian) if pinned => bail!(
+ "{}",
+ tr!(
+ "iphone-control 在 APT 里被锁定。若要升级,请先运行 sudo apt-mark unhold iphone-control。",
+ "iphone-control is on hold in APT. To upgrade, run sudo apt-mark unhold iphone-control first."
+ )
+ ),
(Availability::Available, InstallMethod::Managed) => {
- ensure!(
- report.pinned != Some(true),
- "{}",
- tr!(
- "已固定安装版本。若要升级,请先运行 iphone-control update unpin。",
- "This installation is pinned. To upgrade, run iphone-control update unpin first."
- )
- );
+ if !confirm(&report, yes)? {
+ return Ok(());
+ }
let version = report.available_version.clone().ok_or_else(|| anyhow::anyhow!("missing release version"))?;
transaction::apply(socket, false, report).await?;
println!("{}", trf!("已升级到 {version}。", "Updated to {version}."));
}
(Availability::Available, InstallMethod::Debian) | (Availability::BrewCheck, InstallMethod::Homebrew) => {
- channel::apply(&report).await?;
+ if !confirm(&report, yes)? {
+ return Ok(());
+ }
+ channel::apply(socket, &report).await?;
}
_ => {
let next = report.upgrade_command.as_deref().or(report.release_url.as_deref());
@@ -510,6 +505,55 @@ pub async fn upgrade(socket: &Path, report: Report) -> Result<()> {
Ok(())
}
+/// What installing `report`'s release will do, the same for every caller
+fn plan(report: &Report) -> String {
+ let from = report.installed_version.as_deref().unwrap_or(VERSION);
+ let to = report.available_version.as_deref().unwrap_or("?");
+ let how = match report.install_method {
+ InstallMethod::Managed => trf!(
+ "验证发布者签名后安装,然后重启后台服务:正在执行的 AI 任务和控制台画面会中断。新版本起不来时自动换回 {from}。",
+ "It verifies the publisher's signature, installs, then restarts the background service: running AI tasks and the control page's picture are interrupted. If the new version doesn't start, {from} is put back."
+ ),
+ InstallMethod::Debian => tr!(
+ "下载并验证经发布者签名的 .deb,用 sudo 通过 APT 安装(会询问密码)。后台服务在运行的话会重启,正在执行的任务会中断。",
+ "It downloads and verifies the publisher-signed .deb and installs it with APT through sudo (asks for your password). A running background service is restarted, interrupting running tasks."
+ )
+ .into(),
+ _ => tr!(
+ "运行 brew update 和 brew upgrade。Homebrew 的后台服务在运行的话会重启,正在执行的任务会中断。",
+ "It runs brew update and brew upgrade. A running Homebrew service is restarted, interrupting running tasks."
+ )
+ .into(),
+ };
+ trf!("将从 {from} 升级到 {to}。{how}", "Upgrading from {from} to {to}. {how}")
+}
+
+/// Shows [`plan`] and asks. False: the user said no. Without a terminal it needs `yes`
+fn confirm(report: &Report, yes: bool) -> Result<bool> {
+ use std::io::{BufRead, IsTerminal, Write};
+ println!("{}", plan(report));
+ if yes {
+ return Ok(true);
+ }
+ ensure!(
+ std::io::stdin().is_terminal(),
+ "{}",
+ tr!(
+ "没有终端,无法确认。在终端里运行,或加 --yes 直接升级。",
+ "No terminal to confirm in. Run it in a terminal, or add --yes to upgrade without asking."
+ )
+ );
+ print!("{}", tr!("继续吗?[y/N] ", "Continue? [y/N] "));
+ std::io::stdout().flush()?;
+ let mut answer = String::new();
+ std::io::stdin().lock().read_line(&mut answer)?;
+ if matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes" | "是") {
+ return Ok(true);
+ }
+ println!("{}", tr!("已取消,没有升级。", "Cancelled; nothing was upgraded."));
+ Ok(false)
+}
+
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let unknown = tr!("未知", "unknown");
@@ -586,35 +630,12 @@ impl fmt::Display for Report {
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(pinned));
- assert!(guide.contains("signature") && guide.contains("rollback compatibility"), "{guide}");
+ assert!(guide.contains("signature") && guide.contains("restores the old version"), "{guide}");
}
});
}
@@ -694,16 +715,16 @@ mod tests {
let socket = Path::new("/unused");
// Current or newer local versions succeed even when pinned and without an installer or daemon.
for version in ["1.2.3", "1.2.4"] {
- upgrade(socket, report(version, None, true)).await.unwrap();
+ upgrade(socket, report(version, None, true), false).await.unwrap();
}
// A cached version from an unsuccessful refresh cannot authorize any installation.
let mut stale = report("1.2.2", Some("rate_limited"), false);
stale.availability = Availability::Available;
- let err = upgrade(socket, stale).await.unwrap_err();
+ let err = upgrade(socket, stale, true).await.unwrap_err();
assert!(err.to_string().contains("rate_limited"), "{err}");
let mut pinned = report("1.2.2", None, true);
pinned.availability = Availability::Available;
- let err = upgrade(socket, pinned).await.unwrap_err();
+ let err = upgrade(socket, pinned, true).await.unwrap_err();
assert!(err.to_string().contains("update unpin"), "{err}");
}
@@ -762,31 +783,58 @@ mod tests {
assets: vec![
"iphone-control-v0.2.1-linux-x86_64.tar.gz".into(),
"iphone-control_0.2.1_amd64.deb".into(),
- "iphone-control_0.2.1_amd64.deb.sha256".into(),
+ "iphone-control_0.2.1_amd64.deb.manifest.json".into(),
+ "iphone-control_0.2.1_amd64.deb.manifest.json.sig".into(),
],
notes: None,
};
- let for_install = |running, method, platform| availability(running, method, platform, Some(&release));
+ let for_install =
+ |running, method, platform| availability_with(running, method, platform, Some(&release), true);
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::Managed, Some("linux-x86_64")), Availability::PlatformPending);
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);
}
+ /// APT installs as root: the .deb is offered only once the publisher has signed it, its own manifest (not
+ /// the other architecture's, not a bare checksum file) with the signature; a build without keys can't verify
#[test]
- fn deb_upgrade_waits_for_the_matching_checksum_sidecar() {
+ fn deb_upgrade_waits_for_its_signed_manifest() {
let asset = "iphone-control_0.2.1_amd64.deb";
- let mut release = Release { tag: "v0.2.1".into(), assets: vec![asset.into()], published_at: None, notes: None };
- let status = |r: &Release| availability("0.2.0", InstallMethod::Debian, Some("linux-x86_64"), Some(r));
- assert_eq!(status(&release), Availability::PlatformPending);
- release.assets.push("iphone-control_0.2.1_arm64.deb.sha256".into());
- assert_eq!(status(&release), Availability::PlatformPending);
- release.assets.push(format!("{asset}.sha256"));
- assert_eq!(status(&release), Availability::Available);
+ let mut release = Release {
+ tag: "v0.2.1".into(),
+ assets: vec![asset.into(), format!("{asset}.sha256")],
+ published_at: None,
+ notes: None,
+ };
+ let status =
+ |r: &Release, keys| availability_with("0.2.0", InstallMethod::Debian, Some("linux-x86_64"), Some(r), keys);
+ assert_eq!(status(&release, true), Availability::PlatformPending, "a checksum file is no signature");
+ release.assets.push("iphone-control_0.2.1_arm64.deb.manifest.json".into());
+ release.assets.push("iphone-control_0.2.1_arm64.deb.manifest.json.sig".into());
+ release.assets.push(format!("{asset}.manifest.json"));
+ assert_eq!(status(&release, true), Availability::PlatformPending, "signature still missing");
+ release.assets.push(format!("{asset}.manifest.json.sig"));
+ assert_eq!(status(&release, true), Availability::Available);
+ assert_eq!(status(&release, false), Availability::ManualOnly, "no signing keys in this build");
+ }
+
+ #[test]
+ fn a_held_deb_is_reported_like_a_pinned_installation() {
+ let exe = Path::new("/usr/bin/iphone-control");
+ let held = Installation { method: InstallMethod::Debian, version: Some("0.2.0".into()), pinned: Some(true) };
+ assert_eq!(
+ upgrade_command(Availability::Available, &held, Some(exe)).as_deref(),
+ Some("sudo apt-mark unhold iphone-control && /usr/bin/iphone-control update")
+ );
+ ictl_l10n::with_lang(ictl_l10n::Lang::En, || {
+ assert!(guidance(Availability::Available, InstallMethod::Debian, Some(true)).contains("on hold"));
+ assert!(guidance(Availability::Available, InstallMethod::Debian, Some(false)).contains("signed"));
+ });
}
/// A managed install with signing keys: the archive alone (the signing job hasn't published the manifest and
diff --git a/apps/iphone-control/src/update/archive.rs b/apps/iphone-control/src/update/archive.rs
index 8a52d5c..a7ed252 100644
--- a/apps/iphone-control/src/update/archive.rs
+++ b/apps/iphone-control/src/update/archive.rs
@@ -1,5 +1,7 @@
//! The release metadata and signature are deliberately separate: verify the exact response bytes
-//! with an embedded key before parsing any download instructions.
+//! with an embedded key before parsing any download instructions. The same signed manifest covers the managed
+//! archive (`iphone-control-vX.Y.Z-<target>.tar.gz`) and, on Linux, the Debian package
+//! (`iphone-control_X.Y.Z_<arch>.deb`), each in its own `<asset>.manifest.json` beside it.
use std::fs::File;
use std::io::{Read, Write};
use std::os::unix::fs::PermissionsExt;
@@ -15,33 +17,23 @@ const MAX_ARCHIVE: u64 = 128 << 20;
const MAX_EXPANDED: u64 = 256 << 20;
const MAX_MANIFEST: u64 = 16 << 10;
+/// A signed release manifest. Manifests for 0.2.2's updater also carry `rollback_compatible` and `rollback_from`,
+/// which this version ignores (see `packaging/release.py`)
#[derive(Debug, Deserialize)]
-struct Manifest {
+pub(super) struct Manifest {
schema: u32,
publisher: String,
version: String,
target: String,
- asset: String,
- sha256: String,
- size: u64,
+ pub asset: String,
+ pub sha256: String,
+ pub size: u64,
+ #[serde(default)]
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
+/// with `iphone-control update`, not a failure
#[derive(Debug)]
pub(super) struct NeedsOperator(pub String);
@@ -104,6 +96,33 @@ fn key_bytes(key: &str) -> Option<[u8; 32]> {
Some(decoded)
}
+/// The release signing keys this build trusts (`ICTL_UPDATE_PUBLIC_KEYS`)
+pub(super) fn keys() -> anyhow::Result<&'static str> {
+ option_env!("ICTL_UPDATE_PUBLIC_KEYS").filter(|s| !s.is_empty()).context("this build has no update trust key")
+}
+
+/// Downloads `<asset>.manifest.json` and its signature from release `version` of `publisher` and checks both
+/// against the trusted keys and this exact asset
+pub(super) async fn signed_manifest(
+ client: &Client,
+ publisher: &str,
+ target: &str,
+ version: &str,
+ asset: &str,
+) -> anyhow::Result<Manifest> {
+ let url = format!("https://github.com/{publisher}/releases/download/v{version}/{asset}.manifest.json");
+ let mut raw = Vec::new();
+ let mut sig = Vec::new();
+ download(client, &url, MAX_MANIFEST, &mut raw).await?;
+ download(client, &format!("{url}.sig"), 64, &mut sig).await?;
+ verify(&raw, &sig, keys()?, publisher, target, version, asset)
+}
+
+/// The tar archive's name for a release and target
+pub(super) fn archive_asset(version: &str, target: &str) -> String {
+ format!("iphone-control-v{version}-{target}.tar.gz")
+}
+
fn verify(
raw: &[u8],
sig: &[u8],
@@ -111,7 +130,7 @@ fn verify(
publisher: &str,
target: &str,
version: &str,
- installed_version: &str,
+ asset: &str,
) -> anyhow::Result<Manifest> {
ensure!(
keys.split(',').filter_map(key_bytes).any(|key| UnparsedPublicKey::new(&ED25519, key).verify(raw, sig).is_ok()),
@@ -119,11 +138,7 @@ fn verify(
);
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"),
+ m.schema == 1 && m.publisher == publisher && m.target == target && m.version == version && m.asset == asset,
"manifest does not match this release"
);
ensure!(
@@ -132,9 +147,6 @@ fn verify(
&& 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)
}
@@ -188,17 +200,10 @@ pub(super) async fn stage(
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)?;
+ let asset = archive_asset(version, &receipt.target);
+ let m = signed_manifest(&client, &receipt.publisher, &receipt.target, version, &asset).await?;
+ let base = format!("https://github.com/{}/releases/download/v{version}", receipt.publisher);
if automatic && !m.unattended {
return Err(NeedsOperator(version.to_string()).into());
}
@@ -260,11 +265,12 @@ mod tests {
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"});
+ "unattended":true});
let key = key();
let trusted = hex(&key);
+ let asset = archive_asset("0.2.1", "macos-arm64");
let check = |doc: &[u8], sig: &[u8], keys: &str| {
- verify(doc, sig, keys, "example/update", "macos-arm64", "0.2.1", "0.2.0")
+ verify(doc, sig, keys, "example/update", "macos-arm64", "0.2.1", &asset)
};
let bytes = serde_json::to_vec(&doc).unwrap();
let sig = key.sign(&bytes);
@@ -281,20 +287,24 @@ mod tests {
("target", json!("linux-aarch64")),
("size", json!(MAX_ARCHIVE + 1)),
("publisher", json!("elsewhere/other")),
- ("rollback_compatible", json!(false)),
- ("rollback_from", json!("0.1.9")),
+ ("version", json!("0.2.2")),
("asset", json!("other.tar.gz")),
+ ("asset", json!("iphone-control_0.2.1_arm64.deb")),
] {
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"));
+ assert!(check(&bad, key.sign(&bad).as_ref(), &trusted).is_err(), "{field}");
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>()));
+ // a manifest written for 0.2.2's updater as well: its rollback fields don't matter any more, from any
+ // installed version
+ for (compatible, from) in [(json!(true), json!("0.2.0")), (json!(false), json!(null))] {
+ doc["rollback_compatible"] = compatible;
+ doc["rollback_from"] = from;
+ let legacy = serde_json::to_vec(&doc).unwrap();
+ check(&legacy, key.sign(&legacy).as_ref(), &trusted).unwrap();
+ }
std::fs::write(file, vec![0; m.size as usize]).unwrap();
assert!(unpack(&m, root.path()).is_err());
}
@@ -325,4 +335,22 @@ mod tests {
assert!(!trusted(&Url::parse(url).unwrap()));
}
}
+
+ /// The Debian package's manifest is bound to the .deb's name: a tar manifest of the same release or the other
+ /// architecture's doesn't pass for it
+ #[test]
+ fn deb_manifest_is_bound_to_its_package() {
+ let key = key();
+ let trusted = hex(&key);
+ let deb = "iphone-control_0.2.3_amd64.deb";
+ let doc = json!({"schema":1,"publisher":"example/update","target":"linux-x86_64","version":"0.2.3",
+ "asset":deb,"sha256":"ab".repeat(32),"size":4096,"unattended":false});
+ let bytes = serde_json::to_vec(&doc).unwrap();
+ let sig = key.sign(&bytes);
+ let m = verify(&bytes, sig.as_ref(), &trusted, "example/update", "linux-x86_64", "0.2.3", deb).unwrap();
+ assert_eq!((m.asset.as_str(), m.size), (deb, 4096));
+ for asset in [archive_asset("0.2.3", "linux-x86_64"), "iphone-control_0.2.3_arm64.deb".into()] {
+ assert!(verify(&bytes, sig.as_ref(), &trusted, "example/update", "linux-x86_64", "0.2.3", &asset).is_err());
+ }
+ }
}
diff --git a/apps/iphone-control/src/update/channel.rs b/apps/iphone-control/src/update/channel.rs
index 3f078a2..2afc93e 100644
--- a/apps/iphone-control/src/update/channel.rs
+++ b/apps/iphone-control/src/update/channel.rs
@@ -1,7 +1,11 @@
-//! Operator-initiated upgrades for verified package-manager installations.
+//! Operator-initiated upgrades for verified package-manager installations. The Debian package is installed only
+//! after its publisher-signed manifest (`<deb>.manifest.json` and `.sig`, see `archive.rs`) and the downloaded
+//! bytes match: APT runs the package's scripts as root. After the package manager has replaced the program, a
+//! background service that was running is restarted so it runs the new version, and checked to answer with it.
use std::fs::File;
use std::path::Path;
use std::process::Stdio;
+use std::time::Duration;
use anyhow::{Context, Result, bail, ensure};
use ictl_l10n::tr;
@@ -9,7 +13,10 @@ use tokio::process::Command;
use super::{Availability, InstallMethod, Report, archive, deb_asset, digest, install, publisher, release, tap};
-pub(super) async fn apply(report: &Report) -> Result<()> {
+/// Where the .deb puts its systemd user unit (`deploy/deb/iphone-control.service`)
+const DEB_UNIT: &str = "/usr/lib/systemd/user/iphone-control.service";
+
+pub(super) async fn apply(socket: &Path, report: &Report) -> Result<()> {
let exe = report.executable.as_deref().context("missing installation path")?;
let latest = report.available_version.as_deref().context("missing release version")?;
ensure!(release::stable_tag(&format!("v{latest}")).is_some(), "invalid stable release version");
@@ -18,17 +25,123 @@ pub(super) async fn apply(report: &Report) -> Result<()> {
let cellar = exe.ancestors().nth(4).context("missing Homebrew Cellar")?;
let tap = tap().context("missing Homebrew tap")?;
let brew = install::brew_program(cellar).context("cannot locate the Homebrew executable")?;
- homebrew(&brew, cellar, tap, latest).await
+ if homebrew(&brew, cellar, tap, latest).await? {
+ let running = brew_service_running(&brew).await;
+ restart(
+ socket,
+ latest,
+ running,
+ &[brew.as_os_str(), "services".as_ref(), "restart".as_ref(), "iphone-control".as_ref()],
+ "brew services restart iphone-control",
+ )
+ .await;
+ }
+ Ok(())
}
(InstallMethod::Debian, Availability::Available) => {
let repo = publisher().context("missing release publisher")?;
let target = super::target().context("unsupported Debian architecture")?;
- debian(repo, target, latest, exe).await
+ if debian(repo, target, latest, exe).await? {
+ let running = deb_service_running().await;
+ restart(
+ socket,
+ latest,
+ running,
+ &["systemctl".as_ref(), "--user".as_ref(), "restart".as_ref(), "iphone-control".as_ref()],
+ "systemctl --user restart iphone-control",
+ )
+ .await;
+ }
+ Ok(())
}
_ => bail!("{}", report.guidance),
}
}
+/// The .deb's systemd user service is running (only that unit: not a service the user wrote elsewhere)
+async fn deb_service_running() -> bool {
+ let Ok(out) = Command::new("systemctl")
+ .args(["--user", "show", "iphone-control", "-p", "ActiveState", "-p", "FragmentPath"])
+ .env("LC_ALL", "C")
+ .stderr(Stdio::null())
+ .output()
+ .await
+ else {
+ return false;
+ };
+ let text = String::from_utf8_lossy(&out.stdout);
+ out.status.success()
+ && text.lines().any(|l| l == "ActiveState=active")
+ && text.lines().any(|l| l == format!("FragmentPath={DEB_UNIT}"))
+}
+
+/// `brew services` runs the formula's service. Older Homebrew without `services info --json` counts as not running
+async fn brew_service_running(brew: &Path) -> bool {
+ let Ok(out) = Command::new(brew)
+ .args(["services", "info", "iphone-control", "--json"])
+ .env("HOMEBREW_NO_AUTO_UPDATE", "1")
+ .stderr(Stdio::null())
+ .output()
+ .await
+ else {
+ return false;
+ };
+ serde_json::from_slice::<serde_json::Value>(&out.stdout)
+ .ok()
+ .and_then(|v| v.get(0)?.get("running")?.as_bool())
+ .unwrap_or(false)
+}
+
+/// Restarts the background service if it was `running` and waits until the daemon answers with `version`. Failing
+/// that only prints what to run: the new program is installed either way
+async fn restart(socket: &Path, version: &str, running: bool, cmd: &[&std::ffi::OsStr], by_hand: &str) {
+ if !running {
+ println!(
+ "{}",
+ ictl_l10n::tr!(
+ "后台服务没有在运行,不用重启。Viewer 和 MCP 客户端下次启动时用新版本。",
+ "The background service isn't running, so nothing to restart. Viewer and MCP clients use the new version when they next start."
+ )
+ );
+ return;
+ }
+ println!("{}", ictl_l10n::tr!("正在重启后台服务…", "Restarting the background service…"));
+ let restarted = match Command::new(cmd[0]).args(&cmd[1..]).status().await {
+ Ok(s) if s.success() => wait_for_daemon(socket, version, Duration::from_secs(60)).await,
+ _ => false,
+ };
+ if restarted {
+ println!(
+ "{}",
+ ictl_l10n::trf!(
+ "后台服务已在运行 {version}。重新打开 Viewer、重连 MCP 客户端后它们也会用新版本。",
+ "The background service now runs {version}. Reopen Viewer and reconnect MCP clients to use it there too."
+ )
+ );
+ } else {
+ println!(
+ "{}",
+ ictl_l10n::trf!(
+ "新版本已经装好,但后台服务没能确认重启成功。请运行:{by_hand}",
+ "The new version is installed, but the background service couldn't be confirmed to restart. Run: {by_hand}"
+ )
+ );
+ }
+}
+
+async fn wait_for_daemon(socket: &Path, version: &str, within: Duration) -> bool {
+ let end = tokio::time::Instant::now() + within;
+ while tokio::time::Instant::now() < end {
+ if let Ok(Ok(s)) = tokio::time::timeout(Duration::from_secs(2), crate::snapshot(socket)).await
+ && s.version.as_deref() == Some(version)
+ {
+ return true;
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ false
+}
+
async fn run(cmd: &mut Command) -> Result<()> {
let status =
cmd.status().await.with_context(|| format!("starting {}", cmd.as_std().get_program().to_string_lossy()))?;
@@ -46,7 +159,8 @@ async fn output(cmd: &mut Command) -> Result<String> {
Ok(String::from_utf8(result.stdout)?)
}
-async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result<()> {
+/// True when it upgraded (false: Homebrew already had `latest`)
+async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result<bool> {
let formula = format!("{tap}/iphone-control");
let active = cellar.parent().context("invalid Homebrew prefix")?.join("opt/iphone-control/bin/iphone-control");
let installed = || {
@@ -59,7 +173,7 @@ async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result
let before = semver::Version::parse(&installed()?)?;
if before >= semver::Version::parse(latest)? {
println!("{}", ictl_l10n::trf!("Homebrew 当前版本为 {before}。", "Homebrew already has {before}."));
- return Ok(());
+ return Ok(false);
}
run(Command::new(brew).arg("update")).await?;
// Use exactly the metadata refreshed above for the check and upgrade.
@@ -86,24 +200,8 @@ async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result
);
run(cmd().args(["upgrade", "--formula", &formula])).await?;
ensure!(installed()? == latest, "Homebrew did not activate {latest}");
- println!(
- "{}",
- ictl_l10n::trf!(
- "Homebrew 已升级至 {latest}。如果正在使用 Homebrew 后台服务,运行 brew services restart iphone-control 加载新版。Viewer 和 MCP 客户端将在下次启动时加载新版。",
- "Homebrew upgraded to {latest}. If your Homebrew service is running, run brew services restart iphone-control to load it. Viewer and MCP clients load the new version on their next start."
- )
- );
- Ok(())
-}
-
-fn checksum<'a>(text: &'a str, asset: &str) -> Result<&'a str> {
- // The release job emits exactly one sha256sum record using this filename.
- let (hash, name) = text.trim_end_matches(['\r', '\n']).split_once(" ").context("invalid release checksum file")?;
- ensure!(
- name == asset && hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()),
- "invalid checksum or Debian asset name"
- );
- Ok(hash)
+ println!("{}", ictl_l10n::trf!("Homebrew 已升级至 {latest}。", "Homebrew upgraded to {latest}."));
+ Ok(true)
}
fn check_deb_metadata<'a>(fields: &'a str, version: &str, arch: &str) -> Result<&'a str> {
@@ -145,25 +243,27 @@ async fn check_apt_candidate(apt_cache: &mut Command, path: &Path, deb_version:
Ok(())
}
-async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result<()> {
+/// True when it upgraded (false: APT already had `latest`)
+async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result<bool> {
let asset = deb_asset(latest, target).context("unsupported Debian architecture")?;
let arch = asset.rsplit_once('_').and_then(|(_, s)| s.strip_suffix(".deb")).context("invalid Debian asset name")?;
- let base = format!("https://github.com/{repo}/releases/download/v{latest}/{asset}");
let client = archive::client()?;
- let mut sidecar = Vec::new();
- archive::download(&client, &format!("{base}.sha256"), 1024, &mut sidecar).await?;
- let expected = checksum(std::str::from_utf8(&sidecar)?, &asset)?;
+ let signed = archive::signed_manifest(&client, repo, target, latest, &asset).await?;
let temp = tempfile::tempdir()?;
let path = temp.path().canonicalize()?.join(&asset);
- archive::download(&client, &base, 128 << 20, File::create_new(&path)?).await?;
- ensure!(digest(&path)? == expected, "Debian package SHA-256 mismatch");
+ let url = format!("https://github.com/{repo}/releases/download/v{latest}/{asset}");
+ archive::download(&client, &url, signed.size, File::create_new(&path)?).await?;
+ ensure!(
+ path.metadata()?.len() == signed.size && digest(&path)? == signed.sha256,
+ "Debian package does not match its signed manifest"
+ );
let deb_version = inspect_deb(&path, latest, arch).await?;
let current = install::detect(Some(exe));
ensure!(current.method == InstallMethod::Debian, "Debian package ownership changed");
let current = semver::Version::parse(&current.version.context("missing installed Debian version")?)?;
if current >= semver::Version::parse(latest)? {
println!("{}", ictl_l10n::trf!("APT 当前版本为 {current}。", "APT already has {current}."));
- return Ok(());
+ return Ok(false);
}
let held = output(Command::new("/usr/bin/apt-mark").args(["showhold", "iphone-control"])).await?;
ensure!(held.trim().is_empty(), "{}", tr!("APT 已锁定 iphone-control。", "iphone-control is on hold in APT."));
@@ -194,14 +294,8 @@ async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result<()
installed.method == InstallMethod::Debian && installed.version.as_deref() == Some(latest),
"APT did not install {latest}"
);
- println!(
- "{}",
- ictl_l10n::trf!(
- "APT 已升级至 {latest}。如果正在使用 systemd 用户服务,运行 systemctl --user restart iphone-control 加载新版。Viewer 和 MCP 客户端将在下次启动时加载新版。",
- "APT upgraded to {latest}. If your systemd user service is running, run systemctl --user restart iphone-control to load it. Viewer and MCP clients load the new version on their next start."
- )
- );
- Ok(())
+ println!("{}", ictl_l10n::trf!("APT 已升级至 {latest}。", "APT upgraded to {latest}."));
+ Ok(true)
}
#[cfg(test)]
@@ -263,24 +357,9 @@ esac
let err = homebrew(&brew, &cellar, tap, "1.2.3").await.unwrap_err();
assert!(err.to_string().contains("17"));
std::fs::write(prefix.join("allow"), b"").unwrap();
- homebrew(&brew, &cellar, tap, "1.2.3").await.unwrap();
+ assert!(homebrew(&brew, &cellar, tap, "1.2.3").await.unwrap(), "upgraded");
assert_eq!(active.canonicalize().unwrap(), rack.join("1.2.3"));
- }
-
- #[test]
- fn deb_checksum_is_bound_to_one_exact_asset_and_the_payload() {
- let temp = tempfile::tempdir().unwrap();
- let asset = "iphone-control_1.2.3_arm64.deb";
- let path = temp.path().join(asset);
- std::fs::write(&path, b"package").unwrap();
- let sha = digest(&path).unwrap();
- let record = format!("{sha} {asset}\n");
- assert_eq!(checksum(&record, asset).unwrap(), digest(&path).unwrap());
- std::fs::write(&path, b"different").unwrap();
- assert_ne!(checksum(&record, asset).unwrap(), digest(&path).unwrap());
- for bad in [record.replace(asset, "../pkg.deb"), record.repeat(2), record.replace(&sha, "1234")] {
- assert!(checksum(&bad, asset).is_err());
- }
+ assert!(!homebrew(&brew, &cellar, tap, "1.2.3").await.unwrap(), "already there: nothing to restart");
}
#[cfg(target_os = "linux")]
diff --git a/apps/iphone-control/src/update/install.rs b/apps/iphone-control/src/update/install.rs
index 46ec876..75a8223 100644
--- a/apps/iphone-control/src/update/install.rs
+++ b/apps/iphone-control/src/update/install.rs
@@ -214,7 +214,9 @@ fn brew_installation(exe: &Path, tap: &str) -> Option<String> {
Some(active.canonicalize().ok().and_then(|p| brew_keg(&p, cellar, tap)).unwrap_or(version))
}
-fn deb_package(exe: &Path) -> Option<String> {
+/// The installed Debian package's upstream version, and whether it is on hold in APT (`apt-mark hold`), which is
+/// reported like a pinned managed installation
+fn deb_package(exe: &Path) -> Option<(String, bool)> {
if !cfg!(target_os = "linux") || exe != Path::new("/usr/bin/iphone-control") {
return None;
}
@@ -228,9 +230,13 @@ fn deb_package(exe: &Path) -> Option<String> {
return None;
}
let installed = dpkg(&["-W", "-f=${db:Status-Abbrev} ${Version}", owner])?;
- let version = installed.strip_prefix("ii ").or_else(|| installed.strip_prefix("hi "))?.trim();
+ let (version, held) = match installed.strip_prefix("ii ") {
+ Some(v) => (v, false),
+ None => (installed.strip_prefix("hi ")?, true),
+ };
+ let version = version.trim();
let upstream = version.rsplit_once('-').map_or(version, |(upstream, _)| upstream);
- Some(Version::parse(upstream).ok()?.to_string())
+ Some((Version::parse(upstream).ok()?.to_string(), held))
}
/// Linux marks /proc/self/exe as deleted when Cargo, dpkg or an installer atomically
@@ -271,8 +277,8 @@ pub(super) fn detect(exe: Option<&Path>) -> Installation {
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 };
+ if let Some((version, held)) = deb_package(exe) {
+ return Installation { method: InstallMethod::Debian, version: Some(version), pinned: Some(held) };
}
unknown(InstallMethod::Unknown)
}
diff --git a/apps/iphone-control/src/update/transaction.rs b/apps/iphone-control/src/update/transaction.rs
index d77f51b..601d451 100644
--- a/apps/iphone-control/src/update/transaction.rs
+++ b/apps/iphone-control/src/update/transaction.rs
@@ -15,42 +15,14 @@ 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};
+/// The last installation's result. Records written by 0.2.2 may also carry `migration_source` (and the status
+/// `rolled_back` or `manual_migration`); serde ignores the field
#[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)]
@@ -66,15 +38,11 @@ struct Transaction {
old: Receipt,
new: Receipt,
was_running: bool,
- rollback: bool,
phase: Phase,
}
-#[derive(Serialize, Deserialize)]
-struct Previous {
- before_digest: String,
- receipt: Receipt,
-}
+/// What 0.2.2 kept after an upgrade for `update rollback`, which no longer exists: removed on the next upgrade
+const LEGACY_PREVIOUS: [&str; 2] = ["previous", "previous.json"];
fn state_dir(exe: &Path) -> Result<PathBuf> {
Ok(exe.parent().context("invalid installation path")?.join(".iphone-control-update"))
@@ -138,14 +106,7 @@ impl Store {
self.dir.join("transaction.json")
}
- fn record(
- &self,
- status: &str,
- version: &str,
- detail: impl ToString,
- suppressed: Option<String>,
- migration_source: Option<MigrationSource>,
- ) -> Result<()> {
+ fn record(&self, status: &str, version: &str, detail: impl ToString, suppressed: Option<String>) -> Result<()> {
write_json(
&self.dir.join("outcome.json"),
&Outcome {
@@ -153,7 +114,6 @@ impl Store {
target_version: version.into(),
detail: detail.to_string(),
suppressed_version: suppressed,
- migration_source,
},
)
}
@@ -182,16 +142,13 @@ impl Store {
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() },
- )?;
+ for name in LEGACY_PREVIOUS {
+ match fs::remove_file(self.dir.join(name)) {
+ Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e.into()),
+ _ => {}
+ }
}
- 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.record("installed", &tx.new.version, "installation confirmed", None)?;
self.clear()
}
@@ -368,7 +325,7 @@ async fn restore(store: &Store, host: &impl Services, tx: &Transaction, why: &st
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.record("restored", &tx.new.version, why, Some(tx.new.version.clone()))?;
store.clear()
}
@@ -378,7 +335,6 @@ async fn replace(
old: Receipt,
new: Receipt,
candidate: &Path,
- rollback: bool,
auto: bool,
) -> Result<()> {
let activity = async {
@@ -391,8 +347,8 @@ async fn replace(
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)?;
+ let suppressed = outcome(&store.binary)?.and_then(|o| o.suppressed_version);
+ store.record("busy", &new.version, format!("{e:#}"), suppressed)?;
return Err(e);
}
};
@@ -410,7 +366,7 @@ async fn replace(
);
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 };
+ let mut tx = Transaction { old, new, was_running: running, phase: Phase::Prepared };
write_json(&store.journal(), &tx)?;
let swap = async {
@@ -443,7 +399,7 @@ async fn restore_or_report(store: &Store, host: &impl Services, tx: &Transaction
tx.old.version,
store.dir.join("recovery").display()
);
- store.record("recovery_failed", &tx.new.version, &detail, Some(tx.new.version.clone()), None)?;
+ store.record("recovery_failed", &tx.new.version, &detail, Some(tx.new.version.clone()))?;
bail!(detail);
}
Ok(())
@@ -489,7 +445,7 @@ pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Re
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));
+ let suppressed = outcome(&store.binary)?.and_then(|o| o.suppressed_version);
ensure!(
suppressed.as_ref() != Some(&version),
"automatic retry suppressed for {version}; run iphone-control update to retry"
@@ -497,7 +453,7 @@ pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Re
// 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)?;
+ store.record("busy", &version, format!("{e:#}"), suppressed)?;
return Err(e);
}
}
@@ -507,18 +463,16 @@ pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Re
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))
+ outcome(&store.binary)?.and_then(|o| o.suppressed_version)
} 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)?;
+ store.record(failure_status(&e), &version, format!("{e:#}"), suppressed)?;
return Err(e);
}
};
let next = Receipt { version, sha256: digest(&candidate)?, ..receipt.clone() };
- replace(&store, &host, receipt, next, &candidate, false, background).await
+ replace(&store, &host, receipt, next, &candidate, background).await
}
.await;
let _ = fs::remove_dir_all(&stage);
@@ -526,15 +480,10 @@ pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Re
}
/// 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)
+/// installation is no failure: the automatic job leaves it to `iphone-control update` (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"
- }
+ if e.is::<archive::NeedsOperator>() { "needs_operator" } else { "failed" }
}
pub fn unpin() -> Result<()> {
@@ -544,22 +493,6 @@ pub fn unpin() -> Result<()> {
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
diff --git a/apps/iphone-control/src/update/transaction/tests.rs b/apps/iphone-control/src/update/transaction/tests.rs
index 084cf39..e314983 100644
--- a/apps/iphone-control/src/update/transaction/tests.rs
+++ b/apps/iphone-control/src/update/transaction/tests.rs
@@ -152,7 +152,7 @@ impl Fixture {
}
async fn apply(&self) -> Result<()> {
- replace(&self.store, &self.host, self.old.clone(), self.new.clone(), &self.candidate, false, false).await
+ replace(&self.store, &self.host, self.old.clone(), self.new.clone(), &self.candidate, false).await
}
fn assert_installed(&self, expected: &Receipt) {
@@ -163,7 +163,7 @@ impl Fixture {
}
#[tokio::test]
-async fn busy_then_replace_and_explicit_rollback_while_daemon_is_running() {
+async fn busy_then_replace_while_daemon_is_running() {
if unsafe { libc::geteuid() } == 0 {
return;
}
@@ -181,14 +181,7 @@ async fn busy_then_replace_and_explicit_rollback_while_daemon_is_running() {
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!(outcome(&f.store.binary).unwrap().unwrap().status, "installed");
assert_eq!(fs::read_to_string(&state).unwrap(), "untouched device state");
}
@@ -268,7 +261,7 @@ async fn interrupted_worker() {
busy: Cell::new(false),
},
};
- replace(&store, &host, old, new, &c, false, false).await.unwrap();
+ replace(&store, &host, old, new, &c, false).await.unwrap();
}
#[tokio::test]
@@ -329,17 +322,15 @@ async fn confirmed_checkpoint_finishes_metadata_and_unknown_disk_is_preserved()
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,
- };
+ let mut tx = Transaction { old: f.old.clone(), new: f.new.clone(), was_running: false, phase: Phase::Confirmed };
+ // what 0.2.2 left for `update rollback` goes with the next confirmed installation
+ for name in LEGACY_PREVIOUS {
+ fs::write(f.store.dir.join(name), "left by 0.2.2").unwrap();
+ }
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);
+ assert!(LEGACY_PREVIOUS.iter().all(|n| !f.store.dir.join(n).exists()));
tx.phase = Phase::Replaced;
write_json(&f.store.journal(), &tx).unwrap();
diff --git a/apps/iphone-control/src/viewer.html b/apps/iphone-control/src/viewer.html
index 6252b43..0d41acd 100644
--- a/apps/iphone-control/src/viewer.html
+++ b/apps/iphone-control/src/viewer.html
@@ -2000,8 +2000,8 @@ function drawUpdates(r) {
$('#update-copy').title = r.guidance || tr('复制升级命令');
$('#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'),
+ const outcomes = { installed: t('安装成功', 'Installed'), restored: t('升级失败,已恢复旧版本', 'Previous version restored'),
+ failed: t('更新失败', 'Update failed'),
needs_operator: t('等待手动升级', 'Waiting for manual upgrade'),
busy: t('等待空闲', 'Waiting for idle'), recovery_failed: t('需要手动恢复', 'Recovery needs attention') };
const last = r.last_update?.status;
@@ -2010,7 +2010,7 @@ function drawUpdates(r) {
$('#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 more = $('#update-more');
- const attention = last && !['installed', 'rolled_back'].includes(last) ? outcomes[last] || last :
+ const attention = last && last !== 'installed' ? outcomes[last] || last :
$('#update-mismatch').textContent ? t('版本不一致', 'Version mismatch') : '';
more.dataset.attention = String(Boolean(attention));
more.firstElementChild.textContent = attention || tr('版本详情');
diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md
index 3d261c4..dae6de5 100644
--- a/docs/dev/regression-cases.md
+++ b/docs/dev/regression-cases.md
@@ -97,3 +97,8 @@
| 91 | 手机按请求补发的关键帧不带参数集,新页面从它开始解不了 | 组帧时记下 VPS/SPS/PPS,补到这样的关键帧前面 | 单测 keyframes_get_the_parameter_sets |
| 92 | 横屏时页面上的画面上下颠倒(转正方向写反) | 按「竖放顶边顺时针转过的角度」同向转回来;方向每秒问一次 | 真机:向左、向右横屏的画面和手机截图一致,1.1~2.7 秒跟上;横屏点地址栏点中 |
| 93 | 在本机运行 `iphone-control update` 只出现子命令帮助,还要再查该用哪种升级命令 | 先检查当前版本。已是最新则提示并结束,有可升级版本时按核实的安装渠道处理,固定版本仍需显式解除 | 单测(`user_update_checks_the_release_before_choosing_an_installer`) |
+| 94 | Debian 升级只对照同一发布页上的 `.sha256` 就用 sudo 以 root 安装:能替换发布附件的人可以同时换掉包和校验值 | 发布流程给每个 .deb 签名清单(`release.py sign-deb`);没有签名清单不提供升级,下载后大小和 SHA-256 要和签名清单一致才交给 APT | 单测 deb_manifest_is_bound_to_its_package、deb_upgrade_waits_for_its_signed_manifest;`packaging/test_installer.py` test_debian_package_is_signed_for_its_own_name |
+| 95 | `iphone-control update` 不问就开始安装,受管服务会重启,打断正在执行的任务 | 先说明要做什么并询问,没有终端时要 `--yes` | 单测 update_accepts_no_subcommand_and_preserves_read_only_check;手动:终端里运行,回答 n 不升级 |
+| 96 | Homebrew、Debian 升级后后台服务还在跑旧版本 | 升级后服务在运行就重启,并确认守护进程报告的是新版本;确认不了时写出手动重启命令 | 单测 brew_upgrades_the_exact_active_formula_only_after_the_tap_is_ready(已是最新时不重启);真机:deb 安装下升级 |
+| 97 | APT 锁定(hold)的包仍提示可直接升级,运行后才报错 | hold 当作“已固定”:升级命令带上 `sudo apt-mark unhold`,直接运行时先提示解除锁定 | 单测 a_held_deb_is_reported_like_a_pinned_installation |
+| 98 | 发布清单只允许从声明过的某一个版本升级,其他版本一律“需要手动迁移” | 去掉回滚兼容标记和 `update rollback`;任何更新的签名稳定版都能升级,新版本起不来时仍自动换回旧版本;清单保留两个旧字段让 0.2.2 还能升级 | 单测 verifies_publisher_signed_bytes_before_staging_an_executable、unhealthy_daemon_restores_last_verified_executable_and_service;`test_installer.py` test_archive_manifest_still_lets_0_2_2_upgrade |
diff --git a/docs/dev/release-updates.md b/docs/dev/release-updates.md
index beff86f..3bbe981 100644
--- a/docs/dev/release-updates.md
+++ b/docs/dev/release-updates.md
@@ -26,7 +26,7 @@ The stable tag must match the workspace package version, e.g. `v0.2.1` for `0.2.
## 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.
+Every stable release signs one manifest per archive and, on Linux, one per Debian package (`iphone-control_X.Y.Z_<arch>.deb.manifest.json` and `.sig`): `iphone-control update` installs a .deb through `sudo apt-get` only after its signature, name, size and SHA-256 match. Any newer signed stable release can be installed from any installed version; there is no rollback command and no per-release compatibility setting (the `ICTL_ROLLBACK_*` variables are gone and can be deleted from the repository settings). An upgrade whose new daemon fails its 60-second health check still puts the old executable back. Archive manifests keep `rollback_compatible: true` and `rollback_from: "0.2.2"` only because 0.2.2's updater refuses a manifest without them (`LEGACY_UPDATER` in `packaging/release.py`).
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.
@@ -52,4 +52,4 @@ For an older script installation, close clients and stop the daemon, then uninst
`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.
+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 (since removed) 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 (the per-version rollback check, since removed). 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/packaging/installer.py b/packaging/installer.py
index d0f9c9c..8cd478c 100644
--- a/packaging/installer.py
+++ b/packaging/installer.py
@@ -69,7 +69,7 @@ def digest(path):
return result.hexdigest()
-def verify_manifest(directory, manifest, sig, repo, keys, version, target):
+def verify_manifest(directory, manifest, sig, repo, keys, version, target, asset=None):
keyfile = directory / "public.der"
for key in keys.split(","):
keyfile.write_bytes(bytes.fromhex("302a300506032b6570032100" + key))
@@ -81,12 +81,12 @@ def verify_manifest(directory, manifest, sig, repo, keys, version, target):
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"
+ name = asset or 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):
+ or type(data["unattended"]) is not bool):
raise ValueError("release manifest does not match requested installation")
return data
diff --git a/packaging/release.py b/packaging/release.py
index d006601..7457f93 100644
--- a/packaging/release.py
+++ b/packaging/release.py
@@ -16,6 +16,11 @@ 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")
+DEB_ARCH = {"linux-x86_64": "amd64", "linux-aarch64": "arm64"}
+# 0.2.2's updater refuses a manifest without these two fields and installs only when `rollback_from` is its own
+# version (rollback was removed after it). Written into archive manifests so 0.2.2 can still upgrade with
+# `iphone-control update apply`; later versions ignore them. Drop once 0.2.2 is no longer supported.
+LEGACY_UPDATER = dict(rollback_compatible=True, rollback_from="0.2.2")
def config():
@@ -41,6 +46,10 @@ def main():
cmd = sub.add_parser(action)
cmd.add_argument("directory", type=Path)
cmd.add_argument("target", choices=TARGETS)
+ # The Debian package: `iphone-control update` installs it as root through APT only after this signature
+ cmd = sub.add_parser("sign-deb")
+ cmd.add_argument("directory", type=Path)
+ cmd.add_argument("target", choices=tuple(DEB_ARCH))
args = parser.parse_args()
repo, keys = config()
tag = os.environ["GITHUB_REF_NAME"]
@@ -80,25 +89,27 @@ def main():
data = verify_manifest(args.directory, manifest, Path(str(manifest) + ".sig"), repo, keys, tag[1:], args.target)
print(data["sha256"])
return
+ if args.command == "sign-deb":
+ asset = args.directory / f"iphone-control_{tag[1:]}_{DEB_ARCH[args.target]}.deb"
+ sign(args.directory / f"{asset.name}.manifest.json", manifest_data(repo, tag, args.target, asset, False), keys)
+ return
archive = args.directory / f"{name}.tar.gz"
- size = archive.stat().st_size
+ data = manifest_data(repo, tag, args.target, archive, os.environ.get("ICTL_UNATTENDED_TAG") == tag)
+ sign(manifest, dict(data, **LEGACY_UPDATER), keys)
+
+
+def manifest_data(repo, tag, target, asset, unattended):
+ size = asset.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.
+ raise ValueError("release asset exceeds client limits")
+ return dict(schema=1, publisher=repo, version=tag[1:], target=target, asset=asset.name,
+ sha256=hashlib.sha256(asset.read_bytes()).hexdigest(), size=size, unattended=unattended)
+
+
+def sign(manifest, data, keys):
+ manifest.write_text(json.dumps(data, separators=(",", ":")) + "\n")
+ # The signing key is a PKCS#8 PEM from the protected signing environment. One signature per run: it is taken
+ # out of the environment so the child processes don't inherit it.
with tempfile.TemporaryDirectory() as private:
key = Path(private) / "key.pem"
key.write_text(os.environ.pop("ICTL_UPDATE_SIGNING_KEY"))
diff --git a/packaging/test_installer.py b/packaging/test_installer.py
index a525a70..0d8a840 100644
--- a/packaging/test_installer.py
+++ b/packaging/test_installer.py
@@ -54,7 +54,7 @@ class InstallerTest(unittest.TestCase):
"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": "",
+ "ICTL_UPDATE_SIGNING_KEY": key.read_text(), "ICTL_UNATTENDED_TAG": "",
}))
self.stack.enter_context(patch.multiple(installer, PUBLISHER=REPO, PUBLIC_KEYS=pub))
self.stack.enter_context(patch.object(installer, "download", self.download))
@@ -296,18 +296,35 @@ class InstallerTest(unittest.TestCase):
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()
+ def test_archive_manifest_still_lets_0_2_2_upgrade(self):
+ # 0.2.2's updater needs both fields and its own version in rollback_from; nothing else reads them
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")
+ self.assertIs(data["rollback_compatible"], True)
+ self.assertEqual(data["rollback_from"], "0.2.2")
+
+ def test_debian_package_is_signed_for_its_own_name(self):
+ command = [sys.executable, ROOT / "packaging/release.py", "sign-deb", self.dist, "linux-x86_64"]
+ self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0, "no package to sign")
+ deb = self.dist / f"iphone-control_{VERSION}_amd64.deb"
+ deb.write_bytes(b"debian package bytes")
+ subprocess.run(command, check=True)
+ manifest = self.dist / (deb.name + ".manifest.json")
+ sig = self.dist / (deb.name + ".manifest.json.sig")
+
+ def verify(asset):
+ return installer.verify_manifest(self.root, manifest, sig, REPO, installer.PUBLIC_KEYS,
+ VERSION, "linux-x86_64", asset)
+
+ data = verify(deb.name)
+ self.assertEqual((data["sha256"], data["size"], data["unattended"]),
+ (installer.digest(deb), deb.stat().st_size, False))
+ self.assertNotIn("rollback_from", data)
+ with self.assertRaisesRegex(ValueError, "does not match"):
+ verify(None)
+ sig.write_bytes(b"x" * 64)
+ with self.assertRaisesRegex(ValueError, "verification failed"):
+ verify(deb.name)
def test_bad_key_digest_identity_and_tar(self):
with patch.object(installer, "PUBLIC_KEYS", "11" * 32), self.assertRaisesRegex(ValueError, "verification failed"):
diff --git a/website/deploy/macos.md b/website/deploy/macos.md
index f0a71ff..4682158 100644
--- a/website/deploy/macos.md
+++ b/website/deploy/macos.md
@@ -111,7 +111,7 @@ sudo launchctl kickstart -k system/com.apple.usbmuxd
升级前先看[更新日志](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.zh-CN.md)里的升级注意事项。
-受管脚本安装先关闭 Viewer、MCP 等客户端,再运行 `iphone-control update`。Homebrew 安装也可使用这条命令,它会通过对应的 tap 升级磁盘上的程序。已经通过 Homebrew 运行后台服务的,升级后运行 `brew services restart iphone-control`。原先未启用服务则跳过这一步。重新打开 Viewer、重连 MCP 客户端后即可使用新版。
+受管脚本安装先关闭 Viewer、MCP 等客户端,再运行 `iphone-control update`。Homebrew 安装也可使用这条命令,它会通过对应的 tap 升级磁盘上的程序。`brew services` 在运行的话,升级后会重启它。重新打开 Viewer、重连 MCP 客户端后即可使用新版。
源码安装请运行以下命令。
diff --git a/website/en/deploy/macos.md b/website/en/deploy/macos.md
index 834ef39..6734b43 100644
--- a/website/en/deploy/macos.md
+++ b/website/en/deploy/macos.md
@@ -111,7 +111,7 @@ sudo launchctl kickstart -k system/com.apple.usbmuxd
Read the upgrade notes in the [changelog](https://github.com/Derrors/iphone-control/blob/main/CHANGELOG.md) first.
-For a managed script installation, close Viewer, MCP and other device clients, then run `iphone-control update`. On Homebrew the same command upgrades the executable on disk through the tap. If you already run the Homebrew service, restart it with `brew services restart iphone-control`. Skip this step if you do not use a service. Reopen Viewer and reconnect your MCP client to use the new version.
+For a managed script installation, close Viewer, MCP and other device clients, then run `iphone-control update`. On Homebrew the same command upgrades the executable on disk through the tap. A running `brew services` service is restarted afterwards. Reopen Viewer and reconnect your MCP client to use the new version.
For a source build, run the following commands.
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index de0f108..2967f1a 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -23,22 +23,22 @@ These go before the command, for example `iphone-control --socket /path/ctl.sock
## Host software updates
-Run `iphone-control update` to check the publisher's latest stable release. It reports when you are up to date. When an upgrade is available, it uses the installation method of the running executable.
+Run `iphone-control update` to check the publisher's latest stable release. It reports when you are up to date. When an upgrade is available, it first says what it will do (from which version to which, and whether the background service restarts), asks whether to continue, then upgrades through the installation method of the running executable. In a script or without a terminal, add `--yes` to upgrade without asking.
| Installation | What `iphone-control update` does |
| --- | --- |
-| Managed per-user service installed by the signed release script | Verifies and installs the signed update, then restarts the service and checks its health. Close Viewer, MCP and other device clients first. If you pinned a version with `--version`, run `iphone-control update unpin` when you are ready to upgrade. |
-| Homebrew | Runs the Homebrew upgrade through the tap bound to this installation. The tap determines which version is available. |
-| Debian / Ubuntu package | Downloads the matching `.deb` for the target version and host architecture from the same publisher, verifies it and passes it to apt for installation. |
+| Managed per-user service installed by the signed release script | Verifies the publisher's signature, installs the update, then restarts the service and checks its health; if the new version doesn't start within 60 seconds, the old one is put back. Close Viewer, MCP and other device clients first. If you pinned a version with `--version`, run `iphone-control update unpin` when you are ready to upgrade. |
+| Homebrew | Runs the Homebrew upgrade through the tap bound to this installation. The tap determines which version is available. A running `brew services` service is restarted afterwards. |
+| Debian / Ubuntu package | Downloads the matching `.deb` for the target version and host architecture from the same publisher, checks the publisher's signature for it, then installs it with apt through `sudo` (asks for your password). The package's systemd user service is restarted afterwards if it was running. A package held with `apt-mark hold` isn't upgraded; release it with `sudo apt-mark unhold iphone-control` first. |
| Source builds, script installs without a managed service, or unrecognized installations | Shows instructions for a manual upgrade. A development build without a publisher displays guidance locally. |
-Homebrew and apt upgrade the executable on disk. If you already run a background service, restart it after the upgrade with `brew services restart iphone-control` for Homebrew or `systemctl --user restart iphone-control` for a Debian user service. Skip this step if you do not use a service. Reopen Viewer and reconnect your MCP client to use the new executable.
+Restarting the background service interrupts running AI tasks and the control page's picture. After a Homebrew or apt upgrade the command checks that the service now runs the new version; if it can't confirm that, it prints the restart command to run by hand. Reopen Viewer and reconnect your MCP client to use the new executable there too.
Use `iphone-control update check` for a version check only, or `iphone-control update check --json` for machine-readable output. This check and **About & updates** in Viewer share the local release cache. If the network check fails, the previous successful record is kept. A red dot on the ⓘ button beside **Settings** indicates a newer release. Open the panel to read the release notes and copy the update command for the current executable into a local terminal.
-Viewer listens on loopback. Other users on the same host can read installation information and request a version check. Upgrade, rollback and policy changes are performed from a local terminal.
+Viewer listens on loopback. Other users on the same host can read installation information and request a version check. Upgrades and policy changes are performed from a local terminal.
-Managed services check in the background by default. You can still use `update apply` to install, `update rollback` to restore the previous verified executable and `update recover` after an interrupted replacement. If you currently run the 0.2.2 CLI, use `iphone-control update check` and follow the command it shows to upgrade to a version with the new `iphone-control update` command.
+Managed services check in the background by default. `update apply` installs without asking (managed services), and `update recover` finishes an interrupted replacement. There is no command to go back to the previous version: to run an older one, uninstall with the release's install script and `--uninstall` (settings and device data are kept), then install that version with `--version vX.Y.Z`. If you currently run the 0.2.2 CLI, use `iphone-control update check` and follow the command it shows to upgrade to a version with the new `iphone-control update` command.
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.
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 0ea5eed..7cd1ece 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -23,22 +23,22 @@
## 主机软件更新
-运行 `iphone-control update` 检查发布者的最新稳定版。已是最新时,命令会显示结果并退出。有新版时,它按当前程序的安装方式升级。
+运行 `iphone-control update` 检查发布者的最新稳定版。已是最新时,命令会显示结果并退出。有新版时,它先说明要做什么(从哪个版本升到哪个版本、会不会重启后台服务),问你是否继续,再按当前程序的安装方式升级。脚本里或没有终端时加 `--yes`,不询问直接升级。
| 安装方式 | 运行 `iphone-control update` 后 |
| --- | --- |
-| 签名安装脚本部署的受管用户服务 | 验证并安装签名更新,重启服务并检查健康状态。先关闭 Viewer、MCP 和其他设备客户端。通过 `--version` 固定版本的安装,须先显式运行 `iphone-control update unpin` 才能升级。 |
-| Homebrew | 通过该安装绑定的 tap 运行 Homebrew 升级,以 tap 提供的版本为准。 |
-| Debian / Ubuntu 软件包 | 下载同一发布者提供的、匹配目标版本和主机架构的 `.deb`,经过校验后交给 apt 安装。 |
+| 签名安装脚本部署的受管用户服务 | 验证发布者签名后安装,重启服务并检查健康状态;新版本 60 秒内起不来就自动换回旧版本。先关闭 Viewer、MCP 和其他设备客户端。通过 `--version` 固定版本的安装,须先显式运行 `iphone-control update unpin` 才能升级。 |
+| Homebrew | 通过该安装绑定的 tap 运行 Homebrew 升级,以 tap 提供的版本为准。`brew services` 在运行的话,升级后重启它。 |
+| Debian / Ubuntu 软件包 | 下载同一发布者提供的、匹配目标版本和主机架构的 `.deb`,验证发布者对它的签名后,用 `sudo` 交给 apt 安装(会询问密码)。deb 带的 systemd 用户服务在运行的话,升级后重启它。用 `apt-mark hold` 锁定了的不会升级,先 `sudo apt-mark unhold iphone-control`。 |
| 源码安装、没有受管服务的脚本安装或无法识别的安装 | 显示适用的手动升级指引。未绑定发布者的开发构建在本地给出说明。 |
-Homebrew 和 apt 升级的是磁盘上的程序。如果原先已经运行后台服务,升级后用 `brew services restart iphone-control` 重启 Homebrew 服务,或用 `systemctl --user restart iphone-control` 重启 Debian 的用户服务。原先未启用服务的安装可跳过这一步。重新打开 Viewer、重连 MCP 客户端后,这些进程也会使用新版。
+重启后台服务会中断正在执行的 AI 任务和控制台画面。Homebrew 和 apt 升级后,命令会确认后台服务已经在运行新版本;没能确认时,它会写出要手动运行的重启命令。重新打开 Viewer、重连 MCP 客户端后,这些进程也会使用新版。
只想查看版本可运行 `iphone-control update check`,脚本可用 `iphone-control update check --json` 读取结果。该检查与 Viewer「关于与更新」共用本地缓存,网络失败时保留上次成功的记录。Viewer 在「设置」旁的 ⓘ 上用红点提示新版本。打开面板可查看发行说明,并复制针对当前程序路径的更新命令,在本机终端执行。
-Viewer 只监听本机回环地址。同机其他用户也能查看安装信息、触发版本检查。安装、回滚和更改策略都通过本机 CLI 执行。
+Viewer 只监听本机回环地址。同机其他用户也能查看安装信息、触发版本检查。安装和更改策略都通过本机 CLI 执行。
-受管服务默认只做后台检查。显式安装仍可用 `update apply`,恢复前一个已验证版本用 `update rollback`,替换意外中断后用 `update recover`。如果正在使用 0.2.2 的 CLI,先运行 `iphone-control update check` 并按该版本显示的命令升级。新版 CLI 才支持直接运行 `iphone-control update`。
+受管服务默认只做后台检查。`update apply` 不询问直接安装(受管服务),替换意外中断后用 `update recover`。没有回退到上一版的命令:要换回旧版本,先用发行页的安装脚本加 `--uninstall` 卸载(设置和设备数据保留),再加 `--version vX.Y.Z` 安装那个版本。如果正在使用 0.2.2 的 CLI,先运行 `iphone-control update check` 并按该版本显示的命令升级。新版 CLI 才支持直接运行 `iphone-control update`。
主动运行 `iphone-control update policy auto-patch` 后,服务只在空闲时自动安装兼容补丁。请退出 Viewer、MCP 和直连设备的客户端;暂停的任务也视为占用。新 daemon 健康检查失败会恢复旧程序,失败版本须手动重试。`update policy notify` 改回仅检查,`update policy manual` 移除定时任务。