From a18c9f4b2297f71d5eab4aa5bd90d7a82de2ecb9 Mon Sep 17 00:00:00 2001 From: rgxdev Date: Tue, 17 Nov 2026 10:07:01 +0100 Subject: [PATCH 1/4] fix(windows): find install and data folders after a profile move The installer reused the folder an earlier install recorded, which PrepareToInstall then refused once the user profile had moved to another drive; it now always takes the current Local AppData. Without LOCALAPPDATA in its environment Tarn kept its data in the folder it was started from; it now falls back to the Local AppData known folder, the one the installer and uninstaller use. The installed tarn.exe re-points an earlier Make Default registration that names another path. Signed-off-by: rgxdev --- CHANGELOG.md | 7 +++ crates/app/src/browser.rs | 5 +- crates/app/src/lib.rs | 2 + crates/engine/src/host_windows.rs | 77 +++++++++++++++++++++++++------ crates/engine/src/lib.rs | 4 +- crates/store/src/db.rs | 4 +- docs/windows-plan.md | 7 ++- packaging/windows/tarn.iss | 2 + 8 files changed, 87 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 920df89e..4374807e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,13 @@ All notable changes to Tarn are documented in this file. The format is based on - The privacy notice names Quavon UG (haftungsbeschränkt) as controller, gives the legal basis and your rights, and states per client what it describes. +### Fixed + +- Windows: the installer always installs into the current user's `AppData\Local\Programs\Tarn`, + also after the user profile moved to another drive, and a link set up with Make Default follows + the install to its new folder. Without `LOCALAPPDATA` in its environment, Tarn keeps its data in + the Local AppData folder Windows reports instead of the folder it was started from. + ### Security - On Android, Tarn's own requests and file downloads refuse a server whose verified certificate diff --git a/crates/app/src/browser.rs b/crates/app/src/browser.rs index b26010f4..0b950bd4 100644 --- a/crates/app/src/browser.rs +++ b/crates/app/src/browser.rs @@ -137,7 +137,10 @@ pub(crate) type Core = browser_core::Core; pub(crate) type ProfileRuntime = browser_core::ProfileRuntime; pub(crate) fn data_dir() -> PathBuf { - browser_core::data_dir(None).unwrap_or_default() + let dir = browser_core::data_dir(None); + #[cfg(windows)] + let dir = dir.or_else(|| Some(engine::local_app_data()?.join("Tarn"))); + dir.unwrap_or_default() } /// Purges Chromium's data when its owner is gone or a purge is pending; before CEF starts or once it is gone. diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index 19fc216c..30802f0c 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -465,6 +465,8 @@ pub fn run() { } #[cfg(windows)] engine::chromium::prepare_browser_process(); + #[cfg(windows)] + engine::refresh_browser_registration(); engine::startup::mark("main"); record_panics(browser::data_dir()); #[cfg(feature = "chromium")] diff --git a/crates/engine/src/host_windows.rs b/crates/engine/src/host_windows.rs index 91bafdee..2bec72b6 100644 --- a/crates/engine/src/host_windows.rs +++ b/crates/engine/src/host_windows.rs @@ -1,14 +1,16 @@ +use std::path::PathBuf; + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use url::Url; use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM}; use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, CreateRoundRectRgn, ScreenToClient, SetWindowRgn}; -use windows_sys::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx}; +use windows_sys::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoTaskMemFree}; use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegGetValueW, RegSetKeyValueW}; use windows_sys::Win32::UI::HiDpi::GetDpiForWindow; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, GetKeyState, SetFocus, VK_MENU, VK_SHIFT}; use windows_sys::Win32::UI::Shell::{ - DefSubclassProc, ILCreateFromPathW, ILFree, RemoveWindowSubclass, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify, SHOpenFolderAndSelectItems, - SetWindowSubclass, ShellExecuteW, + DefSubclassProc, FOLDERID_LocalAppData, ILCreateFromPathW, ILFree, RemoveWindowSubclass, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify, + SHGetKnownFolderPath, SHOpenFolderAndSelectItems, SetWindowSubclass, ShellExecuteW, }; use windows_sys::Win32::UI::WindowsAndMessaging::{ GWLP_HWNDPARENT, GetClientRect, GetForegroundWindow, GetWindowRect, GetWindowThreadProcessId, HTTRANSPARENT, HWND_TOP, MB_ICONWARNING, MB_OK, MessageBoxW, @@ -245,7 +247,7 @@ fn set_value(key: &str, name: Option<&str>, value: &str) -> bool { fn value(key: &str, name: &str) -> Option { let (key, name) = (wide(key), wide(name)); - let mut buffer = [0u16; 256]; + let mut buffer = [0u16; 2048]; let mut size = u32::try_from(size_of_val(&buffer)).unwrap_or(0); // SAFETY: NUL-terminated strings; `buffer` holds `size` bytes, and RRF_RT_REG_SZ ends it with NUL. let status = @@ -262,10 +264,37 @@ pub fn is_default_browser() -> bool { /// settings at it; Windows lets only the user make the choice, so the result shows later in /// `is_default_browser`. pub fn make_default_browser() { - let Some(exe) = std::env::current_exe().ok().and_then(|p| p.to_str().map(str::to_owned)) else { return }; - // Chromium, which parses this command line first, takes everything after the marker as one - // URL, so a link cannot add switches. - let command = format!("\"{exe}\" {SINGLE_ARGUMENT} %1"); + if !register_browser() { + return; + } + let (verb, target) = (wide("open"), wide("ms-settings:defaultapps?registeredAppUser=Tarn")); + // SAFETY: NUL-terminated strings that outlive the call. + unsafe { ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), target.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL) }; +} + +/// Points an earlier Make Default at the installed `tarn.exe` once the install folder moved, as it +/// does when the user profile moves to another drive. Development builds leave it alone. +pub fn refresh_browser_registration() { + let (Some(exe), Some(installed)) = (exe(), local_app_data().map(|d| d.join(r"Programs\Tarn\tarn.exe"))) else { return }; + let registered = value(&format!(r"Software\Classes\{PROG_ID}\shell\open\command"), ""); + if exe.eq_ignore_ascii_case(&installed.to_string_lossy()) && registered.is_some_and(|c| !c.eq_ignore_ascii_case(&open_command(&exe))) { + register_browser(); + } +} + +fn exe() -> Option { + std::env::current_exe().ok().and_then(|p| p.to_str().map(str::to_owned)) +} + +/// Chromium, which parses this command line first, takes everything after the marker as one URL, +/// so a link cannot add switches. +fn open_command(exe: &str) -> String { + format!("\"{exe}\" {SINGLE_ARGUMENT} %1") +} + +fn register_browser() -> bool { + let Some(exe) = exe() else { return false }; + let command = open_command(&exe); let classes = format!(r"Software\Classes\{PROG_ID}"); let registered = set_value(&classes, None, "Tarn URL") && set_value(&format!(r"{classes}\DefaultIcon"), None, &format!("{exe},0")) @@ -276,14 +305,32 @@ pub fn make_default_browser() { && set_value(&format!(r"{CLIENT}\Capabilities"), Some("ApplicationDescription"), "A private web browser.") && ["http", "https"].iter().all(|scheme| set_value(&format!(r"{CLIENT}\Capabilities\URLAssociations"), Some(scheme), PROG_ID)) && set_value(r"Software\RegisteredApplications", Some("Tarn"), &format!(r"{CLIENT}\Capabilities")); - if !registered { - return; + if registered { + // SAFETY: tells the shell file associations changed; no item arguments. + unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED as i32, SHCNF_IDLIST, std::ptr::null(), std::ptr::null()) }; } - // SAFETY: tells the shell file associations changed; no item arguments. - unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED as i32, SHCNF_IDLIST, std::ptr::null(), std::ptr::null()) }; - let (verb, target) = (wide("open"), wide("ms-settings:defaultapps?registeredAppUser=Tarn")); - // SAFETY: NUL-terminated strings that outlive the call. - unsafe { ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), target.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL) }; + registered +} + +/// The user's Local AppData folder as the shell resolves it, the folder the installer uses too; +/// for when `LOCALAPPDATA` is missing from the environment. +pub fn local_app_data() -> Option { + known_folder(&FOLDERID_LocalAppData) +} + +fn known_folder(id: &windows_sys::core::GUID) -> Option { + use std::os::windows::ffi::OsStringExt; + let mut path: windows_sys::core::PWSTR = std::ptr::null_mut(); + // SAFETY: `path` receives a NUL-terminated string the shell allocates, freed below. + let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &mut path) }; + let dir = (status >= 0 && !path.is_null()).then(|| { + // SAFETY: `path` is a valid NUL-terminated wide string until it is freed below. + let units = unsafe { std::slice::from_raw_parts(path, (0..).take_while(|&i| *path.add(i) != 0).count()) }; + PathBuf::from(std::ffi::OsString::from_wide(units)) + }); + // SAFETY: frees the shell's allocation; null is allowed. + unsafe { CoTaskMemFree(path.cast()) }; + dir.filter(|d| d.is_absolute()) } /// A modal alert for when no window can show the message; returns once the user dismisses it. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3f4cc56d..543b8c87 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -83,8 +83,8 @@ pub use data_store_windows::{DataStore, FilterLists, builtin_rules_failed}; pub use events::{Event, Protection}; #[cfg(windows)] pub use host_windows::{ - Host, MIN_ZOOM, Popup, alert, app_active, bundle_identifier, is_default_browser, make_default_browser, open_external, option_held, reduce_motion, - reveal_in_finder, shift_held, + Host, MIN_ZOOM, Popup, alert, app_active, bundle_identifier, is_default_browser, local_app_data, make_default_browser, open_external, option_held, + reduce_motion, refresh_browser_registration, reveal_in_finder, shift_held, }; pub use nav_policy::SiteFor; #[cfg(any(target_os = "macos", windows))] diff --git a/crates/store/src/db.rs b/crates/store/src/db.rs index 51492a68..71628ca6 100644 --- a/crates/store/src/db.rs +++ b/crates/store/src/db.rs @@ -295,8 +295,8 @@ pub struct Store { impl Store { pub fn open(dir: &Path) -> Result { let path = dir.join("tarn.db"); - // Windows: the data folder lives under %LOCALAPPDATA%, whose inherited ACL already admits - // only the user, SYSTEM and Administrators. + // Windows: the data folder lives under the user's Local AppData, whose inherited ACL + // already admits only the user, SYSTEM and Administrators. #[cfg(unix)] { DirBuilder::new().recursive(true).mode(0o700).create(dir)?; diff --git a/docs/windows-plan.md b/docs/windows-plan.md index 93e812f9..10d3c866 100644 --- a/docs/windows-plan.md +++ b/docs/windows-plan.md @@ -46,7 +46,12 @@ WebView2 plan and are kept for the security mapping; where they disagree, this s another window), GPUI gets a move just outside it, which clears the hover it would otherwise keep. Key presses with Ctrl or Alt (except editing keys) also go to GPUI. - **Platform:** AI token in the Credential Manager, memory pressure from `GlobalMemoryStatusEx`, - data in `%LOCALAPPDATA%\Tarn` (user-only ACL inherited, no Unix modes). + data in `%LOCALAPPDATA%\Tarn`, or the shell's Local AppData known folder (the one the installer + and uninstaller use) when the variable is missing (user-only ACL inherited, no Unix modes). The + installer needs no administrator rights and always installs into the current + `{localappdata}\Programs\Tarn` (`UsePreviousAppDir=no`); at start the installed `tarn.exe` + re-points an earlier Make Default registration that names another path, a development build's + included. - **Window and input:** the toolbar and the settings header are the caption (the hook starts the system move; a double click maximizes), with Windows minimize/maximize/close buttons. Pop-ups opened without focus (address suggestions, hover cards, peek) stay inactive until clicked, diff --git a/packaging/windows/tarn.iss b/packaging/windows/tarn.iss index 74ccf4d9..7b6d1ea9 100644 --- a/packaging/windows/tarn.iss +++ b/packaging/windows/tarn.iss @@ -22,6 +22,8 @@ VersionInfoVersion={#AppVersion} PrivilegesRequired=lowest DefaultDirName={localappdata}\Programs\Tarn DisableDirPage=yes +; A profile moved to another drive or renamed would otherwise get the old folder, which PrepareToInstall refuses. +UsePreviousAppDir=no DisableProgramGroupPage=yes ArchitecturesAllowed=x64compatible ArchitecturesInstallIn64BitMode=x64compatible From 757fcd5ba80e55202dbf2fa34ebf63c02da9ce3e Mon Sep 17 00:00:00 2001 From: rgxdev Date: Tue, 17 Nov 2026 10:25:32 +0100 Subject: [PATCH 2/4] fix(windows): retry an unfinished browser registration The refresh at start only compared the link command, which Make Default writes third, so a later failed write was never retried. It now reads the link command, the Start menu client command and the Default Apps listing, and registers again when any of them is missing or names another executable. The installed check compares resolved paths, so a short-name or junction launch still counts. Signed-off-by: rgxdev --- crates/engine/src/host_windows.rs | 49 +++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/host_windows.rs b/crates/engine/src/host_windows.rs index 2bec72b6..6411d34b 100644 --- a/crates/engine/src/host_windows.rs +++ b/crates/engine/src/host_windows.rs @@ -264,7 +264,8 @@ pub fn is_default_browser() -> bool { /// settings at it; Windows lets only the user make the choice, so the result shows later in /// `is_default_browser`. pub fn make_default_browser() { - if !register_browser() { + let Some(exe) = std::env::current_exe().ok().and_then(|p| p.to_str().map(str::to_owned)) else { return }; + if !register_browser(&exe) { return; } let (verb, target) = (wide("open"), wide("ms-settings:defaultapps?registeredAppUser=Tarn")); @@ -275,15 +276,24 @@ pub fn make_default_browser() { /// Points an earlier Make Default at the installed `tarn.exe` once the install folder moved, as it /// does when the user profile moves to another drive. Development builds leave it alone. pub fn refresh_browser_registration() { - let (Some(exe), Some(installed)) = (exe(), local_app_data().map(|d| d.join(r"Programs\Tarn\tarn.exe"))) else { return }; - let registered = value(&format!(r"Software\Classes\{PROG_ID}\shell\open\command"), ""); - if exe.eq_ignore_ascii_case(&installed.to_string_lossy()) && registered.is_some_and(|c| !c.eq_ignore_ascii_case(&open_command(&exe))) { - register_browser(); + let Some(installed) = local_app_data().map(|d| d.join(r"Programs\Tarn\tarn.exe")) else { return }; + let running = std::env::current_exe().and_then(std::fs::canonicalize).ok(); + let (Some(exe), true) = (installed.to_str(), running.is_some() && running == std::fs::canonicalize(&installed).ok()) else { return }; + let found = [ + value(&format!(r"Software\Classes\{PROG_ID}\shell\open\command"), ""), + value(&format!(r"{CLIENT}\shell\open\command"), ""), + value(r"Software\RegisteredApplications", "Tarn"), + ]; + if registration_stale(exe, &found) { + register_browser(exe); } } -fn exe() -> Option { - std::env::current_exe().ok().and_then(|p| p.to_str().map(str::to_owned)) +/// Whether an earlier registration, also one a failed write left unfinished, names another +/// executable than `exe`. +fn registration_stale(exe: &str, found: &[Option; 3]) -> bool { + let current = [open_command(exe), format!("\"{exe}\""), format!(r"{CLIENT}\Capabilities")]; + found.iter().any(Option::is_some) && found.iter().zip(¤t).any(|(found, current)| !found.as_ref().is_some_and(|f| f.eq_ignore_ascii_case(current))) } /// Chromium, which parses this command line first, takes everything after the marker as one URL, @@ -292,9 +302,8 @@ fn open_command(exe: &str) -> String { format!("\"{exe}\" {SINGLE_ARGUMENT} %1") } -fn register_browser() -> bool { - let Some(exe) = exe() else { return false }; - let command = open_command(&exe); +fn register_browser(exe: &str) -> bool { + let command = open_command(exe); let classes = format!(r"Software\Classes\{PROG_ID}"); let registered = set_value(&classes, None, "Tarn URL") && set_value(&format!(r"{classes}\DefaultIcon"), None, &format!("{exe},0")) @@ -315,14 +324,10 @@ fn register_browser() -> bool { /// The user's Local AppData folder as the shell resolves it, the folder the installer uses too; /// for when `LOCALAPPDATA` is missing from the environment. pub fn local_app_data() -> Option { - known_folder(&FOLDERID_LocalAppData) -} - -fn known_folder(id: &windows_sys::core::GUID) -> Option { use std::os::windows::ffi::OsStringExt; let mut path: windows_sys::core::PWSTR = std::ptr::null_mut(); // SAFETY: `path` receives a NUL-terminated string the shell allocates, freed below. - let status = unsafe { SHGetKnownFolderPath(id, 0, std::ptr::null_mut(), &mut path) }; + let status = unsafe { SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, std::ptr::null_mut(), &mut path) }; let dir = (status >= 0 && !path.is_null()).then(|| { // SAFETY: `path` is a valid NUL-terminated wide string until it is freed below. let units = unsafe { std::slice::from_raw_parts(path, (0..).take_while(|&i| *path.add(i) != 0).count()) }; @@ -412,4 +417,18 @@ mod tests { assert!(super::external_allowed(&Url::parse(allowed).unwrap()), "{allowed}"); } } + + #[test] + fn a_moved_or_unfinished_registration_is_stale() { + let exe = r"D:\Users\a\AppData\Local\Programs\Tarn\tarn.exe"; + let old = r"C:\Users\a\AppData\Local\Programs\Tarn\tarn.exe"; + let of = |exe: &str| [Some(super::open_command(exe)), Some(format!("\"{exe}\"")), Some(format!(r"{}\Capabilities", super::CLIENT))]; + assert!(!super::registration_stale(exe, &[None, None, None]), "never registered"); + assert!(!super::registration_stale(exe, &of(exe))); + assert!(!super::registration_stale(exe, &of(&exe.to_uppercase())), "case differs only"); + assert!(super::registration_stale(exe, &of(old)), "install folder moved"); + let [command, _, listed] = of(exe); + assert!(super::registration_stale(exe, &[command.clone(), None, listed]), "a write failed after the link command"); + assert!(super::registration_stale(exe, &[command, Some(format!("\"{exe}\"")), None]), "never listed in Default Apps"); + } } From 819792e5eb7ac1205875b565dd5074f1400bc16e Mon Sep 17 00:00:00 2001 From: rgxdev Date: Tue, 17 Nov 2026 10:29:09 +0100 Subject: [PATCH 3/4] docs(changelog): move the Windows install-folder entry to 0.1.2 (#53) Signed-off-by: rgxdev --- CHANGELOG.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 28b81fce..7ef8e5b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,13 +30,6 @@ All notable changes to Tarn are documented in this file. The format is based on - The privacy notice names Quavon UG (haftungsbeschränkt) as controller, gives the legal basis and your rights, and states per client what it describes. -### Fixed - -- Windows: the installer always installs into the current user's `AppData\Local\Programs\Tarn`, - also after the user profile moved to another drive, and a link set up with Make Default follows - the install to its new folder. Without `LOCALAPPDATA` in its environment, Tarn keeps its data in - the Local AppData folder Windows reports instead of the folder it was started from. - ### Security - On Android, Tarn's own requests and file downloads refuse a server whose verified certificate From d915ccbadb3f1d5961f5b65d4621c23ab6c735ee Mon Sep 17 00:00:00 2001 From: rgxdev Date: Tue, 17 Nov 2026 10:36:05 +0100 Subject: [PATCH 4/4] test(extensions): block the real store host in the store-link tests The test rules blocked extension.tarnbrowser.com instead of extensions.tarnbrowser.com, so navigations to the store link reached the live site: the Linux display test failed on the missing load failure and the macOS engine test on the missing blocked request. Signed-off-by: rgxdev --- crates/engine/tests/tarn_extension.rs | 2 +- linux/src/webview/display_tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/tarn_extension.rs b/crates/engine/tests/tarn_extension.rs index f88ceb90..7012bef6 100644 --- a/crates/engine/tests/tarn_extension.rs +++ b/crates/engine/tests/tarn_extension.rs @@ -50,7 +50,7 @@ mod window { let uuid = "6A1B2C3D-0000-4000-8000-00000000E715"; let data = DataStore::persistent(uuid, uuid, Rc::new(|_| {})).unwrap(); let rules = format!( - r#"[{{"trigger":{{"url-filter":"^http://127\\.0\\.0\\.1:{port}/blocked\\.js"}},"action":{{"type":"block"}}}},{{"trigger":{{"url-filter":"^https://extension\\.tarnbrowser\\.com/"}},"action":{{"type":"block"}}}}]"# + r#"[{{"trigger":{{"url-filter":"^http://127\\.0\\.0\\.1:{port}/blocked\\.js"}},"action":{{"type":"block"}}}},{{"trigger":{{"url-filter":"^https://extensions\\.tarnbrowser\\.com/"}},"action":{{"type":"block"}}}}]"# ); let compiled: Rc>> = Rc::default(); let slot = compiled.clone(); diff --git a/linux/src/webview/display_tests.rs b/linux/src/webview/display_tests.rs index b670ff75..c2381013 100644 --- a/linux/src/webview/display_tests.rs +++ b/linux/src/webview/display_tests.rs @@ -98,7 +98,7 @@ fn only_the_users_own_navigation_to_a_store_link_asks_to_install() { let web = open(&state); let block: Rc>> = Rc::default(); let slot = block.clone(); - let rules = r#"[{"trigger":{"url-filter":"^https://extension\\.tarnbrowser\\.com/"},"action":{"type":"block"}}]"#; + let rules = r#"[{"trigger":{"url-filter":"^https://extensions\\.tarnbrowser\\.com/"},"action":{"type":"block"}}]"#; filters::compile_one("store-block.test".into(), rules.into(), move |f| *slot.borrow_mut() = Some(f)); assert!(spin_until(|| block.borrow().is_some(), 20), "the test's rule compiled"); state.content.borrow().as_ref().unwrap().add_filter(block.borrow().as_ref().unwrap());