Skip to main content

vector_core/community/
moderation.rs

1//! Moderation authority: who may remove whose message (CORD-04 §3/§5).
2
3use super::roles::{CommunityRoles, Permissions};
4use super::CommunityId;
5
6/// The community's proven owner as lowercase hex (self-certified by the community id).
7///
8/// A `None` owner is not a safe default: it costs the owner their supremacy AND drops the protection that makes them an
9/// invalid target, so an admin outranks the roleless owner in both directions.
10pub fn owner_hex(community_id: &str) -> Option<String> {
11    let id = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
12    crate::db::community::load_community_v2(&id)
13        .ok()
14        .flatten()
15        .and_then(|c| c.owner().ok())
16        .map(|pk| pk.to_hex())
17}
18
19/// Whether `member_hex` is the owner or holds an admin grant: the bar for @everyone.
20/// A lookup failure answers false.
21pub fn is_owner_or_admin(community_id: &str, member_hex: &str) -> bool {
22    owner_hex(community_id).is_some_and(|o| o == member_hex)
23        || crate::db::community::get_community_roles(community_id).is_ok_and(|r| r.is_admin(member_hex))
24}
25
26/// May `actor_hex` remove a message authored by `author_hex`? The actor needs
27/// `MANAGE_MESSAGES` and a strict outrank; the owner is supreme and is never a
28/// valid target, so owner-protection falls out of the algebra with no carve-out.
29///
30/// Identities are normalized first: a message's stored npub is BECH32 while the
31/// owner and the roster grants are keyed by lowercase HEX, and an unnormalized
32/// author matches neither — it skips owner-protection and misses the roster
33/// lookup, defaulting to the lowest rank.
34pub fn can_hide(
35    owner_hex: Option<&str>,
36    roster: &CommunityRoles,
37    actor_hex: &str,
38    author_hex: &str,
39) -> bool {
40    let to_hex = |s: &str| {
41        nostr_sdk::prelude::PublicKey::parse(s)
42            .map(|pk| pk.to_hex())
43            .unwrap_or_else(|_| s.to_string())
44    };
45    roster.can_act_on_member(
46        &to_hex(actor_hex),
47        owner_hex,
48        &to_hex(author_hex),
49        Permissions::MANAGE_MESSAGES,
50    )
51}
52
53/// [`can_hide`] in one Channel: MANAGE_MESSAGES is overwritable, so it's resolved there
54/// (CORD-04 §8), while the outrank stays server-wide.
55pub fn can_hide_in_channel(
56    owner_hex: Option<&str>,
57    roster: &CommunityRoles,
58    actor_hex: &str,
59    author_hex: &str,
60    channel_hex: &str,
61    private: bool,
62) -> bool {
63    let to_hex = |s: &str| {
64        nostr_sdk::prelude::PublicKey::parse(s)
65            .map(|pk| pk.to_hex())
66            .unwrap_or_else(|_| s.to_string())
67    };
68    let actor = to_hex(actor_hex);
69    // A legacy Roster has no Channel permissions to resolve.
70    if roster.everyone.is_none() {
71        return can_hide(owner_hex, roster, &actor, author_hex);
72    }
73    roster.can_act_on_member(&actor, owner_hex, &to_hex(author_hex), 0)
74        && roster.channel_permissions(owner_hex, &actor, channel_hex, private).contains(Permissions::MANAGE_MESSAGES)
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::community::roles::{MemberGrant, Role};
81
82    fn roster(owner: &str, admin_a: &str, admin_b: &str, mod_hex: &str) -> CommunityRoles {
83        let admin = Role::admin("a".repeat(64));
84        let mut moderator = Role::admin("b".repeat(64));
85        moderator.position = admin.position + 1;
86        let grants = vec![
87            MemberGrant { member: owner.to_string(), role_ids: vec![admin.role_id.clone()] },
88            MemberGrant { member: admin_a.to_string(), role_ids: vec![admin.role_id.clone()] },
89            MemberGrant { member: admin_b.to_string(), role_ids: vec![admin.role_id.clone()] },
90            MemberGrant { member: mod_hex.to_string(), role_ids: vec![moderator.role_id.clone()] },
91        ];
92        CommunityRoles { grants, roles: vec![admin, moderator], everyone: None, overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default() }
93    }
94
95    #[test]
96    fn a_hide_resolves_manage_messages_in_its_channel() {
97        use crate::community::roles::{Overwrite, OverwriteTarget, Permissions as P};
98        let (owner, admin_a, admin_b, moderator) = ("11".repeat(32), "22".repeat(32), "33".repeat(32), "44".repeat(32));
99        let mut r = roster(&owner, &admin_a, &admin_b, &moderator);
100        r.everyone = Some(P(P::VIEW_CHANNEL | P::SEND_MESSAGES));
101        let (here, there) = ("cc".repeat(32), "dd".repeat(32));
102        let member = "55".repeat(32);
103        r.overwrites.push(Overwrite { scope: here.clone(), target: OverwriteTarget::Role("b".repeat(64)), allow: P(0), deny: P(P::MANAGE_MESSAGES) });
104        assert!(can_hide_in_channel(Some(&owner), &r, &moderator, &member, &there, false), "the server-wide bit stands elsewhere");
105        assert!(!can_hide_in_channel(Some(&owner), &r, &moderator, &member, &here, false), "an overwrite's deny takes it away here");
106        r.overwrites.push(Overwrite { scope: here.clone(), target: OverwriteTarget::Member(member.clone()), allow: P(P::MANAGE_MESSAGES), deny: P(0) });
107        assert!(!can_hide_in_channel(Some(&owner), &r, &member, &moderator, &here, false), "an allow never lifts an outrank");
108        assert!(!can_hide_in_channel(Some(&owner), &r, &admin_a, &member, &here, true), "a Private Channel's view comes only through an allow");
109        assert!(can_hide_in_channel(Some(&owner), &r, &owner, &member, &here, true), "the owner holds everything everywhere");
110        r.everyone = None;
111        assert!(can_hide_in_channel(Some(&owner), &r, &moderator, &member, &here, false), "a legacy Roster judges server-wide");
112    }
113
114    #[test]
115    fn the_owner_outranks_an_admin_even_holding_the_same_role() {
116        let (owner, admin_a, admin_b, moderator) =
117            ("11".repeat(32), "22".repeat(32), "33".repeat(32), "44".repeat(32));
118        let r = roster(&owner, &admin_a, &admin_b, &moderator);
119
120        // The owner is supreme: the shared Admin role puts them at the SAME
121        // position as admin_a, and equal-cannot-act-on-equal must not apply.
122        assert!(can_hide(Some(&owner), &r, &owner, &admin_a));
123        assert!(can_hide(Some(&owner), &r, &owner, &moderator));
124        // Peer admins still can't touch each other, and nobody touches the owner.
125        assert!(!can_hide(Some(&owner), &r, &admin_a, &admin_b));
126        assert!(!can_hide(Some(&owner), &r, &admin_a, &owner));
127        assert!(can_hide(Some(&owner), &r, &admin_a, &moderator));
128    }
129
130    #[test]
131    fn an_unresolved_owner_costs_supremacy_and_protection_both_ways() {
132        // Why an unresolvable owner is never a safe default: position 0 is
133        // implicit, so an owner holding no Role ranks LAST once `owner_hex` is
134        // None — unable to moderate anyone, and outranked by their own admins.
135        let (owner, admin, moderator) = ("11".repeat(32), "22".repeat(32), "44".repeat(32));
136        let admin_role = Role::admin("a".repeat(64));
137        let r = CommunityRoles {
138            grants: vec![MemberGrant { member: admin.clone(), role_ids: vec![admin_role.role_id.clone()] }],
139            roles: vec![admin_role],
140            everyone: None,
141            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
142        };
143
144        assert!(!can_hide(None, &r, &owner, &admin), "the owner can't moderate anyone");
145        assert!(!can_hide(None, &r, &owner, &moderator));
146        assert!(can_hide(None, &r, &admin, &owner), "and is exposed to their own admins");
147
148        // Resolved, the same roster behaves: supreme in one direction, untouchable in the other.
149        assert!(can_hide(Some(&owner), &r, &owner, &admin));
150        assert!(!can_hide(Some(&owner), &r, &admin, &owner));
151    }
152
153    #[test]
154    fn a_bech32_author_resolves_to_the_same_verdict_as_hex() {
155        use nostr_sdk::prelude::*;
156        let owner_keys = Keys::generate();
157        let admin_keys = Keys::generate();
158        let owner = owner_keys.public_key().to_hex();
159        let admin = admin_keys.public_key().to_hex();
160        let r = roster(&owner, &admin, &"33".repeat(32), &"44".repeat(32));
161        let admin_bech32 = admin_keys.public_key().to_bech32().unwrap();
162        let owner_bech32 = owner_keys.public_key().to_bech32().unwrap();
163
164        assert!(can_hide(Some(&owner), &r, &owner_bech32, &admin_bech32));
165        // Owner-protection survives a bech32 target.
166        assert!(!can_hide(Some(&owner), &r, &admin_bech32, &owner_bech32));
167    }
168}