Skip to main content

spoolframe_protocol/
well_known.rs

1//! The server's document at its web address: how a device that has
2//! only the address a person typed (`sf.example.org`) learns the key to
3//! dial.
4//!
5//! Iroh dials by key, and a person cannot type 64 hex digits on a TV
6//! remote. A server with `admin.public_url` set answers
7//! `GET https://<its host>/.well-known/spoolframe` with
8//! [`ServerDocument`] as JSON: what its invite links say of it before a
9//! code is put in them ([`crate::invite::Invite`]), and no secret. A
10//! server without `public_url` is not meant to be found from outside, and
11//! answers 404.
12//!
13//! The document is fetched over HTTPS only: the key in it is what the
14//! device then dials, and the user compares the fingerprint the QUIC
15//! handshake proves with the one the server's web UI shows before they
16//! save it as verified. Over plain HTTP anyone on the path could name
17//! their own key.
18
19use std::net::SocketAddr;
20
21use serde::{Deserialize, Serialize};
22
23use crate::invite::{Invite, MAX_HINTS, is_relay_url};
24
25/// Where the document is, at the root of the server's web origin.
26pub const PATH: &str = "/.well-known/spoolframe";
27
28/// The longest document a device reads, in bytes: one with
29/// [`MAX_HINTS`] addresses and relays is a few KiB.
30pub const MAX_DOCUMENT: usize = 64 * 1024;
31
32/// How long a device or a proxy may keep the document, in seconds: its
33/// addresses change when the server's network does.
34pub const MAX_AGE_SECS: u32 = 300;
35
36/// What a server says of itself at [`PATH`].
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct ServerDocument {
39    /// The server's `EndpointId`, hex: the key a device dials.
40    pub endpoint_id: String,
41    /// What the server calls itself.
42    pub name: String,
43    /// Addresses it may be reached at, `ip:port`.
44    #[serde(default)]
45    pub addrs: Vec<String>,
46    /// The URLs of relays it may be reached through.
47    #[serde(default)]
48    pub relays: Vec<String>,
49    /// The pkarr relay it publishes where it is to.
50    #[serde(default)]
51    pub lookup: Option<String>,
52}
53
54impl ServerDocument {
55    /// The document of a server whose invite link (with no code) is
56    /// `invite`: the same key, name, addresses, relays and lookup.
57    pub fn of(invite: &Invite) -> Self {
58        Self {
59            endpoint_id: invite.server.clone(),
60            name: invite.name.clone().unwrap_or_default(),
61            addrs: invite
62                .addrs
63                .iter()
64                .take(MAX_HINTS)
65                .map(ToString::to_string)
66                .collect(),
67            relays: invite.relays.iter().take(MAX_HINTS).cloned().collect(),
68            lookup: invite.lookup.clone(),
69        }
70    }
71
72    /// The addresses that read as `ip:port`, each once, at most
73    /// [`MAX_HINTS`]; the rest are left out.
74    pub fn socket_addrs(&self) -> Vec<SocketAddr> {
75        let mut addrs: Vec<SocketAddr> = Vec::new();
76        for addr in self.addrs.iter().filter_map(|a| a.parse().ok()) {
77            if !addrs.contains(&addr) {
78                addrs.push(addr);
79            }
80            if addrs.len() == MAX_HINTS {
81                break;
82            }
83        }
84        addrs
85    }
86
87    /// The relays that are plain http(s) URLs, each once, at most
88    /// [`MAX_HINTS`], as an invite link's are read.
89    pub fn relay_urls(&self) -> Vec<String> {
90        let mut relays: Vec<String> = Vec::new();
91        for relay in self.relays.iter().filter(|r| is_relay_url(r)) {
92            if !relays.contains(relay) {
93                relays.push(relay.clone());
94            }
95            if relays.len() == MAX_HINTS {
96                break;
97            }
98        }
99        relays
100    }
101
102    /// The lookup, if it is a plain http(s) URL.
103    pub fn lookup_url(&self) -> Option<String> {
104        self.lookup.clone().filter(|url| is_relay_url(url))
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn the_document_says_what_the_invite_link_says() {
114        let invite = Invite {
115            server: "ab".repeat(32),
116            name: Some("Home Media".into()),
117            addrs: vec!["203.0.113.7:7420".parse().unwrap()],
118            relays: vec!["https://relay.example.org/".into()],
119            lookup: Some("https://dns.example.org/pkarr".into()),
120            code: Some("QW7K2MFPXR4T".into()),
121            ..Invite::default()
122        };
123        let json = serde_json::to_value(ServerDocument::of(&invite)).unwrap();
124        assert_eq!(
125            json,
126            serde_json::json!({
127                "endpoint_id": "ab".repeat(32),
128                "name": "Home Media",
129                "addrs": ["203.0.113.7:7420"],
130                "relays": ["https://relay.example.org/"],
131                "lookup": "https://dns.example.org/pkarr",
132            })
133        );
134    }
135
136    #[test]
137    fn hints_are_read_as_an_invite_links_are() {
138        let doc = ServerDocument {
139            endpoint_id: String::new(),
140            name: String::new(),
141            addrs: (0..MAX_HINTS + 3)
142                .map(|i| format!("10.0.0.{}:7420", i % 250))
143                .chain(["not an address".into(), "10.0.0.0:7420".into()])
144                .collect(),
145            relays: vec![
146                "https://relay.example.org/".into(),
147                "https://relay.example.org/".into(),
148                "ftp://relay.example.org/".into(),
149                "http://relay.lan/".into(),
150            ],
151            lookup: Some("javascript:alert(1)".into()),
152        };
153        assert_eq!(doc.socket_addrs().len(), MAX_HINTS);
154        assert_eq!(
155            doc.relay_urls(),
156            vec!["https://relay.example.org/", "http://relay.lan/"]
157        );
158        assert_eq!(doc.lookup_url(), None);
159    }
160
161    #[test]
162    fn a_document_with_only_a_key_and_name_reads() {
163        let doc: ServerDocument =
164            serde_json::from_str(r#"{"endpoint_id":"ab","name":"x"}"#).unwrap();
165        assert!(doc.addrs.is_empty() && doc.relays.is_empty() && doc.lookup.is_none());
166    }
167}