From ebea98e9a443e77bf2a06da05b9c982958439513 Mon Sep 17 00:00:00 2001 From: Loki Date: Sun, 25 Oct 2026 19:15:12 +0100 Subject: [PATCH 1/5] Update links to the new GitHub account --- CHANGELOG.md | 4 ++-- Cargo.toml | 2 +- README.md | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5243923..a524671 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -205,5 +205,5 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - SQLite message history and user records. - Desktop client shell with egui UI and net layer. -[Unreleased]: https://github.com/loki5512344/Vnox/compare/v0.1.0...HEAD -[0.1.0]: https://github.com/loki5512344/Vnox/releases/tag/v0.1.0 +[Unreleased]: https://github.com/loki5512344ss/VNOX-Client/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/loki5512344ss/VNOX-Client/releases/tag/v0.1.0 diff --git a/Cargo.toml b/Cargo.toml index 18f54db..f1fc2e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ version = "0.1.0" edition = "2024" license = "GPL-3.0" authors = ["VNOX Contributors"] -repository = "https://github.com/loki5512344/Vnox" +repository = "https://github.com/loki5512344ss/VNOX-Client" rust-version = "1.94" default-run = "vnox-client" diff --git a/README.md b/README.md index 3ea82cb..f0a78d4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ ## What is this? -The official desktop client for [VNOX](https://github.com/loki5512344/Vnox) - a self-hosted voice and text communication platform. Connects to a VNOX server over the LNEx protocol. +The official desktop client for [VNOX](https://github.com/loki5512344ss/VNOX-Server) - a self-hosted voice and text communication platform. Connects to a VNOX server over the LNEx protocol. - Connects to gateway via **TCP** (text, auth, channels, guilds, DMs) - Connects to voice node via **UDP** (encrypted Opus voice packets) @@ -68,7 +68,7 @@ See [docs/00-status.md](docs/00-status.md) for a full breakdown. ## Quick start -**Requirements:** Rust 1.94+, a running [VNOX Server](https://github.com/loki5512344/Vnox) +**Requirements:** Rust 1.94+, a running [VNOX Server](https://github.com/loki5512344ss/VNOX-Server) Linux builds also need audio/protocol prerequisites and FreeType/fontconfig development libraries (`libfreetype6-dev libfontconfig1-dev` on Ubuntu); native file selection uses the desktop portal. From cd222540275c307df02e921662db50892ba4fd99 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sun, 1 Nov 2026 16:14:56 +0100 Subject: [PATCH 2/5] feat(client): signed updater with check, download and install steps --- Cargo.lock | 38 +++ Cargo.toml | 6 + src/lib.rs | 1 + src/update/archive.rs | 466 +++++++++++++++++++++++++++++++ src/update/feed.rs | 62 +++++ src/update/http.rs | 462 +++++++++++++++++++++++++++++++ src/update/keys.rs | 175 ++++++++++++ src/update/layout.rs | 423 ++++++++++++++++++++++++++++ src/update/manager.rs | 539 ++++++++++++++++++++++++++++++++++++ src/update/manager_tests.rs | 438 +++++++++++++++++++++++++++++ src/update/manifest.rs | 144 ++++++++++ src/update/mod.rs | 128 +++++++++ src/update/settings.rs | 62 +++++ src/update/test_support.rs | 124 +++++++++ 14 files changed, 3068 insertions(+) create mode 100644 src/update/archive.rs create mode 100644 src/update/feed.rs create mode 100644 src/update/http.rs create mode 100644 src/update/keys.rs create mode 100644 src/update/layout.rs create mode 100644 src/update/manager.rs create mode 100644 src/update/manager_tests.rs create mode 100644 src/update/manifest.rs create mode 100644 src/update/mod.rs create mode 100644 src/update/settings.rs create mode 100644 src/update/test_support.rs diff --git a/Cargo.lock b/Cargo.lock index 0276cb2..d46fafe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5797,6 +5797,12 @@ dependencies = [ "serde", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -5966,10 +5972,12 @@ version = "0.1.0" dependencies = [ "anyhow", "argon2", + "base64", "chacha20poly1305", "cpal", "dirs", "ed25519-dalek", + "flate2", "gstreamer", "gstreamer-app", "gstreamer-sdp", @@ -5986,6 +5994,7 @@ dependencies = [ "rcgen", "rfd", "rustls", + "semver", "serde", "serde_bytes", "serde_json", @@ -5993,6 +6002,8 @@ dependencies = [ "slint", "slint-build", "sys-locale", + "tar", + "tempfile", "tokio", "tokio-rustls", "tracing", @@ -6002,6 +6013,7 @@ dependencies = [ "webpki-roots", "x25519-dalek", "zbus", + "zip", ] [[package]] @@ -7098,6 +7110,20 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -7110,6 +7136,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zruntime" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index f1fc2e8..5eb81e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,11 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } anyhow = "1" hex = "0.4" +flate2 = "1" +tar = "0.4" +semver = "1" +base64 = "0.23" +zip = { version = "8", default-features = false, features = ["deflate"] } uuid = { version = "1", features = ["v4"] } argon2 = "0.6" opus = "0.4" @@ -65,6 +70,7 @@ rfd = { version = "0.17.2", default-features = false, features = [dev-dependencies] # Test gateway certificates, and a TLS 1.2 only server for the downgrade test. rcgen = "0.14" +tempfile = "3" rustls = { version = "0.23", features = ["tls12"] } [features] diff --git a/src/lib.rs b/src/lib.rs index 4c45138..7f3b16a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod identity; pub mod identity_vault; pub mod jitter; pub mod net; +pub mod update; pub mod media; diff --git a/src/update/archive.rs b/src/update/archive.rs new file mode 100644 index 0000000..28bdb7a --- /dev/null +++ b/src/update/archive.rs @@ -0,0 +1,466 @@ +//! Safe extraction of a release archive. +//! +//! A release archive is a `.tar.gz` (Linux) or `.zip` (Windows) as built by the release CI: an +//! optional single wrapper directory holding the client binary plus `LICENSE` and `README.md`. +//! Nothing is unpacked by the archive libraries themselves: the one expected binary is read +//! through a size limit and written by us to a path we chose, the other known files are skipped, +//! and anything else (other names, `..`, absolute paths, deeper nesting, links, devices) makes +//! the whole archive rejected. + +use std::io::{Read, Write}; +use std::path::Path; + +use flate2::read::GzDecoder; +use tar::{Archive, EntryType}; + +use super::UpdateError; + +/// Name of the client binary inside the archive and in a release directory. +pub const BINARY_NAME: &str = if cfg!(windows) { + "vnox-client.exe" +} else { + "vnox-client" +}; + +/// Files besides the binary that a release archive may carry. +const EXTRA_FILES: [&str; 2] = ["LICENSE", "README.md"]; + +/// Archives with more entries than this are refused. +const MAX_ENTRIES: usize = 16; + +/// Slack allowed on top of the binary size for the other files of an archive. +const EXTRA_BUDGET: u64 = 8 * 1024 * 1024; + +#[derive(PartialEq, Eq)] +enum Kind { + Binary, + Ignored, + Directory, +} + +/// Tracks the layout (flat or one wrapper directory) while entries are checked. +#[derive(Default)] +struct Layout { + wrapper: Option, + flat_seen: bool, +} + +impl Layout { + fn classify(&mut self, raw: &str, is_dir: bool, expected: &str) -> Result { + let bad = |why: &str| UpdateError::UnsafeArchive(format!("{why}: {raw}")); + if raw.contains(['\\', ':', '\0']) || raw.starts_with('/') { + return Err(bad("unsafe path")); + } + let parts: Vec<&str> = raw + .split('/') + .filter(|p| !p.is_empty() && *p != ".") + .collect(); + if parts.contains(&"..") { + return Err(bad("path traversal")); + } + let wrapper_ok = |this: &mut Layout, name: &str| -> Result<(), UpdateError> { + match &this.wrapper { + Some(existing) if existing != name => Err(bad("several top-level directories")), + Some(_) => Ok(()), + None if this.flat_seen => Err(bad("mixed layout")), + None => { + this.wrapper = Some(name.to_string()); + Ok(()) + } + } + }; + let file_kind = |name: &str| -> Result { + if name == expected { + Ok(Kind::Binary) + } else if EXTRA_FILES.contains(&name) { + Ok(Kind::Ignored) + } else { + Err(bad("unexpected file")) + } + }; + match (parts.as_slice(), is_dir) { + ([], true) => Ok(Kind::Directory), + ([dir], true) => { + wrapper_ok(self, dir)?; + Ok(Kind::Directory) + } + ([name], false) => { + if self.wrapper.is_some() { + return Err(bad("mixed layout")); + } + self.flat_seen = true; + file_kind(name) + } + ([dir, name], false) => { + wrapper_ok(self, dir)?; + file_kind(name) + } + _ => Err(bad("unexpected entry")), + } + } +} + +/// Extracts the expected binary from `archive` (`.zip` or tar.gz, told apart by content) into +/// `dest` (created new, executable on Unix). Returns the number of bytes written. The binary is +/// limited to `max_binary_bytes`. +pub fn extract_binary( + archive: &Path, + expected_name: &str, + dest: &Path, + max_binary_bytes: u64, +) -> Result { + let mut magic = [0u8; 2]; + std::fs::File::open(archive) + .and_then(|mut f| f.read_exact(&mut magic)) + .map_err(|_| UpdateError::UnsafeArchive("unreadable archive".into()))?; + if &magic == b"PK" { + extract_zip(archive, expected_name, dest, max_binary_bytes) + } else { + extract_tar_gz(archive, expected_name, dest, max_binary_bytes) + } +} + +fn write_binary( + source: &mut dyn Read, + dest: &Path, + max_binary_bytes: u64, +) -> Result { + let mut out = std::fs::OpenOptions::new(); + out.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut out, 0o755); + let mut out = out.open(dest).map_err(UpdateError::io)?; + let copied = + std::io::copy(&mut source.take(max_binary_bytes + 1), &mut out).map_err(UpdateError::io)?; + if copied > max_binary_bytes { + return Err(UpdateError::TooLarge); + } + out.flush().map_err(UpdateError::io)?; + out.sync_all().map_err(UpdateError::io)?; + Ok(copied) +} + +fn extract_tar_gz( + archive: &Path, + expected_name: &str, + dest: &Path, + max_binary_bytes: u64, +) -> Result { + let file = std::fs::File::open(archive).map_err(UpdateError::io)?; + // Bounds the decompressed stream so a gzip bomb cannot burn time or disk. + let decoder = GzDecoder::new(file).take(max_binary_bytes + EXTRA_BUDGET); + let mut tar = Archive::new(decoder); + let unsafe_archive = |why: &str| UpdateError::UnsafeArchive(why.to_string()); + let mut layout = Layout::default(); + let mut written = None; + let entries = tar + .entries() + .map_err(|error| UpdateError::UnsafeArchive(error.to_string()))?; + for (index, entry) in entries.enumerate() { + if index >= MAX_ENTRIES { + return Err(unsafe_archive("too many entries")); + } + let mut entry = entry.map_err(|error| UpdateError::UnsafeArchive(error.to_string()))?; + let is_dir = match entry.header().entry_type() { + EntryType::Regular => false, + EntryType::Directory => true, + EntryType::XGlobalHeader => continue, + _ => return Err(unsafe_archive("entry is not a regular file")), + }; + let raw = entry + .path() + .map_err(|_| unsafe_archive("bad entry path"))? + .to_string_lossy() + .into_owned(); + match layout.classify(&raw, is_dir, expected_name)? { + Kind::Binary => { + if written.is_some() { + return Err(unsafe_archive("duplicate binary entry")); + } + if entry.size() > max_binary_bytes { + return Err(UpdateError::TooLarge); + } + written = Some(write_binary(&mut entry, dest, max_binary_bytes)?); + } + Kind::Ignored | Kind::Directory => {} + } + } + written.ok_or_else(|| unsafe_archive("binary missing from archive")) +} + +fn extract_zip( + archive: &Path, + expected_name: &str, + dest: &Path, + max_binary_bytes: u64, +) -> Result { + let unsafe_archive = |why: String| UpdateError::UnsafeArchive(why); + let file = std::fs::File::open(archive).map_err(UpdateError::io)?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| unsafe_archive(e.to_string()))?; + if zip.len() > MAX_ENTRIES { + return Err(unsafe_archive("too many entries".into())); + } + let mut layout = Layout::default(); + let mut written = None; + for index in 0..zip.len() { + let mut entry = zip + .by_index(index) + .map_err(|e| unsafe_archive(e.to_string()))?; + if entry.is_symlink() { + return Err(unsafe_archive("entry is a link".into())); + } + let (raw, is_dir) = (entry.name().to_string(), entry.is_dir()); + match layout.classify(&raw, is_dir, expected_name)? { + Kind::Binary => { + if written.is_some() { + return Err(unsafe_archive("duplicate binary entry".into())); + } + if entry.size() > max_binary_bytes { + return Err(UpdateError::TooLarge); + } + written = Some(write_binary(&mut entry, dest, max_binary_bytes)?); + } + Kind::Ignored | Kind::Directory => {} + } + } + written.ok_or_else(|| unsafe_archive("binary missing from archive".into())) +} + +#[cfg(test)] +pub(crate) mod test_archives { + use flate2::Compression; + use flate2::write::GzEncoder; + + /// One entry of a hand-built test archive. + pub struct Entry<'a> { + pub name: &'a str, + pub kind: u8, + pub data: &'a [u8], + pub link: &'a str, + } + + /// Builds a tar.gz writing the raw header name, so names tar refuses to create (`..`, + /// absolute) can be tested. + pub fn build(entries: &[Entry]) -> Vec { + let mut tar = Vec::new(); + for entry in entries { + let mut header = tar::Header::new_ustar(); + let name = entry.name.as_bytes(); + header.as_old_mut().name[..name.len()].copy_from_slice(name); + let link = entry.link.as_bytes(); + header.as_old_mut().linkname[..link.len()].copy_from_slice(link); + header.set_size(entry.data.len() as u64); + header.set_mode(0o755); + header.set_entry_type(tar::EntryType::new(entry.kind)); + header.set_cksum(); + tar.extend_from_slice(header.as_bytes()); + tar.extend_from_slice(entry.data); + let pad = (512 - entry.data.len() % 512) % 512; + tar.extend(std::iter::repeat_n(0u8, pad)); + } + tar.extend(std::iter::repeat_n(0u8, 1024)); + let mut gz = GzEncoder::new(Vec::new(), Compression::default()); + std::io::Write::write_all(&mut gz, &tar).unwrap(); + gz.finish().unwrap() + } + + pub fn single(name: &str, data: &[u8]) -> Vec { + build(&[Entry { + name, + kind: b'0', + data, + link: "", + }]) + } +} + +#[cfg(test)] +mod tests { + use super::test_archives::*; + use super::*; + + fn run(bytes: &[u8], limit: u64) -> (tempfile::TempDir, Result) { + let dir = tempfile::tempdir().unwrap(); + let archive = dir.path().join("a.tar.gz"); + std::fs::write(&archive, bytes).unwrap(); + let result = extract_binary(&archive, "vnox-client", &dir.path().join("out"), limit); + (dir, result) + } + + #[test] + fn extracts_the_expected_binary() { + let (dir, result) = run(&single("vnox-client", b"BIN"), 100); + assert_eq!(result.unwrap(), 3); + assert_eq!(std::fs::read(dir.path().join("out")).unwrap(), b"BIN"); + } + + #[test] + fn accepts_dot_slash_prefix() { + assert!(run(&single("./vnox-client", b"BIN"), 100).1.is_ok()); + } + + #[test] + fn rejects_path_traversal() { + for name in [ + "../vnox-client", + "../../etc/passwd", + "/etc/passwd", + "a/../vnox-client", + ] { + let (dir, result) = run(&single(name, b"x"), 100); + assert!( + matches!(result, Err(UpdateError::UnsafeArchive(_))), + "{name}" + ); + assert!(!dir.path().join("out").exists()); + } + } + + #[test] + fn rejects_nested_and_extra_entries() { + assert!(run(&single("a/b/vnox-client", b"x"), 100).1.is_err()); + assert!(run(&single("dir/other", b"x"), 100).1.is_err()); + let two = build(&[ + Entry { + name: "vnox-client", + kind: b'0', + data: b"x", + link: "", + }, + Entry { + name: "other", + kind: b'0', + data: b"x", + link: "", + }, + ]); + assert!(run(&two, 100).1.is_err()); + let dup = build(&[ + Entry { + name: "vnox-client", + kind: b'0', + data: b"x", + link: "", + }, + Entry { + name: "vnox-client", + kind: b'0', + data: b"y", + link: "", + }, + ]); + assert!(run(&dup, 100).1.is_err()); + } + + #[test] + fn rejects_symlink_and_hardlink_entries() { + for kind in *b"21" { + let bytes = build(&[Entry { + name: "vnox-client", + kind, + data: b"", + link: "/etc/passwd", + }]); + let (dir, result) = run(&bytes, 100); + assert!(matches!(result, Err(UpdateError::UnsafeArchive(_)))); + assert!(!dir.path().join("out").exists()); + } + } + + #[test] + fn rejects_directory_entry() { + let bytes = build(&[Entry { + name: "vnox-client", + kind: b'5', + data: b"", + link: "", + }]); + assert!(run(&bytes, 100).1.is_err()); + } + + #[test] + fn rejects_oversized_binary() { + let (_dir, result) = run(&single("vnox-client", &[0u8; 500]), 100); + assert!(matches!(result, Err(UpdateError::TooLarge))); + } + + #[test] + fn rejects_missing_binary_and_garbage() { + assert!(run(&build(&[]), 100).1.is_err()); + assert!(run(b"not gzip", 100).1.is_err()); + } + + fn file<'a>(name: &'a str, data: &'a [u8]) -> Entry<'a> { + Entry { + name, + kind: b'0', + data, + link: "", + } + } + + #[test] + fn accepts_the_release_ci_layout() { + let bytes = build(&[ + Entry { + name: "vnox-client-0.2.0-linux-x86_64/", + kind: b'5', + data: b"", + link: "", + }, + file("vnox-client-0.2.0-linux-x86_64/vnox-client", b"BIN"), + file("vnox-client-0.2.0-linux-x86_64/LICENSE", b"lic"), + file("vnox-client-0.2.0-linux-x86_64/README.md", b"readme"), + ]); + let (dir, result) = run(&bytes, 100); + assert_eq!(result.unwrap(), 3); + assert_eq!(std::fs::read(dir.path().join("out")).unwrap(), b"BIN"); + // Only the binary is written. + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2); + } + + #[test] + fn rejects_mixed_or_multiple_wrappers() { + let two = build(&[file("a/vnox-client", b"x"), file("b/LICENSE", b"x")]); + assert!(run(&two, 100).1.is_err()); + let mixed = build(&[file("LICENSE", b"x"), file("a/vnox-client", b"x")]); + assert!(run(&mixed, 100).1.is_err()); + } + + fn zip_bytes(entries: &[(&str, &[u8])]) -> Vec { + use std::io::Write; + let mut out = std::io::Cursor::new(Vec::new()); + let mut zip = zip::ZipWriter::new(&mut out); + for (name, data) in entries { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); + out.into_inner() + } + + #[test] + fn extracts_from_a_zip_and_rejects_bad_zips() { + let good = zip_bytes(&[("w/vnox-client", b"EXE"), ("w/LICENSE", b"l")]); + let (dir, result) = run(&good, 100); + assert_eq!(result.unwrap(), 3); + assert_eq!(std::fs::read(dir.path().join("out")).unwrap(), b"EXE"); + for name in [ + "../vnox-client", + "/abs/vnox-client", + "w\\..\\vnox-client", + "w/x/vnox-client", + ] { + let bad = zip_bytes(&[(name, b"x")]); + assert!( + matches!(run(&bad, 100).1, Err(UpdateError::UnsafeArchive(_))), + "{name}" + ); + } + assert!(matches!( + run(&zip_bytes(&[("vnox-client", &[0u8; 500])]), 100).1, + Err(UpdateError::TooLarge) + )); + } +} diff --git a/src/update/feed.rs b/src/update/feed.rs new file mode 100644 index 0000000..8620324 --- /dev/null +++ b/src/update/feed.rs @@ -0,0 +1,62 @@ +//! Where release metadata comes from. + +use std::future::Future; +use std::pin::Pin; + +use serde::Deserialize; + +use super::UpdateError; +use super::http::{self, HttpPolicy}; +use super::manifest::MAX_MANIFEST_BYTES; + +const MAX_RELEASE_JSON_BYTES: u64 = 512 * 1024; +const MAX_SIGNATURE_BYTES: u64 = 4096; + +/// Optional hook for asking the Central server which client version is latest. +/// +/// No Central endpoint for this is documented yet, so the client ships without an implementation. +/// A source is advisory only: its answer is shown to the person but never causes anything to be +/// downloaded or installed; only the signed Gitea manifest does. +pub trait CentralVersionSource: Send + Sync { + fn latest_version( + &self, + ) -> Pin, UpdateError>> + Send + '_>>; +} + +#[derive(Deserialize)] +struct Release { + #[serde(default)] + assets: Vec, +} + +#[derive(Deserialize)] +struct Asset { + name: String, + browser_download_url: String, +} + +/// Downloads `manifest.json` and `manifest.json.sig` of the latest Gitea release. +/// Returns `(manifest_bytes, signature_bytes)`, both still unverified. +pub async fn fetch_latest_manifest( + policy: &HttpPolicy, + api_base: &str, + repo: &str, +) -> Result<(Vec, Vec), UpdateError> { + let api = format!("{api_base}/api/v1/repos/{repo}/releases/latest"); + let json = http::fetch_bytes(policy, &api, MAX_RELEASE_JSON_BYTES).await?; + let release: Release = + serde_json::from_slice(&json).map_err(|e| UpdateError::Manifest(e.to_string()))?; + let find = |name: &str| { + release + .assets + .iter() + .find(|asset| asset.name == name) + .map(|asset| asset.browser_download_url.clone()) + .ok_or_else(|| UpdateError::Manifest(format!("release has no `{name}` asset"))) + }; + let manifest_url = find("manifest.json")?; + let signature_url = find("manifest.json.sig")?; + let manifest = http::fetch_bytes(policy, &manifest_url, MAX_MANIFEST_BYTES as u64).await?; + let signature = http::fetch_bytes(policy, &signature_url, MAX_SIGNATURE_BYTES).await?; + Ok((manifest, signature)) +} diff --git a/src/update/http.rs b/src/update/http.rs new file mode 100644 index 0000000..79157b6 --- /dev/null +++ b/src/update/http.rs @@ -0,0 +1,462 @@ +//! A small, strict HTTP/1.1 GET client for the updater. +//! +//! It only talks to allow-listed hosts, over HTTPS unless a test policy says otherwise, follows a +//! bounded number of redirects (each one re-checked against the same policy) and never keeps more +//! than a caller-given number of body bytes. + +use std::sync::Arc; +use std::time::Duration; + +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpStream; + +use super::UpdateError; + +const MAX_HEADER_BYTES: usize = 16 * 1024; +const MAX_HEADER_LINES: usize = 100; + +/// Which URLs the updater may fetch. +#[derive(Clone, Debug)] +pub struct HttpPolicy { + /// Lower case host names that may be contacted, including after a redirect. + pub allowed_hosts: Vec, + /// When true only `https://` URLs are accepted. Only tests turn this off. + pub require_https: bool, + pub max_redirects: u8, + /// Limit for connecting and for receiving the response headers. + pub connect_timeout: Duration, + /// Limit for reading each chunk of the body, so a stalled server cannot hang an update. + pub read_timeout: Duration, +} + +impl HttpPolicy { + /// The production policy: HTTPS to the release host only. + pub fn production() -> Self { + Self { + allowed_hosts: vec![super::RELEASE_HOST.to_string()], + require_https: true, + max_redirects: 3, + connect_timeout: Duration::from_secs(15), + read_timeout: Duration::from_secs(30), + } + } +} + +/// A parsed `http(s)` URL. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Url { + pub https: bool, + pub host: String, + pub port: u16, + /// Path and query, always starting with `/`. + pub target: String, +} + +impl Url { + /// Parses and validates `text` against `policy`. + pub fn parse(text: &str, policy: &HttpPolicy) -> Result { + let reject = |why: &str| UpdateError::UrlRejected(format!("{why}: {text}")); + if !text.is_ascii() || text.bytes().any(|b| b.is_ascii_control() || b == b' ') { + return Err(reject("invalid characters")); + } + let (https, rest) = if let Some(rest) = text.strip_prefix("https://") { + (true, rest) + } else if let Some(rest) = text.strip_prefix("http://") { + if policy.require_https { + return Err(reject("plain HTTP is not allowed")); + } + (false, rest) + } else { + return Err(reject("unsupported scheme")); + }; + let rest = rest.split('#').next().unwrap_or(""); + let (authority, target) = match rest.find(['/', '?']) { + Some(index) => { + let (authority, tail) = rest.split_at(index); + let target = if tail.starts_with('/') { + tail.to_string() + } else { + format!("/{tail}") + }; + (authority, target) + } + None => (rest, "/".to_string()), + }; + if authority.contains('@') || authority.is_empty() || authority.starts_with('[') { + return Err(reject("invalid authority")); + } + let (host, port) = match authority.rsplit_once(':') { + Some((host, port)) => ( + host, + port.parse::().map_err(|_| reject("invalid port"))?, + ), + None => (authority, if https { 443 } else { 80 }), + }; + let host = host.to_ascii_lowercase(); + if !policy.allowed_hosts.contains(&host) { + return Err(reject("host is not allowed")); + } + Ok(Url { + https, + host, + port, + target, + }) + } + + fn origin(&self) -> String { + let scheme = if self.https { "https" } else { "http" }; + format!("{scheme}://{}:{}", self.host, self.port) + } +} + +fn tls_config() -> Result, UpdateError> { + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + let config = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|error| UpdateError::Network(error.to_string()))? + .with_root_certificates(roots) + .with_no_client_auth(); + Ok(Arc::new(config)) +} + +async fn within( + limit: Duration, + what: &str, + future: impl std::future::Future>, +) -> Result { + match tokio::time::timeout(limit, future).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(UpdateError::Network(format!("{what}: {error}"))), + Err(_) => Err(UpdateError::Network(format!("{what}: timed out"))), + } +} + +/// Fetches `url` and feeds the body to `sink` in pieces. The body must not exceed `max_bytes`; +/// a larger announced or actual body aborts the transfer with [`UpdateError::TooLarge`]. +pub async fn fetch( + policy: &HttpPolicy, + url: &str, + max_bytes: u64, + sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send), +) -> Result<(), UpdateError> { + let mut current = Url::parse(url, policy)?; + for _ in 0..=policy.max_redirects { + match fetch_once(policy, ¤t, max_bytes, sink).await? { + Outcome::Done => return Ok(()), + Outcome::Redirect(location) => { + let next = if location.starts_with('/') { + format!("{}{}", current.origin(), location) + } else { + location + }; + current = Url::parse(&next, policy)?; + } + } + } + Err(UpdateError::Network("too many redirects".into())) +} + +/// Convenience wrapper that collects the body in memory. +pub async fn fetch_bytes( + policy: &HttpPolicy, + url: &str, + max_bytes: u64, +) -> Result, UpdateError> { + let mut body = Vec::new(); + fetch(policy, url, max_bytes, &mut |chunk| { + body.extend_from_slice(chunk); + Ok(()) + }) + .await?; + Ok(body) +} + +enum Outcome { + Done, + Redirect(String), +} + +async fn fetch_once( + policy: &HttpPolicy, + url: &Url, + max_bytes: u64, + sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send), +) -> Result { + let tcp = within( + policy.connect_timeout, + "connect", + TcpStream::connect((url.host.as_str(), url.port)), + ) + .await?; + if url.https { + let name = rustls::pki_types::ServerName::try_from(url.host.clone()) + .map_err(|_| UpdateError::UrlRejected(url.host.clone()))?; + let connector = tokio_rustls::TlsConnector::from(tls_config()?); + let tls = within( + policy.connect_timeout, + "tls handshake", + connector.connect(name, tcp), + ) + .await?; + exchange(policy, url, tls, max_bytes, sink).await + } else { + exchange(policy, url, tcp, max_bytes, sink).await + } +} + +async fn read_line( + reader: &mut BufReader, + timeout: Duration, + budget: &mut usize, +) -> Result { + let mut line = Vec::new(); + let read = within(timeout, "read", async { + reader + .take(*budget as u64 + 1) + .read_until(b'\n', &mut line) + .await + }) + .await?; + if read == 0 || read > *budget || !line.ends_with(b"\n") { + return Err(UpdateError::Network( + "malformed or oversized response".into(), + )); + } + *budget -= read; + let text = String::from_utf8_lossy(&line); + Ok(text.trim_end_matches(['\r', '\n']).to_string()) +} + +async fn exchange( + policy: &HttpPolicy, + url: &Url, + stream: S, + max_bytes: u64, + sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send), +) -> Result +where + S: AsyncRead + AsyncWriteExt + Unpin, +{ + let mut stream = stream; + let request = format!( + "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: vnox-client-updater/{}\r\nAccept: */*\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n", + url.target, + url.host, + super::CLIENT_VERSION + ); + within(policy.connect_timeout, "send request", async { + stream.write_all(request.as_bytes()).await?; + stream.flush().await + }) + .await?; + + let mut reader = BufReader::new(stream); + let mut budget = MAX_HEADER_BYTES; + let status_line = read_line(&mut reader, policy.connect_timeout, &mut budget).await?; + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|code| code.parse().ok()) + .filter(|_| status_line.starts_with("HTTP/1.")) + .ok_or_else(|| UpdateError::Network("malformed status line".into()))?; + + let mut content_length: Option = None; + let mut chunked = false; + let mut location = None; + for _ in 0..MAX_HEADER_LINES { + let line = read_line(&mut reader, policy.connect_timeout, &mut budget).await?; + if line.is_empty() { + return finish( + policy, + &mut reader, + status, + content_length, + chunked, + location, + max_bytes, + sink, + ) + .await; + } + if let Some((name, value)) = line.split_once(':') { + let value = value.trim(); + match name.trim().to_ascii_lowercase().as_str() { + "content-length" => { + content_length = Some( + value + .parse() + .map_err(|_| UpdateError::Network("bad content-length".into()))?, + ); + } + "transfer-encoding" => chunked = value.eq_ignore_ascii_case("chunked"), + "location" => location = Some(value.to_string()), + _ => {} + } + } + } + Err(UpdateError::Network("too many response headers".into())) +} + +#[allow(clippy::too_many_arguments)] +async fn finish( + policy: &HttpPolicy, + reader: &mut BufReader, + status: u16, + content_length: Option, + chunked: bool, + location: Option, + max_bytes: u64, + sink: &mut (dyn FnMut(&[u8]) -> Result<(), UpdateError> + Send), +) -> Result { + if matches!(status, 301 | 302 | 303 | 307 | 308) { + return location + .map(Outcome::Redirect) + .ok_or_else(|| UpdateError::Network("redirect without location".into())); + } + if status != 200 { + return Err(UpdateError::Http(status)); + } + if content_length.is_some_and(|length| length > max_bytes) { + return Err(UpdateError::TooLarge); + } + let mut total: u64 = 0; + let mut emit = |data: &[u8]| -> Result<(), UpdateError> { + total += data.len() as u64; + if total > max_bytes { + return Err(UpdateError::TooLarge); + } + sink(data) + }; + if chunked { + loop { + let mut budget = 1024; + let size_line = read_line(reader, policy.read_timeout, &mut budget).await?; + let size_text = size_line.split(';').next().unwrap_or("").trim(); + let mut size = u64::from_str_radix(size_text, 16) + .map_err(|_| UpdateError::Network("bad chunk size".into()))?; + if size == 0 { + return Ok(Outcome::Done); + } + if size > max_bytes { + return Err(UpdateError::TooLarge); + } + let mut buffer = [0u8; 16 * 1024]; + while size > 0 { + let want = size.min(buffer.len() as u64) as usize; + let read = within( + policy.read_timeout, + "read body", + reader.read(&mut buffer[..want]), + ) + .await?; + if read == 0 { + return Err(UpdateError::Network("truncated body".into())); + } + emit(&buffer[..read])?; + size -= read as u64; + } + let mut budget = 16; + read_line(reader, policy.read_timeout, &mut budget).await?; + } + } + let mut buffer = [0u8; 16 * 1024]; + loop { + let read = within(policy.read_timeout, "read body", reader.read(&mut buffer)).await?; + if read == 0 { + break; + } + emit(&buffer[..read])?; + } + match content_length { + Some(length) if length != total => Err(UpdateError::Network("truncated body".into())), + _ => Ok(Outcome::Done), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_policy() -> HttpPolicy { + HttpPolicy { + allowed_hosts: vec!["127.0.0.1".into(), "git.wihuk.pro".into()], + require_https: false, + max_redirects: 3, + connect_timeout: Duration::from_secs(2), + read_timeout: Duration::from_secs(2), + } + } + + #[test] + fn production_policy_rejects_http_and_foreign_hosts() { + let policy = HttpPolicy::production(); + assert!(Url::parse("https://git.wihuk.pro/a/b", &policy).is_ok()); + assert!(Url::parse("http://git.wihuk.pro/a", &policy).is_err()); + assert!(Url::parse("https://evil.example/a", &policy).is_err()); + assert!(Url::parse("https://git.wihuk.pro.evil.example/a", &policy).is_err()); + assert!(Url::parse("https://git.wihuk.pro@evil.example/a", &policy).is_err()); + assert!(Url::parse("ftp://git.wihuk.pro/a", &policy).is_err()); + assert!(Url::parse("https://GIT.wihuk.pro/a", &policy).is_ok()); + } + + #[tokio::test] + async fn fetches_plain_body_and_chunked_body() { + let server = crate::update::test_support::FakeServer::start().await; + server.route("/plain", 200, b"hello".to_vec()); + server.route_chunked("/chunked", b"hello world".to_vec()); + let policy = test_policy(); + let got = fetch_bytes(&policy, &server.url("/plain"), 100) + .await + .unwrap(); + assert_eq!(got, b"hello"); + let got = fetch_bytes(&policy, &server.url("/chunked"), 100) + .await + .unwrap(); + assert_eq!(got, b"hello world"); + } + + #[tokio::test] + async fn body_over_limit_is_rejected() { + let server = crate::update::test_support::FakeServer::start().await; + server.route("/big", 200, vec![1u8; 5000]); + server.route_chunked("/bigchunk", vec![1u8; 5000]); + let policy = test_policy(); + assert!(matches!( + fetch_bytes(&policy, &server.url("/big"), 1000).await, + Err(UpdateError::TooLarge) + )); + assert!(matches!( + fetch_bytes(&policy, &server.url("/bigchunk"), 1000).await, + Err(UpdateError::TooLarge) + )); + } + + #[tokio::test] + async fn redirect_to_disallowed_host_is_refused() { + let server = crate::update::test_support::FakeServer::start().await; + server.redirect("/r", "http://evil.example/x"); + server.redirect("/ok", "/plain"); + server.route("/plain", 200, b"fine".to_vec()); + let policy = test_policy(); + assert!(matches!( + fetch_bytes(&policy, &server.url("/r"), 100).await, + Err(UpdateError::UrlRejected(_)) + )); + assert_eq!( + fetch_bytes(&policy, &server.url("/ok"), 100).await.unwrap(), + b"fine" + ); + } + + #[tokio::test] + async fn error_status_is_reported() { + let server = crate::update::test_support::FakeServer::start().await; + let policy = test_policy(); + assert!(matches!( + fetch_bytes(&policy, &server.url("/missing"), 100).await, + Err(UpdateError::Http(404)) + )); + } +} diff --git a/src/update/keys.rs b/src/update/keys.rs new file mode 100644 index 0000000..207fe7b --- /dev/null +++ b/src/update/keys.rs @@ -0,0 +1,175 @@ +//! Release signing key and detached signature verification. +//! +//! The manifest is signed with Ed25519 over its exact bytes. The signature is verified before the +//! manifest is parsed, so a forged or tampered document never reaches the JSON parser. + +use ed25519_dalek::{Signature, VerifyingKey}; + +use super::UpdateError; + +/// Public half of the release signing key, embedded in the binary. +/// +/// This is a PLACEHOLDER (all zeros). While it is unchanged the updater refuses to run +/// ([`is_placeholder`]), so a build without a real key can never accept an update. +/// +/// To replace it: generate an Ed25519 key pair offline, keep the secret key only in the CI +/// secret store (`manifest.json.sig` is produced from it), and paste the 32 byte public key +/// here. Rotating the key requires shipping a release signed with the old key that embeds the new +/// one. +pub const RELEASE_PUBLIC_KEY: [u8; 32] = [0u8; 32]; + +/// Second public key accepted during a key rotation, `None` otherwise. A release that embeds both +/// keys is signed with the old one; the next releases are signed with the new one. +pub const RELEASE_PUBLIC_KEY_NEXT: Option<[u8; 32]> = None; + +/// The keys a production build accepts. +pub fn production_keys() -> Vec<[u8; 32]> { + std::iter::once(RELEASE_PUBLIC_KEY) + .chain(RELEASE_PUBLIC_KEY_NEXT) + .collect() +} + +/// True when `key` is the unconfigured placeholder. +pub fn is_placeholder(key: &[u8; 32]) -> bool { + key.iter().all(|byte| *byte == 0) +} + +/// Decodes a detached signature. The release CI writes base64 text; raw 64 bytes and 128 +/// character hex text are accepted too. +pub fn decode_signature(bytes: &[u8]) -> Result { + let raw: [u8; 64] = if bytes.len() == 64 { + bytes.try_into().map_err(|_| UpdateError::BadSignature)? + } else { + let text = std::str::from_utf8(bytes) + .map_err(|_| UpdateError::BadSignature)? + .trim(); + let decoded = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, text) + .ok() + .filter(|decoded| decoded.len() == 64) + .or_else(|| hex::decode(text).ok()) + .ok_or(UpdateError::BadSignature)?; + decoded.try_into().map_err(|_| UpdateError::BadSignature)? + }; + Ok(Signature::from_bytes(&raw)) +} + +/// Verifies against any of `keys` (placeholders are skipped). With no usable key, updates are off. +pub fn verify_any(keys: &[[u8; 32]], message: &[u8], signature: &[u8]) -> Result<(), UpdateError> { + let usable: Vec<&[u8; 32]> = keys.iter().filter(|k| !is_placeholder(k)).collect(); + if usable.is_empty() { + return Err(UpdateError::NoReleaseKey); + } + let mut last = UpdateError::BadSignature; + for key in usable { + match verify(key, message, signature) { + Ok(()) => return Ok(()), + Err(error) => last = error, + } + } + Err(last) +} + +/// Verifies `signature` over exactly `message` with the strict Ed25519 rules. +pub fn verify(key: &[u8; 32], message: &[u8], signature: &[u8]) -> Result<(), UpdateError> { + if is_placeholder(key) { + return Err(UpdateError::NoReleaseKey); + } + let key = VerifyingKey::from_bytes(key).map_err(|_| UpdateError::NoReleaseKey)?; + let signature = decode_signature(signature)?; + key.verify_strict(message, &signature) + .map_err(|_| UpdateError::BadSignature) +} + +#[cfg(test)] +pub(crate) mod test_keys { + use ed25519_dalek::{Signer, SigningKey}; + + /// Deterministic key used only by tests. + pub fn signing_key() -> SigningKey { + SigningKey::from_bytes(&[7u8; 32]) + } + + pub fn public() -> [u8; 32] { + signing_key().verifying_key().to_bytes() + } + + pub fn sign(message: &[u8]) -> Vec { + signing_key().sign(message).to_bytes().to_vec() + } +} + +#[cfg(test)] +mod tests { + use super::test_keys::*; + use super::*; + + #[test] + fn valid_signature_verifies() { + let msg = b"{\"version\":\"1.0.0\"}"; + verify(&public(), msg, &sign(msg)).unwrap(); + } + + #[test] + fn hex_signature_is_accepted() { + let msg = b"manifest"; + let text = format!("{}\n", hex::encode(sign(msg))); + verify(&public(), msg, text.as_bytes()).unwrap(); + } + + #[test] + fn tampered_message_fails() { + let sig = sign(b"manifest"); + assert!(matches!( + verify(&public(), b"manifesT", &sig), + Err(UpdateError::BadSignature) + )); + } + + #[test] + fn bad_signature_fails() { + let mut sig = sign(b"manifest"); + sig[3] ^= 1; + assert!(verify(&public(), b"manifest", &sig).is_err()); + assert!(verify(&public(), b"manifest", b"short").is_err()); + } + + #[test] + fn wrong_key_fails() { + let other = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]); + let key = other.verifying_key().to_bytes(); + assert!(verify(&key, b"manifest", &sign(b"manifest")).is_err()); + } + + #[test] + fn base64_signature_from_the_ci_is_accepted() { + let msg = b"manifest"; + let text = format!( + "{}\n", + base64::Engine::encode(&base64::engine::general_purpose::STANDARD, sign(msg)) + ); + verify(&public(), msg, text.as_bytes()).unwrap(); + } + + #[test] + fn either_rotation_key_may_sign() { + let old = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]) + .verifying_key() + .to_bytes(); + let msg = b"manifest"; + verify_any(&[old, public()], msg, &sign(msg)).unwrap(); + assert!(verify_any(&[old], msg, &sign(msg)).is_err()); + assert!(matches!( + verify_any(&[RELEASE_PUBLIC_KEY], msg, &sign(msg)), + Err(UpdateError::NoReleaseKey) + )); + } + + #[test] + fn placeholder_key_never_verifies() { + assert!(is_placeholder(&RELEASE_PUBLIC_KEY)); + assert!(matches!( + verify(&RELEASE_PUBLIC_KEY, b"m", &sign(b"m")), + Err(UpdateError::NoReleaseKey) + )); + } +} diff --git a/src/update/layout.rs b/src/update/layout.rs new file mode 100644 index 0000000..e00d692 --- /dev/null +++ b/src/update/layout.rs @@ -0,0 +1,423 @@ +//! On-disk release layout: atomic install, rollback and Windows swap-on-start. +//! +//! Linux layout (matches the existing install): +//! +//! ```text +//! ~/.local/bin/vnox-client symlink to the active release binary +//! ~/.local/lib/vnox/releases//vnox-client +//! ~/.local/lib/vnox/releases/state.json {current, previous, pending} +//! ``` +//! +//! Installing builds the new release in a hidden staging directory, renames it into place, then +//! replaces the symlink with an atomic `rename`, so the launcher always points at a complete +//! binary. The release that was active stays on disk as `previous` for [`rollback`]. +//! Profile and chat data live under the config and data directories and are never touched. +//! +//! On Windows a running executable cannot be replaced, so the new binary is only staged and +//! recorded as `pending`; [`apply_pending`] swaps it in at the next start. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use super::UpdateError; +use super::archive::{self, BINARY_NAME}; + +/// How a new release becomes the active one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Activation { + /// Atomically repoint the launcher symlink (Unix). + SwapLink, + /// Stage only; swap the executable on the next start (Windows). + StageForRestart, +} + +/// Where releases, the launcher and downloads live. +#[derive(Clone, Debug)] +pub struct Layout { + pub releases_dir: PathBuf, + /// Symlink (Unix) or the executable itself (Windows) that starts the client. + pub launcher: PathBuf, + /// Verified downloads waiting for installation. + pub downloads_dir: PathBuf, + pub activation: Activation, +} + +/// What the layout knows about releases, stored next to them. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct InstallState { + pub current: Option, + pub previous: Option, + pub pending: Option, +} + +impl Layout { + /// The default per-user layout for this platform. + pub fn user_default() -> Option { + let downloads_dir = dirs::data_local_dir()?.join("vnox/updates"); + if cfg!(windows) { + Some(Layout { + releases_dir: dirs::data_local_dir()?.join("vnox/releases"), + launcher: std::env::current_exe().ok()?, + downloads_dir, + activation: Activation::StageForRestart, + }) + } else { + let home = dirs::home_dir()?; + Some(Layout { + releases_dir: home.join(".local/lib/vnox/releases"), + launcher: home.join(".local/bin/vnox-client"), + downloads_dir, + activation: Activation::SwapLink, + }) + } + } + + fn state_path(&self) -> PathBuf { + self.releases_dir.join("state.json") + } + + /// Reads the install state; a missing or unreadable file means nothing is recorded. + pub fn state(&self) -> InstallState { + std::fs::read(self.state_path()) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default() + } + + fn save_state(&self, state: &InstallState) -> Result<(), UpdateError> { + let bytes = serde_json::to_vec_pretty(state).map_err(|e| UpdateError::Io(e.to_string()))?; + write_atomic(&self.state_path(), &bytes) + } + + /// Extracts `archive` as release `version` and makes it the active (or pending) release. + /// `max_binary_bytes` bounds the extracted binary. + pub fn install_archive( + &self, + version: &str, + archive_path: &Path, + max_binary_bytes: u64, + ) -> Result { + validate_version_dir(version)?; + std::fs::create_dir_all(&self.releases_dir).map_err(UpdateError::io)?; + let final_dir = self.releases_dir.join(version); + let state = self.state(); + let in_use = [&state.current, &state.previous, &state.pending] + .into_iter() + .flatten() + .any(|path| path.starts_with(&final_dir)); + if in_use { + return Err(UpdateError::AlreadyInstalled); + } + let staging = self + .releases_dir + .join(format!(".staging-{version}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&staging); + std::fs::create_dir(&staging).map_err(UpdateError::io)?; + let built = (|| { + archive::extract_binary( + archive_path, + BINARY_NAME, + &staging.join(BINARY_NAME), + max_binary_bytes, + )?; + // A leftover directory from an interrupted install is replaced. + if final_dir.exists() { + std::fs::remove_dir_all(&final_dir).map_err(UpdateError::io)?; + } + std::fs::rename(&staging, &final_dir).map_err(UpdateError::io) + })(); + if let Err(error) = built { + let _ = std::fs::remove_dir_all(&staging); + return Err(error); + } + let binary = final_dir.join(BINARY_NAME); + self.activate(&binary)?; + self.prune(); + Ok(binary) + } + + /// Makes `target` the active release (or the pending one, for the restart mode). + fn activate(&self, target: &Path) -> Result<(), UpdateError> { + let mut state = self.state(); + match self.activation { + Activation::StageForRestart => { + state.pending = Some(target.to_path_buf()); + } + Activation::SwapLink => { + let old = self.current_target(); + swap_link(target, &self.launcher)?; + if let Some(old) = old.filter(|old| old != target) { + state.previous = Some(old); + } + state.current = Some(target.to_path_buf()); + } + } + self.save_state(&state) + } + + /// The binary the launcher points at now, if it can be determined. + fn current_target(&self) -> Option { + match std::fs::symlink_metadata(&self.launcher) { + Ok(meta) if meta.file_type().is_symlink() => std::fs::read_link(&self.launcher).ok(), + Ok(meta) if meta.is_file() => { + // A plain file (not a symlink): keep a copy so it can be rolled back to. + let legacy = self.releases_dir.join("legacy").join(BINARY_NAME); + std::fs::create_dir_all(legacy.parent()?).ok()?; + std::fs::copy(&self.launcher, &legacy).ok()?; + Some(legacy) + } + _ => None, + } + } + + /// Switches back to the previous release. Rolling back twice returns to the newer one. + pub fn rollback(&self) -> Result { + let state = self.state(); + let previous = state.previous.ok_or(UpdateError::NoPreviousRelease)?; + if !previous.is_file() { + return Err(UpdateError::NoPreviousRelease); + } + self.activate(&previous)?; + Ok(previous) + } + + /// Windows start-up step: swaps a staged binary over the launcher. Returns true when a swap + /// happened and the process should restart into the new binary. + pub fn apply_pending(&self) -> Result { + let mut state = self.state(); + let Some(pending) = state.pending.clone() else { + return Ok(false); + }; + if !pending.is_file() { + state.pending = None; + self.save_state(&state)?; + return Ok(false); + } + let sibling = |suffix: &str| { + let mut name = self.launcher.as_os_str().to_owned(); + name.push(suffix); + PathBuf::from(name) + }; + let (fresh, swap, backup) = (sibling(".new"), sibling(".swap"), sibling(".old")); + let _ = std::fs::remove_file(&fresh); + std::fs::copy(&pending, &fresh).map_err(UpdateError::io)?; + if self.launcher.exists() { + std::fs::rename(&self.launcher, &swap).map_err(UpdateError::io)?; + if let Err(error) = std::fs::rename(&fresh, &self.launcher) { + // Put the running executable back so the client can still start. + let _ = std::fs::rename(&swap, &self.launcher); + return Err(UpdateError::io(error)); + } + let _ = std::fs::remove_file(&backup); + std::fs::rename(&swap, &backup).map_err(UpdateError::io)?; + state.previous = Some(backup); + } else { + std::fs::rename(&fresh, &self.launcher).map_err(UpdateError::io)?; + } + state.current = Some(self.launcher.clone()); + state.pending = None; + self.save_state(&state)?; + Ok(true) + } + + /// Deletes old version directories, keeping the current, previous and pending releases. + /// Directories whose names are not plain versions are left alone. + fn prune(&self) { + let state = self.state(); + let keep: Vec<&PathBuf> = [&state.current, &state.previous, &state.pending] + .into_iter() + .flatten() + .collect(); + let Ok(entries) = std::fs::read_dir(&self.releases_dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let is_version = entry + .file_name() + .to_str() + .is_some_and(|name| semver::Version::parse(name).is_ok()); + if is_version && path.is_dir() && !keep.iter().any(|kept| kept.starts_with(&path)) { + let _ = std::fs::remove_dir_all(&path); + } + } + } +} + +/// A version used as a directory name must be a plain semver, never a path. +fn validate_version_dir(version: &str) -> Result<(), UpdateError> { + if semver::Version::parse(version).is_err() || version.contains(['/', '\\']) { + return Err(UpdateError::Manifest(format!( + "invalid version `{version}`" + ))); + } + Ok(()) +} + +fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), UpdateError> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes).map_err(UpdateError::io)?; + std::fs::rename(&tmp, path).map_err(UpdateError::io) +} + +#[cfg(unix)] +fn swap_link(target: &Path, launcher: &Path) -> Result<(), UpdateError> { + if let Some(parent) = launcher.parent() { + std::fs::create_dir_all(parent).map_err(UpdateError::io)?; + } + let tmp = launcher.with_file_name(".vnox-client.swap"); + let _ = std::fs::remove_file(&tmp); + std::os::unix::fs::symlink(target, &tmp).map_err(UpdateError::io)?; + std::fs::rename(&tmp, launcher).map_err(|error| { + let _ = std::fs::remove_file(&tmp); + UpdateError::io(error) + }) +} + +#[cfg(not(unix))] +fn swap_link(_target: &Path, _launcher: &Path) -> Result<(), UpdateError> { + Err(UpdateError::Io("link swap is not supported here".into())) +} + +#[cfg(test)] +mod tests { + use super::super::archive::test_archives::single; + use super::*; + + fn fixture(mode: Activation) -> (tempfile::TempDir, Layout) { + let dir = tempfile::tempdir().unwrap(); + let layout = Layout { + releases_dir: dir.path().join("lib/releases"), + launcher: dir.path().join("bin/vnox-client"), + downloads_dir: dir.path().join("dl"), + activation: mode, + }; + (dir, layout) + } + + fn archive(dir: &Path, name: &str, body: &[u8]) -> PathBuf { + let path = dir.join(name); + std::fs::write(&path, single(BINARY_NAME, body)).unwrap(); + path + } + + #[cfg(unix)] + #[test] + fn install_swaps_link_and_keeps_previous_then_rolls_back() { + let (dir, layout) = fixture(Activation::SwapLink); + let a1 = archive(dir.path(), "1.tgz", b"v1"); + let a2 = archive(dir.path(), "2.tgz", b"v2"); + layout.install_archive("0.1.0", &a1, 1000).unwrap(); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v1"); + layout.install_archive("0.2.0", &a2, 1000).unwrap(); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v2"); + let state = layout.state(); + assert!( + state + .previous + .as_ref() + .unwrap() + .starts_with(layout.releases_dir.join("0.1.0")) + ); + + layout.rollback().unwrap(); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v1"); + // Rolling back again returns to the newer release. + layout.rollback().unwrap(); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v2"); + } + + #[cfg(unix)] + #[test] + fn old_releases_are_pruned_but_current_and_previous_stay() { + let (dir, layout) = fixture(Activation::SwapLink); + for (i, v) in ["0.1.0", "0.2.0", "0.3.0"].iter().enumerate() { + let a = archive(dir.path(), &format!("{i}.tgz"), v.as_bytes()); + layout.install_archive(v, &a, 1000).unwrap(); + } + assert!(!layout.releases_dir.join("0.1.0").exists()); + assert!(layout.releases_dir.join("0.2.0").exists()); + assert!(layout.releases_dir.join("0.3.0").exists()); + } + + #[cfg(unix)] + #[test] + fn plain_file_launcher_is_preserved_for_rollback() { + let (dir, layout) = fixture(Activation::SwapLink); + std::fs::create_dir_all(layout.launcher.parent().unwrap()).unwrap(); + std::fs::write(&layout.launcher, b"legacy").unwrap(); + let a = archive(dir.path(), "1.tgz", b"new"); + layout.install_archive("0.2.0", &a, 1000).unwrap(); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"new"); + layout.rollback().unwrap(); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"legacy"); + } + + #[cfg(unix)] + #[test] + fn failed_extraction_leaves_the_active_release_untouched() { + let (dir, layout) = fixture(Activation::SwapLink); + let a1 = archive(dir.path(), "1.tgz", b"v1"); + layout.install_archive("0.1.0", &a1, 1000).unwrap(); + let bad = dir.path().join("bad.tgz"); + std::fs::write(&bad, single("../evil", b"x")).unwrap(); + assert!(layout.install_archive("0.2.0", &bad, 1000).is_err()); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"v1"); + assert!(!layout.releases_dir.join("0.2.0").exists()); + let leftovers: Vec<_> = std::fs::read_dir(&layout.releases_dir) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with(".staging")) + .collect(); + assert!(leftovers.is_empty()); + } + + #[test] + fn rollback_without_previous_is_an_error() { + let (_dir, layout) = fixture(Activation::SwapLink); + assert!(matches!( + layout.rollback(), + Err(UpdateError::NoPreviousRelease) + )); + } + + #[test] + fn version_must_not_be_a_path() { + let (dir, layout) = fixture(Activation::SwapLink); + let a = archive(dir.path(), "1.tgz", b"x"); + assert!(layout.install_archive("../../x", &a, 1000).is_err()); + } + + #[test] + fn windows_style_install_stages_then_swaps_on_start() { + let (dir, layout) = fixture(Activation::StageForRestart); + std::fs::create_dir_all(layout.launcher.parent().unwrap()).unwrap(); + std::fs::write(&layout.launcher, b"old").unwrap(); + let a = archive(dir.path(), "1.tgz", b"new"); + layout.install_archive("0.2.0", &a, 1000).unwrap(); + // Nothing replaced yet: the running executable stays as it is. + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"old"); + assert!(layout.state().pending.is_some()); + + assert!(layout.apply_pending().unwrap()); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"new"); + let state = layout.state(); + assert!(state.pending.is_none()); + assert_eq!(std::fs::read(state.previous.unwrap()).unwrap(), b"old"); + assert!(!layout.apply_pending().unwrap()); + } + + #[test] + fn windows_style_rollback_stages_previous() { + let (dir, layout) = fixture(Activation::StageForRestart); + std::fs::create_dir_all(layout.launcher.parent().unwrap()).unwrap(); + std::fs::write(&layout.launcher, b"old").unwrap(); + let a = archive(dir.path(), "1.tgz", b"new"); + layout.install_archive("0.2.0", &a, 1000).unwrap(); + layout.apply_pending().unwrap(); + layout.rollback().unwrap(); + assert!(layout.apply_pending().unwrap()); + assert_eq!(std::fs::read(&layout.launcher).unwrap(), b"old"); + } +} diff --git a/src/update/manager.rs b/src/update/manager.rs new file mode 100644 index 0000000..00b2255 --- /dev/null +++ b/src/update/manager.rs @@ -0,0 +1,539 @@ +//! The update state machine: check, download and install as separate steps. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use sha2::{Digest, Sha256}; + +use super::feed::{self, CentralVersionSource}; +use super::http::{self, HttpPolicy, Url}; +use super::layout::Layout; +use super::manifest::{Artifact, Manifest, parse_version}; +use super::settings::UpdateSettings; +use super::{ + CHANNEL, CLIENT_VERSION, LNEX_PROTOCOL, RELEASE_HOST, RELEASE_REPO, UpdateError, keys, +}; + +const MANIFEST_FILE: &str = "manifest.json"; +const SIGNATURE_FILE: &str = "manifest.json.sig"; +const ARCHIVE_FILE: &str = "artifact.tar.gz"; + +/// Everything the updater needs to know about its environment. +#[derive(Clone, Debug)] +pub struct UpdateConfig { + /// Gitea base URL, without a trailing slash. + pub api_base: String, + pub repo: String, + pub channel: String, + /// Accepted release keys; more than one only while a key is being rotated. + pub public_keys: Vec<[u8; 32]>, + pub http: HttpPolicy, + pub layout: Layout, + /// Version of the running client. + pub installed_version: String, + pub os: String, + pub arch: String, + /// Largest archive accepted. + pub max_artifact_bytes: u64, + /// Largest binary extracted from an archive. + pub max_binary_bytes: u64, +} + +impl UpdateConfig { + /// Production configuration: the embedded key, the release host only, this build's version. + pub fn production(layout: Layout) -> Self { + Self { + api_base: format!("https://{RELEASE_HOST}"), + repo: RELEASE_REPO.to_string(), + channel: CHANNEL.to_string(), + public_keys: keys::production_keys(), + http: HttpPolicy::production(), + layout, + installed_version: CLIENT_VERSION.to_string(), + os: std::env::consts::OS.to_string(), + arch: std::env::consts::ARCH.to_string(), + max_artifact_bytes: 256 * 1024 * 1024, + max_binary_bytes: 512 * 1024 * 1024, + } + } +} + +/// Where the updater is in its flow. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum UpdatePhase { + Idle, + Checking, + UpToDate, + Available { + version: String, + }, + Downloading { + version: String, + }, + /// Downloaded and verified; waiting to be installed. + Ready { + version: String, + }, + /// Install requested during a voice session; it runs once the session ends. + InstallDeferred { + version: String, + }, + Installing { + version: String, + }, + /// Installed; takes effect on the next start. + Installed { + version: String, + }, + /// The installed version is older than the release's `min_version`. + ManualInstallRequired { + version: String, + }, + Error(String), +} + +/// A snapshot for the UI. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UpdateStatus { + pub phase: UpdatePhase, + pub installed_version: String, + pub lnex_version: String, + pub auto_update: bool, + /// Latest version reported by the optional Central source. Advisory only. + pub central_latest: Option, +} + +/// Result of [`UpdateManager::install`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum InstallOutcome { + Installed { + version: String, + }, + /// A voice session is active; the install runs when it ends. + Deferred { + version: String, + }, +} + +struct Candidate { + manifest_bytes: Vec, + signature: Vec, + version: String, + artifact: Artifact, +} + +struct Inner { + phase: UpdatePhase, + candidate: Option, + staged: Option<(String, PathBuf)>, + install_deferred: bool, + central_latest: Option, + settings: UpdateSettings, +} + +/// Drives updates. Share it as `Arc`; every method takes `&self`. +pub struct UpdateManager { + cfg: UpdateConfig, + inner: Mutex, + voice_active: AtomicBool, + central: Option>, + settings_path: PathBuf, + /// Serialises check, download and install so they never overlap. + busy: tokio::sync::Mutex<()>, +} + +impl UpdateManager { + pub fn new( + cfg: UpdateConfig, + central: Option>, + settings_path: PathBuf, + ) -> Arc { + let settings = UpdateSettings::load(&settings_path); + Arc::new(Self { + cfg, + inner: Mutex::new(Inner { + phase: UpdatePhase::Idle, + candidate: None, + staged: None, + install_deferred: false, + central_latest: None, + settings, + }), + voice_active: AtomicBool::new(false), + central, + settings_path, + busy: tokio::sync::Mutex::new(()), + }) + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn set_phase(&self, phase: UpdatePhase) { + self.lock().phase = phase; + } + + fn fail(&self, error: UpdateError) -> Result { + self.set_phase(UpdatePhase::Error(error.to_string())); + Err(error) + } + + pub fn status(&self) -> UpdateStatus { + let inner = self.lock(); + UpdateStatus { + phase: inner.phase.clone(), + installed_version: self.cfg.installed_version.clone(), + lnex_version: LNEX_PROTOCOL.to_string(), + auto_update: inner.settings.auto_update, + central_latest: inner.central_latest.clone(), + } + } + + pub fn auto_update(&self) -> bool { + self.lock().settings.auto_update + } + + /// Changes and persists the automatic update switch. + pub fn set_auto_update(&self, enabled: bool) -> std::io::Result<()> { + let settings = { + let mut inner = self.lock(); + inner.settings.auto_update = enabled; + inner.settings.clone() + }; + settings.save(&self.settings_path) + } + + /// Tells the updater whether a voice session is running. Installs never run during one. + pub fn set_voice_active(&self, active: bool) { + self.voice_active.store(active, Ordering::SeqCst); + } + + /// True when an install was requested during a voice session and is still waiting. + pub fn install_waiting(&self) -> bool { + self.lock().install_deferred + } + + /// Step 1: looks for a newer signed release. Nothing is downloaded. + pub async fn check(&self) -> Result { + let _guard = self.busy.lock().await; + self.set_phase(UpdatePhase::Checking); + if let Some(central) = &self.central { + // Advisory only; a failing Central never blocks the signed Gitea feed. + let latest = central.latest_version().await.ok().flatten(); + self.lock().central_latest = latest; + } + match self.check_inner().await { + Ok(phase) => { + self.set_phase(phase.clone()); + Ok(phase) + } + Err(error) => self.fail(error), + } + } + + async fn check_inner(&self) -> Result { + if self.cfg.public_keys.iter().all(keys::is_placeholder) { + return Err(UpdateError::NoReleaseKey); + } + let (bytes, signature) = + feed::fetch_latest_manifest(&self.cfg.http, &self.cfg.api_base, &self.cfg.repo).await?; + let manifest = Manifest::verify_and_parse(&self.cfg.public_keys, &bytes, &signature)?; + let candidate = self.cfg.evaluate(&manifest)?; + let Some(artifact) = candidate else { + self.lock().candidate = None; + return Ok(UpdatePhase::UpToDate); + }; + let version = manifest.version.trim_start_matches('v').to_string(); + let installed = parse_version(&self.cfg.installed_version)?; + if installed < manifest.min_version()? { + self.lock().candidate = None; + return Ok(UpdatePhase::ManualInstallRequired { version }); + } + self.lock().candidate = Some(Candidate { + manifest_bytes: bytes, + signature, + version: version.clone(), + artifact, + }); + Ok(UpdatePhase::Available { version }) + } + + /// Step 2: downloads and verifies the archive found by [`check`](Self::check). + pub async fn download(&self) -> Result { + let _guard = self.busy.lock().await; + let (version, artifact, manifest_bytes, signature) = { + let inner = self.lock(); + match &inner.candidate { + Some(c) => ( + c.version.clone(), + c.artifact.clone(), + c.manifest_bytes.clone(), + c.signature.clone(), + ), + None => { + drop(inner); + return self.fail(UpdateError::NothingDownloaded); + } + } + }; + self.set_phase(UpdatePhase::Downloading { + version: version.clone(), + }); + match self + .download_inner(&version, &artifact, &manifest_bytes, &signature) + .await + { + Ok(dir) => { + let mut inner = self.lock(); + inner.staged = Some((version.clone(), dir)); + inner.phase = UpdatePhase::Ready { version }; + Ok(inner.phase.clone()) + } + Err(error) => self.fail(error), + } + } + + async fn download_inner( + &self, + version: &str, + artifact: &Artifact, + manifest_bytes: &[u8], + signature: &[u8], + ) -> Result { + let dir = self.cfg.layout.downloads_dir.join(version); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).map_err(UpdateError::io)?; + let partial = dir.join(format!("{ARCHIVE_FILE}.part")); + let result = self.fetch_archive(artifact, &partial).await; + if let Err(error) = result { + let _ = std::fs::remove_dir_all(&dir); + return Err(error); + } + std::fs::write(dir.join(MANIFEST_FILE), manifest_bytes).map_err(UpdateError::io)?; + std::fs::write(dir.join(SIGNATURE_FILE), signature).map_err(UpdateError::io)?; + std::fs::rename(&partial, dir.join(ARCHIVE_FILE)).map_err(UpdateError::io)?; + Ok(dir) + } + + async fn fetch_archive(&self, artifact: &Artifact, partial: &Path) -> Result<(), UpdateError> { + let mut file = std::fs::File::create(partial).map_err(UpdateError::io)?; + let mut hasher = Sha256::new(); + let mut total = 0u64; + http::fetch(&self.cfg.http, &artifact.url, artifact.size, &mut |chunk| { + hasher.update(chunk); + total += chunk.len() as u64; + std::io::Write::write_all(&mut file, chunk).map_err(UpdateError::io) + }) + .await?; + file.sync_all().map_err(UpdateError::io)?; + if total != artifact.size { + return Err(UpdateError::SizeMismatch); + } + if hex::encode(hasher.finalize()) != artifact.sha256 { + return Err(UpdateError::HashMismatch); + } + Ok(()) + } + + /// Looks for a verified download left by an earlier run and makes it ready to install. + /// Invalid or outdated leftovers are deleted. Returns the ready version, if any. + pub fn restore_staged(&self) -> Option { + let entries = std::fs::read_dir(&self.cfg.layout.downloads_dir).ok()?; + let mut best: Option<(semver::Version, String, PathBuf)> = None; + for entry in entries.flatten() { + let dir = entry.path(); + match self.cfg.verify_staged(&dir) { + Ok((version, _)) => { + if let Ok(parsed) = parse_version(&version) + && best.as_ref().is_none_or(|(b, _, _)| parsed > *b) + { + best = Some((parsed, version, dir)); + continue; + } + let _ = std::fs::remove_dir_all(&dir); + } + Err(_) => { + let _ = std::fs::remove_dir_all(&dir); + } + } + } + let (_, version, dir) = best?; + let mut inner = self.lock(); + inner.staged = Some((version.clone(), dir)); + inner.phase = UpdatePhase::Ready { + version: version.clone(), + }; + Some(version) + } + + /// Step 3: installs the verified download. During a voice session the install is deferred + /// and runs from [`run_deferred`](Self::run_deferred) after the session ends. + pub async fn install(&self) -> Result { + let _guard = self.busy.lock().await; + let Some((version, dir)) = self.lock().staged.clone() else { + return self.fail(UpdateError::NothingDownloaded); + }; + if self.voice_active.load(Ordering::SeqCst) { + let mut inner = self.lock(); + inner.install_deferred = true; + inner.phase = UpdatePhase::InstallDeferred { + version: version.clone(), + }; + return Ok(InstallOutcome::Deferred { version }); + } + self.install_now(version, dir).await + } + + async fn install_now( + &self, + version: String, + dir: PathBuf, + ) -> Result { + self.lock().install_deferred = false; + self.set_phase(UpdatePhase::Installing { + version: version.clone(), + }); + let cfg = self.cfg.clone(); + let (this_version, this_dir) = (version.clone(), dir.clone()); + let outcome = tokio::task::spawn_blocking(move || { + let (verified_version, archive) = cfg.verify_staged(&this_dir)?; + if verified_version != this_version { + return Err(UpdateError::Manifest("staged version changed".into())); + } + cfg.layout + .install_archive(&this_version, &archive, cfg.max_binary_bytes) + }) + .await + .unwrap_or_else(|error| Err(UpdateError::Io(error.to_string()))); + match outcome { + Ok(_) => { + let _ = std::fs::remove_dir_all(&dir); + let mut inner = self.lock(); + inner.staged = None; + inner.candidate = None; + inner.phase = UpdatePhase::Installed { + version: version.clone(), + }; + Ok(InstallOutcome::Installed { version }) + } + Err(error) => self.fail(error), + } + } + + /// Runs an install that was deferred by a voice session, once the session is over. + /// Returns `None` when nothing was waiting or voice is still active. + pub async fn run_deferred(&self) -> Option> { + if !self.install_waiting() || self.voice_active.load(Ordering::SeqCst) { + return None; + } + Some(self.install().await) + } + + /// Start-up step: swaps in a staged Windows binary (returns true when the process should + /// restart), then restores a verified download. With automatic updates on, that download is + /// installed now, before any voice session can exist. + pub async fn startup(&self) -> bool { + let restart = self.cfg.layout.apply_pending().unwrap_or(false); + if self.restore_staged().is_some() + && self.auto_update() + && let Err(error) = self.install().await + { + tracing::warn!("startup update install failed: {error}"); + } + restart + } + + /// One background pass for automatic updates: check, then download. Never installs. + pub async fn auto_pass(&self) { + if !self.auto_update() { + return; + } + match self.check().await { + Ok(UpdatePhase::Available { .. }) => { + if let Err(error) = self.download().await { + tracing::warn!("automatic update download failed: {error}"); + } + } + Ok(_) => {} + Err(error) => tracing::warn!("automatic update check failed: {error}"), + } + } + + /// Switches back to the previous release. Takes effect on the next start. + pub fn rollback(&self) -> Result<(), UpdateError> { + self.cfg.layout.rollback().map(|_| ()) + } +} + +impl UpdateConfig { + /// Applies the version, channel and artifact rules to a verified manifest. Returns the + /// artifact to download, or `None` when the installed version is already current. + pub(crate) fn evaluate(&self, manifest: &Manifest) -> Result, UpdateError> { + if manifest.channel != self.channel { + return Err(UpdateError::ChannelMismatch(manifest.channel.clone())); + } + let offered = manifest.version()?; + let installed = parse_version(&self.installed_version)?; + if offered == installed { + return Ok(None); + } + if offered < installed { + return Err(UpdateError::Downgrade { + installed: installed.to_string(), + offered: offered.to_string(), + }); + } + let artifact = manifest + .artifact_for(&format!("{}-{}", self.os, self.arch)) + .ok_or(UpdateError::NoArtifact)? + .clone(); + let digest_ok = artifact.sha256.len() == 64 + && artifact + .sha256 + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + if !digest_ok || artifact.size == 0 || artifact.size > self.max_artifact_bytes { + return Err(UpdateError::Manifest("bad artifact entry".into())); + } + Url::parse(&artifact.url, &self.http)?; + Ok(Some(artifact)) + } + + /// Re-verifies a staged download from disk: signature, version, size and checksum. + /// Nothing from `dir` is trusted until this succeeds. + pub(crate) fn verify_staged(&self, dir: &Path) -> Result<(String, PathBuf), UpdateError> { + let read = |name: &str| std::fs::read(dir.join(name)).map_err(UpdateError::io); + let bytes = read(MANIFEST_FILE)?; + let signature = read(SIGNATURE_FILE)?; + let manifest = Manifest::verify_and_parse(&self.public_keys, &bytes, &signature)?; + let artifact = self + .evaluate(&manifest)? + .ok_or(UpdateError::AlreadyInstalled)?; + let archive = dir.join(ARCHIVE_FILE); + let meta = std::fs::metadata(&archive).map_err(UpdateError::io)?; + if meta.len() != artifact.size { + return Err(UpdateError::SizeMismatch); + } + let mut hasher = Sha256::new(); + let mut file = std::fs::File::open(&archive).map_err(UpdateError::io)?; + let mut buffer = [0u8; 64 * 1024]; + loop { + let read = std::io::Read::read(&mut file, &mut buffer).map_err(UpdateError::io)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + if hex::encode(hasher.finalize()) != artifact.sha256 { + return Err(UpdateError::HashMismatch); + } + Ok(( + manifest.version.trim_start_matches('v').to_string(), + archive, + )) + } +} diff --git a/src/update/manager_tests.rs b/src/update/manager_tests.rs new file mode 100644 index 0000000..3a93303 --- /dev/null +++ b/src/update/manager_tests.rs @@ -0,0 +1,438 @@ +//! Integration tests for the update flow against a local fake release server. + +use std::sync::Arc; +use std::time::Duration; + +use sha2::{Digest, Sha256}; + +use super::archive::{BINARY_NAME, test_archives::single}; +use super::feed::CentralVersionSource; +use super::http::HttpPolicy; +use super::keys::test_keys::{public, sign}; +use super::layout::{Activation, Layout}; +use super::manager::{InstallOutcome, UpdateConfig, UpdateManager, UpdatePhase}; +use super::manifest::{Manifest, sample}; +use super::test_support::FakeServer; +use super::{CLIENT_VERSION, LNEX_PROTOCOL, RELEASE_REPO, UpdateError, keys}; + +const API: &str = "/api/v1/repos/boba/VNOX-Client/releases/latest"; + +struct Fixture { + server: FakeServer, + dir: tempfile::TempDir, + archive: Vec, +} + +impl Fixture { + async fn new() -> Self { + let fixture = Fixture { + server: FakeServer::start().await, + dir: tempfile::tempdir().unwrap(), + archive: single(BINARY_NAME, b"new-binary"), + }; + // The installed client: a launcher symlink to an old release binary. + let old = fixture.dir.path().join("lib/releases/old"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::write(old.join(BINARY_NAME), b"old-binary").unwrap(); + std::fs::create_dir_all(fixture.dir.path().join("bin")).unwrap(); + std::os::unix::fs::symlink( + old.join(BINARY_NAME), + fixture.dir.path().join("bin/vnox-client"), + ) + .unwrap(); + fixture + } + + fn launcher(&self) -> Vec { + std::fs::read(self.dir.path().join("bin/vnox-client")).unwrap() + } + + /// Publishes a signed release whose artifact is served by the fake server. + fn publish(&self, mut manifest: Manifest, archive: &[u8]) { + manifest.artifacts[0].url = self.server.url("/artifact"); + self.publish_manifest(&manifest, archive, false); + } + + fn publish_manifest(&self, manifest: &Manifest, archive: &[u8], wrong_key: bool) { + let bytes = serde_json::to_vec(manifest).unwrap(); + let signature = if wrong_key { + use ed25519_dalek::Signer; + ed25519_dalek::SigningKey::from_bytes(&[1u8; 32]) + .sign(&bytes) + .to_bytes() + .to_vec() + } else { + sign(&bytes) + }; + let release = serde_json::json!({ + "tag_name": format!("v{}", manifest.version), + "assets": [ + {"name": "manifest.json", "browser_download_url": self.server.url("/manifest.json")}, + {"name": "manifest.json.sig", "browser_download_url": self.server.url("/manifest.json.sig")}, + ], + }); + self.server + .route(API, 200, serde_json::to_vec(&release).unwrap()); + self.server.route("/manifest.json", 200, bytes); + self.server.route("/manifest.json.sig", 200, signature); + self.server.route("/artifact", 200, archive.to_vec()); + } + + /// Publishes the fixture archive with a correct hash and size. + fn publish_good(&self, version: &str) { + let manifest = sample( + version, + "", + &hex::encode(Sha256::digest(&self.archive)), + self.archive.len() as u64, + ); + self.publish(manifest, &self.archive.clone()); + } + + fn config(&self) -> UpdateConfig { + UpdateConfig { + api_base: self.server.url(""), + repo: RELEASE_REPO.into(), + channel: "stable".into(), + public_keys: vec![public()], + http: HttpPolicy { + allowed_hosts: vec!["127.0.0.1".into()], + require_https: false, + max_redirects: 2, + connect_timeout: Duration::from_secs(3), + read_timeout: Duration::from_secs(3), + }, + layout: Layout { + releases_dir: self.dir.path().join("lib/releases"), + launcher: self.dir.path().join("bin/vnox-client"), + downloads_dir: self.dir.path().join("dl"), + activation: Activation::SwapLink, + }, + installed_version: "0.1.0".into(), + os: std::env::consts::OS.into(), + arch: std::env::consts::ARCH.into(), + max_artifact_bytes: 1024 * 1024, + max_binary_bytes: 1024 * 1024, + } + } + + fn manager(&self) -> Arc { + UpdateManager::new(self.config(), None, self.dir.path().join("update.json")) + } +} + +#[tokio::test] +async fn full_flow_installs_then_rolls_back() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + let manager = fx.manager(); + + assert_eq!( + manager.check().await.unwrap(), + UpdatePhase::Available { + version: "0.2.0".into() + } + ); + // Checking alone downloads nothing. + assert!(!fx.server.hits().contains(&"/artifact".to_string())); + manager.download().await.unwrap(); + assert_eq!(fx.launcher(), b"old-binary"); + assert_eq!( + manager.install().await.unwrap(), + InstallOutcome::Installed { + version: "0.2.0".into() + } + ); + assert_eq!(fx.launcher(), b"new-binary"); + assert!(matches!( + manager.status().phase, + UpdatePhase::Installed { .. } + )); + + manager.rollback().unwrap(); + assert_eq!(fx.launcher(), b"old-binary"); +} + +#[tokio::test] +async fn bad_or_tampered_signature_is_rejected() { + let fx = Fixture::new().await; + let manifest = sample("0.2.0", &fx.server.url("/artifact"), &"a".repeat(64), 10); + fx.publish_manifest(&manifest, &fx.archive, true); + let manager = fx.manager(); + assert!(matches!( + manager.check().await, + Err(UpdateError::BadSignature) + )); + assert!(matches!(manager.status().phase, UpdatePhase::Error(_))); + + // Valid signature, but the manifest bytes served were modified afterwards. + fx.publish_good("0.2.0"); + let mut bytes = serde_json::to_vec(&sample("0.2.0", "x", "y", 1)).unwrap(); + bytes.push(b' '); + fx.server.route("/manifest.json", 200, bytes); + assert!(matches!( + manager.check().await, + Err(UpdateError::BadSignature) + )); +} + +#[tokio::test] +async fn placeholder_key_disables_updates() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + let mut cfg = fx.config(); + cfg.public_keys = keys::production_keys(); + let manager = UpdateManager::new(cfg, None, fx.dir.path().join("u.json")); + assert!(matches!( + manager.check().await, + Err(UpdateError::NoReleaseKey) + )); +} + +#[tokio::test] +async fn downgrade_is_rejected_and_same_version_is_up_to_date() { + let fx = Fixture::new().await; + let manager = fx.manager(); + fx.publish_good("0.0.9"); + assert!(matches!( + manager.check().await, + Err(UpdateError::Downgrade { .. }) + )); + fx.publish_good("0.1.0"); + assert_eq!(manager.check().await.unwrap(), UpdatePhase::UpToDate); + assert!(matches!( + manager.download().await, + Err(UpdateError::NothingDownloaded) + )); +} + +#[tokio::test] +async fn old_client_below_min_version_must_reinstall() { + let fx = Fixture::new().await; + let mut manifest = sample("0.5.0", "", &"a".repeat(64), 10); + manifest.min_version = "0.3.0".into(); + manifest.artifacts[0].url = fx.server.url("/artifact"); + fx.publish_manifest(&manifest, b"", false); + assert_eq!( + fx.manager().check().await.unwrap(), + UpdatePhase::ManualInstallRequired { + version: "0.5.0".into() + } + ); +} + +#[tokio::test] +async fn hash_mismatch_discards_the_download() { + let fx = Fixture::new().await; + let manifest = sample("0.2.0", "", &"0".repeat(64), fx.archive.len() as u64); + fx.publish(manifest, &fx.archive.clone()); + let manager = fx.manager(); + manager.check().await.unwrap(); + assert!(matches!( + manager.download().await, + Err(UpdateError::HashMismatch) + )); + assert!(!fx.dir.path().join("dl/0.2.0").exists()); + assert_eq!(fx.launcher(), b"old-binary"); +} + +#[tokio::test] +async fn download_larger_than_declared_size_is_aborted() { + let fx = Fixture::new().await; + let big = vec![7u8; 5000]; + let manifest = sample("0.2.0", "", &hex::encode(Sha256::digest(&big)), 100); + fx.publish(manifest, &big); + let manager = fx.manager(); + manager.check().await.unwrap(); + assert!(matches!( + manager.download().await, + Err(UpdateError::TooLarge) + )); + assert!(!fx.dir.path().join("dl/0.2.0").exists()); +} + +#[tokio::test] +async fn short_download_is_a_size_mismatch() { + let fx = Fixture::new().await; + let small = vec![7u8; 50]; + let manifest = sample("0.2.0", "", &hex::encode(Sha256::digest(&small)), 100); + fx.publish(manifest, &small); + let manager = fx.manager(); + manager.check().await.unwrap(); + assert!(matches!( + manager.download().await, + Err(UpdateError::SizeMismatch) + )); +} + +#[tokio::test] +async fn declared_size_over_the_global_limit_is_refused_at_check() { + let fx = Fixture::new().await; + let manifest = sample("0.2.0", "", &"a".repeat(64), 10 * 1024 * 1024); + fx.publish(manifest, b""); + assert!(matches!( + fx.manager().check().await, + Err(UpdateError::Manifest(_)) + )); +} + +#[tokio::test] +async fn manifest_url_outside_the_allowlist_is_refused() { + let fx = Fixture::new().await; + let manifest = sample("0.2.0", "http://evil.example/a", &"a".repeat(64), 10); + fx.publish_manifest(&manifest, b"", false); + assert!(matches!( + fx.manager().check().await, + Err(UpdateError::UrlRejected(_)) + )); +} + +#[tokio::test] +async fn traversal_archive_is_never_installed() { + let fx = Fixture::new().await; + let evil = single("../escape", b"pwn"); + let manifest = sample( + "0.2.0", + "", + &hex::encode(Sha256::digest(&evil)), + evil.len() as u64, + ); + fx.publish(manifest, &evil); + let manager = fx.manager(); + manager.check().await.unwrap(); + manager.download().await.unwrap(); + assert!(matches!( + manager.install().await, + Err(UpdateError::UnsafeArchive(_)) + )); + assert_eq!(fx.launcher(), b"old-binary"); + assert!(!fx.dir.path().join("lib/escape").exists()); + assert!(!fx.dir.path().join("lib/releases/escape").exists()); +} + +#[tokio::test] +async fn install_is_deferred_during_voice_and_runs_afterwards() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + let manager = fx.manager(); + manager.check().await.unwrap(); + manager.download().await.unwrap(); + + manager.set_voice_active(true); + assert_eq!( + manager.install().await.unwrap(), + InstallOutcome::Deferred { + version: "0.2.0".into() + } + ); + assert_eq!(fx.launcher(), b"old-binary"); + assert!(matches!( + manager.status().phase, + UpdatePhase::InstallDeferred { .. } + )); + // The call is still going: nothing happens. + assert!(manager.run_deferred().await.is_none()); + assert_eq!(fx.launcher(), b"old-binary"); + + manager.set_voice_active(false); + let outcome = manager.run_deferred().await.unwrap().unwrap(); + assert_eq!( + outcome, + InstallOutcome::Installed { + version: "0.2.0".into() + } + ); + assert_eq!(fx.launcher(), b"new-binary"); + assert!(manager.run_deferred().await.is_none()); +} + +#[tokio::test] +async fn auto_pass_downloads_but_does_not_install() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + let manager = fx.manager(); + manager.auto_pass().await; + assert!(matches!(manager.status().phase, UpdatePhase::Ready { .. })); + assert_eq!(fx.launcher(), b"old-binary"); +} + +#[tokio::test] +async fn auto_pass_does_nothing_when_disabled() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + let manager = fx.manager(); + manager.set_auto_update(false).unwrap(); + manager.auto_pass().await; + assert_eq!(manager.status().phase, UpdatePhase::Idle); + assert!(fx.server.hits().is_empty()); + // The choice survives a restart. + assert!(!fx.manager().auto_update()); +} + +#[tokio::test] +async fn startup_installs_a_staged_download_when_auto_is_on() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + fx.manager().auto_pass().await; + + // "Restart": a new manager finds the verified download on disk. + let second = fx.manager(); + assert!(!second.startup().await); + assert_eq!(fx.launcher(), b"new-binary"); +} + +#[tokio::test] +async fn startup_keeps_the_download_ready_when_auto_is_off() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + fx.manager().auto_pass().await; + let second = fx.manager(); + second.set_auto_update(false).unwrap(); + second.startup().await; + assert_eq!(fx.launcher(), b"old-binary"); + assert!(matches!(second.status().phase, UpdatePhase::Ready { .. })); +} + +#[tokio::test] +async fn tampered_staged_download_is_discarded_on_restore() { + let fx = Fixture::new().await; + fx.publish_good("0.2.0"); + fx.manager().auto_pass().await; + std::fs::write(fx.dir.path().join("dl/0.2.0/artifact.tar.gz"), b"tampered").unwrap(); + let second = fx.manager(); + assert!(second.restore_staged().is_none()); + assert!(!fx.dir.path().join("dl/0.2.0").exists()); + assert!(matches!( + second.install().await, + Err(UpdateError::NothingDownloaded) + )); +} + +#[tokio::test] +async fn central_source_is_advisory_only() { + struct Central; + impl CentralVersionSource for Central { + fn latest_version( + &self, + ) -> std::pin::Pin< + Box, UpdateError>> + Send + '_>, + > { + Box::pin(async { Ok(Some("9.9.9".to_string())) }) + } + } + let fx = Fixture::new().await; + fx.publish_good("0.1.0"); + let manager = UpdateManager::new( + fx.config(), + Some(Arc::new(Central)), + fx.dir.path().join("u.json"), + ); + assert_eq!(manager.check().await.unwrap(), UpdatePhase::UpToDate); + assert_eq!(manager.status().central_latest.as_deref(), Some("9.9.9")); +} + +#[test] +fn exposes_client_and_protocol_versions() { + assert_eq!(CLIENT_VERSION, env!("CARGO_PKG_VERSION")); + assert_eq!(LNEX_PROTOCOL, crate::net::payloads::LNEX_VERSION); +} diff --git a/src/update/manifest.rs b/src/update/manifest.rs new file mode 100644 index 0000000..88e13c2 --- /dev/null +++ b/src/update/manifest.rs @@ -0,0 +1,144 @@ +//! Release manifest: the signed description of one release. + +use semver::Version; +use serde::{Deserialize, Serialize}; + +use super::{UpdateError, keys}; + +/// Manifest format version understood by this client. +pub const SCHEMA: u32 = 1; + +/// Product name expected in the manifest. +pub const PRODUCT: &str = "vnox-client"; + +/// Largest manifest accepted, in bytes. +pub const MAX_MANIFEST_BYTES: usize = 64 * 1024; + +/// One downloadable build of the client. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Artifact { + /// File name of the release asset. + #[serde(default)] + pub name: String, + /// `-` using `std::env::consts` values, for example `linux-x86_64`. + pub platform: String, + pub url: String, + /// Lower case hex SHA-256 of the downloaded archive. + pub sha256: String, + pub size: u64, +} + +/// The release manifest published as the `manifest.json` release asset. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Manifest { + /// Manifest format version, currently 1. + pub schema: u32, + /// Always `vnox-client`. + pub product: String, + pub version: String, + pub channel: String, + /// Oldest installed version that may update in place. Older clients must reinstall. + pub min_version: String, + /// RFC 3339 publication time, informational. + pub published_at: String, + pub artifacts: Vec, +} + +impl Manifest { + /// Verifies the detached signature over the exact `bytes`, then parses them. + pub fn verify_and_parse( + public_keys: &[[u8; 32]], + bytes: &[u8], + signature: &[u8], + ) -> Result { + keys::verify_any(public_keys, bytes, signature)?; + if bytes.len() > MAX_MANIFEST_BYTES { + return Err(UpdateError::Manifest("manifest too large".into())); + } + let manifest: Manifest = serde_json::from_slice(bytes) + .map_err(|error| UpdateError::Manifest(error.to_string()))?; + if manifest.schema != SCHEMA || manifest.product != PRODUCT { + return Err(UpdateError::Manifest( + "unsupported schema or product".into(), + )); + } + manifest.version()?; + manifest.min_version()?; + Ok(manifest) + } + + pub fn version(&self) -> Result { + parse_version(&self.version) + } + + pub fn min_version(&self) -> Result { + parse_version(&self.min_version) + } + + /// The artifact built for this platform, if the release has one. + pub fn artifact_for(&self, platform: &str) -> Option<&Artifact> { + self.artifacts + .iter() + .find(|artifact| artifact.platform == platform) + } +} + +/// Parses a version, tolerating a leading `v`. +pub fn parse_version(text: &str) -> Result { + Version::parse(text.trim().trim_start_matches('v')) + .map_err(|_| UpdateError::Manifest(format!("invalid version `{text}`"))) +} + +#[cfg(test)] +pub(crate) fn sample(version: &str, url: &str, sha256: &str, size: u64) -> Manifest { + Manifest { + schema: SCHEMA, + product: PRODUCT.into(), + version: version.into(), + channel: "stable".into(), + min_version: "0.1.0".into(), + published_at: "2026-11-01T00:00:00Z".into(), + artifacts: vec![Artifact { + name: "artifact".into(), + platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH), + url: url.into(), + sha256: sha256.into(), + size, + }], + } +} + +#[cfg(test)] +mod tests { + use super::super::keys::test_keys::{public, sign}; + use super::*; + + #[test] + fn signed_manifest_parses() { + let bytes = + serde_json::to_vec(&sample("0.2.0", "https://git.wihuk.pro/x", "ab", 1)).unwrap(); + let manifest = Manifest::verify_and_parse(&[public()], &bytes, &sign(&bytes)).unwrap(); + assert_eq!(manifest.version().unwrap(), Version::new(0, 2, 0)); + } + + #[test] + fn tampered_manifest_is_rejected_before_parsing() { + let mut bytes = + serde_json::to_vec(&sample("0.2.0", "https://git.wihuk.pro/x", "ab", 1)).unwrap(); + let sig = sign(&bytes); + bytes[2] ^= 0x20; + assert!(matches!( + Manifest::verify_and_parse(&[public()], &bytes, &sig), + Err(UpdateError::BadSignature) + )); + } + + #[test] + fn signed_garbage_is_a_manifest_error() { + let bytes = b"not json"; + assert!(matches!( + Manifest::verify_and_parse(&[public()], bytes, &sign(bytes)), + Err(UpdateError::Manifest(_)) + )); + } +} diff --git a/src/update/mod.rs b/src/update/mod.rs new file mode 100644 index 0000000..e5f8cdf --- /dev/null +++ b/src/update/mod.rs @@ -0,0 +1,128 @@ +//! Versioning and the signed self-updater. +//! +//! The version has one source, `CARGO_PKG_VERSION` ([`CLIENT_VERSION`]); the wire protocol +//! version is [`LNEX_PROTOCOL`]. +//! +//! Update flow (each step is separate, see [`UpdateManager`]): +//! +//! 1. **check** reads the latest Gitea release of `boba/VNOX-Client`, downloads the +//! `manifest.json` and `manifest.json.sig` assets and verifies the Ed25519 signature over the +//! exact manifest bytes before parsing them; +//! 2. **download** fetches the archive for this platform with a hard size bound, verifies size +//! and SHA-256 and stores it together with the signed manifest; +//! 3. **install** re-verifies everything from disk, extracts only the expected binary and +//! activates it atomically, keeping the previous release for rollback. It is deferred while a +//! voice session is active. +//! +//! Release feed format produced by CI (assets of the latest, non-prerelease Gitea release): +//! +//! * `manifest.json`: `{"version","channel","min_version","published_at","artifacts":[{"os","arch","url","sha256","size"}]}` +//! where `os`/`arch` are Rust `std::env::consts` values (`linux`/`x86_64`), `url` is an HTTPS +//! URL on `git.wihuk.pro`, `sha256` is lower case hex of the archive and `size` its byte length; +//! * `manifest.json.sig`: detached Ed25519 signature over the exact bytes of `manifest.json`, +//! as 64 raw bytes or 128 hex characters; +//! * the artifact: a `.tar.gz` holding exactly one regular file, `vnox-client` +//! (`vnox-client.exe` on Windows), at its top level. +//! +//! `min_version` is the oldest installed version allowed to update in place; older clients are +//! told to reinstall by hand. + +pub mod archive; +pub mod feed; +pub mod http; +pub mod keys; +pub mod layout; +pub mod manager; +pub mod manifest; +pub mod settings; + +#[cfg(test)] +pub(crate) mod test_support; + +#[cfg(all(test, unix))] +mod manager_tests; + +pub use feed::CentralVersionSource; +pub use layout::{Activation, Layout}; +pub use manager::{InstallOutcome, UpdateConfig, UpdateManager, UpdatePhase, UpdateStatus}; +pub use manifest::Manifest; + +/// Version of this client, from `Cargo.toml`. +pub const CLIENT_VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// LNEx protocol version this client speaks. +pub const LNEX_PROTOCOL: &str = crate::net::payloads::LNEX_VERSION; + +/// The only host updates may be fetched from. +pub const RELEASE_HOST: &str = "git.wihuk.pro"; + +/// Gitea repository that publishes client releases. +pub const RELEASE_REPO: &str = "boba/VNOX-Client"; + +/// Release channel this build follows. +pub const CHANNEL: &str = "stable"; + +/// Why an update step failed. +#[derive(Debug, Clone)] +pub enum UpdateError { + /// The embedded release key is the unconfigured placeholder, so updates are disabled. + NoReleaseKey, + BadSignature, + Manifest(String), + /// The release is older than the installed version. + Downgrade { + installed: String, + offered: String, + }, + ChannelMismatch(String), + NoArtifact, + UrlRejected(String), + Network(String), + Http(u16), + TooLarge, + SizeMismatch, + HashMismatch, + UnsafeArchive(String), + Io(String), + AlreadyInstalled, + NoPreviousRelease, + NothingDownloaded, + NoLayout, +} + +impl UpdateError { + pub(crate) fn io(error: std::io::Error) -> Self { + UpdateError::Io(error.to_string()) + } +} + +impl std::fmt::Display for UpdateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + UpdateError::NoReleaseKey => write!(f, "no release signing key is configured"), + UpdateError::BadSignature => write!(f, "release signature is invalid"), + UpdateError::Manifest(why) => write!(f, "invalid release manifest: {why}"), + UpdateError::Downgrade { installed, offered } => { + write!(f, "refusing to downgrade from {installed} to {offered}") + } + UpdateError::ChannelMismatch(channel) => { + write!(f, "release is on channel `{channel}`") + } + UpdateError::NoArtifact => write!(f, "release has no build for this platform"), + UpdateError::UrlRejected(url) => write!(f, "URL not allowed: {url}"), + UpdateError::Network(why) => write!(f, "network error: {why}"), + UpdateError::Http(status) => write!(f, "server answered HTTP {status}"), + UpdateError::TooLarge => write!(f, "download exceeds the allowed size"), + UpdateError::SizeMismatch => write!(f, "download size does not match the manifest"), + UpdateError::HashMismatch => write!(f, "download checksum does not match"), + UpdateError::UnsafeArchive(why) => write!(f, "unsafe archive: {why}"), + UpdateError::Io(why) => write!(f, "disk error: {why}"), + UpdateError::AlreadyInstalled => write!(f, "this release is already installed"), + UpdateError::NoPreviousRelease => write!(f, "there is no previous release"), + UpdateError::NothingDownloaded => write!(f, "no verified update is downloaded"), + UpdateError::NoLayout => write!(f, "install location is unknown"), + } + } +} + +impl std::error::Error for UpdateError {} diff --git a/src/update/settings.rs b/src/update/settings.rs new file mode 100644 index 0000000..c00fa21 --- /dev/null +++ b/src/update/settings.rs @@ -0,0 +1,62 @@ +//! Persisted updater preferences. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// Updater preferences, stored as `update.json` in the config directory. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct UpdateSettings { + /// Check and download in the background; install on the next start. + pub auto_update: bool, +} + +impl Default for UpdateSettings { + fn default() -> Self { + Self { auto_update: true } + } +} + +/// Default location of the settings file. +pub fn default_path() -> PathBuf { + dirs::config_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join("vnox/update.json") +} + +impl UpdateSettings { + /// Loads settings; a missing or damaged file yields the defaults. + pub fn load(path: &Path) -> Self { + std::fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default() + } + + /// Saves settings atomically. + pub fn save(&self, path: &Path) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?; + std::fs::rename(&tmp, path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_to_auto_update_and_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("sub/update.json"); + assert!(UpdateSettings::load(&path).auto_update); + UpdateSettings { auto_update: false }.save(&path).unwrap(); + assert!(!UpdateSettings::load(&path).auto_update); + std::fs::write(&path, b"garbage").unwrap(); + assert!(UpdateSettings::load(&path).auto_update); + } +} diff --git a/src/update/test_support.rs b/src/update/test_support.rs new file mode 100644 index 0000000..955c876 --- /dev/null +++ b/src/update/test_support.rs @@ -0,0 +1,124 @@ +//! A tiny local HTTP server for updater tests. No real network is used. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +#[derive(Clone)] +enum Route { + Body(u16, Vec), + Chunked(Vec), + Redirect(String), +} + +pub struct FakeServer { + port: u16, + routes: Arc>>, + hits: Arc>>, + task: tokio::task::JoinHandle<()>, +} + +impl Drop for FakeServer { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl FakeServer { + pub async fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let routes: Arc>> = Arc::default(); + let hits: Arc>> = Arc::default(); + let (shared, seen) = (routes.clone(), hits.clone()); + let task = tokio::spawn(async move { + loop { + let Ok((mut stream, _)) = listener.accept().await else { + return; + }; + let (routes, hits) = (shared.clone(), seen.clone()); + tokio::spawn(async move { + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.windows(4).any(|w| w == b"\r\n\r\n") { + match stream.read(&mut buffer).await { + Ok(0) | Err(_) => return, + Ok(n) => request.extend_from_slice(&buffer[..n]), + } + } + let text = String::from_utf8_lossy(&request).to_string(); + let path = text.split_whitespace().nth(1).unwrap_or("/").to_string(); + hits.lock().unwrap().push(path.clone()); + let route = routes.lock().unwrap().get(&path).cloned(); + let response = match route { + Some(Route::Body(status, body)) => { + let mut out = format!( + "HTTP/1.1 {status} X\r\nContent-Length: {}\r\n\r\n", + body.len() + ) + .into_bytes(); + out.extend_from_slice(&body); + out + } + Some(Route::Chunked(body)) => { + let mut out = + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n".to_vec(); + for piece in body.chunks(700) { + out.extend_from_slice(format!("{:x}\r\n", piece.len()).as_bytes()); + out.extend_from_slice(piece); + out.extend_from_slice(b"\r\n"); + } + out.extend_from_slice(b"0\r\n\r\n"); + out + } + Some(Route::Redirect(to)) => format!( + "HTTP/1.1 302 Found\r\nLocation: {to}\r\nContent-Length: 0\r\n\r\n" + ) + .into_bytes(), + None => b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".to_vec(), + }; + let _ = stream.write_all(&response).await; + let _ = stream.shutdown().await; + }); + } + }); + Self { + port, + routes, + hits, + task, + } + } + + pub fn url(&self, path: &str) -> String { + format!("http://127.0.0.1:{}{path}", self.port) + } + + pub fn route(&self, path: &str, status: u16, body: Vec) { + self.routes + .lock() + .unwrap() + .insert(path.into(), Route::Body(status, body)); + } + + pub fn route_chunked(&self, path: &str, body: Vec) { + self.routes + .lock() + .unwrap() + .insert(path.into(), Route::Chunked(body)); + } + + pub fn redirect(&self, path: &str, to: &str) { + self.routes + .lock() + .unwrap() + .insert(path.into(), Route::Redirect(to.into())); + } + + /// Paths requested so far, in order. + pub fn hits(&self) -> Vec { + self.hits.lock().unwrap().clone() + } +} From 2790aadeba9b1bc4e32e9780045a0a094b010328 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sun, 1 Nov 2026 16:20:51 +0100 Subject: [PATCH 3/5] feat(client): updates settings panel and updater wiring --- CHANGELOG.md | 4 + src/main.rs | 1 + src/ui/mod.rs | 1 + src/ui/slint/main.slint | 1 + src/ui/slint/settings.slint | 11 +- src/ui/slint/settings/updates.slint | 79 ++++++++ src/ui/updater.rs | 214 +++++++++++++++++++++ translations/en/LC_MESSAGES/vnox-client.po | 39 ++++ translations/ru.json | 28 ++- translations/ru/LC_MESSAGES/vnox-client.po | 39 ++++ 10 files changed, 412 insertions(+), 5 deletions(-) create mode 100644 src/ui/slint/settings/updates.slint create mode 100644 src/ui/updater.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a524671..fdf5a2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added: signed updater +- Settings, Updates: installed client version and LNEx protocol version, manual check, download and install, rollback, and an automatic update switch (check and download in the background, install on the next start, never during a voice call). +- Updates come from the Gitea release `manifest.json` plus detached Ed25519 `manifest.json.sig`, verified before parsing; archive size and SHA-256 are verified, downgrades and foreign hosts are refused, the archive is extracted safely and the previous release is kept for rollback. The embedded release key in `src/update/keys.rs` is a placeholder until the real key is set, so updates stay off until then. + ### Changed (breaking): LNEx v3, TLS 1.3 control connection - The control connection is TLS 1.3 only (rustls, ALPN `vnox-lnex/3`). The custom X25519/HKDF/ChaCha20 TCP layer, the plaintext loopback shortcut and the `lnex://` plaintext meaning are removed. Protocol version `v3`; old gateways are refused with an explicit error, no fallback. - Server trust: SPKI SHA-256 pin stored in `~/.config/vnox/known_servers.json` (trust on first use with a confirmation dialog, RU/EN), public CA certificates accepted without a prompt, a changed fingerprint or server identity is blocked and offers "Forget this server". diff --git a/src/main.rs b/src/main.rs index 00e5527..faa8f7a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -83,6 +83,7 @@ fn main() -> Result<()> { ))?)); wire_signals(&window, &state); ui::media::wire(&window, &state)?; + let _update_timer = ui::updater::wire(&window, &state); let timer = slint::Timer::default(); { diff --git a/src/ui/mod.rs b/src/ui/mod.rs index a794b63..a60ca23 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -10,5 +10,6 @@ pub mod slint; pub mod sounds; pub mod state; pub mod update; +pub mod updater; pub mod webhooks; diff --git a/src/ui/slint/main.slint b/src/ui/slint/main.slint index 0dfd2e5..f895eed 100644 --- a/src/ui/slint/main.slint +++ b/src/ui/slint/main.slint @@ -2,6 +2,7 @@ export { WebhookWindow, WebhookRow } from "webhooks.slint"; export { ScreenShareWindow, ScreenViewerWindow } from "screen-share.slint"; export { UnlockWindow } from "unlock.slint"; export { Theme } from "theme.slint"; +export { UpdateUi } from "settings/updates.slint"; export { EmojiCatalog, EmojiItem } from "emoji-picker.slint"; import { Theme, ActionButton } from "theme.slint"; import { Sidebar, ChannelItem, GuildItem, DmItem } from "sidebar.slint"; diff --git a/src/ui/slint/settings.slint b/src/ui/slint/settings.slint index 07ae296..6fc8c76 100644 --- a/src/ui/slint/settings.slint +++ b/src/ui/slint/settings.slint @@ -3,6 +3,7 @@ import { AudioSettings } from "settings/audio.slint"; import { SoundSettings } from "settings/sounds.slint"; import { AppearanceSettings } from "settings/appearance.slint"; import { IdentitySettings } from "settings/identity.slint"; +import { UpdateSettings } from "settings/updates.slint"; component SettingsNav inherits Rectangle { in property label; @@ -102,6 +103,7 @@ export component SettingsWindow inherits Rectangle { SettingsNav { label: @tr("Audio & microphone"); detail: @tr("Devices and voice input"); mark: "mic"; active: root.active-tab == "audio"; clicked => { root.active-tab = "audio"; } } SettingsNav { label: @tr("Appearance"); detail: @tr("Themes, colours and text"); mark: "palette"; active: root.active-tab == "appearance"; clicked => { root.active-tab = "appearance"; } } SettingsNav { label: @tr("Profile and keys"); detail: @tr("Security and backup"); mark: "user"; active: root.active-tab == "identity"; clicked => { root.active-tab = "identity"; } } + SettingsNav { label: @tr("Updates"); detail: @tr("Version and updates"); mark: "shield-check"; active: root.active-tab == "updates"; clicked => { root.active-tab = "updates"; } } Rectangle { vertical-stretch: 1; } Rectangle { height: 1px; background: Theme.border; } Text { text: "VNOX"; color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 3px, 11px); font-weight: 700; height: 30px; vertical-alignment: bottom; } @@ -118,8 +120,8 @@ export component SettingsWindow inherits Rectangle { padding-left: 34px; padding-right: 28px; padding-top: 29px; padding-bottom: 20px; spacing: 18px; VerticalLayout { spacing: 6px; - Text { text: root.active-tab == "appearance" ? @tr("Appearance") : root.active-tab == "identity" ? @tr("Profile and keys") : @tr("Audio & microphone"); color: Theme.text-primary; font-size: Theme.font-size + 12px; font-weight: 700; } - Text { text: root.active-tab == "appearance" ? @tr("Make Vnox yours.") : root.active-tab == "identity" ? @tr("Your profile, kept safe.") : @tr("Make yourself heard, your way."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); } + Text { text: root.active-tab == "appearance" ? @tr("Appearance") : root.active-tab == "identity" ? @tr("Profile and keys") : root.active-tab == "updates" ? @tr("Updates") : @tr("Audio & microphone"); color: Theme.text-primary; font-size: Theme.font-size + 12px; font-weight: 700; } + Text { text: root.active-tab == "appearance" ? @tr("Make Vnox yours.") : root.active-tab == "identity" ? @tr("Your profile, kept safe.") : root.active-tab == "updates" ? @tr("Stay current, safely.") : @tr("Make yourself heard, your way."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); } } Rectangle { horizontal-stretch: 1; } VerticalLayout { alignment: start; ActionButton { text: @tr("Close settings"); icon: "x"; width: 34px; height: 34px; quiet: true; clicked => { root.close(); } } } @@ -130,7 +132,7 @@ export component SettingsWindow inherits Rectangle { content-width: self.width; VerticalLayout { padding-left: 34px; padding-right: 34px; padding-top: 28px; padding-bottom: 16px; spacing: 0; - if root.active-tab == "audio" || (root.active-tab != "appearance" && root.active-tab != "identity") : AudioSettings { + if root.active-tab == "audio" || (root.active-tab != "appearance" && root.active-tab != "identity" && root.active-tab != "updates") : AudioSettings { input-devices: root.input-devices; output-devices: root.output-devices; input-device-index <=> root.input-device-index; @@ -140,7 +142,7 @@ export component SettingsWindow inherits Rectangle { volume <=> root.volume; audio-changed => { root.audio-changed(); } } - if root.active-tab == "audio" || (root.active-tab != "appearance" && root.active-tab != "identity") : SoundSettings { + if root.active-tab == "audio" || (root.active-tab != "appearance" && root.active-tab != "identity" && root.active-tab != "updates") : SoundSettings { sounds-enabled <=> root.sounds-enabled; sounds-volume <=> root.sounds-volume; sounds-voice-room <=> root.sounds-voice-room; @@ -167,6 +169,7 @@ export component SettingsWindow inherits Rectangle { import-theme(path) => { root.import-theme(path); } export-theme(path) => { root.export-theme(path); } } + if root.active-tab == "updates" : UpdateSettings { } if root.active-tab == "identity" : IdentitySettings { own-avatar: root.own-avatar; has-avatar: root.has-avatar; diff --git a/src/ui/slint/settings/updates.slint b/src/ui/slint/settings/updates.slint new file mode 100644 index 0000000..4a9e5b1 --- /dev/null +++ b/src/ui/slint/settings/updates.slint @@ -0,0 +1,79 @@ +import { Theme, ActionButton } from "../theme.slint"; + +// State and actions of the updater. Rust fills the properties and handles the callbacks +// (src/ui/updater.rs); the panel below only shows them. +export global UpdateUi { + in-out property installed-version; + in-out property lnex-version; + in-out property state-text; + in-out property central-text; + in-out property auto-update: true; + in-out property busy; + in-out property can-download; + in-out property can-install; + in-out property can-rollback; + callback check(); + callback download(); + callback install(); + callback rollback(); + callback auto-update-changed(bool); +} + +component InfoRow inherits Rectangle { + in property label; + in property value; + height: 30px; + HorizontalLayout { + spacing: 12px; + Text { text: root.label; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 2px, 11px); width: 170px; vertical-alignment: center; } + Text { text: root.value; color: Theme.text-primary; font-size: Math.max(Theme.font-size - 2px, 11px); vertical-alignment: center; overflow: elide; } + } +} + +export component UpdateSettings inherits Rectangle { + VerticalLayout { + spacing: 0; + alignment: start; + Text { text: @tr("Version and updates"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; } + Text { text: @tr("Updates are signed and checked before they are installed. Your profile and data are not touched."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; } + Rectangle { height: 18px; } + InfoRow { label: @tr("Installed version"); value: UpdateUi.installed-version; } + InfoRow { label: @tr("Protocol version"); value: UpdateUi.lnex-version; } + if UpdateUi.central-text != "" : InfoRow { label: @tr("Latest on the server"); value: UpdateUi.central-text; } + Rectangle { height: 10px; } + Text { text: UpdateUi.state-text; color: Theme.text-primary; font-size: Math.max(Theme.font-size - 1px, 12px); wrap: word-wrap; accessible-role: text; accessible-label: UpdateUi.state-text; } + Rectangle { height: 14px; } + HorizontalLayout { + spacing: 10px; alignment: start; + ActionButton { text: @tr("Check for updates"); width: 170px; opacity: UpdateUi.busy ? 0.5 : 1.0; clicked => { UpdateUi.check(); } } + if UpdateUi.can-download : ActionButton { text: @tr("Download"); width: 120px; opacity: UpdateUi.busy ? 0.5 : 1.0; clicked => { UpdateUi.download(); } } + if UpdateUi.can-install : ActionButton { text: @tr("Install"); primary: true; width: 120px; opacity: UpdateUi.busy ? 0.5 : 1.0; clicked => { UpdateUi.install(); } } + } + Rectangle { height: 16px; } + Rectangle { + height: 46px; + accessible-role: checkbox; + accessible-label: @tr("Update automatically"); + accessible-checked: UpdateUi.auto-update; + HorizontalLayout { + spacing: 12px; + VerticalLayout { + alignment: center; spacing: 2px; horizontal-stretch: 1; + Text { text: @tr("Update automatically"); color: Theme.text-primary; font-size: Math.max(Theme.font-size - 2px, 11px); } + Text { text: @tr("Check and download in the background, install on the next start. Never during a voice call."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; } + } + ActionButton { + text: UpdateUi.auto-update ? "✓" : "○"; width: 34px; height: 30px; quiet: true; + clicked => { UpdateUi.auto-update = !UpdateUi.auto-update; UpdateUi.auto-update-changed(UpdateUi.auto-update); } + } + } + } + if UpdateUi.can-rollback : Rectangle { + height: 52px; + HorizontalLayout { + alignment: start; + ActionButton { text: @tr("Roll back to the previous version"); width: 280px; quiet: true; opacity: UpdateUi.busy ? 0.5 : 1.0; clicked => { UpdateUi.rollback(); } } + } + } + } +} diff --git a/src/ui/updater.rs b/src/ui/updater.rs new file mode 100644 index 0000000..590617f --- /dev/null +++ b/src/ui/updater.rs @@ -0,0 +1,214 @@ +//! Glue between the updater (`vnox_client::update`) and the settings panel. +//! +//! Slint owns no logic here: [`wire`] creates the manager, connects the panel callbacks and +//! refreshes the panel from the manager once a second. Installs are deferred while a voice +//! session is active. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Duration; + +use slint::ComponentHandle; +use vnox_client::update::settings::default_path; +use vnox_client::update::{Layout, UpdateConfig, UpdateManager, UpdatePhase}; + +use crate::AppState; +use crate::ui::i18n; +use crate::ui::slint::{MainWindow, UpdateUi}; +use crate::ui::state::VoiceUiState; + +/// How often the background check runs, in panel refresh ticks (one per second). +const AUTO_CHECK_TICKS: u64 = 6 * 60 * 60; + +/// Text shown for an updater phase. +pub fn phase_text(phase: &UpdatePhase) -> String { + let with = + |source: &str, version: &String| i18n::format(source, &[("version", version.clone())]); + match phase { + UpdatePhase::Idle => i18n::text("Not checked yet"), + UpdatePhase::Checking => i18n::text("Checking for updates..."), + UpdatePhase::UpToDate => i18n::text("You are up to date"), + UpdatePhase::Available { version } => i18n::format( + "Version {version} is available", + &[("version", version.clone())], + ), + UpdatePhase::Downloading { version } => with_downloading(version), + UpdatePhase::Ready { version } => i18n::format( + "Version {version} is downloaded and ready to install", + &[("version", version.clone())], + ), + UpdatePhase::InstallDeferred { version } => i18n::format( + "Version {version} will install when the voice session ends", + &[("version", version.clone())], + ), + UpdatePhase::Installing { version } => i18n::format( + "Installing version {version}", + &[("version", version.clone())], + ), + UpdatePhase::Installed { version } => i18n::format( + "Version {version} is installed. Restart Vnox to use it.", + &[("version", version.clone())], + ), + UpdatePhase::ManualInstallRequired { version } => { + with("Version {version} needs a manual reinstall", version) + } + UpdatePhase::Error(error) => { + i18n::format("Update failed: {error}", &[("error", error.clone())]) + } + } +} + +fn with_downloading(version: &str) -> String { + i18n::format( + "Downloading version {version}", + &[("version", version.to_string())], + ) +} + +/// Connects the updater to the settings panel. Keep the returned timer alive for as long as the +/// window lives. +pub fn wire(window: &MainWindow, state: &Rc>) -> slint::Timer { + let ui = window.global::(); + ui.set_installed_version(vnox_client::update::CLIENT_VERSION.into()); + ui.set_lnex_version(vnox_client::update::LNEX_PROTOCOL.into()); + + let layout = Layout::user_default(); + let manager: Option> = layout + .clone() + .map(|layout| UpdateManager::new(UpdateConfig::production(layout), None, default_path())); + let timer = slint::Timer::default(); + let Some(manager) = manager else { + ui.set_state_text(i18n::text("Not checked yet").into()); + return timer; + }; + + // A staged Windows binary is swapped in before the window opens; restart into it. + if let Some(layout) = &layout + && layout.apply_pending().unwrap_or(false) + && let Ok(exe) = std::env::current_exe() + && std::process::Command::new(exe) + .args(std::env::args_os().skip(1)) + .spawn() + .is_ok() + { + std::process::exit(0); + } + ui.set_auto_update(manager.auto_update()); + + let note: Rc> = Rc::default(); + { + let manager = manager.clone(); + tokio::spawn(async move { + manager.startup().await; + manager.auto_pass().await; + }); + } + { + let (manager, note) = (manager.clone(), note.clone()); + ui.on_check(move || { + note.borrow_mut().clear(); + let manager = manager.clone(); + tokio::spawn(async move { + let _ = manager.check().await; + }); + }); + } + { + let (manager, note) = (manager.clone(), note.clone()); + ui.on_download(move || { + note.borrow_mut().clear(); + let manager = manager.clone(); + tokio::spawn(async move { + let _ = manager.download().await; + }); + }); + } + { + let (manager, note) = (manager.clone(), note.clone()); + ui.on_install(move || { + note.borrow_mut().clear(); + let manager = manager.clone(); + tokio::spawn(async move { + let _ = manager.install().await; + }); + }); + } + { + let (manager, note) = (manager.clone(), note.clone()); + ui.on_rollback(move || { + *note.borrow_mut() = match manager.rollback() { + Ok(()) => i18n::text("Rolled back. Restart Vnox to use the previous version."), + Err(error) => { + i18n::format("Update failed: {error}", &[("error", error.to_string())]) + } + }; + }); + } + { + let (manager, note) = (manager.clone(), note.clone()); + ui.on_auto_update_changed(move |enabled| { + if let Err(error) = manager.set_auto_update(enabled) { + *note.borrow_mut() = i18n::format( + "Cannot save the update setting: {error}", + &[("error", error.to_string())], + ); + } + }); + } + + let weak = window.as_weak(); + let state = state.clone(); + let mut ticks: u64 = 0; + timer.start( + slint::TimerMode::Repeated, + Duration::from_secs(1), + move || { + ticks += 1; + let Some(window) = weak.upgrade() else { + return; + }; + let in_voice = { + let s = state.borrow(); + s.voice_channel.is_some() || matches!(s.ui.voice, VoiceUiState::Active { .. }) + }; + manager.set_voice_active(in_voice); + if !in_voice && manager.install_waiting() { + let manager = manager.clone(); + tokio::spawn(async move { + let _ = manager.run_deferred().await; + }); + } + if ticks.is_multiple_of(AUTO_CHECK_TICKS) { + let manager = manager.clone(); + tokio::spawn(async move { manager.auto_pass().await }); + } + let status = manager.status(); + let ui = window.global::(); + let note = note.borrow(); + ui.set_state_text(if note.is_empty() { + phase_text(&status.phase).into() + } else { + note.as_str().into() + }); + ui.set_central_text(status.central_latest.unwrap_or_default().into()); + ui.set_busy(matches!( + status.phase, + UpdatePhase::Checking + | UpdatePhase::Downloading { .. } + | UpdatePhase::Installing { .. } + )); + ui.set_can_download(matches!(status.phase, UpdatePhase::Available { .. })); + ui.set_can_install(matches!( + status.phase, + UpdatePhase::Ready { .. } | UpdatePhase::InstallDeferred { .. } + )); + ui.set_can_rollback( + layout + .as_ref() + .is_some_and(|layout| layout.state().previous.is_some()), + ); + }, + ); + timer +} diff --git a/translations/en/LC_MESSAGES/vnox-client.po b/translations/en/LC_MESSAGES/vnox-client.po index d9a49cf..e8642fa 100644 --- a/translations/en/LC_MESSAGES/vnox-client.po +++ b/translations/en/LC_MESSAGES/vnox-client.po @@ -100,6 +100,12 @@ msgstr "Change photo" msgid "Channel webhooks" msgstr "Channel webhooks" +msgid "Check and download in the background, install on the next start. Never during a voice call." +msgstr "Check and download in the background, install on the next start. Never during a voice call." + +msgid "Check for updates" +msgstr "Check for updates" + msgid "Choose a screen or window in the system dialog…" msgstr "Choose a screen or window in the system dialog…" @@ -199,6 +205,9 @@ msgstr "Disconnect from server" msgid "Dismiss" msgstr "Dismiss" +msgid "Download" +msgstr "Download" + msgid "Drag the photo and adjust the zoom." msgstr "Drag the photo and adjust the zoom." @@ -283,6 +292,12 @@ msgstr "Incoming message" msgid "Incoming requests" msgstr "Incoming requests" +msgid "Install" +msgstr "Install" + +msgid "Installed version" +msgstr "Installed version" + msgid "Integration name" msgstr "Integration name" @@ -310,6 +325,9 @@ msgstr "LOCAL PREVIEW" msgid "Language" msgstr "Language" +msgid "Latest on the server" +msgstr "Latest on the server" + msgid "Laugh" msgstr "Laugh" @@ -484,6 +502,9 @@ msgstr "Profile passphrase" msgid "Profile photo" msgstr "Profile photo" +msgid "Protocol version" +msgstr "Protocol version" + msgid "Push to talk" msgstr "Push to talk" @@ -535,6 +556,9 @@ msgstr "Revoke this webhook?" msgid "Revoke webhook" msgstr "Revoke webhook" +msgid "Roll back to the previous version" +msgstr "Roll back to the previous version" + msgid "Rotate" msgstr "Rotate" @@ -613,6 +637,9 @@ msgstr "Start broadcast" msgid "Starting broadcast…" msgstr "Starting broadcast…" +msgid "Stay current, safely." +msgstr "Stay current, safely." + msgid "Stop" msgstr "Stop" @@ -685,6 +712,15 @@ msgstr "Unmute broadcast" msgid "Unmute microphone" msgstr "Unmute microphone" +msgid "Update automatically" +msgstr "Update automatically" + +msgid "Updates" +msgstr "Updates" + +msgid "Updates are signed and checked before they are installed. Your profile and data are not touched." +msgstr "Updates are signed and checked before they are installed. Your profile and data are not touched." + msgid "Use photo" msgstr "Use photo" @@ -694,6 +730,9 @@ msgstr "Use this key to verify X-Vnox-Signature over the timestamp and raw reque msgid "Use your server's HTTPS webhook endpoint. Generic integrations send this secret in Authorization: Bearer; GitHub uses it as the webhook secret." msgstr "Use your server's HTTPS webhook endpoint. Generic integrations send this secret in Authorization: Bearer; GitHub uses it as the webhook secret." +msgid "Version and updates" +msgstr "Version and updates" + msgid "Video, application audio and your microphone stay separate." msgstr "Video, application audio and your microphone stay separate." diff --git a/translations/ru.json b/translations/ru.json index a06671c..1a5a496 100644 --- a/translations/ru.json +++ b/translations/ru.json @@ -401,5 +401,31 @@ "{n} участника", "{n} участников" ], - "Friend ID": "ID друга" + "Friend ID": "ID друга", + "Updates": "Обновления", + "Version and updates": "Версия и обновления", + "Stay current, safely.": "Всегда актуальная версия, безопасно.", + "Updates are signed and checked before they are installed. Your profile and data are not touched.": "Обновления подписаны и проверяются перед установкой. Профиль и данные не затрагиваются.", + "Installed version": "Установленная версия", + "Protocol version": "Версия протокола", + "Latest on the server": "Последняя на сервере", + "Check for updates": "Проверить обновления", + "Download": "Скачать", + "Install": "Установить", + "Update automatically": "Обновлять автоматически", + "Check and download in the background, install on the next start. Never during a voice call.": "Проверка и загрузка в фоне, установка при следующем запуске. Никогда во время голосового звонка.", + "Roll back to the previous version": "Вернуться к предыдущей версии", + "Not checked yet": "Ещё не проверялось", + "Checking for updates...": "Проверяем обновления...", + "You are up to date": "У вас последняя версия", + "Version {version} is available": "Доступна версия {version}", + "Downloading version {version}": "Скачиваем версию {version}", + "Version {version} is downloaded and ready to install": "Версия {version} скачана и готова к установке", + "Version {version} will install when the voice session ends": "Версия {version} установится после завершения голосового сеанса", + "Installing version {version}": "Устанавливаем версию {version}", + "Version {version} is installed. Restart Vnox to use it.": "Версия {version} установлена. Перезапустите Vnox, чтобы её использовать.", + "Version {version} needs a manual reinstall": "Версию {version} нужно установить вручную", + "Update failed: {error}": "Не удалось обновить: {error}", + "Rolled back. Restart Vnox to use the previous version.": "Откат выполнен. Перезапустите Vnox, чтобы использовать предыдущую версию.", + "Cannot save the update setting: {error}": "Не удалось сохранить настройку обновлений: {error}" } diff --git a/translations/ru/LC_MESSAGES/vnox-client.po b/translations/ru/LC_MESSAGES/vnox-client.po index d22255f..7d0a31e 100644 --- a/translations/ru/LC_MESSAGES/vnox-client.po +++ b/translations/ru/LC_MESSAGES/vnox-client.po @@ -101,6 +101,12 @@ msgstr "Изменить фото" msgid "Channel webhooks" msgstr "Вебхуки канала" +msgid "Check and download in the background, install on the next start. Never during a voice call." +msgstr "Проверка и загрузка в фоне, установка при следующем запуске. Никогда во время голосового звонка." + +msgid "Check for updates" +msgstr "Проверить обновления" + msgid "Choose a screen or window in the system dialog…" msgstr "Выбери экран или окно в системном диалоге…" @@ -200,6 +206,9 @@ msgstr "Отключиться от сервера" msgid "Dismiss" msgstr "Скрыть" +msgid "Download" +msgstr "Скачать" + msgid "Drag the photo and adjust the zoom." msgstr "Перетащи фото и выбери масштаб." @@ -284,6 +293,12 @@ msgstr "Входящие сообщения" msgid "Incoming requests" msgstr "Входящие запросы" +msgid "Install" +msgstr "Установить" + +msgid "Installed version" +msgstr "Установленная версия" + msgid "Integration name" msgstr "Название интеграции" @@ -311,6 +326,9 @@ msgstr "ЛОКАЛЬНЫЙ ПРОСМОТР" msgid "Language" msgstr "Язык" +msgid "Latest on the server" +msgstr "Последняя на сервере" + msgid "Laugh" msgstr "Смех" @@ -485,6 +503,9 @@ msgstr "Пароль профиля" msgid "Profile photo" msgstr "Фото профиля" +msgid "Protocol version" +msgstr "Версия протокола" + msgid "Push to talk" msgstr "Нажми и говори" @@ -536,6 +557,9 @@ msgstr "Отозвать этот вебхук?" msgid "Revoke webhook" msgstr "Отозвать вебхук" +msgid "Roll back to the previous version" +msgstr "Вернуться к предыдущей версии" + msgid "Rotate" msgstr "Заменить секрет" @@ -614,6 +638,9 @@ msgstr "Начать трансляцию" msgid "Starting broadcast…" msgstr "Запуск трансляции…" +msgid "Stay current, safely." +msgstr "Всегда актуальная версия, безопасно." + msgid "Stop" msgstr "Остановить" @@ -686,6 +713,15 @@ msgstr "Включить звук трансляции" msgid "Unmute microphone" msgstr "Включить микрофон" +msgid "Update automatically" +msgstr "Обновлять автоматически" + +msgid "Updates" +msgstr "Обновления" + +msgid "Updates are signed and checked before they are installed. Your profile and data are not touched." +msgstr "Обновления подписаны и проверяются перед установкой. Профиль и данные не затрагиваются." + msgid "Use photo" msgstr "Использовать фото" @@ -695,6 +731,9 @@ msgstr "Проверяйте X-Vnox-Signature этим ключом: подпи msgid "Use your server's HTTPS webhook endpoint. Generic integrations send this secret in Authorization: Bearer; GitHub uses it as the webhook secret." msgstr "Используйте HTTPS-адрес вебхуков вашего сервера. Обычные интеграции передают секрет в Authorization: Bearer; в GitHub укажите его как секрет вебхука." +msgid "Version and updates" +msgstr "Версия и обновления" + msgid "Video, application audio and your microphone stay separate." msgstr "Видео, звук приложения и микрофон передаются отдельно." From 23e725f89e84b2602735ffcdc047af9d565c665a Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sun, 1 Nov 2026 16:26:36 +0100 Subject: [PATCH 4/5] feat(client): embed the release public key --- src/update/keys.rs | 23 ++++++++++++----------- src/update/manager_tests.rs | 2 +- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/update/keys.rs b/src/update/keys.rs index 207fe7b..0f0be85 100644 --- a/src/update/keys.rs +++ b/src/update/keys.rs @@ -9,14 +9,14 @@ use super::UpdateError; /// Public half of the release signing key, embedded in the binary. /// -/// This is a PLACEHOLDER (all zeros). While it is unchanged the updater refuses to run -/// ([`is_placeholder`]), so a build without a real key can never accept an update. -/// -/// To replace it: generate an Ed25519 key pair offline, keep the secret key only in the CI -/// secret store (`manifest.json.sig` is produced from it), and paste the 32 byte public key -/// here. Rotating the key requires shipping a release signed with the old key that embeds the new -/// one. -pub const RELEASE_PUBLIC_KEY: [u8; 32] = [0u8; 32]; +/// The matching secret key lives only in the CI secret `VNOX_RELEASE_SIGNING_KEY` +/// (`manifest.json.sig` is produced from it). An all-zero value is treated as an unconfigured +/// placeholder and the updater refuses to run ([`is_placeholder`]). Rotating the key requires +/// shipping a release signed with the old key that embeds the new one. +pub const RELEASE_PUBLIC_KEY: [u8; 32] = [ + 0x7e, 0xd5, 0x38, 0x8c, 0xff, 0x33, 0xa2, 0xaf, 0x13, 0x52, 0xc2, 0x67, 0xef, 0x84, 0x2f, 0xe0, + 0xac, 0x37, 0x13, 0x42, 0xb7, 0x6b, 0xba, 0x4c, 0x0b, 0x7c, 0x41, 0xaf, 0x11, 0x4c, 0x95, 0x4c, +]; /// Second public key accepted during a key rotation, `None` otherwise. A release that embeds both /// keys is signed with the old one; the next releases are signed with the new one. @@ -159,16 +159,17 @@ mod tests { verify_any(&[old, public()], msg, &sign(msg)).unwrap(); assert!(verify_any(&[old], msg, &sign(msg)).is_err()); assert!(matches!( - verify_any(&[RELEASE_PUBLIC_KEY], msg, &sign(msg)), + verify_any(&[[0u8; 32]], msg, &sign(msg)), Err(UpdateError::NoReleaseKey) )); } #[test] fn placeholder_key_never_verifies() { - assert!(is_placeholder(&RELEASE_PUBLIC_KEY)); + assert!(is_placeholder(&[0u8; 32])); + assert!(!is_placeholder(&RELEASE_PUBLIC_KEY)); assert!(matches!( - verify(&RELEASE_PUBLIC_KEY, b"m", &sign(b"m")), + verify(&[0u8; 32], b"m", &sign(b"m")), Err(UpdateError::NoReleaseKey) )); } diff --git a/src/update/manager_tests.rs b/src/update/manager_tests.rs index 3a93303..ab3d2cb 100644 --- a/src/update/manager_tests.rs +++ b/src/update/manager_tests.rs @@ -181,7 +181,7 @@ async fn placeholder_key_disables_updates() { let fx = Fixture::new().await; fx.publish_good("0.2.0"); let mut cfg = fx.config(); - cfg.public_keys = keys::production_keys(); + cfg.public_keys = vec![[0u8; 32]]; let manager = UpdateManager::new(cfg, None, fx.dir.path().join("u.json")); assert!(matches!( manager.check().await, From ef10482cb1acfab914be875af2318d13a99c0744 Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sun, 1 Nov 2026 16:26:53 +0100 Subject: [PATCH 5/5] test(client): drop unused import --- src/update/manager_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/update/manager_tests.rs b/src/update/manager_tests.rs index ab3d2cb..8f08038 100644 --- a/src/update/manager_tests.rs +++ b/src/update/manager_tests.rs @@ -13,7 +13,7 @@ use super::layout::{Activation, Layout}; use super::manager::{InstallOutcome, UpdateConfig, UpdateManager, UpdatePhase}; use super::manifest::{Manifest, sample}; use super::test_support::FakeServer; -use super::{CLIENT_VERSION, LNEX_PROTOCOL, RELEASE_REPO, UpdateError, keys}; +use super::{CLIENT_VERSION, LNEX_PROTOCOL, RELEASE_REPO, UpdateError}; const API: &str = "/api/v1/repos/boba/VNOX-Client/releases/latest";