Skip to main content

moreinlaw_kernel/
registration.rs

1//! How an organization announces itself to the others: the signed registration naming its
2//! address, and the checks every instance runs before believing one. A registration that fails
3//! a check is ignored, so the organization never appears on other instances.
4//!
5//! This runs when a Host publishes its organization and whenever an instance reads
6//! registrations from relays. Look here first for a bad slug, an address with a path or a
7//! trailing slash, a relay that is not `wss://`, or a signature that does not verify.
8
9use ::url::Url;
10use nostr::prelude::*;
11
12use crate::params::routes;
13pub use crate::params::{DISCOVERY_TAG, REGISTRATION_KIND, SCHEMA_VERSION};
14use crate::params::{MAX_NAME_CHARS, MAX_RELAYS, MAX_URL_CHARS};
15
16const GEOHASH_ALPHABET: &str = "0123456789bcdefghjkmnpqrstuvwxyz";
17
18/// What a Host says about itself, before it is signed.
19#[derive(Debug, Clone, PartialEq)]
20pub struct RegistrationInput {
21    pub slug: String,
22    pub name: String,
23    pub portal_url: String,
24    pub api_url: Option<String>,
25    pub relays: Vec<String>,
26    pub geohash: Option<String>,
27    /// Logo URL; when unset the builder points at this Host's Branding logo endpoint.
28    pub picture: Option<String>,
29}
30
31/// A registration that passed every check, with the facts the signature proves.
32#[derive(Debug, Clone, PartialEq)]
33pub struct HostRegistration {
34    pub slug: String,
35    pub name: String,
36    pub portal_url: String,
37    pub api_url: Option<String>,
38    pub operator_npub: String,
39    pub relays: Vec<String>,
40    pub geohash: Option<String>,
41    pub picture: Option<String>,
42    pub event_id: String,
43    pub created_at: i64,
44}
45
46pub fn valid_slug(slug: &str) -> bool {
47    (2..=63).contains(&slug.len())
48        && slug
49            .bytes()
50            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
51}
52
53/// The one spelling of a URL we accept: lowercase origin, default port dropped, no trailing
54/// slash. The phone app compares the portal origin byte for byte against the `server` tag it
55/// signs into a login, so a second spelling of the same site would break sign-in.
56pub fn check_https_url(label: &str, raw: &str, allow_path: bool) -> Result<(), String> {
57    if raw.is_empty() || raw.chars().count() > MAX_URL_CHARS {
58        return Err(format!("{label} must be 1 to {MAX_URL_CHARS} characters"));
59    }
60    let url = Url::parse(raw).map_err(|_| format!("{label} is not a valid URL"))?;
61    if url.scheme() != "https" || url.host_str().is_none() {
62        return Err(format!("{label} must be an https:// address"));
63    }
64    if !url.username().is_empty() || url.password().is_some() {
65        return Err(format!("{label} must not contain a username or password"));
66    }
67    if url.query().is_some() || url.fragment().is_some() {
68        return Err(format!("{label} must not contain a query or fragment"));
69    }
70    if !allow_path && url.path() != "/" {
71        return Err(format!(
72            "{label} must be the site address only, with no path"
73        ));
74    }
75    if raw.ends_with('/') {
76        return Err(format!("{label} must not end with a slash"));
77    }
78    let origin = url.origin().ascii_serialization();
79    let canonical = if url.path() == "/" {
80        origin
81    } else {
82        format!("{origin}{}", url.path())
83    };
84    if canonical != raw {
85        return Err(format!("{label} must be written as {canonical}"));
86    }
87    Ok(())
88}
89
90fn check_relay(raw: &str) -> Result<(), String> {
91    let url = Url::parse(raw).map_err(|_| format!("relay {raw:?} is not a valid URL"))?;
92    let bad = url.scheme() != "wss"
93        || url.host_str().is_none()
94        || !url.username().is_empty()
95        || url.password().is_some()
96        || url.fragment().is_some()
97        || raw.chars().count() > MAX_URL_CHARS;
98    if bad {
99        return Err(format!("relay {raw:?} must be a wss:// address"));
100    }
101    Ok(())
102}
103
104pub fn validate_input(input: &RegistrationInput) -> Result<(), String> {
105    if !valid_slug(&input.slug) {
106        return Err("slug must be 2 to 63 characters of a-z, 0-9 and '-'".to_string());
107    }
108    let name_len = input.name.chars().count();
109    if input.name.trim().is_empty()
110        || name_len > MAX_NAME_CHARS
111        || input.name.chars().any(char::is_control)
112    {
113        return Err(format!("name must be 1 to {MAX_NAME_CHARS} characters"));
114    }
115    check_https_url("url", &input.portal_url, false)?;
116    if let Some(api) = &input.api_url {
117        check_https_url("api", api, true)?;
118    }
119    if input.relays.is_empty() || input.relays.len() > MAX_RELAYS {
120        return Err(format!("list 1 to {MAX_RELAYS} relays"));
121    }
122    for relay in &input.relays {
123        check_relay(relay)?;
124    }
125    if let Some(p) = &input.picture {
126        check_https_url("picture", p, true)?;
127    }
128    if let Some(g) = &input.geohash {
129        let ok = (1..=12).contains(&g.len()) && g.chars().all(|c| GEOHASH_ALPHABET.contains(c));
130        if !ok {
131            return Err("geohash must be 1 to 12 characters of the geohash alphabet".to_string());
132        }
133    }
134    Ok(())
135}
136
137pub fn build_registration_event(keys: &Keys, input: &RegistrationInput) -> Result<Event, String> {
138    build_registration_event_at(keys, input, Timestamp::now())
139}
140
141/// Same as `build_registration_event` with an explicit time. Ingest keeps the newest event per
142/// Host, so tests need to sign an older and a newer one.
143pub fn build_registration_event_at(
144    keys: &Keys,
145    input: &RegistrationInput,
146    created_at: Timestamp,
147) -> Result<Event, String> {
148    validate_input(input)?;
149    let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));
150
151    let mut tags = vec![
152        Tag::identifier(input.slug.clone()),
153        tag(&["name", &input.name])?,
154        tag(&["url", &input.portal_url])?,
155    ];
156    if let Some(api) = &input.api_url {
157        tags.push(tag(&["api", api])?);
158    }
159    if let Some(g) = &input.geohash {
160        tags.push(tag(&["g", g])?);
161    }
162    let picture = match &input.picture {
163        Some(p) => p.clone(),
164        None => format!(
165            "{}{}",
166            effective_api_base(&input.portal_url, input.api_url.as_deref()),
167            routes::HOST_BRANDING_LOGO
168        ),
169    };
170    tags.push(tag(&["picture", &picture])?);
171    for relay in &input.relays {
172        tags.push(tag(&["relay", relay])?);
173    }
174    tags.push(tag(&["t", DISCOVERY_TAG])?);
175    tags.push(tag(&["v", SCHEMA_VERSION])?);
176
177    EventBuilder::new(Kind::Custom(REGISTRATION_KIND), "{}", tags)
178        .custom_created_at(created_at)
179        .to_event(keys)
180        .map_err(|e| format!("could not sign the registration: {e}"))
181}
182
183fn set_once(slot: &mut Option<String>, key: &str, value: String) -> Result<(), String> {
184    if slot.is_some() {
185        return Err(format!("registration repeats the '{key}' tag"));
186    }
187    *slot = Some(value);
188    Ok(())
189}
190
191/// Checks a kind-30779 event from a relay. Anything that is not exactly what
192/// `build_registration_event` makes is refused, because the signature only proves who sent it,
193/// not that what they claim is safe to list.
194pub fn parse_registration(event: &Event) -> Result<HostRegistration, String> {
195    if event.kind != Kind::Custom(REGISTRATION_KIND) {
196        return Err("not a registration event".to_string());
197    }
198    event
199        .verify()
200        .map_err(|_| "the registration's signature does not verify".to_string())?;
201
202    let (mut slug, mut name, mut url, mut api, mut geohash, mut version, mut picture) =
203        (None, None, None, None, None, None, None);
204    let mut relays = Vec::new();
205    for tag in event.tags() {
206        let parts = tag.as_vec();
207        let (Some(key), Some(value)) = (parts.first(), parts.get(1)) else {
208            continue;
209        };
210        let value = value.clone();
211        match key.as_str() {
212            "d" => set_once(&mut slug, "d", value)?,
213            "name" => set_once(&mut name, "name", value)?,
214            "url" => set_once(&mut url, "url", value)?,
215            "api" => set_once(&mut api, "api", value)?,
216            "g" => set_once(&mut geohash, "g", value)?,
217            "picture" => set_once(&mut picture, "picture", value)?,
218            "v" => set_once(&mut version, "v", value)?,
219            "relay" => relays.push(value),
220            _ => {}
221        }
222    }
223
224    if version.as_deref() != Some(SCHEMA_VERSION) {
225        return Err("registration has a missing or unsupported version".to_string());
226    }
227    let input = RegistrationInput {
228        slug: slug.ok_or("registration has no 'd' tag")?,
229        name: name.ok_or("registration has no 'name' tag")?,
230        portal_url: url.ok_or("registration has no 'url' tag")?,
231        api_url: api,
232        relays,
233        geohash,
234        picture,
235    };
236    validate_input(&input)?;
237
238    Ok(HostRegistration {
239        slug: input.slug,
240        name: input.name,
241        portal_url: input.portal_url,
242        api_url: input.api_url,
243        operator_npub: event
244            .pubkey
245            .to_bech32()
246            .map_err(|e| format!("could not encode the operator key: {e}"))?,
247        relays: input.relays,
248        geohash: input.geohash,
249        picture: input.picture,
250        event_id: event.id.to_hex(),
251        created_at: event.created_at.as_u64() as i64,
252    })
253}
254
255/// Where a client reaches this organization's API: the explicit `api` value, or the portal with
256/// `/backend` (how the shipped Caddy config routes the backend).
257pub fn effective_api_base(portal_url: &str, api_url: Option<&str>) -> String {
258    match api_url {
259        Some(api) => api.to_string(),
260        None => format!("{portal_url}{}", routes::DEFAULT_API_SUFFIX),
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    fn input() -> RegistrationInput {
269        RegistrationInput {
270            slug: "main-org".into(),
271            name: "main-org".into(),
272            portal_url: "https://main-org.example".into(),
273            api_url: None,
274            relays: vec!["wss://relay.damus.io".into(), "wss://nos.lol".into()],
275            geohash: Some("wdw4f".into()),
276            picture: None,
277        }
278    }
279
280    fn built(keys: &Keys, i: &RegistrationInput) -> Event {
281        build_registration_event(keys, i).expect("valid input builds")
282    }
283
284    #[test]
285    fn registration_roundtrip_builds_and_parses() {
286        let keys = Keys::generate();
287        let mut i = input();
288        i.api_url = Some("https://main-org.example/backend".into());
289        let reg = parse_registration(&built(&keys, &i)).unwrap();
290        assert_eq!(reg.slug, i.slug);
291        assert_eq!(reg.name, i.name);
292        assert_eq!(reg.portal_url, i.portal_url);
293        assert_eq!(reg.api_url, i.api_url);
294        assert_eq!(reg.relays, i.relays);
295        assert_eq!(reg.geohash, i.geohash);
296        assert_eq!(reg.operator_npub, keys.public_key().to_bech32().unwrap());
297    }
298
299    #[test]
300    fn picture_defaults_to_branding_logo_and_roundtrips() {
301        let keys = Keys::generate();
302        let reg = parse_registration(&built(&keys, &input())).unwrap();
303        assert_eq!(
304            reg.picture.as_deref(),
305            Some("https://main-org.example/backend/api/host_branding/logo")
306        );
307        let mut i = input();
308        i.picture = Some("https://cdn.example/logo.png".into());
309        let reg = parse_registration(&built(&keys, &i)).unwrap();
310        assert_eq!(reg.picture, i.picture);
311    }
312
313    #[test]
314    fn picture_must_be_https_and_is_validated_on_parse() {
315        let mut i = input();
316        i.picture = Some("http://cdn.example/logo.png".into());
317        assert!(validate_input(&i).is_err());
318        let keys = Keys::generate();
319        let ev = EventBuilder::new(
320            Kind::Custom(REGISTRATION_KIND),
321            "{}",
322            vec![
323                Tag::identifier("main-org"),
324                Tag::parse(&["name", "main-org"]).unwrap(),
325                Tag::parse(&["url", "https://main-org.example"]).unwrap(),
326                Tag::parse(&["picture", "javascript:alert(1)"]).unwrap(),
327                Tag::parse(&["relay", "wss://nos.lol"]).unwrap(),
328                Tag::parse(&["v", "1"]).unwrap(),
329            ],
330        )
331        .to_event(&keys)
332        .unwrap();
333        assert!(parse_registration(&ev).is_err());
334    }
335
336    #[test]
337    fn built_registration_carries_the_discovery_tag() {
338        let ev = built(&Keys::generate(), &input());
339        let has_t = ev.tags().iter().any(|t| {
340            let v = t.as_vec();
341            v.first().map(String::as_str) == Some("t")
342                && v.get(1).map(String::as_str) == Some("moreinlaw")
343        });
344        assert!(has_t);
345    }
346
347    #[test]
348    fn registration_without_optional_fields_roundtrips() {
349        let keys = Keys::generate();
350        let mut i = input();
351        i.geohash = None;
352        let reg = parse_registration(&built(&keys, &i)).unwrap();
353        assert_eq!(reg.api_url, None);
354        assert_eq!(reg.geohash, None);
355    }
356
357    #[test]
358    fn registration_rejects_wrong_kind() {
359        let keys = Keys::generate();
360        let ev = EventBuilder::new(Kind::Custom(30778), "{}", vec![Tag::identifier("x-org")])
361            .to_event(&keys)
362            .unwrap();
363        assert!(parse_registration(&ev).is_err());
364    }
365
366    #[test]
367    fn registration_rejects_bad_slug() {
368        for bad in [
369            "A-org",
370            "a",
371            "has_underscore",
372            "has space",
373            &"a".repeat(64),
374            "",
375        ] {
376            let mut i = input();
377            i.slug = bad.into();
378            assert!(
379                validate_input(&i).is_err(),
380                "slug {bad:?} should be rejected"
381            );
382        }
383        for good in ["ab", "main-org", "a1-b2", &"a".repeat(63)] {
384            let mut i = input();
385            i.slug = good.into();
386            assert!(validate_input(&i).is_ok(), "slug {good:?} should pass");
387        }
388    }
389
390    #[test]
391    fn registration_rejects_empty_or_long_name() {
392        let mut i = input();
393        i.name = "  ".into();
394        assert!(validate_input(&i).is_err());
395        i.name = "x".repeat(121);
396        assert!(validate_input(&i).is_err());
397        i.name = "x".repeat(120);
398        assert!(validate_input(&i).is_ok());
399    }
400
401    #[test]
402    fn registration_rejects_http_url() {
403        let mut i = input();
404        i.portal_url = "http://main-org.example".into();
405        assert!(validate_input(&i).is_err());
406    }
407
408    #[test]
409    fn registration_rejects_url_with_path_slash_query_or_credentials() {
410        for bad in [
411            "https://main-org.example/",
412            "https://main-org.example/app",
413            "https://main-org.example?x=1",
414            "https://main-org.example#frag",
415            "https://user:pw@main-org.example",
416            "https://Main-Org.example",
417            "https://main-org.example:443",
418            "main-org.example",
419            "",
420        ] {
421            let mut i = input();
422            i.portal_url = bad.into();
423            assert!(
424                validate_input(&i).is_err(),
425                "portal {bad:?} should be rejected"
426            );
427        }
428    }
429
430    #[test]
431    fn registration_accepts_url_with_explicit_port() {
432        let mut i = input();
433        i.portal_url = "https://morein.example:8443".into();
434        assert!(validate_input(&i).is_ok());
435    }
436
437    #[test]
438    fn api_url_accepts_a_path_but_not_a_trailing_slash() {
439        let mut i = input();
440        i.api_url = Some("https://morein.ph/backend".into());
441        assert!(validate_input(&i).is_ok());
442        i.api_url = Some("https://morein.ph".into());
443        assert!(validate_input(&i).is_ok());
444        for bad in [
445            "https://morein.ph/backend/",
446            "https://morein.ph/",
447            "http://morein.ph/backend",
448            "https://morein.ph/backend?x=1",
449            "https://u:p@morein.ph/backend",
450        ] {
451            i.api_url = Some(bad.into());
452            assert!(
453                validate_input(&i).is_err(),
454                "api {bad:?} should be rejected"
455            );
456        }
457    }
458
459    #[test]
460    fn registration_rejects_no_relays_too_many_or_insecure_relays() {
461        let mut i = input();
462        i.relays = vec![];
463        assert!(validate_input(&i).is_err());
464        i.relays = (0..11).map(|n| format!("wss://r{n}.example")).collect();
465        assert!(validate_input(&i).is_err());
466        i.relays = (0..10).map(|n| format!("wss://r{n}.example")).collect();
467        assert!(validate_input(&i).is_ok());
468        i.relays = vec!["ws://relay.example".into()];
469        assert!(validate_input(&i).is_err());
470        i.relays = vec!["https://relay.example".into()];
471        assert!(validate_input(&i).is_err());
472    }
473
474    #[test]
475    fn registration_rejects_bad_geohash() {
476        for bad in ["WDW4F", "wdwa4", "", &"w".repeat(13), "wdw 4"] {
477            let mut i = input();
478            i.geohash = Some(bad.into());
479            assert!(
480                validate_input(&i).is_err(),
481                "geohash {bad:?} should be rejected"
482            );
483        }
484        let mut i = input();
485        i.geohash = Some("wdw4f8k2m9pq".into());
486        assert!(validate_input(&i).is_ok());
487    }
488
489    #[test]
490    fn registration_rejects_tampered_event() {
491        let keys = Keys::generate();
492        let json = built(&keys, &input()).as_json();
493        let tampered = json.replace("main-org", "Evil Law Firm");
494        assert_ne!(json, tampered);
495        // A tampered event may be refused when decoded or by parse_registration; either is a rejection.
496        if let Ok(ev) = Event::from_json(&tampered) {
497            assert!(parse_registration(&ev).is_err());
498        }
499    }
500
501    #[test]
502    fn registration_rejects_missing_or_unknown_version() {
503        let keys = Keys::generate();
504        let tags = |v: Option<&str>| {
505            let mut t = vec![
506                Tag::identifier("main-org"),
507                Tag::parse(&["name", "main-org"]).unwrap(),
508                Tag::parse(&["url", "https://main-org.example"]).unwrap(),
509                Tag::parse(&["relay", "wss://nos.lol"]).unwrap(),
510            ];
511            if let Some(v) = v {
512                t.push(Tag::parse(&["v", v]).unwrap());
513            }
514            t
515        };
516        for v in [None, Some("2")] {
517            let ev = EventBuilder::new(Kind::Custom(REGISTRATION_KIND), "{}", tags(v))
518                .to_event(&keys)
519                .unwrap();
520            assert!(
521                parse_registration(&ev).is_err(),
522                "version {v:?} should be rejected"
523            );
524        }
525        let ok = EventBuilder::new(Kind::Custom(REGISTRATION_KIND), "{}", tags(Some("1")))
526            .to_event(&keys)
527            .unwrap();
528        assert!(parse_registration(&ok).is_ok());
529    }
530
531    #[test]
532    fn registration_rejects_duplicate_identity_tags() {
533        let keys = Keys::generate();
534        let ev = EventBuilder::new(
535            Kind::Custom(REGISTRATION_KIND),
536            "{}",
537            vec![
538                Tag::identifier("main-org"),
539                Tag::identifier("other-org"),
540                Tag::parse(&["name", "main-org"]).unwrap(),
541                Tag::parse(&["url", "https://main-org.example"]).unwrap(),
542                Tag::parse(&["relay", "wss://nos.lol"]).unwrap(),
543                Tag::parse(&["v", "1"]).unwrap(),
544            ],
545        )
546        .to_event(&keys)
547        .unwrap();
548        assert!(parse_registration(&ev).is_err());
549    }
550
551    #[test]
552    fn effective_api_base_defaults_to_portal_backend() {
553        assert_eq!(
554            effective_api_base("https://morein.ph", None),
555            "https://morein.ph/backend"
556        );
557        assert_eq!(
558            effective_api_base("https://morein.ph", Some("https://api.morein.ph")),
559            "https://api.morein.ph"
560        );
561    }
562}