From 6e065e0b61484ef2e4f60d5c690c5e08f0afb329 Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Mon, 16 Nov 2026 20:15:56 +0800 Subject: [PATCH] fix(installer): preserve legacy maintenance and parallel installations --- OpenBitFun-Installer/README.md | 29 +- OpenBitFun-Installer/src-tauri/Cargo.toml | 2 +- .../src-tauri/src/installer/commands.rs | 270 +++++--- .../src-tauri/src/installer/elevation.rs | 6 +- .../src-tauri/src/installer/launch.rs | 286 ++++++++ .../src-tauri/src/installer/mod.rs | 1 + .../src-tauri/src/installer/registry.rs | 620 +++++++++++++++--- .../src-tauri/src/installer/shortcut.rs | 174 ++++- .../src-tauri/src/installer/transaction.rs | 125 +++- OpenBitFun-Installer/src-tauri/src/lib.rs | 4 +- OpenBitFun-Installer/src/i18n/locales/en.json | 5 +- .../src/i18n/locales/zh-TW.json | 5 +- OpenBitFun-Installer/src/i18n/locales/zh.json | 5 +- .../src/infrastructure/installPathApi.ts | 1 - .../src/pages/Options.test.tsx | 24 +- OpenBitFun-Installer/src/pages/Options.tsx | 20 - scripts/updater-maintenance.test.mjs | 60 +- src/apps/cli/README.md | 6 + src/apps/cli/install.sh | 56 +- src/apps/cli/install.test.mjs | 63 ++ src/apps/cli/src/main.rs | 9 + src/apps/cli/src/self_update.rs | 82 +++ src/apps/desktop/Cargo.toml | 2 +- src/apps/desktop/src/api/update_api.rs | 164 ++++- .../desktop/src/update_maintenance/mod.rs | 203 ++++++ .../desktop/src/update_maintenance/windows.rs | 20 +- .../services-core/src/installation_scope.rs | 364 ++++++++++ src/crates/services/services-core/src/lib.rs | 3 + .../api/service-api/SystemAPI.ts | 1 + .../update/AppUpdatePanel.test.tsx | 11 +- .../infrastructure/update/AppUpdatePanel.tsx | 11 +- .../update/updateInstallStore.test.ts | 18 + .../update/updateInstallStore.ts | 13 +- src/web-ui/src/locales/en-US/common.json | 2 + src/web-ui/src/locales/zh-CN/common.json | 2 + src/web-ui/src/locales/zh-TW/common.json | 2 + 36 files changed, 2372 insertions(+), 297 deletions(-) create mode 100644 OpenBitFun-Installer/src-tauri/src/installer/launch.rs create mode 100644 src/crates/services/services-core/src/installation_scope.rs diff --git a/OpenBitFun-Installer/README.md b/OpenBitFun-Installer/README.md index b8f7d785b9..a150626b55 100644 --- a/OpenBitFun-Installer/README.md +++ b/OpenBitFun-Installer/README.md @@ -236,13 +236,21 @@ src-tauri/target/release-fast/openbitfun-installer.exe ### Installation, updates and recovery -The default is a current-user installation. Select “Install for all users” for -a new machine-wide installation; Windows then asks for administrator approval. -An existing installation keeps its directory and scope. Updates to protected +New installations use the current-user scope. The installer does not offer a +scope switch or change a selected directory when editing shortcut preferences. +An existing installation keeps its directory and scope, including legacy +machine-wide installations. Updates to protected directories request elevation automatically. Canceling authorization leaves the existing application in place. Model and theme preferences remain with the original user, including when a different administrator approves maintenance. +Multiple installation directories can coexist. New directories have separate +Windows uninstall entries and shortcuts labeled with their location and a stable +directory identifier. Updating or uninstalling one directory preserves the +others. Legacy uninstall entries and shortcuts remain supported. Model settings +and sessions continue to use the existing user data directory; installing another +copy does not create an isolated user profile. + Installations record their managed files in `.openbitfun-installed.json`. Updates and uninstallations preserve other files and user data. A running or locked file produces an error and restores earlier changes. Close OpenBitFun @@ -260,6 +268,21 @@ exits after the maintenance worker is ready. Installation failures after exit are reported by a native dialog and retained for the next application launch. The restarted application runs under the original user's account. +Native maintenance also accepts legacy NSIS arguments: `/D=` selects an install +directory, `/S` requests silent execution, `/P` requests passive execution, and +`_?=` selects the uninstall directory. Uninstall entrypoints retain their operation +when `/UPDATE` is present. `/R /ARGS ...` restarts with the original application +arguments and user token. Native `--quiet` keeps its `0`/`1`/`2` outcome contract; +legacy NSIS uninstall callers receive `0` after successful removal with deferred +cleanup, with the committed journal retained for a later cleanup retry. + +The application and installer share Windows scope detection, including legacy +HKLM records without a new inventory. Same-directory HKCU/HKLM duplicates are +both backed up and removed on uninstall; records for other directories remain. +Protected installation or maintenance-lock locations request elevation before +publication. Cleanup removes the transaction journal last, so cleanup failures +remain retryable. + Uninstall can be entered through Windows Settings, the registered uninstall command, or `uninstall.exe` in the installation directory. `--quiet` selects non-interactive removal. Uninstall progress reflects native operations and the diff --git a/OpenBitFun-Installer/src-tauri/Cargo.toml b/OpenBitFun-Installer/src-tauri/Cargo.toml index 5420fac623..c3e036f584 100644 --- a/OpenBitFun-Installer/src-tauri/Cargo.toml +++ b/OpenBitFun-Installer/src-tauri/Cargo.toml @@ -37,7 +37,7 @@ dirs = "5.0" zip = { version = "9.0.3", default-features = false, features = ["deflate"] } openbitfun-core-types = { path = "../../src/crates/contracts/core-types" } openbitfun-ai-adapters = { path = "../../src/crates/adapters/ai-adapters" } -openbitfun-services-core = { path = "../../src/crates/services/services-core", features = ["json-io"] } +openbitfun-services-core = { path = "../../src/crates/services/services-core", features = ["json-io", "installed-apps"] } [target.'cfg(windows)'.dependencies] winreg = "0.52" diff --git a/OpenBitFun-Installer/src-tauri/src/installer/commands.rs b/OpenBitFun-Installer/src-tauri/src/installer/commands.rs index 6f6050d420..d1560d4573 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/commands.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/commands.rs @@ -104,57 +104,69 @@ impl Drop for UiOperation { pub(crate) const MAINTENANCE_PROTOCOL: &str = "OPENBITFUN_MAINTENANCE_V1"; pub(crate) fn native_mode() -> Option> { - let args = std::env::args().skip(1).collect::>(); - if args.iter().any(|arg| arg == "--maintenance-protocol") { + let request = match super::launch::current() { + Ok(request) => request, + Err(error) => return Some(Err(error)), + }; + if request.has("--maintenance-protocol") { println!("{MAINTENANCE_PROTOCOL}"); return Some(Ok(())); } - let flags = args - .iter() - .take_while(|arg| !arg.eq_ignore_ascii_case("/ARGS")) - .collect::>(); - let update = flags.iter().any(|arg| arg.eq_ignore_ascii_case("/UPDATE")); - let install = flags - .iter() - .any(|arg| arg.eq_ignore_ascii_case("/NATIVE_INSTALL")); - let quiet = flags - .iter() - .any(|arg| *arg == "--quiet" || arg.eq_ignore_ascii_case("/NATIVE_UNINSTALL")); - if !update && !quiet && !install { + if !request.native { return None; } + let args = request.flags.clone(); + let flags = args.iter().collect::>(); + let update = request.operation == super::launch::Operation::Update; + let install = request.operation == super::launch::Operation::Install; if crate::preview::is_enabled() { return Some(Err("Preview cannot execute maintenance".into())); } Some(tauri::async_runtime::block_on(async { + let target = request + .target + .as_ref() + .map(|path| path.to_string_lossy().into_owned()) + .or_else(|| (update || install).then(get_initial_install_path)) + .ok_or("Uninstall requires an explicit installation path")?; + let resolved = if request.operation == super::launch::Operation::Uninstall { + PathBuf::from(&target) + } else { + resolve_install_target(Path::new(&target))? + }; #[cfg(windows)] if let Some(owner) = args.iter().find_map(|arg| arg.strip_prefix("/OWNER_SID=")) { - let target = args - .iter() - .find_map(|arg| arg.strip_prefix("/OPENBITFUN_TARGET=")) - .or_else(|| { - args.iter() - .position(|arg| arg == "--uninstall") - .and_then(|index| args.get(index + 1)) - .map(String::as_str) - }) - .map(PathBuf::from); let machine = flags .iter() .any(|arg| arg.eq_ignore_ascii_case("/ALLUSERS")) - || target - .as_ref() - .is_some_and(|target| super::registry::is_machine_install(target)); + || super::registry::is_machine_install(&resolved)?; if !machine && super::elevation::owner_sid()? != owner { return Err("The administrator account differs from the installation owner. Run maintenance as the original owner or ask your administrator to repair the installation; no files were changed".into()); } } + #[cfg(windows)] + if maintenance_requires_elevation(&resolved, request.has("/ALLUSERS"))? { + let worker_args = + request.elevated_worker_args(&resolved, &super::elevation::owner_sid()?); + let code = super::elevation::run( + &std::env::current_exe().map_err(|error| error.to_string())?, + &worker_args, + )?; + if request.restart { + launch_application_with_args(&resolved.to_string_lossy(), &request.app_args)?; + } + if code == 2 { + return Err(if update || install { + "Update installed, but maintenance cleanup remains pending" + } else { + "Uninstall completed, but maintenance cleanup remains pending" + } + .into()); + } + return Ok(()); + } if update || install { - let target = args - .iter() - .find_map(|arg| arg.strip_prefix("/OPENBITFUN_TARGET=").map(str::to_string)) - .unwrap_or_else(get_initial_install_path); - let validated = prepare_install_target(Path::new(&target))?; + let validated = prepare_install_target(&resolved)?; let space = get_disk_space(validated.to_string_lossy().into_owned())?; if !space.sufficient { return Err("Insufficient disk space for update staging".into()); @@ -163,10 +175,10 @@ pub(crate) fn native_mode() -> Option> { wait_for_update_parent(&args, &validated)?; #[cfg(windows)] if update && !args.iter().any(|arg| arg.starts_with("/READY_EVENT=")) { - wait_for_legacy_update_parent(&validated)?; + wait_for_legacy_update_parent(&validated.join(MAIN_APP_EXE))?; } let options = InstallOptions { - install_path: target.clone(), + install_path: validated.to_string_lossy().into_owned(), all_users: flags .iter() .any(|arg| arg.eq_ignore_ascii_case("/ALLUSERS")), @@ -182,20 +194,14 @@ pub(crate) fn native_mode() -> Option> { model_config: None, }; let result = install_impl(None, options).await?; - if flags.iter().any(|arg| arg.eq_ignore_ascii_case("/R")) { - launch_application(target)?; + if request.restart { + launch_application_with_args(&validated.to_string_lossy(), &request.app_args)?; } if result.cleanup_pending { return Err("Update installed, but maintenance cleanup remains pending; reopen the application and retry cleanup".into()); } } else { - let path = args - .iter() - .position(|arg| arg == "--uninstall") - .and_then(|index| args.get(index + 1)) - .cloned() - .ok_or("Silent uninstall requires an explicit installation path")?; - let result = uninstall_impl(None, path).await?; + let result = uninstall_impl(None, resolved.to_string_lossy().into_owned()).await?; if result.cleanup_pending { return Err( "Uninstall completed, but some maintenance files remain; retry cleanup".into(), @@ -206,8 +212,29 @@ pub(crate) fn native_mode() -> Option> { })) } +pub(crate) fn maintenance_is_non_interactive() -> bool { + super::launch::current().is_ok_and(|request| request.non_interactive()) +} + #[cfg(windows)] -fn wait_for_legacy_update_parent(root: &Path) -> Result<(), String> { +fn maintenance_requires_elevation(path: &Path, all_users: bool) -> Result { + let scope = super::registry::scope(path)?; + let protected_target = match prepare_install_target(path) { + Ok(_) => false, + Err(error) if error.ends_with("not_writable") => true, + Err(error) => return Err(error), + }; + let protected_lock = match super::transaction::probe_lock_access(path) { + Ok(()) => false, + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => true, + Err(error) => return Err(format!("Cannot probe maintenance lock: {error}")), + }; + Ok(!super::elevation::is_elevated() + && (all_users || scope.requires_machine_access() || protected_target || protected_lock)) +} + +#[cfg(windows)] +fn wait_for_legacy_update_parent(executable: &Path) -> Result<(), String> { let powershell = system_powershell()?; let script = r#"$ErrorActionPreference='Stop' $target=[IO.Path]::GetFullPath($env:OPENBITFUN_LEGACY_UPDATE_TARGET) @@ -221,10 +248,13 @@ foreach($process in @(Get-Process -Name $name -ErrorAction SilentlyContinue)) { if(!$process.WaitForExit($left)) { throw 'OpenBitFun did not exit; close the application and retry. No installation files were changed.' } } } +# No matching process means the previous version has already exited. +# Do not inherit the failure status of the suppressed Get-Process lookup. +exit 0 "#; let result = create_windows_silent_command(powershell) .args(["-NoProfile", "-NonInteractive", "-Command", script]) - .env("OPENBITFUN_LEGACY_UPDATE_TARGET", root.join(MAIN_APP_EXE)) + .env("OPENBITFUN_LEGACY_UPDATE_TARGET", executable) .output() .map_err(|e| e.to_string())?; if !result.status.success() { @@ -501,6 +531,13 @@ pub(crate) fn get_default_install_path(all_users: Option) -> String { /// Last successful install path if still valid, otherwise platform default. #[tauri::command] pub(crate) fn get_initial_install_path() -> String { + if let Ok(request) = super::launch::current() { + if let Some(path) = request.target { + if let Ok(resolved) = resolve_install_target(&path) { + return resolved.to_string_lossy().into_owned(); + } + } + } #[cfg(target_os = "windows")] { use super::registry; @@ -787,7 +824,9 @@ pub(crate) fn get_launch_context() -> LaunchContext { app_language: None, }; } - let args: Vec = std::env::args().collect(); + let args: Vec = std::env::args() + .take_while(|arg| !arg.eq_ignore_ascii_case("/ARGS")) + .collect(); let app_language = read_saved_app_language(); if let Some(idx) = args.iter().position(|arg| arg == "--uninstall") { let uninstall_path = args @@ -850,11 +889,7 @@ pub(crate) async fn start_installation( { let path = resolve_install_target(Path::new(&options.install_path))?; super::registry::validate_scope(&path, options.all_users).map_err(|e| e.to_string())?; - let needs_elevation = !super::elevation::is_elevated() - && (options.all_users - || super::registry::is_machine_install(&path) - || prepare_install_target(&path) - .is_err_and(|error| error.ends_with("not_writable"))); + let needs_elevation = maintenance_requires_elevation(&path, options.all_users)?; if needs_elevation { let _ui = UiOperation::acquire()?; let is_update = @@ -870,7 +905,7 @@ pub(crate) async fn start_installation( format!("/OPENBITFUN_TARGET={}", path.display()), format!("/OWNER_SID={}", super::elevation::owner_sid()?), ]; - if options.all_users || super::registry::is_machine_install(&path) { + if options.all_users || super::registry::is_machine_install(&path)? { args.push("/ALLUSERS".into()); } if options.desktop_shortcut { @@ -912,8 +947,8 @@ async fn install_impl( options: InstallOptions, ) -> Result { #[cfg(windows)] - let machine_lock = - options.all_users || super::registry::is_machine_install(Path::new(&options.install_path)); + let machine_lock = options.all_users + || super::registry::scope(Path::new(&options.install_path))?.requires_machine_access(); #[cfg(not(windows))] let machine_lock = options.all_users; let _operation = OperationGuard::acquire(machine_lock)?; @@ -951,7 +986,7 @@ async fn install_impl( } #[cfg(windows)] - let machine = options.all_users || super::registry::is_machine_install(&install_path); + let machine = options.all_users || super::registry::is_machine_install(&install_path)?; #[cfg(not(windows))] let machine = options.all_users; let staging_path = transaction.stage(); @@ -1161,11 +1196,7 @@ pub(crate) async fn uninstall( #[cfg(windows)] { let path = PathBuf::from(&install_path); - if !super::elevation::is_elevated() - && (super::registry::is_machine_install(&path) - || prepare_install_target(&path) - .is_err_and(|error| error.ends_with("not_writable"))) - { + if maintenance_requires_elevation(&path, false)? { let _ui = UiOperation::acquire()?; let current = std::env::current_exe().map_err(|e| e.to_string())?; let mut args = vec![ @@ -1175,7 +1206,7 @@ pub(crate) async fn uninstall( format!("/OPENBITFUN_TARGET={}", path.display()), format!("/OWNER_SID={}", super::elevation::owner_sid()?), ]; - if super::registry::is_machine_install(&path) { + if super::registry::is_machine_install(&path)? { args.push("/ALLUSERS".into()); } let code = tauri::async_runtime::spawn_blocking(move || { @@ -1201,7 +1232,7 @@ async fn uninstall_impl( install_path: String, ) -> Result { #[cfg(windows)] - let machine_lock = super::registry::is_machine_install(Path::new(&install_path)); + let machine_lock = super::registry::scope(Path::new(&install_path))?.requires_machine_access(); #[cfg(not(windows))] let machine_lock = false; let _operation = OperationGuard::acquire(machine_lock)?; @@ -1240,7 +1271,7 @@ async fn uninstall_impl( }) .collect::, _>>()?; #[cfg(windows)] - let machine = super::registry::is_machine_install(&install_path); + let machine = super::registry::is_machine_install(&install_path)?; #[cfg(not(windows))] let machine = false; snapshot_integrations(&install_path, &mut transaction, machine)?; @@ -1310,16 +1341,26 @@ async fn uninstall_impl( #[cfg(windows)] pub(super) fn windows_path_eq_case_insensitive(a: &Path, b: &Path) -> bool { - fn normalize(path: &Path) -> String { - std::fs::canonicalize(path) - .unwrap_or_else(|_| path.to_path_buf()) - .to_string_lossy() - .replace('/', "\\") - .trim_start_matches(r"\\?\") - .trim_end_matches('\\') - .to_lowercase() - } - normalize(a) == normalize(b) + normalized_windows_install_path(a) == normalized_windows_install_path(b) +} + +#[cfg(windows)] +pub(super) fn normalized_windows_install_path(path: &Path) -> String { + std::fs::canonicalize(path) + .unwrap_or_else(|_| path.to_path_buf()) + .to_string_lossy() + .replace('/', "\\") + .trim_start_matches(r"\\?\") + .trim_end_matches('\\') + .to_lowercase() +} + +#[cfg(windows)] +pub(super) fn windows_installation_id(path: &Path) -> String { + format!( + "{:x}", + Sha256::digest(normalized_windows_install_path(path)) + ) } /// Relocate before creating a WebView so the installed executable is never in use @@ -1332,11 +1373,10 @@ pub(crate) fn relocate_uninstaller() -> Result { } let current = std::env::current_exe().map_err(|e| e.to_string())?; let arguments = std::env::args_os().skip(1).collect::>(); - let root = arguments - .iter() - .position(|arg| arg == "--uninstall") - .and_then(|index| arguments.get(index + 1)) - .map(PathBuf::from) + let request = super::launch::current()?; + let root = request + .target + .clone() .or_else(|| current.parent().map(Path::to_path_buf)) .ok_or("Uninstaller has no installation directory")?; let temp = tempfile::Builder::new() @@ -1352,14 +1392,19 @@ pub(crate) fn relocate_uninstaller() -> Result { .spawn() .map_err(|e| format!("Cannot start uninstall maintenance: {e}"))?; let _retained = temp.keep(); - if arguments.iter().any(|arg| arg == "--quiet") { + if request.non_interactive() || request.legacy_uninstall { // Management tools must receive the worker's real result. Keeping // this image mapped may defer backup cleanup (exit 2), but a failed // removal must never be reported as a successful spawn (exit 0). let status = child .wait() .map_err(|e| format!("Cannot read uninstall result: {e}"))?; - std::process::exit(status.code().unwrap_or(1)); + let code = status.code().unwrap_or(1); + std::process::exit(if request.legacy_uninstall && code == 2 { + 0 + } else { + code + }); } return Ok(true); } @@ -1424,10 +1469,7 @@ for($attempt=0;$attempt -lt 20;$attempt++) { #[cfg(windows)] pub(crate) fn uninstall_without_webview(path: String) -> Result<(), String> { let root = Path::new(&path); - if !super::elevation::is_elevated() - && (super::registry::is_machine_install(root) - || prepare_install_target(root).is_err_and(|error| error.ends_with("not_writable"))) - { + if maintenance_requires_elevation(root, false)? { let args = vec![ "/NATIVE_UNINSTALL".into(), "--uninstall".into(), @@ -1455,6 +1497,10 @@ pub(crate) fn uninstall_without_webview(path: String) -> Result<(), String> { /// Launch the installed application. #[tauri::command] pub(crate) fn launch_application(install_path: String) -> Result<(), String> { + launch_application_with_args(&install_path, &[]) +} + +fn launch_application_with_args(install_path: &str, args: &[String]) -> Result<(), String> { let exe = if cfg!(target_os = "windows") { PathBuf::from(&install_path).join(MAIN_APP_EXE) } else if cfg!(target_os = "macos") { @@ -1465,12 +1511,14 @@ pub(crate) fn launch_application(install_path: String) -> Result<(), String> { #[cfg(target_os = "windows")] create_windows_silent_command(&exe) + .args(args) .current_dir(&install_path) .spawn() .map_err(|e| format!("Failed to launch OpenBitFun: {}", e))?; #[cfg(not(target_os = "windows"))] std::process::Command::new(&exe) + .args(args) .current_dir(&install_path) .spawn() .map_err(|e| format!("Failed to launch OpenBitFun: {}", e))?; @@ -1833,7 +1881,8 @@ fn find_existing_ancestor(path: &Path) -> PathBuf { /// Actual install root is always under an `OpenBitFun` directory: `{user choice}/OpenBitFun`. /// If the user already chose a path whose last segment is `OpenBitFun`, do not append again. fn with_openbitfun_install_subdir(path: PathBuf) -> PathBuf { - if path.join(transaction::INVENTORY).exists() + if path.join(MAIN_APP_EXE).is_file() + || path.join(transaction::INVENTORY).exists() || path .join(transaction::WORK_DIR) .join("journal.json") @@ -2606,6 +2655,18 @@ mod tests { assert!(super::validate_upgrade_version(&version, &version).is_ok()); } + #[test] + fn legacy_custom_directories_remain_the_update_target_without_inventory() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("legacy custom host"); + std::fs::create_dir(&root).unwrap(); + std::fs::write(root.join(MAIN_APP_EXE), b"legacy executable").unwrap(); + assert_eq!(super::resolve_install_target(&root).unwrap(), root); + let validated = super::validate_install_path(root.to_string_lossy().into()).unwrap(); + assert_eq!(std::path::PathBuf::from(validated.install_path), root); + assert!(!root.join("OpenBitFun").exists()); + } + #[test] fn path_validation_keeps_interrupted_roots_recoverable_before_the_main_binary_is_restored() { let temp = tempfile::tempdir().unwrap(); @@ -2639,13 +2700,50 @@ mod tests { .stderr(Stdio::null()) .spawn() .unwrap(); - super::wait_for_legacy_update_parent(temp.path()).unwrap(); + super::wait_for_legacy_update_parent(&target).unwrap(); assert!( previous.try_wait().unwrap().is_some(), "legacy handoff must not publish while the old executable is still running" ); } + #[cfg(windows)] + #[test] + fn legacy_update_accepts_an_already_exited_previous_executable() { + use std::process::Stdio; + let temp = tempfile::tempdir().unwrap(); + let ping = std::path::PathBuf::from(std::env::var_os("SYSTEMROOT").unwrap()) + .join("System32/ping.exe"); + // A unique process name keeps other running installations and parallel + // handoff fixtures from hiding the no-process regression. + let target = temp.path().join(format!( + "openbitfun-exited-{}.exe", + temp.path().file_name().unwrap().to_string_lossy() + )); + std::fs::copy(ping, &target).unwrap(); + let status = super::create_windows_silent_command(&target) + .args(["-n", "1", "127.0.0.1"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap(); + assert!(status.success()); + super::wait_for_legacy_update_parent(&target).unwrap(); + } + + #[cfg(windows)] + #[test] + fn legacy_update_still_rejects_invalid_executable_paths() { + let error = super::wait_for_legacy_update_parent(std::path::Path::new( + r"C:\invalid|openbitfun.exe", + )) + .unwrap_err(); + let prefix = "Cannot wait for the previous OpenBitFun version to exit: "; + assert!(error.starts_with(prefix), "{error}"); + assert!(!error[prefix.len()..].trim().is_empty(), "{error}"); + } + #[cfg(windows)] #[test] fn update_handoff_waits_for_the_parent_and_aborts_when_the_supervisor_dies() { diff --git a/OpenBitFun-Installer/src-tauri/src/installer/elevation.rs b/OpenBitFun-Installer/src-tauri/src/installer/elevation.rs index 3ee1182c40..136d062293 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/elevation.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/elevation.rs @@ -217,8 +217,10 @@ fn read_native_error(path: &Path, code: u32) -> Option { } pub(super) fn persist_native_outcome(code: u32, error: Option<&str>) { - let Some(id) = - std::env::args().find_map(|arg| arg.strip_prefix("/RESULT_ID=").map(str::to_owned)) + let Some(id) = std::env::args() + .skip(1) + .take_while(|arg| !arg.eq_ignore_ascii_case("/ARGS")) + .find_map(|arg| arg.strip_prefix("/RESULT_ID=").map(str::to_owned)) else { return; }; diff --git a/OpenBitFun-Installer/src-tauri/src/installer/launch.rs b/OpenBitFun-Installer/src-tauri/src/installer/launch.rs new file mode 100644 index 0000000000..1fa2ceb6e2 --- /dev/null +++ b/OpenBitFun-Installer/src-tauri/src/installer/launch.rs @@ -0,0 +1,286 @@ +//! Native and legacy NSIS command-line compatibility at the installer boundary. +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Operation { + Install, + Update, + Uninstall, +} + +#[derive(Debug)] +pub(super) struct Request { + pub operation: Operation, + pub native: bool, + pub quiet: bool, + pub passive: bool, + pub restart: bool, + pub target: Option, + pub flags: Vec, + pub app_args: Vec, + pub legacy_uninstall: bool, +} + +impl Request { + pub(super) fn elevated_worker_args(&self, target: &Path, owner: &str) -> Vec { + let mut flags = self + .flags + .iter() + .filter(|arg| !arg.eq_ignore_ascii_case("/R")) + .cloned() + .collect::>(); + flags.push(format!("/OPENBITFUN_TARGET={}", target.display())); + if self.value("/OWNER_SID=").is_none() { + flags.push(format!("/OWNER_SID={owner}")); + } + flags + } + pub(super) fn has(&self, flag: &str) -> bool { + self.flags.iter().any(|arg| arg.eq_ignore_ascii_case(flag)) + } + pub(super) fn value(&self, prefix: &str) -> Option<&str> { + self.flags.iter().find_map(|arg| { + arg.get(..prefix.len()) + .filter(|head| head.eq_ignore_ascii_case(prefix)) + .map(|_| &arg[prefix.len()..]) + }) + } + pub(super) fn non_interactive(&self) -> bool { + self.quiet || self.passive || self.value("/READY_EVENT=").is_some() + } +} + +fn legacy_target(flags: &[String], prefix: &str, raw: Option<&str>) -> Option { + let argument = flags.iter().find(|arg| { + arg.get(..prefix.len()) + .is_some_and(|head| head.eq_ignore_ascii_case(prefix)) + })?; + // NSIS /D= and _?= consume the unquoted final command-line tail, including + // spaces. Structured native arguments continue to use the OS argv parser. + if let Some(raw) = raw { + let lowered = raw.to_ascii_lowercase(); + if let Some(index) = lowered + .match_indices(&prefix.to_ascii_lowercase()) + .map(|(i, _)| i) + .find(|&i| i == 0 || raw.as_bytes()[i - 1].is_ascii_whitespace()) + { + let tail = raw[index + prefix.len()..].trim(); + if !tail.is_empty() { + return Some(PathBuf::from(tail.trim_matches('"'))); + } + } + } + Some(PathBuf::from(&argument[prefix.len()..])) +} + +pub(super) fn parse( + executable: &Path, + args: &[String], + raw: Option<&str>, +) -> Result { + let boundary = args + .iter() + .position(|arg| arg.eq_ignore_ascii_case("/ARGS")) + .unwrap_or(args.len()); + let flags = args[..boundary].to_vec(); + let has = |flag: &str| flags.iter().any(|arg| arg.eq_ignore_ascii_case(flag)); + let uninstall = executable + .file_stem() + .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case("uninstall")) + || has("--uninstall") + || has("/NATIVE_UNINSTALL"); + let quiet = has("--quiet") || has("/S"); + let passive = has("/P"); + let update = has("/UPDATE"); + let operation = if uninstall { + Operation::Uninstall + } else if update { + Operation::Update + } else { + Operation::Install + }; + let explicit = flags + .iter() + .position(|arg| arg == "--uninstall") + .map(|index| { + flags + .get(index + 1) + .filter(|arg| !arg.is_empty()) + .map(PathBuf::from) + .ok_or("Uninstall requires an explicit directory") + }) + .transpose()?; + let native_target = flags + .iter() + .find_map(|arg| arg.strip_prefix("/OPENBITFUN_TARGET=").map(PathBuf::from)); + let target = explicit + .or(native_target) + .or_else(|| legacy_target(&flags, if uninstall { "_?=" } else { "/D=" }, raw)); + Ok(Request { + operation, + native: quiet || passive || update || has("/NATIVE_INSTALL") || has("/NATIVE_UNINSTALL"), + quiet, + passive, + restart: !uninstall && has("/R"), + target, + app_args: args.get(boundary + 1..).unwrap_or_default().to_vec(), + legacy_uninstall: uninstall + && !has("--quiet") + && !has("/NATIVE_UNINSTALL") + && (quiet || passive || update || flags.iter().any(|arg| arg.starts_with("_?="))), + flags, + }) +} + +pub(super) fn current() -> Result { + let executable = std::env::current_exe().map_err(|error| error.to_string())?; + let args = std::env::args().skip(1).collect::>(); + #[cfg(windows)] + let raw = { + #[link(name = "kernel32")] + extern "system" { + fn GetCommandLineW() -> *const u16; + } + let pointer = unsafe { GetCommandLineW() }; + let mut length = 0; + unsafe { + while *pointer.add(length) != 0 { + length += 1; + } + } + Some(String::from_utf16_lossy(unsafe { + std::slice::from_raw_parts(pointer, length) + })) + }; + #[cfg(not(windows))] + let raw: Option = None; + parse(&executable, &args, raw.as_deref()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn elevation_retains_handoff_and_owner_but_leaves_restart_with_the_original_token() { + let parsed = request( + "installer.exe", + &[ + "/UPDATE", + "/R", + "/WAITPID=42", + "/READY_EVENT=event", + "/SUPERVISOR_PID=24", + "/RESULT_ID=abc", + "/ARGS", + "workspace with spaces", + ], + None, + ); + let flags = + parsed.elevated_worker_args(Path::new(r"C:\Program Files\OpenBitFun"), "S-1-5-21-1"); + let worker = parse(Path::new("installer.exe"), &flags, None).unwrap(); + assert_eq!(worker.operation, Operation::Update); + assert_eq!(worker.value("/WAITPID="), Some("42")); + assert_eq!(worker.value("/READY_EVENT="), Some("event")); + assert_eq!(worker.value("/SUPERVISOR_PID="), Some("24")); + assert_eq!(worker.value("/RESULT_ID="), Some("abc")); + assert_eq!(worker.value("/OWNER_SID="), Some("S-1-5-21-1")); + assert!(!worker.restart && worker.app_args.is_empty()); + assert!(parsed.restart); + assert_eq!(parsed.app_args, ["workspace with spaces"]); + } + fn request(exe: &str, args: &[&str], raw: Option<&str>) -> Request { + parse( + Path::new(exe), + &args.iter().map(|arg| arg.to_string()).collect::>(), + raw, + ) + .unwrap() + } + #[test] + fn legacy_update_uninstaller_never_becomes_an_installer() { + for args in [ + vec!["/UPDATE", "/P", "_?=C:\\Apps\\OpenBitFun"], + vec!["--uninstall", "C:\\Apps\\OpenBitFun", "/UPDATE", "/P"], + ] { + let parsed = request("uninstall.exe", &args, None); + assert_eq!(parsed.operation, Operation::Uninstall); + assert!(parsed.native && parsed.passive && parsed.legacy_uninstall); + assert!(!parsed.restart); + } + } + #[test] + fn legacy_directory_tails_and_restart_arguments_are_preserved() { + let parsed = request( + "installer.exe", + &["/UPDATE", "/D=C:\\Program", "Files\\OpenBitFun"], + Some(r"installer.exe /UPDATE /D=C:\Program Files\OpenBitFun"), + ); + assert_eq!( + parsed.target.unwrap(), + Path::new(r"C:\Program Files\OpenBitFun") + ); + let parsed = request( + "uninstall.exe", + &["/S", "_?=C:\\Program", "Files\\OpenBitFun"], + Some(r"uninstall.exe /S _?=C:\Program Files\OpenBitFun"), + ); + assert!(parsed.native && parsed.quiet && parsed.legacy_uninstall); + assert_eq!( + parsed.target.unwrap(), + Path::new(r"C:\Program Files\OpenBitFun") + ); + let parsed = request( + "installer.exe", + &[ + "/UPDATE", + "/R", + "/ARGS", + "workspace with spaces", + "--flag", + "/UPDATE", + "/OPENBITFUN_TARGET=not-a-target", + "--maintenance-protocol", + "/OWNER_SID=not-an-owner", + ], + None, + ); + assert!(parsed.restart); + assert!(parsed.target.is_none()); + assert!(!parsed.has("--maintenance-protocol")); + assert!(parsed.value("/OWNER_SID=").is_none()); + assert_eq!( + parsed.app_args, + [ + "workspace with spaces", + "--flag", + "/UPDATE", + "/OPENBITFUN_TARGET=not-a-target", + "--maintenance-protocol", + "/OWNER_SID=not-an-owner" + ] + ); + } + #[test] + fn native_and_interactive_uninstall_contracts_are_retained() { + assert!(!request("uninstall.exe", &[], None).native); + assert!(!request("maintenance.exe", &["--uninstall", "C:\\Apps"], None).native); + let parsed = request( + "maintenance.exe", + &["--uninstall", "C:\\Apps", "--quiet"], + None, + ); + assert!(parsed.native && parsed.quiet && !parsed.legacy_uninstall); + let parsed = request( + "installer.exe", + &[ + "/UPDATE", + "/READY_EVENT=event", + "/OPENBITFUN_TARGET=C:\\Apps", + ], + None, + ); + assert_eq!(parsed.operation, Operation::Update); + assert_eq!(parsed.target.unwrap(), Path::new(r"C:\Apps")); + } +} diff --git a/OpenBitFun-Installer/src-tauri/src/installer/mod.rs b/OpenBitFun-Installer/src-tauri/src/installer/mod.rs index 66cbb8e3cc..696d0bb5d3 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/mod.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/mod.rs @@ -4,6 +4,7 @@ pub(super) mod commands; mod elevation; mod extract; mod generated_locale_contract; +mod launch; mod transaction; mod types; diff --git a/OpenBitFun-Installer/src-tauri/src/installer/registry.rs b/OpenBitFun-Installer/src-tauri/src/installer/registry.rs index 909c332550..d53d92698a 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/registry.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/registry.rs @@ -51,10 +51,19 @@ pub(super) fn register_uninstall_entry( version: &str, uninstall_command: &str, ) -> Result<()> { - let hkcu = root_for(install_path); - ensure_registration_owner(&hkcu, install_path)?; - let (key, _) = hkcu - .create_subkey(UNINSTALL_KEY) + let hkcu = root_for(install_path)?; + register_uninstall_entry_at(&hkcu, install_path, version, uninstall_command) +} + +fn register_uninstall_entry_at( + root: &RegKey, + install_path: &Path, + version: &str, + uninstall_command: &str, +) -> Result<()> { + let keys = registration_keys(root, install_path)?; + let (key, _) = root + .create_subkey(&keys[0]) .with_context(|| "Failed to create uninstall registry key")?; let exe_path = install_path.join(MAIN_APP_EXE); @@ -62,7 +71,12 @@ pub(super) fn register_uninstall_entry( // Establish ownership before optional metadata so interrupted first-time // registration remains recognizable during journal recovery. key.set_value("InstallLocation", "e_windows_path(install_path))?; - key.set_value("DisplayName", &APP_NAME)?; + let display_name = if keys[0] == UNINSTALL_KEY { + APP_NAME.to_string() + } else { + format!("{APP_NAME} ({})", install_path.display()) + }; + key.set_value("DisplayName", &display_name)?; key.set_value("DisplayVersion", &version)?; key.set_value("Publisher", &TAURI_MANUFACTURER)?; key.set_value("MainBinaryName", &MAIN_APP_EXE)?; @@ -75,16 +89,19 @@ pub(super) fn register_uninstall_entry( key.set_value("NoModify", &1u32)?; key.set_value("NoRepair", &1u32)?; - log::info!("Registered uninstall entry at {}", UNINSTALL_KEY); + log::info!("Registered uninstall entry at {}", keys[0]); Ok(()) } /// Same as Tauri NSIS `WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR` — used for default install dir / upgrades. pub(super) fn register_tauri_install_location(install_path: &Path) -> Result<()> { - let hkcu = root_for(install_path); - ensure_registration_owner(&hkcu, install_path)?; - let path = tauri_manufacturer_product_key(); - let (key, _) = hkcu + let hkcu = root_for(install_path)?; + register_tauri_install_location_at(&hkcu, install_path) +} + +fn register_tauri_install_location_at(root: &RegKey, install_path: &Path) -> Result<()> { + let path = registration_keys(root, install_path)?[1].clone(); + let (key, _) = root .create_subkey(&path) .with_context(|| format!("Failed to create registry key {}", path))?; let dir = install_path.to_string_lossy(); @@ -104,14 +121,28 @@ pub(super) fn read_tauri_install_location() -> Option { /// Remove only keys that still point to the selected installation. pub(super) fn remove_tauri_install_location(install_path: &Path) -> Result<()> { - remove_owned_key(install_path, &tauri_manufacturer_product_key(), "") + for root in [maintenance_user_root()?, RegKey::predef(HKEY_LOCAL_MACHINE)] { + remove_registration_keys(&root, install_path, false)?; + } + Ok(()) } pub(super) fn remove_uninstall_entry(install_path: &Path) -> Result<()> { - remove_owned_key(install_path, UNINSTALL_KEY, "InstallLocation") + for root in [maintenance_user_root()?, RegKey::predef(HKEY_LOCAL_MACHINE)] { + remove_registration_keys(&root, install_path, true)?; + } + Ok(()) } -fn remove_owned_key(install_path: &Path, path: &str, value: &str) -> Result<()> { - let root = root_for(install_path); - delete_owned_key(&root, install_path, path, value) + +fn remove_registration_keys(root: &RegKey, install_path: &Path, uninstall: bool) -> Result<()> { + let (legacy, index, value) = if uninstall { + (UNINSTALL_KEY.to_string(), 0, "InstallLocation") + } else { + (tauri_manufacturer_product_key(), 1, "") + }; + for key in [legacy, installation_keys(install_path)[index].clone()] { + delete_owned_key(root, install_path, &key, value)?; + } + Ok(()) } fn delete_owned_key(root: &RegKey, install_path: &Path, path: &str, value: &str) -> Result<()> { @@ -148,30 +179,33 @@ pub(super) fn remove_autostart_run_entry(install_path: &Path) -> Result<()> { } Ok(()) } -pub(super) fn is_machine_install(path: &Path) -> bool { - !read_uninstall_key(RegKey::predef(HKEY_CURRENT_USER), "hkcu") - .is_some_and(|v| path_matches(&v.install_location, path)) - && (read_uninstall_key(RegKey::predef(HKEY_LOCAL_MACHINE), "hklm") - .is_some_and(|v| path_matches(&v.install_location, path)) - || std::fs::read(path.join(super::transaction::INVENTORY)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .is_some_and(|value| { - value.get("allUsers").and_then(serde_json::Value::as_bool) == Some(true) - }) - // The inventory and registration may already be backed up when an - // interrupted machine uninstall re-enters maintenance. - || std::fs::read(path.join(super::transaction::WORK_DIR).join("journal.json")) - .ok().and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .is_some_and(|value| value.get("schema").and_then(serde_json::Value::as_u64) == Some(1) - && value.pointer("/integrations/registry/machine").and_then(serde_json::Value::as_bool) == Some(true))) +pub(super) fn scope( + path: &Path, +) -> std::result::Result { + let owner = std::env::args() + .skip(1) + .take_while(|arg| !arg.eq_ignore_ascii_case("/ARGS")) + .find_map(|arg| arg.strip_prefix("/OWNER_SID=").map(str::to_string)); + openbitfun_services_core::installation_scope::windows_installation_scope( + path, + APP_NAME, + owner.as_deref(), + ) +} + +pub(super) fn is_machine_install(path: &Path) -> std::result::Result { + scope(path).map(|scope| scope.machine_install) } pub(super) fn validate_scope(path: &Path, all_users: bool) -> Result<()> { - if all_users - && read_uninstall_key(RegKey::predef(HKEY_CURRENT_USER), "hkcu") - .is_some_and(|value| path_matches(&value.install_location, path)) - { + validate_scope_facts(scope(path).map_err(anyhow::Error::msg)?, all_users) +} + +fn validate_scope_facts( + scope: openbitfun_services_core::installation_scope::InstallationScope, + all_users: bool, +) -> Result<()> { + if all_users && scope.current_user_registration && !scope.machine_install { anyhow::bail!("This directory is a current-user installation; retain its scope or uninstall before changing scope"); } Ok(()) @@ -180,16 +214,16 @@ pub(super) fn validate_scope(path: &Path, all_users: bool) -> Result<()> { pub(super) fn installed_version(path: &Path) -> Option { [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE] .into_iter() - .filter_map(|hive| read_uninstall_key(RegKey::predef(hive), "registry")) + .filter_map(|hive| read_installation_at(&RegKey::predef(hive), "registry", path)) .find(|value| path_matches(&value.install_location, path)) .and_then(|value| value.display_version) } -fn root_for(path: &Path) -> RegKey { - RegKey::predef(if is_machine_install(path) { - HKEY_LOCAL_MACHINE +fn root_for(path: &Path) -> Result { + if is_machine_install(path).map_err(anyhow::Error::msg)? { + Ok(RegKey::predef(HKEY_LOCAL_MACHINE)) } else { - HKEY_CURRENT_USER - }) + maintenance_user_root() + } } fn path_matches(value: &str, path: &Path) -> bool { normalize_registry_path(value) @@ -204,33 +238,63 @@ fn command_targets(value: &str, path: &Path) -> bool { }; path_matches(program, &path.join(MAIN_APP_EXE)) } -fn ensure_registration_owner(root: &RegKey, path: &Path) -> Result<()> { - for (name, value) in [ - (UNINSTALL_KEY.to_string(), "InstallLocation"), - (tauri_manufacturer_product_key(), ""), - ] { +fn installation_keys(path: &Path) -> [String; 2] { + let id = super::commands::windows_installation_id(path); + [ + format!("{UNINSTALL_KEY}-{id}"), + format!("{}-{id}", tauri_manufacturer_product_key()), + ] +} + +// Keep updating legacy installations under their original keys. New directories +// get independent sibling keys, so uninstalling a legacy copy cannot erase them. +fn registration_keys(root: &RegKey, path: &Path) -> Result<[String; 2]> { + let keys = installation_keys(path); + let mut scoped_registration = false; + for (name, value) in [(&keys[0], "InstallLocation"), (&keys[1], "")] { + match root.open_subkey(name) { + Ok(key) => { + let existing: String = key.get_value(value)?; + anyhow::ensure!(path_matches(&existing, path), "Installation registration belongs to another directory; registry data was preserved"); + scoped_registration = true; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + } + if scoped_registration { + return Ok(keys); + } + let legacy = [UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()]; + for (name, value) in [(&legacy[0], "InstallLocation"), (&legacy[1], "")] { match root.open_subkey(name) { Ok(key) => { let existing: String = key.get_value(value).context( "Cannot establish existing installation ownership; registry data was preserved", )?; - anyhow::ensure!(path_matches(&existing, path), "An installation is registered at {existing}; select that directory to update or uninstall it first"); // Older desktop builds rewrote the manufacturer location even // in development. The owned uninstall record is authoritative; // a successful maintenance transaction repairs that stale hint. - return Ok(()); + if path_matches(&existing, path) { + return Ok(legacy.clone()); + } + break; } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error.into()), } } - Ok(()) + Ok(keys) } #[derive(serde::Serialize, serde::Deserialize)] pub(super) struct Snapshot { machine: bool, - keys: Vec)>>>, + keys: Vec, + #[serde(default)] + installation_keys: Vec, + #[serde(default)] + other_registration: Option, #[serde(default)] user_sid: Option, #[serde(default)] @@ -239,6 +303,16 @@ pub(super) struct Snapshot { context_keys: Vec<(String, Vec<(String, Vec<(String, u32, Vec)>)>)>, } +type KeySnapshot = Option)>>; + +#[derive(serde::Serialize, serde::Deserialize)] +struct RegistrationSnapshot { + machine: bool, + keys: Vec, + #[serde(default)] + installation_keys: Vec, +} + const CONTEXT_KEYS: [&str; 2] = [ r"Software\Classes\Directory\Background\shell\OpenBitFun", r"Software\Classes\Directory\shell\OpenBitFun", @@ -246,6 +320,8 @@ const CONTEXT_KEYS: [&str; 2] = [ fn maintenance_user_sid() -> Result { let sid = std::env::args() + .skip(1) + .take_while(|arg| !arg.eq_ignore_ascii_case("/ARGS")) .find_map(|arg| arg.strip_prefix("/OWNER_SID=").map(str::to_string)) .map(Ok) .unwrap_or_else(super::elevation::owner_sid) @@ -313,16 +389,9 @@ fn raw_value(kind: u32, bytes: &[u8]) -> Result { }) } -pub(super) fn snapshot(path: &Path, machine: bool) -> Result { - let install_path = path; - let root = RegKey::predef(if machine { - HKEY_LOCAL_MACHINE - } else { - HKEY_CURRENT_USER - }); - ensure_registration_owner(&root, path)?; +fn snapshot_registration_keys(root: &RegKey, names: &[String]) -> Result> { let mut keys = Vec::new(); - for name in [UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()] { + for name in names { keys.push(match root.open_subkey(name) { Ok(key) => Some( key.enum_values() @@ -333,8 +402,45 @@ pub(super) fn snapshot(path: &Path, machine: bool) -> Result { Err(e) => return Err(e.into()), }); } + Ok(keys) +} + +pub(super) fn snapshot(path: &Path, machine: bool) -> Result { + let install_path = path; let sid = maintenance_user_sid()?; let user = user_root(&sid)?; + let root = if machine { + RegKey::predef(HKEY_LOCAL_MACHINE) + } else { + user_root(&sid)? + }; + registration_keys(&root, path)?; + // Keep the legacy two-key payload intact for interrupted older transactions. + let keys = snapshot_registration_keys( + &root, + &[UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()], + )?; + let installation_keys = snapshot_registration_keys(&root, &installation_keys(path))?; + let scope = scope(path).map_err(anyhow::Error::msg)?; + let other_registration = if (machine && scope.current_user_registration) + || (!machine && scope.machine_registration) + { + let other = if machine { + user_root(&sid)? + } else { + RegKey::predef(HKEY_LOCAL_MACHINE) + }; + Some(RegistrationSnapshot { + machine: !machine, + keys: snapshot_registration_keys( + &other, + &[UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()], + )?, + installation_keys: snapshot_registration_keys(&other, &self::installation_keys(path))?, + }) + } else { + None + }; let mut user_values = Vec::new(); for (path, name) in [ ("Environment", "Path"), @@ -380,31 +486,82 @@ pub(super) fn snapshot(path: &Path, machine: bool) -> Result { Ok(Snapshot { machine, keys, + installation_keys, + other_registration, user_sid: Some(sid), user_values, context_keys, }) } -pub(super) fn restore(install_path: &Path, snapshot: &Snapshot) -> Result<()> { +fn restore_registration_keys( + root: &RegKey, + install_path: &Path, + snapshot: &Snapshot, +) -> Result<()> { + restore_registration_values( + root, + install_path, + &snapshot.keys, + &snapshot.installation_keys, + ) +} + +fn restore_registration_values( + root: &RegKey, + install_path: &Path, + keys: &[KeySnapshot], + installation: &[KeySnapshot], +) -> Result<()> { + anyhow::ensure!(keys.len() == 2, "Invalid registry recovery snapshot"); anyhow::ensure!( - snapshot.keys.len() == 2, - "Invalid registry recovery snapshot" + installation.is_empty() || installation.len() == 2, + "Invalid per-installation registry recovery snapshot" ); - let root = RegKey::predef(if snapshot.machine { - HKEY_LOCAL_MACHINE - } else { - HKEY_CURRENT_USER - }); - for ((path, name), original) in [ + let mut paths = vec![ (UNINSTALL_KEY.to_string(), "InstallLocation"), (tauri_manufacturer_product_key(), ""), - ] - .into_iter() - .zip(&snapshot.keys) - { + ]; + if !installation.is_empty() { + let scoped = installation_keys(install_path); + paths.extend([ + (scoped[0].clone(), "InstallLocation"), + (scoped[1].clone(), ""), + ]); + } + let originals = keys.iter().chain(installation).collect::>(); + let mut preserve_foreign = vec![false; paths.len()]; + for (index, ((path, name), original)) in paths.iter().zip(&originals).enumerate() { + if index < 2 && !installation.is_empty() { + // A new directory does not own the shared legacy records. Do not + // roll back another installation's metadata or resurrect its keys. + use winreg::types::FromRegValue; + let originally_owned = original + .as_ref() + .and_then(|values| values.iter().find(|(key, _, _)| key == name)) + .map(|(_, kind, bytes)| -> Result { + Ok(path_matches( + &String::from_reg_value(&raw_value(*kind, bytes)?)?, + install_path, + )) + }) + .transpose()? + .unwrap_or(false); + let currently_owned = match root + .open_subkey(path) + .and_then(|key| key.get_value::(*name)) + { + Ok(value) => path_matches(&value, install_path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(error) => return Err(error.into()), + }; + if !originally_owned && !currently_owned { + preserve_foreign[index] = true; + continue; + } + } match root.open_subkey(&path) { - Ok(key) => match key.get_value::(name) { + Ok(key) => match key.get_value::(*name) { Ok(value) => anyhow::ensure!( path_matches(&value, install_path) || original.as_ref().is_some_and(|values| { @@ -430,10 +587,10 @@ pub(super) fn restore(install_path: &Path, snapshot: &Snapshot) -> Result<()> { Err(error) => return Err(error.into()), } } - for (path, values) in [UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()] - .iter() - .zip(&snapshot.keys) - { + for (index, ((path, _), values)) in paths.iter().zip(originals).enumerate() { + if preserve_foreign[index] { + continue; + } if let Some(values) = values { let (key, _) = root.create_subkey(path)?; let names = key @@ -475,6 +632,39 @@ pub(super) fn restore(install_path: &Path, snapshot: &Snapshot) -> Result<()> { } } } + Ok(()) +} + +pub(super) fn restore(install_path: &Path, snapshot: &Snapshot) -> Result<()> { + if let Some(sid) = &snapshot.user_sid { + anyhow::ensure!( + sid == &maintenance_user_sid()?, + "Registry recovery belongs to another user" + ); + } + let root = if snapshot.machine { + RegKey::predef(HKEY_LOCAL_MACHINE) + } else if let Some(sid) = &snapshot.user_sid { + user_root(sid)? + } else { + RegKey::predef(HKEY_CURRENT_USER) + }; + restore_registration_keys(&root, install_path, snapshot)?; + if let Some(other) = &snapshot.other_registration { + anyhow::ensure!( + other.machine != snapshot.machine, + "Invalid duplicate-registration recovery scope" + ); + let root = + if other.machine { + RegKey::predef(HKEY_LOCAL_MACHINE) + } else { + user_root(snapshot.user_sid.as_deref().ok_or_else(|| { + anyhow::anyhow!("Duplicate registration recovery has no owner") + })?)? + }; + restore_registration_values(&root, install_path, &other.keys, &other.installation_keys)?; + } if let Some(sid) = &snapshot.user_sid { anyhow::ensure!( sid == &maintenance_user_sid()?, @@ -579,6 +769,236 @@ fn merge_owned_path(previous: &str, present: &str, install_path: &Path) -> Strin #[cfg(test)] mod maintenance_tests { use super::*; + + #[test] + fn duplicate_user_registration_does_not_change_an_existing_machine_scope() { + use openbitfun_services_core::installation_scope::InstallationScope; + let mut facts = InstallationScope { + current_user_registration: true, + machine_registration: true, + machine_install: true, + }; + assert!(validate_scope_facts(facts, true).is_ok()); + facts.machine_install = false; + assert!(validate_scope_facts(facts, true).is_err()); + assert!(validate_scope_facts(facts, false).is_ok()); + facts.current_user_registration = false; + assert!(validate_scope_facts(facts, true).is_ok()); + } + + struct RegistryFixture(String, RegKey); + + impl RegistryFixture { + fn new() -> Self { + let name = format!( + r"Software\OpenBitFunMaintenanceTests\{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + let (root, _) = RegKey::predef(HKEY_CURRENT_USER) + .create_subkey(&name) + .unwrap(); + Self(name, root) + } + } + + impl Drop for RegistryFixture { + fn drop(&mut self) { + RegKey::predef(HKEY_CURRENT_USER) + .delete_subkey_all(&self.0) + .unwrap(); + } + } + + fn registration_snapshot(root: &RegKey, path: &Path) -> Snapshot { + Snapshot { + machine: false, + keys: snapshot_registration_keys( + root, + &[UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()], + ) + .unwrap(), + installation_keys: snapshot_registration_keys(root, &installation_keys(path)).unwrap(), + other_registration: None, + user_sid: None, + user_values: Vec::new(), + context_keys: Vec::new(), + } + } + + #[test] + fn duplicate_hive_records_are_removed_and_restored_without_touching_other_directories() { + let fixture = RegistryFixture::new(); + let (user, _) = fixture.1.create_subkey("User").unwrap(); + let (machine, _) = fixture.1.create_subkey("Machine").unwrap(); + let ours = Path::new(r"C:\Apps\OpenBitFun"); + let other = Path::new(r"D:\Other\OpenBitFun"); + for hive in [&user, &machine] { + register_uninstall_entry_at(hive, ours, "1.0.11", "uninstall.exe").unwrap(); + register_tauri_install_location_at(hive, ours).unwrap(); + register_uninstall_entry_at(hive, other, "1.0.11", "other.exe").unwrap(); + } + let original = registration_snapshot(&user, ours); + let extra = RegistrationSnapshot { + machine: true, + keys: snapshot_registration_keys( + &machine, + &[UNINSTALL_KEY.to_string(), tauri_manufacturer_product_key()], + ) + .unwrap(), + installation_keys: snapshot_registration_keys(&machine, &installation_keys(ours)) + .unwrap(), + }; + for hive in [&user, &machine] { + remove_registration_keys(hive, ours, false).unwrap(); + remove_registration_keys(hive, ours, true).unwrap(); + assert!(read_installation_at(hive, "fixture", ours).is_none()); + assert!(read_installation_at(hive, "fixture", other).is_some()); + } + restore_registration_keys(&user, ours, &original).unwrap(); + let extra: RegistrationSnapshot = + serde_json::from_slice(&serde_json::to_vec(&extra).unwrap()).unwrap(); + restore_registration_values(&machine, ours, &extra.keys, &extra.installation_keys).unwrap(); + assert!(read_installation_at(&user, "fixture", ours).is_some()); + assert!(read_installation_at(&machine, "fixture", ours).is_some()); + } + + #[test] + fn parallel_installations_register_update_rollback_and_uninstall_independently() { + let fixture = RegistryFixture::new(); + let root = &fixture.1; + let first = Path::new(r"C:\Apps\OpenBitFun"); + let second = Path::new(r"D:\Apps\OpenBitFun"); + for path in [first, second] { + register_uninstall_entry_at(root, path, "1.0.11", "uninstall.exe").unwrap(); + register_tauri_install_location_at(root, path).unwrap(); + } + assert_ne!(installation_keys(first), installation_keys(second)); + // A legacy runtime may rewrite this global hint. It must not move an + // already registered independent installation back to the global keys. + root.create_subkey(tauri_manufacturer_product_key()) + .unwrap() + .0 + .set_value("", &second.to_string_lossy().as_ref()) + .unwrap(); + assert_eq!( + registration_keys(root, second).unwrap(), + installation_keys(second) + ); + let snapshot = registration_snapshot(root, second); + register_uninstall_entry_at(root, second, "1.0.12", "uninstall.exe").unwrap(); + assert_eq!( + read_installation_at(root, "fixture", first) + .unwrap() + .display_version + .as_deref(), + Some("1.0.11") + ); + assert_eq!( + read_installation_at(root, "fixture", second) + .unwrap() + .display_version + .as_deref(), + Some("1.0.12") + ); + restore_registration_keys(root, second, &snapshot).unwrap(); + assert_eq!( + read_installation_at(root, "fixture", second) + .unwrap() + .display_version + .as_deref(), + Some("1.0.11") + ); + for (key, value) in installation_keys(first).iter().zip(["InstallLocation", ""]) { + delete_owned_key(root, first, key, value).unwrap(); + } + assert!(read_installation_at(root, "fixture", first).is_none()); + assert_eq!( + read_first_installation(root, "fixture") + .unwrap() + .install_location, + second.to_string_lossy() + ); + } + + #[test] + fn legacy_registration_and_recovery_payloads_remain_compatible() { + let fixture = RegistryFixture::new(); + let root = &fixture.1; + let legacy = Path::new(r"C:\Legacy\OpenBitFun"); + let second = Path::new(r"D:\Other\OpenBitFun"); + let (key, _) = root.create_subkey(UNINSTALL_KEY).unwrap(); + key.set_value("InstallLocation", "e_windows_path(legacy)) + .unwrap(); + key.set_value("DisplayVersion", &"1.0.10").unwrap(); + let (hint, _) = root + .create_subkey(tauri_manufacturer_product_key()) + .unwrap(); + hint.set_value("", &r"C:\OldDevelopmentHost").unwrap(); + let original = registration_snapshot(root, legacy); + // This is the shape written before per-directory registration existed. + let old_payload = serde_json::json!({"machine": false, "keys": original.keys}); + let old: Snapshot = serde_json::from_value(old_payload.clone()).unwrap(); + assert!(old.installation_keys.is_empty()); + register_uninstall_entry_at(root, legacy, "1.0.11", "uninstall.exe").unwrap(); + register_tauri_install_location_at(root, legacy).unwrap(); + assert_eq!(registration_keys(root, legacy).unwrap()[0], UNINSTALL_KEY); + assert_eq!( + hint.get_value::("").unwrap(), + legacy.to_string_lossy() + ); + restore_registration_keys(root, legacy, &old).unwrap(); + assert_eq!( + key.get_value::("DisplayVersion").unwrap(), + "1.0.10" + ); + assert_eq!( + hint.get_value::("").unwrap(), + r"C:\OldDevelopmentHost" + ); + let before_new = registration_snapshot(root, second); + register_uninstall_entry_at(root, second, "1.0.11", "uninstall.exe").unwrap(); + register_tauri_install_location_at(root, second).unwrap(); + assert_eq!( + key.get_value::("DisplayVersion").unwrap(), + "1.0.10" + ); + register_uninstall_entry_at(root, legacy, "1.0.12", "uninstall.exe").unwrap(); + restore_registration_keys(root, second, &before_new).unwrap(); + assert!(read_installation_at(root, "fixture", second).is_none()); + assert_eq!( + read_installation_at(root, "fixture", legacy) + .unwrap() + .display_version + .as_deref(), + Some("1.0.12") + ); + + // Older readers still see exactly the original two legacy key snapshots. + #[derive(serde::Deserialize, serde::Serialize)] + struct LegacySnapshot { + machine: bool, + keys: Vec, + } + let old_reader: LegacySnapshot = + serde_json::from_value(serde_json::to_value(&original).unwrap()).unwrap(); + assert_eq!(serde_json::to_value(old_reader).unwrap(), old_payload); + let roundtrip: Snapshot = + serde_json::from_slice(&serde_json::to_vec(&old).unwrap()).unwrap(); + restore_registration_keys(root, legacy, &roundtrip).unwrap(); + } + + #[test] + fn directory_identity_is_stable_across_windows_path_spellings() { + assert_eq!( + installation_keys(Path::new(r"C:\Apps\OpenBitFun")), + installation_keys(Path::new("c:/apps/openbitfun/")) + ); + } + #[test] fn path_recovery_preserves_concurrent_changes_and_is_idempotent() { let root = Path::new(r"C:\OpenBitFun"); @@ -630,8 +1050,12 @@ pub(super) struct UninstallRegistryData { pub hive: &'static str, } -fn read_uninstall_key(root: RegKey, hive_name: &'static str) -> Option { - let key = root.open_subkey(UNINSTALL_KEY).ok()?; +fn read_uninstall_key( + root: &RegKey, + name: &str, + hive_name: &'static str, +) -> Option { + let key = root.open_subkey(name).ok()?; let install_location: String = key.get_value("InstallLocation").ok()?; let display_version: Option = key.get_value("DisplayVersion").ok(); let uninstall_string: Option = key.get_value("UninstallString").ok(); @@ -643,10 +1067,42 @@ fn read_uninstall_key(root: RegKey, hive_name: &'static str) -> Option Option { + [ + UNINSTALL_KEY.to_string(), + installation_keys(path)[0].clone(), + ] + .iter() + .filter_map(|name| read_uninstall_key(root, name, hive)) + .find(|value| path_matches(&value.install_location, path)) +} + +fn read_first_installation(root: &RegKey, hive: &'static str) -> Option { + if let Some(legacy) = read_uninstall_key(root, UNINSTALL_KEY, hive) { + return Some(legacy); + } + let (parent, product) = UNINSTALL_KEY.rsplit_once('\\')?; + let key = root.open_subkey(parent).ok()?; + let mut names = key.enum_keys().collect::>>().ok()?; + names.sort(); + names + .into_iter() + .filter(|name| name.starts_with(&format!("{product}-"))) + .find_map(|name| { + let name = format!(r"{parent}\{name}"); + let data = read_uninstall_key(root, &name, hive)?; + (installation_keys(Path::new(&data.install_location))[0] == name).then_some(data) + }) +} + /// Detect existing install like NSIS `ReadRegStr` on `UNINSTKEY` (HKCU then HKLM). pub(super) fn read_existing_install_from_uninstall_registry() -> Option { - read_uninstall_key(RegKey::predef(HKEY_CURRENT_USER), "hkcu") - .or_else(|| read_uninstall_key(RegKey::predef(HKEY_LOCAL_MACHINE), "hklm")) + read_first_installation(&RegKey::predef(HKEY_CURRENT_USER), "hkcu") + .or_else(|| read_first_installation(&RegKey::predef(HKEY_LOCAL_MACHINE), "hklm")) } /// Remove OpenBitFun context menu entries (no longer registered on install). diff --git a/OpenBitFun-Installer/src-tauri/src/installer/shortcut.rs b/OpenBitFun-Installer/src-tauri/src/installer/shortcut.rs index e4a7820151..bd32ae7f3c 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/shortcut.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/shortcut.rs @@ -8,10 +8,46 @@ use super::MAIN_APP_EXE; const SHORTCUT_NAME: &str = "OpenBitFun.lnk"; const NESTED_START_MENU_DIR: &str = "OpenBitFun"; +fn installation_shortcut_name(install_path: &Path) -> String { + let label = super::commands::normalized_windows_install_path(install_path) + .chars() + .rev() + .take(60) + .collect::() + .chars() + .rev() + .map(|c| { + if r#"\/:*?"<>|"#.contains(c) || c.is_control() { + '_' + } else { + c + } + }) + .collect::(); + format!( + "OpenBitFun ({} - {}).lnk", + label, + &super::commands::windows_installation_id(install_path)[..12] + ) +} + +fn shortcut_path(directory: &Path, install_path: &Path) -> Result { + let legacy = directory.join(SHORTCUT_NAME); + if legacy.try_exists()? + && super::commands::windows_path_eq_case_insensitive( + &shortcut_target(&legacy)?, + &install_path.join(MAIN_APP_EXE), + ) + { + return Ok(legacy); + } + Ok(directory.join(installation_shortcut_name(install_path))) +} + /// Create a desktop shortcut for OpenBitFun. pub(super) fn create_desktop_shortcut(install_path: &Path) -> Result<()> { let desktop = desktop_dir(install_path)?; - let shortcut_path = desktop.join(SHORTCUT_NAME); + let shortcut_path = shortcut_path(&desktop, install_path)?; let exe_path = install_path.join(MAIN_APP_EXE); create_lnk(&shortcut_path, &exe_path, install_path)?; @@ -23,7 +59,7 @@ pub(super) fn create_desktop_shortcut(install_path: &Path) -> Result<()> { pub(super) fn create_start_menu_shortcut(install_path: &Path) -> Result<()> { let start_menu = get_start_menu_dir(install_path)?; remove_nested_start_menu_shortcut(&start_menu, install_path)?; - let shortcut_path = start_menu.join(SHORTCUT_NAME); + let shortcut_path = shortcut_path(&start_menu, install_path)?; let exe_path = install_path.join(MAIN_APP_EXE); create_lnk(&shortcut_path, &exe_path, install_path)?; @@ -33,8 +69,10 @@ pub(super) fn create_start_menu_shortcut(install_path: &Path) -> Result<()> { /// Remove desktop shortcut. pub(super) fn remove_desktop_shortcut(install_path: &Path) -> Result<()> { + let desktop = desktop_dir(install_path)?; + remove_owned_shortcut(&desktop.join(SHORTCUT_NAME), install_path)?; remove_owned_shortcut( - &desktop_dir(install_path)?.join(SHORTCUT_NAME), + &desktop.join(installation_shortcut_name(install_path)), install_path, ) } @@ -44,13 +82,17 @@ pub(super) fn remove_start_menu_shortcut(install_path: &Path) -> Result<()> { let start_menu = get_start_menu_dir(install_path)?; let shortcut_path = start_menu.join(SHORTCUT_NAME); remove_owned_shortcut(&shortcut_path, install_path)?; + remove_owned_shortcut( + &start_menu.join(installation_shortcut_name(install_path)), + install_path, + )?; remove_nested_start_menu_shortcut(&start_menu, install_path)?; Ok(()) } /// Get the current user's Start Menu Programs directory. fn desktop_dir(install_path: &Path) -> Result { - if super::registry::is_machine_install(install_path) { + if super::registry::is_machine_install(install_path).map_err(anyhow::Error::msg)? { Ok(PathBuf::from(std::env::var("PUBLIC")?).join("Desktop")) } else { dirs::desktop_dir().with_context(|| "Cannot find Desktop directory") @@ -58,11 +100,13 @@ fn desktop_dir(install_path: &Path) -> Result { } fn get_start_menu_dir(install_path: &Path) -> Result { - let appdata = std::env::var(if super::registry::is_machine_install(install_path) { - "PROGRAMDATA" - } else { - "APPDATA" - }) + let appdata = std::env::var( + if super::registry::is_machine_install(install_path).map_err(anyhow::Error::msg)? { + "PROGRAMDATA" + } else { + "APPDATA" + }, + ) .with_context(|| "Start Menu location is unavailable")?; Ok(PathBuf::from(appdata) .join("Microsoft") @@ -109,9 +153,11 @@ fn remove_owned_shortcut(path: &Path, install_path: &Path) -> Result<()> { pub(super) struct Snapshot { files: Vec>>, machine: bool, + #[serde(default)] + installation_files: Vec>>, } -pub(super) fn snapshot(_install_path: &Path, machine: bool) -> Result { +pub(super) fn snapshot(install_path: &Path, machine: bool) -> Result { let start = PathBuf::from(std::env::var(if machine { "PROGRAMDATA" } else { @@ -128,15 +174,25 @@ pub(super) fn snapshot(_install_path: &Path, machine: bool) -> Result start.join(SHORTCUT_NAME), start.join(NESTED_START_MENU_DIR).join(SHORTCUT_NAME), ]; - let files = paths + let files = snapshot_files(&paths)?; + let name = installation_shortcut_name(install_path); + let installation_files = snapshot_files(&[desktop.join(&name), start.join(&name)])?; + Ok(Snapshot { + files, + machine, + installation_files, + }) +} + +fn snapshot_files(paths: &[PathBuf]) -> Result>>> { + Ok(paths .iter() .map(|path| match std::fs::read(path) { Ok(bytes) => Ok(Some(bytes)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e), }) - .collect::>>()?; - Ok(Snapshot { files, machine }) + .collect::>>()?) } pub(super) fn restore(install_path: &Path, snapshot: &Snapshot) -> Result<()> { @@ -154,12 +210,32 @@ pub(super) fn restore(install_path: &Path, snapshot: &Snapshot) -> Result<()> { } else { dirs::desktop_dir().with_context(|| "Desktop is unavailable")? }; - let paths = [ + let mut paths = vec![ desktop.join(SHORTCUT_NAME), start.join(SHORTCUT_NAME), start.join(NESTED_START_MENU_DIR).join(SHORTCUT_NAME), ]; - for (path, bytes) in paths.iter().zip(&snapshot.files) { + anyhow::ensure!( + snapshot.installation_files.is_empty() || snapshot.installation_files.len() == 2, + "Invalid per-installation shortcut recovery snapshot" + ); + if !snapshot.installation_files.is_empty() { + let name = installation_shortcut_name(install_path); + paths.extend([desktop.join(&name), start.join(&name)]); + } + restore_files( + install_path, + &paths, + snapshot.files.iter().chain(&snapshot.installation_files), + ) +} + +fn restore_files<'a>( + install_path: &Path, + paths: &[PathBuf], + files: impl Iterator>>, +) -> Result<()> { + for (path, bytes) in paths.iter().zip(files) { if let Some(bytes) = bytes { if std::fs::read(path).is_ok_and(|current| current == *bytes) { continue; @@ -210,3 +286,71 @@ fn create_lnk(shortcut_path: &Path, target: &Path, _working_dir: &Path) -> Resul ); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parallel_shortcuts_and_legacy_shortcuts_survive_other_installation_maintenance() { + let temp = tempfile::tempdir().unwrap(); + let first = temp.path().join("first"); + let second = temp.path().join("second"); + let links = temp.path().join("links"); + for path in [&first, &second, &links] { + std::fs::create_dir(path).unwrap(); + } + let ping = PathBuf::from(std::env::var_os("SYSTEMROOT").unwrap()).join("System32/ping.exe"); + for path in [&first, &second] { + std::fs::copy(&ping, path.join(MAIN_APP_EXE)).unwrap(); + } + let legacy = links.join(SHORTCUT_NAME); + create_lnk(&legacy, &first.join(MAIN_APP_EXE), &first).unwrap(); + let additional = shortcut_path(&links, &second).unwrap(); + assert_ne!(legacy, additional); + let before = snapshot_files(&[legacy.clone(), additional.clone()]).unwrap(); + create_lnk(&additional, &second.join(MAIN_APP_EXE), &second).unwrap(); + assert_eq!(shortcut_path(&links, &first).unwrap(), legacy); + assert!(super::super::commands::windows_path_eq_case_insensitive( + &shortcut_target(&legacy).unwrap(), + &first.join(MAIN_APP_EXE) + )); + restore_files( + &second, + &[legacy.clone(), additional.clone()], + before.iter(), + ) + .unwrap(); + assert!(legacy.is_file()); + assert!(!additional.exists()); + create_lnk(&additional, &second.join(MAIN_APP_EXE), &second).unwrap(); + remove_owned_shortcut(&legacy, &second).unwrap(); + assert!(legacy.is_file()); + remove_owned_shortcut(&additional, &second).unwrap(); + assert!(legacy.is_file()); + assert!(!additional.exists()); + } + + #[test] + fn legacy_shortcut_snapshots_roundtrip_without_new_required_fields() { + let payload = serde_json::json!({"files": [null, [1, 2, 3], null], "machine": true}); + let snapshot: Snapshot = serde_json::from_value(payload.clone()).unwrap(); + assert!(snapshot.installation_files.is_empty()); + let roundtrip: Snapshot = + serde_json::from_slice(&serde_json::to_vec(&snapshot).unwrap()).unwrap(); + assert_eq!(roundtrip.files, snapshot.files); + assert_eq!(roundtrip.machine, snapshot.machine); + #[derive(serde::Deserialize, serde::Serialize)] + struct LegacySnapshot { + files: Vec>>, + machine: bool, + } + let old_reader: LegacySnapshot = + serde_json::from_value(serde_json::to_value(&snapshot).unwrap()).unwrap(); + assert_eq!(serde_json::to_value(old_reader).unwrap(), payload); + assert_eq!( + installation_shortcut_name(Path::new(r"C:\Apps\OpenBitFun")), + installation_shortcut_name(Path::new("c:/apps/openbitfun/")) + ); + } +} diff --git a/OpenBitFun-Installer/src-tauri/src/installer/transaction.rs b/OpenBitFun-Installer/src-tauri/src/installer/transaction.rs index 256525338b..3f6fb45924 100644 --- a/OpenBitFun-Installer/src-tauri/src/installer/transaction.rs +++ b/OpenBitFun-Installer/src-tauri/src/installer/transaction.rs @@ -11,6 +11,30 @@ pub(super) const WORK_DIR: &str = ".openbitfun-maintenance"; pub(super) const LOCK_FILE: &str = ".openbitfun-maintenance.lock"; pub(super) const INVENTORY: &str = ".openbitfun-installed.json"; +/// Probe the same sibling lock used by maintenance, before an unelevated host +/// promises it can write. Existing installations can have a writable root but +/// a protected parent; opening an existing lock still requires write access. +pub(super) fn probe_lock_access(root: &Path) -> std::io::Result<()> { + if !root.exists() { + return Ok(()); + } + let root = root.canonicalize()?; + let name = root + .file_name() + .ok_or_else(|| std::io::Error::other("Installation has no directory name"))? + .to_string_lossy(); + let parent = root + .parent() + .ok_or_else(|| std::io::Error::other("Installation has no parent"))?; + let _file = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(parent.join(format!(".{name}.maintenance.lock")))?; + Ok(()) +} + #[derive(Serialize, Deserialize)] struct Entry { path: String, @@ -380,22 +404,33 @@ impl Transaction { fn clean_work(&self) -> Result<(), String> { // Never follow links while recursively deleting our own transaction tree. - fn remove_tree(path: &Path) -> Result<(), String> { + fn remove_tree(path: &Path, keep_journal_until_last: bool) -> Result<(), String> { if !path.exists() { return Ok(()); } for entry in fs::read_dir(path).map_err(|e| e.to_string())? { let entry = entry.map_err(|e| e.to_string())?; + if keep_journal_until_last && entry.file_name() == "journal.json" { + continue; + } checked_path(path, Path::new(&entry.file_name()))?; if entry.file_type().map_err(|e| e.to_string())?.is_dir() { - remove_tree(&entry.path())?; + remove_tree(&entry.path(), false)?; } else { fs::remove_file(entry.path()).map_err(|e| e.to_string())?; } } + if keep_journal_until_last { + let journal = checked_path(path, Path::new("journal.json"))?; + match fs::remove_file(journal) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.to_string()), + } + } fs::remove_dir(path).map_err(|e| e.to_string()) } - remove_tree(&self.work) + remove_tree(&self.work, true) } } @@ -403,6 +438,90 @@ impl Transaction { mod tests { use super::*; + #[cfg(windows)] + #[test] + fn lock_probe_detects_a_protected_parent_even_when_the_installation_is_writable() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("OpenBitFun"); + fs::create_dir(&root).unwrap(); + let script = r#"$ErrorActionPreference='Stop' +$sid=[Security.Principal.WindowsIdentity]::GetCurrent().User +$acl=Get-Acl -LiteralPath $env:OPENBITFUN_LOCK_PARENT +$rule=[Security.AccessControl.FileSystemAccessRule]::new($sid,[Security.AccessControl.FileSystemRights]::CreateFiles,[Security.AccessControl.InheritanceFlags]::None,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Deny) +if($env:OPENBITFUN_LOCK_RESTORE -eq '1'){$acl.RemoveAccessRuleSpecific($rule)}else{$acl.AddAccessRule($rule)} +Set-Acl -LiteralPath $env:OPENBITFUN_LOCK_PARENT -AclObject $acl +"#; + let acl = |restore: bool| { + super::super::commands::create_windows_silent_command( + super::super::commands::system_powershell().unwrap(), + ) + .args(["-NoProfile", "-NonInteractive", "-Command", script]) + .env( + "PSModulePath", + super::super::commands::system_powershell() + .unwrap() + .parent() + .unwrap() + .join("Modules"), + ) + .env("OPENBITFUN_LOCK_PARENT", temp.path()) + .env("OPENBITFUN_LOCK_RESTORE", if restore { "1" } else { "0" }) + .output() + .unwrap() + }; + let configured = acl(false); + if !configured.status.success() { + let _ = acl(true); + panic!( + "Cannot configure temporary ACL: {}", + String::from_utf8_lossy(&configured.stderr) + ); + } + let target_writable = tempfile::NamedTempFile::new_in(&root).is_ok(); + let lock = probe_lock_access(&root); + let restored = acl(true); + assert!( + restored.status.success(), + "{}", + String::from_utf8_lossy(&restored.stderr) + ); + assert!(target_writable); + assert_eq!( + lock.unwrap_err().kind(), + std::io::ErrorKind::PermissionDenied + ); + probe_lock_access(&root).unwrap(); + } + + #[cfg(windows)] + #[test] + fn cleanup_failure_keeps_committed_journal_until_retry_finishes() { + use std::os::windows::fs::OpenOptionsExt; + let temp = tempfile::tempdir().unwrap(); + fs::write(temp.path().join("app.exe"), b"old").unwrap(); + let mut tx = Transaction::open(temp.path()).unwrap(); + staged(&tx, "app.exe", b"new"); + tx.publish(&["app.exe".into()], &[]).unwrap(); + // On NTFS this sorts after journal.json. Cleanup must retain the journal + // even when earlier backup cleanup succeeded before this file blocks it. + fs::write(tx.stage().join("locked.tmp"), b"staging residue").unwrap(); + let held = OpenOptions::new() + .read(true) + .share_mode(1) + .open(tx.stage().join("locked.tmp")) + .unwrap(); + assert!(!tx.commit().unwrap()); + let journal: Journal = + serde_json::from_slice(&fs::read(tx.work.join("journal.json")).unwrap()).unwrap(); + assert!(journal.committed); + drop(held); + drop(tx); + let next = Transaction::open(temp.path()).unwrap(); + assert_eq!(fs::read(temp.path().join("app.exe")).unwrap(), b"new"); + assert!(!next.work.join("journal.json").exists()); + assert!(!next.stage().join("locked.tmp").exists()); + } + fn staged(transaction: &Transaction, name: &str, bytes: &[u8]) { let target = transaction.stage().join(name); fs::create_dir_all(target.parent().unwrap()).unwrap(); diff --git a/OpenBitFun-Installer/src-tauri/src/lib.rs b/OpenBitFun-Installer/src-tauri/src/lib.rs index 00e72c1058..d581b382a4 100644 --- a/OpenBitFun-Installer/src-tauri/src/lib.rs +++ b/OpenBitFun-Installer/src-tauri/src/lib.rs @@ -9,7 +9,7 @@ pub fn run() { Ok(true) => return, Ok(false) => {} Err(error) => { - if std::env::args().any(|arg| arg == "--quiet") { + if commands::maintenance_is_non_interactive() { eprintln!("Cannot start uninstaller: {error}"); } else { show_native_error(&format!("Cannot start uninstaller: {error}")); @@ -32,7 +32,7 @@ pub fn run() { commands::persist_native_outcome(code, result.as_ref().err().map(String::as_str)); if let Err(error) = result { eprintln!("Maintenance failed: {error}"); - if !std::env::args().any(|arg| arg.starts_with("/READY_EVENT=") || arg == "--quiet") { + if !commands::maintenance_is_non_interactive() { show_native_error(&error); } std::process::exit(code as i32); diff --git a/OpenBitFun-Installer/src/i18n/locales/en.json b/OpenBitFun-Installer/src/i18n/locales/en.json index 1265ab80ca..e155dcdc3a 100644 --- a/OpenBitFun-Installer/src/i18n/locales/en.json +++ b/OpenBitFun-Installer/src/i18n/locales/en.json @@ -42,12 +42,11 @@ "back": "Back", "install": "Install", "installing": "Preparing…", - "existingInstallTitle": "OpenBitFun is installed. You can update or repair it in place.", + "existingInstallTitle": "OpenBitFun is installed. Update this copy or choose another directory to install an additional copy.", "existingInstallVersion": "Installed version: {{version}}", "existingInstallLocation": "Install location: {{path}}", "existingInstallBinaryMissing": "The installed app is missing. Reinstall to repair it.", - "existingInstallRunUninstaller": "Run uninstaller", - "allUsers": "Install for all users (administrator authorization required)" + "existingInstallRunUninstaller": "Run uninstaller" }, "model": { "title": "Connect a model", diff --git a/OpenBitFun-Installer/src/i18n/locales/zh-TW.json b/OpenBitFun-Installer/src/i18n/locales/zh-TW.json index 2e60ac2253..96f47737d6 100644 --- a/OpenBitFun-Installer/src/i18n/locales/zh-TW.json +++ b/OpenBitFun-Installer/src/i18n/locales/zh-TW.json @@ -42,12 +42,11 @@ "back": "返回", "install": "安裝", "installing": "準備中…", - "existingInstallTitle": "已安裝 OpenBitFun,可在原位置更新或修復。", + "existingInstallTitle": "已安裝 OpenBitFun,可在原目錄更新,或選擇其他目錄另行安裝。", "existingInstallVersion": "已安裝版本:{{version}}", "existingInstallLocation": "安裝位置:{{path}}", "existingInstallBinaryMissing": "偵測到安裝記錄,主程式缺失,可重新安裝修復。", - "existingInstallRunUninstaller": "運行解除安裝程式", - "allUsers": "為所有使用者安裝(需要系統管理員授權)" + "existingInstallRunUninstaller": "運行解除安裝程式" }, "model": { "title": "連接模型", diff --git a/OpenBitFun-Installer/src/i18n/locales/zh.json b/OpenBitFun-Installer/src/i18n/locales/zh.json index 8071f03cb5..ca947db590 100644 --- a/OpenBitFun-Installer/src/i18n/locales/zh.json +++ b/OpenBitFun-Installer/src/i18n/locales/zh.json @@ -42,12 +42,11 @@ "back": "返回", "install": "安装", "installing": "准备中…", - "existingInstallTitle": "已安装 OpenBitFun,可在原位置更新或修复。", + "existingInstallTitle": "已安装 OpenBitFun,可在原目录更新,或选择其他目录另行安装。", "existingInstallVersion": "已安装版本:{{version}}", "existingInstallLocation": "安装位置:{{path}}", "existingInstallBinaryMissing": "检测到安装记录,主程序缺失,可重新安装修复。", - "existingInstallRunUninstaller": "运行卸载程序", - "allUsers": "为所有用户安装(需要管理员授权)" + "existingInstallRunUninstaller": "运行卸载程序" }, "model": { "title": "连接模型", diff --git a/OpenBitFun-Installer/src/infrastructure/installPathApi.ts b/OpenBitFun-Installer/src/infrastructure/installPathApi.ts index 2426a2c029..5bb182fd5f 100644 --- a/OpenBitFun-Installer/src/infrastructure/installPathApi.ts +++ b/OpenBitFun-Installer/src/infrastructure/installPathApi.ts @@ -3,7 +3,6 @@ import { open } from '@tauri-apps/plugin-dialog'; import type { InstallPathValidation } from '../types/installer'; export const installPathApi = { - defaultPath: (allUsers: boolean) => invoke('get_default_install_path', { allUsers }), validate: (path: string) => invoke('validate_install_path', { path }), chooseDirectory: (defaultPath: string, title: string) => open({ directory: true, defaultPath, title }), }; diff --git a/OpenBitFun-Installer/src/pages/Options.test.tsx b/OpenBitFun-Installer/src/pages/Options.test.tsx index 80520e7767..2a0893fe64 100644 --- a/OpenBitFun-Installer/src/pages/Options.test.tsx +++ b/OpenBitFun-Installer/src/pages/Options.test.tsx @@ -109,21 +109,23 @@ it('keeps the theme page open and shows the error if saving preferences fails', expect(close).not.toHaveBeenCalled(); expect(launch).not.toHaveBeenCalled(); }); -it('keeps installation scope and directory coherent while resolving a machine path, and reports resolution failures', async () => { - let reject!: (error: string) => void; - vi.mocked(invoke).mockImplementationOnce(() => new Promise((_, no) => { reject = no; })); +it('offers shortcut preferences without a scope switch or changing the custom directory', async () => { const changed = vi.fn(); const install = vi.fn(); await act(async () => root.render()); const labels = [...container.querySelectorAll('[data-openbitfun-component="checkbox"]')]; - const scope = labels.find(label => label.textContent?.includes('options.allUsers'))!; - act(() => scope.click()); - expect(changed).not.toHaveBeenCalled(); + expect(labels).toHaveLength(2); + expect(container.textContent).not.toContain('options.allUsers'); + for (const label of labels) { + act(() => label.click()); + const update = changed.mock.lastCall![0]; + expect(update(initial).installPath).toBe(initial.installPath); + expect(update(initial).allUsers).toBeUndefined(); + } + expect(invoke).not.toHaveBeenCalled(); const installButton = [...container.querySelectorAll('button')].find(button => button.textContent === 'options.install')!; - expect(installButton.disabled).toBe(true); - await act(async () => { reject('Cannot locate Program Files'); }); - expect(changed).not.toHaveBeenCalled(); - expect(container.textContent).toContain('errors.maintenance.failed'); - expect(install).not.toHaveBeenCalled(); + expect(installButton.disabled).toBe(false); + await act(async () => installButton.click()); + expect(install).toHaveBeenCalledOnce(); }); diff --git a/OpenBitFun-Installer/src/pages/Options.tsx b/OpenBitFun-Installer/src/pages/Options.tsx index f656bf3de5..a8a0caae08 100644 --- a/OpenBitFun-Installer/src/pages/Options.tsx +++ b/OpenBitFun-Installer/src/pages/Options.tsx @@ -45,7 +45,6 @@ export function Options({ const [pathError, setPathError] = useState(null); const shownError = error ?? pathError; const busy = isInstalling || isSelectingPath; - const existingTarget = Boolean(existingInstall?.detected && existingInstall.installLocation === options.installPath); useEffect(() => { if (options.installPath) refreshDiskSpace(options.installPath); @@ -67,19 +66,6 @@ export function Options({ finally { pathOperation.current = false; setIsSelectingPath(false); } }; - const changeScope = async (allUsers: boolean) => { - if (pathOperation.current) return; - pathOperation.current = true; - setIsSelectingPath(true); - setPathError(null); - try { - const installPath = await installPathApi.defaultPath(allUsers); - setOptions(previous => ({ ...previous, allUsers, installPath })); - clearInstallError(); - } catch (error) { setPathError(String(error)); } - finally { pathOperation.current = false; setIsSelectingPath(false); } - }; - const formatBytes = (bytes: number): string => { if (bytes === 0) return '0 B'; const k = 1024; @@ -165,12 +151,6 @@ export function Options({ onCheckedChange={(checked) => setOptions((prev) => ({ ...prev, startMenu: checked }))} label={t('options.startMenu')} /> - { void changeScope(checked); }} - label={t('options.allUsers')} - /> diff --git a/scripts/updater-maintenance.test.mjs b/scripts/updater-maintenance.test.mjs index 0587cfb223..15da212479 100644 --- a/scripts/updater-maintenance.test.mjs +++ b/scripts/updater-maintenance.test.mjs @@ -17,6 +17,23 @@ test('desktop updates use the official registry crate without a source patch', ( assert.match(updater, /checksum = "[0-9a-f]{64}"/); }); +test('packaged native maintenance does not consume application flags after /ARGS', { + skip: process.platform !== 'win32' || !process.env.OPENBITFUN_INSTALLER_FIXTURE, +}, () => { + // Relative targets fail before publication; this smoke test never installs + // or removes a real application, even if command routing regresses. + for (const args of [ + ['/S', '/D=relative-test-directory', '/ARGS', '--maintenance-protocol'], + ['--uninstall', 'relative-test-directory', '/UPDATE', '/P', '/ARGS', '/OWNER_SID=not-an-owner', '/RESULT_ID=../invalid'], + ]) { + const result = spawnSync(process.env.OPENBITFUN_INSTALLER_FIXTURE, args, + { encoding: 'utf8', windowsHide: true, timeout: 15000 }); + assert.equal(result.status, 1, String(result.error ?? result.stderr)); + assert.match(result.stderr, /INSTALL_PATH::not_absolute/); + assert.equal(result.stdout.trim(), ''); + } +}); + test('native Windows supervisor records startup failure before authorizing application exit', { skip: process.platform !== 'win32' }, t => { const temp = mkdtempSync(join(tmpdir(), "openbitfun-update-'测试-")); t.after(() => rmSync(temp, { recursive: true, force: true })); @@ -27,7 +44,7 @@ test('native Windows supervisor records startup failure before authorizing appli const receipt = join(temp, 'result.json'); const args = { pid: String(process.pid), version: "'2.0.0'", file: quote(join(temp, 'missing-installer.exe')), - parameters: "''", transactional: '$true', event: quote(`Local\\OpenBitFunUpdate-test-${process.pid}`), + parameters: "''", transactional: '$true', msi: '$false', event: quote(`Local\\OpenBitFunUpdate-test-${process.pid}`), elevate: '$false', receipt: quote(receipt), current: quote(join(temp, 'missing-application.exe')), restart: "''", user_results: quote(join(temp, 'user-results')), machine_results: quote(join(temp, 'machine-results')), cleanup: "''", }; @@ -68,3 +85,44 @@ test('native Windows supervisor records startup failure before authorizing appli assert.match(nativeResult.error, /previous files restored/); assert.match(nativeResult.error, /运行时/); }); + +test('Windows supervisor interprets native, NSIS and MSI results by their own contracts', { skip: process.platform !== 'win32' }, t => { + const temp = mkdtempSync(join(tmpdir(), 'openbitfun-update-outcomes-')); + t.after(() => rmSync(temp, { recursive: true, force: true })); + const source = readFileSync(new URL('../src/apps/desktop/src/update_maintenance/windows.rs', import.meta.url), 'utf8'); + const template = source.match(/r#"(\$ErrorActionPreference='Stop'[\s\S]*?)"#,/)?.[1]; + assert.ok(template); + const quote = value => `'${value.replaceAll("'", "''")}'`; + for (const [kind, code, success, reboot] of [ + ['native', 0, true, false], ['native', 2, true, false], ['native', 1, false, false], + ['nsis', 0, true, false], ['nsis', 2, false, false], + ['msi', 0, true, false], ['msi', 3010, true, true], ['msi', 1641, true, true], ['msi', 2, false, false], + ]) { + const receipt = join(temp, `${kind}-${code}.json`); + const event = `Local\\OpenBitFunUpdate-outcome-${process.pid}-${kind}-${code}`; + const args = { pid: '123', version: "'2.0.0'", file: "'mock.exe'", parameters: "''", + transactional: kind === 'native' ? '$true' : '$false', msi: kind === 'msi' ? '$true' : '$false', event: quote(event), + elevate: '$false', receipt: quote(receipt), current: "'unused'", restart: "''", + user_results: quote(temp), machine_results: quote(temp), cleanup: "''" }; + const fields = []; + const script = template.replace(/\{([a-z_]+)\}/g, (_, key) => { + assert.ok(key in args, key); fields.push(args[key]); return `\u0001${fields.length - 1}\u0002`; + }).replaceAll('{{', '{').replaceAll('}}', '}').replace(/\u0001(\d+)\u0002/g, (_, index) => fields[Number(index)]) + .split('if ($result.error -and $announced)')[0]; + const mocks = `function Get-Process { param([int]$Id) + $p=[pscustomobject]@{Handle=0}; $p | Add-Member ScriptMethod WaitForExit {} -PassThru + } + function Start-Process { param([string]$FilePath,[string]$ArgumentList,[switch]$PassThru,[string]$Verb) + if (${args.transactional}) { $ready=[Threading.EventWaitHandle]::OpenExisting(${args.event}); $ready.Set() | Out-Null; $ready.Dispose() } + $p=[pscustomobject]@{HasExited=$true;ExitCode=${code}}; $p | Add-Member ScriptMethod WaitForExit {} -PassThru + } + `; + const result = spawnSync(join(process.env.SYSTEMROOT, 'System32/WindowsPowerShell/v1.0/powershell.exe'), + ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(mocks + script, 'utf16le').toString('base64')], + { encoding: 'utf8', windowsHide: true, timeout: 15000 }); + assert.ok(existsSync(receipt), result.stdout + result.stderr); + const saved = JSON.parse(readFileSync(receipt, 'utf8')); + assert.equal(saved.success, success, `${kind} ${code}: ${saved.error}`); + assert.equal(saved.rebootRequired, reboot, `${kind} ${code}`); + } +}); diff --git a/src/apps/cli/README.md b/src/apps/cli/README.md index 1c5c680b5c..aeab570f54 100644 --- a/src/apps/cli/README.md +++ b/src/apps/cli/README.md @@ -19,6 +19,12 @@ so the updated `PATH` is visible. Official release archives contain the same `openbitfun` executable. +Installation and self-update share an OS-backed lock. On macOS/Linux without +the `flock` command, the installer uses available Perl, Python, or the packaged +CLI lock helper. A PID-file-only `shlock` is not sufficient. Installing an older +release without the helper requires `flock`, Perl, or Python; a missing compatible +lock stops installation before replacing existing files. + Prerequisites for a source install are a Rust toolchain and this repository. See the repository [contribution guide](../../../CONTRIBUTING.md) for development setup and build commands. diff --git a/src/apps/cli/install.sh b/src/apps/cli/install.sh index f945b9ace0..ace2211b56 100755 --- a/src/apps/cli/install.sh +++ b/src/apps/cli/install.sh @@ -158,6 +158,49 @@ assert_plugin_host_resources() { } install_bundle() ( + local primary_source="$1" plugin_host_source="$2" destination="$3" + mkdir -p "$destination" + destination="$(cd "$destination" && pwd -P)" + local lock="$destination/.openbitfun-cli-install.lock" + if command -v flock >/dev/null 2>&1; then + exec 9<>"$lock" + flock -n 9 || { echo "Error: another CLI installation or update is running." >&2; return 1; } + install_bundle_locked "$primary_source" "$plugin_host_source" "$destination" + elif command -v perl >/dev/null 2>&1; then + # Perl uses the same native flock as Rust, including on macOS. Preserve the + # locked descriptor across exec; never unlink a held kernel-lock file. + perl -MFcntl=:DEFAULT,:flock -e ' + sysopen(my $lock, shift @ARGV, O_RDWR|O_CREAT, 0666) or die "Cannot open installation lock: $!\n"; + flock($lock, LOCK_EX|LOCK_NB) or die "Another CLI installation or update is running\n"; + fcntl($lock, F_SETFD, 0) or die "Cannot retain installation lock: $!\n"; + exec @ARGV; die "Cannot start installer: $!\n"; + ' "$lock" bash -euo pipefail -c "$(declare -f); install_bundle_locked \"\$@\"" installer "$primary_source" "$plugin_host_source" "$destination" + elif command -v python3 >/dev/null 2>&1; then + python3 -c ' +import fcntl, os, sys +lock = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT, 0o666) +fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) +os.set_inheritable(lock, True) +os.execvp(sys.argv[2], sys.argv[2:]) +' "$lock" bash -euo pipefail -c "$(declare -f); install_bundle_locked \"\$@\"" installer "$primary_source" "$plugin_host_source" "$destination" + else + local pipes helper marker + pipes="$(mktemp -d "$destination/.openbitfun-lock.XXXXXX")" + mkfifo "$pipes/hold" "$pipes/ready" + "$primary_source" --internal-hold-installation-lock "$lock" <"$pipes/hold" >"$pipes/ready" 2>"$pipes/error" & + helper=$! + exec 9>"$pipes/hold" + trap 'exec 9>&-; wait "$helper" || true; rm -f "$pipes/hold" "$pipes/ready" "$pipes/error"; rmdir "$pipes"' EXIT + if ! IFS= read -r marker <"$pipes/ready" || [ "$marker" != OPENBITFUN_INSTALL_LOCK_V1 ]; then + cat "$pipes/error" >&2 + echo "Error: a compatible native installation lock helper, flock, Perl, or Python is required." >&2 + return 1 + fi + install_bundle_locked "$primary_source" "$plugin_host_source" "$destination" + fi +) + +install_bundle_locked() ( local primary_source="$1" local plugin_host_source="$2" local destination="$3" @@ -168,18 +211,7 @@ install_bundle() ( local primary_committed=0 plugin_host_committed=0 local failed=0 - mkdir -p "$destination" - if command -v flock >/dev/null 2>&1; then - exec 9>"$destination/.openbitfun-cli-install.lock" - flock -n 9 || { echo "Error: another CLI installation or update is running." >&2; return 1; } - elif command -v shlock >/dev/null 2>&1; then - shlock -p "$$" -f "$destination/.openbitfun-cli-install.lock" || { echo "Error: another CLI installation is running." >&2; return 1; } - trap 'rm -f "$destination/.openbitfun-cli-install.lock"' EXIT - else - echo "Error: a native installation lock (flock or shlock) is required." >&2 - return 1 - fi - stage_dir="$(mktemp -d "${destination}/.openbitfun-install.XXXXXX")" + stage_dir="$(mktemp -d "${destination}/.openbitfun-install.XXXXXX")" || return 1 staged_primary="${stage_dir}/openbitfun" staged_plugin_host="${stage_dir}/ext-host" primary_target="${destination}/openbitfun" diff --git a/src/apps/cli/install.test.mjs b/src/apps/cli/install.test.mjs index 71e13089f9..507632d84c 100644 --- a/src/apps/cli/install.test.mjs +++ b/src/apps/cli/install.test.mjs @@ -5,6 +5,69 @@ import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; import test from 'node:test'; +test('Bash fallbacks use the same kernel lock and never fall back to shlock', { skip: process.platform !== 'linux' }, t => { + const temp = mkdtempSync(join(tmpdir(), 'openbitfun-native-lock-')); + t.after(() => rmSync(temp, { recursive: true, force: true })); + const source = readFileSync(new URL('./install.sh', import.meta.url), 'utf8').split('for arg in "$@"; do')[0]; + const script = source + ` +fixture="$OPENBITFUN_INSTALL_TEST_ROOT" +mkdir -p "$fixture/host" +printf host > "$fixture/host/extension-host.js" +cat > "$fixture/source" <<'EXE' +#!/usr/bin/env bash +if [ "$1" = --internal-hold-installation-lock ]; then + exec /usr/bin/python3 -c 'import fcntl,sys; lock=open(sys.argv[1],"a+"); fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB); print("OPENBITFUN_INSTALL_LOCK_V1",flush=True); sys.stdin.buffer.read()' "$2" +fi +echo new +EXE +chmod +x "$fixture/source" +shlock() { echo 'Incorrect PID-file lock fallback' >&2; return 97; } +for BACKEND in perl python native; do + command() { + if [ "$1" = -v ]; then + case "$2" in + flock) return 1;; + perl) [ "$BACKEND" = perl ] || return 1;; + python3) [ "$BACKEND" != native ] || return 1;; + esac + fi + builtin command "$@" + } + destination="$fixture/$BACKEND" + mkdir -p "$destination" + printf old > "$destination/openbitfun" + exec 8<>"$destination/.openbitfun-cli-install.lock" + flock -n 8 + inode=$(stat -c '%i' "$destination/.openbitfun-cli-install.lock") + if install_bundle "$fixture/source" "$fixture/host" "$destination"; then exit 31; fi + [ "$(cat "$destination/openbitfun")" = old ] + [ "$(stat -c '%i' "$destination/.openbitfun-cli-install.lock")" = "$inode" ] + exec 8>&- + install_bundle "$fixture/source" "$fixture/host" "$destination" + [ "$("$destination/openbitfun" --version)" = new ] + [ "$(stat -c '%i' "$destination/.openbitfun-cli-install.lock")" = "$inode" ] + mktemp() { + case "$*" in *'/.openbitfun-install.'*) return 1;; esac + builtin command mktemp "$@" + } + install() { + touch "$OPENBITFUN_INSTALL_TEST_ROOT/unexpected-stage" + return 97 + } + if install_bundle "$fixture/source" "$fixture/host" "$destination"; then exit 32; fi + [ ! -e "$fixture/unexpected-stage" ] + [ "$("$destination/openbitfun" --version)" = new ] + unset -f install mktemp +done +echo 'PASS native lock fallback fixtures' +`; + const file = join(temp, 'fixture.sh'); writeFileSync(file, script); + const result = spawnSync('bash', [file], { encoding: 'utf8', timeout: 30000, + env: { ...process.env, OPENBITFUN_INSTALL_TEST_ROOT: temp } }); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.match(result.stdout, /PASS native lock fallback fixtures/); +}); + test('CLI installer serializes writers, rolls back publication errors and preserves failed recovery copies', t => { const temp = mkdtempSync(join(tmpdir(), 'openbitfun-cli-install-test-')); t.after(() => rmSync(temp, { recursive: true, force: true })); diff --git a/src/apps/cli/src/main.rs b/src/apps/cli/src/main.rs index e6307773a1..c43e678be1 100644 --- a/src/apps/cli/src/main.rs +++ b/src/apps/cli/src/main.rs @@ -1765,6 +1765,15 @@ async fn run_interactive_with_session( mod computer_use; fn main() { + if let Some(result) = + self_update::run_install_lock_helper(&std::env::args_os().skip(1).collect::>()) + { + if let Err(error) = result { + eprintln!("Installation lock failed: {error:#}"); + std::process::exit(1); + } + return; + } // Install the workspace-owned ring CryptoProvider before any TLS-capable // work (relay WS, reqwest rustls paths, Feishu wss) so every client uses // the same explicit process-level provider. diff --git a/src/apps/cli/src/self_update.rs b/src/apps/cli/src/self_update.rs index a845ae4332..ce6486a2d1 100644 --- a/src/apps/cli/src/self_update.rs +++ b/src/apps/cli/src/self_update.rs @@ -259,6 +259,10 @@ impl InstallLock { fn acquire() -> Result { let path = Self::path() .ok_or_else(|| anyhow!("cannot resolve the CLI installation lock location"))?; + Self::acquire_at(&path) + } + + fn acquire_at(path: &Path) -> Result { let mut options = fs::OpenOptions::new(); options.read(true).write(true).create(true).truncate(false); #[cfg(windows)] @@ -282,6 +286,38 @@ impl InstallLock { } } +/// Bootstrap lock holder for systems without a flock command. It runs before +/// any Agent/runtime setup and holds the same kernel lock as self-update until +/// the installing shell closes stdin. It never launches commands itself. +pub(crate) fn run_install_lock_helper(args: &[std::ffi::OsString]) -> Option> { + if args + .first() + .is_none_or(|arg| arg != "--internal-hold-installation-lock") + { + return None; + } + Some((|| { + use std::io::Write; + anyhow::ensure!( + args.len() == 2, + "Installation lock helper requires one lock path" + ); + let path = Path::new(&args[1]); + anyhow::ensure!( + path.is_absolute() + && path + .file_name() + .is_some_and(|name| name == ".openbitfun-cli-install.lock"), + "Invalid installation lock path" + ); + let _lock = InstallLock::acquire_at(path)?; + println!("OPENBITFUN_INSTALL_LOCK_V1"); + std::io::stdout().flush()?; + std::io::copy(&mut std::io::stdin().lock(), &mut std::io::sink())?; + Ok(()) + })()) +} + async fn update_from_configured_sources(check_only: bool) -> Result { let Some(platform_key) = current_platform_key() else { return Ok(UpdateOutcome::Unsupported); @@ -1260,6 +1296,52 @@ mod tests { use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; + #[test] + fn installer_helper_fixture() { + if let Some(path) = std::env::var_os("OPENBITFUN_LOCK_HELPER_FIXTURE") { + run_install_lock_helper(&["--internal-hold-installation-lock".into(), path]) + .unwrap() + .unwrap(); + } + } + + #[test] + fn installation_helper_and_self_update_contend_for_the_same_lock() { + use std::io::{BufRead, BufReader}; + let root = tempfile::tempdir().unwrap(); + let path = root.path().join(".openbitfun-cli-install.lock"); + let mut helper = openbitfun_services_core::process_manager::create_command( + std::env::current_exe().unwrap(), + ) + .args([ + "--exact", + "self_update::tests::installer_helper_fixture", + "--nocapture", + ]) + .env("OPENBITFUN_LOCK_HELPER_FIXTURE", &path) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdout = BufReader::new(helper.stdout.take().unwrap()); + loop { + let mut line = String::new(); + assert!( + stdout.read_line(&mut line).unwrap() > 0, + "helper exited before acquiring lock" + ); + if line.trim() == "OPENBITFUN_INSTALL_LOCK_V1" { + break; + } + } + assert!(InstallLock::acquire_at(&path).is_err()); + drop(helper.stdin.take()); + assert!(helper.wait().unwrap().success()); + assert!(InstallLock::acquire_at(&path).is_ok()); + assert!(path.is_file(), "the stable lock inode must not be unlinked"); + } + /// Minimal HTTP/1.1 origin that serves `body` at a fixed rate, honours /// `Range: bytes=-` and can be told to hang up mid-response. Enough to /// exercise the parts of the updater that only misbehave on a slow link. diff --git a/src/apps/desktop/Cargo.toml b/src/apps/desktop/Cargo.toml index 0b7891e043..bb40836236 100644 --- a/src/apps/desktop/Cargo.toml +++ b/src/apps/desktop/Cargo.toml @@ -20,7 +20,7 @@ serde_json = { workspace = true } [dependencies] openbitfun-computer-use = { path = "../../crates/services/computer-use" } openbitfun-miniapp-ipc = { path = "../../crates/adapters/miniapp-ipc" } -openbitfun-services-core = { path = "../../crates/services/services-core", features = ["pet-packages", "local-storage"] } +openbitfun-services-core = { path = "../../crates/services/services-core", features = ["pet-packages", "local-storage", "installed-apps"] } # Internal crates openbitfun-core = { path = "../../crates/assembly/core", features = ["product-full"] } openbitfun-relay-service = { path = "../../crates/services/relay-service" } diff --git a/src/apps/desktop/src/api/update_api.rs b/src/apps/desktop/src/api/update_api.rs index 80adeb12e6..559b577830 100644 --- a/src/apps/desktop/src/api/update_api.rs +++ b/src/apps/desktop/src/api/update_api.rs @@ -77,6 +77,8 @@ pub struct PendingUpdateResponse { pub version: String, #[serde(skip_serializing_if = "Option::is_none")] pub install_error: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reboot_required: Option, } #[derive(Debug, Serialize, Deserialize)] @@ -95,6 +97,7 @@ impl PendingUpdateRecord { PendingUpdateResponse { version: self.version.clone(), install_error: None, + reboot_required: None, } } @@ -135,6 +138,8 @@ struct InstallationReceipt { success: bool, #[serde(default)] error: Option, + #[serde(default)] + reboot_required: bool, } fn pending_response( @@ -150,8 +155,12 @@ fn pending_response( // A matching pending record is offered only while the running // version is older. Even exit code zero must not hide that fact. if receipt.version == record.version { + response.reboot_required = + (receipt.success && receipt.reboot_required).then_some(true); response.install_error = Some(receipt.error.unwrap_or_else(|| { - if receipt.success { + if receipt.reboot_required { + "Restart Windows to finish installing the OpenBitFun update.".into() + } else if receipt.success { "The installer finished, but the running version is still older; restart or repair the installation".into() } else { "The previous update installation failed; retry or reinstall manually".into() @@ -193,8 +202,14 @@ fn read_record( if !record.applies_to(current, platform)? { return Ok(None); } - if record.package_kind.as_deref() != Some(package_kind()) { - return Err("Update package belongs to another installation format or has legacy metadata; download it again".into()); + if record + .package_kind + .as_deref() + .is_some_and(|kind| kind != package_kind()) + { + return Err( + "Update package belongs to another installation format; download it again".into(), + ); } let package = dir.join(record.package_name()?); if !package.is_file() { @@ -203,6 +218,24 @@ fn read_record( Ok(Some(record)) } +fn migrate_verified_legacy_record( + dir: &Path, + record: &mut PendingUpdateRecord, + bytes: &[u8], + kind: &str, +) -> Result<(), String> { + if record.package_kind.is_some() { + return Ok(()); + } + crate::update_maintenance::validate_cached_package(bytes, kind)?; + record.package_kind = Some(kind.to_string()); + atomic_write( + dir, + RECORD_NAME, + &serde_json::to_vec(record).map_err(|error| error.to_string())?, + ) +} + fn atomic_write(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), String> { std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; let mut file = tempfile::NamedTempFile::new_in(dir).map_err(|e| e.to_string())?; @@ -254,21 +287,15 @@ pub(super) fn configure_updater(builder: UpdaterBuilder) -> UpdaterBuilder { }) } -#[cfg(any(windows, test))] -pub(crate) fn windows_machine_install(directory: &Path) -> bool { - let read = |path: &Path| { - std::fs::read(path) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - }; - read(&directory.join(".openbitfun-installed.json")).is_some_and(|value| { - value.get("allUsers").and_then(serde_json::Value::as_bool) == Some(true) - }) || read(&directory.join(".openbitfun-maintenance/journal.json")).is_some_and(|value| { - value - .pointer("/integrations/registry/machine") - .and_then(serde_json::Value::as_bool) - == Some(true) - }) +#[cfg(windows)] +pub(crate) fn windows_installation_scope( + directory: &Path, +) -> Result { + openbitfun_services_core::installation_scope::windows_installation_scope( + directory, + "OpenBitFun", + None, + ) } #[tauri::command] @@ -370,7 +397,7 @@ pub async fn install_pending_update( .ok_or_else(|| "Update signature public key is unavailable".to_string())? .to_owned(); let (record, bytes) = tokio::task::spawn_blocking(move || { - let record = read_record(&dir, ¤t, &platform())? + let mut record = read_record(&dir, ¤t, &platform())? .ok_or_else(|| "No downloaded update is available".to_string())?; if record.version != request.version { return Err( @@ -379,6 +406,7 @@ pub async fn install_pending_update( } let bytes = std::fs::read(dir.join(record.package_name()?)).map_err(|e| e.to_string())?; verify_package(&bytes, &record, &pubkey)?; + migrate_verified_legacy_record(&dir, &mut record, &bytes, package_kind())?; Ok::<_, String>((record, bytes)) }) .await @@ -390,7 +418,10 @@ pub async fn install_pending_update( &maintenance_app, &bytes, &record.version, - record.package_kind.as_deref().unwrap_or("unbundled"), + record + .package_kind + .as_deref() + .ok_or("Verified update format was not retained")?, &receipt, ) }) @@ -414,16 +445,21 @@ pub async fn install_pending_update( mod tests { use super::*; + #[cfg(windows)] #[test] fn machine_installs_request_elevation_even_in_writable_custom_directories() { let root = tempfile::tempdir().unwrap(); - assert!(!windows_machine_install(root.path())); + assert!(!windows_installation_scope(root.path()) + .unwrap() + .requires_machine_access()); std::fs::write( root.path().join(".openbitfun-installed.json"), br#"{"allUsers":true}"#, ) .unwrap(); - assert!(windows_machine_install(root.path())); + assert!(windows_installation_scope(root.path()) + .unwrap() + .requires_machine_access()); std::fs::remove_file(root.path().join(".openbitfun-installed.json")).unwrap(); std::fs::create_dir(root.path().join(".openbitfun-maintenance")).unwrap(); std::fs::write( @@ -431,7 +467,9 @@ mod tests { br#"{"integrations":{"registry":{"machine":true}}}"#, ) .unwrap(); - assert!(windows_machine_install(root.path())); + assert!(windows_installation_scope(root.path()) + .unwrap() + .requires_machine_access()); } #[test] @@ -549,23 +587,85 @@ mod tests { } #[test] - fn legacy_and_other_package_formats_are_preserved_for_explicit_redownload() { + fn legacy_cache_is_readable_and_only_verified_matching_packages_are_migrated() { let dir = tempfile::tempdir().unwrap(); let mut record = record(b"package"); - for kind in [None, Some("other-format".into())] { - record.package_kind = kind; - save_package(dir.path(), &record, b"package").unwrap(); - assert!(read_record(dir.path(), &"1.0.0".parse().unwrap(), "test") - .unwrap_err() - .contains("installation format")); - assert!(dir.path().join(record.package_name().unwrap()).is_file()); - } + record.package_kind = None; + save_package(dir.path(), &record, b"package").unwrap(); + let mut old = serde_json::to_value(&record).unwrap(); + old.as_object_mut().unwrap().remove("packageKind"); + std::fs::write( + dir.path().join(RECORD_NAME), + serde_json::to_vec(&old).unwrap(), + ) + .unwrap(); + assert!(read_record(dir.path(), &"1.0.0".parse().unwrap(), "test") + .unwrap() + .is_some()); + let original = std::fs::read(dir.path().join(RECORD_NAME)).unwrap(); + assert!( + migrate_verified_legacy_record(dir.path(), &mut record, b"ambiguous", "nsis").is_err() + ); + assert_eq!( + std::fs::read(dir.path().join(RECORD_NAME)).unwrap(), + original + ); + let bytes = b"MZfixture-OPENBITFUN_MAINTENANCE_V1"; + record = self::record(bytes); + record.package_kind = None; + save_package(dir.path(), &record, bytes).unwrap(); + assert!(verify_package(bytes, &record, "invalid-key").is_err()); + assert_eq!( + serde_json::from_slice::( + &std::fs::read(dir.path().join(RECORD_NAME)).unwrap() + ) + .unwrap() + .package_kind, + None + ); + migrate_verified_legacy_record(dir.path(), &mut record, bytes, "nsis").unwrap(); + assert_eq!( + serde_json::from_slice::( + &std::fs::read(dir.path().join(RECORD_NAME)).unwrap() + ) + .unwrap() + .package_kind + .as_deref(), + Some("nsis") + ); + record.package_kind = Some("other-format".into()); + save_package(dir.path(), &record, b"package").unwrap(); + assert!(read_record(dir.path(), &"1.0.0".parse().unwrap(), "test") + .unwrap_err() + .contains("installation format")); + assert!(dir.path().join(record.package_name().unwrap()).is_file()); let mut legacy = serde_json::to_value(&record).unwrap(); legacy.as_object_mut().unwrap().remove("packageKind"); let decoded: PendingUpdateRecord = serde_json::from_value(legacy).unwrap(); assert!(decoded.package_kind.is_none()); } + #[test] + fn successful_reboot_receipts_preserve_legacy_receipt_compatibility() { + let dir = tempfile::tempdir().unwrap(); + for reboot in [false, true] { + let mut receipt = serde_json::json!({"version":"2.0.0", "success":true}); + if reboot { + receipt["rebootRequired"] = true.into(); + } + std::fs::write( + dir.path().join(RECEIPT_NAME), + serde_json::to_vec(&receipt).unwrap(), + ) + .unwrap(); + let response = pending_response(dir.path(), record(b"package")).unwrap(); + assert_eq!(response.reboot_required, reboot.then_some(true)); + if reboot { + assert!(response.install_error.unwrap().contains("Restart")); + } + } + } + #[test] fn installation_receipts_report_failures_and_a_still_running_old_version() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/apps/desktop/src/update_maintenance/mod.rs b/src/apps/desktop/src/update_maintenance/mod.rs index 49defc623f..3ea1a1c17e 100644 --- a/src/apps/desktop/src/update_maintenance/mod.rs +++ b/src/apps/desktop/src/update_maintenance/mod.rs @@ -5,6 +5,209 @@ use std::path::Path; use tauri::AppHandle; +/// Used only after the cached bytes pass checksum and signature verification. +/// Missing legacy metadata is inferred from the actual package, never guessed +/// from the running package type alone. +pub(crate) fn validate_cached_package(bytes: &[u8], kind: &str) -> Result<(), String> { + use std::io::Read; + let windows = |payload: &[u8]| { + let msi = payload.starts_with(&[0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]); + let exe = payload.starts_with(b"MZ") + && [ + b"OPENBITFUN_MAINTENANCE_V1".as_slice(), + b"NullsoftInst".as_slice(), + ] + .iter() + .any(|marker| payload.windows(marker.len()).any(|part| part == *marker)); + (kind != "msi" && exe) || (kind != "nsis" && msi) + }; + let valid = match kind { + "nsis" | "msi" | "unbundled" if kind != "unbundled" || cfg!(windows) => { + if bytes.starts_with(b"PK\x03\x04") { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)) + .map_err(|error| error.to_string())?; + let mut found = None; + for index in 0..archive.len() { + let mut entry = archive.by_index(index).map_err(|error| error.to_string())?; + if !entry.is_dir() + && std::path::Path::new(entry.name()) + .extension() + .is_some_and(|ext| { + ext.eq_ignore_ascii_case("exe") || ext.eq_ignore_ascii_case("msi") + }) + { + if found.is_some() { + return Err("Legacy update archive contains multiple installers; cache was retained".into()); + } + let mut payload = Vec::new(); + entry + .read_to_end(&mut payload) + .map_err(|error| error.to_string())?; + found = Some(windows(&payload)); + } + } + found.unwrap_or(false) + } else { + windows(bytes) + } + } + "deb" => bytes.starts_with(b"!\n"), + "rpm" => bytes.starts_with(&[0xed, 0xab, 0xee, 0xdb]), + "appimage" if !bytes.starts_with(&[0x1f, 0x8b]) => { + bytes.starts_with(b"\x7fELF") && matches!(bytes.get(8..11), Some(b"AI\x01" | b"AI\x02")) + } + "app" | "appimage" => { + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(bytes)); + let mut apps = std::collections::HashSet::new(); + let mut info = false; + let mut executable = false; + let mut appimages = 0; + for entry in archive.entries().map_err(|error| error.to_string())? { + let mut entry = entry.map_err(|error| error.to_string())?; + let path = entry + .path() + .map_err(|error| error.to_string())? + .into_owned(); + if path.components().any(|part| { + matches!( + part, + std::path::Component::ParentDir + | std::path::Component::RootDir + | std::path::Component::Prefix(_) + ) + }) { + return Err("Invalid legacy update archive path; cache was retained".into()); + } + let path = path + .components() + .filter(|part| matches!(part, std::path::Component::Normal(_))) + .collect::(); + if kind == "appimage" + && path.extension().is_some_and(|ext| ext == "AppImage") + && entry.header().entry_type().is_file() + { + let mut header = [0u8; 11]; + entry + .read_exact(&mut header) + .map_err(|error| error.to_string())?; + if !header.starts_with(b"\x7fELF") + || !matches!(&header[8..], b"AI\x01" | b"AI\x02") + { + return Err("Invalid cached AppImage; cache was retained".into()); + } + appimages += 1; + } + if kind == "app" { + let name = path + .components() + .next() + .map(|part| part.as_os_str().to_owned()); + if let Some(name) = name.filter(|name| { + std::path::Path::new(name) + .extension() + .is_some_and(|ext| ext == "app") + }) { + apps.insert(name.clone()); + let relative = path + .strip_prefix(std::path::Path::new(&name)) + .map_err(|error| error.to_string())?; + info |= relative == std::path::Path::new("Contents/Info.plist") + && entry.header().entry_type().is_file(); + executable |= relative.starts_with("Contents/MacOS") + && entry.header().entry_type().is_file(); + } + } + } + if kind == "appimage" { + appimages == 1 + } else { + apps.len() == 1 && info && executable + } + } + _ => false, + }; + if valid { + Ok(()) + } else { + Err("Legacy cached package format cannot be verified for this installation; the cache was retained".into()) + } +} + +#[cfg(test)] +mod cache_format_tests { + use super::*; + use std::io::Write; + + #[test] + fn legacy_windows_archives_accept_one_installer_and_reject_ambiguity() { + let archive = |count| { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for index in 0..count { + zip.start_file( + format!("installer{index}.exe"), + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(b"MZfixture-NullsoftInst").unwrap(); + } + zip.finish().unwrap().into_inner() + }; + assert!(validate_cached_package(&archive(1), "nsis").is_ok()); + assert!(validate_cached_package(&archive(1), "msi").is_err()); + assert!(validate_cached_package(&archive(2), "nsis").is_err()); + } + + #[test] + fn legacy_unix_archives_accept_dot_paths_and_reject_multiple_bundles() { + let archive = |names: &[(&str, &[u8])]| { + let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + let mut tar = tar::Builder::new(encoder); + for (name, contents) in names { + let mut header = tar::Header::new_gnu(); + header.set_size(contents.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + tar.append_data(&mut header, name, *contents).unwrap(); + } + tar.into_inner().unwrap().finish().unwrap() + }; + let files = [ + ("./OpenBitFun.app/Contents/Info.plist", b"plist".as_slice()), + ( + "./OpenBitFun.app/Contents/MacOS/OpenBitFun", + b"executable".as_slice(), + ), + ]; + assert!(validate_cached_package(&archive(&files), "app").is_ok()); + assert!(validate_cached_package(&archive(&files[..1]), "app").is_err()); + let mut multiple = files.to_vec(); + multiple.push(("Other.app/Contents/Info.plist", b"plist")); + assert!(validate_cached_package(&archive(&multiple), "app").is_err()); + let image = b"\x7fELF\0\0\0\0AI\x02fixture"; + assert!( + validate_cached_package(&archive(&[("./OpenBitFun.AppImage", image)]), "appimage") + .is_ok() + ); + assert!(validate_cached_package( + &archive(&[("a.AppImage", image), ("b.AppImage", image)]), + "appimage" + ) + .is_err()); + } + + #[test] + fn legacy_packages_require_a_recognizable_matching_format() { + let native = b"MZfixture-OPENBITFUN_MAINTENANCE_V1"; + assert!(validate_cached_package(native, "nsis").is_ok()); + assert!(validate_cached_package(b"MZunknown executable", "nsis").is_err()); + assert!(validate_cached_package(native, "msi").is_err()); + assert!(validate_cached_package(b"!\nfixture", "deb").is_ok()); + assert!(validate_cached_package(b"!\nfixture", "rpm").is_err()); + assert!(validate_cached_package(b"\x7fELF\0\0\0\0AI\x02fixture", "appimage").is_ok()); + assert!(validate_cached_package(b"\x7fELFfixture", "appimage").is_err()); + } +} + #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "macos")] diff --git a/src/apps/desktop/src/update_maintenance/windows.rs b/src/apps/desktop/src/update_maintenance/windows.rs index b4ae4d02e5..a871c68cb4 100644 --- a/src/apps/desktop/src/update_maintenance/windows.rs +++ b/src/apps/desktop/src/update_maintenance/windows.rs @@ -110,7 +110,9 @@ pub(super) fn install( Err(error) if error.kind() == io::ErrorKind::PermissionDenied => true, Err(error) => return Err(error), }; - let machine = crate::api::update_api::windows_machine_install(target); + let scope = + crate::api::update_api::windows_installation_scope(target).map_err(io::Error::other)?; + let machine = scope.machine_install; let event_name = format!("Local\\OpenBitFunUpdate-{}", uuid::Uuid::new_v4()); let file = if package.msi { system_directory()?.join("msiexec.exe") @@ -176,7 +178,7 @@ function Read-NativeFailure($code) {{ }} return $null }} -$result=@{{version={version};success=$false;exitCode=$null;error=$null}} +$result=@{{version={version};success=$false;exitCode=$null;error=$null;rebootRequired=$false}} $announced=$false try {{ $parameters=@{{FilePath={file};ArgumentList={parameters};PassThru=$true}} @@ -210,9 +212,12 @@ try {{ $installer.WaitForExit() $result.exitCode=$installer.ExitCode $detail=Read-NativeFailure $installer.ExitCode - if ($installer.ExitCode -ne 0 -and $installer.ExitCode -ne 2) {{ if($detail) {{ throw $detail }}; throw "Installer exited with code $($installer.ExitCode)" }} + $accepted=if({transactional}){{@(0,2)}}elseif({msi}){{@(0,1641,3010)}}else{{@(0)}} + if ($installer.ExitCode -notin $accepted) {{ if($detail) {{ throw $detail }}; throw "Installer exited with code $($installer.ExitCode)" }} $result.success=$true - if ($installer.ExitCode -eq 2) {{ $result.error=if($detail){{$detail}}else{{'The update was installed, but some maintenance files require cleanup.'}} }} + $result.rebootRequired={msi} -and ($installer.ExitCode -in @(1641,3010)) + if ($result.rebootRequired) {{ $result.error='Restart Windows to finish installing the OpenBitFun update.' }} + elseif ({transactional} -and $installer.ExitCode -eq 2) {{ $result.error=if($detail){{$detail}}else{{'The update was installed, but some maintenance files require cleanup.'}} }} }} catch {{ $result.error=$_.Exception.Message if (!$announced) {{ [Console]::Out.WriteLine('ERROR: '+$result.error); [Console]::Out.Flush() }} @@ -225,13 +230,13 @@ try {{ }} catch {{}} if ($result.error -and $announced) {{ Add-Type -AssemblyName System.Windows.Forms - $message=if($result.success){{'OpenBitFun update completed with a cleanup warning. '}}else{{'OpenBitFun update failed. The downloaded package is retained. '}} + $message=if($result.rebootRequired){{'OpenBitFun update requires a Windows restart. '}}elseif($result.success){{'OpenBitFun update completed with a cleanup warning. '}}else{{'OpenBitFun update failed. The downloaded package is retained. '}} [Windows.Forms.MessageBox]::Show($message+$result.error,'OpenBitFun',[Windows.Forms.MessageBoxButtons]::OK,[Windows.Forms.MessageBoxIcon]::Warning) | Out-Null }} if ({cleanup} -ne '') {{ try {{ Remove-Item -LiteralPath {cleanup} -Force; [IO.Directory]::Delete([IO.Path]::GetDirectoryName({cleanup}),$false) }} catch {{}} }} -if ($announced -and (Test-Path -LiteralPath {current})) {{ +if ($announced -and !$result.rebootRequired -and (Test-Path -LiteralPath {current})) {{ $restart=@{{FilePath={current}}} if ({restart} -ne '') {{ $restart.ArgumentList={restart} }} Start-Process @restart @@ -242,8 +247,9 @@ if ($announced -and (Test-Path -LiteralPath {current})) {{ file = quote(&file.to_string_lossy()), parameters = quote(¶meters), transactional = if package.native { "$true" } else { "$false" }, + msi = if package.msi { "$true" } else { "$false" }, event = quote(&event_name), - elevate = if protected || machine { + elevate = if protected || scope.requires_machine_access() { "$true" } else { "$false" diff --git a/src/crates/services/services-core/src/installation_scope.rs b/src/crates/services/services-core/src/installation_scope.rs new file mode 100644 index 0000000000..502526a091 --- /dev/null +++ b/src/crates/services/services-core/src/installation_scope.rs @@ -0,0 +1,364 @@ +//! Read-only scope facts shared by Windows maintenance callers. No elevation, +//! publication, registration mutation, or product capability selection lives here. +use std::{ffi::c_void, path::Path}; +type Hkey = *mut c_void; +const HKCU: Hkey = -2147483647_isize as Hkey; +const HKLM: Hkey = -2147483646_isize as Hkey; +const HKU: Hkey = -2147483645_isize as Hkey; +const UNINSTALL: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"; + +#[link(name = "advapi32")] +extern "system" { + fn RegOpenKeyExW( + root: Hkey, + name: *const u16, + options: u32, + access: u32, + key: *mut Hkey, + ) -> i32; + fn RegCloseKey(key: Hkey) -> i32; + fn RegEnumKeyExW( + key: Hkey, + index: u32, + name: *mut u16, + count: *mut u32, + reserved: *mut u32, + class: *mut u16, + class_count: *mut u32, + time: *mut c_void, + ) -> i32; + fn RegQueryValueExW( + key: Hkey, + name: *const u16, + reserved: *mut u32, + kind: *mut u32, + data: *mut u8, + length: *mut u32, + ) -> i32; +} +fn wide(value: &str) -> Vec { + value.encode_utf16().chain(Some(0)).collect() +} +struct Key(Hkey); +impl Drop for Key { + fn drop(&mut self) { + unsafe { + RegCloseKey(self.0); + } + } +} +impl Key { + fn open(root: Hkey, name: &str) -> Result, String> { + let mut key = std::ptr::null_mut(); + let code = unsafe { RegOpenKeyExW(root, wide(name).as_ptr(), 0, 0x20019, &mut key) }; + match code { + 0 => Ok(Some(Self(key))), + 2 => Ok(None), + _ => Err(format!( + "Cannot read installation registration {name} (Windows error {code})" + )), + } + } + fn location(&self) -> Result, String> { + let name = wide("InstallLocation"); + let mut kind = 0; + let mut size = 0; + let code = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null_mut(), + &mut kind, + std::ptr::null_mut(), + &mut size, + ) + }; + if code == 2 { + return Ok(None); + } + if code != 0 || !matches!(kind, 1 | 2) || size % 2 != 0 { + return Err( + "Installation registration has an unreadable location; registry data was preserved" + .into(), + ); + } + let mut value = vec![0u16; size as usize / 2]; + let code = unsafe { + RegQueryValueExW( + self.0, + name.as_ptr(), + std::ptr::null_mut(), + &mut kind, + value.as_mut_ptr().cast(), + &mut size, + ) + }; + if code != 0 { + return Err(format!( + "Cannot read installation location (Windows error {code})" + )); + } + Ok(Some( + String::from_utf16_lossy(&value) + .trim_end_matches('\0') + .trim() + .trim_matches('"') + .to_string(), + )) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InstallationScope { + pub current_user_registration: bool, + pub machine_registration: bool, + pub machine_install: bool, +} +impl InstallationScope { + pub fn requires_machine_access(self) -> bool { + self.machine_registration || self.machine_install + } +} + +fn normalized(path: &Path) -> String { + path.canonicalize() + .unwrap_or_else(|_| path.to_path_buf()) + .to_string_lossy() + .replace('/', "\\") + .trim_start_matches(r"\\?\") + .trim_end_matches('\\') + .to_lowercase() +} +fn registered(root: Hkey, product: &str, directory: &Path) -> Result { + let Some(parent) = Key::open(root, UNINSTALL)? else { + return Ok(false); + }; + for index in 0.. { + let mut name = [0u16; 512]; + let mut count = name.len() as u32; + let code = unsafe { + RegEnumKeyExW( + parent.0, + index, + name.as_mut_ptr(), + &mut count, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + if code == 259 { + return Ok(false); + } + if code != 0 { + return Err(format!( + "Cannot enumerate installation registrations (Windows error {code})" + )); + } + let name = String::from_utf16_lossy(&name[..count as usize]); + let lower = name.to_ascii_lowercase(); + if !name.eq_ignore_ascii_case(product) + && !lower.starts_with(&format!("{}-", product.to_ascii_lowercase())) + { + continue; + } + if let Some(key) = Key::open(parent.0, &name)? { + if key + .location()? + .is_some_and(|location| normalized(Path::new(&location)) == normalized(directory)) + { + return Ok(true); + } + } + } + unreachable!() +} +fn metadata_hint(directory: &Path) -> Result, String> { + for (file, pointer) in [ + (".openbitfun-installed.json", "/allUsers"), + ( + ".openbitfun-maintenance/journal.json", + "/integrations/registry/machine", + ), + ] { + let bytes = match std::fs::read(directory.join(file)) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => { + return Err(format!( + "Cannot read installation scope; metadata was preserved: {error}" + )) + } + }; + let value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|error| { + format!("Installation scope metadata is unreadable; retained for repair: {error}") + })?; + if let Some(schema) = value.get("schema") { + if schema.as_u64() != Some(1) { + return Err("Unsupported installation scope metadata; retained for repair".into()); + } + } + if let Some(value) = value.pointer(pointer) { + return value + .as_bool() + .map(Some) + .ok_or_else(|| "Invalid installation scope; metadata was preserved".into()); + } + } + Ok(None) +} +fn resolve( + directory: &Path, + product: &str, + user: Hkey, + machine: Hkey, +) -> Result { + let current_user_registration = registered(user, product, directory)?; + let machine_registration = registered(machine, product, directory)?; + Ok(InstallationScope { + current_user_registration, + machine_registration, + machine_install: metadata_hint(directory)? + .unwrap_or(machine_registration && !current_user_registration), + }) +} + +/// `owner_sid` keeps an elevated worker bound to the submitting user's hive. +pub fn windows_installation_scope( + directory: &Path, + product: &str, + owner_sid: Option<&str>, +) -> Result { + let user = if let Some(sid) = owner_sid { + if !sid.starts_with("S-1-") + || !sid + .bytes() + .all(|c| c.is_ascii_digit() || matches!(c, b'S' | b'-')) + { + return Err("Invalid installation owner SID".into()); + } + Some(Key::open(HKU, sid)?.ok_or("Installation owner's registry hive is unavailable")?) + } else { + None + }; + resolve( + directory, + product, + user.as_ref().map_or(HKCU, |key| key.0), + HKLM, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[link(name = "advapi32")] + extern "system" { + fn RegCreateKeyExW( + root: Hkey, + name: *const u16, + reserved: u32, + class: *mut u16, + options: u32, + access: u32, + security: *const c_void, + result: *mut Hkey, + disposition: *mut u32, + ) -> i32; + fn RegSetValueExW( + key: Hkey, + name: *const u16, + reserved: u32, + kind: u32, + bytes: *const u8, + count: u32, + ) -> i32; + fn RegDeleteTreeW(root: Hkey, name: *const u16) -> i32; + } + fn create(root: Hkey, name: &str) -> Key { + let mut key = std::ptr::null_mut(); + assert_eq!( + unsafe { + RegCreateKeyExW( + root, + wide(name).as_ptr(), + 0, + std::ptr::null_mut(), + 0, + 0xf003f, + std::ptr::null(), + &mut key, + std::ptr::null_mut(), + ) + }, + 0 + ); + Key(key) + } + fn register(root: Hkey, name: &str, directory: &Path) { + let key = create(root, &format!(r"{UNINSTALL}\{name}")); + let value = wide(&format!("\"{}\"", directory.display())); + assert_eq!( + unsafe { + RegSetValueExW( + key.0, + wide("InstallLocation").as_ptr(), + 0, + 1, + value.as_ptr().cast(), + (value.len() * 2) as u32, + ) + }, + 0 + ); + } + #[test] + fn legacy_machine_registration_dual_registration_and_inventory_share_one_rule() { + let name = format!( + r"Software\OpenBitFunScopeTests\{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + let fixture = create(HKCU, &name); + let user = create(fixture.0, "User"); + let machine = create(fixture.0, "Machine"); + let temp = tempfile::tempdir().unwrap(); + register(machine.0, "OpenBitFun", temp.path()); + let scope = resolve(temp.path(), "OpenBitFun", user.0, machine.0).unwrap(); + assert!(scope.machine_install && scope.requires_machine_access()); + register(user.0, "OpenBitFun-directory-id", temp.path()); + let scope = resolve(temp.path(), "OpenBitFun", user.0, machine.0).unwrap(); + assert!( + scope.current_user_registration && scope.machine_registration && !scope.machine_install + ); + assert!(scope.requires_machine_access()); + std::fs::write( + temp.path().join(".openbitfun-installed.json"), + br#"{"schema":1,"allUsers":true}"#, + ) + .unwrap(); + assert!( + resolve(temp.path(), "OpenBitFun", user.0, machine.0) + .unwrap() + .machine_install + ); + std::fs::write( + temp.path().join(".openbitfun-installed.json"), + b"unreadable", + ) + .unwrap(); + assert!(resolve(temp.path(), "OpenBitFun", user.0, machine.0).is_err()); + assert_eq!( + std::fs::read(temp.path().join(".openbitfun-installed.json")).unwrap(), + b"unreadable" + ); + drop(machine); + drop(user); + drop(fixture); + assert_eq!(unsafe { RegDeleteTreeW(HKCU, wide(&name).as_ptr()) }, 0); + } +} diff --git a/src/crates/services/services-core/src/lib.rs b/src/crates/services/services-core/src/lib.rs index 171f3a3f7e..c2761f4726 100644 --- a/src/crates/services/services-core/src/lib.rs +++ b/src/crates/services/services-core/src/lib.rs @@ -109,3 +109,6 @@ pub mod asar; #[cfg(all(feature = "installed-apps", target_os = "windows"))] pub mod installed_apps; + +#[cfg(all(feature = "installed-apps", target_os = "windows"))] +pub mod installation_scope; diff --git a/src/web-ui/src/infrastructure/api/service-api/SystemAPI.ts b/src/web-ui/src/infrastructure/api/service-api/SystemAPI.ts index 838b4ca3a8..ffec15181a 100644 --- a/src/web-ui/src/infrastructure/api/service-api/SystemAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/SystemAPI.ts @@ -29,6 +29,7 @@ export interface CheckForUpdatesResponse { export interface PendingUpdateResponse { version: string; installError?: string; + rebootRequired?: boolean; } /** Matches `toggle_main_window_fullscreen` / desktop `ToggleMainWindowFullscreenResponse`. */ diff --git a/src/web-ui/src/infrastructure/update/AppUpdatePanel.test.tsx b/src/web-ui/src/infrastructure/update/AppUpdatePanel.test.tsx index f3ac107cff..b5adeaf620 100644 --- a/src/web-ui/src/infrastructure/update/AppUpdatePanel.test.tsx +++ b/src/web-ui/src/infrastructure/update/AppUpdatePanel.test.tsx @@ -38,7 +38,7 @@ beforeEach(async () => { }); localStorage.clear(); useUpdateInstallStore.setState({ - status: 'idle', progress: { downloaded: 0, total: null }, error: null, + status: 'idle', progress: { downloaded: 0, total: null }, error: null, rebootRequired: false, startedAt: null, version: null, promptOpen: false, initialized: false, downloadVersion: null, availableUpdate: null, currentVersion: null, checkStatus: 'idle', checkError: null, lastCheckedAt: null, lastCheckAttemptAt: null, @@ -79,6 +79,15 @@ it('shows explicit release details without the general manual-check action', asy expect(selectHasUpdateAttention(state())).toBe(true); }); +it('shows successful installation awaiting a system reboot and disables repeat installation', async () => { + await act(async () => useUpdateInstallStore.setState({ status: 'ready', version: '2.0.0', rebootRequired: true, error: null })); + expect(container.textContent).toContain(common.update.systemRestartMessage); + const button = [...container.querySelectorAll('button')].find(button => button.textContent?.includes(common.update.systemRestartRequired)); + expect(button).toBeDefined(); + expect(button!.disabled).toBe(true); + expect(container.textContent).not.toContain(common.update.retryDownload); +}); + it('enables normal download controls and installation confirmation in explicit release details', async () => { let reportProgress!: (progress: UpdateDownloadProgressPayload) => void; let finish!: (pending: { version: string }) => void; diff --git a/src/web-ui/src/infrastructure/update/AppUpdatePanel.tsx b/src/web-ui/src/infrastructure/update/AppUpdatePanel.tsx index 11c4946d42..820cd80643 100644 --- a/src/web-ui/src/infrastructure/update/AppUpdatePanel.tsx +++ b/src/web-ui/src/infrastructure/update/AppUpdatePanel.tsx @@ -21,8 +21,8 @@ export function AppUpdatePanel() { const skipped = Boolean(target && target === state.skippedVersion); const busy = !state.initialized || state.checkStatus === 'checking' || downloading || state.status === 'installing'; const versionChanged = isUpdateVersionChangedError(state.error); - const canDownload = !versionChanged && Boolean((candidate && candidate !== state.version) || state.error); - const canSkip = Boolean(target && target !== state.version); + const canDownload = !state.rebootRequired && !versionChanged && Boolean((candidate && candidate !== state.version) || state.error); + const canSkip = !state.rebootRequired && Boolean(target && target !== state.version); const fraction = getUpdateDownloadFraction(state.progress); const percent = fraction == null ? null : Math.round(fraction * 100); const productName = getVersionInfo().name; @@ -55,11 +55,12 @@ export function AppUpdatePanel() {
- {(status || state.error || state.checkError) &&
{status &&

{status}

} {state.error && } + {state.rebootRequired && } {state.checkError && }
} {releaseNotes ? ( @@ -113,8 +114,8 @@ export function AppUpdatePanel() { onClick={() => void state.checkForUpdates()}> {t(state.checkStatus === 'checking' ? 'update.checking' : 'update.checkForUpdates')} } - {state.version && } {!canDownload && !canSkip && !versionChanged && !state.version &&