diff --git a/NOSTR.md b/NOSTR.md index c0498a3678d..27e28aef4d4 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. | @@ -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,48 @@ 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. + +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 +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/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 8a5c0879fa9..76cf26b7e48 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 101); + assert_eq!(migrations.len(), 102); assert_eq!(migrations[100].version, 101); assert!(strip_sql_comments(migrations[100].sql.as_str()) .contains("DROP CONSTRAINT IF EXISTS push_gateway_delegations_installation_id_fkey")); @@ -970,6 +970,10 @@ mod postgres_tests { "0095 must run {statement}" ); } + assert_eq!(migrations[101].version, 102); + let guest_grants = migrations[101].sql.as_str(); + assert!(guest_grants.contains("ADD COLUMN guest_replies BOOLEAN NOT NULL DEFAULT false")); + assert!(guest_grants.contains("ADD COLUMN guest_reactions BOOLEAN NOT NULL DEFAULT false")); assert!(migrations[70] .sql .as_str() diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index 233660c9d61..0dbf2e28ac3 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 "#, ) @@ -238,6 +242,7 @@ pub async fn create_channel_with_id( ttl_seconds, labels, unlisted: false, + guest_contributions: None, members: &[], }, ) @@ -251,7 +256,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 "#, ) @@ -265,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. @@ -283,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], @@ -365,6 +381,7 @@ async fn insert_channel_rows( ttl_seconds, labels, unlisted, + guest_contributions, members, } = channel; let community_id = tx.community(); @@ -386,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 "#, ) @@ -404,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)))? @@ -541,7 +567,7 @@ pub(crate) 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 +656,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 +676,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 +717,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 +821,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"])); } @@ -1163,6 +1207,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, @@ -1181,6 +1229,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() } @@ -1449,6 +1499,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; @@ -1492,6 +1551,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); } @@ -2551,6 +2616,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, } @@ -3204,6 +3271,7 @@ mod postgres_tests { ttl_seconds: None, labels: &[], unlisted: false, + guest_contributions: None, members, } } diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 64dfd3bc670..d452d9886c2 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -2052,7 +2052,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 "#, ) @@ -2150,7 +2150,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 39cbd6b1fd1..9e82aa00139 100644 --- a/crates/buzz-db/src/store/dm.rs +++ b/crates/buzz-db/src/store/dm.rs @@ -1349,6 +1349,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-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 new file mode 100644 index 00000000000..b7b2c259ce0 --- /dev/null +++ b/crates/buzz-relay/src/handlers/guest_contributions_postgres_tests.rs @@ -0,0 +1,385 @@ +//! 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, edit_channel, group_state_tags, http_auth, state, +}; +use super::ingest::{ingest_event, IngestAuth, IngestError, IngestResult}; + +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] +#[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 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 + .get_member_role(tenant.community(), channel, &guest.public_key().to_bytes()) + .await + .unwrap() + .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); + for (replies, reactions) in [(false, false), (true, false), (false, true), (true, true)] { + 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; + for grant in [reply_grant, react_grant] { + assert!( + tags.iter() + .any(|tag| tag.iter().map(String::as_str).eq(grant)), + "missing {grant:?}" + ); + } + check( + submit( + event(&guest, 9, "Reply", &[&h, &reply_tag]), + http_auth(&guest), + ) + .await, + (!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, emoji, &[&target_tag]), http_auth(&guest)).await, + (!reactions).then_some(REACT_DENIED), + &format!("reaction with grants {replies}/{reactions}"), + ); + } + + 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", + ); + 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", + ); + + let other_channel = create_channel(&state, &tenant, &owner, &[]).await; + let other_root = event( + &owner, + 9, + "Other channel", + &[&["h", &other_channel.to_string()]], + ); + 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); + + // 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, + ), + ( + "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, + vec![&h, &["guest_replies", "false"]], + "actor not authorized", + ), + ("canvas write", 40100, vec![h.as_slice()], POST_DENIED), + ] { + let content = if kind == 9 { "Conversation" } else { "" }; + check( + submit(event(&guest, kind, content, &tags), http_auth(&guest)).await, + Some(denial), + case, + ); + } + + let nested = event( + &guest, + 9, + "Nested reply", + &[ + &h, + &["e", &root_id, "", "root"], + &["e", &parent_id, "", "reply"], + ], + ); + 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 + .unwrap(); + let settings = state + .db + .get_channel(tenant.community(), channel) + .await + .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_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", + ); +} + +#[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 58edf331c86..ae2c16bb760 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -1036,6 +1036,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( @@ -1487,15 +1604,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. @@ -2548,6 +2685,7 @@ struct ChannelCreateRequest { ttl_seconds: Option, labels: Vec, unlisted: bool, + guest_contributions: Option, members: Vec>, } @@ -2909,6 +3047,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` @@ -2952,7 +3091,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, @@ -2961,6 +3100,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 @@ -3321,19 +3469,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}")))? @@ -3359,6 +3537,7 @@ async fn ingest_event_inner( ttl_seconds: super::resolve_ttl(&event, state.config.ephemeral_ttl_override), labels, unlisted, + guest_contributions, members, }); } else { @@ -3449,7 +3628,9 @@ async fn ingest_event_inner( validate_event_imeta(tenant, state, &event, &tenant_media_base).await?; - let thread_meta = if kind_u32 != KIND_SOLO_MEMBER_ROLE && requires_h_channel_scope(kind_u32) { + let thread_meta = if guest_thread_meta.is_some() { + guest_thread_meta + } else if kind_u32 != KIND_SOLO_MEMBER_ROLE && requires_h_channel_scope(kind_u32) { if let Some(ch_id) = channel_id { resolve_nip10_thread_meta(tenant.community(), &event, ch_id, state) .await @@ -3634,6 +3815,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/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index ad1284feda7..94b1b1d2540 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 4f3d4e93121..79635e62148 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -768,6 +768,9 @@ pub async fn validate_admin_event( } } + 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 // a name the column cannot hold would fail only after the command @@ -1486,6 +1489,8 @@ const PRIVILEGED_METADATA_TAGS: &[&str] = &[ "ttl", "t", "join_role", + "guest_replies", + "guest_reactions", "unlisted", ]; @@ -2347,6 +2352,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. @@ -2584,6 +2601,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 @@ -2693,82 +2726,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); } @@ -2804,12 +2776,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, @@ -2840,7 +2807,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/migrations/0102_channel_guest_contributions.sql b/migrations/0102_channel_guest_contributions.sql new file mode 100644 index 00000000000..1e01b1c23f4 --- /dev/null +++ b/migrations/0102_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/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.dart b/mobile/lib/features/channels/channel.dart index c03f307445a..49a975b4526 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 d924dad8b1d..dbc404d086c 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -1,6 +1,7 @@ import 'package:duo_kit/duo_kit.dart'; import '../../shared/widgets/ios_navigation_bar.dart'; import 'bestie_transcription_status.dart'; +import 'channel_permissions.dart'; import '../../shared/widgets/duo_toolbar.dart'; import 'composer_geometry.dart'; import 'message_author_visibility.dart'; @@ -323,10 +324,15 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { ], ); final memberProfilesPreloadState = useFuture(memberProfilesPreload); + final permissions = ref.watch( + channelPermissionsProvider(resolvedChannel.id), + ); final showsComposer = !resolvedChannel.isForum && - resolvedChannel.isMember && - !resolvedChannel.isArchived; + ChannelPermissions( + resolvedChannel, + permissions.role, + ).allows(ChannelAction.post); final profileOwnedAgentPubkeys = []; for (final participantPubkey in resolvedChannel.participantPubkeys) { final normalized = participantPubkey.trim().toLowerCase(); @@ -913,9 +919,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..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 @@ -1105,6 +1159,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_actions.dart b/mobile/lib/features/channels/channel_management_actions.dart index ac1f044b3ff..3d300b608f1 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 8e4398ee828..45542342add 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, @@ -554,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, @@ -563,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'); @@ -573,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/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_page.dart b/mobile/lib/features/channels/channels_page.dart index 4128014a699..2013a5e6286 100644 --- a/mobile/lib/features/channels/channels_page.dart +++ b/mobile/lib/features/channels/channels_page.dart @@ -578,12 +578,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/channels_provider.dart b/mobile/lib/features/channels/channels_provider.dart index 5e67273e0b9..e966405e967 100644 --- a/mobile/lib/features/channels/channels_provider.dart +++ b/mobile/lib/features/channels/channels_provider.dart @@ -824,58 +824,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, - ); - } - void _publishUnreadCatchUp(Map recordedAtByChannel) { state = state.whenData( (channels) => [ 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/lib/features/channels/message_actions.dart b/mobile/lib/features/channels/message_actions.dart index 0755bc03942..a75e6c78aeb 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,16 @@ 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, + channelId: channelId, + 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 +260,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/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/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 0fcafaba506..f13cf9ed8dd 100644 --- a/mobile/lib/features/channels/send_message_provider.dart +++ b/mobile/lib/features/channels/send_message_provider.dart @@ -8,6 +8,7 @@ import '../channels/channel_management_provider.dart'; import '../../shared/profile/user_cache_provider.dart'; import '../../shared/profile/user_profile.dart'; import 'channel.dart'; +import 'channel_permissions.dart'; import 'me/me_messages_provider.dart'; import 'channel_messages_provider.dart'; import 'message_mention_pubkeys.dart'; @@ -25,6 +26,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, Channel? channel)? _canSend; SendMessage({ required SignedEventRelay signedEventRelay, @@ -38,6 +40,7 @@ class SendMessage { completeLocalMessage, required void Function(String channelId, String eventId) removeLocalMessage, bool Function()? isDeliveryValid, + bool Function(String channelId, bool reply, Channel? channel)? canSend, }) : _signedEventRelay = signedEventRelay, _fetchMembers = fetchMembers, _readUserCache = readUserCache, @@ -46,7 +49,8 @@ class SendMessage { markLocalMessageForAnimation ?? ((_, _) {}), _completeLocalMessage = completeLocalMessage, _removeLocalMessage = removeLocalMessage, - _isDeliveryValid = isDeliveryValid; + _isDeliveryValid = isDeliveryValid, + _canSend = canSend; /// Send a text message to a channel. /// @@ -69,7 +73,14 @@ class SendMessage { void Function()? validateDelivery, Future Function()? mayPublish, }) async { - _ensureDeliveryValid(); + void ensureAllowed() { + _ensureDeliveryValid(); + if (_canSend?.call(channelId, parentEventId != null, channel) == 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 = @@ -120,7 +131,7 @@ class SendMessage { if (!isReference(tag)) tag, ]; - _ensureDeliveryValid(); + ensureAllowed(); NostrEvent? localMessage; try { await _signedEventRelay.submit( @@ -128,8 +139,8 @@ class SendMessage { content: content, tags: tags, onSigned: (event) async { - await beforePublish?.call(event); - _ensureDeliveryValid(); + if (beforePublish != null) await beforePublish(event); + ensureAllowed(); validateDelivery?.call(); localMessage = event; _markLocalMessageForAnimation(channelId, event.id); @@ -283,6 +294,17 @@ SendMessage _sender(Ref ref, {bool personal = false}) { session: ref.read(relaySessionProvider.notifier), nsec: config.nsec, ), + 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/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_detail_page_test.dart b/mobile/test/features/channels/channel_detail_page_test.dart index 049ee2be062..4592b86301b 100644 --- a/mobile/test/features/channels/channel_detail_page_test.dart +++ b/mobile/test/features/channels/channel_detail_page_test.dart @@ -60,6 +60,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'; @@ -416,6 +417,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_management_provider_test.dart b/mobile/test/features/channels/channel_management_provider_test.dart index 6598681c22d..1aafba85457 100644 --- a/mobile/test/features/channels/channel_management_provider_test.dart +++ b/mobile/test/features/channels/channel_management_provider_test.dart @@ -489,6 +489,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(); @@ -943,6 +989,9 @@ const _memberPubkey = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; class _RecordingPublishRelaySession extends RelaySessionNotifier { + _RecordingPublishRelaySession({this.publishError}); + + final Object? publishError; final publishedEvents = []; final queryFilters = []; int historyQueryCount = 0; @@ -957,6 +1006,7 @@ class _RecordingPublishRelaySession extends RelaySessionNotifier { Future Function()? mayPublish, }) async { publishedEvents.add(event); + if (publishError case final error?) throw error; return event; } 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_permissions_test.dart b/mobile/test/features/channels/channel_permissions_test.dart new file mode 100644 index 00000000000..bd9ae38546c --- /dev/null +++ b/mobile/test/features/channels/channel_permissions_test.dart @@ -0,0 +1,165 @@ +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 provider = channelPermissionsProvider('room'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + bool allows(ChannelAction action) => + container.read(provider).allows(action); + + expect(allows(ChannelAction.post), isTrue); + role = 'guest'; + container.invalidate(latestChannelMembersProvider('room')); + expect(allows(ChannelAction.post), isFalse); + expect(allows(ChannelAction.reply), isTrue); + expect(allows(ChannelAction.react), isTrue); + + room = channel(); + container.invalidate(channelByIdProvider('room')); + 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 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); + } + } + + 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); + } + } + }); + + 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/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/channels_page_test.dart b/mobile/test/features/channels/channels_page_test.dart index 10802082c98..7fb7f9364a0 100644 --- a/mobile/test/features/channels/channels_page_test.dart +++ b/mobile/test/features/channels/channels_page_test.dart @@ -3656,6 +3656,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); @@ -4964,6 +4991,8 @@ class _CreateSheetActions implements ChannelActions { List labels = const [], String? description, int? ttlSeconds, + bool guestReplies = false, + bool guestReactions = false, bool waitForChannelList = true, }) async { creations.add({ @@ -4972,6 +5001,10 @@ class _CreateSheetActions implements ChannelActions { 'visibility': visibility, 'description': description, 'ttl': ttlSeconds, + if (visibility == viewOnlyCreateVisibility) ...{ + 'guestReplies': guestReplies, + 'guestReactions': guestReactions, + }, }); throw StateError('Try again'); } @@ -4994,6 +5027,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(); diff --git a/mobile/test/features/channels/message_actions_test.dart b/mobile/test/features/channels/message_actions_test.dart index 2c99a656be3..eb01e106efd 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'; @@ -68,7 +69,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', @@ -78,8 +79,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]; @@ -175,6 +183,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( @@ -301,6 +314,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, @@ -350,6 +365,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( @@ -413,13 +435,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: '👍', @@ -432,6 +458,8 @@ void main() { ), prefs: await _mockPrefs(), createChannelActions: (_) => actions, + channelSnapshot: () => channel, + viewerRole: 'guest', ); final emoji = find.byKey(const ValueKey('quick-reaction-👍')); final owner = tester.widget( @@ -442,8 +470,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(); 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 5e63012d12e..05cf61e7e4c 100644 --- a/mobile/test/features/channels/send_message_provider_test.dart +++ b/mobile/test/features/channels/send_message_provider_test.dart @@ -9,6 +9,87 @@ 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( + 'revoking reply permission during journaling prevents publication', + () async { + final session = _PendingPublishRelaySession(); + unawaited(session.published.then((_) => session.accept())); + final signed = Completer(); + final journalWrite = Completer(); + var allowed = true; + var localCount = 0; + final send = SendMessage( + signedEventRelay: SignedEventRelay( + session: session, + nsec: nostr.Keys.generate().nsec, + ), + fetchMembers: (_) async => const [], + readUserCache: () => const {}, + canSend: (_, reply, _) => reply && allowed, + addLocalMessage: (_, _) => localCount++, + completeLocalMessage: (_, _) {}, + removeLocalMessage: (_, _) {}, + ); + + final pending = send( + channelId: _channelId, + content: 'Reply', + parentEventId: 'root', + beforePublish: (event) { + signed.complete(event); + return journalWrite.future; + }, + ); + expect((await signed.future).content, 'Reply'); + expect(session.hasPublished, isFalse); + allowed = false; + journalWrite.complete(); + + await expectLater(pending, throwsStateError); + expect(localCount, 0); + expect(session.hasPublished, isFalse); + }, + ); + test( 'adds the signed message locally before relay acknowledgement', () async { @@ -265,6 +346,7 @@ class _PendingPublishRelaySession extends RelaySessionNotifier { late NostrEvent event; Future get published => _published.future; + bool get hasPublished => _published.isCompleted; @override SessionState build() => const SessionState(status: SessionStatus.connected); 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()), 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, ); 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)