From e3a62aa6ae8dd8496329b36994634052e7d91b24 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Tue, 24 Nov 2026 21:49:35 +0100 Subject: [PATCH] app: check Gitea releases and install update capsules The app asks the project's Gitea release list about five seconds after startup and every six hours. A stable release beats a newer prerelease, and a release is offered only when its tag is newer than the running build and it carries a .capsule asset for this target. A capsule is a ZIP with capsule.json and a payload. Every payload file carries its size and BLAKE3 digest in the manifest, and staging rejects absolute paths, parent segments, undeclared entries, digest mismatches, and versions that are not newer. The verified payload is stored under the app data directory, so a download survives a restart. The manifest and archive format live in crates/capsule-format, shared by the app's verifier and the release tool. Settings > Advanced shows the state, the notes, and the download and install buttons. The status bar shows an accent chip while an update is waiting. Install copies the app to a temp helper, asks the daemon to stop, and quits. The helper waits for the process, swaps the files with a rollback copy of each old file, removes stale files, and starts the new app. A failed swap puts the old files back and logs the reason. --check-updates runs the release check from a shell. The release tool in tools/capsule builds a capsule from the same files the installer puts down, using packager.toml, so a release does not need an installed copy. docs/updates.md covers the format and the release steps. --- .gitignore | 2 + AGENTS.md | 6 +- app/Cargo.lock | 15 + app/Cargo.toml | 6 + app/README.md | 22 + app/packager.toml | 4 + app/src/app.rs | 120 ++- app/src/main.rs | 30 + app/src/screens/settings.rs | 92 ++ app/src/update.rs | 1458 ++++++++++++++++++++++++++++++ crates/capsule-format/Cargo.lock | 419 +++++++++ crates/capsule-format/Cargo.toml | 13 + crates/capsule-format/src/lib.rs | 365 ++++++++ docs/updates.md | 152 ++++ tools/capsule/Cargo.lock | 489 ++++++++++ tools/capsule/Cargo.toml | 12 + tools/capsule/src/main.rs | 336 +++++++ 17 files changed, 3535 insertions(+), 6 deletions(-) create mode 100644 app/src/update.rs create mode 100644 crates/capsule-format/Cargo.lock create mode 100644 crates/capsule-format/Cargo.toml create mode 100644 crates/capsule-format/src/lib.rs create mode 100644 docs/updates.md create mode 100644 tools/capsule/Cargo.lock create mode 100644 tools/capsule/Cargo.toml create mode 100644 tools/capsule/src/main.rs diff --git a/.gitignore b/.gitignore index a80076b..92cadfa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /.rhema/ /app/vendor/rune/target +/tools/capsule/target +/crates/capsule-format/target diff --git a/AGENTS.md b/AGENTS.md index 1cea3bc..487e69c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,11 +1,13 @@ # Working in this repository The repository holds two Rust programs: `record-daemon/` (the recorder) and `app/` (the rune -front end). +front end). The release tool under `tools/capsule/` and the capsule format it shares with the +app under `crates/capsule-format/` are built only for releases. ## Before every commit -In `app/` and in `record-daemon/`, all of these must pass: +In `app/`, `record-daemon/`, `tools/capsule/`, and `crates/capsule-format/`, all of these must +pass: ```sh cargo fmt diff --git a/app/Cargo.lock b/app/Cargo.lock index b8bb2c0..842c6f2 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -530,6 +530,17 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "capsule-format" +version = "0.1.0" +dependencies = [ + "blake3", + "semver", + "serde", + "serde_json", + "zip", +] + [[package]] name = "cc" version = "1.11.2" @@ -1549,6 +1560,8 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" name = "leaguerecorder" version = "0.3.3" dependencies = [ + "blake3", + "capsule-format", "chrono", "directories", "ffmpeg-sidecar", @@ -1556,6 +1569,7 @@ dependencies = [ "rune", "rune-kit", "rune-notify", + "semver", "serde", "serde_json", "tokio", @@ -1564,6 +1578,7 @@ dependencies = [ "windows", "winreg", "winresource", + "zip", ] [[package]] diff --git a/app/Cargo.toml b/app/Cargo.toml index a6c146e..4347675 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -17,6 +17,7 @@ winresource = "0.1" rune = { path = "vendor/rune/crates/rune", features = ["native-file-dialog"] } rune-kit = { path = "vendor/rune/crates/rune-kit" } rune-notify = { path = "vendor/rune/crates/rune-notify" } +capsule-format = { path = "../crates/capsule-format" } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -26,6 +27,11 @@ tokio = { version = "1", features = ["rt", "net", "io-util", "time", "sync"] } uuid = { version = "1", features = ["v4", "serde"] } ffmpeg-sidecar = "2.7" ureq = "3.5" +# Updates: the Gitea release list over ureq, a capsule is a ZIP, and every file in it carries +# a BLAKE3 digest. +semver = "1" +blake3 = "1" +zip = { version = "9.6", default-features = false, features = ["deflate-flate2"] } # PNG decode of the bundled tray icon; the same crate and features rune itself uses. image = { version = "0.25", default-features = false, features = ["png"] } diff --git a/app/README.md b/app/README.md index 4c8fd71..9e6dd64 100644 --- a/app/README.md +++ b/app/README.md @@ -74,6 +74,7 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti | `src/export.rs` | ffmpeg clip export, the clips folder it fills and its miniatures | | `src/os.rs` | Run key, toasts, tray icon and menu | | `src/ui.rs` | Colours, cards, switches, sliders, buttons | +| `src/update.rs` | Release checks, the capsule format, staging, and the apply helper | | `src/screens/` | Settings, match history, clips, game review, the recording in progress | ## Where this stands against TODO.txt @@ -118,6 +119,9 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti runtime beside the exe. `cargo install cargo-packager --locked && cargo packager --release`. On the first run the app downloads ffmpeg (`--fetch-ffmpeg` does it from a shell), so clip export is ready before the first clip. The installer has not been run on a clean VM yet. +10. Updates: the app checks Gitea releases, downloads a capsule, verifies it, and restarts into + a helper that swaps the files. The apply path has been exercised on a scratch folder; it has + not run against a capsule published on Gitea yet. ### The recording screen @@ -136,6 +140,24 @@ in Match history as a game that never happened, next to one with no champion. Th the open timeline into the one holding the video (`history::close_stopped`), and "Stop and delete" removes the clip and both. +## Updates + +The app checks the project's Gitea releases about five seconds after startup, then every six +hours. Settings > Advanced has the running version, the result, and the buttons that download a +release and restart to install it. A release carries a `.capsule` asset: a ZIP with +`capsule.json` at the root and every install file under `payload/`. The manifest names each +file with a size and BLAKE3 digest, and the app checks every one before it stages the update. + +`../tools/capsule` builds a capsule from the release tree and `packager.toml`, without an +installed copy. `--check-updates` runs the same check from a shell. The restart starts a copy +of the app from the temp folder; that copy waits for the app and daemon to exit, replaces the +files, and starts the new app. A failed replace puts the old files back and writes +`update.log` under the app data directory. `../docs/updates.md` has the format, the release +steps, and the limits. + +The capsule is not signed. HTTPS and the per-file digests detect a broken or truncated +download, not a server that serves a matching capsule. + ### Known gaps - Item images are not drawn. Champion portraits download from Data Dragon on first sight and are diff --git a/app/packager.toml b/app/packager.toml index a5a16d6..744f3cd 100644 --- a/app/packager.toml +++ b/app/packager.toml @@ -3,6 +3,10 @@ # The app exe is the cargo binary. Everything the daemon needs at run time sits beside it in the # install root: the daemon, OBS and its data are built into record-daemon/target/release by the # daemon's own build and copied from there. The app downloads ffmpeg itself on the first export. +# After packaging, build the matching update capsule from the same release files and upload it +# to the Gitea release: +# cargo run --manifest-path ../tools/capsule/Cargo.toml -- --config packager.toml +# See ../docs/updates.md for the format and the release steps. "$schema" = "https://raw.githubusercontent.com/crabnebula-dev/cargo-packager/main/crates/packager/schema.json" name = "leaguerecorder" diff --git a/app/src/app.rs b/app/src/app.rs index 25ece54..dbab10d 100644 --- a/app/src/app.rs +++ b/app/src/app.rs @@ -2,9 +2,9 @@ use std::path::PathBuf; use std::sync::mpsc::{Receiver, TryRecvError, channel}; -use std::time::Duration; +use std::time::{Duration, Instant}; -use rune::tok::type_; +use rune::tok::{radius, type_}; use rune::{ChromeInsets, Cx, El, Key, KeyEvent, Tx, col, el, row, text}; use crate::export::{self, Clip}; @@ -188,6 +188,11 @@ pub struct App { /// ffmpeg being downloaded on the first run, and the whole percent it last reported. pub ffmpeg_rx: Option>, pub ffmpeg_pct: Option, + /// The release check, the capsule being downloaded, and the one waiting to install. + pub update: crate::update::Updates, + /// When the user pressed Restart and install: the daemon gets a moment to stop before + /// the app quits and the helper replaces its files. + pub quitting_for_update: Option, pub autostart: bool, pub logs: String, pub pending_review: bool, @@ -251,6 +256,8 @@ impl App { notice: None, ffmpeg_rx: None, ffmpeg_pct: None, + update: crate::update::Updates::new(), + quitting_for_update: None, autostart, logs: String::new(), pending_review: false, @@ -368,6 +375,7 @@ impl App { }, ]; self.form.apply(&settings); + self.update.demo_available(); // The sample sources read as a running process and one that is not, so a snapshot // shows both states of the chip. self.processes = settings @@ -765,6 +773,11 @@ pub fn setup(app: &mut App, waker: rune::Waker) { app.icons = Some(rune::ImageCache::new(waker.clone())); app.thumbs = Some(rune::ImageCache::new(waker.clone())); app.daemon.set_waker(waker.clone()); + // A snapshot run reads nothing from the network: the update card keeps its "not checked" + // state unless the scene gives it demo data. + if headless() { + app.update.auto = false; + } app.refresh_settings(); app.refresh_games(); app.daemon.get_status(); @@ -841,10 +854,65 @@ impl App { } } +impl App { + /// Keep the release check moving and turn its results into notices. The worker sends on a + /// channel, so this never waits on the network. + fn poll_updates(&mut self, t: f64) -> bool { + let (news, arrived) = self.update.drain(); + let mut changed = arrived; + for news in news { + changed = true; + match news { + crate::update::News::Available(available) => self.notify(format!( + "League Recorder {} is available. Settings > Advanced downloads it.", + available.version + )), + crate::update::News::UpToDate => self.notify("League Recorder is up to date"), + crate::update::News::Ready(staged) => self.notify(format!( + "Update {} is ready. Restart from Settings > Advanced to install it.", + staged.version + )), + crate::update::News::Error(e) => self.notify_error(format!("Update: {e}")), + } + } + changed | self.update.tick(t) + } + + /// Download and install the staged capsule. The update helper waits for this process to + /// exit, so the app stays up long enough to ask the daemon to stop and flush that request. + pub fn install_update(&mut self, tx: &mut Tx) { + if self.status.is_recording { + self.notify_error("Stop the recording before installing an update."); + return; + } + match self.update.install() { + Ok(()) => { + self.daemon.shutdown(); + self.quitting_for_update = Some(Instant::now()); + self.notify("Restarting to install the update..."); + tx.wake_after(Duration::from_millis(300)); + } + Err(e) => self.notify_error(e), + } + } +} + impl App { fn handle_poll(&mut self, t: f64, tx: &mut Tx) -> bool { let mut changed = false; + // A staged update asks the daemon to stop, then quits so the helper can replace the + // files. The short pause is for the shutdown request to leave this process. + if let Some(at) = self.quitting_for_update { + if at.elapsed() >= Duration::from_millis(1500) { + tx.quit(); + } else { + tx.wake_after(Duration::from_millis(200)); + } + } + + changed |= self.poll_updates(t); + // Being full screen is a state of the window, not only of the review: the view drops // the title bar and the status bar the moment the review asks for it, and the window // follows in the same frame. Any way out of the review, or off the screen it was on, @@ -1275,8 +1343,11 @@ fn statusbar(p: Paint, app: &App) -> El { .key("status-text") .font(body(11.5)) .color(p.muted()), - ) - .child(el().grow(1.0)); + ); + if let Some(chip) = update_chip(app, p) { + bar = bar.child(chip); + } + bar = bar.child(el().grow(1.0)); if let Some(note) = recording { bar = bar.child( text(note) @@ -1288,6 +1359,47 @@ fn statusbar(p: Paint, app: &App) -> El { bar } +/// The status bar's way into a pending update. Accent ink marks it as an action rather than a +/// daemon state; a staged update says it is ready instead of available. +fn update_chip(app: &App, p: Paint) -> Option { + use crate::update::Phase; + let (label, version) = match (&app.update.phase, &app.update.available, &app.update.staged) { + (Phase::Staged, _, Some(staged)) => ("Update ready", staged.version.to_string()), + (Phase::Available | Phase::Failed, Some(available), _) => { + ("Update available", available.version.to_string()) + } + _ => return None, + }; + Some( + el().key("update-chip") + .role("button") + .label(format!("{label}, version {version}")) + .focusable(true) + .h(20.0) + .px(8.0) + .gap(6.0) + .center_y() + .radius(radius::SM) + .fill(p.accent.alpha(0.14)) + .border(p.hair, p.accent.alpha(0.32)) + .hover(p.accent.alpha(0.22)) + .press(p.accent.alpha(0.3)) + .on_press_tx(|app: &mut App, tx: &mut Tx| { + app.jump(Screen::Settings); + app.settings_tab = SettingsTab::Advanced; + tx.scroll_to("scroller", 0.0, 0.0); + }) + .child(ui::dot(p.accent)) + .child( + text(format!("{label} ยท {version}")) + .key("label") + .font(body(10.5)) + .color(p.accent) + .a11y_hidden(), + ), + ) +} + /// What the back arrow says it returns to. fn back_label(screen: Screen) -> &'static str { match screen { diff --git a/app/src/main.rs b/app/src/main.rs index 8041033..d0d5389 100644 --- a/app/src/main.rs +++ b/app/src/main.rs @@ -23,6 +23,7 @@ mod screens; mod settings; mod theme; mod ui; +mod update; /// Print to the shell that started this app, when there is one. /// @@ -55,6 +56,20 @@ fn demo_recording(app: &mut app::App) { fn main() { attach_console(); + // The update helper is this same exe in apply mode: no window and no single-instance lock. + if let Some(index) = std::env::args().position(|arg| arg == "--apply-update") { + let args: Vec = std::env::args().skip(index + 1).collect(); + update::run_apply(&args); + return; + } + if std::env::args().any(|arg| arg == "--version") { + println!("leaguerecorder {}", update::current_version()); + return; + } + if std::env::args().any(|arg| arg == "--check-updates") { + check_updates(); + return; + } if std::env::args().any(|arg| arg == "--games") { println!("{} timelines", crate::history::timeline_paths().len()); return; @@ -232,6 +247,21 @@ fn fetch_ffmpeg() { } } +/// `--check-updates`: ask the release list whether a newer capsule exists, then print it. +fn check_updates() { + match update::check(&update::releases_url()) { + Ok(Some(available)) => println!( + "{} is available: {} ({})", + available.version, available.asset, available.url + ), + Ok(None) => println!("up to date ({})", update::current_version()), + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + } +} + /// `--probe`: bring the daemon up and print what it answers, then exit. A quick check that the /// IPC client and the daemon agree without opening a window. fn probe() { diff --git a/app/src/screens/settings.rs b/app/src/screens/settings.rs index f8f9966..0bf0d87 100644 --- a/app/src/screens/settings.rs +++ b/app/src/screens/settings.rs @@ -930,6 +930,17 @@ fn captioned_field( )) } +/// The first lines of a release note, enough to say what changed without turning the card +/// into a document. +fn notes_excerpt(notes: &str) -> String { + let mut text = notes.lines().take(6).collect::>().join("\n"); + if let Some((cut, _)) = text.char_indices().nth(700) { + text.truncate(cut); + text.push_str("..."); + } + text +} + fn advanced(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec, content: El) -> El { let status_row = |key: &str, label: &'static str, value: String| { row() @@ -951,7 +962,88 @@ fn advanced(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec, conte }; let recording = if app.status.is_recording { "yes" } else { "no" }; + let mut update_rows = vec![ + status_row("app-version", "Version", app.update.current.to_string()), + status_row("update-status", "Status", app.update.status_text()), + ]; + if let Some(available) = &app.update.available { + if let Some(published) = available.published.as_deref() { + let shown = chrono::DateTime::parse_from_rfc3339(published) + .map(|at| crate::format::relative_time(at.with_timezone(&chrono::Utc))) + .unwrap_or_else(|_| published.to_string()); + update_rows.push(status_row("update-published", "Published", shown)); + } + if !available.notes.trim().is_empty() { + update_rows.push( + row() + .key("update-notes") + .w_full() + .px(space::S3) + .py(space::S2) + .child( + text(notes_excerpt(&available.notes)) + .key("notes") + .font(body(11.5)) + .color(p.muted()) + .w_full(), + ), + ); + } + } + if app.update.can_check() || app.update.can_download() || app.update.can_install() { + let mut actions = row() + .key("update-actions") + .w_full() + .gap(8.0) + .px(space::S3) + .py(space::S2) + .center_y(); + if app.update.can_check() { + actions = actions.child(ui::button( + p, + "update-check", + "Check now", + false, + |app: &mut App| app.update.check(true), + )); + } + if app.update.can_download() { + let available = app.update.available.as_ref(); + let version = available + .map(|available| available.version.to_string()) + .unwrap_or_default(); + let size = available + .map(|available| format!(" ({})", crate::format::bytes(available.size))) + .unwrap_or_default(); + actions = actions.child(ui::button( + p, + "update-download", + &format!("Download {version}{size}"), + true, + |app: &mut App| app.update.download(), + )); + } + if app.update.can_install() { + actions = actions.child(ui::button_tx( + p, + "update-install", + "Restart and install", + true, + |app: &mut App, tx: &mut rune::Tx| app.install_update(tx), + )); + } + actions = actions.child(ui::button( + p, + "update-folder", + "Open update folder", + false, + |_app: &mut App| crate::daemon::open_folder(&crate::update::updates_dir()), + )); + update_rows.push(actions); + } + content + .child(ui::card(p, Some("Updates"), update_rows)) .child(ui::card( p, Some("Daemon"), diff --git a/app/src/update.rs b/app/src/update.rs new file mode 100644 index 0000000..5234028 --- /dev/null +++ b/app/src/update.rs @@ -0,0 +1,1458 @@ +//! Finding, downloading and installing updates. +//! +//! A release on the project's Gitea carries a `.capsule` asset. A capsule is a ZIP with +//! `capsule.json` at the root and every installed file under `payload/`. The manifest names +//! each file with its size and BLAKE3 digest, so a download either matches the release or is +//! refused. +//! +//! The app checks the release list on a worker thread, downloads and verifies a capsule into +//! the user's data directory, then starts a copy of itself in apply mode. That copy waits for +//! the app to exit, swaps the files, and starts the new app. + +use capsule_format::{Manifest, PRODUCT, default_entry, target}; +use semver::Version; +use std::collections::HashSet; +use std::fs::{self, File}; +use std::io::{BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; +use std::time::{Duration, Instant, SystemTime}; + +/// The release list the app reads by default. Set `LEAGUERECORDER_RELEASES_URL` to point a +/// build at a mirror or a test server. +pub const DEFAULT_RELEASES_URL: &str = + "https://git.vhaudiquet.fr/api/v1/repos/vhaudiquet/leaguerecorder/releases"; +/// How often an automatic check runs, in seconds. +pub const AUTO_CHECK_SECS: f64 = 6.0 * 60.0 * 60.0; +/// The delay before the first automatic check, so startup does not wait on the network. +const FIRST_CHECK_SECS: f64 = 5.0; +/// A capsule larger than this is refused before the download starts. +const MAX_CAPSULE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +const USER_AGENT: &str = concat!("leaguerecorder/", env!("CARGO_PKG_VERSION")); + +/// The version this build reports. The release check compares against it. +pub fn current_version() -> Version { + env!("CARGO_PKG_VERSION") + .parse() + .unwrap_or_else(|_| Version::new(0, 0, 0)) +} + +/// The configured release list, or the project's own. +pub fn releases_url() -> String { + std::env::var("LEAGUERECORDER_RELEASES_URL") + .ok() + .map(|url| url.trim().to_string()) + .filter(|url| !url.is_empty()) + .unwrap_or_else(|| DEFAULT_RELEASES_URL.to_string()) +} + +/// Where staged updates and the apply log live. The app's own data directory, not the +/// daemon's, because an update replaces both programs. +pub fn updates_dir() -> PathBuf { + if let Some(dir) = std::env::var_os("LEAGUERECORDER_UPDATE_DIR").filter(|v| !v.is_empty()) { + return PathBuf::from(dir); + } + directories::ProjectDirs::from("com", "leaguerecorder", "leaguerecorder") + .map(|dirs| dirs.data_local_dir().join("updates")) + .unwrap_or_else(|| std::env::temp_dir().join("leaguerecorder-updates")) +} + +// --------------------------------------------------------------------------- +// Releases +// --------------------------------------------------------------------------- + +/// One release from the Gitea API. Fields other than these are ignored. +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Release { + #[serde(default)] + pub tag_name: String, + #[serde(default)] + pub body: String, + #[serde(default)] + pub draft: bool, + #[serde(default)] + pub prerelease: bool, + #[serde(default)] + pub published_at: Option, + #[serde(default)] + pub assets: Vec, +} + +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Asset { + pub name: String, + #[serde(default)] + pub size: u64, + #[serde(default)] + pub browser_download_url: String, +} + +/// A newer release with a capsule to download. +#[derive(Debug, Clone)] +pub struct Available { + pub version: Version, + pub asset: String, + pub url: String, + pub size: u64, + pub notes: String, + pub published: Option, + pub prerelease: bool, +} + +/// Read the tag as a version. The project tags releases `v0.3.3`; a plain `0.3.3` works too. +fn parse_tag(tag: &str) -> Option { + let tag = tag.trim(); + let tag = tag + .strip_prefix('v') + .or_else(|| tag.strip_prefix('V')) + .unwrap_or(tag); + Version::parse(tag).ok() +} + +/// The capsule asset in a release, preferring one built for this target. +fn pick_asset(release: &Release) -> Option<&Asset> { + let mut fallback = None; + for asset in &release.assets { + let name = asset.name.to_ascii_lowercase(); + if !name.ends_with(".capsule") || asset.browser_download_url.is_empty() { + continue; + } + if name.contains(target()) { + return Some(asset); + } + fallback.get_or_insert(asset); + } + fallback +} + +/// The newest release with a capsule, by version. Stable releases win when one exists; this +/// project marks every release prerelease, so prereleases are the normal case rather than a +/// reason to find nothing. +pub fn latest(releases: &[Release], current: &Version) -> Option { + let (version, release, asset) = + pick(releases, current, false).or_else(|| pick(releases, current, true))?; + Some(Available { + version, + asset: asset.name.clone(), + url: asset.browser_download_url.clone(), + size: asset.size, + notes: release.body.clone(), + published: release.published_at.clone(), + prerelease: release.prerelease, + }) +} + +fn pick<'a>( + releases: &'a [Release], + current: &Version, + allow_prerelease: bool, +) -> Option<(Version, &'a Release, &'a Asset)> { + let mut best: Option<(Version, &'a Release, &'a Asset)> = None; + for release in releases { + if release.draft || (release.prerelease && !allow_prerelease) { + continue; + } + let Some(version) = parse_tag(&release.tag_name) else { + continue; + }; + if version <= *current { + continue; + } + let Some(asset) = pick_asset(release) else { + continue; + }; + let higher = best.as_ref().is_none_or(|(best, _, _)| version > *best); + if higher { + best = Some((version, release, asset)); + } + } + best +} + +fn read_json(url: &str, limit: u64) -> Result, String> { + let mut response = ureq::get(url) + .header("Accept", "application/json") + .header("User-Agent", USER_AGENT) + .config() + .timeout_global(Some(Duration::from_secs(20))) + .build() + .call() + .map_err(|e| format!("the release page could not be read: {e}"))?; + let mut reader = response.body_mut().as_reader().take(limit); + let mut bytes = Vec::new(); + reader + .read_to_end(&mut bytes) + .map_err(|e| format!("the release page ended early: {e}"))?; + Ok(bytes) +} + +/// Ask the release list for a newer version. No update is `Ok(None)`. +pub fn check(url: &str) -> Result, String> { + // Gitea pages the list; a page of 60 covers far more than the versions anyone skips. + let url = if url.contains('?') { + format!("{url}&limit=60") + } else { + format!("{url}?limit=60") + }; + let body = read_json(&url, 4 * 1024 * 1024)?; + let releases: Vec = serde_json::from_slice(&body) + .map_err(|e| format!("the release page did not parse: {e}"))?; + Ok(latest(&releases, ¤t_version())) +} + +// --------------------------------------------------------------------------- +// The capsule +// --------------------------------------------------------------------------- + +#[cfg(test)] +fn digest(bytes: &[u8]) -> String { + blake3::hash(bytes).to_hex().to_string() +} + +fn hash_file(path: &Path) -> Result<(u64, String), String> { + let mut file = File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + let mut hasher = blake3::Hasher::new(); + let mut size = 0u64; + let mut buf = [0u8; 64 * 1024]; + loop { + let read = file + .read(&mut buf) + .map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if read == 0 { + break; + } + size += read as u64; + hasher.update(&buf[..read]); + } + Ok((size, hasher.finalize().to_hex().to_string())) +} + +/// A capsule extracted and verified under the updates folder. +#[derive(Debug, Clone)] +pub struct Staged { + pub dir: PathBuf, + pub manifest: Manifest, + pub version: Version, +} + +/// Extract and verify a capsule into `root//`. The folder is created fresh, and a +/// capsule that fails any check leaves nothing behind. +pub fn stage_into(capsule: &Path, current: &Version, root: &Path) -> Result { + let file = + File::open(capsule).map_err(|e| format!("cannot open {}: {e}", capsule.display()))?; + let mut archive = zip::ZipArchive::new(file) + .map_err(|e| format!("the capsule is not a readable ZIP: {e}"))?; + + let manifest: Manifest = { + let mut entry = archive + .by_name("capsule.json") + .map_err(|_| "the capsule has no capsule.json".to_string())?; + let mut text = String::new(); + entry + .read_to_string(&mut text) + .map_err(|e| format!("cannot read capsule.json: {e}"))?; + serde_json::from_str(&text).map_err(|e| format!("capsule.json did not parse: {e}"))? + }; + manifest.validate()?; + let version = manifest.version()?; + if version <= *current { + return Err(format!( + "the capsule holds {version}, which is not newer than {current}" + )); + } + + // Every payload entry has to be in the manifest. A capsule cannot smuggle in a file that + // no digest covers. + let listed: HashSet<&str> = manifest + .files + .iter() + .map(|file| file.path.as_str()) + .collect(); + for index in 0..archive.len() { + let entry = archive + .by_index(index) + .map_err(|e| format!("cannot read a capsule entry: {e}"))?; + let name = entry + .name() + .map_err(|e| format!("cannot read a capsule entry name: {e}"))? + .to_string(); + if name.ends_with('/') || name == "capsule.json" { + continue; + } + let Some(path) = name.strip_prefix("payload/") else { + return Err(format!( + "the capsule holds {name}, which the format does not name" + )); + }; + if !listed.contains(path) { + return Err(format!( + "the capsule holds {name}, which capsule.json does not name" + )); + } + } + + let stage_dir = root.join(version.to_string()); + if stage_dir.exists() { + fs::remove_dir_all(&stage_dir) + .map_err(|e| format!("cannot clear {}: {e}", stage_dir.display()))?; + } + let payload = stage_dir.join("payload"); + fs::create_dir_all(&payload) + .map_err(|e| format!("cannot create {}: {e}", payload.display()))?; + + let result = extract_files(&mut archive, &manifest, &payload).and_then(|()| { + let text = serde_json::to_vec_pretty(&manifest) + .map_err(|e| format!("capsule.json did not serialize: {e}"))?; + let path = stage_dir.join("manifest.json"); + let part = path.with_extension("part"); + fs::write(&part, text).map_err(|e| format!("cannot write {}: {e}", part.display()))?; + fs::rename(&part, &path).map_err(|e| format!("cannot write {}: {e}", path.display()))?; + Ok(()) + }); + if let Err(e) = result { + let _ = fs::remove_dir_all(&stage_dir); + return Err(e); + } + + // Older staged versions are of no use once this one is complete. + if let Ok(entries) = fs::read_dir(root) { + for entry in entries.flatten() { + let path = entry.path(); + if path != stage_dir && path.is_dir() { + let _ = fs::remove_dir_all(path); + } + } + } + + Ok(Staged { + dir: stage_dir, + manifest, + version, + }) +} + +fn extract_files( + archive: &mut zip::ZipArchive, + manifest: &Manifest, + payload: &Path, +) -> Result<(), String> { + for file in &manifest.files { + let name = format!("payload/{}", file.path); + let mut entry = archive + .by_name(&name) + .map_err(|_| format!("the capsule has no {name}"))?; + if entry.size() != file.size { + return Err(format!( + "{name} is {} bytes in the capsule and {} in capsule.json", + entry.size(), + file.size + )); + } + let out_path = payload.join(&file.path); + if let Some(parent) = out_path.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + let out = File::create(&out_path) + .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?; + let mut writer = BufWriter::new(out); + let mut hasher = blake3::Hasher::new(); + let mut size = 0u64; + let mut buf = [0u8; 64 * 1024]; + loop { + let read = entry + .read(&mut buf) + .map_err(|e| format!("cannot read {name}: {e}"))?; + if read == 0 { + break; + } + size += read as u64; + if size > file.size { + return Err(format!("{name} is larger than capsule.json says")); + } + hasher.update(&buf[..read]); + writer + .write_all(&buf[..read]) + .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?; + } + writer + .flush() + .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?; + let found = hasher.finalize().to_hex().to_string(); + if size != file.size { + return Err(format!( + "{name} came out {size} bytes and capsule.json says {}", + file.size + )); + } + if !found.eq_ignore_ascii_case(&file.blake3) { + return Err(format!( + "{name} does not match its BLAKE3 digest (found {found})" + )); + } + } + Ok(()) +} + +/// Find a complete capsule left by an earlier run, newest version first. +fn discover_staged(root: &Path, current: &Version) -> Option { + let entries = fs::read_dir(root).ok()?; + let mut best: Option = None; + for entry in entries.flatten() { + let dir = entry.path(); + if !dir.is_dir() { + continue; + } + let Ok(text) = fs::read_to_string(dir.join("manifest.json")) else { + continue; + }; + let Ok(manifest) = serde_json::from_str::(&text) else { + continue; + }; + if manifest.validate().is_err() { + continue; + } + let Ok(version) = manifest.version() else { + continue; + }; + if version <= *current || !dir.join("payload").is_dir() { + continue; + } + let replace = best.as_ref().is_none_or(|staged| version > staged.version); + if replace { + best = Some(Staged { + dir, + manifest, + version, + }); + } + } + best +} + +// --------------------------------------------------------------------------- +// Download +// --------------------------------------------------------------------------- + +fn download_capsule( + available: &Available, + capsule: &Path, + tx: &Sender, +) -> Result<(), String> { + if available.size > MAX_CAPSULE_BYTES { + return Err(format!( + "the release is {} bytes, larger than the {} byte limit", + available.size, MAX_CAPSULE_BYTES + )); + } + if let Some(parent) = capsule.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + let part = capsule.with_extension("part"); + let _ = fs::remove_file(&part); + + let result = (|| -> Result<(), String> { + let mut response = ureq::get(&available.url) + .header("User-Agent", USER_AGENT) + .config() + .timeout_global(Some(Duration::from_secs(600))) + .build() + .call() + .map_err(|e| format!("the capsule could not be downloaded: {e}"))?; + let header_total = response + .headers() + .get("content-length") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|total| *total > 0); + let total = header_total.unwrap_or(available.size); + if total > MAX_CAPSULE_BYTES { + return Err(format!( + "the capsule is {total} bytes, larger than the {MAX_CAPSULE_BYTES} byte limit" + )); + } + + let out = + File::create(&part).map_err(|e| format!("cannot write {}: {e}", part.display()))?; + let mut writer = BufWriter::new(out); + let mut reader = response.body_mut().as_reader(); + let mut done = 0u64; + let mut buf = [0u8; 64 * 1024]; + loop { + let read = reader + .read(&mut buf) + .map_err(|e| format!("the capsule ended early: {e}"))?; + if read == 0 { + break; + } + done += read as u64; + if done > MAX_CAPSULE_BYTES { + return Err(format!( + "the capsule is larger than the {MAX_CAPSULE_BYTES} byte limit" + )); + } + writer + .write_all(&buf[..read]) + .map_err(|e| format!("cannot write {}: {e}", part.display()))?; + let _ = tx.send(Event::Progress { done, total }); + } + writer + .flush() + .map_err(|e| format!("cannot write {}: {e}", part.display()))?; + if available.size > 0 && done != available.size { + return Err(format!( + "the capsule is {done} bytes and the release says {}", + available.size + )); + } + fs::rename(&part, capsule) + .map_err(|e| format!("cannot keep {}: {e}", capsule.display()))?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(&part); + } + result +} + +// --------------------------------------------------------------------------- +// The update state the app draws +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Idle, + Checking, + UpToDate, + Available, + Downloading, + Staged, + Failed, +} + +#[derive(Debug)] +enum Event { + Checked { + result: Result, String>, + manual: bool, + }, + Progress { + done: u64, + total: u64, + }, + Staged(Result), +} + +/// What the app should tell the user, once per finished step. +#[derive(Debug, Clone)] +pub enum News { + Available(Available), + UpToDate, + Ready(Staged), + Error(String), +} + +pub struct Updates { + pub current: Version, + pub phase: Phase, + pub available: Option, + pub staged: Option, + pub progress: Option<(u64, u64)>, + pub message: Option, + pub checked_at: Option, + /// Whether the app checks on its own. Snapshot runs turn this off. + pub auto: bool, + rx: Option>, + started: Instant, +} + +impl Updates { + pub fn new() -> Self { + let current = current_version(); + let staged = discover_staged(&updates_dir(), ¤t); + let auto = std::env::var_os("LEAGUERECORDER_NO_UPDATE_CHECK").is_none(); + Self { + current, + phase: if staged.is_some() { + Phase::Staged + } else { + Phase::Idle + }, + available: None, + staged, + progress: None, + message: None, + checked_at: None, + auto, + rx: None, + started: Instant::now(), + } + } + + /// A made-up release for `--scene` snapshots, so the update card has something to show. + pub fn demo_available(&mut self) { + let mut next = self.current.clone(); + next.patch += 1; + self.available = Some(Available { + version: next.clone(), + asset: format!("{PRODUCT}-{next}-{}.capsule", target()), + url: String::new(), + size: 42 * 1024 * 1024, + notes: "The recording screen keeps its place when a game starts.\n\ + Clips gain a name field, and the export button explains a missing ffmpeg." + .into(), + published: None, + prerelease: true, + }); + self.phase = Phase::Available; + } + + pub fn is_busy(&self) -> bool { + matches!(self.phase, Phase::Checking | Phase::Downloading) + } + + pub fn can_check(&self) -> bool { + !self.is_busy() && self.phase != Phase::Staged + } + + pub fn can_download(&self) -> bool { + self.available.is_some() + && matches!(self.phase, Phase::Available | Phase::Failed) + && !self.is_busy() + } + + pub fn can_install(&self) -> bool { + self.staged.is_some() && self.phase == Phase::Staged + } + + pub fn status_text(&self) -> String { + match self.phase { + Phase::Idle => "Not checked yet".into(), + Phase::Checking => "Checking the release page...".into(), + Phase::UpToDate => "Up to date".into(), + Phase::Available => match &self.available { + Some(available) => { + format!("{} is available{}", available.version, pre(available)) + } + None => "An update is available".into(), + }, + Phase::Downloading => match (&self.available, self.progress) { + (Some(available), Some((done, total))) if total > 0 => format!( + "Downloading {}: {}%", + available.version, + done.saturating_mul(100) / total + ), + (Some(available), _) => format!("Downloading {}...", available.version), + _ => "Downloading...".into(), + }, + Phase::Staged => match &self.staged { + Some(staged) => format!("{} is ready to install", staged.version), + None => "An update is ready to install".into(), + }, + Phase::Failed => self + .message + .clone() + .unwrap_or_else(|| "The update check failed".into()), + } + } +} + +impl Updates { + /// Start a check. `manual` decides whether the result interrupts the user. + pub fn check(&mut self, manual: bool) { + if !self.can_check() { + return; + } + let url = releases_url(); + let (tx, rx) = channel(); + self.rx = Some(rx); + self.phase = Phase::Checking; + self.progress = None; + self.message = None; + let spawned = std::thread::Builder::new() + .name("update-check".into()) + .spawn(move || { + let result = check(&url); + let _ = tx.send(Event::Checked { result, manual }); + }); + if let Err(e) = spawned { + self.rx = None; + self.phase = Phase::Failed; + self.message = Some(format!("the update check did not start: {e}")); + } + } + + /// Download and verify the available capsule, then keep it staged for [`install`]. + pub fn download(&mut self) { + if !self.can_download() { + return; + } + let Some(available) = self.available.clone() else { + return; + }; + let current = self.current.clone(); + let root = updates_dir(); + let (tx, rx) = channel(); + self.rx = Some(rx); + self.phase = Phase::Downloading; + self.progress = Some((0, available.size)); + self.message = None; + let spawned = std::thread::Builder::new() + .name("update-download".into()) + .spawn(move || { + let capsule = root.join(format!("{PRODUCT}-{}.capsule", available.version)); + let result = download_capsule(&available, &capsule, &tx) + .and_then(|()| stage_into(&capsule, ¤t, &root)); + let _ = fs::remove_file(&capsule); + let _ = tx.send(Event::Staged(result)); + }); + if let Err(e) = spawned { + self.rx = None; + self.phase = Phase::Failed; + self.progress = None; + self.message = Some(format!("the download did not start: {e}")); + } + } + + /// Start the apply helper, a copy of this exe that waits for this process to exit and + /// then replaces the install files. The caller quits after this returns. A helper that + /// cannot start leaves the state failed, so the user can check and download again. + pub fn install(&mut self) -> Result<(), String> { + let result = self.start_helper(); + if let Err(e) = &result { + self.phase = Phase::Failed; + self.message = Some(e.clone()); + } + result + } + + fn start_helper(&self) -> Result<(), String> { + let staged = self + .staged + .as_ref() + .ok_or("there is no update ready to install")?; + if !self.can_install() { + return Err("the update is not ready to install".into()); + } + staged.manifest.validate()?; + let exe = + std::env::current_exe().map_err(|e| format!("cannot find the running app: {e}"))?; + let install = exe + .parent() + .ok_or("the running app has no folder")? + .to_path_buf(); + let helper = std::env::temp_dir().join(format!( + "{PRODUCT}-updater-{}{}", + std::process::id(), + if cfg!(windows) { ".exe" } else { "" } + )); + let _ = fs::remove_file(&helper); + fs::copy(&exe, &helper) + .map_err(|e| format!("cannot copy the updater to {}: {e}", helper.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)); + } + Command::new(&helper) + .arg("--apply-update") + .arg(&staged.dir) + .arg(&install) + .arg(std::process::id().to_string()) + .current_dir(&install) + .spawn() + .map_err(|e| format!("cannot start the updater: {e}"))?; + Ok(()) + } + + /// Take the worker's messages and say what the user should see. Progress is folded into + /// the state; the news list carries one entry per finished step. + pub fn drain(&mut self) -> (Vec, bool) { + let mut news = Vec::new(); + let mut arrived = false; + let mut disconnected = false; + if let Some(rx) = self.rx.take() { + loop { + match rx.try_recv() { + Ok(event) => { + arrived = true; + self.apply_event(event, &mut news); + } + Err(TryRecvError::Empty) => { + self.rx = Some(rx); + break; + } + Err(TryRecvError::Disconnected) => { + disconnected = true; + break; + } + } + } + } + if disconnected { + arrived = true; + if self.is_busy() { + self.phase = Phase::Failed; + self.message = Some("the update worker stopped without an answer".into()); + news.push(News::Error(self.message.clone().unwrap_or_default())); + } + } + (news, arrived) + } + + fn apply_event(&mut self, event: Event, news: &mut Vec) { + match event { + Event::Checked { result, manual } => { + self.checked_at = Some(SystemTime::now()); + match result { + Ok(Some(available)) if available.version > self.current => { + self.available = Some(available.clone()); + self.phase = Phase::Available; + self.message = None; + news.push(News::Available(available)); + } + Ok(_) => { + self.available = None; + self.phase = Phase::UpToDate; + self.message = None; + if manual { + news.push(News::UpToDate); + } + } + Err(e) => { + self.phase = Phase::Failed; + self.message = Some(e.clone()); + if manual { + news.push(News::Error(e)); + } + } + } + } + Event::Progress { done, total } => { + self.progress = Some((done, total)); + } + Event::Staged(result) => { + self.progress = None; + match result { + Ok(staged) => { + self.available = None; + self.staged = Some(staged.clone()); + self.phase = Phase::Staged; + self.message = None; + news.push(News::Ready(staged)); + } + Err(e) => { + self.phase = Phase::Failed; + self.message = Some(e.clone()); + news.push(News::Error(e)); + } + } + } + } + } + + /// Start the automatic check when one is due. Returns whether the state changed. + pub fn tick(&mut self, t: f64) -> bool { + if !self.auto || self.is_busy() || self.phase == Phase::Staged { + return false; + } + if self.started.elapsed().as_secs_f64() < FIRST_CHECK_SECS && t < FIRST_CHECK_SECS { + return false; + } + let due = match self.checked_at { + None => true, + Some(at) => at + .elapsed() + .map(|elapsed| elapsed.as_secs_f64() >= AUTO_CHECK_SECS) + .unwrap_or(true), + }; + if !due { + return false; + } + self.check(false); + true + } +} + +impl Default for Updates { + fn default() -> Self { + Self::new() + } +} + +fn pre(available: &Available) -> &'static str { + if available.prerelease { + " (pre-release)" + } else { + "" + } +} + +// --------------------------------------------------------------------------- +// Apply mode +// --------------------------------------------------------------------------- + +/// `--apply-update `: the mode the helper runs in. It waits for +/// the app to exit, replaces the files, then starts the new app. Both outcomes are written to +/// `updates/update.log`, because by the time this runs there is no window to report to. +pub fn run_apply(args: &[String]) { + let (Some(stage), Some(install)) = (args.first(), args.get(1)) else { + return; + }; + let stage = PathBuf::from(stage); + let install = PathBuf::from(install); + if let Some(pid) = args.get(2).and_then(|pid| pid.parse::().ok()) { + wait_for_process(pid); + } + log_line(&format!( + "apply from {} to {}", + stage.display(), + install.display() + )); + let manifest = match load_manifest(&stage) { + Ok(manifest) => manifest, + Err(e) => { + log_line(&format!("failed: {e}")); + launch(&install, default_entry()); + std::process::exit(1); + } + }; + let entry = manifest.entry.clone(); + let mut result = apply_to(&stage, &install); + // A daemon can hold its files for a second or two after it is asked to stop. Replacing is + // all or nothing, so a retry starts from the same verified stage. + for _ in 0..30 { + if result.is_ok() { + break; + } + std::thread::sleep(Duration::from_secs(1)); + result = copy_payload(&manifest, &stage.join("payload"), &install); + } + match result { + Ok(()) => { + log_line("files replaced"); + let _ = fs::remove_dir_all(&stage); + log_line("staging folder removed"); + launch(&install, &entry); + } + Err(e) => { + log_line(&format!("failed: {e}")); + // Put the app back even when the update did not land, so the user is not left + // with a stopped daemon and no window. + launch(&install, &entry); + std::process::exit(1); + } + } +} + +fn load_manifest(stage: &Path) -> Result { + let text = fs::read_to_string(stage.join("manifest.json")) + .map_err(|e| format!("cannot read the staged manifest: {e}"))?; + let manifest: Manifest = serde_json::from_str(&text) + .map_err(|e| format!("the staged manifest did not parse: {e}"))?; + manifest.validate()?; + Ok(manifest) +} + +/// Read the staged manifest and install it. Split from [`run_apply`] so it can be tested +/// without starting a process. +pub fn apply_to(stage: &Path, install: &Path) -> Result<(), String> { + let manifest = load_manifest(stage)?; + copy_payload(&manifest, &stage.join("payload"), install) +} + +fn copy_payload(manifest: &Manifest, payload: &Path, install: &Path) -> Result<(), String> { + let mut planned: Vec<(PathBuf, PathBuf)> = Vec::new(); + let discard = |planned: &[(PathBuf, PathBuf)]| { + for (_, next) in planned { + let _ = fs::remove_file(next); + } + }; + for file in &manifest.files { + let source = payload.join(&file.path); + let target = install.join(&file.path); + if let Some(parent) = target.parent() + && let Err(e) = fs::create_dir_all(parent) + { + discard(&planned); + return Err(format!("cannot create {}: {e}", parent.display())); + } + let next = sibling(&target, ".lrnew"); + let _ = fs::remove_file(&next); + if let Err(e) = fs::copy(&source, &next) { + let _ = fs::remove_file(&next); + discard(&planned); + return Err(format!( + "cannot copy {} to {}: {e}", + source.display(), + next.display() + )); + } + let (size, hash) = match hash_file(&next) { + Ok(found) => found, + Err(e) => { + let _ = fs::remove_file(&next); + discard(&planned); + return Err(e); + } + }; + if size != file.size || !hash.eq_ignore_ascii_case(&file.blake3) { + let _ = fs::remove_file(&next); + discard(&planned); + return Err(format!( + "{} does not match the manifest ({} bytes, digest {hash})", + file.path, size + )); + } + planned.push((target, next)); + } + + // Each old file is moved aside before the new one takes its name, and the moves are kept + // until every file has landed. A failure part way through puts the old install back. + let mut applied: Vec<(PathBuf, Option)> = Vec::new(); + let outcome = (|| -> Result<(), String> { + for (target, next) in &planned { + let old = if target.exists() { + let old = sibling(target, ".lrold"); + let _ = fs::remove_file(&old); + fs::rename(target, &old) + .map_err(|e| format!("cannot move {} aside: {e}", target.display()))?; + Some(old) + } else { + None + }; + if let Err(e) = fs::rename(next, target) { + if let Some(old) = &old { + let _ = fs::rename(old, target); + } + return Err(format!("cannot write {}: {e}", target.display())); + } + applied.push((target.clone(), old)); + } + for path in &manifest.remove { + let target = install.join(path); + if target.exists() { + let old = sibling(&target, ".lrold"); + let _ = fs::remove_file(&old); + fs::rename(&target, &old) + .map_err(|e| format!("cannot remove {}: {e}", target.display()))?; + applied.push((target, Some(old))); + } + } + Ok(()) + })(); + + match outcome { + Ok(()) => { + for (_, old) in &applied { + if let Some(old) = old { + let _ = fs::remove_file(old); + } + } + Ok(()) + } + Err(e) => { + for (target, old) in applied.iter().rev() { + let _ = fs::remove_file(target); + if let Some(old) = old { + let _ = fs::rename(old, target); + } + } + discard(&planned); + Err(e) + } + } +} + +/// `path` with `suffix` added after its whole name, so `app.exe` becomes `app.exe.lrnew`. +fn sibling(path: &Path, suffix: &str) -> PathBuf { + let name = path + .file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_else(|| "file".into()); + path.with_file_name(format!("{name}{suffix}")) +} + +fn launch(install: &Path, entry: &str) { + let exe = install.join(entry); + if !exe.is_file() { + log_line(&format!( + "cannot start {}: the file is missing", + exe.display() + )); + return; + } + if let Err(e) = Command::new(&exe).current_dir(install).spawn() { + log_line(&format!("cannot start {}: {e}", exe.display())); + } +} + +fn log_line(line: &str) { + let dir = updates_dir(); + let _ = fs::create_dir_all(&dir); + let path = dir.join("update.log"); + if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(&path) { + let _ = writeln!( + file, + "{} {}", + chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), + line + ); + } +} + +#[cfg(windows)] +fn wait_for_process(pid: u32) { + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject, + }; + unsafe { + if let Ok(handle) = OpenProcess(PROCESS_SYNCHRONIZE, false, pid) { + let _ = WaitForSingleObject(handle, 120_000); + let _ = CloseHandle(handle); + } + } +} + +#[cfg(not(windows))] +fn wait_for_process(_pid: u32) { + std::thread::sleep(Duration::from_secs(1)); +} + +#[cfg(test)] +mod tests { + use super::*; + use capsule_format::{CAPSULE_FORMAT, FileEntry}; + use zip::write::SimpleFileOptions; + + fn release(tag: &str, prerelease: bool, assets: &[(&str, u64)]) -> Release { + Release { + tag_name: tag.into(), + body: format!("notes for {tag}"), + draft: false, + prerelease, + published_at: Some("2026-11-24T00:00:00Z".into()), + assets: assets + .iter() + .map(|(name, size)| Asset { + name: (*name).into(), + size: *size, + browser_download_url: format!("https://example.invalid/{name}"), + }) + .collect(), + } + } + + fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "leaguerecorder-update-{tag}-{}", + uuid::Uuid::new_v4() + )); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn manifest(version: &str, files: &[(&str, &[u8])]) -> Manifest { + Manifest { + format: CAPSULE_FORMAT, + product: PRODUCT.into(), + version: version.into(), + target: target().into(), + entry: default_entry().into(), + notes: String::new(), + files: files + .iter() + .map(|(path, bytes)| FileEntry { + path: (*path).into(), + size: bytes.len() as u64, + blake3: digest(bytes), + }) + .collect(), + remove: Vec::new(), + } + } + + fn write_capsule(path: &Path, manifest: &Manifest, files: &[(&str, &[u8])]) { + let file = File::create(path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + let options = + SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + zip.start_file("capsule.json", options).unwrap(); + zip.write_all(&serde_json::to_vec(manifest).unwrap()) + .unwrap(); + for (name, bytes) in files { + zip.start_file(format!("payload/{name}"), options).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap(); + } + + #[test] + fn a_tag_reads_with_or_without_a_leading_v() { + assert_eq!(parse_tag("v0.3.3"), Some(Version::new(0, 3, 3))); + assert_eq!(parse_tag("0.3.3"), Some(Version::new(0, 3, 3))); + assert_eq!(parse_tag("nightly"), None); + assert_eq!(parse_tag("v"), None); + } + + #[test] + fn the_newest_release_with_a_capsule_wins() { + let current = Version::new(0, 3, 3); + let releases = vec![ + release("v0.3.2", true, &[("old.capsule", 10)]), + release("v0.3.5", true, &[("new.capsule", 20)]), + release("v0.3.4", true, &[("mid.capsule", 15)]), + ]; + let found = latest(&releases, ¤t).unwrap(); + assert_eq!(found.version, Version::new(0, 3, 5)); + assert_eq!(found.asset, "new.capsule"); + assert_eq!(found.size, 20); + assert!(found.prerelease); + } + + #[test] + fn a_stable_release_beats_a_newer_prerelease() { + let current = Version::new(0, 3, 3); + let releases = vec![ + release("v0.4.1", true, &[("new.capsule", 10)]), + release("v0.4.0", false, &[("stable.capsule", 10)]), + ]; + assert_eq!( + latest(&releases, ¤t).unwrap().version, + Version::new(0, 4, 0) + ); + } + + #[test] + fn releases_without_a_capsule_are_skipped() { + let current = Version::new(0, 3, 3); + let releases = vec![ + release("v0.4.0", false, &[("setup.exe", 10)]), + release("v0.3.9", true, &[("thing.zip", 10)]), + ]; + assert!(latest(&releases, ¤t).is_none()); + } + + #[test] + fn drafts_and_versions_that_are_not_newer_are_skipped() { + let current = Version::new(0, 3, 3); + let mut draft = release("v0.9.0", false, &[("x.capsule", 10)]); + draft.draft = true; + let releases = vec![draft, release("v0.3.3", false, &[("x.capsule", 10)])]; + assert!(latest(&releases, ¤t).is_none()); + } + + #[test] + fn a_capsule_round_trips_through_its_hashes() { + let root = temp_dir("roundtrip"); + let payload = root.join("payload"); + fs::create_dir_all(payload.join("data")).unwrap(); + fs::write(payload.join(default_entry()), b"app").unwrap(); + fs::write(payload.join("data").join("file.bin"), b"some data").unwrap(); + let manifest = + capsule_format::pack(&payload, &root.join("release.capsule"), "0.4.0").unwrap(); + assert_eq!(manifest.files.len(), 2); + + let staged = stage_into( + &root.join("release.capsule"), + &Version::new(0, 3, 3), + &root.join("updates"), + ) + .unwrap(); + assert_eq!(staged.version, Version::new(0, 4, 0)); + assert_eq!( + fs::read(staged.dir.join("payload").join("data").join("file.bin")).unwrap(), + b"some data" + ); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn a_file_that_does_not_match_its_digest_is_refused() { + let root = temp_dir("tampered"); + let file = root.join("bad.capsule"); + let manifest = manifest("0.4.0", &[(default_entry(), b"good")]); + write_capsule(&file, &manifest, &[(default_entry(), b"bad!")]); + let error = stage_into(&file, &Version::new(0, 3, 3), &root.join("updates")).unwrap_err(); + assert!(error.contains("BLAKE3"), "{error}"); + assert!(!root.join("updates").join("0.4.0").exists()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn a_second_payload_file_the_manifest_does_not_name_is_refused() { + let root = temp_dir("extra"); + let file = root.join("extra.capsule"); + let manifest = manifest("0.4.0", &[(default_entry(), b"app")]); + write_capsule( + &file, + &manifest, + &[(default_entry(), b"app"), ("extra.dll", b"surprise")], + ); + let error = stage_into(&file, &Version::new(0, 3, 3), &root.join("updates")).unwrap_err(); + assert!(error.contains("does not name"), "{error}"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn a_capsule_that_is_not_newer_is_refused() { + let root = temp_dir("old"); + let file = root.join("old.capsule"); + let manifest = manifest("0.3.3", &[(default_entry(), b"app")]); + write_capsule(&file, &manifest, &[(default_entry(), b"app")]); + assert!(stage_into(&file, &Version::new(0, 3, 3), &root.join("updates")).is_err()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn applying_replaces_files_and_removes_stale_ones() { + let root = temp_dir("apply"); + let stage = root.join("stage"); + let install = root.join("install"); + fs::create_dir_all(stage.join("payload").join("data")).unwrap(); + fs::create_dir_all(install.join("data")).unwrap(); + fs::write(install.join(default_entry()), b"old app").unwrap(); + fs::write(install.join("data").join("keep.bin"), b"old").unwrap(); + fs::write(install.join("stale.dll"), b"stale").unwrap(); + + let mut manifest = manifest("0.4.0", &[(default_entry(), b"new app")]); + manifest.files.push(FileEntry { + path: "data/keep.bin".into(), + size: 3, + blake3: digest(b"new"), + }); + manifest.remove.push("stale.dll".into()); + fs::write(stage.join("payload").join(default_entry()), b"new app").unwrap(); + fs::write(stage.join("payload").join("data").join("keep.bin"), b"new").unwrap(); + fs::write( + stage.join("manifest.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + + apply_to(&stage, &install).unwrap(); + assert_eq!(fs::read(install.join(default_entry())).unwrap(), b"new app"); + assert_eq!( + fs::read(install.join("data").join("keep.bin")).unwrap(), + b"new" + ); + assert!(!install.join("stale.dll").exists()); + assert!(!install.join(format!("{}.lrnew", default_entry())).exists()); + assert!(!install.join(format!("{}.lrold", default_entry())).exists()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn a_complete_stage_is_found_again() { + let root = temp_dir("discover"); + let manifest = manifest("0.4.0", &[(default_entry(), b"app")]); + let dir = root.join("0.4.0"); + fs::create_dir_all(dir.join("payload")).unwrap(); + fs::write(dir.join("payload").join(default_entry()), b"app").unwrap(); + fs::write( + dir.join("manifest.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + let staged = discover_staged(&root, &Version::new(0, 3, 3)).unwrap(); + assert_eq!(staged.version, Version::new(0, 4, 0)); + let _ = fs::remove_dir_all(&root); + } + #[test] + fn a_capsule_downloads_with_progress() { + use std::io::{Read as _, Write as _}; + use std::net::TcpListener; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let body = b"capsule bytes".to_vec(); + let served = body.clone(); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut request = [0u8; 1024]; + let _ = stream.read(&mut request); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", + served.len() + ) + .unwrap(); + stream.write_all(&served).unwrap(); + let _ = stream.flush(); + }); + + let root = temp_dir("download"); + let capsule = root.join("test.capsule"); + let available = Available { + version: Version::new(0, 4, 0), + asset: "test.capsule".into(), + url: format!("http://{address}/test.capsule"), + size: body.len() as u64, + notes: String::new(), + published: None, + prerelease: false, + }; + let (tx, rx) = channel(); + download_capsule(&available, &capsule, &tx).unwrap(); + server.join().unwrap(); + assert_eq!(fs::read(&capsule).unwrap(), body); + + let mut progress = Vec::new(); + while let Ok(event) = rx.try_recv() { + if let Event::Progress { done, total } = event { + progress.push((done, total)); + } + } + assert_eq!( + progress.last(), + Some(&(body.len() as u64, body.len() as u64)) + ); + let _ = fs::remove_dir_all(&root); + } + #[test] + fn a_capsule_needs_the_app_binary() { + let root = temp_dir("no-entry"); + fs::write(root.join("other.exe"), b"not the app").unwrap(); + let error = capsule_format::pack(&root, &root.join("x.capsule"), "0.4.0").unwrap_err(); + assert!(error.contains(default_entry()), "{error}"); + assert!(!root.join("x.capsule").exists()); + let _ = fs::remove_dir_all(&root); + } + #[test] + fn the_remove_list_stays_under_the_install_folder() { + let mut manifest = manifest("0.4.0", &[(default_entry(), b"app")]); + manifest.remove.push("../old.dll".into()); + assert!(manifest.validate().is_err()); + manifest.remove = vec![default_entry().into()]; + assert!(manifest.validate().is_err()); + } + + #[test] + fn an_asset_built_for_this_target_is_preferred() { + let current = Version::new(0, 3, 3); + let mut release = release( + "v0.4.0", + false, + &[ + ("leaguerecorder-0.4.0-linux-x86_64.capsule", 10), + ("leaguerecorder-0.4.0-windows-x86_64.capsule", 20), + ], + ); + if target() == "windows-x86_64" { + let found = latest(std::slice::from_ref(&release), ¤t).unwrap(); + assert_eq!(found.size, 20); + } + // A release with no target in the name still offers its only capsule. + release.assets.truncate(1); + release.assets[0].name = "update.capsule".into(); + assert_eq!( + latest(std::slice::from_ref(&release), ¤t) + .unwrap() + .size, + 10 + ); + } +} diff --git a/crates/capsule-format/Cargo.lock b/crates/capsule-format/Cargo.lock new file mode 100644 index 0000000..6cb1fd5 --- /dev/null +++ b/crates/capsule-format/Cargo.lock @@ -0,0 +1,419 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq 0.4.2", + "cpufeatures", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "capsule-format" +version = "0.1.0" +dependencies = [ + "blake3", + "semver", + "serde", + "serde_json", + "zip", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "zlib-rs", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zip" +version = "9.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e" +dependencies = [ + "constant_time_eq 0.6.1", + "crc32fast", + "flate2", + "getrandom", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys", + "zeroize", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/capsule-format/Cargo.toml b/crates/capsule-format/Cargo.toml new file mode 100644 index 0000000..5970560 --- /dev/null +++ b/crates/capsule-format/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "capsule-format" +version = "0.1.0" +edition = "2024" +description = "The .capsule manifest and archive format shared by the app and the release tool" +license = "MIT" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +semver = "1" +blake3 = "1" +zip = { version = "9.6", default-features = false, features = ["deflate-flate2-zlib-rs"] } diff --git a/crates/capsule-format/src/lib.rs b/crates/capsule-format/src/lib.rs new file mode 100644 index 0000000..bf31305 --- /dev/null +++ b/crates/capsule-format/src/lib.rs @@ -0,0 +1,365 @@ +//! The `.capsule` archive the updater reads and the release tool writes. +//! +//! A capsule is a ZIP with `capsule.json` at the root and every installed file under +//! `payload/`. The manifest names each file with its size and BLAKE3 digest. + +use semver::Version; +use std::collections::HashSet; +use std::fs::{self, File}; +use std::io::{BufWriter, Read, Write}; +use std::path::{Path, PathBuf}; + +/// The product name a capsule must carry. +pub const PRODUCT: &str = "leaguerecorder"; +/// The capsule manifest version this build understands. +pub const CAPSULE_FORMAT: u32 = 1; + +/// The target string a capsule is built for, such as `windows-x86_64`. +pub fn target() -> &'static str { + if cfg!(all(target_os = "windows", target_arch = "x86_64")) { + "windows-x86_64" + } else if cfg!(all(target_os = "windows", target_arch = "aarch64")) { + "windows-aarch64" + } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + "linux-x86_64" + } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) { + "macos-aarch64" + } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) { + "macos-x86_64" + } else { + "unknown" + } +} + +/// The app binary's name, which is also the capsule entry. +pub fn default_entry() -> &'static str { + if cfg!(windows) { + "leaguerecorder.exe" + } else { + "leaguerecorder" + } +} + +/// One file in a capsule: its path relative to the install root, its size, and its BLAKE3 +/// digest in lowercase hex. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct FileEntry { + pub path: String, + pub size: u64, + pub blake3: String, +} + +/// `capsule.json`: what a capsule holds and the version it installs. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Manifest { + pub format: u32, + pub product: String, + pub version: String, + pub target: String, + pub entry: String, + #[serde(default)] + pub notes: String, + pub files: Vec, + /// Files from an older install that the new version no longer ships. + #[serde(default)] + pub remove: Vec, +} + +/// The byte for a backslash. Capsule paths use forward slashes only. +const BACKSLASH: u8 = 0x5c; + +/// A relative path a capsule may name. Anything that could leave the install root is refused: +/// an absolute path, a drive prefix, a backslash, an empty segment, `.` or `..`. +pub fn safe_relative(path: &str) -> bool { + if path.is_empty() + || path.starts_with('/') + || path.as_bytes().contains(&BACKSLASH) + || path.contains(':') + { + return false; + } + !path + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") +} + +fn hash_file(path: &Path) -> Result<(u64, String), String> { + let mut file = File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + let mut hasher = blake3::Hasher::new(); + let mut size = 0u64; + let mut buf = [0u8; 64 * 1024]; + loop { + let read = file + .read(&mut buf) + .map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if read == 0 { + break; + } + size += read as u64; + hasher.update(&buf[..read]); + } + Ok((size, hasher.finalize().to_hex().to_string())) +} + +impl Manifest { + /// Check the parts that do not depend on the running version. + pub fn validate(&self) -> Result<(), String> { + if self.format != CAPSULE_FORMAT { + return Err(format!( + "the capsule has format {}, and this app reads {CAPSULE_FORMAT}", + self.format + )); + } + if self.product != PRODUCT { + return Err(format!( + "the capsule is for {}, not {PRODUCT}", + self.product + )); + } + if self.target != target() { + return Err(format!( + "the capsule is built for {}, and this app runs on {}", + self.target, + target() + )); + } + if self.files.is_empty() { + return Err("the capsule holds no files".into()); + } + if !safe_relative(&self.entry) { + return Err(format!( + "the capsule entry {:?} is not a plain path", + self.entry + )); + } + let mut seen = HashSet::new(); + for file in &self.files { + if !safe_relative(&file.path) { + return Err(format!( + "the capsule names {:?}, which is not a plain path under the install folder", + file.path + )); + } + if !seen.insert(file.path.as_str()) { + return Err(format!("the capsule names {} twice", file.path)); + } + if file.blake3.len() != 64 || !file.blake3.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(format!("{} has no BLAKE3 digest", file.path)); + } + } + if !seen.contains(self.entry.as_str()) { + return Err(format!( + "the capsule entry {} is not one of its files", + self.entry + )); + } + for path in &self.remove { + if !safe_relative(path) { + return Err(format!( + "the capsule asks to remove {path:?}, which is not a plain path under the install folder" + )); + } + if seen.contains(path.as_str()) { + return Err(format!("the capsule installs and removes {path}")); + } + } + Ok(()) + } + + /// The version the capsule installs. + pub fn version(&self) -> Result { + Version::parse(&self.version) + .map_err(|e| format!("the capsule version {:?} does not parse: {e}", self.version)) + } +} + +/// Pack the install folder `dir` into `out` for `version`. +pub fn pack(dir: &Path, out: &Path, version: &str) -> Result { + let version = Version::parse(version) + .map_err(|e| format!("the version {version:?} does not parse: {e}"))?; + if !dir.join(default_entry()).is_file() { + return Err(format!("{} has no {}", dir.display(), default_entry())); + } + let mut paths = Vec::new(); + collect_files(dir, out, &mut paths)?; + paths.sort(); + + let mut files = Vec::new(); + for path in &paths { + let relative = path + .strip_prefix(dir) + .map_err(|_| format!("{} is not under {}", path.display(), dir.display()))?; + let relative = relative + .components() + .filter_map(|part| match part { + std::path::Component::Normal(part) => Some(part.to_string_lossy().to_string()), + _ => None, + }) + .collect::>() + .join("/"); + let (size, blake3) = hash_file(path)?; + files.push(FileEntry { + path: relative, + size, + blake3, + }); + } + if files.is_empty() { + return Err(format!("{} holds no files", dir.display())); + } + + let manifest = Manifest { + format: CAPSULE_FORMAT, + product: PRODUCT.into(), + version: version.to_string(), + target: target().into(), + entry: default_entry().into(), + notes: String::new(), + files, + remove: Vec::new(), + }; + manifest.validate()?; + + if let Some(parent) = out.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + let part = out.with_extension("capsule.part"); + let file = File::create(&part).map_err(|e| format!("cannot write {}: {e}", part.display()))?; + let mut zip = zip::ZipWriter::new(BufWriter::new(file)); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + zip.start_file("capsule.json", options) + .map_err(|e| format!("cannot write capsule.json: {e}"))?; + let text = serde_json::to_vec_pretty(&manifest) + .map_err(|e| format!("the manifest did not serialize: {e}"))?; + zip.write_all(&text) + .map_err(|e| format!("cannot write capsule.json: {e}"))?; + for file in &manifest.files { + let path = dir.join(&file.path); + zip.start_file(format!("payload/{}", file.path), options) + .map_err(|e| format!("cannot add {}: {e}", file.path))?; + let mut input = + File::open(&path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + std::io::copy(&mut input, &mut zip) + .map_err(|e| format!("cannot add {}: {e}", file.path))?; + } + let mut writer = zip + .finish() + .map_err(|e| format!("cannot finish the capsule: {e}"))?; + writer + .flush() + .map_err(|e| format!("cannot finish {}: {e}", part.display()))?; + drop(writer); + fs::rename(&part, out).map_err(|e| format!("cannot write {}: {e}", out.display()))?; + Ok(manifest) +} + +fn collect_files(dir: &Path, out: &Path, files: &mut Vec) -> Result<(), String> { + let entries = fs::read_dir(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?; + for entry in entries.flatten() { + let path = entry.path(); + if path == out || path == out.with_extension("capsule.part") { + continue; + } + let kind = entry + .file_type() + .map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if kind.is_dir() { + collect_files(&path, out, files)?; + } else if kind.is_file() { + let name = path + .file_name() + .map(|name| name.to_string_lossy().to_ascii_lowercase()) + .unwrap_or_default(); + if name.ends_with(".capsule") || name.ends_with(".lrnew") || name.ends_with(".lrold") { + continue; + } + files.push(path); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn digest(bytes: &[u8]) -> String { + blake3::hash(bytes).to_hex().to_string() + } + + fn manifest(version: &str, files: &[(&str, &[u8])]) -> Manifest { + Manifest { + format: CAPSULE_FORMAT, + product: PRODUCT.into(), + version: version.into(), + target: target().into(), + entry: default_entry().into(), + notes: String::new(), + files: files + .iter() + .map(|(path, bytes)| FileEntry { + path: (*path).into(), + size: bytes.len() as u64, + blake3: digest(bytes), + }) + .collect(), + remove: Vec::new(), + } + } + + #[test] + fn capsule_paths_must_stay_under_the_install_folder() { + for bad in [ + "../evil.exe", + "/etc/passwd", + "a/../../b", + "C:/Windows/system32", + "a//b", + "./a", + "", + ] { + let mut manifest = manifest("0.4.0", &[(default_entry(), b"app")]); + manifest.files[0].path = bad.into(); + assert!(manifest.validate().is_err(), "{bad:?} was accepted"); + } + assert!(!safe_relative(&format!("a{}b", char::from(0x5cu8)))); + } + + #[test] + fn the_entry_must_be_one_of_the_files() { + let mut manifest = manifest("0.4.0", &[(default_entry(), b"app")]); + manifest.entry = "other.exe".into(); + assert!(manifest.validate().is_err()); + } + + #[test] + fn a_capsule_with_the_wrong_target_is_refused() { + let mut manifest = manifest("0.4.0", &[(default_entry(), b"app")]); + manifest.target = "plan9-sparc".into(); + assert!(manifest.validate().is_err()); + } + + #[test] + fn a_folder_packs_with_a_manifest_that_names_every_file() { + let root = std::env::temp_dir().join(format!("capsule-format-pack-{}", std::process::id())); + let payload = root.join("payload"); + fs::create_dir_all(payload.join("data")).unwrap(); + fs::write(payload.join(default_entry()), b"app").unwrap(); + fs::write(payload.join("data").join("file.bin"), b"some data").unwrap(); + + let manifest = pack(&payload, &root.join("release.capsule"), "0.4.0").unwrap(); + assert_eq!(manifest.files.len(), 2); + assert_eq!(manifest.version, "0.4.0"); + assert!(manifest.validate().is_ok()); + + let file = File::open(root.join("release.capsule")).unwrap(); + let mut archive = zip::ZipArchive::new(file).unwrap(); + assert!(archive.by_name("capsule.json").is_ok()); + assert!(archive.by_name("payload/data/file.bin").is_ok()); + drop(archive); + + let _ = fs::remove_dir_all(&root); + } +} diff --git a/docs/updates.md b/docs/updates.md new file mode 100644 index 0000000..71c338c --- /dev/null +++ b/docs/updates.md @@ -0,0 +1,152 @@ +# Updates + +The app checks the project's Gitea release list, downloads a `.capsule` asset, verifies every +file in it, and replaces the install with a small helper process. + +## The check + +`src/update.rs` reads: + +``` +https://git.vhaudiquet.fr/api/v1/repos/vhaudiquet/leaguerecorder/releases?limit=60 +``` + +The first automatic check runs about five seconds after startup. Later ones run every six hours, +only while the app is open. The check runs on its own thread, so the window never waits on the +network. A manual check is in Settings > Advanced, under Updates. When a release is waiting, +the status bar carries a yellow **Update available** chip beside the daemon state; it opens +Settings > Advanced. The chip turns into **Update ready** once the capsule is staged. + +A release is offered when all of these hold: + +- it is not a draft; +- its tag parses as a version, with or without a leading `v`; +- the version is newer than the running build; +- it has an asset whose name ends in `.capsule`. + +A stable release beats a newer prerelease. The project currently marks every release as a +prerelease at Gitea, so the check falls back to prereleases when that is all it finds. + +`--check-updates` runs the same check from a shell and prints the result. + +## The capsule + +A capsule is a ZIP file with this layout: + +``` +capsule.json +payload/leaguerecorder.exe +payload/record-daemon.exe +payload/... +``` + +`capsule.json` looks like this: + +```json +{ + "format": 1, + "product": "leaguerecorder", + "version": "0.4.0", + "target": "windows-x86_64", + "entry": "leaguerecorder.exe", + "notes": "", + "files": [ + { + "path": "leaguerecorder.exe", + "size": 67496448, + "blake3": "5a3c..." + } + ], + "remove": [] +} +``` + +`path` is relative to the install root and always uses forward slashes. `blake3` is the +lowercase hex digest of the file. `remove` names files from an older install that the new +version no longer ships; it is optional and empty by default. + +The downloader refuses a capsule when: + +- the ZIP cannot be read, or `capsule.json` is missing or malformed; +- the manifest format, product, or target does not match this build; +- any path is absolute, contains `..`, a backslash, a drive prefix, or an empty segment; +- a file in `payload/` is not named in `capsule.json`; +- a size or BLAKE3 digest does not match; +- the version is not newer than the running build. + +The extracted payload is kept under the app data directory in `updates//`. A +complete stage is found again on the next start, so an update downloaded before a restart can +still be installed. + +## Building a capsule + +The release tool builds the install tree from `packager.toml` and packs it. It does not need an +installed copy, and the app has no packaging mode. + +Build the release, then run the tool from `app/`: + +```sh +cargo packager --release +cargo run --manifest-path ../tools/capsule/Cargo.toml -- --config packager.toml +``` + +`cargo packager` builds both programs and writes the NSIS installer. The tool reads the same +release binaries, so the capsule carries the files the installer puts down. It writes +`dist/leaguerecorder--windows-x86_64.capsule`, using the version in `packager.toml`. +The tool also checks that `Cargo.toml` carries that version, so a release cannot pack one +version's files under another version's manifest. + +Pass `--out ` to write somewhere else. The tool also accepts +`--folder --version --out ` for a tree that is already assembled. + +The builder skips `.capsule`, `.lrnew`, and `.lrold` files. It writes an empty `remove` list. If +a release drops a file, unzip the capsule, add the path to `remove` in `capsule.json`, and zip +it again with `capsule.json` at the root. The payload hashes stay valid. + +Upload the `.capsule` as an asset on the Gitea release whose tag matches the version. The +manifest version and the tag should name the same release. The check compares tags, and staging +compares the manifest. Put the target in the asset name (`windows-x86_64`) so a machine picks +the right one when a release carries several builds. + +## Installing + +Press **Download** in Settings > Advanced. The app downloads the capsule, verifies it, and leaves +it staged. Press **Restart and install**. + +The app starts a copy of itself from the temp folder, asks the daemon to stop, then quits. The +copy is started with: + +``` +--apply-update +``` + +The helper waits for that process to exit, then: + +1. copies each new file beside its target as `.lrnew`; +2. moves each old file aside as `.lrold`, then renames the new file into place; +3. removes the files named in `remove`; +4. deletes the `.lrold` copies and the staging folder; +5. starts the installed `leaguerecorder.exe`. + +A failure at any step puts the old files back, starts the old app, and writes the reason to +`updates/update.log` in the app data directory. On Windows that is +`%LOCALAPPDATA%\leaguerecorder\leaguerecorder\data\updates`. If the daemon still holds a file, +the whole install is retried once a second for 30 seconds. The Open update folder button in the +same card opens that folder. + +## What this does not protect against + +The app reads the release page over HTTPS and checks each file against the manifest inside the +same capsule. That detects a broken or truncated download. It does not detect a server that +serves a matching capsule and manifest, because the manifest is not signed. + +Signing the exe and the capsule remains a separate task. Until then, a compromised Gitea account +or DNS can install arbitrary code, and Windows SmartScreen still warns on the first run. + +## Environment variables + +| Name | Use | +| --- | --- | +| `LEAGUERECORDER_RELEASES_URL` | Read a different release list, such as a mirror or a test server. | +| `LEAGUERECORDER_UPDATE_DIR` | Put staged capsules and `update.log` somewhere else. | +| `LEAGUERECORDER_NO_UPDATE_CHECK` | Turn the automatic check off for this process. | diff --git a/tools/capsule/Cargo.lock b/tools/capsule/Cargo.lock new file mode 100644 index 0000000..0f5a2d9 --- /dev/null +++ b/tools/capsule/Cargo.lock @@ -0,0 +1,489 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq 0.4.2", + "cpufeatures", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "capsule-format" +version = "0.1.0" +dependencies = [ + "blake3", + "semver", + "serde", + "serde_json", + "zip", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "zlib-rs", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "make-capsule" +version = "0.1.0" +dependencies = [ + "capsule-format", + "glob", + "serde", + "toml", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "1.2.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zip" +version = "9.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e" +dependencies = [ + "constant_time_eq 0.6.1", + "crc32fast", + "flate2", + "getrandom", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys", + "zeroize", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tools/capsule/Cargo.toml b/tools/capsule/Cargo.toml new file mode 100644 index 0000000..9a5706c --- /dev/null +++ b/tools/capsule/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "make-capsule" +version = "0.1.0" +edition = "2024" +description = "Build a .capsule update archive from the release build" +license = "MIT" + +[dependencies] +capsule-format = { path = "../../crates/capsule-format" } +serde = { version = "1", features = ["derive"] } +toml = "1" +glob = "0.3" diff --git a/tools/capsule/src/main.rs b/tools/capsule/src/main.rs new file mode 100644 index 0000000..a896854 --- /dev/null +++ b/tools/capsule/src/main.rs @@ -0,0 +1,336 @@ +//! Build a `.capsule` update archive from the release build. +//! +//! The install tree comes from `packager.toml`, so the capsule carries exactly the files the +//! installer puts down. No installed copy of the app is needed. + +use serde::Deserialize; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Deserialize)] +struct Config { + version: String, + #[serde(rename = "binaries-dir", default)] + binaries_dir: Option, + #[serde(default)] + binaries: Vec, + #[serde(default)] + resources: Vec, + #[serde(rename = "out-dir", default)] + out_dir: Option, +} + +#[derive(Debug, Deserialize)] +struct Binary { + path: String, +} + +#[derive(Debug, Deserialize)] +struct Resource { + src: String, + #[serde(default)] + target: String, +} + +fn main() { + if let Err(e) = run(std::env::args().skip(1).collect()) { + eprintln!("{e}"); + std::process::exit(1); + } +} + +fn run(args: Vec) -> Result<(), String> { + let mut config = None; + let mut folder = None; + let mut out = None; + let mut version = None; + let mut args = args.into_iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--config" => config = Some(args.next().ok_or("--config needs a path")?), + "--folder" => folder = Some(args.next().ok_or("--folder needs a path")?), + "--out" => out = Some(args.next().ok_or("--out needs a path")?), + "--version" => version = Some(args.next().ok_or("--version needs a version")?), + "-h" | "--help" => { + println!("{}", usage()); + return Ok(()); + } + other => return Err(format!("unknown argument {other:?}\n\n{}", usage())), + } + } + match (config, folder) { + (Some(_), Some(_)) => Err("use --config or --folder, not both".into()), + (None, None) => Err(usage().into()), + (Some(config), None) => from_config(Path::new(&config), version, out), + (None, Some(folder)) => { + let version = version.ok_or("--version is required with --folder")?; + let out = out.ok_or("--out is required with --folder")?; + let manifest = capsule_format::pack(Path::new(&folder), Path::new(&out), &version)?; + println!( + "{}: {} files for {} on {}", + out, + manifest.files.len(), + manifest.version, + manifest.target + ); + Ok(()) + } + } +} + +fn from_config( + config_path: &Path, + version: Option, + out: Option, +) -> Result<(), String> { + let text = fs::read_to_string(config_path) + .map_err(|e| format!("cannot read {}: {e}", config_path.display()))?; + let config: Config = + toml::from_str(&text).map_err(|e| format!("cannot read {}: {e}", config_path.display()))?; + if let Some(version) = version + && version != config.version + { + return Err(format!( + "--version says {version}, and {} says {}; bump the file or drop the flag", + config_path.display(), + config.version + )); + } + let config_dir = config_path.parent().unwrap_or(Path::new(".")); + if let Some(cargo) = cargo_version(config_dir) + && cargo != config.version + { + return Err(format!( + "{} says {cargo}, and {} says {}; bump both", + config_dir.join("Cargo.toml").display(), + config_path.display(), + config.version + )); + } + let out = out.map(PathBuf::from).unwrap_or_else(|| { + config_dir + .join(config.out_dir.as_deref().unwrap_or("dist")) + .join(format!( + "{}-{}-{}.capsule", + capsule_format::PRODUCT, + config.version, + capsule_format::target() + )) + }); + + let stage = std::env::temp_dir().join(format!("make-capsule-{}", std::process::id())); + if stage.exists() { + fs::remove_dir_all(&stage).map_err(|e| format!("cannot clear {}: {e}", stage.display()))?; + } + fs::create_dir_all(&stage).map_err(|e| format!("cannot create {}: {e}", stage.display()))?; + let result = (|| { + stage_config(&config, config_dir, &stage)?; + let manifest = capsule_format::pack(&stage, &out, &config.version)?; + println!( + "{}: {} files for {} on {}", + out.display(), + manifest.files.len(), + manifest.version, + manifest.target + ); + Ok(()) + })(); + let _ = fs::remove_dir_all(&stage); + result +} + +fn cargo_version(dir: &Path) -> Option { + let text = fs::read_to_string(dir.join("Cargo.toml")).ok()?; + let value: toml::Value = toml::from_str(&text).ok()?; + value + .get("package")? + .get("version")? + .as_str() + .map(str::to_string) +} + +fn usage() -> &'static str { + "usage:\n \ + make-capsule --config [--out ]\n \ + make-capsule --folder --version --out " +} + +fn stage_config(config: &Config, dir: &Path, stage: &Path) -> Result<(), String> { + let binaries_dir = dir.join(config.binaries_dir.as_deref().unwrap_or(".")); + for binary in &config.binaries { + let source = with_exe(binaries_dir.join(&binary.path)); + copy_file(&source, &stage.join(file_name(&source)?))?; + } + for resource in &config.resources { + copy_resource(dir, resource, stage)?; + } + Ok(()) +} + +fn with_exe(path: PathBuf) -> PathBuf { + if cfg!(windows) && path.extension().is_none() { + path.with_extension("exe") + } else { + path + } +} + +fn copy_resource(dir: &Path, resource: &Resource, stage: &Path) -> Result<(), String> { + let source = dir.join(&resource.src); + let pattern = source.to_string_lossy().replace(char::from(0x5c), "/"); + if pattern.contains(['*', '?', '[']) { + let mut found = false; + for path in + glob::glob(&pattern).map_err(|e| format!("{} is not a glob: {e}", source.display()))? + { + let path = path.map_err(|e| format!("cannot read {}: {e}", source.display()))?; + if path.is_file() { + found = true; + let target = target_dir(stage, &resource.target)?; + copy_file(&path, &target.join(file_name(&path)?))?; + } + } + if !found { + return Err(format!("{} matched no files", source.display())); + } + return Ok(()); + } + if source.is_dir() { + copy_dir(&source, &target_dir(stage, &resource.target)?) + } else if source.is_file() { + let target = if resource.target.is_empty() + || resource.target == "." + || resource.target.ends_with('/') + || resource.target.ends_with(char::from(0x5c)) + { + target_dir(stage, &resource.target)?.join(file_name(&source)?) + } else { + stage.join(&resource.target) + }; + copy_file(&source, &target) + } else { + Err(format!("{} does not exist", source.display())) + } +} + +fn target_dir(stage: &Path, target: &str) -> Result { + if target.is_empty() || target == "." { + return Ok(stage.to_path_buf()); + } + if target.starts_with('/') + || target.starts_with(char::from(0x5c)) + || target.contains(':') + || target + .split(['/', char::from(0x5c)]) + .any(|part| part == "..") + { + return Err(format!("resource target {target:?} is not a relative path")); + } + Ok(stage.join(target)) +} + +fn copy_dir(from: &Path, to: &Path) -> Result<(), String> { + fs::create_dir_all(to).map_err(|e| format!("cannot create {}: {e}", to.display()))?; + let entries = fs::read_dir(from).map_err(|e| format!("cannot read {}: {e}", from.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot read {}: {e}", from.display()))?; + let path = entry.path(); + let dest = to.join(entry.file_name()); + if path.is_dir() { + copy_dir(&path, &dest)?; + } else if path.is_file() { + copy_file(&path, &dest)?; + } + } + Ok(()) +} + +fn copy_file(from: &Path, to: &Path) -> Result<(), String> { + if let Some(parent) = to.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + fs::copy(from, to) + .map(|_| ()) + .map_err(|e| format!("cannot copy {} to {}: {e}", from.display(), to.display())) +} + +fn file_name(path: &Path) -> Result { + path.file_name() + .map(|name| name.to_os_string()) + .ok_or_else(|| format!("{} has no file name", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn temp_dir(tag: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("make-capsule-test-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn the_release_tree_follows_the_packager_entries() { + let root = temp_dir("stage"); + let app = root.join("app"); + fs::create_dir_all(app.join("target/release")).unwrap(); + fs::write(app.join("target/release/leaguerecorder.exe"), b"app").unwrap(); + fs::create_dir_all(app.join("vendor/vcruntime")).unwrap(); + fs::write(app.join("vendor/vcruntime/vcruntime140.dll"), b"runtime").unwrap(); + + let daemon = root.join("daemon/target/release"); + fs::create_dir_all(daemon.join("data")).unwrap(); + fs::create_dir_all(daemon.join("obs-plugins")).unwrap(); + fs::write(daemon.join("record-daemon.exe"), b"daemon").unwrap(); + fs::write(daemon.join("libobs.dll"), b"dll").unwrap(); + fs::write(daemon.join("data/area.effect"), b"effect").unwrap(); + fs::write(daemon.join("obs-plugins/plugin.dll"), b"plugin").unwrap(); + + let config = Config { + version: "0.4.0".into(), + binaries_dir: Some("app/target/release".into()), + binaries: vec![Binary { + path: "leaguerecorder".into(), + }], + resources: vec![ + Resource { + src: "daemon/target/release/record-daemon.exe".into(), + target: ".".into(), + }, + Resource { + src: "daemon/target/release/*.dll".into(), + target: ".".into(), + }, + Resource { + src: "daemon/target/release/data".into(), + target: "data".into(), + }, + Resource { + src: "daemon/target/release/obs-plugins".into(), + target: "obs-plugins".into(), + }, + Resource { + src: "app/vendor/vcruntime/*.dll".into(), + target: ".".into(), + }, + ], + out_dir: None, + }; + + let stage = root.join("stage-out"); + stage_config(&config, &root, &stage).unwrap(); + + assert!(stage.join("leaguerecorder.exe").is_file()); + assert!(stage.join("record-daemon.exe").is_file()); + assert!(stage.join("libobs.dll").is_file()); + assert!(stage.join("vcruntime140.dll").is_file()); + assert!(stage.join("data/area.effect").is_file()); + assert!(stage.join("obs-plugins/plugin.dll").is_file()); + let _ = fs::remove_dir_all(&root); + } +}