From cb7830d63076ab971d0a1d5562f17935ddb40970 Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:38:57 -0800 Subject: [PATCH 1/2] feat(relay): add artifact conversations for task comments A NIP-AR artifact can now have a conversation: a private `artifact` channel at a UUIDv8 address derived from its `d`, filed under the artifact's home with no member rows. Anyone who may post in the home opens it with kind:9007 and an `artifact` tag; access comes only through the home. Moves refile it in the same transaction, delete closes it and restore reopens it. People and settings events are refused in it, and the home's owners and admins moderate comments. Incremental artifact sync now includes channels with a TTL. Co-Authored-By: Claude Opus 5.5 Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> --- NOSTR.md | 47 ++ crates/buzz-core/src/artifact.rs | 27 + crates/buzz-core/src/channel.rs | 19 +- crates/buzz-db/src/runtime/migration.rs | 8 +- crates/buzz-db/src/store/artifact.rs | 202 ++++++- .../src/store/artifact_postgres_tests.rs | 57 +- crates/buzz-db/src/store/artifact_sync.rs | 3 +- crates/buzz-db/src/store/channel.rs | 8 +- crates/buzz-db/src/store/channel_tree.rs | 57 +- .../sync_access_postgres_tests.rs | 47 +- .../sync_postgres_tests.rs | 2 +- crates/buzz-relay/src/handlers/artifact.rs | 89 ++- .../artifact_conversation_postgres_tests.rs | 505 ++++++++++++++++++ crates/buzz-relay/src/handlers/ingest.rs | 47 +- crates/buzz-relay/src/handlers/mod.rs | 4 +- .../handlers/parent_access_postgres_tests.rs | 38 +- .../buzz-relay/src/handlers/side_effects.rs | 31 +- crates/buzz-relay/src/nip11.rs | 5 + docs/nips/NIP-AR.md | 8 +- migrations/0091_artifact_channel_type.sql | 9 + schema/types/channel_type.sql | 2 +- 21 files changed, 1123 insertions(+), 92 deletions(-) create mode 100644 crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs create mode 100644 migrations/0091_artifact_channel_type.sql diff --git a/NOSTR.md b/NOSTR.md index 27af1ffc56b..47b6bedb175 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -253,6 +253,53 @@ the child, without joining it. `parent_access` tag beside `parent` and files the channel unnarrowed, so a client checks for it before filing a narrowed channel. +### Artifact conversations + +A NIP-AR artifact, such as a task, can have a **conversation**: a channel +for its comments. It belongs to the artifact, not to anyone who posts in it. + +- **Address.** The conversation's channel ID is derived from the artifact's + `d` alone, so every client computes the same one: take the first 16 bytes + of `SHA-256("nip-ar-conversation" || 0x00 || UTF-8(d))`, then set the + RFC 9562 version (8) and variant bits (byte 6 = `(b & 0x0f) | 0x80`, + byte 8 = `(b & 0x3f) | 0x80`). It does not change when the artifact moves. + Fixture: `d` `8c1f3d2e-4b5a-4c6d-9e7f-0a1b2c3d4e5f` gives + `3f3e3cd7-3b56-81d9-8dd2-8d8b5b1f6d57`. Version-8 channel IDs are + reserved for conversations: an ordinary kind:9007 at one is refused. +- **Opening.** kind:9007 with `["h", ]` and + `["artifact", ]`. Anyone who may post in the artifact's home may send + it; it needs the `messages:write` scope. The relay checks that `h` is the + derived address and that the artifact exists, is not deleted and lives in + that home. It then creates a private channel of type `artifact`, filed + under the home (`parent`), with no member rows: nobody owns it. Other + tags are ignored. Opening one that already exists is accepted and writes + nothing. The home must be a live, unarchived stream or forum with at most + one parent, so the conversation is at most the third level; otherwise the + relay refuses with `invalid: comments aren't available here`. An + artifact cannot itself live in a conversation. +- **Comments** are kind:9 events with the conversation's `h`. Who reads and + posts comes only from the home, through [Channel parents](#channel-parents): + the home's readers read, a view-only (`guest`) home's people read but do + not post, and a home's `parent_access` applies as it does to any child. + Comments close to new posts while the home is archived. +- **No people or settings of its own.** kind:9000, 9001, 9002, 9008, 9021 + and 9022 are refused in a conversation. The home's direct owners and + admins may delete comments with kind:9005; authors may delete their own. +- **Moves.** When the artifact moves, the conversation moves with it in the + same transaction: its parent becomes the new home, the old home's readers + lose it at once, and their live subscriptions close. A move to a home that + could not hold a conversation is refused with + `invalid: this artifact's comments can't move there`. +- **Delete and restore.** Deleting the artifact closes its conversation to + everyone: nothing in it is readable and nothing can be posted, and opening + one is refused. Restoring the artifact reopens it. +- **Hidden.** `artifact` is not a legacy channel type, so conversations are + left out of reads that name no channel ([NIP-CL](docs/nips/NIP-CL.md)). + Read them by naming the channel. +- Relays that support conversations advertise `buzz-artifact-conversations` + in NIP-11 `supported_extensions`. They also include artifacts in + auto-archiving channels in incremental artifact sync. + ### Default channels A community's owners and admins can mark a channel as a **default channel**: diff --git a/crates/buzz-core/src/artifact.rs b/crates/buzz-core/src/artifact.rs index 50e8f6070db..2d8bfb67ccf 100644 --- a/crates/buzz-core/src/artifact.rs +++ b/crates/buzz-core/src/artifact.rs @@ -165,9 +165,36 @@ pub fn validate(event: &Event) -> Result { root, }) } +/// Domain separator for [`conversation_id`]. +pub const CONVERSATION_ID_DOMAIN: &[u8] = b"nip-ar-conversation\0"; + +/// The channel ID of an artifact's conversation, derived from its `d` alone: +/// the first 16 bytes of `SHA-256("nip-ar-conversation\0" || UTF-8(d))`, with +/// the RFC 9562 version (8) and variant bits set. Anyone holding the artifact +/// can compute it, and it does not change when the artifact moves. +pub fn conversation_id(d: &str) -> Uuid { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(CONVERSATION_ID_DOMAIN); + hasher.update(d.as_bytes()); + let digest = hasher.finalize(); + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&digest[..16]); + uuid::Builder::from_custom_bytes(bytes).into_uuid() +} + #[cfg(test)] mod tests { use super::*; + + #[test] + fn conversation_id_matches_the_documented_fixture() { + let id = conversation_id("8c1f3d2e-4b5a-4c6d-9e7f-0a1b2c3d4e5f"); + assert_eq!(id.get_version_num(), 8); + assert_eq!(id.get_variant(), uuid::Variant::RFC4122); + assert_eq!(id.to_string(), "3f3e3cd7-3b56-81d9-8dd2-8d8b5b1f6d57"); + assert_ne!(id, conversation_id("8c1f3d2e-4b5a-4c6d-9e7f-0a1b2c3d4e50")); + } use nostr::{EventBuilder, Keys, Kind, Tag}; fn event(extra: Vec>, op: &str, content: &str) -> Event { let mut tags = vec![ diff --git a/crates/buzz-core/src/channel.rs b/crates/buzz-core/src/channel.rs index 3e3a7b10904..ce0d3ca95da 100644 --- a/crates/buzz-core/src/channel.rs +++ b/crates/buzz-core/src/channel.rs @@ -44,7 +44,8 @@ pub const MAX_CHANNEL_LABEL_LEN: usize = 64; /// Names a label may not take, because the channel type uses the same `t` /// tag. A label equal to one of these could make a channel look like /// another type. The list includes types that a later relay may add. -pub const RESERVED_CHANNEL_LABELS: &[&str] = &["stream", "forum", "dm", "workflow", "system"]; +pub const RESERVED_CHANNEL_LABELS: &[&str] = + &["stream", "forum", "dm", "workflow", "system", "artifact"]; /// Why a set of channel labels was refused. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -377,6 +378,11 @@ pub enum ChannelType { /// filter names it, or asks for system channels with `#t:["system"]` on /// kinds 39000-39003. System, + /// A NIP-AR artifact's conversation, such as a task's comments. Its ID is + /// derived from the artifact ([`crate::artifact::conversation_id`]), its + /// parent is the artifact's home, and it has no members or settings of + /// its own: who reads and posts comes from the home. + Artifact, } /// The channel types that every client knew before NIP-CL added new ones. @@ -401,6 +407,7 @@ impl ChannelType { Self::Dm => "dm", Self::Workflow => "workflow", Self::System => "system", + Self::Artifact => "artifact", } } @@ -409,7 +416,7 @@ impl ChannelType { /// private unless its creator asks for open. pub fn default_visibility(&self) -> ChannelVisibility { match self { - Self::System => ChannelVisibility::Private, + Self::System | Self::Artifact => ChannelVisibility::Private, Self::Stream | Self::Forum | Self::Dm | Self::Workflow => ChannelVisibility::Open, } } @@ -431,6 +438,7 @@ impl FromStr for ChannelType { "dm" => Ok(Self::Dm), "workflow" => Ok(Self::Workflow), "system" => Ok(Self::System), + "artifact" => Ok(Self::Artifact), other => Err(format!("unknown channel type: {other:?}")), } } @@ -570,6 +578,7 @@ mod tests { let _: ChannelType = name.parse().expect("legacy type parses"); } assert!(!LEGACY_CHANNEL_TYPES.contains(&ChannelType::System.as_str())); + assert!(!LEGACY_CHANNEL_TYPES.contains(&ChannelType::Artifact.as_str())); } /// Every channel type name is reserved, so a label cannot pose as a type. @@ -578,12 +587,13 @@ mod tests { /// until its name is in `RESERVED_CHANNEL_LABELS`. #[test] fn every_channel_type_name_is_a_reserved_label() { - const ALL: [ChannelType; 5] = [ + const ALL: [ChannelType; 6] = [ ChannelType::Stream, ChannelType::Forum, ChannelType::Dm, ChannelType::Workflow, ChannelType::System, + ChannelType::Artifact, ]; for channel_type in ALL { match channel_type { @@ -591,7 +601,8 @@ mod tests { | ChannelType::Forum | ChannelType::Dm | ChannelType::Workflow - | ChannelType::System => {} + | ChannelType::System + | ChannelType::Artifact => {} } assert!( RESERVED_CHANNEL_LABELS.contains(&channel_type.as_str()), diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 46c87d57c4d..53b560af692 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -902,7 +902,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 90); + assert_eq!(migrations.len(), 91); assert!(migrations[83] .sql .as_str() @@ -940,6 +940,12 @@ mod postgres_tests { assert!(parent_access .contains("ADD COLUMN IF NOT EXISTS parent_access TEXT NOT NULL DEFAULT 'member'")); assert!(!parent_access.to_ascii_uppercase().contains("UPDATE ")); + // Artifact conversations (0091): one additive enum value. + let artifact_type = strip_sql_comments(migrations[90].sql.as_str()); + assert_eq!( + artifact_type.trim(), + "ALTER TYPE channel_type ADD VALUE IF NOT EXISTS 'artifact';" + ); for (index, migration) in migrations.iter().enumerate() { assert_eq!(migration.version, (index + 1) as i64); } diff --git a/crates/buzz-db/src/store/artifact.rs b/crates/buzz-db/src/store/artifact.rs index 6f9f46eb174..c80dec1dea1 100644 --- a/crates/buzz-db/src/store/artifact.rs +++ b/crates/buzz-db/src/store/artifact.rs @@ -14,9 +14,16 @@ use uuid::Uuid; /// which the caller discloses after authorizing its channel. #[derive(Debug)] pub enum ArtifactOutcome { - /// Accepted once; stored events to publish (the revision, plus the source - /// removal on a move). - Accepted(Vec), + /// Accepted once. + Accepted { + /// Stored events to publish (the revision, plus the source removal on + /// a move). + events: Vec, + /// The artifact's conversation, when this revision changed who may + /// read it (a move, delete or restore). Its readers' caches and live + /// subscriptions need refreshing after commit. + conversation: Option, + }, /// Identical previously accepted event; no repeated side effects. Duplicate, /// `prev` or identity no longer matches; the client should reconcile. @@ -25,6 +32,23 @@ pub enum ArtifactOutcome { Rejected(&'static str), } +/// Outcome of a request to open an artifact's conversation. +#[derive(Debug)] +pub enum ConversationOutcome { + /// Created, with the stored kind:9007 to publish. + Created(Box), + /// It already existed; nothing was written. + Exists, + /// The artifact is missing, deleted, or not in the home the caller + /// authorized. Answered like a missing artifact. + Unavailable, + /// Refused with a public-safe reason. + Rejected(&'static str), +} + +/// Refusal for a move that would take a conversation where none may be. +pub const CONVERSATION_CANNOT_MOVE: &str = "this artifact's comments can't move there"; + /// Conflict for a non-create revision whose artifact is missing or lives /// outside every channel the sender was authorized for. pub const HEAD_UNAVAILABLE: &str = "artifact head unavailable"; @@ -173,6 +197,21 @@ impl Db { } } } + if source != Some(env.home) { + // A conversation holds comments, never artifacts. + let home_type: Option = sqlx::query_scalar( + "SELECT channel_type::text FROM channels WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(env.home) + .fetch_optional(tx.conn()) + .await?; + if home_type.as_deref() == Some(buzz_core::channel::ChannelType::Artifact.as_str()) { + return Ok(ArtifactOutcome::Rejected( + "an artifact cannot live in a conversation", + )); + } + } if head.is_none() || env.root != old_root || source != Some(env.home) { if let Some(root) = &env.root { let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2 AND channel_id=$3 AND deleted_at IS NULL AND kind IN (9,40002,45001,45003))") @@ -195,6 +234,16 @@ impl Db { .await?; sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted,modified_at) VALUES ($1,$2,$3,$4,$5,$6,$7,clock_timestamp()) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted,modified_at=clock_timestamp()") .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(env.home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).execute(tx.conn()).await?; + let conversation = match env.op { + ArtifactOp::Move | ArtifactOp::Delete | ArtifactOp::Restore => { + match follow_artifact(&mut tx, env).await? { + Follow::Unchanged => None, + Follow::Changed(id) => Some(id), + Follow::Refused(reason) => return Ok(ArtifactOutcome::Rejected(reason)), + } + } + _ => None, + }; let (stored, _) = crate::event::insert_event_in_transaction(&mut tx, event, Some(env.home)).await?; crate::insert_mentions_in_transaction(&mut tx, event, Some(env.home)).await?; @@ -206,6 +255,151 @@ impl Db { accepted.push(stored); } tx.commit().await?; - Ok(ArtifactOutcome::Accepted(accepted)) + Ok(ArtifactOutcome::Accepted { + events: accepted, + conversation, + }) + } + + /// Open `artifact`'s conversation with the kind:9007 `event`, whose `h` + /// the caller checked is [`buzz_core::artifact::conversation_id`]. The + /// caller authorized the sender to post in `authorized_home`; the + /// artifact must live there and not be deleted. The conversation is a + /// private `artifact` channel filed under the home, with no members: + /// everyone reaches it through the home. Opening one that exists writes + /// nothing. + pub async fn ensure_artifact_conversation( + &self, + community: CommunityId, + event: &Event, + artifact: Uuid, + authorized_home: Uuid, + ) -> Result { + let conversation = buzz_core::artifact::conversation_id(&artifact.to_string()); + let mut tx = self.begin_event_write_transaction(community).await?; + sqlx::query("SET LOCAL statement_timeout='5s'") + .execute(tx.conn()) + .await?; + // The artifact's own lock: a revision that moves or deletes it waits. + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") + .bind(format!("artifact:{}:{}", community.as_uuid(), artifact)) + .execute(tx.conn()) + .await?; + let head: Option<(Uuid, bool)> = sqlx::query_as( + "SELECT channel_id, deleted FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2", + ) + .bind(community.as_uuid()) + .bind(artifact) + .fetch_optional(tx.conn()) + .await?; + let Some((home, false)) = head else { + return Ok(ConversationOutcome::Unavailable); + }; + if home != authorized_home { + return Ok(ConversationOutcome::Unavailable); + } + let existing: Option = sqlx::query_scalar( + "SELECT channel_type::text FROM channels WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(conversation) + .fetch_optional(tx.conn()) + .await?; + match existing.as_deref() { + None => {} + Some(t) if t == buzz_core::channel::ChannelType::Artifact.as_str() => { + return Ok(ConversationOutcome::Exists) + } + // Ingest refuses other channels at derived addresses; one made + // before that rule is never treated as the conversation. + Some(_) => { + return Ok(ConversationOutcome::Rejected( + "conversation address is taken", + )) + } + } + if let Some(reason) = crate::channel_tree::refuse_conversation_home(&mut tx, home).await? { + return Ok(ConversationOutcome::Rejected(reason)); + } + sqlx::query( + "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by, parent_id) \ + VALUES ($1, $2, $3, 'artifact', 'private', $4, $5)", + ) + .bind(conversation) + .bind(community.as_uuid()) + .bind(artifact.to_string()) + .bind(event.pubkey.to_bytes().as_slice()) + .bind(home) + .execute(tx.conn()) + .await?; + let (stored, _) = + crate::event::insert_event_in_transaction(&mut tx, event, Some(conversation)).await?; + tx.commit().await?; + Ok(ConversationOutcome::Created(Box::new(stored))) + } +} + +/// What a move, delete or restore did to the artifact's conversation. +enum Follow { + /// There is no conversation. + Unchanged, + /// The conversation was refiled or its access changed. + Changed(Uuid), + /// The conversation cannot follow, so the revision is refused. + Refused(&'static str), +} + +/// Keep `env`'s conversation, if it has one, with its artifact, on the +/// revision's transaction. A move refiles it under the new home, a delete +/// closes it to the home's readers (`parent_access = 'none'`; it has no rows +/// of its own), and a restore reopens it. +async fn follow_artifact(tx: &mut crate::AdmittedTx, env: &ArtifactEnvelope) -> Result { + let community = tx.community(); + let conversation = buzz_core::artifact::conversation_id(&env.id.to_string()); + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM channels WHERE community_id=$1 AND id=$2 \ + AND channel_type='artifact')", + ) + .bind(community.as_uuid()) + .bind(conversation) + .fetch_one(tx.conn()) + .await?; + if !exists { + return Ok(Follow::Unchanged); + } + match env.op { + ArtifactOp::Move => { + if crate::channel_tree::refuse_conversation_home(tx, env.home) + .await? + .is_some() + { + return Ok(Follow::Refused(CONVERSATION_CANNOT_MOVE)); + } + sqlx::query( + "UPDATE channels SET parent_id=$3, updated_at=NOW() WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(conversation) + .bind(env.home) + .execute(tx.conn()) + .await?; + } + ArtifactOp::Delete | ArtifactOp::Restore => { + let access = if env.op == ArtifactOp::Delete { + crate::channel_tree::ParentAccess::NoAccess + } else { + crate::channel_tree::ParentAccess::Member + }; + sqlx::query( + "UPDATE channels SET parent_access=$3, updated_at=NOW() WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(conversation) + .bind(access.as_str()) + .execute(tx.conn()) + .await?; + } + _ => return Ok(Follow::Unchanged), } + Ok(Follow::Changed(conversation)) } diff --git a/crates/buzz-db/src/store/artifact_postgres_tests.rs b/crates/buzz-db/src/store/artifact_postgres_tests.rs index 3b422f40bf0..d8be9b92812 100644 --- a/crates/buzz-db/src/store/artifact_postgres_tests.rs +++ b/crates/buzz-db/src/store/artifact_postgres_tests.rs @@ -130,14 +130,14 @@ async fn lifecycle_cas_queries_move_redaction_and_retention() { let create = f.revision(d, "create", f.a, None, &f.owner, project("A")); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let x = f.revision(d, "update", f.a, Some(&create), &f.owner, project("B")); let y = f.revision(d, "update", f.a, Some(&create), &f.peer, project("B")); let (rx, ry) = tokio::join!(f.accept(&x, None), f.accept(&y, None)); let head = match (rx, ry) { - (ArtifactOutcome::Accepted(_), ArtifactOutcome::Conflict(..)) => &x, - (ArtifactOutcome::Conflict(..), ArtifactOutcome::Accepted(_)) => &y, + (ArtifactOutcome::Accepted { .. }, ArtifactOutcome::Conflict(..)) => &x, + (ArtifactOutcome::Conflict(..), ArtifactOutcome::Accepted { .. }) => &y, other => panic!("exactly one CAS winner: {other:?}"), }; assert!(matches!( @@ -161,7 +161,7 @@ async fn lifecycle_cas_queries_move_redaction_and_retention() { ); assert!(matches!( f.accept(&wrong, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); assert_eq!(f.count(&f.owner, current("B")).await, 0); @@ -171,7 +171,7 @@ async fn lifecycle_cas_queries_move_redaction_and_retention() { f.accept(&moved, Some(f.b)).await, ArtifactOutcome::Conflict(..) )); - let ArtifactOutcome::Accepted(stored) = f.accept(&moved, Some(f.a)).await else { + let ArtifactOutcome::Accepted { events: stored, .. } = f.accept(&moved, Some(f.a)).await else { panic!("move accepted"); }; let removal = &stored[1]; @@ -231,7 +231,7 @@ async fn lifecycle_cas_queries_move_redaction_and_retention() { let deleted = f.revision(d, "delete", f.b, Some(&moved), &f.owner, vec![]); assert!(matches!( f.accept(&deleted, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); assert_eq!(f.count(&f.owner, all.clone()).await, 0); let update = f.revision(d, "update", f.b, Some(&deleted), &f.owner, vec![]); @@ -242,7 +242,7 @@ async fn lifecycle_cas_queries_move_redaction_and_retention() { let restore = f.revision(d, "restore", f.b, Some(&deleted), &f.peer, vec![]); assert!(matches!( f.accept(&restore, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); assert_eq!(f.count(&f.owner, all.clone()).await, 1); // Reads observe removed private membership. @@ -278,7 +278,7 @@ async fn system_channel_artifacts_are_read_only_by_name() { let create = f.revision(Uuid::new_v4(), "create", home, None, &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); } for reader in [&f.owner, &f.peer] { @@ -329,7 +329,7 @@ async fn unlisted_channel_artifacts_are_read_by_name_for_non_members() { let create = f.revision(Uuid::new_v4(), "create", home, None, &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); } let unnamed = serde_json::json!({"artifact":"current"}); @@ -380,12 +380,12 @@ async fn artifacts_of_a_later_channel_type_are_read_only_by_name() { let create = f.revision(d, "create", home, None, &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let update = f.revision(d, "update", home, Some(&create), &f.owner, vec![]); assert!(matches!( f.accept(&update, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); ds.push(d.to_string()); } @@ -420,7 +420,7 @@ async fn repeated_moves_get_distinct_source_safe_markers() { let again = f.revision(d, "move", f.b, Some(&back), &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let mut markers = Vec::new(); for (event, source, replaced) in [ @@ -428,7 +428,8 @@ async fn repeated_moves_get_distinct_source_safe_markers() { (&back, f.b, &there), (&again, f.a, &back), ] { - let ArtifactOutcome::Accepted(stored) = f.accept(event, Some(source)).await else { + let ArtifactOutcome::Accepted { events: stored, .. } = f.accept(event, Some(source)).await + else { panic!("move accepted"); }; let marker = stored[1].event.clone(); @@ -477,7 +478,7 @@ async fn root_anchor_and_tenant_boundaries() { let create = f.revision(d, "create", f.a, None, &f.owner, root()); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); // Later loss of the anchor does not block edits that keep it. sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") @@ -489,7 +490,7 @@ async fn root_anchor_and_tenant_boundaries() { let update = f.revision(d, "update", f.a, Some(&create), &f.peer, root()); assert!(matches!( f.accept(&update, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let bad_delete = f.revision(d, "delete", f.a, Some(&update), &f.owner, vec![]); assert!(matches!( @@ -505,7 +506,7 @@ async fn root_anchor_and_tenant_boundaries() { let same_id = other.revision(d, "create", other.a, None, &other.owner, vec![]); assert!(matches!( other.accept(&same_id, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); assert_eq!( other @@ -531,8 +532,8 @@ async fn concurrent_artifacts_on_ttl_channel_commit() { let a = f.revision(Uuid::new_v4(), "create", f.a, None, &f.owner, vec![]); let b = f.revision(Uuid::new_v4(), "create", f.a, None, &f.peer, vec![]); let (a, b) = tokio::join!(f.accept(&a, None), f.accept(&b, None)); - assert!(matches!(a, ArtifactOutcome::Accepted(_))); - assert!(matches!(b, ArtifactOutcome::Accepted(_))); + assert!(matches!(a, ArtifactOutcome::Accepted { .. })); + assert!(matches!(b, ArtifactOutcome::Accepted { .. })); let live: bool = sqlx::query_scalar( "SELECT ttl_deadline>now() FROM channels WHERE community_id=$1 AND id=$2", ) @@ -602,14 +603,14 @@ async fn head_outside_authorized_channel_matches_missing_head() { let create = f.revision(d, "create", f.a, None, &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let gone = Uuid::new_v4(); let deleted_d = Uuid::new_v4(); let deleted_create = f.revision(deleted_d, "create", f.a, None, &f.owner, vec![]); assert!(matches!( f.accept(&deleted_create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let deleted = f.revision( deleted_d, @@ -621,7 +622,7 @@ async fn head_outside_authorized_channel_matches_missing_head() { ); assert!(matches!( f.accept(&deleted, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let retyped = { let mut tags: Vec> = vec![ @@ -688,7 +689,7 @@ async fn head_outside_authorized_channel_matches_missing_head() { let update = f.revision(d, "update", f.a, Some(&create), &f.peer, vec![]); assert!(matches!( f.accept(&update, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); } @@ -707,7 +708,7 @@ async fn sync_snapshot_pages_are_one_cut_and_head_includes_deletions() { let create = f.revision(*d, "create", f.a, None, &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); heads.push(create); } @@ -715,7 +716,7 @@ async fn sync_snapshot_pages_are_one_cut_and_head_includes_deletions() { let deleted = f.revision(ids[4], "delete", f.a, Some(&heads[4]), &f.owner, vec![]); assert!(matches!( f.accept(&deleted, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let reader = f.owner.public_key(); let mut snapshot = @@ -735,7 +736,7 @@ async fn sync_snapshot_pages_are_one_cut_and_head_includes_deletions() { let late_create = f.revision(late, "create", f.a, None, &f.owner, vec![]); assert!(matches!( f.accept(&late_create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let mut seen: Vec<_> = first.iter().map(|e| e.event.id).collect(); loop { @@ -814,7 +815,7 @@ async fn sync_snapshot_pages_are_one_cut_and_head_includes_deletions() { let create = f.revision(private, "create", f.b, None, &f.owner, vec![]); assert!(matches!( f.accept(&create, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); assert!(f .db @@ -874,7 +875,7 @@ async fn artifacts_are_read_synced_and_revoked_through_a_parent() { for event in [&in_child, &in_hidden] { assert!(matches!( f.accept(event, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); } let unnamed = serde_json::json!({"artifact":"current"}); @@ -984,7 +985,7 @@ async fn a_restricted_childs_artifacts_stay_hidden_from_the_project() { let in_child = f.revision(artifact, "create", f.b, None, &f.owner, vec![]); assert!(matches!( f.accept(&in_child, None).await, - ArtifactOutcome::Accepted(_) + ArtifactOutcome::Accepted { .. } )); let ids = |events: Vec| { events.into_iter().map(|e| e.event.id).collect::>() diff --git a/crates/buzz-db/src/store/artifact_sync.rs b/crates/buzz-db/src/store/artifact_sync.rs index 43035fa6e2a..c6c03610dc8 100644 --- a/crates/buzz-db/src/store/artifact_sync.rs +++ b/crates/buzz-db/src/store/artifact_sync.rs @@ -140,7 +140,6 @@ impl Db { let mut qb = QueryBuilder::new("SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id FROM events e "); super::artifact_query::predicates(&mut qb, community, reader, query); qb.push(" AND a.artifact_id=ANY(").push_bind(ids).push(")"); - qb.push(" AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.ttl_seconds IS NULL)"); qb.push(" LIMIT ").push_bind(PAGE_ROWS as i64); let mut events = Vec::new(); let mut bytes = 0; @@ -176,7 +175,7 @@ const CANDIDATES: &str = concat!( r#" WITH readable AS NOT MATERIALIZED ( SELECT c.id FROM channels c - WHERE c.community_id=$1 AND c.deleted_at IS NULL AND c.ttl_seconds IS NULL + WHERE c.community_id=$1 AND c.deleted_at IS NULL AND (NOT $12::boolean OR c.id=ANY($9)) AND (c.channel_type::text=ANY($11) OR c.id=ANY($9)) AND ((c.visibility='open' AND (NOT c.unlisted OR c.id=ANY($9))) OR EXISTS ( diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index 89670818a47..30e2f9beaeb 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -872,9 +872,11 @@ pub fn group_metadata_tags(channel: &ChannelRecord, members: &[MemberRecord]) -> tags.push(tag(&["restricted"])); } // NIP-29 hidden tag: hide metadata from non-members. Set for DMs and - // for private system channels. Not a security boundary — access control - // is handled by channel-scoped storage. - if channel.channel_type == ChannelType::System.as_str() && !open { + // for private system channels and artifact conversations. Not a security + // boundary — access control is handled by channel-scoped storage. + let hidden_type = channel.channel_type == ChannelType::System.as_str() + || channel.channel_type == ChannelType::Artifact.as_str(); + if hidden_type && !open { tags.push(tag(&["hidden"])); } if group_metadata_uses_members(channel) { diff --git a/crates/buzz-db/src/store/channel_tree.rs b/crates/buzz-db/src/store/channel_tree.rs index e675cd524b5..031dfd1f13d 100644 --- a/crates/buzz-db/src/store/channel_tree.rs +++ b/crates/buzz-db/src/store/channel_tree.rs @@ -577,6 +577,58 @@ pub(crate) async fn decide_parent_change( Ok(()) } +/// Why a channel cannot hold an artifact's conversation. +pub const CONVERSATION_HOME_REFUSED: &str = + "comments aren't available here: only a stream or forum at most two levels deep can hold them"; + +/// Lock, on `tx`, the channel that holds or will hold an artifact's +/// conversation, and its parents nearest first (`FOR NO KEY UPDATE`, as +/// [`decide_parent_change`] locks a new parent's chain), and say why it +/// cannot hold one. A conversation is filed under its artifact's home, so the +/// home must be a live, unarchived stream or forum with at most one parent: +/// the conversation is then at most the third level. Filing the home or one +/// of its parents elsewhere counts the conversation in the subtree height, +/// and waits on these locks, so the depth cannot change before commit. +pub(crate) async fn refuse_conversation_home( + tx: &mut crate::AdmittedTx, + home: Uuid, +) -> Result> { + let community_id = tx.community(); + let mut levels = 0; + let mut next = Some(home); + while let Some(id) = next { + if levels == MAX_ANCESTORS { + return Ok(Some(CONVERSATION_HOME_REFUSED)); + } + let row = sqlx::query( + "SELECT channel_type::text AS channel_type, archived_at IS NOT NULL AS archived, \ + deleted_at IS NOT NULL AS deleted, parent_id \ + FROM channels WHERE community_id = $1 AND id = $2 FOR NO KEY UPDATE", + ) + .bind(community_id.as_uuid()) + .bind(id) + .fetch_optional(tx.conn()) + .await?; + let Some(row) = row else { + return Ok(Some(CONVERSATION_HOME_REFUSED)); + }; + if id == home { + let channel_type: String = row.try_get("channel_type")?; + if !PARENTABLE_CHANNEL_TYPES.contains(&channel_type.as_str()) + || row.try_get::("deleted")? + { + return Ok(Some(CONVERSATION_HOME_REFUSED)); + } + if row.try_get::("archived")? { + return Ok(Some("channel is archived")); + } + } + levels += 1; + next = row.try_get("parent_id")?; + } + Ok(None) +} + /// Decide, on `tx`, whether `actor` may change `channel_id`'s /// `parent_access`: only a direct owner or admin row may. The caller holds /// the channel's row lock. Either direction changes who reads the channel @@ -655,12 +707,13 @@ fn refuse_auto_archiving_project(has_parent: bool, has_live_children: bool) -> R )) } -/// Whether `channel_id` has a live child. +/// Whether `channel_id` has a live child. An artifact's conversation is not +/// one: holding a task's comments does not make a channel a project. async fn has_live_children(tx: &mut crate::AdmittedTx, channel_id: Uuid) -> Result { let community_id = tx.community(); Ok(sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM channels WHERE community_id = $1 AND parent_id = $2 \ - AND deleted_at IS NULL)", + AND deleted_at IS NULL AND channel_type <> 'artifact')", ) .bind(community_id.as_uuid()) .bind(channel_id) diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs index 89f08e9338d..8538196557c 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs @@ -126,7 +126,7 @@ async fn sync_rejoin_replays_old_heads_without_resetting_on_task_edits() { #[tokio::test] #[ignore = "requires Postgres"] -async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { +async fn sync_includes_auto_archiving_channels_and_resets_on_ttl_changes() { let _guard = SERIAL.lock().await; let f = fixture().await; let permanent_id = Uuid::new_v4(); @@ -171,13 +171,30 @@ async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { let expiring_id = Uuid::new_v4(); let expiring = f.revision_as(&f.owner, f.private, expiring_id, "create", None); accept(&f, &expiring).await; - for checkpoint in [None, Some(&next["checkpoint"])] { - let page = sync(&f, checkpoint).await; - assert_eq!(page["changes"].as_array().unwrap().len(), 1); - assert_eq!(page["changes"][0]["artifactId"], permanent_id.to_string()); - assert_eq!(page["changes"][0]["type"], "upsert"); - assert!(page["checkpoint"].is_string()); - } + // An auto-archiving channel's artifacts sync like any other. + let ids = |page: &serde_json::Value| { + let mut ids: Vec<(String, String)> = page["changes"] + .as_array() + .unwrap() + .iter() + .map(|c| { + ( + c["artifactId"].as_str().unwrap().to_owned(), + c["type"].as_str().unwrap().to_owned(), + ) + }) + .collect(); + ids.sort(); + ids + }; + let upsert = |id: Uuid| (id.to_string(), "upsert".to_owned()); + let mut both = vec![upsert(permanent_id), upsert(expiring_id)]; + both.sort(); + let initial = sync(&f, None).await; + assert_eq!(ids(&initial), both); + // A checkpoint replays its overlap, so the permanent artifact repeats. + let delta = sync(&f, Some(&next["checkpoint"])).await; + assert_eq!(ids(&delta), both); let (status, current) = f .request( "/query", @@ -188,11 +205,7 @@ async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { ) .await; assert!(status.is_success(), "{status}: {current}"); - assert_eq!(current["changes"][0]["type"], "upsert"); - assert_eq!( - current["changes"][1], - json!({"type":"remove","artifactId":expiring_id}) - ); + assert_eq!(ids(¤t), both); let (status, named) = f .request( "/query", @@ -202,14 +215,12 @@ async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { ) .await; assert!(status.is_success(), "{status}: {named}"); - assert_eq!(named["changes"], json!([])); + assert_eq!(ids(&named), vec![upsert(expiring_id)]); + // A move into an auto-archiving channel is an upsert there, not a removal. let moved = f.revision_as(&f.owner, f.private, permanent_id, "move", Some(&permanent)); accept(&f, &moved).await; let delta = sync(&f, Some(&next["checkpoint"])).await; - assert_eq!( - delta["changes"], - json!([{"type":"remove","artifactId":permanent_id}]) - ); + assert_eq!(ids(&delta), both); let (status, scoped) = f .request( "/query", diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs index db76a358c54..c3cb82e32a8 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs @@ -49,7 +49,7 @@ async fn accept(f: &Fixture, event: &Event) { ) .await .unwrap(), - buzz_db::artifact::ArtifactOutcome::Accepted(_) + buzz_db::artifact::ArtifactOutcome::Accepted { .. } )); } diff --git a/crates/buzz-relay/src/handlers/artifact.rs b/crates/buzz-relay/src/handlers/artifact.rs index c52e71d6d4d..1bfc17c29ed 100644 --- a/crates/buzz-relay/src/handlers/artifact.rs +++ b/crates/buzz-relay/src/handlers/artifact.rs @@ -3,7 +3,7 @@ use super::ingest::{IngestAuth, IngestError, IngestResult}; use crate::state::AppState; use buzz_core::artifact::ArtifactOp; use buzz_core::{StoredEvent, TenantContext}; -use buzz_db::artifact::ArtifactOutcome; +use buzz_db::artifact::{ArtifactOutcome, ConversationOutcome}; use nostr::Event; use std::sync::Arc; @@ -48,7 +48,18 @@ pub(crate) async fn accept( .await .map_err(|e| IngestError::Internal(format!("artifact storage: {e}")))?; match outcome { - ArtifactOutcome::Accepted(events) => { + ArtifactOutcome::Accepted { + events, + conversation, + } => { + if let Some(conversation) = conversation { + super::side_effects::artifact_conversation_access_changed( + tenant, + state, + conversation, + ) + .await; + } for stored in &events { publish(state, tenant, stored).await; } @@ -68,6 +79,80 @@ pub(crate) async fn accept( }) } +/// The tag on a kind:9007 that opens an artifact's conversation and names +/// the artifact. +pub(crate) const CONVERSATION_ARTIFACT_TAG: &str = "artifact"; + +/// Whether a kind:9007 opens an artifact's conversation. +pub(crate) fn opens_conversation(event: &Event) -> bool { + event + .tags + .iter() + .any(|t| t.kind().to_string() == CONVERSATION_ARTIFACT_TAG) +} + +/// Kinds refused in an artifact's conversation: it has no members or +/// settings of its own (add, remove, edit, delete, join, leave). +pub(crate) fn conversation_refuses_kind(kind: u32) -> bool { + matches!(kind, 9000 | 9001 | 9002 | 9008 | 9021 | 9022) +} + +/// Open the conversation of the artifact named by a kind:9007's `artifact` +/// tag, at the address derived from it (`h`). Anyone who may post in the +/// artifact's home may; the channel is filed under the home, with no +/// members, so nobody owns it. Opening one that exists is accepted and +/// writes nothing. +pub(crate) async fn open_conversation( + state: &Arc, + tenant: &TenantContext, + event: &Event, + auth: &IngestAuth, +) -> Result { + let invalid = |m: &str| IngestError::Rejected(format!("invalid: {m}")); + let mut tags = event + .tags + .iter() + .filter(|t| t.kind().to_string() == CONVERSATION_ARTIFACT_TAG); + let (Some(tag), None) = (tags.next(), tags.next()) else { + return Err(invalid("exactly one artifact tag is required")); + }; + let d = tag.content().unwrap_or_default(); + let artifact = buzz_core::artifact::canonical_uuid(d).map_err(invalid)?; + let conversation = buzz_core::artifact::conversation_id(d); + if super::ingest::extract_channel_id(event) != Some(conversation) { + return Err(invalid("h must be the artifact's conversation address")); + } + let home = state + .db + .artifact_home(tenant.community(), artifact) + .await + .map_err(|e| IngestError::Internal(format!("artifact storage: {e}")))? + .ok_or_else(head_unavailable)?; + // A home the sender cannot post in answers like a missing artifact. + super::ingest::check_channel_write(tenant, state, auth, home) + .await + .map_err(|e| match e { + IngestError::Internal(_) => e, + _ => head_unavailable(), + })?; + let outcome = state + .db + .ensure_artifact_conversation(tenant.community(), event, artifact, home) + .await + .map_err(|e| IngestError::Internal(format!("artifact storage: {e}")))?; + match outcome { + ConversationOutcome::Created(stored) => publish(state, tenant, &stored).await, + ConversationOutcome::Exists => {} + ConversationOutcome::Unavailable => return Err(head_unavailable()), + ConversationOutcome::Rejected(message) => return Err(invalid(message)), + } + Ok(IngestResult { + event_id: event.id.to_hex(), + accepted: true, + message: String::new(), + }) +} + fn head_unavailable() -> IngestError { IngestError::CanvasConflict(format!("conflict: {}", buzz_db::artifact::HEAD_UNAVAILABLE)) } diff --git a/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs new file mode 100644 index 00000000000..d334d90b90e --- /dev/null +++ b/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs @@ -0,0 +1,505 @@ +//! Postgres-backed tests for artifact conversations (NOSTR.md, Artifact +//! conversations): a task's comments live in a channel at an address derived +//! from the task, filed under the task's home, with no members of its own. +//! Every step goes through the real ingest, REQ and COUNT paths. + +use std::sync::Arc; + +use buzz_core::TenantContext; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use uuid::Uuid; + +use buzz_auth::Scope; + +use crate::handlers::group_state_postgres_tests::{create_channel, edit_channel, test_conn}; +use crate::handlers::ingest::{ingest_event, HttpAuthMethod, IngestAuth}; +use crate::handlers::parent_access_postgres_tests::{ + add, auto_archive, count_named, post, read_implicit, read_named, role_in, set_parent, + set_parent_access, Tree, +}; +use crate::state::AppState; + +/// Ingest `event` as its signer; `Err` carries the refusal. +async fn send(state: &Arc, tenant: &TenantContext, event: Event) -> Result<(), String> { + let auth = IngestAuth::Http { + pubkey: event.pubkey, + scopes: vec![ + Scope::ChannelsWrite, + Scope::MessagesWrite, + Scope::AdminChannels, + Scope::ChannelsRead, + ], + auth_method: HttpAuthMethod::Nip98, + }; + match ingest_event(state, tenant, event, auth).await { + Ok(result) if result.accepted => Ok(()), + Ok(result) => Err(result.message), + Err(error) => Err(format!("{error:?}")), + } +} + +/// A `buzz.task` revision of `id` in `home`, signed by `key`. +fn task(key: &Keys, home: Uuid, id: Uuid, op: &str, prev: Option<&Event>) -> Event { + let mut tags = vec![ + vec!["ar".to_owned(), "1".into()], + vec!["d".into(), id.to_string()], + vec!["h".into(), home.to_string()], + vec!["type".into(), "buzz.task".into()], + vec!["op".into(), op.into()], + ]; + if op != "delete" { + tags.push(vec!["title".into(), "Review".into()]); + } + if let Some(prev) = prev { + tags.push(vec!["prev".into(), prev.id.to_hex()]); + } + EventBuilder::new(Kind::Custom(45010), if op == "delete" { "" } else { "x" }) + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .sign_with_keys(key) + .unwrap() +} + +/// Create a task in `home` as `key`: its ID and create revision. +async fn create_task( + state: &Arc, + tenant: &TenantContext, + key: &Keys, + home: Uuid, +) -> (Uuid, Event) { + let id = Uuid::new_v4(); + let event = task(key, home, id, "create", None); + send(state, tenant, event.clone()) + .await + .expect("create task"); + (id, event) +} + +/// A kind:9007 opening `artifact`'s conversation at `h`. +fn open_event(key: &Keys, artifact: &str, h: Uuid) -> Event { + EventBuilder::new(Kind::Custom(9007), "") + .tags([ + Tag::parse(["h", &h.to_string()]).unwrap(), + Tag::parse(["artifact", artifact]).unwrap(), + ]) + .sign_with_keys(key) + .unwrap() +} + +/// Open `artifact`'s conversation as `key`, at its derived address. +async fn open( + state: &Arc, + tenant: &TenantContext, + key: &Keys, + artifact: Uuid, +) -> Result { + let conversation = buzz_core::artifact::conversation_id(&artifact.to_string()); + send( + state, + tenant, + open_event(key, &artifact.to_string(), conversation), + ) + .await + .map(|()| conversation) +} + +/// A kind:9005 by `actor` deleting `target` in `channel`. +async fn moderate( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + channel: Uuid, + target: &str, +) -> Result<(), String> { + let event = EventBuilder::new(Kind::Custom(9005), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["e", target]).unwrap(), + ]) + .sign_with_keys(actor) + .unwrap(); + send(state, tenant, event).await +} + +/// Register `reader` as a connected client subscribed to `channel`; its +/// connection ID. +fn subscribe(state: &Arc, tenant: &TenantContext, reader: &Keys, channel: Uuid) -> Uuid { + let (conn, _rx) = test_conn(tenant, reader); + let conn_id = conn.conn_id; + let (tx, _rx) = tokio::sync::mpsc::channel(32); + state.conn_manager.register( + conn_id, + tx, + tokio::sync::mpsc::channel(4).0, + tokio::sync::mpsc::channel(1).0, + None, + tokio_util::sync::CancellationToken::new(), + tenant.community(), + Arc::new(std::sync::atomic::AtomicU8::new(0)), + Arc::new(tokio::sync::Mutex::new(Default::default())), + 3, + crate::state::CommunityConnectionControl::new(tokio_util::sync::CancellationToken::new()), + ); + state + .conn_manager + .set_authenticated_pubkey(conn_id, reader.public_key().to_bytes().to_vec()); + let filter = serde_json::json!({"kinds": [9], "#h": [channel.to_string()]}); + state.sub_registry.register_scoped( + tenant.community(), + conn_id, + "comments".into(), + vec![serde_json::from_value(filter).expect("filter")], + Some(channel), + ); + conn_id +} + +fn subscribed(state: &AppState, tenant: &TenantContext, channel: Uuid, conn_id: Uuid) -> bool { + state + .sub_registry + .channel_subscriber_conns_scoped(tenant.community(), channel) + .contains(&conn_id) +} + +/// Anyone who may post in a task's home opens its conversation, which is a +/// private `artifact` channel filed under the home that nobody owns. The +/// home's readers read and comment through the home; an outsider does +/// nothing. It is hidden from reads that name no channel. Opening is +/// idempotent, and only the derived address works. +/// Mutation: drop the derivation check in `open_conversation`, or the home +/// write check → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_home_reader_opens_and_comments_in_a_tasks_conversation() { + let t = Tree::new("conversation-open").await; + let (state, tenant) = (&t.state, &t.tenant); + let (id, _) = create_task(state, tenant, &t.owner, t.child).await; + + let wrong = Uuid::new_v4(); + assert!( + send(state, tenant, open_event(&t.reader, &id.to_string(), wrong)) + .await + .is_err(), + "only the derived address opens it" + ); + assert!( + open(state, tenant, &t.outsider, id).await.is_err(), + "an outsider cannot open it" + ); + let conversation = open(state, tenant, &t.reader, id) + .await + .expect("a project reader opens it"); + open(state, tenant, &t.owner, id) + .await + .expect("opening again is accepted"); + + let channel = state + .db + .get_channel_for_event_write(tenant.community(), conversation) + .await + .expect("conversation"); + assert_eq!(channel.channel_type, "artifact"); + assert_eq!(channel.visibility, "private"); + assert_eq!(channel.parent_id, Some(t.child)); + assert_eq!(role_in(state, tenant, conversation, &t.reader).await, None); + assert_eq!(role_in(state, tenant, conversation, &t.owner).await, None); + + let comment = post(state, tenant, &t.reader, conversation) + .await + .expect("a project reader comments"); + let reply = post(state, tenant, &t.owner, conversation) + .await + .expect("the home's owner comments"); + let mut both = vec![comment.clone(), reply.clone()]; + both.sort(); + for reader in [&t.reader, &t.owner] { + let mut read = read_named(state, tenant, reader, conversation).await; + read.sort(); + assert_eq!(read, both); + assert_eq!( + count_named(state, tenant, reader, conversation).await, + Some(2) + ); + let implicit = read_implicit(state, tenant, reader).await; + assert!( + !implicit.contains(&comment) && !implicit.contains(&reply), + "comments are left out of reads that name no channel" + ); + } + assert!(read_named(state, tenant, &t.outsider, conversation) + .await + .is_empty()); + assert!(post(state, tenant, &t.outsider, conversation) + .await + .is_err()); +} + +/// A view-only home lets its project read a task's comments but not add any +/// or open a conversation. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_view_only_home_reads_comments_but_cannot_add_them() { + let t = Tree::new("conversation-guest").await; + let (state, tenant) = (&t.state, &t.tenant); + let (id, _) = create_task(state, tenant, &t.owner, t.child).await; + let (other, _) = create_task(state, tenant, &t.owner, t.child).await; + let conversation = open(state, tenant, &t.owner, id).await.unwrap(); + let comment = post(state, tenant, &t.owner, conversation).await.unwrap(); + + set_parent_access(state, tenant, &t.owner, t.child, "guest") + .await + .expect("view only"); + assert_eq!( + read_named(state, tenant, &t.reader, conversation).await, + vec![comment] + ); + assert!(post(state, tenant, &t.reader, conversation).await.is_err()); + assert!(open(state, tenant, &t.reader, other).await.is_err()); +} + +/// Deleting a task closes its conversation to everyone and refuses opening +/// one; restoring it reopens the conversation. +/// Mutation: skip the `parent_access` change in `follow_artifact` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn deleting_a_task_closes_its_comments_and_restoring_reopens_them() { + let t = Tree::new("conversation-delete").await; + let (state, tenant) = (&t.state, &t.tenant); + let (id, created) = create_task(state, tenant, &t.owner, t.child).await; + let conversation = open(state, tenant, &t.reader, id).await.unwrap(); + let comment = post(state, tenant, &t.reader, conversation).await.unwrap(); + let subscription = subscribe(state, tenant, &t.reader, conversation); + + let deleted = task(&t.owner, t.child, id, "delete", Some(&created)); + send(state, tenant, deleted.clone()).await.expect("delete"); + for person in [&t.reader, &t.owner] { + assert!(read_named(state, tenant, person, conversation) + .await + .is_empty()); + assert!(post(state, tenant, person, conversation).await.is_err()); + } + assert!(!subscribed(state, tenant, conversation, subscription)); + assert!(open(state, tenant, &t.owner, id).await.is_err()); + let (gone, gone_create) = create_task(state, tenant, &t.owner, t.child).await; + send( + state, + tenant, + task(&t.owner, t.child, gone, "delete", Some(&gone_create)), + ) + .await + .unwrap(); + assert!( + open(state, tenant, &t.owner, gone).await.is_err(), + "a deleted task's conversation cannot be opened" + ); + + send( + state, + tenant, + task(&t.owner, t.child, id, "restore", Some(&deleted)), + ) + .await + .expect("restore"); + assert_eq!( + read_named(state, tenant, &t.reader, conversation).await, + vec![comment] + ); + post(state, tenant, &t.reader, conversation) + .await + .expect("comments reopen"); +} + +/// Moving a task moves its conversation: the old home's readers lose it, +/// at once and live, and the new home's readers gain it. A move that would +/// put the conversation at a fourth level is refused, as is opening a +/// conversation for a task that lives there. +/// Mutation: skip the re-parent in `follow_artifact`, or the eviction after +/// it, or `refuse_conversation_home` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn moving_a_task_moves_its_comments() { + let t = Tree::new("conversation-move").await; + let (state, tenant) = (&t.state, &t.tenant); + let (id, created) = create_task(state, tenant, &t.owner, t.child).await; + let conversation = open(state, tenant, &t.reader, id).await.unwrap(); + let comment = post(state, tenant, &t.reader, conversation).await.unwrap(); + let subscription = subscribe(state, tenant, &t.reader, conversation); + + let grandchild = create_channel(state, tenant, &t.owner, &[&["visibility", "private"]]).await; + set_parent(state, tenant, &t.owner, grandchild, Some(t.child)) + .await + .expect("file a grandchild"); + let too_deep = task(&t.owner, grandchild, id, "move", Some(&created)); + let refused = send(state, tenant, too_deep).await.unwrap_err(); + assert!(refused.contains("can't move there"), "{refused}"); + let (deep, _) = create_task(state, tenant, &t.owner, grandchild).await; + let refused = open(state, tenant, &t.owner, deep).await.unwrap_err(); + assert!( + refused.contains("comments aren't available here"), + "{refused}" + ); + + let elsewhere = create_channel(state, tenant, &t.owner, &[&["visibility", "private"]]).await; + let newcomer = Keys::generate(); + add(state, tenant, &t.owner, elsewhere, &newcomer, "member").await; + assert!(read_named(state, tenant, &newcomer, conversation) + .await + .is_empty()); + send( + state, + tenant, + task(&t.owner, elsewhere, id, "move", Some(&created)), + ) + .await + .expect("move"); + + let channel = state + .db + .get_channel_for_event_write(tenant.community(), conversation) + .await + .unwrap(); + assert_eq!(channel.parent_id, Some(elsewhere)); + assert!(read_named(state, tenant, &t.reader, conversation) + .await + .is_empty()); + assert!(post(state, tenant, &t.reader, conversation).await.is_err()); + assert!(!subscribed(state, tenant, conversation, subscription)); + assert_eq!( + read_named(state, tenant, &newcomer, conversation).await, + vec![comment] + ); + post(state, tenant, &newcomer, conversation) + .await + .expect("the new home's reader comments"); +} + +/// A conversation has no people or settings of its own; no other channel +/// may take its address or type, and it holds no artifacts. +/// Mutation: drop `conversation_refuses_kind`, or the generic 9007 guard +/// → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_conversation_has_no_people_or_settings() { + let t = Tree::new("conversation-closed").await; + let (state, tenant) = (&t.state, &t.tenant); + let (id, _) = create_task(state, tenant, &t.owner, t.child).await; + let conversation = open(state, tenant, &t.owner, id).await.unwrap(); + let h = conversation.to_string(); + let person = Keys::generate().public_key().to_hex(); + let attempts: [(u16, Vec>); 5] = [ + (9000, vec![vec!["p", &person]]), + (9001, vec![vec!["p", &person]]), + (9002, vec![vec!["name", "renamed"]]), + (9008, vec![]), + (9021, vec![]), + ]; + for (kind, extra) in attempts { + let mut tags = vec![Tag::parse(["h", h.as_str()]).unwrap()]; + tags.extend(extra.into_iter().map(|t| Tag::parse(t).unwrap())); + let event = EventBuilder::new(Kind::Custom(kind), "") + .tags(tags) + .sign_with_keys(&t.owner) + .unwrap(); + let refused = send(state, tenant, event).await.unwrap_err(); + assert!( + refused.contains("no members or settings"), + "{kind}: {refused}" + ); + } + + let squat = |h: Uuid, channel_type: &str| { + EventBuilder::new(Kind::Custom(9007), "") + .tags([ + Tag::parse(["h", &h.to_string()]).unwrap(), + Tag::parse(["name", "squat"]).unwrap(), + Tag::parse(["channel_type", channel_type]).unwrap(), + ]) + .sign_with_keys(&t.owner) + .unwrap() + }; + let (later, _) = create_task(state, tenant, &t.owner, t.child).await; + let derived = buzz_core::artifact::conversation_id(&later.to_string()); + assert!(send(state, tenant, squat(derived, "stream")).await.is_err()); + assert!(send(state, tenant, squat(Uuid::new_v4(), "artifact")) + .await + .is_err()); + open(state, tenant, &t.owner, later) + .await + .expect("its address is still free"); + + let refused = send( + state, + tenant, + task(&t.owner, conversation, Uuid::new_v4(), "create", None), + ) + .await + .unwrap_err(); + assert!( + refused.contains("cannot live in a conversation"), + "{refused}" + ); +} + +/// The home's own owners and admins delete comments; a member of the home +/// cannot delete someone else's, but may delete their own. +/// Mutation: moderate the conversation by its own rows only → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_homes_admins_moderate_comments() { + let t = Tree::new("conversation-moderation").await; + let (state, tenant) = (&t.state, &t.tenant); + let member = Keys::generate(); + add(state, tenant, &t.owner, t.child, &member, "member").await; + let (id, _) = create_task(state, tenant, &t.owner, t.child).await; + let conversation = open(state, tenant, &t.owner, id).await.unwrap(); + let comment = post(state, tenant, &t.reader, conversation).await.unwrap(); + let own = post(state, tenant, &member, conversation).await.unwrap(); + + assert!(moderate(state, tenant, &member, conversation, &comment) + .await + .is_err()); + moderate(state, tenant, &member, conversation, &own) + .await + .expect("an author deletes their own comment"); + moderate(state, tenant, &t.owner, conversation, &comment) + .await + .expect("the home's owner deletes a comment"); + assert!(read_named(state, tenant, &t.reader, conversation) + .await + .is_empty()); +} + +/// An auto-archiving chat outside any project holds task conversations +/// without becoming a project, and its comments close when it archives. +/// Mutation: count conversations in `has_live_children`, or drop the +/// home-archived check in ingest → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_auto_archiving_chat_holds_task_comments() { + let t = Tree::new("conversation-ttl").await; + let (state, tenant) = (&t.state, &t.tenant); + let chat = create_channel(state, tenant, &t.owner, &[]).await; + edit_channel(state, tenant, &t.owner, chat, &[&["ttl", "3600"]]) + .await + .expect("an auto-archiving chat"); + let (id, _) = create_task(state, tenant, &t.owner, chat).await; + let conversation = open(state, tenant, &t.owner, id) + .await + .expect("its task's comments open"); + post(state, tenant, &t.owner, conversation).await.unwrap(); + edit_channel(state, tenant, &t.owner, chat, &[&["ttl", "7200"]]) + .await + .expect("a conversation does not make the chat a project"); + + auto_archive(state, tenant, chat).await; + let refused = post(state, tenant, &t.owner, conversation) + .await + .unwrap_err(); + assert!(refused.contains("archived"), "{refused}"); + assert_eq!( + read_named(state, tenant, &t.owner, conversation) + .await + .len(), + 1, + "comments stay readable" + ); +} diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index cc5857e6d57..8b4fba6af40 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -678,6 +678,11 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result { + Ok(Scope::MessagesWrite) + } KIND_NIP29_CREATE_GROUP | KIND_CANVAS => Ok(Scope::ChannelsWrite), KIND_NIP29_JOIN_REQUEST | KIND_NIP29_LEAVE_REQUEST | KIND_NIP43_LEAVE_REQUEST => { Ok(Scope::ChannelsRead) @@ -3005,6 +3010,18 @@ async fn ingest_event_inner( } } + // An artifact's conversation has no members or settings of its own: + // everyone reaches it through its home. + if channel_row + .as_ref() + .is_some_and(|ch| ch.channel_type == buzz_db::channel::ChannelType::Artifact.as_str()) + && super::artifact::conversation_refuses_kind(kind_u32) + { + return Err(IngestError::Rejected( + "invalid: an artifact's conversation has no members or settings of its own".into(), + )); + } + // Handled directly — these mutate relay_members and do NOT get stored. // The handler enforces the durable community ban itself: the write-path // gate above exempts relay-admin kinds so timed-out admins keep their @@ -3173,7 +3190,19 @@ async fn ingest_event_inner( if !is_edit_metadata && !is_self_departure { if let Some(channel) = &channel_row { - if channel.archived_at.is_some() { + // An artifact's conversation is archived with its home. + let home_archived = match channel.parent_id { + Some(home) + if channel.channel_type + == buzz_db::channel::ChannelType::Artifact.as_str() => + { + load_channel_for_write(tenant, state, home) + .await? + .is_some_and(|home| home.archived_at.is_some()) + } + _ => false, + }; + if channel.archived_at.is_some() || home_archived { return Err(match target_denial { Some(reason) => target_denied(reason), None => IngestError::Rejected("invalid: channel is archived".into()), @@ -3204,6 +3233,12 @@ async fn ingest_event_inner( return Ok(result); } + // Opening an artifact's conversation. Its own handler authorizes the + // sender in the artifact's home; nobody becomes the channel's owner. + if kind_u32 == KIND_NIP29_CREATE_GROUP && super::artifact::opens_conversation(&event) { + return super::artifact::open_conversation(state, tenant, &event, &auth).await; + } + if kind_u32 == KIND_STREAM_MESSAGE_EDIT { validate_edit_ownership(tenant.community(), &event, state) .await @@ -3321,6 +3356,16 @@ async fn ingest_event_inner( channel_type_str.parse().map_err(|_| { IngestError::Rejected(format!("invalid channel_type: {channel_type_str}")) })?; + // Artifact conversations live at addresses derived from their + // artifact (UUIDv8) and open only through their own route above. + if channel_type == buzz_db::channel::ChannelType::Artifact + || channel_id.is_some_and(|id| id.get_version_num() == 8) + { + return Err(IngestError::Rejected( + "invalid: artifact conversations open with an artifact tag, at their derived address" + .into(), + )); + } let visibility: buzz_db::channel::ChannelVisibility = match event.tags.iter().find_map(|t| { if t.kind().to_string() == "visibility" { diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index c0ec021426a..f435759510a 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -1,6 +1,8 @@ /// NIP-42 authentication handler. pub mod admin_action_worker; pub mod admin_outbox_worker; +#[cfg(test)] +mod artifact_conversation_postgres_tests; /// NIP-AR Sync subscriptions. pub mod artifact_sync; #[cfg(test)] @@ -49,7 +51,7 @@ pub mod multinode_fanout; /// Reading and writing a private channel through its parents. pub(crate) mod parent_access; #[cfg(test)] -mod parent_access_postgres_tests; +pub(crate) mod parent_access_postgres_tests; /// Product-feedback validation + deployment sidecar persistence. pub mod product_feedback; #[allow(dead_code, missing_docs)] diff --git a/crates/buzz-relay/src/handlers/parent_access_postgres_tests.rs b/crates/buzz-relay/src/handlers/parent_access_postgres_tests.rs index e66e35e8509..2987ac9ec17 100644 --- a/crates/buzz-relay/src/handlers/parent_access_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/parent_access_postgres_tests.rs @@ -17,7 +17,7 @@ use crate::state::AppState; /// Ingest a kind:9000 that `actor` signs, adding `person` to `channel` with /// `role`. -async fn add( +pub(crate) async fn add( state: &Arc, tenant: &TenantContext, actor: &Keys, @@ -62,7 +62,7 @@ async fn remove( /// Post a kind:9 that `author` signs in `channel`; the event ID when the /// relay accepted it, its message otherwise. -async fn post( +pub(crate) async fn post( state: &Arc, tenant: &TenantContext, author: &Keys, @@ -81,7 +81,7 @@ async fn post( } /// Set `child`'s parent to `parent`, or clear it, as `actor`. -async fn set_parent( +pub(crate) async fn set_parent( state: &Arc, tenant: &TenantContext, actor: &Keys, @@ -94,7 +94,7 @@ async fn set_parent( /// The IDs of the events `reader` gets for one historical REQ before EOSE; /// none when the relay closes it. -async fn req_event_ids( +pub(crate) async fn req_event_ids( state: &Arc, tenant: &TenantContext, reader: &Keys, @@ -124,7 +124,7 @@ async fn req_event_ids( } /// The kind:9 event IDs `reader` gets for a REQ naming `channel`. -async fn read_named( +pub(crate) async fn read_named( state: &Arc, tenant: &TenantContext, reader: &Keys, @@ -140,7 +140,7 @@ async fn read_named( } /// The kind:9 event IDs `reader` gets for a REQ that names no channel. -async fn read_implicit( +pub(crate) async fn read_implicit( state: &Arc, tenant: &TenantContext, reader: &Keys, @@ -149,7 +149,7 @@ async fn read_implicit( } /// The COUNT `reader` gets for kind:9 in `channel`, or `None` when refused. -async fn count_named( +pub(crate) async fn count_named( state: &Arc, tenant: &TenantContext, reader: &Keys, @@ -174,7 +174,7 @@ async fn count_named( panic!("no COUNT reply"); } -async fn role_in( +pub(crate) async fn role_in( state: &AppState, tenant: &TenantContext, channel: Uuid, @@ -188,19 +188,19 @@ async fn role_in( } /// A private project, a private child under it, and an outsider. -struct Tree { - state: Arc, - tenant: TenantContext, - owner: Keys, - reader: Keys, - outsider: Keys, - project: Uuid, - child: Uuid, +pub(crate) struct Tree { + pub(crate) state: Arc, + pub(crate) tenant: TenantContext, + pub(crate) owner: Keys, + pub(crate) reader: Keys, + pub(crate) outsider: Keys, + pub(crate) project: Uuid, + pub(crate) child: Uuid, } impl Tree { /// `reader` is a member of the project only. - async fn new(label: &str) -> Self { + pub(crate) async fn new(label: &str) -> Self { Self::with_project(label, &[&["visibility", "private"]]).await } @@ -685,7 +685,7 @@ async fn an_archived_project_still_grants_its_children() { } /// Set `channel`'s `parent_access` to `value` as `actor`. -async fn set_parent_access( +pub(crate) async fn set_parent_access( state: &Arc, tenant: &TenantContext, actor: &Keys, @@ -945,7 +945,7 @@ async fn only_the_channels_own_admin_changes_parent_access() { } /// Expire `channel`'s TTL now and run the reaper, which must archive it. -async fn auto_archive(state: &Arc, tenant: &TenantContext, channel: Uuid) { +pub(crate) async fn auto_archive(state: &Arc, tenant: &TenantContext, channel: Uuid) { sqlx::query( "UPDATE channels SET ttl_deadline = clock_timestamp() - interval '1 second' \ WHERE community_id = $1 AND id = $2", diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index 9bdd211cba7..9935079e472 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -343,6 +343,20 @@ pub(crate) async fn evict_conn_channel_subscriptions( /// subscriptions promptly so clients stop treating the channel as live. A /// reader whose parent access could not be checked keeps the subscription, /// and the fan-out gate decides. +/// After an artifact's move, delete or restore changed who may read its +/// conversation (committed), clear accessible-channel caches and close live +/// subscriptions of people who can no longer read it. +pub(crate) async fn artifact_conversation_access_changed( + tenant: &TenantContext, + state: &Arc, + conversation: Uuid, +) { + state.invalidate_all_accessible_channels(tenant); + if let Err(e) = evict_non_reader_channel_subscriptions(tenant, state, conversation).await { + warn!(channel = %conversation, error = %e, "non-reader subscription eviction failed"); + } +} + async fn evict_non_reader_channel_subscriptions( tenant: &TenantContext, state: &Arc, @@ -570,8 +584,23 @@ async fn may_delete_channel_event( { return Ok(true); } + // An artifact's conversation has no rows of its own: its home's direct + // owners and admins moderate it. + let channel = state + .db + .get_channel_for_event_write(tenant.community(), channel_id) + .await?; + let moderated_by = match channel.parent_id { + Some(home) if channel.channel_type == buzz_db::channel::ChannelType::Artifact.as_str() => { + home + } + _ => channel_id, + }; Ok(actor_is_channel_owner_or_admin( - &state.db.get_members(tenant.community(), channel_id).await?, + &state + .db + .get_members(tenant.community(), moderated_by) + .await?, actor, ) || state .db diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index fb7b30b1925..cd20494f04f 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -273,6 +273,10 @@ impl RelayInfo { // filing a channel without narrowing it, so a client checks this // before filing a narrowed channel. "buzz-channel-parent-access".to_string(), + // kind:9007 with an `artifact` tag opens an artifact's + // conversation (NOSTR.md, Artifact conversations), and task + // sync includes auto-archiving channels. + "buzz-artifact-conversations".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -844,6 +848,7 @@ mod tests { assert!(extensions.contains(&"buzz-unlisted-channels".to_string())); assert!(extensions.contains(&"buzz-channel-parents".to_string())); assert!(extensions.contains(&"buzz-channel-parent-access".to_string())); + assert!(extensions.contains(&"buzz-artifact-conversations".to_string())); } /// NIP-WP → NIP-11 mirror: a set workspace icon is served in the standard diff --git a/docs/nips/NIP-AR.md b/docs/nips/NIP-AR.md index da0c36a17db..075c31e4e66 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -361,10 +361,10 @@ server permits four concurrent operations per process, a two-second SQL statement budget, and an eight-second operation budget. There is no identity-wide membership count limit on this path. -Incremental reads include only matching readable artifacts in permanent channels. -TTL channels do not contribute discovery candidates. A known-ID read returns -`remove` for an artifact in a TTL channel. Moves into a TTL channel return -removals for the permanent source. An explicit `#h` scope limits candidates +Incremental reads include matching readable artifacts in every channel, +including channels with a TTL. (Relays before `buzz-artifact-conversations` +left TTL channels out: a known-ID read returned `remove` for their +artifacts.) A TTL change still resets progress. An explicit `#h` scope limits candidates to those channels, including retained move sources and membership removals. Initial reads omit deleted heads. Later reads retain deletion removals. HTTP 400 `incremental_invalid` diff --git a/migrations/0091_artifact_channel_type.sql b/migrations/0091_artifact_channel_type.sql new file mode 100644 index 00000000000..e81bc58a859 --- /dev/null +++ b/migrations/0091_artifact_channel_type.sql @@ -0,0 +1,9 @@ +-- Artifact conversations: a channel that holds an artifact's comments, such as +-- a task's. Its ID is derived from the artifact, its parent is the artifact's +-- home, and access comes only through that parent. Like 'system', it is not a +-- legacy type, so the relay leaves it out of queries that do not name it. +-- +-- Additive. Do not roll the relay back past this change while artifact +-- conversations exist: an older relay cannot read the value and does not +-- exclude these channels. +ALTER TYPE channel_type ADD VALUE IF NOT EXISTS 'artifact'; diff --git a/schema/types/channel_type.sql b/schema/types/channel_type.sql index fc1a1b7e7cc..0b545d849ef 100644 --- a/schema/types/channel_type.sql +++ b/schema/types/channel_type.sql @@ -1,3 +1,3 @@ -- ── Custom types ────────────────────────────────────────────────────────────── -CREATE TYPE channel_type AS ENUM ('stream', 'forum', 'dm', 'workflow', 'system'); +CREATE TYPE channel_type AS ENUM ('stream', 'forum', 'dm', 'workflow', 'system', 'artifact'); From 0fafecffd45575bd77152ab36ab8bdb42a51c6ad Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:37:22 -0800 Subject: [PATCH 2/2] fix(relay): hold task conversations to comments and cover the review gaps A task conversation now accepts only the kinds comments need (messages, edits, deletes, reactions and the open itself) and refuses everything else, so a canvas or any future setting stays out without a refuse list. Adds tests for two first comments at once, a forged or early-claimed address, filing a channel with comments at the depth limit, and keeping conversations out of lists and search. NOSTR.md records that an archived parent still grants comment access, as a decision. Co-Authored-By: Claude Opus 5.5 Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> --- NOSTR.md | 15 +- crates/buzz-relay/src/handlers/artifact.rs | 21 +- .../artifact_conversation_postgres_tests.rs | 217 ++++++++++++++++-- crates/buzz-relay/src/handlers/ingest.rs | 8 +- 4 files changed, 234 insertions(+), 27 deletions(-) diff --git a/NOSTR.md b/NOSTR.md index 47b6bedb175..b9f8c02a327 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -281,10 +281,17 @@ for its comments. It belongs to the artifact, not to anyone who posts in it. posts comes only from the home, through [Channel parents](#channel-parents): the home's readers read, a view-only (`guest`) home's people read but do not post, and a home's `parent_access` applies as it does to any child. - Comments close to new posts while the home is archived. -- **No people or settings of its own.** kind:9000, 9001, 9002, 9008, 9021 - and 9022 are refused in a conversation. The home's direct owners and - admins may delete comments with kind:9005; authors may delete their own. + Comments close to new posts while the home is archived. Only the home + counts: an archived project above it still grants access and does not + archive its channels, so it does not close their comments either, just as + it does not close posting in those channels. +- **Only comments.** A conversation accepts only kind:9 messages, kind:40003 + edits, kind:7 reactions, kind:5 and kind:9005 deletions, and the opening + kind:9007. Every other kind with its `h`, including people (9000, 9001, + 9021, 9022), settings (9002), deletion (9008), a canvas, and any kind added + later, is refused with `invalid: an artifact's conversation only holds + comments`. The home's direct owners and admins may delete comments with + kind:9005; authors may delete their own. - **Moves.** When the artifact moves, the conversation moves with it in the same transaction: its parent becomes the new home, the old home's readers lose it at once, and their live subscriptions close. A move to a home that diff --git a/crates/buzz-relay/src/handlers/artifact.rs b/crates/buzz-relay/src/handlers/artifact.rs index 1bfc17c29ed..01f418a2711 100644 --- a/crates/buzz-relay/src/handlers/artifact.rs +++ b/crates/buzz-relay/src/handlers/artifact.rs @@ -91,10 +91,23 @@ pub(crate) fn opens_conversation(event: &Event) -> bool { .any(|t| t.kind().to_string() == CONVERSATION_ARTIFACT_TAG) } -/// Kinds refused in an artifact's conversation: it has no members or -/// settings of its own (add, remove, edit, delete, join, leave). -pub(crate) fn conversation_refuses_kind(kind: u32) -> bool { - matches!(kind, 9000 | 9001 | 9002 | 9008 | 9021 | 9022) +/// The only kinds an artifact's conversation accepts: what comments need. +/// It has no members or settings of its own, so every other kind, including +/// any added later, is refused there. +pub(crate) fn conversation_accepts_kind(kind: u32) -> bool { + use buzz_core::kind::{ + KIND_DELETION, KIND_NIP29_CREATE_GROUP, KIND_NIP29_DELETE_EVENT, KIND_REACTION, + KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_EDIT, + }; + matches!( + kind, + KIND_STREAM_MESSAGE + | KIND_STREAM_MESSAGE_EDIT + | KIND_REACTION + | KIND_DELETION + | KIND_NIP29_DELETE_EVENT + | KIND_NIP29_CREATE_GROUP + ) } /// Open the conversation of the artifact named by a kind:9007's `artifact` diff --git a/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs index d334d90b90e..eceb12aa0a7 100644 --- a/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs @@ -14,8 +14,8 @@ use buzz_auth::Scope; use crate::handlers::group_state_postgres_tests::{create_channel, edit_channel, test_conn}; use crate::handlers::ingest::{ingest_event, HttpAuthMethod, IngestAuth}; use crate::handlers::parent_access_postgres_tests::{ - add, auto_archive, count_named, post, read_implicit, read_named, role_in, set_parent, - set_parent_access, Tree, + add, auto_archive, count_named, post, read_implicit, read_named, req_event_ids, role_in, + set_parent, set_parent_access, Tree, }; use crate::state::AppState; @@ -372,10 +372,11 @@ async fn moving_a_task_moves_its_comments() { .expect("the new home's reader comments"); } -/// A conversation has no people or settings of its own; no other channel -/// may take its address or type, and it holds no artifacts. -/// Mutation: drop `conversation_refuses_kind`, or the generic 9007 guard -/// → RED. +/// A conversation holds only comments: people, settings, a canvas or any +/// other kind it does not list are refused. No other channel may take its +/// address or type, and it holds no artifacts. +/// Mutation: drop `conversation_accepts_kind`, accept every kind, or drop the +/// generic 9007 guard → RED. #[tokio::test] #[ignore = "requires Postgres"] async fn a_conversation_has_no_people_or_settings() { @@ -385,12 +386,18 @@ async fn a_conversation_has_no_people_or_settings() { let conversation = open(state, tenant, &t.owner, id).await.unwrap(); let h = conversation.to_string(); let person = Keys::generate().public_key().to_hex(); - let attempts: [(u16, Vec>); 5] = [ + let message = "0".repeat(64); + let attempts: [(u16, Vec>); 8] = [ (9000, vec![vec!["p", &person]]), (9001, vec![vec!["p", &person]]), (9002, vec![vec!["name", "renamed"]]), (9008, vec![]), (9021, vec![]), + // A canvas, and kinds an ordinary channel takes that no refuse + // list ever named: a pin and a forum post. + (40100, vec![]), + (40004, vec![vec!["e", &message]]), + (45001, vec![]), ]; for (kind, extra) in attempts { let mut tags = vec![Tag::parse(["h", h.as_str()]).unwrap()]; @@ -400,10 +407,7 @@ async fn a_conversation_has_no_people_or_settings() { .sign_with_keys(&t.owner) .unwrap(); let refused = send(state, tenant, event).await.unwrap_err(); - assert!( - refused.contains("no members or settings"), - "{kind}: {refused}" - ); + assert!(refused.contains("only holds comments"), "{kind}: {refused}"); } let squat = |h: Uuid, channel_type: &str| { @@ -433,10 +437,8 @@ async fn a_conversation_has_no_people_or_settings() { ) .await .unwrap_err(); - assert!( - refused.contains("cannot live in a conversation"), - "{refused}" - ); + // An artifact is not a comment, so the allowlist refuses it first. + assert!(refused.contains("only holds comments"), "{refused}"); } /// The home's own owners and admins delete comments; a member of the home @@ -503,3 +505,188 @@ async fn an_auto_archiving_chat_holds_task_comments() { "comments stay readable" ); } + +/// Two people opening a task's conversation at once both succeed and get +/// the same channel, which nobody owns, and both comment in it. +/// Mutation: drop the artifact lock from `ensure_artifact_conversation` → +/// RED or flaky. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn two_first_comments_at_once_share_one_conversation() { + let t = Tree::new("conversation-race").await; + let (state, tenant) = (&t.state, &t.tenant); + for _ in 0..8 { + let (id, _) = create_task(state, tenant, &t.owner, t.child).await; + let (a, b) = tokio::join!( + open(state, tenant, &t.owner, id), + open(state, tenant, &t.reader, id) + ); + let (a, b) = (a.expect("first opener"), b.expect("second opener")); + assert_eq!(a, b); + let members: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM channel_members WHERE community_id = $1 AND channel_id = $2", + ) + .bind(tenant.community().as_uuid()) + .bind(a) + .fetch_one(state.db.pool()) + .await + .unwrap(); + assert_eq!(members, 0, "nobody owns it"); + let (x, y) = tokio::join!( + post(state, tenant, &t.owner, a), + post(state, tenant, &t.reader, a) + ); + x.expect("owner comments"); + y.expect("reader comments"); + assert_eq!(count_named(state, tenant, &t.reader, a).await, Some(2)); + } +} + +/// A conversation opens only at its own task's address: not at a made-up +/// one, not at another task's, and nobody can claim a task's address before +/// its first comment, with or without the `artifact` type. +/// Mutation: drop the derivation check or the generic 9007 guard → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_forged_or_claimed_address_is_refused() { + let t = Tree::new("conversation-forged").await; + let (state, tenant) = (&t.state, &t.tenant); + let (mine, _) = create_task(state, tenant, &t.owner, t.child).await; + let (theirs, _) = create_task(state, tenant, &t.owner, t.child).await; + let theirs_at = buzz_core::artifact::conversation_id(&theirs.to_string()); + + for h in [Uuid::new_v4(), theirs_at] { + let refused = send(state, tenant, open_event(&t.owner, &mine.to_string(), h)) + .await + .unwrap_err(); + assert!(!refused.is_empty()); + } + let claim = |extra: Option<[&str; 2]>| { + let mut tags = vec![ + Tag::parse(["h", &theirs_at.to_string()]).unwrap(), + Tag::parse(["name", "early"]).unwrap(), + ]; + tags.extend(extra.map(|t| Tag::parse(t).unwrap())); + EventBuilder::new(Kind::Custom(9007), "") + .tags(tags) + .sign_with_keys(&t.owner) + .unwrap() + }; + for extra in [ + None, + Some(["channel_type", "stream"]), + Some(["channel_type", "artifact"]), + ] { + assert!( + send(state, tenant, claim(extra)).await.is_err(), + "claiming early: {extra:?}" + ); + } + assert!(state + .db + .get_channel_for_event_write(tenant.community(), theirs_at) + .await + .is_err()); + assert_eq!( + open(state, tenant, &t.owner, theirs).await.unwrap(), + theirs_at, + "its own task still opens it" + ); + assert_eq!( + state + .db + .get_channel_for_event_write(tenant.community(), theirs_at) + .await + .unwrap() + .name, + theirs.to_string() + ); +} + +/// A channel whose tasks have comments can be filed into a project, but not +/// under a project's child, where its comments would be a fourth level. +/// Mutation: leave conversations out of the depth check → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn filing_a_channel_with_comments_respects_the_depth_limit() { + let t = Tree::new("conversation-filing").await; + let (state, tenant) = (&t.state, &t.tenant); + let chat = create_channel(state, tenant, &t.owner, &[&["visibility", "private"]]).await; + let (id, _) = create_task(state, tenant, &t.owner, chat).await; + let conversation = open(state, tenant, &t.owner, id).await.unwrap(); + + let refused = set_parent(state, tenant, &t.owner, chat, Some(t.child)) + .await + .unwrap_err(); + assert!(!refused.is_empty()); + let parent = |id| async move { + state + .db + .get_channel_for_event_write(tenant.community(), id) + .await + .unwrap() + .parent_id + }; + assert_eq!(parent(chat).await, None, "nothing was saved"); + + set_parent(state, tenant, &t.owner, chat, Some(t.project)) + .await + .expect("filed into the project"); + assert_eq!(parent(chat).await, Some(t.project)); + assert_eq!(parent(conversation).await, Some(chat)); + post(state, tenant, &t.reader, conversation) + .await + .expect("the project's reader comments"); +} + +/// Task conversations stay out of everything that does not name them: +/// reads, counts, searches and channel listings. +/// Mutation: list the `artifact` type among the legacy types → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn task_conversations_stay_out_of_lists_and_search() { + let t = Tree::new("conversation-hidden").await; + let (state, tenant) = (&t.state, &t.tenant); + let (id, _) = create_task(state, tenant, &t.owner, t.child).await; + let conversation = open(state, tenant, &t.owner, id).await.unwrap(); + let word = format!("needle{}", Uuid::new_v4().simple()); + let comment = EventBuilder::new(Kind::Custom(9), format!("look {word}")) + .tags([Tag::parse(["h", &conversation.to_string()]).unwrap()]) + .sign_with_keys(&t.reader) + .unwrap(); + let comment_id = comment.id.to_hex(); + send(state, tenant, comment).await.expect("comment"); + + for reader in [&t.owner, &t.reader] { + for filter in [ + serde_json::json!({"kinds": [9]}), + serde_json::json!({"kinds": [9], "search": word}), + serde_json::json!({"ids": [comment_id]}), + ] { + let ids = req_event_ids(state, tenant, reader, filter.clone()).await; + assert!(!ids.contains(&comment_id), "{filter}"); + } + assert_eq!( + req_event_ids( + state, + tenant, + reader, + serde_json::json!({"kinds": [9], "#h": [conversation], "search": word}), + ) + .await, + vec![comment_id.clone()], + "naming it finds it" + ); + let accessible = state + .get_accessible_channel_ids_cached(tenant.community(), &reader.public_key().to_bytes()) + .await + .unwrap(); + assert!(!accessible.contains(&conversation), "not in channel lists"); + let snapshot = state + .db + .get_member_channel_ids(tenant.community(), &reader.public_key().to_bytes()) + .await + .unwrap(); + assert!(!snapshot.contains(&conversation), "not in membership lists"); + } +} diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 8b4fba6af40..a366a425636 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -3010,15 +3010,15 @@ async fn ingest_event_inner( } } - // An artifact's conversation has no members or settings of its own: - // everyone reaches it through its home. + // An artifact's conversation holds only comments: everything it does + // not list is refused, so a new kind stays out until it is added. if channel_row .as_ref() .is_some_and(|ch| ch.channel_type == buzz_db::channel::ChannelType::Artifact.as_str()) - && super::artifact::conversation_refuses_kind(kind_u32) + && !super::artifact::conversation_accepts_kind(kind_u32) { return Err(IngestError::Rejected( - "invalid: an artifact's conversation has no members or settings of its own".into(), + "invalid: an artifact's conversation only holds comments".into(), )); }