Skip to main content

moreinlaw_kernel/
directory.rs

1//! The maintainer-signed kind-30778 directory entry: the public statement "this operator key is
2//! a MoreInLaw Host, and here is where to reach it". The phone app lists organizations from
3//! these and ignores any entry the maintainer key did not sign.
4//!
5//! Only the maintainer instance signs these. Other Hosts apply with a kind-30779 registration
6//! instead (`registration`).
7
8use nostr::prelude::*;
9
10pub use crate::params::ORG_DIRECTORY_KIND;
11use crate::params::SCHEMA_VERSION;
12use crate::registration::effective_api_base;
13
14/// What a directory entry says about the organization. The phone app lists only `Listed`
15/// entries: a status tag is how suspension and removal reach relays that ignore deletion.
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub enum EntryStatus {
18    Listed,
19    Suspended,
20    Removed,
21}
22
23impl EntryStatus {
24    fn tag_value(self) -> Option<&'static str> {
25        match self {
26            EntryStatus::Listed => None,
27            EntryStatus::Suspended => Some("suspended"),
28            EntryStatus::Removed => Some("removed"),
29        }
30    }
31}
32
33/// The organization an entry describes, as the maintainer approved it.
34#[derive(Debug, Clone, Copy, PartialEq)]
35pub struct DirectoryOrg<'a> {
36    pub slug: &'a str,
37    pub name: &'a str,
38    pub portal_url: &'a str,
39    pub api_url: Option<&'a str>,
40    pub operator_npub: &'a str,
41    pub geohash: Option<&'a str>,
42}
43
44/// The entry for one organization, stamped now.
45pub fn build_directory_event(
46    maintainer: &Keys,
47    org: &DirectoryOrg,
48    status: EntryStatus,
49) -> Result<Event, String> {
50    build_directory_event_at(maintainer, org, status, Timestamp::now())
51}
52
53/// Same as `build_directory_event` with an explicit time.
54pub fn build_directory_event_at(
55    maintainer: &Keys,
56    org: &DirectoryOrg,
57    status: EntryStatus,
58    created_at: Timestamp,
59) -> Result<Event, String> {
60    let operator = PublicKey::from_bech32(org.operator_npub)
61        .map_err(|e| format!("operator key of {} is not a valid npub: {e}", org.slug))?;
62    let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));
63
64    let mut tags = vec![
65        Tag::identifier(org.slug),
66        Tag::public_key(operator),
67        tag(&["name", org.name])?,
68        tag(&["url", org.portal_url])?,
69        tag(&["api", &effective_api_base(org.portal_url, org.api_url)])?,
70    ];
71    if let Some(g) = org.geohash {
72        tags.push(tag(&["g", g])?);
73    }
74    tags.push(tag(&["v", SCHEMA_VERSION])?);
75    if let Some(value) = status.tag_value() {
76        tags.push(tag(&["status", value])?);
77    }
78
79    // Older phone builds read name and url from the content.
80    let content = serde_json::json!({ "name": org.name, "url": org.portal_url }).to_string();
81    EventBuilder::new(Kind::Custom(ORG_DIRECTORY_KIND), content, tags)
82        .custom_created_at(created_at)
83        .to_event(maintainer)
84        .map_err(|e| format!("could not sign the directory entry: {e}"))
85}
86
87/// Asks relays to drop the organization's directory entry (NIP-09, addressed by its slot).
88fn build_removal_event_at(
89    maintainer: &Keys,
90    slug: &str,
91    created_at: Timestamp,
92) -> Result<Event, String> {
93    let coordinate = format!(
94        "{ORG_DIRECTORY_KIND}:{}:{slug}",
95        maintainer.public_key().to_hex()
96    );
97    let tags =
98        vec![Tag::parse(&["a", &coordinate]).map_err(|e| format!("could not build tag: {e}"))?];
99    EventBuilder::new(
100        Kind::EventDeletion,
101        "organization is no longer listed",
102        tags,
103    )
104    .custom_created_at(created_at)
105    .to_event(maintainer)
106    .map_err(|e| format!("could not sign the removal: {e}"))
107}
108
109/// The two events that take an organization off the list: a deletion of its entry, then a
110/// status-tagged entry one second later. Not every relay honours deletion, but every relay
111/// replaces an addressable event with a newer one, so the second is what reliably hides it.
112pub fn build_withdrawal(
113    maintainer: &Keys,
114    org: &DirectoryOrg,
115    status: EntryStatus,
116) -> Result<(Event, Event), String> {
117    if status == EntryStatus::Listed {
118        return Err("a withdrawal needs a suspended or removed status".to_string());
119    }
120    let now = Timestamp::now();
121    let deletion = build_removal_event_at(maintainer, org.slug, now)?;
122    let entry = build_directory_event_at(maintainer, org, status, now + 1)?;
123    Ok((deletion, entry))
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    fn tag_values(event: &Event, key: &str) -> Vec<String> {
131        event
132            .tags()
133            .iter()
134            .filter_map(|t| {
135                let parts = t.as_vec();
136                (parts.first().map(String::as_str) == Some(key))
137                    .then(|| parts.get(1).cloned())
138                    .flatten()
139            })
140            .collect()
141    }
142
143    fn org(npub: &str) -> DirectoryOrg<'_> {
144        DirectoryOrg {
145            slug: "main-org",
146            name: "main-org",
147            portal_url: "https://main-org.example",
148            api_url: None,
149            operator_npub: npub,
150            geohash: Some("wdw4f"),
151        }
152    }
153
154    fn keys() -> (Keys, Keys, String) {
155        let operator = Keys::generate();
156        let npub = operator.public_key().to_bech32().unwrap();
157        (Keys::generate(), operator, npub)
158    }
159
160    #[test]
161    fn directory_event_includes_api_and_version_tags() {
162        let (maintainer, operator, npub) = keys();
163        let ev = build_directory_event(&maintainer, &org(&npub), EntryStatus::Listed).unwrap();
164
165        assert_eq!(ev.kind, Kind::Custom(30778));
166        assert_eq!(ev.pubkey, maintainer.public_key());
167        assert!(ev.verify().is_ok());
168        assert_eq!(tag_values(&ev, "d"), vec!["main-org"]);
169        assert_eq!(tag_values(&ev, "p"), vec![operator.public_key().to_hex()]);
170        assert_eq!(tag_values(&ev, "name"), vec!["main-org"]);
171        assert_eq!(tag_values(&ev, "url"), vec!["https://main-org.example"]);
172        assert_eq!(
173            tag_values(&ev, "api"),
174            vec!["https://main-org.example/backend"]
175        );
176        assert_eq!(tag_values(&ev, "g"), vec!["wdw4f"]);
177        assert_eq!(tag_values(&ev, "v"), vec![SCHEMA_VERSION]);
178        assert!(tag_values(&ev, "status").is_empty());
179        let content: serde_json::Value = serde_json::from_str(&ev.content).unwrap();
180        assert_eq!(content["name"], "main-org");
181        assert_eq!(content["url"], "https://main-org.example");
182    }
183
184    #[test]
185    fn directory_event_uses_an_explicit_api_and_omits_an_unset_geohash() {
186        let (maintainer, _, npub) = keys();
187        let mut o = org(&npub);
188        o.api_url = Some("https://api.main-org.example");
189        o.geohash = None;
190        let ev = build_directory_event(&maintainer, &o, EntryStatus::Listed).unwrap();
191        assert_eq!(tag_values(&ev, "api"), vec!["https://api.main-org.example"]);
192        assert!(tag_values(&ev, "g").is_empty());
193    }
194
195    #[test]
196    fn directory_event_marks_suspended_and_removed() {
197        let (maintainer, _, npub) = keys();
198        for (status, value) in [
199            (EntryStatus::Suspended, "suspended"),
200            (EntryStatus::Removed, "removed"),
201        ] {
202            let ev = build_directory_event(&maintainer, &org(&npub), status).unwrap();
203            assert_eq!(tag_values(&ev, "status"), vec![value]);
204            assert_eq!(tag_values(&ev, "d"), vec!["main-org"]);
205        }
206    }
207
208    #[test]
209    fn a_bad_operator_npub_is_refused() {
210        let (maintainer, _, _) = keys();
211        assert!(
212            build_directory_event(&maintainer, &org("npub1nope"), EntryStatus::Listed).is_err()
213        );
214    }
215
216    #[test]
217    fn withdrawal_entry_is_newer_than_the_deletion_it_follows() {
218        // A deletion covers events up to its own time, so an entry stamped the same second
219        // would be deleted along with the listing it is meant to replace.
220        let (maintainer, _, npub) = keys();
221        let (deletion, entry) =
222            build_withdrawal(&maintainer, &org(&npub), EntryStatus::Suspended).unwrap();
223        assert_eq!(deletion.kind, Kind::EventDeletion);
224        assert_eq!(entry.kind, Kind::Custom(ORG_DIRECTORY_KIND));
225        assert!(entry.created_at > deletion.created_at);
226        assert_eq!(tag_values(&entry, "status"), vec!["suspended"]);
227        assert_eq!(
228            tag_values(&deletion, "a"),
229            vec![format!(
230                "{ORG_DIRECTORY_KIND}:{}:main-org",
231                maintainer.public_key().to_hex()
232            )]
233        );
234        assert!(build_withdrawal(&maintainer, &org(&npub), EntryStatus::Listed).is_err());
235    }
236}