diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 280f465..d012a32 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,10 +82,12 @@ jobs: if [[ "$RUNNER_OS" == Windows ]]; then binary="$binary.exe"; fi if [[ "$RUNNER_OS" == macOS ]]; then codesign --force --sign - "$binary"; fi cargo xtask bundle "$binary" dist "$ASSET" - - name: Ensure Inno Setup is available + - name: Install the Velopack packaging tool if: runner.os == 'Windows' shell: bash - run: choco install innosetup --yes --no-progress + run: | + dotnet tool install --global vpk --version 1.2.161 + echo "$USERPROFILE/.dotnet/tools" >> "$GITHUB_PATH" - name: Build native installer shell: bash env: diff --git a/.github/workflows/winget.yml b/.github/workflows/winget.yml index a626fb8..233f052 100644 --- a/.github/workflows/winget.yml +++ b/.github/workflows/winget.yml @@ -37,8 +37,19 @@ jobs: & $winget --version if ($LASTEXITCODE -ne 0) { throw 'WinGet could not start' } $failed = $false - $versions = Get-ChildItem packaging/winget -Recurse -Filter '*.installer.yaml' - if (-not $versions) { throw 'No WinGet manifests found' } + $versions = @() + if (Test-Path packaging/winget) { + $versions = Get-ChildItem packaging/winget -Recurse -Filter '*.installer.yaml' + } + if (-not $versions) { + # A version or locale manifest without its installer manifest is an + # incomplete submission, not an empty folder. + if ((Test-Path packaging/winget) -and (Get-ChildItem packaging/winget -Recurse -Filter '*.yaml')) { + throw 'WinGet manifests are present without an installer manifest' + } + 'No WinGet manifests to validate.' >> $env:GITHUB_STEP_SUMMARY + exit 0 + } foreach ($installer in $versions) { $directory = $installer.Directory.FullName $log = Join-Path $env:RUNNER_TEMP ($installer.BaseName + '.validation.txt') diff --git a/README.md b/README.md index 532cb53..a293c7e 100644 --- a/README.md +++ b/README.md @@ -163,9 +163,9 @@ Set the package version in `Cargo.toml`, refresh `Cargo.lock`, commit, and push Windows builds statically link the Microsoft C++ runtime and verify the executable imports before packaging, so clean Windows installations do not need the Visual C++ Redistributable. -The workflow publishes a stable GitHub release with generated release notes after all four builds pass, making the downloads and in-app update available immediately. Rerunning it for the same tag replaces the release assets and publishes any existing draft. Prereleases and drafts are ignored by the updater. Release asset names form the updater contract and must stay consistent with `src/updater.rs`. Forks should change the repository constant there. Every release also includes a compressed Inno Setup installer, an xz-compressed Debian package, and architecture-specific macOS `.pkg` installers. Installer assets receive SHA-256 sidecars too. The macOS packages are unsigned until Developer ID signing and notarization credentials are configured; the workflow currently uses ad-hoc app signing. If the `VERCEL_DEPLOY_HOOK` secret is set, the workflow also asks Vercel to rebuild the website. +The workflow publishes a stable GitHub release with generated release notes after all four builds pass, making the downloads and in-app update available immediately. Rerunning it for the same tag replaces the release assets and publishes any existing draft. Prereleases and drafts are ignored by the updater. Release asset names form the updater contract and must stay consistent with `src/updater.rs`. Forks should change the repository constant there. Every release also includes a Velopack Windows setup with its full update package (`reclaim-windows-x86_64-full.nupkg`), an xz-compressed Debian package, and architecture-specific macOS `.pkg` installers. Installer assets receive SHA-256 sidecars too. The macOS packages are unsigned until Developer ID signing and notarization credentials are configured; the workflow currently uses ad-hoc app signing. If the `VERCEL_DEPLOY_HOOK` secret is set, the workflow also asks Vercel to rebuild the website. -To build a native installer locally after compiling the release executable, run `cargo xtask package linux --binary target/release/reclaim` (or use `windows` / `macos` with the matching executable and `--arch aarch64` for Apple Silicon). The Rust tool requires `dpkg-deb` on Linux, Inno Setup 6 on Windows, or Apple command-line tools on macOS. Output goes to `dist/`. +To build a native installer locally after compiling the release executable, run `cargo xtask package linux --binary target/release/reclaim` (or use `windows` / `macos` with the matching executable and `--arch aarch64` for Apple Silicon). The Rust tool requires `dpkg-deb` on Linux, the Velopack `vpk` tool on Windows (`dotnet tool install --global vpk --version 1.2.161`), or Apple command-line tools on macOS. Output goes to `dist/`. diff --git a/docs/DISTRIBUTION.md b/docs/DISTRIBUTION.md index 8a6768f..9ab8cff 100644 --- a/docs/DISTRIBUTION.md +++ b/docs/DISTRIBUTION.md @@ -2,25 +2,27 @@ ## WinGet -The initial package is `sudo-py-dev.Reclaim` version `0.2.3`, submitted for review at -https://github.com/microsoft/winget-pkgs/pull/478554. Publication depends on Microsoft's review and checks; opening the PR does not make the package available immediately. - -The submission files are in `packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/`. -The installer is the existing upstream per-user x64 Inno Setup release. Its SHA-256 -was independently downloaded and verified, and the manifests pass Microsoft's -1.28.0 JSON schemas. Windows installation testing must be completed by WinGet CI -or on a Windows machine. The account owner must personally handle any required -Contributor License Agreement acceptance. - -Once accepted: +The package id is `sudo-py-dev.Reclaim`. Version 0.2.3 was submitted for review at +https://github.com/microsoft/winget-pkgs/pull/478554; its manifests were removed +from this repository with the move to Velopack, and the copy in that PR is the +record. Publication depends on Microsoft's review and checks. ```powershell winget install --id sudo-py-dev.Reclaim --exact ``` -For subsequent releases, create a new version directory, update every version and -the version-specific download URL, hash the actual installer, and submit an update -PR to `microsoft/winget-pkgs`. Do not point installer URLs at `latest`. +For each new release, add `packaging/winget/manifests/s/sudo-py-dev/Reclaim//` +with the three manifest files, point the installer URL at that version's +`reclaim-windows-x86_64-setup.exe` (never at `latest`), hash the actual file, and +submit an update PR to `microsoft/winget-pkgs`. The WinGet workflow validates any +manifests in that folder. The account owner must personally handle any required +Contributor License Agreement acceptance. + +The Velopack setup needs `InstallerType: exe`, `Scope: user`, `InstallerSwitches` +with `Silent: --silent` and `SilentWithProgress: --silent`, and +`ProductCode: sudo-py-dev.Reclaim` (the Velopack package id, which is also its +uninstall entry). It installs to `%LocalAppData%\sudo-py-dev.Reclaim`. Check the +uninstall entry name on a real install before the first submission. ## Standalone Flatpak diff --git a/docs/security-review.md b/docs/security-review.md index 6146e39..7658a62 100644 --- a/docs/security-review.md +++ b/docs/security-review.md @@ -212,8 +212,15 @@ this policy does not require the operating system to run in one process. The updater uses HTTPS through Rust libraries and SHA-256 verification. Unix executable replacement uses Rust filesystem operations. On Windows, Rust code -starts the verified Inno Setup package directly through the Win32 process API; -the app never launches cmd.exe, PowerShell, or a cleanup executable. Native OS +downloads the Velopack full package (`.nupkg`), checks its Minisign signature +and SHA-256, then starts the installed Velopack `Update.exe apply` directly +through the Win32 process API with the verified file. Velopack's own release +feed is not used, so the release key stays the only trust root. The app never +launches cmd.exe or PowerShell. Velopack hook commands (`--veloapp-*`) exit +before any window opens. The install and update hooks remove a copy left +by the old installer (0.2.4 and earlier): `src/legacy_install.rs` reads its +folder from the per-user uninstall entry, falls back to the default folder, +and starts `unins000.exe` silently only when the old marker file is next to it. Native OS APIs open browser links and installer files without command helpers. On Linux a native D-Bus session address is required. Process-backed transports, diff --git a/locales/ar.json b/locales/ar.json index e0572bb..7a59e83 100644 --- a/locales/ar.json +++ b/locales/ar.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "واجه Reclaim خطأً غير متوقع ويجب إغلاقه.", "Reclaim stopped because of a Windows exception.": "توقف Reclaim بسبب استثناء في Windows.", "Run the Windows setup once to enable automatic updates": "شغّل برنامج إعداد Windows مرة واحدة لتفعيل التحديثات التلقائية", - "Starting installer…": "جارٍ تشغيل برنامج التثبيت…", "The desktop did not open the link or file. Try opening it manually.": "لم يفتح سطح المكتب الرابط أو الملف. جرّب فتحه يدويًا.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "أعاد سطح المكتب طلب فتح غير متوقع. جرّب فتح الرابط أو الملف يدويًا.", "The diagnostic log could not be written.": "تعذرت كتابة سجل التشخيص.", diff --git a/locales/de.json b/locales/de.json index 2db3fd8..26c0516 100644 --- a/locales/de.json +++ b/locales/de.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "In Reclaim ist ein unerwarteter Fehler aufgetreten. Die App muss beendet werden.", "Reclaim stopped because of a Windows exception.": "Reclaim wurde wegen einer Windows-Ausnahme beendet.", "Run the Windows setup once to enable automatic updates": "Führen Sie einmal das Windows-Setup aus, um automatische Updates zu aktivieren", - "Starting installer…": "Installationsprogramm wird gestartet…", "The desktop did not open the link or file. Try opening it manually.": "Der Desktop hat den Link oder die Datei nicht geöffnet. Öffnen Sie sie manuell.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "Der Desktop hat eine unerwartete Öffnen-Anfrage zurückgegeben. Öffnen Sie den Link oder die Datei manuell.", "The diagnostic log could not be written.": "Das Diagnoseprotokoll konnte nicht geschrieben werden.", diff --git a/locales/en.json b/locales/en.json index 89d12a9..a5a5a88 100644 --- a/locales/en.json +++ b/locales/en.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "Reclaim encountered an unexpected error and must close.", "Reclaim stopped because of a Windows exception.": "Reclaim stopped because of a Windows exception.", "Run the Windows setup once to enable automatic updates": "Run the Windows setup once to enable automatic updates", - "Starting installer…": "Starting installer…", "The desktop did not open the link or file. Try opening it manually.": "The desktop did not open the link or file. Try opening it manually.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "The desktop returned an unexpected open request. Try opening the link or file manually.", "The diagnostic log could not be written.": "The diagnostic log could not be written.", diff --git a/locales/es.json b/locales/es.json index d206376..3597356 100644 --- a/locales/es.json +++ b/locales/es.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "Reclaim encontró un error inesperado y debe cerrarse.", "Reclaim stopped because of a Windows exception.": "Reclaim se detuvo por una excepción de Windows.", "Run the Windows setup once to enable automatic updates": "Ejecuta una vez el instalador de Windows para activar las actualizaciones automáticas", - "Starting installer…": "Iniciando el instalador…", "The desktop did not open the link or file. Try opening it manually.": "El escritorio no abrió el enlace ni el archivo. Prueba a abrirlo manualmente.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "El escritorio devolvió una solicitud de apertura inesperada. Prueba a abrir el enlace o el archivo manualmente.", "The diagnostic log could not be written.": "No se pudo escribir el registro de diagnóstico.", diff --git a/locales/fr.json b/locales/fr.json index 108b3e0..4def425 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "Reclaim a rencontré une erreur inattendue et doit se fermer.", "Reclaim stopped because of a Windows exception.": "Reclaim s’est arrêté à cause d’une exception Windows.", "Run the Windows setup once to enable automatic updates": "Lancez une fois le programme d’installation Windows pour activer les mises à jour automatiques", - "Starting installer…": "Lancement du programme d’installation…", "The desktop did not open the link or file. Try opening it manually.": "Le bureau n’a pas ouvert le lien ou le fichier. Essayez de l’ouvrir manuellement.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "Le bureau a renvoyé une demande d’ouverture inattendue. Essayez d’ouvrir le lien ou le fichier manuellement.", "The diagnostic log could not be written.": "Impossible d’écrire le journal de diagnostic.", diff --git a/locales/he.json b/locales/he.json index e16ff28..9250695 100644 --- a/locales/he.json +++ b/locales/he.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "אירעה ב־Reclaim שגיאה לא צפויה, והיא תיסגר.", "Reclaim stopped because of a Windows exception.": "Reclaim נעצרה בגלל חריגה של Windows.", "Run the Windows setup once to enable automatic updates": "הריצו פעם אחת את תוכנית ההתקנה של Windows כדי לאפשר עדכונים אוטומטיים", - "Starting installer…": "מפעילה את תוכנית ההתקנה…", "The desktop did not open the link or file. Try opening it manually.": "שולחן העבודה לא פתח את הקישור או הקובץ. נסו לפתוח אותו ידנית.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "שולחן העבודה החזיר בקשת פתיחה לא צפויה. נסו לפתוח את הקישור או הקובץ ידנית.", "The diagnostic log could not be written.": "לא ניתן לכתוב את יומן האבחון.", diff --git a/locales/ru.json b/locales/ru.json index 8e1404d..7d33f09 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -196,7 +196,6 @@ "Reclaim encountered an unexpected error and must close.": "В Reclaim произошла непредвиденная ошибка, приложение будет закрыто.", "Reclaim stopped because of a Windows exception.": "Reclaim остановлен из-за исключения Windows.", "Run the Windows setup once to enable automatic updates": "Один раз запустите установщик Windows, чтобы включить автоматические обновления", - "Starting installer…": "Запуск установщика…", "The desktop did not open the link or file. Try opening it manually.": "Рабочий стол не открыл ссылку или файл. Попробуйте открыть вручную.", "The desktop returned an unexpected open request. Try opening the link or file manually.": "Рабочий стол вернул неожиданный запрос на открытие. Попробуйте открыть ссылку или файл вручную.", "The diagnostic log could not be written.": "Не удалось записать журнал диагностики.", diff --git a/packaging/windows/installed-by-inno b/packaging/windows/installed-by-inno deleted file mode 100644 index 9d5d0c8..0000000 --- a/packaging/windows/installed-by-inno +++ /dev/null @@ -1 +0,0 @@ -Installed by Inno Setup. Updates should use the setup executable. diff --git a/packaging/windows/reclaim.iss b/packaging/windows/reclaim.iss deleted file mode 100644 index 5b283f7..0000000 --- a/packaging/windows/reclaim.iss +++ /dev/null @@ -1,51 +0,0 @@ -; Compile with ISCC /DAppVersion=X.Y.Z /DBinaryPath=... /DOutputPath=... reclaim.iss -#ifndef AppVersion - #error AppVersion is required -#endif -#ifndef BinaryPath - #error BinaryPath is required -#endif -#ifndef OutputPath - #define OutputPath "..\..\dist" -#endif -[Setup] -AppId={{0EC19857-83F3-4B19-9239-A900C15E1661} -AppName=Reclaim -AppVersion={#AppVersion} -AppPublisher=Reclaim contributors -AppPublisherURL=https://github.com/sudo-py-dev/reclaim -AppUpdatesURL=https://github.com/sudo-py-dev/reclaim/releases -DefaultDirName={localappdata}\Programs\Reclaim -DefaultGroupName=Reclaim -DisableProgramGroupPage=yes -PrivilegesRequired=lowest -ArchitecturesAllowed=x64compatible -ArchitecturesInstallIn64BitMode=x64compatible -OutputDir={#OutputPath} -OutputBaseFilename=reclaim-windows-x86_64-setup -Compression=lzma2/ultra64 -SolidCompression=yes -; Search longer matches and retain one solid block for the best payload ratio. -LZMANumFastBytes=273 -LZMANumBlockThreads=1 -WizardStyle=modern -SetupIconFile=..\..\assets\icons\reclaim.ico -LicenseFile=..\..\LICENSE -UninstallDisplayIcon={app}\reclaim.exe -CloseApplications=yes -RestartApplications=yes -SetupMutex=ReclaimSetup -[Tasks] -Name: "desktopicon"; Description: "Create a desktop shortcut"; GroupDescription: "Shortcuts:"; Flags: unchecked -[Files] -Source: "{#BinaryPath}"; DestDir: "{app}"; DestName: "reclaim.exe"; Flags: ignoreversion -Source: "installed-by-inno"; DestDir: "{app}"; Flags: ignoreversion -Source: "..\..\LICENSE"; DestDir: "{app}"; Flags: ignoreversion -Source: "..\..\assets\fonts\DejaVu-LICENSE.txt"; DestDir: "{app}\licenses"; Flags: ignoreversion -[Icons] -Name: "{group}\Reclaim"; Filename: "{app}\reclaim.exe" -Name: "{autodesktop}\Reclaim"; Filename: "{app}\reclaim.exe"; Tasks: desktopicon -[Run] -Filename: "{app}\reclaim.exe"; Description: "Launch Reclaim"; Flags: nowait postinstall skipifsilent -; A silent update closes the old process, then starts the installed version. -Filename: "{app}\reclaim.exe"; Flags: nowait runasoriginaluser; Check: WizardSilent diff --git a/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.installer.yaml b/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.installer.yaml deleted file mode 100644 index 94725f0..0000000 --- a/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.installer.yaml +++ /dev/null @@ -1,21 +0,0 @@ -# yaml-language-server: $schema=https://aka.ms/winget-manifest.installer.1.28.0.schema.json -PackageIdentifier: sudo-py-dev.Reclaim -PackageVersion: 0.2.3 -InstallerType: inno -Scope: user -InstallModes: -- interactive -- silent -- silentWithProgress -UpgradeBehavior: install -ProductCode: '{0EC19857-83F3-4B19-9239-A900C15E1661}_is1' -AppsAndFeaturesEntries: -- DisplayName: Reclaim version 0.2.3 - Publisher: Reclaim contributors - ProductCode: '{0EC19857-83F3-4B19-9239-A900C15E1661}_is1' -Installers: -- Architecture: x64 - InstallerUrl: https://github.com/sudo-py-dev/reclaim/releases/download/v0.2.3/reclaim-windows-x86_64-setup.exe - InstallerSha256: A3C6617C36CE4ACCCFB9A6083AD78D36D44F1C47BE39243F4F0410207F9FC2E8 -ManifestType: installer -ManifestVersion: 1.28.0 diff --git a/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.locale.en-US.yaml b/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.locale.en-US.yaml deleted file mode 100644 index 3cc0d82..0000000 --- a/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.locale.en-US.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# yaml-language-server: $schema=https://aka.ms/winget-manifest.defaultLocale.1.28.0.schema.json -PackageIdentifier: sudo-py-dev.Reclaim -PackageVersion: 0.2.3 -PackageLocale: en-US -Publisher: Reclaim contributors -PublisherUrl: https://github.com/sudo-py-dev/reclaim -PublisherSupportUrl: https://github.com/sudo-py-dev/reclaim/issues -PackageName: Reclaim -PackageUrl: https://github.com/sudo-py-dev/reclaim -License: MIT -LicenseUrl: https://github.com/sudo-py-dev/reclaim/blob/v0.2.3/LICENSE -Copyright: Copyright (c) 2026 Reclaim contributors -ShortDescription: Recover files from drives and disk images with read-only scanning. -Description: |- - Reclaim scans drives and raw disk images for recoverable files. Review results, - filter by file type, preview supported images, and save selected files to a - different drive. The source is opened read-only. Supports Windows, Linux and - macOS, with a multilingual interface and light and dark themes. -Moniker: reclaim -Tags: -- data-recovery -- disk-image -- file-recovery -- recovery -ReleaseNotesUrl: https://github.com/sudo-py-dev/reclaim/releases/tag/v0.2.3 -ManifestType: defaultLocale -ManifestVersion: 1.28.0 diff --git a/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.yaml b/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.yaml deleted file mode 100644 index 72f7c34..0000000 --- a/packaging/winget/manifests/s/sudo-py-dev/Reclaim/0.2.3/sudo-py-dev.Reclaim.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# yaml-language-server: $schema=https://aka.ms/winget-manifest.version.1.28.0.schema.json -PackageIdentifier: sudo-py-dev.Reclaim -PackageVersion: 0.2.3 -DefaultLocale: en-US -ManifestType: version -ManifestVersion: 1.28.0 diff --git a/src/legacy_install.rs b/src/legacy_install.rs new file mode 100644 index 0000000..8e0ad4a --- /dev/null +++ b/src/legacy_install.rs @@ -0,0 +1,135 @@ +//! One-time cleanup of the copy that Reclaim's old Inno Setup installer left +//! behind (0.2.4 and earlier), so Windows lists Reclaim once after the move +//! to Velopack. Delete this file once those versions are no longer in use. +// Hardened module: no unchecked indexing or arithmetic in shipped code (CWE-125, CWE-190). +#![cfg_attr( + not(test), + deny(clippy::indexing_slicing, clippy::arithmetic_side_effects) +)] +#[cfg(any(windows, test))] +use std::path::{Path, PathBuf}; + +/// The old installer's per-user uninstall entry (its `AppId` plus `_is1`). +#[cfg(windows)] +const UNINSTALL_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\{0EC19857-83F3-4B19-9239-A900C15E1661}_is1"; + +/// The old uninstaller in `folder`, recognised only by the marker file the +/// old installer wrote next to it. Anything else is left alone. +#[cfg(any(windows, test))] +fn uninstaller(folder: &Path) -> Option { + let uninstaller = folder.join("unins000.exe"); + (folder.is_absolute() && folder.join("installed-by-inno").is_file() && uninstaller.is_file()) + .then_some(uninstaller) +} + +/// The folder the user chose in the old setup comes first, then its default. +#[cfg(any(windows, test))] +fn find_uninstaller( + registered: Option, + local_app_data: Option, +) -> Option { + registered + .into_iter() + .chain(local_app_data.map(|p| p.join("Programs").join("Reclaim"))) + .find_map(|folder| uninstaller(&folder)) +} + +/// Starts the old uninstaller silently. It is not awaited: Velopack gives a +/// hook 30 seconds, and the uninstaller removes only the old folder, its +/// shortcuts and its uninstall entry. Settings live elsewhere and stay. +#[cfg(windows)] +pub fn remove() { + let local_app_data = std::env::var_os("LOCALAPPDATA") + .map(PathBuf::from) + .filter(|p| p.is_absolute()); + let Some(uninstaller) = find_uninstaller(registered_folder(), local_app_data) else { + return; + }; + let arguments = ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"].map(str::to_owned); + if let Err(error) = crate::native_process::spawn(&uninstaller, &arguments) { + log::warn!("Could not remove the earlier installation: {error}"); + } +} + +#[cfg(not(windows))] +pub fn remove() {} + +/// `InstallLocation` from the old uninstall entry, read into a bounded buffer. +#[cfg(windows)] +fn registered_folder() -> Option { + use std::os::windows::ffi::OsStringExt; + use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_SZ, RegGetValueW}; + let key: Vec = UNINSTALL_KEY.encode_utf16().chain(Some(0)).collect(); + let value: Vec = "InstallLocation".encode_utf16().chain(Some(0)).collect(); + let mut buffer = [0u16; 1024]; + let mut bytes = u32::try_from(size_of_val(&buffer)).ok()?; + // SAFETY: both names are NUL-terminated and alive for the call; `bytes` + // holds the buffer's size, which the call never writes past. + let status = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_SZ, + std::ptr::null_mut(), + buffer.as_mut_ptr().cast(), + &raw mut bytes, + ) + }; + if status != 0 { + return None; + } + let units = usize::try_from(bytes).ok()? / 2; + let text = buffer.get(..units)?; + let end = text + .iter() + .position(|&unit| unit == 0) + .unwrap_or(text.len()); + let folder = PathBuf::from(std::ffi::OsString::from_wide(text.get(..end)?)); + Some(folder).filter(|p| p.is_absolute()) +} + +#[cfg(test)] +mod tests { + use std::fs; + + #[test] + fn finds_the_old_copy_only_by_its_marker() { + let local = tempfile::tempdir().unwrap(); + let folder = local.path().join("Programs/Reclaim"); + fs::create_dir_all(&folder).unwrap(); + fs::write(folder.join("unins000.exe"), b"uninstaller").unwrap(); + assert_eq!( + super::find_uninstaller(None, Some(local.path().into())), + None + ); + fs::write(folder.join("installed-by-inno"), b"marker").unwrap(); + assert_eq!( + super::find_uninstaller(None, Some(local.path().into())), + Some(folder.join("unins000.exe")) + ); + } + + #[test] + fn prefers_the_folder_chosen_in_the_old_setup() { + let chosen = tempfile::tempdir().unwrap(); + let local = tempfile::tempdir().unwrap(); + for folder in [ + chosen.path().to_owned(), + local.path().join("Programs/Reclaim"), + ] { + fs::create_dir_all(&folder).unwrap(); + fs::write(folder.join("unins000.exe"), b"uninstaller").unwrap(); + fs::write(folder.join("installed-by-inno"), b"marker").unwrap(); + } + assert_eq!( + super::find_uninstaller(Some(chosen.path().into()), Some(local.path().into())), + Some(chosen.path().join("unins000.exe")) + ); + // A relative or unmarked registry value falls back to the default. + assert_eq!( + super::find_uninstaller(Some("Reclaim".into()), Some(local.path().into())), + Some(local.path().join("Programs/Reclaim/unins000.exe")) + ); + } +} diff --git a/src/main.rs b/src/main.rs index 52aaf4f..a369fac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ mod diagnostics; mod drives; mod installer; +mod legacy_install; #[cfg(any(target_os = "linux", windows))] mod native_process; mod preview; @@ -1355,6 +1356,16 @@ fn run() -> Result<(), slint::PlatformError> { result } fn main() { + // Velopack runs the app with a hook command during install, update and + // uninstall; it must exit at once without opening a window. + if let Some(hook) = std::env::args_os() + .nth(1) + .as_deref() + .and_then(update_runtime::VelopackHook::parse) + { + update_runtime::run_velopack_hook(hook); + return; + } // The privileged update step runs as root through pkexec, with no desktop // session, so it is handled before any GUI, D-Bus or settings setup. #[cfg(target_os = "linux")] diff --git a/src/update_runtime.rs b/src/update_runtime.rs index cbcaa3e..e46ad9c 100644 --- a/src/update_runtime.rs +++ b/src/update_runtime.rs @@ -27,18 +27,65 @@ pub fn supported() -> bool { cfg!(any(target_os = "linux", windows)) } +/// Velopack installs to `\\current\\reclaim.exe` with its updater at +/// `\\Update.exe` and the package manifest at `current\\sq.version`. +/// Returns the updater for that layout; `None` for a portable copy. #[cfg(any(windows, test))] -fn windows_installer_arguments() -> Vec { - [ - "/SILENT", - "/SUPPRESSMSGBOXES", - "/NORESTART", - "/CLOSEAPPLICATIONS", - "/NORESTARTAPPLICATIONS", - ] - .into_iter() - .map(str::to_owned) - .collect() +fn velopack_updater(executable: &Path) -> Option { + let current = executable.parent()?; + if current.file_name()? != "current" || !current.join("sq.version").is_file() { + return None; + } + let updater = current.parent()?.join("Update.exe"); + updater.is_file().then_some(updater) +} + +/// `Update.exe apply` waits for this process to exit, installs the verified +/// full package, then starts the new version. +#[cfg(any(windows, test))] +fn velopack_apply_arguments(package: &Path, process: u32) -> anyhow::Result> { + let package = package + .to_str() + .with_context(|| reclaim::i18n::diagnostic("Update cache path is not valid Unicode"))?; + Ok(vec![ + "apply".to_owned(), + "--silent".to_owned(), + "--waitPid".to_owned(), + process.to_string(), + "--package".to_owned(), + package.to_owned(), + ]) +} + +/// The commands Velopack's setup and updater run the app with. Each must +/// exit quickly and show no window, or Velopack kills the process. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VelopackHook { + Install, + Updated, + Obsolete, + Uninstall, +} + +impl VelopackHook { + pub fn parse(argument: &std::ffi::OsStr) -> Option { + match argument.to_str()? { + "--veloapp-install" => Some(Self::Install), + "--veloapp-updated" => Some(Self::Updated), + "--veloapp-obsolete" => Some(Self::Obsolete), + "--veloapp-uninstall" => Some(Self::Uninstall), + _ => None, + } + } +} + +/// Runs a Velopack hook. Install and update both retry the cleanup of an +/// old installation, so a copy that was still busy is removed next time. +pub fn run_velopack_hook(hook: VelopackHook) { + match hook { + VelopackHook::Install | VelopackHook::Updated => crate::legacy_install::remove(), + VelopackHook::Obsolete | VelopackHook::Uninstall => {} + } } /// Private per-user folder for staged update packages. Each download gets its @@ -107,14 +154,11 @@ pub fn update( bail!("Automatic package updates require pkexec (polkit)"); } #[cfg(windows)] - if !executable - .parent() - .is_some_and(|p| p.join("installed-by-inno").is_file()) - { + let Some(velopack) = velopack_updater(&executable) else { bail!("Run the Windows setup once to enable automatic updates"); - } + }; // Dropping `stage` deletes the package on every path, including errors; - // only the Windows hand-off keeps it, because the installer is still running. + // only the Windows hand-off keeps it, because the updater still needs it. let stage = new_stage()?; let package = stage.path().join(&release.asset); phase("Downloading and verifying update…"); @@ -130,10 +174,10 @@ pub fn update( } #[cfg(windows)] { - phase("Starting installer…"); - let directory = stage.keep(); - let package = directory.join(&release.asset); - crate::native_process::spawn(&package, &windows_installer_arguments())?; + phase("Restarting Reclaim…"); + let package = stage.keep().join(&release.asset); + let arguments = velopack_apply_arguments(&package, std::process::id())?; + crate::native_process::spawn(&velopack, &arguments)?; Ok(()) } #[cfg(not(any(target_os = "linux", windows)))] @@ -227,11 +271,27 @@ fn pkexec_result(code: Option) -> anyhow::Result<()> { /// symbolic links are never followed. Locked files are retried next launch. pub fn cleanup_staged_updates() { if let Ok(root) = cache_root() { - remove_stages(&root); + remove_stages(&root, std::time::SystemTime::now()); } } -fn remove_stages(root: &Path) { +/// Stages younger than this may still be in use: a download in another +/// Reclaim window, or a package Velopack's `Update.exe` is waiting to apply +/// (it waits at most a minute for Reclaim to exit). +const STAGE_GRACE: std::time::Duration = std::time::Duration::from_hours(1); + +/// A stage is old once its folder has not changed for [`STAGE_GRACE`]. A +/// timestamp that cannot be read or lies in the future counts as recent. +fn stage_is_old(entry: &std::fs::DirEntry, now: std::time::SystemTime) -> bool { + entry + .metadata() + .and_then(|metadata| metadata.modified()) + .ok() + .and_then(|modified| now.duration_since(modified).ok()) + .is_some_and(|age| age >= STAGE_GRACE) +} + +fn remove_stages(root: &Path, now: std::time::SystemTime) { let Ok(entries) = std::fs::read_dir(root) else { return; }; @@ -241,7 +301,8 @@ fn remove_stages(root: &Path) { .file_name() .to_string_lossy() .starts_with(STAGE_PREFIX) - && entry.file_type().is_ok_and(|kind| kind.is_dir()); + && entry.file_type().is_ok_and(|kind| kind.is_dir()) + && stage_is_old(&entry, now); if is_stage && let Err(error) = std::fs::remove_dir_all(entry.path()) { log::warn!("Could not remove a staged update yet: {error}"); } @@ -251,21 +312,60 @@ fn remove_stages(root: &Path) { #[cfg(test)] mod tests { #[test] - fn windows_update_uses_direct_installer_handoff() { + fn windows_update_hands_the_verified_package_to_velopack() { + let package = std::path::Path::new("C:/cache/pending-1/reclaim-windows-x86_64-full.nupkg"); assert_eq!( - super::windows_installer_arguments(), + super::velopack_apply_arguments(package, 42).unwrap(), [ - "/SILENT", - "/SUPPRESSMSGBOXES", - "/NORESTART", - "/CLOSEAPPLICATIONS", - "/NORESTARTAPPLICATIONS" + "apply", + "--silent", + "--waitPid", + "42", + "--package", + "C:/cache/pending-1/reclaim-windows-x86_64-full.nupkg" ] ); - let installer = include_str!("../packaging/windows/reclaim.iss"); - assert!(installer.contains("RestartApplications=yes")); - assert!(installer.contains("Check: WizardSilent")); - assert!(!installer.contains("reclaim-update.exe")); + } + + #[test] + fn recognises_only_velopack_hook_commands() { + use super::VelopackHook; + for (argument, hook) in [ + ("--veloapp-install", Some(VelopackHook::Install)), + ("--veloapp-updated", Some(VelopackHook::Updated)), + ("--veloapp-obsolete", Some(VelopackHook::Obsolete)), + ("--veloapp-uninstall", Some(VelopackHook::Uninstall)), + ("--veloapp-install=1", None), + ("--install-deb-update", None), + ("disk.img", None), + ] { + assert_eq!( + VelopackHook::parse(std::ffi::OsStr::new(argument)), + hook, + "{argument}" + ); + } + } + + #[test] + fn only_a_velopack_layout_enables_windows_updates() { + let root = tempfile::tempdir().unwrap(); + let current = root.path().join("current"); + std::fs::create_dir(¤t).unwrap(); + let executable = current.join("reclaim.exe"); + std::fs::write(&executable, b"app").unwrap(); + assert_eq!(super::velopack_updater(&executable), None); + std::fs::write(current.join("sq.version"), b"manifest").unwrap(); + assert_eq!(super::velopack_updater(&executable), None); + std::fs::write(root.path().join("Update.exe"), b"updater").unwrap(); + assert_eq!( + super::velopack_updater(&executable), + Some(root.path().join("Update.exe")) + ); + // A portable copy next to a stray Update.exe is not an installation. + let portable = root.path().join("reclaim.exe"); + std::fs::write(&portable, b"app").unwrap(); + assert_eq!(super::velopack_updater(&portable), None); } #[test] @@ -281,8 +381,12 @@ mod tests { #[cfg(unix)] std::os::unix::fs::symlink(outside.path(), root.path().join("pending-link")).unwrap(); - super::remove_stages(root.path()); + let now = std::time::SystemTime::now(); + // A fresh stage may belong to a running download or update hand-off. + super::remove_stages(root.path(), now); + assert!(stage.exists()); + super::remove_stages(root.path(), now + super::STAGE_GRACE); assert!(!stage.exists()); assert!(root.path().join("pending-file").exists()); assert!(root.path().join("keep").exists()); diff --git a/src/updater.rs b/src/updater.rs index 04ab9b0..edce3cf 100644 --- a/src/updater.rs +++ b/src/updater.rs @@ -372,6 +372,10 @@ fn parse_release_after( Ok(Some(release)) } +/// The Velopack full package that `Update.exe apply` installs. The setup +/// executable is only for first installs and is never run by the updater. +const WINDOWS_PACKAGE: &str = "reclaim-windows-x86_64-full.nupkg"; + /// Installed packages must be updated as packages to preserve receipts and uninstall metadata. pub fn installer_download(release: &Release) -> Option { is_installer(&release.asset).then(|| release.url.clone()) @@ -382,7 +386,7 @@ pub fn installer_download(release: &Release) -> Option { reason = "release asset names are exact; another case is not one of our assets" )] fn is_installer(name: &str) -> bool { - name.ends_with("-setup.exe") || name.ends_with(".deb") || name.ends_with(".pkg") + name.ends_with("-full.nupkg") || name.ends_with(".deb") || name.ends_with(".pkg") } /// Download the actual package asset, verify it, then atomically publish the @@ -459,7 +463,7 @@ fn installer_name(executable: &std::path::Path, version: &semver::Version) -> Op { Some(format!("reclaim-macos-{}.pkg", std::env::consts::ARCH)) } else if cfg!(windows) { - Some("reclaim-windows-x86_64-setup.exe".into()) + Some(WINDOWS_PACKAGE.into()) } else { None } @@ -717,7 +721,7 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT .unwrap(); let version = json["tag_name"].as_str().unwrap().trim_start_matches('v'); let name = if cfg!(windows) { - "reclaim-windows-x86_64-setup.exe".into() + WINDOWS_PACKAGE.into() } else if cfg!(target_os = "macos") { format!("reclaim-macos-{}.pkg", std::env::consts::ARCH) } else { diff --git a/tests/audit/rules.rs b/tests/audit/rules.rs index 75007ac..e7286be 100644 --- a/tests/audit/rules.rs +++ b/tests/audit/rules.rs @@ -10,6 +10,7 @@ const UNSAFE_FILES: &[&str] = &[ "src/drives/macos.rs", // DiskArbitration and IOKit "src/drives/windows.rs", // volume and device IOCTLs "src/installer.rs", // ShellExecuteW + "src/legacy_install.rs", // reading the old uninstall entry "src/native_process.rs", // posix_spawn / CreateProcessW "src/preview.rs", // reopening a Windows handle, extended volume reads "src/update_runtime.rs", // geteuid for the elevated update helper diff --git a/tests/audit/workspace.rs b/tests/audit/workspace.rs index 5de0350..63ca2d2 100644 --- a/tests/audit/workspace.rs +++ b/tests/audit/workspace.rs @@ -160,7 +160,7 @@ const SKIP_DIRS: &[&str] = &[ ]; const TEXT_EXTENSIONS: &[&str] = &[ "rs", "slint", "toml", "json", "md", "yml", "yaml", "ts", "astro", "mjs", "css", "html", "txt", - "iss", "plist", "desktop", "pub", "svg", + "plist", "desktop", "pub", "svg", ]; impl Workspace { diff --git a/tools/src/package.rs b/tools/src/package.rs index b6afc30..9ef2719 100644 --- a/tools/src/package.rs +++ b/tools/src/package.rs @@ -122,32 +122,88 @@ fn mac(binary: &Path, output: &Path, work: &Path, arch: &str) -> Result { ]) .arg(output.join(format!("reclaim-macos-{arch}.pkg")))) } -fn windows(binary: &Path, output: &Path) -> Result { - let base = std::env::var_os("ProgramFiles(x86)") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(r"C:\Program Files (x86)")); - let mut candidates: Vec<_> = fs::read_dir(base) - .into_iter() - .flatten() - .filter_map(|entry| entry.ok()) - .filter(|entry| { - entry - .file_name() - .to_string_lossy() - .starts_with("Inno Setup ") - }) - .map(|entry| entry.path().join("ISCC.exe")) - .filter(|path| path.is_file()) - .collect(); - candidates.sort(); - let compiler = candidates - .pop() - .unwrap_or_else(|| PathBuf::from("ISCC.exe")); - run(Command::new(compiler) - .arg(format!("/DAppVersion={}", version()?)) - .arg(format!("/DBinaryPath={}", binary.display())) - .arg(format!("/DOutputPath={}", output.display())) - .arg(root().join("packaging/windows/reclaim.iss"))) +/// Velopack package id: names the install folder (`%LocalAppData%\\`) and +/// the uninstall entry. Matches the WinGet identifier. +const VELOPACK_ID: &str = "sudo-py-dev.Reclaim"; +/// Release asset names. The updater (`src/updater.rs`) downloads the package; +/// the setup is only for first installs and WinGet. +const WINDOWS_SETUP: &str = "reclaim-windows-x86_64-setup.exe"; +const WINDOWS_PACKAGE: &str = "reclaim-windows-x86_64-full.nupkg"; + +/// The files Velopack installs into `current\\`: the app and its licenses. +fn velopack_tree(binary: &Path, tree: &Path) -> Result { + copy(binary, tree.join("reclaim.exe"))?; + licenses(&tree.join("licenses")) +} + +/// Move vpk's version-stamped outputs to the fixed release asset names. +fn velopack_outputs(packed: &Path, output: &Path) -> Result { + for (suffix, name) in [ + ("-Setup.exe", WINDOWS_SETUP), + ("-full.nupkg", WINDOWS_PACKAGE), + ] { + let mut found = fs::read_dir(packed)? + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .is_some_and(|n| n.to_string_lossy().ends_with(suffix)) + }); + let source = found + .next() + .ok_or_else(|| format!("vpk produced no *{suffix}"))?; + if found.next().is_some() { + return Err(format!("vpk produced more than one *{suffix}").into()); + } + let target = output.join(name); + if target.exists() { + fs::remove_file(&target)?; + } + copy(&source, &target)?; + } + Ok(()) +} + +fn windows(binary: &Path, output: &Path, work: &Path) -> Result { + let tree = work.join("app"); + let packed = work.join("velopack"); + velopack_tree(binary, &tree)?; + run(Command::new("vpk") + .args([ + "pack", + "--packId", + VELOPACK_ID, + "--packVersion", + &version()?, + ]) + .args([ + "--packTitle", + "Reclaim", + "--packAuthors", + "Reclaim contributors", + ]) + .args([ + "--mainExe", + "reclaim.exe", + "--runtime", + "win-x64", + "--channel", + "win", + ]) + .args([ + "--shortcuts", + "StartMenuRoot", + "--delta", + "None", + "--noPortable", + ]) + .arg("--icon") + .arg(root().join("assets/icons/reclaim.ico")) + .arg("--packDir") + .arg(&tree) + .arg("--outputDir") + .arg(&packed))?; + velopack_outputs(&packed, output) } pub fn main(args: &[String]) -> Result { let platform = args @@ -191,7 +247,7 @@ pub fn main(args: &[String]) -> Result { match platform.as_str() { "linux" => deb(&binary, &output, work.path()), "macos" => mac(&binary, &output, work.path(), arch), - "windows" => windows(&binary, &output), + "windows" => windows(&binary, &output, work.path()), _ => unreachable!(), } } @@ -238,4 +294,33 @@ mod tests { } Ok(()) } + + #[test] + fn velopack_tree_and_outputs_use_fixed_release_names() -> Result { + let work = tempfile::tempdir()?; + let binary = work.path().join("binary"); + fs::write(&binary, b"installer input")?; + let tree = work.path().join("tree"); + velopack_tree(&binary, &tree)?; + assert_eq!(fs::read(tree.join("reclaim.exe"))?, b"installer input"); + assert!(tree.join("licenses/LICENSE").is_file()); + assert!(tree.join("licenses/DejaVu-LICENSE.txt").is_file()); + + let packed = work.path().join("packed"); + fs::create_dir(&packed)?; + let output = work.path().join("dist"); + fs::create_dir(&output)?; + fs::write(packed.join("sudo-py-dev.Reclaim-win-Setup.exe"), b"setup")?; + assert!(velopack_outputs(&packed, &output).is_err()); + fs::write( + packed.join("sudo-py-dev.Reclaim-1.0.0-full.nupkg"), + b"package", + )?; + fs::write(packed.join("releases.win.json"), b"{}")?; + velopack_outputs(&packed, &output)?; + assert_eq!(fs::read(output.join(WINDOWS_SETUP))?, b"setup"); + assert_eq!(fs::read(output.join(WINDOWS_PACKAGE))?, b"package"); + assert_eq!(fs::read_dir(&output)?.count(), 2); + Ok(()) + } }