Skip to main content

brep_app/
update.rs

1//! The desktop app's updates: master's Linux and Windows builds, offered from
2//! next.brep.io and installed only with the user's say-so.
3//!
4//! In the background the app hashes its own executable and asks the server's
5//! update channel (`/api/public/app-update/<os>`) for the current build's
6//! manifest. The manifest is signed with an ed25519 key whose public half is
7//! `PUBLIC_KEY_HEX`; one that does not verify is ignored. When the signed
8//! sha256 differs from this executable's, a notice offers **Update and
9//! restart**. The download must match the signed length and sha256 before it
10//! touches the executable, so a server or connection that hands over
11//! anything else can only make an update fail.
12//!
13//! The executable is replaced by rename beside itself, which a running
14//! program allows on both systems: on Linux the new file is renamed over the
15//! old one; on Windows the running file is renamed to `<exe>.old` (deleted at
16//! the next start) and the new one takes its name. The app then closes
17//! through its normal close path, which writes unsaved work for recovery, and
18//! starts the new executable with the same arguments.
19//!
20//! The check never runs for a build out of a cargo `target/` directory or
21//! `~/.cargo/bin` (a developer's or a crates.io build, which is not the
22//! channel's), with `BREP_NO_UPDATE_CHECK` set, or after **Don't check again**
23//! (`update.json` in the app's config directory). `BREP_UPDATE_URL` points the
24//! check at another server.
25
26use std::path::{Path, PathBuf};
27use std::sync::mpsc::{channel, Receiver, Sender};
28use std::sync::Mutex;
29use std::time::Duration;
30
31use eframe::egui;
32use sha2::{Digest, Sha256};
33
34/// The update signing key's public half.
35pub const PUBLIC_KEY_HEX: &str = "a2bcdee9fcd8aefba42a566ff1f8eacd3f9ef5504e466580fbf291c81b622b94";
36
37/// The first line of every signed message; the server's `FORMAT`.
38pub const FORMAT: &str = "brep-app-update-v1";
39
40/// The server the channel is on, unless `BREP_UPDATE_URL` says otherwise.
41pub const DEFAULT_SERVER: &str = "https://next.brep.io";
42
43/// How often a running app asks again (a CAD session can last days).
44const CHECK_EVERY: Duration = Duration::from_secs(6 * 60 * 60);
45
46/// A build the channel offers, as its manifest describes it.
47#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
48pub struct Manifest {
49    pub format: String,
50    pub os: String,
51    pub filename: String,
52    pub sha256: String,
53    pub bytes: u64,
54    pub commit: String,
55    pub built_at: String,
56    pub signature: String,
57    pub download_path: String,
58}
59
60/// What the manifest's signature covers. Byte-for-byte the server's
61/// `desktop_update::signed_message`; both sides' tests pin one vector.
62pub fn signed_message(os: &str, sha256: &str, bytes: u64, commit: &str, built_at: &str) -> String {
63    format!("{FORMAT}\nos={os}\nsha256={sha256}\nbytes={bytes}\ncommit={commit}\nbuilt_at={built_at}\n")
64}
65
66fn hex_decode(s: &str) -> Option<Vec<u8>> {
67    if s.len() % 2 != 0 {
68        return None;
69    }
70    (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
71}
72
73impl Manifest {
74    pub fn parse(json: &str) -> Result<Manifest, String> {
75        serde_json::from_str(json).map_err(|e| format!("update manifest: {e}"))
76    }
77
78    /// Whether `public_key` signed this manifest, and it is for `os`.
79    pub fn verify(&self, public_key_hex: &str, os: &str) -> Result<(), String> {
80        if self.format != FORMAT {
81            return Err(format!("update manifest format {:?} is not {FORMAT}", self.format));
82        }
83        if self.os != os {
84            return Err(format!("update manifest is for {}, not {os}", self.os));
85        }
86        if self.sha256.len() != 64 || hex_decode(&self.sha256).is_none() {
87            return Err("update manifest sha256 is not 64 hex digits".into());
88        }
89        let key = hex_decode(public_key_hex).ok_or("bad public key")?;
90        let key = ed25519_compact::PublicKey::from_slice(&key).map_err(|e| e.to_string())?;
91        let signature = hex_decode(&self.signature).ok_or("update manifest signature is not hex")?;
92        let signature = ed25519_compact::Signature::from_slice(&signature).map_err(|e| e.to_string())?;
93        let message = signed_message(&self.os, &self.sha256, self.bytes, &self.commit, &self.built_at);
94        key.verify(message.as_bytes(), &signature)
95            .map_err(|_| "update manifest signature does not verify".to_string())
96    }
97
98    /// "2026-11-04 05:00 UTC (commit 1234abc)", for the notice.
99    pub fn describe(&self) -> String {
100        let when = self.built_at.get(..16).unwrap_or(&self.built_at).replace('T', " ");
101        let commit = self.commit.get(..9).unwrap_or(&self.commit);
102        if commit.is_empty() {
103            format!("built {when} UTC")
104        } else {
105            format!("built {when} UTC, commit {commit}")
106        }
107    }
108}
109
110/// The channel's name for this system, or `None` where it serves no build.
111pub fn platform_os() -> Option<&'static str> {
112    if cfg!(target_os = "linux") {
113        Some("linux")
114    } else if cfg!(windows) {
115        Some("windows")
116    } else {
117        None
118    }
119}
120
121/// A build cargo put where it builds (`…/target/release/brep-app`,
122/// `…/target/<triple>/debug/…`, a test binary under `deps/`) or installed
123/// (`~/.cargo/bin`): a developer's or a crates.io build, not the channel's.
124pub fn is_dev_build(exe: &Path) -> bool {
125    let parts: Vec<String> = exe.components().map(|c| c.as_os_str().to_string_lossy().to_ascii_lowercase()).collect();
126    let cargo_target = parts.iter().enumerate().any(|(i, p)| {
127        p == "target" && parts[i + 1..].iter().take(3).any(|q| q == "release" || q == "debug")
128    });
129    let cargo_bin = parts.windows(2).any(|w| w[0] == ".cargo" && w[1] == "bin");
130    cargo_target || cargo_bin
131}
132
133fn settings_path(config_dir: &Path) -> PathBuf {
134    config_dir.join("update.json")
135}
136
137/// Whether the user said **Don't check again**.
138pub fn turned_off(config_dir: &Path) -> bool {
139    std::fs::read_to_string(settings_path(config_dir))
140        .ok()
141        .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
142        .and_then(|v| v.get("check").and_then(|c| c.as_bool()))
143        == Some(false)
144}
145
146pub fn turn_off(config_dir: &Path) -> std::io::Result<()> {
147    std::fs::create_dir_all(config_dir)?;
148    std::fs::write(settings_path(config_dir), "{\"check\": false}\n")
149}
150
151/// Why this run does not check, or `None` when it does.
152pub fn disabled_reason(exe: &Path, env: &dyn Fn(&str) -> Option<String>, config_dir: &Path) -> Option<&'static str> {
153    if platform_os().is_none() {
154        Some("no build is published for this system")
155    } else if env("BREP_NO_UPDATE_CHECK").is_some_and(|v| !v.is_empty()) {
156        Some("BREP_NO_UPDATE_CHECK is set")
157    } else if is_dev_build(exe) {
158        Some("a cargo build")
159    } else if turned_off(config_dir) {
160        Some("turned off")
161    } else {
162        None
163    }
164}
165
166pub fn sha256_file(path: &Path) -> std::io::Result<String> {
167    let mut file = std::fs::File::open(path)?;
168    let mut hasher = Sha256::new();
169    std::io::copy(&mut file, &mut hasher)?;
170    Ok(format!("{:x}", hasher.finalize()))
171}
172
173fn sibling(exe: &Path, suffix: &str) -> PathBuf {
174    let mut name = exe.file_name().unwrap_or_default().to_os_string();
175    name.push(suffix);
176    exe.with_file_name(name)
177}
178
179/// What an earlier update left beside the executable: the Windows `.old`
180/// (no longer running) and a `.new` an interrupted install wrote.
181pub fn clean_leftovers(exe: &Path) {
182    let _ = std::fs::remove_file(sibling(exe, ".old"));
183    let _ = std::fs::remove_file(sibling(exe, ".new"));
184}
185
186/// Put `bytes` in place of `exe`, once they are what `manifest` signed.
187pub fn install(exe: &Path, bytes: &[u8], manifest: &Manifest) -> Result<(), String> {
188    if bytes.len() as u64 != manifest.bytes {
189        return Err(format!("the download is {} bytes, the signed build {}", bytes.len(), manifest.bytes));
190    }
191    let sha = format!("{:x}", Sha256::digest(bytes));
192    if sha != manifest.sha256 {
193        return Err("the download's sha256 is not the signed build's".into());
194    }
195    let new = sibling(exe, ".new");
196    let write = || -> std::io::Result<()> {
197        std::fs::write(&new, bytes)?;
198        #[cfg(unix)]
199        {
200            use std::os::unix::fs::PermissionsExt;
201            let mode = std::fs::metadata(exe).map(|m| m.permissions().mode()).unwrap_or(0o755) | 0o111;
202            std::fs::set_permissions(&new, std::fs::Permissions::from_mode(mode))?;
203        }
204        Ok(())
205    };
206    if let Err(e) = write() {
207        let _ = std::fs::remove_file(&new);
208        return Err(format!("cannot write beside {}: {e}", exe.display()));
209    }
210    swap(exe, &new).map_err(|e| {
211        let _ = std::fs::remove_file(&new);
212        format!("cannot replace {}: {e}", exe.display())
213    })
214}
215
216/// A running executable can be renamed but, on Windows, not replaced: move it
217/// aside first there, and back if the new one cannot take its place.
218fn swap(exe: &Path, new: &Path) -> std::io::Result<()> {
219    if cfg!(windows) {
220        let old = sibling(exe, ".old");
221        let _ = std::fs::remove_file(&old);
222        std::fs::rename(exe, &old)?;
223        if let Err(e) = std::fs::rename(new, exe) {
224            let _ = std::fs::rename(&old, exe);
225            return Err(e);
226        }
227        Ok(())
228    } else {
229        std::fs::rename(new, exe)
230    }
231}
232
233/// The executable to start once the window has closed, set by an install.
234static RELAUNCH: Mutex<Option<PathBuf>> = Mutex::new(None);
235
236/// After the event loop returns: start the installed build with this run's
237/// arguments, if an update was installed.
238pub fn relaunch_if_installed() {
239    let Some(exe) = RELAUNCH.lock().ok().and_then(|mut r| r.take()) else { return };
240    if let Err(e) = std::process::Command::new(&exe).args(std::env::args_os().skip(1)).spawn() {
241        eprintln!("brep-app: the update is installed but {} did not start: {e}", exe.display());
242    }
243}
244
245/// The update server: `BREP_UPDATE_URL`, else [`DEFAULT_SERVER`]. The help
246/// download (`help_local`) comes from the same one.
247pub(crate) fn server() -> String {
248    std::env::var("BREP_UPDATE_URL")
249        .ok()
250        .filter(|u| !u.is_empty())
251        .unwrap_or_else(|| DEFAULT_SERVER.to_string())
252        .trim_end_matches('/')
253        .to_string()
254}
255
256/// The build on offer, if it is signed and not this one.
257fn check(server: &str, os: &str, own_sha: &str) -> Result<Option<Manifest>, String> {
258    let response = crate::net::fetch_blocking(&crate::net::Request::get(format!("{server}/api/public/app-update/{os}")))?;
259    if !response.ok {
260        return Err(format!("update check: HTTP {} {}", response.status, response.status_text));
261    }
262    let manifest = Manifest::parse(&String::from_utf8_lossy(&response.bytes))?;
263    manifest.verify(PUBLIC_KEY_HEX, os)?;
264    Ok((manifest.sha256 != own_sha).then_some(manifest))
265}
266
267fn download_and_install(server: &str, exe: &Path, manifest: &Manifest) -> Result<(), String> {
268    let response = crate::net::fetch_blocking(&crate::net::Request::get(format!("{server}{}", manifest.download_path)))?;
269    if !response.ok {
270        return Err(format!("download: HTTP {} {}", response.status, response.status_text));
271    }
272    install(exe, &response.bytes, manifest)
273}
274
275enum Msg {
276    Available(Manifest),
277    Installed,
278    Failed(String),
279}
280
281#[derive(Clone, Debug, PartialEq, Eq)]
282enum Phase {
283    Quiet,
284    Offered(Manifest),
285    Installing,
286    Failed(String),
287}
288
289/// The background check and the notice it raises.
290pub struct Updater {
291    exe: Option<PathBuf>,
292    rx: Option<Receiver<Msg>>,
293    tx: Option<Sender<Msg>>,
294    phase: Phase,
295    /// The sha256 of a build the user said **Later** to: not offered again.
296    declined: Option<String>,
297    restart: bool,
298}
299
300impl Updater {
301    /// An updater that never checks (tests, a dev build, turned off).
302    pub fn inert() -> Updater {
303        Updater { exe: None, rx: None, tx: None, phase: Phase::Quiet, declined: None, restart: false }
304    }
305
306    /// Start checking in the background, unless this run is not the channel's.
307    pub fn start(ctx: &egui::Context) -> Updater {
308        let Ok(exe) = std::env::current_exe() else { return Updater::inert() };
309        // An earlier update's leftovers go even when checks are now off.
310        if !is_dev_build(&exe) {
311            clean_leftovers(&exe);
312        }
313        let config_dir = crate::plm::config::app_config_dir();
314        if let Some(reason) = disabled_reason(&exe, &|n| std::env::var(n).ok(), &config_dir) {
315            log::info!("update check off: {reason}");
316            return Updater::inert();
317        }
318        let os = platform_os().expect("disabled_reason checks the platform");
319        let (tx, rx) = channel();
320        let (thread_tx, thread_exe, ctx) = (tx.clone(), exe.clone(), ctx.clone());
321        let spawned = std::thread::Builder::new().name("brep-update-check".into()).spawn(move || {
322            let Ok(own) = sha256_file(&thread_exe) else { return };
323            let server = server();
324            loop {
325                match check(&server, os, &own) {
326                    Ok(Some(manifest)) => {
327                        if thread_tx.send(Msg::Available(manifest)).is_err() {
328                            return;
329                        }
330                        ctx.request_repaint();
331                    }
332                    Ok(None) => {}
333                    Err(e) => log::info!("{e}"),
334                }
335                std::thread::sleep(CHECK_EVERY);
336            }
337        });
338        if spawned.is_err() {
339            return Updater::inert();
340        }
341        Updater { exe: Some(exe), rx: Some(rx), tx: Some(tx), phase: Phase::Quiet, declined: None, restart: false }
342    }
343
344    fn drain(&mut self) {
345        let Some(rx) = &self.rx else { return };
346        while let Ok(msg) = rx.try_recv() {
347            match msg {
348                Msg::Available(m) => {
349                    let busy = matches!(self.phase, Phase::Installing);
350                    if !busy && self.declined.as_deref() != Some(&m.sha256) {
351                        self.phase = Phase::Offered(m);
352                    }
353                }
354                Msg::Installed => {
355                    self.phase = Phase::Quiet;
356                    if let (Ok(mut r), Some(exe)) = (RELAUNCH.lock(), &self.exe) {
357                        *r = Some(exe.clone());
358                    }
359                    self.restart = true;
360                }
361                Msg::Failed(e) => self.phase = Phase::Failed(e),
362            }
363        }
364    }
365
366    fn begin_install(&mut self, ctx: &egui::Context, manifest: Manifest) {
367        let (Some(exe), Some(tx)) = (self.exe.clone(), self.tx.clone()) else { return };
368        self.phase = Phase::Installing;
369        let ctx = ctx.clone();
370        let _ = std::thread::Builder::new().name("brep-update-install".into()).spawn(move || {
371            let msg = match download_and_install(&server(), &exe, &manifest) {
372                Ok(()) => Msg::Installed,
373                Err(e) => Msg::Failed(e),
374            };
375            let _ = tx.send(msg);
376            ctx.request_repaint();
377        });
378    }
379
380    /// Draw the notice. `true` once: an update is installed and the app
381    /// should close (its normal close path) so the new build can start.
382    pub fn show(&mut self, ctx: &egui::Context) -> bool {
383        self.drain();
384        if std::mem::take(&mut self.restart) {
385            return true;
386        }
387        if self.phase == Phase::Quiet {
388            return false;
389        }
390        let mut next = None;
391        egui::Area::new(egui::Id::new("brep-update-notice"))
392            .anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-12.0, -36.0))
393            .order(egui::Order::Foreground)
394            .show(ctx, |ui| {
395                egui::Frame::popup(ui.style()).show(ui, |ui| {
396                    ui.set_max_width(360.0);
397                    match &self.phase {
398                        Phase::Offered(m) => {
399                            ui.strong("A newer BREP build is available");
400                            ui.label(m.describe());
401                            ui.horizontal(|ui| {
402                                if ui
403                                    .button("Update and restart")
404                                    .on_hover_text("Unsaved work is kept and offered again when the app restarts.")
405                                    .clicked()
406                                {
407                                    next = Some(Action::Install(m.clone()));
408                                }
409                                if ui.button("Later").clicked() {
410                                    next = Some(Action::Later(m.sha256.clone()));
411                                }
412                                if ui.button("Don't check again").clicked() {
413                                    next = Some(Action::Off);
414                                }
415                            });
416                        }
417                        Phase::Installing => {
418                            ui.horizontal(|ui| {
419                                ui.spinner();
420                                ui.label("Downloading and checking the update…");
421                            });
422                        }
423                        Phase::Failed(e) => {
424                            ui.strong("The update was not installed");
425                            ui.label(e);
426                            ui.label(format!("You can download it from {}.", server()));
427                            if ui.button("Close").clicked() {
428                                next = Some(Action::Dismiss);
429                            }
430                        }
431                        Phase::Quiet => {}
432                    }
433                });
434            });
435        match next {
436            Some(Action::Install(m)) => self.begin_install(ctx, m),
437            Some(Action::Later(sha)) => {
438                self.declined = Some(sha);
439                self.phase = Phase::Quiet;
440            }
441            Some(Action::Off) => {
442                if let Err(e) = turn_off(&crate::plm::config::app_config_dir()) {
443                    log::warn!("could not save the update setting: {e}");
444                }
445                self.phase = Phase::Quiet;
446                self.rx = None;
447            }
448            Some(Action::Dismiss) => self.phase = Phase::Quiet,
449            None => {}
450        }
451        if self.phase == Phase::Installing {
452            ctx.request_repaint_after(Duration::from_millis(200));
453        }
454        false
455    }
456}
457
458enum Action {
459    Install(Manifest),
460    Later(String),
461    Off,
462    Dismiss,
463}
464