Skip to main content

vector_core/
relay_info.rs

1//! What Vector shows of a relay: its NIP-11 name and icon, and whether it asks clients to AUTH.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5use std::time::Duration;
6
7use futures_util::StreamExt;
8
9#[derive(serde::Serialize, Clone, Debug, Default, PartialEq, Eq)]
10pub struct RelayInfo {
11    pub name: Option<String>,
12    /// An `https` URL, for the backend image cache: the webview never loads it itself.
13    pub icon: Option<String>,
14    /// The relay says it requires NIP-42 AUTH, or it has challenged Vector since launch.
15    pub auth: bool,
16}
17
18const FRESH: Duration = Duration::from_secs(60 * 60);
19const FAILED_FRESH: Duration = Duration::from_secs(5 * 60);
20const DOC_MAX_BYTES: usize = 64 * 1024;
21const NAME_MAX_CHARS: usize = 48;
22const ICON_MAX_BYTES: usize = 2048;
23
24struct Memo;
25type Entries = Mutex<HashMap<String, (RelayInfo, web_time::Instant, Duration)>>;
26
27fn memo() -> Arc<Entries> {
28    crate::db::current_session().scoped::<Memo, _>()
29}
30
31/// The relay's info, fetched over the network in use at most once an hour per account. A relay
32/// that serves no document still reports a challenge it sent since launch.
33pub async fn relay_info(relay_url: &str) -> Result<RelayInfo, String> {
34    let url = crate::transport::validate_relay_url(relay_url)?;
35    let key = crate::inbox_relays::normalize_relay_url(&url);
36    let cached = memo().lock().unwrap_or_else(|e| e.into_inner()).get(&key).filter(|(_, at, fresh)| at.elapsed() < *fresh).map(|(i, ..)| i.clone());
37    let mut info = match cached {
38        Some(info) => info,
39        None => {
40            let doc = fetch_document(&url).await;
41            let fresh = if doc.is_some() { FRESH } else { FAILED_FRESH };
42            let info = doc.as_ref().map(from_document).unwrap_or_default();
43            memo().lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone(), (info.clone(), web_time::Instant::now(), fresh));
44            info
45        }
46    };
47    info.auth |= crate::community::v2::streamauth::challenged(&url);
48    Ok(info)
49}
50
51async fn fetch_document(relay_url: &str) -> Option<serde_json::Value> {
52    let url = crate::transport::nip11_url(relay_url).ok()?;
53    crate::net::validate_url_not_private(&url).ok()?;
54    let timeout = crate::transport::budget(crate::transport::budget::Op::HttpTotal, Duration::from_secs(10));
55    let client = crate::net::build_http_client(timeout).ok()?;
56    let resp = client.get(url).header("Accept", "application/nostr+json").send().await.ok()?;
57    if !resp.status().is_success() || resp.content_length().is_some_and(|n| n > DOC_MAX_BYTES as u64) {
58        return None;
59    }
60    let mut body = Vec::new();
61    let mut stream = resp.bytes_stream();
62    while let Some(chunk) = stream.next().await {
63        body.extend_from_slice(&chunk.ok()?);
64        if body.len() > DOC_MAX_BYTES {
65            return None;
66        }
67    }
68    serde_json::from_slice(&body).ok()
69}
70
71/// The parts of a NIP-11 document Vector shows, each dropped when it isn't what it should be.
72pub fn from_document(doc: &serde_json::Value) -> RelayInfo {
73    let name = doc.get("name").and_then(|v| v.as_str()).map(clean_name).filter(|n| !n.is_empty());
74    let icon = doc
75        .get("icon")
76        .and_then(|v| v.as_str())
77        .map(str::trim)
78        .filter(|s| s.len() <= ICON_MAX_BYTES)
79        .and_then(|s| url::Url::parse(s).ok())
80        .filter(|u| u.scheme() == "https" && u.host_str().is_some())
81        .map(String::from);
82    let auth = doc.pointer("/limitation/auth_required").and_then(|v| v.as_bool()) == Some(true);
83    RelayInfo { name, icon, auth }
84}
85
86/// One line of at most [`NAME_MAX_CHARS`]: control and format characters go, runs of spaces close up.
87fn clean_name(raw: &str) -> String {
88    let mut out = String::new();
89    for word in raw.split(|c: char| c.is_whitespace() || c.is_control()).filter(|w| !w.is_empty()) {
90        if !out.is_empty() {
91            out.push(' ');
92        }
93        out.extend(word.chars().filter(|c| !is_format(*c)));
94    }
95    if out.chars().count() > NAME_MAX_CHARS {
96        out = out.chars().take(NAME_MAX_CHARS - 1).collect::<String>().trim_end().to_string() + "…";
97    }
98    out
99}
100
101/// Bidi overrides and zero-width characters: they can make a name read as something else.
102fn is_format(c: char) -> bool {
103    matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}')
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use serde_json::json;
110
111    #[test]
112    fn a_document_gives_its_name_icon_and_auth_requirement() {
113        let doc = json!({ "name": "  Vector\tRelay \n", "icon": "https://relay.example/icon.png", "limitation": { "auth_required": true } });
114        assert_eq!(from_document(&doc), RelayInfo { name: Some("Vector Relay".into()), icon: Some("https://relay.example/icon.png".into()), auth: true });
115    }
116
117    #[test]
118    fn what_a_document_gets_wrong_is_left_out() {
119        for icon in ["http://relay.example/icon.png", "data:image/png;base64,AAAA", "javascript:alert(1)", "not a url"] {
120            assert_eq!(from_document(&json!({ "icon": icon })).icon, None, "{icon}");
121        }
122        assert_eq!(from_document(&json!({ "icon": format!("https://relay.example/{}", "a".repeat(ICON_MAX_BYTES)) })).icon, None);
123        assert_eq!(from_document(&json!({ "name": " \u{202E}\u{200B} " })).name, None);
124        assert!(!from_document(&json!({ "limitation": { "auth_required": "yes" } })).auth);
125        assert_eq!(from_document(&json!(["not", "an", "object"])), RelayInfo::default());
126    }
127
128    #[test]
129    fn a_name_is_one_short_line_that_reads_as_itself() {
130        assert_eq!(clean_name("Evil\u{202E}gnp.exe"), "Evilgnp.exe");
131        assert_eq!(clean_name("a\u{0}b\r\nc"), "a b c");
132        let long = clean_name(&"x".repeat(200));
133        assert_eq!(long.chars().count(), NAME_MAX_CHARS);
134        assert!(long.ends_with('…'));
135    }
136
137    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
138        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
139        crate::db::close_database();
140        crate::db::clear_id_caches();
141        use nostr_sdk::prelude::ToBech32;
142        let tmp = tempfile::tempdir().unwrap();
143        let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
144        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
145        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
146        crate::db::set_current_account(account.clone()).unwrap();
147        crate::db::init_database(&account).unwrap();
148        (tmp, guard)
149    }
150
151    #[tokio::test]
152    async fn auth_shows_for_a_live_challenge_never_for_one_recorded_long_ago() {
153        let (_tmp, _guard) = init_test_db();
154        let url = "wss://quiet.relay.invalid";
155        crate::db::set_sql_setting(format!("auth_gate:{}", crate::inbox_relays::normalize_relay_url(url)), "1".into()).unwrap();
156        assert!(!relay_info(url).await.unwrap().auth, "a relay that challenged under other software once is not AUTH now");
157        crate::community::v2::streamauth::note_challenge(&format!("{url}/"));
158        assert!(relay_info(url).await.unwrap().auth, "a cached answer still reads the live challenge");
159        assert!(relay_info("https://not.a.relay").await.is_err());
160    }
161}