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

+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>