Repository navigation
Expand file tree
/
Copy pathupdater.rs
More file actions
1125 lines (1054 loc) · 40.4 KB
/
Copy pathupdater.rs
File metadata and controls
1125 lines (1054 loc) · 40.4 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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Hex's in-app updater on every OS, a client of the Anomaly release service
//! (`docs/plans/release-service.md`). One worker polls the channel's manifest
//! 10 seconds after launch, then hourly or on "Check for updates", decides with the
//! protocol's client rules, and for a direct install downloads the target,
//! checks its size, SHA-256, and OS code signature, and stages it until the
//! user restarts. Checks continue while an update is staged, so a newer
//! release replaces it, and Restart to update checks once more before it
//! switches over. Versions are display text and never compared: whenever the
//! channel's current release is not the running build (its target SHA-256,
//! else its exact version), Hex takes it, and switching channels does so
//! after the user confirms. Package-managed installs only learn the command to run;
//! source builds, test builds, and installs whose administrator set
//! `DisableUpdates` never check. Manifests are not signed: HTTPS, the
//! manifest's SHA-256, and (macOS, Windows) the code signature are the
//! integrity checks.
#[cfg_attr(target_os = "linux", path = "updater/linux.rs")]
#[cfg_attr(target_os = "macos", path = "updater/macos.rs")]
#[cfg_attr(target_os = "windows", path = "updater/windows.rs")]
mod platform;
pub mod protocol;
mod transport;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
use color_eyre::eyre::{Result, WrapErr, eyre};
use crate::app_settings::{AppSettings, UpdateChannel};
use crate::desktop_host::{DesktopAction, DesktopUpdateStatus};
use protocol::{Decision, Install};
use platform::Staged;
#[cfg(target_os = "macos")]
pub use platform::finish_on_launch;
const APP: &str = "hex";
const ARTIFACT: &str = "desktop";
const ORIGIN: &str = "https://anoma.ly/release";
const STARTUP_DELAY: Duration = Duration::from_secs(10);
const CHECK_INTERVAL: Duration = Duration::from_secs(60 * 60);
/// Dev builds land on every push to dev, so the Dev channel checks often.
const DEV_CHECK_INTERVAL: Duration = Duration::from_secs(10 * 60);
/// Opening or focusing the window checks the Dev channel at most this often.
const FOCUS_CHECK_GAP: Duration = Duration::from_secs(60);
/// Failed checks back off, but never past hourly: the release service counts
/// a running install from at least one check an hour.
const MAX_BACKOFF: Duration = CHECK_INTERVAL;
/// The manifest fetch of an ordinary check.
const MANIFEST_TIMEOUT: Duration = Duration::from_secs(60);
/// The final check behind Restart to update: an unreachable service must
/// not hold the restart for long.
const RESTART_MANIFEST_TIMEOUT: Duration = Duration::from_secs(15);
/// How this install receives updates, which decides what the updater does.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Method {
/// Our installer's receipt (or, on macOS, a writable `Hex.app`): Hex
/// downloads and stages updates itself on this channel.
Direct { channel: String },
/// A direct install Hex cannot replace (macOS: a read-only or translocated
/// location); updates link to the download.
DownloadOnly,
/// A package manager (`aur`, `deb-x64`, `rpm-arm64`, `nix`, `brew`, …) updates
/// it; Hex shows its command once it serves a newer version.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
Package(&'static str),
/// Built from a checkout, which updates it.
Source,
/// Anything else, such as a downloaded executable run in place.
#[cfg_attr(target_os = "macos", allow(dead_code))]
Unknown,
}
impl Method {
fn distribution(&self) -> &str {
match self {
Self::Direct { .. } | Self::DownloadOnly => "direct",
Self::Package(kind) => kind,
Self::Source | Self::Unknown => "unknown",
}
}
fn channel(&self) -> &str {
match self {
Self::Direct { channel } => channel,
_ => "stable",
}
}
}
/// The channel the Release workflow published this build on, stamped at
/// build time beside its version (`HEX_BUILD_CHANNEL`).
const BUILD_CHANNEL: Option<&str> = option_env!("HEX_BUILD_CHANNEL");
/// The channel this build belongs to: the one it was published on, else
/// (builds from before the stamp) `dev` for a dev version, else the
/// install's own channel. Package managers follow `stable`.
fn home_channel(method: &Method, built: Option<&str>, version: &str) -> String {
if matches!(method, Method::Package(_)) {
return method.channel().into();
}
match built.filter(|channel| ["stable", "beta", "dev"].contains(channel)) {
Some(channel) => channel.into(),
None if is_dev_version(version) => UpdateChannel::Dev.name().into(),
None => method.channel().into(),
}
}
/// The channel to check: the `updates.channel` setting, else the build's
/// own. Package managers follow `stable`. A setting other than the build's
/// channel makes the decision a switch, which waits for the user.
fn channel(method: &Method, setting: Option<UpdateChannel>, home: &str) -> String {
match setting {
Some(channel) if !matches!(method, Method::Package(_)) => channel.name().into(),
_ => home.into(),
}
}
/// Dev builds are `0.0.0-dev-<run>` (`X.Y.Z-dev.N` before 2026-10-27).
fn is_dev_version(version: &str) -> bool {
version.contains("-dev")
}
/// The control that confirms a channel switch, e.g. "Switch to Stable 2.3.1".
pub fn switch_label(channel: &str, version: &str) -> String {
let channel = match channel {
"dev" => UpdateChannel::Dev.label(),
"stable" => UpdateChannel::Stable.label(),
other => other,
};
crate::desktop_i18n::tr_named(
"Switch to {channel} {version}",
&[
("channel", crate::desktop_i18n::tr(channel)),
("version", version),
],
)
}
/// The Update channel Settings shows when none is saved: this build's own.
pub fn build_channel() -> UpdateChannel {
let home = home_channel(&Method::Unknown, BUILD_CHANNEL, crate::VERSION);
if home == UpdateChannel::Dev.name() {
UpdateChannel::Dev
} else {
UpdateChannel::Stable
}
}
#[derive(Clone, Debug)]
enum State {
Disabled(DesktopUpdateStatus),
Checking,
Current,
Failed,
Downloading,
/// `Shared::staged` waits for the restart.
Ready,
/// Switched over; the restart is under way.
Applied,
/// A newer release this install cannot apply itself.
Download {
url: String,
},
/// The setting names another channel, whose current release waits for
/// the user to confirm the switch.
Switch {
channel: String,
version: String,
sha256: String,
},
/// The package manager serves another version.
Command {
command: String,
},
}
struct Shared {
state: Mutex<State>,
/// A package manager installed Hex, so "up to date" is its to say.
packaged: bool,
/// Set by "Check for updates" and `stop`; the worker waits on it between checks.
wake: Mutex<Wake>,
signal: Condvar,
/// The channel and start of the latest check.
last: Mutex<Option<(String, std::time::Instant)>>,
/// The SHA-256 of the other channel's release the user agreed to switch to.
confirmed: Mutex<Option<String>>,
/// The newest staged update. Checks continue while one waits, and a
/// different current release replaces it before the restart.
staged: Mutex<Option<StagedUpdate>>,
restart: Mutex<Restart>,
}
impl Shared {
fn new(state: State, packaged: bool) -> Self {
Self {
state: Mutex::new(state),
packaged,
wake: Mutex::new(Wake::default()),
signal: Condvar::new(),
last: Mutex::new(None),
confirmed: Mutex::new(None),
staged: Mutex::new(None),
restart: Mutex::new(Restart::Idle),
}
}
}
/// A staged update and the SHA-256 of the target it came from, which tells
/// a later check whether the channel still offers that release.
#[derive(Clone, Debug)]
struct StagedUpdate {
staged: Staged,
sha256: String,
}
#[derive(Debug, Default)]
enum Restart {
#[default]
Idle,
/// Restart to update was pressed: the worker checks the channel once
/// more, then switches to the newest staged update.
Requested,
/// The worker switched over (the host quits) or could not.
Done(std::result::Result<(), String>),
}
#[derive(Default)]
struct Wake {
check: bool,
stop: bool,
}
#[derive(Clone)]
pub struct Updater {
shared: Arc<Shared>,
}
impl Updater {
pub fn start() -> Self {
let method = platform::method();
let disabled = if option_env!("HEX_TEST_BUILD") == Some("1") {
Some(DesktopUpdateStatus::Unavailable)
} else if crate::app_paths::is_local_build() {
Some(DesktopUpdateStatus::SourceBuild)
} else if managed_by_policy() {
Some(DesktopUpdateStatus::Managed)
} else if method == Method::Source {
Some(DesktopUpdateStatus::SourceBuild)
} else {
None
};
let checks = disabled.is_none();
let shared = Arc::new(Shared::new(
match disabled {
Some(status) => State::Disabled(status),
None => State::Checking,
},
matches!(method, Method::Package(_)),
));
if checks {
let worker = shared.clone();
if let Err(error) = std::thread::Builder::new()
.name("updater".into())
.spawn(move || run(&worker, &method))
{
tracing::error!(%error, "could not start the updater");
*lock(&shared.state) = State::Failed;
}
}
Self { shared }
}
/// An updater with no worker in the Current state, for tests of when it
/// asks for a check.
#[cfg(test)]
fn idle_checking() -> Self {
Self {
shared: Arc::new(Shared::new(State::Current, false)),
}
}
/// An updater that never checks, for tests of the hosts that own one.
#[cfg(all(test, target_os = "linux"))]
pub fn idle() -> Self {
Self {
shared: Arc::new(Shared::new(
State::Disabled(DesktopUpdateStatus::Unavailable),
false,
)),
}
}
/// Checks now instead of at the next interval. A staged update stays
/// offered while the check looks for a newer release.
pub fn check_now(&self) {
let mut state = lock(&self.shared.state);
match &*state {
State::Disabled(_) | State::Applied | State::Downloading => return,
State::Ready => {}
_ => *state = State::Checking,
}
drop(state);
self.wake();
}
fn wake(&self) {
lock(&self.shared.wake).check = true;
self.shared.signal.notify_all();
}
/// The window opened or gained focus: on the Dev channel, check now
/// unless a check started within the last minute.
pub fn window_focused(&self) {
let recent = lock(&self.shared.last)
.as_ref()
.is_some_and(|(channel, at)| channel != "dev" || at.elapsed() < FOCUS_CHECK_GAP);
if !recent {
self.check_now();
}
}
pub fn stop(&self) {
lock(&self.shared.wake).stop = true;
self.shared.signal.notify_all();
}
pub fn status(&self) -> DesktopUpdateStatus {
match &*lock(&self.shared.state) {
State::Disabled(status) => status.clone(),
// A package manager updates Hex: its own checks only look for
// the manager's command, so they show nothing of their own.
State::Checking | State::Current | State::Failed if self.shared.packaged => {
DesktopUpdateStatus::PackageManager
}
State::Checking => DesktopUpdateStatus::Checking,
State::Current => DesktopUpdateStatus::Current,
State::Failed => DesktopUpdateStatus::Failed,
State::Downloading => DesktopUpdateStatus::Downloading,
State::Ready | State::Applied => DesktopUpdateStatus::ReadyToRestart,
State::Download { .. } => DesktopUpdateStatus::Available,
State::Switch {
channel, version, ..
} => DesktopUpdateStatus::SwitchAvailable {
channel: channel.clone(),
version: version.clone(),
},
State::Command { command } => DesktopUpdateStatus::PackageUpdate {
command: command.clone(),
},
}
}
/// Carries out an update control: check now, open the download, or
/// restart into the staged update. A restart finishes on the worker;
/// [`Self::take_restart`] says when Hex must quit.
pub fn act(&self, action: &DesktopAction) -> Result<()> {
match action {
DesktopAction::CheckForUpdates => self.check_now(),
DesktopAction::WindowFocused => self.window_focused(),
DesktopAction::OpenUpdate => self.open_download(),
DesktopAction::ConfirmUpdateSwitch => self.confirm_switch(),
DesktopAction::RestartIntoUpdate => self.request_restart()?,
_ => {}
}
Ok(())
}
/// Restart to update: the worker checks the channel once more, so a
/// release published since the update was staged replaces it first,
/// then switches to the newest staged update.
fn request_restart(&self) -> Result<()> {
let mut state = lock(&self.shared.state);
let mut restart = lock(&self.shared.restart);
// A second click while the restart is under way changes nothing.
if matches!(*restart, Restart::Requested) || matches!(*state, State::Applied) {
return Ok(());
}
if !matches!(*state, State::Ready) {
return Err(eyre!("no update is ready"));
}
*restart = Restart::Requested;
*state = State::Checking;
drop(restart);
drop(state);
self.wake();
Ok(())
}
/// The outcome of Restart to update, once: `Ok` when the update starts
/// as soon as Hex quits, which the caller must now do.
pub fn take_restart(&self) -> Option<Result<()>> {
let mut restart = lock(&self.shared.restart);
if !matches!(*restart, Restart::Done(_)) {
return None;
}
match std::mem::take(&mut *restart) {
Restart::Done(result) => Some(result.map_err(|error| eyre!(error))),
Restart::Idle | Restart::Requested => None,
}
}
/// The action of a single "update" menu item, which follows the status.
#[cfg(target_os = "macos")]
pub fn menu_action(&self) -> DesktopAction {
match self.status() {
DesktopUpdateStatus::ReadyToRestart => DesktopAction::RestartIntoUpdate,
DesktopUpdateStatus::Available => DesktopAction::OpenUpdate,
DesktopUpdateStatus::SwitchAvailable { .. } => DesktopAction::ConfirmUpdateSwitch,
_ => DesktopAction::CheckForUpdates,
}
}
/// The user agreed to switch to the other channel's release on offer:
/// download and stage it now.
fn confirm_switch(&self) {
let State::Switch { sha256, .. } = lock(&self.shared.state).clone() else {
return;
};
*lock(&self.shared.confirmed) = Some(sha256);
self.check_now();
}
/// Opens the download an install that cannot update itself needs.
fn open_download(&self) {
let State::Download { url } = lock(&self.shared.state).clone() else {
return;
};
if let Err(error) = crate::opencode_catalog::open_url(&url) {
tracing::warn!(%error, "could not open the Hex download");
}
}
/// Quitting with an update ready installs it for the next launch; the
/// other platforms activate it when it is staged.
#[cfg(target_os = "macos")]
pub fn install_on_quit(&self) {
let mut state = lock(&self.shared.state);
if matches!(*state, State::Applied) {
return;
}
if let Some(update) = lock(&self.shared.staged).as_ref() {
platform::install_on_quit(&update.staged);
*state = State::Applied;
}
}
}
/// Whether an administrator turned updates off (`DisableUpdates`), read
/// once per launch so a managed value applies at the next one.
pub fn managed_by_policy() -> bool {
static MANAGED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*MANAGED.get_or_init(platform::updates_disabled_by_policy)
}
/// Shown in place of update actions when an administrator turned them off.
#[cfg(target_os = "macos")]
pub const MANAGED_LABEL: &str = "Updates Managed by Your Organization";
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|error| error.into_inner())
}
/// Waits `delay` or until woken; true when the updater should stop.
fn wait(shared: &Shared, delay: Duration) -> bool {
let mut wake = lock(&shared.wake);
let deadline = std::time::Instant::now() + delay;
while !wake.check && !wake.stop {
let now = std::time::Instant::now();
if now >= deadline {
break;
}
wake = shared
.signal
.wait_timeout(wake, deadline - now)
.unwrap_or_else(|error| error.into_inner())
.0;
}
wake.check = false;
wake.stop
}
/// How often a channel is checked: Dev every few minutes, others hourly.
fn check_interval(channel: &str) -> Duration {
if channel == "dev" {
DEV_CHECK_INTERVAL
} else {
CHECK_INTERVAL
}
}
fn run(shared: &Shared, method: &Method) {
let mut cache = transport::ManifestCache::default();
let mut failures = 0;
if wait(shared, STARTUP_DELAY) {
return;
}
loop {
let restarting = matches!(*lock(&shared.restart), Restart::Requested);
let staged = lock(&shared.staged).clone();
{
// A staged update stays offered while the check runs.
let mut state = lock(&shared.state);
if !matches!(*state, State::Ready) {
*state = State::Checking;
}
}
let result = check(shared, method, &mut cache, staged.as_ref(), restarting);
let interval = lock(&shared.last)
.as_ref()
.map_or(CHECK_INTERVAL, |(channel, _)| check_interval(channel));
let (next, delay) = match result {
Ok(next) => {
failures = 0;
(next, interval)
}
Err(error) => {
tracing::warn!(error = %format!("{error:#}"), "update check failed");
failures = (failures + 1).min(8);
let next = if lock(&shared.staged).is_some() {
State::Ready
} else {
State::Failed
};
(next, (interval * 2u32.pow(failures)).min(MAX_BACKOFF))
}
};
if restarting {
if finish_restart(shared, next) {
return;
}
} else {
let mut state = lock(&shared.state);
// Restart to update was pressed during this check: the next
// check, which starts at once, finishes it.
if !matches!(*lock(&shared.restart), Restart::Requested) {
*state = next;
}
}
if wait(shared, delay) {
return;
}
}
}
/// Switches to the newest staged update once Restart to update's final
/// check has run, whatever its result. True when Hex now quits.
fn finish_restart(shared: &Shared, next: State) -> bool {
let mut state = lock(&shared.state);
let staged = lock(&shared.staged).clone();
let result = match &staged {
Some(update) => {
platform::restart_into(&update.staged).map_err(|error| format!("{error:#}"))
}
None => Err("no update is ready".into()),
};
let restarted = result.is_ok();
if let Err(error) = &result {
tracing::warn!(%error, "could not restart into the update");
}
*state = if restarted {
State::Applied
} else if staged.is_some() {
State::Ready
} else {
next
};
*lock(&shared.restart) = Restart::Done(result);
restarted
}
fn check(
shared: &Shared,
method: &Method,
cache: &mut transport::ManifestCache,
staged: Option<&StagedUpdate>,
restarting: bool,
) -> Result<State> {
let updates = updates_dir()?;
// Read each check, so a change from the window or `hex settings` applies
// at the next one.
let setting = AppSettings::saved_update_channel();
let home = home_channel(method, BUILD_CHANNEL, crate::VERSION);
let channel = channel(method, setting, &home);
let user_agent = transport::user_agent(&home, crate::VERSION);
*lock(&shared.last) = Some((channel.clone(), std::time::Instant::now()));
let manifest_url = manifest_url(&channel);
let timeout = if restarting {
RESTART_MANIFEST_TIMEOUT
} else {
MANIFEST_TIMEOUT
};
let manifest = cache.fetch(&manifest_url, &user_agent, &updates, timeout)?;
let install = Install {
version: crate::VERSION.into(),
target: platform::TARGET.into(),
distribution: method.distribution().into(),
rollout_bucket: rollout_bucket(&crate::app_paths::support_dir()?)?,
sha256: match method {
Method::Direct { .. } => running_sha256(),
_ => None,
},
channel: (!matches!(method, Method::Package(_))).then_some(home),
};
let decision = protocol::decide(APP, ARTIFACT, &channel, &manifest, &install);
tracing::info!(?decision, "update decision");
match decision {
Decision::Reject { reason } => Err(eyre!("the update manifest was rejected: {reason}")),
Decision::None { .. } | Decision::Install { .. }
if staged.is_some_and(|staged| !replaces_staged(&decision, &staged.sha256)) =>
{
Ok(State::Ready)
}
Decision::None { .. } => {
transport::prune(&updates, None);
Ok(State::Current)
}
Decision::Notify {
command, notes_url, ..
} => Ok(match command {
Some(command) => State::Command { command },
None => State::Download {
url: notes_url.unwrap_or_else(|| "https://anoma.ly/hex".into()),
},
}),
Decision::Install {
reason: protocol::Reason::Switch,
version,
target,
} if *method != Method::DownloadOnly
&& lock(&shared.confirmed).as_deref() != Some(target.sha256.as_str()) =>
{
Ok(State::Switch {
channel,
version,
sha256: target.sha256,
})
}
Decision::Install {
version, target, ..
} => {
if *method == Method::DownloadOnly {
let url = protocol::parse_manifest(&manifest)
.and_then(|manifest| {
manifest
.release
.target(platform::DOWNLOAD_TARGET)
.and_then(|target| protocol::resolve_url(&manifest_url, &target.url))
.or(manifest.release.notes_url)
})
.unwrap_or_else(|| "https://anoma.ly/hex".into());
return Ok(State::Download { url });
}
let url = protocol::resolve_url(&manifest_url, &target.url)
.ok_or_else(|| eyre!("the update URL {} is not usable", target.url))?;
// A staged update stays offered while a newer one downloads in
// the background.
if staged.is_none() || restarting {
*lock(&shared.state) = State::Downloading;
}
transport::prune(&updates, Some(&target.sha256));
#[cfg(target_os = "linux")]
verify_linux_signature(&manifest, &manifest_url, &user_agent, &target, &updates)?;
let file = transport::download(&url, &user_agent, &target, &updates)?;
let staged = platform::stage(&file, &version)
.wrap_err_with(|| format!("could not stage Hex {version}"))?;
*lock(&shared.staged) = Some(StagedUpdate {
staged,
sha256: target.sha256,
});
Ok(State::Ready)
}
}
}
/// Checks the manifest's `<target>-sig` file: Anomaly's release key signing
/// the SHA-256 the executable is downloaded against. Without it, whoever
/// controls the manifest could name any executable.
#[cfg(target_os = "linux")]
fn verify_linux_signature(
manifest: &str,
manifest_url: &str,
user_agent: &str,
target: &protocol::Target,
updates: &Path,
) -> Result<()> {
let manifest = protocol::parse_manifest(manifest)
.ok_or_else(|| eyre!("the update manifest was rejected: malformed"))?;
let signature = manifest
.release
.target(&platform::signature_target())
.ok_or_else(|| eyre!("the Linux update has no signature"))?;
if signature.size != 64 {
return Err(eyre!("the Linux update's signature is malformed"));
}
let url = protocol::resolve_url(manifest_url, &signature.url)
.ok_or_else(|| eyre!("the signature URL {} is not usable", signature.url))?;
let file = transport::download(&url, user_agent, signature, updates)?;
platform::verify_signature(&target.sha256, &std::fs::read(file)?)
}
/// Whether `decision` replaces the staged update: only a different release
/// this install takes by itself does. A rollout that has not reached this
/// install, an unconfirmed channel switch, or the same release keeps it.
fn replaces_staged(decision: &Decision, staged_sha256: &str) -> bool {
matches!(
decision,
Decision::Install {
reason: protocol::Reason::Update | protocol::Reason::Required,
target,
..
} if target.sha256 != staged_sha256
)
}
/// `HEX_RELEASE_BASE_URL` (HTTPS only) points a build at another service
/// origin, for local tests against a fixture service. Nothing defaults to the
/// service's dev stage, which only tests the service itself.
fn manifest_url(channel: &str) -> String {
let origin = std::env::var("HEX_RELEASE_BASE_URL")
.ok()
.filter(|origin| origin.starts_with("https://"));
format!(
"{}/{APP}/{ARTIFACT}/{channel}.json",
origin.as_deref().unwrap_or(ORIGIN).trim_end_matches('/')
)
}
/// This build's target SHA-256, when the platform can tell (the target is
/// the executable itself); hashed once per launch.
fn running_sha256() -> Option<String> {
static SHA256: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
SHA256.get_or_init(platform::running_sha256).clone()
}
fn updates_dir() -> Result<PathBuf> {
let updates = crate::app_paths::support_dir()?.join("updates");
std::fs::create_dir_all(&updates)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&updates, std::fs::Permissions::from_mode(0o700))?;
}
Ok(updates)
}
/// This install's rollout bucket, 0–99: a random 32-bit number drawn once
/// from the OS's secure source and kept with the install. It never leaves
/// the device.
fn rollout_bucket(support: &Path) -> Result<u64> {
let path = support.join("update-bucket");
if let Some(number) = std::fs::read_to_string(&path)
.ok()
.and_then(|text| text.trim().parse::<u32>().ok())
{
return Ok(u64::from(number) % 100);
}
let mut bytes = [0; 4];
getrandom::fill(&mut bytes).map_err(|error| eyre!("no secure random source: {error}"))?;
let number = u32::from_le_bytes(bytes);
std::fs::create_dir_all(support)?;
let partial = path.with_extension("partial");
std::fs::write(&partial, format!("{number}\n"))?;
std::fs::rename(&partial, &path)?;
Ok(u64::from(number) % 100)
}
/// The channel in our installer's receipt at `root`, when it names this app
/// and root and no other user can write the root.
#[cfg_attr(target_os = "macos", allow(dead_code))]
fn receipt_channel(root: &Path) -> Option<String> {
#[derive(serde::Deserialize)]
struct Receipt {
app: String,
artifact: String,
channel: String,
method: String,
root: PathBuf,
}
let receipt: Receipt =
serde_json::from_slice(&std::fs::read(root.join("install.json")).ok()?).ok()?;
let canonical = |path: &Path| path.canonicalize().ok();
(receipt.app == APP
&& receipt.artifact == ARTIFACT
&& receipt.method == "direct"
&& canonical(&receipt.root).is_some()
&& canonical(&receipt.root) == canonical(root)
&& ["stable", "beta", "dev"].contains(&receipt.channel.as_str()))
.then_some(receipt.channel)
}
#[cfg(test)]
mod tests {
use super::*;
fn temporary(name: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!("hex-updater-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
path
}
#[test]
fn the_rollout_bucket_is_drawn_once_and_kept() {
let support = temporary("bucket");
let first = rollout_bucket(&support).unwrap();
assert!(first < 100);
assert_eq!(rollout_bucket(&support).unwrap(), first);
std::fs::write(support.join("update-bucket"), "4294967295\n").unwrap();
assert_eq!(rollout_bucket(&support).unwrap(), 95);
let _ = std::fs::remove_dir_all(support);
}
#[test]
fn receipts_must_name_this_app_and_root() {
let root = temporary("receipt");
let write = |value: serde_json::Value| {
std::fs::write(root.join("install.json"), value.to_string()).unwrap()
};
let receipt = |channel: &str, root_path: &Path| serde_json::json!({"app":"hex","artifact":"desktop","channel":channel,"method":"direct","root":root_path});
assert_eq!(receipt_channel(&root), None);
write(receipt("stable", &root));
assert_eq!(receipt_channel(&root).as_deref(), Some("stable"));
write(receipt("beta", &root));
assert_eq!(receipt_channel(&root).as_deref(), Some("beta"));
write(receipt("nightly", &root));
assert_eq!(receipt_channel(&root), None);
write(receipt("stable", &std::env::temp_dir()));
assert_eq!(receipt_channel(&root), None);
write(
serde_json::json!({"app":"opencode","artifact":"desktop","channel":"stable","method":"direct","root":root}),
);
assert_eq!(receipt_channel(&root), None);
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn methods_map_to_protocol_distributions() {
assert_eq!(
Method::Direct {
channel: "beta".into()
}
.distribution(),
"direct"
);
assert_eq!(
Method::Direct {
channel: "beta".into()
}
.channel(),
"beta"
);
assert_eq!(Method::DownloadOnly.distribution(), "direct");
assert_eq!(Method::Package("aur").distribution(), "aur");
assert_eq!(Method::Unknown.distribution(), "unknown");
assert_eq!(Method::Package("aur").channel(), "stable");
}
#[test]
fn a_package_manager_install_never_shows_its_own_checks() {
let updater = |state: State, packaged: bool| Updater {
shared: Arc::new(Shared::new(state, packaged)),
};
for state in [State::Checking, State::Current, State::Failed] {
assert_eq!(
updater(state, true).status(),
DesktopUpdateStatus::PackageManager
);
}
assert_eq!(
updater(State::Checking, false).status(),
DesktopUpdateStatus::Checking
);
assert_eq!(
updater(State::Failed, false).status(),
DesktopUpdateStatus::Failed
);
}
#[test]
fn a_build_belongs_to_the_channel_it_was_published_on() {
let direct = Method::Direct {
channel: "beta".into(),
};
assert_eq!(home_channel(&direct, Some("dev"), "0.0.0-dev-40"), "dev");
assert_eq!(home_channel(&direct, Some("stable"), "2.4.0"), "stable");
// Builds from before the stamp: a dev version, else the receipt.
assert_eq!(home_channel(&direct, None, "2.3.2-dev.29"), "dev");
assert_eq!(home_channel(&direct, None, "0.0.0-dev-40"), "dev");
assert_eq!(home_channel(&direct, None, "2.4.0"), "beta");
assert_eq!(home_channel(&direct, Some("nightly"), "2.4.0"), "beta");
assert_eq!(
home_channel(&Method::Package("aur"), Some("dev"), "0.0.0-dev-40"),
"stable"
);
}
#[test]
fn the_setting_picks_the_channel_unless_a_package_manager_updates_hex() {
let direct = Method::Direct {
channel: "stable".into(),
};
assert_eq!(channel(&direct, None, "dev"), "dev");
assert_eq!(
channel(&direct, Some(UpdateChannel::Stable), "dev"),
"stable"
);
assert_eq!(channel(&direct, Some(UpdateChannel::Dev), "stable"), "dev");
assert_eq!(
channel(&Method::DownloadOnly, Some(UpdateChannel::Dev), "stable"),
"dev"
);
assert_eq!(
channel(&Method::Package("aur"), Some(UpdateChannel::Dev), "stable"),
"stable"
);
}
fn manifest(channel: &str, version: &str, sha: char) -> String {
let sha = sha.to_string().repeat(64);
serde_json::json!({
"schema": 1,
"app": "hex",
"artifact": "desktop",
"channel": channel,
"sequence": 1,
"published_at": "2026-10-27T00:00:00Z",
"release": {
"version": version,
"rollout_percent": 100,
"revoked_versions": [],
"distributions": [{ "kind": "direct" }],
"targets": {
"linux-x64": {
"url": format!("/release/hex/files/{sha}/hex"),
"sha256": sha,
"size": 1
}
}
}
})
.to_string()
}
fn install(version: &str, sha: char, channel: &str) -> Install {
Install {
version: version.into(),
target: "linux-x64".into(),
distribution: "direct".into(),
rollout_bucket: 0,
sha256: Some(sha.to_string().repeat(64)),
channel: Some(channel.into()),
}
}
#[test]
fn versions_are_never_compared_across_or_within_channels() {
let dev = install("0.0.0-dev-40", 'a', "dev");
// A legacy dev version above the new numbering still moves to it.
let legacy = install("2.3.2-dev.29", 'f', "dev");
let next = manifest("dev", "0.0.0-dev-41", 'b');
for running in [&dev, &legacy] {
assert!(matches!(
protocol::decide(APP, ARTIFACT, "dev", &next, running),
Decision::Install {
reason: protocol::Reason::Update,
..
}
));
}
let same = manifest("dev", "0.0.0-dev-40", 'a');
assert!(matches!(
protocol::decide(APP, ARTIFACT, "dev", &same, &dev),
Decision::None { .. }
));
// Stable 2.3.1 is a switch from dev, never "older".
let stable = manifest("stable", "2.3.1", 'c');
assert!(matches!(
protocol::decide(APP, ARTIFACT, "stable", &stable, &dev),
Decision::Install {
reason: protocol::Reason::Switch,
..
}
));
}
#[test]
fn a_switch_waits_for_the_user_to_confirm() {
let updater = Updater::idle_checking();
*lock(&updater.shared.state) = State::Switch {
channel: "stable".into(),
version: "2.3.1".into(),
sha256: "c".repeat(64),
};
assert_eq!(
updater.status(),
DesktopUpdateStatus::SwitchAvailable {