Skip to main content

vector_core/
blossom_servers.rs

1//! BUD-03 user blossom server list (kind 10063) — store, merge, publish, fetch.
2//!
3//! Two SQL settings rows back the user's preferences:
4//!   * `custom_blossom_servers`             — `Vec<CustomBlossomServer>` JSON
5//!   * `disabled_default_blossom_servers`   — `Vec<String>` JSON
6//!
7//! Resolution order (BUD-03 trust order): enabled defaults, then enabled customs.
8
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::collections::HashSet;
11
12use nostr_sdk::prelude::*;
13use serde::{Deserialize, Serialize};
14
15use crate::state::nostr_client;
16
17/// Default servers in trust order (first = first try). All verified to
18/// accept Vector's encrypted octet-stream uploads at common sizes.
19pub const DEFAULT_BLOSSOM_SERVERS: &[&str] = &[
20    "https://blossom.primal.net",
21    "https://nostr.download",
22    "https://blossom.ditto.pub",
23    "https://blossom.data.haus",
24];
25
26#[derive(Serialize, Deserialize, Clone, Debug)]
27pub struct CustomBlossomServer {
28    pub url: String,
29    pub enabled: bool,
30}
31
32/// Validate + canonicalize a server URL: trim, strip trailing slash,
33/// auto-prefix `https://` on bare domains, enforce http(s) + non-empty host.
34pub fn validate_url(url: &str) -> Result<String, String> {
35    let trimmed = url.trim();
36    if trimmed.is_empty() {
37        return Err("URL cannot be empty".to_string());
38    }
39    let with_scheme = if trimmed.contains("://") {
40        trimmed.to_string()
41    } else {
42        format!("https://{}", trimmed)
43    };
44    let parsed = ::url::Url::parse(&with_scheme)
45        .map_err(|e| format!("Invalid URL: {}", e))?;
46    let scheme = parsed.scheme();
47    if scheme != "https" && scheme != "http" {
48        return Err("URL must use https:// or http://".to_string());
49    }
50    if parsed.host_str().map_or(true, str::is_empty) {
51        return Err("URL must include a host".to_string());
52    }
53    Ok(with_scheme.trim_end_matches('/').to_string())
54}
55
56/// One row in the frontend's Media Servers list.
57#[derive(Serialize, Clone, Debug)]
58pub struct BlossomServerInfo {
59    pub url: String,
60    pub is_default: bool,
61    pub is_custom: bool,
62    pub enabled: bool,
63}
64
65// ============================================================================
66// Storage
67// ============================================================================
68
69pub fn load_custom_blossom_servers() -> Result<Vec<CustomBlossomServer>, String> {
70    match crate::db::get_sql_setting("custom_blossom_servers".to_string())
71        .ok().flatten()
72    {
73        Some(json) => serde_json::from_str(&json)
74            .map_err(|e| format!("Failed to parse custom_blossom_servers: {}", e)),
75        None => Ok(Vec::new()),
76    }
77}
78
79pub fn save_custom_blossom_servers(servers: &[CustomBlossomServer]) -> Result<(), String> {
80    let json = serde_json::to_string(servers)
81        .map_err(|e| format!("Failed to serialize custom blossom servers: {}", e))?;
82    crate::db::set_sql_setting("custom_blossom_servers".to_string(), json)
83}
84
85pub fn load_disabled_default_blossom_servers() -> Result<Vec<String>, String> {
86    match crate::db::get_sql_setting("disabled_default_blossom_servers".to_string())
87        .ok().flatten()
88    {
89        Some(json) => serde_json::from_str(&json)
90            .map_err(|e| format!("Failed to parse disabled_default_blossom_servers: {}", e)),
91        None => Ok(Vec::new()),
92    }
93}
94
95pub fn save_disabled_default_blossom_servers(urls: &[String]) -> Result<(), String> {
96    let json = serde_json::to_string(urls)
97        .map_err(|e| format!("Failed to serialize disabled default blossom servers: {}", e))?;
98    crate::db::set_sql_setting("disabled_default_blossom_servers".to_string(), json)
99}
100
101// ============================================================================
102// Resolver — defaults (minus disabled) + enabled customs, preserving order
103// ============================================================================
104
105pub fn is_default_server(url: &str) -> bool {
106    let norm = url.trim().trim_end_matches('/').to_lowercase();
107    DEFAULT_BLOSSOM_SERVERS.iter()
108        .any(|d| d.trim_end_matches('/').to_lowercase() == norm)
109}
110
111/// Race-guard for in-flight probes: true if `url` is in the currently
112/// enabled list at this moment.
113pub fn is_enabled_server(url: &str) -> bool {
114    let target = url.trim().trim_end_matches('/').to_lowercase();
115    compute_enabled_servers().iter()
116        .any(|s| s.trim_end_matches('/').to_lowercase() == target)
117}
118
119pub fn compute_enabled_servers() -> Vec<String> {
120    let disabled = load_disabled_default_blossom_servers().unwrap_or_default();
121    let disabled_lower: HashSet<String> = disabled.iter()
122        .map(|s| s.trim().trim_end_matches('/').to_lowercase())
123        .collect();
124
125    let mut out: Vec<String> = Vec::new();
126    for d in DEFAULT_BLOSSOM_SERVERS {
127        let key = d.trim_end_matches('/').to_lowercase();
128        if !disabled_lower.contains(&key) {
129            out.push((*d).to_string());
130        }
131    }
132    let customs = load_custom_blossom_servers().unwrap_or_default();
133    for c in customs {
134        if c.enabled {
135            out.push(c.url);
136        }
137    }
138    out
139}
140
141/// All rows for the frontend (defaults then customs, including disabled).
142pub fn list_all_servers() -> Vec<BlossomServerInfo> {
143    let disabled = load_disabled_default_blossom_servers().unwrap_or_default();
144    let disabled_lower: HashSet<String> = disabled.iter()
145        .map(|s| s.trim().trim_end_matches('/').to_lowercase())
146        .collect();
147
148    let mut out: Vec<BlossomServerInfo> = Vec::new();
149    for d in DEFAULT_BLOSSOM_SERVERS {
150        let key = d.trim_end_matches('/').to_lowercase();
151        out.push(BlossomServerInfo {
152            url: (*d).to_string(),
153            is_default: true,
154            is_custom: false,
155            enabled: !disabled_lower.contains(&key),
156        });
157    }
158    for c in load_custom_blossom_servers().unwrap_or_default() {
159        out.push(BlossomServerInfo {
160            url: c.url,
161            is_default: false,
162            is_custom: true,
163            enabled: c.enabled,
164        });
165    }
166    out
167}
168
169/// Refresh the in-memory `BLOSSOM_SERVERS` cache. Call after edits + on login.
170pub fn refresh_cache() {
171    let merged = compute_enabled_servers();
172    let mutex = crate::state::BLOSSOM_SERVERS
173        .get_or_init(|| std::sync::Mutex::new(merged.clone()));
174    if let Ok(mut guard) = mutex.lock() {
175        *guard = merged;
176    }
177}
178
179// ============================================================================
180// BUD-03 publish (kind 10063)
181// ============================================================================
182
183/// Publish the resolved enabled list (defaults + customs, in trust order)
184/// as a BUD-03 kind 10063 replaceable event. Peers using our list as a
185/// fallback need to see every server we use, not just the customs.
186pub async fn publish_blossom_servers(client: &Client) -> Result<(), String> {
187    let servers = compute_enabled_servers();
188    let mut builder = EventBuilder::new(Kind::Custom(10063), "");
189    for url in &servers {
190        builder = builder.tag(Tag::custom(TagKind::custom("server"), vec![url.clone()]));
191    }
192    client.send_event_builder(builder).await
193        .map_err(|e| format!("Failed to publish blossom servers: {}", e))?;
194    crate::log_info!("[BlossomServers] Published kind 10063 with {} server(s)", servers.len());
195    Ok(())
196}
197
198static REPUBLISH_GEN: AtomicU64 = AtomicU64::new(0);
199
200/// Debounced republish: rapid edits coalesce; mid-window session swap aborts.
201/// Retries once on failure (5s backoff): a stale event on the network would
202/// otherwise let `fetch_and_merge_own_list` overwrite the local prefs on
203/// the next boot.
204pub fn republish_blossom_servers_debounced() {
205    let gen = REPUBLISH_GEN.fetch_add(1, Ordering::SeqCst) + 1;
206    let session = crate::state::SessionGuard::capture();
207    tokio::spawn(async move {
208        tokio::time::sleep(std::time::Duration::from_millis(800)).await;
209        if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
210        if !session.is_valid() { return; }
211        let client = match nostr_client() {
212            Some(c) => c,
213            None => return,
214        };
215        if let Err(e) = publish_blossom_servers(&client).await {
216            crate::log_warn!("[BlossomServers] Republish failed: {} (retrying in 5s)", e);
217            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
218            if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
219            if !session.is_valid() { return; }
220            if let Err(e2) = publish_blossom_servers(&client).await {
221                crate::log_warn!("[BlossomServers] Republish retry failed: {}", e2);
222            }
223        }
224    });
225}
226
227// ============================================================================
228// BUD-03 fetch — pull our own kind 10063, merge into customs
229// ============================================================================
230
231/// Pure merge: append novel URLs from `incoming` (validated, normalized)
232/// into `customs` as enabled. Existing rows are never removed or reordered.
233pub fn merge_urls_into_customs(
234    incoming: &[String],
235    mut customs: Vec<CustomBlossomServer>,
236) -> (Vec<CustomBlossomServer>, usize) {
237    let mut known_lower: HashSet<String> = customs.iter()
238        .map(|c| c.url.trim_end_matches('/').to_lowercase())
239        .collect();
240    for d in DEFAULT_BLOSSOM_SERVERS {
241        known_lower.insert(d.trim_end_matches('/').to_lowercase());
242    }
243
244    let mut added = 0usize;
245    for raw in incoming {
246        let normalized = match validate_url(raw) {
247            Ok(u) => u,
248            Err(_) => continue,
249        };
250        let key = normalized.to_lowercase();
251        if known_lower.contains(&key) { continue; }
252        customs.push(CustomBlossomServer { url: normalized, enabled: true });
253        known_lower.insert(key);
254        added += 1;
255    }
256    (customs, added)
257}
258
259/// Fetch our latest kind 10063 and reconcile: append unknown customs,
260/// follow the originating device's default enable/disable choices.
261/// `session` gates writes against a mid-fetch account swap.
262pub async fn fetch_and_merge_own_list(
263    client: &Client,
264    my_pubkey: PublicKey,
265    session: crate::state::SessionGuard,
266) -> Result<usize, String> {
267    let filter = Filter::new()
268        .author(my_pubkey)
269        .kind(Kind::Custom(10063))
270        .limit(1);
271    let events = client
272        .fetch_events(filter, std::time::Duration::from_secs(8))
273        .await
274        .map_err(|e| format!("Failed to fetch kind 10063: {}", e))?;
275
276    if !session.is_valid() { return Ok(0); }
277
278    let event = match events.into_iter().max_by_key(|e| e.created_at) {
279        Some(e) => e,
280        None => {
281            crate::log_debug!("[BlossomServers] No kind 10063 found for own pubkey");
282            return Ok(0);
283        }
284    };
285
286    let urls_from_event: Vec<String> = event.tags.iter()
287        .filter_map(|t| {
288            if t.kind() == TagKind::custom("server") {
289                t.content().map(|s| s.to_string())
290            } else {
291                None
292            }
293        })
294        .collect();
295
296    // Event presence means the user has published preferences somewhere.
297    // A default's absence from the list = explicit disable on that
298    // device. (No event at all takes the early return above.)
299    let urls_lower: HashSet<String> = urls_from_event.iter()
300        .map(|u| u.trim().trim_end_matches('/').to_lowercase())
301        .collect();
302    let mut disabled = load_disabled_default_blossom_servers().unwrap_or_default();
303    let mut defaults_changed = false;
304    for d in DEFAULT_BLOSSOM_SERVERS {
305        let key = d.trim_end_matches('/').to_lowercase();
306        let in_event = urls_lower.contains(&key);
307        let currently_disabled = disabled.iter()
308            .any(|s| s.trim_end_matches('/').to_lowercase() == key);
309        if in_event && currently_disabled {
310            disabled.retain(|s| s.trim_end_matches('/').to_lowercase() != key);
311            defaults_changed = true;
312        } else if !in_event && !currently_disabled {
313            disabled.push(d.to_string());
314            defaults_changed = true;
315        }
316    }
317
318    let customs = load_custom_blossom_servers().unwrap_or_default();
319    let (new_customs, customs_added) = merge_urls_into_customs(&urls_from_event, customs);
320
321    let any_changes = customs_added > 0 || defaults_changed;
322    if any_changes {
323        if !session.is_valid() { return Ok(0); }
324        if defaults_changed {
325            save_disabled_default_blossom_servers(&disabled)?;
326        }
327        if customs_added > 0 {
328            save_custom_blossom_servers(&new_customs)?;
329        }
330        if !session.is_valid() { return Ok(customs_added); }
331        refresh_cache();
332        crate::traits::emit_event("blossom_servers_updated", &());
333        crate::log_info!(
334            "[BlossomServers] Merged kind 10063: {} custom server(s) added, defaults reconciled (disabled now {})",
335            customs_added, disabled.len(),
336        );
337    }
338    Ok(customs_added)
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    fn custom(url: &str, enabled: bool) -> CustomBlossomServer {
346        CustomBlossomServer { url: url.to_string(), enabled }
347    }
348
349    #[test]
350    fn validate_url_strips_trailing_slash_and_whitespace() {
351        assert_eq!(validate_url("  https://example.com/  ").unwrap(), "https://example.com");
352        assert_eq!(validate_url("https://example.com").unwrap(), "https://example.com");
353    }
354
355    #[test]
356    fn validate_url_auto_prefixes_bare_domain_with_https() {
357        assert_eq!(validate_url("blossom.band").unwrap(), "https://blossom.band");
358        assert_eq!(validate_url("  blossom.primal.net/ ").unwrap(), "https://blossom.primal.net");
359    }
360
361    #[test]
362    fn validate_url_keeps_explicit_http_scheme() {
363        assert_eq!(validate_url("http://localhost:8080").unwrap(), "http://localhost:8080");
364    }
365
366    #[test]
367    fn validate_url_rejects_non_http_schemes() {
368        assert!(validate_url("ftp://example.com").is_err());
369        assert!(validate_url("wss://example.com").is_err());
370        assert!(validate_url("javascript:alert(1)").is_err());
371    }
372
373    #[test]
374    fn validate_url_rejects_empty_or_hostless() {
375        assert!(validate_url("").is_err());
376        assert!(validate_url("https://").is_err());
377        assert!(validate_url("not a url").is_err());
378    }
379
380    #[test]
381    fn is_default_server_normalizes() {
382        assert!(is_default_server("https://blossom.primal.net"));
383        assert!(is_default_server("https://blossom.primal.net/"));
384        assert!(is_default_server("HTTPS://BLOSSOM.PRIMAL.NET"));
385        assert!(!is_default_server("https://other.example.com"));
386    }
387
388    #[test]
389    fn merge_appends_new_urls_normalized() {
390        let incoming = vec![
391            "https://new.example.com/".to_string(),
392            "https://another.example.com".to_string(),
393        ];
394        let (out, added) = merge_urls_into_customs(&incoming, vec![]);
395        assert_eq!(added, 2);
396        assert_eq!(out.len(), 2);
397        assert_eq!(out[0].url, "https://new.example.com");
398        assert!(out[0].enabled);
399    }
400
401    #[test]
402    fn merge_skips_urls_already_in_customs_regardless_of_slash_or_case() {
403        let existing = vec![custom("https://Existing.example.com", true)];
404        let incoming = vec![
405            "https://existing.example.com/".to_string(),
406            "HTTPS://EXISTING.EXAMPLE.COM".to_string(),
407        ];
408        let (out, added) = merge_urls_into_customs(&incoming, existing);
409        assert_eq!(added, 0);
410        assert_eq!(out.len(), 1);
411    }
412
413    #[test]
414    fn merge_skips_default_servers() {
415        let incoming = vec!["https://blossom.primal.net/".to_string()];
416        let (out, added) = merge_urls_into_customs(&incoming, vec![]);
417        assert_eq!(added, 0);
418        assert!(out.is_empty());
419    }
420
421    #[test]
422    fn merge_drops_malformed_urls() {
423        let incoming = vec![
424            "".to_string(),
425            "not a url".to_string(),
426            "ftp://example.com".to_string(),
427            "https://".to_string(),
428            "https://valid.example.com".to_string(),
429        ];
430        let (out, added) = merge_urls_into_customs(&incoming, vec![]);
431        assert_eq!(added, 1);
432        assert_eq!(out[0].url, "https://valid.example.com");
433    }
434
435    #[test]
436    fn merge_preserves_existing_order_and_appends() {
437        let existing = vec![
438            custom("https://a.example.com", true),
439            custom("https://b.example.com", false),
440        ];
441        let incoming = vec!["https://c.example.com".to_string()];
442        let (out, _) = merge_urls_into_customs(&incoming, existing);
443        assert_eq!(out.len(), 3);
444        assert_eq!(out[0].url, "https://a.example.com");
445        assert_eq!(out[1].url, "https://b.example.com");
446        assert!(!out[1].enabled, "merge must not flip enabled state of existing rows");
447        assert_eq!(out[2].url, "https://c.example.com");
448    }
449}