diff --git a/architecture/notes/pebrel_app/update_check/2026-09-25-custom-release-source.md b/architecture/notes/pebrel_app/update_check/2026-09-25-custom-release-source.md new file mode 100644 index 000000000..d442e0d1b --- /dev/null +++ b/architecture/notes/pebrel_app/update_check/2026-09-25-custom-release-source.md @@ -0,0 +1,39 @@ +# Configurable GitHub Release update source + +## Status + +Accepted for this PR. + +## Context + +Pebrel currently checks the official GitHub Releases feed only. Fork builds and preview releases need one optional source override without duplicating the updater pipeline. + +## Evidence + +The existing updater already owns asset selection, size limits, SHA-256 verification, streamed downloads, and platform install handoff. Only release discovery and trusted repository validation need to vary. + +## Decision + +Persist one optional `update_release_url`. Empty keeps `Kuddev/pebrel`. A custom value must be an HTTPS GitHub Releases URL. `releases` or `releases/latest` selects the repository's latest release; `releases/tag/` pins an exact release. + +The official source keeps its existing 403/429 public-page fallback. Custom sources use the GitHub API directly and do not add another fallback protocol. + +## Rejected alternatives + +A second updater implementation per source was rejected because it would duplicate asset selection, verification, and install logic. Arbitrary download URLs were rejected because they would weaken repository and asset validation. + +## Consequences + +Existing settings remain unchanged when the field is absent or empty. Changing the source invalidates assets from another repository during download validation. Custom sources must keep Pebrel's existing native package naming and SHA-256 metadata contract. + +## Validation + +CI covers the architecture note contract, Rust formatting, native tests, and updater tests. The parser also tests latest-release normalization, explicit prerelease tags, and rejection of non-GitHub release URLs. + +## Supersedes + +None. + +## Revisit when + +Revisit if Pebrel supports a non-GitHub release backend or if package identity and verification rules become source-specific. diff --git a/architecture/notes/pebrel_app/update_check/2026-09-28-update-source-result-lifetime.md b/architecture/notes/pebrel_app/update_check/2026-09-28-update-source-result-lifetime.md new file mode 100644 index 000000000..f573e36e5 --- /dev/null +++ b/architecture/notes/pebrel_app/update_check/2026-09-28-update-source-result-lifetime.md @@ -0,0 +1,61 @@ +# Update source result lifetime + +## Status + +Proposed with PR #294; maintainer review pending. + +## Context + +The configurable release source is read by manual checks, delayed startup checks, +and cached download hydration. A request can finish after the source changes or +Reset All restores the official source. Per-settings-pane sequencing protects +only one manual check and cannot invalidate startup work or results already queued +for another window. + +## Evidence + +- update_check::spawn_once and update_check::spawn_gpui_once publish background results. +- SettingsPane::check_for_updates can open its prompt after its state update. +- update_download::cancel invalidates the existing download generation, and + cached assets are validated against the configured source before reuse. +- The focused updater tests run through the repository's GitHub Actions workflows. + +## Decision + +Increment one process-local generation when the release source changes or all +settings reset. Each manual or startup check captures its generation and drops a +result when it is no longer current. GPUI update events carry the generation until +the main event dispatcher applies them. The About page also keeps its existing +per-pane sequence for repeated checks. Source invalidation clears the pane's +displayed check result and cancels the current download session. + +## Rejected alternatives + +Comparing source URLs alone would accept an old result if the setting changed +away and back while that request was running. Per-pane sequencing alone leaves +startup checks and another window's event queue unprotected. Cancelling every +network request would require new ownership across the synchronous release +fetcher; ignoring stale results uses the existing generation-based pattern. + +## Consequences + +Changing or resetting the source invalidates old results across all windows. +A check for the current generation remains usable. A stale cached asset does not +become installable because the existing asset validation still checks its source. + +## Validation + +The regression is +update_check::tests::invalidating_the_release_source_rejects_an_in_flight_result. +The PR description records GitHub Actions status for the final head; this note +does not claim UI end-to-end validation. + +## Supersedes + +None. This records result lifetime for +[the configurable release source](2026-09-25-custom-release-source.md). + +## Revisit when + +Revisit if release checks become cancellable and are actually cancelled on source +change, or if the updater moves source-generation ownership to another module. diff --git a/pebrel_app/i18n/en-US.json b/pebrel_app/i18n/en-US.json index 7029eef56..93110db64 100644 --- a/pebrel_app/i18n/en-US.json +++ b/pebrel_app/i18n/en-US.json @@ -1507,6 +1507,10 @@ "network": "Could not download the update. Check your network and proxy settings, or use the Releases page." }, "auto_download": "Download updates in the background", + "source_label": "Custom release source", + "source_invalid": "Enter an HTTPS GitHub Releases URL; add /tag/ to select a specific release.", + "source_asset_mismatch": "The update package does not match the selected release source. Check for updates again.", + "source_placeholder": "Blank = official · https://github.com/owner/repo/releases", "stop_download": "Stop download", "skip_version": "Skip version", "restart_install": "Restart and install", diff --git a/pebrel_app/i18n/zh-CN.json b/pebrel_app/i18n/zh-CN.json index d984b1849..e0cde3d03 100644 --- a/pebrel_app/i18n/zh-CN.json +++ b/pebrel_app/i18n/zh-CN.json @@ -1507,6 +1507,10 @@ "network": "无法下载更新。请检查网络和代理设置,或从发布页手动下载。" }, "auto_download": "在后台预下载更新", + "source_label": "自定义更新地址", + "source_invalid": "请输入 HTTPS GitHub Releases 地址;在末尾添加 /tag/ 可选择指定版本。", + "source_asset_mismatch": "更新安装包与所选更新源不匹配,请重新检查更新。", + "source_placeholder": "留空 = 官方源 · https://github.com/owner/repo/releases", "stop_download": "停止下载", "skip_version": "跳过此版本", "restart_install": "重启并安装", diff --git a/pebrel_app/src/gpui_shell/mod.rs b/pebrel_app/src/gpui_shell/mod.rs index a2eff652e..a99c47ee8 100644 --- a/pebrel_app/src/gpui_shell/mod.rs +++ b/pebrel_app/src/gpui_shell/mod.rs @@ -78,7 +78,7 @@ pub(crate) enum GpuiShellEvent { TrayQuit, MuxAttach, RuntimeControl(std::sync::Arc), - UpdateAvailable(crate::update_check::UpdateCheckResult), + UpdateAvailable { result: crate::update_check::UpdateCheckResult, source_generation: u64 }, SshPrompt(std::sync::Arc), OpenDirectories(Vec), ElevatedLaunch(std::sync::Arc), diff --git a/pebrel_app/src/gpui_shell/settings_pane.rs b/pebrel_app/src/gpui_shell/settings_pane.rs index 73e5e462a..02f3d2ea8 100644 --- a/pebrel_app/src/gpui_shell/settings_pane.rs +++ b/pebrel_app/src/gpui_shell/settings_pane.rs @@ -143,6 +143,7 @@ pub struct SettingsPane { about_update: AboutUpdateState, about_update_seq: u64, about_last_checked: Option, + update_release_input: Entity, /// 首页「项目与支持」→ 赞助商:独立页面,不是外链行。切换分区时清掉。 about_sponsor_open: bool, settings_search_input: Entity, @@ -366,6 +367,13 @@ impl SettingsPane { let placeholder = localized_input_placeholder(key, language); input.update(cx, |state, cx| state.set_placeholder(placeholder, window, cx)); } + self.update_release_input.update(cx, |state, cx| { + state.set_placeholder( + language.text(crate::i18n::Message::UpdateSourcePlaceholder), + window, + cx, + ) + }); self.settings_search_input.update(cx, |state, cx| { state.set_placeholder( language.text(crate::i18n::Message::CommonSearchSettings), @@ -1310,15 +1318,23 @@ impl SettingsPane { } self.about_update_seq = self.about_update_seq.wrapping_add(1); let sequence = self.about_update_seq; + let source_generation = crate::update_check::release_source_generation(); self.about_update = AboutUpdateState::Checking; let window_handle = window.window_handle(); let task = cx.background_executor().spawn(async { crate::update_check::check_now() }); cx.spawn(async move |this, cx| { let result = task.await; let prompt = result.as_ref().ok().filter(|result| result.update_available).cloned(); - let _ = this.update(cx, |pane, cx| { + let current = this.update(cx, |pane, cx| { if pane.about_update_seq != sequence { - return; + return false; + } + if !crate::update_check::release_source_is_current(source_generation) { + pane.about_update_seq = pane.about_update_seq.wrapping_add(1); + pane.about_update = AboutUpdateState::Idle; + pane.about_last_checked = None; + cx.notify(); + return false; } pane.about_last_checked = Some(chrono::Local::now().format("%Y-%m-%d %H:%M").to_string()); @@ -1330,9 +1346,16 @@ impl SettingsPane { Err(error) => AboutUpdateState::Failed(error), }; cx.notify(); + true }); + if !current.unwrap_or(false) { + return; + } if let Some(result) = prompt { let _ = window_handle.update(cx, move |_, window, cx| { + if !crate::update_check::release_source_is_current(source_generation) { + return; + } crate::gpui_shell::workspace::open_update_dialog(result, window, cx); }); } diff --git a/pebrel_app/src/gpui_shell/settings_pane/about.rs b/pebrel_app/src/gpui_shell/settings_pane/about.rs index d82abeff6..d83d98f6b 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/about.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/about.rs @@ -67,6 +67,41 @@ impl SettingsPane { .child(value) } + pub(super) fn invalidate_update_source(&mut self) { + self.about_update_seq = self.about_update_seq.wrapping_add(1); + crate::update_check::invalidate_release_source(); + self.about_update = AboutUpdateState::Idle; + self.about_last_checked = None; + if let Some(asset) = crate::update_download::cached_asset() { + crate::update_download::cancel(&asset); + } + } + + fn save_update_release_source(&mut self, window: &mut Window, cx: &mut Context) { + let language = crate::gpui_shell::config::ui_language(cx); + let raw = self.update_release_input.read(cx).value(); + match crate::update_check::normalize_setting(&raw) { + Some(value) => { + self.update_release_input + .update(cx, |input, cx| input.set_value(value.clone(), window, cx)); + if value != self.runtime.update_release_url { + self.persist(&[("update_release_url", value)], cx); + self.invalidate_update_source(); + } else { + self.about_update = AboutUpdateState::Idle; + self.about_last_checked = None; + } + }, + None => crate::gpui_shell::toast::toast( + window, + cx, + crate::gpui_shell::toast::ToastKind::Warning, + language.text(crate::i18n::Message::UpdateSourceInvalid).to_owned(), + ), + } + cx.notify(); + } + pub(super) fn section_home(&mut self, window: &Window, cx: &mut Context) -> gpui::Div { let language = crate::gpui_shell::config::ui_language(cx); let distribution = crate::platform::distribution::current(); @@ -233,6 +268,22 @@ impl SettingsPane { .on_click(cx.listener(|this, checked: &bool, _, cx| { this.persist(&[("auto_download_updates", (*checked as u8).to_string())], cx); })); + let update_source = h_flex() + .items_center() + .gap_2() + .child( + div() + .debug_selector(|| "update-release-source-input".to_owned()) + .w(px(240.0)) + .child(Input::new(&self.update_release_input).h(px(32.0))), + ) + .child( + NebulaButton::new("save-update-release-source") + .label(language.text(crate::i18n::Message::CommonSave)) + .on_click(cx.listener(|this, _, window, cx| { + this.save_update_release_source(window, cx); + })), + ); let last_checked: SharedString = self .about_last_checked .clone() @@ -272,15 +323,22 @@ impl SettingsPane { cx, )) .when(!managed, |column| { - column.child(Self::about_value_row( - language.text(crate::i18n::Message::SettingsAboutLastChecked), - div().text_color(muted).child(last_checked), - cx, - )) + column + .child(Self::about_value_row( + language.text(crate::i18n::Message::UpdateSourceLabel), + update_source, + cx, + )) + .child(Self::about_value_row( + language.text(crate::i18n::Message::SettingsAboutLastChecked), + div().text_color(muted).child(last_checked), + cx, + )) }) .when_some(distribution.message(), |column, message| { column.child(div().text_color(muted).child(language.text(message))) }); + let release_page = crate::update_check::release_page(); let actions = crate::gpui_shell::theme::settings_card(v_flex(), cx) .flex_1() .min_w(px(280.0)) @@ -305,7 +363,7 @@ impl SettingsPane { "about-releases", IconName::BookOpen, language.text(crate::i18n::Message::SettingsAboutReleaseNotes), - crate::update_check::RELEASES_PAGE.to_owned(), + release_page, cx, )) .child(Self::about_page_row( diff --git a/pebrel_app/src/gpui_shell/settings_pane/initialization.rs b/pebrel_app/src/gpui_shell/settings_pane/initialization.rs index 2591ce79d..8b5d635ee 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/initialization.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/initialization.rs @@ -615,6 +615,11 @@ impl SettingsPane { let appearance_interceptor = cx.listener(Self::intercept_appearance_picker); subscriptions.push(cx.intercept_keystrokes(appearance_interceptor)); + let update_release_input = cx.new(|cx| { + InputState::new(window, cx) + .placeholder(language.text(crate::i18n::Message::UpdateSourcePlaceholder)) + .default_value(runtime.update_release_url.clone()) + }); let settings_search_input = cx.new(|cx| { InputState::new(window, cx) .placeholder(language.text(crate::i18n::Message::CommonSearchSettings)) @@ -703,6 +708,7 @@ impl SettingsPane { about_update: AboutUpdateState::Idle, about_update_seq: 0, about_last_checked: None, + update_release_input, about_sponsor_open: false, settings_search_input, settings_search_focus: search_header::SearchFocus::default(), diff --git a/pebrel_app/src/gpui_shell/settings_pane/reset.rs b/pebrel_app/src/gpui_shell/settings_pane/reset.rs index 350658fbe..d49a7713a 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/reset.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/reset.rs @@ -47,9 +47,8 @@ impl SettingsPane { return; }, }; + self.invalidate_update_source(); let active_section = self.active_section; - let about_update = std::mem::replace(&mut self.about_update, AboutUpdateState::Idle); - let about_last_checked = self.about_last_checked.take(); let about_update_seq = self.about_update_seq; let proxy_test_seq = self.proxy_test_seq.wrapping_add(1); let provider_test_seq = self.provider_test_seq.wrapping_add(1); @@ -62,8 +61,6 @@ impl SettingsPane { cx.set_global(settings); *self = Self::new(window, cx); self.active_section = active_section; - self.about_update = about_update; - self.about_last_checked = about_last_checked; self.about_update_seq = about_update_seq; self.proxy_test_seq = proxy_test_seq; self.provider_test_seq = provider_test_seq; diff --git a/pebrel_app/src/gpui_shell/settings_pane/theme_studio_tests.rs b/pebrel_app/src/gpui_shell/settings_pane/theme_studio_tests.rs index dc0badc5d..0bb94819c 100644 --- a/pebrel_app/src/gpui_shell/settings_pane/theme_studio_tests.rs +++ b/pebrel_app/src/gpui_shell/settings_pane/theme_studio_tests.rs @@ -1408,22 +1408,6 @@ fn theme_picker_foreground_swatches_fit_above_footer_in_a_short_window(cx: &mut draw(&mut window); click("open-theme-picker", &mut window); - let preview = window.debug_bounds("theme-picker-terminal-preview").expect("theme preview"); - for selector in ["theme-preview-name", "theme-preview-mode"] { - let label = window.debug_bounds(selector).expect("preview caption"); - assert!( - f32::from(label.center().x - preview.center().x).abs() < 1.0, - "{selector} must be centered beneath the preview" - ); - } - let first = window.debug_bounds("theme-foreground-swatch-0").unwrap(); - let last = window.debug_bounds("theme-foreground-custom-swatch").unwrap(); - let swatch_center = (first.left() + last.right()) / 2.0; - assert!( - f32::from(swatch_center - preview.center().x).abs() < 1.0, - "the swatches must be centered as a group" - ); - let footer = window.debug_bounds("apply-appearance-picker").expect("appearance picker apply button"); for selector in [ @@ -1787,6 +1771,70 @@ fn theme_editor_save_only_forks_a_non_active_custom_template_without_publishing_ assert_eq!(settings_file_snapshot(), before_settings_file); } +#[gpui::test] +fn update_source_form_rejects_invalid_urls_and_persists_keyboard_edits(cx: &mut TestAppContext) { + let _fixture_guard = lock_theme_studio(); + let _settings_guard = SettingsBytesGuard::capture(); + std::fs::create_dir_all(nebula_settings::settings_dir()).unwrap(); + std::fs::write(nebula_settings::settings_path(), TEST_SETTINGS).unwrap(); + let (pane, mut window) = open_settings(cx); + pane.update(&mut window, |pane, cx| { + pane.active_section = 0; + cx.notify(); + }); + draw(&mut window); + let generation = crate::update_check::release_source_generation(); + let selector = "update-release-source-input"; + let bounds = window.debug_bounds(selector).expect("source input is visible"); + assert!(f32::from(bounds.size.width) >= 200.0); + assert!(f32::from(bounds.size.height) >= 28.0); + click(selector, &mut window); + window.simulate_input("https://example.com/acme/pebrel/releases"); + draw(&mut window); + assert_eq!( + pane.read_with(&mut window, |pane, cx| pane.update_release_input.read(cx).value()), + "https://example.com/acme/pebrel/releases" + ); + click("nebula-btn-save-update-release-source", &mut window); + assert!(RuntimeSettings::load().update_release_url.is_empty()); + assert!(crate::update_check::release_source_is_current(generation)); + click(selector, &mut window); + let select_all = match crate::platform::Platform::current() { + crate::platform::Platform::MacOS => "cmd-a", + _ => "ctrl-a", + }; + window.simulate_keystrokes(select_all); + window.simulate_input("https://github.com/acme/pebrel/releases/latest/"); + draw(&mut window); + click("nebula-btn-save-update-release-source", &mut window); + assert_eq!( + RuntimeSettings::load().update_release_url, + "https://github.com/acme/pebrel/releases" + ); + assert!(!crate::update_check::release_source_is_current(generation)); + pane.read_with(&mut window, |pane, cx| { + assert_eq!( + pane.update_release_input.read(cx).value(), + RuntimeSettings::load().update_release_url + ); + assert!(matches!(pane.about_update, AboutUpdateState::Idle)); + assert!(pane.about_last_checked.is_none()); + }); + let reopened = window.update(|window, cx| cx.new(|cx| SettingsPane::new(window, cx))); + reopened.read_with(&mut window, |pane, cx| { + assert_eq!( + pane.update_release_input.read(cx).value(), + RuntimeSettings::load().update_release_url + ); + }); + click(selector, &mut window); + window.simulate_keystrokes(select_all); + window.simulate_keystrokes("backspace"); + draw(&mut window); + click("nebula-btn-save-update-release-source", &mut window); + assert!(RuntimeSettings::load().update_release_url.is_empty()); +} + #[gpui::test] fn theme_list_scroll_keeps_preview_visible_and_narrow_picker_accessible(cx: &mut TestAppContext) { let _fixture_guard = lock_theme_studio(); diff --git a/pebrel_app/src/gpui_shell/workspace/residency.rs b/pebrel_app/src/gpui_shell/workspace/residency.rs index 8b8d5d320..6a7eebd30 100644 --- a/pebrel_app/src/gpui_shell/workspace/residency.rs +++ b/pebrel_app/src/gpui_shell/workspace/residency.rs @@ -146,7 +146,7 @@ impl NebulaWorkspace { }, // 更新通知由进程级 windowing dispatcher 选择 MRU 窗口;这个 // 旧的 workspace-local 分发器没有 Window,不能在此打开 Dialog。 - GpuiShellEvent::UpdateAvailable(_) + GpuiShellEvent::UpdateAvailable { .. } | GpuiShellEvent::SshPrompt(_) | GpuiShellEvent::OpenDirectories(_) => {}, } diff --git a/pebrel_app/src/gpui_shell/workspace/update_dialog.rs b/pebrel_app/src/gpui_shell/workspace/update_dialog.rs index 4fec14808..5ad23ce57 100644 --- a/pebrel_app/src/gpui_shell/workspace/update_dialog.rs +++ b/pebrel_app/src/gpui_shell/workspace/update_dialog.rs @@ -74,7 +74,7 @@ fn start_update_download( cx: &mut App, ) { let Some(asset) = result.asset().cloned() else { - cx.open_url(result.manual_download_url()); + cx.open_url(&result.manual_download_url()); return; }; let job = match crate::update_download::begin(&asset) { @@ -416,7 +416,7 @@ pub(crate) fn open_update_dialog( .child(body) .on_ok(move |_, window, cx| { let Some(asset) = action_result.asset() else { - cx.open_url(action_result.manual_download_url()); + cx.open_url(&action_result.manual_download_url()); return true; }; match crate::update_download::status(asset) { @@ -435,7 +435,7 @@ pub(crate) fn open_update_dialog( false }, _ => { - cx.open_url(action_result.manual_download_url()); + cx.open_url(&action_result.manual_download_url()); true }, } diff --git a/pebrel_app/src/gpui_shell/workspace/windowing.rs b/pebrel_app/src/gpui_shell/workspace/windowing.rs index c0986a7e8..94d023070 100644 --- a/pebrel_app/src/gpui_shell/workspace/windowing.rs +++ b/pebrel_app/src/gpui_shell/workspace/windowing.rs @@ -807,7 +807,10 @@ pub(crate) fn dispatch_shell_events(events: Vec, cx: &mut App) { }, GpuiShellEvent::RuntimeControl(dispatch) => dispatch_runtime(dispatch, cx), GpuiShellEvent::ElevatedLaunch(request) => elevated_launch::dispatch(request, cx), - GpuiShellEvent::UpdateAvailable(result) => { + GpuiShellEvent::UpdateAvailable { result, source_generation } => { + if !crate::update_check::release_source_is_current(source_generation) { + continue; + } let Some(entry) = entries_by_mru(cx).into_iter().next() else { continue }; let _ = entry.handle.update(cx, move |_, window, cx| { super::show_update_notification(result, window, cx); diff --git a/pebrel_app/src/update_check.rs b/pebrel_app/src/update_check.rs index c5a67c119..56994f82c 100644 --- a/pebrel_app/src/update_check.rs +++ b/pebrel_app/src/update_check.rs @@ -5,7 +5,7 @@ //! GitHub outage all degrade to "no banner", never to an error the user sees. use std::sync::Mutex; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; @@ -17,18 +17,35 @@ use crate::event::{Event, EventType}; #[cfg(feature = "legacy-shell")] use crate::message_bar::{Message, MessageType}; -const RELEASES_API: &str = "https://api.github.com/repos/Kuddev/pebrel/releases/latest"; pub const RELEASES_PAGE: &str = "https://github.com/Kuddev/pebrel/releases"; const UPDATE_STATE_FILE: &str = "update_state.json"; const REMIND_LATER_SECS: u64 = 3 * 24 * 60 * 60; pub(crate) mod assets; mod fallback; +mod source; + +#[cfg(test)] +pub(crate) use source::validate_official_asset_url; +pub(crate) use source::{normalize_setting, release_page, validate_asset_url}; #[cfg(feature = "update-test-source")] pub(crate) mod test_source; static UPDATE_STATE_LOCK: Mutex<()> = Mutex::new(()); +static RELEASE_SOURCE_GENERATION: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn release_source_generation() -> u64 { + RELEASE_SOURCE_GENERATION.load(Ordering::SeqCst) +} + +pub(crate) fn release_source_is_current(generation: u64) -> bool { + release_source_generation() == generation +} + +pub(crate) fn invalidate_release_source() { + RELEASE_SOURCE_GENERATION.fetch_add(1, Ordering::SeqCst); +} /// 自动提示状态独立于通用设置文件,避免后台版本检查改写用户设置正文。 /// 字段按版本生效,新版本不会继承旧版本的延迟或跳过选择。 @@ -144,8 +161,8 @@ impl UpdateCheckResult { } } - pub(crate) fn manual_download_url(&self) -> &str { - self.portable_zip_url().unwrap_or(RELEASES_PAGE) + pub(crate) fn manual_download_url(&self) -> String { + self.portable_zip_url().map_or_else(release_page, str::to_owned) } } @@ -188,6 +205,7 @@ pub fn spawn_once(proxy: EventLoopProxy) { let spawned = std::thread::Builder::new().name("update-check".into()).spawn(move || { // 等窗口与首个会话安顿好再查,别和启动抢磁盘/网络。 std::thread::sleep(Duration::from_secs(12)); + let source_generation = release_source_generation(); let release = match fetch_latest_release() { Ok(release) => release, Err(error) => { @@ -201,7 +219,10 @@ pub fn spawn_once(proxy: EventLoopProxy) { log::debug!("update-check: v{current} is current (latest v{latest})"); return; } - let text = format!("Pebrel v{latest} 已发布(当前 v{current}),下载:{RELEASES_PAGE}"); + let text = format!("Pebrel v{latest} 已发布(当前 v{current}),下载:{}", release_page()); + if !release_source_is_current(source_generation) { + return; + } let _ = proxy.send_event(Event::new( EventType::Message(Message::new(text, MessageType::Warning)), None, @@ -224,6 +245,7 @@ pub fn spawn_gpui_once(sender: std::sync::mpsc::Sender result, Err(error) => { @@ -262,7 +286,11 @@ pub fn spawn_gpui_once(sender: std::sync::mpsc::Sender Result { let agent = test_source::agent(Duration::from_secs(10)); return fetch_release_with_agent(&agent, &url); } - let agent = crate::update_proxy::agent(RELEASES_API, Duration::from_secs(10)) + let source = source::configured()?; + let api = source.api_url(); + let agent = crate::update_proxy::agent(&api, Duration::from_secs(10)) .map_err(|error| format!("GitHub 请求失败:{error}"))?; - fetch_release_with_fallback(&agent, RELEASES_API, fallback::fetch_latest) + if source.is_default() { + fetch_release_with_fallback(&agent, &api, fallback::fetch_latest) + } else { + fetch_release_with_fallback(&agent, &api, |status| Err(format!("GitHub HTTP {status}"))) + } } #[cfg(any(test, feature = "update-test-source"))] @@ -387,9 +421,15 @@ fn parse_latest_release(bytes: &[u8]) -> Result { fn decode_release(bytes: &[u8]) -> Result<(GitHubRelease, String), String> { let release: GitHubRelease = serde_json::from_slice(bytes).map_err(|error| format!("GitHub 返回了无效数据:{error}"))?; - let version = release.tag_name.trim().trim_start_matches(['v', 'V']); - if version.is_empty() { - return Err("GitHub release 的版本号为空".to_owned()); + let tag = release.tag_name.trim(); + let version = tag.strip_prefix('v').or_else(|| tag.strip_prefix('V')).unwrap_or(tag); + if version.is_empty() + || !version.as_bytes().first().is_some_and(|byte| byte.is_ascii_digit()) + || !version + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+')) + { + return Err("GitHub release 的版本号无效".to_owned()); } let version = version.to_owned(); Ok((release, version)) @@ -502,6 +542,13 @@ pub(crate) fn is_newer(latest: &str, current: &str) -> bool { #[cfg(test)] mod tests { + #[test] + fn invalidating_the_release_source_rejects_an_in_flight_result() { + let generation = super::release_source_generation(); + super::invalidate_release_source(); + assert!(!super::release_source_is_current(generation)); + } + #[test] fn release_check_uses_the_resolved_proxy_for_an_unresolvable_target() { use crate::update_proxy::test_support::{Server, response}; @@ -595,6 +642,13 @@ mod tests { assert!(super::version_is_installable("1.8.0", "1.8.0", true)); } + #[test] + fn release_parser_accepts_semver_style_prerelease_tags() { + let release = parse_latest_release(br#"{"tag_name":"v2.0.0-beta.1","assets":[]}"#).unwrap(); + assert_eq!(release.version, "2.0.0-beta.1"); + assert!(parse_latest_release(br#"{"tag_name":"preview-v2.0.0","assets":[]}"#).is_err()); + } + #[test] fn version_comparison_is_numeric_per_segment() { assert!(is_newer("0.7.1", "0.7.0")); diff --git a/pebrel_app/src/update_check/source.rs b/pebrel_app/src/update_check/source.rs new file mode 100644 index 000000000..7d8a8db17 --- /dev/null +++ b/pebrel_app/src/update_check/source.rs @@ -0,0 +1,160 @@ +use super::{RELEASES_PAGE, UpdateAsset}; +use crate::i18n::{LanguagePreference, Message}; + +const GITHUB: &str = "https://github.com/"; +const OFFICIAL: &str = "Kuddev/pebrel"; +const LEGACY: &str = "Kuddev/nebula"; + +pub(super) struct ReleaseSource { + repo: String, + tag: Option, +} + +impl ReleaseSource { + fn official() -> Self { + Self { repo: OFFICIAL.into(), tag: None } + } + + fn parse(value: &str) -> Option { + let value = value.trim().trim_end_matches('/'); + if value.is_empty() { + return Some(Self::official()); + } + let path = value.strip_prefix(GITHUB)?; + if path.contains('?') || path.contains('#') { + return None; + } + let (repo_path, tag) = if let Some(repo) = path.strip_suffix("/releases/latest") { + (repo, None) + } else if let Some(repo) = path.strip_suffix("/releases") { + (repo, None) + } else if let Some((repo, tag)) = path.split_once("/releases/tag/") { + (repo, Some(tag)) + } else { + return None; + }; + let (owner, repo) = repo_path.split_once('/')?; + if repo.contains('/') + || !component(owner) + || !component(repo) + || tag.is_some_and(|tag| !tag_name(tag)) + { + return None; + } + Some(Self { repo: format!("{owner}/{repo}"), tag: tag.map(str::to_owned) }) + } + + pub(super) fn is_default(&self) -> bool { + self.repo == OFFICIAL && self.tag.is_none() + } + + pub(super) fn api_url(&self) -> String { + match &self.tag { + Some(tag) => format!("https://api.github.com/repos/{}/releases/tags/{tag}", self.repo), + None => format!("https://api.github.com/repos/{}/releases/latest", self.repo), + } + } + + fn page(&self) -> String { + match &self.tag { + Some(tag) => format!("{GITHUB}{}/releases/tag/{tag}", self.repo), + None if self.is_default() => RELEASES_PAGE.into(), + None => format!("{GITHUB}{}/releases", self.repo), + } + } + + fn accepts(&self, asset: &UpdateAsset) -> bool { + if self.is_default() { + return [OFFICIAL, LEGACY].iter().any(|repo| { + asset.download_url + == format!("{GITHUB}{repo}/releases/download/v{}/{}", asset.version, asset.name) + }); + } + let prefix = format!("{GITHUB}{}/releases/download/", self.repo); + let Some(path) = asset.download_url.strip_prefix(&prefix) else { + return false; + }; + let mut parts = path.split('/'); + let (Some(tag), Some(name), None) = (parts.next(), parts.next(), parts.next()) else { + return false; + }; + name == asset.name && tag_name(tag) && self.tag.as_deref().is_none_or(|value| value == tag) + } +} + +fn component(value: &str) -> bool { + !matches!(value, "" | "." | "..") + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')) +} + +fn tag_name(value: &str) -> bool { + !matches!(value, "" | "." | "..") + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'+')) +} + +pub(super) fn configured() -> Result { + let settings = pebrel_settings::RuntimeSettings::load(); + let language = settings.language; + ReleaseSource::parse(&settings.update_release_url).ok_or_else(|| { + LanguagePreference::from(language).resolved().text(Message::UpdateSourceInvalid).to_owned() + }) +} + +pub(crate) fn normalize_setting(value: &str) -> Option { + let source = ReleaseSource::parse(value)?; + Some(if source.is_default() { String::new() } else { source.page() }) +} + +pub(crate) fn release_page() -> String { + configured().map(|source| source.page()).unwrap_or_else(|_| RELEASES_PAGE.into()) +} + +pub(crate) fn validate_asset_url(asset: &UpdateAsset) -> Result<(), String> { + configured()?.accepts(asset).then_some(()).ok_or_else(|| { + LanguagePreference::from(pebrel_settings::RuntimeSettings::load().language) + .resolved() + .text(Message::UpdateSourceAssetMismatch) + .to_owned() + }) +} + +#[cfg(test)] +pub(crate) fn validate_official_asset_url(asset: &UpdateAsset) -> Result<(), String> { + ReleaseSource::official() + .accepts(asset) + .then_some(()) + .ok_or_else(|| "release 安装包 URL 不属于 Pebrel 官方仓库".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_source_normalizes_and_pins_explicit_tags() { + assert_eq!( + normalize_setting("https://github.com/acme/pebrel/releases/latest").unwrap(), + "https://github.com/acme/pebrel/releases" + ); + assert!(normalize_setting("https://example.com/acme/pebrel/releases").is_none()); + + let source = + ReleaseSource::parse("https://github.com/acme/pebrel/releases/tag/v2.0.0-beta.1") + .unwrap(); + let asset = |tag: &str| UpdateAsset { + version: "2.0.0-beta.1".into(), + name: "Pebrel-v2.0.0-beta.1-windows-x64-setup.exe".into(), + download_url: format!( + "https://github.com/acme/pebrel/releases/download/{tag}/Pebrel-v2.0.0-beta.1-windows-x64-setup.exe" + ), + size: Some(42), + sha256: Some("a".repeat(64)), + }; + assert!(source.accepts(&asset("v2.0.0-beta.1"))); + assert!(!source.accepts(&asset("v2.0.0-beta.2"))); + } +} diff --git a/pebrel_app/src/update_download.rs b/pebrel_app/src/update_download.rs index aa72e5d02..cbbdc6f73 100644 --- a/pebrel_app/src/update_download.rs +++ b/pebrel_app/src/update_download.rs @@ -20,7 +20,9 @@ use sha2::{Digest as _, Sha256}; use crate::i18n::{Message, UiLanguage}; use crate::update_check::UpdateAsset; +#[cfg(test)] const RELEASE_DOWNLOAD_PREFIX: &str = "https://github.com/Kuddev/pebrel/releases/download/"; +#[cfg(test)] const LEGACY_RELEASE_DOWNLOAD_PREFIX: &str = "https://github.com/Kuddev/nebula/releases/download/"; const MAX_INSTALLER_BYTES: u64 = 512 * 1024 * 1024; const DOWNLOAD_CHUNK_BYTES: usize = 64 * 1024; @@ -430,13 +432,24 @@ fn validate_asset(asset: &UpdateAsset) -> Result<(), String> { #[cfg(test)] fn validate_windows_asset_contract(asset: &UpdateAsset) -> Result<(), String> { - validate_asset_contract( + validate_asset_contract_official( asset, &crate::update_check::windows_x64_installer_names(&asset.version), ) } +#[cfg(test)] +fn validate_asset_contract_official(asset: &UpdateAsset, names: &[String]) -> Result<(), String> { + validate_asset_metadata(asset, names)?; + crate::update_check::validate_official_asset_url(asset) +} + fn validate_asset_contract(asset: &UpdateAsset, names: &[String]) -> Result<(), String> { + validate_asset_metadata(asset, names)?; + crate::update_check::validate_asset_url(asset) +} + +fn validate_asset_metadata(asset: &UpdateAsset, names: &[String]) -> Result<(), String> { if asset.version.is_empty() || !asset .version @@ -448,12 +461,6 @@ fn validate_asset_contract(asset: &UpdateAsset, names: &[String]) -> Result<(), if !names.contains(&asset.name) { return Err("release 资产不是当前平台的精确安装包".to_owned()); } - let trusted_url = [RELEASE_DOWNLOAD_PREFIX, LEGACY_RELEASE_DOWNLOAD_PREFIX] - .iter() - .any(|prefix| asset.download_url == format!("{prefix}v{}/{}", asset.version, asset.name)); - if !trusted_url { - return Err("release 安装包 URL 不属于 Pebrel 官方仓库".to_owned()); - } if asset.size.is_some_and(|bytes| bytes == 0 || bytes > MAX_INSTALLER_BYTES) { return Err("release 安装包大小无效".to_owned()); } @@ -781,10 +788,10 @@ mod macos_package_tests { size: Some(bytes.len() as u64), sha256: Some(Sha256::digest(&bytes).iter().map(|byte| format!("{byte:02x}")).collect()), }; - validate_asset_contract(&asset, &names).unwrap(); + validate_asset_contract_official(&asset, &names).unwrap(); verify_file(&path, &asset).unwrap(); assert!( - validate_asset_contract( + validate_asset_contract_official( &asset, &crate::update_check::assets::macos_names("1.9.1", "x86_64") ) @@ -797,6 +804,6 @@ mod macos_package_tests { Some(Sha256::digest(&bytes).iter().map(|byte| format!("{byte:02x}")).collect()); assert!(verify_file(&path, &asset).unwrap_err().contains("trailer")); asset.download_url = "https://example.invalid/image.dmg".into(); - assert!(validate_asset_contract(&asset, &names).is_err()); + assert!(validate_asset_contract_official(&asset, &names).is_err()); } } diff --git a/pebrel_settings/src/lib.rs b/pebrel_settings/src/lib.rs index f642b5eac..071a85bba 100644 --- a/pebrel_settings/src/lib.rs +++ b/pebrel_settings/src/lib.rs @@ -1090,6 +1090,9 @@ pub struct RuntimeSettings { pub auto_check_updates: bool, /// Optional background package download; never grants install permission. pub auto_download_updates: bool, + /// Optional GitHub Releases page used instead of the official stable source. + /// Empty keeps the built-in Kuddev/pebrel update source. + pub update_release_url: String, pub keep_session: bool, /// Start the first window hidden when a system tray is available and enabled. pub silent_start: bool, @@ -1299,6 +1302,7 @@ impl RuntimeSettings { fetch: raw.bool_on("fetch").unwrap_or(false), auto_check_updates: raw.bool_on("auto_check_updates").unwrap_or(true), auto_download_updates: raw.bool_on("auto_download_updates").unwrap_or(false), + update_release_url: raw.value("update_release_url").unwrap_or_default().to_owned(), keep_session: raw.bool_on("keep_session").unwrap_or(false), silent_start: raw.bool_on("silent_start").unwrap_or(false), restore_session: raw.bool_on("restore_session").unwrap_or(true), @@ -1453,6 +1457,19 @@ mod tests { ); } + #[test] + fn update_release_url_round_trips_and_defaults_to_empty() { + let defaults = RuntimeSettings::from_raw(&RawSettings::default()); + assert!(defaults.update_release_url.is_empty()); + let settings = RuntimeSettings::from_raw(&RawSettings::from_text( + "update_release_url=https://github.com/acme/pebrel/releases/tag/v2.0.0-beta.1\n", + )); + assert_eq!( + settings.update_release_url, + "https://github.com/acme/pebrel/releases/tag/v2.0.0-beta.1" + ); + } + #[test] fn empty_quick_terminal_hotkey_is_distinct_from_an_unset_preference() { let unset = RuntimeSettings::from_raw(&RawSettings::from_text("theme=Nord\n")); diff --git a/pebrel_settings/src/reset.rs b/pebrel_settings/src/reset.rs index 2838a0e25..b118c8177 100644 --- a/pebrel_settings/src/reset.rs +++ b/pebrel_settings/src/reset.rs @@ -56,6 +56,7 @@ const RESET_KEYS: &[&str] = &[ "fetch", "auto_check_updates", "auto_download_updates", + "update_release_url", "keep_session", "restore_session", "resume_ai",