//! 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) }