moreinlaw-kernel 0.3.2

The MoreInLaw federation protocol: what every instance must agree on to stay on the network.
Documentation
//! The maintainer-signed kind-30778 directory entry: the public statement "this operator key is
//! a MoreInLaw Host, and here is where to reach it". The phone app lists organizations from
//! these and ignores any entry the maintainer key did not sign.
//!
//! Only the maintainer instance signs these, so this module sits behind the `directory`
//! feature. Other Hosts apply with a kind-30779 registration instead (`registration`).

use nostr::prelude::*;

pub use crate::params::ORG_DIRECTORY_KIND;
use crate::params::SCHEMA_VERSION;
use crate::registration::effective_api_base;

/// What a directory entry says about the organization. The phone app lists only `Listed`
/// entries: a status tag is how suspension and removal reach relays that ignore deletion.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EntryStatus {
    Listed,
    Suspended,
    Removed,
}

impl EntryStatus {
    fn tag_value(self) -> Option<&'static str> {
        match self {
            EntryStatus::Listed => None,
            EntryStatus::Suspended => Some("suspended"),
            EntryStatus::Removed => Some("removed"),
        }
    }
}

/// The organization an entry describes, as the maintainer approved it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DirectoryOrg<'a> {
    pub slug: &'a str,
    pub name: &'a str,
    pub portal_url: &'a str,
    pub api_url: Option<&'a str>,
    pub operator_npub: &'a str,
    pub geohash: Option<&'a str>,
}

/// The entry for one organization, stamped now.
pub fn build_directory_event(
    maintainer: &Keys,
    org: &DirectoryOrg,
    status: EntryStatus,
) -> Result<Event, String> {
    build_directory_event_at(maintainer, org, status, Timestamp::now())
}

/// Same as `build_directory_event` with an explicit time.
pub fn build_directory_event_at(
    maintainer: &Keys,
    org: &DirectoryOrg,
    status: EntryStatus,
    created_at: Timestamp,
) -> Result<Event, String> {
    let operator = PublicKey::from_bech32(org.operator_npub)
        .map_err(|e| format!("operator key of {} is not a valid npub: {e}", org.slug))?;
    let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));

    let mut tags = vec![
        Tag::identifier(org.slug),
        Tag::public_key(operator),
        tag(&["name", org.name])?,
        tag(&["url", org.portal_url])?,
        tag(&["api", &effective_api_base(org.portal_url, org.api_url)])?,
    ];
    if let Some(g) = org.geohash {
        tags.push(tag(&["g", g])?);
    }
    tags.push(tag(&["v", SCHEMA_VERSION])?);
    if let Some(value) = status.tag_value() {
        tags.push(tag(&["status", value])?);
    }

    // Older phone builds read name and url from the content.
    let content = serde_json::json!({ "name": org.name, "url": org.portal_url }).to_string();
    EventBuilder::new(Kind::Custom(ORG_DIRECTORY_KIND), content, tags)
        .custom_created_at(created_at)
        .to_event(maintainer)
        .map_err(|e| format!("could not sign the directory entry: {e}"))
}

/// Asks relays to drop the organization's directory entry (NIP-09, addressed by its slot).
fn build_removal_event_at(
    maintainer: &Keys,
    slug: &str,
    created_at: Timestamp,
) -> Result<Event, String> {
    let coordinate = format!(
        "{ORG_DIRECTORY_KIND}:{}:{slug}",
        maintainer.public_key().to_hex()
    );
    let tags =
        vec![Tag::parse(&["a", &coordinate]).map_err(|e| format!("could not build tag: {e}"))?];
    EventBuilder::new(
        Kind::EventDeletion,
        "organization is no longer listed",
        tags,
    )
    .custom_created_at(created_at)
    .to_event(maintainer)
    .map_err(|e| format!("could not sign the removal: {e}"))
}

/// The two events that take an organization off the list: a deletion of its entry, then a
/// status-tagged entry one second later. Not every relay honours deletion, but every relay
/// replaces an addressable event with a newer one, so the second is what reliably hides it.
pub fn build_withdrawal(
    maintainer: &Keys,
    org: &DirectoryOrg,
    status: EntryStatus,
) -> Result<(Event, Event), String> {
    if status == EntryStatus::Listed {
        return Err("a withdrawal needs a suspended or removed status".to_string());
    }
    let now = Timestamp::now();
    let deletion = build_removal_event_at(maintainer, org.slug, now)?;
    let entry = build_directory_event_at(maintainer, org, status, now + 1)?;
    Ok((deletion, entry))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tag_values(event: &Event, key: &str) -> Vec<String> {
        event
            .tags()
            .iter()
            .filter_map(|t| {
                let parts = t.as_vec();
                (parts.first().map(String::as_str) == Some(key))
                    .then(|| parts.get(1).cloned())
                    .flatten()
            })
            .collect()
    }

    fn org(npub: &str) -> DirectoryOrg<'_> {
        DirectoryOrg {
            slug: "main-org",
            name: "main-org",
            portal_url: "https://main-org.example",
            api_url: None,
            operator_npub: npub,
            geohash: Some("wdw4f"),
        }
    }

    fn keys() -> (Keys, Keys, String) {
        let operator = Keys::generate();
        let npub = operator.public_key().to_bech32().unwrap();
        (Keys::generate(), operator, npub)
    }

    #[test]
    fn directory_event_includes_api_and_version_tags() {
        let (maintainer, operator, npub) = keys();
        let ev = build_directory_event(&maintainer, &org(&npub), EntryStatus::Listed).unwrap();

        assert_eq!(ev.kind, Kind::Custom(30778));
        assert_eq!(ev.pubkey, maintainer.public_key());
        assert!(ev.verify().is_ok());
        assert_eq!(tag_values(&ev, "d"), vec!["main-org"]);
        assert_eq!(tag_values(&ev, "p"), vec![operator.public_key().to_hex()]);
        assert_eq!(tag_values(&ev, "name"), vec!["main-org"]);
        assert_eq!(tag_values(&ev, "url"), vec!["https://main-org.example"]);
        assert_eq!(
            tag_values(&ev, "api"),
            vec!["https://main-org.example/backend"]
        );
        assert_eq!(tag_values(&ev, "g"), vec!["wdw4f"]);
        assert_eq!(tag_values(&ev, "v"), vec![SCHEMA_VERSION]);
        assert!(tag_values(&ev, "status").is_empty());
        let content: serde_json::Value = serde_json::from_str(&ev.content).unwrap();
        assert_eq!(content["name"], "main-org");
        assert_eq!(content["url"], "https://main-org.example");
    }

    #[test]
    fn directory_event_uses_an_explicit_api_and_omits_an_unset_geohash() {
        let (maintainer, _, npub) = keys();
        let mut o = org(&npub);
        o.api_url = Some("https://api.main-org.example");
        o.geohash = None;
        let ev = build_directory_event(&maintainer, &o, EntryStatus::Listed).unwrap();
        assert_eq!(tag_values(&ev, "api"), vec!["https://api.main-org.example"]);
        assert!(tag_values(&ev, "g").is_empty());
    }

    #[test]
    fn directory_event_marks_suspended_and_removed() {
        let (maintainer, _, npub) = keys();
        for (status, value) in [
            (EntryStatus::Suspended, "suspended"),
            (EntryStatus::Removed, "removed"),
        ] {
            let ev = build_directory_event(&maintainer, &org(&npub), status).unwrap();
            assert_eq!(tag_values(&ev, "status"), vec![value]);
            assert_eq!(tag_values(&ev, "d"), vec!["main-org"]);
        }
    }

    #[test]
    fn a_bad_operator_npub_is_refused() {
        let (maintainer, _, _) = keys();
        assert!(
            build_directory_event(&maintainer, &org("npub1nope"), EntryStatus::Listed).is_err()
        );
    }

    #[test]
    fn withdrawal_entry_is_newer_than_the_deletion_it_follows() {
        // A deletion covers events up to its own time, so an entry stamped the same second
        // would be deleted along with the listing it is meant to replace.
        let (maintainer, _, npub) = keys();
        let (deletion, entry) =
            build_withdrawal(&maintainer, &org(&npub), EntryStatus::Suspended).unwrap();
        assert_eq!(deletion.kind, Kind::EventDeletion);
        assert_eq!(entry.kind, Kind::Custom(ORG_DIRECTORY_KIND));
        assert!(entry.created_at > deletion.created_at);
        assert_eq!(tag_values(&entry, "status"), vec!["suspended"]);
        assert_eq!(
            tag_values(&deletion, "a"),
            vec![format!(
                "{ORG_DIRECTORY_KIND}:{}:main-org",
                maintainer.public_key().to_hex()
            )]
        );
        assert!(build_withdrawal(&maintainer, &org(&npub), EntryStatus::Listed).is_err());
    }
}