From a3cb0e6032bbb1ce5737775008493b7ea63c6e4c Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 29 Sep 2026 04:17:54 +0000 Subject: [PATCH] host: updater (signed native updates and the hotfix channel) updater (tauri + net features): the launch handshake, the cached hotfix (re-verified on every load), the 30 min +/- 5 check loop, download and verification through tauri-plugin-updater, the size-capped hotfix fetch (no identifiers), hotfix delivery to the site's tabs, and status/apply/ ready for the app's shell-only commands. An UpdaterConfig carries what differs per app: SiteSpec, hotfix URL and public key, page global/event, manual download page, user agent and the "update ready" hook. --- crates/waybetter-host/Cargo.lock | 294 +++++++++++++++++++++++++-- crates/waybetter-host/Cargo.toml | 6 +- crates/waybetter-host/src/lib.rs | 5 +- crates/waybetter-host/src/updater.rs | 275 +++++++++++++++++++++++++ 4 files changed, 566 insertions(+), 14 deletions(-) create mode 100644 crates/waybetter-host/src/updater.rs diff --git a/crates/waybetter-host/Cargo.lock b/crates/waybetter-host/Cargo.lock index 74430e4..f4b550f 100644 --- a/crates/waybetter-host/Cargo.lock +++ b/crates/waybetter-host/Cargo.lock @@ -57,6 +57,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "arboard" version = "3.6.1" @@ -496,6 +505,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + [[package]] name = "cfb" version = "0.14.0" @@ -614,6 +634,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -637,7 +667,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types", "libc", @@ -650,7 +680,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "libc", ] @@ -854,6 +884,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -886,6 +927,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + [[package]] name = "dirs" version = "7.0.0" @@ -1165,6 +1215,16 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -1765,9 +1825,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -1951,13 +2013,22 @@ dependencies = [ "serde_core", ] +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb 0.7.3", +] + [[package]] name = "infer" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" dependencies = [ - "cfb", + "cfb 0.14.0", ] [[package]] @@ -2602,6 +2673,18 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + [[package]] name = "objc2-quartz-core" version = "0.3.2" @@ -2693,6 +2776,20 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "pango" version = "0.18.3" @@ -3297,7 +3394,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "jni 0.22.4", "log", @@ -3417,7 +3514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -3879,6 +3976,27 @@ dependencies = [ "libc", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "system-deps" version = "6.2.2" @@ -3900,7 +4018,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" dependencies = [ "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -3943,6 +4061,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.12.16" @@ -3958,7 +4087,7 @@ dependencies = [ "anyhow", "bytes", "cookie", - "dirs", + "dirs 7.0.0", "dunce", "embed_plist", "getrandom 0.3.4", @@ -4008,7 +4137,7 @@ checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644" dependencies = [ "anyhow", "cargo_toml", - "dirs", + "dirs 7.0.0", "glob", "heck 0.5.0", "json-patch", @@ -4097,6 +4226,39 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-updater" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fae4783480c5d97373b98ae9f2e70158ca992cdf29e04b236a42b1f82b1b3804" +dependencies = [ + "base64 0.22.1", + "dirs 6.0.0", + "flate2", + "futures-util", + "http", + "infer 0.19.0", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.21", + "time", + "tokio", + "url", + "windows-sys 0.60.2", + "zip", +] + [[package]] name = "tauri-runtime" version = "2.12.0" @@ -4162,7 +4324,7 @@ dependencies = [ "dunce", "glob", "http", - "infer", + "infer 0.22.0", "json-patch", "log", "memchr", @@ -4546,7 +4708,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" dependencies = [ "crossbeam-channel", - "dirs", + "dirs 7.0.0", "libappindicator", "muda", "objc2", @@ -4820,6 +4982,7 @@ dependencies = [ "sys-locale", "tauri", "tauri-plugin-notification", + "tauri-plugin-updater", "tempfile", "tokio", "url", @@ -5082,6 +5245,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -5127,6 +5301,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -5160,13 +5343,30 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + [[package]] name = "windows-threading" version = "0.2.1" @@ -5197,6 +5397,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -5209,6 +5415,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -5221,12 +5433,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -5239,6 +5463,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -5251,6 +5481,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -5263,6 +5499,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -5275,6 +5517,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.5.40" @@ -5325,7 +5573,7 @@ dependencies = [ "block2", "cookie", "crossbeam-channel", - "dirs", + "dirs 7.0.0", "dom_query", "dpi", "dunce", @@ -5397,6 +5645,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "yoke" version = "0.8.3" @@ -5570,6 +5828,18 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap 2.14.2", + "memchr", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/crates/waybetter-host/Cargo.toml b/crates/waybetter-host/Cargo.toml index f9818ce..ad45dd8 100644 --- a/crates/waybetter-host/Cargo.toml +++ b/crates/waybetter-host/Cargo.toml @@ -14,7 +14,7 @@ path = "src/lib.rs" [features] default = [] # Tauri glue (webview helpers, window system menu). Off for headless tests. -tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:arboard", "dep:clipboard-win", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"] +tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:tauri-plugin-updater", "dep:tokio", "dep:arboard", "dep:clipboard-win", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"] # Store downloads (`store::net`): allow-listed https, no redirects or cookies, size caps. net = ["dep:reqwest", "dep:rustls"] @@ -40,6 +40,10 @@ getrandom = "0.2" tauri = { version = "2", features = ["unstable"], optional = true } # Native OS notifications (alerts::notify); the app registers the plugin. tauri-plugin-notification = { version = "2", optional = true } +# Signed native updates (updater, with `net`); the app registers the plugin with its endpoint and key. +tauri-plugin-updater = { version = "2", optional = true } +# The updater loop's waits. +tokio = { version = "1", features = ["time"], optional = true } # Opt-in local clipboard history (media::clipboard), polled natively. arboard = { version = "3", optional = true } reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"], optional = true } diff --git a/crates/waybetter-host/src/lib.rs b/crates/waybetter-host/src/lib.rs index 8d7732b..b8da754 100644 --- a/crates/waybetter-host/src/lib.rs +++ b/crates/waybetter-host/src/lib.rs @@ -28,7 +28,8 @@ //! signed multi-app wayBetter Store (allow-list, caps, catalog signatures, staging, install records); //! downloads with the `net` feature. //! -//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state. +//! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state; with +//! `tauri` and `net`, [`updater`] runs signed native updates and the hotfix channel. pub mod alerts; pub mod backup; @@ -52,3 +53,5 @@ pub mod workspaces; #[cfg(feature = "tauri")] pub mod host; +#[cfg(all(feature = "tauri", feature = "net"))] +pub mod updater; diff --git a/crates/waybetter-host/src/updater.rs b/crates/waybetter-host/src/updater.rs new file mode 100644 index 0000000..d80ac1b --- /dev/null +++ b/crates/waybetter-host/src/updater.rs @@ -0,0 +1,275 @@ +//! Native updates (tauri-plugin-updater: the app's signed endpoint and public key from its +//! `tauri.conf.json`) and the signed, data-only hotfix channel, run from Rust (`tauri` + `net` +//! features). The scheduling and the crash handshake are [`crate::update`]; the hotfix format and +//! its verification are [`crate::hotfix`]. +//! +//! The app registers the updater plugin, calls [`init`] from `setup` with its [`UpdaterConfig`], +//! and wraps [`status`], [`apply`] and [`ready`] in its own shell-only commands; its shell gets an +//! `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data +//! ([`hotfix_script`]). + +use crate::hotfix::{self, Hotfix, Outcome}; +use crate::site::SiteSpec; +use crate::update::{self, PendingUpdate, UpdateStatus}; +use std::path::PathBuf; +use std::sync::Mutex; +use tauri::{AppHandle, Manager}; +use tauri_plugin_updater::{Update, UpdaterExt}; + +/// Shell event carrying the current [`UpdateStatus`]. +pub const EVENT: &str = "update-status"; +const HOTFIX_FILE: &str = "hotfix.json"; +const HOTFIX_SIG_FILE: &str = "hotfix.json.sig"; + +/// What differs between apps: the hotfix channel, the page names hotfix data is delivered under, +/// the manual download page and what to do when an update is ready. +pub struct UpdaterConfig { + /// Hotfix data goes to this site's tabs. + pub site: &'static SiteSpec, + /// Hotfix channel URL (`.sig` is appended for the signature). + pub hotfix_url: &'static str, + /// Hotfix public key (base64 of the minisign `.pub` file). + pub hotfix_pubkey: &'static str, + /// Page global and event the hotfix is delivered under (`window.`, ``). + pub hotfix_global: &'static str, + pub hotfix_event: &'static str, + /// Offered when an update keeps failing to start. + pub manual_download_url: &'static str, + /// Generic user agent of the hotfix fetch (no identifiers, no cookies). + pub user_agent: &'static str, + /// An update was downloaded and verified (`version`): e.g. a notification in the owner's language. + pub on_ready: fn(&AppHandle, &str), +} + +#[derive(Default)] +struct Inner { + status: Option, + /// A downloaded, signature-verified update waiting for the user's restart. + ready: Option<(Update, Vec)>, + hotfix: Option, + /// Automatic apply is off after repeated failed starts of an update. + problem: bool, +} + +struct UpdateState { + config: &'static UpdaterConfig, + inner: Mutex, +} + +fn status_of(config: &UpdaterConfig, inner: &Inner) -> UpdateStatus { + if inner.problem { + return UpdateStatus::Problem { download_url: config.manual_download_url.into() }; + } + inner.status.clone().unwrap_or(UpdateStatus::Idle) +} + +fn set_status(app: &AppHandle, status: UpdateStatus) { + let state = app.state::(); + let Ok(mut inner) = state.inner.lock() else { return }; + inner.status = Some(status); + let current = status_of(state.config, &inner); + drop(inner); + crate::host::emit_shell(app, EVENT, current); +} + +fn data_path(app: &AppHandle, name: &str) -> Option { + app.path().app_data_dir().ok().map(|dir| dir.join(name)) +} + +fn entropy() -> u64 { + let mut bytes = [0u8; 8]; + if getrandom::getrandom(&mut bytes).is_err() { + return std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0); + } + u64::from_le_bytes(bytes) +} + +/// Called from `setup`: runs the launch handshake, loads the cached hotfix and starts the loop +/// (first check after [`update::FIRST_CHECK`], then every 30 min +/- 5). +pub fn init(app: &AppHandle, config: &'static UpdaterConfig) { + let current = app.package_info().version.to_string(); + let pending_path = data_path(app, update::PENDING_FILE); + let pending = pending_path + .as_ref() + .and_then(|path| std::fs::read_to_string(path).ok()) + .and_then(|text| serde_json::from_str::(&text).ok()); + let decision = update::on_boot(pending, ¤t); + if let Some(path) = &pending_path { + match &decision.marker { + Some(marker) => { + let _ = std::fs::write(path, serde_json::to_string(marker).unwrap_or_default()); + } + None => { + let _ = std::fs::remove_file(path); + } + } + } + let hotfix = load_cached_hotfix(app, config, ¤t); + app.manage(UpdateState { config, inner: Mutex::new(Inner { problem: decision.problem, hotfix, ..Default::default() }) }); + + let app = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(update::FIRST_CHECK).await; + loop { + check_native(&app).await; + check_hotfix(&app).await; + tokio::time::sleep(update::next_check_delay(entropy())).await; + } + }); +} + +async fn check_native(app: &AppHandle) { + { + let state = app.state::(); + let Ok(inner) = state.inner.lock() else { return }; + // Already downloaded, or automatic apply disabled after failed starts. + // Also skip while an install is in flight (`ready` was taken by `apply`). + if inner.ready.is_some() || inner.problem || matches!(inner.status, Some(UpdateStatus::Installing { .. })) { + return; + } + } + set_status(app, UpdateStatus::Checking); + let update = match app.updater().map_err(|e| e.to_string()) { + Ok(updater) => updater.check().await.map_err(|e| e.to_string()), + Err(error) => Err(error), + }; + match update { + Ok(Some(update)) => { + let version = update.version.clone(); + set_status(app, UpdateStatus::Downloading { version: version.clone() }); + // The plugin verifies the minisign signature against the embedded pubkey here. + match update.download(|_, _| {}, || {}).await { + Ok(bytes) => { + let notes = update.body.clone().unwrap_or_default(); + let state = app.state::(); + if let Ok(mut inner) = state.inner.lock() { + inner.ready = Some((update, bytes)); + } + (state.config.on_ready)(app, &version); + set_status(app, UpdateStatus::Ready { version, notes }); + } + Err(error) => set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }), + } + } + Ok(None) => set_status(app, UpdateStatus::UpToDate), + // Offline or server trouble: stay quiet, try again next round. + Err(error) => set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }), + } +} + +fn load_cached_hotfix(app: &AppHandle, config: &UpdaterConfig, native: &str) -> Option { + let body = std::fs::read(data_path(app, HOTFIX_FILE)?).ok()?; + let sig = std::fs::read_to_string(data_path(app, HOTFIX_SIG_FILE)?).ok()?; + // Re-verified on every load: the cache on disk is not trusted either. Expired → defaults. + match hotfix::accept(config.hotfix_pubkey, &body, &sig, chrono::Utc::now(), native, None) { + Ok(Outcome::Accepted(hotfix)) => Some(hotfix), + _ => None, + } +} + +async fn fetch_limited(client: &reqwest::Client, url: &str, max: usize) -> Result, String> { + let response = client.get(url).send().await.map_err(|e| format!("HOTFIX: {e}"))?; + if !response.status().is_success() { + return Err(format!("HOTFIX: HTTP {}", response.status())); + } + if response.content_length().is_some_and(|len| len as usize > max) { + return Err("HOTFIX: response too large".into()); + } + // Stream with a hard cap: a chunked response without Content-Length must not grow unbounded. + let mut response = response; + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| format!("HOTFIX: {e}"))? { + if bytes.len() + chunk.len() > max { + return Err("HOTFIX: response too large".into()); + } + bytes.extend_from_slice(&chunk); + } + Ok(bytes) +} + +async fn check_hotfix(app: &AppHandle) { + if let Err(error) = try_check_hotfix(app).await { + let product = app.state::().config.site.product; + eprintln!("{product}: {error}"); + } +} + +async fn try_check_hotfix(app: &AppHandle) -> Result<(), String> { + let config = app.state::().config; + if rustls::crypto::CryptoProvider::get_default().is_none() { + let _ = rustls::crypto::ring::default_provider().install_default(); + } + // No identifiers: no cookies, no install id, a generic user agent. + let client = reqwest::Client::builder() + .user_agent(config.user_agent) + .timeout(std::time::Duration::from_secs(20)) + .build() + .map_err(|e| format!("HOTFIX: {e}"))?; + let body = fetch_limited(&client, config.hotfix_url, hotfix::MAX_BODY_BYTES).await?; + let sig_url = format!("{}.sig", config.hotfix_url); + let sig = fetch_limited(&client, &sig_url, hotfix::MAX_SIG_BYTES).await?; + let sig = String::from_utf8(sig).map_err(|_| "HOTFIX: signature is not text")?; + let native = app.package_info().version.to_string(); + let held = app.state::().inner.lock().ok().and_then(|inner| inner.hotfix.as_ref().map(|h| h.version)); + let Outcome::Accepted(hotfix) = hotfix::accept(config.hotfix_pubkey, &body, &sig, chrono::Utc::now(), &native, held)? else { + return Ok(()); + }; + if let (Some(body_path), Some(sig_path)) = (data_path(app, HOTFIX_FILE), data_path(app, HOTFIX_SIG_FILE)) { + let _ = std::fs::write(body_path, &body); + let _ = std::fs::write(sig_path, &sig); + } + let script = hotfix::script(&hotfix, config.hotfix_global, config.hotfix_event); + if let Ok(mut inner) = app.state::().inner.lock() { + inner.hotfix = Some(hotfix); + } + crate::host::eval_in_site_tabs(app, config.site, &script); + Ok(()) +} + +/// Hotfix data for a freshly loaded site document, if one is held. +pub fn hotfix_script(app: &AppHandle) -> Option { + let state = app.try_state::()?; + let inner = state.inner.lock().ok()?; + inner.hotfix.as_ref().map(|hotfix| hotfix::script(hotfix, state.config.hotfix_global, state.config.hotfix_event)) +} + +/// The current status (for the app's shell-only `update_status`). +pub fn status(app: &AppHandle) -> Result { + let state = app.try_state::().ok_or("UPDATE: state unavailable")?; + let inner = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?; + Ok(status_of(state.config, &inner)) +} + +/// Installs the downloaded update and restarts (the app's shell-only `apply_update`). On Windows +/// the quiet NSIS installer replaces the app and relaunches it (`/UPDATE /R`), and this process +/// exits inside `install`. +pub fn apply(app: &AppHandle) -> Result<(), String> { + let state = app.try_state::().ok_or("UPDATE: state unavailable")?; + let (update, bytes) = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?.ready.take().ok_or("UPDATE: no update is ready")?; + let version = update.version.clone(); + if let Some(path) = data_path(app, update::PENDING_FILE) { + let marker = PendingUpdate { version: version.clone(), boots: 0 }; + let _ = std::fs::write(path, serde_json::to_string(&marker).unwrap_or_default()); + } + set_status(app, UpdateStatus::Installing { version }); + if let Err(error) = update.install(&bytes) { + if let Some(path) = data_path(app, update::PENDING_FILE) { + let _ = std::fs::remove_file(path); + } + set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }); + return Err(format!("UPDATE: {error}")); + } + app.restart(); +} + +/// The shell reached a working state (the app's shell-only `app_ready`): confirms a +/// just-installed update and returns the status. +pub fn ready(app: &AppHandle) -> Result { + if let Some(path) = data_path(app, update::PENDING_FILE) { + let _ = std::fs::remove_file(path); + } + // `problem` is deliberately kept for this session: the shell always calls `app_ready` on + // mount, so clearing it here would hide the "Update problem" chip on the very launch that + // detected the failed starts. + status(app) +}