//! App updates (admin.spec.md, "Updates"): the app looks for a newer release on the project's //! Gitea, downloads its installer into the data folder checked against the release's SHA-256, and //! on request stops what runs and starts the installer silently (`/S /RUN`), which waits for the //! app to close, replaces it and starts it again. //! //! A release of this app is tagged `app-v` and carries `Jarvis-Setup-.exe` and //! `Jarvis-Setup-.exe.sha256` (what `app/shell/installer.sh` writes). Other releases of the //! repository (v1's `v1.x` tags) are not this app's and are skipped. use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex}; use serde::Serialize; use serde_json::{json, Value}; /// The project's releases (Gitea API, newest first). pub const SOURCE: &str = "https://git.tkrmagid.kr/api/v1/repos/tkrmagid/javis_bot/releases"; pub const TAG_PREFIX: &str = "app-v"; /// Where to look: `JARVIS_UPDATE_SOURCE` when set (a test server), else `SOURCE`. pub fn source() -> String { std::env::var("JARVIS_UPDATE_SOURCE").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| SOURCE.into()) } #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Release { pub version: String, pub notes: String, pub file: String, pub size: u64, #[serde(skip)] pub installer_url: String, #[serde(skip)] pub checksum_url: String, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub enum Phase { Idle, Checking, UpToDate, Available, Downloading, Ready, Failed, } /// Dotted numbers ("0.2.0"), padded to four parts so "1.0" equals "1.0.0"; anything else is `None`. fn version(s: &str) -> Option<[u64; 4]> { let parts: Vec = s.split('.').map(|p| p.parse().ok()).collect::>()?; if parts.is_empty() || parts.len() > 4 { return None; } let mut v = [0; 4]; v[..parts.len()].copy_from_slice(&parts); Some(v) } /// "https://host[:port]" of a URL: downloads come only from where the release list came from. fn origin(url: &str) -> Option<&str> { let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"))?; Some(&url[..url.len() - rest.len() + rest.find('/').unwrap_or(rest.len())]) } /// HTTPS only; plain HTTP only to this PC (a test server). fn allowed(url: &str) -> bool { url.starts_with("https://") || url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:") } /// The newest release of this app above `current` in a Gitea release list, if any. Drafts, /// prereleases, other tags and releases without both assets on `source`'s origin are skipped. pub fn pick(list: &Value, current: &str, source: &str) -> Result, String> { let list = list.as_array().ok_or("릴리스 목록을 읽지 못했습니다")?; let current = version(current).ok_or("현재 버전을 읽지 못했습니다")?; let home = origin(source); let mut best: Option<([u64; 4], Release)> = None; for r in list { if r["draft"] == json!(true) || r["prerelease"] == json!(true) { continue; } let Some(v) = r["tag_name"].as_str().and_then(|t| t.strip_prefix(TAG_PREFIX)) else { continue }; let Some(parsed) = version(v) else { continue }; if parsed <= current || best.as_ref().is_some_and(|(b, _)| parsed <= *b) { continue; } let file = format!("Jarvis-Setup-{v}.exe"); let asset = |name: &str| r["assets"].as_array()?.iter().find(|a| a["name"].as_str() == Some(name)).cloned(); let (Some(exe), Some(sum)) = (asset(&file), asset(&format!("{file}.sha256"))) else { continue }; let url = |a: &Value| a["browser_download_url"].as_str().map(str::to_owned) .filter(|u| allowed(u) && origin(u).is_some() && origin(u) == home); let (Some(installer_url), Some(checksum_url)) = (url(&exe), url(&sum)) else { continue }; best = Some((parsed, Release { version: v.into(), notes: r["body"].as_str().unwrap_or("").into(), file, size: exe["size"].as_u64().unwrap_or(0), installer_url, checksum_url })); } Ok(best.map(|(_, r)| r)) } /// The SHA-256 in a `.sha256` file (" "): 64 hex digits, for `file` when it names one. pub fn checksum(text: &str, file: &str) -> Result { let mut words = text.split_whitespace(); let hex = words.next().unwrap_or("").to_ascii_lowercase(); let named = words.next().map(|n| n.trim_start_matches('*')); if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) || named.is_some_and(|n| n != file) { return Err("릴리스의 SHA-256 파일이 올바르지 않습니다".into()); } Ok(hex) } struct State { phase: Phase, latest: Option, error: Option, done: u64, total: Option, sha256: Option, } /// The update state for the screens: checks, the download in the background, and the ready file. pub struct Updater { source: String, current: String, dir: PathBuf, state: Mutex, } impl Updater { /// `dir`: where installers are downloaded (the data folder's `cache/updates`). pub fn new(source: String, current: &str, dir: PathBuf) -> Arc { Arc::new(Self { source, current: current.into(), dir, state: Mutex::new(State { phase: Phase::Idle, latest: None, error: None, done: 0, total: None, sha256: None }) }) } pub fn status(&self) -> Value { let s = self.state.lock().unwrap(); json!({"current": self.current, "phase": s.phase, "latest": s.latest, "error": s.error, "done": s.done, "total": s.total}) } fn client() -> Result { reqwest::Client::builder().timeout(std::time::Duration::from_secs(30)).build().map_err(|e| e.to_string()) } async fn get_text(url: &str) -> Result { let r = Self::client()?.get(url).header("accept", "application/json").send().await .map_err(|e| format!("업데이트 서버에 연결하지 못했습니다: {e}"))?; if !r.status().is_success() { return Err(format!("업데이트 서버가 HTTP {}로 답했습니다", r.status())); } r.text().await.map_err(|e| format!("업데이트 정보를 받지 못했습니다: {e}")) } fn fail(&self, e: String) -> String { let mut s = self.state.lock().unwrap(); (s.phase, s.error) = (Phase::Failed, Some(e.clone())); crate::warn_log!("app", "update: {e}"); e } /// Look for a newer release; not while downloading. pub async fn check(&self) -> Result { let was = { let mut s = self.state.lock().unwrap(); if matches!(s.phase, Phase::Checking | Phase::Downloading) { return Ok(json!({"current": self.current, "phase": s.phase, "latest": s.latest})); } std::mem::replace(&mut s.phase, Phase::Checking) }; self.state.lock().unwrap().error = None; if !allowed(&self.source) { return Err(self.fail(format!("업데이트 주소는 https여야 합니다: {}", self.source))); } let url = format!("{}?limit=50", self.source); let found = match Self::get_text(&url).await .and_then(|t| serde_json::from_str::(&t).map_err(|_| "릴리스 목록을 읽지 못했습니다".into())) .and_then(|v| pick(&v, &self.current, &self.source)) { Ok(f) => f, Err(e) => return Err(self.fail(e)), }; let mut s = self.state.lock().unwrap(); // The release already downloaded stays ready. if was == Phase::Ready && found.is_some() && s.latest == found { s.phase = Phase::Ready; } else { s.phase = if found.is_some() { Phase::Available } else { Phase::UpToDate }; (s.done, s.total, s.sha256) = (0, None, None); } crate::info_log!("app", "update check: {}", found.as_ref().map_or("up to date".into(), |r| format!("{} available", r.version))); s.latest = found; Ok(json!({"current": self.current, "phase": s.phase, "latest": s.latest})) } /// Download the release found by `check` in the background (resumed where an earlier try stopped). pub fn download(self: &Arc) -> Result<(), String> { let release = { let mut s = self.state.lock().unwrap(); let release = match (s.phase, &s.latest) { (Phase::Available | Phase::Failed, Some(r)) => r.clone(), (Phase::Downloading | Phase::Ready, Some(_)) => return Ok(()), _ => return Err("먼저 새 버전을 확인해 주세요".into()), }; (s.phase, s.error, s.done, s.total) = (Phase::Downloading, None, 0, Some(release.size)); release }; let me = self.clone(); tokio::spawn(async move { let dest = me.dir.join(&release.file); let got = async { let sha = checksum(&Self::get_text(&release.checksum_url).await?, &release.file)?; std::fs::create_dir_all(&me.dir).map_err(|e| format!("업데이트 폴더를 만들지 못했습니다: {e}"))?; let never = AtomicBool::new(false); let progress = |done: u64, total: Option| { let mut s = me.state.lock().unwrap(); (s.done, s.total) = (done, total.or(s.total)); }; crate::download::download(&release.installer_url, &dest, &sha, &progress, &never).await .map_err(|e| format!("설치 파일을 받지 못했습니다: {e}"))?; Ok::<_, String>(sha) }.await; match got { Ok(sha) => { // Earlier installers and broken parts go; this one stays until it is installed. let keep = [release.file.clone(), format!("{}.part", release.file)]; for e in std::fs::read_dir(&me.dir).into_iter().flatten().flatten() { if !keep.iter().any(|k| e.file_name() == k.as_str()) { let _ = std::fs::remove_file(e.path()); } } let mut s = me.state.lock().unwrap(); (s.phase, s.sha256) = (Phase::Ready, Some(sha)); crate::info_log!("app", "update {} downloaded", release.version); } Err(e) => { me.fail(e); } } }); Ok(()) } /// The downloaded installer, checked again right before it is started. pub fn ready_installer(&self) -> Result { let s = self.state.lock().unwrap(); let (Phase::Ready, Some(r), Some(sha)) = (s.phase, &s.latest, &s.sha256) else { return Err("설치할 업데이트를 먼저 받아 주세요".into()); }; let path = self.dir.join(&r.file); if crate::download::sha256_file(&path).ok().as_deref() != Some(sha.as_str()) { return Err("받은 설치 파일이 바뀌었습니다. 다시 받아 주세요".into()); } Ok(path) } } /// Start the installer silently, as administrator (Windows asks), without waiting: it waits for /// this app to close, installs, and starts the app again. #[cfg(windows)] pub fn launch_installer(path: &Path) -> Result<(), String> { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::{GetLastError, ERROR_CANCELLED}; use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW}; use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; let wide = |s: &std::ffi::OsStr| s.encode_wide().chain(Some(0)).collect::>(); let (verb, file, params) = (wide("runas".as_ref()), wide(path.as_os_str()), wide("/S /RUN".as_ref())); // SAFETY: SHELLEXECUTEINFOW is plain data; all zero is its documented empty state. let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() }; info.cbSize = std::mem::size_of::() as u32; info.lpVerb = verb.as_ptr(); info.lpFile = file.as_ptr(); info.lpParameters = params.as_ptr(); info.nShow = SW_SHOWNORMAL; // SAFETY: `info` is filled as documented and its strings live through the call; no process // handle is asked for. if unsafe { ShellExecuteExW(&mut info) } == 0 { let e = unsafe { GetLastError() }; return Err(if e == ERROR_CANCELLED { "관리자 권한을 받지 못해 업데이트를 설치하지 않았습니다".into() } else { format!("설치 파일을 실행하지 못했습니다 ({e})") }); } Ok(()) } #[cfg(not(windows))] pub fn launch_installer(_path: &Path) -> Result<(), String> { Err("업데이트 설치는 Windows에서만 됩니다".into()) } #[cfg(test)] pub(crate) mod tests { use super::*; use crate::datadir::temp_dir; use sha2::{Digest, Sha256}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; fn both(v: &str) -> Vec { vec![format!("Jarvis-Setup-{v}.exe"), format!("Jarvis-Setup-{v}.exe.sha256")] } fn rel(tag: &str, base: &str, files: &[String]) -> Value { json!({"tag_name": tag, "draft": false, "prerelease": false, "body": format!("notes {tag}"), "assets": files.iter().map(|f| json!({"name": f, "size": 10, "browser_download_url": format!("{base}/download/{tag}/{f}")})).collect::>()}) } #[test] fn the_newest_release_of_this_app_above_the_current_version_is_picked() { let src = "https://git.example/api/v1/repos/o/r/releases"; let base = "https://git.example/o/r/releases"; let mut pre = rel("app-v0.4.0", base, &both("0.4.0")); pre["prerelease"] = json!(true); let list = json!([ rel("v1.10.0", base, &[]), // v1's release rel("app-v0.3.0", base, &both("0.3.0")[..1]), // no checksum pre, rel("app-v0.2.1", "https://elsewhere.example/o/r", &both("0.2.1")), // another server rel("app-v0.2.0", base, &both("0.2.0")), rel("app-v0.1.5", base, &both("0.1.5")), ]); let r = pick(&list, "0.1.0", src).unwrap().unwrap(); assert_eq!((r.version.as_str(), r.file.as_str(), r.notes.as_str()), ("0.2.0", "Jarvis-Setup-0.2.0.exe", "notes app-v0.2.0")); assert_eq!(r.installer_url, format!("{base}/download/app-v0.2.0/Jarvis-Setup-0.2.0.exe")); assert_eq!(pick(&list, "0.2.0", src).unwrap(), None, "nothing newer"); assert_eq!(pick(&list, "0.2", src).unwrap(), None, "0.2 is 0.2.0"); assert_eq!(pick(&json!([]), "0.1.0", src).unwrap(), None); assert!(pick(&json!({"message": "not found"}), "0.1.0", src).is_err()); // Plain http only to this PC. let http = rel("app-v0.2.0", "http://git.example/o/r", &both("0.2.0")); assert_eq!(pick(&json!([http]), "0.1.0", "http://git.example/api").unwrap(), None); } #[test] fn a_checksum_file_gives_its_hash_for_the_right_file_only() { let h = "AB".repeat(32); assert_eq!(checksum(&format!("{h} Jarvis-Setup-0.2.0.exe\n"), "Jarvis-Setup-0.2.0.exe").unwrap(), h.to_lowercase()); assert_eq!(checksum(&format!("{h} *Jarvis-Setup-0.2.0.exe"), "Jarvis-Setup-0.2.0.exe").unwrap(), h.to_lowercase()); assert_eq!(checksum(&h, "x.exe").unwrap(), h.to_lowercase()); assert!(checksum(&format!("{h} other.exe"), "Jarvis-Setup-0.2.0.exe").is_err()); assert!(checksum("abc Jarvis-Setup-0.2.0.exe", "Jarvis-Setup-0.2.0.exe").is_err()); assert!(checksum("", "x").is_err()); } /// A fake Gitea on this PC: the release list and the two assets of `app-v`. pub(crate) async fn gitea(version: &str, installer: Vec, sum: String) -> String { let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); let base = format!("http://{}", l.local_addr().unwrap()); let file = format!("Jarvis-Setup-{version}.exe"); let list = json!([rel("v1.10.0", &base, &[]), rel(&format!("app-v{version}"), &base, &both(version))]).to_string(); let sum_text = format!("{sum} {file}\n"); tokio::spawn(async move { while let Ok((mut s, _)) = l.accept().await { let mut buf = vec![0u8; 4096]; let n = s.read(&mut buf).await.unwrap_or(0); let path = String::from_utf8_lossy(&buf[..n]).split_whitespace().nth(1).unwrap_or("").to_owned(); let body: Vec = if path.starts_with("/releases") { list.clone().into_bytes() } else if path.ends_with(".sha256") { sum_text.clone().into_bytes() } else if path.ends_with(".exe") { installer.clone() } else { vec![] }; let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); let _ = s.write_all(head.as_bytes()).await; let _ = s.write_all(&body).await; } }); base } async fn settle(u: &Updater) -> Value { for _ in 0..200 { let s = u.status(); if s["phase"] != json!("downloading") { return s; } tokio::time::sleep(std::time::Duration::from_millis(20)).await; } panic!("the download did not end"); } #[tokio::test] async fn a_newer_release_is_found_downloaded_checked_and_handed_over() { let installer: Vec = (0..50_000u32).map(|i| (i % 253) as u8).collect(); let sum = format!("{:x}", Sha256::digest(&installer)); let base = gitea("0.2.0", installer.clone(), sum).await; let dir = temp_dir("upd1").join("cache/updates"); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("Jarvis-Setup-0.1.5.exe"), b"old").unwrap(); let u = Updater::new(format!("{base}/releases"), "0.1.0", dir.clone()); assert!(u.ready_installer().is_err(), "nothing to install yet"); assert!(u.download().is_err(), "check first"); let c = u.check().await.unwrap(); assert_eq!((c["phase"].clone(), c["latest"]["version"].clone()), (json!("available"), json!("0.2.0"))); u.download().unwrap(); let s = settle(&u).await; assert_eq!((s["phase"].clone(), s["done"].clone()), (json!("ready"), json!(installer.len()))); let path = u.ready_installer().unwrap(); assert_eq!(std::fs::read(&path).unwrap(), installer); assert!(!dir.join("Jarvis-Setup-0.1.5.exe").exists(), "the earlier installer is gone"); // Checking again keeps the ready file; a file changed after the download is refused. assert_eq!(u.check().await.unwrap()["phase"], json!("ready")); std::fs::write(&path, b"changed").unwrap(); assert!(u.ready_installer().unwrap_err().contains("바뀌었")); // The same version as the release: up to date. let same = Updater::new(format!("{base}/releases"), "0.2.0", temp_dir("upd1b")); assert_eq!(same.check().await.unwrap()["phase"], json!("upToDate")); } #[tokio::test] async fn a_download_that_does_not_match_its_checksum_is_not_offered_for_install() { let base = gitea("0.2.0", b"tampered".to_vec(), "0".repeat(64)).await; let dir = temp_dir("upd2"); let u = Updater::new(format!("{base}/releases"), "0.1.0", dir.clone()); u.check().await.unwrap(); u.download().unwrap(); let s = settle(&u).await; assert_eq!(s["phase"], json!("failed")); assert!(s["error"].as_str().unwrap().contains("damaged")); assert!(u.ready_installer().is_err()); assert!(!dir.join("Jarvis-Setup-0.2.0.exe").exists()); } #[tokio::test] async fn a_server_that_cannot_be_reached_or_is_not_https_fails_with_a_reason() { let u = Updater::new("http://127.0.0.1:9/releases".into(), "0.1.0", temp_dir("upd3")); assert!(u.check().await.unwrap_err().contains("연결하지 못했습니다")); assert_eq!(u.status()["phase"], json!("failed")); let plain = Updater::new("http://git.example/releases".into(), "0.1.0", temp_dir("upd4")); assert!(plain.check().await.unwrap_err().contains("https")); } #[test] fn the_app_and_its_installer_carry_the_same_version() { // installer.sh names the setup after the shell's version; the app compares its own; the // program file's version comes from the shell's Cargo.toml when tauri.conf.json sets none. let shell = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/shell/Cargo.toml")).unwrap(); let v = shell.lines().find_map(|l| l.strip_prefix("version = \"")).unwrap().trim_end_matches('"'); assert_eq!(v, env!("CARGO_PKG_VERSION")); let conf: Value = serde_json::from_str(&std::fs::read_to_string( concat!(env!("CARGO_MANIFEST_DIR"), "/shell/tauri.conf.json")).unwrap()).unwrap(); assert_eq!(conf.get("version"), None, "one version, in the Cargo.toml files"); } }