Skip to main content

cosmic_applet_avestruz/nostr/
nip05.rs

1// SPDX-License-Identifier: MIT
2
3//! Names at a domain (NIP-05): `ana@example.com`.
4//!
5//! Anyone can write any name into their profile. It is theirs only if the
6//! domain says so: `https://<domain>/.well-known/nostr.json?name=<name>`
7//! has to give their public key for that name. Until it has, the name is
8//! not shown; a name that could be shown unchecked is a name that could be
9//! borrowed.
10//!
11//! The domain has to answer itself. An answer from somewhere it redirects
12//! to is not taken, as NIP-05 has it.
13
14use nostr_sdk::prelude::{Nip05Address, Nip05Profile, PublicKey, verify_from_raw_json};
15
16use crate::http;
17
18/// The most a domain's answer may weigh. Asked for one name, a domain
19/// answers with one; some answer with every name they have.
20const ANSWER_MAX_BYTES: usize = 1024 * 1024;
21
22/// What `claimed` says, if it is a name at a domain: the name in lower
23/// case, which is how it is looked up, and where to ask.
24fn parse(claimed: &str) -> Option<Nip05Address> {
25    let claimed = claimed.trim().to_lowercase();
26    let address = Nip05Address::parse(&claimed).ok()?;
27    let name_is_plain =
28        !address.name().is_empty() && address.name().chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
29    // What follows the `@` has to be a host and nothing more: anything
30    // else would have the question asked of another place on it.
31    let url = address.url();
32    let domain_is_a_host = address.domain().contains('.')
33        && url.host_str() == Some(address.domain())
34        && url.path() == "/.well-known/nostr.json"
35        && url.port().is_none()
36        && url.username().is_empty();
37    (name_is_plain && domain_is_a_host).then_some(address)
38}
39
40/// How a name shows: `ana@example.com`, or the domain alone for the name
41/// `_`, which stands for the domain itself.
42pub fn shown(claimed: &str) -> String {
43    match parse(claimed) {
44        Some(address) if address.name() == "_" => address.domain().to_string(),
45        Some(address) => address.to_string(),
46        None => claimed.trim().to_string(),
47    }
48}
49
50/// Whether the domain in `claimed` says that name is `public_key`'s.
51/// Anything short of that is no: a name that isn't one, a domain that
52/// doesn't answer, an answer that names someone else.
53pub async fn verify(http: &reqwest::Client, public_key: PublicKey, claimed: &str) -> bool {
54    let Some(address) = parse(claimed) else {
55        return false;
56    };
57    match http::get_in_place(http, address.url().as_str(), ANSWER_MAX_BYTES).await {
58        Ok(answer) => verify_from_raw_json(&public_key, &address, &String::from_utf8_lossy(&answer)).unwrap_or(false),
59        Err(e) => {
60            tracing::debug!("{} did not answer for {}: {e}", address.domain(), address.name());
61            false
62        }
63    }
64}
65
66/// Whether `typed` reads as a name at a domain, `ana@example.com`: what
67/// can be asked of the domain. A domain alone does not: it reads as a
68/// word, or as the address of a page.
69pub fn is_name(typed: &str) -> bool {
70    typed.contains('@') && parse(typed).is_some()
71}
72
73/// Whose name `claimed` is, as its domain says. Nobody's, if it is no
74/// name at a domain, the domain doesn't answer, or it knows no such name.
75pub async fn resolve(http: &reqwest::Client, claimed: &str) -> Option<PublicKey> {
76    let address = parse(claimed)?;
77    match http::get_in_place(http, address.url().as_str(), ANSWER_MAX_BYTES).await {
78        Ok(answer) => Nip05Profile::from_raw_json(&address, &String::from_utf8_lossy(&answer)).ok().map(|named| named.public_key),
79        Err(e) => {
80            tracing::debug!("{} did not answer for {}: {e}", address.domain(), address.name());
81            None
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::{is_name, parse, shown};
89    use nostr_sdk::prelude::{Keys, verify_from_raw_json};
90
91    #[test]
92    fn a_name_at_a_domain_is_told_from_a_word_and_from_a_domain() {
93        assert!(is_name("ana@example.com") && is_name(" Ana@Example.com "));
94        for not_a_name in ["example.com", "ana", "ana@localhost", "two words@example.com", "@example.com", ""] {
95            assert!(!is_name(not_a_name), "{not_a_name}");
96        }
97    }
98
99    #[test]
100    fn a_name_is_asked_of_its_own_domain_and_nowhere_else() {
101        let url = |claimed: &str| parse(claimed).map(|address| address.url().to_string());
102        assert_eq!(url("ana@example.com").as_deref(), Some("https://example.com/.well-known/nostr.json?name=ana"));
103        assert_eq!(url(" Ana@Example.com ").as_deref(), Some("https://example.com/.well-known/nostr.json?name=ana"));
104        assert_eq!(url("example.com").as_deref(), Some("https://example.com/.well-known/nostr.json?name=_"));
105
106        // Not a host, or more than a host.
107        assert_eq!(url("ana@localhost"), None);
108        assert_eq!(url("ana@example.com/elsewhere?x="), None);
109        assert_eq!(url("ana@example.com:8443"), None);
110        assert_eq!(url("ana@someone@example.com"), None);
111        assert_eq!(url("ana@example.com#"), None);
112        // Not a name.
113        assert_eq!(url("ana&name=bruno@example.com"), None);
114        assert_eq!(url("@example.com"), None);
115        assert_eq!(url(""), None);
116    }
117
118    #[test]
119    fn a_name_shows_whole_and_the_domains_own_name_as_the_domain() {
120        assert_eq!(shown("Ana@Example.com"), "ana@example.com");
121        assert_eq!(shown("_@example.com"), "example.com");
122        assert_eq!(shown("example.com"), "example.com");
123    }
124
125    #[test]
126    fn a_name_is_someones_only_if_the_domain_gives_their_key_for_it() {
127        let (ana, bruno) = (Keys::generate().public_key(), Keys::generate().public_key());
128        let address = parse("ana@example.com").unwrap();
129        let answer = format!(r#"{{"names":{{"ana":"{}"}}}}"#, ana.to_hex());
130
131        assert_eq!(verify_from_raw_json(&ana, &address, &answer).ok(), Some(true));
132        assert_eq!(verify_from_raw_json(&bruno, &address, &answer).ok(), Some(false), "someone else's name");
133        assert_eq!(verify_from_raw_json(&ana, &address, r#"{"names":{}}"#).ok(), Some(false));
134        assert!(verify_from_raw_json(&ana, &address, "<html>").is_err());
135    }
136}