diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 000000000..dbb1ffe39 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,33 @@ + + + + 1 + + + + $([System.Text.RegularExpressions.Regex]::Match('$(Version)', '^\d+\.\d+\.\d+').Value) + + + + $(ForkBaseVersion).$(ForkRevision) + $(ForkBaseVersion).$(ForkRevision) + $(ForkBaseVersion).$(ForkRevision) + $(ForkBaseVersion).$(ForkRevision) + + diff --git a/src/DeskBox/Services/AppUpdateService.cs b/src/DeskBox/Services/AppUpdateService.cs index be9ca7ef0..fabccee8c 100644 --- a/src/DeskBox/Services/AppUpdateService.cs +++ b/src/DeskBox/Services/AppUpdateService.cs @@ -12,9 +12,10 @@ namespace DeskBox.Services; public sealed partial class AppUpdateService : IAppUpdateService { - public const string DefaultManifestUrl = "https://deskbox.fun/update/stable.json"; - public const string DefaultGitHubLatestReleaseApiUrl = "https://api.github.com/repos/Tianyu199509/DeskBox/releases/latest"; - public const string DefaultManualDownloadUrl = "https://deskbox.fun/download"; + // GOXF fork: update sources live in ForkUpdateConfig (fork releases only). + public const string DefaultManifestUrl = ForkUpdateConfig.ManifestUrl; + public const string DefaultGitHubLatestReleaseApiUrl = ForkUpdateConfig.ForkLatestReleaseApiUrl; + public const string DefaultManualDownloadUrl = ForkUpdateConfig.ForkReleasesPageUrl; private readonly HttpClient _httpClient; private readonly string _manifestUrl; @@ -191,10 +192,16 @@ public async Task CheckForUpdatesAsync(CancellationToken c public async Task CheckForUpdatesAsync(string currentVersion, CancellationToken cancellationToken = default) { - var manifestResult = await CheckManifestForUpdatesAsync(currentVersion, cancellationToken); - if (manifestResult.Status is AppUpdateCheckStatus.UpdateAvailable or AppUpdateCheckStatus.UpToDate) + // GOXF fork: no manifest by default (ForkUpdateConfig.ManifestUrl is + // empty), so the fork's GitHub latest release is the only source. + AppUpdateCheckResult? manifestResult = null; + if (!string.IsNullOrWhiteSpace(_manifestUrl)) { - return SetLastCheckResult(manifestResult); + manifestResult = await CheckManifestForUpdatesAsync(currentVersion, cancellationToken); + if (manifestResult.Status is AppUpdateCheckStatus.UpdateAvailable or AppUpdateCheckStatus.UpToDate) + { + return SetLastCheckResult(manifestResult); + } } var githubResult = await CheckGitHubLatestReleaseForUpdatesAsync(currentVersion, cancellationToken); @@ -203,7 +210,7 @@ public async Task CheckForUpdatesAsync(string currentVersi return SetLastCheckResult(githubResult); } - return SetLastCheckResult(manifestResult); + return SetLastCheckResult(manifestResult ?? githubResult); } private async Task CheckManifestForUpdatesAsync(string currentVersion, CancellationToken cancellationToken) @@ -707,6 +714,11 @@ public static bool IsManifestUsable(AppUpdateManifest? manifest) public static async Task FetchContentManifestAsync( CancellationToken cancellationToken = default) { + if (string.IsNullOrWhiteSpace(DefaultManifestUrl)) + { + return null; + } + try { return await FetchContentManifestAsync(DefaultManifestUrl, s_contentHttpClient, cancellationToken); @@ -756,7 +768,7 @@ public static AppUpdateManifest CreateReleaseNotesOnlyManifest(string version) { Channel = "direct", Version = version.Trim(), - ReleaseNotesUrl = $"https://github.com/Tianyu199509/DeskBox/releases/tag/v{version.Trim()}", + ReleaseNotesUrl = ForkUpdateConfig.GetReleaseTagUrl(version), }; } @@ -768,32 +780,8 @@ public static AppUpdateManifest CreateReleaseNotesOnlyManifest(string version) /// private static bool IsTrustedInstallerDownloadUri(Uri uri) { - if (!string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - if (IsHostOrSubdomain(uri, "deskbox.fun")) - { - return true; - } - - // GitHub hosts third-party repositories, so trusting the whole domain - // would let a tampered manifest point at any attacker repository with - // a matching hash. Only this project's own release downloads count; - // the actual asset bytes arrive via redirect from - // objects.githubusercontent.com, which the HTTP client follows and - // which therefore must never be trusted as a manifest origin itself. - return string.Equals(uri.Host, "github.com", StringComparison.OrdinalIgnoreCase) && - uri.AbsolutePath.StartsWith( - "/Tianyu199509/DeskBox/releases/download/", - StringComparison.OrdinalIgnoreCase); - } - - private static bool IsHostOrSubdomain(Uri uri, string domain) - { - return uri.Host.Equals(domain, StringComparison.OrdinalIgnoreCase) || - uri.Host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase); + // GOXF fork: only GOXF/DeskBox release downloads (see ForkUpdateConfig). + return ForkUpdateConfig.IsTrustedInstallerDownloadUri(uri); } internal static bool TrySelectInstallerForArchitecture( diff --git a/src/DeskBox/Services/ForkUpdateConfig.cs b/src/DeskBox/Services/ForkUpdateConfig.cs new file mode 100644 index 000000000..dff15f6b5 --- /dev/null +++ b/src/DeskBox/Services/ForkUpdateConfig.cs @@ -0,0 +1,102 @@ +namespace DeskBox.Services; + +/// +/// GOXF/DeskBox fork: where the installed app looks for its own updates and +/// for upstream (Tianyu199509/DeskBox) releases. Kept in a fork-only file so +/// upstream changes to merge with only a few +/// one-line touch points. +/// +/// Fork versions are the upstream base version plus a 4th "fork revision" +/// segment (1.5.9 + 1 => 1.5.9.1, see Directory.Build.targets). Fork releases +/// are tagged v1.5.9.1 on GOXF/DeskBox with the same asset names upstream +/// uses (DeskBox_Setup_1.5.9.1_x64.exe + .sha256). +/// +public static class ForkUpdateConfig +{ + public const string ForkOwner = "GOXF"; + public const string UpstreamOwner = "Tianyu199509"; + public const string RepositoryName = "DeskBox"; + + /// The fork's own releases: the only source of installers. + public const string ForkLatestReleaseApiUrl = "https://api.github.com/repos/GOXF/DeskBox/releases/latest"; + + /// Upstream releases: informational only, never downloaded. + public const string UpstreamLatestReleaseApiUrl = "https://api.github.com/repos/Tianyu199509/DeskBox/releases/latest"; + + public const string ForkReleasesPageUrl = "https://github.com/GOXF/DeskBox/releases/latest"; + public const string UpstreamReleasesPageUrl = "https://github.com/Tianyu199509/DeskBox/releases/latest"; + + /// + /// The fork publishes no JSON manifest. The upstream one at + /// deskbox.fun/update/stable.json describes upstream installers and must + /// never drive this build's updater, so the default is empty (= skip). + /// + public const string ManifestUrl = ""; + + internal const string ForkReleaseDownloadPathPrefix = "/GOXF/DeskBox/releases/download/"; + + /// + /// Only this fork's GitHub release downloads may be installed. The asset + /// bytes arrive by redirect from objects.githubusercontent.com, which the + /// HTTP client follows and which therefore is never trusted as an origin. + /// Upstream hosts (deskbox.fun, github.com/Tianyu199509) are deliberately + /// NOT trusted: an upstream installer would overwrite the fork build. + /// + public static bool IsTrustedInstallerDownloadUri(Uri uri) + { + return uri.IsAbsoluteUri && + string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase) && + string.Equals(uri.Host, "github.com", StringComparison.OrdinalIgnoreCase) && + uri.AbsolutePath.StartsWith(ForkReleaseDownloadPathPrefix, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Release-tag page for one version: 4-segment versions are fork builds + /// (GOXF/DeskBox), 3-segment versions are upstream releases whose notes + /// live on Tianyu199509/DeskBox. + /// + public static string GetReleaseTagUrl(string version) + { + string trimmed = version.Trim(); + if (trimmed.StartsWith('v') || trimmed.StartsWith('V')) + { + trimmed = trimmed[1..]; + } + + string owner = IsForkVersion(trimmed) ? ForkOwner : UpstreamOwner; + return $"https://github.com/{owner}/{RepositoryName}/releases/tag/v{trimmed}"; + } + + public static bool IsForkVersion(string? version) + { + return AppUpdateService.TryParseVersion(version, out Version parsed) && parsed.Revision >= 0; + } + + /// + /// The upstream base (first three segments) of a fork or upstream + /// version: "1.5.9.1" => "1.5.9", "v1.6.0" => "1.6.0". Empty when the + /// text is not a version. + /// + public static string GetBaseVersion(string? version) + { + if (!AppUpdateService.TryParseVersion(version, out Version parsed)) + { + return string.Empty; + } + + return new Version(parsed.Major, parsed.Minor, Math.Max(0, parsed.Build)).ToString(3); + } + + /// + /// True when upstream released a version newer than the upstream base + /// this build was made from. Only the first three segments are compared. + /// + public static bool IsUpstreamNewer(string? currentVersion, string? upstreamVersion) + { + string currentBase = GetBaseVersion(currentVersion); + string upstreamBase = GetBaseVersion(upstreamVersion); + return currentBase.Length > 0 && + upstreamBase.Length > 0 && + Version.Parse(upstreamBase) > Version.Parse(currentBase); + } +} diff --git a/src/DeskBox/Services/UpstreamReleaseCheckService.cs b/src/DeskBox/Services/UpstreamReleaseCheckService.cs new file mode 100644 index 000000000..0094e057e --- /dev/null +++ b/src/DeskBox/Services/UpstreamReleaseCheckService.cs @@ -0,0 +1,106 @@ +using System.Text.Json; + +namespace DeskBox.Services; + +/// +/// Result of the informational upstream check: upstream's latest release +/// tag compared against the upstream base of the running fork build. +/// +public sealed record UpstreamReleaseInfo( + string UpstreamVersion, + string CurrentBaseVersion, + string ReleaseUrl, + bool IsNewer); + +/// +/// GOXF/DeskBox fork: asks Tianyu199509/DeskBox's GitHub "latest release" +/// whether upstream has moved past the base this build was made from. Purely +/// informational: nothing is downloaded from upstream, and any failure +/// (offline, rate limit, malformed JSON) yields null so it can never block or +/// alter the normal update flow. +/// +public static class UpstreamReleaseCheckService +{ + private static readonly HttpClient s_httpClient = CreateHttpClient(); + + private static HttpClient CreateHttpClient() + { + var client = new HttpClient + { + Timeout = TimeSpan.FromSeconds(10) + }; + client.DefaultRequestHeaders.UserAgent.ParseAdd($"DeskBox/{AppUpdateService.GetCurrentAppVersion()}"); + client.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json"); + return client; + } + + public static Task CheckAsync( + string currentVersion, + CancellationToken cancellationToken = default) + { + return CheckAsync(currentVersion, s_httpClient, ForkUpdateConfig.UpstreamLatestReleaseApiUrl, cancellationToken); + } + + internal static async Task CheckAsync( + string currentVersion, + HttpClient httpClient, + string latestReleaseApiUrl, + CancellationToken cancellationToken) + { + try + { + using var response = await httpClient.GetAsync(latestReleaseApiUrl, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + return null; + } + + string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + return ParseLatestRelease(currentVersion, json); + } + catch (Exception ex) + { + App.Log($"[Update] Upstream release check skipped: {ex.GetType().Name}"); + return null; + } + } + + internal static UpstreamReleaseInfo? ParseLatestRelease(string currentVersion, string json) + { + try + { + using var document = JsonDocument.Parse(json); + JsonElement root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("tag_name", out JsonElement tagElement) || + tagElement.ValueKind != JsonValueKind.String) + { + return null; + } + + string upstreamVersion = ForkUpdateConfig.GetBaseVersion(tagElement.GetString()); + string currentBase = ForkUpdateConfig.GetBaseVersion(currentVersion); + if (upstreamVersion.Length == 0 || currentBase.Length == 0) + { + return null; + } + + string releaseUrl = root.TryGetProperty("html_url", out JsonElement urlElement) && + urlElement.ValueKind == JsonValueKind.String && + Uri.TryCreate(urlElement.GetString(), UriKind.Absolute, out Uri? uri) && + uri.Scheme == Uri.UriSchemeHttps + ? uri.ToString() + : ForkUpdateConfig.UpstreamReleasesPageUrl; + + return new UpstreamReleaseInfo( + upstreamVersion, + currentBase, + releaseUrl, + ForkUpdateConfig.IsUpstreamNewer(currentBase, upstreamVersion)); + } + catch (JsonException) + { + return null; + } + } +} diff --git a/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs b/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs index 1902a6b2a..e24fab359 100644 --- a/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs +++ b/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs @@ -311,6 +311,7 @@ public async Task CheckForUpdatesAsync() _updateOperationCts?.Cancel(); _updateOperationCts = new CancellationTokenSource(); + StartUpstreamReleaseCheck(); // GOXF fork: informational, never awaited IsCheckingForUpdates = true; UpdateStatusText = _localizationService.T("Settings.Update.Status.Checking"); UpdateDetailText = _localizationService.T("Settings.Update.Detail.Checking"); diff --git a/src/DeskBox/ViewModels/SettingsViewModel.ForkUpstream.cs b/src/DeskBox/ViewModels/SettingsViewModel.ForkUpstream.cs new file mode 100644 index 000000000..c1994dcfd --- /dev/null +++ b/src/DeskBox/ViewModels/SettingsViewModel.ForkUpstream.cs @@ -0,0 +1,100 @@ +using DeskBox.Services; +using Microsoft.UI.Xaml; + +namespace DeskBox.ViewModels; + +/// +/// GOXF/DeskBox fork: on a user-initiated update check, also asks upstream +/// (Tianyu199509/DeskBox) whether it has released a newer base version and +/// shows a one-line notice under the update details. The fork's own update +/// flow never waits on this and is unaffected when it fails. +/// +/// The notice text lives here instead of Strings/*.json on purpose: those +/// files are upstream-owned and edited on every upstream release, so fork +/// keys there would conflict on nearly every automatic sync. +/// +public partial class SettingsViewModel +{ + private string _upstreamReleaseNoticeText = string.Empty; + private int _upstreamReleaseCheckInFlight; + + public string UpstreamReleaseNoticeText => _upstreamReleaseNoticeText; + + public Visibility UpstreamReleaseNoticeVisibility => + IsDirectInstallerUpdateDelivery && !string.IsNullOrWhiteSpace(_upstreamReleaseNoticeText) + ? Visibility.Visible + : Visibility.Collapsed; + + /// + /// Fire-and-forget: started alongside the fork's own check, never awaited + /// by it. Store builds skip it (they update through the Store). + /// + private void StartUpstreamReleaseCheck() + { + if (!IsDirectInstallerUpdateDelivery || + Interlocked.Exchange(ref _upstreamReleaseCheckInFlight, 1) == 1) + { + return; + } + + _ = RunUpstreamReleaseCheckAsync(AppVersion); + } + + private async Task RunUpstreamReleaseCheckAsync(string currentVersion) + { + try + { + UpstreamReleaseInfo? info = await UpstreamReleaseCheckService.CheckAsync(currentVersion) + .ConfigureAwait(false); + if (info is null) + { + // Unknown: keep whatever an earlier successful check showed. + return; + } + + string notice = info.IsNewer + ? FormatUpstreamReleaseNotice(_localizationService.CurrentCultureName, info.UpstreamVersion, info.CurrentBaseVersion) + : string.Empty; + SetUpstreamReleaseNotice(notice); + } + catch (Exception ex) + { + App.Log($"[Update] Upstream release notice failed: {ex.GetType().Name}"); + } + finally + { + Volatile.Write(ref _upstreamReleaseCheckInFlight, 0); + } + } + + private void SetUpstreamReleaseNotice(string notice) + { + if (_uiDispatcherQueue is { } queue && !queue.HasThreadAccess) + { + queue.TryEnqueue(() => SetUpstreamReleaseNotice(notice)); + return; + } + + if (string.Equals(_upstreamReleaseNoticeText, notice, StringComparison.Ordinal)) + { + return; + } + + _upstreamReleaseNoticeText = notice; + OnPropertyChanged(nameof(UpstreamReleaseNoticeText)); + OnPropertyChanged(nameof(UpstreamReleaseNoticeVisibility)); + } + + internal static string FormatUpstreamReleaseNotice(string? cultureName, string upstreamVersion, string currentBaseVersion) + { + return cultureName switch + { + LocalizationService.LanguageChinese => + $"上游 DeskBox 已发布 v{upstreamVersion}(你当前基于 v{currentBaseVersion})。自动同步会合并它,发布你的新版本后即可更新。", + LocalizationService.LanguageChineseTraditional => + $"上游 DeskBox 已發布 v{upstreamVersion}(你目前基於 v{currentBaseVersion})。自動同步會合併它,發布你的新版本後即可更新。", + _ => + $"Upstream DeskBox released v{upstreamVersion} (this build is based on v{currentBaseVersion}). The automatic sync will merge it; update once your new fork release is published.", + }; + } +} diff --git a/src/DeskBox/Views/SettingsWindow.xaml b/src/DeskBox/Views/SettingsWindow.xaml index 116e26a86..45a879134 100644 --- a/src/DeskBox/Views/SettingsWindow.xaml +++ b/src/DeskBox/Views/SettingsWindow.xaml @@ -3404,6 +3404,11 @@ Text="DeskBox" /> Style="{StaticResource SettingDescriptionTextStyle}" Text="{Binding UpdateDetailText}" TextWrapping="Wrap" /> + new HttpResponseMessage(HttpStatusCode.OK) { @@ -441,6 +451,13 @@ public async Task ContentManifestFetch_AcceptsNotesOnlyManifest_AndRejectsInstal [Fact] public void ReleaseNotesOnlyManifest_PointsAtGitHubTagForExactVersion() { + // GOXF fork: 3-segment versions are upstream releases (notes on the + // upstream repo); 4-segment versions are fork builds. + AppUpdateManifest forkManifest = AppUpdateService.CreateReleaseNotesOnlyManifest("1.5.9.1"); + Assert.Equal( + "https://github.com/GOXF/DeskBox/releases/tag/v1.5.9.1", + forkManifest.ReleaseNotesUrl); + AppUpdateManifest manifest = AppUpdateService.CreateReleaseNotesOnlyManifest("1.5.9"); Assert.Equal("1.5.9", manifest.Version); @@ -481,10 +498,17 @@ protected override Task SendAsync(HttpRequestMessage reques } [Theory] - [InlineData("https://deskbox.fun/update/DeskBox_Setup.exe", true)] - [InlineData("https://cdn.deskbox.fun/DeskBox_Setup.exe", true)] - [InlineData("https://github.com/Tianyu199509/DeskBox/releases/download/v1.5.2/DeskBox_Setup.exe", true)] + [InlineData("https://github.com/GOXF/DeskBox/releases/download/v1.5.2.1/DeskBox_Setup_1.5.2.1_x64.exe", true)] + [InlineData("https://github.com/goxf/deskbox/releases/download/v1.5.2.1/DeskBox_Setup.exe", true)] + [InlineData("http://github.com/GOXF/DeskBox/releases/download/v1.5.2.1/DeskBox_Setup.exe", false)] + // GOXF fork: upstream installer origins must never be trusted, or an + // upstream build would overwrite the fork install. + [InlineData("https://deskbox.fun/update/DeskBox_Setup.exe", false)] + [InlineData("https://cdn.deskbox.fun/DeskBox_Setup.exe", false)] + [InlineData("https://github.com/Tianyu199509/DeskBox/releases/download/v1.5.2/DeskBox_Setup.exe", false)] [InlineData("http://deskbox.fun/update/DeskBox_Setup.exe", false)] + [InlineData("https://github.com/GOXF/DeskBox/blob/custom/DeskBox_Setup.exe", false)] + [InlineData("https://github.com/GOXF/DeskBoxEvil/releases/download/v1.0.0/DeskBox_Setup.exe", false)] [InlineData("https://evil.example.com/DeskBox_Setup.exe", false)] [InlineData("https://deskbox.fun.evil.example.com/DeskBox_Setup.exe", false)] [InlineData("https://github.evil.example.com/DeskBox_Setup.exe", false)] @@ -510,7 +534,7 @@ public void IsManifestUsable_RejectsAnUntrustedArm64DownloadUrl() var manifest = new AppUpdateManifest { Version = "1.5.2.0", - DownloadUrl = "https://deskbox.fun/update/DeskBox_Setup_x64.exe", + DownloadUrl = "https://github.com/GOXF/DeskBox/releases/download/v1.5.2/DeskBox_Setup_x64.exe", Arm64DownloadUrl = "http://evil.example.com/DeskBox_Setup_arm64.exe" }; diff --git a/tests/DeskBox.Tests/ForkUpdateTests.cs b/tests/DeskBox.Tests/ForkUpdateTests.cs new file mode 100644 index 000000000..78356deaf --- /dev/null +++ b/tests/DeskBox.Tests/ForkUpdateTests.cs @@ -0,0 +1,248 @@ +using System.Net; +using System.Text; +using DeskBox.Models; +using DeskBox.Services; +using DeskBox.ViewModels; + +namespace DeskBox.Tests; + +/// +/// GOXF/DeskBox fork: the installed fork build must update only from the +/// fork's own GitHub releases, and a user-initiated check additionally +/// reports (informationally) whether upstream has a newer base version. +/// +public sealed class ForkUpdateTests : IDisposable +{ + private readonly string _tempRoot = Path.Combine(Path.GetTempPath(), "DeskBox.Tests", Guid.NewGuid().ToString("N")); + + [Fact] + public void Defaults_PointAtForkReleasesAndSkipTheUpstreamManifest() + { + Assert.Equal("https://api.github.com/repos/GOXF/DeskBox/releases/latest", AppUpdateService.DefaultGitHubLatestReleaseApiUrl); + Assert.Empty(AppUpdateService.DefaultManifestUrl); + Assert.Equal("https://github.com/GOXF/DeskBox/releases/latest", AppUpdateService.DefaultManualDownloadUrl); + Assert.Equal("https://api.github.com/repos/Tianyu199509/DeskBox/releases/latest", ForkUpdateConfig.UpstreamLatestReleaseApiUrl); + } + + [Fact] + public async Task ContentManifestFetch_IsSkippedWithoutAFeed() + { + Assert.Null(await AppUpdateService.FetchContentManifestAsync()); + } + + [Fact] + public async Task CheckForUpdatesAsync_DefaultServiceOnlyQueriesTheForkRelease() + { + var requested = new List(); + using var httpClient = new HttpClient(new StubHandler(request => + { + string url = request.RequestUri!.ToString(); + requested.Add(url); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent( + $$""" + { + "tag_name": "v1.5.9.2", + "html_url": "https://github.com/GOXF/DeskBox/releases/tag/v1.5.9.2", + "body": "fork build", + "assets": [ + { + "name": "DeskBox_Setup_1.5.9.2_{{AppUpdateService.CurrentInstallerArchitectureSuffix}}.exe", + "browser_download_url": "https://github.com/GOXF/DeskBox/releases/download/v1.5.9.2/DeskBox_Setup_1.5.9.2_{{AppUpdateService.CurrentInstallerArchitectureSuffix}}.exe", + "size": 1000, + "digest": "sha256:8ecb3092ae5bd6883f8a75bbea03d9800251e0c23fdbe1bf4d91fd3a62565561" + } + ] + } + """, + Encoding.UTF8, + "application/json") + }; + })); + + var service = new AppUpdateService(httpClient, updateRootPath: _tempRoot); + AppUpdateCheckResult result = await service.CheckForUpdatesAsync("1.5.9.1"); + + Assert.Equal(AppUpdateCheckStatus.UpdateAvailable, result.Status); + Assert.Equal("1.5.9.2", result.Manifest!.Version); + Assert.Equal(new[] { ForkUpdateConfig.ForkLatestReleaseApiUrl }, requested); + Assert.DoesNotContain(requested, url => url.Contains("deskbox.fun", StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain(requested, url => url.Contains("Tianyu199509", StringComparison.OrdinalIgnoreCase)); + + AppUpdateCheckResult same = await service.CheckForUpdatesAsync("1.5.9.2"); + Assert.Equal(AppUpdateCheckStatus.UpToDate, same.Status); + } + + [Fact] + public async Task CheckForUpdatesAsync_RejectsAReleasePointingAtUpstreamInstallers() + { + using var httpClient = new HttpClient(new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent( + $$""" + { + "tag_name": "v1.6.0", + "assets": [ + { + "name": "DeskBox_Setup_1.6.0_{{AppUpdateService.CurrentInstallerArchitectureSuffix}}.exe", + "browser_download_url": "https://github.com/Tianyu199509/DeskBox/releases/download/v1.6.0/DeskBox_Setup_1.6.0_{{AppUpdateService.CurrentInstallerArchitectureSuffix}}.exe", + "size": 1000, + "digest": "sha256:8ecb3092ae5bd6883f8a75bbea03d9800251e0c23fdbe1bf4d91fd3a62565561" + } + ] + } + """, + Encoding.UTF8, + "application/json") + })); + + var service = new AppUpdateService(httpClient, updateRootPath: _tempRoot); + AppUpdateCheckResult result = await service.CheckForUpdatesAsync("1.5.9.1"); + + Assert.NotEqual(AppUpdateCheckStatus.UpdateAvailable, result.Status); + } + + [Fact] + public async Task CheckForUpdatesAsync_NoForkReleaseYetIsAFailureNotAnUpstreamFallback() + { + var requested = new List(); + using var httpClient = new HttpClient(new StubHandler(request => + { + requested.Add(request.RequestUri!.ToString()); + return new HttpResponseMessage(HttpStatusCode.NotFound); + })); + + var service = new AppUpdateService(httpClient, updateRootPath: _tempRoot); + AppUpdateCheckResult result = await service.CheckForUpdatesAsync("1.5.9.1"); + + Assert.Equal(AppUpdateCheckStatus.Failed, result.Status); + Assert.Single(requested); + } + + [Theory] + [InlineData("1.5.9.1", "1.5.9")] + [InlineData("v1.6.0", "1.6.0")] + [InlineData("1.6.0-beta.1", "1.6.0")] + [InlineData("1.5", "1.5.0")] + [InlineData("not-a-version", "")] + [InlineData("", "")] + public void GetBaseVersion_TakesTheFirstThreeSegments(string version, string expected) + { + Assert.Equal(expected, ForkUpdateConfig.GetBaseVersion(version)); + } + + [Theory] + [InlineData("1.5.9.1", "v1.6.0", true)] + [InlineData("1.5.9.3", "v1.5.10", true)] + [InlineData("1.5.9.1", "v1.5.9", false)] + [InlineData("1.6.0.1", "v1.5.9", false)] + [InlineData("1.5.9.7", "1.5.9.9", false)] + [InlineData("1.5.9.1", "garbage", false)] + public void IsUpstreamNewer_ComparesOnlyTheUpstreamBase(string current, string upstream, bool expected) + { + Assert.Equal(expected, ForkUpdateConfig.IsUpstreamNewer(current, upstream)); + } + + [Theory] + [InlineData("1.5.9.1", "https://github.com/GOXF/DeskBox/releases/tag/v1.5.9.1")] + [InlineData("v1.5.9.2", "https://github.com/GOXF/DeskBox/releases/tag/v1.5.9.2")] + [InlineData("1.5.8", "https://github.com/Tianyu199509/DeskBox/releases/tag/v1.5.8")] + public void GetReleaseTagUrl_RoutesForkAndUpstreamVersions(string version, string expected) + { + Assert.Equal(expected, ForkUpdateConfig.GetReleaseTagUrl(version)); + } + + [Fact] + public void ParseLatestRelease_ReportsANewerUpstreamBase() + { + UpstreamReleaseInfo? info = UpstreamReleaseCheckService.ParseLatestRelease( + "1.5.9.1", + """{"tag_name":"v1.6.0","html_url":"https://github.com/Tianyu199509/DeskBox/releases/tag/v1.6.0"}"""); + + Assert.NotNull(info); + Assert.True(info!.IsNewer); + Assert.Equal("1.6.0", info.UpstreamVersion); + Assert.Equal("1.5.9", info.CurrentBaseVersion); + Assert.Equal("https://github.com/Tianyu199509/DeskBox/releases/tag/v1.6.0", info.ReleaseUrl); + } + + [Theory] + [InlineData("""{"tag_name":"v1.5.9"}""", false)] + [InlineData("""{"tag_name":"v1.5.8"}""", false)] + public void ParseLatestRelease_SameOrOlderUpstreamIsNotNewer(string json, bool expected) + { + UpstreamReleaseInfo? info = UpstreamReleaseCheckService.ParseLatestRelease("1.5.9.1", json); + Assert.NotNull(info); + Assert.Equal(expected, info!.IsNewer); + Assert.Equal(ForkUpdateConfig.UpstreamReleasesPageUrl, info.ReleaseUrl); + } + + [Theory] + [InlineData("not json")] + [InlineData("[]")] + [InlineData("""{"message":"API rate limit exceeded"}""")] + [InlineData("""{"tag_name":"nightly"}""")] + public void ParseLatestRelease_MalformedPayloadYieldsNull(string json) + { + Assert.Null(UpstreamReleaseCheckService.ParseLatestRelease("1.5.9.1", json)); + } + + [Fact] + public async Task UpstreamCheck_NetworkFailuresNeverThrow() + { + using var failing = new HttpClient(new StubHandler(_ => throw new HttpRequestException("offline"))); + Assert.Null(await UpstreamReleaseCheckService.CheckAsync( + "1.5.9.1", failing, ForkUpdateConfig.UpstreamLatestReleaseApiUrl, CancellationToken.None)); + + using var limited = new HttpClient(new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.Forbidden))); + Assert.Null(await UpstreamReleaseCheckService.CheckAsync( + "1.5.9.1", limited, ForkUpdateConfig.UpstreamLatestReleaseApiUrl, CancellationToken.None)); + } + + [Fact] + public async Task UpstreamCheck_QueriesUpstreamLatestRelease() + { + string? requested = null; + using var client = new HttpClient(new StubHandler(request => + { + requested = request.RequestUri!.ToString(); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("""{"tag_name":"v1.6.0"}""", Encoding.UTF8, "application/json") + }; + })); + + UpstreamReleaseInfo? info = await UpstreamReleaseCheckService.CheckAsync( + "1.5.9.1", client, ForkUpdateConfig.UpstreamLatestReleaseApiUrl, CancellationToken.None); + + Assert.Equal("https://api.github.com/repos/Tianyu199509/DeskBox/releases/latest", requested); + Assert.True(info!.IsNewer); + } + + [Fact] + public void UpstreamNotice_IsLocalizedForChineseAndFallsBackToEnglish() + { + Assert.Equal( + "上游 DeskBox 已发布 v1.6.0(你当前基于 v1.5.9)。自动同步会合并它,发布你的新版本后即可更新。", + SettingsViewModel.FormatUpstreamReleaseNotice(LocalizationService.LanguageChinese, "1.6.0", "1.5.9")); + Assert.Contains("v1.6.0", SettingsViewModel.FormatUpstreamReleaseNotice(LocalizationService.LanguageChineseTraditional, "1.6.0", "1.5.9")); + Assert.StartsWith("Upstream DeskBox released v1.6.0", SettingsViewModel.FormatUpstreamReleaseNotice("ja-JP", "1.6.0", "1.5.9")); + } + + public void Dispose() + { + if (Directory.Exists(_tempRoot)) + { + Directory.Delete(_tempRoot, recursive: true); + } + } + + private sealed class StubHandler(Func handler) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(handler(request)); + } + } +} diff --git a/tests/DeskBox.Tests/ReleaseNotesKnownVersionsTests.cs b/tests/DeskBox.Tests/ReleaseNotesKnownVersionsTests.cs index 43b6b77a3..84d6a43c6 100644 --- a/tests/DeskBox.Tests/ReleaseNotesKnownVersionsTests.cs +++ b/tests/DeskBox.Tests/ReleaseNotesKnownVersionsTests.cs @@ -40,7 +40,9 @@ public void KnownReleaseVersions_NewestMatchesCurrentRelease() // pin turns a forgotten append into a red suite on the first build // of the next version instead of a silently missing rail entry on // every 1.5.9 machine. - string current = AppUpdateService.GetCurrentAppVersion(); + // GOXF fork: the running version carries a 4th fork-revision segment + // (1.5.9.1); the known-versions rail lists upstream base versions. + string current = ForkUpdateConfig.GetBaseVersion(AppUpdateService.GetCurrentAppVersion()); Assert.NotEqual("0.0.0", current); Assert.Equal(current, ReleaseNotesService.KnownReleaseVersions[0]); }