Skip to main content

vector_core/
proxy.rs

1//! Pictures, files and previews fetched by the user's Magnitude server
2//! instead of by this device.
3//!
4//! A picture loaded here, a file downloaded here, or a page previewed here
5//! is a request from this device's address to whoever hosts the thing, and
6//! most of it arrives without a click: sending someone a link or an emoji
7//! is enough to learn where they are. Magnitude fetches on the client's
8//! behalf (`magnitude-unfurl` for a page's metadata, `magnitude-proxy` for
9//! everything else), advertised in its information document. This module
10//! finds the first configured server that offers it and routes through it,
11//! under one privacy setting, on by default.
12//!
13//! Every outbound request in every crate resolves its destination through
14//! [`crate::net::egress`], which asks here. The only requests that never come
15//! through are the ones that cannot: Nostr relay sockets, and the signed
16//! writes (upload, mirror, delete, discovery) to a Blossom server the user
17//! chose, which already carry the user's key.
18//!
19//! When the setting is on and no configured server offers previews, there is
20//! no preview on Clearnet: falling back to fetching the page here would be the
21//! leak with a new name. Off Clearnet the page is fetched through the network
22//! in use, which already hides this device's address. Pictures do fall back to
23//! a direct load when no server offers the proxy, because an avatar that never
24//! appears is not a privacy feature anyone chose; the setting's own help text
25//! says so.
26//!
27//! Names native to one network (`.i2p`, `.onion`) are never wrapped: a
28//! clearnet proxy can't reach them, and the transport routes or refuses them.
29
30use std::sync::Mutex;
31use std::time::Duration;
32use web_time::Instant;
33
34pub const SETTING_KEY: &str = "privacy_proxy_media";
35pub const UNFURL_EXT: &str = "magnitude-unfurl";
36pub const PROXY_EXT: &str = "magnitude-proxy";
37
38/// The setting, read fresh each time: it is one SQLite row and a change in
39/// Settings must take effect on the next picture, not the next launch.
40pub fn enabled() -> bool {
41    match crate::db::get_sql_setting(SETTING_KEY.to_string()) {
42        Ok(Some(v)) => v == "true" || v == "1",
43        _ => true,
44    }
45}
46
47/// Which server offers what, remembered briefly so a chat full of pictures
48/// does not scan the server list per picture.
49struct Pick {
50    extension: &'static str,
51    server: Option<String>,
52    at: Instant,
53}
54
55static PICKS: Mutex<Vec<Pick>> = Mutex::new(Vec::new());
56const PICK_TTL: Duration = Duration::from_secs(10 * 60);
57/// How long "no server offers it" is believed before asking again.
58const NEGATIVE_PICK_TTL: Duration = Duration::from_secs(60);
59
60/// The first configured Blossom server whose information document lists
61/// `extension`, as an origin without a trailing slash.
62pub async fn server_offering(extension: &'static str) -> Option<String> {
63    if let Ok(picks) = PICKS.lock() {
64        if let Some(p) = picks.iter().find(|p| p.extension == extension) {
65            if p.at.elapsed() < PICK_TTL {
66                return p.server.clone();
67            }
68        }
69    }
70    // The list is installed at login, and the first pictures are asked for
71    // in the same seconds; a pick made against an empty list is not "no
72    // server offers it", it is "not yet". Wait a little for it.
73    let mut servers = crate::state::get_blossom_servers();
74    for _ in 0..25 {
75        if !servers.is_empty() {
76            break;
77        }
78        crate::rt::time::sleep(Duration::from_millis(200)).await;
79        servers = crate::state::get_blossom_servers();
80    }
81    let mut found = None;
82    // Whether every server was actually asked. A document that could not
83    // be fetched says nothing about what the server offers.
84    let mut every_answer_known = !servers.is_empty();
85    for server in servers {
86        // A document no older than an hour, refetched otherwise. Never the
87        // persisted copy at any age: this account's was written before the
88        // server offered previews or the proxy, and trusting it meant every
89        // picture loaded directly while the toggle said otherwise.
90        let info = match crate::signer::active_signer() {
91            Ok(signer) => match crate::blossom_info::refresh(&signer, &server, Duration::from_secs(60 * 60)).await {
92                Ok(i) => i,
93                Err(_) => {
94                    every_answer_known = false;
95                    None
96                }
97            },
98            // No signer to ask with: the last copy is all there is.
99            Err(_) => {
100                every_answer_known = false;
101                crate::blossom_info::cached(&server)
102            }
103        };
104        if info.map(|i| i.extensions.iter().any(|e| e == extension)).unwrap_or(false) {
105            found = Some(server.trim_end_matches('/').to_string());
106            break;
107        }
108    }
109    match &found {
110        Some(s) => crate::log_debug!("[Proxy] {} offered by {}", extension, s),
111        None if every_answer_known => crate::log_warn!("[Proxy] no configured Blossom server offers {}; falling back", extension),
112        None => crate::log_warn!("[Proxy] could not learn which server offers {}; asking again next time", extension),
113    }
114    // A found server is remembered; "none", settled or not, only briefly, so a
115    // server that starts offering it (or answers again) is seen soon. An
116    // unsettled answer loads pictures directly either way; remembering it only
117    // spares every picture meanwhile a round of document fetches (a browser
118    // can't read a server whose error pages refuse cross-origin reads).
119    if let Ok(mut picks) = PICKS.lock() {
120        picks.retain(|p| p.extension != extension);
121        match &found {
122            Some(_) => picks.push(Pick { extension, server: found.clone(), at: Instant::now() }),
123            // Dated back so it ages out after the short window, not the long.
124            None => {
125                if let Some(at) = Instant::now().checked_sub(PICK_TTL - NEGATIVE_PICK_TTL) {
126                    picks.push(Pick { extension, server: None, at });
127                }
128            }
129        }
130    }
131    found
132}
133
134/// Forget the remembered picks: the server list or a setting changed.
135pub fn forget_picks() {
136    if let Ok(mut picks) = PICKS.lock() {
137        picks.clear();
138    }
139}
140
141/// Where to actually load `url` from. The proxy's address when the setting is
142/// on, a server offers it, and the URL is somebody else's; `None` means load
143/// it directly. A blob on one of the user's own servers is already theirs to
144/// fetch, and a proxy URL is not proxied again.
145pub async fn proxied(url: &str) -> Option<String> {
146    if !enabled() || !wants_proxy(url) {
147        return None;
148    }
149    let server = server_offering(PROXY_EXT).await?;
150    Some(proxy_url(&server, url))
151}
152
153pub fn proxy_url(server: &str, url: &str) -> String {
154    let encoded: String = url::form_urlencoded::byte_serialize(url.as_bytes()).collect();
155    format!("{server}/proxy?url={encoded}")
156}
157
158/// Domains that are ours: a Magnitude answers these, so loading from them
159/// directly reveals nothing to anyone else, and routing them through a
160/// Magnitude would be Magnitude proxying Magnitude.
161const OWN_DOMAINS: &[&str] = &["vectorapp.io", "jskitty.com"];
162
163fn is_own_host(host: &str) -> bool {
164    let h = host.to_ascii_lowercase();
165    OWN_DOMAINS.iter().any(|d| h == *d || h.ends_with(&format!(".{d}")))
166}
167
168/// A host only one network can reach (`.i2p`, `.onion`).
169pub fn is_network_native(host: &str) -> bool {
170    let h = host.trim_end_matches('.').to_ascii_lowercase();
171    crate::transport::Kind::ALL.iter().any(|k| k.native_suffixes().iter().any(|s| h.ends_with(s)))
172}
173
174/// Everything over http(s) that is not ours goes through the proxy: a
175/// picture, an avatar, an emoji, and an attachment on somebody's Blossom
176/// server, which otherwise learns the recipient's address on every
177/// download. Only our own domains and network-native names skip it, and a
178/// URL that is already a proxy or preview request is never wrapped again.
179pub fn wants_proxy(url: &str) -> bool {
180    let Ok(parsed) = url::Url::parse(url) else { return false };
181    if !matches!(parsed.scheme(), "http" | "https") {
182        return false;
183    }
184    if parsed.path() == "/proxy" || parsed.path() == "/unfurl" {
185        return false;
186    }
187    !parsed.host_str().map(|h| is_own_host(h) || is_network_native(h)).unwrap_or(true)
188}
189
190/// A signed `Authorization` for a proxied request, so the proxy charges the
191/// account rather than the address and a recognised account gets its own
192/// allowance. `None` when nobody is signed in; the proxy then treats the
193/// request as a stranger's, which still works.
194pub async fn proxy_authorization(server: &str) -> Option<reqwest::header::HeaderValue> {
195    let signer = crate::signer::active_signer().ok()?;
196    let server_url = url::Url::parse(server).ok()?;
197    crate::blossom_info::build_get_auth_header(&signer, &server_url, "Proxied fetch")
198        .await
199        .ok()
200}
201
202/// The proxy server a proxied URL points at, so its authorization can be
203/// scoped to it.
204pub fn proxy_server_of(url: &str) -> Option<String> {
205    let parsed = url::Url::parse(url).ok()?;
206    if parsed.path() != "/proxy" {
207        return None;
208    }
209    Some(parsed.origin().ascii_serialization())
210}
211
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn everything_but_our_own_domains_wants_the_proxy() {
219        assert!(wants_proxy("https://cdn.example.net/a.jpg"));
220        assert!(wants_proxy("https://blossom.primal.net/abc.bin"), "somebody's Blossom server is somebody's");
221        assert!(wants_proxy("https://image.nostr.build/x.png"));
222        assert!(!wants_proxy("https://magnitude.jskitty.com/abc.png"), "ours");
223        assert!(!wants_proxy("https://us.magnitude.jskitty.com/abc.png"), "ours, an edge");
224        assert!(!wants_proxy("https://vectorapp.io/assets/x.png"), "ours");
225        assert!(wants_proxy("https://notjskitty.com/x.png"), "a suffix is not a subdomain");
226        assert!(!wants_proxy("data:image/png;base64,AAAA"));
227        assert!(!wants_proxy("asset://localhost/x.png"));
228        assert!(!wants_proxy("https://magnitude.example/proxy?url=x"));
229        let b32 = "nostrajmjieip3dqgeefsgpydy3bbshe3o32z65dwkssl7qxkn5a.b32.i2p";
230        assert!(!wants_proxy(&format!("http://{b32}/a.png")), "a clearnet proxy can't reach I2P");
231        assert!(!wants_proxy("http://forum.i2p./x"), "nor an I2P name");
232        assert!(!wants_proxy("https://abc.onion/a.png"), "nor an onion");
233        assert!(wants_proxy("https://i2p.example.com/a.png"), "a clearnet host named after it is clearnet");
234        assert_eq!(proxy_server_of("https://us.magnitude.jskitty.com/proxy?url=x").as_deref(), Some("https://us.magnitude.jskitty.com"));
235        assert!(proxy_server_of("https://cdn.example.net/a.jpg").is_none());
236    }
237}