From 9ce610bf1657b11dd2495ccdff9233afabf43086 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 11:50:55 +0000 Subject: [PATCH 1/7] craft-update: a Windows MSI copy updates itself in its own context, wherever it is installed Self-update only recognised an MSI copy by the launcher's per-user folder (the HKCU InstallDir key, or %LOCALAPPDATA%\Programs\). Every app installed for everyone, in Program Files\ArtCraft\ or the older Program Files\, was treated as a loose folder and updated by unpacking the portable zip over Program Files without permission. - msi_context moves here from the launcher (craft-launcher crates/native/src/msi_context.rs at b827fed, unchanged apart from visibility, MsiScope and scope_arguments). Windows Installer's own registration decides a copy's context, for the launcher and the apps alike, so the launcher can drop its copy and both routes follow one rule. - New msi_copy module: a copy is an MSI copy when an App Paths entry names its exe (a registry read, cheap enough for status checks). Its update asks Windows Installer for the context; the App Paths hive is only the fallback when that lookup cannot run. - The update stops, before the app exits, when the copy is registered in both hives, the lookup is unclear, or Windows lists the app more than once. - After the update the helper starts the exe the registrations name now, since the package may have moved an exact old default folder. - A failed self-update now names the Windows Installer log, as the launcher's installs do. - The launcher's own per-user package is recognised and updated exactly as before. Co-Authored-By: Claude Opus 5.5 --- crates/update/src/install.rs | 43 ++++- crates/update/src/lib.rs | 2 + crates/update/src/msi_context.ps1 | 23 +++ crates/update/src/msi_context.rs | 282 ++++++++++++++++++++++++++++++ crates/update/src/msi_copy.rs | 252 ++++++++++++++++++++++++++ crates/update/src/self_update.rs | 44 +++-- 6 files changed, 623 insertions(+), 23 deletions(-) create mode 100644 crates/update/src/msi_context.ps1 create mode 100644 crates/update/src/msi_context.rs create mode 100644 crates/update/src/msi_copy.rs diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 09de4e0c2..7c9e773ee 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -1645,6 +1645,15 @@ fn msi_command(program: &Path, msi: &Path) -> Result Result { + let mut command = msi_command(program, msi)?; + command.args(context); + Ok(command) +} + /// Where `msi_command` asks Windows Installer to write its log. #[cfg_attr(not(windows), allow(dead_code))] fn msi_log(msi: &Path) -> PathBuf { @@ -1667,7 +1676,9 @@ pub(crate) fn msi_path(msi: &Path) -> Result { pub mod windows { use crate::protocol::CANCELLED; - use super::{App, INSTALLER, JobPhase, Path, PathBuf, Stop, cancelled, msi_command, msi_folder_argument, msi_log, process, turn}; + use super::{ + App, INSTALLER, JobPhase, Path, PathBuf, Stop, cancelled, msi_command, msi_folder_argument, msi_log, process, reinstall_command, turn, + }; fn msiexec() -> PathBuf { std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from).join(r"System32\msiexec.exe") @@ -1700,11 +1711,15 @@ pub mod windows { }) } - /// Runs the launcher's own new MSI for a self-update, with the same progress window and no - /// restart as [`run_msi`], and waits for it. - pub fn reinstall(msi: &Path) -> Result<(), String> { - let status = msi_command(&msiexec(), msi)?.status().map_err(|e| format!("couldn't start the Windows Installer ({e})"))?; - explain(status.code()) + /// Runs an app's own new MSI for a self-update, with the same progress window and no restart + /// as [`run_msi`], and waits for it. `context` keeps the installed copy's Windows Installer + /// context. A failure names the installer's log, which is the only place 1603 is explained. + pub fn reinstall(msi: &Path, context: &[&str]) -> Result<(), String> { + let status = reinstall_command(&msiexec(), msi, context)?.status().map_err(|e| format!("couldn't start the Windows Installer ({e})"))?; + explain(status.code()).map_err(|e| match status.code() { + Some(1602) | None => e, + _ => format!("{e}. Its log is at {}", msi_log(msi).display()), + }) } /// Runs `work` once no other Windows Installer job of ours is running (a second one would @@ -1760,6 +1775,22 @@ mod tests { ); } + #[test] + fn a_self_update_keeps_the_installed_copys_context_after_the_package_options() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("GridCraft.msi"); + std::fs::write(&file, b"test package").unwrap(); + let resolved = msi_path(&file).unwrap(); + for context in [&["ALLUSERS=1"][..], &["ALLUSERS=2", "MSIINSTALLPERUSER=1"], &[]] { + let command = reinstall_command(Path::new("msiexec.exe"), &file, context).unwrap(); + let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let mut expected: Vec = ["/i", &resolved.to_string_lossy(), "/passive", "/norestart", "/l*v"].map(String::from).to_vec(); + expected.push(resolved.with_extension("log").to_string_lossy().into_owned()); + expected.extend(context.iter().map(|p| p.to_string())); + assert_eq!(args, expected); + } + } + #[test] fn an_unavailable_msi_is_refused_before_starting_the_installer() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index d0fec4961..58bb0e946 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -10,6 +10,8 @@ mod folders; pub mod http; pub mod install; pub mod manifest; +pub mod msi_context; +mod msi_copy; pub mod packages; pub mod paths; pub mod platform; diff --git a/crates/update/src/msi_context.ps1 b/crates/update/src/msi_context.ps1 new file mode 100644 index 000000000..d0e0e0ebc --- /dev/null +++ b/crates/update/src/msi_context.ps1 @@ -0,0 +1,23 @@ +# Read-only MSI registration, limited to the current account and machine contexts. +# $code is supplied by the caller only after strict braced-GUID validation. +$ErrorActionPreference = 'Stop' +$installer = $null +$products = $null +try { + $installer = New-Object -ComObject WindowsInstaller.Installer + $products = $installer.ProductsEx($code, '', 7) + foreach ($product in $products) { + try { + $context = $product.GetType().InvokeMember('Context', 'GetProperty', $null, $product, $null) + Write-Output ([int]$context) + } finally { + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($product) + } + } +} finally { + foreach ($com in @($products, $installer)) { + if ($null -ne $com) { + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($com) + } + } +} diff --git a/crates/update/src/msi_context.rs b/crates/update/src/msi_context.rs new file mode 100644 index 000000000..9819bde0c --- /dev/null +++ b/crates/update/src/msi_context.rs @@ -0,0 +1,282 @@ +//! The Windows Installer context of an installed copy, from Windows Installer's own registration, +//! never inferred from a display registry entry. An existing copy must never fall back to a fresh +//! installation when discovery fails. +//! +//! Shared by the launcher's installs and the apps' self-updates, so both keep a copy in the same +//! context by the same rule. + +#![cfg_attr(not(windows), allow(dead_code))] + +/// The Windows Installer context a copy is installed in. A per-machine copy elevates and writes +/// HKLM registrations; a per-user one must not silently become a second, per-machine copy (or the +/// other way round). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MsiScope { + PerUser, + PerMachine, +} + +/// The `msiexec` properties that ask a dual-scope package for `scope`. `ALLUSERS=1` installs for +/// everyone (Windows asks for permission); `ALLUSERS=2` with `MSIINSTALLPERUSER=1` is the documented +/// single-package way to ask for a per-user install. +pub fn scope_arguments(scope: MsiScope) -> &'static [&'static str] { + match scope { + MsiScope::PerUser => &["ALLUSERS=2", "MSIINSTALLPERUSER=1"], + MsiScope::PerMachine => &["ALLUSERS=1"], + } +} + +const UNKNOWN_CONTEXT: &str = "Windows could not confirm who this app is installed for. No changes were made. Try the app's installer instead."; +const CONFLICTING_CONTEXT: &str = "This app is installed for both your account and everyone. Use its installer to choose which copy to update."; + +/// Why the Windows Installer lookup gave no context. +#[derive(Debug, PartialEq, Eq)] +pub enum ProbeError { + /// The lookup ran but gave no usable answer. The context is never guessed from that. + Unknown, + /// The same product is registered for this account and for everyone. + Conflicting, + /// The lookup could not run (a blocked shell, a timeout, a slow first start). Carries the real + /// error so it can be logged. + Unavailable(String), +} + +/// The context an update must keep. Windows Installer's own registration decides. Only when that +/// lookup cannot run at all does the context come from the uninstall record the copy was found by +/// (`record_scope`): the machine's records are per-machine and the account's own are per-user. A +/// lookup that ran and gave no answer, or a copy registered twice, still stops the update. +pub fn update_scope( + is_msi: bool, + product_code: Option<&str>, + probe: impl FnOnce(&str) -> Result, + record_scope: impl FnOnce(&str) -> Option, +) -> Result, String> { + if !is_msi { + return Ok(None); + } + let code = product_code.filter(|code| valid_product_code(code)).ok_or(UNKNOWN_CONTEXT)?; + match probe(code) { + Ok(scope) => Ok(Some(scope)), + Err(ProbeError::Conflicting) => Err(CONFLICTING_CONTEXT.into()), + Err(ProbeError::Unknown) => Err(UNKNOWN_CONTEXT.into()), + Err(ProbeError::Unavailable(reason)) => { + log::warn!("Windows Installer context lookup for {code} could not run: {reason}"); + let scope = record_scope(code).ok_or(UNKNOWN_CONTEXT)?; + log::info!("{code}: keeping the {scope:?} context of its uninstall record"); + Ok(Some(scope)) + } + } +} + +/// The one context every uninstall record of a product agrees on. Records that disagree (the copy is +/// registered for this account and for everyone) or no records at all give `None`, so the update stops. +pub fn single_scope(scopes: impl IntoIterator) -> Option { + let mut scopes = scopes.into_iter(); + let first = scopes.next()?; + scopes.all(|scope| scope == first).then_some(first) +} + +/// The context to install in. An update keeps `updated`, the context of the copy it replaces. A fresh +/// install (no copy at all) is machine-wide, so every app lands in `C:\Program Files\ArtCraft\` +/// (or the folder the person chose) and not in one account's profile; a dual-scope package would +/// otherwise take its own default, which is per-user. Windows asks for permission once, for that +/// install. Anything else (a copy that is not an MSI) takes the package's own default. +pub fn install_scope(updated: Option, fresh: bool) -> Option { + updated.or_else(|| fresh.then_some(MsiScope::PerMachine)) +} + +pub fn valid_product_code(code: &str) -> bool { + code.len() == 38 + && code.bytes().enumerate().all(|(index, byte)| match index { + 0 => byte == b'{', + 37 => byte == b'}', + 9 | 14 | 19 | 24 => byte == b'-', + _ => byte.is_ascii_hexdigit(), + }) +} + +fn parse_contexts(output: &str) -> Result { + let mut scope = None; + for line in output.lines().map(str::trim).filter(|line| !line.is_empty()) { + let context = match line { + "1" | "2" => MsiScope::PerUser, + "4" => MsiScope::PerMachine, + _ => return Err(ProbeError::Unknown), + }; + if scope.is_some_and(|previous| previous != context) { + return Err(ProbeError::Conflicting); + } + scope = Some(context); + } + scope.ok_or(ProbeError::Unknown) +} + +#[cfg(windows)] +pub fn probe(product_code: &str) -> Result { + use std::path::PathBuf; + use std::time::Duration; + + if !valid_product_code(product_code) { + return Err(ProbeError::Unknown); + } + let root = std::env::var_os("SystemRoot") + .map(PathBuf::from) + .filter(|root| root.is_absolute()) + .ok_or_else(|| ProbeError::Unavailable("SystemRoot is not set to an absolute path".into()))?; + let powershell = root.join(r"System32\WindowsPowerShell\v1.0\powershell.exe"); + // Only a validated GUID is interpolated. ProductsEx reads registration for the current + // account and the machine, never another account and never Win32_Product (which repairs). + let script = format!("$code='{product_code}';\n{}", include_str!("msi_context.ps1")); + let mut command = crate::process::command(powershell); + command.args(["-NoProfile", "-NonInteractive", "-Command", &script]); + let output = crate::process::run_command(command, "Windows installation lookup", Duration::from_secs(10)).map_err(ProbeError::Unavailable)?; + parse_contexts(&output) +} + +#[cfg(test)] +mod tests { + use super::*; + + const CODE: &str = "{12345678-1234-1234-1234-123456789ABC}"; + + #[test] + fn authoritative_machine_context_is_preserved() { + assert_eq!(parse_contexts("4\r\n"), Ok(MsiScope::PerMachine)); + } + + #[test] + fn managed_and_unmanaged_accounts_are_both_per_user() { + assert_eq!(parse_contexts("1\n"), Ok(MsiScope::PerUser)); + assert_eq!(parse_contexts("2\n"), Ok(MsiScope::PerUser)); + assert_eq!(parse_contexts("1\n2\n"), Ok(MsiScope::PerUser)); + } + + #[test] + fn missing_unknown_or_conflicting_contexts_are_not_guessed() { + for output in ["", " \r\n", "0", "7", "user", "2\n4", "4\n1", "4\nnoise"] { + assert!(parse_contexts(output).is_err(), "{output:?}"); + } + assert_eq!(parse_contexts("4\n1"), Err(ProbeError::Conflicting)); + assert_eq!(parse_contexts("7"), Err(ProbeError::Unknown)); + } + + #[test] + fn a_fresh_install_is_not_looked_up() { + assert_eq!(update_scope(false, None, |_| Err(ProbeError::Unknown), |_| None), Ok(None)); + } + + #[test] + fn known_updates_keep_the_authoritative_context() { + for scope in [MsiScope::PerUser, MsiScope::PerMachine] { + assert_eq!(update_scope(true, Some(CODE), |_| Ok(scope), |_| None), Ok(Some(scope))); + } + } + + #[test] + fn an_update_without_its_product_code_stops_before_probing() { + let called = std::cell::Cell::new(false); + assert!( + update_scope( + true, + None, + |_| { + called.set(true); + Ok(MsiScope::PerMachine) + }, + |_| None + ) + .is_err() + ); + assert!(!called.get()); + } + + #[test] + fn malformed_product_codes_stop_before_any_shell_call() { + for code in ["", "not-a-guid", "{12345678-1234-1234-1234-123456789ABZ}", "';exit 0;#", "{12345678-1234-1234-1234-123456789ABC}\n"] { + let called = std::cell::Cell::new(false); + assert!( + update_scope( + true, + Some(code), + |_| { + called.set(true); + Ok(MsiScope::PerMachine) + }, + |_| None + ) + .is_err() + ); + assert!(!called.get(), "{code:?}"); + } + } + + #[test] + fn unavailable_context_never_becomes_a_fresh_install() { + let unavailable = || Err(ProbeError::Unavailable("query failed".into())); + assert!(update_scope(true, Some(CODE), |_| unavailable(), |_| None).is_err()); + } + + #[test] + fn a_lookup_that_cannot_run_falls_back_to_the_uninstall_record() { + for scope in [MsiScope::PerUser, MsiScope::PerMachine] { + let seen = std::cell::RefCell::new(String::new()); + let result = update_scope( + true, + Some(CODE), + |_| Err(ProbeError::Unavailable("PowerShell is blocked".into())), + |code| { + *seen.borrow_mut() = code.to_owned(); + Some(scope) + }, + ); + assert_eq!(result, Ok(Some(scope))); + assert_eq!(*seen.borrow(), CODE); + } + } + + #[test] + fn an_answer_that_is_unclear_or_doubled_never_uses_the_uninstall_record() { + for failure in [ProbeError::Unknown, ProbeError::Conflicting] { + let result = update_scope(true, Some(CODE), |_| Err(failure), |_| panic!("must not consult the record")); + assert!(result.is_err()); + } + } + + #[test] + fn a_blocked_lookup_without_a_record_stops_the_update() { + let result = update_scope(true, Some(CODE), |_| Err(ProbeError::Unavailable("timed out".into())), |_| None); + assert_eq!(result, Err(UNKNOWN_CONTEXT.to_string())); + } + + #[test] + fn records_in_two_contexts_give_no_fallback_scope() { + assert_eq!(single_scope([]), None); + assert_eq!(single_scope([MsiScope::PerUser]), Some(MsiScope::PerUser)); + assert_eq!(single_scope([MsiScope::PerMachine, MsiScope::PerMachine]), Some(MsiScope::PerMachine)); + assert_eq!(single_scope([MsiScope::PerMachine, MsiScope::PerUser]), None); + assert_eq!(single_scope([MsiScope::PerUser, MsiScope::PerMachine, MsiScope::PerMachine]), None); + } + + #[test] + fn each_context_asks_the_package_for_itself() { + assert_eq!(scope_arguments(MsiScope::PerMachine), ["ALLUSERS=1"]); + assert_eq!(scope_arguments(MsiScope::PerUser), ["ALLUSERS=2", "MSIINSTALLPERUSER=1"]); + } + + #[test] + fn a_fresh_install_is_machine_wide() { + assert_eq!(install_scope(None, true), Some(MsiScope::PerMachine)); + } + + #[test] + fn an_update_keeps_the_context_of_the_copy_it_replaces() { + for scope in [MsiScope::PerUser, MsiScope::PerMachine] { + assert_eq!(install_scope(Some(scope), false), Some(scope)); + } + } + + #[test] + fn a_copy_that_is_not_an_msi_takes_the_package_default() { + assert_eq!(install_scope(None, false), None); + } +} diff --git a/crates/update/src/msi_copy.rs b/crates/update/src/msi_copy.rs new file mode 100644 index 000000000..4a629f4c9 --- /dev/null +++ b/crates/update/src/msi_copy.rs @@ -0,0 +1,252 @@ +//! Whether a running Windows copy was installed by its MSI, and the `msiexec` properties its +//! self-update needs to keep that copy's context. +//! +//! Every Craft App MSI registers its exe under `App Paths` (HKLM when installed for everyone, +//! HKCU for one account). A copy whose exe one of those entries names is an MSI copy, wherever its +//! folder is: `Program Files\ArtCraft\`, the older `Program Files\`, a folder the person +//! chose. Recognising it only reads the registry, so it is cheap enough for any status check. +//! +//! Which context to update in is a separate, slower question that only an update asks. Windows +//! Installer's own registration answers it ([`crate::msi_context`]), as it does for the launcher; +//! the `App Paths` hive is only the fallback when that lookup cannot run at all. So a copy +//! installed for everyone is never unpacked over without permission, and a per-user copy never +//! gains a second, per-machine twin. +//! +//! The launcher's own per-user MSI is still recognised by the folder it records in HKCU (or its +//! default folder) and updated exactly as before, with the package's own default context. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::path::{Path, PathBuf}; + +use crate::msi_context::MsiScope; + +/// How an MSI copy was recognised. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum MsiCopy { + /// An `App Paths` entry in the hive of `hive` names this exe. + Registered { hive: MsiScope }, + /// Entries in both hives name it: the update stops rather than guess. + Conflicting, + /// The launcher's own per-user package, found by its recorded or default folder. + Legacy, +} + +const CONFLICTING: &str = + "this app is registered both for your account and for everyone, so it can't tell which copy to update. Use the app's installer instead."; +const NOT_ONE_PRODUCT: &str = + "Windows lists this app's installation more than once or not at all, so it can't tell which copy to update. Use the app's installer instead."; + +/// The `msiexec` properties for `copy`'s update. `product_codes` are the app's Windows Installer +/// registrations; `probe` asks Windows Installer for one product's context. Exactly one product +/// must be registered: with two, either could be the copy that runs. +pub(crate) fn update_arguments( + copy: MsiCopy, + product_codes: &[String], + probe: impl FnOnce(&str) -> Result, +) -> Result<&'static [&'static str], String> { + let hive = match copy { + MsiCopy::Legacy => return Ok(&[]), + MsiCopy::Conflicting => return Err(CONFLICTING.into()), + MsiCopy::Registered { hive } => hive, + }; + let [code] = product_codes else { return Err(NOT_ONE_PRODUCT.into()) }; + let scope = crate::msi_context::update_scope(true, Some(code), probe, |_| Some(hive))?.ok_or(NOT_ONE_PRODUCT)?; + Ok(crate::msi_context::scope_arguments(scope)) +} + +/// Which registrations name `exe`. `registered` holds every `App Paths` target with the context +/// of the hive it came from; both sides are expected in one canonical form. +pub(crate) fn match_registration(exe: &Path, registered: &[(MsiScope, PathBuf)]) -> Option { + let mut hives = registered.iter().filter(|(_, target)| same_path(target, exe)).map(|(hive, _)| *hive); + let first = hives.next()?; + Some(if hives.all(|hive| hive == first) { MsiCopy::Registered { hive: first } } else { MsiCopy::Conflicting }) +} + +/// The one exe the app's registrations name after an update. The package may have moved an exact +/// old default folder, so the helper starts this rather than the path it was given. `None` unless +/// every registration names the same file. +pub(crate) fn registered_exe(registered: &[(MsiScope, PathBuf)]) -> Option { + let mut targets = registered.iter().map(|(_, target)| target); + let first = targets.next()?; + targets.all(|t| same_path(t, first)).then(|| first.clone()) +} + +/// Windows paths compare without regard to case. +fn same_path(a: &Path, b: &Path) -> bool { + a.as_os_str().to_string_lossy().eq_ignore_ascii_case(&b.as_os_str().to_string_lossy()) +} + +/// An `App Paths` default value as a path: Windows allows it in quotes. +pub(crate) fn app_path_value(value: &str) -> Option { + let value = value.trim().trim_matches('"').trim(); + (!value.is_empty()).then(|| PathBuf::from(value)) +} + +#[cfg(windows)] +pub(crate) mod windows { + use std::path::{Path, PathBuf}; + + use winreg::RegKey; + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY}; + + use super::{MsiCopy, MsiScope, app_path_value, match_registration}; + use crate::app::App; + + fn canonical(path: &Path) -> PathBuf { + dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) + } + + /// Every `App Paths` target registered for one of `app`'s exe names, with the context of its + /// hive. Entries naming a missing file are left out. + pub(crate) fn registered_exes(app: &App) -> Vec<(MsiScope, PathBuf)> { + let hives = [ + (HKEY_LOCAL_MACHINE, KEY_WOW64_64KEY, MsiScope::PerMachine), + (HKEY_LOCAL_MACHINE, KEY_WOW64_32KEY, MsiScope::PerMachine), + (HKEY_CURRENT_USER, 0, MsiScope::PerUser), + ]; + let mut out: Vec<(MsiScope, PathBuf)> = Vec::new(); + for stem in app.stems() { + let key = format!(r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{stem}.exe"); + for (hive, flags, scope) in hives { + let Ok(entry) = RegKey::predef(hive).open_subkey_with_flags(&key, KEY_READ | flags) else { continue }; + let Some(target) = entry.get_value::("").ok().as_deref().and_then(app_path_value) else { continue }; + if target.is_file() { + let target = canonical(&target); + if !out.iter().any(|(s, t)| *s == scope && *t == target) { + out.push((scope, target)); + } + } + } + } + out + } + + /// How `exe` was installed by an MSI, or `None` when it wasn't. Reads the registry only. + pub(crate) fn find(app: &App, exe: &Path) -> Option { + let exe = canonical(exe); + // The launcher first, so its own per-user updates are exactly as before. + if is_legacy(app, &exe) { + return Some(MsiCopy::Legacy); + } + match_registration(&exe, ®istered_exes(app)) + } + + /// The `msiexec` properties for `exe`'s update, asking Windows Installer for its context. + pub(crate) fn update_arguments(app: &App, exe: &Path) -> Result<&'static [&'static str], String> { + let copy = find(app, exe).ok_or_else(|| format!("{} isn't registered with the Windows Installer", app.name))?; + let codes: Vec = crate::detect::windows::msi_installs(app) + .into_iter() + .map(|m| m.product_code) + .filter(|code| crate::msi_context::valid_product_code(code)) + .collect(); + super::update_arguments(copy, &codes, crate::msi_context::probe) + } + + /// The launcher's own per-user MSI: the folder its wizard records in HKCU, or its default + /// `%LOCALAPPDATA%\Programs\`. + fn is_legacy(app: &App, exe: &Path) -> bool { + let Some(dir) = exe.parent() else { return false }; + let recorded = recorded_dir(app).map(|d| canonical(&d)); + let default = crate::folders::data_local_dir().map(|d| canonical(&d.join("Programs").join(app.name))); + [recorded, default].into_iter().flatten().any(|d| d == dir) + } + + fn recorded_dir(app: &App) -> Option { + let key = RegKey::predef(HKEY_CURRENT_USER).open_subkey(format!(r"Software\Learning Machines LLC\{}", app.name)).ok()?; + let dir: String = key.get_value("InstallDir").ok()?; + let dir = dir.trim(); + (!dir.is_empty()).then(|| PathBuf::from(dir)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::msi_context::ProbeError; + + const CODE: &str = "{500F5254-26F4-4AAA-B90D-6F3FD9947D14}"; + + fn p(s: &str) -> PathBuf { + PathBuf::from(s) + } + + fn codes(list: &[&str]) -> Vec { + list.iter().map(|c| c.to_string()).collect() + } + + #[test] + fn a_registration_makes_an_msi_copy_wherever_its_folder_is() { + let registered = [(MsiScope::PerMachine, p(r"C:\Program Files\GridCraft\gridcraft.exe"))]; + let copy = Some(MsiCopy::Registered { hive: MsiScope::PerMachine }); + assert_eq!(match_registration(&p(r"C:\Program Files\GridCraft\gridcraft.exe"), ®istered), copy); + assert_eq!(match_registration(&p(r"c:\program files\gridcraft\GRIDCRAFT.EXE"), ®istered), copy); + let user = [(MsiScope::PerUser, p(r"D:\Chosen\GridCraft\gridcraft.exe"))]; + assert_eq!(match_registration(&p(r"D:\Chosen\GridCraft\gridcraft.exe"), &user), Some(MsiCopy::Registered { hive: MsiScope::PerUser })); + } + + #[test] + fn an_exe_no_registration_names_is_not_an_msi_copy() { + let registered = [(MsiScope::PerMachine, p(r"C:\Program Files\ArtCraft\GridCraft\gridcraft.exe"))]; + assert_eq!(match_registration(&p(r"D:\Tools\GridCraft\gridcraft.exe"), ®istered), None); + assert_eq!(match_registration(&p(r"D:\Tools\GridCraft\gridcraft.exe"), &[]), None); + } + + #[test] + fn a_copy_registered_in_both_hives_stops_before_any_lookup() { + let exe = p(r"C:\Program Files\ArtCraft\GridCraft\gridcraft.exe"); + let copy = match_registration(&exe, &[(MsiScope::PerMachine, exe.clone()), (MsiScope::PerUser, exe.clone())]).unwrap(); + assert_eq!(copy, MsiCopy::Conflicting); + assert!(update_arguments(copy, &codes(&[CODE]), |_| panic!("must not look up")).is_err()); + } + + #[test] + fn windows_installer_decides_the_context_not_the_hive() { + let copy = MsiCopy::Registered { hive: MsiScope::PerUser }; + assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerMachine)).unwrap(), ["ALLUSERS=1"]); + let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; + assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerUser)).unwrap(), ["ALLUSERS=2", "MSIINSTALLPERUSER=1"]); + } + + #[test] + fn the_hive_is_only_the_fallback_when_the_lookup_cannot_run() { + let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; + let blocked = |_: &str| Err(ProbeError::Unavailable("PowerShell is blocked".into())); + assert_eq!(update_arguments(copy, &codes(&[CODE]), blocked).unwrap(), ["ALLUSERS=1"]); + for unclear in [ProbeError::Unknown, ProbeError::Conflicting] { + assert!(update_arguments(copy, &codes(&[CODE]), |_| Err(unclear)).is_err()); + } + } + + #[test] + fn the_update_stops_unless_exactly_one_product_is_registered() { + let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; + assert!(update_arguments(copy, &[], |_| panic!("must not look up")).is_err()); + let two = codes(&[CODE, "{0BE5923F-1AAB-4240-8174-2F0CCC05E14C}"]); + assert!(update_arguments(copy, &two, |_| panic!("must not look up")).is_err()); + } + + #[test] + fn the_launchers_own_package_keeps_its_default() { + assert!(update_arguments(MsiCopy::Legacy, &[], |_| panic!("must not look up")).unwrap().is_empty()); + } + + #[test] + fn the_helper_restarts_the_one_exe_the_registrations_name() { + let moved = p(r"C:\Program Files\ArtCraft\GridCraft\gridcraft.exe"); + assert_eq!(registered_exe(&[(MsiScope::PerMachine, moved.clone())]), Some(moved.clone())); + assert_eq!(registered_exe(&[(MsiScope::PerMachine, moved.clone()), (MsiScope::PerUser, moved.clone())]), Some(moved)); + assert_eq!(registered_exe(&[]), None); + let two = [(MsiScope::PerMachine, p(r"C:\a\gridcraft.exe")), (MsiScope::PerUser, p(r"C:\b\gridcraft.exe"))]; + assert_eq!(registered_exe(&two), None); + } + + #[test] + fn app_paths_values_may_be_quoted() { + assert_eq!( + app_path_value(r#""C:\Program Files\ArtCraft\GridCraft\gridcraft.exe""#), + Some(p(r"C:\Program Files\ArtCraft\GridCraft\gridcraft.exe")) + ); + assert_eq!(app_path_value(" "), None); + } +} diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index f22dfb35a..7382b6f6c 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -9,7 +9,7 @@ //! | Installed as | Swap | //! |---|---| //! | macOS `.app` | copy the new bundle from the DMG over this one (fine while running), reopen it | -//! | Windows MSI (per-user, any folder) | after exit, run the new MSI (it reinstalls into the same folder), then start the exe | +//! | Windows MSI (any folder, for one account or everyone) | after exit, run the new MSI in the copy's own context (everyone asks for permission), then start the exe it registers | //! | Windows portable zip | after exit, unzip over this folder (settings in `ArtCraftLauncherData` stay) | //! | Linux AppImage | rename the new AppImage over this one (fine while running), start it | //! | Linux `.deb` / `.rpm` | the system package manager, with the password prompt; then restart | @@ -188,12 +188,9 @@ fn detect(app: &App, exe: &Path) -> Option { if dir.join("portable.txt").is_file() { return Some(Install::Portable(exe.to_path_buf())); } - // The MSI installs per user, into the folder chosen in its wizard (which it records in the - // registry) or by default %LOCALAPPDATA%\Programs\. - let canonical = |p: PathBuf| p.canonicalize().unwrap_or(p); - let recorded = msi_install_dir(app).map(canonical); - let default = crate::folders::data_local_dir().map(|d| canonical(d.join("Programs").join(app.name))); - if [recorded, default].into_iter().flatten().any(|d| d == dir) { + // Any folder, either context: the MSI's own registration says so (see `msi_copy`). A copy + // installed for everyone must never be unpacked over as if it were a loose folder. + if crate::msi_copy::windows::find(app, exe).is_some() { return Some(Install::Msi(exe.to_path_buf())); } if exe.is_file() { @@ -202,16 +199,22 @@ fn detect(app: &App, exe: &Path) -> Option { None } -/// The folder the MSI installed into, as it records it. +/// The `msiexec` properties that keep `exe`'s Windows Installer context, or why its update stops. +/// Asked while the app still runs (so it can show the error) and again by the helper. #[cfg(windows)] -fn msi_install_dir(app: &App) -> Option { - use winreg::RegKey; - use winreg::enums::HKEY_CURRENT_USER; - let subkey = format!(r"Software\Learning Machines LLC\{}", app.name); - let key = RegKey::predef(HKEY_CURRENT_USER).open_subkey(&subkey).ok()?; - let dir: String = key.get_value("InstallDir").ok()?; - let dir = dir.trim(); - (!dir.is_empty()).then(|| PathBuf::from(dir)) +fn msi_arguments(app: &App, exe: &Path) -> Result<&'static [&'static str], String> { + crate::msi_copy::windows::update_arguments(app, exe) +} + +/// The exe to start after an MSI update of a registered copy: the one its registrations name now +/// (the package may have moved an exact old default folder), else `exe`. +#[cfg(windows)] +fn exe_after_msi(app: &App, registered: bool, exe: &Path) -> PathBuf { + registered + .then(|| crate::msi_copy::registered_exe(&crate::msi_copy::windows::registered_exes(app))) + .flatten() + .filter(|moved| is_own_executable(app, moved)) + .unwrap_or_else(|| exe.to_path_buf()) } #[cfg(target_os = "linux")] @@ -628,11 +631,15 @@ pub fn finish(app: &App, args: &[OsString]) -> Option> { record_failure(&paths, &e); return Some(Err(e)); } + // Read before the step: the update may move or replace the old exe. + let registered = + matches!(step, Finish::Msi(_)) && matches!(crate::msi_copy::windows::find(app, &exe), Some(crate::msi_copy::MsiCopy::Registered { .. })); let done = run_step(app, &me, pid, &exe, &step, std::time::Duration::from_secs(60)); if let Err(e) = &done { record_failure(&paths, e); } // The new app, or the old one when the step failed. + let exe = if done.is_ok() { exe_after_msi(app, registered, &exe) } else { exe }; let started = signed_like(app, &me, &exe) .and_then(|()| process::spawn_detached(std::process::Command::new(&exe)).map_err(|e| format!("couldn't start {} ({e})", exe.display()))); if let Err(e) = &started { @@ -688,6 +695,7 @@ fn windows_precheck(app: &App, install: &Install, paths: &Paths, download: &Path let me = std::env::current_exe().map_err(|e| format!("couldn't find this program ({e})"))?; match install { Install::Msi(exe) => signed_like(app, &me, exe) + .and_then(|()| msi_arguments(app, exe).map(drop)) .and_then(|()| signed_like(app, &me, download)) .and_then(|()| own_executable(app, exe)) .and_then(|()| same_cache_as_helper(app, paths, exe)), @@ -824,7 +832,9 @@ fn run_step(app: &App, reference: &Path, pid: u32, exe: &Path, step: &Finish, wa wait_watch::returned(pid, waited); let result = if waited { match step { - Finish::Msi(msi) => signed_like(app, reference, msi).and_then(|()| install::windows::reinstall(msi)), + Finish::Msi(msi) => signed_like(app, reference, msi) + .and_then(|()| msi_arguments(app, exe)) + .and_then(|arguments| install::windows::reinstall(msi, arguments)), Finish::Portable { zip, tmp } => match (exe.parent(), exe.file_name()) { (Some(dir), Some(executable)) => crate::portable::unpack_over(zip, tmp, dir, executable, &|file| { // The expected executable must be signed even when its contents aren't a PE file. From 7898779169413d8299066dac1525263e9c5dd4ef Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 12:21:27 +0000 Subject: [PATCH 2/7] craft-update: a copy only takes the Windows Installer context of its own hive Review follow-up (CodeRabbit on #419). The product code for the context lookup came from the app's only uninstall record, which was not proven to own the running exe. A package writes App Paths under HKMU, always the hive of its own context, so a registration whose Windows Installer context differs from the hive that named this exe belongs to another copy. The update now stops then, instead of taking the other copy's context. Also documents the remaining helpers the diff touches. Co-Authored-By: Claude Opus 5.5 --- crates/update/src/msi_context.rs | 6 ++++++ crates/update/src/msi_copy.rs | 32 +++++++++++++++++++++++++------- crates/update/src/self_update.rs | 2 ++ 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/update/src/msi_context.rs b/crates/update/src/msi_context.rs index 9819bde0c..b51c2eedd 100644 --- a/crates/update/src/msi_context.rs +++ b/crates/update/src/msi_context.rs @@ -85,6 +85,8 @@ pub fn install_scope(updated: Option, fresh: bool) -> Option updated.or_else(|| fresh.then_some(MsiScope::PerMachine)) } +/// Whether `code` is a braced Windows Installer product GUID, the only text ever placed in the +/// lookup script. pub fn valid_product_code(code: &str) -> bool { code.len() == 38 && code.bytes().enumerate().all(|(index, byte)| match index { @@ -95,6 +97,8 @@ pub fn valid_product_code(code: &str) -> bool { }) } +/// The one context in the lookup's output (one `MSIINSTALLCONTEXT` number per line): 1 and 2 are +/// an account (managed or not), 4 the machine. Anything else is unclear, and two contexts conflict. fn parse_contexts(output: &str) -> Result { let mut scope = None; for line in output.lines().map(str::trim).filter(|line| !line.is_empty()) { @@ -111,6 +115,8 @@ fn parse_contexts(output: &str) -> Result { scope.ok_or(ProbeError::Unknown) } +/// Asks Windows Installer, read-only, which context `product_code` is installed in, for this +/// account and the machine. Runs PowerShell with a 10 second limit. #[cfg(windows)] pub fn probe(product_code: &str) -> Result { use std::path::PathBuf; diff --git a/crates/update/src/msi_copy.rs b/crates/update/src/msi_copy.rs index 4a629f4c9..30396b4c8 100644 --- a/crates/update/src/msi_copy.rs +++ b/crates/update/src/msi_copy.rs @@ -8,9 +8,11 @@ //! //! Which context to update in is a separate, slower question that only an update asks. Windows //! Installer's own registration answers it ([`crate::msi_context`]), as it does for the launcher; -//! the `App Paths` hive is only the fallback when that lookup cannot run at all. So a copy -//! installed for everyone is never unpacked over without permission, and a per-user copy never -//! gains a second, per-machine twin. +//! the `App Paths` hive is only the fallback when that lookup cannot run at all. The answer must +//! match the hive that named this exe: a package writes `App Paths` under `HKMU`, which is always +//! the hive of its own context, so a registration in the other context belongs to another copy and +//! the update stops. So a copy installed for everyone is never unpacked over without permission, +//! and a per-user copy never gains a second, per-machine twin or takes another copy's context. //! //! The launcher's own per-user MSI is still recognised by the folder it records in HKCU (or its //! default folder) and updated exactly as before, with the package's own default context. @@ -34,12 +36,14 @@ pub(crate) enum MsiCopy { const CONFLICTING: &str = "this app is registered both for your account and for everyone, so it can't tell which copy to update. Use the app's installer instead."; +const ANOTHER_COPY: &str = "Windows lists this app for a different account setting than this copy, so it can't be sure which copy it would update. Use the app's installer instead."; const NOT_ONE_PRODUCT: &str = "Windows lists this app's installation more than once or not at all, so it can't tell which copy to update. Use the app's installer instead."; /// The `msiexec` properties for `copy`'s update. `product_codes` are the app's Windows Installer /// registrations; `probe` asks Windows Installer for one product's context. Exactly one product -/// must be registered: with two, either could be the copy that runs. +/// must be registered: with two, either could be the copy that runs. Its context must be the +/// context of the hive that named this exe, or the registration is another copy's. pub(crate) fn update_arguments( copy: MsiCopy, product_codes: &[String], @@ -52,6 +56,9 @@ pub(crate) fn update_arguments( }; let [code] = product_codes else { return Err(NOT_ONE_PRODUCT.into()) }; let scope = crate::msi_context::update_scope(true, Some(code), probe, |_| Some(hive))?.ok_or(NOT_ONE_PRODUCT)?; + if scope != hive { + return Err(ANOTHER_COPY.into()); + } Ok(crate::msi_context::scope_arguments(scope)) } @@ -93,6 +100,8 @@ pub(crate) mod windows { use super::{MsiCopy, MsiScope, app_path_value, match_registration}; use crate::app::App; + /// `path` with links and `..` resolved in ordinary drive syntax, or as given when it cannot be + /// resolved, so registry values and the running exe compare in one form. fn canonical(path: &Path) -> PathBuf { dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) } @@ -152,6 +161,7 @@ pub(crate) mod windows { [recorded, default].into_iter().flatten().any(|d| d == dir) } + /// The install folder the launcher's per-user wizard records in HKCU, when it recorded one. fn recorded_dir(app: &App) -> Option { let key = RegKey::predef(HKEY_CURRENT_USER).open_subkey(format!(r"Software\Learning Machines LLC\{}", app.name)).ok()?; let dir: String = key.get_value("InstallDir").ok()?; @@ -201,13 +211,21 @@ mod tests { } #[test] - fn windows_installer_decides_the_context_not_the_hive() { - let copy = MsiCopy::Registered { hive: MsiScope::PerUser }; - assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerMachine)).unwrap(), ["ALLUSERS=1"]); + fn windows_installer_confirms_the_context_of_the_hive_that_named_the_exe() { let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; + assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerMachine)).unwrap(), ["ALLUSERS=1"]); + let copy = MsiCopy::Registered { hive: MsiScope::PerUser }; assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerUser)).unwrap(), ["ALLUSERS=2", "MSIINSTALLPERUSER=1"]); } + #[test] + fn a_registration_in_the_other_context_is_another_copys_and_stops_the_update() { + for (hive, other) in [(MsiScope::PerUser, MsiScope::PerMachine), (MsiScope::PerMachine, MsiScope::PerUser)] { + let error = update_arguments(MsiCopy::Registered { hive }, &codes(&[CODE]), |_| Ok(other)).unwrap_err(); + assert_eq!(error, ANOTHER_COPY); + } + } + #[test] fn the_hive_is_only_the_fallback_when_the_lookup_cannot_run() { let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index 7382b6f6c..a3b3bc4c4 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -182,6 +182,8 @@ fn detect(app: &App, exe: &Path) -> Option { None } +/// How the Windows copy at `exe` was installed: portable (a `portable.txt` beside it), by its MSI +/// (registered in either context, or the launcher's own per-user package), else a loose folder. #[cfg(windows)] fn detect(app: &App, exe: &Path) -> Option { let dir = exe.parent()?; From 1e0196487196385aa1b74c2890e08250e0967e77 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 12:36:08 +0000 Subject: [PATCH 3/7] craft-update: an app in the old per-user folder is judged by its registration first Review follow-up (CodeRabbit on #419). The folder rule for the launcher's per-user package also matched an app installed in %LOCALAPPDATA%\Programs\, and it ran before the App Paths check, so such a copy skipped the product-count, conflict and context checks. Now an app is judged by its registration first; the folder rule only covers an app copy no registration names. The launcher in its own folder still keeps its old path whatever is registered: on a real PC it has an App Paths entry and a stale second uninstall record, and registration-first would have stopped its self-update. Co-Authored-By: Claude Opus 5.5 --- crates/update/src/msi_copy.rs | 39 +++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/update/src/msi_copy.rs b/crates/update/src/msi_copy.rs index 30396b4c8..9c2af1bac 100644 --- a/crates/update/src/msi_copy.rs +++ b/crates/update/src/msi_copy.rs @@ -15,7 +15,8 @@ //! and a per-user copy never gains a second, per-machine twin or takes another copy's context. //! //! The launcher's own per-user MSI is still recognised by the folder it records in HKCU (or its -//! default folder) and updated exactly as before, with the package's own default context. +//! default folder) and updated exactly as before, with the package's own default context. An app +//! copy in that kind of folder is judged by its registration first ([`classify`]). #![cfg_attr(not(windows), allow(dead_code))] @@ -62,6 +63,18 @@ pub(crate) fn update_arguments( Ok(crate::msi_context::scope_arguments(scope)) } +/// How a copy was installed, from what is known about it. The launcher's own per-user package in +/// its recorded or default folder keeps its update exactly as before, whatever else is registered +/// (a stale second record must not stop it). An app is judged by its `App Paths` registration +/// first, so a registered copy always passes the context checks; the folder rule only covers an +/// app copy that no registration names. `registration` is only read when it can decide. +pub(crate) fn classify(is_launcher: bool, in_legacy_folder: bool, registration: impl FnOnce() -> Option) -> Option { + if is_launcher && in_legacy_folder { + return Some(MsiCopy::Legacy); + } + registration().or_else(|| in_legacy_folder.then_some(MsiCopy::Legacy)) +} + /// Which registrations name `exe`. `registered` holds every `App Paths` target with the context /// of the hive it came from; both sides are expected in one canonical form. pub(crate) fn match_registration(exe: &Path, registered: &[(MsiScope, PathBuf)]) -> Option { @@ -134,11 +147,8 @@ pub(crate) mod windows { /// How `exe` was installed by an MSI, or `None` when it wasn't. Reads the registry only. pub(crate) fn find(app: &App, exe: &Path) -> Option { let exe = canonical(exe); - // The launcher first, so its own per-user updates are exactly as before. - if is_legacy(app, &exe) { - return Some(MsiCopy::Legacy); - } - match_registration(&exe, ®istered_exes(app)) + let is_launcher = app.id == crate::suite::LAUNCHER.id; + super::classify(is_launcher, is_legacy(app, &exe), || match_registration(&exe, ®istered_exes(app))) } /// The `msiexec` properties for `exe`'s update, asking Windows Installer for its context. @@ -244,6 +254,23 @@ mod tests { assert!(update_arguments(copy, &two, |_| panic!("must not look up")).is_err()); } + #[test] + fn the_launcher_in_its_own_folder_keeps_its_old_path_whatever_is_registered() { + let registered = Some(MsiCopy::Registered { hive: MsiScope::PerUser }); + assert_eq!(classify(true, true, || registered), Some(MsiCopy::Legacy)); + assert_eq!(classify(true, false, || registered), registered); + assert_eq!(classify(true, false, || None), None); + } + + #[test] + fn an_app_in_the_old_per_user_folder_is_judged_by_its_registration_first() { + for registered in [MsiCopy::Registered { hive: MsiScope::PerUser }, MsiCopy::Conflicting] { + assert_eq!(classify(false, true, || Some(registered)), Some(registered)); + } + assert_eq!(classify(false, true, || None), Some(MsiCopy::Legacy)); + assert_eq!(classify(false, false, || None), None); + } + #[test] fn the_launchers_own_package_keeps_its_default() { assert!(update_arguments(MsiCopy::Legacy, &[], |_| panic!("must not look up")).unwrap().is_empty()); From cd7cc8eb398f5e04e17eb97b1febc5f922fef8a1 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 12:51:39 +0000 Subject: [PATCH 4/7] craft-update: when the Windows Installer lookup cannot run, the uninstall records decide Review follow-up (CodeRabbit on #419). The fallback trusted the App Paths hive, so a stale entry or a product registered in both scopes could run the update in the wrong context. The fallback now follows the launcher's rule: the context every uninstall record of the product agrees on (msi_context::single_scope over HKLM in both views and HKCU). Missing or mixed records stop the update, and an agreed context that differs from the App Paths hive still stops it as another copy's registration. Co-Authored-By: Claude Opus 5.5 --- crates/update/src/msi_copy.rs | 73 +++++++++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 16 deletions(-) diff --git a/crates/update/src/msi_copy.rs b/crates/update/src/msi_copy.rs index 9c2af1bac..05e1ca3ff 100644 --- a/crates/update/src/msi_copy.rs +++ b/crates/update/src/msi_copy.rs @@ -8,7 +8,8 @@ //! //! Which context to update in is a separate, slower question that only an update asks. Windows //! Installer's own registration answers it ([`crate::msi_context`]), as it does for the launcher; -//! the `App Paths` hive is only the fallback when that lookup cannot run at all. The answer must +//! only when that lookup cannot run at all do the product's own uninstall records answer, and +//! only when they all agree. The answer must //! match the hive that named this exe: a package writes `App Paths` under `HKMU`, which is always //! the hive of its own context, so a registration in the other context belongs to another copy and //! the update stops. So a copy installed for everyone is never unpacked over without permission, @@ -42,13 +43,16 @@ const NOT_ONE_PRODUCT: &str = "Windows lists this app's installation more than once or not at all, so it can't tell which copy to update. Use the app's installer instead."; /// The `msiexec` properties for `copy`'s update. `product_codes` are the app's Windows Installer -/// registrations; `probe` asks Windows Installer for one product's context. Exactly one product -/// must be registered: with two, either could be the copy that runs. Its context must be the -/// context of the hive that named this exe, or the registration is another copy's. +/// registrations; `probe` asks Windows Installer for one product's context, and `record_scopes` +/// lists the context of every uninstall record of that product, read only when the lookup cannot +/// run. Exactly one product must be registered: with two, either could be the copy that runs. The +/// records must agree on one context. Whichever answers, it must be the context of the hive that +/// named this exe, or the registration is another copy's. pub(crate) fn update_arguments( copy: MsiCopy, product_codes: &[String], probe: impl FnOnce(&str) -> Result, + record_scopes: impl FnOnce(&str) -> Vec, ) -> Result<&'static [&'static str], String> { let hive = match copy { MsiCopy::Legacy => return Ok(&[]), @@ -56,7 +60,8 @@ pub(crate) fn update_arguments( MsiCopy::Registered { hive } => hive, }; let [code] = product_codes else { return Err(NOT_ONE_PRODUCT.into()) }; - let scope = crate::msi_context::update_scope(true, Some(code), probe, |_| Some(hive))?.ok_or(NOT_ONE_PRODUCT)?; + let fallback = |code: &str| crate::msi_context::single_scope(record_scopes(code)); + let scope = crate::msi_context::update_scope(true, Some(code), probe, fallback)?.ok_or(NOT_ONE_PRODUCT)?; if scope != hive { return Err(ANOTHER_COPY.into()); } @@ -159,7 +164,26 @@ pub(crate) mod windows { .map(|m| m.product_code) .filter(|code| crate::msi_context::valid_product_code(code)) .collect(); - super::update_arguments(copy, &codes, crate::msi_context::probe) + super::update_arguments(copy, &codes, crate::msi_context::probe, record_scopes) + } + + /// The context of every uninstall record of `code`: the machine's (both registry views) are + /// per-machine, the account's own per-user. Two views of one machine record count once. + fn record_scopes(code: &str) -> Vec { + const UNINSTALL: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; + let roots = [ + (HKEY_LOCAL_MACHINE, KEY_WOW64_64KEY, MsiScope::PerMachine), + (HKEY_LOCAL_MACHINE, KEY_WOW64_32KEY, MsiScope::PerMachine), + (HKEY_CURRENT_USER, 0, MsiScope::PerUser), + ]; + let mut scopes = Vec::new(); + for (hive, flags, scope) in roots { + let found = RegKey::predef(hive).open_subkey_with_flags(format!(r"{UNINSTALL}\{code}"), KEY_READ | flags).is_ok(); + if found && !scopes.contains(&scope) { + scopes.push(scope); + } + } + scopes } /// The launcher's own per-user MSI: the folder its wizard records in HKCU, or its default @@ -217,41 +241,58 @@ mod tests { let exe = p(r"C:\Program Files\ArtCraft\GridCraft\gridcraft.exe"); let copy = match_registration(&exe, &[(MsiScope::PerMachine, exe.clone()), (MsiScope::PerUser, exe.clone())]).unwrap(); assert_eq!(copy, MsiCopy::Conflicting); - assert!(update_arguments(copy, &codes(&[CODE]), |_| panic!("must not look up")).is_err()); + assert!(update_arguments(copy, &codes(&[CODE]), |_| panic!("must not look up"), |_| panic!("must not read the records")).is_err()); } #[test] fn windows_installer_confirms_the_context_of_the_hive_that_named_the_exe() { let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; - assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerMachine)).unwrap(), ["ALLUSERS=1"]); + assert_eq!( + update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerMachine), |_| panic!("must not read the records")).unwrap(), + ["ALLUSERS=1"] + ); let copy = MsiCopy::Registered { hive: MsiScope::PerUser }; - assert_eq!(update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerUser)).unwrap(), ["ALLUSERS=2", "MSIINSTALLPERUSER=1"]); + assert_eq!( + update_arguments(copy, &codes(&[CODE]), |_| Ok(MsiScope::PerUser), |_| panic!("must not read the records")).unwrap(), + ["ALLUSERS=2", "MSIINSTALLPERUSER=1"] + ); } #[test] fn a_registration_in_the_other_context_is_another_copys_and_stops_the_update() { for (hive, other) in [(MsiScope::PerUser, MsiScope::PerMachine), (MsiScope::PerMachine, MsiScope::PerUser)] { - let error = update_arguments(MsiCopy::Registered { hive }, &codes(&[CODE]), |_| Ok(other)).unwrap_err(); + let error = + update_arguments(MsiCopy::Registered { hive }, &codes(&[CODE]), |_| Ok(other), |_| panic!("must not read the records")).unwrap_err(); assert_eq!(error, ANOTHER_COPY); } } #[test] - fn the_hive_is_only_the_fallback_when_the_lookup_cannot_run() { + fn the_uninstall_records_answer_only_when_the_lookup_cannot_run() { let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; let blocked = |_: &str| Err(ProbeError::Unavailable("PowerShell is blocked".into())); - assert_eq!(update_arguments(copy, &codes(&[CODE]), blocked).unwrap(), ["ALLUSERS=1"]); + assert_eq!(update_arguments(copy, &codes(&[CODE]), blocked, |_| vec![MsiScope::PerMachine]).unwrap(), ["ALLUSERS=1"]); for unclear in [ProbeError::Unknown, ProbeError::Conflicting] { - assert!(update_arguments(copy, &codes(&[CODE]), |_| Err(unclear)).is_err()); + assert!(update_arguments(copy, &codes(&[CODE]), |_| Err(unclear), |_| panic!("must not read the records")).is_err()); } } + #[test] + fn missing_mixed_or_mismatched_records_stop_the_fallback() { + let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; + let blocked = |_: &str| Err(ProbeError::Unavailable("PowerShell is blocked".into())); + assert!(update_arguments(copy, &codes(&[CODE]), blocked, |_| vec![]).is_err()); + assert!(update_arguments(copy, &codes(&[CODE]), blocked, |_| vec![MsiScope::PerMachine, MsiScope::PerUser]).is_err()); + let error = update_arguments(copy, &codes(&[CODE]), blocked, |_| vec![MsiScope::PerUser]).unwrap_err(); + assert_eq!(error, ANOTHER_COPY); + } + #[test] fn the_update_stops_unless_exactly_one_product_is_registered() { let copy = MsiCopy::Registered { hive: MsiScope::PerMachine }; - assert!(update_arguments(copy, &[], |_| panic!("must not look up")).is_err()); + assert!(update_arguments(copy, &[], |_| panic!("must not look up"), |_| panic!("must not read the records")).is_err()); let two = codes(&[CODE, "{0BE5923F-1AAB-4240-8174-2F0CCC05E14C}"]); - assert!(update_arguments(copy, &two, |_| panic!("must not look up")).is_err()); + assert!(update_arguments(copy, &two, |_| panic!("must not look up"), |_| panic!("must not read the records")).is_err()); } #[test] @@ -273,7 +314,7 @@ mod tests { #[test] fn the_launchers_own_package_keeps_its_default() { - assert!(update_arguments(MsiCopy::Legacy, &[], |_| panic!("must not look up")).unwrap().is_empty()); + assert!(update_arguments(MsiCopy::Legacy, &[], |_| panic!("must not look up"), |_| panic!("must not read the records")).unwrap().is_empty()); } #[test] From 2e2e8f8daa8f403e2872e3605b973b87edca9f88 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 13:14:18 +0000 Subject: [PATCH 5/7] craft-update: an app installed for one account moves to an install for everyone on its update Temporary (craft-libs#422, step 4): new msi_migrate module, to be removed two releases after the app packages become per-machine only. The released packages refuse a per-machine install while a per-user copy exists, so the move removes first and installs second: remove the per-user product (no permission prompt; if that fails nothing has changed), install the new version for everyone, and if that fails or permission is refused, install the new version for the account again in its old folder. Settings and documents live outside the program folder and are never touched. Which copies move: a per-user default folder goes to Program Files\ArtCraft\; a chosen folder outside the profile moves in place; a chosen folder inside the profile keeps updating for the account. The launcher's own package never moves. Tested with real Windows Installer runs of a renamed dual-scope package carrying the apps' own install-policy.wxi: the move with the permission prompt accepted (twice), and with it refused (the app came back for the account at the new version, the failed log kept). Also unit tests for every plan and the order of steps, and a mutation check (9 of 9 killed). Co-Authored-By: Claude Opus 5.5 --- crates/update/src/install.rs | 28 +++- crates/update/src/lib.rs | 1 + crates/update/src/msi_copy.rs | 25 ++- crates/update/src/msi_migrate.rs | 270 +++++++++++++++++++++++++++++++ crates/update/src/self_update.rs | 16 +- 5 files changed, 322 insertions(+), 18 deletions(-) create mode 100644 crates/update/src/msi_migrate.rs diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 7c9e773ee..5f1f7ff32 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -1656,7 +1656,7 @@ fn reinstall_command(program: &Path, msi: &Path, context: &[&str]) -> Result PathBuf { +pub(crate) fn msi_log(msi: &Path) -> PathBuf { msi.with_extension("log") } @@ -1713,9 +1713,15 @@ pub mod windows { /// Runs an app's own new MSI for a self-update, with the same progress window and no restart /// as [`run_msi`], and waits for it. `context` keeps the installed copy's Windows Installer - /// context. A failure names the installer's log, which is the only place 1603 is explained. - pub fn reinstall(msi: &Path, context: &[&str]) -> Result<(), String> { - let status = reinstall_command(&msiexec(), msi, context)?.status().map_err(|e| format!("couldn't start the Windows Installer ({e})"))?; + /// context; `folder`, when given, is where it goes. A failure names the installer's log, + /// which is the only place 1603 is explained. + pub fn reinstall(msi: &Path, context: &[&str], folder: Option<&Path>) -> Result<(), String> { + use std::os::windows::process::CommandExt; + let mut command = reinstall_command(&msiexec(), msi, context)?; + if let Some(dir) = folder { + command.raw_arg(msi_folder_argument(dir)?); + } + let status = command.status().map_err(|e| format!("couldn't start the Windows Installer ({e})"))?; explain(status.code()).map_err(|e| match status.code() { Some(1602) | None => e, _ => format!("{e}. Its log is at {}", msi_log(msi).display()), @@ -1728,6 +1734,20 @@ pub mod windows { INSTALLER.alone(&cancelled(stop), &mut turn(phase, working), work).unwrap_or_else(|| Err(CANCELLED.into())) } + /// Removes one installed product by its code, with a progress window and no restart, and waits. + /// A per-user product asks for no permission. `log` receives the installer's verbose log. + pub fn remove_product(product_code: &str, log: &Path) -> Result<(), String> { + if !crate::msi_context::valid_product_code(product_code) { + return Err(format!("{product_code} isn't a Windows Installer product code")); + } + let status = process::command(msiexec()) + .args(["/x", product_code, "/passive", "/norestart", "/l*v"]) + .arg(log) + .status() + .map_err(|e| format!("couldn't start the Windows Installer ({e})"))?; + explain(status.code()).map_err(|e| format!("{e}. Its log is at {}", log.display())) + } + pub fn uninstall_msi(app: &App, stop: &Stop, phase: &mut dyn FnMut(JobPhase)) -> Result<(), String> { let installs = crate::detect::windows::msi_installs(app); if installs.is_empty() { diff --git a/crates/update/src/lib.rs b/crates/update/src/lib.rs index 58bb0e946..40a5825a2 100644 --- a/crates/update/src/lib.rs +++ b/crates/update/src/lib.rs @@ -12,6 +12,7 @@ pub mod install; pub mod manifest; pub mod msi_context; mod msi_copy; +mod msi_migrate; pub mod packages; pub mod paths; pub mod platform; diff --git a/crates/update/src/msi_copy.rs b/crates/update/src/msi_copy.rs index 05e1ca3ff..a78ad435d 100644 --- a/crates/update/src/msi_copy.rs +++ b/crates/update/src/msi_copy.rs @@ -42,20 +42,32 @@ const ANOTHER_COPY: &str = "Windows lists this app for a different account setti const NOT_ONE_PRODUCT: &str = "Windows lists this app's installation more than once or not at all, so it can't tell which copy to update. Use the app's installer instead."; -/// The `msiexec` properties for `copy`'s update. `product_codes` are the app's Windows Installer +/// The `msiexec` properties for `copy`'s update (as [`crate::msi_migrate`] uses them). `product_codes` are the app's Windows Installer /// registrations; `probe` asks Windows Installer for one product's context, and `record_scopes` /// lists the context of every uninstall record of that product, read only when the lookup cannot /// run. Exactly one product must be registered: with two, either could be the copy that runs. The /// records must agree on one context. Whichever answers, it must be the context of the hive that /// named this exe, or the registration is another copy's. +#[cfg(test)] pub(crate) fn update_arguments( copy: MsiCopy, product_codes: &[String], probe: impl FnOnce(&str) -> Result, record_scopes: impl FnOnce(&str) -> Vec, ) -> Result<&'static [&'static str], String> { + Ok(resolve(copy, product_codes, probe, record_scopes)?.map_or(&[][..], |(scope, _)| crate::msi_context::scope_arguments(scope))) +} + +/// The confirmed context and product code of `copy`, by the rules of [`update_arguments`]. `None` +/// for the launcher's own package, which keeps its package default and is never moved. +pub(crate) fn resolve( + copy: MsiCopy, + product_codes: &[String], + probe: impl FnOnce(&str) -> Result, + record_scopes: impl FnOnce(&str) -> Vec, +) -> Result, String> { let hive = match copy { - MsiCopy::Legacy => return Ok(&[]), + MsiCopy::Legacy => return Ok(None), MsiCopy::Conflicting => return Err(CONFLICTING.into()), MsiCopy::Registered { hive } => hive, }; @@ -65,7 +77,7 @@ pub(crate) fn update_arguments( if scope != hive { return Err(ANOTHER_COPY.into()); } - Ok(crate::msi_context::scope_arguments(scope)) + Ok(Some((scope, code.clone()))) } /// How a copy was installed, from what is known about it. The launcher's own per-user package in @@ -156,15 +168,16 @@ pub(crate) mod windows { super::classify(is_launcher, is_legacy(app, &exe), || match_registration(&exe, ®istered_exes(app))) } - /// The `msiexec` properties for `exe`'s update, asking Windows Installer for its context. - pub(crate) fn update_arguments(app: &App, exe: &Path) -> Result<&'static [&'static str], String> { + /// The confirmed context and product code of `exe`'s copy, asking Windows Installer; `None` + /// for the launcher's own package. See [`super::resolve`]. + pub(crate) fn resolve(app: &App, exe: &Path) -> Result, String> { let copy = find(app, exe).ok_or_else(|| format!("{} isn't registered with the Windows Installer", app.name))?; let codes: Vec = crate::detect::windows::msi_installs(app) .into_iter() .map(|m| m.product_code) .filter(|code| crate::msi_context::valid_product_code(code)) .collect(); - super::update_arguments(copy, &codes, crate::msi_context::probe, record_scopes) + super::resolve(copy, &codes, crate::msi_context::probe, record_scopes) } /// The context of every uninstall record of `code`: the machine's (both registry views) are diff --git a/crates/update/src/msi_migrate.rs b/crates/update/src/msi_migrate.rs new file mode 100644 index 000000000..a043781e8 --- /dev/null +++ b/crates/update/src/msi_migrate.rs @@ -0,0 +1,270 @@ +//! TEMPORARY: moves an app installed for one account to an install for everyone during its own +//! update. Remove this module two releases after the app packages become per-machine only +//! (craft-libs#422, step 4); from then on there are no per-user copies left to move. +//! +//! The released packages refuse a per-machine install while a per-user copy exists, so the move +//! removes first and installs second: +//! +//! 1. Remove the per-user copy (no permission prompt). If that fails nothing has changed. +//! 2. Install the new version for everyone (Windows asks for permission). +//! 3. If that fails or permission is refused, install the new version for the account again, in +//! the folder it had. The person always keeps a working app; settings and documents live +//! outside the program folder and are never touched. +//! +//! Which copies move: one in a per-user default folder goes to `Program Files\ArtCraft\`; one +//! in a folder the person chose outside their profile moves in place; one in a chosen folder +//! inside the profile keeps updating for the account, since program files for everyone must not +//! live in one person's profile. The launcher's own package never moves. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::path::{Path, PathBuf}; + +use crate::msi_context::{MsiScope, scope_arguments}; + +/// What an MSI self-update does. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Step { + /// Update in place with these `msiexec` properties. + Update(&'static [&'static str]), + /// Remove the per-user product, install for everyone into `folder`, and fall back to the + /// account in `old_folder` if that fails. + Move { product_code: String, folder: PathBuf, old_folder: PathBuf }, +} + +/// Where this account's files live: `USERPROFILE`, `LOCALAPPDATA` and `APPDATA`, which may be +/// redirected away from one another. +#[derive(Clone, Debug, Default)] +pub(crate) struct Profile { + pub roots: Vec, + pub local_app_data: Option, +} + +/// The step for a copy whose exe is in `dir`. `resolved` is its confirmed context and product +/// code (`None` for the launcher's own package); `program_files` is the root a new install for +/// everyone goes under, for this package's architecture. +pub(crate) fn plan(resolved: Option<(MsiScope, String)>, dir: &Path, app_name: &str, profile: &Profile, program_files: Option<&Path>) -> Step { + let Some((scope, product_code)) = resolved else { return Step::Update(&[]) }; + if scope == MsiScope::PerMachine { + return Step::Update(scope_arguments(scope)); + } + let stay = Step::Update(scope_arguments(MsiScope::PerUser)); + let defaults = profile.local_app_data.iter().flat_map(|local| { + let programs = local.join("Programs"); + [programs.join("ArtCraft").join(app_name), programs.join(app_name)] + }); + let folder = if defaults.into_iter().any(|default| same_path(&default, dir)) { + match program_files { + Some(root) => root.join("ArtCraft").join(app_name), + None => return stay, + } + } else if profile.roots.iter().any(|root| is_within(dir, root)) { + return stay; + } else { + dir.to_path_buf() + }; + Step::Move { product_code, folder, old_folder: dir.to_path_buf() } +} + +/// Windows paths compare without regard to case or a trailing separator. +fn normal(path: &Path) -> String { + path.as_os_str().to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_ascii_lowercase() +} + +fn same_path(a: &Path, b: &Path) -> bool { + normal(a) == normal(b) +} + +/// Whether `path` is `root` or inside it, by whole folder names. +fn is_within(path: &Path, root: &Path) -> bool { + let (path, root) = (normal(path), normal(root)); + !root.is_empty() && (path == root || path.strip_prefix(&root).is_some_and(|rest| rest.starts_with('\\'))) +} + +/// Moves a copy in the only safe order: `remove` the per-user copy (stop if that fails, nothing has +/// changed), install `to_everyone`, and only if that fails `keep_log` of it and install +/// `back_to_account`. The error says where the app is now. +pub(crate) fn run_move( + remove: impl FnOnce() -> Result<(), String>, + to_everyone: impl FnOnce() -> Result<(), String>, + keep_log: impl FnOnce(), + back_to_account: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + remove()?; + let Err(installed) = to_everyone() else { return Ok(()) }; + keep_log(); + Err(move_failure(&installed, back_to_account())) +} + +/// The error a failed move reports, saying where the app now is. +pub(crate) fn move_failure(installed: &str, rollback: Result<(), String>) -> String { + match rollback { + Ok(()) => format!("couldn't move the app to an install for everyone ({installed}); it was updated for your account instead"), + Err(again) => format!( + "couldn't move the app to an install for everyone ({installed}), and reinstalling it for your account failed too ({again}). Run its installer to get it back; your settings and documents are untouched" + ), + } +} + +#[cfg(windows)] +pub(crate) mod windows { + use std::path::{Path, PathBuf}; + + use super::{Profile, Step, plan, run_move}; + use crate::app::App; + use crate::install::windows::{reinstall, remove_product}; + use crate::msi_context::{MsiScope, scope_arguments}; + + fn env_path(name: &str) -> Option { + std::env::var_os(name).map(PathBuf::from).filter(|p| p.is_absolute()) + } + + /// The step for `exe`'s update, asking Windows Installer for its context. + pub(crate) fn step(app: &App, exe: &Path) -> Result { + let resolved = crate::msi_copy::windows::resolve(app, exe)?; + let dir = exe.parent().ok_or_else(|| format!("{} isn't in a folder", app.name))?; + let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); + let profile = Profile { + roots: ["USERPROFILE", "LOCALAPPDATA", "APPDATA"].into_iter().filter_map(env_path).collect(), + local_app_data: crate::folders::data_local_dir(), + }; + // This process has the package's architecture (the helper is a copy of the app), so its + // own `ProgramFiles` is the right root: `Program Files (x86)` for a 32-bit app. + Ok(plan(resolved, &dir, app.name, &profile, env_path("ProgramFiles").as_deref())) + } + + /// Runs `step` with the downloaded package `msi`. + pub(crate) fn run(msi: &Path, step: &Step) -> Result<(), String> { + match step { + Step::Update(context) => reinstall(msi, context, None), + Step::Move { product_code, folder, old_folder } => run_move( + || remove_product(product_code, &msi.with_extension("remove.log")), + || reinstall(msi, scope_arguments(MsiScope::PerMachine), Some(folder)), + // The fallback writes a fresh log; keep the failed install's beside it. + || { + let _ = std::fs::rename(crate::install::msi_log(msi), msi.with_extension("everyone.log")); + }, + || reinstall(msi, scope_arguments(MsiScope::PerUser), Some(old_folder)), + ), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const CODE: &str = "{500F5254-26F4-4AAA-B90D-6F3FD9947D14}"; + + fn p(s: &str) -> PathBuf { + PathBuf::from(s) + } + + fn profile() -> Profile { + Profile { + roots: vec![p(r"C:\Users\Ann"), p(r"C:\Users\Ann\AppData\Local"), p(r"C:\Users\Ann\AppData\Roaming")], + local_app_data: Some(p(r"C:\Users\Ann\AppData\Local")), + } + } + + fn user() -> Option<(MsiScope, String)> { + Some((MsiScope::PerUser, CODE.to_string())) + } + + fn moved(folder: &str, old: &str) -> Step { + Step::Move { product_code: CODE.to_string(), folder: p(folder), old_folder: p(old) } + } + + fn pf() -> Option<&'static Path> { + Some(Path::new(r"C:\Program Files")) + } + + #[test] + fn a_copy_for_everyone_and_the_launcher_update_in_place() { + let machine = Some((MsiScope::PerMachine, CODE.to_string())); + assert_eq!(plan(machine, &p(r"C:\Program Files\GridCraft"), "GridCraft", &profile(), pf()), Step::Update(&["ALLUSERS=1"])); + assert_eq!( + plan(None, &p(r"C:\Users\Ann\AppData\Local\Programs\ArtCraft\Launcher"), "ArtCraft Launcher", &profile(), pf()), + Step::Update(&[]) + ); + } + + #[test] + fn a_per_user_copy_in_a_default_folder_moves_to_the_suite_folder() { + for old in [r"C:\Users\Ann\AppData\Local\Programs\ArtCraft\GridCraft", r"c:\users\ann\appdata\local\programs\gridcraft\"] { + assert_eq!(plan(user(), &p(old), "GridCraft", &profile(), pf()), moved(r"C:\Program Files\ArtCraft\GridCraft", old)); + } + } + + #[test] + fn a_chosen_folder_outside_the_profile_moves_in_place() { + let old = r"D:\Apps\GridCraft"; + assert_eq!(plan(user(), &p(old), "GridCraft", &profile(), pf()), moved(old, old)); + } + + #[test] + fn a_chosen_folder_inside_the_profile_keeps_updating_for_the_account() { + for dir in [r"C:\Users\Ann\Tools\GridCraft", r"C:\Users\Ann\AppData\Local\Other\GridCraft", r"C:\Users\Ann\AppData\Roaming\GridCraft"] { + assert_eq!(plan(user(), &p(dir), "GridCraft", &profile(), pf()), Step::Update(&["ALLUSERS=2", "MSIINSTALLPERUSER=1"]), "{dir}"); + } + } + + #[test] + fn a_folder_that_only_shares_a_prefix_with_the_profile_is_outside_it() { + let old = r"C:\Users\Anna\GridCraft"; + assert_eq!(plan(user(), &p(old), "GridCraft", &profile(), pf()), moved(old, old)); + } + + #[test] + fn without_a_program_files_folder_a_default_copy_stays_for_the_account() { + let dir = p(r"C:\Users\Ann\AppData\Local\Programs\ArtCraft\GridCraft"); + assert_eq!(plan(user(), &dir, "GridCraft", &profile(), None), Step::Update(&["ALLUSERS=2", "MSIINSTALLPERUSER=1"])); + } + + fn steps(results: [Result<(), String>; 3]) -> (Result<(), String>, Vec<&'static str>) { + let done = std::cell::RefCell::new(Vec::new()); + let [remove, everyone, account] = results; + let result = run_move( + || { + done.borrow_mut().push("remove"); + remove + }, + || { + done.borrow_mut().push("everyone"); + everyone + }, + || done.borrow_mut().push("keep log"), + || { + done.borrow_mut().push("account"); + account + }, + ); + (result, done.into_inner()) + } + + #[test] + fn a_move_removes_first_and_installs_for_everyone() { + assert_eq!(steps([Ok(()), Ok(()), Ok(())]), (Ok(()), vec!["remove", "everyone"])); + } + + #[test] + fn a_failed_removal_changes_nothing_else() { + let (result, done) = steps([Err("error 1603".into()), Ok(()), Ok(())]); + assert_eq!(result, Err("error 1603".into())); + assert_eq!(done, ["remove"]); + } + + #[test] + fn a_refused_install_for_everyone_puts_the_app_back_for_the_account() { + let (result, done) = steps([Ok(()), Err("cancelled".into()), Ok(())]); + assert_eq!(done, ["remove", "everyone", "keep log", "account"]); + assert!(result.is_err_and(|e| e.contains("updated for your account instead"))); + } + + #[test] + fn a_failed_move_says_where_the_app_is() { + assert!(move_failure("error 1602", Ok(())).contains("updated for your account instead")); + let both = move_failure("error 1602", Err("error 1603".into())); + assert!(both.contains("error 1603") && both.contains("Run its installer"), "{both}"); + } +} diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index a3b3bc4c4..394e65f01 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -201,11 +201,11 @@ fn detect(app: &App, exe: &Path) -> Option { None } -/// The `msiexec` properties that keep `exe`'s Windows Installer context, or why its update stops. -/// Asked while the app still runs (so it can show the error) and again by the helper. +/// What `exe`'s MSI update does (update in place, or move a per-user copy to everyone), or why it +/// stops. Asked while the app still runs (so it can show the error) and again by the helper. #[cfg(windows)] -fn msi_arguments(app: &App, exe: &Path) -> Result<&'static [&'static str], String> { - crate::msi_copy::windows::update_arguments(app, exe) +fn msi_step(app: &App, exe: &Path) -> Result { + crate::msi_migrate::windows::step(app, exe) } /// The exe to start after an MSI update of a registered copy: the one its registrations name now @@ -697,7 +697,7 @@ fn windows_precheck(app: &App, install: &Install, paths: &Paths, download: &Path let me = std::env::current_exe().map_err(|e| format!("couldn't find this program ({e})"))?; match install { Install::Msi(exe) => signed_like(app, &me, exe) - .and_then(|()| msi_arguments(app, exe).map(drop)) + .and_then(|()| msi_step(app, exe).map(drop)) .and_then(|()| signed_like(app, &me, download)) .and_then(|()| own_executable(app, exe)) .and_then(|()| same_cache_as_helper(app, paths, exe)), @@ -834,9 +834,9 @@ fn run_step(app: &App, reference: &Path, pid: u32, exe: &Path, step: &Finish, wa wait_watch::returned(pid, waited); let result = if waited { match step { - Finish::Msi(msi) => signed_like(app, reference, msi) - .and_then(|()| msi_arguments(app, exe)) - .and_then(|arguments| install::windows::reinstall(msi, arguments)), + Finish::Msi(msi) => { + signed_like(app, reference, msi).and_then(|()| msi_step(app, exe)).and_then(|step| crate::msi_migrate::windows::run(msi, &step)) + } Finish::Portable { zip, tmp } => match (exe.parent(), exe.file_name()) { (Some(dir), Some(executable)) => crate::portable::unpack_over(zip, tmp, dir, executable, &|file| { // The expected executable must be signed even when its contents aren't a PE file. From eff2500447c4a27c979b6a1068b8f0d72ca0b4d9 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 13:33:30 +0000 Subject: [PATCH 6/7] craft-update: migration review fixes (profile links, recovery message, Linux test) Review follow-up (CodeRabbit and CI on #423): - The profile roots and LOCALAPPDATA are canonicalised like the exe's folder, so a profile behind a junction or a subst drive still matches its default folder and still counts as the profile. - When a failed move leaves no program to start, the helper starts nothing, so the recorded "run its installer" message is not replaced by a restart error. - The default-folder test builds its expected path the way the plan does, so it also passes where Path::join uses '/' (Linux CI). Co-Authored-By: Claude Opus 5.5 --- crates/update/src/msi_migrate.rs | 11 ++++++++--- crates/update/src/self_update.rs | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/update/src/msi_migrate.rs b/crates/update/src/msi_migrate.rs index a043781e8..6c69ddfc6 100644 --- a/crates/update/src/msi_migrate.rs +++ b/crates/update/src/msi_migrate.rs @@ -124,9 +124,11 @@ pub(crate) mod windows { let resolved = crate::msi_copy::windows::resolve(app, exe)?; let dir = exe.parent().ok_or_else(|| format!("{} isn't in a folder", app.name))?; let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); + // Resolved like `dir`, so a profile behind a junction or a `subst` drive still matches. + let canonical = |p: PathBuf| dunce::canonicalize(&p).unwrap_or(p); let profile = Profile { - roots: ["USERPROFILE", "LOCALAPPDATA", "APPDATA"].into_iter().filter_map(env_path).collect(), - local_app_data: crate::folders::data_local_dir(), + roots: ["USERPROFILE", "LOCALAPPDATA", "APPDATA"].into_iter().filter_map(env_path).map(canonical).collect(), + local_app_data: crate::folders::data_local_dir().map(canonical), }; // This process has the package's architecture (the helper is a copy of the app), so its // own `ProgramFiles` is the right root: `Program Files (x86)` for a 32-bit app. @@ -192,7 +194,10 @@ mod tests { #[test] fn a_per_user_copy_in_a_default_folder_moves_to_the_suite_folder() { for old in [r"C:\Users\Ann\AppData\Local\Programs\ArtCraft\GridCraft", r"c:\users\ann\appdata\local\programs\gridcraft\"] { - assert_eq!(plan(user(), &p(old), "GridCraft", &profile(), pf()), moved(r"C:\Program Files\ArtCraft\GridCraft", old)); + // Joined like the plan joins it: `\` on Windows, `/` where these tests also run. + let suite = pf().map(|root| root.join("ArtCraft").join("GridCraft")).unwrap(); + let expected = Step::Move { product_code: CODE.to_string(), folder: suite, old_folder: p(old) }; + assert_eq!(plan(user(), &p(old), "GridCraft", &profile(), pf()), expected); } } diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index 394e65f01..fe88b06e4 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -208,6 +208,13 @@ fn msi_step(app: &App, exe: &Path) -> Result { crate::msi_migrate::windows::step(app, exe) } +/// Whether the helper starts the app after the update step: always after a successful one, and +/// after a failed one only while its exe is still there. +#[cfg_attr(not(windows), allow(dead_code))] +fn restarts(step_succeeded: bool, exe_exists: bool) -> bool { + step_succeeded || exe_exists +} + /// The exe to start after an MSI update of a registered copy: the one its registrations name now /// (the package may have moved an exact old default folder), else `exe`. #[cfg(windows)] @@ -642,6 +649,11 @@ pub fn finish(app: &App, args: &[OsString]) -> Option> { } // The new app, or the old one when the step failed. let exe = if done.is_ok() { exe_after_msi(app, registered, &exe) } else { exe }; + // A failed move can leave no program to start; its recorded error already says how to get + // the app back, and a restart error must not replace it. + if !restarts(done.is_ok(), exe.is_file()) { + return Some(done); + } let started = signed_like(app, &me, &exe) .and_then(|()| process::spawn_detached(std::process::Command::new(&exe)).map_err(|e| format!("couldn't start {} ({e})", exe.display()))); if let Err(e) = &started { @@ -1723,6 +1735,14 @@ mod tests { assert_eq!(pick(Os::Linux, Install::Package(PackageKind::ArchPkg, PathBuf::new()).kind()).as_deref(), Some(names[6])); } + #[test] + fn a_failed_step_that_removed_the_app_starts_nothing_and_keeps_its_message() { + assert!(restarts(true, true)); + assert!(restarts(true, false)); + assert!(restarts(false, true)); + assert!(!restarts(false, false)); + } + #[test] fn update_refuses_to_downgrade_when_release_is_older() { let dir = tempfile::tempdir().unwrap(); From 25c2e9ffc5eca7cc98c19e2368034acd91470a22 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Thu, 29 Oct 2026 13:50:36 +0000 Subject: [PATCH 7/7] craft-update: resolve the whole default folders, not just LOCALAPPDATA Review follow-up (CodeRabbit on #423). If LOCALAPPDATA\Programs or Programs\ArtCraft is itself a junction, the exe's folder resolves through it but a default path built from a resolved LOCALAPPDATA does not, so a default install was planned as a chosen folder. The Windows layer now resolves each complete default folder (new default_folders) and hands them to the planner, which only compares. Co-Authored-By: Claude Opus 5.5 --- crates/update/src/msi_migrate.rs | 48 ++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/crates/update/src/msi_migrate.rs b/crates/update/src/msi_migrate.rs index 6c69ddfc6..5ceb90020 100644 --- a/crates/update/src/msi_migrate.rs +++ b/crates/update/src/msi_migrate.rs @@ -32,12 +32,21 @@ pub(crate) enum Step { Move { product_code: String, folder: PathBuf, old_folder: PathBuf }, } -/// Where this account's files live: `USERPROFILE`, `LOCALAPPDATA` and `APPDATA`, which may be -/// redirected away from one another. +/// Where this account's files live. `roots` are `USERPROFILE`, `LOCALAPPDATA` and `APPDATA`, which +/// may be redirected away from one another; `defaults` are the app's per-user default folders +/// ([`default_folders`]). All resolved the way the exe's folder is, so links and `subst` drives +/// compare as the same place. #[derive(Clone, Debug, Default)] pub(crate) struct Profile { pub roots: Vec, - pub local_app_data: Option, + pub defaults: Vec, +} + +/// The per-user default folders of `app_name` under `local_app_data`: the suite folder +/// `Programs\ArtCraft\`, then the older `Programs\`. +pub(crate) fn default_folders(local_app_data: &Path, app_name: &str) -> [PathBuf; 2] { + let programs = local_app_data.join("Programs"); + [programs.join("ArtCraft").join(app_name), programs.join(app_name)] } /// The step for a copy whose exe is in `dir`. `resolved` is its confirmed context and product @@ -49,11 +58,7 @@ pub(crate) fn plan(resolved: Option<(MsiScope, String)>, dir: &Path, app_name: & return Step::Update(scope_arguments(scope)); } let stay = Step::Update(scope_arguments(MsiScope::PerUser)); - let defaults = profile.local_app_data.iter().flat_map(|local| { - let programs = local.join("Programs"); - [programs.join("ArtCraft").join(app_name), programs.join(app_name)] - }); - let folder = if defaults.into_iter().any(|default| same_path(&default, dir)) { + let folder = if profile.defaults.iter().any(|default| same_path(default, dir)) { match program_files { Some(root) => root.join("ArtCraft").join(app_name), None => return stay, @@ -124,11 +129,14 @@ pub(crate) mod windows { let resolved = crate::msi_copy::windows::resolve(app, exe)?; let dir = exe.parent().ok_or_else(|| format!("{} isn't in a folder", app.name))?; let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); - // Resolved like `dir`, so a profile behind a junction or a `subst` drive still matches. + // Resolved like `dir`, whole path at a time, so a profile or a default folder reached + // through a junction or a `subst` drive still matches. let canonical = |p: PathBuf| dunce::canonicalize(&p).unwrap_or(p); let profile = Profile { roots: ["USERPROFILE", "LOCALAPPDATA", "APPDATA"].into_iter().filter_map(env_path).map(canonical).collect(), - local_app_data: crate::folders::data_local_dir().map(canonical), + defaults: crate::folders::data_local_dir() + .map(|local| super::default_folders(&local, app.name).into_iter().map(canonical).collect()) + .unwrap_or_default(), }; // This process has the package's architecture (the helper is a copy of the app), so its // own `ProgramFiles` is the right root: `Program Files (x86)` for a 32-bit app. @@ -165,10 +173,28 @@ mod tests { fn profile() -> Profile { Profile { roots: vec![p(r"C:\Users\Ann"), p(r"C:\Users\Ann\AppData\Local"), p(r"C:\Users\Ann\AppData\Roaming")], - local_app_data: Some(p(r"C:\Users\Ann\AppData\Local")), + defaults: [r"C:\Users\Ann\AppData\Local\Programs\ArtCraft\GridCraft", r"C:\Users\Ann\AppData\Local\Programs\GridCraft"].map(p).to_vec(), } } + #[test] + fn the_default_folders_are_the_suite_folder_then_the_older_one() { + let local = p(r"C:\Users\Ann\AppData\Local"); + let expected = [local.join("Programs").join("ArtCraft").join("GridCraft"), local.join("Programs").join("GridCraft")]; + assert_eq!(default_folders(&local, "GridCraft"), expected); + } + + #[test] + fn a_default_folder_reached_through_a_link_still_moves_to_the_suite_folder() { + // The Windows layer resolves each default folder whole, so a linked `Programs` arrives + // here as the real path the exe's folder also resolves to. + let old = r"D:\Redirected\Programs\ArtCraft\GridCraft"; + let linked = Profile { defaults: vec![p(old)], ..profile() }; + let suite = pf().map(|root| root.join("ArtCraft").join("GridCraft")).unwrap(); + let expected = Step::Move { product_code: CODE.to_string(), folder: suite, old_folder: p(old) }; + assert_eq!(plan(user(), &p(old), "GridCraft", &linked, pf()), expected); + } + fn user() -> Option<(MsiScope, String)> { Some((MsiScope::PerUser, CODE.to_string())) }