From ed53d19fb16cb8fc5a504a31dc4a62e4674f13ff Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:55:45 +0800 Subject: [PATCH] fix(updater): gate cached updates on semver and confirm offers before installing --- Cargo.lock | 1 + package.json | 1 - pnpm-lock.yaml | 3 - src-tauri/Cargo.toml | 1 + src-tauri/src/core/notify/mod.rs | 6 +- src-tauri/src/core/notify/notification.rs | 4 +- src-tauri/src/core/updater.rs | 188 +++++++++--------- .../setting/setting-verge-advanced.tsx | 2 +- src/hooks/use-update.ts | 4 +- src/services/bindings.ts | 1 - src/services/notice-handlers.ts | 3 - src/services/update.ts | 48 +---- 12 files changed, 104 insertions(+), 158 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c41e9101d..25ef4c61d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1124,6 +1124,7 @@ dependencies = [ "rfd 0.18.0", "runas", "rustls", + "semver 1.0.28", "serde", "serde_json", "serde_yaml_ng", diff --git a/package.json b/package.json index c401adfdb..fcea7184e 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,6 @@ "@tauri-apps/plugin-updater": "2.14.1", "ahooks": "^3.10.0", "cidr-block": "^2.3.0", - "compare-versions": "^6.1.1", "dayjs": "1.11.23", "foxact": "^0.3.12", "foxts": "^5.9.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ed31c0489..019edc0ae 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -245,9 +245,6 @@ importers: cidr-block: specifier: ^2.3.0 version: 2.3.0 - compare-versions: - specifier: ^6.1.1 - version: 6.1.1 dayjs: specifier: 1.11.23 version: 1.11.23 diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b3a2551d8..ac928e0c6 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -64,6 +64,7 @@ chrono = { workspace = true } boa_engine = "0.22.0" http-body-util = "0.1.5" percent-encoding = "2.3.2" +semver = "1.0" reqwest = { workspace = true } sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [ "guard", diff --git a/src-tauri/src/core/notify/mod.rs b/src-tauri/src/core/notify/mod.rs index 9a6b7699f..581394494 100644 --- a/src-tauri/src/core/notify/mod.rs +++ b/src-tauri/src/core/notify/mod.rs @@ -6,8 +6,6 @@ pub mod notification; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, specta::Type)] pub enum NoticeStatus { - #[serde(rename = "info")] - Info, #[serde(rename = "import_sub_url::ok")] ImportSubUrlOk, #[serde(rename = "import_sub_url::error")] @@ -83,8 +81,7 @@ impl NoticeStatus { /// test both derive their variant list from here; expected strings stay /// hand-written in the test so renames cannot slip through. #[cfg(test)] - pub const ALL: [Self; 34] = [ - Self::Info, + pub const ALL: [Self; 33] = [ Self::ImportSubUrlOk, Self::ImportSubUrlError, Self::SetConfigError, @@ -129,7 +126,6 @@ mod tests { fn notice_status_wire_contract() -> Result<(), serde_json::Error> { let statuses = NoticeStatus::ALL; let expected = [ - "info", "import_sub_url::ok", "import_sub_url::error", "set_config::error", diff --git a/src-tauri/src/core/notify/notification.rs b/src-tauri/src/core/notify/notification.rs index 7ee40b090..c5c07e549 100644 --- a/src-tauri/src/core/notify/notification.rs +++ b/src-tauri/src/core/notify/notification.rs @@ -387,11 +387,11 @@ fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, se ), ( FrontendEvent::NoticeMessage { - status: NoticeStatus::Info, + status: NoticeStatus::UpdateFailed, message: Arc::from("ok"), }, "verge://notice-message", - json!(["info", "ok"]), + json!(["update_failed", "ok"]), ), ( FrontendEvent::TimerUpdated { profile_index: uid }, diff --git a/src-tauri/src/core/updater.rs b/src-tauri/src/core/updater.rs index 061d3da01..648973b43 100644 --- a/src-tauri/src/core/updater.rs +++ b/src-tauri/src/core/updater.rs @@ -6,16 +6,16 @@ use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use std::{ path::PathBuf, - sync::atomic::{AtomicBool, AtomicU64, Ordering}, + sync::atomic::{AtomicU64, Ordering}, time::Duration, }; use tauri_plugin_updater::{Update, UpdaterExt as _}; use tokio_util::sync::CancellationToken; pub struct SilentUpdater { - update_ready: AtomicBool, manual_cancel: Mutex>, background_cancel: Mutex>, + download_lock: tokio::sync::Mutex<()>, } #[derive(Serialize, specta::Type)] @@ -31,15 +31,11 @@ singleton!(SilentUpdater, SILENT_UPDATER); impl SilentUpdater { const fn new() -> Self { Self { - update_ready: AtomicBool::new(false), manual_cancel: Mutex::new(None), background_cancel: Mutex::new(None), + download_lock: tokio::sync::Mutex::const_new(()), } } - - pub fn is_update_ready(&self) -> bool { - self.update_ready.load(Ordering::Acquire) - } } #[derive(Serialize, Deserialize)] @@ -142,33 +138,13 @@ pub fn is_build_to_stable(current: &str, remote: &str) -> bool { !build.is_empty() && !base.contains('-') && base == remote.trim_start_matches('v') } -/// Compares numeric version components after stripping version suffixes. +/// Order by semver; versions that fail to parse order only by exact match. fn version_lte(a: &str, b: &str) -> bool { - let parse = |v: &str| -> Vec { - v.trim_start_matches('v') - .split(['-', '+']) - .next() - .unwrap_or("0") - .split('.') - .filter_map(|part| part.parse::().ok()) - .collect() - }; - - let a_parts = parse(a); - let b_parts = parse(b); - let len = a_parts.len().max(b_parts.len()); - - for i in 0..len { - let av = a_parts.get(i).copied().unwrap_or(0); - let bv = b_parts.get(i).copied().unwrap_or(0); - if av < bv { - return true; - } - if av > bv { - return false; - } + let parse = |v: &str| semver::Version::parse(v.trim_start_matches('v')); + match (parse(a), parse(b)) { + (Ok(a), Ok(b)) => a <= b, + _ => a == b, } - true // equal } /// Maps UI language to one of the three NSIS translations, defaulting to English. @@ -202,6 +178,8 @@ const MIRRORS: [&str; 2] = ["https://update.hwdns.net/", "https://gh-proxy.org/" /// A source delivering less than this per window is dropped for the next one. const MIN_PROGRESS: u64 = 1024 * 1024; const PROGRESS_WINDOW: Duration = Duration::from_secs(30); +/// Bounds the startup check so a black-holed endpoint cannot stall startup. +const CHECK_TIMEOUT: Duration = Duration::from_secs(30); #[cfg(target_os = "windows")] const INSTALL_TIMEOUT: Duration = Duration::from_secs(30); #[cfg(not(target_os = "windows"))] @@ -343,20 +321,17 @@ impl SilentUpdater { logging!( info, Type::System, - "Update cache version ({}) > current ({}), asking user to install", + "Update cache version ({}) > current ({}), checking the server", cached_version, current_version ); - // Preserve the cache when skipped so the next launch asks again. - if !Self::ask_user_to_install(app_handle, cached_version).await { - logging!(info, Type::System, "User skipped update install, starting normally"); - return false; - } - - let update = match Self::check(app_handle).await { - Ok(Some(u)) => u, - Ok(None) => { + // Installing requires the server manifest's signature, so an offline launch keeps + // the cache and waits for a connected one. + let checked = tokio::time::timeout(CHECK_TIMEOUT, Self::check(app_handle)).await; + let update = match checked { + Ok(Ok(Some(u))) => u, + Ok(Ok(None)) => { logging!( info, Type::System, @@ -365,13 +340,21 @@ impl SilentUpdater { Self::delete_cache(); return false; } - Err(e) => { + Ok(Err(e)) => { logging!( warn, Type::System, "Failed to check for update at startup: {e:#}, will retry next launch" ); - return false; // Keep cache for next attempt + return false; + } + Err(_) => { + logging!( + warn, + Type::System, + "Startup update check timed out, will retry next launch" + ); + return false; } }; @@ -380,6 +363,13 @@ impl SilentUpdater { }; let version = update.version.clone(); + + // Preserve the cache when skipped so the next launch asks again. + if !Self::ask_user_to_install(app_handle, &version).await { + logging!(info, Type::System, "User skipped update install, starting normally"); + return false; + } + logging!(info, Type::System, "Installing cached update v{version} at startup..."); Self::show_update_splash(app_handle, &version); @@ -408,7 +398,7 @@ impl SilentUpdater { let cancel = CancellationToken::new(); *self.manual_cancel.lock() = Some(cancel.clone()); let prepared = tokio::select! { - prepared = Self::prepare_install(app_handle, version, &on_event) => Some(prepared), + prepared = self.prepare_install(app_handle, version, &on_event) => Some(prepared), () = cancel.cancelled() => None, }; // `cancel_download` cancels under the lock, so once the token is taken back its state is @@ -429,6 +419,7 @@ impl SilentUpdater { } async fn prepare_install( + &self, app_handle: &tauri::AppHandle, version: &str, on_event: &(impl Fn(DownloadEvent) + Sync), @@ -439,6 +430,7 @@ impl SilentUpdater { else { return Ok(None); }; + let _download_guard = self.download_lock.lock().await; let bytes = match Self::verified_cache(&update) { Some(bytes) => bytes, None => download(&update, on_event).await?, @@ -459,7 +451,6 @@ impl SilentUpdater { if let Some(cancel) = cancel { cancel.cancel(); } - self.update_ready.store(false, Ordering::Release); Self::delete_cache(); } } @@ -494,26 +485,6 @@ impl SilentUpdater { fn show_update_splash(app_handle: &tauri::AppHandle, version: &str) { use tauri::{WebviewUrl, WebviewWindowBuilder}; - let window = match WebviewWindowBuilder::new(app_handle, "update-splash", WebviewUrl::App("index.html".into())) - .title("Clash Verge - Updating") - .inner_size(300.0, 180.0) - .resizable(false) - .maximizable(false) - .minimizable(false) - .closable(false) - .decorations(false) - .center() - .always_on_top(true) - .visible(true) - .build() - { - Ok(w) => w, - Err(e) => { - logging!(warn, Type::System, "Failed to create update splash: {e}"); - return; - } - }; - let js = format!( r#" document.documentElement.innerHTML = ` @@ -547,17 +518,27 @@ impl SilentUpdater { "# ); - // The new webview may not accept evaluation immediately. - std::thread::spawn(move || { - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; - let _ = retry_sync( - RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(9), std::time::Duration::ZERO), - |index| { - std::thread::sleep(std::time::Duration::from_millis(100 * (index as u64 + 1))); - window.eval(&js).map_err(RetryError::Retry) - }, - ); - }); + let Ok(url) = tauri::Url::parse("about:blank") else { + logging!(warn, Type::System, "Failed to parse the splash URL"); + return; + }; + if let Err(e) = WebviewWindowBuilder::new(app_handle, "update-splash", WebviewUrl::CustomProtocol(url)) + .initialization_script(&js) + .title("Clash Verge - Updating") + .inner_size(300.0, 180.0) + .resizable(false) + .maximizable(false) + .minimizable(false) + .closable(false) + .decorations(false) + .center() + .always_on_top(true) + .visible(true) + .build() + { + logging!(warn, Type::System, "Failed to create update splash: {e}"); + return; + } logging!(info, Type::System, "Update splash window shown"); } @@ -582,11 +563,6 @@ impl SilentUpdater { return Ok(()); } - if self.is_update_ready() { - logging!(debug, Type::System, "Silent update skipped: update already pending"); - return Ok(()); - } - logging!(info, Type::System, "Silent updater: checking for updates..."); let updater = app_handle.updater()?; @@ -605,18 +581,9 @@ impl SilentUpdater { let version = update.version.as_str(); logging!(info, Type::System, "Silent updater: update available: v{version}"); - if let Some(body) = &update.body - && body.to_lowercase().contains("break change") - { - logging!( - info, - Type::System, - "Silent updater: breaking change detected in v{version}, notifying frontend" - ); - super::handle::Handle::notice( - super::notify::NoticeStatus::Info, - format!("New version v{version} contains breaking changes. Please update manually."), - ); + let download_guard = self.download_lock.lock().await; + // A discard that arrived while waiting for the lock must not start a doomed download. + if cancel.is_cancelled() { return Ok(()); } @@ -636,6 +603,7 @@ impl SilentUpdater { logging!(info, Type::System, "Silent updater: download complete"); Self::write_cache(&bytes, version)?; } + drop(download_guard); // Serialized with `discard_pending` in the verge patch, which holds the same lock. let _config_write = Config::lock_config_write().await; @@ -649,8 +617,6 @@ impl SilentUpdater { return Ok(()); } - self.update_ready.store(true, Ordering::Release); - logging!( info, Type::System, @@ -674,3 +640,33 @@ impl SilentUpdater { } } } + +#[cfg(test)] +mod tests { + use super::{is_build_to_stable, version_lte}; + + #[test] + fn version_lte_orders_prereleases_below_their_release() { + assert!(version_lte("2.2.0-beta.1", "2.2.0")); + assert!(!version_lte("2.2.0", "2.2.0-alpha.1")); + assert!(version_lte("2.2.0", "2.2.0")); + assert!(version_lte("2.1.9", "2.2.0")); + assert!(!version_lte("2.2.1", "2.2.0")); + } + + #[test] + fn version_lte_strips_prefixes_and_falls_back_to_equality() { + assert!(version_lte("v2.2.0", "2.2.0")); + assert!(version_lte("2.2.0+5", "2.2.1")); + assert!(version_lte("2.1.1臻fix", "2.1.1臻fix")); + assert!(!version_lte("2.1.1臻fix", "2.2.0")); + } + + #[test] + fn is_build_to_stable_matches_build_metadata_to_the_same_base() { + assert!(is_build_to_stable("2.4.3+5", "2.4.3")); + assert!(!is_build_to_stable("2.4.3+5", "2.4.4")); + assert!(!is_build_to_stable("2.4.3", "2.4.3")); + assert!(!is_build_to_stable("2.4.3-beta+5", "2.4.3")); + } +} diff --git a/src/components/setting/setting-verge-advanced.tsx b/src/components/setting/setting-verge-advanced.tsx index b0dcd7008..414225b25 100644 --- a/src/components/setting/setting-verge-advanced.tsx +++ b/src/components/setting/setting-verge-advanced.tsx @@ -15,7 +15,7 @@ import { } from '@/services/cmds' import { mutate } from '@/services/mutate' import { showNotice } from '@/services/notice-service' -import { checkUpdateSafe as checkUpdate } from '@/services/update' +import { checkForUpdate as checkUpdate } from '@/services/update' import { version } from '@root/package.json' import { BackupViewer } from './mods/backup-viewer' diff --git a/src/hooks/use-update.ts b/src/hooks/use-update.ts index 37dff3055..0c5c5f955 100644 --- a/src/hooks/use-update.ts +++ b/src/hooks/use-update.ts @@ -1,5 +1,5 @@ import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client' -import { checkUpdateSafe } from '@/services/update' +import { checkForUpdate } from '@/services/update' import { useVerge } from './use-verge' @@ -26,7 +26,7 @@ export const useUpdate = (enabled: boolean = true) => { const shouldCheck = enabled && auto_check_update !== false const fetchUpdate = async () => { - const result = await checkUpdateSafe() + const result = await checkForUpdate() updateLastCheckTime() return result } diff --git a/src/services/bindings.ts b/src/services/bindings.ts index 8c2887493..89c74e223 100644 --- a/src/services/bindings.ts +++ b/src/services/bindings.ts @@ -621,7 +621,6 @@ export type NetworkInterfaceView_Serialize = { } export type NoticeStatus = - | 'info' | 'import_sub_url::ok' | 'import_sub_url::error' | 'set_config::error' diff --git a/src/services/notice-handlers.ts b/src/services/notice-handlers.ts index 3a8ff5eba..f633cbdf0 100644 --- a/src/services/notice-handlers.ts +++ b/src/services/notice-handlers.ts @@ -35,9 +35,6 @@ const handlers: Record< NoticeStatus, (msg: string, navigate: NavigateFunction) => void > = { - info: (msg) => { - if (msg) showNotice.info(msg) - }, 'import_sub_url::ok': (_msg, navigate) => { // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。 // 未来细分事件通知时,可以考虑传入订阅 ID 或其他标识符 diff --git a/src/services/update.ts b/src/services/update.ts index 16eea0773..f541aee11 100644 --- a/src/services/update.ts +++ b/src/services/update.ts @@ -3,51 +3,11 @@ import { type CheckOptions, type Update, } from '@tauri-apps/plugin-updater' -import { compareVersions as compareSemver } from 'compare-versions' -import { version as appVersion } from '@root/package.json' - -const normalizeVersion = (input: string | null | undefined): string | null => { - if (typeof input !== 'string') return null - const trimmed = input.trim() - if (!trimmed) return null - return trimmed.replace(/^v/i, '') -} - -const compareVersions = (a: string | null, b: string | null): number | null => { - if (!a || !b) return null - try { - return compareSemver(a, b) - } catch { - return null - } -} - -const localVersionNormalized = normalizeVersion(appVersion) - -export const checkUpdateSafe = async ( +// The plugin's version comparator is overridden in src-tauri/src/lib.rs, so an update +// returned by `check` is already installable and needs no extra filtering here. +export const checkForUpdate = async ( options?: CheckOptions, ): Promise => { - const result = await check(options ?? {}) - if (!result) return null - - const remoteVersion = result.version - const comparison = compareVersions(remoteVersion, localVersionNormalized) - - const isBuildToStable = - /^\d+\.\d+\.\d+\+[0-9A-Za-z.-]+$/.test(localVersionNormalized ?? '') && - remoteVersion === localVersionNormalized?.split('+')[0] - - if (comparison !== null && comparison <= 0 && !isBuildToStable) { - try { - await result.close() - } catch (err) { - console.warn('[updater] failed to close stale update resource', err) - } - return null - } - - return result + return check(options ?? {}) } - -export type { CheckOptions }