Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/buzz-core/src/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ pub const KIND_NIP29_JOIN_REQUEST: u32 = 9021;
/// NIP-29: Request to leave a group.
pub const KIND_NIP29_LEAVE_REQUEST: u32 = 9022;

/// Buzz: Conditionally change the role of an existing Solo member.
pub const KIND_SOLO_MEMBER_ROLE: u32 = 9050;

// Buzz community moderation commands (mod-signed, processed like 9030-series:
// validated + executed directly, never stored as regular events; every
// accepted command writes a `moderation_actions` audit row).
Expand Down Expand Up @@ -740,6 +743,7 @@ pub const ALL_KINDS: &[u32] = &[
KIND_NIP29_CREATE_INVITE,
KIND_NIP29_JOIN_REQUEST,
KIND_NIP29_LEAVE_REQUEST,
KIND_SOLO_MEMBER_ROLE,
KIND_MODERATION_BAN,
KIND_MODERATION_UNBAN,
KIND_MODERATION_TIMEOUT,
Expand Down
34 changes: 34 additions & 0 deletions crates/buzz-db/src/store/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,40 @@ pub fn group_members_tags(
Ok(tags)
}

/// Sign and replace one group-state event while the caller holds its
/// replacement lock. The caller commits or rolls back the replacement.
pub(crate) async fn replace_signed_group_state_under_lock(
tx: &mut crate::AdmittedTx,
channel_id: Uuid,
kind: i32,
tags: Vec<nostr::Tag>,
signer: &nostr::Keys,
) -> Result<(StoredEvent, bool)> {
let relay_pubkey = signer.public_key().to_bytes();
let latest: Option<DateTime<Utc>> = sqlx::query_scalar(
"SELECT created_at FROM events WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \
AND channel_id = $4 AND deleted_at IS NULL ORDER BY created_at DESC, id ASC LIMIT 1",
)
.bind(tx.community().as_uuid())
.bind(kind)
.bind(relay_pubkey.as_slice())
.bind(channel_id)
.fetch_optional(tx.conn())
.await?;
let now = nostr::Timestamp::now().as_secs();
let timestamp = latest
.map(|timestamp| (timestamp.timestamp() as u64).saturating_add(1))
.unwrap_or(now)
.max(now);
let event = nostr::EventBuilder::new(nostr::Kind::Custom(kind as u16), "")
.tags(tags)
.allow_self_tagging()
.custom_created_at(nostr::Timestamp::from(timestamp))
.sign_with_keys(signer)
.map_err(|error| DbError::InvalidData(error.to_string()))?;
crate::replaceable::replace_addressable_event_under_lock(tx, &event, Some(channel_id)).await
}

fn group_list_identity_tags(
group_id: &str,
identity: Option<&ChannelIdentity>,
Expand Down
173 changes: 172 additions & 1 deletion crates/buzz-db/src/store/channel_members.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use uuid::Uuid;
use crate::channel::{row_to_channel_record, ChannelRecord};
use crate::error::{DbError, Result};
use crate::{AdmittedTx, Db, ReadAt};
use buzz_core::CommunityId;
use buzz_core::{
kind::{KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS},
CommunityId, StoredEvent,
};
use buzz_datastore_tracing::datastore_span;

pub use buzz_core::channel::MemberRole;
Expand All @@ -35,6 +38,16 @@ pub struct MemberRecord {
pub removed_at: Option<DateTime<Utc>>,
}

/// A conditional role change for an existing Solo member.
pub struct SoloMemberRoleChange {
/// The member whose role is being edited.
pub target: nostr::PublicKey,
/// The active role the signer saw when confirming.
pub expected_role: MemberRole,
/// The requested access (admin, participating, or viewing only).
pub role: MemberRole,
}

/// Namespace for the per-channel membership advisory lock. Serializes the
/// role-authorization + last-owner-count + write sequences in [`add_member`]
/// and [`remove_member`] against each other.
Expand Down Expand Up @@ -2437,6 +2450,164 @@ impl Db {
.await
}

/// Store a signed Solo role command, its membership change, and both
/// relay-signed membership lists in one transaction. A duplicate returns
/// the stored command with no new lists.
#[datastore_span(name = "change_solo_member_role_with_event", system = "postgresql")]
pub async fn change_solo_member_role_with_event(
&self,
community: CommunityId,
channel_id: Uuid,
change: SoloMemberRoleChange,
event: &nostr::Event,
relay_signer: &nostr::Keys,
) -> Result<(StoredEvent, Vec<StoredEvent>)> {
let actor = event.pubkey.to_bytes();
let target = change.target.to_bytes();
let denied = |reason: &str| DbError::AccessDenied(reason.to_owned());
if actor == target || change.expected_role == MemberRole::Owner {
return Err(denied("cannot change a Solo owner's role"));
}
let read_agent_owner = match (change.expected_role, change.role) {
(MemberRole::Admin | MemberRole::Member | MemberRole::Bot, MemberRole::Guest) => false,
(MemberRole::Admin | MemberRole::Guest, MemberRole::Member)
| (MemberRole::Member | MemberRole::Bot | MemberRole::Guest, MemberRole::Admin) => true,
_ => return Err(denied("unsupported Solo member role transition")),
};

let mut tx = crate::begin_community_event_write_transaction(
&self.pool,
community,
crate::observability::WriterOperation::EventWrite,
)
.await?;
tx.set_push_enqueue(self.push_enqueue.clone());
// Roster replacement takes its coordinate lock before the membership
// lock. Account cleanup takes both list locks in this same order.
let relay_pubkey = relay_signer.public_key().to_bytes();
let admins_kind = KIND_NIP29_GROUP_ADMINS as i32;
let members_kind = KIND_NIP29_GROUP_MEMBERS as i32;
for kind in [admins_kind, members_kind] {
crate::replaceable::take_replacement_lock(
&mut tx,
kind,
&relay_pubkey,
Some(channel_id),
)
.await?;
}
lock_channel_for_member_put(&mut tx, channel_id).await?;
let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx(
&mut tx,
event,
Some(channel_id),
None,
)
.await?;
if !inserted {
tx.rollback().await?;
return Ok((stored, Vec::new()));
}

let channel = get_channel_tx(tx.conn(), community, channel_id).await?;
if channel.channel_type != "stream"
|| channel.visibility != "private"
|| !channel.labels.iter().any(|label| label == "buzz.solo")
{
return Err(denied("channel is not a Solo chat"));
}
if channel.archived_at.is_some() {
return Err(denied("channel is archived"));
}
let actor_role = get_active_role_tx(tx.conn(), community, channel_id, &actor).await?;
if actor_role.as_deref() != Some(MemberRole::Owner.as_str()) {
return Err(denied("only a Solo chat owner may change member roles"));
}

// Only the relay's verified ownership record establishes agent identity.
let agent_owner: Option<Vec<u8>> = if read_agent_owner {
sqlx::query_scalar(
"SELECT agent_owner_pubkey FROM users \
WHERE community_id = $1 AND pubkey = $2 AND agent_owner_pubkey IS NOT NULL",
)
.bind(community.as_uuid())
.bind(target.as_slice())
.fetch_optional(tx.conn())
.await?
} else {
None
};
let role = match change.role {
MemberRole::Admin if agent_owner.as_deref() != Some(actor.as_slice()) => {
return Err(denied(
"only an agent's owner may grant it Admin in a Solo chat",
))
}
MemberRole::Member if agent_owner.is_some() => MemberRole::Bot,
MemberRole::Member if change.expected_role == MemberRole::Guest => {
return Err(denied(
"only a verified agent may move from Viewing only to Participating",
))
}
role => role,
};

// Update the active row in place. The same channel lock serializes
// removal and role writes, and a mismatch never inserts a membership.
let affected = sqlx::query(
"UPDATE channel_members SET role = $4::member_role \
WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 \
AND removed_at IS NULL AND role = $5::member_role",
)
.bind(community.as_uuid())
.bind(channel_id)
.bind(target.as_slice())
.bind(role.as_str())
.bind(change.expected_role.as_str())
.execute(tx.conn())
.await?
.rows_affected();
if affected != 1 {
return Err(denied(
"membership or role changed; refresh before trying again",
));
}
crate::insert_mentions_in_transaction(&mut tx, event, Some(channel_id)).await?;

let members = select_active_members(tx.conn(), community, channel_id).await?;
let group_id = channel_id.to_string();
let identity = channel.identity();
let mut group_state = Vec::with_capacity(2);
for (kind, tags) in [
(
admins_kind,
crate::channel::group_admins_tags(&group_id, &identity, &members),
),
(
members_kind,
crate::channel::group_members_tags(&group_id, Some(&identity), &members),
),
] {
let tags = tags.map_err(|error| DbError::InvalidData(error.to_string()))?;
let (snapshot, inserted) = crate::channel::replace_signed_group_state_under_lock(
&mut tx,
channel_id,
kind,
tags,
relay_signer,
)
.await?;
if !inserted {
return Err(DbError::InvalidData(
"Solo group state replacement failed".into(),
));
}
group_state.push(snapshot);
}
tx.commit().await?;
Ok((stored, group_state))
}

/// Removes a member from a channel.
#[datastore_span(name = "remove_member", system = "postgresql")]
pub async fn remove_member(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Membership removal and the three signed discovery lists share one commit.
use super::*;
use buzz_core::CommunityId;
use nostr::{EventBuilder, Kind, Tag, Timestamp};
use nostr::Tag;

impl UserDeletionStore {
pub(super) async fn preflight_memberships(
Expand Down Expand Up @@ -171,22 +171,10 @@ pub(super) async fn rebuild(
)
.map_err(|e| invalid(e.to_string()))?
};
let latest: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar("SELECT max(created_at) FROM events WHERE community_id=$1 AND channel_id=$2 AND kind=$3 AND pubkey=$4 AND deleted_at IS NULL")
.bind(community.as_uuid()).bind(channel_id).bind(kind).bind(signer.public_key().to_bytes().as_slice()).fetch_one(tx.conn()).await?;
let now = Timestamp::now().as_secs();
let timestamp = latest
.map(|t| (t.timestamp() as u64).saturating_add(1))
.unwrap_or(now)
.max(now);
let event = EventBuilder::new(Kind::Custom(kind as u16), "")
.tags(tags)
.allow_self_tagging()
.custom_created_at(Timestamp::from(timestamp))
.sign_with_keys(signer)
.map_err(|e| invalid(e.to_string()))?;
let (_, inserted) =
crate::replaceable::replace_addressable_event_under_lock(tx, &event, Some(channel_id))
.await?;
let (_, inserted) = crate::channel::replace_signed_group_state_under_lock(
tx, channel_id, kind, tags, signer,
)
.await?;
if !inserted {
return Err(invalid(
"channel list replacement failed; membership removal rolled back",
Expand Down
4 changes: 3 additions & 1 deletion crates/buzz-relay/src/handlers/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use tracing::{debug, error, info, warn};
use buzz_core::event::StoredEvent;
use buzz_core::kind::{
event_kind_u32, is_ephemeral, is_unshared_gated_event, KIND_AGENT_OBSERVER_FRAME,
KIND_AGENT_PRESENCE, KIND_GIFT_WRAP, KIND_PRESENCE_UPDATE, KIND_TYPING_INDICATOR,
KIND_AGENT_PRESENCE, KIND_GIFT_WRAP, KIND_PRESENCE_UPDATE, KIND_SOLO_MEMBER_ROLE,
KIND_TYPING_INDICATOR,
};
use buzz_core::observer::{
content_looks_like_nip44, OBSERVER_AGENT_TAG, OBSERVER_FRAME_CONTROL, OBSERVER_FRAME_TAG,
Expand All @@ -35,6 +36,7 @@ pub(crate) fn bounded_kind_label(kind: u32) -> String {
match kind {
0..=9 | 1059 | 1063 => kind.to_string(),
8000..=8003 | 9000..=9022 | 9030..=9036 => kind.to_string(),
KIND_SOLO_MEMBER_ROLE => kind.to_string(),
13534..=13535 => kind.to_string(),
20000..=29999 => kind.to_string(),
30023 | 30315 | 39000..=39003 => kind.to_string(),
Expand Down
Loading
Loading