diff --git a/i18n/en/About.resx b/i18n/en/About.resx
index ce8aea99..1dc68f3f 100644
--- a/i18n/en/About.resx
+++ b/i18n/en/About.resx
@@ -23,6 +23,11 @@
Checking…Up to dateDownload
+ Download failed
+ Downloading {0:P0}Check failed
+ Download not verified
+ Titano {0} downloaded
+ Show setupUpdates
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 7ca6cbe4..a815b5e5 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -6,11 +6,12 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Ask the public releases page for a newer version · a few secondsZip the logs and an environment report into a folder you choose; settings and passwords are not included
- Open the release page in the browser
+ Download the setup, check it against the release's SHA-256 list and show it in Explorer · tens of MBOpen the licence in the browserOpen the folder with database, settings and logsOpen the public releases page in the browserEvery language but English is machine-translated; propose a better wording on the public issue tracker
+ Show the verified setup in Explorer; close Titano and run it to upgrade. Archive and settings are keptTitano uses no third-party code: everything beyond .NET and Windows is written in-houseDismissOpen the folder with the log files
diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx
index 2370ca1e..2f871e07 100644
--- a/i18n/it/About.it.resx
+++ b/i18n/it/About.it.resx
@@ -23,6 +23,11 @@
Verifica in corso…AggiornatoScarica
+ Download non riuscito
+ Download in corso {0:P0}Verifica non riuscita
+ Download non verificato
+ Titano {0} scaricato
+ Mostra installerAggiornamenti
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index c81ad08f..1eba743f 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -6,11 +6,12 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondiComprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse
- Apre la pagina della versione nel browser
+ Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · decine di MBApre la licenza nel browserApri la cartella con database, impostazioni e logApri la pagina pubblica delle versioni nel browserTutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico
+ Mostra in Esplora file l'installer verificato; chiudi Titano ed eseguilo per aggiornare. Archivio e impostazioni restano invariatiTitano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamenteChiudiApri la cartella dei file di log
diff --git a/src/Titano.App/About/UpdateCheck.cs b/src/Titano.App/About/UpdateCheck.cs
index 8434cb88..0ad76278 100644
--- a/src/Titano.App/About/UpdateCheck.cs
+++ b/src/Titano.App/About/UpdateCheck.cs
@@ -4,8 +4,14 @@ using System.Text.Json;
namespace Titano.App.About;
-/// The newest public release (BRIEF §18).
-public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl);
+/// The newest public release (BRIEF §18) with its downloadable files.
+public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl)
+{
+ public IReadOnlyList Assets { get; init; } = [];
+}
+
+/// One file attached to a release.
+public sealed record ReleaseAsset(string Name, string DownloadUrl, long Size);
///
/// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the
@@ -26,7 +32,8 @@ public static class UpdateCheck
return new Version(version.Major, version.Minor, Math.Max(0, version.Build));
}
- /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags.
+ /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags.
+ /// Assets without an https download link are left out.
public static ReleaseInfo? Parse(string json)
{
using var document = JsonDocument.Parse(json);
@@ -37,7 +44,7 @@ public static class UpdateCheck
var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null;
var version = ParseVersion(tag);
if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null;
- return new ReleaseInfo(version, tag, url);
+ return new ReleaseInfo(version, tag, url) { Assets = ParseAssets(root) };
}
/// True when is newer than (build/revision ignored).
@@ -68,6 +75,22 @@ public static class UpdateCheck
}
}
+ private static List ParseAssets(JsonElement root)
+ {
+ var assets = new List();
+ if (!root.TryGetProperty("assets", out var list) || list.ValueKind != JsonValueKind.Array) return assets;
+ foreach (var a in list.EnumerateArray())
+ {
+ if (a.ValueKind != JsonValueKind.Object) continue;
+ var name = a.TryGetProperty("name", out var n) && n.ValueKind == JsonValueKind.String ? n.GetString() : null;
+ var link = a.TryGetProperty("browser_download_url", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null;
+ var size = a.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number && z.TryGetInt64(out var bytes) ? bytes : -1;
+ if (string.IsNullOrEmpty(name) || link is null || !link.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
+ assets.Add(new ReleaseAsset(name, link, size));
+ }
+ return assets;
+ }
+
private static bool Flag(JsonElement root, string name) =>
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
diff --git a/src/Titano.App/About/UpdateDownload.cs b/src/Titano.App/About/UpdateDownload.cs
new file mode 100644
index 00000000..7fade974
--- /dev/null
+++ b/src/Titano.App/About/UpdateDownload.cs
@@ -0,0 +1,165 @@
+using System.Buffers;
+using System.IO;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Security.Cryptography;
+
+namespace Titano.App.About;
+
+/// A downloaded update was refused: the release lacks a setup or checksum line, or the bytes do not match.
+public sealed class UpdateVerificationException(string message) : Exception(message);
+
+///
+/// "Download" of the update notice (BRIEF §18, P1): fetches the desktop setup of the latest release into a temporary
+/// folder and keeps it only when its SHA-256 equals the line for it in the release's SHA256SUMS. BRIEF §8.6 does
+/// not list starting an installer among the OS actions Titano may perform, so callers show the verified file in
+/// Explorer and the user runs it.
+///
+public static class UpdateDownload
+{
+ public const string ChecksumsName = "SHA256SUMS";
+ private const int MaxChecksumsBytes = 64 * 1024;
+ private static readonly SearchValues Hex = SearchValues.Create("0123456789abcdefABCDEF");
+
+ /// The desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's.
+ public static ReleaseAsset? Installer(ReleaseInfo release) =>
+ release.Assets.FirstOrDefault(a => a.Name.StartsWith("Titano-Setup-", StringComparison.OrdinalIgnoreCase)
+ && a.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
+ && a.Name == Path.GetFileName(a.Name));
+
+ public static ReleaseAsset? Checksums(ReleaseInfo release) => release.Assets.FirstOrDefault(a => a.Name == ChecksumsName);
+
+ /// The release carries both a setup and SHA256SUMS; otherwise only its page can be opened.
+ public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null;
+
+ /// %TEMP%\Titano\updates\<tag> under .
+ public static string Folder(string tempRoot, ReleaseInfo release) =>
+ Path.Combine(tempRoot, "Titano", "updates", string.Concat(release.Tag.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' ? c : '_')));
+
+ ///
+ /// File name → lower-case hex SHA-256 from sha256sum output (hash name or hash *name); lines
+ /// that are not a 64-digit hash followed by a name are ignored.
+ ///
+ public static Dictionary ParseChecksums(string text)
+ {
+ var sums = new Dictionary(StringComparer.Ordinal);
+ foreach (var raw in text.Split('\n'))
+ {
+ var line = raw.TrimEnd('\r');
+ if (line.Length < 66 || line[64] != ' ' || line.AsSpan(0, 64).ContainsAnyExcept(Hex)) continue;
+ var name = line[65..];
+ if (name.StartsWith(' ') || name.StartsWith('*')) name = name[1..];
+ if (name.Length > 0) sums[name] = line[..64].ToLowerInvariant();
+ }
+ return sums;
+ }
+
+ ///
+ /// Downloads the setup of into , verifies it against
+ /// SHA256SUMS and returns its path. A verified copy already there is reused; a partial or mismatching
+ /// download is deleted.
+ ///
+ /// The release cannot be verified or the bytes do not match.
+ /// A request failed.
+ public static async Task DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress? progress,
+ CancellationToken ct)
+ {
+ var installer = Installer(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no Titano setup.");
+ var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}.");
+ var expected = ParseChecksums(await ReadChecksumsAsync(http, checksums, userAgentVersion, ct).ConfigureAwait(false)).GetValueOrDefault(installer.Name)
+ ?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {installer.Name}.");
+
+ Directory.CreateDirectory(folder);
+ var target = Path.Combine(folder, installer.Name);
+ if (File.Exists(target) && await HashFileAsync(target, ct).ConfigureAwait(false) == expected)
+ {
+ progress?.Report(1);
+ return target;
+ }
+
+ var part = target + ".part";
+ try
+ {
+ var actual = await DownloadToAsync(http, installer, part, userAgentVersion, progress, ct).ConfigureAwait(false);
+ if (actual != expected) throw new UpdateVerificationException($"{installer.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}.");
+ File.Move(part, target, overwrite: true);
+ return target;
+ }
+ finally
+ {
+ DeleteQuietly(part);
+ }
+ }
+
+ private static async Task ReadChecksumsAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct)
+ {
+ using var response = await SendAsync(http, asset, userAgentVersion, ct).ConfigureAwait(false);
+ if (response.Content.Headers.ContentLength > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large.");
+ var bytes = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
+ if (bytes.Length > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large.");
+ return System.Text.Encoding.UTF8.GetString(bytes);
+ }
+
+ /// Streams the asset into , hashing as it goes; refuses more bytes than the release announced.
+ private static async Task DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress? progress,
+ CancellationToken ct)
+ {
+ using var response = await SendAsync(http, asset, userAgentVersion, ct).ConfigureAwait(false);
+ var length = asset.Size > 0 ? asset.Size : response.Content.Headers.ContentLength ?? -1;
+ await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
+ await using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous);
+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ var buffer = new byte[1 << 16];
+ long total = 0;
+ int read;
+ while ((read = await input.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0)
+ {
+ total += read;
+ if (asset.Size > 0 && total > asset.Size) throw new UpdateVerificationException($"{asset.Name} is larger than the release announced.");
+ hash.AppendData(buffer, 0, read);
+ await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
+ if (length > 0) progress?.Report(Math.Min(1.0, (double)total / length));
+ }
+ await output.FlushAsync(ct).ConfigureAwait(false);
+ return Convert.ToHexStringLower(hash.GetHashAndReset());
+ }
+
+ private static async Task SendAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, asset.DownloadUrl);
+ request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion));
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
+ var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
+ try
+ {
+ response.EnsureSuccessStatusCode();
+ return response;
+ }
+ catch
+ {
+ response.Dispose();
+ throw;
+ }
+ }
+
+ private static void DeleteQuietly(string path)
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (IOException)
+ {
+ // A scanner may hold the partial file; %TEMP% cleanup removes it later.
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
+ }
+
+ private static async Task HashFileAsync(string path, CancellationToken ct)
+ {
+ await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
+ return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
+ }
+}
diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs
index 5ed5098f..d6dc5a8d 100644
--- a/src/Titano.App/Infrastructure/AppServices.cs
+++ b/src/Titano.App/Infrastructure/AppServices.cs
@@ -38,6 +38,9 @@ public sealed class AppServices : IAsyncDisposable
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
+
+ /// Setups are large: the download is bounded by the caller's cancellation, not a short timeout.
+ private static readonly Lazy DownloadHttp = new(() => new HttpClient { Timeout = TimeSpan.FromMinutes(30) });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary _scans = [];
private Task _polling = Task.CompletedTask;
@@ -55,6 +58,8 @@ public sealed class AppServices : IAsyncDisposable
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
+ DownloadUpdateAsync = (release, progress, ct) =>
+ UpdateDownload.DownloadAsync(DownloadHttp.Value, release, UpdateDownload.Folder(Path.GetTempPath(), release), VersionText, progress, ct);
}
public AppEnvironment Environment { get; }
@@ -89,6 +94,9 @@ public sealed class AppServices : IAsyncDisposable
/// Latest public release (GitHub Releases API of the releases repository, BRIEF §18).
public Func> CheckForUpdateAsync { get; set; }
+ /// Downloads and verifies the setup of a release (BRIEF §18 P1) and returns its path.
+ public Func?, CancellationToken, Task> DownloadUpdateAsync { get; set; }
+
/// The index; null until succeeded.
public TitanoDatabase? Database { get; private set; }
diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml
index 30236370..7b445788 100644
--- a/src/Titano.App/Sections/AboutView.xaml
+++ b/src/Titano.App/Sections/AboutView.xaml
@@ -57,6 +57,9 @@
+
diff --git a/src/Titano.App/Sections/AboutViewModel.cs b/src/Titano.App/Sections/AboutViewModel.cs
index b3e85495..7d63387a 100644
--- a/src/Titano.App/Sections/AboutViewModel.cs
+++ b/src/Titano.App/Sections/AboutViewModel.cs
@@ -15,22 +15,27 @@ namespace Titano.App.Sections;
///
/// About (BRIEF §12.9): version and build, licence link, third-party notice (none), translation notice,
-/// diagnostics bundle and the update check against the public releases repository (BRIEF §18).
+/// diagnostics bundle and the update check against the public releases repository (BRIEF §18). Download fetches the
+/// setup and verifies it against the release's SHA256SUMS, then shows it in Explorer: BRIEF §8.6 does not allow Titano
+/// to start an installer, so the user runs it.
///
public sealed class AboutViewModel : SectionViewModel
{
private ReleaseInfo? _release;
private UpdateState _state = UpdateState.Unknown;
+ private double _downloaded;
+ private string? _setupPath;
public AboutViewModel(ShellViewModel shell)
: base(SectionKey.About, "Icon.About")
{
Shell = shell;
- CheckCommand = new AsyncRelayCommand(() => CheckAsync(notify: false), () => _state != UpdateState.Checking);
- DownloadCommand = new RelayCommand(() =>
+ CheckCommand = new AsyncRelayCommand(() => CheckAsync(notify: false), () => _state is not (UpdateState.Checking or UpdateState.Downloading));
+ DownloadCommand = new AsyncRelayCommand(DownloadAsync, () => _release is not null && _state != UpdateState.Downloading);
+ ShowSetupCommand = new RelayCommand(() =>
{
- if (_release is { } release) ShellActions.OpenUrl(release.PageUrl);
- }, () => _release is not null);
+ if (_setupPath is { } path) ShellActions.Reveal(path);
+ }, () => _setupPath is not null);
OpenReleasesCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Releases));
OpenLicenceCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Licence));
ReviewTranslationCommand = new RelayCommand(() => ShellActions.OpenUrl(ProductLinks.Issues));
@@ -45,6 +50,10 @@ public sealed class AboutViewModel : SectionViewModel
UpToDate,
Available,
Failed,
+ Downloading,
+ Downloaded,
+ DownloadFailed,
+ NotVerified,
}
public ShellViewModel Shell { get; }
@@ -66,6 +75,7 @@ public sealed class AboutViewModel : SectionViewModel
public ICommand CheckCommand { get; }
public ICommand DownloadCommand { get; }
+ public ICommand ShowSetupCommand { get; }
public ICommand OpenReleasesCommand { get; }
public ICommand OpenLicenceCommand { get; }
public ICommand ReviewTranslationCommand { get; }
@@ -79,20 +89,28 @@ public sealed class AboutViewModel : SectionViewModel
UpdateState.UpToDate => Loc.L("About.Update.Current"),
UpdateState.Available when _release is { } r => Loc.L("About.Update.Available", UpdateCheck.Display(r.Version)),
UpdateState.Failed => Loc.L("About.Update.Failed"),
+ UpdateState.Downloading => Loc.L("About.Update.Downloading", _downloaded),
+ UpdateState.Downloaded when _release is { } r => Loc.L("About.Update.Ready", UpdateCheck.Display(r.Version)),
+ UpdateState.DownloadFailed => Loc.L("About.Update.DownloadFailed"),
+ UpdateState.NotVerified => Loc.L("About.Update.NotVerified"),
_ => null,
};
public StatusKind UpdateKind => _state switch
{
- UpdateState.Checking => StatusKind.Running,
- UpdateState.UpToDate => StatusKind.Done,
+ UpdateState.Checking or UpdateState.Downloading => StatusKind.Running,
+ UpdateState.UpToDate or UpdateState.Downloaded => StatusKind.Done,
UpdateState.Available => StatusKind.Warning,
_ => StatusKind.Error,
};
public bool HasUpdateText => UpdateText is not null;
- public bool IsUpdateAvailable => _state == UpdateState.Available;
+ /// Download is offered: a newer release exists and no verified setup is waiting (a failed download can be retried).
+ public bool IsUpdateAvailable => _state is UpdateState.Available or UpdateState.DownloadFailed or UpdateState.NotVerified;
+
+ /// The verified setup is in the temporary folder.
+ public bool IsSetupReady => _state == UpdateState.Downloaded;
/// Starts the update check on start when allowed (opt-out, BRIEF §18).
public void Attach()
@@ -105,6 +123,7 @@ public sealed class AboutViewModel : SectionViewModel
{
_release = release is not null && UpdateCheck.IsNewer(release, UpdateCheck.RunningVersion(Version)) ? release : null;
_state = failed ? UpdateState.Failed : _release is null ? UpdateState.UpToDate : UpdateState.Available;
+ _setupPath = null;
RaiseUpdate();
}
@@ -120,7 +139,7 @@ public sealed class AboutViewModel : SectionViewModel
if (notify && _release is { } newer)
{
Shell.Notify(Loc.L("About.Update.Available", UpdateCheck.Display(newer.Version)), actionText: Loc.L("About.Update.Download"),
- actionToolTip: Loc.L("Tooltips.About.Download"), action: () => ShellActions.OpenUrl(newer.PageUrl));
+ actionToolTip: Loc.L("Tooltips.About.Download"), action: () => DownloadCommand.Execute(null));
}
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException)
@@ -130,6 +149,48 @@ public sealed class AboutViewModel : SectionViewModel
}
}
+ ///
+ /// Downloads and verifies the setup, then shows it in Explorer. A release without a setup or SHA256SUMS only opens
+ /// the release page; a capture run never touches the network.
+ ///
+ private async Task DownloadAsync()
+ {
+ if (_release is not { } release || Shell.Services.Environment.IsCapture) return;
+ if (!UpdateDownload.CanDownload(release))
+ {
+ ShellActions.OpenUrl(release.PageUrl);
+ return;
+ }
+ _state = UpdateState.Downloading;
+ _downloaded = 0;
+ RaiseUpdate();
+ var progress = new Progress(fraction =>
+ {
+ if (_state != UpdateState.Downloading || fraction - _downloaded < 0.01) return;
+ _downloaded = fraction;
+ OnPropertyChanged(nameof(UpdateText));
+ });
+ try
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(30));
+ _setupPath = await Shell.Services.DownloadUpdateAsync(release, progress, timeout.Token);
+ _state = UpdateState.Downloaded;
+ Log.Info("update", $"Setup of {release.Tag} downloaded and verified: {_setupPath}");
+ ShellActions.Reveal(_setupPath);
+ }
+ catch (UpdateVerificationException ex)
+ {
+ Log.Warning("update", "Update download refused: " + ex.Message);
+ _state = UpdateState.NotVerified;
+ }
+ catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("update", "Update download failed: " + ex.Message);
+ _state = UpdateState.DownloadFailed;
+ }
+ RaiseUpdate();
+ }
+
private async Task DiagnosticsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
@@ -144,6 +205,7 @@ public sealed class AboutViewModel : SectionViewModel
OnPropertyChanged(nameof(UpdateKind));
OnPropertyChanged(nameof(HasUpdateText));
OnPropertyChanged(nameof(IsUpdateAvailable));
+ OnPropertyChanged(nameof(IsSetupReady));
CommandManager.InvalidateRequerySuggested();
}
}
diff --git a/src/Titano.App/Sections/SettingsView.xaml b/src/Titano.App/Sections/SettingsView.xaml
index 62f231bd..018d322c 100644
--- a/src/Titano.App/Sections/SettingsView.xaml
+++ b/src/Titano.App/Sections/SettingsView.xaml
@@ -294,6 +294,9 @@
+
diff --git a/tests/Titano.App.Tests/About/UpdateDownloadTests.cs b/tests/Titano.App.Tests/About/UpdateDownloadTests.cs
new file mode 100644
index 00000000..3929ab4a
--- /dev/null
+++ b/tests/Titano.App.Tests/About/UpdateDownloadTests.cs
@@ -0,0 +1,145 @@
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Security.Cryptography;
+using System.Text;
+using Titano.App.About;
+using Titano.Testing;
+
+namespace Titano.App.Tests.About;
+
+public sealed class UpdateDownloadTests(TestContext context)
+{
+ private const string SetupUrl = "https://github.com/o/r/releases/download/v1.0.0/Titano-Setup-1.0.0.exe";
+ private const string SumsUrl = "https://github.com/o/r/releases/download/v1.0.0/SHA256SUMS";
+
+ private static readonly byte[] Setup = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("MZ setup payload ", 20_000)));
+
+ [Test]
+ public void ChecksumLinesOfBothSha256sumModesAreRead()
+ {
+ var hash = new string('A', 64);
+ var sums = UpdateDownload.ParseChecksums(
+ $"{hash} Titano-Setup-1.0.0.exe\r\n{new string('b', 64)} *Titano-Uploader-Setup-1.0.0.exe\nnot a checksum line\n{new string('c', 63)} short.exe\n\n");
+ Assert.Equal(2, sums.Count);
+ Assert.Equal(new string('a', 64), sums["Titano-Setup-1.0.0.exe"]);
+ Assert.Equal(new string('b', 64), sums["Titano-Uploader-Setup-1.0.0.exe"]);
+ }
+
+ [Test]
+ public void TheDesktopSetupAndTheChecksumsAreFoundAmongTheAssets()
+ {
+ var release = UpdateCheck.Parse($$"""
+ { "tag_name": "v1.0.0", "html_url": "https://github.com/o/r/releases/tag/v1.0.0", "assets": [
+ { "name": "Titano-Uploader-Setup-1.0.0.exe", "browser_download_url": "https://github.com/o/r/releases/download/v1.0.0/Titano-Uploader-Setup-1.0.0.exe", "size": 10 },
+ { "name": "Titano-Setup-1.0.0.exe", "browser_download_url": "{{SetupUrl}}", "size": {{Setup.Length}} },
+ { "name": "SHA256SUMS", "browser_download_url": "{{SumsUrl}}", "size": 300 },
+ { "name": "evil.exe", "browser_download_url": "http://example.com/evil.exe", "size": 1 }
+ ] }
+ """)!;
+ Assert.Equal(3, release.Assets.Count);
+ Assert.Equal("Titano-Setup-1.0.0.exe", UpdateDownload.Installer(release)!.Name);
+ Assert.Equal(SumsUrl, UpdateDownload.Checksums(release)!.DownloadUrl);
+ Assert.True(UpdateDownload.CanDownload(release));
+ Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != "SHA256SUMS")] }));
+ Assert.True(UpdateDownload.Folder(Path.GetTempPath(), release).EndsWith(Path.Combine("Titano", "updates", "v1.0.0"), StringComparison.Ordinal));
+ }
+
+ [Test]
+ public async Task AVerifiedSetupIsKeptAndReusedWithoutDownloadingAgain()
+ {
+ var folder = context.CreateTempDirectory();
+ var server = new FakeReleases(Sums(Setup), Setup);
+ using var http = new HttpClient(server);
+ var reported = new List();
+
+ var path = await UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", new SyncProgress(reported.Add), CancellationToken.None);
+ Assert.Equal(Path.Combine(folder, "Titano-Setup-1.0.0.exe"), path);
+ Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path));
+ Assert.Equal(1.0, reported[^1]);
+ Assert.Equal(1, server.SetupRequests);
+ Assert.SequenceEqual(new[] { "Titano-Setup-1.0.0.exe" }, Directory.GetFiles(folder).Select(f => Path.GetFileName(f)));
+
+ await UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None);
+ Assert.Equal(1, server.SetupRequests);
+ }
+
+ [Test]
+ public async Task ASetupThatDoesNotMatchItsChecksumIsDeleted()
+ {
+ var folder = context.CreateTempDirectory();
+ var tampered = Setup.ToArray();
+ tampered[^1] ^= 1;
+ using var http = new HttpClient(new FakeReleases(Sums(Setup), tampered));
+ var error = await Assert.ThrowsAsync(() =>
+ UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
+ Assert.Contains("does not match", error.Message);
+ Assert.Empty(Directory.GetFiles(folder));
+ }
+
+ [Test]
+ public async Task ASetupWithoutAChecksumLineIsNeverDownloaded()
+ {
+ var folder = context.CreateTempDirectory();
+ var server = new FakeReleases($"{new string('0', 64)} Titano-Uploader-Setup-1.0.0.exe\n", Setup);
+ using var http = new HttpClient(server);
+ await Assert.ThrowsAsync(() => UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
+ Assert.Equal(0, server.SetupRequests);
+ Assert.Empty(Directory.GetFiles(folder));
+ }
+
+ [Test]
+ public async Task MoreBytesThanTheReleaseAnnouncedAreRefused()
+ {
+ var folder = context.CreateTempDirectory();
+ var longer = Setup.Concat(new byte[100]).ToArray();
+ using var http = new HttpClient(new FakeReleases(Sums(longer), longer));
+ await Assert.ThrowsAsync(() => UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
+ Assert.Empty(Directory.GetFiles(folder));
+ }
+
+ [Test]
+ public async Task AFailedRequestLeavesNoPartialFile()
+ {
+ var folder = context.CreateTempDirectory();
+ using var http = new HttpClient(new FakeReleases(Sums(Setup), null));
+ await Assert.ThrowsAsync(() => UpdateDownload.DownloadAsync(http, Release(), folder, "0.1.0", null, CancellationToken.None));
+ Assert.Empty(Directory.GetFiles(folder));
+ }
+
+ private static ReleaseInfo Release() => new(new Version(1, 0, 0), "v1.0.0", "https://github.com/o/r/releases/tag/v1.0.0")
+ {
+ Assets =
+ [
+ new ReleaseAsset("Titano-Setup-1.0.0.exe", SetupUrl, Setup.Length),
+ new ReleaseAsset("SHA256SUMS", SumsUrl, 200),
+ ],
+ };
+
+ private static string Sums(byte[] setup) =>
+ $"{new string('1', 64)} Titano-Uploader-Setup-1.0.0.exe\n{Convert.ToHexStringLower(SHA256.HashData(setup))} Titano-Setup-1.0.0.exe\n";
+
+ /// Serves SHA256SUMS and the setup (null: the setup answers 500).
+ private sealed class FakeReleases(string sums, byte[]? setup) : HttpMessageHandler
+ {
+ public int SetupRequests { get; private set; }
+
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ Assert.True(request.Headers.UserAgent.ToString().StartsWith("Titano/", StringComparison.Ordinal), "GitHub requires a User-Agent");
+ var url = request.RequestUri!.AbsoluteUri;
+ if (url == SumsUrl) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(sums) });
+ Assert.Equal(SetupUrl, url);
+ SetupRequests++;
+ return Task.FromResult(setup is null
+ ? new HttpResponseMessage(HttpStatusCode.InternalServerError)
+ : new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(setup) });
+ }
+ }
+
+ /// Reports synchronously ( would post to the thread pool).
+ private sealed class SyncProgress(Action report) : IProgress
+ {
+ public void Report(double value) => report(value);
+ }
+}