Skip to main content

toolblox_lib/
startup.rs

1//! Fail-closed release update gate shown before the main application state loads.
2
3use std::fs;
4#[cfg(not(debug_assertions))]
5use std::path::PathBuf;
6use std::sync::Mutex;
7use std::sync::atomic::{AtomicBool, Ordering};
8#[cfg(not(debug_assertions))]
9use std::time::{SystemTime, UNIX_EPOCH};
10
11#[cfg(not(debug_assertions))]
12use base64::Engine;
13#[cfg(not(debug_assertions))]
14use ed25519_dalek::{Signature, Verifier, VerifyingKey};
15#[cfg(not(debug_assertions))]
16use semver::Version;
17use serde::Serialize;
18#[cfg(not(debug_assertions))]
19use sha2::{Digest, Sha256};
20use tauri::{AppHandle, Manager};
21#[cfg(not(debug_assertions))]
22use tauri_plugin_updater::UpdaterExt;
23
24#[cfg(not(debug_assertions))]
25use crate::app_commands::Runtime;
26#[cfg(not(debug_assertions))]
27use crate::update::{HighestSeenStore, ManifestSignatureVerifier, ReleaseDecision};
28
29/// The startup phase shown by the startup screen, serialized with a `phase` tag.
30#[derive(Clone, Debug, Serialize)]
31#[cfg_attr(debug_assertions, allow(dead_code))]
32#[serde(tag = "phase", rename_all = "snake_case")]
33pub enum StartupView {
34    /// Checking the signed update manifest.
35    Checking,
36    /// Downloading and installing a required update.
37    Installing { version: String },
38    /// The update check passed and local data is ready.
39    Ready,
40    /// Startup stopped. The app stays closed until a retry succeeds.
41    Failed { message: String },
42}
43
44/// Shared startup phase, guarded so only one check runs at a time.
45pub struct StartupState {
46    view: Mutex<StartupView>,
47    in_progress: AtomicBool,
48}
49
50impl StartupState {
51    /// Starts in the checking phase.
52    pub fn new() -> Self {
53        Self {
54            view: Mutex::new(StartupView::Checking),
55            in_progress: AtomicBool::new(false),
56        }
57    }
58
59    /// Replaces the current phase.
60    fn set(&self, view: StartupView) {
61        *self.view.lock().unwrap_or_else(|error| error.into_inner()) = view;
62    }
63
64    /// Returns the current phase.
65    pub fn view(&self) -> StartupView {
66        self.view
67            .lock()
68            .unwrap_or_else(|error| error.into_inner())
69            .clone()
70    }
71}
72
73/// Waits until startup reaches the ready phase.
74pub async fn wait_until_ready(app: &AppHandle) {
75    loop {
76        if matches!(app.state::<StartupState>().view(), StartupView::Ready) {
77            return;
78        }
79        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
80    }
81}
82
83/// Verifies detached manifest signatures against the compiled-in public key.
84#[cfg(not(debug_assertions))]
85struct Ed25519Verifier {
86    public_key: VerifyingKey,
87}
88
89#[cfg(not(debug_assertions))]
90impl Ed25519Verifier {
91    /// Decodes a base64 raw 32-byte Ed25519 public key.
92    fn new(encoded: &str) -> Result<Self, String> {
93        let bytes = base64::engine::general_purpose::STANDARD
94            .decode(encoded.trim())
95            .map_err(|_| "The update manifest public key isn't valid.".to_string())?;
96        let bytes: [u8; 32] = bytes
97            .try_into()
98            .map_err(|_| "The update manifest public key has the wrong length.".to_string())?;
99        Ok(Self {
100            public_key: VerifyingKey::from_bytes(&bytes)
101                .map_err(|_| "The update manifest public key isn't valid.".to_string())?,
102        })
103    }
104}
105
106#[cfg(not(debug_assertions))]
107impl ManifestSignatureVerifier for Ed25519Verifier {
108    fn verify(&self, manifest_bytes: &[u8], detached_signature: &[u8]) -> Result<(), String> {
109        let encoded = std::str::from_utf8(detached_signature)
110            .map_err(|_| "The update manifest signature isn't text.".to_string())?;
111        let bytes = base64::engine::general_purpose::STANDARD
112            .decode(encoded.trim())
113            .map_err(|_| "The update manifest signature isn't valid base64.".to_string())?;
114        let signature = Signature::from_slice(&bytes)
115            .map_err(|_| "The update manifest signature has the wrong length.".to_string())?;
116        self.public_key
117            .verify(manifest_bytes, &signature)
118            .map_err(|_| "The update manifest signature didn't match.".to_string())
119    }
120}
121
122/// Stores the highest verified release version, for rollback protection.
123#[cfg(not(debug_assertions))]
124struct FileHighestSeen(PathBuf);
125
126#[cfg(not(debug_assertions))]
127impl HighestSeenStore for FileHighestSeen {
128    fn load(&self) -> Result<Option<Version>, String> {
129        match fs::read_to_string(&self.0) {
130            Ok(value) => Version::parse(value.trim()).map(Some).map_err(|_| {
131                "The saved update security state isn't valid. Would reinstalling Toolblox help?"
132                    .into()
133            }),
134            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
135            Err(_) => Err(
136                "The update security state couldn't be read. Is the data folder available?".into(),
137            ),
138        }
139    }
140
141    fn store(&self, version: &Version) -> Result<(), String> {
142        let parent = self.0.parent().ok_or_else(|| {
143            "The update security path isn't valid. Is the data folder available?".to_string()
144        })?;
145        fs::create_dir_all(parent).map_err(|_| {
146            "The update security state couldn't be saved. Is the data folder writable?".to_string()
147        })?;
148        let temporary = self.0.with_extension("tmp");
149        fs::write(&temporary, format!("{version}\n"))
150            .and_then(|_| crate::storage::replace_file(&temporary, &self.0))
151            .map_err(|_| {
152                "The update security state couldn't be saved. Is the data folder writable?"
153                    .to_string()
154            })
155    }
156}
157
158/// Runs the startup update check unless one is already running, recording the outcome.
159pub async fn run(app: AppHandle) {
160    let state = app.state::<StartupState>();
161    if state.in_progress.swap(true, Ordering::SeqCst) {
162        return;
163    }
164    state.set(StartupView::Checking);
165    let result = run_inner(&app).await;
166    if let Err(message) = result {
167        log::error!("Startup stopped: {message}");
168        state.set(StartupView::Failed { message });
169    }
170    state.in_progress.store(false, Ordering::SeqCst);
171}
172
173/// Downloads and verifies the signed manifest, then either opens the app or installs the
174/// required update and restarts.
175///
176/// Release builds need the manifest URL and public keys at compile time. The installer must match
177/// the manifest's version, URL, updater signature, and SHA-256. Debug builds skip the check.
178async fn run_inner(app: &AppHandle) -> Result<(), String> {
179    #[cfg(debug_assertions)]
180    {
181        log::debug!("Debug build: the update check is skipped");
182        prepare_local_data(&app.state::<crate::app_commands::Runtime>())?;
183        app.state::<StartupState>().set(StartupView::Ready);
184        Ok(())
185    }
186
187    #[cfg(not(debug_assertions))]
188    {
189        let endpoint = option_env!("TOOLBLOX_UPDATE_MANIFEST_URL")
190            .filter(|value| value.starts_with("https://"))
191            .ok_or_else(|| "This build doesn't have a secure update endpoint. Would reinstalling Toolblox from the official release help?".to_string())?;
192        let manifest_key = option_env!("TOOLBLOX_MANIFEST_PUBLIC_KEY")
193            .ok_or_else(|| "This build doesn't have an update manifest key. Would reinstalling Toolblox from the official release help?".to_string())?;
194        let updater_key = option_env!("TOOLBLOX_UPDATER_PUBLIC_KEY")
195            .ok_or_else(|| "This build doesn't have an updater key. Would reinstalling Toolblox from the official release help?".to_string())?;
196        let runtime = app.state::<Runtime>();
197        let manifest_response = runtime.client.get(endpoint).send().await.map_err(|_| {
198            "Toolblox couldn't check for updates. Is the connection working?".to_string()
199        })?;
200        if !manifest_response.status().is_success() {
201            return Err(format!(
202                "The update service returned status {}. Can you try again?",
203                manifest_response.status().as_u16()
204            ));
205        }
206        let manifest_bytes = crate::app_commands::read_response_limited(
207            manifest_response,
208            1024 * 1024,
209            "The update information is larger than 1 MB. Can you try again later?",
210            "The update information couldn't be read. Can you try again?",
211        )
212        .await?;
213        let signature_response = runtime
214            .client
215            .get(format!("{endpoint}.sig"))
216            .send()
217            .await
218            .map_err(|_| {
219                "The update signature couldn't be downloaded. Is the connection working?"
220                    .to_string()
221            })?;
222        if !signature_response.status().is_success() {
223            return Err("The update signature isn't available. Can you try again later?".into());
224        }
225        let signature_bytes = crate::app_commands::read_response_limited(
226            signature_response,
227            8 * 1024,
228            "The update signature is too large. Can you try again later?",
229            "The update signature couldn't be read. Can you try again?",
230        )
231        .await?;
232        let verified = crate::update::verify_and_parse(
233            &manifest_bytes,
234            &signature_bytes,
235            &Ed25519Verifier::new(manifest_key)?,
236        )
237        .map_err(|error| error.to_string())?;
238        let installed = Version::parse(env!("CARGO_PKG_VERSION")).map_err(|_| {
239            "This Toolblox version isn't valid. Would reinstalling Toolblox help?".to_string()
240        })?;
241        let target = tauri_plugin_updater::target().ok_or_else(|| {
242            "Updates aren't supported on this platform. Is this device running Windows or macOS?".to_string()
243        })?;
244        let now = SystemTime::now()
245            .duration_since(UNIX_EPOCH)
246            .map_err(|_| "The system clock isn't valid. Can you correct it?".to_string())?
247            .as_secs();
248        let decision = crate::update::decide_and_record(
249            &verified,
250            &installed,
251            "stable",
252            &target,
253            now,
254            &FileHighestSeen(runtime.storage.root().join("highest-update-version")),
255        )
256        .map_err(|error| error.to_string())?;
257        match decision {
258            ReleaseDecision::Current { .. } => {
259                log::info!("Update check passed: {installed} is current");
260                prepare_local_data(&runtime)?;
261                app.state::<StartupState>().set(StartupView::Ready);
262                Ok(())
263            }
264            ReleaseDecision::UpdateRequired { version, artifact } => {
265                log::info!("Update required: installing {version} over {installed}");
266                app.state::<StartupState>().set(StartupView::Installing {
267                    version: version.to_string(),
268                });
269                let endpoint = endpoint.parse().map_err(|_| {
270                    "The update endpoint isn't valid. Would reinstalling Toolblox help?".to_string()
271                })?;
272                let update = app
273                    .updater_builder()
274                    .pubkey(updater_key)
275                    .endpoints(vec![endpoint])
276                    .map_err(|error| error.to_string())?
277                    .build()
278                    .map_err(|error| error.to_string())?
279                    .check()
280                    .await
281                    .map_err(|error| error.to_string())?
282                    .ok_or_else(|| {
283                        "The installer didn't offer the verified update. Can you try again?"
284                            .to_string()
285                    })?;
286                if update.version != version.to_string()
287                    || update.download_url.as_str() != artifact.url
288                    || update.signature != artifact.signature
289                {
290                    return Err("The update changed during verification. Can you try again?".into());
291                }
292                let bytes = update
293                    .download(|_, _| {}, || {})
294                    .await
295                    .map_err(|error| error.to_string())?;
296                let digest = hex::encode(Sha256::digest(&bytes));
297                if !digest.eq_ignore_ascii_case(&artifact.sha256) {
298                    return Err(
299                        "The downloaded update checksum doesn't match. Can you try again?".into(),
300                    );
301                }
302                update.install(bytes).map_err(|error| error.to_string())?;
303                log::info!("Update {version} installed, restarting");
304                log::logger().flush();
305                app.restart();
306            }
307            #[cfg(debug_assertions)]
308            ReleaseDecision::DebugBypass => Ok(()),
309        }
310    }
311}
312
313/// Creates the widget folder. Development builds also add the example widget.
314fn prepare_local_data(runtime: &crate::app_commands::Runtime) -> Result<(), String> {
315    fs::create_dir_all(&runtime.widgets_root)
316        .map_err(|_| "Toolblox couldn't create the widget folder. Is it writable?".to_string())?;
317    #[cfg(debug_assertions)]
318    if let Err(error) = crate::widgets::add_example_widget(&runtime.widgets_root) {
319        log::warn!("Example widget unavailable: {error}");
320    }
321    Ok(())
322}
323
324/// Returns the current startup phase to the startup screen.
325#[tauri::command]
326pub fn startup_status(state: tauri::State<'_, StartupState>) -> StartupView {
327    state.view()
328}
329
330/// Runs the startup check again after a failure.
331#[tauri::command]
332pub async fn retry_startup_update(app: AppHandle) {
333    run(app).await;
334}
335
336/// Exits the app from the startup screen.
337#[tauri::command]
338pub fn quit_startup(app: AppHandle) {
339    app.exit(0);
340}