From 90f663ed5431f5ad6fda16fe5f68e45aa5cf4754 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:35:17 -0700 Subject: [PATCH] feat(app): the window tells when a newer version exists and where to get it (P15 C1) Update is an ordinary app update: the newer package installed over the old one. The program's part is to say one exists. Once a day, on a thread of its own, it reads one small file a release publishes (latest.json: only a version number is taken from it; where to get the update is a fixed address in the program) and notes the answer in the data root's updates folder. A higher x.y.z shows a standing notice with a button that opens the download page and the words that books, keys and connections stay. Check for updates does the same look at once on every platform; where a program may replace itself with a signed release it also stages one as before. A macOS app is never replaced one file at a time (that breaks its signature): it is treated as managed, and says to drag the new app over the old. Window prose names the product Wanderbooks. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 9 + crates/ledger-gui/src/owner.rs | 82 ++++++- crates/ledger-gui/src/welcome.rs | 2 +- crates/ledger-gui/tests/update_notice.rs | 59 ++++- crates/ledger-host/src/commands.rs | 60 ++--- crates/ledger-host/src/lib.rs | 1 + crates/ledger-host/src/newer.rs | 289 +++++++++++++++++++++++ crates/ledger-host/src/update.rs | 57 ++++- 8 files changed, 510 insertions(+), 49 deletions(-) create mode 100644 crates/ledger-host/src/newer.rs diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index a4940241..3bc9c36b 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -409,6 +409,15 @@ impl ledger_gui::owner::Owner for ViewerOwner { }) } + fn newer_version(&self) -> Option { + ledger_host::commands::newer_version(&self.common).map(|(version, page)| { + ledger_gui::owner::NewerVersion { + version, + page: page.to_string(), + } + }) + } + fn check_for_updates(&self) -> Result, String> { ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l]) } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index c9289be6..0f459d62 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -474,6 +474,11 @@ pub trait Owner: Send + Sync { fn check_for_updates(&self) -> Result, String> { Err("not here".into()) } + /// A newer version exists, and where to get it (WB-pkg-3): what the + /// program's daily look found. Cheap: called every few seconds. + fn newer_version(&self) -> Option { + None + } /// Accept the waiting update: the books' host installs it and restarts /// onto it when no call is running, the books staying open. fn apply_update(&self) -> Result, String> { @@ -486,6 +491,16 @@ pub trait Owner: Send + Sync { } } +/// A newer version of the program that the person may get and install over +/// this one (WB-pkg-3). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NewerVersion { + /// Its version. + pub version: String, + /// The page to get it from: the program's own, never a feed's. + pub page: String, +} + /// The Claude desktop extension the Connect page made (WB-pkg-5). #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExtensionMade { @@ -642,6 +657,8 @@ pub struct OwnerMenu { /// The update waiting, as last read, and when (re-read every few /// seconds and after any job). update: Option<(std::time::Instant, Option)>, + /// A newer version the person may get, as last read, and when. + newer: Option<(std::time::Instant, Option)>, /// The tab's threads: every job is one of them (INVARIANT 6). jobs: crate::jobs::Spawner, } @@ -687,6 +704,23 @@ impl OwnerMenu { self.update.as_ref().and_then(|(_, u)| u.clone()) } + /// A newer version to get, if any (read now and then, not every frame). + fn newer_version( + &mut self, + ctx: &egui::Context, + owner: &Arc, + ) -> Option { + if self + .newer + .as_ref() + .is_none_or(|(at, _)| at.elapsed() > UPDATE_LOOK) + { + self.newer = Some((std::time::Instant::now(), owner.newer_version())); + } + ctx.request_repaint_after(UPDATE_LOOK); + self.newer.as_ref().and_then(|(_, n)| n.clone()) + } + /// The standing notices above the page: an update waiting for the /// owner's accept, and a format upgrade the books wait for, whose /// go-ahead is asked for once each open (INVARIANT 5). @@ -708,7 +742,7 @@ impl OwnerMenu { ui.horizontal_wrapped(|ui| { ui.label( RichText::new(format!( - "{} Version {} of wanderbooks is ready.", + "{} Version {} of Wanderbooks is ready.", icon::ARROW_FAT_UP, update.version )) @@ -738,12 +772,48 @@ impl OwnerMenu { ui.ctx(), ( "Update".into(), - Effect::Changes("Updating wanderbooks"), + Effect::Changes("Updating Wanderbooks"), work, ), ); } } + // No update of the program's own is waiting: is a newer version + // out for the person to get and install over this one? + else if let Some(newer) = self.newer_version(ui.ctx(), &owner) { + let p = crate::theme::pal(ui.ctx()); + egui::Frame::new() + .fill(p.warning_soft) + .inner_margin(egui::Margin::symmetric(20, 10)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(format!( + "{} Version {} of Wanderbooks is available.", + icon::ARROW_FAT_UP, + newer.version + )) + .font(crate::theme::semibold(13.0)) + .color(p.warning), + ); + ui.label( + RichText::new( + "Download it and install it over this one. Your books, keys and connections stay as they are.", + ) + .font(crate::theme::regular(13.0)) + .color(p.text), + ); + if ui + .button("Open the download page") + .on_hover_text(newer.page.clone()) + .clicked() + { + ui.ctx().open_url(egui::OpenUrl::new_tab(newer.page.clone())); + } + }); + }); + } let Some(upgrade) = books.format_upgrade.clone() else { return; }; @@ -771,7 +841,7 @@ impl OwnerMenu { ); ui.label( RichText::new( - "An older version of wanderbooks wrote them. They work on their old format until you agree; what needs the new one is refused.", + "An older version of Wanderbooks wrote them. They work on their old format until you agree; what needs the new one is refused.", ) .font(crate::theme::regular(13.0)) .color(p.text), @@ -886,7 +956,7 @@ impl OwnerMenu { ui.separator(); if ui .button(format!("{} Check for updates", icon::ARROWS_CLOCKWISE)) - .on_hover_text("Look for a newer version of wanderbooks now") + .on_hover_text("Look for a newer version of Wanderbooks now") .clicked() { let o = owner.clone(); @@ -905,7 +975,7 @@ impl OwnerMenu { let o = owner.clone(); start = Some(( "Update".into(), - Effect::Changes("Updating wanderbooks"), + Effect::Changes("Updating Wanderbooks"), Box::new(move || o.apply_update()), )); } @@ -1167,7 +1237,7 @@ fn upgrade_dialog( ui.heading("Upgrade these books' format?"); ui.add_space(4.0); ui.label(format!( - "An older version of wanderbooks wrote these books, in journal format {}. The upgrade adds {}.", + "An older version of Wanderbooks wrote these books, in journal format {}. The upgrade adds {}.", form.upgrade.from.format, form.upgrade.adds().join(", ") )); diff --git a/crates/ledger-gui/src/welcome.rs b/crates/ledger-gui/src/welcome.rs index a03e5954..e8a123eb 100644 --- a/crates/ledger-gui/src/welcome.rs +++ b/crates/ledger-gui/src/welcome.rs @@ -158,7 +158,7 @@ impl Welcome { ui.vertical_centered(|ui| { ui.set_max_width(640.0); ui.add_space(36.0); - ui.label(RichText::new("Welcome to wanderbooks").font(crate::theme::bold(28.0))); + ui.label(RichText::new("Welcome to Wanderbooks").font(crate::theme::bold(28.0))); ui.label( RichText::new( "Your company's books, kept by an assistant and checked by you. A few short steps; nothing here needs a terminal.", diff --git a/crates/ledger-gui/tests/update_notice.rs b/crates/ledger-gui/tests/update_notice.rs index 91d3be45..8375bd14 100644 --- a/crates/ledger-gui/tests/update_notice.rs +++ b/crates/ledger-gui/tests/update_notice.rs @@ -21,6 +21,7 @@ use std::sync::{Arc, Mutex, OnceLock}; struct Fake { asked: Mutex>, staged: Mutex, + newer: Mutex, } impl Fake { @@ -57,6 +58,12 @@ impl Owner for Fake { staged_at: "2026-10-30T08:00:00Z".into(), }) } + fn newer_version(&self) -> Option { + (*self.newer.lock().unwrap()).then(|| ledger_gui::owner::NewerVersion { + version: "9.2.0".into(), + page: "https://example.test/releases/latest".into(), + }) + } fn check_for_updates(&self) -> Result, String> { self.said("check"); *self.staged.lock().unwrap() = true; @@ -159,7 +166,7 @@ fn the_menu_checks_for_updates_and_a_waiting_update_shows_a_notice_that_accepts( // owner, and the notice goes once it is installed. for _ in 0..60 { h.run_steps(2); - if h.query_by_label_contains("Version 9.1.0 of wanderbooks is ready") + if h.query_by_label_contains("Version 9.1.0 of Wanderbooks is ready") .is_some() { break; @@ -167,7 +174,7 @@ fn the_menu_checks_for_updates_and_a_waiting_update_shows_a_notice_that_accepts( std::thread::sleep(std::time::Duration::from_millis(100)); } assert!( - h.query_by_label_contains("Version 9.1.0 of wanderbooks is ready") + h.query_by_label_contains("Version 9.1.0 of Wanderbooks is ready") .is_some(), "no notice" ); @@ -194,3 +201,51 @@ fn books_outside_a_data_root_have_no_update_notice() { assert!(h.query_by_label_contains("is ready.").is_none()); *f.staged.lock().unwrap() = false; } + +/// WB-pkg-3: with no update of the program's own waiting, a newer version +/// the daily look found is told in a standing notice that says where to +/// get it and that books, keys and connections stay; an update that is +/// waiting is the only notice shown (one at a time). +#[test] +fn a_newer_version_is_told_with_where_to_get_it() { + let _alone = alone(); + let f = fake(); + *f.newer.lock().unwrap() = true; + let (_dir, _book, b) = books(true); + let mut h = harness(b); + for _ in 0..60 { + h.run_steps(2); + if h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available") + .is_some() + { + break; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + assert!( + h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available") + .is_some(), + "no notice" + ); + assert!( + h.query_by_label_contains("Your books, keys and connections stay as they are") + .is_some() + ); + assert!(h.query_by_label("Open the download page").is_some()); + // One notice at a time: a staged update wins. + *f.staged.lock().unwrap() = true; + for _ in 0..60 { + h.run_steps(2); + if h.query_by_label_contains("is ready.").is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + assert!(h.query_by_label_contains("is ready.").is_some()); + assert!( + h.query_by_label_contains("Version 9.2.0 of Wanderbooks is available") + .is_none() + ); + *f.staged.lock().unwrap() = false; + *f.newer.lock().unwrap() = false; +} diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 73797754..be17a3d0 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1525,39 +1525,45 @@ pub fn update_waiting(_common: &Common) -> Option { None } -/// "Check for updates": look at the feed now, whatever the daily look -/// last did, and stage a newer release if there is one (it never swaps -/// the program: accepting is [`apply_update`]). What came of it. -#[cfg(unix)] +/// "Check for updates": say whether a newer version exists and where to +/// get it (the note of [`crate::newer`], looked at now whatever the last +/// look was). Where a program may replace itself (an AppImage, a program +/// put somewhere by hand, with a release key) a newer release is also +/// downloaded and checked, for [`apply_update`] (it never swaps the +/// program: accepting is). What came of it. pub fn check_for_updates(common: &Common) -> Result { let found = ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; - let mine = crate::update::program_version(); - if let crate::update::Install::PackageManaged(manager) = crate::update::this_install()? { - return Err(format!( - "this install is updated by {manager}, not here: use the package manager" - )); - } - match crate::update::stage_if_due(&found, mine, Duration::ZERO) { - Ok(Some(version)) => Ok(format!( - "Version {version} is downloaded and checked. Accept it to start using it." - )), - Ok(None) => Ok(match update_waiting(common) { - Some(u) => format!( - "Version {} is downloaded and checked. Accept it to start using it.", - u.version - ), - None => format!("You have the newest version ({mine})."), - }), - Err(why) => Err(why.to_string()), + let mine = crate::program_version(); + #[cfg(unix)] + if let Ok(crate::update::Install::SelfUpdating(_)) = crate::update::this_install() { + match crate::update::stage_if_due(&found, mine, Duration::ZERO) { + Ok(Some(version)) => { + return Ok(format!( + "Version {version} is downloaded and checked. Accept it to start using it." + )); + } + Ok(None) => { + if let Some(u) = update_waiting(common) { + return Ok(format!( + "Version {} is downloaded and checked. Accept it to start using it.", + u.version + )); + } + } + // No release key or local feed: the look below still tells. + Err(_) => {} + } } + crate::newer::check_now(found.path(), mine) } -/// Checking for updates isn't built for this platform: say so, and -/// change nothing. -#[cfg(not(unix))] -pub fn check_for_updates(_common: &Common) -> Result { - Err(NO_SELF_UPDATE.into()) +/// The newer version the window may tell the person of, with where to get +/// it: what the last (daily) look found, a look begun when one is due. +pub fn newer_version(common: &Common) -> Option<(String, &'static str)> { + let found = ledger_store::root::Root::find(common.root.as_deref()).ok()?; + let version = crate::newer::found_and_refresh(found.path(), crate::program_version())?; + Some((version, crate::newer::DOWNLOAD_PAGE)) } /// Accept the staged update: the books' host installs it and restarts diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index 119e700d..67380eaa 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -24,6 +24,7 @@ pub mod extension; pub mod host; pub mod knobs; pub mod lease; +pub mod newer; pub mod opener; mod start; pub mod tokens; diff --git a/crates/ledger-host/src/newer.rs b/crates/ledger-host/src/newer.rs new file mode 100644 index 00000000..6c55c2d1 --- /dev/null +++ b/crates/ledger-host/src/newer.rs @@ -0,0 +1,289 @@ +//! "A newer version exists, and where to get it" (plan P15 unit C1, 3.1: +//! update is an ordinary app update). +//! +//! The installed program is replaced by installing the newer package over +//! it (the installer on Windows, the `.dmg` on macOS, the package manager +//! or a new AppImage on Linux). The program's part is to tell the person +//! that one exists. This module is that part, on every platform: a look at +//! one small file a release publishes, at most once a day, and a note of +//! what it found in the data root. +//! +//! ```text +//! GOAL: a person who installed Wanderbooks is told, in the window, when a +//! newer version is out, and where to get it; nothing is downloaded +//! or installed by the program. +//! SOURCE: WB-pkg-3; plan/p15-app-and-relay.md 3.1 ("Update becomes an +//! ordinary app update"), D-24 (anything the program installs by +//! itself must be verified against our own release keys: this +//! installs nothing, so it needs none). +//! INVARIANTS: +//! 1. Only a version number is read from the feed: the place to get the +//! update is a fixed address in this program ([`DOWNLOAD_PAGE`]), +//! never one the feed names. A feed that lies can at most say a +//! number. +//! 2. The feed is looked at at most once a day ([`EVERY`]); a failed look +//! counts as a look (no hammering) and is never an error the person +//! sees. The look is never in the window's own thread. +//! 3. A version is "newer" only when it is a higher `x.y.z` than this +//! program's; anything else is no version of ours. +//! 4. The note is a small file in the data root's `updates/` folder, +//! private to the account; the books are not read or changed. +//! 5. The look sends no version, company, key or identifier of the +//! person: a plain request for a public file. +//! SCENARIOS: +//! 1. IF the feed says 0.2.0 and this is 0.1.0: SHOULD say 0.2.0 is +//! newer, for a day. +//! 2. IF the feed says the same, an older, or a word: SHOULD say nothing. +//! 3. IF the feed can't be reached: SHOULD say nothing and look again +//! tomorrow. +//! ``` + +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +/// The small file a release publishes: `{"version": "x.y.z"}`. +pub const FEED: &str = "https://github.com/swaits/wanderbooks/releases/latest/download/latest.json"; + +/// Where a person gets the newest version (INVARIANT 1). +pub const DOWNLOAD_PAGE: &str = "https://github.com/swaits/wanderbooks/releases/latest"; + +/// How often the feed is looked at (INVARIANT 2). +pub const EVERY: Duration = Duration::from_secs(24 * 60 * 60); + +/// The note's name in `/updates/`. +const NOTE: &str = "newer.json"; + +/// The longest feed read, in bytes. +const MAX_FEED: usize = 4096; + +/// `1.2.3` as numbers; anything else (a pre-release, a `v`) is no version +/// of ours. +pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> { + let mut parts = text.split('.'); + let mut next = || -> Option { + let p = parts.next()?; + (!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + .then(|| p.parse().ok()) + .flatten() + }; + let v = (next()?, next()?, next()?); + parts.next().is_none().then_some(v) +} + +/// Whether `theirs` is a version higher than `mine` (INVARIANT 3). +pub fn is_newer(mine: &str, theirs: &str) -> bool { + parse_version(theirs) + .zip(parse_version(mine)) + .is_some_and(|(theirs, mine)| theirs > mine) +} + +/// The version the feed's text names (INVARIANT 1): nothing else of it is +/// read. +pub fn version_in_feed(text: &str) -> Option { + #[derive(Deserialize)] + struct Feed { + version: String, + } + let feed: Feed = serde_json::from_str(text).ok()?; + parse_version(&feed.version).map(|_| feed.version) +} + +/// What the last look found. +#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +struct Note { + /// Seconds since 1970 when the look was made. + looked: u64, + /// The version the feed named, when it named one. + version: Option, +} + +fn note_path(root: &Path) -> PathBuf { + root.join("updates").join(NOTE) +} + +fn read_note(root: &Path) -> Option { + let bytes = std::fs::read(note_path(root)).ok()?; + serde_json::from_slice(&bytes).ok() +} + +fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// The newer version the last look found, if it found one newer than +/// `mine` (a note about a version this program already is, or is past, is +/// nothing). +pub fn found(root: &Path, mine: &str) -> Option { + read_note(root)? + .version + .filter(|theirs| is_newer(mine, theirs)) +} + +/// Whether the feed is due to be looked at at `now` (INVARIANT 2). +pub fn due(root: &Path, now: u64) -> bool { + read_note(root) + .is_none_or(|n| now.saturating_sub(n.looked) >= EVERY.as_secs() || n.looked > now) +} + +/// Look at the feed through `fetch` (its text) and note what it said, at +/// `now`. A feed that can't be read is noted as a look with nothing found +/// (INVARIANT 2). The newer version, if there is one. +pub fn look( + root: &Path, + mine: &str, + now: u64, + fetch: impl FnOnce() -> Result, +) -> Result, String> { + let said = fetch(); + let version = said.as_deref().ok().and_then(version_in_feed); + let note = Note { + looked: now, + version: version.clone(), + }; + let dir = root.join("updates"); + ledger_link::private::make_dir(&dir).map_err(|e| e.kind().to_string())?; + let bytes = serde_json::to_vec(¬e).map_err(|e| e.to_string())?; + ledger_link::private::write(¬e_path(root), &bytes).map_err(|e| e.kind().to_string())?; + match said { + Ok(_) => Ok(version.filter(|theirs| is_newer(mine, theirs))), + Err(why) => Err(why), + } +} + +/// The feed, over https: a plain request for a public file (INVARIANT 5). +pub fn fetch_feed() -> Result { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| e.to_string())?; + rt.block_on(async { + let mut response = reqwest::Client::new() + .get(FEED) + .timeout(Duration::from_secs(20)) + .send() + .await + .and_then(|r| r.error_for_status()) + .map_err(|e| format!("can't look for a newer version: {}", e.without_url()))?; + let mut bytes = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|e| format!("can't look for a newer version: {}", e.without_url()))? + { + bytes.extend_from_slice(&chunk); + if bytes.len() > MAX_FEED { + return Err("the release note is larger than it can be".to_string()); + } + } + String::from_utf8(bytes).map_err(|_| "the release note is not text".to_string()) + }) +} + +/// "Check for updates", now: look whatever the last look was, and say +/// what came of it in plain words. +pub fn check_now(root: &Path, mine: &str) -> Result { + match look(root, mine, now_secs(), fetch_feed)? { + Some(version) => Ok(format!( + "Version {version} of Wanderbooks is available (this is {mine}). Get it at {DOWNLOAD_PAGE} and install it over this one: your books, keys and connections stay as they are." + )), + None => Ok(format!("You have the newest version ({mine}).")), + } +} + +/// Whether a background look is under way. +static LOOKING: AtomicBool = AtomicBool::new(false); + +/// The newer version known, and, when a look is due, one begun on a thread +/// of its own (INVARIANT 2): cheap, for the window to call every few +/// seconds. +pub fn found_and_refresh(root: &Path, mine: &'static str) -> Option { + if due(root, now_secs()) + && LOOKING + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_ok() + { + let root = root.to_path_buf(); + let started = std::thread::Builder::new() + .name("wanderbooks-newer".into()) + .spawn(move || { + // Whatever it came to, it was a look (noted), and the next + // is a day away. + let _ = look(&root, mine, now_secs(), fetch_feed); + LOOKING.store(false, Ordering::SeqCst); + }); + if started.is_err() { + LOOKING.store(false, Ordering::SeqCst); + } + } + found(root, mine) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_higher_plain_version_is_newer() { + assert!(is_newer("0.1.0", "0.2.0")); + assert!(is_newer("0.1.9", "0.1.10")); + assert!(!is_newer("0.2.0", "0.2.0")); + assert!(!is_newer("0.2.0", "0.1.9")); + for odd in ["v0.3.0", "0.3", "0.3.0-rc1", "", "latest", "1.2.3.4"] { + assert!(!is_newer("0.1.0", odd), "{odd}"); + } + } + + #[test] + fn the_feed_gives_a_version_and_nothing_else() { + assert_eq!( + version_in_feed(r#"{"version":"0.2.0","url":"https://evil.example/x"}"#), + Some("0.2.0".into()) + ); + assert_eq!(version_in_feed(r#"{"version":"soon"}"#), None); + assert_eq!(version_in_feed("not json"), None); + // Where to get it is this program's, never the feed's. + assert!(DOWNLOAD_PAGE.starts_with("https://github.com/swaits/wanderbooks/")); + } + + #[test] + fn a_look_is_noted_and_the_next_is_a_day_away() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert!(due(root, 1_000)); + let said = look(root, "0.1.0", 1_000, || Ok(r#"{"version":"0.2.0"}"#.into())).unwrap(); + assert_eq!(said, Some("0.2.0".into())); + assert_eq!(found(root, "0.1.0"), Some("0.2.0".into())); + assert!(!due(root, 1_000 + EVERY.as_secs() - 1)); + assert!(due(root, 1_000 + EVERY.as_secs())); + // A clock that went backwards is due, not stuck for years. + assert!(due(root, 10)); + // Once this program is that version, nothing is newer. + assert_eq!(found(root, "0.2.0"), None); + } + + #[test] + fn a_failed_look_says_nothing_and_still_counts() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + look(root, "0.1.0", 1_000, || Ok(r#"{"version":"0.2.0"}"#.into())).unwrap(); + let err = look(root, "0.1.0", 2_000, || Err("offline".into())).unwrap_err(); + assert_eq!(err, "offline"); + assert_eq!(found(root, "0.1.0"), None, "what was found is forgotten"); + assert!(!due(root, 2_001), "the failed look counts"); + } + + #[cfg(unix)] + #[test] + fn the_note_is_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + look(dir.path(), "0.1.0", 1, || Ok("{}".into())).unwrap(); + let mode = |p: PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(dir.path().join("updates")), 0o700); + assert_eq!(mode(note_path(dir.path())), 0o600); + } +} diff --git a/crates/ledger-host/src/update.rs b/crates/ledger-host/src/update.rs index dea7e848..15d2d8f4 100644 --- a/crates/ledger-host/src/update.rs +++ b/crates/ledger-host/src/update.rs @@ -136,6 +136,17 @@ pub fn install_kind(exe: &Path, appimage: Option<&Path>) -> Install { if let Some(image) = appimage.filter(|p| p.is_file()) { return Install::SelfUpdating(image.to_path_buf()); } + // A macOS app is signed whole: one file replaced inside it breaks the + // signature, so it is only ever replaced whole, by the person (the + // newer .dmg), never by this program (WB-pkg-3). + if exe + .ancestors() + .skip(1) + .take(3) + .any(|dir| dir.extension().is_some_and(|e| e == "app") && dir.join("Contents").is_dir()) + { + return Install::PackageManaged("app".to_string()); + } if let Some(prefix) = exe.parent().and_then(Path::parent) && let Ok(text) = std::fs::read_to_string(prefix.join("share/wanderbooks/install-method")) { @@ -153,25 +164,20 @@ pub fn this_install() -> Result { } fn refuse_package_managed(manager: &str, what: &str) -> Failure { + if manager == "app" { + return format!( + "this is the macOS app, which is replaced whole and never one file at a time: get the newer Wanderbooks at {} and drag it over this one", + crate::newer::DOWNLOAD_PAGE + ) + .into(); + } format!( "this install is managed by {manager}, which also {what} it: use the package manager (our apt and dnf repositories keep every release, and the AUR keeps old PKGBUILDs)" ) .into() } -/// `1.2.3` as numbers; anything else (a pre-release, a `v`) is no version -/// of ours. -pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> { - let mut parts = text.split('.'); - let mut next = || -> Option { - let p = parts.next()?; - (!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) - .then(|| p.parse().ok()) - .flatten() - }; - let v = (next()?, next()?, next()?); - parts.next().is_none().then_some(v) -} +pub use crate::newer::parse_version; fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() @@ -966,6 +972,31 @@ mod tests { ); } + /// WB-pkg-3: a macOS app is signed whole, so this program never + /// replaces a file inside one; the person replaces the whole app. + #[test] + fn a_macos_app_is_never_updated_in_place() { + let dir = tempfile::tempdir().unwrap(); + let macos = dir.path().join("Wanderbooks.app/Contents/MacOS"); + std::fs::create_dir_all(&macos).unwrap(); + let exe = macos.join("wanderbooks"); + std::fs::write(&exe, b"x").unwrap(); + assert_eq!( + install_kind(&exe, None), + Install::PackageManaged("app".into()) + ); + let said = refuse_package_managed("app", "updates").to_string(); + assert!(said.contains("replaced whole"), "{said}"); + assert!(said.contains(crate::newer::DOWNLOAD_PAGE), "{said}"); + // A folder that only happens to be called .app, with no bundle in + // it, is not one. + let plain = dir.path().join("tools.app/bin"); + std::fs::create_dir_all(&plain).unwrap(); + let exe = plain.join("wanderbooks"); + std::fs::write(&exe, b"x").unwrap(); + assert_eq!(install_kind(&exe, None), Install::SelfUpdating(exe)); + } + #[test] fn a_public_key_is_read_in_every_form_minisign_and_the_packager_write_it() { let bare = "RWQdrs7W5/jf6drdD0G/ymxFmRWYAIOyggYlubz4NQzdQm5e/Fj0nrb0";