From 1aafb02620b571a2f85f99ee1deed0c580cd37cc Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 10:35:37 -0800 Subject: [PATCH 01/10] feat(relay): add opt-in guest replies and reactions Co-authored-by: Carl Signed-off-by: Taylor Ho --- NOSTR.md | 31 +- crates/buzz-db/src/store/channel.rs | 57 ++- crates/buzz-db/src/store/channel_members.rs | 4 +- crates/buzz-db/src/store/dm.rs | 2 + .../guest_contributions_postgres_tests.rs | 436 ++++++++++++++++++ crates/buzz-relay/src/handlers/ingest.rs | 171 ++++++- crates/buzz-relay/src/handlers/mod.rs | 3 + .../buzz-relay/src/handlers/side_effects.rs | 29 ++ .../0094_channel_guest_contributions.sql | 6 + schema/tables/public/channels.sql | 2 + 10 files changed, 717 insertions(+), 24 deletions(-) create mode 100644 crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs create mode 100644 migrations/0094_channel_guest_contributions.sql diff --git a/NOSTR.md b/NOSTR.md index 3ee50488bbe..dbd89fac17e 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -103,8 +103,8 @@ relay to specific external Nostr identities without granting full access. ### Announce channels -Roles have the same permissions in every channel. A channel's settings -decide only who can join and which role a new person gets: +A channel's settings decide who can join, which role a new person gets, +and whether guests may contribute within existing conversations: - `visibility` (`open` | `private`) decides who can find, join and read. - `join_role` (`member` | `guest`) is the role a person gets when nobody @@ -112,18 +112,39 @@ decide only who can join and which role a new person gets: add with no `role` tag. The default, `member`, keeps today's behavior. An open channel with `join_role = guest` is an **announce channel**: anyone -can find, read and join it, but people who join are guests and cannot write. +can find, read and join it, but people who join are guests and cannot start +conversations. By default they cannot reply or react either. What each role can do: | Action | Guest | Member or bot | Admin / owner | |--------|-------|---------------|---------------| | Read, leave | Yes | Yes | Yes | -| Post, reply, edit, delete own, react, artifacts, canvas, forum, pins, typing, workflow messages, huddles | No | Yes | Yes | +| Start conversations, artifacts, canvas, forum posts, pins, typing, workflow messages, huddles | No | Yes | Yes | +| Reply, edit/delete own reply | When `guest_replies = true` | Yes | Yes | +| Add reactions | When `guest_reactions = true` | Yes | Yes | +| Remove own reactions | Yes | Yes | Yes | | Topic, purpose (kind:9002) | No | Yes | Yes | | Add people (kind:9000) | No | Yes, as member, guest or bot | Yes; only owners can grant owner | | Push to the channel's git repositories | No | Yes | Yes | -| Name, about, visibility, TTL, `join_role`, `unlisted` | No | No | Yes | +| Name, about, visibility, TTL, `join_role`, `guest_replies`, `guest_reactions`, `unlisted` | No | No | Yes | + +Owners and admins may set `["guest_replies", "true" | "false"]` and +`["guest_reactions", "true" | "false"]` with kind:9002. Both default to false; +omitted tags preserve the setting, and duplicate or malformed values are refused. +Kind:39000 always publishes both flags. Older clients omitting them do not reset +them. These grants apply only to active Guest members of streams and forums; +non-members receive no additional authority. + +The reply grant covers stream message kinds 9 and 40002, including their threads +in forum channels. Forum-specific comments (45003), votes and new posts retain +their existing writer-only gate. A Guest reply must resolve to an existing message root and parent in the same +channel through NIP-10. Unknown, inaccessible, cross-channel and auxiliary-event +parents are refused. A lone root marker is not a reply. `["broadcast", "1"]` +and separate root copies remain forbidden. Reply edits/deletions check the +original target and its author. Removing one's own reaction remains possible +after additions are disabled; other deletion authority is unchanged. Archive, +moderation, token scope and visibility checks still apply. A non-member may write only where joining would give a role that can write: an open channel with `join_role = member`. A refused write gets diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index 7473db74a31..84ef159af2b 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -84,6 +84,10 @@ pub struct ChannelRecord { /// The role a new person gets (`"member"` or `"guest"`). Parse with /// [`buzz_core::channel::ChannelJoinRole::parse_fail_closed`]. pub join_role: String, + /// Whether active guests may reply within existing conversation threads. + pub guest_replies: bool, + /// Whether active guests may add reactions. + pub guest_reactions: bool, /// Whether the channel is left out of channel listings for non-members. /// It matters only while the channel is open: anyone can still read and /// join an unlisted open channel by naming it, and private channels are @@ -188,7 +192,7 @@ pub async fn create_channel( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 "#, ) @@ -251,7 +255,7 @@ pub async fn create_channel_with_id( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 "#, ) @@ -541,7 +545,7 @@ async fn select_channel( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL "#, ) @@ -630,7 +634,7 @@ async fn list_channels_with_operation( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND deleted_at IS NULL AND visibility::text = $2 ORDER BY created_at DESC @@ -650,7 +654,7 @@ async fn list_channels_with_operation( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC @@ -691,7 +695,7 @@ pub async fn list_auto_join_channels( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND auto_join AND channel_type = 'stream' AND visibility = 'open' AND archived_at IS NULL AND deleted_at IS NULL @@ -795,6 +799,8 @@ pub(crate) fn row_to_channel_record(row: sqlx::postgres::PgRow) -> Result &channel.created_at.timestamp().to_string(), ])); tags.push(tag(&["join_role", join_role.as_str()])); + tags.push(tag(&[ + "guest_replies", + if channel.guest_replies { + "true" + } else { + "false" + }, + ])); + tags.push(tag(&[ + "guest_reactions", + if channel.guest_reactions { + "true" + } else { + "false" + }, + ])); if channel.auto_join && open && channel.archived_at.is_none() { tags.push(tag(&["auto_join"])); } @@ -1069,6 +1091,10 @@ pub struct ChannelUpdate { pub labels: Option>, /// New join role (`"member"`/`"guest"`), or `None` to leave unchanged. pub join_role: Option, + /// Whether guests may reply; omission preserves the setting. + pub guest_replies: Option, + /// Whether guests may react; omission preserves the setting. + pub guest_reactions: Option, /// New unlisted flag, or `None` to leave unchanged. It decides listing, /// not admission, so it does not take the membership lock. pub unlisted: Option, @@ -1087,6 +1113,8 @@ impl ChannelUpdate { && self.ttl_seconds.is_none() && self.labels.is_none() && self.join_role.is_none() + && self.guest_replies.is_none() + && self.guest_reactions.is_none() && self.unlisted.is_none() && self.auto_join.is_none() } @@ -1355,6 +1383,15 @@ async fn update_channel_on( set_parts.push(format!("join_role = ${param_idx}")); param_idx += 1; } + for (name, value) in [ + ("guest_replies", updates.guest_replies), + ("guest_reactions", updates.guest_reactions), + ] { + if value.is_some() { + set_parts.push(format!("{name} = ${param_idx}")); + param_idx += 1; + } + } if updates.unlisted.is_some() { set_parts.push(format!("unlisted = ${param_idx}")); param_idx += 1; @@ -1398,6 +1435,12 @@ async fn update_channel_on( if let Some(ref join_role) = updates.join_role { q = q.bind(join_role); } + for value in [updates.guest_replies, updates.guest_reactions] + .into_iter() + .flatten() + { + q = q.bind(value); + } if let Some(unlisted) = updates.unlisted { q = q.bind(unlisted); } @@ -2371,6 +2414,8 @@ mod group_metadata_tag_tests { ttl_deadline: None, labels: Vec::new(), join_role: join_role.into(), + guest_replies: false, + guest_reactions: false, unlisted: false, auto_join: false, } diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 1ba517c547d..908aaaaa869 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2032,7 +2032,7 @@ async fn get_channel_tx( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + ttl_seconds, ttl_deadline, labels, join_role, guest_replies, guest_reactions, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL "#, ) @@ -2130,7 +2130,7 @@ pub async fn get_accessible_channels( c.nip29_group_id, c.topic_required, c.max_members, c.topic, c.topic_set_by, c.topic_set_at, c.purpose, c.purpose_set_by, c.purpose_set_at, - c.ttl_seconds, c.ttl_deadline, c.labels, c.join_role, c.unlisted, c.auto_join, + c.ttl_seconds, c.ttl_deadline, c.labels, c.join_role, c.guest_replies, c.guest_reactions, c.unlisted, c.auto_join, (cm.channel_id IS NOT NULL) AS is_member FROM channels c LEFT JOIN channel_members cm diff --git a/crates/buzz-db/src/store/dm.rs b/crates/buzz-db/src/store/dm.rs index 1a12ba2402a..afbbd448447 100644 --- a/crates/buzz-db/src/store/dm.rs +++ b/crates/buzz-db/src/store/dm.rs @@ -1206,6 +1206,8 @@ fn row_to_channel_record(row: sqlx::postgres::PgRow) -> Result { ttl_deadline: row.try_get("ttl_deadline").unwrap_or(None), labels: row.try_get("labels")?, join_role: row.try_get("join_role")?, + guest_replies: false, + guest_reactions: false, unlisted: row.try_get("unlisted")?, auto_join: row.try_get("auto_join")?, }) diff --git a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs new file mode 100644 index 00000000000..b2ff954da70 --- /dev/null +++ b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs @@ -0,0 +1,436 @@ +//! Critical permission journey through the shared HTTP/WebSocket ingestion seam. +use buzz_auth::Scope; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use uuid::Uuid; + +use super::group_state_postgres_tests::{ + community, create_channel, group_state_tags, http_auth, state, +}; +use super::ingest::{ingest_event, IngestAuth}; + +fn event(keys: &Keys, kind: u16, tags: &[Vec]) -> Event { + EventBuilder::new( + Kind::Custom(kind), + if kind == 9 { "Conversation" } else { "" }, + ) + .tags( + tags.iter() + .cloned() + .chain([vec!["nonce".into(), Uuid::new_v4().to_string()]]) + .map(|tag| Tag::parse(tag).unwrap()), + ) + .sign_with_keys(keys) + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn guests_contribute_only_through_explicit_reply_and_reaction_grants() { + let state = state().await; + let tenant = community(&state, "guest-contributions").await; + let owner = Keys::generate(); + let guest = Keys::generate(); + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let h = vec!["h".into(), channel.to_string()]; + let previous_root = event(&guest, 9, std::slice::from_ref(&h)); + assert!( + ingest_event(&state, &tenant, previous_root.clone(), http_auth(&guest)) + .await + .unwrap() + .accepted + ); + let other_channel = create_channel(&state, &tenant, &owner, &[]).await; + let other_root = event(&owner, 9, &[vec!["h".into(), other_channel.to_string()]]); + assert!( + ingest_event(&state, &tenant, other_root.clone(), http_auth(&owner)) + .await + .unwrap() + .accepted + ); + let add = event( + &owner, + 9000, + &[ + h.clone(), + vec!["p".into(), guest.public_key().to_hex()], + vec!["role".into(), "guest".into()], + ], + ); + assert!( + ingest_event(&state, &tenant, add, http_auth(&owner)) + .await + .unwrap() + .accepted + ); + assert_eq!( + state + .db + .get_member_role(tenant.community(), channel, &guest.public_key().to_bytes()) + .await + .unwrap() + .as_deref(), + Some("guest") + ); + let initial = state + .db + .get_channel(tenant.community(), channel) + .await + .unwrap(); + assert!(!initial.guest_replies && !initial.guest_reactions); + let root = event(&owner, 9, std::slice::from_ref(&h)); + assert!( + ingest_event(&state, &tenant, root.clone(), http_auth(&owner)) + .await + .unwrap() + .accepted + ); + let reply_tags = vec![ + h.clone(), + vec!["e".into(), root.id.to_hex(), "".into(), "reply".into()], + ]; + for (replies, reactions) in [(false, false), (true, false), (false, true), (true, true)] { + let settings = event( + &owner, + 9002, + &[ + h.clone(), + vec!["guest_replies".into(), replies.to_string()], + vec!["guest_reactions".into(), reactions.to_string()], + ], + ); + assert!( + ingest_event(&state, &tenant, settings, http_auth(&owner)) + .await + .unwrap() + .accepted + ); + let tags = group_state_tags(&state, &tenant, channel, 39000).await; + assert!(tags.contains(&vec!["guest_replies".into(), replies.to_string()])); + assert!(tags.contains(&vec!["guest_reactions".into(), reactions.to_string()])); + for websocket in [false, true] { + let auth = || { + if websocket { + IngestAuth::Nip42 { + pubkey: guest.public_key(), + scopes: vec![ + Scope::MessagesWrite, + Scope::ChannelsWrite, + Scope::AdminChannels, + ], + channel_ids: None, + conn_id: Uuid::new_v4(), + } + } else { + http_auth(&guest) + } + }; + let reply = event(&guest, 9, &reply_tags); + let outcome = ingest_event(&state, &tenant, reply.clone(), auth()).await; + assert_eq!( + outcome.is_ok_and(|r| r.accepted), + replies, + "reply {replies}/{reactions}/{websocket}" + ); + if replies { + let nested = event( + &guest, + 9, + &[ + h.clone(), + vec!["e".into(), root.id.to_hex(), "".into(), "root".into()], + vec!["e".into(), reply.id.to_hex(), "".into(), "reply".into()], + ], + ); + assert!( + ingest_event(&state, &tenant, nested, auth()) + .await + .unwrap() + .accepted + ); + let edit = event( + &guest, + 40003, + &[h.clone(), vec!["e".into(), reply.id.to_hex()]], + ); + assert!( + ingest_event(&state, &tenant, edit, auth()) + .await + .unwrap() + .accepted + ); + } + if replies { + let deletion = event(&guest, 5, &[h.clone(), vec!["e".into(), reply.id.to_hex()]]); + assert!( + ingest_event(&state, &tenant, deletion, auth()) + .await + .unwrap() + .accepted + ); + } + let mut reaction_tags = vec![ + Tag::parse(["e", &root.id.to_hex()]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]; + if websocket { + reaction_tags.push(Tag::parse(h.clone()).unwrap()); + } + let reaction = EventBuilder::new(Kind::Reaction, "๐Ÿ‘") + .tags(reaction_tags) + .sign_with_keys(&guest) + .unwrap(); + let outcome = ingest_event(&state, &tenant, reaction.clone(), auth()).await; + assert_eq!( + outcome.is_ok_and(|r| r.accepted), + reactions, + "reaction {replies}/{reactions}/{websocket}" + ); + for forbidden in [ + event( + &guest, + 40003, + &[h.clone(), vec!["e".into(), previous_root.id.to_hex()]], + ), + event( + &guest, + 5, + &[h.clone(), vec!["e".into(), previous_root.id.to_hex()]], + ), + event( + &guest, + 9, + &[ + h.clone(), + vec![ + "e".into(), + other_root.id.to_hex(), + "".into(), + "reply".into(), + ], + ], + ), + event(&guest, 9, std::slice::from_ref(&h)), + event( + &guest, + 9, + &[ + h.clone(), + vec!["e".into(), root.id.to_hex(), "".into(), "root".into()], + ], + ), + event( + &guest, + 9, + &[ + reply_tags[0].clone(), + reply_tags[1].clone(), + vec!["broadcast".into(), "1".into()], + ], + ), + event( + &guest, + 9, + &[ + h.clone(), + vec!["e".into(), "f".repeat(64), "".into(), "reply".into()], + ], + ), + event( + &guest, + 9002, + &[h.clone(), vec!["guest_replies".into(), "true".into()]], + ), + event(&guest, 40100, std::slice::from_ref(&h)), + ] { + assert!(ingest_event(&state, &tenant, forbidden, auth()) + .await + .is_err()); + } + if reactions { + let fake_thread = event( + &guest, + 9, + &[ + h.clone(), + vec!["e".into(), reaction.id.to_hex(), "".into(), "reply".into()], + ], + ); + assert!(ingest_event(&state, &tenant, fake_thread, auth()) + .await + .is_err()); + let removal = event( + &guest, + 5, + &[ + vec!["e".into(), reaction.id.to_hex()], + vec!["k".into(), "7".into()], + ], + ); + assert!( + ingest_event(&state, &tenant, removal, auth()) + .await + .unwrap() + .accepted + ); + } + } + } + // Managing one's persisted reply still works after its parent was deleted. + let orphan = event(&guest, 9, &reply_tags); + assert!( + ingest_event(&state, &tenant, orphan.clone(), http_auth(&guest)) + .await + .unwrap() + .accepted + ); + let delete_root = event(&owner, 5, &[h.clone(), vec!["e".into(), root.id.to_hex()]]); + assert!( + ingest_event(&state, &tenant, delete_root, http_auth(&owner)) + .await + .unwrap() + .accepted + ); + for kind in [40003, 5] { + let operation = event( + &guest, + kind, + &[h.clone(), vec!["e".into(), orphan.id.to_hex()]], + ); + assert!( + ingest_event(&state, &tenant, operation, http_auth(&guest)) + .await + .unwrap() + .accepted + ); + } + // An unrelated edit preserves the grants; malformed and duplicate grants fail. + let rename = event( + &owner, + 9002, + &[h.clone(), vec!["about".into(), "Updated".into()]], + ); + assert!( + ingest_event(&state, &tenant, rename, http_auth(&owner)) + .await + .unwrap() + .accepted + ); + assert!( + state + .db + .get_channel(tenant.community(), channel) + .await + .unwrap() + .guest_replies + ); + for values in [vec!["yes"], vec!["true", "false"]] { + let mut tags = vec![h.clone()]; + tags.extend( + values + .into_iter() + .map(|v| vec!["guest_replies".into(), v.into()]), + ); + assert!(ingest_event( + &state, + &tenant, + event(&owner, 9002, &tags), + http_auth(&owner) + ) + .await + .is_err()); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn revoking_guest_grants_blocks_additions_but_preserves_own_reaction_removal() { + let state = state().await; + let tenant = community(&state, "guest-revocation").await; + let owner = Keys::generate(); + let guest = Keys::generate(); + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let h = vec!["h".into(), channel.to_string()]; + for command in [ + event( + &owner, + 9000, + &[ + h.clone(), + vec!["p".into(), guest.public_key().to_hex(), "guest".into()], + ], + ), + event( + &owner, + 9002, + &[ + h.clone(), + vec!["guest_replies".into(), "true".into()], + vec!["guest_reactions".into(), "true".into()], + ], + ), + ] { + assert!( + ingest_event(&state, &tenant, command, http_auth(&owner)) + .await + .unwrap() + .accepted + ); + } + let root = event(&owner, 9, std::slice::from_ref(&h)); + assert!( + ingest_event(&state, &tenant, root.clone(), http_auth(&owner)) + .await + .unwrap() + .accepted + ); + let reaction = EventBuilder::new(Kind::Reaction, "+") + .tags([Tag::parse(["e", &root.id.to_hex()]).unwrap()]) + .sign_with_keys(&guest) + .unwrap(); + assert!( + ingest_event(&state, &tenant, reaction.clone(), http_auth(&guest)) + .await + .unwrap() + .accepted + ); + let revoke = event( + &owner, + 9002, + &[ + h.clone(), + vec!["guest_replies".into(), "false".into()], + vec!["guest_reactions".into(), "false".into()], + ], + ); + assert!( + ingest_event(&state, &tenant, revoke, http_auth(&owner)) + .await + .unwrap() + .accepted + ); + let reply = event( + &guest, + 9, + &[ + h.clone(), + vec!["e".into(), root.id.to_hex(), "".into(), "reply".into()], + ], + ); + assert!(ingest_event(&state, &tenant, reply, http_auth(&guest)) + .await + .is_err()); + let addition = EventBuilder::new(Kind::Reaction, "๐Ÿ‘") + .tags([Tag::parse(["e", &root.id.to_hex()]).unwrap()]) + .sign_with_keys(&guest) + .unwrap(); + assert!(ingest_event(&state, &tenant, addition, http_auth(&guest)) + .await + .is_err()); + let removal = event(&guest, 5, &[vec!["e".into(), reaction.id.to_hex()]]); + assert!( + ingest_event(&state, &tenant, removal, http_auth(&guest)) + .await + .unwrap() + .accepted + ); +} diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 2f2ce7257c9..eeb924d8aad 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -1033,6 +1033,123 @@ pub(crate) fn non_member_may_post(visibility: &str, join_role: &str) -> bool { visibility == "open" && ChannelJoinRole::parse_fail_closed(join_role) == ChannelJoinRole::Member } +/// The only exceptions to a Guest's broad write denial. Existing writers and +/// non-content callers continue to use `check_channel_membership` unchanged. +/// A resolved reply is returned for reuse by the persistence path. +async fn guest_contribution( + community_id: CommunityId, + state: &AppState, + channel: &buzz_db::channel::ChannelRecord, + event: &Event, +) -> Result, String> { + let actor = effective_message_author(event, &state.relay_keypair.public_key()); + if !matches!(channel.channel_type.as_str(), "stream" | "forum") + || !state + .is_member_cached(community_id, channel.id, &actor) + .await + .map_err(|e| format!("error: database error: {e}"))? + || state + .db + .get_member_role(community_id, channel.id, &actor) + .await + .map_err(|e| format!("error: database error: {e}"))? + .as_deref() + != Some("guest") + { + return Err(MEMBERS_ONLY_POSTING.into()); + } + match event_kind_u32(event) { + KIND_STREAM_MESSAGE | KIND_STREAM_MESSAGE_V2 if channel.guest_replies => { + guest_reply_meta(community_id, state, channel.id, event) + .await + .map(Some) + } + // Target visibility/channel and reaction validity are checked by ingest. + KIND_REACTION if channel.guest_reactions => Ok(None), + KIND_DELETION | KIND_STREAM_MESSAGE_EDIT => { + let targets = super::side_effects::extract_target_event_ids(event); + let [id] = targets.as_slice() else { + return Err(MEMBERS_ONLY_POSTING.into()); + }; + let target = state + .db + .get_event_by_id_including_deleted_for_event_write(community_id, id) + .await + .map_err(|e| format!("error: database error: {e}"))? + .filter(|target| { + target_readable_in_channel(target, channel.id, &actor) + && effective_message_author( + &target.event, + &state.relay_keypair.public_key(), + ) == actor + }) + .ok_or_else(|| MEMBERS_ONLY_POSTING.to_string())?; + match event_kind_u32(&target.event) { + // Removal of one's own reaction remains possible after disabling + // additions, without granting deletion of any other event kind. + KIND_REACTION if event_kind_u32(event) == KIND_DELETION => Ok(None), + KIND_STREAM_MESSAGE | KIND_STREAM_MESSAGE_V2 if channel.guest_replies => { + let metadata = state + .db + .get_thread_metadata_by_event(community_id, id) + .await + .map_err(|e| format!("error: database error: {e}"))?; + // Persisted ancestry remains authoritative after a parent is + // deleted. Legacy events without metadata are resolved below. + if !metadata.is_some_and(|meta| { + meta.channel_id == channel.id + && meta.parent_event_id.is_some() + && !meta.broadcast + }) { + guest_reply_meta(community_id, state, channel.id, &target.event).await?; + } + Ok(None) + } + _ => Err(MEMBERS_ONLY_POSTING.into()), + } + } + _ => Err(MEMBERS_ONLY_POSTING.into()), + } +} + +async fn guest_reply_meta( + community_id: CommunityId, + state: &AppState, + channel_id: Uuid, + event: &Event, +) -> Result { + if event.tags.iter().any(|tag| { + let parts = tag.as_slice(); + parts.first().map(String::as_str) == Some("broadcast") + && parts.get(1).map(String::as_str) == Some("1") + }) { + return Err(MEMBERS_ONLY_POSTING.into()); + } + let meta = resolve_nip10_thread_meta(community_id, event, channel_id, state) + .await? + .ok_or_else(|| MEMBERS_ONLY_POSTING.to_string())?; + let actor = effective_message_author(event, &state.relay_keypair.public_key()); + // An auxiliary event must not become a synthetic conversation root/parent. + for id in [&meta.root_event_id, &meta.parent_event_id] { + let valid = state + .db + .get_event_by_id_for_event_write(community_id, id) + .await + .map_err(|e| format!("error: database error: {e}"))? + .is_some_and(|target| { + target_readable_in_channel(&target, channel_id, &actor) + && matches!( + event_kind_u32(&target.event), + KIND_STREAM_MESSAGE | KIND_STREAM_MESSAGE_V2 + ) + }); + if !valid { + return Err(MEMBERS_ONLY_POSTING.into()); + } + } + Ok(meta) +} + /// The kind-9 channel write gates (token scope, membership or open channel, /// not archived) for a channel other than the event's own `h`. pub(crate) async fn check_channel_write( @@ -1484,15 +1601,35 @@ async fn validate_edit_ownership( if let Some(ch_id) = target_event.channel_id { // A refused write is denied exactly like a missing target; // database errors keep their own message. - check_channel_membership(community_id, state, ch_id, &actor, None, ChannelWrite::Post) - .await - .map_err(|error| { - if error.starts_with("error:") { - error - } else { - EDIT_TARGET_DENIED.to_string() - } - })?; + let access = check_channel_membership( + community_id, + state, + ch_id, + &actor, + None, + ChannelWrite::Post, + ) + .await; + let access = if access.as_ref().err().map(String::as_str) == Some(MEMBERS_ONLY_POSTING) + { + let channel = state + .db + .get_channel_for_event_write(community_id, ch_id) + .await + .map_err(|e| format!("error: database error: {e}"))?; + guest_contribution(community_id, state, &channel, event) + .await + .map(|_| ()) + } else { + access + }; + access.map_err(|error| { + if error.starts_with("error:") { + error + } else { + EDIT_TARGET_DENIED.to_string() + } + })?; } } else { // Allow the owning human to edit messages authored by their agent. @@ -2906,6 +3043,7 @@ async fn ingest_event_inner( Some(ch_id) => load_channel_for_write(tenant, state, ch_id).await?, None => None, }; + let mut guest_thread_meta = None; // E1 phase-2 (ยง4.8 phase-2 addendum): resolve the fan-out visibility once, // here, through the same `channel_visibility_cached` gate fan-out uses // (fence 2: cached `private` wins over the prefetched row; a `private` @@ -2949,7 +3087,7 @@ async fn ingest_event_inner( // at `check_channel_membership`'s `is_member_cached(tenant // .community(), โ€ฆ)` call (see crates/buzz-relay/src/handlers // /ingest.rs:424). - let auth_result = check_channel_membership( + let mut auth_result = check_channel_membership( tenant.community(), state, ch_id, @@ -2958,6 +3096,15 @@ async fn ingest_event_inner( ChannelWrite::for_kind(kind_u32), ) .await; + if auth_result.as_ref().err().map(String::as_str) == Some(MEMBERS_ONLY_POSTING) { + if let Some(channel) = &channel_row { + auth_result = guest_contribution(tenant.community(), state, channel, &event) + .await + .map(|meta| { + guest_thread_meta = meta; + }); + } + } let claimed = claimed_community_from_event(&event); let verdict = if auth_result.is_ok() { Verdict::Allow @@ -3424,7 +3571,9 @@ async fn ingest_event_inner( validate_event_imeta(tenant, state, &event, &tenant_media_base).await?; - let thread_meta = if requires_h_channel_scope(kind_u32) { + let thread_meta = if guest_thread_meta.is_some() { + guest_thread_meta + } else if requires_h_channel_scope(kind_u32) { if let Some(ch_id) = channel_id { resolve_nip10_thread_meta(tenant.community(), &event, ch_id, state) .await diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 19d9942e068..c83f2507ad5 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -26,10 +26,13 @@ mod deletion_postgres_tests; mod dm_growth_postgres_tests; #[cfg(test)] mod edit_metadata_postgres_tests; + /// EVENT handler โ€” WS dispatcher โ†’ ingest pipeline โ†’ fan-out. pub mod event; #[cfg(test)] pub(crate) mod group_state_postgres_tests; +#[cfg(test)] +mod guest_contributions_postgres_tests; /// NIP-IA identity archive request handler (kinds 9035โ€“9036). pub mod identity_archive; /// imeta tag validation helpers. diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index e402f469c41..f6645cf53ca 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -768,6 +768,21 @@ pub async fn validate_admin_event( } } + for name in ["guest_replies", "guest_reactions"] { + let tags: Vec<_> = event + .tags + .iter() + .filter(|t| t.kind().to_string() == name) + .collect(); + if tags.len() > 1 + || tags.iter().any(|t| { + t.as_slice().len() != 2 || !matches!(t.content(), Some("true" | "false")) + }) + { + return Err(anyhow::anyhow!("{name} must be one true/false tag")); + } + } + // Validate channel names before storage. A name made entirely of // display-prefix hashes becomes empty after canonicalization, and // a name the column cannot hold would fail only after the command @@ -1484,6 +1499,8 @@ const PRIVILEGED_METADATA_TAGS: &[&str] = &[ "ttl", "t", "join_role", + "guest_replies", + "guest_reactions", "unlisted", ]; @@ -2379,6 +2396,18 @@ pub(crate) async fn persist_edit_metadata( val.parse().map_err(|e: String| anyhow::anyhow!(e))?; edit.columns.join_role = Some(join_role.as_str().to_string()); } + "guest_replies" | "guest_reactions" => { + let value = match val { + "true" => true, + "false" => false, + _ => return Err(anyhow::anyhow!("invalid guest contribution value")), + }; + if tag.kind().to_string() == "guest_replies" { + edit.columns.guest_replies = Some(value); + } else { + edit.columns.guest_reactions = Some(value); + } + } "auto_join" => { // Validated during authorization; fail closed on a resend // that somehow carries another value. diff --git a/migrations/0094_channel_guest_contributions.sql b/migrations/0094_channel_guest_contributions.sql new file mode 100644 index 00000000000..1e01b1c23f4 --- /dev/null +++ b/migrations/0094_channel_guest_contributions.sql @@ -0,0 +1,6 @@ +-- Narrow, opt-in contribution grants; existing channels remain unchanged. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; +ALTER TABLE channels + ADD COLUMN guest_replies BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN guest_reactions BOOLEAN NOT NULL DEFAULT false; diff --git a/schema/tables/public/channels.sql b/schema/tables/public/channels.sql index 9162b502a64..625b04ca569 100644 --- a/schema/tables/public/channels.sql +++ b/schema/tables/public/channels.sql @@ -41,6 +41,8 @@ CREATE TABLE channels ( -- An unlisted open channel is readable and joinable by id but left out of -- channel listings for non-members. Matters only while the channel is open. unlisted BOOLEAN NOT NULL DEFAULT FALSE, + guest_replies BOOLEAN NOT NULL DEFAULT false, + guest_reactions BOOLEAN NOT NULL DEFAULT false, auto_join BOOLEAN NOT NULL DEFAULT false, PRIMARY KEY (community_id, id), CONSTRAINT chk_channels_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) From b04afa5cde2a3e34d5350aca2e0da79e312fa687 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 10:35:57 -0800 Subject: [PATCH 02/10] feat(mobile): honor viewer contribution permissions Co-authored-by: Carl Signed-off-by: Taylor Ho --- mobile/lib/features/channels/channel.dart | 20 ++ .../channels/channel_detail_page.dart | 11 +- .../channels/channel_detail_page/banners.dart | 9 +- .../features/channels/channel_directory.dart | 2 + .../channels/channel_management_provider.dart | 2 + .../channels/channel_permissions.dart | 47 +++++ .../features/channels/channels_provider.dart | 2 + .../features/channels/message_actions.dart | 40 +++- .../lib/features/channels/reaction_row.dart | 52 ++++- .../channels/send_message_provider.dart | 22 ++- .../features/channels/thread_detail_page.dart | 6 + .../lib/features/forum/forum_posts_view.dart | 5 +- .../lib/features/forum/forum_thread_page.dart | 7 +- mobile/lib/shared/relay/nostr_models.dart | 15 ++ .../channels/channel_permissions_test.dart | 178 ++++++++++++++++++ .../channels/send_message_provider_test.dart | 39 ++++ 16 files changed, 436 insertions(+), 21 deletions(-) create mode 100644 mobile/lib/features/channels/channel_permissions.dart create mode 100644 mobile/test/features/channels/channel_permissions_test.dart diff --git a/mobile/lib/features/channels/channel.dart b/mobile/lib/features/channels/channel.dart index 1fd26f9d09e..95788da0594 100644 --- a/mobile/lib/features/channels/channel.dart +++ b/mobile/lib/features/channels/channel.dart @@ -37,6 +37,8 @@ class Channel { /// Whether joining gives the read-only `guest` role (see /// [ChannelData.joinsAsGuest]). final bool joinsAsGuest; + final bool guestReplies; + final bool guestReactions; const Channel({ required this.id, @@ -59,6 +61,8 @@ class Channel { this.ttlDeadline, this.isUnlisted = false, this.joinsAsGuest = false, + this.guestReplies = false, + this.guestReactions = false, }); factory Channel.fromJson(Map json) => Channel( @@ -91,6 +95,8 @@ class Channel { : null, isUnlisted: json['unlisted'] as bool? ?? false, joinsAsGuest: json['joins_as_guest'] as bool? ?? false, + guestReplies: json['guest_replies'] == true, + guestReactions: json['guest_reactions'] == true, ); /// Inverse of [Channel.fromJson]. @@ -115,6 +121,8 @@ class Channel { 'ttl_deadline': ttlDeadline?.toIso8601String(), 'unlisted': isUnlisted, 'joins_as_guest': joinsAsGuest, + 'guest_replies': guestReplies, + 'guest_reactions': guestReactions, }; bool get isEphemeral => ttlSeconds != null || ttlDeadline != null; @@ -202,6 +210,8 @@ class Channel { ttlDeadline: details.ttlDeadline, isUnlisted: isUnlisted, joinsAsGuest: joinsAsGuest, + guestReplies: details.guestReplies, + guestReactions: details.guestReactions, ); Channel copyWith({ @@ -237,12 +247,16 @@ class Channel { ttlDeadline: ttlDeadline, isUnlisted: isUnlisted, joinsAsGuest: joinsAsGuest ?? this.joinsAsGuest, + guestReplies: guestReplies, + guestReactions: guestReactions, ); } @immutable class ChannelDetails { final String id; + final bool guestReplies; + final bool guestReactions; final String name; /// NIP-CL labels from metadata; presentation hints, never access grants. @@ -261,6 +275,8 @@ class ChannelDetails { const ChannelDetails({ required this.id, + this.guestReplies = false, + this.guestReactions = false, required this.name, required this.channelType, this.labels = const [], @@ -278,6 +294,8 @@ class ChannelDetails { factory ChannelDetails.fromJson(Map json) => ChannelDetails( id: json['id'] as String, + guestReplies: json['guest_replies'] == true, + guestReactions: json['guest_reactions'] == true, name: json['name'] as String, channelType: json['channel_type'] as String, labels: (json['labels'] as List? ?? const []).cast(), @@ -299,6 +317,8 @@ class ChannelDetails { factory ChannelDetails.fromChannel(Channel channel) => ChannelDetails( id: channel.id, + guestReplies: channel.guestReplies, + guestReactions: channel.guestReactions, name: channel.name, channelType: channel.channelType, labels: channel.labels, diff --git a/mobile/lib/features/channels/channel_detail_page.dart b/mobile/lib/features/channels/channel_detail_page.dart index b11580fff61..91bfe03bf90 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -1,3 +1,4 @@ +import 'channel_permissions.dart'; import '../../shared/widgets/duo_toolbar.dart'; import 'composer_geometry.dart'; import 'message_author_visibility.dart'; @@ -5,6 +6,7 @@ import 'message_author_visibility.dart'; import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; + import 'message_swipe_reply.dart'; import 'bestie_welcome.dart'; import 'bestie_welcome_storage.dart'; @@ -318,8 +320,9 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { final memberProfilesPreloadState = useFuture(memberProfilesPreload); final showsComposer = !resolvedChannel.isForum && - resolvedChannel.isMember && - !resolvedChannel.isArchived; + ref + .watch(channelPermissionsProvider(resolvedChannel.id)) + .allows(ChannelAction.post); final profileOwnedAgentPubkeys = []; for (final participantPubkey in resolvedChannel.participantPubkeys) { final normalized = participantPubkey.trim().toLowerCase(); @@ -906,9 +909,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { ), ), ), - if (!resolvedChannel.isForum && - (!resolvedChannel.isMember || - resolvedChannel.isArchived)) ...[ + if (!resolvedChannel.isForum && !showsComposer) ...[ if (!resolvedChannel.isDm) _ReadOnlyNotice(channel: resolvedChannel), ], diff --git a/mobile/lib/features/channels/channel_detail_page/banners.dart b/mobile/lib/features/channels/channel_detail_page/banners.dart index 9616722f9cd..0a184058ed8 100644 --- a/mobile/lib/features/channels/channel_detail_page/banners.dart +++ b/mobile/lib/features/channels/channel_detail_page/banners.dart @@ -14,7 +14,8 @@ class _ReadOnlyNotice extends HookConsumerWidget { final isOpen = channel.visibility == 'open' && !channel.isArchived; // Joining a guest-join channel grants a role that cannot post, so it // offers no Join (as on desktop). - final canJoin = isOpen && !channel.joinsAsGuest; + final canJoin = isOpen && !channel.isMember && !channel.joinsAsGuest; + final permissions = ref.watch(channelPermissionsProvider(channel.id)); Future join() async { if (isJoining.value) return; @@ -40,6 +41,12 @@ class _ReadOnlyNotice extends HookConsumerWidget { final message = channel.isArchived ? 'This $place is archived and read-only on mobile.' + : channel.isMember + ? permissions.allows(ChannelAction.reply) + ? 'You can reply in threads, but cannot start conversations.' + : permissions.allows(ChannelAction.react) + ? 'You can react, but cannot send messages.' + : 'You have viewing access to this $place.' : isOpen && channel.joinsAsGuest ? 'This $place is read-only' : canJoin && isUnconfirmed.value diff --git a/mobile/lib/features/channels/channel_directory.dart b/mobile/lib/features/channels/channel_directory.dart index 4a12ec760f2..3bab05f1c22 100644 --- a/mobile/lib/features/channels/channel_directory.dart +++ b/mobile/lib/features/channels/channel_directory.dart @@ -1105,6 +1105,8 @@ extension _ChannelsNotifierDirectory on ChannelsNotifier { prev.isArchived != channel.isArchived || prev.channelType != channel.channelType || prev.visibility != channel.visibility || + prev.guestReplies != channel.guestReplies || + prev.guestReactions != channel.guestReactions || prev.createdBy != channel.createdBy || !listEquals(prev.labels, channel.labels)) { _lifecycleRef.invalidate(channelDetailsProvider(channel.id)); diff --git a/mobile/lib/features/channels/channel_management_provider.dart b/mobile/lib/features/channels/channel_management_provider.dart index 8e4398ee828..2e2da168943 100644 --- a/mobile/lib/features/channels/channel_management_provider.dart +++ b/mobile/lib/features/channels/channel_management_provider.dart @@ -349,6 +349,8 @@ ChannelDetails channelDetailsFromEvent(NostrEvent event) { ); return ChannelDetails( id: data.id, + guestReplies: data.guestReplies, + guestReactions: data.guestReactions, name: data.name, channelType: data.channelType, labels: data.labels, diff --git a/mobile/lib/features/channels/channel_permissions.dart b/mobile/lib/features/channels/channel_permissions.dart new file mode 100644 index 00000000000..480e73f0250 --- /dev/null +++ b/mobile/lib/features/channels/channel_permissions.dart @@ -0,0 +1,47 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/relay/relay.dart'; +import 'channel.dart'; +import 'channel_management_provider.dart'; +import 'channels_provider.dart'; + +enum ChannelAction { post, reply, react, removeReaction } + +/// Admission defaults never describe an existing participant's authority. +class ChannelPermissions { + final Channel? channel; + final String? role; + + const ChannelPermissions(this.channel, this.role); + + bool allows(ChannelAction action) { + final channel = this.channel; + if (channel == null || !channel.isMember || channel.isArchived) { + return false; + } + if (channel.isDm || + const ['owner', 'admin', 'member', 'bot'].contains(role)) { + return true; + } + if (role != 'guest' || !(channel.isStream || channel.isForum)) return false; + return switch (action) { + ChannelAction.post => false, + ChannelAction.reply => channel.guestReplies, + ChannelAction.react => channel.guestReactions, + ChannelAction.removeReaction => true, + }; + } +} + +/// Reuses the page's roster cache and its existing live invalidation path. +final channelPermissionsProvider = Provider.autoDispose + .family((ref, channelId) { + final channel = ref.watch(channelByIdProvider(channelId)); + final viewer = ref.watch(myPubkeyProvider)?.toLowerCase(); + final members = ref.watch(latestChannelMembersProvider(channelId)); + final role = members + ?.where((member) => member.pubkey.toLowerCase() == viewer) + .firstOrNull + ?.role; + return ChannelPermissions(channel, role); + }); diff --git a/mobile/lib/features/channels/channels_provider.dart b/mobile/lib/features/channels/channels_provider.dart index eca2637784f..4d3b404beb8 100644 --- a/mobile/lib/features/channels/channels_provider.dart +++ b/mobile/lib/features/channels/channels_provider.dart @@ -825,6 +825,8 @@ class ChannelsNotifier extends AsyncNotifier> { ttlDeadline: data.ttlDeadline, isUnlisted: data.isUnlisted, joinsAsGuest: data.joinsAsGuest, + guestReplies: data.guestReplies, + guestReactions: data.guestReactions, ); } diff --git a/mobile/lib/features/channels/message_actions.dart b/mobile/lib/features/channels/message_actions.dart index 36535b5ffba..b144f468382 100644 --- a/mobile/lib/features/channels/message_actions.dart +++ b/mobile/lib/features/channels/message_actions.dart @@ -1,4 +1,7 @@ +import 'channel_permissions.dart'; + import 'package:buzz/shared/widgets/feedback_snackbar.dart'; + import 'dart:async'; import 'dart:io'; import 'dart:ui' as ui; @@ -87,6 +90,14 @@ Future showMessageActions({ }) async { if (!context.mounted) return; unawaited(HapticFeedback.mediumImpact()); + final permissions = ref.read(channelPermissionsProvider(channelId)); + canManageMessage = + canManageMessage && + (message.pubkey.toLowerCase() != + ref.read(myPubkeyProvider)?.toLowerCase() || + permissions.allows( + message.parentId == null ? ChannelAction.post : ChannelAction.reply, + )); final restoreFocusOnCancel = composerFocusNode?.hasFocus ?? false; composerFocusNode?.unfocus(); @@ -118,14 +129,15 @@ Future showMessageActions({ child: Column( mainAxisSize: MainAxisSize.min, children: [ - _QuickReactionRow( - message: message, - reactions: reactions ?? message.reactions, - onToggleReaction: onToggleReaction, - sheetContext: sheetContext, - pageContext: context, - pageRef: ref, - ), + if (permissions.allows(ChannelAction.react)) + _QuickReactionRow( + message: message, + reactions: reactions ?? message.reactions, + onToggleReaction: onToggleReaction, + sheetContext: sheetContext, + pageContext: context, + pageRef: ref, + ), SizedBox(height: message.isSystem ? Grid.xxs : Grid.xs), if (!message.isSystem) ...[ // Fast actions: respond now, hand off context, defer. @@ -247,6 +259,18 @@ void showImageActions({ required bool canManageMessage, VoidCallback? onDeleted, }) { + if (message.pubkey.toLowerCase() == + ref.read(myPubkeyProvider)?.toLowerCase()) { + canManageMessage = + canManageMessage && + ref + .read(channelPermissionsProvider(channelId)) + .allows( + message.parentId == null + ? ChannelAction.post + : ChannelAction.reply, + ); + } showBuzzModalBottomSheet( context: context, isScrollControlled: true, diff --git a/mobile/lib/features/channels/reaction_row.dart b/mobile/lib/features/channels/reaction_row.dart index e7d406f9611..ceae2fc1fd7 100644 --- a/mobile/lib/features/channels/reaction_row.dart +++ b/mobile/lib/features/channels/reaction_row.dart @@ -1,4 +1,7 @@ +import 'channel_permissions.dart'; + import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; @@ -56,6 +59,20 @@ const _pillGlyphSize = 16.0; void toggleReaction(WidgetRef ref, TimelineMessage message, String emoji) { final reaction = message.reactions.where((r) => r.emoji == emoji).firstOrNull; if (reaction == null) return; + final channelId = message.tags + .where((t) => t.length >= 2 && t[0] == 'h') + .firstOrNull + ?.elementAt(1); + if (channelId == null || + !ref + .read(channelPermissionsProvider(channelId)) + .allows( + reaction.reactedByCurrentUser + ? ChannelAction.removeReaction + : ChannelAction.react, + )) { + return; + } final actions = ref.read(channelActionsProvider); if (reaction.reactedByCurrentUser && reaction.currentUserReactionId != null) { actions.removeReaction(reaction.currentUserReactionId!, emoji); @@ -91,9 +108,24 @@ void showAddReactionPicker({ required WidgetRef ref, required TimelineMessage message, }) { + final channelId = message.tags + .where((t) => t.length >= 2 && t[0] == 'h') + .firstOrNull + ?.elementAt(1); + if (channelId == null || + !ref + .read(channelPermissionsProvider(channelId)) + .allows(ChannelAction.react)) { + return; + } showEmojiPicker( context: context, onSelect: (emoji) { + if (!ref + .read(channelPermissionsProvider(channelId)) + .allows(ChannelAction.react)) { + return; + } ref.read(recentEmojiProvider.notifier).record(emoji); armReactionBurst(ref, message, emoji); ref @@ -103,7 +135,7 @@ void showAddReactionPicker({ ); } -class ReactionRow extends HookWidget { +class ReactionRow extends HookConsumerWidget { /// The message these reactions belong to. Used to match a pending burst to /// the right pill โ€” the same emoji can be pending on a different message. final String messageId; @@ -137,7 +169,23 @@ class ReactionRow extends HookWidget { }); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + void onToggle(String emoji) { + final own = reactions.any( + (reaction) => reaction.emoji == emoji && reaction.reactedByCurrentUser, + ); + if (ref + .read(channelPermissionsProvider(channelId)) + .allows(own ? ChannelAction.removeReaction : ChannelAction.react)) { + this.onToggle(emoji); + } + } + + final showAddButton = + this.showAddButton && + ref + .watch(channelPermissionsProvider(channelId)) + .allows(ChannelAction.react); final liveReactions = useMemoized(() => ValueNotifier(reactions)); useEffect( () => () { diff --git a/mobile/lib/features/channels/send_message_provider.dart b/mobile/lib/features/channels/send_message_provider.dart index f7900280165..7b6ca6543a1 100644 --- a/mobile/lib/features/channels/send_message_provider.dart +++ b/mobile/lib/features/channels/send_message_provider.dart @@ -1,3 +1,5 @@ +import 'channel_permissions.dart'; + import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../shared/mentions/mention_tags.dart'; @@ -23,6 +25,7 @@ class SendMessage { final void Function(String channelId, String eventId) _completeLocalMessage; final void Function(String channelId, String eventId) _removeLocalMessage; final bool Function()? _isDeliveryValid; + final bool Function(String channelId, bool reply)? _canSend; SendMessage({ required SignedEventRelay signedEventRelay, @@ -36,6 +39,7 @@ class SendMessage { completeLocalMessage, required void Function(String channelId, String eventId) removeLocalMessage, bool Function()? isDeliveryValid, + bool Function(String channelId, bool reply)? canSend, }) : _signedEventRelay = signedEventRelay, _fetchMembers = fetchMembers, _readUserCache = readUserCache, @@ -44,7 +48,8 @@ class SendMessage { markLocalMessageForAnimation ?? ((_, _) {}), _completeLocalMessage = completeLocalMessage, _removeLocalMessage = removeLocalMessage, - _isDeliveryValid = isDeliveryValid; + _isDeliveryValid = isDeliveryValid, + _canSend = canSend; /// Send a text message to a channel. /// @@ -62,7 +67,14 @@ class SendMessage { Channel? channel, List> mediaTags = const [], }) async { - _ensureDeliveryValid(); + void ensureAllowed() { + _ensureDeliveryValid(); + if (_canSend?.call(channelId, parentEventId != null) == false) { + throw StateError('You do not have permission to send this message.'); + } + } + + ensureAllowed(); // Use explicitly passed pubkeys, or resolve @mentions against // channel members to avoid matching the wrong user. final explicitMentions = @@ -113,7 +125,7 @@ class SendMessage { if (!isReference(tag)) tag, ]; - _ensureDeliveryValid(); + ensureAllowed(); NostrEvent? localMessage; try { await _signedEventRelay.submit( @@ -121,6 +133,7 @@ class SendMessage { content: content, tags: tags, onSigned: (event) { + ensureAllowed(); localMessage = event; _markLocalMessageForAnimation(channelId, event.id); _addLocalMessage(channelId, event); @@ -272,6 +285,9 @@ SendMessage _sender(Ref ref, {bool personal = false}) { session: ref.read(relaySessionProvider.notifier), nsec: config.nsec, ), + canSend: (channelId, reply) => ref + .read(channelPermissionsProvider(channelId)) + .allows(reply ? ChannelAction.reply : ChannelAction.post), fetchMembers: (channelId) => ref.read(channelMembersProvider(channelId).future), readUserCache: () => ref.read(userCacheProvider), diff --git a/mobile/lib/features/channels/thread_detail_page.dart b/mobile/lib/features/channels/thread_detail_page.dart index ca704306366..6ed0e1e83c1 100644 --- a/mobile/lib/features/channels/thread_detail_page.dart +++ b/mobile/lib/features/channels/thread_detail_page.dart @@ -1,5 +1,8 @@ +import 'channel_permissions.dart'; import 'message_author_visibility.dart'; + import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; + import 'message_swipe_reply.dart'; import '../../shared/widgets/ios_scroll_to_top.dart'; import 'message_footer_layout.dart'; @@ -122,6 +125,9 @@ class ThreadDetailPage extends HookConsumerWidget { final canReply = isMember && !isArchived && + ref + .watch(channelPermissionsProvider(channelId)) + .allows(ChannelAction.reply) && ref.watch(channelStartsThreadsProvider(channelId)); final appView = View.of(context); final composerDockHeight = useState(0.0); diff --git a/mobile/lib/features/forum/forum_posts_view.dart b/mobile/lib/features/forum/forum_posts_view.dart index f05898bd989..415b258ba1b 100644 --- a/mobile/lib/features/forum/forum_posts_view.dart +++ b/mobile/lib/features/forum/forum_posts_view.dart @@ -1,3 +1,4 @@ +import '../channels/channel_permissions.dart'; import 'dart:async'; import 'package:flutter/material.dart'; @@ -63,7 +64,9 @@ class ForumPostsView extends HookConsumerWidget { return timer.cancel; }, [channel.id]); - final canPost = channel.isMember && !channel.isArchived; + final canPost = ref + .watch(channelPermissionsProvider(channel.id)) + .allows(ChannelAction.post); return Column( children: [ diff --git a/mobile/lib/features/forum/forum_thread_page.dart b/mobile/lib/features/forum/forum_thread_page.dart index 6d4755ddc90..90c23e20404 100644 --- a/mobile/lib/features/forum/forum_thread_page.dart +++ b/mobile/lib/features/forum/forum_thread_page.dart @@ -1,3 +1,4 @@ +import '../channels/channel_permissions.dart'; import 'dart:async'; import 'package:flutter/material.dart'; @@ -315,7 +316,11 @@ class _ThreadContent extends HookConsumerWidget { ), // Reply composer - if (isMember && !isArchived) + if (isMember && + !isArchived && + ref + .watch(channelPermissionsProvider(channelId)) + .allows(ChannelAction.post)) ComposeBar( channelId: channelId, hintText: 'Reply to this post\u2026', diff --git a/mobile/lib/shared/relay/nostr_models.dart b/mobile/lib/shared/relay/nostr_models.dart index 8e546903278..c3537ccf272 100644 --- a/mobile/lib/shared/relay/nostr_models.dart +++ b/mobile/lib/shared/relay/nostr_models.dart @@ -309,6 +309,8 @@ class ChannelData { /// the relay's `["join_role", ...]` tag. A missing tag (an older relay) /// means member; anything but a single `member` value fails closed to guest. final bool joinsAsGuest; + final bool guestReplies; + final bool guestReactions; const ChannelData({ required this.id, @@ -325,6 +327,8 @@ class ChannelData { this.isArchived = false, this.isUnlisted = false, this.joinsAsGuest = false, + this.guestReplies = false, + this.guestReactions = false, }); factory ChannelData.fromEvent(NostrEvent event) { @@ -371,6 +375,15 @@ class ChannelData { !(joinRoles.length == 1 && joinRoles.single.length == 2 && joinRoles.single[1] == 'member'); + bool grant(String name) { + final tags = event.tags + .where((t) => t.isNotEmpty && t[0] == name) + .toList(); + return tags.length == 1 && + tags.single.length == 2 && + tags.single[1] == 'true'; + } + return ChannelData( id: id, name: name, @@ -390,6 +403,8 @@ class ChannelData { isArchived: isArchived, isUnlisted: event.tags.any((t) => t.isNotEmpty && t[0] == 'unlisted'), joinsAsGuest: joinsAsGuest, + guestReplies: grant('guest_replies'), + guestReactions: grant('guest_reactions'), ); } } diff --git a/mobile/test/features/channels/channel_permissions_test.dart b/mobile/test/features/channels/channel_permissions_test.dart new file mode 100644 index 00000000000..98a4090fbbd --- /dev/null +++ b/mobile/test/features/channels/channel_permissions_test.dart @@ -0,0 +1,178 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:buzz/features/channels/channel_management_provider.dart'; +import 'package:buzz/features/channels/channels_provider.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_permissions.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Channel channel({ + bool replies = false, + bool reactions = false, + bool joined = true, + bool archived = false, +}) => Channel( + id: 'room', + name: 'Room', + channelType: 'stream', + visibility: 'open', + description: '', + createdBy: 'owner', + createdAt: DateTime.utc(2026), + memberCount: 2, + isMember: joined, + archivedAt: archived ? DateTime.utc(2026) : null, + guestReplies: replies, + guestReactions: reactions, +); + +void main() { + test( + 'live roster changes and grant revocation update effective permissions', + () { + var role = 'member'; + var room = channel(replies: true, reactions: true); + final container = ProviderContainer( + overrides: [ + myPubkeyProvider.overrideWithValue('viewer'), + channelByIdProvider('room').overrideWith((ref) => room), + latestChannelMembersProvider('room').overrideWith( + (ref) => [ + ChannelMember( + pubkey: 'viewer', + role: role, + joinedAt: DateTime.utc(2026), + ), + ], + ), + ], + ); + addTearDown(container.dispose); + final subscription = container.listen( + channelPermissionsProvider('room'), + (_, _) {}, + ); + addTearDown(subscription.close); + expect( + container + .read(channelPermissionsProvider('room')) + .allows(ChannelAction.post), + isTrue, + ); + role = 'guest'; + container.invalidate(latestChannelMembersProvider('room')); + expect( + container + .read(channelPermissionsProvider('room')) + .allows(ChannelAction.post), + isFalse, + ); + expect( + container + .read(channelPermissionsProvider('room')) + .allows(ChannelAction.reply), + isTrue, + ); + room = channel(); + container.invalidate(channelByIdProvider('room')); + expect( + container + .read(channelPermissionsProvider('room')) + .allows(ChannelAction.reply), + isFalse, + ); + expect( + container + .read(channelPermissionsProvider('room')) + .allows(ChannelAction.react), + isFalse, + ); + }, + ); + + test('viewer grants are independent and never grant root publishing', () { + for (final replies in [false, true]) { + for (final reactions in [false, true]) { + final room = channel(replies: replies, reactions: reactions); + final guest = ChannelPermissions(room, 'guest'); + expect(guest.allows(ChannelAction.post), isFalse); + expect(guest.allows(ChannelAction.reply), replies); + expect(guest.allows(ChannelAction.react), reactions); + expect(guest.allows(ChannelAction.removeReaction), isTrue); + for (final role in ['member', 'admin', 'owner', 'bot']) { + for (final action in ChannelAction.values) { + expect(ChannelPermissions(room, role).allows(action), isTrue); + } + } + for (final action in ChannelAction.values) { + expect(ChannelPermissions(room, null).allows(action), isFalse); + expect( + ChannelPermissions( + channel(replies: true, reactions: true, joined: false), + 'guest', + ).allows(action), + isFalse, + ); + expect( + ChannelPermissions( + channel(replies: true, reactions: true, archived: true), + 'guest', + ).allows(action), + isFalse, + ); + } + final restored = Channel.fromJson(room.toJson()); + expect(restored.guestReplies, replies); + expect(restored.copyWith(name: 'Updated').guestReactions, reactions); + expect( + restored.mergeDetails(ChannelDetails.fromChannel(room)).guestReplies, + replies, + ); + } + } + }); + + test('only exact, singular metadata flags grant contributions', () { + for (final name in ['guest_replies', 'guest_reactions']) { + for (final tags in >>[ + [], + [ + [name], + ], + [ + [name, 'false'], + ], + [ + [name, 'yes'], + ], + [ + [name, 'true', 'extra'], + ], + [ + [name, 'true'], + [name, 'true'], + ], + [ + [name, 'true'], + ], + ]) { + final metadata = NostrEvent( + id: 'metadata', + pubkey: 'relay', + createdAt: 1, + kind: 39000, + tags: tags, + content: '', + sig: '', + ); + final data = ChannelData.fromEvent(metadata); + expect( + name == 'guest_replies' ? data.guestReplies : data.guestReactions, + tags.length == 1 && + tags.single.length == 2 && + tags.single[1] == 'true', + ); + } + } + }); +} diff --git a/mobile/test/features/channels/send_message_provider_test.dart b/mobile/test/features/channels/send_message_provider_test.dart index 5766fab2551..b6dc417684f 100644 --- a/mobile/test/features/channels/send_message_provider_test.dart +++ b/mobile/test/features/channels/send_message_provider_test.dart @@ -9,6 +9,45 @@ import 'package:buzz/features/channels/send_message_provider.dart'; import 'package:buzz/shared/relay/relay.dart'; void main() { + test( + 'revoking permission during recipient lookup prevents signing and publication', + () async { + final session = _PendingPublishRelaySession(); + final members = Completer>(); + final peerKey = nostr.Keys.generate().public; + var allowed = true; + var localCount = 0; + final send = SendMessage( + signedEventRelay: SignedEventRelay( + session: session, + nsec: nostr.Keys.generate().nsec, + ), + fetchMembers: (_) => members.future, + readUserCache: () => const {}, + canSend: (_, _) => allowed, + addLocalMessage: (_, _) => localCount++, + completeLocalMessage: (_, _) {}, + removeLocalMessage: (_, _) {}, + ); + final pending = send( + channelId: _channelId, + content: 'Reply', + parentEventId: 'root', + mentionPubkeys: [peerKey], + ); + allowed = false; + members.complete([ + ChannelMember( + pubkey: peerKey, + role: 'member', + joinedAt: DateTime.utc(2026), + ), + ]); + await expectLater(pending, throwsStateError); + expect(localCount, 0); + }, + ); + test( 'adds the signed message locally before relay acknowledgement', () async { From 84abc741fdeea13adc38698b64df4370a34c6d22 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:01:39 -0800 Subject: [PATCH 03/10] test(channels): consolidate guest permission coverage Co-authored-by: Carl Signed-off-by: Taylor Ho --- .../guest_contributions_postgres_tests.rs | 623 +++++++----------- .../channels/channel_permissions_test.dart | 117 ++-- 2 files changed, 300 insertions(+), 440 deletions(-) diff --git a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs index b2ff954da70..c6f5b09f3da 100644 --- a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs @@ -1,26 +1,36 @@ -//! Critical permission journey through the shared HTTP/WebSocket ingestion seam. +//! Critical permission journey through shared ingestion with both auth inputs. use buzz_auth::Scope; use nostr::{Event, EventBuilder, Keys, Kind, Tag}; use uuid::Uuid; use super::group_state_postgres_tests::{ - community, create_channel, group_state_tags, http_auth, state, + community, create_channel, edit_channel, group_state_tags, http_auth, state, }; -use super::ingest::{ingest_event, IngestAuth}; +use super::ingest::{ingest_event, IngestAuth, IngestError, IngestResult}; -fn event(keys: &Keys, kind: u16, tags: &[Vec]) -> Event { - EventBuilder::new( - Kind::Custom(kind), - if kind == 9 { "Conversation" } else { "" }, - ) - .tags( - tags.iter() - .cloned() - .chain([vec!["nonce".into(), Uuid::new_v4().to_string()]]) - .map(|tag| Tag::parse(tag).unwrap()), - ) - .sign_with_keys(keys) - .unwrap() +const POST_DENIED: &str = "only members can post in this channel"; +const REACT_DENIED: &str = "reaction target event not found"; + +fn event(keys: &Keys, kind: u16, content: &str, tags: &[&[&str]]) -> Event { + let nonce = Uuid::new_v4().to_string(); + EventBuilder::new(Kind::from(kind), content) + .tags( + tags.iter() + .copied() + .chain([["nonce", nonce.as_str()].as_slice()]) + .map(|tag| Tag::parse(tag.iter().copied()).unwrap()), + ) + .sign_with_keys(keys) + .unwrap() +} + +fn check(result: Result, denial: Option<&str>, case: &str) { + match (result, denial) { + (Ok(result), None) => assert!(result.accepted, "{case}: {}", result.message), + (Err(IngestError::Rejected(reason)), Some(expected)) if reason.contains(expected) => {} + (Ok(result), expected) => panic!("{case}: expected {expected:?}, got {}", result.message), + (Err(error), expected) => panic!("{case}: expected {expected:?}, got {error:?}"), + } } #[tokio::test] @@ -31,37 +41,20 @@ async fn guests_contribute_only_through_explicit_reply_and_reaction_grants() { let owner = Keys::generate(); let guest = Keys::generate(); let channel = create_channel(&state, &tenant, &owner, &[]).await; - let h = vec!["h".into(), channel.to_string()]; - let previous_root = event(&guest, 9, std::slice::from_ref(&h)); - assert!( - ingest_event(&state, &tenant, previous_root.clone(), http_auth(&guest)) - .await - .unwrap() - .accepted - ); - let other_channel = create_channel(&state, &tenant, &owner, &[]).await; - let other_root = event(&owner, 9, &[vec!["h".into(), other_channel.to_string()]]); - assert!( - ingest_event(&state, &tenant, other_root.clone(), http_auth(&owner)) - .await - .unwrap() - .accepted - ); - let add = event( - &owner, - 9000, - &[ - h.clone(), - vec!["p".into(), guest.public_key().to_hex()], - vec!["role".into(), "guest".into()], - ], - ); - assert!( - ingest_event(&state, &tenant, add, http_auth(&owner)) - .await - .unwrap() - .accepted + let channel_id = channel.to_string(); + let h = ["h", channel_id.as_str()]; + let guest_key = guest.public_key().to_hex(); + let submit = async |event, auth| ingest_event(&state, &tenant, event, auth).await; + let post = |keys| event(keys, 9, "Conversation", &[&h]); + + let old_root = post(&guest); + check( + submit(old_root.clone(), http_auth(&guest)).await, + None, + "root published before becoming a Guest", ); + let add = event(&owner, 9000, "", &[&h, &["p", &guest_key, "guest"]]); + check(submit(add, http_auth(&owner)).await, None, "add Guest"); assert_eq!( state .db @@ -71,366 +64,246 @@ async fn guests_contribute_only_through_explicit_reply_and_reaction_grants() { .as_deref(), Some("guest") ); + + let root = post(&owner); + let root_id = root.id.to_hex(); + check(submit(root, http_auth(&owner)).await, None, "owner root"); + let reply_tag = ["e", root_id.as_str(), "", "reply"]; + let target_tag = ["e", root_id.as_str()]; + + // Start with the actual channel defaults, then exercise each opt-in combination. let initial = state .db .get_channel(tenant.community(), channel) .await .unwrap(); assert!(!initial.guest_replies && !initial.guest_reactions); - let root = event(&owner, 9, std::slice::from_ref(&h)); - assert!( - ingest_event(&state, &tenant, root.clone(), http_auth(&owner)) - .await - .unwrap() - .accepted - ); - let reply_tags = vec![ - h.clone(), - vec!["e".into(), root.id.to_hex(), "".into(), "reply".into()], - ]; for (replies, reactions) in [(false, false), (true, false), (false, true), (true, true)] { - let settings = event( - &owner, - 9002, - &[ - h.clone(), - vec!["guest_replies".into(), replies.to_string()], - vec!["guest_reactions".into(), reactions.to_string()], - ], - ); - assert!( - ingest_event(&state, &tenant, settings, http_auth(&owner)) - .await - .unwrap() - .accepted - ); + let reply_grant = ["guest_replies", if replies { "true" } else { "false" }]; + let react_grant = ["guest_reactions", if reactions { "true" } else { "false" }]; + if replies || reactions { + edit_channel( + &state, + &tenant, + &owner, + channel, + &[&reply_grant, &react_grant], + ) + .await + .unwrap(); + } let tags = group_state_tags(&state, &tenant, channel, 39000).await; - assert!(tags.contains(&vec!["guest_replies".into(), replies.to_string()])); - assert!(tags.contains(&vec!["guest_reactions".into(), reactions.to_string()])); - for websocket in [false, true] { - let auth = || { - if websocket { - IngestAuth::Nip42 { - pubkey: guest.public_key(), - scopes: vec![ - Scope::MessagesWrite, - Scope::ChannelsWrite, - Scope::AdminChannels, - ], - channel_ids: None, - conn_id: Uuid::new_v4(), - } - } else { - http_auth(&guest) - } - }; - let reply = event(&guest, 9, &reply_tags); - let outcome = ingest_event(&state, &tenant, reply.clone(), auth()).await; - assert_eq!( - outcome.is_ok_and(|r| r.accepted), - replies, - "reply {replies}/{reactions}/{websocket}" + for grant in [reply_grant, react_grant] { + assert!( + tags.iter() + .any(|tag| tag.iter().map(String::as_str).eq(grant)), + "missing {grant:?}" ); - if replies { - let nested = event( - &guest, - 9, - &[ - h.clone(), - vec!["e".into(), root.id.to_hex(), "".into(), "root".into()], - vec!["e".into(), reply.id.to_hex(), "".into(), "reply".into()], - ], - ); - assert!( - ingest_event(&state, &tenant, nested, auth()) - .await - .unwrap() - .accepted - ); - let edit = event( - &guest, - 40003, - &[h.clone(), vec!["e".into(), reply.id.to_hex()]], - ); - assert!( - ingest_event(&state, &tenant, edit, auth()) - .await - .unwrap() - .accepted - ); - } - if replies { - let deletion = event(&guest, 5, &[h.clone(), vec!["e".into(), reply.id.to_hex()]]); - assert!( - ingest_event(&state, &tenant, deletion, auth()) - .await - .unwrap() - .accepted - ); - } - let mut reaction_tags = vec![ - Tag::parse(["e", &root.id.to_hex()]).unwrap(), - Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), - ]; - if websocket { - reaction_tags.push(Tag::parse(h.clone()).unwrap()); - } - let reaction = EventBuilder::new(Kind::Reaction, "๐Ÿ‘") - .tags(reaction_tags) - .sign_with_keys(&guest) - .unwrap(); - let outcome = ingest_event(&state, &tenant, reaction.clone(), auth()).await; - assert_eq!( - outcome.is_ok_and(|r| r.accepted), - reactions, - "reaction {replies}/{reactions}/{websocket}" - ); - for forbidden in [ - event( - &guest, - 40003, - &[h.clone(), vec!["e".into(), previous_root.id.to_hex()]], - ), - event( - &guest, - 5, - &[h.clone(), vec!["e".into(), previous_root.id.to_hex()]], - ), - event( - &guest, - 9, - &[ - h.clone(), - vec![ - "e".into(), - other_root.id.to_hex(), - "".into(), - "reply".into(), - ], - ], - ), - event(&guest, 9, std::slice::from_ref(&h)), - event( - &guest, - 9, - &[ - h.clone(), - vec!["e".into(), root.id.to_hex(), "".into(), "root".into()], - ], - ), - event( - &guest, - 9, - &[ - reply_tags[0].clone(), - reply_tags[1].clone(), - vec!["broadcast".into(), "1".into()], - ], - ), - event( - &guest, - 9, - &[ - h.clone(), - vec!["e".into(), "f".repeat(64), "".into(), "reply".into()], - ], - ), - event( - &guest, - 9002, - &[h.clone(), vec!["guest_replies".into(), "true".into()]], - ), - event(&guest, 40100, std::slice::from_ref(&h)), - ] { - assert!(ingest_event(&state, &tenant, forbidden, auth()) - .await - .is_err()); - } - if reactions { - let fake_thread = event( - &guest, - 9, - &[ - h.clone(), - vec!["e".into(), reaction.id.to_hex(), "".into(), "reply".into()], - ], - ); - assert!(ingest_event(&state, &tenant, fake_thread, auth()) - .await - .is_err()); - let removal = event( - &guest, - 5, - &[ - vec!["e".into(), reaction.id.to_hex()], - vec!["k".into(), "7".into()], - ], - ); - assert!( - ingest_event(&state, &tenant, removal, auth()) - .await - .unwrap() - .accepted - ); - } } - } - // Managing one's persisted reply still works after its parent was deleted. - let orphan = event(&guest, 9, &reply_tags); - assert!( - ingest_event(&state, &tenant, orphan.clone(), http_auth(&guest)) - .await - .unwrap() - .accepted - ); - let delete_root = event(&owner, 5, &[h.clone(), vec!["e".into(), root.id.to_hex()]]); - assert!( - ingest_event(&state, &tenant, delete_root, http_auth(&owner)) - .await - .unwrap() - .accepted - ); - for kind in [40003, 5] { - let operation = event( - &guest, - kind, - &[h.clone(), vec!["e".into(), orphan.id.to_hex()]], + check( + submit( + event(&guest, 9, "Reply", &[&h, &reply_tag]), + http_auth(&guest), + ) + .await, + (!replies).then_some(POST_DENIED), + &format!("reply with grants {replies}/{reactions}"), ); - assert!( - ingest_event(&state, &tenant, operation, http_auth(&guest)) - .await - .unwrap() - .accepted + check( + submit(event(&guest, 7, "๐Ÿ‘", &[&target_tag]), http_auth(&guest)).await, + (!reactions).then_some(REACT_DENIED), + &format!("reaction with grants {replies}/{reactions}"), ); } - // An unrelated edit preserves the grants; malformed and duplicate grants fail. - let rename = event( - &owner, - 9002, - &[h.clone(), vec!["about".into(), "Updated".into()]], + + let websocket = || IngestAuth::Nip42 { + pubkey: guest.public_key(), + scopes: vec![Scope::MessagesWrite], + channel_ids: None, + conn_id: Uuid::new_v4(), + }; + let parent = event(&guest, 9, "Reply", &[&h, &reply_tag]); + let parent_id = parent.id.to_hex(); + check(submit(parent, websocket()).await, None, "NIP-42 reply"); + check( + submit(post(&guest), websocket()).await, + Some(POST_DENIED), + "NIP-42 root", ); - assert!( - ingest_event(&state, &tenant, rename, http_auth(&owner)) - .await - .unwrap() - .accepted + let reaction = event(&guest, 7, "+", &[&h, &target_tag]); + let reaction_id = reaction.id.to_hex(); + check( + submit(reaction, websocket()).await, + None, + "NIP-42 reaction with h", ); - assert!( - state - .db - .get_channel(tenant.community(), channel) - .await - .unwrap() - .guest_replies + + let other_channel = create_channel(&state, &tenant, &owner, &[]).await; + let other_root = event( + &owner, + 9, + "Other channel", + &[&["h", &other_channel.to_string()]], ); - for values in [vec!["yes"], vec!["true", "false"]] { - let mut tags = vec![h.clone()]; - tags.extend( - values - .into_iter() - .map(|v| vec!["guest_replies".into(), v.into()]), - ); - assert!(ingest_event( - &state, - &tenant, - event(&owner, 9002, &tags), - http_auth(&owner) - ) - .await - .is_err()); - } -} + let other_id = other_root.id.to_hex(); + check( + submit(other_root, http_auth(&owner)).await, + None, + "other channel root", + ); + let old_root_id = old_root.id.to_hex(); + let missing_id = "f".repeat(64); -#[tokio::test] -#[ignore = "requires Postgres"] -async fn revoking_guest_grants_blocks_additions_but_preserves_own_reaction_removal() { - let state = state().await; - let tenant = community(&state, "guest-revocation").await; - let owner = Keys::generate(); - let guest = Keys::generate(); - let channel = create_channel(&state, &tenant, &owner, &[]).await; - let h = vec!["h".into(), channel.to_string()]; - for command in [ - event( - &owner, - 9000, - &[ - h.clone(), - vec!["p".into(), guest.public_key().to_hex(), "guest".into()], - ], + // With both grants on, each denial must reach the boundary it exercises. + for (case, kind, tags, denial) in [ + ("root", 9, vec![h.as_slice()], POST_DENIED), + ( + "lone root marker", + 9, + vec![&h, &["e", &root_id, "", "root"]], + POST_DENIED, + ), + ( + "broadcast reply", + 9, + vec![&h, &reply_tag, &["broadcast", "1"]], + POST_DENIED, + ), + ( + "missing parent", + 9, + vec![&h, &["e", &missing_id, "", "reply"]], + "reply parent not found", + ), + ( + "cross-channel parent", + 9, + vec![&h, &["e", &other_id, "", "reply"]], + "reply parent not found", + ), + ( + "reaction as parent", + 9, + vec![&h, &["e", &reaction_id, "", "reply"]], + POST_DENIED, ), - event( - &owner, + ( + "old root edit", + 40003, + vec![&h, &["e", &old_root_id]], + "edit target not found or not editable", + ), + ( + "old root deletion", + 5, + vec![&h, &["e", &old_root_id]], + "deletion target not found or not deletable", + ), + ( + "privileged metadata", 9002, - &[ - h.clone(), - vec!["guest_replies".into(), "true".into()], - vec!["guest_reactions".into(), "true".into()], - ], + vec![&h, &["guest_replies", "false"]], + "actor not authorized", ), + ("canvas write", 40100, vec![h.as_slice()], POST_DENIED), ] { - assert!( - ingest_event(&state, &tenant, command, http_auth(&owner)) - .await - .unwrap() - .accepted + let content = if kind == 9 { "Conversation" } else { "" }; + check( + submit(event(&guest, kind, content, &tags), http_auth(&guest)).await, + Some(denial), + case, ); } - let root = event(&owner, 9, std::slice::from_ref(&h)); - assert!( - ingest_event(&state, &tenant, root.clone(), http_auth(&owner)) - .await - .unwrap() - .accepted - ); - let reaction = EventBuilder::new(Kind::Reaction, "+") - .tags([Tag::parse(["e", &root.id.to_hex()]).unwrap()]) - .sign_with_keys(&guest) - .unwrap(); - assert!( - ingest_event(&state, &tenant, reaction.clone(), http_auth(&guest)) - .await - .unwrap() - .accepted - ); - let revoke = event( - &owner, - 9002, - &[ - h.clone(), - vec!["guest_replies".into(), "false".into()], - vec!["guest_reactions".into(), "false".into()], - ], - ); - assert!( - ingest_event(&state, &tenant, revoke, http_auth(&owner)) - .await - .unwrap() - .accepted - ); - let reply = event( + + let nested = event( &guest, 9, + "Nested reply", &[ - h.clone(), - vec!["e".into(), root.id.to_hex(), "".into(), "reply".into()], + &h, + &["e", &root_id, "", "root"], + &["e", &parent_id, "", "reply"], ], ); - assert!(ingest_event(&state, &tenant, reply, http_auth(&guest)) + let nested_id = nested.id.to_hex(); + check( + submit(nested, http_auth(&guest)).await, + None, + "nested reply", + ); + let delete_parent = event(&guest, 5, "", &[&h, &["e", &parent_id]]); + check( + submit(delete_parent, http_auth(&guest)).await, + None, + "delete own reply", + ); + assert!(state + .db + .get_event_by_id_for_event_write(tenant.community(), &hex::decode(&parent_id).unwrap()) + .await + .unwrap() + .is_none()); + for kind in [40003, 5] { + let operation = event(&guest, kind, "", &[&h, &["e", &nested_id]]); + check( + submit(operation, http_auth(&guest)).await, + None, + "manage own reply after parent deletion", + ); + } + + edit_channel(&state, &tenant, &owner, channel, &[&["about", "Updated"]]) .await - .is_err()); - let addition = EventBuilder::new(Kind::Reaction, "๐Ÿ‘") - .tags([Tag::parse(["e", &root.id.to_hex()]).unwrap()]) - .sign_with_keys(&guest) .unwrap(); - assert!(ingest_event(&state, &tenant, addition, http_auth(&guest)) + let settings = state + .db + .get_channel(tenant.community(), channel) .await - .is_err()); - let removal = event(&guest, 5, &[vec!["e".into(), reaction.id.to_hex()]]); - assert!( - ingest_event(&state, &tenant, removal, http_auth(&guest)) + .unwrap(); + assert!(settings.guest_replies && settings.guest_reactions); + for grants in [ + vec![["guest_replies", "yes"].as_slice()], + vec![ + ["guest_replies", "true"].as_slice(), + &["guest_replies", "false"], + ], + ] { + let error = edit_channel(&state, &tenant, &owner, channel, &grants) .await - .unwrap() - .accepted + .unwrap_err(); + assert!( + error.contains("guest_replies must be one true/false tag"), + "{error}" + ); + } + + edit_channel( + &state, + &tenant, + &owner, + channel, + &[&["guest_replies", "false"], &["guest_reactions", "false"]], + ) + .await + .unwrap(); + check( + submit( + event(&guest, 9, "Reply after revocation", &[&h, &reply_tag]), + http_auth(&guest), + ) + .await, + Some(POST_DENIED), + "revoked reply", + ); + check( + submit(event(&guest, 7, "๐Ÿ‘€", &[&target_tag]), http_auth(&guest)).await, + Some(REACT_DENIED), + "revoked reaction", + ); + let removal = event(&guest, 5, "", &[&["e", &reaction_id], &["k", "7"]]); + check( + submit(removal, http_auth(&guest)).await, + None, + "remove own reaction after revocation", ); } diff --git a/mobile/test/features/channels/channel_permissions_test.dart b/mobile/test/features/channels/channel_permissions_test.dart index 98a4090fbbd..bd9ae38546c 100644 --- a/mobile/test/features/channels/channel_permissions_test.dart +++ b/mobile/test/features/channels/channel_permissions_test.dart @@ -48,86 +48,73 @@ void main() { ], ); addTearDown(container.dispose); - final subscription = container.listen( - channelPermissionsProvider('room'), - (_, _) {}, - ); + final provider = channelPermissionsProvider('room'); + final subscription = container.listen(provider, (_, _) {}); addTearDown(subscription.close); - expect( - container - .read(channelPermissionsProvider('room')) - .allows(ChannelAction.post), - isTrue, - ); + bool allows(ChannelAction action) => + container.read(provider).allows(action); + + expect(allows(ChannelAction.post), isTrue); role = 'guest'; container.invalidate(latestChannelMembersProvider('room')); - expect( - container - .read(channelPermissionsProvider('room')) - .allows(ChannelAction.post), - isFalse, - ); - expect( - container - .read(channelPermissionsProvider('room')) - .allows(ChannelAction.reply), - isTrue, - ); + expect(allows(ChannelAction.post), isFalse); + expect(allows(ChannelAction.reply), isTrue); + expect(allows(ChannelAction.react), isTrue); + room = channel(); container.invalidate(channelByIdProvider('room')); - expect( - container - .read(channelPermissionsProvider('room')) - .allows(ChannelAction.reply), - isFalse, - ); - expect( - container - .read(channelPermissionsProvider('room')) - .allows(ChannelAction.react), - isFalse, - ); + expect(allows(ChannelAction.reply), isFalse); + expect(allows(ChannelAction.react), isFalse); }, ); test('viewer grants are independent and never grant root publishing', () { for (final replies in [false, true]) { for (final reactions in [false, true]) { - final room = channel(replies: replies, reactions: reactions); - final guest = ChannelPermissions(room, 'guest'); + final guest = ChannelPermissions( + channel(replies: replies, reactions: reactions), + 'guest', + ); expect(guest.allows(ChannelAction.post), isFalse); expect(guest.allows(ChannelAction.reply), replies); expect(guest.allows(ChannelAction.react), reactions); expect(guest.allows(ChannelAction.removeReaction), isTrue); - for (final role in ['member', 'admin', 'owner', 'bot']) { - for (final action in ChannelAction.values) { - expect(ChannelPermissions(room, role).allows(action), isTrue); - } - } - for (final action in ChannelAction.values) { - expect(ChannelPermissions(room, null).allows(action), isFalse); - expect( - ChannelPermissions( - channel(replies: true, reactions: true, joined: false), - 'guest', - ).allows(action), - isFalse, - ); - expect( - ChannelPermissions( - channel(replies: true, reactions: true, archived: true), - 'guest', - ).allows(action), - isFalse, - ); - } - final restored = Channel.fromJson(room.toJson()); - expect(restored.guestReplies, replies); - expect(restored.copyWith(name: 'Updated').guestReactions, reactions); - expect( - restored.mergeDetails(ChannelDetails.fromChannel(room)).guestReplies, - replies, - ); + } + } + + final room = channel(); + for (final role in ['member', 'admin', 'owner', 'bot']) { + expect( + ChannelAction.values.every(ChannelPermissions(room, role).allows), + isTrue, + ); + } + for (final permissions in [ + ChannelPermissions(room, null), + ChannelPermissions( + channel(replies: true, reactions: true, joined: false), + 'guest', + ), + ChannelPermissions( + channel(replies: true, reactions: true, archived: true), + 'guest', + ), + ]) { + expect(ChannelAction.values.any(permissions.allows), isFalse); + } + }); + + test('channel snapshots and updates preserve independent grants', () { + for (final replies in [false, true]) { + final original = channel(replies: replies, reactions: !replies); + final restored = Channel.fromJson(original.toJson()); + for (final room in [ + restored, + restored.copyWith(name: 'Updated'), + channel().mergeDetails(ChannelDetails.fromChannel(original)), + ]) { + expect(room.guestReplies, replies); + expect(room.guestReactions, !replies); } } }); From 484f7a9f3f8fb18444801925dc5785f207af7c8d Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:38:20 -0800 Subject: [PATCH 04/10] fix(db): assign the next migration number to viewer grants Co-authored-by: Carl Signed-off-by: Taylor Ho --- crates/buzz-db/src/runtime/migration.rs | 2 +- ...t_contributions.sql => 0095_channel_guest_contributions.sql} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename migrations/{0094_channel_guest_contributions.sql => 0095_channel_guest_contributions.sql} (100%) diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index ae2fab29bc2..8d9dc311774 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -890,7 +890,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 94); + assert_eq!(migrations.len(), 95); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql diff --git a/migrations/0094_channel_guest_contributions.sql b/migrations/0095_channel_guest_contributions.sql similarity index 100% rename from migrations/0094_channel_guest_contributions.sql rename to migrations/0095_channel_guest_contributions.sql From c0395d5522a121b1adb1e41856137ab33b199497 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:40:12 -0800 Subject: [PATCH 05/10] fix(mobile): recheck permissions when picking a reaction Co-authored-by: Carl Signed-off-by: Taylor Ho --- .../features/channels/message_actions.dart | 1 + .../message_actions/quick_reaction_row.dart | 15 ++++- .../channels/message_actions_test.dart | 60 +++++++++++++++++-- 3 files changed, 71 insertions(+), 5 deletions(-) diff --git a/mobile/lib/features/channels/message_actions.dart b/mobile/lib/features/channels/message_actions.dart index b144f468382..ce078facff9 100644 --- a/mobile/lib/features/channels/message_actions.dart +++ b/mobile/lib/features/channels/message_actions.dart @@ -132,6 +132,7 @@ Future showMessageActions({ if (permissions.allows(ChannelAction.react)) _QuickReactionRow( message: message, + channelId: channelId, reactions: reactions ?? message.reactions, onToggleReaction: onToggleReaction, sheetContext: sheetContext, diff --git a/mobile/lib/features/channels/message_actions/quick_reaction_row.dart b/mobile/lib/features/channels/message_actions/quick_reaction_row.dart index 0a73d8f23ce..665e0322a3f 100644 --- a/mobile/lib/features/channels/message_actions/quick_reaction_row.dart +++ b/mobile/lib/features/channels/message_actions/quick_reaction_row.dart @@ -2,6 +2,7 @@ part of '../message_actions.dart'; class _QuickReactionRow extends ConsumerWidget { final TimelineMessage message; + final String channelId; final List reactions; final ValueChanged? onToggleReaction; @@ -18,6 +19,7 @@ class _QuickReactionRow extends ConsumerWidget { const _QuickReactionRow({ required this.message, + required this.channelId, required this.reactions, this.onToggleReaction, required this.sheetContext, @@ -40,7 +42,18 @@ class _QuickReactionRow extends ConsumerWidget { }; void react(String value) { - if (reactions.any((r) => r.emoji == value && r.reactedByCurrentUser)) { + final removing = reactions.any( + (reaction) => reaction.emoji == value && reaction.reactedByCurrentUser, + ); + if (!pageContext.mounted || + !pageRef + .read(channelPermissionsProvider(channelId)) + .allows( + removing ? ChannelAction.removeReaction : ChannelAction.react, + )) { + return; + } + if (removing) { if (onToggleReaction != null) { onToggleReaction!(value); } else { diff --git a/mobile/test/features/channels/message_actions_test.dart b/mobile/test/features/channels/message_actions_test.dart index af1b4e11051..a21ef391c0f 100644 --- a/mobile/test/features/channels/message_actions_test.dart +++ b/mobile/test/features/channels/message_actions_test.dart @@ -8,6 +8,7 @@ import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/features/channels/channels_provider.dart'; import 'package:buzz/features/channels/message_actions.dart'; import 'package:buzz/features/channels/message_long_press_region.dart'; +import 'package:buzz/shared/emoji/emoji_picker.dart'; import 'package:buzz/shared/read_state/read_state_provider.dart'; import 'package:buzz/features/channels/thread_follows/thread_follows_provider.dart'; import 'package:buzz/features/channels/timeline_message.dart'; @@ -65,7 +66,7 @@ class _RecordingReactionActions implements ChannelActions { dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } -final _listedChannel = Channel( +Channel _testChannel({bool guestReactions = false}) => Channel( id: _channelId, name: 'general', channelType: 'stream', @@ -75,8 +76,15 @@ final _listedChannel = Channel( createdAt: DateTime(2026), memberCount: 2, isMember: true, + guestReactions: guestReactions, ); +final _listedChannel = _testChannel(); + +List _viewerRoster(String role) => [ + ChannelMember(pubkey: 'self', role: role, joinedAt: DateTime.utc(2026)), +]; + class _ListedChannelsNotifier extends ChannelsNotifier { @override Future> build() async => [_listedChannel]; @@ -172,6 +180,11 @@ Future _pumpSheet( overrides: [ savedPrefsProvider.overrideWithValue(prefs), myPubkeyProvider.overrideWithValue('self'), + if (!listChannel) + channelByIdProvider(_channelId).overrideWithValue(_listedChannel), + latestChannelMembersProvider( + _channelId, + ).overrideWithValue(_viewerRoster('member')), readStateProvider.overrideWith( readStateOverride ?? () => _FakeReadStateNotifier( @@ -293,6 +306,8 @@ Future<_MessageActionsPopoverHarness> _pumpMessageActionsPopover( bool composerInitiallyFocused = false, bool launcherOnNestedRoute = false, ChannelActions Function(Ref ref)? createChannelActions, + Channel Function()? channelSnapshot, + String viewerRole = 'member', Rect anchorRect = const Rect.fromLTWH(32, 260, 300, 72), String? currentPubkey = 'self', bool listChannel = false, @@ -342,6 +357,13 @@ Future<_MessageActionsPopoverHarness> _pumpMessageActionsPopover( overrides: [ savedPrefsProvider.overrideWithValue(prefs), myPubkeyProvider.overrideWithValue('self'), + if (!listChannel) + channelByIdProvider( + _channelId, + ).overrideWith((ref) => channelSnapshot?.call() ?? _listedChannel), + latestChannelMembersProvider( + _channelId, + ).overrideWithValue(_viewerRoster(viewerRole)), readStateProvider.overrideWith( readStateOverride ?? () => _FakeReadStateNotifier( @@ -405,13 +427,17 @@ Future<_MessageActionsPopoverHarness> _pumpMessageActionsPopover( void main() { testWidgets( - 'quick reactions show selection, label controls, and remove our reaction', + 'open reaction picker respects revocation and still removes our reaction', (tester) async { final semantics = tester.ensureSemantics(); final actions = _RecordingReactionActions(); - await _pumpMessageActionsPopover( + var channel = _testChannel(guestReactions: true); + final harness = await _pumpMessageActionsPopover( tester, message: _message( + tags: const [ + ['h', _channelId], + ], reactions: [ const TimelineReaction( emoji: '๐Ÿ‘', @@ -424,6 +450,8 @@ void main() { ), prefs: await _mockPrefs(), createChannelActions: (_) => actions, + channelSnapshot: () => channel, + viewerRole: 'guest', ); final emoji = find.byKey(const ValueKey('quick-reaction-๐Ÿ‘')); final owner = tester.widget( @@ -434,8 +462,32 @@ void main() { expect(owner.properties.label, isNotEmpty); expect(owner.properties.onTap, isNotNull); expect(find.bySemanticsLabel('Add reaction'), findsOneWidget); - await tester.tap(emoji); + + void setReactionGrant(bool allowed) { + channel = _testChannel(guestReactions: allowed); + harness.container.invalidate(channelByIdProvider(_channelId)); + } + + Future selectAfterRevocation(String emoji) async { + await tester.tap(find.byKey(const ValueKey('quick-reaction-more'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + final picker = find.byType(EmojiPickerSheet); + expect(picker, findsOneWidget); + setReactionGrant(false); + await tester.pump(); + tester.widget(picker).onSelect(emoji); + await tester.pumpAndSettle(); + } + + await selectAfterRevocation('๐ŸŽ‰'); + expect(actions.added, isEmpty); + setReactionGrant(true); + await tester.tap( + find.byKey(const ValueKey('open-message-actions-popover')), + ); await tester.pumpAndSettle(); + await selectAfterRevocation('๐Ÿ‘'); expect(actions.removed, ['our-reaction']); expect(actions.added, isEmpty); semantics.dispose(); From 49676e262e4c6c6103c8cd423f7636dd266c9d48 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:40:49 -0800 Subject: [PATCH 06/10] test(relay): use distinct reactions in the grant matrix Co-authored-by: Carl Signed-off-by: Taylor Ho --- .../src/handlers/guest_contributions_postgres_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs index c6f5b09f3da..88572c38806 100644 --- a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs @@ -109,8 +109,10 @@ async fn guests_contribute_only_through_explicit_reply_and_reaction_grants() { (!replies).then_some(POST_DENIED), &format!("reply with grants {replies}/{reactions}"), ); + // The relay deduplicates emoji per author and target, even with fresh event IDs. + let emoji = if replies { "๐ŸŽ‰" } else { "๐Ÿ‘" }; check( - submit(event(&guest, 7, "๐Ÿ‘", &[&target_tag]), http_auth(&guest)).await, + submit(event(&guest, 7, emoji, &[&target_tag]), http_auth(&guest)).await, (!reactions).then_some(REACT_DENIED), &format!("reaction with grants {replies}/{reactions}"), ); @@ -130,7 +132,7 @@ async fn guests_contribute_only_through_explicit_reply_and_reaction_grants() { Some(POST_DENIED), "NIP-42 root", ); - let reaction = event(&guest, 7, "+", &[&h, &target_tag]); + let reaction = event(&guest, 7, "๐Ÿ”ฅ", &[&h, &target_tag]); let reaction_id = reaction.id.to_hex(); check( submit(reaction, websocket()).await, From c20eb02c058cadfadc899c401813577b2b37aa2d Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 11:50:03 -0800 Subject: [PATCH 07/10] fix(mobile): keep the composer available in newly opened chats Co-authored-by: Carl Signed-off-by: Taylor Ho --- .../channels/channel_detail_page.dart | 10 +++-- .../channels/send_message_provider.dart | 20 ++++++--- .../channels/channel_detail_page_test.dart | 8 ++++ .../channel_messages_journey_test.dart | 29 +++++++++++- .../channels/channel_send_journey_test.dart | 10 +++++ .../features/channels/reaction_row_test.dart | 44 ++++++++++++++++--- .../reaction_row_test/combined_tests.dart | 7 ++- .../reaction_row_test/shortcode_tests.dart | 4 +- .../channels/send_message_provider_test.dart | 2 +- .../features/forum/forum_widgets_test.dart | 10 +++++ 10 files changed, 122 insertions(+), 22 deletions(-) diff --git a/mobile/lib/features/channels/channel_detail_page.dart b/mobile/lib/features/channels/channel_detail_page.dart index 91bfe03bf90..44b60cfa0fa 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -318,11 +318,15 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { ], ); final memberProfilesPreloadState = useFuture(memberProfilesPreload); + final permissions = ref.watch( + channelPermissionsProvider(resolvedChannel.id), + ); final showsComposer = !resolvedChannel.isForum && - ref - .watch(channelPermissionsProvider(resolvedChannel.id)) - .allows(ChannelAction.post); + ChannelPermissions( + resolvedChannel, + permissions.role, + ).allows(ChannelAction.post); final profileOwnedAgentPubkeys = []; for (final participantPubkey in resolvedChannel.participantPubkeys) { final normalized = participantPubkey.trim().toLowerCase(); diff --git a/mobile/lib/features/channels/send_message_provider.dart b/mobile/lib/features/channels/send_message_provider.dart index 7b6ca6543a1..516407c0606 100644 --- a/mobile/lib/features/channels/send_message_provider.dart +++ b/mobile/lib/features/channels/send_message_provider.dart @@ -25,7 +25,7 @@ class SendMessage { final void Function(String channelId, String eventId) _completeLocalMessage; final void Function(String channelId, String eventId) _removeLocalMessage; final bool Function()? _isDeliveryValid; - final bool Function(String channelId, bool reply)? _canSend; + final bool Function(String channelId, bool reply, Channel? channel)? _canSend; SendMessage({ required SignedEventRelay signedEventRelay, @@ -39,7 +39,7 @@ class SendMessage { completeLocalMessage, required void Function(String channelId, String eventId) removeLocalMessage, bool Function()? isDeliveryValid, - bool Function(String channelId, bool reply)? canSend, + bool Function(String channelId, bool reply, Channel? channel)? canSend, }) : _signedEventRelay = signedEventRelay, _fetchMembers = fetchMembers, _readUserCache = readUserCache, @@ -69,7 +69,7 @@ class SendMessage { }) async { void ensureAllowed() { _ensureDeliveryValid(); - if (_canSend?.call(channelId, parentEventId != null) == false) { + if (_canSend?.call(channelId, parentEventId != null, channel) == false) { throw StateError('You do not have permission to send this message.'); } } @@ -285,9 +285,17 @@ SendMessage _sender(Ref ref, {bool personal = false}) { session: ref.read(relaySessionProvider.notifier), nsec: config.nsec, ), - canSend: (channelId, reply) => ref - .read(channelPermissionsProvider(channelId)) - .allows(reply ? ChannelAction.reply : ChannelAction.post), + canSend: (channelId, reply, channel) { + final permissions = ref.read(channelPermissionsProvider(channelId)); + // A newly opened DM can send before the channel list includes it. + final openedDm = channel?.id == channelId && channel?.isDm == true + ? channel + : null; + return ChannelPermissions( + permissions.channel ?? openedDm, + permissions.role, + ).allows(reply ? ChannelAction.reply : ChannelAction.post); + }, fetchMembers: (channelId) => ref.read(channelMembersProvider(channelId).future), readUserCache: () => ref.read(userCacheProvider), diff --git a/mobile/test/features/channels/channel_detail_page_test.dart b/mobile/test/features/channels/channel_detail_page_test.dart index 5de42bb7624..bb47eba0fa4 100644 --- a/mobile/test/features/channels/channel_detail_page_test.dart +++ b/mobile/test/features/channels/channel_detail_page_test.dart @@ -57,6 +57,7 @@ import 'package:scrollable_positioned_list/scrollable_positioned_list.dart'; import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channel_detail_page.dart'; import 'package:buzz/features/channels/channel_management_provider.dart'; +import 'package:buzz/features/channels/channel_permissions.dart'; import 'package:buzz/features/channels/channel_messages_provider.dart'; import 'package:buzz/features/channels/channel_window.dart'; import 'package:buzz/features/channels/channel_mutes/channel_mutes_provider.dart'; @@ -409,6 +410,13 @@ Widget _buildTestable({ presenceCacheProvider.overrideWith(() => presenceCache), if (!useRealChannelProviders) channelsProvider.overrideWith(() => fakeChannelsNotifier), + channelPermissionsProvider.overrideWith( + (ref, id) => ChannelPermissions( + ref.watch(channelByIdProvider(id)) ?? + (id == resolvedChannel.id ? resolvedChannel : null), + 'member', + ), + ), channelStarsProvider.overrideWith(_FakeChannelStarsNotifier.new), channelMutesProvider.overrideWith(_FakeChannelMutesNotifier.new), if (!useRealChannelProviders) diff --git a/mobile/test/features/channels/channel_messages_journey_test.dart b/mobile/test/features/channels/channel_messages_journey_test.dart index b0009c1c83a..5a0b3d8f15e 100644 --- a/mobile/test/features/channels/channel_messages_journey_test.dart +++ b/mobile/test/features/channels/channel_messages_journey_test.dart @@ -1,4 +1,7 @@ +import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/features/channels/channel_messages_provider.dart'; +import 'package:buzz/features/channels/channels_provider.dart'; import 'package:buzz/features/channels/channel_typing_provider.dart'; import 'package:buzz/features/channels/pending_local_messages_provider.dart'; import 'package:buzz/features/channels/send_message_provider.dart'; @@ -30,7 +33,31 @@ void main() { // The relay admits the live REQ only after its access checks. final admitted = relay.holdReq(); - final container = ProviderContainer(overrides: relay.overrides); + final container = ProviderContainer( + overrides: [ + ...relay.overrides, + channelByIdProvider(_channel).overrideWithValue( + Channel( + id: _channel, + name: 'general', + channelType: 'stream', + visibility: 'open', + description: '', + createdBy: relay.pubkey, + createdAt: DateTime.utc(2026), + memberCount: 1, + isMember: true, + ), + ), + latestChannelMembersProvider(_channel).overrideWithValue([ + ChannelMember( + pubkey: relay.pubkey, + role: 'member', + joinedAt: DateTime.utc(2026), + ), + ]), + ], + ); addTearDown(container.dispose); var messages = container.listen( channelMessagesProvider(_channel), diff --git a/mobile/test/features/channels/channel_send_journey_test.dart b/mobile/test/features/channels/channel_send_journey_test.dart index f2ea068b6be..4cb99c8b4db 100644 --- a/mobile/test/features/channels/channel_send_journey_test.dart +++ b/mobile/test/features/channels/channel_send_journey_test.dart @@ -1,5 +1,7 @@ import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channel_detail_page.dart'; +import 'package:buzz/features/channels/channel_management_provider.dart'; +import 'package:buzz/features/channels/channels_provider.dart'; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/theme/buzz_icons.dart'; import 'package:buzz/shared/theme/theme.dart'; @@ -47,6 +49,14 @@ void main() { ProviderScope( overrides: [ ...relay.overrides, + channelByIdProvider(_channelId).overrideWithValue(_channel), + latestChannelMembersProvider(_channelId).overrideWithValue([ + ChannelMember( + pubkey: relay.pubkey, + role: 'member', + joinedAt: DateTime.utc(2026), + ), + ]), savedPrefsProvider.overrideWithValue(prefs), appLifecycleProvider.overrideWith(_Resumed.new), ], diff --git a/mobile/test/features/channels/reaction_row_test.dart b/mobile/test/features/channels/reaction_row_test.dart index e6600976a09..b142ffef61c 100644 --- a/mobile/test/features/channels/reaction_row_test.dart +++ b/mobile/test/features/channels/reaction_row_test.dart @@ -1,3 +1,5 @@ +import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_permissions.dart'; import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/shared/custom_emoji/custom_emoji.dart'; import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart'; @@ -79,6 +81,32 @@ final _dataset = EmojiDataset( const _messageId = 'msg-1'; +final _channelPermission = channelPermissionsProvider('channel') + .overrideWithValue( + ChannelPermissions( + Channel( + id: 'channel', + name: 'general', + channelType: 'stream', + visibility: 'open', + description: '', + createdBy: _alice, + createdAt: DateTime.utc(2026), + memberCount: 1, + isMember: true, + ), + 'member', + ), + ); + +Widget _testableReactionRow({ + required Widget child, + List overrides = const [], +}) => WidgetHelpers.testable( + child: child, + overrides: [_channelPermission, ...overrides], +); + /// Pumps the row and hands back the enclosing container, so tests can arm a /// pending burst or inspect the particle controller. /// @@ -96,7 +124,7 @@ Future _pumpRow( VoidCallback? onMessageLongPress, }) async { await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), userCacheProvider.overrideWith( @@ -163,7 +191,7 @@ void main() { ]); addTearDown(reactions.dispose); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ userCacheProvider.overrideWith(() => _FakeUserCacheNotifier({})), ], @@ -192,7 +220,7 @@ void main() { tester, ) async { await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( child: Consumer( builder: (context, ref, _) => TextButton( onPressed: () => toggleReaction( @@ -310,7 +338,7 @@ void main() { ), ); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), userCacheProvider.overrideWith( @@ -497,7 +525,7 @@ void main() { ), ); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), relayConfigProvider.overrideWith( @@ -639,7 +667,7 @@ void main() { }, ); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), userCacheProvider.overrideWith(() => _FakeUserCacheNotifier({})), @@ -853,7 +881,7 @@ void main() { ), ); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), mediaHttpClientProvider.overrideWithValue( @@ -1158,6 +1186,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + _channelPermission, emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), userCacheProvider.overrideWith( () => _FakeUserCacheNotifier(const {}), @@ -1204,6 +1233,7 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ + _channelPermission, emojiDatasetOrEmptyProvider.overrideWithValue(_dataset), userCacheProvider.overrideWith( () => _FakeUserCacheNotifier(const {}), diff --git a/mobile/test/features/channels/reaction_row_test/combined_tests.dart b/mobile/test/features/channels/reaction_row_test/combined_tests.dart index fa13dae6b9d..d56a2c79f94 100644 --- a/mobile/test/features/channels/reaction_row_test/combined_tests.dart +++ b/mobile/test/features/channels/reaction_row_test/combined_tests.dart @@ -45,6 +45,9 @@ void combinedReactionTests() { pubkey: _alice, createdAt: 1, content: '', + tags: const [ + ['h', 'channel'], + ], reactions: [ TimelineReaction( emoji: _fire, @@ -56,7 +59,7 @@ void combinedReactionTests() { ], ); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [ channelActionsProvider.overrideWithValue(actions), userCacheProvider.overrideWith(() => _FakeUserCacheNotifier({})), @@ -114,7 +117,7 @@ void combinedReactionTests() { ); addTearDown(client.close); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: [mediaHttpClientProvider.overrideWithValue(client)], child: MediaQuery( data: MediaQueryData(textScaler: TextScaler.linear(scale)), diff --git a/mobile/test/features/channels/reaction_row_test/shortcode_tests.dart b/mobile/test/features/channels/reaction_row_test/shortcode_tests.dart index 95492aec78a..c3d62b5d597 100644 --- a/mobile/test/features/channels/reaction_row_test/shortcode_tests.dart +++ b/mobile/test/features/channels/reaction_row_test/shortcode_tests.dart @@ -46,7 +46,7 @@ void shortcodeReactionTests() { ); addTearDown(client.close); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: overrides(client), child: ReactionRow( messageId: _messageId, @@ -135,7 +135,7 @@ void shortcodeReactionTests() { final client = MockClient((_) async => http.Response('missing', 404)); addTearDown(client.close); await tester.pumpWidget( - WidgetHelpers.testable( + _testableReactionRow( overrides: overrides(client), child: ReactionRow( messageId: _messageId, diff --git a/mobile/test/features/channels/send_message_provider_test.dart b/mobile/test/features/channels/send_message_provider_test.dart index b6dc417684f..a71fa1fabbc 100644 --- a/mobile/test/features/channels/send_message_provider_test.dart +++ b/mobile/test/features/channels/send_message_provider_test.dart @@ -24,7 +24,7 @@ void main() { ), fetchMembers: (_) => members.future, readUserCache: () => const {}, - canSend: (_, _) => allowed, + canSend: (_, _, _) => allowed, addLocalMessage: (_, _) => localCount++, completeLocalMessage: (_, _) {}, removeLocalMessage: (_, _) {}, diff --git a/mobile/test/features/forum/forum_widgets_test.dart b/mobile/test/features/forum/forum_widgets_test.dart index 671e8d6f9a1..0ff392e2dd5 100644 --- a/mobile/test/features/forum/forum_widgets_test.dart +++ b/mobile/test/features/forum/forum_widgets_test.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_permissions.dart'; import 'package:buzz/features/forum/forum_models.dart'; import 'package:buzz/features/forum/forum_post_card.dart'; import 'package:buzz/features/forum/forum_posts_view.dart'; @@ -104,6 +105,9 @@ Widget _buildPostsView({ overrides: [ userCacheProvider.overrideWith(() => _FakeUserCacheNotifier(users)), profileProvider.overrideWith(() => _FakeProfileNotifier()), + channelPermissionsProvider( + ch.id, + ).overrideWithValue(ChannelPermissions(ch, 'member')), forumPostsProvider(ch.id).overrideWith((ref) async => postsResponse), relayClientProvider.overrideWithValue( RelayClient(baseUrl: 'http://localhost:3000'), @@ -145,6 +149,9 @@ Widget _buildThreadPage({ _channelId, ).overrideWith((ref) async => channelBotPubkeys), profileProvider.overrideWith(() => _FakeProfileNotifier()), + channelPermissionsProvider( + _channelId, + ).overrideWithValue(ChannelPermissions(_forumChannel, 'member')), forumThreadProvider(( channelId: _channelId, eventId: postEventId, @@ -208,6 +215,9 @@ Widget _buildLiveForum(_CountingForumSession session, Widget child) => retry: (_, _) => null, overrides: [ relaySessionProvider.overrideWith(() => session), + channelPermissionsProvider( + _channelId, + ).overrideWithValue(ChannelPermissions(_forumChannel, 'member')), userCacheProvider.overrideWith(() => _FakeUserCacheNotifier(const {})), knownAgentPubkeysProvider.overrideWithValue(const {}), profileProvider.overrideWith(() => _FakeProfileNotifier()), From 9ba2f6f6c157a3af2a3264eac975f1761a07cd91 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 12:38:42 -0800 Subject: [PATCH 08/10] refactor(mobile): move the channel metadata mapper Co-authored-by: Carl Signed-off-by: Taylor Ho --- .../features/channels/channel_directory.dart | 54 +++++++++++++++++++ .../features/channels/channels_provider.dart | 54 ------------------- 2 files changed, 54 insertions(+), 54 deletions(-) diff --git a/mobile/lib/features/channels/channel_directory.dart b/mobile/lib/features/channels/channel_directory.dart index 3bab05f1c22..5029fa48539 100644 --- a/mobile/lib/features/channels/channel_directory.dart +++ b/mobile/lib/features/channels/channel_directory.dart @@ -110,6 +110,60 @@ Future> _fetchChannelDirectoryMetas( since: since, ); +/// Build a [Channel] from a kind:39000 metadata event. +/// +/// [displayNames] maps lowercase participant pubkey โ†’ resolved label and is +/// used to populate [Channel.participants] for DMs so [Channel.displayLabel] +/// can render real names instead of the relay-canonical "DM" name. +Channel _channelFromMeta( + NostrEvent event, + ChannelData data, { + required bool isMember, + Map displayNames = const {}, +}) { + final participants = data.channelType == 'dm' + ? [ + for (final pk in data.participantPubkeys) + displayNames[pk.toLowerCase()] ?? shortPubkey(pk), + ] + : const []; + return Channel( + id: data.id, + name: data.name, + channelType: data.channelType, + labels: data.labels, + visibility: data.visibility, + description: data.description, + topic: data.topic, + createdBy: data.creator ?? event.pubkey, + createdAt: DateTime.fromMillisecondsSinceEpoch( + event.createdAt * 1000, + isUtc: true, + ), + memberCount: 0, + lastMessageAt: null, + // `archivedAt` doubles as both the archived-state flag and the timestamp. + // The kind:39000 metadata only carries `["archived", "true"]`, not the + // moment of archival, so we stamp the event's `createdAt` โ€” that's when + // the relay republished the metadata, which is the closest signal we have. + archivedAt: data.isArchived + ? DateTime.fromMillisecondsSinceEpoch( + event.createdAt * 1000, + isUtc: true, + ) + : null, + participants: participants, + participantPubkeys: data.participantPubkeys, + isMember: isMember, + ttlSeconds: data.ttlSeconds, + ttlDeadline: data.ttlDeadline, + isUnlisted: data.isUnlisted, + joinsAsGuest: data.joinsAsGuest, + guestReplies: data.guestReplies, + guestReactions: data.guestReactions, + ); +} + /// Thrown when a channel-list request is retired before it settles. /// /// Callers must treat this as "write nothing": a newer request or scope now diff --git a/mobile/lib/features/channels/channels_provider.dart b/mobile/lib/features/channels/channels_provider.dart index 06fa9d02244..2c07d7e849b 100644 --- a/mobile/lib/features/channels/channels_provider.dart +++ b/mobile/lib/features/channels/channels_provider.dart @@ -776,60 +776,6 @@ class ChannelsNotifier extends AsyncNotifier> { return events; } - /// Build a [Channel] from a kind:39000 metadata event. - /// - /// [displayNames] maps lowercase participant pubkey โ†’ resolved label and is - /// used to populate [Channel.participants] for DMs so [Channel.displayLabel] - /// can render real names instead of the relay-canonical "DM" name. - Channel _channelFromMeta( - NostrEvent event, - ChannelData data, { - required bool isMember, - Map displayNames = const {}, - }) { - final participants = data.channelType == 'dm' - ? [ - for (final pk in data.participantPubkeys) - displayNames[pk.toLowerCase()] ?? shortPubkey(pk), - ] - : const []; - return Channel( - id: data.id, - name: data.name, - channelType: data.channelType, - labels: data.labels, - visibility: data.visibility, - description: data.description, - topic: data.topic, - createdBy: data.creator ?? event.pubkey, - createdAt: DateTime.fromMillisecondsSinceEpoch( - event.createdAt * 1000, - isUtc: true, - ), - memberCount: 0, - lastMessageAt: null, - // `archivedAt` doubles as both the archived-state flag and the timestamp. - // The kind:39000 metadata only carries `["archived", "true"]`, not the - // moment of archival, so we stamp the event's `createdAt` โ€” that's when - // the relay republished the metadata, which is the closest signal we have. - archivedAt: data.isArchived - ? DateTime.fromMillisecondsSinceEpoch( - event.createdAt * 1000, - isUtc: true, - ) - : null, - participants: participants, - participantPubkeys: data.participantPubkeys, - isMember: isMember, - ttlSeconds: data.ttlSeconds, - ttlDeadline: data.ttlDeadline, - isUnlisted: data.isUnlisted, - joinsAsGuest: data.joinsAsGuest, - guestReplies: data.guestReplies, - guestReactions: data.guestReactions, - ); - } - void _publishUnreadCatchUp(Map recordedAtByChannel) { state = state.whenData( (channels) => [ From b8c5823d4bf6f9bf53e604de36b95119f7458753 Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Tue, 17 Nov 2026 14:04:40 -0800 Subject: [PATCH 09/10] feat(channels): create view-only streams with viewer grants Co-authored-by: Carl Signed-off-by: Taylor Ho --- NOSTR.md | 11 +- crates/buzz-db/src/store/channel.rs | 27 +++- .../store/event_hydration/postgres_tests.rs | 1 + .../store/unlisted_channels_postgres_tests.rs | 1 + .../guest_contributions_postgres_tests.rs | 74 +++++++++++ crates/buzz-relay/src/handlers/ingest.rs | 55 ++++++-- .../buzz-relay/src/handlers/side_effects.rs | 120 +++++------------- .../ios/Runner/NativeCreateChannelSheet.swift | 37 +++++- .../channels/channel_management_actions.dart | 16 ++- .../channels/channel_management_provider.dart | 9 ++ .../lib/features/channels/channels_page.dart | 4 + .../channels/channels_page/sheets.dart | 33 ++++- .../channels/ios_create_channel_sheet.dart | 7 +- .../channel_management_provider_test.dart | 50 ++++++++ .../features/channels/channels_page_test.dart | 35 +++++ .../ios_create_channel_sheet_test.dart | 11 +- 16 files changed, 376 insertions(+), 115 deletions(-) diff --git a/NOSTR.md b/NOSTR.md index dbd89fac17e..0db230ce7dd 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -50,7 +50,7 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **Reactions (kind:7)** | โœ… | Standard NIP-25; channel derived from target event's `#e` tag (client `#h` ignored) | | **Deletions (kind:5)** | โœ… | Standard NIP-09; self-authored only. `#h` optional, `#e` required | | **User profiles (kind:0)** | โœ… | NIP-01 metadata; synced to users table (display_name, avatar, about, NIP-05). NIP-05 handles must canonicalize to this relay's domain โ€” off-domain or invalid handles are silently cleared. If a NIP-05 handle collides with another user's (UNIQUE constraint), the handle is skipped but other profile fields (display_name, avatar, about) are still synced. | -| **Group creation (kind:9007)** | โœ… | NIP-29; include an `h` tag with the new channel id and a `name` tag, optional `visibility`, `channel_type`, label `t` and `unlisted` tags. The relay refuses a 9007 without `h`. It refuses a listed channel (open, not unlisted, stream or forum) whose name another listed channel already has, ignoring case and including archived ones: `invalid: an open channel named "" already exists`. | +| **Group creation (kind:9007)** | โœ… | NIP-29; include an `h` tag with the new channel id and a `name` tag, optional `visibility`, `channel_type`, label `t` and `unlisted` tags. A stream may start View only with `["visibility", "view-only"]` and optional Viewer grants. The relay refuses a 9007 without `h`. It refuses a listed channel (open, not unlisted, stream or forum) whose name another listed channel already has, ignoring case and including archived ones: `invalid: an open channel named "" already exists`. | | **Add user (kind:9000)** | โœ… | Open: any user, subject to target's `channel_add_policy` (`owner_only`/`nobody` can block). Private: owner/admin only. Self-add bypasses agent policy but not private-channel auth. A guest cannot add anyone. A new member with no role tag gets the channel's `join_role`; a non-member adding themselves may ask for `join_role` or a lower role. One event may name up to 100 people: one `p` tag each, with an optional role as the `p` tag's third element (NIP-29), falling back to the event's `role` tag. Each person is checked and added on their own. When the event names several people, the OK message is `members: ` followed by JSON listing the non-empty `added`, `updated` (role changed), `already_member` and `rejected` (`[{"reason", "pubkeys"}]`) results. The event is refused only when it is malformed or nobody it names may be added; then one person keeps the single-add error, and several get `invalid: members: {โ€ฆ}`. The event and its membership changes are stored together, so an `error:` rejection stores nothing and the same event can be resent; a resent stored event returns `duplicate:` without results. Re-adding someone at their current role posts no second `member_joined` notice. | | **Remove user (kind:9001)** | โœ… | Self-remove allowed (with last-owner guard). Removing others: owner/admin, or an active member removing their own agent. Only a channel owner may remove another channel owner. | | **Edit group metadata (kind:9002)** | โœ… | `name`/`about`/label `t`/`visibility`/`ttl`/`archived`/`join_role`/`unlisted` tags: owner/admin. `topic`/`purpose` tags: any member except a guest. `auto_join` tag: relay owner/admin (see [Default channels](#default-channels)). A relay operator may also send a 9002 that changes only `name` on a listed channel, archived ones included, whatever its channel role, so that duplicate names can be repaired; the channel stays archived. The relay refuses a `name`, `visibility` or `unlisted` change that leaves a listed channel with a name another listed channel already has: `invalid: an open channel named "" already exists`. The relay refuses a private-to-open `visibility` change while the channel has, or once had, a member who is neither the sender nor an agent the sender owns (NIP-OA); removed members count, because their posts stay in its history: `invalid: a private channel with other members cannot be made open; create a new open channel instead`. Buzz applies 9002 as a partial update: an absent tag leaves that setting unchanged. | @@ -136,6 +136,15 @@ Kind:39000 always publishes both flags. Older clients omitting them do not reset them. These grants apply only to active Guest members of streams and forums; non-members receive no additional authority. +To create a View only stream, send kind:9007 with exactly one +`["visibility", "view-only"]` tag and optional `guest_replies` and +`guest_reactions` boolean tags in the same event. Omitted grants start as false. +The channel commits as open with `join_role = guest` and the requested grants; +the creator is still its owner. The first self-join therefore yields a Viewer. +Signed kind:39000 reports `public`, `restricted`, `join_role = guest`, and both +boolean flags. The creation-only visibility is rejected by older Buzz relays; +clients must surface the refusal and must never retry with `visibility = open`. + The reply grant covers stream message kinds 9 and 40002, including their threads in forum channels. Forum-specific comments (45003), votes and new posts retain their existing writer-only gate. A Guest reply must resolve to an existing message root and parent in the same diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index 68a24c8ea33..97242583bbd 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -242,6 +242,7 @@ pub async fn create_channel_with_id( ttl_seconds, labels, unlisted: false, + guest_contributions: None, members: &[], }, ) @@ -269,6 +270,15 @@ pub async fn create_channel_with_id( Ok((record, was_created)) } +/// Contributions enabled at creation for a channel that admits viewers. +#[derive(Clone, Copy, Debug, Default)] +pub struct GuestContributions { + /// Viewers may send thread replies. + pub replies: bool, + /// Viewers may add message reactions. + pub reactions: bool, +} + /// A channel to create: the fields a kind:9007 sets. pub struct NewChannel<'a> { /// Display name, canonicalized before storage. @@ -287,6 +297,8 @@ pub struct NewChannel<'a> { pub labels: &'a [String], /// Leave the channel out of listings for non-members from the start. pub unlisted: bool, + /// When present, self-joins start as viewers with these grants. + pub guest_contributions: Option, /// 32-byte pubkeys added as ordinary members invited by the creator. The /// caller has authorized each addition. pub members: &'a [Vec], @@ -369,6 +381,7 @@ async fn insert_channel_rows( ttl_seconds, labels, unlisted, + guest_contributions, members, } = channel; let community_id = tx.community(); @@ -390,11 +403,17 @@ async fn insert_channel_rows( return Err(DbError::InvalidData("channel name is required".into())); } + let join_role = if guest_contributions.is_some() { + ChannelJoinRole::Guest + } else { + ChannelJoinRole::Member + }; + let grants = guest_contributions.unwrap_or_default(); let rows_affected = sqlx::query( r#" - INSERT INTO channels (id, community_id, name, channel_type, visibility, description, created_by, ttl_seconds, ttl_deadline, labels, unlisted) + INSERT INTO channels (id, community_id, name, channel_type, visibility, description, created_by, ttl_seconds, ttl_deadline, labels, unlisted, join_role, guest_replies, guest_reactions) VALUES ($1, $2, $3, $4::channel_type, $5::channel_visibility, $6, $7, $8, - CASE WHEN $8 IS NOT NULL THEN NOW() + ($8 || ' seconds')::interval ELSE NULL END, $9, $10) + CASE WHEN $8 IS NOT NULL THEN NOW() + ($8 || ' seconds')::interval ELSE NULL END, $9, $10, $11, $12, $13) ON CONFLICT (community_id, id) DO NOTHING "#, ) @@ -408,6 +427,9 @@ async fn insert_channel_rows( .bind(ttl_seconds) .bind(labels) .bind(unlisted) + .bind(join_role.as_str()) + .bind(grants.replies) + .bind(grants.reactions) .execute(tx.conn()) .await .map_err(|e| listed_name_taken(e, Some(name)))? @@ -3215,6 +3237,7 @@ mod postgres_tests { ttl_seconds: None, labels: &[], unlisted: false, + guest_contributions: None, members, } } diff --git a/crates/buzz-db/src/store/event_hydration/postgres_tests.rs b/crates/buzz-db/src/store/event_hydration/postgres_tests.rs index 5e8acf1b407..e3892b46903 100644 --- a/crates/buzz-db/src/store/event_hydration/postgres_tests.rs +++ b/crates/buzz-db/src/store/event_hydration/postgres_tests.rs @@ -380,6 +380,7 @@ async fn channel_create_resend_requires_exact_timestamp_and_live_community_row() ttl_seconds: None, labels: &[], unlisted: false, + guest_contributions: None, members: &[], }; assert!(matches!( diff --git a/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs b/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs index dbba7b7bd8f..0446fdea616 100644 --- a/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs +++ b/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs @@ -371,6 +371,7 @@ async fn channel_created_unlisted_is_never_listed() { ttl_seconds: None, labels: &[], unlisted: true, + guest_contributions: None, members: &[], }, &event, diff --git a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs index 88572c38806..b7b2c259ce0 100644 --- a/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs @@ -309,3 +309,77 @@ async fn guests_contribute_only_through_explicit_reply_and_reaction_grants() { "remove own reaction after revocation", ); } + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn view_only_stream_has_viewer_admission_and_grants_from_creation() { + let state = state().await; + let tenant = community(&state, "view-only-create").await; + let owner = Keys::generate(); + let viewer = Keys::generate(); + let channel = Uuid::new_v4(); + let channel_id = channel.to_string(); + let h = ["h", channel_id.as_str()]; + let create = event( + &owner, + 9007, + "", + &[ + &h, + &["name", "Announcements"], + &["visibility", "view-only"], + &["guest_replies", "true"], + ], + ); + let submit = async |event, keys| ingest_event(&state, &tenant, event, http_auth(keys)).await; + check(submit(create, &owner).await, None, "create View only"); + check( + submit(event(&viewer, 9021, "", &[&h]), &viewer).await, + None, + "first self-join", + ); + let roster = group_state_tags(&state, &tenant, channel, 39002).await; + let viewer_pubkey = viewer.public_key().to_hex(); + assert!(roster.iter().any(|tag| matches!( + tag.as_slice(), [kind, key, _, role, ..] + if kind == "p" && key == &viewer_pubkey && role == "guest" + ))); + let metadata = group_state_tags(&state, &tenant, channel, 39000).await; + for tag in [ + &["public"][..], + &["restricted"], + &["join_role", "guest"], + &["guest_replies", "true"], + &["guest_reactions", "false"], + ] { + assert!( + metadata + .iter() + .any(|actual| actual.iter().map(String::as_str).eq(tag.iter().copied())), + "missing {tag:?}" + ); + } + + let root = event(&owner, 9, "Update", &[&h]); + let root_id = root.id.to_hex(); + check(submit(root, &owner).await, None, "owner root"); + check( + submit( + event(&viewer, 9, "Reply", &[&h, &["e", &root_id, "", "reply"]]), + &viewer, + ) + .await, + None, + "Viewer reply", + ); + check( + submit(event(&viewer, 9, "New post", &[&h]), &viewer).await, + Some(POST_DENIED), + "Viewer cannot post a channel message", + ); + check( + submit(event(&viewer, 7, "๐Ÿ‘", &[&["e", &root_id]]), &viewer).await, + Some(REACT_DENIED), + "Viewer cannot add a reaction with only replies enabled", + ); +} diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index eeb924d8aad..4256f68556f 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -2682,6 +2682,7 @@ struct ChannelCreateRequest { ttl_seconds: Option, labels: Vec, unlisted: bool, + guest_contributions: Option, members: Vec>, } @@ -3443,19 +3444,49 @@ async fn ingest_event_inner( channel_type_str.parse().map_err(|_| { IngestError::Rejected(format!("invalid channel_type: {channel_type_str}")) })?; - let visibility: buzz_db::channel::ChannelVisibility = - match event.tags.iter().find_map(|t| { - if t.kind().to_string() == "visibility" { - t.content().map(|s| s.to_string()) - } else { - None - } - }) { - Some(visibility_str) => visibility_str.parse().map_err(|_| { - IngestError::Rejected(format!("invalid visibility: {visibility_str}")) - })?, + use buzz_db::channel::{ChannelType, ChannelVisibility, GuestContributions}; + let visibility_tags = || { + event + .tags + .iter() + .filter(|tag| tag.kind().to_string() == "visibility") + }; + let view_only = visibility_tags().any(|tag| tag.content() == Some("view-only")); + let grant = |name| { + super::side_effects::guest_grant_from_tags(&event, name) + .map_err(|error| IngestError::Rejected(format!("invalid: {error}"))) + }; + let replies = grant("guest_replies")?; + let reactions = grant("guest_reactions")?; + let (visibility, guest_contributions) = if view_only { + if channel_type != ChannelType::Stream + || !visibility_tags().map(|tag| tag.as_slice().len()).eq([2]) + { + return Err(IngestError::Rejected( + "invalid: view-only requires a stream and one visibility tag".into(), + )); + } + ( + ChannelVisibility::Open, + Some(GuestContributions { + replies: replies.unwrap_or_default(), + reactions: reactions.unwrap_or_default(), + }), + ) + } else { + if replies.is_some() || reactions.is_some() { + return Err(IngestError::Rejected( + "invalid: viewer grants require view-only creation".into(), + )); + } + let visibility = match visibility_tags().find_map(|tag| tag.content()) { + Some(value) => value + .parse() + .map_err(|_| IngestError::Rejected(format!("invalid visibility: {value}")))?, None => channel_type.default_visibility(), }; + (visibility, None) + }; let labels = super::side_effects::channel_labels_from_tags(&event) .transpose() .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))? @@ -3481,6 +3512,7 @@ async fn ingest_event_inner( ttl_seconds: super::resolve_ttl(&event, state.config.ephemeral_ttl_override), labels, unlisted, + guest_contributions, members, }); } else { @@ -3744,6 +3776,7 @@ async fn ingest_event_inner( ttl_seconds: create.ttl_seconds, labels: &create.labels, unlisted: create.unlisted, + guest_contributions: create.guest_contributions, members: &create.members, }; match state diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index de69d3d84d4..d592a00f5f4 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -768,20 +768,8 @@ pub async fn validate_admin_event( } } - for name in ["guest_replies", "guest_reactions"] { - let tags: Vec<_> = event - .tags - .iter() - .filter(|t| t.kind().to_string() == name) - .collect(); - if tags.len() > 1 - || tags.iter().any(|t| { - t.as_slice().len() != 2 || !matches!(t.content(), Some("true" | "false")) - }) - { - return Err(anyhow::anyhow!("{name} must be one true/false tag")); - } - } + guest_grant_from_tags(event, "guest_replies")?; + guest_grant_from_tags(event, "guest_reactions")?; // Validate channel names before storage. A name made entirely of // display-prefix hashes becomes empty after canonicalization, and @@ -2611,6 +2599,22 @@ pub(crate) fn channel_labels_from_tags( } } +/// Read one optional, explicit boolean grant on kind:9007 or kind:9002. +pub(super) fn guest_grant_from_tags(event: &Event, name: &str) -> anyhow::Result> { + let mut tags = event.tags.iter().filter(|t| t.kind().to_string() == name); + let Some(tag) = tags.next() else { + return Ok(None); + }; + if tags.next().is_some() || tag.as_slice().len() != 2 { + anyhow::bail!("{name} must be one true/false tag"); + } + match tag.content() { + Some("true") => Ok(Some(true)), + Some("false") => Ok(Some(false)), + _ => anyhow::bail!("{name} must be one true/false tag"), + } +} + /// The kind:9007 `["unlisted", "true"|"false"]` setting: whether a new /// channel starts out of channel listings for non-members. A missing tag means /// listed. Any other value is refused, as kind:9002 refuses it; the last tag @@ -2720,82 +2724,21 @@ async fn handle_create_group( event: &Event, state: &Arc, ) -> anyhow::Result<()> { - let name = - extract_tag_value(event, "name").ok_or_else(|| anyhow::anyhow!("missing name tag"))?; - let channel_type_str = - extract_tag_value(event, "channel_type").unwrap_or_else(|| "stream".to_string()); - let channel_type: buzz_db::channel::ChannelType = channel_type_str - .parse() - .map_err(|_| anyhow::anyhow!("invalid channel_type: {channel_type_str}"))?; - let visibility: buzz_db::channel::ChannelVisibility = - match extract_tag_value(event, "visibility") { - Some(visibility_str) => visibility_str - .parse() - .map_err(|_| anyhow::anyhow!("invalid visibility: {visibility_str}"))?, - None => channel_type.default_visibility(), - }; - + // Ingest already committed the channel, its creator and its initial members. + // A failed lookup must not create a second channel with different permissions. + let channel_id = + extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing or invalid h tag"))?; + let channel = state + .db + .get_channel_for_event_write(tenant.community(), channel_id) + .await?; let actor_bytes = event.pubkey.to_bytes().to_vec(); - let description = extract_tag_value(event, "about"); - let ttl_seconds = super::resolve_ttl(event, state.config.ephemeral_ttl_override); - let labels = channel_labels_from_tags(event) - .transpose() - .map_err(|e| anyhow::anyhow!("{e}"))? - .unwrap_or_default(); - let unlisted = create_unlisted_from_tags(event)?; - - // Ingest already created the channel named by the h tag, in the same - // commit as this event. Fetch it rather than creating a duplicate. - // - // Double-count analysis (C5): the counter increment below does NOT - // double-count vs. ingest.rs. Ingest increments on was_created=true and - // this handler only reaches create_channel() on a DB lookup Err โ€” an - // error recovery path where ingest's channel is inaccessible, so the - // counter correctly records a new creation. - // `members_added`: ingest's create also added the event's `p` tags. - let (channel, members_added) = if let Some(client_uuid) = extract_h_tag_channel(event) { - match state - .db - .get_channel_for_event_write(tenant.community(), client_uuid) - .await - { - Ok(ch) => (ch, true), - Err(_) => { - // Channel not found โ€” shouldn't happen (ingest_event pre-created it), - // but fall back to creation to stay resilient. - let ch = state - .db - .create_labeled_channel( - tenant.community(), - &name, - channel_type, - visibility, - description.as_deref(), - &actor_bytes, - ttl_seconds, - &labels, - unlisted, - ) - .await?; - metrics::counter!( - "buzz_channels_created_total", - "community" => tenant.host().to_owned(), - "type" => channel_type.to_string() - ) - .increment(1); - (ch, false) - } - } - } else { - // Ingest refuses a kind:9007 without an `h` tag before storing it. - anyhow::bail!("missing or invalid h tag"); - }; // Creator becomes owner โ€” evict any stale negative membership lookup. state.invalidate_membership(tenant, channel.id, &actor_bytes); // Open channels appear in everyone's accessible set; a private channel only // affects its initial members, whose entries the invalidations here drop. - if visibility == buzz_db::channel::ChannelVisibility::Open { + if channel.visibility == buzz_db::channel::ChannelVisibility::Open.as_str() { state.invalidate_all_accessible_channels(tenant); } @@ -2831,12 +2774,7 @@ async fn handle_create_group( // Ingest added these in the create's transaction; announce them as a // kind:9000 would. A failed announcement for one member must not cost the // rest theirs: a resend writes nothing, so nothing would retry them. - let members = if members_added { - initial_members(event)? - } else { - Vec::new() - }; - for member in members { + for member in initial_members(event)? { state.invalidate_membership(tenant, channel.id, &member); if let Err(e) = emit_system_message( tenant, @@ -2867,7 +2805,7 @@ async fn handle_create_group( } } - info!(channel_id = %channel.id, name = %name, "NIP-29 CREATE_GROUP processed"); + info!(channel_id = %channel.id, name = %channel.name, "NIP-29 CREATE_GROUP processed"); Ok(()) } diff --git a/mobile/ios/Runner/NativeCreateChannelSheet.swift b/mobile/ios/Runner/NativeCreateChannelSheet.swift index 6e25589532d..361206bdafa 100644 --- a/mobile/ios/Runner/NativeCreateChannelSheet.swift +++ b/mobile/ios/Runner/NativeCreateChannelSheet.swift @@ -78,6 +78,11 @@ final class NativeCreateChannelViewController: UITableViewController, UITextView private let rowColor: UIColor private var temporary = false private var visibility = "open" + private var guestReplies = false + private var guestReactions = false + private let visibilityOptions = [ + ("Public", "open"), ("View only", "view-only"), ("Private", "private"), + ] private var ttl = 604800 private var busy = false private let expiry: [(String, Int)] = [ @@ -167,6 +172,10 @@ final class NativeCreateChannelViewController: UITableViewController, UITextView updateControls() var values: [String: Any] = ["name": value, "description": details.text.trimmingCharacters(in: .whitespacesAndNewlines), "visibility": visibility] if temporary { values["ttlSeconds"] = ttl } + if visibility == "view-only" { + values["guestReplies"] = guestReplies + values["guestReactions"] = guestReactions + } onCreate?(values) } @@ -187,7 +196,11 @@ final class NativeCreateChannelViewController: UITableViewController, UITextView } override func numberOfSections(in tableView: UITableView) -> Int { 3 } - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { section == 2 ? (temporary ? 3 : 2) : 1 } + private var pickerRowCount: Int { temporary ? 3 : 2 } + + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + section == 2 ? pickerRowCount + (visibility == "view-only" ? 2 : 0) : 1 + } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { section == 0 ? "Name" : section == 1 ? "Description ยท Optional" : nil } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { @@ -218,11 +231,29 @@ final class NativeCreateChannelViewController: UITableViewController, UITextView field.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -12), field.heightAnchor.constraint(greaterThanOrEqualToConstant: indexPath.section == 0 ? 28 : 96), ]) + } else if indexPath.row >= pickerRowCount { + let isReplies = indexPath.row == pickerRowCount + let label = isReplies ? "Allow viewers to reply in threads" : "Allow viewers to react" + var content = cell.defaultContentConfiguration() + content.text = label + cell.contentConfiguration = content + let toggle = UISwitch() + toggle.isOn = isReplies ? guestReplies : guestReactions + toggle.accessibilityLabel = label + toggle.addAction(UIAction { [weak self, weak toggle] _ in + guard let self, let toggle, !self.busy else { return } + if isReplies { self.guestReplies = toggle.isOn } + else { self.guestReactions = toggle.isOn } + }, for: .valueChanged) + cell.accessoryView = toggle + cell.isAccessibilityElement = false + cell.accessibilityElements = [toggle] } else { let isType = indexPath.row == 0 let isVisibility = indexPath.row == 1 let label = isType ? "Channel type" : isVisibility ? "Visibility" : "Delete after inactivity" - let value = isType ? (temporary ? "Temporary" : "Ongoing") : isVisibility ? (visibility == "open" ? "Public" : "Private") : expiry.first(where: { $0.1 == ttl })?.0 ?? "7 days" + let visibilityLabel = visibilityOptions.first(where: { $0.1 == visibility })?.0 ?? "Public" + let value = isType ? (temporary ? "Temporary" : "Ongoing") : isVisibility ? visibilityLabel : expiry.first(where: { $0.1 == ttl })?.0 ?? "7 days" let button = UIButton(type: .system) let titleLabel = UILabel() titleLabel.text = label @@ -245,7 +276,7 @@ final class NativeCreateChannelViewController: UITableViewController, UITextView button.accessibilityLabel = label button.accessibilityValue = value button.showsMenuAsPrimaryAction = true - let choices: [(String, String)] = isType ? [("Ongoing", "ongoing"), ("Temporary", "temporary")] : isVisibility ? [("Public", "open"), ("Private", "private")] : expiry.map { ($0.0, String($0.1)) } + let choices: [(String, String)] = isType ? [("Ongoing", "ongoing"), ("Temporary", "temporary")] : isVisibility ? visibilityOptions : expiry.map { ($0.0, String($0.1)) } let selected = isType ? (temporary ? "temporary" : "ongoing") : isVisibility ? visibility : String(ttl) button.menu = UIMenu(children: choices.map { title, key in UIAction(title: title, state: key == selected ? .on : .off) { [weak self] _ in diff --git a/mobile/lib/features/channels/channel_management_actions.dart b/mobile/lib/features/channels/channel_management_actions.dart index 4fd6eeb1af5..67a4a0f9e51 100644 --- a/mobile/lib/features/channels/channel_management_actions.dart +++ b/mobile/lib/features/channels/channel_management_actions.dart @@ -60,6 +60,8 @@ class ChannelActions { List labels = const [], String? description, int? ttlSeconds, + bool guestReplies = false, + bool guestReactions = false, bool waitForChannelList = true, }) async { final resolvedChannelId = channelId ?? _newUuidV4(); @@ -71,9 +73,21 @@ class ChannelActions { labels: labels, description: description, ttlSeconds: ttlSeconds, + guestReplies: guestReplies, + guestReactions: guestReactions, ); _ensureCommunityValid(); - await _signedEventRelay.submit(kind: 9007, content: '', tags: tags); + try { + await _signedEventRelay.submit(kind: 9007, content: '', tags: tags); + } catch (error) { + if (visibility == viewOnlyCreateVisibility && + error.toString().contains('invalid visibility: view-only')) { + throw Exception( + 'This relay does not support creating View only channels.', + ); + } + rethrow; + } _ensureCommunityValid(); if (!waitForChannelList) { // Solo can open from its own confirmed metadata and roster. Reconcile diff --git a/mobile/lib/features/channels/channel_management_provider.dart b/mobile/lib/features/channels/channel_management_provider.dart index 2e2da168943..45542342add 100644 --- a/mobile/lib/features/channels/channel_management_provider.dart +++ b/mobile/lib/features/channels/channel_management_provider.dart @@ -556,6 +556,9 @@ List> buildDeleteMessageTags({ ]; } +/// Creation-only visibility accepted atomically or refused by the relay. +const viewOnlyCreateVisibility = 'view-only'; + /// Builds the signed kind:9007 tags used by mobile channel creation. List> buildCreateChannelTags({ required String channelId, @@ -565,6 +568,8 @@ List> buildCreateChannelTags({ List labels = const [], String? description, int? ttlSeconds, + bool guestReplies = false, + bool guestReactions = false, }) { if (ttlSeconds != null && ttlSeconds <= 0) { throw ArgumentError.value(ttlSeconds, 'ttlSeconds', 'must be positive'); @@ -575,6 +580,10 @@ List> buildCreateChannelTags({ ['name', name], ['visibility', visibility], ['channel_type', channelType], + if (visibility == viewOnlyCreateVisibility) ...[ + ['guest_replies', guestReplies.toString()], + ['guest_reactions', guestReactions.toString()], + ], for (final label in labels) ['t', label], if (description case final about? when about.trim().isNotEmpty) ['about', about.trim()], diff --git a/mobile/lib/features/channels/channels_page.dart b/mobile/lib/features/channels/channels_page.dart index ec11aa621bd..798d43e4c0b 100644 --- a/mobile/lib/features/channels/channels_page.dart +++ b/mobile/lib/features/channels/channels_page.dart @@ -573,12 +573,16 @@ class ChannelsPage extends HookConsumerWidget { required description, required visibility, required ttlSeconds, + required guestReplies, + required guestReactions, }) => actions.createChannel( name: name, description: description, visibility: visibility, channelType: 'stream', ttlSeconds: ttlSeconds, + guestReplies: guestReplies, + guestReactions: guestReactions, ), ); } else { diff --git a/mobile/lib/features/channels/channels_page/sheets.dart b/mobile/lib/features/channels/channels_page/sheets.dart index 2e949b447ad..02478610b7a 100644 --- a/mobile/lib/features/channels/channels_page/sheets.dart +++ b/mobile/lib/features/channels/channels_page/sheets.dart @@ -27,6 +27,8 @@ class _CreateChannelSheet extends HookConsumerWidget { final nameController = useTextEditingController(); final descriptionController = useTextEditingController(); final visibility = useState('open'); + final guestReplies = useState(false); + final guestReactions = useState(false); final temporary = useState(false); final ttlSeconds = useState(_defaultCreateChannelTtlSeconds); final isSubmitting = useState(false); @@ -53,6 +55,8 @@ class _CreateChannelSheet extends HookConsumerWidget { visibility: visibility.value, description: descriptionController.text.trim(), ttlSeconds: temporary.value ? ttlSeconds.value : null, + guestReplies: guestReplies.value, + guestReactions: guestReactions.value, ); if (context.mounted) { Navigator.of(context).pop(created); @@ -200,9 +204,11 @@ class _CreateChannelSheet extends HookConsumerWidget { grouped: true, preserveTextInput: true, trailingIcon: Icons.unfold_more, - valueLabel: visibility.value == 'open' - ? 'Public' - : 'Private', + valueLabel: switch (visibility.value) { + 'open' => 'Public', + viewOnlyCreateVisibility => 'View only', + _ => 'Private', + }, enabled: !isSubmitting.value, label: 'Visibility', onSelected: (value) => visibility.value = value, @@ -212,6 +218,11 @@ class _CreateChannelSheet extends HookConsumerWidget { label: 'Public', value: 'open', ), + _CreateChannelMenuOption( + key: Key('create-channel-visibility-view-only'), + label: 'View only', + value: viewOnlyCreateVisibility, + ), _CreateChannelMenuOption( key: Key('create-channel-visibility-private'), label: 'Private', @@ -220,6 +231,22 @@ class _CreateChannelSheet extends HookConsumerWidget { ], value: visibility.value, ), + if (visibility.value == viewOnlyCreateVisibility) ...[ + SwitchListTile.adaptive( + title: const Text('Allow viewers to reply in threads'), + value: guestReplies.value, + onChanged: isSubmitting.value + ? null + : (value) => guestReplies.value = value, + ), + SwitchListTile.adaptive( + title: const Text('Allow viewers to react'), + value: guestReactions.value, + onChanged: isSubmitting.value + ? null + : (value) => guestReactions.value = value, + ), + ], ], ), if (errorMessage.value case final error?) ...[ diff --git a/mobile/lib/features/channels/ios_create_channel_sheet.dart b/mobile/lib/features/channels/ios_create_channel_sheet.dart index 45e040bda29..3110e45ef08 100644 --- a/mobile/lib/features/channels/ios_create_channel_sheet.dart +++ b/mobile/lib/features/channels/ios_create_channel_sheet.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../../shared/relay/relay.dart'; import '../../shared/theme/theme.dart'; import 'channel.dart'; @@ -16,6 +17,8 @@ class IosCreateChannelSheet { required String description, required String visibility, required int? ttlSeconds, + required bool guestReplies, + required bool guestReactions, }) onCreate, }) async { @@ -33,10 +36,12 @@ class IosCreateChannelSheet { description: data['description'] as String, visibility: data['visibility'] as String, ttlSeconds: data['ttlSeconds'] as int?, + guestReplies: data['guestReplies'] == true, + guestReactions: data['guestReactions'] == true, ); return {'success': true}; } catch (error) { - return {'error': error.toString()}; + return {'error': relayErrorMessage(error)}; } }); try { diff --git a/mobile/test/features/channels/channel_management_provider_test.dart b/mobile/test/features/channels/channel_management_provider_test.dart index 091391c5589..02196f50ef2 100644 --- a/mobile/test/features/channels/channel_management_provider_test.dart +++ b/mobile/test/features/channels/channel_management_provider_test.dart @@ -492,6 +492,52 @@ void main() { }, ); + test('old relay refusal never retries creation as Public', () async { + final keys = nostr.Keys.generate(); + final session = _RecordingPublishRelaySession( + publishError: Exception('invalid visibility: view-only'), + ); + final provider = Provider( + (ref) => ChannelActions( + ref: ref, + session: session, + signedEventRelay: SignedEventRelay(session: session, nsec: keys.nsec), + currentPubkey: keys.public, + ), + ); + final container = ProviderContainer(retry: (_, _) => null); + addTearDown(container.dispose); + + await expectLater( + container + .read(provider) + .createChannel( + channelId: _channelId, + name: 'announcements', + channelType: 'stream', + visibility: viewOnlyCreateVisibility, + guestReplies: true, + ), + throwsA( + predicate( + (e) => relayErrorMessage( + e!, + ).contains('This relay does not support creating View only channels'), + ), + ), + ); + final created = session.publishedEvents.single; + expect(created.kind, 9007); + expect(created.tags, [ + ['h', _channelId], + ['name', 'announcements'], + ['visibility', 'view-only'], + ['channel_type', 'stream'], + ['guest_replies', 'true'], + ['guest_reactions', 'false'], + ]); + }); + test('reactions tag the reacted-to message author', () async { final keys = nostr.Keys.generate(); final session = _RecordingPublishRelaySession(); @@ -946,6 +992,9 @@ const _memberPubkey = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; class _RecordingPublishRelaySession extends RelaySessionNotifier { + _RecordingPublishRelaySession({this.publishError}); + + final Object? publishError; final publishedEvents = []; final queryFilters = []; int historyQueryCount = 0; @@ -959,6 +1008,7 @@ class _RecordingPublishRelaySession extends RelaySessionNotifier { Duration timeout = const Duration(seconds: 8), }) async { publishedEvents.add(event); + if (publishError case final error?) throw error; return event; } diff --git a/mobile/test/features/channels/channels_page_test.dart b/mobile/test/features/channels/channels_page_test.dart index 4279b024f95..42e682a90f3 100644 --- a/mobile/test/features/channels/channels_page_test.dart +++ b/mobile/test/features/channels/channels_page_test.dart @@ -3377,6 +3377,33 @@ void main() { 'description': 'Release updates', 'ttl': 7 * 24 * 60 * 60, }); + await tester.tap(find.byKey(const Key('create-channel-visibility'))); + await tester.pumpAndSettle(); + final viewOnly = find.byKey( + const Key('create-channel-visibility-view-only'), + ); + await tester.ensureVisible(viewOnly); + await tester.tap(viewOnly); + await tester.pumpAndSettle(); + final replies = find.widgetWithText( + SwitchListTile, + 'Allow viewers to reply in threads', + ); + final reactions = find.widgetWithText( + SwitchListTile, + 'Allow viewers to react', + ); + expect(tester.widget(replies).value, isFalse); + expect(tester.widget(reactions).value, isFalse); + await tester.ensureVisible(replies); + await tester.tap(replies); + await tester.pumpAndSettle(); + expect(tester.widget(reactions).value, isFalse); + await tester.tap(submit); + await tester.pumpAndSettle(); + expect(actions.creations.last, containsPair('visibility', 'view-only')); + expect(actions.creations.last, containsPair('guestReplies', true)); + expect(actions.creations.last, containsPair('guestReactions', false)); await tester.tap(find.byTooltip('Close')); await tester.pumpAndSettle(); expect(find.byKey(const Key('create-channel-name')), findsNothing); @@ -4543,6 +4570,8 @@ class _CreateSheetActions implements ChannelActions { List labels = const [], String? description, int? ttlSeconds, + bool guestReplies = false, + bool guestReactions = false, bool waitForChannelList = true, }) async { creations.add({ @@ -4551,6 +4580,10 @@ class _CreateSheetActions implements ChannelActions { 'visibility': visibility, 'description': description, 'ttl': ttlSeconds, + if (visibility == viewOnlyCreateVisibility) ...{ + 'guestReplies': guestReplies, + 'guestReactions': guestReactions, + }, }); throw StateError('Try again'); } @@ -4573,6 +4606,8 @@ class _RefusingCreateActions implements ChannelActions { List labels = const [], String? description, int? ttlSeconds, + bool guestReplies = false, + bool guestReactions = false, bool waitForChannelList = true, }) async => throw error; diff --git a/mobile/test/features/channels/ios_create_channel_sheet_test.dart b/mobile/test/features/channels/ios_create_channel_sheet_test.dart index 6beb9ee5252..04c38e05620 100644 --- a/mobile/test/features/channels/ios_create_channel_sheet_test.dart +++ b/mobile/test/features/channels/ios_create_channel_sheet_test.dart @@ -46,12 +46,16 @@ void main() { required description, required visibility, required ttlSeconds, + required guestReplies, + required guestReactions, }) async { payloads.add({ 'name': name, 'description': description, 'visibility': visibility, 'ttl': ttlSeconds, + 'guestReplies': guestReplies, + 'guestReactions': guestReactions, }); if (payloads.length == 1) { throw StateError('Try again'); @@ -80,6 +84,7 @@ void main() { 'description': 'Details', 'visibility': visibility, 'ttlSeconds': ttl, + if (visibility == 'view-only') 'guestReplies': true, }), ), (bytes) => response.complete( @@ -95,12 +100,14 @@ void main() { ); expect(result, isNull); expect(configuration!['session'], session); - expect(await create('private', 3600), {'success': true}); + expect(await create('view-only', 3600), {'success': true}); expect(payloads.last, { 'name': 'Test', 'description': 'Details', - 'visibility': 'private', + 'visibility': 'view-only', 'ttl': 3600, + 'guestReplies': true, + 'guestReactions': false, }); expect(result, isNull); // Navigation waits until UIKit has dismissed. dismissed.complete(); From b5852f0fbc6b2928a8076540052a25dc9422645a Mon Sep 17 00:00:00 2001 From: Taylor Ho Date: Wed, 18 Nov 2026 16:15:15 -0800 Subject: [PATCH 10/10] test(mobile): wait for community cache cleanup Observe removal of the cache directory itself because background recursive cleanup can remove its child before the parent disappears. Co-authored-by: Carl Signed-off-by: Taylor Ho --- mobile/test/shared/community/community_provider_test.dart | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index 1f5481a99aa..e3e4abc4b3f 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -621,10 +621,9 @@ void main() { expect(await cache.write(newToken, snapshot), isFalse); expect(await eventuallyExists(newMedia), isFalse); expect( - await MediaDiskCache.communityDirectory( - mediaRoot, - community.id, - ).exists(), + await eventuallyExists( + MediaDiskCache.communityDirectory(mediaRoot, community.id), + ), isFalse, );