Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

feat(updater): implement production in-app self-update engine and multi-platform lifecycle

Samir Hossains1e498e563cb9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3896e14..b02770e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,14 @@
## [Unreleased]
### Added
+- **Production-Grade In-App Self-Update Engine**:
+ - Implemented modular self-update architecture (`src/updater/` with `check.rs`, `artifact.rs`, `download.rs`, `verify.rs`, `extract.rs`, and `apply.rs`).
+ - Added streaming SHA-256 integrity verification validating exact hash matching against release `SHA256SUMS`.
+ - Added hardened archive extraction for `.tar.gz` and `.zip` with strict path traversal protection against `..` components and absolute root paths.
+ - Added multi-platform installation strategies: atomic binary replacement with `.old` backup and automatic rollback on Unix/Linux/macOS/Termux, detached helper process on Windows, and Homebrew prefix detection guiding users to `brew upgrade moviebox-tui`.
+ - Added active work protection deferring self-update when active video playback or background downloads are running.
+ - Connected `[u]` shortcut and `[u] Update Now` button in the existing Update Available modal, preserving visual styling, animations, and dismissal model.
+ - Added safe terminal state restoration (`disable_raw_mode`, `LeaveAlternateScreen`, `DisableMouseCapture`, `ShowCursor`) before process exec/restart.
- **Update System Concurrency & Platform Compatibility Architecture**:
- Added single-flight guard (`is_checking_updates`) ensuring manual (`/update`) and automatic startup checks never spawn duplicate concurrent network requests.
- Added shared geometry calculation (`UpdateModalLayout`, `update_modal_layout`) guaranteeing 1:1 synchronization between popup rendering and mouse hit testing.
diff --git a/Cargo.lock b/Cargo.lock
index cfc4b19..0206ee5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -47,6 +47,15 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+dependencies = [
+ "derive_arbitrary",
+]
+
[[package]]
name = "atomic"
version = "0.6.1"
@@ -478,6 +487,17 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+[[package]]
+name = "derive_arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -651,6 +671,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "filetime"
+version = "0.2.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
+dependencies = [
+ "cfg-if",
+ "libc",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.10"
@@ -1194,6 +1224,16 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
[[package]]
name = "indoc"
version = "2.0.7"
@@ -1479,6 +1519,7 @@ dependencies = [
"base64 0.23.1",
"crossterm",
"dirs",
+ "flate2",
"flexi_logger",
"futures",
"hmac",
@@ -1498,11 +1539,15 @@ dependencies = [
"semver",
"serde",
"serde_json",
+ "sha2",
+ "tar",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"unicode-segmentation",
"unicode-width",
"url",
+ "zip",
]
[[package]]
@@ -2786,6 +2831,30 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
+[[package]]
+name = "tar"
+version = "0.4.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
+dependencies = [
+ "filetime",
+ "libc",
+ "xattr",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix 1.1.4",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "tendril"
version = "0.5.1"
@@ -3627,6 +3696,16 @@ dependencies = [
"tap",
]
+[[package]]
+name = "xattr"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
+dependencies = [
+ "libc",
+ "rustix 1.1.4",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -3730,12 +3809,41 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "zip"
+version = "2.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "crossbeam-utils",
+ "displaydoc",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "thiserror 2.0.20",
+ "zopfli",
+]
+
[[package]]
name = "zmij"
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 = "zune-core"
version = "0.5.3"
diff --git a/Cargo.toml b/Cargo.toml
index 8a362ac..2d89b8e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -46,6 +46,11 @@ percent-encoding = "2.3.2"
log = "0.4.33"
flexi_logger = "0.31.10"
reqwest = { version = "0.12.12", default-features = false, features = ["json", "rustls-tls-webpki-roots"] }
+sha2 = "0.10.8"
+flate2 = "1.0.35"
+tar = "0.4.44"
+zip = { version = "2.2.2", default-features = false, features = ["deflate"] }
+tempfile = "3.17.1"
[lib]
name = "moviebox_tui"
diff --git a/docs/known-issues.md b/docs/known-issues.md
index 60594db..87f3b7b 100644
--- a/docs/known-issues.md
+++ b/docs/known-issues.md
@@ -26,6 +26,6 @@ Tracked here so future work and issue reports reference the same facts.
## Verification
-- Automated testing is enforced via `cargo test --locked` covering 98 unit and integration tests across 13 test suites (see [`docs/testing.md`](testing.md)).
+- Automated testing is enforced via `cargo test --locked` covering 124 unit and integration tests across 15 test suites (see [`docs/testing.md`](testing.md)).
- Static correctness is enforced by strict compiler type checking, the lint gate (`cargo clippy --all-targets --all-features -- -D warnings`), formatting (`cargo fmt --check`), dependency vulnerability scanning (`cargo audit`), and packaging verification (`cargo package --locked`).
- Runtime and platform-specific behavior (terminal resize, focus handling, external player launch, and Termux chooser) are verified through the release checklist in [`release-checklist.md`](release-checklist.md).
diff --git a/docs/testing.md b/docs/testing.md
index c9fde54..0df4445 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -29,6 +29,8 @@ MovieBox-TUI/
├── content_pipeline.rs # Content/metadata pipeline, stale request isolation, & cache keys
├── tui_acceptance.rs # Headless TUI rendering, theme rendering, and resize matrix
├── update_lifecycle.rs # Update single-flight checks, modal hitboxes, & platform assets
+ ├── real_acceptance.rs # Real artifact downloads, live SHA256 integrity, & version verify
+ ├── version_upgrade_e2e.rs # Genuine 0.1.12 -> 0.1.13 end-to-end upgrade execution
└── addons_manifest.rs # Addon manifest deserialization & catalog checks
```
@@ -42,7 +44,9 @@ Inline unit tests live inside `#[cfg(test)] mod tests` blocks within their respe
### B. Subsystem Integration Tests (`tests/*.rs`)
Integration tests live in the `tests/` directory and test externally observable behaviors without mocking internal types:
-- **`update_lifecycle.rs`**: Validates update single-flight concurrency barriers, error recovery on network failure, 1:1 mouse hit-test synchronization with rendered popup geometry, and deterministic platform asset filtering.
+- **`version_upgrade_e2e.rs`**: Validates genuine end-to-end version upgrade from `0.1.12` to `0.1.13`, verifying discovery, live HTTP asset and checksum download, SHA-256 integrity check, staging, atomic replacement, and verification that the newly installed binary returns `moviebox-tui 0.1.13` (where old version != new version).
+- **`update_lifecycle.rs`**: Validates update single-flight concurrency barriers, error recovery on network failure, 1:1 mouse hit-test synchronization with rendered popup geometry, deterministic platform asset filtering, checksum integrity verification (valid, mismatch, missing, multi-format), archive extraction with strict path traversal rejection (`..`), active work protection (playback and download guards), environment detection (Homebrew, ReadOnly, DirectReplace), and safe atomic binary replacement/rollback.
+- **`real_acceptance.rs`**: Validates real-world GitHub release artifact downloads, live streaming SHA-256 verification against upstream `SHA256SUMS`, actual archive extraction to non-empty executable binaries (`chmod 0755`), real `--version` validation of extracted binaries, Windows helper script batch syntax, and data preservation across updates.
- **`content_pipeline.rs`**: Validates search result identity, ambiguous title isolation, stale metadata response protection (`request_id` validation), cache key dimensional isolation, addon metadata mapping & partial degradation, search failure vs empty result status distinction, and mode-switch stale response isolation.
- **`error_handling.rs`**: Validates active player session lifecycle, playback debounce guards, search failure cleanup, addon manifest error toasts, stream and download resolution failure notifications, malformed M3U recovery, and URL scheme rejection.
- **`tui_acceptance.rs`**: Validates headless TUI rendering, all theme palettes, end-to-end user journeys (search, details, navigation, mode switching), mouse click and scroll interactions, modal dismissals, and terminal resize matrices across 8 standard and boundary dimensions without panics.
diff --git a/src/tui/action.rs b/src/tui/action.rs
index f253152..e126466 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -123,6 +123,9 @@ pub enum Action {
SearchPosterLoaded(String, Option<std::sync::Arc<image::DynamicImage>>),
UpdateAvailable(Result<Option<(String, String)>, String>),
CheckForUpdates,
+ StartSelfUpdate,
+ SelfUpdateProgress(String),
+ SelfUpdateComplete(Result<crate::updater::SelfUpdateOutcome, String>),
SetStatus(String),
Refresh,
ClearCache,
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 4941fd6..7eb8982 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -77,8 +77,8 @@ impl App {
if let Some((version, _)) = &self.state.update_available {
match key.code {
- KeyCode::Enter | KeyCode::Esc => {
- self.state.update_available = None;
+ KeyCode::Char('u') | KeyCode::Char('U') => {
+ self.action_sender.send(Action::StartSelfUpdate).ok();
}
KeyCode::Char('o') | KeyCode::Char('O') => {
let url = format!(
@@ -88,6 +88,9 @@ impl App {
let _ = open::that(&url);
self.state.update_available = None;
}
+ KeyCode::Esc => {
+ self.state.update_available = None;
+ }
_ => {}
}
return None;
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index f22da10..e2ac482 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -95,7 +95,9 @@ impl App {
.contains(ratatui::layout::Position::new(col, row))
{
if row == layout.button_row_y {
- if col < layout.open_button_midpoint_x {
+ if col < layout.update_btn_end_x {
+ self.action_sender.send(Action::StartSelfUpdate).ok();
+ } else if col < layout.open_btn_end_x {
let url =
format!("https://github.com/mesamirh/MovieBox-Tui/releases/tag/v{ver}");
let _ = open::that(&url);
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index 4660efb..8b28fe0 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -152,7 +152,10 @@ impl App {
| Action::ShowBrowseMenu
| Action::SetStatus(..)
| Action::CheckForUpdates
- | Action::UpdateAvailable(..) => {
+ | Action::UpdateAvailable(..)
+ | Action::StartSelfUpdate
+ | Action::SelfUpdateProgress(..)
+ | Action::SelfUpdateComplete(..) => {
self.handle_system(action).await;
}
@@ -501,9 +504,11 @@ impl App {
text.push(Line::from(""));
text.push(
Line::from(vec![
+ Span::styled("[u]", self.theme.shortcut),
+ Span::styled(" Update Now ", self.theme.text),
Span::styled("[o]", self.theme.shortcut),
Span::styled(" Open Release Page ", self.theme.text),
- Span::styled("[Esc / Enter]", self.theme.shortcut),
+ Span::styled("[Esc]", self.theme.shortcut),
Span::styled(" Dismiss", self.theme.text),
])
.alignment(Alignment::Center),
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 13e81aa..6e28585 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -346,7 +346,7 @@ impl App {
self.state.is_checking_updates = true;
let update_sender = self.action_sender.clone();
tokio::spawn(async move {
- let task = tokio::spawn(crate::tui::updater::check(env!("CARGO_PKG_VERSION")));
+ let task = tokio::spawn(crate::updater::check(env!("CARGO_PKG_VERSION")));
let result = match task.await {
Ok(res) => res,
Err(join_err) => Err(format!("update check task error: {join_err}")),
@@ -400,6 +400,114 @@ impl App {
}
}
}
+
+ Action::StartSelfUpdate => {
+ if self.state.is_updating {
+ return None;
+ }
+ if self.state.download_progress.is_some() {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Update Deferred",
+ "Cannot perform in-app update while a download is active.",
+ );
+ return None;
+ }
+ if self.state.is_playing {
+ self.state.notify(
+ NotificationKind::Warning,
+ "Update Deferred",
+ "Cannot perform in-app update while playback is active.",
+ );
+ return None;
+ }
+
+ self.state.is_updating = true;
+ self.state.update_available = None;
+ self.state
+ .set_status("Starting self-update...".to_string(), 180);
+ self.state.notify(
+ NotificationKind::Info,
+ "Self-Update",
+ "Downloading release artifact and verifying checksum...",
+ );
+
+ let update_sender = self.action_sender.clone();
+ tokio::spawn(async move {
+ let release =
+ match crate::updater::check_release(env!("CARGO_PKG_VERSION")).await {
+ Ok(Some(r)) => r,
+ Ok(None) => {
+ update_sender
+ .send(Action::SelfUpdateComplete(Err(
+ "Already on the latest version.".to_string(),
+ )))
+ .ok();
+ return;
+ }
+ Err(e) => {
+ update_sender.send(Action::SelfUpdateComplete(Err(e))).ok();
+ return;
+ }
+ };
+
+ let (progress_tx, mut progress_rx) =
+ tokio::sync::mpsc::unbounded_channel::<String>();
+ let fwd_sender = update_sender.clone();
+ tokio::spawn(async move {
+ while let Some(msg) = progress_rx.recv().await {
+ fwd_sender.send(Action::SelfUpdateProgress(msg)).ok();
+ }
+ });
+
+ let outcome =
+ crate::updater::perform_self_update(&release, Some(&progress_tx)).await;
+ update_sender.send(Action::SelfUpdateComplete(outcome)).ok();
+ });
+ }
+
+ Action::SelfUpdateProgress(msg) => {
+ self.state.set_status(msg, 180);
+ }
+
+ Action::SelfUpdateComplete(result) => {
+ self.state.is_updating = false;
+ match result {
+ Ok(crate::updater::SelfUpdateOutcome::Success) => {
+ self.state
+ .set_status("Update successful! Restarting...".to_string(), 180);
+ self.state.notify(
+ NotificationKind::Success,
+ "Update Installed",
+ "MovieBox-Tui was updated successfully. Restarting process...",
+ );
+
+ crossterm::terminal::disable_raw_mode().ok();
+ crossterm::execute!(
+ std::io::stdout(),
+ crossterm::terminal::LeaveAlternateScreen,
+ crossterm::event::DisableMouseCapture,
+ crossterm::cursor::Show
+ )
+ .ok();
+
+ if let Ok(exe_path) = std::env::current_exe() {
+ let _ = crate::updater::restart_process(&exe_path);
+ }
+ std::process::exit(0);
+ }
+ Ok(crate::updater::SelfUpdateOutcome::RequiresManualUpgrade(msg)) => {
+ self.state.set_status(msg.clone(), 300);
+ self.state
+ .notify(NotificationKind::Warning, "Manual Update Required", msg);
+ }
+ Err(err) => {
+ self.state.set_status(format!("Update failed: {err}"), 240);
+ self.state
+ .notify(NotificationKind::Error, "Update Failed", err);
+ }
+ }
+ }
_ => return None,
}
None
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index 450b570..11b7e00 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -293,19 +293,16 @@ mod tests {
..Default::default()
};
- // 1. Streaming Mode
state.is_addon_mode = false;
state.is_tv_mode = false;
let stream_sug = SlashCommand::suggest(&state, "/download-dir");
assert!(stream_sug.contains(&"/download-dir reset".to_string()));
- // 2. Addon Mode
state.is_addon_mode = true;
state.is_tv_mode = false;
let addon_sug = SlashCommand::suggest(&state, "/download-dir");
assert!(addon_sug.contains(&"/download-dir reset".to_string()));
- // 3. TV Mode
state.is_addon_mode = false;
state.is_tv_mode = true;
let tv_sug = SlashCommand::suggest(&state, "/download-dir");
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index 8c7452a..b08c3be 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -374,6 +374,8 @@ pub struct UpdateModalLayout {
pub display_count: usize,
pub has_more: bool,
pub button_row_y: u16,
+ pub update_btn_end_x: u16,
+ pub open_btn_end_x: u16,
pub open_button_midpoint_x: u16,
}
@@ -402,6 +404,8 @@ pub fn update_modal_layout(area: Rect, notes: &str) -> UpdateModalLayout {
let popup_area = centered(area, desired_w, desired_h, min_w, max_w);
let button_row_y = popup_area.y + popup_area.height.saturating_sub(2);
+ let update_btn_end_x = popup_area.x + popup_area.width / 3;
+ let open_btn_end_x = popup_area.x + (popup_area.width * 2) / 3;
let open_button_midpoint_x = popup_area.x + popup_area.width / 2;
UpdateModalLayout {
@@ -409,6 +413,8 @@ pub fn update_modal_layout(area: Rect, notes: &str) -> UpdateModalLayout {
display_count,
has_more,
button_row_y,
+ update_btn_end_x,
+ open_btn_end_x,
open_button_midpoint_x,
}
}
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 5c89433..05011fe 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -138,6 +138,8 @@ pub struct AppState {
pub last_update_check: u64,
pub manual_update_check: bool,
pub is_checking_updates: bool,
+ pub is_updating: bool,
+ pub update_release: Option<crate::updater::Release>,
pub download_progress: Option<f64>,
pub download_status: Option<String>,
@@ -281,6 +283,8 @@ impl Default for AppState {
last_update_check: 0,
manual_update_check: false,
is_checking_updates: false,
+ is_updating: false,
+ update_release: None,
download_progress: None,
download_status: None,
diff --git a/src/updater/apply.rs b/src/updater/apply.rs
new file mode 100644
index 0000000..f79da29
--- /dev/null
+++ b/src/updater/apply.rs
@@ -0,0 +1,193 @@
+use std::path::Path;
+use std::process::Command;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SelfUpdateOutcome {
+ Success,
+ RequiresManualUpgrade(String),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InstallationEnvironment {
+ DirectReplace,
+ Homebrew,
+ ReadOnly,
+ WindowsHelper,
+}
+
+pub fn detect_environment(exe_path: &Path) -> InstallationEnvironment {
+ if is_homebrew_managed(exe_path) {
+ return InstallationEnvironment::Homebrew;
+ }
+
+ if cfg!(windows) {
+ return InstallationEnvironment::WindowsHelper;
+ }
+
+ if !is_writable(exe_path) {
+ return InstallationEnvironment::ReadOnly;
+ }
+
+ InstallationEnvironment::DirectReplace
+}
+
+pub fn is_homebrew_managed(exe_path: &Path) -> bool {
+ let check_path = |p: &Path| -> bool {
+ let s = p.to_string_lossy();
+ s.contains("/Cellar/")
+ || s.contains("/opt/homebrew/")
+ || s.contains("/usr/local/Cellar/")
+ || s.contains("/home/linuxbrew/.linuxbrew/Cellar/")
+ };
+
+ if check_path(exe_path) {
+ return true;
+ }
+
+ if let Ok(canonical) = exe_path.canonicalize() {
+ if check_path(&canonical) {
+ return true;
+ }
+ }
+
+ false
+}
+
+pub fn is_writable(exe_path: &Path) -> bool {
+ let parent = match exe_path.parent() {
+ Some(p) => p,
+ None => return false,
+ };
+
+ let test_file = parent.join(format!(".moviebox_write_test_{}", std::process::id()));
+ match std::fs::File::create(&test_file) {
+ Ok(_) => {
+ let _ = std::fs::remove_file(test_file);
+ true
+ }
+ Err(_) => false,
+ }
+}
+
+pub fn apply_staged_binary(
+ staged_path: &Path,
+ current_exe: &Path,
+) -> Result<SelfUpdateOutcome, String> {
+ let env = detect_environment(current_exe);
+
+ match env {
+ InstallationEnvironment::Homebrew => {
+ Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "This installation is managed by Homebrew. Run: brew upgrade moviebox-tui".to_string(),
+ ))
+ }
+ InstallationEnvironment::ReadOnly => {
+ Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
+ ))
+ }
+ InstallationEnvironment::DirectReplace => {
+ replace_binary_with_backup(staged_path, current_exe)?;
+ Ok(SelfUpdateOutcome::Success)
+ }
+ InstallationEnvironment::WindowsHelper => {
+ spawn_windows_helper(staged_path, current_exe)?;
+ Ok(SelfUpdateOutcome::Success)
+ }
+ }
+}
+
+fn replace_binary_with_backup(staged_path: &Path, current_exe: &Path) -> Result<(), String> {
+ let backup_path = current_exe.with_extension("old");
+ if backup_path.exists() {
+ let _ = std::fs::remove_file(&backup_path);
+ }
+
+ if let Err(e) = std::fs::rename(current_exe, &backup_path) {
+ if let Err(copy_err) = std::fs::copy(current_exe, &backup_path) {
+ return Err(format!(
+ "failed to backup existing binary: {e} (copy: {copy_err})"
+ ));
+ }
+ }
+
+ let install_result = match std::fs::rename(staged_path, current_exe) {
+ Ok(_) => Ok(()),
+ Err(_) => match std::fs::copy(staged_path, current_exe) {
+ Ok(_) => {
+ let _ = std::fs::remove_file(staged_path);
+ Ok(())
+ }
+ Err(copy_err) => Err(format!("failed to replace binary: {copy_err}")),
+ },
+ };
+
+ if let Err(err) = install_result {
+ if backup_path.exists() {
+ let _ = std::fs::rename(&backup_path, current_exe);
+ }
+ return Err(err);
+ }
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ if let Ok(metadata) = std::fs::metadata(current_exe) {
+ let mut perms = metadata.permissions();
+ perms.set_mode(0o755);
+ let _ = std::fs::set_permissions(current_exe, perms);
+ }
+ }
+
+ if backup_path.exists() {
+ let _ = std::fs::remove_file(&backup_path);
+ }
+
+ Ok(())
+}
+
+fn spawn_windows_helper(staged_path: &Path, current_exe: &Path) -> Result<(), String> {
+ let helper_path = current_exe.with_file_name("moviebox_update_helper.bat");
+ let pid = std::process::id();
+
+ let script_content = format!(
+ "@echo off\r\n\
+ :wait_loop\r\n\
+ tasklist /FI \"PID eq {pid}\" 2>NUL | find \"{pid}\" >NUL\r\n\
+ if %ERRORLEVEL% == 0 (\r\n\
+ timeout /t 1 /nobreak >NUL\r\n\
+ goto wait_loop\r\n\
+ )\r\n\
+ move /y \"{}\" \"{}\"\r\n\
+ start \"\" \"{}\"\r\n\
+ del \"%~f0\"\r\n",
+ staged_path.to_string_lossy(),
+ current_exe.to_string_lossy(),
+ current_exe.to_string_lossy()
+ );
+
+ std::fs::write(&helper_path, script_content)
+ .map_err(|e| format!("failed to write Windows update helper: {e}"))?;
+
+ Command::new("cmd.exe")
+ .args(["/C", &helper_path.to_string_lossy()])
+ .spawn()
+ .map_err(|e| format!("failed to spawn Windows update helper: {e}"))?;
+
+ Ok(())
+}
+
+pub fn restart_process(exe_path: &Path) -> Result<(), String> {
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let err = Command::new(exe_path).args(&args).exec();
+ Err(format!("failed to exec restarted process: {err}"))
+ }
+
+ #[cfg(windows)]
+ {
+ Ok(())
+ }
+}
diff --git a/src/updater/artifact.rs b/src/updater/artifact.rs
new file mode 100644
index 0000000..8c3759c
--- /dev/null
+++ b/src/updater/artifact.rs
@@ -0,0 +1,96 @@
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub struct ReleaseAsset {
+ pub name: String,
+ pub download_url: String,
+ pub size: Option<u64>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub struct Release {
+ pub version: String,
+ pub tag_name: String,
+ pub notes: String,
+ pub assets: Vec<ReleaseAsset>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TargetPlatform {
+ MacosUniversal,
+ LinuxX64,
+ LinuxArm64,
+ WindowsX64,
+ WindowsArm64,
+}
+
+impl TargetPlatform {
+ pub fn current() -> Option<Self> {
+ Self::detect(
+ std::env::consts::OS,
+ std::env::consts::ARCH,
+ is_termux_environment(),
+ )
+ }
+
+ pub fn detect(os: &str, arch: &str, is_termux: bool) -> Option<Self> {
+ if is_termux {
+ if arch == "aarch64" || arch == "arm64" {
+ return Some(Self::LinuxArm64);
+ } else {
+ return None;
+ }
+ }
+
+ match os {
+ "macos" | "darwin" => Some(Self::MacosUniversal),
+ "linux" => match arch {
+ "x86_64" | "x86-64" | "x64" | "amd64" => Some(Self::LinuxX64),
+ "aarch64" | "arm64" => Some(Self::LinuxArm64),
+ _ => None,
+ },
+ "windows" => match arch {
+ "x86_64" | "x86-64" | "x64" | "amd64" => Some(Self::WindowsX64),
+ "aarch64" | "arm64" => Some(Self::WindowsArm64),
+ _ => None,
+ },
+ _ => None,
+ }
+ }
+
+ pub fn expected_asset_name(self) -> &'static str {
+ match self {
+ Self::MacosUniversal => "MovieBox_macOS_Universal.tar.gz",
+ Self::LinuxX64 => "MovieBox_Linux_x64.tar.gz",
+ Self::LinuxArm64 => "MovieBox_Linux_arm64.tar.gz",
+ Self::WindowsX64 => "MovieBox_Windows_x64.zip",
+ Self::WindowsArm64 => "MovieBox_Windows_arm64.zip",
+ }
+ }
+
+ pub fn expected_binary_name(self) -> &'static str {
+ match self {
+ Self::WindowsX64 | Self::WindowsArm64 => "moviebox-tui.exe",
+ _ => "moviebox-tui",
+ }
+ }
+}
+
+pub fn is_termux_environment() -> bool {
+ std::env::var("PREFIX").is_ok_and(|p| p.contains("com.termux"))
+}
+
+impl Release {
+ pub fn find_compatible_asset(&self, platform: TargetPlatform) -> Option<&ReleaseAsset> {
+ let expected = platform.expected_asset_name();
+ self.assets.iter().find(|a| a.name == expected)
+ }
+
+ pub fn find_checksum_asset(&self) -> Option<&ReleaseAsset> {
+ self.assets.iter().find(|a| a.name == "SHA256SUMS")
+ }
+
+ pub fn is_compatible_with_current_platform(&self) -> bool {
+ TargetPlatform::current()
+ .and_then(|p| self.find_compatible_asset(p))
+ .is_some()
+ }
+}
diff --git a/src/updater/check.rs b/src/updater/check.rs
new file mode 100644
index 0000000..d7970f0
--- /dev/null
+++ b/src/updater/check.rs
@@ -0,0 +1,118 @@
+use super::artifact::{Release, ReleaseAsset};
+
+const OWNER: &str = "mesamirh";
+const REPOSITORY: &str = "MovieBox-Tui";
+
+pub async fn check_release(current: &str) -> Result<Option<Release>, String> {
+ let release = match fetch_release().await {
+ Ok(release) => release,
+ Err(error) => {
+ log::warn!("update check via API failed ({error}); falling back to release page");
+ let tag = fetch_latest_tag().await?;
+ log::info!("resolved latest release via redirect: {tag}");
+ Release {
+ version: tag.trim_start_matches('v').to_string(),
+ tag_name: tag,
+ notes: String::new(),
+ assets: Vec::new(),
+ }
+ }
+ };
+
+ if !is_newer(current, &release.version) {
+ return Ok(None);
+ }
+
+ Ok(Some(release))
+}
+
+pub async fn check(current: &str) -> Result<Option<(String, String)>, String> {
+ let release = check_release(current).await?;
+ Ok(release.map(|r| (r.version, r.notes)))
+}
+
+pub fn is_newer(current: &str, other: &str) -> bool {
+ let parse = |v: &str| semver::Version::parse(v.trim_start_matches('v'));
+ match (parse(current), parse(other)) {
+ (Ok(cur), Ok(o)) => o > cur,
+ _ => other != current,
+ }
+}
+
+async fn fetch_release() -> Result<Release, String> {
+ let url = format!("https://api.github.com/repos/{OWNER}/{REPOSITORY}/releases/latest");
+ let client = http_client()?;
+
+ let resp = client
+ .get(&url)
+ .send()
+ .await
+ .map_err(|e| format!("GitHub request failed: {e}"))?;
+ let status = resp.status();
+ if status == reqwest::StatusCode::FORBIDDEN || status == reqwest::StatusCode::TOO_MANY_REQUESTS
+ {
+ return Err(format!("GitHub API rate limited ({status})"));
+ }
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!("GitHub API {status}: {body}"));
+ }
+
+ let item: serde_json::Value = resp.json().await.map_err(|e| format!("bad JSON: {e}"))?;
+ let tag = item["tag_name"].as_str().ok_or("missing tag_name")?;
+ let notes = item["body"].as_str().unwrap_or("").to_string();
+ let assets = if let Some(arr) = item["assets"].as_array() {
+ arr.iter()
+ .filter_map(|a| {
+ let name = a["name"].as_str()?.to_string();
+ let download_url = a["browser_download_url"].as_str()?.to_string();
+ let size = a["size"].as_u64();
+ Some(ReleaseAsset {
+ name,
+ download_url,
+ size,
+ })
+ })
+ .collect()
+ } else {
+ Vec::new()
+ };
+
+ Ok(Release {
+ version: tag.trim_start_matches('v').to_string(),
+ tag_name: tag.to_string(),
+ notes,
+ assets,
+ })
+}
+
+async fn fetch_latest_tag() -> Result<String, String> {
+ let url = format!("https://github.com/{OWNER}/{REPOSITORY}/releases/latest");
+ let client = http_client()?;
+
+ let resp = client
+ .get(&url)
+ .send()
+ .await
+ .map_err(|e| format!("GitHub release page failed: {e}"))?;
+ let status = resp.status();
+ if !status.is_success() {
+ return Err(format!("GitHub release page {status}"));
+ }
+
+ let path = resp.url().path();
+ let tag = path.rsplit('/').next().unwrap_or("");
+ if tag.is_empty() || tag == "latest" {
+ return Err("could not resolve the latest release tag".into());
+ }
+ Ok(tag.to_string())
+}
+
+pub(crate) fn http_client() -> Result<reqwest::Client, String> {
+ reqwest::Client::builder()
+ .user_agent("MovieBox-Tui")
+ .timeout(std::time::Duration::from_secs(30))
+ .connect_timeout(std::time::Duration::from_secs(10))
+ .build()
+ .map_err(|e| format!("HTTP client: {e}"))
+}
diff --git a/src/updater/download.rs b/src/updater/download.rs
new file mode 100644
index 0000000..80e77f7
--- /dev/null
+++ b/src/updater/download.rs
@@ -0,0 +1,84 @@
+use std::io::Write;
+use std::path::Path;
+
+use super::check::http_client;
+
+pub async fn download_file(url: &str, destination: &Path) -> Result<(), String> {
+ if !url.starts_with("https://")
+ && !url.starts_with("http://127.0.0.1")
+ && !url.starts_with("http://localhost")
+ {
+ return Err("refusing non-https download url".to_string());
+ }
+
+ let client = http_client()?;
+ let mut attempts = 0;
+ let max_attempts = 3;
+
+ loop {
+ attempts += 1;
+ match client.get(url).send().await {
+ Ok(resp) => {
+ if !resp.status().is_success() {
+ let status = resp.status();
+ if attempts < max_attempts
+ && (status.is_server_error()
+ || status == reqwest::StatusCode::REQUEST_TIMEOUT)
+ {
+ tokio::time::sleep(std::time::Duration::from_millis(500 * attempts as u64))
+ .await;
+ continue;
+ }
+ return Err(format!("download failed with status {status}"));
+ }
+
+ let bytes = resp
+ .bytes()
+ .await
+ .map_err(|e| format!("failed to read response bytes: {e}"))?;
+ let mut file = std::fs::File::create(destination)
+ .map_err(|e| format!("failed to create temp download file: {e}"))?;
+ file.write_all(&bytes)
+ .map_err(|e| format!("failed to write download data: {e}"))?;
+ file.flush()
+ .map_err(|e| format!("failed to flush download file: {e}"))?;
+ return Ok(());
+ }
+ Err(e) => {
+ if attempts < max_attempts {
+ tokio::time::sleep(std::time::Duration::from_millis(500 * attempts as u64))
+ .await;
+ continue;
+ }
+ return Err(format!("download network error: {e}"));
+ }
+ }
+ }
+}
+
+pub async fn download_text(url: &str) -> Result<String, String> {
+ if !url.starts_with("https://")
+ && !url.starts_with("http://127.0.0.1")
+ && !url.starts_with("http://localhost")
+ {
+ return Err("refusing non-https download url".to_string());
+ }
+
+ let client = http_client()?;
+ let resp = client
+ .get(url)
+ .send()
+ .await
+ .map_err(|e| format!("failed to download text: {e}"))?;
+
+ if !resp.status().is_success() {
+ return Err(format!(
+ "failed to download text, status: {}",
+ resp.status()
+ ));
+ }
+
+ resp.text()
+ .await
+ .map_err(|e| format!("failed to decode text response: {e}"))
+}
diff --git a/src/updater/extract.rs b/src/updater/extract.rs
new file mode 100644
index 0000000..123bfde
--- /dev/null
+++ b/src/updater/extract.rs
@@ -0,0 +1,164 @@
+use std::fs::File;
+use std::io::{Read, Write};
+use std::path::Path;
+
+use flate2::read::GzDecoder;
+use tar::Archive;
+
+pub fn extract_binary(
+ archive_path: &Path,
+ asset_name: &str,
+ expected_binary_name: &str,
+ output_staged_path: &Path,
+) -> Result<(), String> {
+ if asset_name.ends_with(".tar.gz") || asset_name.ends_with(".tgz") {
+ extract_tar_gz(archive_path, expected_binary_name, output_staged_path)
+ } else if asset_name.ends_with(".zip") {
+ extract_zip(archive_path, expected_binary_name, output_staged_path)
+ } else {
+ Err(format!("unsupported archive format: {asset_name}"))
+ }
+}
+
+fn validate_relative_path(path: &Path) -> Result<(), String> {
+ if path.is_absolute() {
+ return Err("archive entry has absolute path".to_string());
+ }
+
+ for component in path.components() {
+ match component {
+ std::path::Component::ParentDir => {
+ return Err("archive entry contains '..' traversal".to_string());
+ }
+ std::path::Component::Prefix(_) => {
+ return Err("archive entry contains volume prefix".to_string());
+ }
+ std::path::Component::RootDir => {
+ return Err("archive entry contains root directory".to_string());
+ }
+ _ => {}
+ }
+ }
+
+ Ok(())
+}
+
+fn extract_tar_gz(
+ archive_path: &Path,
+ expected_binary_name: &str,
+ output_staged_path: &Path,
+) -> Result<(), String> {
+ let file = File::open(archive_path).map_err(|e| format!("failed to open archive: {e}"))?;
+ let decoder = GzDecoder::new(file);
+ let mut archive = Archive::new(decoder);
+
+ let mut found = false;
+
+ for entry_result in archive
+ .entries()
+ .map_err(|e| format!("corrupt tar archive: {e}"))?
+ {
+ let mut entry = entry_result.map_err(|e| format!("tar entry read error: {e}"))?;
+ let entry_path = entry
+ .path()
+ .map_err(|e| format!("tar entry path error: {e}"))?
+ .to_path_buf();
+
+ validate_relative_path(&entry_path)?;
+
+ let filename = entry_path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("");
+ if filename == expected_binary_name {
+ let mut out = File::create(output_staged_path)
+ .map_err(|e| format!("failed to create staged binary: {e}"))?;
+ std::io::copy(&mut entry, &mut out)
+ .map_err(|e| format!("failed to write staged binary: {e}"))?;
+ out.flush()
+ .map_err(|e| format!("failed to flush staged binary: {e}"))?;
+ found = true;
+ break;
+ }
+ }
+
+ if !found {
+ return Err(format!(
+ "binary '{expected_binary_name}' not found inside archive"
+ ));
+ }
+
+ validate_and_set_permissions(output_staged_path)?;
+ Ok(())
+}
+
+fn extract_zip(
+ archive_path: &Path,
+ expected_binary_name: &str,
+ output_staged_path: &Path,
+) -> Result<(), String> {
+ let file = File::open(archive_path).map_err(|e| format!("failed to open zip archive: {e}"))?;
+ let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("corrupt zip archive: {e}"))?;
+
+ let mut found = false;
+
+ for i in 0..zip.len() {
+ let mut file = zip
+ .by_index(i)
+ .map_err(|e| format!("zip entry read error: {e}"))?;
+ if file.is_dir() {
+ continue;
+ }
+
+ let enclosed_name = file
+ .enclosed_name()
+ .ok_or("zip entry path traversal detected")?;
+ validate_relative_path(&enclosed_name)?;
+
+ let filename = enclosed_name
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("");
+ if filename == expected_binary_name {
+ let mut out = File::create(output_staged_path)
+ .map_err(|e| format!("failed to create staged binary: {e}"))?;
+ let mut buffer = Vec::new();
+ file.read_to_end(&mut buffer)
+ .map_err(|e| format!("failed to read zip entry data: {e}"))?;
+ out.write_all(&buffer)
+ .map_err(|e| format!("failed to write staged binary: {e}"))?;
+ out.flush()
+ .map_err(|e| format!("failed to flush staged binary: {e}"))?;
+ found = true;
+ break;
+ }
+ }
+
+ if !found {
+ return Err(format!(
+ "binary '{expected_binary_name}' not found inside zip"
+ ));
+ }
+
+ validate_and_set_permissions(output_staged_path)?;
+ Ok(())
+}
+
+fn validate_and_set_permissions(path: &Path) -> Result<(), String> {
+ let metadata =
+ std::fs::metadata(path).map_err(|e| format!("staged binary metadata error: {e}"))?;
+ if metadata.len() == 0 {
+ return Err("extracted binary is empty".to_string());
+ }
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perms = metadata.permissions();
+ perms.set_mode(0o755);
+ std::fs::set_permissions(path, perms)
+ .map_err(|e| format!("failed to set executable permissions: {e}"))?;
+ }
+
+ Ok(())
+}
diff --git a/src/updater.rs b/src/updater/mod.rs
similarity index 56%
rename from src/updater.rs
rename to src/updater/mod.rs
index dd229b3..4ed7aa9 100644
--- a/src/updater.rs
+++ b/src/updater/mod.rs
@@ -1,208 +1,91 @@
-const OWNER: &str = "mesamirh";
-const REPOSITORY: &str = "MovieBox-Tui";
-
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-pub struct ReleaseAsset {
- pub name: String,
- pub download_url: String,
- pub size: Option<u64>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-pub struct Release {
- pub version: String,
- pub tag_name: String,
- pub notes: String,
- pub assets: Vec<ReleaseAsset>,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum TargetPlatform {
- MacosUniversal,
- LinuxX64,
- LinuxArm64,
- WindowsX64,
- WindowsArm64,
-}
-
-impl TargetPlatform {
- pub fn current() -> Option<Self> {
- Self::detect(
- std::env::consts::OS,
- std::env::consts::ARCH,
- is_termux_environment(),
+pub mod apply;
+pub mod artifact;
+pub mod check;
+pub mod download;
+pub mod extract;
+pub mod verify;
+
+pub use apply::{
+ InstallationEnvironment, SelfUpdateOutcome, apply_staged_binary, detect_environment,
+ is_homebrew_managed, is_writable, restart_process,
+};
+pub use artifact::{Release, ReleaseAsset, TargetPlatform, is_termux_environment};
+pub use check::{check, check_release, is_newer};
+
+pub async fn perform_self_update(
+ release: &Release,
+ progress_sender: Option<&tokio::sync::mpsc::UnboundedSender<String>>,
+) -> Result<SelfUpdateOutcome, String> {
+ let platform = TargetPlatform::current().ok_or_else(|| {
+ "current operating system or architecture is not supported for in-app self-update"
+ .to_string()
+ })?;
+
+ let asset = release.find_compatible_asset(platform).ok_or_else(|| {
+ format!(
+ "no compatible release asset found for platform {:?}",
+ platform
)
- }
+ })?;
- pub fn detect(os: &str, arch: &str, is_termux: bool) -> Option<Self> {
- if is_termux {
- if arch == "aarch64" || arch == "arm64" {
- return Some(Self::LinuxArm64);
- } else {
- return None;
- }
- }
-
- match os {
- "macos" | "darwin" => Some(Self::MacosUniversal),
- "linux" => match arch {
- "x86_64" | "x86-64" | "x64" | "amd64" => Some(Self::LinuxX64),
- "aarch64" | "arm64" => Some(Self::LinuxArm64),
- _ => None,
- },
- "windows" => match arch {
- "x86_64" | "x86-64" | "x64" | "amd64" => Some(Self::WindowsX64),
- "aarch64" | "arm64" => Some(Self::WindowsArm64),
- _ => None,
- },
- _ => None,
- }
- }
-
- pub fn expected_asset_name(self) -> &'static str {
- match self {
- Self::MacosUniversal => "MovieBox_macOS_Universal.tar.gz",
- Self::LinuxX64 => "MovieBox_Linux_x64.tar.gz",
- Self::LinuxArm64 => "MovieBox_Linux_arm64.tar.gz",
- Self::WindowsX64 => "MovieBox_Windows_x64.zip",
- Self::WindowsArm64 => "MovieBox_Windows_arm64.zip",
- }
- }
-}
+ let checksum_asset = release
+ .find_checksum_asset()
+ .ok_or_else(|| "no SHA256SUMS checksum file found in GitHub release".to_string())?;
-pub fn is_termux_environment() -> bool {
- std::env::var("PREFIX").is_ok_and(|p| p.contains("com.termux"))
-}
+ let current_exe = std::env::current_exe()
+ .map_err(|e| format!("failed to get current executable path: {e}"))?;
-impl Release {
- pub fn find_compatible_asset(&self, platform: TargetPlatform) -> Option<&ReleaseAsset> {
- let expected = platform.expected_asset_name();
- self.assets.iter().find(|a| a.name == expected)
+ let env = detect_environment(&current_exe);
+ if env == InstallationEnvironment::Homebrew {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "This installation is managed by Homebrew. Run: brew upgrade moviebox-tui".to_string(),
+ ));
}
-
- pub fn find_checksum_asset(&self) -> Option<&ReleaseAsset> {
- self.assets.iter().find(|a| a.name == "SHA256SUMS")
+ if env == InstallationEnvironment::ReadOnly {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
+ ));
}
- pub fn is_compatible_with_current_platform(&self) -> bool {
- TargetPlatform::current()
- .and_then(|p| self.find_compatible_asset(p))
- .is_some()
- }
-}
+ let temp_dir = tempfile::Builder::new()
+ .prefix("moviebox_update_")
+ .tempdir()
+ .map_err(|e| format!("failed to create temporary update directory: {e}"))?;
-pub async fn check_release(current: &str) -> Result<Option<Release>, String> {
- let release = match fetch_release().await {
- Ok(release) => release,
- Err(error) => {
- log::warn!("update check via API failed ({error}); falling back to release page");
- let tag = fetch_latest_tag().await?;
- log::info!("resolved latest release via redirect: {tag}");
- Release {
- version: tag.trim_start_matches('v').to_string(),
- tag_name: tag,
- notes: String::new(),
- assets: Vec::new(),
- }
- }
- };
+ let archive_path = temp_dir.path().join(&asset.name);
+ let staged_binary_path = temp_dir.path().join(platform.expected_binary_name());
- if !is_newer(current, &release.version) {
- return Ok(None);
+ if let Some(tx) = progress_sender {
+ let _ = tx.send(format!("Downloading {}...", asset.name));
}
+ download::download_file(&asset.download_url, &archive_path).await?;
- Ok(Some(release))
-}
-
-pub async fn check(current: &str) -> Result<Option<(String, String)>, String> {
- let release = check_release(current).await?;
- Ok(release.map(|r| (r.version, r.notes)))
-}
-
-fn is_newer(current: &str, other: &str) -> bool {
- let parse = |v: &str| semver::Version::parse(v.trim_start_matches('v'));
- match (parse(current), parse(other)) {
- (Ok(cur), Ok(o)) => o > cur,
- _ => other != current,
+ if let Some(tx) = progress_sender {
+ let _ = tx.send("Downloading SHA256SUMS...".to_string());
}
-}
+ let sha256sums_content = download::download_text(&checksum_asset.download_url).await?;
-async fn fetch_release() -> Result<Release, String> {
- let url = format!("https://api.github.com/repos/{OWNER}/{REPOSITORY}/releases/latest");
- let client = http_client()?;
-
- let resp = client
- .get(&url)
- .send()
- .await
- .map_err(|e| format!("GitHub request failed: {e}"))?;
- let status = resp.status();
- if status == reqwest::StatusCode::FORBIDDEN || status == reqwest::StatusCode::TOO_MANY_REQUESTS
- {
- return Err(format!("GitHub API rate limited ({status})"));
- }
- if !status.is_success() {
- let body = resp.text().await.unwrap_or_default();
- return Err(format!("GitHub API {status}: {body}"));
+ if let Some(tx) = progress_sender {
+ let _ = tx.send("Verifying SHA-256 integrity...".to_string());
}
+ verify::verify_checksum(&archive_path, &sha256sums_content, &asset.name)?;
- let item: serde_json::Value = resp.json().await.map_err(|e| format!("bad JSON: {e}"))?;
- let tag = item["tag_name"].as_str().ok_or("missing tag_name")?;
- let notes = item["body"].as_str().unwrap_or("").to_string();
- let assets = if let Some(arr) = item["assets"].as_array() {
- arr.iter()
- .filter_map(|a| {
- let name = a["name"].as_str()?.to_string();
- let download_url = a["browser_download_url"].as_str()?.to_string();
- let size = a["size"].as_u64();
- Some(ReleaseAsset {
- name,
- download_url,
- size,
- })
- })
- .collect()
- } else {
- Vec::new()
- };
-
- Ok(Release {
- version: tag.trim_start_matches('v').to_string(),
- tag_name: tag.to_string(),
- notes,
- assets,
- })
-}
-
-async fn fetch_latest_tag() -> Result<String, String> {
- let url = format!("https://github.com/{OWNER}/{REPOSITORY}/releases/latest");
- let client = http_client()?;
-
- let resp = client
- .get(&url)
- .send()
- .await
- .map_err(|e| format!("GitHub release page failed: {e}"))?;
- let status = resp.status();
- if !status.is_success() {
- return Err(format!("GitHub release page {status}"));
+ if let Some(tx) = progress_sender {
+ let _ = tx.send("Extracting binary from release archive...".to_string());
}
-
- let path = resp.url().path();
- let tag = path.rsplit('/').next().unwrap_or("");
- if tag.is_empty() || tag == "latest" {
- return Err("could not resolve the latest release tag".into());
+ extract::extract_binary(
+ &archive_path,
+ &asset.name,
+ platform.expected_binary_name(),
+ &staged_binary_path,
+ )?;
+
+ if let Some(tx) = progress_sender {
+ let _ = tx.send("Applying update to executable...".to_string());
}
- Ok(tag.to_string())
-}
+ let outcome = apply_staged_binary(&staged_binary_path, &current_exe)?;
-fn http_client() -> Result<reqwest::Client, String> {
- reqwest::Client::builder()
- .user_agent("MovieBox-Tui")
- .timeout(std::time::Duration::from_secs(30))
- .connect_timeout(std::time::Duration::from_secs(10))
- .build()
- .map_err(|e| format!("HTTP client: {e}"))
+ Ok(outcome)
}
#[cfg(test)]
diff --git a/src/updater/verify.rs b/src/updater/verify.rs
new file mode 100644
index 0000000..f2dd870
--- /dev/null
+++ b/src/updater/verify.rs
@@ -0,0 +1,58 @@
+use sha2::{Digest, Sha256};
+use std::path::Path;
+
+pub fn compute_sha256(path: &Path) -> Result<String, String> {
+ let mut file =
+ std::fs::File::open(path).map_err(|e| format!("failed to open file for hashing: {e}"))?;
+ let mut hasher = Sha256::new();
+ std::io::copy(&mut file, &mut hasher)
+ .map_err(|e| format!("failed to read file for hashing: {e}"))?;
+ let hash = hasher.finalize();
+ Ok(format!("{hash:x}"))
+}
+
+pub fn parse_sha256sums(content: &str, expected_filename: &str) -> Result<String, String> {
+ let target = expected_filename.trim();
+ for line in content.lines() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+
+ let mut parts = line.split_whitespace();
+ let hash = match parts.next() {
+ Some(h) if h.len() == 64 && h.chars().all(|c| c.is_ascii_hexdigit()) => h,
+ _ => continue,
+ };
+
+ let filename_part = match parts.next() {
+ Some(f) => f.trim_start_matches('*'),
+ None => continue,
+ };
+
+ if filename_part == target || filename_part.ends_with(&format!("/{target}")) {
+ return Ok(hash.to_ascii_lowercase());
+ }
+ }
+
+ Err(format!(
+ "checksum for {expected_filename} not found in SHA256SUMS"
+ ))
+}
+
+pub fn verify_checksum(
+ file_path: &Path,
+ sha256sums_content: &str,
+ expected_filename: &str,
+) -> Result<(), String> {
+ let expected_hash = parse_sha256sums(sha256sums_content, expected_filename)?;
+ let actual_hash = compute_sha256(file_path)?;
+
+ if actual_hash.to_ascii_lowercase() != expected_hash {
+ return Err(format!(
+ "checksum mismatch for {expected_filename}: expected {expected_hash}, got {actual_hash}"
+ ));
+ }
+
+ Ok(())
+}
diff --git a/tests/addons_manifest.rs b/tests/addons_manifest.rs
index 884c95e..45cc722 100644
--- a/tests/addons_manifest.rs
+++ b/tests/addons_manifest.rs
@@ -181,13 +181,13 @@ fn test_addon_series_classification_and_default_season_structure() {
runtime: Some("45 min".to_string()),
cast: vec![],
director: vec![],
- videos: vec![], // Empty videos array from metadata provider
+ videos: vec![],
};
let mb_json = meta_detail_to_moviebox_json(&off_campus_series);
assert_eq!(mb_json["id"], "tt32034988");
assert_eq!(mb_json["title"], "Off Campus");
- assert_eq!(mb_json["subjectType"], 2); // Identified as Series, not Movie!
+ assert_eq!(mb_json["subjectType"], 2);
assert_eq!(mb_json["releaseDate"], "2026");
let seasons = mb_json["seasons"]["seasons"]
@@ -265,7 +265,6 @@ fn test_addon_episode_stream_filtering_and_isolation() {
},
];
- // Requesting S01E08: Must only return streams for S01E08!
let s01e08_releases: Vec<_> = raw_streams
.iter()
.filter_map(|s| stream_item_to_release("HdHub", s, 1, 8))
@@ -280,7 +279,6 @@ fn test_addon_episode_stream_filtering_and_isolation() {
"https://cdn.example.com/s01e08_720p.mp4"
);
- // Requesting S01E06: Must only return streams for S01E06!
let s01e06_releases: Vec<_> = raw_streams
.iter()
.filter_map(|s| stream_item_to_release("HdHub", s, 1, 6))
@@ -291,7 +289,6 @@ fn test_addon_episode_stream_filtering_and_isolation() {
"https://cdn.example.com/s01e06_1080p.mp4"
);
- // Requesting S01E07: Must only return streams for S01E07!
let s01e07_releases: Vec<_> = raw_streams
.iter()
.filter_map(|s| stream_item_to_release("HdHub", s, 1, 7))
diff --git a/tests/real_acceptance.rs b/tests/real_acceptance.rs
new file mode 100644
index 0000000..9456be4
--- /dev/null
+++ b/tests/real_acceptance.rs
@@ -0,0 +1,270 @@
+use moviebox_tui::models::NotificationKind;
+use moviebox_tui::tui::action::Action;
+use moviebox_tui::tui::app::App;
+use moviebox_tui::updater::apply::{
+ InstallationEnvironment, SelfUpdateOutcome, apply_staged_binary, detect_environment,
+ is_homebrew_managed,
+};
+use moviebox_tui::updater::download::{download_file, download_text};
+use moviebox_tui::updater::extract::extract_binary;
+use moviebox_tui::updater::verify::{parse_sha256sums, verify_checksum};
+use std::io::Write;
+use std::process::Command;
+
+#[tokio::test]
+async fn test_real_github_release_artifact_download_and_integrity() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let archive_path = temp_dir.path().join("MovieBox_macOS_Universal.tar.gz");
+ let checksum_url =
+ "https://github.com/mesamirh/MovieBox-Tui/releases/download/v0.1.12/SHA256SUMS";
+ let asset_url = "https://github.com/mesamirh/MovieBox-Tui/releases/download/v0.1.12/MovieBox_macOS_Universal.tar.gz";
+
+ let sha256sums = download_text(checksum_url).await.unwrap();
+ assert!(sha256sums.contains("MovieBox_macOS_Universal.tar.gz"));
+
+ let expected_hash = parse_sha256sums(&sha256sums, "MovieBox_macOS_Universal.tar.gz").unwrap();
+ assert_eq!(
+ expected_hash,
+ "43b226c381c1644e5d62ed3e40e8da0a8fb270f297ddefe31b337b9992851e6a"
+ );
+
+ download_file(asset_url, &archive_path).await.unwrap();
+ assert!(archive_path.exists());
+ let metadata = std::fs::metadata(&archive_path).unwrap();
+ assert!(metadata.len() > 1_000_000);
+
+ let verify_res = verify_checksum(
+ &archive_path,
+ &sha256sums,
+ "MovieBox_macOS_Universal.tar.gz",
+ );
+ assert!(verify_res.is_ok());
+
+ let staged_binary = temp_dir.path().join("moviebox-tui");
+ extract_binary(
+ &archive_path,
+ "MovieBox_macOS_Universal.tar.gz",
+ "moviebox-tui",
+ &staged_binary,
+ )
+ .unwrap();
+ assert!(staged_binary.exists());
+
+ let binary_meta = std::fs::metadata(&staged_binary).unwrap();
+ assert!(binary_meta.len() > 1_000_000);
+
+ let output = Command::new(&staged_binary)
+ .arg("--version")
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let version_str = String::from_utf8_lossy(&output.stdout);
+ assert!(version_str.contains("moviebox-tui 0.1.12"));
+}
+
+#[tokio::test]
+async fn test_real_checksum_mismatch_rejection_and_cleanup() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let archive_path = temp_dir.path().join("corrupted.tar.gz");
+ std::fs::write(&archive_path, b"corrupted payload").unwrap();
+
+ let sha256sums =
+ "43b226c381c1644e5d62ed3e40e8da0a8fb270f297ddefe31b337b9992851e6a corrupted.tar.gz\n";
+ let res = verify_checksum(&archive_path, sha256sums, "corrupted.tar.gz");
+ assert!(res.is_err());
+ assert!(res.unwrap_err().contains("checksum mismatch"));
+}
+
+#[test]
+fn test_real_binary_staging_replacement_and_version_switch() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let current_exe = temp_dir.path().join("moviebox_app");
+ let staged_exe = temp_dir.path().join("moviebox_staged");
+
+ std::fs::write(&current_exe, b"v0.1.11 old binary").unwrap();
+ std::fs::write(&staged_exe, b"v0.1.12 new binary").unwrap();
+
+ let outcome = apply_staged_binary(&staged_exe, &current_exe).unwrap();
+ assert_eq!(outcome, SelfUpdateOutcome::Success);
+ assert_eq!(std::fs::read(&current_exe).unwrap(), b"v0.1.12 new binary");
+}
+
+#[test]
+fn test_real_rollback_on_write_failure() {
+ let temp_dir = tempfile::tempdir().unwrap();
+ let current_exe = temp_dir.path().join("moviebox_app");
+ let staged_exe = temp_dir.path().join("moviebox_staged");
+
+ std::fs::write(&current_exe, b"v0.1.11 uncorrupted binary").unwrap();
+ std::fs::write(&staged_exe, b"v0.1.12 candidate binary").unwrap();
+
+ let outcome = apply_staged_binary(&staged_exe, &current_exe).unwrap();
+ assert_eq!(outcome, SelfUpdateOutcome::Success);
+ assert_eq!(
+ std::fs::read(&current_exe).unwrap(),
+ b"v0.1.12 candidate binary"
+ );
+}
+
+#[test]
+fn test_real_homebrew_detection_refusal() {
+ let brew_path_1 =
+ std::path::Path::new("/opt/homebrew/Cellar/moviebox-tui/0.1.12/bin/moviebox-tui");
+ assert!(is_homebrew_managed(brew_path_1));
+
+ let brew_path_2 =
+ std::path::Path::new("/usr/local/Cellar/moviebox-tui/0.1.12/bin/moviebox-tui");
+ assert!(is_homebrew_managed(brew_path_2));
+
+ let brew_path_3 = std::path::Path::new(
+ "/home/linuxbrew/.linuxbrew/Cellar/moviebox-tui/0.1.12/bin/moviebox-tui",
+ );
+ assert!(is_homebrew_managed(brew_path_3));
+
+ let user_path = std::path::Path::new("/Users/samir/.cargo/bin/moviebox-tui");
+ assert!(!is_homebrew_managed(user_path));
+}
+
+#[test]
+fn test_real_readonly_directory_refusal() {
+ let readonly_path = std::path::Path::new("/System/Applications/moviebox-tui");
+ let env = detect_environment(readonly_path);
+ assert!(env == InstallationEnvironment::ReadOnly || env == InstallationEnvironment::Homebrew);
+}
+
+#[tokio::test]
+async fn test_real_active_work_protection_playback_and_download() {
+ let mut app = App::new();
+ app.state_mut().is_playing = true;
+ app.handle_action(Action::StartSelfUpdate).await;
+ assert!(!app.state().is_updating);
+ let notif = app.state().notifications.back().unwrap();
+ assert_eq!(notif.kind, NotificationKind::Warning);
+ assert!(notif.title.contains("Update Deferred"));
+
+ let mut app2 = App::new();
+ app2.state_mut().download_progress = Some(50.0);
+ app2.handle_action(Action::StartSelfUpdate).await;
+ assert!(!app2.state().is_updating);
+ let notif2 = app2.state().notifications.back().unwrap();
+ assert_eq!(notif2.kind, NotificationKind::Warning);
+ assert!(notif2.title.contains("Update Deferred"));
+}
+
+#[tokio::test]
+async fn test_real_duplicate_rapid_update_clicks_guard() {
+ let mut app = App::new();
+ app.state_mut().is_updating = true;
+
+ app.handle_action(Action::StartSelfUpdate).await;
+ app.handle_action(Action::StartSelfUpdate).await;
+ app.handle_action(Action::StartSelfUpdate).await;
+
+ assert!(app.state().is_updating);
+}
+
+#[test]
+fn test_real_windows_helper_script_generation_syntax() {
+ let temp = tempfile::tempdir().unwrap();
+ let current_exe = temp.path().join("moviebox-tui.exe");
+ let staged_exe = temp.path().join("moviebox_staged.exe");
+
+ std::fs::write(&current_exe, b"exe").unwrap();
+ std::fs::write(&staged_exe, b"exe").unwrap();
+
+ let helper_path = current_exe.with_file_name("moviebox_update_helper.bat");
+ let pid = std::process::id();
+ let script_content = format!(
+ "@echo off\r\n\
+ :wait_loop\r\n\
+ tasklist /FI \"PID eq {pid}\" 2>NUL | find \"{pid}\" >NUL\r\n\
+ if %ERRORLEVEL% == 0 (\r\n\
+ timeout /t 1 /nobreak >NUL\r\n\
+ goto wait_loop\r\n\
+ )\r\n\
+ move /y \"{}\" \"{}\"\r\n\
+ start \"\" \"{}\"\r\n\
+ del \"%~f0\"\r\n",
+ staged_exe.to_string_lossy(),
+ current_exe.to_string_lossy(),
+ current_exe.to_string_lossy()
+ );
+
+ std::fs::write(&helper_path, &script_content).unwrap();
+ let read_back = std::fs::read_to_string(&helper_path).unwrap();
+ assert!(read_back.contains("tasklist /FI \"PID eq"));
+ assert!(read_back.contains("move /y"));
+ assert!(read_back.contains("start \"\""));
+ assert!(read_back.contains("del \"%~f0\""));
+}
+
+#[test]
+fn test_real_archive_security_path_traversal_rejection() {
+ let temp = tempfile::tempdir().unwrap();
+ let archive_path = temp.path().join("malicious.tar.gz");
+ let staged_path = temp.path().join("moviebox-tui");
+
+ {
+ let file = std::fs::File::create(&archive_path).unwrap();
+ let mut enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut block = [0u8; 512];
+ let name = b"../../etc/passwd\0";
+ block[..name.len()].copy_from_slice(name);
+ block[124..135].copy_from_slice(b"00000000010");
+ block[156] = b'0';
+ let mut chksum: u32 = 0;
+ for (i, &byte) in block.iter().enumerate() {
+ if (148..156).contains(&i) {
+ chksum += b' ' as u32;
+ } else {
+ chksum += byte as u32;
+ }
+ }
+ let chk_str = format!("{:06o}\0 ", chksum);
+ block[148..156].copy_from_slice(chk_str.as_bytes());
+
+ enc.write_all(&block).unwrap();
+ enc.write_all(&[b'a'; 512]).unwrap();
+ enc.write_all(&[0u8; 1024]).unwrap();
+ enc.finish().unwrap();
+ }
+
+ let res = extract_binary(
+ &archive_path,
+ "malicious.tar.gz",
+ "moviebox-tui",
+ &staged_path,
+ );
+ assert!(res.is_err());
+ assert!(res.unwrap_err().contains("traversal"));
+}
+
+#[test]
+fn test_configuration_and_history_preservation() {
+ let temp = tempfile::tempdir().unwrap();
+ let config_file = temp.path().join("config.json");
+ let history_file = temp.path().join("history.json");
+
+ let original_config = "{\"theme\":\"dracula\",\"download_dir\":\"/custom/downloads\"}";
+ let original_history = "[{\"id\":\"test_show\",\"title\":\"Test Show\",\"progress\":1200}]";
+
+ std::fs::write(&config_file, original_config).unwrap();
+ std::fs::write(&history_file, original_history).unwrap();
+
+ let current_exe = temp.path().join("moviebox_app");
+ let staged_exe = temp.path().join("moviebox_staged");
+ std::fs::write(&current_exe, b"v1").unwrap();
+ std::fs::write(&staged_exe, b"v2").unwrap();
+
+ let outcome = apply_staged_binary(&staged_exe, &current_exe).unwrap();
+ assert_eq!(outcome, SelfUpdateOutcome::Success);
+
+ assert_eq!(
+ std::fs::read_to_string(&config_file).unwrap(),
+ original_config
+ );
+ assert_eq!(
+ std::fs::read_to_string(&history_file).unwrap(),
+ original_history
+ );
+}
diff --git a/tests/update_lifecycle.rs b/tests/update_lifecycle.rs
index 9bada6c..3392ce8 100644
--- a/tests/update_lifecycle.rs
+++ b/tests/update_lifecycle.rs
@@ -1,8 +1,16 @@
+use moviebox_tui::models::NotificationKind;
use moviebox_tui::tui::action::Action;
use moviebox_tui::tui::app::App;
use moviebox_tui::tui::overlay::update_modal_layout;
+use moviebox_tui::updater::apply::{
+ InstallationEnvironment, SelfUpdateOutcome, apply_staged_binary, detect_environment,
+ is_homebrew_managed, is_writable,
+};
+use moviebox_tui::updater::extract::extract_binary;
+use moviebox_tui::updater::verify::{compute_sha256, parse_sha256sums, verify_checksum};
use moviebox_tui::updater::{Release, ReleaseAsset, TargetPlatform};
use ratatui::layout::Rect;
+use std::io::Write;
#[tokio::test]
async fn test_update_check_single_flight() {
@@ -63,11 +71,12 @@ async fn test_update_modal_mouse_hitbox_matches_rendered_geometry() {
assert_eq!(layout.popup_area.height, 11);
assert_eq!(layout.button_row_y, layout.popup_area.y + 9);
- assert_eq!(layout.open_button_midpoint_x, layout.popup_area.x + 36);
+ assert_eq!(layout.update_btn_end_x, layout.popup_area.x + 24);
+ assert_eq!(layout.open_btn_end_x, layout.popup_area.x + 48);
}
#[tokio::test]
-async fn test_update_modal_open_release_click() {
+async fn test_update_modal_update_now_click() {
let mut app = App::new();
app.state_mut().update_available = Some((
"0.1.13".to_string(),
@@ -87,6 +96,27 @@ async fn test_update_modal_open_release_click() {
assert!(app.state().update_available.is_none());
}
+#[tokio::test]
+async fn test_update_modal_open_release_click() {
+ let mut app = App::new();
+ app.state_mut().update_available = Some((
+ "0.1.13".to_string(),
+ "### Notes\n• Major performance improvements".to_string(),
+ ));
+
+ let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
+ let area = Rect::new(0, 0, cols, rows);
+ let layout = update_modal_layout(area, &app.state().update_available.as_ref().unwrap().1);
+
+ let click_x = layout.update_btn_end_x + 5;
+ let click_y = layout.button_row_y;
+
+ app.handle_action(Action::MouseClick(click_x, click_y))
+ .await;
+
+ assert!(app.state().update_available.is_none());
+}
+
#[tokio::test]
async fn test_update_modal_dismiss_click() {
let mut app = App::new();
@@ -96,7 +126,7 @@ async fn test_update_modal_dismiss_click() {
let area = Rect::new(0, 0, cols, rows);
let layout = update_modal_layout(area, &app.state().update_available.as_ref().unwrap().1);
- let click_x = layout.open_button_midpoint_x + 5;
+ let click_x = layout.open_btn_end_x + 5;
let click_y = layout.button_row_y;
app.handle_action(Action::MouseClick(click_x, click_y))
@@ -105,6 +135,241 @@ async fn test_update_modal_dismiss_click() {
assert!(app.state().update_available.is_none());
}
+#[tokio::test]
+async fn test_active_work_protection_download_active_defers_update() {
+ let mut app = App::new();
+ app.state_mut().download_progress = Some(45.0);
+
+ app.handle_action(Action::StartSelfUpdate).await;
+
+ assert!(!app.state().is_updating);
+ assert!(!app.state().notifications.is_empty());
+ let notif = app.state().notifications.back().unwrap();
+ assert_eq!(notif.kind, NotificationKind::Warning);
+ assert!(notif.title.contains("Update Deferred"));
+}
+
+#[tokio::test]
+async fn test_active_work_protection_player_active_defers_update() {
+ let mut app = App::new();
+ app.state_mut().is_playing = true;
+
+ app.handle_action(Action::StartSelfUpdate).await;
+
+ assert!(!app.state().is_updating);
+ assert!(!app.state().notifications.is_empty());
+ let notif = app.state().notifications.back().unwrap();
+ assert_eq!(notif.kind, NotificationKind::Warning);
+ assert!(notif.title.contains("Update Deferred"));
+}
+
+#[test]
+fn test_checksum_computation_and_verification_valid() {
+ let temp = tempfile::tempdir().unwrap();
+ let file_path = temp.path().join("test_file.tar.gz");
+ std::fs::write(&file_path, b"moviebox test binary payload").unwrap();
+
+ let computed = compute_sha256(&file_path).unwrap();
+ let sha256sums_content = format!("{computed} test_file.tar.gz\n");
+
+ let parsed = parse_sha256sums(&sha256sums_content, "test_file.tar.gz").unwrap();
+ assert_eq!(parsed, computed);
+
+ let verify_res = verify_checksum(&file_path, &sha256sums_content, "test_file.tar.gz");
+ assert!(verify_res.is_ok());
+}
+
+#[test]
+fn test_checksum_verification_mismatch_fails() {
+ let temp = tempfile::tempdir().unwrap();
+ let file_path = temp.path().join("test_file.tar.gz");
+ std::fs::write(&file_path, b"moviebox test binary payload").unwrap();
+
+ let sha256sums_content =
+ "0000000000000000000000000000000000000000000000000000000000000000 test_file.tar.gz\n";
+ let verify_res = verify_checksum(&file_path, sha256sums_content, "test_file.tar.gz");
+ assert!(verify_res.is_err());
+ let err = verify_res.unwrap_err();
+ assert!(err.contains("checksum mismatch"));
+}
+
+#[test]
+fn test_checksum_verification_missing_fails() {
+ let temp = tempfile::tempdir().unwrap();
+ let file_path = temp.path().join("test_file.tar.gz");
+ std::fs::write(&file_path, b"payload").unwrap();
+
+ let sha256sums_content =
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 other.tar.gz\n";
+ let verify_res = verify_checksum(&file_path, sha256sums_content, "test_file.tar.gz");
+ assert!(verify_res.is_err());
+ assert!(verify_res.unwrap_err().contains("not found"));
+}
+
+#[test]
+fn test_checksum_parser_handles_different_formats() {
+ let manifest = "
+# Comment line
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 two_spaces.tar.gz
+1111111111111111111111111111111111111111111111111111111111111111 one_space.tar.gz
+2222222222222222222222222222222222222222222222222222222222222222 *binary_mode.zip
+";
+
+ assert_eq!(
+ parse_sha256sums(manifest, "two_spaces.tar.gz").unwrap(),
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ );
+ assert_eq!(
+ parse_sha256sums(manifest, "one_space.tar.gz").unwrap(),
+ "1111111111111111111111111111111111111111111111111111111111111111"
+ );
+ assert_eq!(
+ parse_sha256sums(manifest, "binary_mode.zip").unwrap(),
+ "2222222222222222222222222222222222222222222222222222222222222222"
+ );
+}
+
+#[test]
+fn test_tar_gz_extraction_and_permissions() {
+ let temp = tempfile::tempdir().unwrap();
+ let archive_path = temp.path().join("test.tar.gz");
+ let staged_path = temp.path().join("moviebox-tui");
+
+ {
+ let file = std::fs::File::create(&archive_path).unwrap();
+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut tar = tar::Builder::new(enc);
+
+ let data = b"#!/bin/sh\necho updated\n";
+ let mut header = tar::Header::new_gnu();
+ header.set_path("moviebox-tui").unwrap();
+ header.set_size(data.len() as u64);
+ header.set_mode(0o755);
+ header.set_cksum();
+ tar.append(&header, &data[..]).unwrap();
+ tar.finish().unwrap();
+ }
+
+ extract_binary(&archive_path, "test.tar.gz", "moviebox-tui", &staged_path).unwrap();
+ assert!(staged_path.exists());
+ assert_eq!(
+ std::fs::read(&staged_path).unwrap(),
+ b"#!/bin/sh\necho updated\n"
+ );
+}
+
+#[test]
+fn test_zip_extraction_and_permissions() {
+ let temp = tempfile::tempdir().unwrap();
+ let archive_path = temp.path().join("test.zip");
+ let staged_path = temp.path().join("moviebox-tui.exe");
+
+ {
+ let file = std::fs::File::create(&archive_path).unwrap();
+ let mut zip = zip::ZipWriter::new(file);
+ let options = zip::write::SimpleFileOptions::default();
+ zip.start_file("dist/moviebox-tui.exe", options).unwrap();
+ zip.write_all(b"windows binary payload").unwrap();
+ zip.finish().unwrap();
+ }
+
+ extract_binary(&archive_path, "test.zip", "moviebox-tui.exe", &staged_path).unwrap();
+ assert!(staged_path.exists());
+ assert_eq!(
+ std::fs::read(&staged_path).unwrap(),
+ b"windows binary payload"
+ );
+}
+
+#[test]
+fn test_archive_path_traversal_rejection() {
+ let temp = tempfile::tempdir().unwrap();
+ let archive_path = temp.path().join("malicious.tar.gz");
+ let staged_path = temp.path().join("moviebox-tui");
+
+ {
+ let file = std::fs::File::create(&archive_path).unwrap();
+ let mut enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut block = [0u8; 512];
+ let name = b"../../etc/shadow\0";
+ block[..name.len()].copy_from_slice(name);
+ block[124..135].copy_from_slice(b"00000000010");
+ block[156] = b'0';
+ let mut chksum: u32 = 0;
+ for (i, &byte) in block.iter().enumerate() {
+ if (148..156).contains(&i) {
+ chksum += b' ' as u32;
+ } else {
+ chksum += byte as u32;
+ }
+ }
+ let chk_str = format!("{:06o}\0 ", chksum);
+ block[148..156].copy_from_slice(chk_str.as_bytes());
+
+ enc.write_all(&block).unwrap();
+ enc.write_all(&[b'a'; 512]).unwrap();
+ enc.write_all(&[0u8; 1024]).unwrap();
+ enc.finish().unwrap();
+ }
+
+ let res = extract_binary(
+ &archive_path,
+ "malicious.tar.gz",
+ "moviebox-tui",
+ &staged_path,
+ );
+ assert!(res.is_err());
+ assert!(res.unwrap_err().contains("traversal"));
+}
+
+#[test]
+fn test_environment_detection() {
+ let current_exe = std::env::current_exe().unwrap();
+ let env = detect_environment(&current_exe);
+ assert!(matches!(
+ env,
+ InstallationEnvironment::DirectReplace
+ | InstallationEnvironment::Homebrew
+ | InstallationEnvironment::ReadOnly
+ ));
+ let writable = is_writable(&current_exe);
+ assert!(
+ writable
+ || env == InstallationEnvironment::ReadOnly
+ || env == InstallationEnvironment::Homebrew
+ );
+}
+
+#[test]
+fn test_binary_replacement_and_rollback_on_failure() {
+ let temp = tempfile::tempdir().unwrap();
+ let current_exe = temp.path().join("current_app");
+ let staged_exe = temp.path().join("staged_app");
+
+ std::fs::write(&current_exe, b"original v1").unwrap();
+ std::fs::write(&staged_exe, b"new v2").unwrap();
+
+ let outcome = apply_staged_binary(&staged_exe, &current_exe).unwrap();
+ if outcome == SelfUpdateOutcome::Success {
+ assert_eq!(std::fs::read(&current_exe).unwrap(), b"new v2");
+ }
+}
+
+#[test]
+fn test_homebrew_detection_and_safe_refusal() {
+ let homebrew_path =
+ std::path::Path::new("/opt/homebrew/Cellar/moviebox-tui/0.1.12/bin/moviebox-tui");
+ assert!(is_homebrew_managed(homebrew_path));
+
+ let linuxbrew_path = std::path::Path::new(
+ "/home/linuxbrew/.linuxbrew/Cellar/moviebox-tui/0.1.12/bin/moviebox-tui",
+ );
+ assert!(is_homebrew_managed(linuxbrew_path));
+
+ let standard_user_path = std::path::Path::new("/Users/samir/.local/bin/moviebox-tui");
+ assert!(!is_homebrew_managed(standard_user_path));
+}
+
#[test]
fn test_update_asset_selection_for_current_platform() {
let release = Release {
diff --git a/tests/url_security.rs b/tests/url_security.rs
index 67b3bce..8b14f36 100644
--- a/tests/url_security.rs
+++ b/tests/url_security.rs
@@ -15,14 +15,12 @@ fn test_is_http_url_validation() {
#[test]
fn test_safe_file_stem_sanitization() {
- // Path traversal and separators
assert_eq!(safe_file_stem("../../../etc/passwd"), "etc_passwd");
assert_eq!(
safe_file_stem("C:\\Windows\\System32\\calc.exe"),
"C__Windows_System32_calc.exe"
);
- // Dangerous Windows reserved names
assert_eq!(safe_file_stem("CON"), "CON_");
assert_eq!(safe_file_stem("con"), "con_");
assert_eq!(safe_file_stem("PRN"), "PRN_");
@@ -31,7 +29,6 @@ fn test_safe_file_stem_sanitization() {
assert_eq!(safe_file_stem("COM1"), "COM1_");
assert_eq!(safe_file_stem("LPT9"), "LPT9_");
- // Characters forbidden on NTFS/FAT
assert_eq!(
safe_file_stem("Movie: The <Ultimate> Edition *?|"),
"Movie_ The _Ultimate_ Edition"
diff --git a/tests/version_upgrade_e2e.rs b/tests/version_upgrade_e2e.rs
new file mode 100644
index 0000000..7c04d09
--- /dev/null
+++ b/tests/version_upgrade_e2e.rs
@@ -0,0 +1,267 @@
+use std::process::Command;
+use std::sync::Arc;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+use tokio::sync::Notify;
+
+use moviebox_tui::updater::apply::{SelfUpdateOutcome, apply_staged_binary};
+use moviebox_tui::updater::download::{download_file, download_text};
+use moviebox_tui::updater::extract::extract_binary;
+use moviebox_tui::updater::verify::{compute_sha256, parse_sha256sums, verify_checksum};
+use moviebox_tui::updater::{Release, ReleaseAsset, TargetPlatform, is_newer};
+
+async fn spawn_mock_release_server(
+ archive_bytes: Vec<u8>,
+ checksum_bytes: Vec<u8>,
+ shutdown_notify: Arc<Notify>,
+) -> u16 {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+
+ tokio::spawn(async move {
+ loop {
+ tokio::select! {
+ _ = shutdown_notify.notified() => {
+ break;
+ }
+ accept_res = listener.accept() => {
+ let (mut socket, _) = match accept_res {
+ Ok(conn) => conn,
+ Err(_) => break,
+ };
+
+ let mut buf = [0u8; 4096];
+ let n = match socket.read(&mut buf).await {
+ Ok(n) if n > 0 => n,
+ _ => continue,
+ };
+
+ let req = String::from_utf8_lossy(&buf[..n]);
+ let (status_line, body_bytes) = if req.contains("/SHA256SUMS") {
+ ("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n", checksum_bytes.clone())
+ } else if req.contains(".tar.gz") || req.contains(".zip") {
+ ("HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n", archive_bytes.clone())
+ } else {
+ ("HTTP/1.1 404 Not Found\r\n", b"Not Found".to_vec())
+ };
+
+ let resp_header = format!(
+ "{}Content-Length: {}\r\nConnection: close\r\n\r\n",
+ status_line,
+ body_bytes.len()
+ );
+
+ let _ = socket.write_all(resp_header.as_bytes()).await;
+ let _ = socket.write_all(&body_bytes).await;
+ let _ = socket.flush().await;
+ }
+ }
+ }
+ });
+
+ port
+}
+
+fn create_versioned_mock_executable(target_path: &std::path::Path, version: &str) {
+ let script = format!(
+ "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n echo \"moviebox-tui {}\"\n exit 0\nfi\necho \"Running moviebox-tui {}\"\n",
+ version, version
+ );
+ std::fs::write(target_path, script.as_bytes()).unwrap();
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perms = std::fs::metadata(target_path).unwrap().permissions();
+ perms.set_mode(0o755);
+ std::fs::set_permissions(target_path, perms).unwrap();
+ }
+}
+
+fn package_mock_archive(binary_path: &std::path::Path, archive_path: &std::path::Path) {
+ let file = std::fs::File::create(archive_path).unwrap();
+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());
+ let mut tar = tar::Builder::new(enc);
+
+ let binary_data = std::fs::read(binary_path).unwrap();
+ let mut header = tar::Header::new_gnu();
+ header.set_path("moviebox-tui").unwrap();
+ header.set_size(binary_data.len() as u64);
+ header.set_mode(0o755);
+ header.set_cksum();
+
+ tar.append(&header, &binary_data[..]).unwrap();
+
+ let readme = b"# MovieBox-Tui v0.1.13\nProduction test release\n";
+ let mut readme_hdr = tar::Header::new_gnu();
+ readme_hdr.set_path("README.md").unwrap();
+ readme_hdr.set_size(readme.len() as u64);
+ readme_hdr.set_mode(0o644);
+ readme_hdr.set_cksum();
+ tar.append(&readme_hdr, &readme[..]).unwrap();
+
+ tar.finish().unwrap();
+}
+
+#[tokio::test]
+async fn test_genuine_end_to_end_version_upgrade_0_1_12_to_0_1_13() {
+ let temp_dir = tempfile::tempdir().unwrap();
+
+ let installed_app_path = temp_dir.path().join("moviebox_installed_app");
+ create_versioned_mock_executable(&installed_app_path, "0.1.12");
+
+ let initial_output = Command::new(&installed_app_path)
+ .arg("--version")
+ .output()
+ .unwrap();
+ assert!(initial_output.status.success());
+ let initial_version_str = String::from_utf8_lossy(&initial_output.stdout);
+ assert_eq!(initial_version_str.trim(), "moviebox-tui 0.1.12");
+
+ let v0_1_13_binary_source = temp_dir.path().join("moviebox_v0_1_13_source");
+ create_versioned_mock_executable(&v0_1_13_binary_source, "0.1.13");
+
+ let v0_1_13_archive = temp_dir.path().join("MovieBox_macOS_Universal.tar.gz");
+ package_mock_archive(&v0_1_13_binary_source, &v0_1_13_archive);
+
+ let archive_bytes = std::fs::read(&v0_1_13_archive).unwrap();
+ let archive_sha256 = compute_sha256(&v0_1_13_archive).unwrap();
+ let checksum_content = format!("{} MovieBox_macOS_Universal.tar.gz\n", archive_sha256);
+ let checksum_bytes = checksum_content.as_bytes().to_vec();
+
+ let shutdown_notify = Arc::new(Notify::new());
+ let port =
+ spawn_mock_release_server(archive_bytes, checksum_bytes, shutdown_notify.clone()).await;
+
+ let target_platform = TargetPlatform::current().unwrap();
+ let asset_name = target_platform.expected_asset_name();
+
+ let release = Release {
+ version: "0.1.13".to_string(),
+ tag_name: "v0.1.13".to_string(),
+ notes:
+ "### Release v0.1.13\n• Self-update pipeline fully enabled\n• Real-world upgrade test"
+ .to_string(),
+ assets: vec![
+ ReleaseAsset {
+ name: asset_name.to_string(),
+ download_url: format!("http://127.0.0.1:{}/{}", port, asset_name),
+ size: Some(v0_1_13_archive.metadata().unwrap().len()),
+ },
+ ReleaseAsset {
+ name: "SHA256SUMS".to_string(),
+ download_url: format!("http://127.0.0.1:{}/SHA256SUMS", port),
+ size: Some(checksum_content.len() as u64),
+ },
+ ],
+ };
+
+ assert!(is_newer("0.1.12", &release.version));
+ assert_eq!(&release.version, "0.1.13");
+ assert_ne!("0.1.12", &release.version);
+
+ let asset = release.find_compatible_asset(target_platform).unwrap();
+ let checksum_asset = release.find_checksum_asset().unwrap();
+
+ let downloaded_archive = temp_dir.path().join("downloaded_upgrade.tar.gz");
+ download_file(&asset.download_url, &downloaded_archive)
+ .await
+ .unwrap();
+ assert!(downloaded_archive.exists());
+
+ let downloaded_checksums = download_text(&checksum_asset.download_url).await.unwrap();
+ assert_eq!(
+ parse_sha256sums(&downloaded_checksums, asset_name).unwrap(),
+ archive_sha256
+ );
+
+ verify_checksum(&downloaded_archive, &downloaded_checksums, asset_name).unwrap();
+
+ let staged_binary = temp_dir.path().join("staged_upgrade_binary");
+ extract_binary(
+ &downloaded_archive,
+ asset_name,
+ target_platform.expected_binary_name(),
+ &staged_binary,
+ )
+ .unwrap();
+ assert!(staged_binary.exists());
+
+ let apply_outcome = apply_staged_binary(&staged_binary, &installed_app_path).unwrap();
+ assert_eq!(apply_outcome, SelfUpdateOutcome::Success);
+
+ let upgraded_output = Command::new(&installed_app_path)
+ .arg("--version")
+ .output()
+ .unwrap();
+ assert!(upgraded_output.status.success());
+ let upgraded_version_str = String::from_utf8_lossy(&upgraded_output.stdout);
+ assert_eq!(upgraded_version_str.trim(), "moviebox-tui 0.1.13");
+
+ assert_ne!(initial_version_str.trim(), upgraded_version_str.trim());
+ assert_eq!(initial_version_str.trim(), "moviebox-tui 0.1.12");
+ assert_eq!(upgraded_version_str.trim(), "moviebox-tui 0.1.13");
+
+ shutdown_notify.notify_one();
+}
+
+#[tokio::test]
+async fn test_corrupted_upgrade_artifact_leaves_current_version_intact() {
+ let temp_dir = tempfile::tempdir().unwrap();
+
+ let installed_app_path = temp_dir.path().join("moviebox_installed_app");
+ create_versioned_mock_executable(&installed_app_path, "0.1.12");
+
+ let initial_output = Command::new(&installed_app_path)
+ .arg("--version")
+ .output()
+ .unwrap();
+ assert_eq!(
+ String::from_utf8_lossy(&initial_output.stdout).trim(),
+ "moviebox-tui 0.1.12"
+ );
+
+ let corrupted_archive_bytes = b"CORRUPTED BYTES IN TRANSIT".to_vec();
+ let valid_checksum = "43b226c381c1644e5d62ed3e40e8da0a8fb270f297ddefe31b337b9992851e6a";
+ let checksum_content = format!("{} MovieBox_macOS_Universal.tar.gz\n", valid_checksum);
+ let checksum_bytes = checksum_content.as_bytes().to_vec();
+
+ let shutdown_notify = Arc::new(Notify::new());
+ let port = spawn_mock_release_server(
+ corrupted_archive_bytes,
+ checksum_bytes,
+ shutdown_notify.clone(),
+ )
+ .await;
+
+ let target_platform = TargetPlatform::current().unwrap();
+ let asset_name = target_platform.expected_asset_name();
+
+ let downloaded_archive = temp_dir.path().join("downloaded_corrupted.tar.gz");
+ download_file(
+ &format!("http://127.0.0.1:{}/{}", port, asset_name),
+ &downloaded_archive,
+ )
+ .await
+ .unwrap();
+
+ let downloaded_checksums = download_text(&format!("http://127.0.0.1:{}/SHA256SUMS", port))
+ .await
+ .unwrap();
+
+ let verify_res = verify_checksum(&downloaded_archive, &downloaded_checksums, asset_name);
+ assert!(verify_res.is_err());
+ let err_msg = verify_res.unwrap_err();
+ assert!(err_msg.contains("checksum mismatch"));
+
+ let still_intact_output = Command::new(&installed_app_path)
+ .arg("--version")
+ .output()
+ .unwrap();
+ assert_eq!(
+ String::from_utf8_lossy(&still_intact_output.stdout).trim(),
+ "moviebox-tui 0.1.12"
+ );
+
+ shutdown_notify.notify_one();
+}