Skip to main content

vector_core/
blossom_info.rs

1//! The server information document (`GET /.well-known/blossom`).
2//!
3//! No BUD defines one. Magnitude publishes it (extension `magnitude-info`)
4//! and personalises it for a signed caller: the caller's tier, per-file
5//! limit, storage and daily allowances with what is used of each, and
6//! whether the server would take an upload at all. A server that has it is
7//! told what it can do before sending a byte; one that hasn't is learned the
8//! old way, by bouncing uploads (`blossom_capabilities`).
9//!
10//! Documents are cached per account. Ranking reads the cache and never waits
11//! on the network; login and the server dialog refresh it.
12
13use std::collections::HashMap;
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16use web_time::Instant;
17
18use nostr_sdk::prelude::Url;
19use reqwest::header::{ACCEPT, AUTHORIZATION};
20use serde::Serialize;
21use serde_json::Value;
22
23use crate::signer::VectorSigner;
24
25/// The extension name a server advertises when its document carries limits
26/// and a `caller` block.
27pub const INFO_EXTENSION: &str = "magnitude-info";
28
29/// A plan label is brief vanity at most. Anything past these is dropped
30/// whole rather than trimmed, so a server cannot half-render into the card.
31pub const PLAN_TITLE_MAX: usize = 24;
32pub const PLAN_DESCRIPTION_MAX: usize = 100;
33
34/// One line of plain text within `max` characters, or nothing.
35pub fn plan_text(raw: Option<&str>, max: usize) -> Option<String> {
36    let cleaned: String = raw?
37        .split_whitespace()
38        .collect::<Vec<_>>()
39        .join(" ");
40    let ok = !cleaned.is_empty()
41        && cleaned.chars().count() <= max
42        && !cleaned.chars().any(|c| c.is_control());
43    ok.then_some(cleaned)
44}
45
46/// What this server will do for the account that asked.
47#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
48pub struct CallerInfo {
49    pub tier: String,
50    pub max_blob: u64,
51    pub storage_used: u64,
52    pub storage_limit: u64,
53    pub blobs: u64,
54    pub daily_used: u64,
55    pub daily_limit: u64,
56    /// Whether an upload would be admitted at all; `reasons` says why not.
57    pub allowed: bool,
58    pub reasons: Vec<String>,
59    /// The operator's name for this tier, bounded by [`PLAN_TITLE_MAX`].
60    pub plan_title: Option<String>,
61    /// One line under it, bounded by [`PLAN_DESCRIPTION_MAX`].
62    pub plan_description: Option<String>,
63}
64
65#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
66pub struct ServerInfo {
67    pub name: Option<String>,
68    pub software: Option<String>,
69    pub version: Option<String>,
70    pub description: Option<String>,
71    pub buds: Vec<u8>,
72    pub extensions: Vec<String>,
73    /// The largest blob any account may upload.
74    pub max_blob: Option<u64>,
75    pub mime: Vec<String>,
76    pub capacity_used: Option<u64>,
77    pub capacity_limit: Option<u64>,
78    pub caller: Option<CallerInfo>,
79    /// Unix seconds.
80    pub fetched_at: i64,
81    /// The document as received, for persisting; not sent to the UI.
82    #[serde(skip)]
83    pub raw: Value,
84}
85
86impl ServerInfo {
87    /// Read a document. `None` when the JSON is not an information document
88    /// at all (a server that answers the path with something else).
89    pub fn parse(v: &Value) -> Option<Self> {
90        let obj = v.as_object()?;
91        let looks_like_one = obj.contains_key("buds")
92            || obj.contains_key("software")
93            || obj.contains_key("accepts");
94        if !looks_like_one {
95            return None;
96        }
97        let str_of = |key: &str| obj.get(key).and_then(|v| v.as_str()).map(|s| s.to_string());
98        let u64_at = |path: &[&str]| {
99            let mut cur = v;
100            for p in path {
101                cur = cur.get(p)?;
102            }
103            cur.as_u64()
104        };
105        let strings = |val: Option<&Value>| -> Vec<String> {
106            val.and_then(|v| v.as_array())
107                .map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_string())).collect())
108                .unwrap_or_default()
109        };
110        let caller = obj.get("caller").and_then(|c| {
111            let allowed = c.get("allowed")?.as_bool()?;
112            let n = |key: &str| c.get(key).and_then(|v| v.as_u64()).unwrap_or(0);
113            let plan = c.get("plan");
114            let plan_str = |key: &str| plan.and_then(|p| p.get(key)).and_then(|v| v.as_str());
115            Some(CallerInfo {
116                tier: c.get("tier").and_then(|v| v.as_str()).unwrap_or("").to_string(),
117                max_blob: n("max_blob"),
118                storage_used: n("storage_used"),
119                storage_limit: n("storage_limit"),
120                blobs: n("blobs"),
121                daily_used: n("daily_used"),
122                daily_limit: n("daily_limit"),
123                allowed,
124                reasons: strings(c.get("reasons")),
125                plan_title: plan_text(plan_str("title"), PLAN_TITLE_MAX),
126                plan_description: plan_text(plan_str("description"), PLAN_DESCRIPTION_MAX),
127            })
128        });
129        Some(ServerInfo {
130            name: str_of("name"),
131            software: str_of("software"),
132            version: str_of("version"),
133            description: str_of("description"),
134            buds: obj
135                .get("buds")
136                .and_then(|b| b.as_array())
137                .map(|a| a.iter().filter_map(|x| x.as_u64().map(|n| n as u8)).collect())
138                .unwrap_or_default(),
139            extensions: strings(obj.get("extensions")),
140            max_blob: u64_at(&["accepts", "max_blob"]),
141            mime: strings(obj.get("accepts").and_then(|a| a.get("mime"))),
142            capacity_used: u64_at(&["capacity", "stored_bytes"]),
143            capacity_limit: u64_at(&["capacity", "limit_bytes"]),
144            caller,
145            fetched_at: now_secs(),
146            raw: v.clone(),
147        })
148    }
149
150    /// The document carries limits and a caller block, not just a BUD list.
151    pub fn is_personalised(&self) -> bool {
152        self.extensions.iter().any(|e| e == INFO_EXTENSION)
153    }
154
155    /// Whether this server would take a blob of `size` from us, as far as the
156    /// document says. `None` when it says nothing about size.
157    pub fn accepts_size(&self, size: u64) -> Option<bool> {
158        if let Some(c) = &self.caller {
159            return Some(c.allowed && size <= c.max_blob);
160        }
161        self.max_blob.map(|max| size <= max)
162    }
163
164    /// Why an upload of `size` would be refused, for a person. `None` when
165    /// the document does not say it would be.
166    pub fn refusal_reason(&self, host: &str, size: u64) -> Option<String> {
167        let bytes = crate::crypto::format_bytes;
168        match &self.caller {
169            Some(c) if !c.allowed => Some(match c.reasons.first() {
170                Some(why) => format!("{}: {}", host, why),
171                None => format!("{} won't take uploads from this account.", host),
172            }),
173            Some(c) if size > c.max_blob => Some(format!(
174                "{} allows files up to {} for your account.", host, bytes(c.max_blob),
175            )),
176            Some(_) => None,
177            None => match self.max_blob {
178                Some(max) if size > max => Some(format!("{} allows files up to {}.", host, bytes(max))),
179                _ => None,
180            },
181        }
182    }
183}
184
185fn now_secs() -> i64 {
186    crate::clock::now_secs() as i64
187}
188
189fn norm_url(url: &str) -> String {
190    url.trim().trim_end_matches('/').to_lowercase()
191}
192
193// ============================================================================
194// Cache — one document per server, per account
195// ============================================================================
196
197struct Cached {
198    /// `None`: the server was asked and has no document.
199    info: Option<ServerInfo>,
200    at: Instant,
201}
202
203struct InfoCache;
204fn cache() -> Arc<Mutex<HashMap<String, Cached>>> {
205    crate::db::current_session().scoped::<InfoCache, _>()
206}
207
208/// The last document fetched for `server_url`, at any age. `None` when the
209/// server has none or was never asked.
210///
211/// Memory first; failing that, the copy persisted by the last fetch, so a
212/// fresh process paints the dialog's final shape before it has asked anyone.
213pub fn cached(server_url: &str) -> Option<ServerInfo> {
214    let key = norm_url(server_url);
215    if let Ok(c) = cache().lock() {
216        if let Some(entry) = c.get(&key) {
217            return entry.info.clone();
218        }
219    }
220    load_persisted(&key)
221}
222
223fn persist_key(key: &str) -> String {
224    format!("blossom_info:{}", key)
225}
226
227fn load_persisted(key: &str) -> Option<ServerInfo> {
228    let json = crate::db::get_sql_setting(persist_key(key)).ok().flatten()?;
229    serde_json::from_str::<Value>(&json).ok().and_then(|v| ServerInfo::parse(&v))
230}
231
232/// Whether `server_url` has been asked at all this session.
233pub fn is_known(server_url: &str) -> bool {
234    cache().lock().map(|c| c.contains_key(&norm_url(server_url))).unwrap_or(false)
235}
236
237fn age_of(server_url: &str) -> Option<Duration> {
238    cache().lock().ok()?.get(&norm_url(server_url)).map(|c| c.at.elapsed())
239}
240
241fn store(server_url: &str, info: Option<ServerInfo>) {
242    let key = norm_url(server_url);
243    if let Ok(mut c) = cache().lock() {
244        c.insert(key.clone(), Cached { info: info.clone(), at: Instant::now() });
245    }
246    // The raw document is what parse() reads back, so it is what is kept.
247    let persisted = info.as_ref().and_then(|i| serde_json::to_string(&i.raw).ok()).unwrap_or_default();
248    let _ = crate::db::set_sql_setting(persist_key(&key), persisted);
249}
250
251pub fn invalidate(server_url: &str) {
252    let key = norm_url(server_url);
253    if let Ok(mut c) = cache().lock() {
254        c.remove(&key);
255    }
256    let _ = crate::db::set_sql_setting(persist_key(&key), String::new());
257}
258
259/// An upload of `bytes` just landed on `server_url`: move the caller's usage
260/// so the dialog is right before the next fetch.
261pub fn note_upload(server_url: &str, bytes: u64) {
262    if let Ok(mut c) = cache().lock() {
263        if let Some(caller) = c
264            .get_mut(&norm_url(server_url))
265            .and_then(|e| e.info.as_mut())
266            .and_then(|i| i.caller.as_mut())
267        {
268            caller.storage_used = caller.storage_used.saturating_add(bytes);
269            caller.daily_used = caller.daily_used.saturating_add(bytes);
270            caller.blobs = caller.blobs.saturating_add(1);
271        }
272    }
273}
274
275// ============================================================================
276// Fetch
277// ============================================================================
278
279/// A signed `get` authorization scoped to the server, so the document comes
280/// back personalised.
281async fn build_info_auth_header<T>(signer: &T, server: &Url) -> Result<reqwest::header::HeaderValue, String>
282where
283    T: VectorSigner,
284{
285    build_get_auth_header(signer, server, "Blossom server information").await
286}
287
288/// A signed `Authorization` for a `GET` scoped to `server`, good for two
289/// minutes: what the information document is fetched with, and what a
290/// proxied fetch carries so the proxy charges the account, not the address.
291pub async fn build_get_auth_header<T>(signer: &T, server: &Url, reason: &str) -> Result<reqwest::header::HeaderValue, String>
292where
293    T: VectorSigner,
294{
295    let ttl = Duration::from_secs(120);
296    crate::blossom::auth_header(signer, "get", crate::blossom::AuthScope::Server(server), reason, ttl).await
297}
298
299/// Ask `server_url` for its document. `Ok(None)` is a server without one.
300pub async fn fetch<T>(signer: &T, server_url: &str) -> Result<Option<ServerInfo>, String>
301where
302    T: VectorSigner,
303{
304    let base = Url::parse(&format!("{}/", server_url.trim_end_matches('/')))
305        .map_err(|e| format!("Invalid server URL: {}", e))?;
306    let doc_url = base
307        .join(".well-known/blossom")
308        .map_err(|e| format!("Invalid server URL: {}", e))?;
309    let auth = build_info_auth_header(signer, &base).await?;
310    // The user's lane: the request carries their signed authorization.
311    let client = crate::net::build_http_client_for(crate::net::Lane::Account, Some(Duration::from_secs(8)), None, true)?;
312    let asked_at = Instant::now();
313    let resp = match client
314        .get(doc_url)
315        .header(ACCEPT, "application/json")
316        .header(AUTHORIZATION, auth)
317        .send()
318        .await
319    {
320        Ok(r) => r,
321        Err(e) => {
322            // Only an attempt that left this device says anything about the server: a network
323            // that refused it, or changed under it, does not.
324            if !matches!(e, crate::net::HttpError::Refused(_) | crate::net::HttpError::NetworkChanged) {
325                crate::blossom_stats::record_failure(server_url, crate::blossom_stats::FAIL_OFFLINE);
326            }
327            return Err(format!("Info request failed: {}", e));
328        }
329    };
330    // Any answer, document or not, is the server being there.
331    crate::blossom_stats::record_latency(server_url, asked_at.elapsed().as_secs_f64() * 1000.0);
332    if !resp.status().is_success() {
333        return Ok(None);
334    }
335    let body = resp.text().await.map_err(|e| format!("Info body unreadable: {}", e))?;
336    let doc = serde_json::from_str::<Value>(&body).ok();
337    if doc.as_ref().and_then(|d| d.pointer("/caller/retry")).and_then(Value::as_str) == Some("fix_clock") {
338        crate::clock::resync_soon();
339    }
340    Ok(doc.and_then(|v| ServerInfo::parse(&v)))
341}
342
343/// The document for `server_url`, fetched unless a copy younger than
344/// `max_age` is held.
345pub async fn refresh<T>(signer: &T, server_url: &str, max_age: Duration) -> Result<Option<ServerInfo>, String>
346where
347    T: VectorSigner,
348{
349    if age_of(server_url).is_some_and(|age| age < max_age) {
350        return Ok(cached(server_url));
351    }
352    let info = fetch(signer, server_url).await?;
353    match &info {
354        Some(i) => crate::log_info!(
355            "[Blossom Info] {} → {} {} (personalised: {}, tier: {})",
356            server_url,
357            i.software.as_deref().unwrap_or("?"),
358            i.version.as_deref().unwrap_or(""),
359            i.is_personalised(),
360            i.caller.as_ref().map(|c| c.tier.as_str()).unwrap_or("-"),
361        ),
362        None => crate::log_debug!("[Blossom Info] {} has no information document", server_url),
363    }
364    store(server_url, info.clone());
365    Ok(info)
366}
367
368/// Refresh every server, concurrently. Returns how many have a document.
369pub async fn refresh_all<T>(signer: T, server_urls: Vec<String>, max_age: Duration) -> usize
370where
371    T: VectorSigner + Clone,
372{
373    let futures = server_urls.into_iter().map(|server| {
374        let signer = signer.clone();
375        async move {
376            match refresh(&signer, &server, max_age).await {
377                Ok(Some(_)) => true,
378                Ok(None) => false,
379                Err(e) => {
380                    crate::log_debug!("[Blossom Info] {} not fetched: {}", server, e);
381                    false
382                }
383            }
384        }
385    });
386    futures_util::future::join_all(futures)
387        .await
388        .into_iter()
389        .filter(|has| *has)
390        .count()
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396    use serde_json::json;
397
398    fn magnitude_doc() -> Value {
399        json!({
400            "name": "Magnitude", "software": "magnitude", "version": "0.1.0",
401            "buds": [1, 2, 4, 6, 8, 11, 12],
402            "extensions": ["magnitude-info", "magnitude-errors"],
403            "accepts": { "max_blob": 1073741824, "mime": ["*/*"] },
404            "capacity": { "stored_bytes": 552631601, "limit_bytes": 107374182400u64 },
405            "description": "Media server for Vector",
406            "caller": {
407                "pubkey": "ab", "tier": "badged", "max_blob": 1073741824,
408                "storage_used": 1000, "storage_limit": 26843545600u64, "blobs": 3,
409                "daily_used": 500, "daily_limit": 10737418240u64, "rps": 10,
410                "allowed": true, "reasons": []
411            }
412        })
413    }
414
415    #[test]
416    fn a_magnitude_document_is_read_in_full() {
417        let info = ServerInfo::parse(&magnitude_doc()).unwrap();
418        assert_eq!(info.name.as_deref(), Some("Magnitude"));
419        assert_eq!(info.buds, vec![1, 2, 4, 6, 8, 11, 12]);
420        assert!(info.is_personalised());
421        assert_eq!(info.max_blob, Some(1073741824));
422        assert_eq!(info.capacity_limit, Some(107374182400));
423        let c = info.caller.unwrap();
424        assert_eq!(c.tier, "badged");
425        assert_eq!(c.storage_limit, 26843545600);
426        assert!(c.allowed);
427    }
428
429    #[test]
430    fn the_caller_block_decides_what_is_accepted() {
431        let info = ServerInfo::parse(&magnitude_doc()).unwrap();
432        assert_eq!(info.accepts_size(1 << 20), Some(true));
433        assert_eq!(info.accepts_size(2 << 30), Some(false));
434        assert_eq!(info.refusal_reason("m.example", 1 << 20), None);
435        assert_eq!(
436            info.refusal_reason("m.example", 2 << 30),
437            Some("m.example allows files up to 1.0 GB for your account.".to_string()),
438        );
439    }
440
441    #[test]
442    fn a_closed_gate_refuses_every_size_and_says_why() {
443        let mut doc = magnitude_doc();
444        doc["caller"] = json!({
445            "tier": "default", "max_blob": 0, "allowed": false,
446            "reasons": ["Uploads require a profile published from Vector"]
447        });
448        let info = ServerInfo::parse(&doc).unwrap();
449        assert_eq!(info.accepts_size(1), Some(false));
450        assert_eq!(
451            info.refusal_reason("m.example", 1),
452            Some("m.example: Uploads require a profile published from Vector".to_string()),
453        );
454    }
455
456    #[test]
457    fn a_plan_label_is_taken_within_bounds_and_dropped_whole_beyond_them() {
458        let mut doc = magnitude_doc();
459        doc["caller"]["plan"] = json!({ "title": "  Premium ", "description": "Earned by\nearly  supporters." });
460        let c = ServerInfo::parse(&doc).unwrap().caller.unwrap();
461        assert_eq!(c.plan_title.as_deref(), Some("Premium"));
462        assert_eq!(c.plan_description.as_deref(), Some("Earned by early supporters."));
463
464        doc["caller"]["plan"] = json!({ "title": "x".repeat(25), "description": "y".repeat(101) });
465        let c = ServerInfo::parse(&doc).unwrap().caller.unwrap();
466        assert_eq!(c.plan_title, None, "not truncated: dropped");
467        assert_eq!(c.plan_description, None);
468
469        doc["caller"]["plan"] = json!({ "title": "Bad\u{7}", "description": "" });
470        let c = ServerInfo::parse(&doc).unwrap().caller.unwrap();
471        assert_eq!(c.plan_title, None);
472        assert_eq!(c.plan_description, None);
473
474        doc["caller"].as_object_mut().unwrap().remove("plan");
475        let c = ServerInfo::parse(&doc).unwrap().caller.unwrap();
476        assert_eq!(c.plan_title, None);
477    }
478
479    #[test]
480    fn a_bad_token_leaves_a_caller_that_is_not_allowed() {
481        // The shape Magnitude sends when the Authorization header did not verify.
482        let mut doc = magnitude_doc();
483        doc["caller"] = json!({ "allowed": false, "reasons": ["authorization expired"] });
484        let info = ServerInfo::parse(&doc).unwrap();
485        let c = info.caller.unwrap();
486        assert!(!c.allowed);
487        assert_eq!(c.tier, "");
488        assert_eq!(c.reasons, vec!["authorization expired"]);
489    }
490
491    #[test]
492    fn a_document_without_a_caller_falls_back_to_the_server_wide_limit() {
493        let mut doc = magnitude_doc();
494        doc.as_object_mut().unwrap().remove("caller");
495        let info = ServerInfo::parse(&doc).unwrap();
496        assert_eq!(info.accepts_size(1 << 20), Some(true));
497        assert_eq!(info.accepts_size(2 << 30), Some(false));
498        assert_eq!(info.refusal_reason("m.example", 2 << 30), Some("m.example allows files up to 1.0 GB.".to_string()));
499    }
500
501    #[test]
502    fn a_bare_bud_list_says_nothing_about_size() {
503        let info = ServerInfo::parse(&json!({ "buds": [1, 2] })).unwrap();
504        assert!(!info.is_personalised());
505        assert_eq!(info.accepts_size(1), None);
506        assert_eq!(info.refusal_reason("x", 1), None);
507    }
508
509    #[test]
510    fn something_that_is_not_a_document_is_not_one() {
511        assert!(ServerInfo::parse(&json!({ "status": "ok" })).is_none());
512        assert!(ServerInfo::parse(&json!("<html>")).is_none());
513        assert!(ServerInfo::parse(&json!([1, 2, 3])).is_none());
514    }
515
516    #[test]
517    fn a_noted_upload_moves_the_usage_counters() {
518        // The cache lives on the session, which a concurrent database test can replace.
519        let _serialized = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
520        let info = ServerInfo::parse(&magnitude_doc()).unwrap();
521        store("https://m.example/", Some(info));
522        note_upload("https://M.example", 250);
523        let c = cached("https://m.example").unwrap().caller.unwrap();
524        assert_eq!(c.storage_used, 1250);
525        assert_eq!(c.daily_used, 750);
526        assert_eq!(c.blobs, 4);
527        invalidate("https://m.example");
528        assert!(cached("https://m.example").is_none());
529    }
530}