feat(app): download the update and verify it against SHA256SUMS

Download now fetches the desktop setup of the latest release into
%TEMP%\Titano\updates\<tag>, keeps it only when its SHA-256 matches the
release's SHA256SUMS line, and shows it in Explorer. BRIEF 8.6 does not list
starting an installer among the allowed shell actions, so the user runs it.
A release without a setup or SHA256SUMS still opens its page; capture runs
never download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 22:20:45 +00:00
1 parent d0beb7d3bf
commit 85d091d1fe
11 files changed
+436 -15

No files matched your search

+5
View File
@@ -23,6 +23,11 @@
<data name="About.Update.Checking" xml:space="preserve"><value>Checking…</value></data>
<data name="About.Update.Current" xml:space="preserve"><value>Up to date</value></data>
<data name="About.Update.Download" xml:space="preserve"><value>Download</value></data>
<data name="About.Update.DownloadFailed" xml:space="preserve"><value>Download failed</value></data>
<data name="About.Update.Downloading" xml:space="preserve"><value>Downloading {0:P0}</value></data>
<data name="About.Update.Failed" xml:space="preserve"><value>Check failed</value></data>
<data name="About.Update.NotVerified" xml:space="preserve"><value>Download not verified</value></data>
<data name="About.Update.Ready" xml:space="preserve"><value>Titano {0} downloaded</value></data>
<data name="About.Update.ShowSetup" xml:space="preserve"><value>Show setup</value></data>
<data name="About.Updates" xml:space="preserve"><value>Updates</value></data>
</root>
+2 -1
View File
@@ -6,11 +6,12 @@
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Tooltips.About.Check" xml:space="preserve"><value>Ask the public releases page for a newer version · a few seconds</value></data>
<data name="Tooltips.About.Diagnostics" xml:space="preserve"><value>Zip the logs and an environment report into a folder you choose; settings and passwords are not included</value></data>
<data name="Tooltips.About.Download" xml:space="preserve"><value>Open the release page in the browser</value></data>
<data name="Tooltips.About.Download" xml:space="preserve"><value>Download the setup, check it against the release's SHA-256 list and show it in Explorer · tens of MB</value></data>
<data name="Tooltips.About.Licence" xml:space="preserve"><value>Open the licence in the browser</value></data>
<data name="Tooltips.About.OpenData" xml:space="preserve"><value>Open the folder with database, settings and logs</value></data>
<data name="Tooltips.About.Releases" xml:space="preserve"><value>Open the public releases page in the browser</value></data>
<data name="Tooltips.About.Review" xml:space="preserve"><value>Every language but English is machine-translated; propose a better wording on the public issue tracker</value></data>
<data name="Tooltips.About.ShowSetup" xml:space="preserve"><value>Show the verified setup in Explorer; close Titano and run it to upgrade. Archive and settings are kept</value></data>
<data name="Tooltips.About.ThirdParty" xml:space="preserve"><value>Titano uses no third-party code: everything beyond .NET and Windows is written in-house</value></data>
<data name="Tooltips.Common.Dismiss" xml:space="preserve"><value>Dismiss</value></data>
<data name="Tooltips.Common.OpenLogs" xml:space="preserve"><value>Open the folder with the log files</value></data>
+5
View File
@@ -23,6 +23,11 @@
<data name="About.Update.Checking" xml:space="preserve"><value>Verifica in corso…</value></data>
<data name="About.Update.Current" xml:space="preserve"><value>Aggiornato</value></data>
<data name="About.Update.Download" xml:space="preserve"><value>Scarica</value></data>
<data name="About.Update.DownloadFailed" xml:space="preserve"><value>Download non riuscito</value></data>
<data name="About.Update.Downloading" xml:space="preserve"><value>Download in corso {0:P0}</value></data>
<data name="About.Update.Failed" xml:space="preserve"><value>Verifica non riuscita</value></data>
<data name="About.Update.NotVerified" xml:space="preserve"><value>Download non verificato</value></data>
<data name="About.Update.Ready" xml:space="preserve"><value>Titano {0} scaricato</value></data>
<data name="About.Update.ShowSetup" xml:space="preserve"><value>Mostra installer</value></data>
<data name="About.Updates" xml:space="preserve"><value>Aggiornamenti</value></data>
</root>
+2 -1
View File
@@ -6,11 +6,12 @@
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Tooltips.About.Check" xml:space="preserve"><value>Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondi</value></data>
<data name="Tooltips.About.Diagnostics" xml:space="preserve"><value>Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse</value></data>
<data name="Tooltips.About.Download" xml:space="preserve"><value>Apre la pagina della versione nel browser</value></data>
<data name="Tooltips.About.Download" xml:space="preserve"><value>Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · decine di MB</value></data>
<data name="Tooltips.About.Licence" xml:space="preserve"><value>Apre la licenza nel browser</value></data>
<data name="Tooltips.About.OpenData" xml:space="preserve"><value>Apri la cartella con database, impostazioni e log</value></data>
<data name="Tooltips.About.Releases" xml:space="preserve"><value>Apri la pagina pubblica delle versioni nel browser</value></data>
<data name="Tooltips.About.Review" xml:space="preserve"><value>Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico</value></data>
<data name="Tooltips.About.ShowSetup" xml:space="preserve"><value>Mostra in Esplora file l'installer verificato; chiudi Titano ed eseguilo per aggiornare. Archivio e impostazioni restano invariati</value></data>
<data name="Tooltips.About.ThirdParty" xml:space="preserve"><value>Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente</value></data>
<data name="Tooltips.Common.Dismiss" xml:space="preserve"><value>Chiudi</value></data>
<data name="Tooltips.Common.OpenLogs" xml:space="preserve"><value>Apri la cartella dei file di log</value></data>
+27 -4
View File
@@ -4,8 +4,14 @@ using System.Text.Json;
namespace Titano.App.About;
/// <summary>The newest public release (BRIEF §18).</summary>
public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl);
/// <summary>The newest public release (BRIEF §18) with its downloadable files.</summary>
public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl)
{
public IReadOnlyList<ReleaseAsset> Assets { get; init; } = [];
}
/// <summary>One file attached to a release.</summary>
public sealed record ReleaseAsset(string Name, string DownloadUrl, long Size);
/// <summary>
/// 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));
}
/// <summary>The release described by a <c>releases/latest</c> response; null for drafts, pre-releases or unparsable tags.</summary>
/// <summary>The release described by a <c>releases/latest</c> response; null for drafts, pre-releases or unparsable tags.
/// Assets without an https download link are left out.</summary>
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) };
}
/// <summary>True when <paramref name="release"/> is newer than <paramref name="running"/> (build/revision ignored).</summary>
@@ -68,6 +75,22 @@ public static class UpdateCheck
}
}
private static List<ReleaseAsset> ParseAssets(JsonElement root)
{
var assets = new List<ReleaseAsset>();
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;
+165
View File
@@ -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;
/// <summary>A downloaded update was refused: the release lacks a setup or checksum line, or the bytes do not match.</summary>
public sealed class UpdateVerificationException(string message) : Exception(message);
/// <summary>
/// "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 <c>SHA256SUMS</c>. 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.
/// </summary>
public static class UpdateDownload
{
public const string ChecksumsName = "SHA256SUMS";
private const int MaxChecksumsBytes = 64 * 1024;
private static readonly SearchValues<char> Hex = SearchValues.Create("0123456789abcdefABCDEF");
/// <summary>The desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's.</summary>
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);
/// <summary>The release carries both a setup and <c>SHA256SUMS</c>; otherwise only its page can be opened.</summary>
public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null;
/// <summary><c>%TEMP%\Titano\updates\&lt;tag&gt;</c> under <paramref name="tempRoot"/>.</summary>
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 : '_')));
/// <summary>
/// File name → lower-case hex SHA-256 from <c>sha256sum</c> output (<c>hash name</c> or <c>hash *name</c>); lines
/// that are not a 64-digit hash followed by a name are ignored.
/// </summary>
public static Dictionary<string, string> ParseChecksums(string text)
{
var sums = new Dictionary<string, string>(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;
}
/// <summary>
/// Downloads the setup of <paramref name="release"/> into <paramref name="folder"/>, verifies it against
/// <c>SHA256SUMS</c> and returns its path. A verified copy already there is reused; a partial or mismatching
/// download is deleted.
/// </summary>
/// <exception cref="UpdateVerificationException">The release cannot be verified or the bytes do not match.</exception>
/// <exception cref="HttpRequestException">A request failed.</exception>
public static async Task<string> DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress<double>? 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<string> 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);
}
/// <summary>Streams the asset into <paramref name="path"/>, hashing as it goes; refuses more bytes than the release announced.</summary>
private static async Task<string> DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress<double>? 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<HttpResponseMessage> 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<string> 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));
}
}
@@ -38,6 +38,9 @@ public sealed class AppServices : IAsyncDisposable
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
/// <summary>Setups are large: the download is bounded by the caller's cancellation, not a short timeout.</summary>
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = TimeSpan.FromMinutes(30) });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _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
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
public Func<CancellationToken, Task<ReleaseInfo?>> CheckForUpdateAsync { get; set; }
/// <summary>Downloads and verifies the setup of a release (BRIEF §18 P1) and returns its path.</summary>
public Func<ReleaseInfo, IProgress<double>?, CancellationToken, Task<string>> DownloadUpdateAsync { get; set; }
/// <summary>The index; null until <see cref="OpenAsync"/> succeeded.</summary>
public TitanoDatabase? Database { get; private set; }
+3
View File
@@ -57,6 +57,9 @@
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.Download}"
Command="{Binding DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
Visibility="{Binding IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center" Content="{l:Loc About.Update.ShowSetup}"
Command="{Binding ShowSetupCommand}" ToolTip="{l:Loc Tooltips.About.ShowSetup}"
Visibility="{Binding IsSetupReady, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</Grid>
+71 -9
View File
@@ -15,22 +15,27 @@ namespace Titano.App.Sections;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Download is offered: a newer release exists and no verified setup is waiting (a failed download can be retried).</summary>
public bool IsUpdateAvailable => _state is UpdateState.Available or UpdateState.DownloadFailed or UpdateState.NotVerified;
/// <summary>The verified setup is in the temporary folder.</summary>
public bool IsSetupReady => _state == UpdateState.Downloaded;
/// <summary>Starts the update check on start when allowed (opt-out, BRIEF §18).</summary>
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
}
}
/// <summary>
/// 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.
/// </summary>
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<double>(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();
}
}
@@ -294,6 +294,9 @@
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.Download}" Command="{Binding Shell.About.DownloadCommand}" ToolTip="{l:Loc Tooltips.About.Download}"
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
Visibility="{Binding Shell.About.IsUpdateAvailable, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Link}" Content="{l:Loc About.Update.ShowSetup}" Command="{Binding Shell.About.ShowSetupCommand}" ToolTip="{l:Loc Tooltips.About.ShowSetup}"
VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13"
Visibility="{Binding Shell.About.IsSetupReady, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
@@ -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<double>();
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<UpdateVerificationException>(() =>
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<UpdateVerificationException>(() => 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<UpdateVerificationException>(() => 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<HttpRequestException>(() => 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";
/// <summary>Serves SHA256SUMS and the setup (null: the setup answers 500).</summary>
private sealed class FakeReleases(string sums, byte[]? setup) : HttpMessageHandler
{
public int SetupRequests { get; private set; }
protected override Task<HttpResponseMessage> 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) });
}
}
/// <summary>Reports synchronously (<see cref="Progress{T}"/> would post to the thread pool).</summary>
private sealed class SyncProgress(Action<double> report) : IProgress<double>
{
public void Report(double value) => report(value);
}
}