-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdateDialog.cs
More file actions
912 lines (819 loc) · 39.6 KB
/
UpdateDialog.cs
File metadata and controls
912 lines (819 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Reflection;
using System.Security.Cryptography;
using System.Text.Json;
namespace MWBToggle;
/// <summary>
/// Manual update checker — no telemetry, no background requests.
/// User clicks the button, we check GitHub once, download if needed.
/// </summary>
internal sealed class UpdateDialog : Form
{
private static readonly HttpClient _http = CreateHttpClient();
private readonly Label _lblStatus;
private readonly Label _lblDetail;
private readonly Panel _progressOuter;
private readonly Panel _progressFill;
private readonly Button _btnAction;
private readonly Button _btnCancel;
private CancellationTokenSource? _cts;
private string? _remoteVersion;
private string? _downloadUrl;
private string? _hashFileUrl;
private readonly Font _boldFont;
private readonly Font _italicFont;
private readonly System.Windows.Forms.Timer _marqueeTimer;
private int _marqueePos;
private bool _marqueeForward = true;
private const string AppName = "MWBToggle";
private const string GitHubRepo = "itsnateai/MousewithoutBordersToggle";
// First version tag that emits a SHA256SUMS release asset (commit 6f7f1db).
// For any remote version >= this, a missing SHA256SUMS is treated as a
// supply-chain error and the update is aborted. Older releases are
// grandfathered so existing users on pre-2.5.0 can still self-update.
private static readonly Version FIRST_HASH_EMITTING_VERSION = new Version(2, 5, 0);
public UpdateDialog()
{
Text = $"{AppName} — Update";
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false;
MinimizeBox = false;
StartPosition = FormStartPosition.CenterScreen;
TopMost = true;
BackColor = Theme.BgColor;
ForeColor = Theme.FgColor;
// Pin design baseline to 96 DPI BEFORE setting AutoScaleMode so every
// Size/Point literal below is interpreted as 96-DPI design pixels. The
// Form base default is AutoScaleMode.Font, which scales by Font.Height
// ratio and diverges from PerMonitorV2's pixel scaling on non-integer
// DPI ratios; switching to Dpi aligns this dialog with the rest of the app.
AutoScaleDimensions = new SizeF(96F, 96F);
AutoScaleMode = AutoScaleMode.Dpi;
ClientSize = new Size(420, 180);
_boldFont = new Font("Segoe UI", 9.5f, FontStyle.Bold);
_italicFont = new Font("Segoe UI", 7.5f, FontStyle.Italic);
_lblStatus = new Label
{
Text = "Checking GitHub for new version...",
Location = new Point(20, 20),
Size = new Size(370, 24),
Font = _boldFont,
ForeColor = Theme.FgColor,
BackColor = Theme.BgColor,
TextAlign = ContentAlignment.MiddleCenter
};
Controls.Add(_lblStatus);
_lblDetail = new Label
{
Text = "",
Location = new Point(20, 48),
Size = new Size(370, 20),
ForeColor = Theme.DimColor,
BackColor = Theme.BgColor,
Font = _italicFont,
TextAlign = ContentAlignment.MiddleCenter
};
Controls.Add(_lblDetail);
_progressOuter = new Panel
{
Location = new Point(30, 80),
Size = new Size(350, 18),
BackColor = Theme.HighlightBg,
BorderStyle = BorderStyle.None
};
_progressFill = new Panel
{
Location = new Point(0, 0),
Size = new Size(0, 18),
BackColor = Theme.AccentGreen
};
_progressOuter.Controls.Add(_progressFill);
Controls.Add(_progressOuter);
_btnAction = new Button
{
Text = "Upgrade Now",
Location = new Point(155, 112),
Size = new Size(110, 32),
Visible = false,
AccessibleName = "Download and install the latest version"
};
ThemeButton(_btnAction);
_btnAction.Click += OnActionClick;
Controls.Add(_btnAction);
_btnCancel = new Button
{
Text = "Cancel",
Location = new Point(295, 112),
Size = new Size(80, 32),
AccessibleName = "Cancel update check"
};
ThemeButton(_btnCancel);
_btnCancel.Click += (_, _) =>
{
try { _cts?.Cancel(); }
catch (ObjectDisposedException) { /* rapid double-click race with Dispose */ }
DialogResult = DialogResult.Cancel;
Close();
};
Controls.Add(_btnCancel);
// Enter triggers the currently-primary action (Upgrade Now once visible, nothing
// before that), Esc always cancels and disposes the in-flight HTTP request.
AcceptButton = _btnAction;
CancelButton = _btnCancel;
_marqueeTimer = new System.Windows.Forms.Timer { Interval = 30 };
_marqueeTimer.Tick += (_, _) =>
{
// step + barW are design-pixel values; walk them through the current
// monitor DPI each tick so animation pace + bar width stay proportional
// at 125%+. Cost is two int property reads — negligible at 30 ms cadence.
// _progressOuter.Width and .Height are already AutoScale-walked device
// pixels, so they bound and size the fill directly.
int step = _progressOuter.LogicalToDeviceUnits(4);
int barW = _progressOuter.LogicalToDeviceUnits(80);
if (_marqueeForward) _marqueePos += step; else _marqueePos -= step;
if (_marqueePos + barW >= _progressOuter.Width) _marqueeForward = false;
if (_marqueePos <= 0) _marqueeForward = true;
_progressFill.Location = new Point(_marqueePos, 0);
_progressFill.Size = new Size(barW, _progressOuter.Height);
};
Shown += async (_, _) => await CheckForUpdateAsync();
}
private static HttpClient CreateHttpClient()
{
var version = Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "0.0.0";
// Disable auto-redirect: the default handler follows redirects WITHOUT re-checking
// each hop against the allowlist, which would let an allowlisted origin (e.g. the
// GitHub API) hand off to an attacker-controlled CDN via a crafted 3xx. We follow
// manually below, validating each hop.
var handler = new HttpClientHandler { AllowAutoRedirect = false };
var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
// Cap the in-memory response buffer for ReadAsStringAsync calls (releases
// JSON, SHA256SUMS body). The default ceiling is ~2 GB; tighten to 1 MB
// so a hostile CDN edge can't blow up the tray with an unbounded text
// body. Streaming downloads (DownloadFileAsync) use a separate per-write
// ceiling — see MaxDownloadBytes. 2026-04-25 verifier follow-up.
client.MaxResponseContentBufferSize = 1L * 1024 * 1024;
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(AppName, version));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
return client;
}
// Host-based allowlist validated at every redirect hop via SendAllowlistedAsync.
// Replaces a prior `string[] UrlAllowlist + StartsWith` prefix check with
// Uri parsing + host-equality so malformed URLs (mixed-case scheme,
// embedded whitespace, weird userinfo) can't slip through, and so repo
// scoping on github.com / api.github.com is checked against AbsolutePath
// rather than the raw URL string. Pattern lifted from MicMute / CapsNumTray
// (host-equality canonical). v2.5.19 upgrade.
//
// GitHub release-asset CDN: both `objects.githubusercontent.com` (legacy)
// and `release-assets.githubusercontent.com` (new edge, rolled alongside)
// appear in the wild as redirect targets for github.com/.../releases/download.
// Keeping both keeps self-update working through the rollout.
internal static bool IsAllowedHost(Uri uri, bool allowApi)
{
if (uri.Scheme != Uri.UriSchemeHttps) return false;
string host = uri.Host;
if (host.Equals("objects.githubusercontent.com", StringComparison.OrdinalIgnoreCase))
return true;
if (host.Equals("release-assets.githubusercontent.com", StringComparison.OrdinalIgnoreCase))
return true;
if (host.Equals("github.com", StringComparison.OrdinalIgnoreCase))
return uri.AbsolutePath.StartsWith($"/{GitHubRepo}/", StringComparison.OrdinalIgnoreCase);
if (allowApi && host.Equals("api.github.com", StringComparison.OrdinalIgnoreCase))
return uri.AbsolutePath.StartsWith($"/repos/{GitHubRepo}/", StringComparison.OrdinalIgnoreCase);
return false;
}
internal static bool IsAllowlisted(string? url) =>
!string.IsNullOrEmpty(url) &&
Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
IsAllowedHost(uri, allowApi: true);
/// <summary>
/// Extract the hex hash for <paramref name="filename"/> from a SHA256SUMS body.
/// Handles GNU-coreutils format (`hexhash filename` or `hexhash *filename`),
/// BSD-tag format (`SHA256 (filename) = hexhash`), CRLF line endings, multi-entry
/// files, and tab separators. Filename match is case-insensitive. Returns null if
/// no entry for the file is found OR if the parsed hash isn't a 64-char lowercase-or
/// -uppercase hex string (defends against malformed SHA256SUMS bodies — the parser
/// is the actual trust-decision input for self-update).
/// </summary>
internal static string? ParseHashFor(string? content, string filename)
{
if (string.IsNullOrEmpty(content) || string.IsNullOrEmpty(filename)) return null;
foreach (var rawLine in content.Split('\n'))
{
var line = rawLine.TrimEnd('\r').Trim();
if (line.Length == 0) continue;
string? candidate = null;
// BSD-tag format: SHA256 (filename) = hexhash
if (line.StartsWith("SHA256 (", StringComparison.OrdinalIgnoreCase))
{
int lparen = line.IndexOf('(');
int rparen = line.IndexOf(')');
int eq = line.IndexOf('=');
if (lparen >= 0 && rparen > lparen && eq > rparen)
{
var name = line.Substring(lparen + 1, rparen - lparen - 1).Trim();
if (name.Equals(filename, StringComparison.OrdinalIgnoreCase))
candidate = line.Substring(eq + 1).Trim();
}
}
else
{
// GNU-coreutils format: "hexhash filename" or "hexhash *filename"
// (binary-mode emit). Tab separator also seen in the wild.
var parts = line.Split(new[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2 &&
parts[1].Trim().TrimStart('*').Equals(filename, StringComparison.OrdinalIgnoreCase))
{
candidate = parts[0].Trim();
}
}
if (candidate != null && IsValidSha256Hex(candidate))
return candidate;
}
return null;
}
// SHA-256 produces 32 bytes = 64 hex chars. Reject anything else so a malformed
// SHA256SUMS body (truncated, non-hex, empty after `=`) can't reach the equality
// compare and silently fall into the "no entry" branch by accident.
private static bool IsValidSha256Hex(string s)
{
if (s.Length != 64) return false;
foreach (var c in s)
{
bool isHex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
if (!isHex) return false;
}
return true;
}
/// <summary>
/// Issue a GET and follow up to 5 redirects manually. Every hop's URL — including
/// the initial one — is validated against <see cref="IsAllowlisted(string)"/> before
/// the request is sent. Throws if any hop lands off-list or if the redirect chain
/// exceeds the hop limit.
/// </summary>
private static async Task<HttpResponseMessage> SendAllowlistedAsync(
string url, HttpCompletionOption completion, CancellationToken ct)
{
const int maxHops = 5;
for (int hop = 0; hop < maxHops; hop++)
{
// Belt-and-suspenders: IsAllowedHost already requires Uri.Scheme == https,
// but a future allowlist edit accidentally accepting http would silently
// disable transport encryption. Independently enforce HTTPS here so
// scheme-downgrade can never happen regardless of allowlist contents.
if (!Uri.TryCreate(url, UriKind.Absolute, out var validatedUri) ||
!validatedUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
throw new HttpRequestException($"URL must be HTTPS: {url}");
if (!IsAllowlisted(url))
throw new HttpRequestException($"URL not in allowlist: {url}");
var response = await _http.GetAsync(url, completion, ct);
int status = (int)response.StatusCode;
if (status >= 300 && status < 400 && response.Headers.Location != null)
{
var next = response.Headers.Location.IsAbsoluteUri
? response.Headers.Location.ToString()
: new Uri(new Uri(url), response.Headers.Location).ToString();
response.Dispose();
url = next;
continue;
}
return response;
}
throw new HttpRequestException($"Too many redirects (>{maxHops}) starting from initial URL.");
}
// ─── Check GitHub ───────────────────────────────────────────
private async Task CheckForUpdateAsync()
{
_cts = new CancellationTokenSource();
// Winget-managed installs should use `winget upgrade` instead of self-update
if (IsWingetManaged())
{
_marqueeTimer.Stop();
_progressOuter.Visible = false;
_lblStatus.Text = "This installation is managed by winget.";
_lblDetail.Text = "Use: winget upgrade itsnateai.MWBToggle";
_btnAction.Visible = false;
_btnCancel.Text = "OK";
// Post-Show reassignments bypass the AutoScale walk — raw literals
// here render in device pixels regardless of monitor DPI, so at
// 125%+ the OK button stays "100%-sized" while the rest of the
// dialog has scaled larger. LogicalToDeviceUnits walks the design
// pixel through the form's current DPI to keep the button
// proportional. Width must be computed first so Location can
// centre against it.
int btnW = _btnCancel.LogicalToDeviceUnits(64);
int btnH = _btnCancel.LogicalToDeviceUnits(26);
_btnCancel.Size = new Size(btnW, btnH);
_btnCancel.Location = new Point((ClientSize.Width - btnW) / 2,
_btnCancel.LogicalToDeviceUnits(112));
return;
}
_marqueeTimer.Start();
try
{
var response = await SendAllowlistedAsync(
$"https://api.github.com/repos/{GitHubRepo}/releases/latest",
HttpCompletionOption.ResponseContentRead,
_cts.Token);
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
var remaining = response.Headers.TryGetValues("X-RateLimit-Remaining", out var vals)
? vals.FirstOrDefault() : null;
ShowError(remaining == "0"
? "GitHub API rate limit reached." : "GitHub API access denied (403).",
remaining == "0" ? "Try again in a few minutes." : "Check your network connection.");
return;
}
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
ShowError("No releases found on GitHub.", "The repository may not have any published releases.");
return;
}
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(_cts.Token);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
_remoteVersion = root.GetProperty("tag_name").GetString()?.TrimStart('v') ?? "";
if (root.TryGetProperty("assets", out var assets))
{
foreach (var asset in assets.EnumerateArray())
{
var name = asset.GetProperty("name").GetString() ?? "";
if (name.Equals("MWBToggle.exe", StringComparison.OrdinalIgnoreCase))
{
_downloadUrl = asset.GetProperty("browser_download_url").GetString() ?? "";
}
if (name.Equals("SHA256SUMS", StringComparison.OrdinalIgnoreCase) ||
name.Equals("SHA256SUMS.txt", StringComparison.OrdinalIgnoreCase))
{
_hashFileUrl = asset.GetProperty("browser_download_url").GetString() ?? "";
}
}
}
if (string.IsNullOrEmpty(_downloadUrl))
{
ShowError("No update package found in the latest release.", "The release may be incomplete.");
return;
}
ShowVersionComparison();
}
catch (TaskCanceledException)
{
if (_cts?.IsCancellationRequested != true)
ShowError("Request timed out.", "Check your internet connection and try again.");
}
catch (HttpRequestException ex)
{
ShowError("Could not reach GitHub.", ex.Message);
}
catch (JsonException)
{
ShowError("Unexpected response from GitHub.", "The API response format may have changed.");
}
catch (Exception ex)
{
ShowError("Update check failed.", ex.Message);
}
}
// ─── Compare Versions ───────────────────────────────────────
private void ShowVersionComparison()
{
_marqueeTimer.Stop();
_progressFill.Size = new Size(0, _progressOuter.Height);
_progressFill.Location = new Point(0, 0);
var localVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "0.0.0";
var isNewer = Version.TryParse(_remoteVersion, out var remote)
&& Version.TryParse(localVersion, out var local)
&& remote > local;
_lblDetail.Text = $"Current: {localVersion} → GitHub: {_remoteVersion}";
_progressOuter.Visible = false;
if (isNewer)
{
_lblStatus.Text = "A new version is available!";
_btnAction.Text = "Upgrade Now";
_btnAction.Visible = true;
_btnCancel.Text = "Cancel";
}
else
{
_lblStatus.Text = "You're on the latest version!";
_btnAction.Visible = false;
_btnCancel.Text = "OK";
// Shrink the OK button for this acknowledgment-only state — a large
// Cancel-sized button makes the simple "you're up to date" popup feel
// heavier than it needs to be. LogicalToDeviceUnits keeps it
// proportional at 125%+ (see winget-managed branch above for the
// post-Show-bypasses-AutoScale rationale).
int btnW = _btnCancel.LogicalToDeviceUnits(64);
int btnH = _btnCancel.LogicalToDeviceUnits(26);
_btnCancel.Size = new Size(btnW, btnH);
_btnCancel.Location = new Point((ClientSize.Width - btnW) / 2,
_btnCancel.LogicalToDeviceUnits(112));
}
}
// ─── Download & Apply ───────────────────────────────────────
private async void OnActionClick(object? sender, EventArgs e)
{
_btnAction.Enabled = false;
_btnCancel.Text = "Cancel";
_progressOuter.Visible = true;
_progressFill.Location = new Point(0, 0);
_lblStatus.Text = $"Downloading {AppName} {_remoteVersion}...";
_cts?.Dispose();
_cts = new CancellationTokenSource();
var exePath = Environment.ProcessPath
?? throw new InvalidOperationException("Cannot determine executable path.");
var newPath = exePath + ".new";
var oldPath = exePath + ".old";
try
{
// Validate download URL origin before fetching. Stricter than the
// general IsAllowlisted: api.github.com is not a release-asset host,
// so allowApi:false here even though the catalogue fetch needed it.
if (!Uri.TryCreate(_downloadUrl, UriKind.Absolute, out var dlUri) ||
!IsAllowedHost(dlUri, allowApi: false))
{
ShowError("Update failed: download URL is not from the expected source.", _downloadUrl!);
return;
}
if (!await DownloadFileAsync(_downloadUrl!, newPath))
return;
// Verify SHA256 hash if the release includes a SHA256SUMS file
if (!string.IsNullOrEmpty(_hashFileUrl))
{
// Tighten the hash-URL origin check to match _downloadUrl above.
// The general IsAllowlisted would also let through api.github.com,
// but a release asset must come from github.com/{repo}/… or the CDN.
if (!Uri.TryCreate(_hashFileUrl, UriKind.Absolute, out var hashUri) ||
!IsAllowedHost(hashUri, allowApi: false))
{
// Stranded `.new` cleanup. The download already wrote `newPath`
// (line ~495); returning here without TryDelete leaves it on disk.
// Pre-existing in the prefix-StartsWith era; preserved by the
// v2.5.19 refactor, caught by v2.5.20 verifier sweep.
TryDelete(newPath);
ShowError("Update failed: hash URL is not from the expected source.", _hashFileUrl);
return;
}
_lblStatus.Text = "Verifying integrity...";
try
{
using var hashResponse = await SendAllowlistedAsync(
_hashFileUrl, HttpCompletionOption.ResponseContentRead, _cts!.Token);
hashResponse.EnsureSuccessStatusCode();
var hashContent = await hashResponse.Content.ReadAsStringAsync(_cts.Token);
string? expectedHash = ParseHashFor(hashContent, "MWBToggle.exe");
if (!string.IsNullOrEmpty(expectedHash))
{
var actualHash = ComputeFileHash(newPath);
if (!actualHash.Equals(expectedHash, StringComparison.OrdinalIgnoreCase))
{
TryDelete(newPath);
ShowError("Hash verification failed.",
"The downloaded file doesn't match the expected SHA256 checksum.");
return;
}
}
else
{
TryDelete(newPath);
ShowError("Hash verification failed.",
"SHA256SUMS file found but contains no entry for MWBToggle.exe.");
return;
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
// SHA256SUMS fetch failed — fail closed. The hash is the primary integrity
// control (the exe is not Authenticode-signed), so we never ship an update
// we couldn't verify.
Logger.Warn($"SHA256SUMS fetch failed: {ex.Message}");
TryDelete(newPath);
ShowError("Hash verification failed.",
"Could not fetch SHA256SUMS. Try again, or run `winget upgrade`.");
return;
}
}
else
{
// Version-gated fail-closed: if the remote release is >= FIRST_HASH_EMITTING_VERSION
// and no SHA256SUMS asset was found, abort rather than installing unverified.
// Grandfathered older releases (<v2.5.0) keep the skip-with-log behavior so users
// upgrading from very old builds can still reach a hash-emitting version safely.
bool isGrandfathered = Version.TryParse(_remoteVersion, out var remoteVer)
&& remoteVer < FIRST_HASH_EMITTING_VERSION;
if (isGrandfathered)
{
Logger.Warn($"Update verify SKIPPED (grandfathered release {_remoteVersion} < {FIRST_HASH_EMITTING_VERSION})");
// continue to apply
}
else
{
TryDelete(newPath);
Logger.Error($"Update aborted: SHA256SUMS missing for release {_remoteVersion} (>= {FIRST_HASH_EMITTING_VERSION}). Fail-closed.");
ShowError("Update integrity file missing.",
$"SHA256SUMS was not found in release {_remoteVersion}. Aborting for security — try `winget upgrade` or download manually.");
return;
}
}
_lblStatus.Text = "Applying update...";
_progressOuter.Visible = false;
TryDelete(oldPath);
if (File.Exists(exePath))
File.Move(exePath, oldPath);
File.Move(newPath, exePath);
// nosemgrep: gitlab.security_code_scan.SCS0001-1 -- exePath is Environment.ProcessPath; the replacement binary was SHA256-verified above against a SHA256SUMS asset from the github.com/itsnateai/ allowlisted origin (fail-closed on missing sums for >= v2.5.0)
using var _ = Process.Start(new ProcessStartInfo(exePath)
{
Arguments = "--after-update",
UseShellExecute = true
});
Application.Exit();
}
catch (IOException ex)
{
// Rollback: restore old exe if possible
if (File.Exists(oldPath))
{
TryDelete(exePath);
try { File.Move(oldPath, exePath); }
catch (Exception rollbackEx) { Logger.Error($"Rollback Move failed (torn state — .old may be stranded): {rollbackEx.Message}"); }
}
TryDelete(newPath);
ShowError(
ex.Message.Contains("being used by another process", StringComparison.OrdinalIgnoreCase)
? "Cannot replace the executable." : "Failed to apply update.",
ex.Message.Contains("being used by another process", StringComparison.OrdinalIgnoreCase)
? "Your antivirus may be locking the file. Try again." : ex.Message);
}
catch (TaskCanceledException)
{
if (File.Exists(oldPath))
{
TryDelete(exePath);
try { File.Move(oldPath, exePath); }
catch (Exception rollbackEx) { Logger.Error($"Rollback Move failed (torn state — .old may be stranded): {rollbackEx.Message}"); }
}
TryDelete(newPath);
if (!IsDisposed) ShowVersionComparison();
}
catch (Exception ex)
{
if (File.Exists(oldPath))
{
TryDelete(exePath);
try { File.Move(oldPath, exePath); }
catch (Exception rollbackEx) { Logger.Error($"Rollback Move failed (torn state — .old may be stranded): {rollbackEx.Message}"); }
}
TryDelete(newPath);
if (!IsDisposed) ShowError("Update failed.", ex.Message);
}
}
// Hard ceiling on a single download. The legitimate self-contained release
// is ~150 MB; 200 MB gives ~33% headroom for asset growth without giving a
// compromised CDN edge unbounded write authority. Without this cap, a
// hostile Content-Length: 50_000_000_000 (or chunked-transfer with no
// Content-Length at all) could fill the user's disk inside the 30s
// HttpClient.Timeout window before the SHA256 verify step fires.
internal const long MaxDownloadBytes = 200L * 1024 * 1024;
/// <summary>
/// True when an asserted download size is within the per-file ceiling.
/// Negative or zero is ALLOWED here (caller handles "no Content-Length"
/// separately by streaming + counting); the ceiling test is a "is this
/// number too big" gate, not a "is this number sane" gate.
/// </summary>
internal static bool IsAllowedDownloadSize(long bytes) =>
bytes <= MaxDownloadBytes;
private async Task<bool> DownloadFileAsync(string url, string destPath)
{
using var response = await SendAllowlistedAsync(url, HttpCompletionOption.ResponseHeadersRead, _cts!.Token);
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength ?? 0;
// Header-side gate: if the server tells us up-front that the body
// exceeds the ceiling, fail-closed before opening the destination file.
if (!IsAllowedDownloadSize(totalBytes))
{
ShowError("Download too large.",
$"Server reports {totalBytes:N0} bytes; max is {MaxDownloadBytes:N0}.");
return false;
}
await using var contentStream = await response.Content.ReadAsStreamAsync(_cts.Token);
await using var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920);
var buffer = new byte[81920];
long downloaded = 0;
int read;
while ((read = await contentStream.ReadAsync(buffer, _cts.Token)) > 0)
{
await fileStream.WriteAsync(buffer.AsMemory(0, read), _cts.Token);
downloaded += read;
// Mid-stream gate: defends against chunked-transfer bodies (no
// Content-Length up front) that stream forever within the
// HttpClient.Timeout window. Header check above missed this case
// because totalBytes was 0.
if (downloaded > MaxDownloadBytes)
{
TryDelete(destPath);
ShowError("Download exceeded size limit.",
$"Got {downloaded:N0} bytes; max is {MaxDownloadBytes:N0}.");
return false;
}
if (totalBytes > 0 && !IsDisposed) BeginInvoke(() =>
{
if (IsDisposed) return;
int pct = (int)(downloaded * 100 / totalBytes);
_progressFill.Size = new Size(
(int)(_progressOuter.Width * downloaded / totalBytes),
_progressOuter.Height);
var dlMB = downloaded / (1024.0 * 1024.0);
var totalMB = totalBytes / (1024.0 * 1024.0);
_lblDetail.Text = totalMB < 1
? $"{pct}% ({downloaded / 1024.0:F0} / {totalBytes / 1024.0:F0} KB)"
: $"{pct}% ({dlMB:F0} / {totalMB:F0} MB)";
});
}
if (totalBytes > 0 && downloaded != totalBytes)
{
TryDelete(destPath);
ShowError("Download was incomplete.",
$"Expected {totalBytes:N0} bytes, got {downloaded:N0}.");
return false;
}
// Minimum size sanity check — reject truncated/empty downloads
if (downloaded < 100_000)
{
TryDelete(destPath);
ShowError("Downloaded file is too small.",
$"Got {downloaded:N0} bytes — expected a valid executable.");
return false;
}
return true;
}
// ─── Error ──────────────────────────────────────────────────
private void ShowError(string message, string detail)
{
_marqueeTimer.Stop();
_progressOuter.Visible = false;
_lblStatus.Text = message;
_lblStatus.ForeColor = Theme.AccentWarn;
_lblDetail.Text = detail;
_btnAction.Visible = false;
_btnCancel.Text = "OK";
// Centre the lone OK button at runtime device pixels — _btnCancel.Width
// is already AutoScale-walked from its constructor Size, and Y must be
// scaled from the design literal 112 to keep its position proportional
// at 125%+ (post-Show raw literals bypass the AutoScale walk).
_btnCancel.Location = new Point((ClientSize.Width - _btnCancel.Width) / 2,
_btnCancel.LogicalToDeviceUnits(112));
}
// ─── Static Helpers (called from Program.cs) ────────────────
/// <summary>Detect whether the app was installed via winget (lives under WinGet\Packages).</summary>
internal static bool IsWingetManaged() =>
(Environment.ProcessPath ?? "").Contains(@"Microsoft\WinGet\Packages", StringComparison.OrdinalIgnoreCase);
/// <summary>Clean up .old/.new artifacts from a previous update.</summary>
/// <remarks>
/// Rollback safety: .old is kept until the new version proves itself by writing
/// a .ok sentinel (see <see cref="WriteStartupSentinel"/>). If the new exe crashes
/// before the sentinel is written, .old survives for manual recovery.
/// </remarks>
internal static void CleanupUpdateArtifacts()
{
var exePath = Environment.ProcessPath;
if (string.IsNullOrEmpty(exePath)) return;
// Torn-state recovery: if update was interrupted between moving exe→.old
// and .new→exe, the exe is gone but .old still has the previous version.
if (!File.Exists(exePath))
{
var oldPath = exePath + ".old";
if (File.Exists(oldPath))
{
try { File.Move(oldPath, exePath); }
catch (Exception ex) { Logger.Warn($"Torn-state restore failed: {ex.Message}"); }
}
return;
}
// Always safe to remove a stray .new (half-downloaded from a cancelled update).
TryDelete(exePath + ".new");
// Only remove .old once the new version has successfully started once (sentinel present).
var okSentinel = exePath + ".ok";
if (File.Exists(okSentinel))
{
TryDelete(exePath + ".old");
}
}
/// <summary>
/// Write a .ok sentinel next to the exe once the new version has successfully
/// reached its running state. CleanupUpdateArtifacts uses this to decide whether
/// it's safe to remove .old — if the new exe crashes before the sentinel is
/// written, .old persists and the user can rename it to recover manually.
/// </summary>
internal static void WriteStartupSentinel()
{
try
{
var exePath = Environment.ProcessPath;
if (string.IsNullOrEmpty(exePath)) return;
var sentinel = exePath + ".ok";
if (!File.Exists(sentinel))
File.WriteAllText(sentinel, DateTime.UtcNow.ToString("O"));
}
catch (Exception ex)
{
Logger.Warn($"WriteStartupSentinel: {ex.Message}");
}
}
/// <summary>Show a brief floating toast near the system tray after a successful update.</summary>
internal static void ShowUpdateToast()
{
var version = Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "?";
var timer = new System.Windows.Forms.Timer { Interval = 1500 };
timer.Tick += (_, _) =>
{
timer.Stop();
timer.Dispose();
var toast = new Form
{
// Pin design baseline to 96 DPI BEFORE AutoScaleMode so the
// Padding literal below scales correctly on 125%+ monitors.
AutoScaleDimensions = new SizeF(96F, 96F),
AutoScaleMode = AutoScaleMode.Dpi,
FormBorderStyle = FormBorderStyle.None,
ShowInTaskbar = false,
TopMost = true,
StartPosition = FormStartPosition.Manual,
// Theme.HighlightBg = elevated-pill bg, matches OsdForm's choice.
// Invoked from MWBToggleApp's restoreTimer after Theme.Initialize
// has run, so this captures the user's active palette.
BackColor = Theme.HighlightBg,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
Padding = new Padding(12, 8, 12, 8)
};
var toastFont = new Font("Segoe UI", 9.5f, FontStyle.Bold);
var lbl = new Label
{
Text = $"{AppName} updated to v{version}",
AutoSize = true,
Font = toastFont,
ForeColor = Theme.FgColor,
BackColor = Theme.HighlightBg,
};
toast.Controls.Add(lbl);
toast.FormClosed += (_, _) => toastFont.Dispose();
var screen = (Screen.PrimaryScreen ?? Screen.AllScreens[0]).WorkingArea;
toast.Load += (_, _) =>
toast.Location = new Point(screen.Right - toast.Width - 20, screen.Bottom - toast.Height - 20);
toast.Show();
var dismiss = new System.Windows.Forms.Timer { Interval = 5000 };
dismiss.Tick += (_, _) =>
{
dismiss.Stop();
dismiss.Dispose();
toast.Close();
};
dismiss.Start();
};
timer.Start();
}
// ─── Helpers ────────────────────────────────────────────────
private static void ThemeButton(Button btn)
{
btn.FlatStyle = FlatStyle.Flat;
btn.ForeColor = Theme.FgColor;
btn.BackColor = Theme.BgColor;
btn.FlatAppearance.BorderColor = Theme.DividerColor;
btn.FlatAppearance.MouseOverBackColor = Theme.HighlightBg;
btn.FlatAppearance.MouseDownBackColor = Theme.EditBgColor;
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
Theme.ApplyTitleBarMode(Handle);
}
private static void TryDelete(string path)
{
try { if (File.Exists(path)) File.Delete(path); }
catch (Exception ex) { Logger.Warn($"TryDelete({path}): {ex.Message}"); }
}
private static string ComputeFileHash(string filePath)
{
using var stream = File.OpenRead(filePath);
var hashBytes = SHA256.HashData(stream);
return Convert.ToHexString(hashBytes).ToLowerInvariant();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_boldFont?.Dispose();
_italicFont?.Dispose();
_marqueeTimer.Stop();
_marqueeTimer.Dispose();
try { _cts?.Cancel(); } catch (ObjectDisposedException) { }
try { _cts?.Dispose(); } catch (ObjectDisposedException) { }
}
base.Dispose(disposing);
}
}