From 544e0557d7cf2a98dc55db3bb69f5b7a9267a0bd Mon Sep 17 00:00:00 2001
From: GOXF <131693427+GOXF@users.noreply.github.com>
Date: Sun, 8 Nov 2026 05:00:37 +0000
Subject: [PATCH 1/2] =?UTF-8?q?feat(update):=20=E5=8F=AF=E9=85=8D=E7=BD=AE?=
=?UTF-8?q?=E7=9A=84=E6=9B=B4=E6=96=B0=E4=B8=8B=E8=BD=BD=E4=BB=A3=E7=90=86?=
=?UTF-8?q?=20+=2030=20=E7=A7=92=E6=97=A0=E6=95=B0=E6=8D=AE=E8=87=AA?=
=?UTF-8?q?=E5=8A=A8=E5=88=87=E6=8D=A2/=E5=A4=B1=E8=B4=A5=EF=BC=88?=
=?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8D=A1=E5=9C=A8=200=20B=EF=BC=89?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Services/AppUpdateService.ForkDownload.cs | 69 +++++++++++
src/DeskBox/Services/AppUpdateService.cs | 66 +++++-----
.../Services/ForkDownloadProxySettings.cs | 117 ++++++++++++++++++
.../SettingsViewModel.ForkDownloadProxy.cs | 72 +++++++++++
src/DeskBox/Views/SettingsWindow.xaml | 10 ++
tests/DeskBox.Tests/ForkUpdateTests.cs | 40 ++++++
6 files changed, 341 insertions(+), 33 deletions(-)
create mode 100644 src/DeskBox/Services/AppUpdateService.ForkDownload.cs
create mode 100644 src/DeskBox/Services/ForkDownloadProxySettings.cs
create mode 100644 src/DeskBox/ViewModels/SettingsViewModel.ForkDownloadProxy.cs
diff --git a/src/DeskBox/Services/AppUpdateService.ForkDownload.cs b/src/DeskBox/Services/AppUpdateService.ForkDownload.cs
new file mode 100644
index 000000000..8f6b197a9
--- /dev/null
+++ b/src/DeskBox/Services/AppUpdateService.ForkDownload.cs
@@ -0,0 +1,69 @@
+using System.Security.Cryptography;
+
+namespace DeskBox.Services;
+
+public sealed partial class AppUpdateService
+{
+ /// No bytes for this long fails the source (it used to sit at 0 B forever).
+ internal static TimeSpan ForkDownloadStallTimeout { get; set; } = TimeSpan.FromSeconds(30);
+
+ private async Task<(long BytesReceived, long? TotalBytes, string Sha256)> ForkDownloadToFileAsync(
+ Uri source,
+ string tempPath,
+ long manifestSize,
+ IProgress? progress,
+ CancellationToken cancellationToken)
+ {
+ using var stallCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ stallCts.CancelAfter(ForkDownloadStallTimeout);
+ try
+ {
+ using var response = await _httpClient.GetAsync(
+ source,
+ HttpCompletionOption.ResponseHeadersRead,
+ stallCts.Token);
+ response.EnsureSuccessStatusCode();
+
+ long? totalBytes = response.Content.Headers.ContentLength;
+ if (totalBytes is null && manifestSize > 0)
+ {
+ totalBytes = manifestSize;
+ }
+
+ progress?.Report(new AppUpdateDownloadProgress(0, totalBytes));
+ long bytesReceived = 0;
+ await using var remoteStream = await response.Content.ReadAsStreamAsync(stallCts.Token);
+ await using var fileStream = new FileStream(
+ tempPath,
+ FileMode.Create,
+ FileAccess.Write,
+ FileShare.None,
+ bufferSize: 1024 * 128,
+ useAsync: true);
+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ byte[] buffer = new byte[1024 * 128];
+ while (true)
+ {
+ stallCts.CancelAfter(ForkDownloadStallTimeout);
+ int bytesRead = await remoteStream.ReadAsync(buffer.AsMemory(0, buffer.Length), stallCts.Token);
+ if (bytesRead <= 0)
+ {
+ break;
+ }
+
+ await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
+ hash.AppendData(buffer, 0, bytesRead);
+ bytesReceived += bytesRead;
+ progress?.Report(new AppUpdateDownloadProgress(bytesReceived, totalBytes));
+ }
+
+ await fileStream.FlushAsync(cancellationToken);
+ return (bytesReceived, totalBytes, Convert.ToHexString(hash.GetHashAndReset()));
+ }
+ catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+ {
+ throw new TimeoutException(
+ $"No data from {source.Host} for {ForkDownloadStallTimeout.TotalSeconds:0} seconds.");
+ }
+ }
+}
diff --git a/src/DeskBox/Services/AppUpdateService.cs b/src/DeskBox/Services/AppUpdateService.cs
index 7d4e22fcc..c261b6935 100644
--- a/src/DeskBox/Services/AppUpdateService.cs
+++ b/src/DeskBox/Services/AppUpdateService.cs
@@ -375,48 +375,48 @@ private async Task DownloadUpdateCoreAsync(
File.Delete(tempPath);
}
- using var response = await _httpClient.GetAsync(
+ // GOXF fork: try the user's download proxy first (if set), then
+ // github.com directly; a stalled or failed source moves on to the
+ // next. The SHA-256 below still comes from the GitHub API.
+ IReadOnlyList candidates = ForkDownloadProxySettings.GetDownloadCandidates(
downloadUri,
- HttpCompletionOption.ResponseHeadersRead,
- cancellationToken);
- response.EnsureSuccessStatusCode();
-
- long? totalBytes = response.Content.Headers.ContentLength;
- if (totalBytes is null && manifest.Size > 0)
- {
- totalBytes = manifest.Size;
- }
-
+ ForkDownloadProxySettings.Load());
long bytesReceived = 0;
- string actualSha256;
- await using (var remoteStream = await response.Content.ReadAsStreamAsync(cancellationToken))
- await using (var fileStream = new FileStream(
- tempPath,
- FileMode.Create,
- FileAccess.Write,
- FileShare.None,
- bufferSize: 1024 * 128,
- useAsync: true))
- using (var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
+ long? totalBytes = null;
+ Exception? lastError = null;
+ bool hashMatched = false;
+ foreach (Uri candidate in candidates)
{
- byte[] buffer = new byte[1024 * 128];
- int bytesRead;
- while ((bytesRead = await remoteStream.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken)) > 0)
+ try
{
- await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
- hash.AppendData(buffer, 0, bytesRead);
- bytesReceived += bytesRead;
- progress?.Report(new AppUpdateDownloadProgress(bytesReceived, totalBytes));
+ (bytesReceived, totalBytes, string actualSha256) = await ForkDownloadToFileAsync(
+ candidate, tempPath, manifest.Size, progress, cancellationToken);
+ if (string.Equals(actualSha256, NormalizeSha256(manifest.Sha256), StringComparison.OrdinalIgnoreCase))
+ {
+ hashMatched = true;
+ break;
+ }
+
+ App.Log($"[Update] Hash mismatch from {candidate.Host}; trying next source.");
+ lastError = null;
+ }
+ catch (Exception ex) when (
+ !cancellationToken.IsCancellationRequested &&
+ ex is HttpRequestException or TaskCanceledException or TimeoutException)
+ {
+ App.Log($"[Update] Download from {candidate.Host} failed: {ex.GetType().Name}: {ex.Message}");
+ lastError = ex;
}
- await fileStream.FlushAsync(cancellationToken);
- actualSha256 = Convert.ToHexString(hash.GetHashAndReset());
+ TryDelete(tempPath);
}
- if (!string.Equals(actualSha256, NormalizeSha256(manifest.Sha256), StringComparison.OrdinalIgnoreCase))
+ if (!hashMatched)
{
TryDelete(tempPath);
- return AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.HashMismatch);
+ return lastError is null
+ ? AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.HashMismatch)
+ : AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.Network, lastError.Message);
}
File.Move(tempPath, targetPath, overwrite: true);
@@ -428,7 +428,7 @@ private async Task DownloadUpdateCoreAsync(
TryDelete(tempPath);
return AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.Cancelled);
}
- catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or TimeoutException)
{
TryDelete(tempPath);
return AppUpdateDownloadResult.Failed(AppUpdateDownloadFailureKind.Network, ex.Message);
diff --git a/src/DeskBox/Services/ForkDownloadProxySettings.cs b/src/DeskBox/Services/ForkDownloadProxySettings.cs
new file mode 100644
index 000000000..fc5f39f65
--- /dev/null
+++ b/src/DeskBox/Services/ForkDownloadProxySettings.cs
@@ -0,0 +1,117 @@
+using System.Text.Json;
+
+namespace DeskBox.Services;
+
+///
+/// GOXF/DeskBox fork: optional download proxy for update installers, for
+/// networks where github.com release downloads stall. Stored in its own small
+/// file (not the upstream settings model) so the settings process writes it
+/// and the main process reads it at download time without any IPC, and
+/// upstream settings changes never conflict with it.
+///
+/// The proxy only carries bytes. The installer's SHA-256 still comes from the
+/// GitHub API (asset digest / .sha256), and the original URL must still pass
+/// , so a bad or
+/// hostile proxy can at worst fail the download, never install other bytes.
+///
+/// Formats: a prefix such as "https://gh-proxy.com/" (original URL appended)
+/// or a template containing "{url}" (replaced with the original URL).
+///
+public static class ForkDownloadProxySettings
+{
+ private const string FileName = "fork-update.json";
+ private const string UrlPlaceholder = "{url}";
+
+ private static string FilePath => Path.Combine(DeskBoxDataPathService.Current.RootPath, FileName);
+
+ public static string Load()
+ {
+ try
+ {
+ if (!File.Exists(FilePath))
+ {
+ return string.Empty;
+ }
+
+ using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath));
+ return doc.RootElement.TryGetProperty("downloadProxy", out JsonElement value) &&
+ value.ValueKind == JsonValueKind.String
+ ? value.GetString()?.Trim() ?? string.Empty
+ : string.Empty;
+ }
+ catch (Exception)
+ {
+ // Missing data root (tests), unreadable or malformed file: no proxy.
+ return string.Empty;
+ }
+ }
+
+ /// Saves a normalized value; returns false when it is not a usable http(s) proxy.
+ public static bool TrySave(string? proxy)
+ {
+ string value = (proxy ?? string.Empty).Trim();
+ if (value.Length > 0 && !IsValidProxy(value))
+ {
+ return false;
+ }
+
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
+ File.WriteAllText(FilePath, "{\"downloadProxy\":" + JsonEncode(value) + "}");
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ }
+
+ public static bool IsValidProxy(string proxy)
+ {
+ string probe = proxy.Trim().Replace(UrlPlaceholder, "x", StringComparison.OrdinalIgnoreCase);
+ return Uri.TryCreate(probe, UriKind.Absolute, out Uri? uri) &&
+ (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp) &&
+ !string.IsNullOrEmpty(uri.Host);
+ }
+
+ public static Uri? BuildProxiedUri(string? proxy, Uri original)
+ {
+ if (string.IsNullOrWhiteSpace(proxy) || !IsValidProxy(proxy))
+ {
+ return null;
+ }
+
+ string value = proxy.Trim();
+ string url = value.Contains(UrlPlaceholder, StringComparison.OrdinalIgnoreCase)
+ ? value.Replace(UrlPlaceholder, original.AbsoluteUri, StringComparison.OrdinalIgnoreCase)
+ : value.TrimEnd('/') + "/" + original.AbsoluteUri;
+ return Uri.TryCreate(url, UriKind.Absolute, out Uri? result) ? result : null;
+ }
+
+ /// Proxy first (when set), then the original GitHub URL as fallback.
+ public static IReadOnlyList GetDownloadCandidates(Uri original, string? proxy)
+ {
+ Uri? proxied = BuildProxiedUri(proxy, original);
+ return proxied is null || proxied == original ? [original] : [proxied, original];
+ }
+
+ private static string JsonEncode(string value)
+ {
+ var sb = new System.Text.StringBuilder("\"");
+ foreach (char c in value)
+ {
+ switch (c)
+ {
+ case '"': sb.Append("\\\""); break;
+ case '\\': sb.Append("\\\\"); break;
+ default:
+ if (c < 0x20) { sb.Append("\\u").Append(((int)c).ToString("x4")); }
+ else { sb.Append(c); }
+ break;
+ }
+ }
+
+ return sb.Append('"').ToString();
+ }
+}
diff --git a/src/DeskBox/ViewModels/SettingsViewModel.ForkDownloadProxy.cs b/src/DeskBox/ViewModels/SettingsViewModel.ForkDownloadProxy.cs
new file mode 100644
index 000000000..ae94c94e9
--- /dev/null
+++ b/src/DeskBox/ViewModels/SettingsViewModel.ForkDownloadProxy.cs
@@ -0,0 +1,72 @@
+using DeskBox.Services;
+using Microsoft.UI.Xaml;
+
+namespace DeskBox.ViewModels;
+
+///
+/// GOXF/DeskBox fork: "update download proxy" field under the update details.
+/// Text lives here (not Strings/*.json) for the same merge-conflict reason as
+/// SettingsViewModel.ForkUpstream.cs. Saved to its own file on edit; the main
+/// process reads it on the next download.
+///
+public partial class SettingsViewModel
+{
+ private string? _updateDownloadProxy;
+ private string _updateDownloadProxyStatus = string.Empty;
+
+ public Visibility UpdateDownloadProxyVisibility =>
+ IsDirectInstallerUpdateDelivery ? Visibility.Visible : Visibility.Collapsed;
+
+ public string UpdateDownloadProxy
+ {
+ get => _updateDownloadProxy ??= ForkDownloadProxySettings.Load();
+ set
+ {
+ string normalized = (value ?? string.Empty).Trim();
+ if (string.Equals(normalized, UpdateDownloadProxy, StringComparison.Ordinal))
+ {
+ return;
+ }
+
+ bool saved = ForkDownloadProxySettings.TrySave(normalized);
+ if (saved)
+ {
+ _updateDownloadProxy = normalized;
+ }
+
+ _updateDownloadProxyStatus = ForkProxyText(saved
+ ? (normalized.Length == 0 ? ProxyText.Cleared : ProxyText.Saved)
+ : ProxyText.Invalid);
+ OnPropertyChanged(nameof(UpdateDownloadProxy));
+ OnPropertyChanged(nameof(UpdateDownloadProxyStatus));
+ }
+ }
+
+ public string UpdateDownloadProxyLabel => ForkProxyText(ProxyText.Label);
+
+ public string UpdateDownloadProxyStatus =>
+ _updateDownloadProxyStatus.Length > 0 ? _updateDownloadProxyStatus : ForkProxyText(ProxyText.Hint);
+
+ internal enum ProxyText { Label, Hint, Saved, Cleared, Invalid }
+
+ internal string ForkProxyText(ProxyText key) =>
+ FormatForkProxyText(_localizationService.CurrentCultureName, key);
+
+ internal static string FormatForkProxyText(string? cultureName, ProxyText key)
+ {
+ bool zhHans = cultureName == LocalizationService.LanguageChinese;
+ bool zhHant = cultureName == LocalizationService.LanguageChineseTraditional;
+ return key switch
+ {
+ ProxyText.Label => zhHans ? "更新下载代理(可选)" : zhHant ? "更新下載代理(可選)" : "Update download proxy (optional)",
+ ProxyText.Hint => zhHans
+ ? "GitHub 下载慢时填写,如 https://gh-proxy.com/ 或含 {url} 的模板;先走代理,30 秒无数据自动改用 GitHub 直连。安装包仍按 GitHub 公布的 SHA-256 校验。"
+ : zhHant
+ ? "GitHub 下載慢時填寫,如 https://gh-proxy.com/ 或含 {url} 的範本;先走代理,30 秒無資料自動改用 GitHub 直連。安裝包仍按 GitHub 公布的 SHA-256 校驗。"
+ : "For slow GitHub downloads, e.g. https://gh-proxy.com/ or a template containing {url}. The proxy is tried first; after 30 s without data DeskBox falls back to GitHub. Installers are still verified against GitHub's SHA-256.",
+ ProxyText.Saved => zhHans ? "已保存,下次下载更新时生效。" : zhHant ? "已儲存,下次下載更新時生效。" : "Saved. Used for the next update download.",
+ ProxyText.Cleared => zhHans ? "已清除,将直连 GitHub 下载。" : zhHant ? "已清除,將直連 GitHub 下載。" : "Cleared. Updates download directly from GitHub.",
+ _ => zhHans ? "地址无效,需以 http:// 或 https:// 开头。" : zhHant ? "位址無效,需以 http:// 或 https:// 開頭。" : "Invalid address: it must start with http:// or https://.",
+ };
+ }
+}
diff --git a/src/DeskBox/Views/SettingsWindow.xaml b/src/DeskBox/Views/SettingsWindow.xaml
index 45a879134..640c87550 100644
--- a/src/DeskBox/Views/SettingsWindow.xaml
+++ b/src/DeskBox/Views/SettingsWindow.xaml
@@ -3409,6 +3409,16 @@ Text="DeskBox" />
Text="{x:Bind UpstreamReleaseNoticeText, Mode=OneWay}"
Visibility="{x:Bind UpstreamReleaseNoticeVisibility, Mode=OneWay}"
TextWrapping="Wrap" />
+
+
+
+
+
SendAsync(HttpRequestMessage reques
}
}
}
+
+public class ForkDownloadProxyTests
+{
+ private static readonly Uri Original = new("https://github.com/GOXF/DeskBox/releases/download/v1.5.9.3/DeskBox_Setup_1.5.9.3_x64.exe");
+
+ [Fact]
+ public void Prefix_IsPrependedToOriginalUrl()
+ {
+ Uri? uri = DeskBox.Services.ForkDownloadProxySettings.BuildProxiedUri("https://gh-proxy.com/", Original);
+ Assert.Equal("https://gh-proxy.com/" + Original.AbsoluteUri, uri!.AbsoluteUri);
+ }
+
+ [Fact]
+ public void Template_ReplacesUrlPlaceholder()
+ {
+ Uri? uri = DeskBox.Services.ForkDownloadProxySettings.BuildProxiedUri("https://my.vps.example/dl?u={url}", Original);
+ Assert.StartsWith("https://my.vps.example/dl?u=https://github.com/GOXF/", uri!.OriginalString);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("gh-proxy.com")]
+ [InlineData("ftp://x.example/")]
+ public void InvalidOrEmptyProxy_FallsBackToDirectOnly(string proxy)
+ {
+ var candidates = DeskBox.Services.ForkDownloadProxySettings.GetDownloadCandidates(Original, proxy);
+ Assert.Single(candidates);
+ Assert.Equal(Original, candidates[0]);
+ }
+
+ [Fact]
+ public void ValidProxy_IsTriedFirst_ThenDirect()
+ {
+ var candidates = DeskBox.Services.ForkDownloadProxySettings.GetDownloadCandidates(Original, "https://gh-proxy.com");
+ Assert.Equal(2, candidates.Count);
+ Assert.Equal("gh-proxy.com", candidates[0].Host);
+ Assert.Equal(Original, candidates[1]);
+ }
+}
From 8168134b597d0ae8461ffb87c02e8a412867643a Mon Sep 17 00:00:00 2001
From: GOXF <131693427+GOXF@users.noreply.github.com>
Date: Sun, 8 Nov 2026 05:04:14 +0000
Subject: [PATCH 2/2] fix: missing using DeskBox.Models
---
src/DeskBox/Services/AppUpdateService.ForkDownload.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/DeskBox/Services/AppUpdateService.ForkDownload.cs b/src/DeskBox/Services/AppUpdateService.ForkDownload.cs
index 8f6b197a9..029e632a6 100644
--- a/src/DeskBox/Services/AppUpdateService.ForkDownload.cs
+++ b/src/DeskBox/Services/AppUpdateService.ForkDownload.cs
@@ -1,4 +1,5 @@
using System.Security.Cryptography;
+using DeskBox.Models;
namespace DeskBox.Services;