Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix(macos): skip the system proxy for downloads where the page does
Tw93c454d9383a77
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 8769259c..5a1e8458 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2881,6 +2881,7 @@ dependencies = ["serde","serde_json","sha2 0.11.1",+ "system-configuration","tauri","tauri-build","tauri-plugin-global-shortcut",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 8a7b3fe7..7b39e769 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -49,6 +49,9 @@ tauri-plugin-notification = "2.8.1"[target.'cfg(target_os = "macos")'.dependencies]block2 = "0.6"dispatch = "0.2"+# Reads the system proxy's exceptions list for downloads; already in the+# tree through hyper-util, which reads the proxy without that list.+system-configuration = "0.7"objc2 = "0.6"objc2-app-kit = { version = "0.3", features = ["NSApplication", "NSDockTile", "NSWindow"] }objc2-foundation = { version = "0.3", features = [diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rsindex 116d7eb8..c1333685 100644--- a/src-tauri/src/app/invoke.rs+++ b/src-tauri/src/app/invoke.rs@@ -561,16 +561,217 @@ fn normalize_proxy_url(proxy_url: Option<&str>) -> Result<Option<String>, Stringfn build_download_client(proxy_url: Option<&str>) -> Result<Client, String> {let normalized = normalize_proxy_url(proxy_url)?;let mut builder = ClientBuilder::new().redirect(Policy::none()).referer(false);- if let Some(proxy) = &normalized {- let reqwest_proxy =- Proxy::all(proxy).map_err(|e| format!("Invalid download proxy URL: {e}"))?;- builder = builder.proxy(reqwest_proxy);+ match &normalized {+ Some(proxy) => {+ let reqwest_proxy =+ Proxy::all(proxy).map_err(|e| format!("Invalid download proxy URL: {e}"))?;+ builder = builder.proxy(reqwest_proxy);+ }+ None =>+ {+ #[cfg(target_os = "macos")]+ if let Some(rule) = macos_system_proxy().and_then(system_proxy_rule) {+ builder = builder.proxy(rule);+ }+ }}builder.build().map_err(|e| format!("Failed to build download HTTP client: {e}"))}+/// The macOS system proxy as a download needs it. The HTTP stack reads the+/// system's HTTP and HTTPS servers but not its exceptions list (hyper-util+/// 0.1.21), while the page honors that list, so a download from a host the+/// page reaches directly went to the proxy and failed (a loopback page got+/// a 502 from the test Mac's proxy, 2026-12-01).+#[cfg(any(target_os = "macos", test))]+#[derive(Debug, Default, PartialEq)]+struct SystemProxy {+ http: Option<String>,+ https: Option<String>,+ exceptions: Vec<String>,+ exclude_simple_hostnames: bool,+}++/// Whether a host skips the system proxy: loopback always, as in every+/// browser, then each entry of the exceptions list the way macOS reads it: an+/// address, a CIDR range (`169.254/16`, the default, pads the missing octets),+/// `*`, or a domain that also covers its subdomains (`*.local`, `example.com`).+/// `<local>`, the Windows token some proxy apps copy into the list, means the+/// same as Exclude Simple Hostnames: a name without a dot goes direct.+#[cfg(any(target_os = "macos", test))]+fn system_proxy_bypasses(host: &str, proxy: &SystemProxy) -> bool {+ use std::net::IpAddr;+ let host = host.trim_start_matches('[').trim_end_matches(']');+ let address = host.parse::<IpAddr>().ok();+ if address.is_some_and(|ip| ip.is_loopback())+ || host.eq_ignore_ascii_case("localhost")+ || host.to_ascii_lowercase().ends_with(".localhost")+ {+ return true;+ }+ let mut simple_direct = proxy.exclude_simple_hostnames;+ for entry in proxy.exceptions.iter().map(|entry| entry.trim()) {+ if entry.is_empty() {+ continue;+ }+ if entry == "<local>" {+ simple_direct = true;+ } else if entry == "*" {+ return true;+ } else if let Some((network, bits)) = entry.split_once('/') {+ if address.is_some_and(|ip| cidr_contains(network, bits, ip)) {+ return true;+ }+ } else if let Ok(ip) = entry.parse::<IpAddr>() {+ if address == Some(ip) {+ return true;+ }+ } else {+ let domain = entry.trim_start_matches("*.").trim_start_matches('.');+ let host = host.to_ascii_lowercase();+ let domain = domain.to_ascii_lowercase();+ if host == domain || host.ends_with(&format!(".{domain}")) {+ return true;+ }+ }+ }+ simple_direct && address.is_none() && !host.contains('.')+}++#[cfg(any(target_os = "macos", test))]+fn cidr_contains(network: &str, bits: &str, ip: std::net::IpAddr) -> bool {+ use std::net::{IpAddr, Ipv4Addr};+ let Ok(bits) = bits.parse::<u32>() else {+ return false;+ };+ let network = if network.contains(':') {+ network.parse::<IpAddr>().ok()+ } else {+ let mut octets: Vec<&str> = network.split('.').collect();+ octets.resize(4, "0");+ octets.join(".").parse::<Ipv4Addr>().ok().map(IpAddr::V4)+ };+ match (network, ip) {+ (Some(IpAddr::V4(net)), IpAddr::V4(ip)) if bits <= 32 => {+ let mask = u32::MAX.checked_shl(32 - bits).unwrap_or(0);+ u32::from(net) & mask == u32::from(ip) & mask+ }+ (Some(IpAddr::V6(net)), IpAddr::V6(ip)) if bits <= 128 => {+ let mask = u128::MAX.checked_shl(128 - bits).unwrap_or(0);+ u128::from(net) & mask == u128::from(ip) & mask+ }+ _ => false,+ }+}++#[cfg(any(target_os = "macos", test))]+fn system_proxy_target(url: &Url, proxy: &SystemProxy) -> Option<String> {+ if system_proxy_bypasses(url.host_str()?, proxy) {+ return None;+ }+ match url.scheme() {+ "http" => proxy.http.clone(),+ "https" => proxy.https.clone(),+ _ => None,+ }+}++/// reqwest 0.12.28 stores a custom proxy's `no_proxy` but never consults it,+/// so the exceptions are decided in the closure.+#[cfg(any(target_os = "macos", test))]+fn system_proxy_rule(proxy: SystemProxy) -> Option<Proxy> {+ if proxy.http.is_none() && proxy.https.is_none() {+ return None;+ }+ Some(Proxy::custom(move |url| system_proxy_target(url, &proxy)))+}++/// Reads the system proxy, or `None` when proxy environment variables are set+/// (the HTTP stack then applies them and `NO_PROXY` itself) or none is on.+#[cfg(target_os = "macos")]+fn macos_system_proxy() -> Option<SystemProxy> {+ use system_configuration::core_foundation::array::CFArray;+ use system_configuration::core_foundation::base::{CFType, TCFType};+ use system_configuration::core_foundation::number::CFNumber;+ use system_configuration::core_foundation::string::{CFString, CFStringRef};+ use system_configuration::dynamic_store::SCDynamicStoreBuilder;+ use system_configuration::sys::schema_definitions::{+ kSCPropNetProxiesExceptionsList, kSCPropNetProxiesExcludeSimpleHostnames,+ kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPPort, kSCPropNetProxiesHTTPProxy,+ kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSPort, kSCPropNetProxiesHTTPSProxy,+ };++ let from_env = [+ "ALL_PROXY",+ "all_proxy",+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ ]+ .iter()+ .any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()));+ if from_env {+ return None;+ }+ let map = SCDynamicStoreBuilder::new("pake-downloads")+ .build()?+ .get_proxies()?;+ let number = |key: CFStringRef| {+ map.find(key)+ .and_then(|value| value.downcast::<CFNumber>())+ .and_then(|value| value.to_i32())+ };+ let server = |enable: CFStringRef, host: CFStringRef, port: CFStringRef| {+ if number(enable) != Some(1) {+ return None;+ }+ let host = map.find(host)?.downcast::<CFString>()?.to_string();+ Some(match number(port) {+ Some(port) => format!("http://{host}:{port}"),+ None => format!("http://{host}"),+ })+ };+ // SAFETY: the keys are immutable constants exported by SystemConfiguration.+ let (http, https, exceptions_key, simple_key) = unsafe {+ (+ server(+ kSCPropNetProxiesHTTPEnable,+ kSCPropNetProxiesHTTPProxy,+ kSCPropNetProxiesHTTPPort,+ ),+ server(+ kSCPropNetProxiesHTTPSEnable,+ kSCPropNetProxiesHTTPSProxy,+ kSCPropNetProxiesHTTPSPort,+ ),+ kSCPropNetProxiesExceptionsList,+ kSCPropNetProxiesExcludeSimpleHostnames,+ )+ };+ let exceptions = map+ .find(exceptions_key)+ .and_then(|value| value.downcast::<CFArray>())+ .map(|list| {+ list.iter()+ // SAFETY: a property list array holds CF objects only.+ .filter_map(|entry| {+ unsafe { CFType::wrap_under_get_rule(*entry) }.downcast::<CFString>()+ })+ .map(|entry| entry.to_string())+ .collect()+ })+ .unwrap_or_default();+ Some(SystemProxy {+ http,+ https,+ exceptions,+ exclude_simple_hostnames: number(simple_key) == Some(1),+ })+}+fn download_client_for_proxy(proxy_url: Option<&str>) -> Result<Client, String> {let normalized = normalize_proxy_url(proxy_url)?;let key = normalized.clone().unwrap_or_default();@@ -1539,6 +1740,105 @@ mod tests {(origin, thread)}+ #[test]+ fn the_system_proxy_carries_downloads_except_for_loopback() {+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ // The test server is the proxy too: a proxied request arrives with the+ // absolute URL, a direct one with only the path.+ let (origin, server) = serve_downloads(|_| vec![(200, None), (200, None)]);+ let rule = system_proxy_rule(SystemProxy {+ http: Some(origin.as_str().trim_end_matches('/').to_string()),+ ..SystemProxy::default()+ })+ .unwrap();+ let client = ClientBuilder::new().proxy(rule).build().unwrap();+ runtime.block_on(async {+ client+ .get("http://downloads.example.test/a.zip")+ .send()+ .await+ .unwrap();+ client+ .get(origin.join("b.zip").unwrap())+ .send()+ .await+ .unwrap();+ });+ let requests = server.join().unwrap();+ assert!(requests[0].starts_with("get http://downloads.example.test/a.zip "));+ assert!(requests[1].starts_with("get /b.zip "));+ }++ #[test]+ fn system_proxy_exceptions_read_like_the_page_reads_them() {+ let proxy = |exceptions: &[&str], exclude_simple_hostnames| SystemProxy {+ http: Some("http://127.0.0.1:7890".into()),+ https: Some("http://127.0.0.1:7891".into()),+ exceptions: exceptions.iter().map(|entry| entry.to_string()).collect(),+ exclude_simple_hostnames,+ };+ let target =+ |url: &str, proxy: &SystemProxy| system_proxy_target(&Url::parse(url).unwrap(), proxy);+ // The test Mac's list, and macOS's own default `169.254/16`.+ let listed = proxy(+ &[+ "127.0.0.1",+ "192.168.0.0/16",+ "10.0.0.0/8",+ "localhost",+ "*.local",+ " Corp.Example ",+ "169.254/16",+ "fd00::/8",+ ],+ false,+ );+ for direct in [+ "http://192.168.31.46:5000/a.zip",+ "http://10.1.2.3/",+ "https://nas.local/",+ "https://files.corp.example/",+ "http://corp.example/",+ "http://169.254.7.1/",+ "http://[fd12::1]/",+ "http://[::1]:8080/",+ "http://127.0.0.2/",+ "http://app.localhost/",+ ] {+ assert_eq!(target(direct, &listed), None, "{direct}");+ }+ for proxied in [+ "http://192.169.0.1/",+ "https://notcorp.example/",+ "https://example.com/",+ "http://nas/",+ ] {+ assert!(target(proxied, &listed).is_some(), "{proxied}");+ }+ assert_eq!(+ target("http://example.com/", &listed).as_deref(),+ Some("http://127.0.0.1:7890")+ );+ assert_eq!(+ target("https://example.com/", &listed).as_deref(),+ Some("http://127.0.0.1:7891")+ );+ assert_eq!(target("ftp://example.com/", &listed), None);++ // Simple hostnames go direct only when the system says so.+ assert_eq!(target("http://nas/", &proxy(&[], true)), None);+ assert_eq!(target("http://nas/", &proxy(&["<local>"], false)), None);+ assert!(target("http://nas.lan/", &proxy(&["<local>"], true)).is_some());+ assert_eq!(+ target("https://anything.test/", &proxy(&["*"], false)),+ None+ );+ assert!(system_proxy_rule(SystemProxy::default()).is_none());+ }+#[test]fn redirects_recheck_cookies_and_never_restore_full_referrer() {let runtime = tokio::runtime::Builder::new_current_thread()