diff --git a/CHANGELOG.md b/CHANGELOG.md index c6d1d5d3b..d05d9b01a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,8 +22,10 @@ Rename this heading to the version number when you release it. level: recommended ko: GitHub에서 업데이트 파일을 받지 못하면 Filee 다운로드 서버(dl.filee.sh)에서 받아요 en: Updates come from Filee's download server (dl.filee.sh) when GitHub doesn't answer +en: In-app updates now install in-place directly on macOS app bundles and Windows Portable without opening download pages --> +- **In-app updates now install in-place directly on macOS and Windows Portable**: Previously, portable Windows copies and macOS app bundles directed users to manual browser download pages. Filee now downloads and installs in-place automatically: Windows Portable safely extracts the verified portable zip and swaps files via a detached background PowerShell helper (preserving user `data` and portable settings), while macOS unpacks the verified app bundle and swaps it via a detached helper with quarantine removal and automatic rollback on failure. - **Updating from Settings → About works when GitHub's downloads don't answer** (#1593). The in-app update on Windows gave up when GitHub's download link didn't answer within 20 seconds, which some networks hit every time. Filee now takes the same file from its own download server (`dl.filee.sh`) instead, and the rest of that update goes there diff --git a/README.md b/README.md index 5418132f0..f96157c23 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ winget install KnifeLemon.Filee Portable releases keep their data beside the app; see [portable mode](docs/PORTABLE.md). -Filee shows new releases in its menu and updates itself, keeping your settings and engines. +Filee shows new releases in its menu and updates itself in-place across Windows (both Setup and Portable), macOS app bundles, and Linux, keeping your settings and engines without redirecting to manual download pages. After an update, a few slides show what's new. **Windows: Filee doesn't start (no window, no error)?** diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c04b128c3..4cb558d79 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -820,11 +820,15 @@ have no semibold) instead of the app's embedded Noto fonts. Inno Setup's: 0 done, 1 could not start, 2 cancelled before installing (also a declined UAC prompt), 4 failed. - **In-app updates** (`UpdateService`): an installed copy downloads `Filee--SHA256SUMS.txt`, its `.sig` and `Filee--win[-arm64]-Setup.exe` from the GitHub release, checks the signature with the update key, the Setup's - SHA-256 and its Authenticode publisher, and runs it with `/SILENT /NORESTART`. A file GitHub doesn't hand out (an - HTTP error, a timeout, a cut connection) is taken from the download mirror, `https://dl.filee.sh//` - (`UpdateService.MirrorRoot`, filled by `build/sign-release.ps1`); after one GitHub failure, the update's other files - try the mirror first. The checks don't depend on the source. A file that arrived and was refused is not fetched - again from the other source. Linux and macOS files aren't on the mirror. + SHA-256 and its Authenticode publisher, and runs it with `/SILENT /NORESTART`. Portable Windows copies (`win-portable`, + `win-arm64-portable`) download `Filee--win[-arm64]-Portable.zip`, verify its SHA-256 (and `.sig`), safely extract the + archive verifying path traversal (Zip Slip defense), and delegate file replacement to a background helper script + (`powershell.exe -ExecutionPolicy Bypass -File update-portable.ps1`), preserving the user's `data` folder and `filee.portable` + marker before restarting Filee with `--background --whats-new`. A file GitHub doesn't hand out (an HTTP error, a timeout, + a cut connection) is taken from the download mirror, `https://dl.filee.sh//` (`UpdateService.MirrorRoot`, + filled by `build/sign-release.ps1`); after one GitHub failure, the update's other files try the mirror first. The checks + don't depend on the source. A file that arrived and was refused is not fetched again from the other source. Linux and macOS + files aren't on the mirror. - **Testing**: `Filee.Setup.Tests` runs installs, updates (also over a simulated 1.x installation) and uninstalls against `MemoryRegistry`, a fake `ISetupSystem` and scratch folders, and renders every page. `/SANDBOX=` runs the real Setup with a registry file and all folders inside ``; `build-installer.ps1 -CheckOnly` (CI) @@ -855,6 +859,13 @@ and standalone shell scripts (`install.sh`, `uninstall.sh`). - **Uninstallation**: `uninstall.sh` removes the application directory, desktop launcher, and `~/.local/bin/filee` symlink after verifying the `.filee-package` marker. User settings and converted files are kept. +## macOS app bundle and updates + +On macOS, Filee is packaged as `Filee.app` and distributed as a self-contained archive (`Filee--.tar.gz` for `osx-arm64` and `osx-x64`) and disk image (`.dmg`). + +- **In-app updates** (`UpdateService`): Running from a `Filee.app` bundle enables self-updating (`CanSelfUpdate`). Checks GitHub releases for matching `.tar.gz` and `-SHA256SUMS.txt` assets. Verifies archive SHA-256 and `.sig` before extraction. Archive extraction validates that all entries stay within the secure staging directory. +- **Atomic bundle replacement**: `UpdateAsync` stages the new `Filee.app` in a private temporary workspace, spawns a detached `/bin/sh` helper script, and requests application shutdown (`App.Quit`). Once Filee exits, the helper backs up the existing `.app` bundle, synchronizes the new bundle with `/usr/bin/ditto` (preserving bundle structure and code signatures), clears quarantine attributes via `/usr/bin/xattr -dr com.apple.quarantine`, refreshes the `~/.local/bin/filee` CLI link if present, and launches the updated application with `open -n` and `--background --whats-new` (falling back to direct executable launch). On failure, the helper automatically rolls back to the previous bundle, records diagnostics, and writes an update failure marker. + ## Filee Connect Filee Connect (`Filee.App.Services.Connect`) is an embedded local Wi-Fi server providing instant device-to-device file transfers and quick note exchanges between desktop and mobile devices. See [FILEE-CONNECT.md](FILEE-CONNECT.md) for full details. diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.cs index cea4ad321..a00097414 100644 --- a/src/Filee.App/Services/UpdateService.cs +++ b/src/Filee.App/Services/UpdateService.cs @@ -113,14 +113,24 @@ internal UpdateService(ILogger log, HttpMessageHandler handler) private static readonly bool InstalledCopy = OperatingSystem.IsWindows() && IsInstalledIn(AppContext.BaseDirectory) - || OperatingSystem.IsLinux() && IsLinuxInstalled(AppContext.BaseDirectory); + || OperatingSystem.IsLinux() && IsLinuxInstalled(AppContext.BaseDirectory) + || OperatingSystem.IsMacOS() && IsMacAppBundle(AppContext.BaseDirectory); /// - /// Installed by Windows Setup or Linux install.sh, and not marked portable. A marked copy is updated manually + /// Installed by Windows Setup or Linux install.sh or macOS app bundle, and not marked portable. A marked copy is updated manually /// so an installer cannot register it or replace the user's installed copy. /// public static bool IsInstalled => !PortableMode.IsEnabled && InstalledCopy; + /// + /// Whether Filee can update itself in-place: installed Windows (Setup), portable Windows (zip), + /// installed Linux (install.sh), or macOS app bundle (ditto). + /// + public static bool CanSelfUpdate => + OperatingSystem.IsWindows() + || OperatingSystem.IsLinux() && IsLinuxInstalled(AppContext.BaseDirectory) + || OperatingSystem.IsMacOS() && IsMacAppBundle(AppContext.BaseDirectory); + internal static bool IsInstalledIn(string folder) => File.Exists(Path.Combine(folder, "uninstall.exe")) || File.Exists(Path.Combine(folder, "unins000.exe")); @@ -137,6 +147,29 @@ internal static bool IsLinuxInstalled(string baseDirectory) } } + internal static bool IsMacAppBundle(string baseDirectory) => + MacAppBundleOverride is not null || GetMacAppBundlePath(baseDirectory) is not null; + + internal static string? GetMacAppBundlePath(string? path = null) + { + if (MacAppBundleOverride is { } ovr) + return ovr; + var current = Path.GetFullPath(path ?? Environment.ProcessPath ?? AppContext.BaseDirectory); + const string contentsMacOS = "/Contents/MacOS"; + var index = current.LastIndexOf(contentsMacOS, StringComparison.OrdinalIgnoreCase); + if (index > 0 && current[..index].EndsWith(".app", StringComparison.OrdinalIgnoreCase)) + return current[..index]; + + var dir = new DirectoryInfo(current); + while (dir is not null) + { + if (dir.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase)) + return dir.FullName; + dir = dir.Parent; + } + return null; + } + /// Returns the RID for the current Linux process architecture ("linux-x64" or "linux-arm64"). internal static string GetLinuxRid() => GetLinuxRid(RuntimeInformation.ProcessArchitecture); @@ -149,6 +182,18 @@ internal static string GetLinuxRid(Architecture architecture) => var arch => throw new PlatformNotSupportedException($"Unsupported Linux architecture: {arch}"), }; + /// Returns the RID for the current macOS process architecture ("osx-arm64" or "osx-x64"). + internal static string GetMacOsRid() => GetMacOsRid(RuntimeInformation.ProcessArchitecture); + + /// Maps to supported macOS RIDs or throws . + internal static string GetMacOsRid(Architecture architecture) => + architecture switch + { + Architecture.Arm64 => "osx-arm64", + Architecture.X64 => "osx-x64", + var arch => throw new PlatformNotSupportedException($"Unsupported macOS architecture: {arch}"), + }; + /// /// The Windows release files for a process of : "win-arm64" for the native ARM64 /// build, "win" (the x64 files) otherwise. It is the process, not the PC: the x64 build on Windows on ARM keeps @@ -156,17 +201,30 @@ internal static string GetLinuxRid(Architecture architecture) => /// internal static string GetWindowsTarget(Architecture architecture) => architecture == Architecture.Arm64 ? "win-arm64" : "win"; - private static bool IsWindowsTarget(string target) => target is "win" or "win-arm64"; + private static bool IsWindowsTarget(string target) => + target is "win" or "win-arm64" or "win-portable" or "win-arm64-portable"; + + private static bool IsWindowsPortable(string target) => + target is "win-portable" or "win-arm64-portable"; + + private static bool IsLinuxTarget(string target) => + target.StartsWith("linux-", StringComparison.OrdinalIgnoreCase); + + private static bool IsMacOsTarget(string target) => + target.StartsWith("osx-", StringComparison.OrdinalIgnoreCase); /// - /// Target platform for release assets ("win", "win-arm64", "linux-x64", "linux-arm64"). Tests can override this. + /// Target platform for release assets ("win", "win-arm64", "win-portable", "win-arm64-portable", "linux-x64", "linux-arm64", "osx-arm64", "osx-x64"). Tests can override this. /// internal string TargetPlatform { get; set; } = DefaultTargetPlatform(); private static string DefaultTargetPlatform() { if (OperatingSystem.IsWindows()) - return GetWindowsTarget(RuntimeInformation.ProcessArchitecture); + { + var arch = GetWindowsTarget(RuntimeInformation.ProcessArchitecture); + return PortableMode.IsEnabled || !InstalledCopy ? $"{arch}-portable" : arch; + } if (OperatingSystem.IsLinux()) { try @@ -178,6 +236,17 @@ private static string DefaultTargetPlatform() return "unsupported"; } } + if (OperatingSystem.IsMacOS()) + { + try + { + return GetMacOsRid(); + } + catch (PlatformNotSupportedException) + { + return "unsupported"; + } + } return "unsupported"; } @@ -190,14 +259,20 @@ private static string DefaultTargetPlatform() /// Allows tests to redirect Linux installation target directory to an isolated temporary folder. internal string? LinuxInstallDirectoryOverride { get; set; } + /// Allows tests to redirect macOS installation target bundle to an isolated temporary location. + internal string? MacAppBundleOverride { get; set; } + + /// Allows tests to redirect Windows portable target directory to an isolated temporary folder. + internal string? WindowsInstallDirectoryOverride { get; set; } + /// Allows tests to redirect update failure marker path to an isolated temporary location. internal string? FailureMarkerPathOverride { get; set; } /// The log file path recorded in the update failure marker from the previous run, if any. internal string? LastFailureLogPath { get; private set; } - /// Whether installs by itself (; tests set it). - internal bool InstallsItself { get; init; } = IsInstalled; + /// Whether installs by itself (; tests set it). + internal bool InstallsItself { get; init; } = CanSelfUpdate; /// /// Who signed a program, if Windows trusts the signature (; the flag also @@ -403,6 +478,121 @@ public async Task UpdateAsync() if (IsWindowsTarget(TargetPlatform)) { + if (IsWindowsPortable(TargetPlatform)) + { + string? workspace = null; + string archive; + try + { + workspace = CreateSecureWorkspace(); + var progress = new Progress(percent => DownloadPercent = percent); + archive = await DownloadInstallerAsync(workspace, progress); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException + or InvalidDataException or UnauthorizedAccessException) + { + DeleteSecureWorkspace(workspace); + Fail("download", ex); + return; + } + + var stagingDir = Path.Combine(workspace, "payload"); + string payloadDir; + try + { + Directory.CreateDirectory(stagingDir); + payloadDir = ExtractZipArchive(archive, stagingDir); + var newFileeExe = Path.Combine(payloadDir, "Filee.exe"); + if (ExpectedPublisher is not null) + { + await Task.Run(() => CheckPublisher(newFileeExe)); + } + } + catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException + or UpdateVerificationException) + { + DeleteSecureWorkspace(workspace); + Fail("extract", ex); + return; + } + + var targetInstallDir = WindowsInstallDirectoryOverride ?? AppContext.BaseDirectory; + var newExe = Path.Combine(targetInstallDir, "Filee.exe"); + var currentPid = Environment.ProcessId; + var logDir = Path.Combine(UserDataStore.DefaultDirectory, "logs"); + Directory.CreateDirectory(logDir); + var logFile = Path.Combine(logDir, $"filee-{DateTime.Now:yyyyMMdd}.log"); + var markerFile = FailureMarkerPathOverride ?? Path.Combine(UserDataStore.DefaultDirectory, ".update-failed"); + + var scriptPath = Path.Combine(workspace, "update-portable.ps1"); + var scriptContent = + "param([int]$TargetPid, [string]$StagingDir, [string]$TargetDir, [string]$LogFile, [string]$WorkspaceDir, [string]$MarkerFile, [string]$NewExe)\r\n" + + "$sw = [Diagnostics.Stopwatch]::StartNew()\r\n" + + "while ((Get-Process -Id $TargetPid -ErrorAction SilentlyContinue) -and $sw.ElapsedMilliseconds -lt 60000) {\r\n" + + " Start-Sleep -Milliseconds 100\r\n" + + "}\r\n" + + "if (Get-Process -Id $TargetPid -ErrorAction SilentlyContinue) {\r\n" + + " Add-Content -LiteralPath $LogFile -Value \"Update aborted: Filee (PID $TargetPid) did not exit within timeout\"\r\n" + + " Remove-Item -LiteralPath $WorkspaceDir -Recurse -Force -ErrorAction SilentlyContinue\r\n" + + " exit 1\r\n" + + "}\r\n" + + "try {\r\n" + + " Get-ChildItem -LiteralPath $StagingDir -Force | ForEach-Object {\r\n" + + " Copy-Item -LiteralPath $_.FullName -Destination $TargetDir -Recurse -Force\r\n" + + " }\r\n" + + " $marker = Join-Path $TargetDir 'filee.portable'\r\n" + + " if (-not (Test-Path -LiteralPath $marker)) { New-Item -ItemType File -Path $marker -Force | Out-Null }\r\n" + + " Remove-Item -LiteralPath $WorkspaceDir -Recurse -Force -ErrorAction SilentlyContinue\r\n" + + " Start-Process -FilePath $NewExe -ArgumentList @('--background', '--whats-new')\r\n" + + "}\r\n" + + "catch {\r\n" + + " Add-Content -LiteralPath $LogFile -Value \"Update failed: $($_.Exception.Message)\"\r\n" + + " Set-Content -LiteralPath \"$MarkerFile.tmp\" -Value $LogFile\r\n" + + " Move-Item -LiteralPath \"$MarkerFile.tmp\" -Destination $MarkerFile -Force -ErrorAction SilentlyContinue\r\n" + + " Remove-Item -LiteralPath $WorkspaceDir -Recurse -Force -ErrorAction SilentlyContinue\r\n" + + " Start-Process -FilePath $NewExe -ArgumentList @('--background')\r\n" + + " exit 1\r\n" + + "}\r\n"; + File.WriteAllText(scriptPath, scriptContent, Encoding.UTF8); + + Process? helper; + try + { + var startInfo = new ProcessStartInfo("powershell.exe") + { + WorkingDirectory = payloadDir, + UseShellExecute = false, + CreateNoWindow = true, + }; + startInfo.ArgumentList.Add("-NoProfile"); + startInfo.ArgumentList.Add("-NonInteractive"); + startInfo.ArgumentList.Add("-ExecutionPolicy"); + startInfo.ArgumentList.Add("Bypass"); + startInfo.ArgumentList.Add("-File"); + startInfo.ArgumentList.Add(scriptPath); + startInfo.ArgumentList.Add(currentPid.ToString()); + startInfo.ArgumentList.Add(payloadDir); + startInfo.ArgumentList.Add(targetInstallDir); + startInfo.ArgumentList.Add(logFile); + startInfo.ArgumentList.Add(workspace); + startInfo.ArgumentList.Add(markerFile); + startInfo.ArgumentList.Add(newExe); + + helper = StartProcess(startInfo); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) + { + DeleteSecureWorkspace(workspace); + Fail("start", ex); + return; + } + + _log.LogInformation("Started Windows portable update helper for {Version}, exiting current process", LatestVersion); + Step = UpdateStep.Installing; + RequestApplicationShutdown?.Invoke(); + return; + } + var folder = Path.Combine(Path.GetTempPath(), "Filee-update"); string installer; try @@ -448,7 +638,7 @@ public async Task UpdateAsync() return; } - if (TargetPlatform.StartsWith("linux-", StringComparison.OrdinalIgnoreCase)) + if (IsLinuxTarget(TargetPlatform)) { string? workspace = null; string installer; @@ -535,7 +725,101 @@ public async Task UpdateAsync() return; } - throw new PlatformNotSupportedException("In-app update is only supported on Windows and Linux"); + if (IsMacOsTarget(TargetPlatform)) + { + string? workspace = null; + string installer; + try + { + workspace = CreateSecureWorkspace(); + var progress = new Progress(percent => DownloadPercent = percent); + installer = await DownloadInstallerAsync(workspace, progress); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException + or InvalidDataException or UnauthorizedAccessException) + { + DeleteSecureWorkspace(workspace); + Fail("download", ex); + return; + } + + var stagingDir = Path.Combine(workspace, "payload"); + string payloadAppBundle; + try + { + Directory.CreateDirectory(stagingDir); + payloadAppBundle = ExtractMacArchive(installer, stagingDir); + } + catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException) + { + DeleteSecureWorkspace(workspace); + Fail("extract", ex); + return; + } + + var targetAppBundle = MacAppBundleOverride ?? GetMacAppBundlePath() ?? "/Applications/Filee.app"; + var newExe = Path.Combine(targetAppBundle, "Contents", "MacOS", "Filee"); + var currentPid = Environment.ProcessId; + var logDir = Path.Combine(UserDataStore.DefaultDirectory, "logs"); + Directory.CreateDirectory(logDir); + var logFile = Path.Combine(logDir, $"filee-{DateTime.Now:yyyyMMdd}.log"); + var markerFile = FailureMarkerPathOverride ?? Path.Combine(UserDataStore.DefaultDirectory, ".update-failed"); + + Process? helper; + try + { + var startInfo = new ProcessStartInfo("/bin/sh") + { + WorkingDirectory = stagingDir, + UseShellExecute = false, + }; + startInfo.ArgumentList.Add("-c"); + startInfo.ArgumentList.Add( + "for _ in $(seq 1 600); do if ! kill -0 \"$1\" 2>/dev/null; then break; fi; sleep 0.1; done; " + + "if kill -0 \"$1\" 2>/dev/null; then echo \"Update aborted: Filee (PID $1) did not exit within timeout\" >> \"$4\"; rm -rf \"$5\" 2>/dev/null; exit 1; fi; " + + "backup=\"${3}.old.$$\"; " + + "if [ -e \"$3\" ]; then mv -f \"$3\" \"$backup\" 2>/dev/null || true; fi; " + + "/usr/bin/ditto \"$2\" \"$3\" >> \"$4\" 2>&1; " + + "status=$?; " + + "rm -rf \"$5\" 2>/dev/null; " + + "if [ $status -eq 0 ]; then " + + "rm -rf \"$backup\" 2>/dev/null; " + + "/usr/bin/xattr -dr com.apple.quarantine \"$3\" 2>/dev/null || true; " + + "bin_dir=\"$HOME/.local/bin\"; " + + "if [ -d \"$bin_dir\" ] && [ -f \"$3/Contents/MacOS/filee-cli\" ]; then ln -sf \"$3/Contents/MacOS/filee-cli\" \"$bin_dir/filee\" 2>/dev/null || true; fi; " + + "if [ -x \"$7\" ]; then open -n \"$3\" --args --background --whats-new 2>/dev/null || exec \"$7\" --background --whats-new; else echo \"Update succeeded but '$7' is not executable\" >> \"$4\"; exit 1; fi; " + + "else " + + "echo \"Update failed with status $status\" >> \"$4\"; " + + "echo \"$4\" > \"$6.tmp\" 2>/dev/null && mv -f \"$6.tmp\" \"$6\" 2>/dev/null || true; " + + "if [ -e \"$backup\" ]; then rm -rf \"$3\" 2>/dev/null; mv -f \"$backup\" \"$3\" 2>/dev/null || true; fi; " + + "if [ -x \"$7\" ]; then open -n \"$3\" --args --background 2>/dev/null || exec \"$7\" --background; else echo \"Cannot restart Filee: '$7' is not executable after rollback\" >> \"$4\"; exit $status; fi; " + + "fi" + ); + startInfo.ArgumentList.Add("_"); + startInfo.ArgumentList.Add(currentPid.ToString()); + startInfo.ArgumentList.Add(payloadAppBundle); + startInfo.ArgumentList.Add(targetAppBundle); + startInfo.ArgumentList.Add(logFile); + startInfo.ArgumentList.Add(workspace); + startInfo.ArgumentList.Add(markerFile); + startInfo.ArgumentList.Add(newExe); + + helper = StartProcess(startInfo); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) + { + DeleteSecureWorkspace(workspace); + Fail("start", ex); + return; + } + + _log.LogInformation("Started macOS update helper for {Version}, exiting current process", LatestVersion); + Step = UpdateStep.Installing; + RequestApplicationShutdown?.Invoke(); + return; + } + + throw new PlatformNotSupportedException("In-app update is only supported on Windows, Linux, and macOS"); } /// @@ -873,12 +1157,29 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE if (!release.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array) return (null, null); - // Windows has one checksum file for x64 and ARM64, Filee--SHA256SUMS.txt: Filee 2.4.0 and older take the - // last file ending in -SHA256SUMS.txt that isn't Linux or macOS, so an ARM64 one next to it would break their - // updates. The x64 Setup is Filee--win-Setup.exe, the ARM64 one Filee--win-arm64-Setup.exe. var isLinux = target.StartsWith("linux-", StringComparison.OrdinalIgnoreCase); - var expectedInstallerSuffix = isLinux ? $"-{target}.tar.gz" : $"-{target}-Setup.exe"; - var expectedChecksumsSuffix = isLinux ? $"-{target}-SHA256SUMS.txt" : "-SHA256SUMS.txt"; + var isMac = target.StartsWith("osx-", StringComparison.OrdinalIgnoreCase); + var isWinPortable = target is "win-portable" or "win-arm64-portable"; + + string expectedInstallerSuffix; + string expectedChecksumsSuffix; + + if (isLinux || isMac) + { + expectedInstallerSuffix = $"-{target}.tar.gz"; + expectedChecksumsSuffix = $"-{target}-SHA256SUMS.txt"; + } + else if (isWinPortable) + { + var archPart = target == "win-arm64-portable" ? "-win-arm64-Portable.zip" : "-win-Portable.zip"; + expectedInstallerSuffix = archPart; + expectedChecksumsSuffix = "-SHA256SUMS.txt"; + } + else + { + expectedInstallerSuffix = $"-{target}-Setup.exe"; + expectedChecksumsSuffix = "-SHA256SUMS.txt"; + } foreach (var asset in assets.EnumerateArray()) { @@ -896,7 +1197,7 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE { // The other platforms' checksum files end in -SHA256SUMS.txt too (-linux-x64-, -osx-arm64-), and so does // the ARM64 build's own one (CI's package), should one ever be attached. - if (!isLinux && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) + if (!isLinux && !isMac && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) || name.Contains("-osx-", StringComparison.OrdinalIgnoreCase) || name.Contains("-win-arm64-", StringComparison.OrdinalIgnoreCase))) continue; @@ -913,11 +1214,11 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute; /// - /// Extracts a Linux release archive (.tar.gz) into with security validation + /// Extracts a tar.gz archive into with security validation /// (rejecting path traversal, absolute paths, unsafe entry types, directory symlinks, and escaping/component symlinks). - /// Returns the path to the extracted payload folder containing install.sh. + /// Returns the canonical destination directory root with a trailing separator. /// - internal static string ExtractLinuxArchive(string archivePath, string destinationDirectory) + internal static string ExtractTarArchive(string archivePath, string destinationDirectory) { if (!File.Exists(archivePath)) throw new FileNotFoundException("Archive file not found", archivePath); @@ -981,7 +1282,7 @@ internal static string ExtractLinuxArchive(string archivePath, string destinatio entry.ExtractToFile(destinationPath, overwrite: true); - if (OperatingSystem.IsLinux()) + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) { var mode = (entry.Mode & RwxMask) | UnixFileMode.UserRead | UnixFileMode.UserWrite; File.SetUnixFileMode(destinationPath, mode); @@ -1068,6 +1369,17 @@ internal static string ExtractLinuxArchive(string archivePath, string destinatio } } + return fullDestRoot; + } + + /// + /// Extracts a Linux release archive (.tar.gz) into with security validation + /// (rejecting path traversal, absolute paths, unsafe entry types, directory symlinks, and escaping/component symlinks). + /// Returns the path to the extracted payload folder containing install.sh. + /// + internal static string ExtractLinuxArchive(string archivePath, string destinationDirectory) + { + var fullDestRoot = ExtractTarArchive(archivePath, destinationDirectory); var rootTrimmed = Path.TrimEndingDirectorySeparator(fullDestRoot); string payloadDir; if (File.Exists(Path.Combine(rootTrimmed, "install.sh"))) @@ -1096,7 +1408,7 @@ internal static string ExtractLinuxArchive(string archivePath, string destinatio throw new InvalidDataException("Archive is missing install.sh or Filee executable in the payload directory."); } - if (OperatingSystem.IsLinux()) + if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) { EnsureExecutable(installSh); EnsureExecutable(fileeExe); @@ -1111,6 +1423,143 @@ internal static string ExtractLinuxArchive(string archivePath, string destinatio return payloadDir; } + /// + /// Extracts a macOS release archive (.tar.gz) into with security validation + /// (rejecting path traversal, absolute paths, unsafe entry types, directory symlinks, and escaping/component symlinks). + /// Returns the path to the extracted Filee.app bundle. + /// + internal static string ExtractMacArchive(string archivePath, string destinationDirectory) + { + var fullDestRoot = ExtractTarArchive(archivePath, destinationDirectory); + var rootTrimmed = Path.TrimEndingDirectorySeparator(fullDestRoot); + + string appBundlePath; + var directApp = Path.Combine(rootTrimmed, "Filee.app"); + if (Directory.Exists(directApp)) + { + appBundlePath = directApp; + } + else + { + var candidates = Directory.GetDirectories(rootTrimmed, "Filee.app", SearchOption.AllDirectories) + .Where(d => File.Exists(Path.Combine(d, "Contents", "MacOS", "Filee"))) + .ToList(); + if (candidates.Count == 1) + { + appBundlePath = candidates[0]; + } + else + { + throw new InvalidDataException("Archive does not contain a single valid Filee.app bundle."); + } + } + + var mainExe = Path.Combine(appBundlePath, "Contents", "MacOS", "Filee"); + if (!File.Exists(mainExe)) + { + throw new InvalidDataException("Archive is missing Filee executable in Contents/MacOS."); + } + + if (OperatingSystem.IsMacOS() || OperatingSystem.IsLinux()) + { + EnsureExecutable(mainExe); + var cli = Path.Combine(appBundlePath, "Contents", "MacOS", "filee-cli"); + if (File.Exists(cli)) + EnsureExecutable(cli); + } + + return appBundlePath; + } + + /// + /// Extracts a Windows portable zip archive into with security validation + /// (rejecting path traversal, absolute paths, empty entry names, and escaping symlinks/reparse points). + /// Returns the directory path containing Filee.exe. + /// + internal static string ExtractZipArchive(string archivePath, string destinationDirectory) + { + if (!File.Exists(archivePath)) + throw new FileNotFoundException("Archive file not found", archivePath); + + var fullDestRoot = Path.GetFullPath(destinationDirectory); + if (!fullDestRoot.EndsWith(Path.DirectorySeparatorChar)) + fullDestRoot += Path.DirectorySeparatorChar; + + Directory.CreateDirectory(fullDestRoot); + + using (var zipStream = File.OpenRead(archivePath)) + using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) + { + foreach (var entry in archive.Entries) + { + if (string.IsNullOrWhiteSpace(entry.FullName)) + throw new InvalidDataException("Archive contains an entry with an empty name."); + + var entryName = entry.FullName.Replace('\\', '/'); + if (Path.IsPathRooted(entryName) || entryName.StartsWith('/') || entry.FullName.Contains(':')) + throw new InvalidDataException($"Archive entry '{entry.FullName}' has an invalid or rooted path."); + + var destinationPath = Path.GetFullPath(Path.Combine(fullDestRoot, entry.FullName)); + if (!destinationPath.StartsWith(fullDestRoot, StringComparison.Ordinal)) + throw new InvalidDataException($"Archive entry '{entry.FullName}' attempts path traversal outside destination."); + + ValidateNoSymlinkComponents(fullDestRoot, destinationPath); + + if (entryName.EndsWith('/')) + { + if (Path.Exists(destinationPath)) + { + var info = new DirectoryInfo(destinationPath); + if (info.LinkTarget is not null || info.Attributes.HasFlag(FileAttributes.ReparsePoint)) + throw new InvalidDataException($"Archive entry '{entry.FullName}' conflicts with an existing symbolic link."); + } + Directory.CreateDirectory(destinationPath); + } + else + { + if (Directory.Exists(destinationPath)) + throw new InvalidDataException($"Archive entry '{entry.FullName}' conflicts with an existing directory."); + + var parentDir = Path.GetDirectoryName(destinationPath); + if (!string.IsNullOrEmpty(parentDir)) + Directory.CreateDirectory(parentDir); + + if (Path.Exists(destinationPath)) + { + var existingInfo = new FileInfo(destinationPath); + if (existingInfo.LinkTarget is not null || existingInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)) + File.Delete(destinationPath); + } + + entry.ExtractToFile(destinationPath, overwrite: true); + } + } + } + + var rootTrimmed = Path.TrimEndingDirectorySeparator(fullDestRoot); + string payloadDir; + if (File.Exists(Path.Combine(rootTrimmed, "Filee.exe"))) + { + payloadDir = rootTrimmed; + } + else + { + var candidates = Directory.GetDirectories(rootTrimmed) + .Where(d => File.Exists(Path.Combine(d, "Filee.exe"))) + .ToList(); + if (candidates.Count == 1) + { + payloadDir = candidates[0]; + } + else + { + throw new InvalidDataException("Archive does not contain a single valid Filee payload with Filee.exe."); + } + } + + return payloadDir; + } + /// /// Verifies that no intermediate directory component between and is a symbolic link. /// diff --git a/src/Filee.App/Services/UpdateTexts.cs b/src/Filee.App/Services/UpdateTexts.cs index 2dc978e1c..13f78df4d 100644 --- a/src/Filee.App/Services/UpdateTexts.cs +++ b/src/Filee.App/Services/UpdateTexts.cs @@ -6,11 +6,11 @@ namespace Filee.App.Services; public static class UpdateTexts { - /// Button text: "Update" in an installed copy (it installs by itself), "Download" in a portable one. - public static string ButtonKey => UpdateService.IsInstalled ? "update.install" : "update.download"; + /// Button text: "Update" in an installed/self-updating copy (it installs by itself), "Download" in an unsupported one. + public static string ButtonKey => UpdateService.CanSelfUpdate ? "update.install" : "update.download"; /// What the update button does, for the notice and tooltips. - public static string HowKey => UpdateService.IsInstalled ? "update.notice_text" : "update.notice_text_portable"; + public static string HowKey => UpdateService.CanSelfUpdate ? "update.notice_text" : "update.notice_text_portable"; /// /// Short label for the sidebar button and the tray menu ("Update to 1.4.0", "Downloading… 42%"). The download has a diff --git a/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs b/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs index 1ba4d5827..a9091a449 100644 --- a/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs +++ b/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs @@ -39,7 +39,7 @@ private async void OnDownload(object? sender, RoutedEventArgs e) { if (_updates is null) return; - if (!UpdateService.IsInstalled) + if (!_updates.InstallsItself) { _updates.OpenDownloadPage(); Close(); diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.cs index 90f5552b4..077d11094 100644 --- a/tests/Filee.App.Tests/UpdateServiceTests.cs +++ b/tests/Filee.App.Tests/UpdateServiceTests.cs @@ -218,6 +218,54 @@ public void Linux_still_takes_its_own_files_next_to_both_windows_builds() Assert.Equal("Filee-9.9.9-linux-arm64-SHA256SUMS.txt", checksums?.Name); } + [Theory] + [InlineData("osx-arm64", "Filee-9.9.9-osx-arm64.tar.gz", "Filee-9.9.9-osx-arm64-SHA256SUMS.txt")] + [InlineData("osx-x64", "Filee-9.9.9-osx-x64.tar.gz", "Filee-9.9.9-osx-x64-SHA256SUMS.txt")] + public void Mac_takes_its_own_files_next_to_windows_and_linux_builds(string target, string expectedInstaller, string expectedSums) + { + using var release = ReleaseWithEveryPlatform(); + + var (installer, checksums) = UpdateService.FindFiles(release.RootElement, target); + + Assert.Equal(expectedInstaller, installer?.Name); + Assert.Equal(expectedSums, checksums?.Name); + } + + [Theory] + [InlineData("win-portable", "Filee-9.9.9-win-Portable.zip", "Filee-9.9.9-SHA256SUMS.txt")] + [InlineData("win-arm64-portable", "Filee-9.9.9-win-arm64-Portable.zip", "Filee-9.9.9-SHA256SUMS.txt")] + public void Windows_portable_takes_portable_zip_and_shared_windows_checksums(string target, string expectedInstaller, string expectedSums) + { + using var release = ReleaseWithEveryPlatform(); + + var (installer, checksums) = UpdateService.FindFiles(release.RootElement, target); + + Assert.Equal(expectedInstaller, installer?.Name); + Assert.Equal(expectedSums, checksums?.Name); + } + + [Fact] + public void The_macos_target_follows_the_process_architecture() + { + Assert.Equal("osx-arm64", UpdateService.GetMacOsRid(Architecture.Arm64)); + Assert.Equal("osx-x64", UpdateService.GetMacOsRid(Architecture.X64)); + Assert.Throws(() => UpdateService.GetMacOsRid(Architecture.X86)); + } + + [Fact] + public void GetMacAppBundlePath_locates_bundle_from_nested_or_direct_path() + { + var temp = TempFolder(); + var appPath = Path.Combine(temp, "Filee.app"); + var nestedBinary = Path.Combine(appPath, "Contents", "MacOS", "Filee"); + Directory.CreateDirectory(Path.GetDirectoryName(nestedBinary)!); + File.WriteAllText(nestedBinary, "binary"); + + Assert.Equal(appPath, UpdateService.GetMacAppBundlePath(nestedBinary)); + Assert.Equal(appPath, UpdateService.GetMacAppBundlePath(appPath)); + Assert.Null(UpdateService.GetMacAppBundlePath(temp)); + } + [Fact] public void Arm64_windows_does_not_fall_back_to_the_x64_setup_of_an_older_release() { @@ -832,6 +880,188 @@ public async Task UpdateAsync_on_linux_handles_helper_start_failure() Assert.False(shutdownRequested, "Application shutdown must not be requested when helper fails to start"); } + [AvaloniaFact] + public async Task UpdateAsync_on_windows_portable_downloads_extracts_and_spawns_powershell_helper() + { + var zipBytes = CreateZip(archive => + { + AddZipEntry(archive, "Filee.exe", "exe"); + AddZipEntry(archive, "filee.portable", ""); + }); + var hash = Sha256(zipBytes); + var network = new FakeArchiveRelease(zipBytes, hash, "Filee-9.9.9-win-Portable.zip", "Filee-9.9.9-SHA256SUMS.txt"); + + var mockInstallDir = TempFolder(); + + var updates = new UpdateService(NullLogger.Instance, network) + { + InstallsItself = true, + TargetPlatform = "win-portable", + WindowsInstallDirectoryOverride = mockInstallDir, + }; + updates.UseRelease( + new UpdateService.ReleaseFile("Filee-9.9.9-win-Portable.zip", Base + "Filee-9.9.9-win-Portable.zip", zipBytes.Length), + new UpdateService.ReleaseFile("Filee-9.9.9-SHA256SUMS.txt", Base + "Filee-9.9.9-SHA256SUMS.txt", 100)); + + var processes = new List(); + var shutdownRequested = false; + updates.RequestApplicationShutdown = () => shutdownRequested = true; + updates.StartProcess = psi => + { + processes.Add(psi); + return null; + }; + + await updates.UpdateAsync(); + + Assert.Equal(UpdateStep.Installing, updates.Step); + Assert.Single(processes); + + var helperPsi = processes[0]; + Assert.Equal("powershell.exe", helperPsi.FileName); + Assert.Contains("-ExecutionPolicy", helperPsi.ArgumentList); + Assert.Contains("Bypass", helperPsi.ArgumentList); + Assert.Contains("-File", helperPsi.ArgumentList); + Assert.Equal(Environment.ProcessId.ToString(), helperPsi.ArgumentList[6]); + Assert.Equal(mockInstallDir, helperPsi.ArgumentList[8]); + Assert.EndsWith(".log", helperPsi.ArgumentList[9]); + Assert.EndsWith(".update-failed", helperPsi.ArgumentList[11]); + Assert.Equal(Path.Combine(mockInstallDir, "Filee.exe"), helperPsi.ArgumentList[12]); + Assert.True(shutdownRequested, "Application shutdown must be requested before portable file swap"); + } + + [AvaloniaFact] + public async Task UpdateAsync_on_windows_portable_handles_helper_start_failure() + { + var zipBytes = CreateZip(archive => + { + AddZipEntry(archive, "Filee.exe", "exe"); + AddZipEntry(archive, "filee.portable", ""); + }); + var hash = Sha256(zipBytes); + var network = new FakeArchiveRelease(zipBytes, hash, "Filee-9.9.9-win-Portable.zip", "Filee-9.9.9-SHA256SUMS.txt"); + + var mockInstallDir = TempFolder(); + + var updates = new UpdateService(NullLogger.Instance, network) + { + InstallsItself = true, + TargetPlatform = "win-portable", + WindowsInstallDirectoryOverride = mockInstallDir, + }; + updates.UseRelease( + new UpdateService.ReleaseFile("Filee-9.9.9-win-Portable.zip", Base + "Filee-9.9.9-win-Portable.zip", zipBytes.Length), + new UpdateService.ReleaseFile("Filee-9.9.9-SHA256SUMS.txt", Base + "Filee-9.9.9-SHA256SUMS.txt", 100)); + + var failedCount = 0; + updates.UpdateFailed += (_, _) => failedCount++; + + var shutdownRequested = false; + updates.RequestApplicationShutdown = () => shutdownRequested = true; + + updates.StartProcess = psi => throw new Win32Exception("Cannot spawn PowerShell helper"); + + await updates.UpdateAsync(); + + Assert.Equal(UpdateStep.Failed, updates.Step); + Assert.Equal(1, failedCount); + Assert.NotNull(updates.LastError); + Assert.Contains("Cannot spawn PowerShell helper", updates.LastError.Message); + Assert.False(shutdownRequested, "Application shutdown must not be requested when helper fails to start"); + } + + [AvaloniaFact] + public async Task UpdateAsync_on_macos_downloads_extracts_and_delegates_to_detached_helper() + { + var tarBytes = CreateTarGz(writer => + { + AddFileEntry(writer, "Filee-9.9.9-osx-arm64/Filee.app/Contents/MacOS/Filee", "#!/bin/sh\nexit 0\n"); + AddFileEntry(writer, "Filee-9.9.9-osx-arm64/Filee.app/Contents/Info.plist", ""); + }); + var hash = Sha256(tarBytes); + var network = new FakeArchiveRelease(tarBytes, hash, "Filee-9.9.9-osx-arm64.tar.gz", "Filee-9.9.9-osx-arm64-SHA256SUMS.txt"); + + var mockBundle = Path.Combine(TempFolder(), "Filee.app"); + + var updates = new UpdateService(NullLogger.Instance, network) + { + InstallsItself = true, + TargetPlatform = "osx-arm64", + MacAppBundleOverride = mockBundle, + }; + updates.UseRelease( + new UpdateService.ReleaseFile("Filee-9.9.9-osx-arm64.tar.gz", Base + "Filee-9.9.9-osx-arm64.tar.gz", tarBytes.Length), + new UpdateService.ReleaseFile("Filee-9.9.9-osx-arm64-SHA256SUMS.txt", Base + "Filee-9.9.9-osx-arm64-SHA256SUMS.txt", 100)); + + var processes = new List(); + var shutdownRequested = false; + updates.RequestApplicationShutdown = () => shutdownRequested = true; + updates.StartProcess = psi => + { + processes.Add(psi); + return null; + }; + + await updates.UpdateAsync(); + + Assert.Equal(UpdateStep.Installing, updates.Step); + Assert.Single(processes); + + var helperPsi = processes[0]; + Assert.Equal("/bin/sh", helperPsi.FileName); + Assert.Equal("-c", helperPsi.ArgumentList[0]); + Assert.Contains("ditto", helperPsi.ArgumentList[1]); + Assert.Contains("xattr -dr com.apple.quarantine", helperPsi.ArgumentList[1]); + Assert.Equal(Environment.ProcessId.ToString(), helperPsi.ArgumentList[3]); + Assert.EndsWith("Filee.app", helperPsi.ArgumentList[4]); + Assert.Equal(mockBundle, helperPsi.ArgumentList[5]); + Assert.EndsWith(".log", helperPsi.ArgumentList[6]); + Assert.EndsWith(".update-failed", helperPsi.ArgumentList[8]); + Assert.Equal(Path.Combine(mockBundle, "Contents", "MacOS", "Filee"), helperPsi.ArgumentList[9]); + + Assert.True(shutdownRequested, "Application shutdown must be requested before macOS bundle swap"); + } + + [AvaloniaFact] + public async Task UpdateAsync_on_macos_handles_helper_start_failure() + { + var tarBytes = CreateTarGz(writer => + { + AddFileEntry(writer, "Filee-9.9.9-osx-arm64/Filee.app/Contents/MacOS/Filee", "#!/bin/sh\nexit 0\n"); + AddFileEntry(writer, "Filee-9.9.9-osx-arm64/Filee.app/Contents/Info.plist", ""); + }); + var hash = Sha256(tarBytes); + var network = new FakeArchiveRelease(tarBytes, hash, "Filee-9.9.9-osx-arm64.tar.gz", "Filee-9.9.9-osx-arm64-SHA256SUMS.txt"); + + var mockBundle = Path.Combine(TempFolder(), "Filee.app"); + + var updates = new UpdateService(NullLogger.Instance, network) + { + InstallsItself = true, + TargetPlatform = "osx-arm64", + MacAppBundleOverride = mockBundle, + }; + updates.UseRelease( + new UpdateService.ReleaseFile("Filee-9.9.9-osx-arm64.tar.gz", Base + "Filee-9.9.9-osx-arm64.tar.gz", tarBytes.Length), + new UpdateService.ReleaseFile("Filee-9.9.9-osx-arm64-SHA256SUMS.txt", Base + "Filee-9.9.9-osx-arm64-SHA256SUMS.txt", 100)); + + var failedCount = 0; + updates.UpdateFailed += (_, _) => failedCount++; + + var shutdownRequested = false; + updates.RequestApplicationShutdown = () => shutdownRequested = true; + + updates.StartProcess = psi => throw new Win32Exception("Cannot spawn macOS helper process"); + + await updates.UpdateAsync(); + + Assert.Equal(UpdateStep.Failed, updates.Step); + Assert.Equal(1, failedCount); + Assert.NotNull(updates.LastError); + Assert.Contains("Cannot spawn macOS helper process", updates.LastError.Message); + Assert.False(shutdownRequested, "Application shutdown must not be requested when helper fails to start"); + } + [Fact] public void ExtractLinuxArchive_rejects_symlink_component_traversal() { @@ -876,6 +1106,116 @@ public void ExtractLinuxArchive_rejects_link_order_attack() Assert.Throws(() => UpdateService.ExtractLinuxArchive(archiveFile, destFolder)); } + [Fact] + public void ExtractZipArchive_valid_payload_extracts_and_returns_folder() + { + var folder = TempFolder(); + var archiveFile = Path.Combine(folder, "package.zip"); + var destFolder = Path.Combine(folder, "extracted"); + + var zipBytes = CreateZip(archive => + { + AddZipEntry(archive, "Filee.exe", "fake exe"); + AddZipEntry(archive, "filee.portable", ""); + AddZipEntry(archive, "sub/helper.dll", "dll"); + }); + File.WriteAllBytes(archiveFile, zipBytes); + + var payloadDir = UpdateService.ExtractZipArchive(archiveFile, destFolder); + + Assert.Equal(destFolder, payloadDir); + Assert.True(File.Exists(Path.Combine(payloadDir, "Filee.exe"))); + Assert.True(File.Exists(Path.Combine(payloadDir, "sub", "helper.dll"))); + } + + [Fact] + public void ExtractZipArchive_nested_payload_extracts_and_returns_nested_folder() + { + var folder = TempFolder(); + var archiveFile = Path.Combine(folder, "package.zip"); + var destFolder = Path.Combine(folder, "extracted"); + + var zipBytes = CreateZip(archive => + { + AddZipEntry(archive, "Filee-1.0.0-win-Portable/Filee.exe", "fake exe"); + AddZipEntry(archive, "Filee-1.0.0-win-Portable/filee.portable", ""); + }); + File.WriteAllBytes(archiveFile, zipBytes); + + var payloadDir = UpdateService.ExtractZipArchive(archiveFile, destFolder); + + Assert.Equal(Path.Combine(destFolder, "Filee-1.0.0-win-Portable"), payloadDir); + Assert.True(File.Exists(Path.Combine(payloadDir, "Filee.exe"))); + } + + [Fact] + public void ExtractZipArchive_rejects_path_traversal() + { + var folder = TempFolder(); + var archiveFile = Path.Combine(folder, "traversal.zip"); + var destFolder = Path.Combine(folder, "extracted"); + + var zipBytes = CreateZip(archive => + { + AddZipEntry(archive, "../evil.exe", "fake"); + }); + File.WriteAllBytes(archiveFile, zipBytes); + + Assert.Throws(() => UpdateService.ExtractZipArchive(archiveFile, destFolder)); + } + + [Fact] + public void ExtractZipArchive_rejects_missing_filee_exe() + { + var folder = TempFolder(); + var archiveFile = Path.Combine(folder, "missing.zip"); + var destFolder = Path.Combine(folder, "extracted"); + + var zipBytes = CreateZip(archive => + { + AddZipEntry(archive, "other.exe", "fake"); + }); + File.WriteAllBytes(archiveFile, zipBytes); + + Assert.Throws(() => UpdateService.ExtractZipArchive(archiveFile, destFolder)); + } + + [Fact] + public void ExtractMacArchive_valid_payload_extracts_and_returns_app_bundle() + { + var folder = TempFolder(); + var archiveFile = Path.Combine(folder, "package.tar.gz"); + var destFolder = Path.Combine(folder, "extracted"); + + var tarBytes = CreateTarGz(writer => + { + AddFileEntry(writer, "Filee-1.0.0-osx-arm64/Filee.app/Contents/MacOS/Filee", "#!/bin/sh\nexit 0\n"); + AddFileEntry(writer, "Filee-1.0.0-osx-arm64/Filee.app/Contents/Info.plist", ""); + }); + File.WriteAllBytes(archiveFile, tarBytes); + + var appBundle = UpdateService.ExtractMacArchive(archiveFile, destFolder); + + Assert.Equal(Path.Combine(destFolder, "Filee-1.0.0-osx-arm64", "Filee.app"), appBundle); + Assert.True(File.Exists(Path.Combine(appBundle, "Contents", "MacOS", "Filee"))); + } + + [Fact] + public void ExtractMacArchive_rejects_missing_executable() + { + var folder = TempFolder(); + var archiveFile = Path.Combine(folder, "invalid.tar.gz"); + var destFolder = Path.Combine(folder, "extracted"); + + var tarBytes = CreateTarGz(writer => + { + AddFileEntry(writer, "Filee-1.0.0-osx-arm64/Filee.app/Contents/Info.plist", ""); + }); + File.WriteAllBytes(archiveFile, tarBytes); + + Assert.Throws(() => UpdateService.ExtractMacArchive(archiveFile, destFolder)); + } + [Fact] public void CreateSecureWorkspace_creates_private_unshared_directory() {