From 277d6ffa94c5d1ac87282e71d3c712ee138dedcd Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:43:19 -0600 Subject: [PATCH 1/5] feat(core): NIP-CI conversation import kinds, payloads and acceptance rules Adds kinds 42110 to 42113 and the relay-only 30623 snapshot, the payload structs, the import tag parser, the pure session status and acceptance rule functions, the rejection reasons (including the session warm-up and the per-channel and per-proposer session caps) and the relay import limits. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- crates/buzz-core/src/import.rs | 1322 ++++++++++++++++++++++++++++++++ crates/buzz-core/src/kind.rs | 56 ++ crates/buzz-core/src/lib.rs | 2 + 3 files changed, 1380 insertions(+) create mode 100644 crates/buzz-core/src/import.rs diff --git a/crates/buzz-core/src/import.rs b/crates/buzz-core/src/import.rs new file mode 100644 index 00000000000..41efb10069a --- /dev/null +++ b/crates/buzz-core/src/import.rs @@ -0,0 +1,1322 @@ +//! NIP-CI conversation import: payload types, tag helpers and pure rules. +//! +//! A conversation import brings a shared history from an external messaging +//! source into one Buzz channel. Every imported event is signed by its real +//! author and keeps its original `created_at`. The relay only accepts such a +//! backdated event while an import session is `active`, meaning every +//! required participant has consented to a proposal bound to a manifest hash +//! of the exact corpus. +//! +//! This module is zero-I/O: it holds the wire payloads for kinds +//! 42110 to 42113 and 30623, the import tag parser, and the pure state and +//! acceptance rules the relay evaluates against stored session state. See +//! `docs/nips/NIP-CI.md`. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::kind::{KIND_REACTION, KIND_STREAM_MESSAGE}; + +/// Wire version carried in the `v` field of every NIP-CI payload. +pub const IMPORT_PAYLOAD_VERSION: u32 = 1; + +/// Maximum serialized size of a 42110 proposal content, in bytes (16 KiB). +pub const MAX_PROPOSAL_CONTENT_BYTES: usize = 16 * 1024; + +/// Minimum number of participants a proposal may list. +pub const MIN_IMPORT_PARTICIPANTS: usize = 1; + +/// Maximum number of participants a proposal may list. +pub const MAX_IMPORT_PARTICIPANTS: usize = 64; + +/// Maximum length of `source.label`, in characters. +pub const MAX_SOURCE_LABEL_CHARS: usize = 80; + +/// Maximum length of a 42112 withdraw `reason`, in characters. +pub const MAX_WITHDRAW_REASON_CHARS: usize = 200; + +/// Maximum length of the `source.type` token, in bytes. +pub const MAX_SOURCE_TYPE_LEN: usize = 32; + +/// Allowed forward clock skew for an imported event's `created_at`, in seconds. +pub const IMPORT_FUTURE_SKEW_SECS: i64 = 900; + +/// The relay republishes the session snapshot after this many accepted +/// imported events per participant. +pub const SNAPSHOT_REPUBLISH_EVERY: u64 = 50; + +/// Literal `source_user` value that marks a 42111 as a channel-admin consent. +pub const ADMIN_CONSENT_SOURCE_USER: &str = "admin"; + +/// Tag name that binds an imported content event to its proposal. +pub const IMPORT_TAG: &str = "import"; + +/// Tag name carrying `["source", , ]`. +pub const SOURCE_TAG: &str = "source"; + +/// Tag name carrying the manifest hash on proposals and consents. +pub const MANIFEST_TAG: &str = "manifest"; + +/// Tag name carrying the source type on proposals. +pub const IMPORT_SOURCE_TAG: &str = "import-source"; + +/// Snapshot tag carrying the unix second from which an active session +/// accepts imported events. +pub const ACCEPTS_AFTER_TAG: &str = "accepts_after"; + +/// Exact relay rejection reasons for imported content events. +pub mod reason { + /// The `import` tag names no stored 42110 in this community. + pub const PROPOSAL_NOT_FOUND: &str = "invalid: import proposal not found"; + /// The session is not `active` (or this author already completed). + pub const SESSION_NOT_ACTIVE: &str = "invalid: import session not active"; + /// The author is not a participant who accepted. + pub const NOT_CONSENTING: &str = "invalid: import author not a consenting participant"; + /// `created_at` falls outside the declared range or too far in the future. + pub const TIMESTAMP_OUT_OF_RANGE: &str = "invalid: import timestamp outside declared range"; + /// The author already published its declared count for this kind. + pub const COUNT_EXCEEDED: &str = "invalid: import count exceeded"; + /// A reaction's target does not carry the same `import` tag. + pub const REACTION_TARGET_NOT_IMPORTED: &str = "invalid: import reaction target not imported"; + /// The event's `h` differs from the proposal's `h`. + pub const CHANNEL_MISMATCH: &str = "invalid: import channel mismatch"; + /// An `import` tag on a kind other than 9 or 7. + pub const KIND_NOT_ALLOWED: &str = "invalid: import kind not allowed"; + /// The import tags are duplicated or malformed. + pub const TAGS_MALFORMED: &str = "invalid: import tags malformed"; + /// The per-pubkey `ImportEvents` budget is exhausted. + pub const RATE_LIMITED: &str = "rate-limited: import"; + /// A control event's author is neither the proposer nor a participant + /// (nor, for an admin consent, a current channel admin). + pub const NOT_PARTICIPANT: &str = "restricted: import author not a participant"; + /// The proposer is not an active member of the destination channel. + pub const PROPOSER_NOT_MEMBER: &str = + "restricted: import proposer not an active channel member"; + /// A listed participant is not an active member of the destination channel. + pub const PARTICIPANT_NOT_MEMBER: &str = + "invalid: import participant not an active channel member"; + /// A DM proposal whose participants differ from the DM member set. + pub const DM_PARTICIPANTS_MISMATCH: &str = + "invalid: import participants must equal the DM members"; + /// A consent whose manifest or `source_user` does not match the proposal. + pub const CONSENT_MISMATCH: &str = "invalid: import consent does not match proposal"; + /// A proposal lists a participant who is an agent. + pub const PARTICIPANTS_INCLUDE_AGENTS: &str = + "restricted: import participants cannot include agents"; + /// A DM or private destination has an agent among its current members. + pub const DESTINATION_HAS_AGENTS: &str = "restricted: import destination has agent members"; + /// Declared counts exceed the relay's per-participant or per-session cap. + pub const COUNTS_EXCEED_LIMIT: &str = "invalid: import counts exceed the relay limit"; + /// An imported reaction collides with a reaction row already stored. + pub const REACTION_CONFLICT: &str = + "invalid: import reaction conflicts with an existing reaction"; + /// The event's `source` type differs from the proposal's source type. + pub const SOURCE_TYPE_MISMATCH: &str = "invalid: import source type does not match the session"; + /// Prefix for a malformed control event; a detail follows. + pub const MALFORMED_PREFIX: &str = "invalid: import event malformed: "; + /// The session is active but its `accepts_after` time has not passed. + /// Retryable: the snapshot names the time to wait for. + pub const SESSION_WARMING: &str = "invalid: import session warming"; + /// The destination already has the relay's maximum of unended sessions. + pub const CHANNEL_SESSION_LIMIT: &str = + "restricted: too many active import sessions in this channel"; + /// The proposer already has the relay's maximum of unended sessions. + pub const PROPOSER_SESSION_LIMIT: &str = + "restricted: too many active import sessions for this proposer"; +} + +/// Source conversation shape declared by a proposal. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ImportSourceKind { + /// Two-person direct message. + Dm, + /// Multi-person direct message. + GroupDm, + /// Private (invite-only) channel. + PrivateChannel, + /// Public channel. + PublicChannel, +} + +/// The `source` object of a 42110 proposal. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportSource { + /// Lowercase source type token, `[a-z0-9_-]{1,32}`. + #[serde(rename = "type")] + pub source_type: String, + /// sha256 hex of the source conversation id. + pub conversation: String, + /// Source conversation shape. + pub kind: ImportSourceKind, + /// Display label, at most 80 characters. + pub label: String, +} + +/// The `range` object of a 42110 proposal, unix seconds, inclusive. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportRange { + /// Earliest allowed `created_at`. + pub from: i64, + /// Latest allowed `created_at`. + pub to: i64, +} + +/// One participant entry of a 42110 proposal. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportParticipant { + /// Participant Buzz pubkey, lowercase hex. + pub pubkey: String, + /// sha256 hex of `type:source_user_id`, the identity binding. + pub source_user: String, + /// Declared number of kind 9 events this participant will publish. + pub messages: u64, + /// Declared number of kind 7 events this participant will publish. + pub reactions: u64, +} + +/// Content of a kind 42110 Import Proposal. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportProposalContent { + /// Payload version, always 1. + pub v: u32, + /// Source conversation description. + pub source: ImportSource, + /// Declared time range of the imported history. + pub range: ImportRange, + /// Participants, one per Buzz author. + pub participants: Vec, + /// Count of source authors with no Buzz participant. + pub excluded_authors: u64, + /// sha256 hex manifest of the exact corpus. + pub manifest: String, + /// Requested session expiry; the relay caps it. + pub expires_at: i64, +} + +/// A consent decision. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ImportDecision { + /// The participant agrees to the import. + Accept, + /// The participant refuses the import. + Decline, +} + +impl ImportDecision { + /// Wire string for this decision. + pub const fn as_str(self) -> &'static str { + match self { + Self::Accept => "accept", + Self::Decline => "decline", + } + } + + /// Parse a wire string; `None` for anything else. + pub fn parse(value: &str) -> Option { + match value { + "accept" => Some(Self::Accept), + "decline" => Some(Self::Decline), + _ => None, + } + } +} + +/// Content of a kind 42111 Import Consent. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportConsentContent { + /// Payload version, always 1. + pub v: u32, + /// Accept or decline. + pub decision: ImportDecision, + /// Must equal the author's participant `source_user`, or `"admin"`. + pub source_user: String, +} + +/// Content of a kind 42112 Import Withdraw. The content may also be empty. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportWithdrawContent { + /// Payload version, always 1. + pub v: u32, + /// Optional human-readable reason, at most 200 characters. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +/// Message and reaction counts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportCounts { + /// Kind 9 count. + pub messages: u64, + /// Kind 7 count. + pub reactions: u64, +} + +/// Content of a kind 42113 Import Complete. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportCompleteContent { + /// Payload version, always 1. + pub v: u32, + /// What the participant reports it published. + pub published: ImportCounts, +} + +/// Session status carried by the 30623 snapshot. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ImportSessionStatus { + /// Waiting for required consents. + Proposed, + /// Every required consent is present; imported events are accepted. + Active, + /// A required participant declined before activation (or any DM decline). + Declined, + /// The proposer or a participant withdrew the session. + Withdrawn, + /// The session passed `expires_at` without completing. + Expired, + /// Every accepting participant sent 42113. + Completed, +} + +impl ImportSessionStatus { + /// Wire and storage string. + pub const fn as_str(self) -> &'static str { + match self { + Self::Proposed => "proposed", + Self::Active => "active", + Self::Declined => "declined", + Self::Withdrawn => "withdrawn", + Self::Expired => "expired", + Self::Completed => "completed", + } + } + + /// Parse a storage string; `None` for anything else. + pub fn parse(value: &str) -> Option { + match value { + "proposed" => Some(Self::Proposed), + "active" => Some(Self::Active), + "declined" => Some(Self::Declined), + "withdrawn" => Some(Self::Withdrawn), + "expired" => Some(Self::Expired), + "completed" => Some(Self::Completed), + _ => None, + } + } + + /// Whether no further transition is possible. + pub const fn is_terminal(self) -> bool { + matches!( + self, + Self::Declined | Self::Withdrawn | Self::Expired | Self::Completed + ) + } +} + +/// Content of a kind 30623 Import Session Snapshot. +/// +/// `required` lists every pubkey whose accept is needed, plus the literal +/// `"admin"` when a channel-admin consent is also required. `consents` uses +/// the same keys; the admin consent is keyed `"admin"`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportSessionSnapshotContent { + /// Payload version, always 1. + pub v: u32, + /// Current session status. + pub status: ImportSessionStatus, + /// Who must accept before the session becomes active. + pub required: Vec, + /// Latest decision per consenter. + pub consents: BTreeMap, + /// Accepted imported event counts per participant. + pub published: BTreeMap, + /// Participants that sent 42113, sorted. + pub completed: Vec, + /// Effective (relay-capped) expiry. + pub expires_at: i64, +} + +/// Whether `value` is exactly 64 lowercase hex characters. +pub fn is_lower_hex_64(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +/// Whether `value` is a valid `source.type` token, `[a-z0-9_-]{1,32}`. +pub fn is_valid_source_type(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_SOURCE_TYPE_LEN + && value + .bytes() + .all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-')) +} + +fn tag_name(tag: &nostr::Tag) -> Option<&str> { + tag.as_slice().first().map(String::as_str) +} + +/// Whether the event carries at least one `import` tag. +/// +/// Every event that returns `true` is treated as an import event for +/// side-effect suppression. +pub fn is_import_event(event: &nostr::Event) -> bool { + event + .tags + .iter() + .any(|tag| tag_name(tag) == Some(IMPORT_TAG)) +} + +/// Parsed `import` and `source` tags of an imported content event. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ImportTags { + /// Proposal event id, lowercase hex. + pub proposal_id: String, + /// The same proposal id, decoded. + pub proposal_bytes: [u8; 32], + /// Source type token. + pub source_type: String, + /// Source message reference. + pub source_ref: String, +} + +/// Rule 1 of NIP-CI acceptance: kind is 9 or 7, exactly one well-formed +/// `import` tag and exactly one well-formed `source` tag. +/// +/// Returns `Ok(None)` when the event carries no `import` tag at all (a normal +/// event). Returns the exact rejection reason otherwise. +pub fn parse_import_tags(event: &nostr::Event) -> Result, &'static str> { + let mut import: Vec<&[String]> = Vec::new(); + let mut source: Vec<&[String]> = Vec::new(); + for tag in event.tags.iter() { + match tag_name(tag) { + Some(IMPORT_TAG) => import.push(tag.as_slice()), + Some(SOURCE_TAG) => source.push(tag.as_slice()), + _ => {} + } + } + if import.is_empty() { + return Ok(None); + } + let kind = u32::from(event.kind.as_u16()); + if kind != KIND_STREAM_MESSAGE && kind != KIND_REACTION { + return Err(reason::KIND_NOT_ALLOWED); + } + if import.len() != 1 || source.len() != 1 { + return Err(reason::TAGS_MALFORMED); + } + let (import, source) = (import[0], source[0]); + let proposal_id = match import.get(1) { + Some(id) if import.len() == 2 && is_lower_hex_64(id) => id.clone(), + _ => return Err(reason::TAGS_MALFORMED), + }; + let mut proposal_bytes = [0u8; 32]; + hex::decode_to_slice(&proposal_id, &mut proposal_bytes).map_err(|_| reason::TAGS_MALFORMED)?; + match (source.get(1), source.get(2)) { + (Some(source_type), Some(source_ref)) + if source.len() == 3 && is_valid_source_type(source_type) && !source_ref.is_empty() => + { + Ok(Some(ImportTags { + proposal_id, + proposal_bytes, + source_type: source_type.clone(), + source_ref: source_ref.clone(), + })) + } + _ => Err(reason::TAGS_MALFORMED), + } +} + +/// Caps a relay enforces on proposals. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ImportLimits { + /// Cap on one participant's declared messages plus reactions. + pub max_events_per_participant: u64, + /// Cap on the declared messages plus reactions of all participants. + pub max_events_per_session: u64, + /// Cap on unended (proposed or active, unexpired) sessions per channel. + pub max_active_sessions_per_channel: u64, + /// Cap on unended sessions one proposer holds across the community. + pub max_active_sessions_per_proposer: u64, +} + +impl Default for ImportLimits { + fn default() -> Self { + Self { + max_events_per_participant: 50_000, + max_events_per_session: 200_000, + max_active_sessions_per_channel: 2, + max_active_sessions_per_proposer: 8, + } + } +} + +/// Earliest `range.from` a proposal may declare: 2000-01-01T00:00:00Z. +pub const MIN_IMPORT_RANGE_FROM: i64 = 946_684_800; + +/// Why a proposal body was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProposalRejection { + /// A shape rule failed; the detail follows [`reason::MALFORMED_PREFIX`]. + Malformed(&'static str), + /// Declared counts exceed [`ImportLimits`] (or overflow). + CountsExceedLimit, +} + +impl ProposalRejection { + /// The exact relay rejection message. + pub fn reason(self) -> String { + match self { + Self::Malformed(detail) => format!("{}{detail}", reason::MALFORMED_PREFIX), + Self::CountsExceedLimit => reason::COUNTS_EXCEED_LIMIT.to_string(), + } + } +} + +/// Validate a decoded proposal body against NIP-CI shape rules and the +/// relay's count caps, none of which need storage. `now` is the relay clock +/// in unix seconds. +pub fn validate_proposal_content( + content: &ImportProposalContent, + now: i64, + limits: ImportLimits, +) -> Result<(), ProposalRejection> { + use ProposalRejection::{CountsExceedLimit, Malformed}; + if content.v != IMPORT_PAYLOAD_VERSION { + return Err(Malformed("unsupported version")); + } + if !is_valid_source_type(&content.source.source_type) { + return Err(Malformed("source type must match [a-z0-9_-]{1,32}")); + } + if !is_lower_hex_64(&content.source.conversation) { + return Err(Malformed("source conversation must be 64 lowercase hex")); + } + if content.source.label.chars().count() > MAX_SOURCE_LABEL_CHARS { + return Err(Malformed("source label exceeds 80 characters")); + } + if content.range.from < MIN_IMPORT_RANGE_FROM { + return Err(Malformed("range must not start before 2000-01-01")); + } + if content.range.from >= content.range.to || content.range.to > now { + return Err(Malformed("range must satisfy from < to <= now")); + } + let count = content.participants.len(); + if !(MIN_IMPORT_PARTICIPANTS..=MAX_IMPORT_PARTICIPANTS).contains(&count) { + return Err(Malformed("participants must number 1 to 64")); + } + let mut seen = std::collections::BTreeSet::new(); + let mut session_total: u64 = 0; + for participant in &content.participants { + if !is_lower_hex_64(&participant.pubkey) { + return Err(Malformed("participant pubkey must be 64 lowercase hex")); + } + if !is_lower_hex_64(&participant.source_user) { + return Err(Malformed( + "participant source_user must be 64 lowercase hex", + )); + } + if !seen.insert(participant.pubkey.as_str()) { + return Err(Malformed("duplicate participant pubkey")); + } + let total = participant + .messages + .checked_add(participant.reactions) + .filter(|total| *total <= limits.max_events_per_participant) + .ok_or(CountsExceedLimit)?; + session_total = session_total + .checked_add(total) + .filter(|total| *total <= limits.max_events_per_session) + .ok_or(CountsExceedLimit)?; + } + if !is_lower_hex_64(&content.manifest) { + return Err(Malformed("manifest must be 64 lowercase hex")); + } + Ok(()) +} + +/// Validate a decoded proposal's tags against its content: the `p` tags +/// equal the participant set (sorted ascending), the single `manifest` tag +/// equals `content.manifest`, and the single `import-source` tag equals +/// `source.type`. +pub fn validate_proposal_tags( + event: &nostr::Event, + content: &ImportProposalContent, +) -> Result<(), &'static str> { + let mut p_tags = Vec::new(); + let mut manifest = Vec::new(); + let mut import_source = Vec::new(); + for tag in event.tags.iter() { + let slice = tag.as_slice(); + match (slice.first().map(String::as_str), slice.get(1)) { + (Some("p"), Some(v)) => p_tags.push(v.as_str()), + (Some(MANIFEST_TAG), Some(v)) => manifest.push(v.as_str()), + (Some(IMPORT_SOURCE_TAG), Some(v)) => import_source.push(v.as_str()), + _ => {} + } + } + let mut expected: Vec<&str> = content + .participants + .iter() + .map(|p| p.pubkey.as_str()) + .collect(); + expected.sort_unstable(); + if p_tags != expected { + return Err("p tags must list every participant, sorted ascending"); + } + if manifest != [content.manifest.as_str()] { + return Err("manifest tag must equal content manifest"); + } + if import_source != [content.source.source_type.as_str()] { + return Err("import-source tag must equal source type"); + } + Ok(()) +} + +/// Tag names a control event of `kind` may carry. Anything else is refused, +/// so a record's tags are exactly what the session state was derived from. +pub fn allowed_control_tags(kind: u32) -> &'static [&'static str] { + use crate::kind::{ + KIND_IMPORT_COMPLETE, KIND_IMPORT_CONSENT, KIND_IMPORT_PROPOSAL, KIND_IMPORT_WITHDRAW, + }; + match kind { + KIND_IMPORT_PROPOSAL => &["h", "p", MANIFEST_TAG, IMPORT_SOURCE_TAG], + KIND_IMPORT_CONSENT => &["e", "h", MANIFEST_TAG, "p"], + KIND_IMPORT_WITHDRAW | KIND_IMPORT_COMPLETE => &["e", "h"], + _ => &[], + } +} + +/// The first tag name on a control event that its kind does not allow. +pub fn first_unexpected_control_tag(event: &nostr::Event, kind: u32) -> Option<&str> { + let allowed = allowed_control_tags(kind); + event + .tags + .iter() + .filter_map(|tag| tag.as_slice().first()) + .map(String::as_str) + .find(|name| !allowed.contains(name)) +} + +/// Cap a requested expiry at `now + max_days`. A requested expiry already in +/// the past is kept, so the session is immediately expired. +pub fn cap_expires_at(requested: i64, now: i64, max_days: u32) -> i64 { + let cap = now.saturating_add(i64::from(max_days).saturating_mul(86_400)); + requested.min(cap) +} + +/// Per-participant state used by [`derive_status`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParticipantState { + /// Participant pubkey, lowercase hex. + pub pubkey: String, + /// Latest consent; the proposer starts as `Accept`. + pub consent: Option, + /// Whether this participant sent 42113. + pub completed: bool, +} + +/// Stored session facts used to derive the next status. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionFacts { + /// Status currently stored. + pub status: ImportSessionStatus, + /// Whether the destination channel is a DM. + pub is_dm: bool, + /// Whether an admin consent is required. + pub requires_admin: bool, + /// Latest channel-admin consent, if any. + pub admin_consent: Option, + /// Effective expiry, unix seconds. + pub expires_at: i64, + /// Every participant, in any order. + pub participants: Vec, +} + +/// Derive the session status from stored facts at time `now`. +/// +/// Terminal statuses never change. Past `expires_at`, a non-terminal session +/// is `expired`. In a DM any decline ends the session as `declined`. A +/// required admin decline ends the session as `declined` before activation +/// and `withdrawn` after it. In a +/// channel, a decline before activation is `declined`; a decline after +/// activation withdraws only that participant and the session stays +/// `active`, or becomes `withdrawn` once no accepting participant remains. +/// The session is `completed` once it is active and every accepting +/// participant has completed. +pub fn derive_status(facts: &SessionFacts, now: i64) -> ImportSessionStatus { + if facts.status.is_terminal() { + return facts.status; + } + if now > facts.expires_at { + return ImportSessionStatus::Expired; + } + if facts.requires_admin && facts.admin_consent == Some(ImportDecision::Decline) { + return if facts.status == ImportSessionStatus::Active { + ImportSessionStatus::Withdrawn + } else { + ImportSessionStatus::Declined + }; + } + let is_accept = |p: &&ParticipantState| p.consent == Some(ImportDecision::Accept); + let any_decline = facts + .participants + .iter() + .any(|p| p.consent == Some(ImportDecision::Decline)); + if any_decline && (facts.is_dm || facts.status == ImportSessionStatus::Proposed) { + return ImportSessionStatus::Declined; + } + let all_accepted = facts.participants.iter().all(|p| is_accept(&p)); + let admin_ok = !facts.requires_admin || facts.admin_consent == Some(ImportDecision::Accept); + let active = facts.status == ImportSessionStatus::Active || (all_accepted && admin_ok); + if !active { + return ImportSessionStatus::Proposed; + } + let mut accepting = facts.participants.iter().filter(is_accept).peekable(); + if accepting.peek().is_none() { + return ImportSessionStatus::Withdrawn; + } + if accepting.all(|p| p.completed) { + return ImportSessionStatus::Completed; + } + ImportSessionStatus::Active +} + +/// Author-specific facts for rules 3 to 6. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorFacts { + /// The author's latest consent, `None` while undecided. + pub consent: Option, + /// Whether the author already sent 42113. + pub completed: bool, + /// Counts declared in the proposal. + pub declared: ImportCounts, + /// Counts already accepted under this session. + pub published: ImportCounts, +} + +/// Evaluate rules 3 to 6 for one imported event. +/// +/// `author` is `None` when the event author is not a listed participant. +/// `status` must already be derived with [`derive_status`] at `now`. +pub fn evaluate_import_rules( + status: ImportSessionStatus, + range: ImportRange, + author: Option<&AuthorFacts>, + kind: u32, + created_at: i64, + now: i64, +) -> Result<(), &'static str> { + if status != ImportSessionStatus::Active { + return Err(reason::SESSION_NOT_ACTIVE); + } + let Some(author) = author else { + return Err(reason::NOT_CONSENTING); + }; + if author.consent != Some(ImportDecision::Accept) { + return Err(reason::NOT_CONSENTING); + } + if author.completed { + return Err(reason::SESSION_NOT_ACTIVE); + } + if created_at < range.from + || created_at > range.to + || created_at > now.saturating_add(IMPORT_FUTURE_SKEW_SECS) + { + return Err(reason::TIMESTAMP_OUT_OF_RANGE); + } + let within = if kind == KIND_REACTION { + author.published.reactions < author.declared.reactions + } else { + author.published.messages < author.declared.messages + }; + if !within { + return Err(reason::COUNT_EXCEEDED); + } + Ok(()) +} + +/// Whether an accepted import event crosses a snapshot republish boundary +/// for its author (every [`SNAPSHOT_REPUBLISH_EVERY`] events, messages and +/// reactions combined). +pub fn crosses_republish_boundary(published_after: ImportCounts) -> bool { + let total = published_after + .messages + .saturating_add(published_after.reactions); + total > 0 && total.is_multiple_of(SNAPSHOT_REPUBLISH_EVERY) +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + const HEX_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const HEX_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + const HEX_C: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + + fn proposal() -> ImportProposalContent { + ImportProposalContent { + v: 1, + source: ImportSource { + source_type: "test".into(), + conversation: HEX_C.into(), + kind: ImportSourceKind::Dm, + label: "Direct message".into(), + }, + range: ImportRange { + from: 1_000, + to: 2_000, + }, + participants: vec![ + ImportParticipant { + pubkey: HEX_A.into(), + source_user: HEX_C.into(), + messages: 3, + reactions: 1, + }, + ImportParticipant { + pubkey: HEX_B.into(), + source_user: HEX_C.into(), + messages: 2, + reactions: 0, + }, + ], + excluded_authors: 0, + manifest: HEX_C.into(), + expires_at: 5_000, + } + } + + fn event(kind: u16, tags: &[&[&str]]) -> nostr::Event { + let tags: Vec = tags + .iter() + .map(|t| Tag::parse(t.iter().copied()).expect("tag")) + .collect(); + EventBuilder::new(Kind::Custom(kind), "x") + .tags(tags) + .sign_with_keys(&Keys::generate()) + .expect("sign") + } + + #[test] + fn proposal_round_trips_with_spec_key_order() { + let content = proposal(); + let json = serde_json::to_string(&content).expect("serialize"); + assert!(json.starts_with(r#"{"v":1,"source":{"type":"test","conversation":"#)); + let order = [ + "\"source\"", + "\"range\"", + "\"participants\"", + "\"excluded_authors\"", + "\"manifest\"", + "\"expires_at\"", + ]; + let positions: Vec = order.iter().map(|k| json.find(k).expect("key")).collect(); + assert!(positions.windows(2).all(|w| w[0] < w[1])); + assert!(json.contains(r#""kind":"dm""#)); + let back: ImportProposalContent = serde_json::from_str(&json).expect("parse"); + assert_eq!(back, content); + } + + #[test] + fn source_kinds_use_snake_case() { + for (kind, wire) in [ + (ImportSourceKind::Dm, "\"dm\""), + (ImportSourceKind::GroupDm, "\"group_dm\""), + (ImportSourceKind::PrivateChannel, "\"private_channel\""), + (ImportSourceKind::PublicChannel, "\"public_channel\""), + ] { + assert_eq!(serde_json::to_string(&kind).expect("ser"), wire); + } + } + + #[test] + fn consent_withdraw_complete_round_trip() { + let consent = ImportConsentContent { + v: 1, + decision: ImportDecision::Accept, + source_user: HEX_A.into(), + }; + let json = serde_json::to_string(&consent).expect("ser"); + assert_eq!( + json, + format!(r#"{{"v":1,"decision":"accept","source_user":"{HEX_A}"}}"#) + ); + assert_eq!( + serde_json::from_str::(&json).expect("de"), + consent + ); + + let withdraw: ImportWithdrawContent = serde_json::from_str(r#"{"v":1}"#).expect("de"); + assert_eq!(withdraw.reason, None); + assert_eq!(serde_json::to_string(&withdraw).expect("ser"), r#"{"v":1}"#); + let withdraw = ImportWithdrawContent { + v: 1, + reason: Some("changed my mind".into()), + }; + let json = serde_json::to_string(&withdraw).expect("ser"); + assert_eq!( + serde_json::from_str::(&json).expect("de"), + withdraw + ); + + let complete = ImportCompleteContent { + v: 1, + published: ImportCounts { + messages: 4, + reactions: 2, + }, + }; + let json = serde_json::to_string(&complete).expect("ser"); + assert_eq!(json, r#"{"v":1,"published":{"messages":4,"reactions":2}}"#); + assert_eq!( + serde_json::from_str::(&json).expect("de"), + complete + ); + } + + #[test] + fn snapshot_round_trips() { + let mut consents = BTreeMap::new(); + consents.insert(HEX_A.to_string(), ImportDecision::Accept); + consents.insert(HEX_B.to_string(), ImportDecision::Decline); + let mut published = BTreeMap::new(); + published.insert( + HEX_A.to_string(), + ImportCounts { + messages: 1, + reactions: 0, + }, + ); + let snapshot = ImportSessionSnapshotContent { + v: 1, + status: ImportSessionStatus::Declined, + required: vec![HEX_A.into(), HEX_B.into()], + consents, + published, + completed: vec![], + expires_at: 9, + }; + let json = serde_json::to_string(&snapshot).expect("ser"); + assert!(json.starts_with(r#"{"v":1,"status":"declined","required":["#)); + assert_eq!( + serde_json::from_str::(&json).expect("de"), + snapshot + ); + } + + #[test] + fn negative_counts_and_unknown_fields_fail_to_parse() { + let mut value = serde_json::to_value(proposal()).expect("ser"); + value["participants"][0]["messages"] = serde_json::json!(-1); + assert!(serde_json::from_value::(value).is_err()); + let mut value = serde_json::to_value(proposal()).expect("ser"); + value["extra"] = serde_json::json!(true); + assert!(serde_json::from_value::(value).is_err()); + } + + #[test] + fn status_and_decision_strings_round_trip() { + for status in [ + ImportSessionStatus::Proposed, + ImportSessionStatus::Active, + ImportSessionStatus::Declined, + ImportSessionStatus::Withdrawn, + ImportSessionStatus::Expired, + ImportSessionStatus::Completed, + ] { + assert_eq!(ImportSessionStatus::parse(status.as_str()), Some(status)); + } + assert_eq!( + ImportDecision::parse("accept"), + Some(ImportDecision::Accept) + ); + assert_eq!(ImportDecision::parse("nope"), None); + } + + #[test] + fn proposal_validation_rules() { + const T: i64 = 1_700_000_000; + let now = T + 3_000; + let limits = ImportLimits::default(); + let good = || { + let mut p = proposal(); + p.range = ImportRange { + from: T + 1_000, + to: T + 2_000, + }; + p + }; + let check = |p: &ImportProposalContent| validate_proposal_content(p, now, limits); + assert_eq!(check(&good()), Ok(())); + + let mut bad = good(); + bad.range.from = bad.range.to; + assert!(check(&bad).is_err()); + let mut bad = good(); + bad.range.to = now + 1; + assert!(check(&bad).is_err()); + let mut bad = good(); + bad.range.from = MIN_IMPORT_RANGE_FROM - 1; + assert!(matches!(check(&bad), Err(ProposalRejection::Malformed(_)))); + let mut bad = good(); + bad.participants.clear(); + assert!(check(&bad).is_err()); + let mut bad = good(); + let template = bad.participants[0].clone(); + bad.participants = (0..65) + .map(|i| ImportParticipant { + pubkey: format!("{i:064x}"), + ..template.clone() + }) + .collect(); + assert!(check(&bad).is_err()); + let mut bad = good(); + bad.manifest = HEX_A.to_uppercase(); + assert!(check(&bad).is_err()); + let mut bad = good(); + bad.source.source_type = "Upper".into(); + assert!(check(&bad).is_err()); + let mut bad = good(); + bad.source.label = "x".repeat(81); + assert!(check(&bad).is_err()); + let mut bad = good(); + bad.participants[1].pubkey = HEX_A.into(); + assert!(check(&bad).is_err()); + } + + #[test] + fn proposal_counts_are_capped() { + const T: i64 = 1_700_000_000; + let limits = ImportLimits { + max_events_per_participant: 10, + max_events_per_session: 15, + ..ImportLimits::default() + }; + let mut p = proposal(); + p.range = ImportRange { from: T, to: T + 1 }; + let check = |p: &ImportProposalContent| validate_proposal_content(p, T + 2, limits); + p.participants[0].messages = 6; + p.participants[0].reactions = 4; + p.participants[1].messages = 5; + assert_eq!(check(&p), Ok(())); + p.participants[0].reactions = 5; + assert_eq!(check(&p), Err(ProposalRejection::CountsExceedLimit)); + p.participants[0].reactions = 4; + p.participants[1].reactions = 1; + assert_eq!(check(&p), Err(ProposalRejection::CountsExceedLimit)); + p.participants[1].reactions = 0; + p.participants[0].messages = u64::MAX; + assert_eq!(check(&p), Err(ProposalRejection::CountsExceedLimit)); + assert_eq!( + ProposalRejection::CountsExceedLimit.reason(), + "invalid: import counts exceed the relay limit" + ); + assert_eq!( + ProposalRejection::Malformed("x").reason(), + "invalid: import event malformed: x" + ); + } + + #[test] + fn proposal_tags_must_match_content() { + let content = proposal(); + let good = event( + 42110, + &[ + &["h", "chan"], + &["p", HEX_A], + &["p", HEX_B], + &["manifest", HEX_C], + &["import-source", "test"], + ], + ); + assert_eq!(validate_proposal_tags(&good, &content), Ok(())); + let unsorted = event( + 42110, + &[ + &["h", "chan"], + &["p", HEX_B], + &["p", HEX_A], + &["manifest", HEX_C], + &["import-source", "test"], + ], + ); + assert!(validate_proposal_tags(&unsorted, &content).is_err()); + let wrong_manifest = event( + 42110, + &[ + &["h", "chan"], + &["p", HEX_A], + &["p", HEX_B], + &["manifest", HEX_A], + &["import-source", "test"], + ], + ); + assert!(validate_proposal_tags(&wrong_manifest, &content).is_err()); + } + + #[test] + fn control_events_carry_only_their_spec_tags() { + let cases: [(u32, &[&[&str]]); 4] = [ + ( + 42110, + &[ + &["h", "chan"], + &["p", HEX_A], + &["manifest", HEX_C], + &["import-source", "test"], + ], + ), + ( + 42111, + &[ + &["e", HEX_A], + &["h", "chan"], + &["manifest", HEX_C], + &["p", HEX_B], + ], + ), + (42112, &[&["e", HEX_A], &["h", "chan"]]), + (42113, &[&["e", HEX_A], &["h", "chan"]]), + ]; + for (kind, tags) in cases { + assert_eq!( + first_unexpected_control_tag(&event(kind as u16, tags), kind), + None + ); + for extra in ["ms", "client-id"] { + let mut with_extra = tags.to_vec(); + let tag = [extra, "1"]; + with_extra.push(&tag); + assert_eq!( + first_unexpected_control_tag(&event(kind as u16, &with_extra), kind), + Some(extra), + "kind {kind} accepted {extra}" + ); + } + } + let withdraw_with_manifest = event(42112, &[&["e", HEX_A], &["manifest", HEX_C]]); + assert_eq!( + first_unexpected_control_tag(&withdraw_with_manifest, 42112), + Some("manifest") + ); + } + + #[test] + fn import_tag_parsing_rule_one() { + let plain = event(9, &[&["h", "chan"]]); + assert_eq!(parse_import_tags(&plain), Ok(None)); + assert!(!is_import_event(&plain)); + + let good = event( + 9, + &[ + &["h", "chan"], + &["import", HEX_A], + &["source", "test", "1.2"], + ], + ); + assert!(is_import_event(&good)); + assert_eq!( + parse_import_tags(&good), + Ok(Some(ImportTags { + proposal_id: HEX_A.into(), + proposal_bytes: [0xaa; 32], + source_type: "test".into(), + source_ref: "1.2".into(), + })) + ); + + let wrong_kind = event(1, &[&["import", HEX_A], &["source", "test", "1"]]); + assert_eq!( + parse_import_tags(&wrong_kind), + Err(reason::KIND_NOT_ALLOWED) + ); + + let two_imports = event( + 7, + &[ + &["import", HEX_A], + &["import", HEX_B], + &["source", "test", "1"], + ], + ); + assert_eq!(parse_import_tags(&two_imports), Err(reason::TAGS_MALFORMED)); + + let no_source = event(9, &[&["import", HEX_A]]); + assert_eq!(parse_import_tags(&no_source), Err(reason::TAGS_MALFORMED)); + + let bad_id = event(9, &[&["import", "xyz"], &["source", "test", "1"]]); + assert_eq!(parse_import_tags(&bad_id), Err(reason::TAGS_MALFORMED)); + } + + #[test] + fn expiry_is_capped() { + assert_eq!(cap_expires_at(10_000_000, 0, 30), 30 * 86_400); + assert_eq!(cap_expires_at(100, 0, 30), 100); + } + + fn facts( + status: ImportSessionStatus, + is_dm: bool, + consents: &[Option], + ) -> SessionFacts { + SessionFacts { + status, + is_dm, + requires_admin: false, + admin_consent: None, + expires_at: 100, + participants: consents + .iter() + .enumerate() + .map(|(i, c)| ParticipantState { + pubkey: format!("{i:064x}"), + consent: *c, + completed: false, + }) + .collect(), + } + } + + #[test] + fn status_derivation() { + use ImportDecision::{Accept, Decline}; + use ImportSessionStatus::*; + let f = facts(Proposed, true, &[Some(Accept), None]); + assert_eq!(derive_status(&f, 50), Proposed); + let f = facts(Proposed, true, &[Some(Accept), Some(Accept)]); + assert_eq!(derive_status(&f, 50), Active); + assert_eq!(derive_status(&f, 101), Expired); + let f = facts(Active, true, &[Some(Accept), Some(Decline)]); + assert_eq!(derive_status(&f, 50), Declined); + let f = facts(Proposed, false, &[Some(Accept), Some(Decline)]); + assert_eq!(derive_status(&f, 50), Declined); + let f = facts(Active, false, &[Some(Accept), Some(Decline)]); + assert_eq!(derive_status(&f, 50), Active); + let f = facts(Active, false, &[Some(Decline), Some(Decline)]); + assert_eq!(derive_status(&f, 50), Withdrawn); + let f = facts(Withdrawn, false, &[Some(Accept), Some(Accept)]); + assert_eq!(derive_status(&f, 50), Withdrawn); + + let mut f = facts(Proposed, false, &[Some(Accept), Some(Accept)]); + f.requires_admin = true; + assert_eq!(derive_status(&f, 50), Proposed); + f.admin_consent = Some(Accept); + assert_eq!(derive_status(&f, 50), Active); + f.admin_consent = Some(Decline); + assert_eq!(derive_status(&f, 50), Declined); + f.status = Active; + assert_eq!(derive_status(&f, 50), Withdrawn); + + let mut f = facts(Active, false, &[Some(Accept), Some(Decline)]); + f.participants[0].completed = true; + assert_eq!(derive_status(&f, 50), Completed); + } + + #[test] + fn acceptance_rules_three_to_six() { + use ImportSessionStatus::*; + let range = ImportRange { from: 10, to: 20 }; + let author = AuthorFacts { + consent: Some(ImportDecision::Accept), + completed: false, + declared: ImportCounts { + messages: 1, + reactions: 1, + }, + published: ImportCounts::default(), + }; + let now = 1_000; + assert_eq!( + evaluate_import_rules(Active, range, Some(&author), 9, 15, now), + Ok(()) + ); + assert_eq!( + evaluate_import_rules(Proposed, range, Some(&author), 9, 15, now), + Err(reason::SESSION_NOT_ACTIVE) + ); + assert_eq!( + evaluate_import_rules(Active, range, None, 9, 15, now), + Err(reason::NOT_CONSENTING) + ); + let undecided = AuthorFacts { + consent: None, + ..author.clone() + }; + assert_eq!( + evaluate_import_rules(Active, range, Some(&undecided), 9, 15, now), + Err(reason::NOT_CONSENTING) + ); + let done = AuthorFacts { + completed: true, + ..author.clone() + }; + assert_eq!( + evaluate_import_rules(Active, range, Some(&done), 9, 15, now), + Err(reason::SESSION_NOT_ACTIVE) + ); + assert_eq!( + evaluate_import_rules(Active, range, Some(&author), 9, 9, now), + Err(reason::TIMESTAMP_OUT_OF_RANGE) + ); + assert_eq!( + evaluate_import_rules(Active, range, Some(&author), 9, 21, now), + Err(reason::TIMESTAMP_OUT_OF_RANGE) + ); + let future_range = ImportRange { + from: 10, + to: 5_000, + }; + assert_eq!( + evaluate_import_rules(Active, future_range, Some(&author), 9, now + 901, now), + Err(reason::TIMESTAMP_OUT_OF_RANGE) + ); + let full = AuthorFacts { + published: ImportCounts { + messages: 1, + reactions: 0, + }, + ..author.clone() + }; + assert_eq!( + evaluate_import_rules(Active, range, Some(&full), 9, 15, now), + Err(reason::COUNT_EXCEEDED) + ); + assert_eq!( + evaluate_import_rules(Active, range, Some(&full), 7, 15, now), + Ok(()) + ); + } + + #[test] + fn republish_boundary_every_fifty() { + assert!(!crosses_republish_boundary(ImportCounts::default())); + assert!(!crosses_republish_boundary(ImportCounts { + messages: 49, + reactions: 0 + })); + assert!(crosses_republish_boundary(ImportCounts { + messages: 30, + reactions: 20 + })); + assert!(crosses_republish_boundary(ImportCounts { + messages: 100, + reactions: 0 + })); + } +} diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index ae7a6221ebc..4f3a923e1b8 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -373,6 +373,17 @@ pub const KIND_REPORT: u32 = 1984; /// deployment feedback table, and never stored or fanned out as an event. pub const KIND_PRODUCT_FEEDBACK: u32 = 42000; +// Conversation import (42100-42199). See `docs/nips/NIP-CI.md`. +/// NIP-CI: import proposal. Proposer-signed, scoped to one channel `h`; opens an +/// import session whose id is this event's id. +pub const KIND_IMPORT_PROPOSAL: u32 = 42110; +/// NIP-CI: import consent (accept or decline) from one proposal participant. +pub const KIND_IMPORT_CONSENT: u32 = 42111; +/// NIP-CI: import withdraw. Ends the session; sent by the proposer or a participant. +pub const KIND_IMPORT_WITHDRAW: u32 = 42112; +/// NIP-CI: import complete. A participant marks its own publishing as finished. +pub const KIND_IMPORT_COMPLETE: u32 = 42113; + // NIP-29 group admin events /// NIP-29: Add a user to a group. pub const KIND_NIP29_PUT_USER: u32 = 9000; @@ -493,6 +504,12 @@ pub const KIND_WORKFLOW_DEF: u32 = 30620; /// `hidden_at` per viewer; this is the only Nostr-visible projection of it. pub const KIND_DM_VISIBILITY: u32 = 30622; +/// NIP-CI: import session snapshot (relay-signed, parameterized replaceable, +/// d=proposal event id). Republished by the relay after every accepted import +/// control event, every 50 accepted imported events per participant, and on +/// completion. Readable by channel members only. +pub const KIND_IMPORT_SESSION_SNAPSHOT: u32 = 30623; + /// Lower bound of the NIP-33 parameterized replaceable range (30000–39999). pub const PARAM_REPLACEABLE_KIND_MIN: u32 = 30000; /// Upper bound of the NIP-33 parameterized replaceable range (30000–39999). @@ -713,6 +730,10 @@ pub const ALL_KINDS: &[u32] = &[ KIND_PRIVATE_MANAGED_AGENT, KIND_REPORT, KIND_PRODUCT_FEEDBACK, + KIND_IMPORT_PROPOSAL, + KIND_IMPORT_CONSENT, + KIND_IMPORT_WITHDRAW, + KIND_IMPORT_COMPLETE, KIND_NIP29_PUT_USER, KIND_NIP29_REMOVE_USER, KIND_NIP29_EDIT_METADATA, @@ -769,6 +790,7 @@ pub const ALL_KINDS: &[u32] = &[ KIND_CHANNEL_SUMMARY, KIND_PRESENCE_SNAPSHOT, KIND_DM_VISIBILITY, + KIND_IMPORT_SESSION_SNAPSHOT, KIND_DM_OPEN, KIND_DM_ADD_MEMBER, KIND_DM_HIDE, @@ -885,6 +907,15 @@ pub const fn is_command_kind(kind: u32) -> bool { ) } +/// Returns `true` if `kind` is a NIP-CI conversation import control kind +/// (proposal, consent, withdraw, complete). +pub const fn is_import_control_kind(kind: u32) -> bool { + matches!( + kind, + KIND_IMPORT_PROPOSAL | KIND_IMPORT_CONSENT | KIND_IMPORT_WITHDRAW | KIND_IMPORT_COMPLETE + ) +} + /// NIP-85 relay-signed NIP-FI verified profile (output only). pub const KIND_VERIFIED_PROFILE: u32 = 30382; @@ -899,6 +930,7 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { | KIND_CHANNEL_SUMMARY | KIND_PRESENCE_SNAPSHOT | KIND_DM_VISIBILITY + | KIND_IMPORT_SESSION_SNAPSHOT | KIND_THREAD_SUMMARY | KIND_WINDOW_BOUNDS | KIND_THREAD_WINDOW_BOUNDS @@ -927,6 +959,14 @@ const _: () = assert!(is_parameterized_replaceable(KIND_PRIVATE_MANAGED_AGENT)); const _: () = assert!(is_parameterized_replaceable(KIND_WORKFLOW_DEF)); // 30620 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_EVENT_REMINDER)); // 30300 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_DM_VISIBILITY)); // 30622 ∈ 30000–39999 + +// 30623 is parameterized replaceable; the NIP-CI control kinds are regular +// stored events. +const _: () = assert!(is_parameterized_replaceable(KIND_IMPORT_SESSION_SNAPSHOT)); +const _: () = assert!(!is_parameterized_replaceable(KIND_IMPORT_PROPOSAL)); +const _: () = assert!(!is_replaceable(KIND_IMPORT_PROPOSAL)); +const _: () = assert!(!is_ephemeral(KIND_IMPORT_COMPLETE)); +const _: () = assert!(KIND_IMPORT_COMPLETE <= u16::MAX as u32); const _: () = assert!(is_parameterized_replaceable(KIND_PROJECT)); // 30621 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_THREAD_SUMMARY)); // 39005 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_WINDOW_BOUNDS)); // 39006 ∈ 30000–39999 @@ -985,6 +1025,22 @@ mod tests { assert!(is_relay_only_kind(KIND_THREAD_WINDOW_BOUNDS)); } + #[test] + fn import_kinds_are_registered() { + assert!(is_relay_only_kind(KIND_IMPORT_SESSION_SNAPSHOT)); + for kind in [ + KIND_IMPORT_PROPOSAL, + KIND_IMPORT_CONSENT, + KIND_IMPORT_WITHDRAW, + KIND_IMPORT_COMPLETE, + ] { + assert!(is_import_control_kind(kind)); + assert!(!is_relay_only_kind(kind)); + assert!(ALL_KINDS.contains(&kind)); + } + assert!(!is_import_control_kind(KIND_IMPORT_SESSION_SNAPSHOT)); + } + #[test] fn parameterized_replaceable_range() { assert!(!is_parameterized_replaceable(29999)); diff --git a/crates/buzz-core/src/lib.rs b/crates/buzz-core/src/lib.rs index 99b4aa68032..a832bb1260c 100644 --- a/crates/buzz-core/src/lib.rs +++ b/crates/buzz-core/src/lib.rs @@ -20,6 +20,8 @@ pub mod event; pub mod filter; /// Git permission types — ref patterns, protection rules, policy evaluation. pub mod git_perms; +/// NIP-CI conversation import: payloads, tag helpers and pure acceptance rules. +pub mod import; /// Shared invite-link contract constants. pub mod invite; /// Buzz kind number registry — custom event type constants. From 0be1af0477d14b365bf949c55d955f1bac873f6d Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:43:25 -0600 Subject: [PATCH 2/5] feat(db): import session store with atomic counters and quiet imported writes Adds import_sessions and import_session_participants, the session store that applies control events and imported events under the session row lock and republishes the relay-signed snapshot, and keeps imported events out of mention rows, the listener outbox, unread evidence and thread activity. New proposals are refused once the channel or the proposer holds the configured number of unended sessions; both counts run under transaction-scoped advisory locks. Every imported event rechecks that its author is not an agent. At this commit the replica-fence floor still refuses an imported event's original timestamp, so the tests here cover sessions, consent, caps, expiry and deletion; the next commit adds the transaction-local floor exception, the covered-read guard that keeps it sound, and the tests that store imported events. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- crates/buzz-db/src/lib.rs | 3 + crates/buzz-db/src/runtime/admitted_tx.rs | 6 + crates/buzz-db/src/runtime/migration.rs | 6 +- crates/buzz-db/src/runtime/mod.rs | 6 + crates/buzz-db/src/store/deletion.rs | 92 ++ crates/buzz-db/src/store/event.rs | 10 +- crates/buzz-db/src/store/feed.rs | 35 +- crates/buzz-db/src/store/import_session.rs | 1351 +++++++++++++++++ .../store/import_session/postgres_tests.rs | 627 ++++++++ crates/buzz-db/src/store/mod.rs | 3 + crates/buzz-db/src/store/operator_listener.rs | 3 +- .../src/store/personal_read/projection.rs | 4 + .../0081_conversation_import_sessions.sql | 44 + schema/schema.sql | 2 + .../public/import_session_participants.sql | 14 + schema/tables/public/import_sessions.sql | 23 + 16 files changed, 2223 insertions(+), 6 deletions(-) create mode 100644 crates/buzz-db/src/store/import_session.rs create mode 100644 crates/buzz-db/src/store/import_session/postgres_tests.rs create mode 100644 migrations/0081_conversation_import_sessions.sql create mode 100644 schema/tables/public/import_session_participants.sql create mode 100644 schema/tables/public/import_sessions.sql diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index eb3f9ed7783..55678c51b45 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -93,3 +93,6 @@ use buzz_core::CommunityId; /// Durable NIP-FI verified-profile projection state. pub use store::verified_profiles; + +/// NIP-CI conversation import session state. +pub use store::import_session; diff --git a/crates/buzz-db/src/runtime/admitted_tx.rs b/crates/buzz-db/src/runtime/admitted_tx.rs index 2e4ce60a758..a9271864cf9 100644 --- a/crates/buzz-db/src/runtime/admitted_tx.rs +++ b/crates/buzz-db/src/runtime/admitted_tx.rs @@ -154,6 +154,12 @@ impl AdmittedTx { } } + /// Drop the TTL refresh recorded so far, for writes that are not channel + /// activity. + pub(crate) fn skip_ttl_refresh(&mut self) { + self.ttl_refresh_channels.clear(); + } + /// Commit the transaction. This is the only commit path for admitted /// writes. /// diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index c78a99eab5b..d8a5fb326b7 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -777,7 +777,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 80); + assert_eq!(migrations.len(), 81); for (index, migration) in migrations.iter().enumerate() { assert_eq!(migration.version, (index + 1) as i64); } @@ -2897,6 +2897,8 @@ mod postgres_tests { "communities", "entity_deletion_stage_history", "user_deletion_fences", + "import_sessions", + "import_session_participants", ] { assert_eq!( columns(&desired, table).await, @@ -2935,6 +2937,8 @@ mod postgres_tests { "entity_deletion_stage_history", "user_deletion_fences", "entity_deletion_approvals", + "import_sessions", + "import_session_participants", ] { assert_eq!( constraints(&desired, table).await, diff --git a/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index 061076cae1c..b3d48168d2e 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -53,11 +53,17 @@ pub async fn insert_mentions( /// Insert mention rows on the caller's admitted transaction. Replacement /// writes use this so the authoritative event and its discovery index commit /// or roll back as one unit. +/// +/// NIP-CI imported events are history, not new activity: they never create +/// mention rows, so they never reach the mention feed or inbox. pub(crate) async fn insert_mentions_in_transaction( tx: &mut AdmittedTx, event: &nostr::Event, channel_id: Option, ) -> Result<()> { + if buzz_core::import::is_import_event(event) { + return Ok(()); + } let community_id = tx.community(); let p_tags: Vec<&str> = event .tags diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 9c1eb2f433b..a907955155b 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -92,6 +92,8 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "event_mentions", "events", "git_repo_names", + "import_session_participants", + "import_sessions", "join_policy_acceptances", "moderation_actions", "moderation_reports", @@ -131,6 +133,8 @@ const EXCLUDED_SCOPED_TABLES: &[&str] = &[ /// Foreign-key-safe child-before-parent order for the PostgreSQL purge. pub const PURGE_SCOPED_TABLES: &[&str] = &[ "nip_fi_profile_heads", + "import_session_participants", + "import_sessions", "personal_read_frontiers", "personal_read_accounts", "workflow_approvals", @@ -8762,6 +8766,94 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("verify after straggler removed"); } + /// NIP-CI import session rows are tenant-owned: purge removes the target + /// community's sessions and participants and leaves a bystander's alone. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn purge_postgres_removes_import_session_rows() { + async fn seed(db: &Db, community: Uuid) { + let proposal = Uuid::new_v4().as_bytes().to_vec(); + sqlx::query( + "INSERT INTO import_sessions (community_id, proposal_id, channel_id, proposer, \ + manifest, source_type, is_dm, range_from, range_to, expires_at, \ + requires_admin, status) \ + VALUES ($1, $2, $3, $4, 'm', 'test', false, 1, 2, 3, false, 'proposed')", + ) + .bind(community) + .bind(&proposal) + .bind(Uuid::new_v4()) + .bind([1u8; 32].as_slice()) + .execute(&db.pool) + .await + .expect("seed import session"); + sqlx::query( + "INSERT INTO import_session_participants (community_id, proposal_id, pubkey, \ + source_user, declared_messages, declared_reactions) \ + VALUES ($1, $2, $3, 's', 1, 0)", + ) + .bind(community) + .bind(&proposal) + .bind([1u8; 32].as_slice()) + .execute(&db.pool) + .await + .expect("seed import participant"); + } + async fn counts(db: &Db, community: Uuid) -> (i64, i64) { + sqlx::query_as( + "SELECT (SELECT count(*) FROM import_sessions WHERE community_id = $1), \ + (SELECT count(*) FROM import_session_participants WHERE community_id = $1)", + ) + .bind(community) + .fetch_one(&db.pool) + .await + .expect("count import rows") + } + + let (db, store) = store().await; + let (request, inventory) = inventoried_request(&db, &store).await; + let community = *request.community_id.as_uuid(); + seed(&db, community).await; + let bystander = db + .ensure_configured_community(&format!("bystander-{}.example", Uuid::new_v4().simple())) + .await + .expect("create bystander community") + .id + .as_uuid() + .to_owned(); + seed(&db, bystander).await; + + store + .approve(request.id, "approver", None) + .await + .expect("approve"); + let claim = store + .claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION) + .await + .expect("claim") + .expect("won claim"); + store.begin_quiescing(&claim.lease).await.expect("quiesce"); + let generation = store.fence(&claim.lease).await.expect("fence"); + let token = LeaseToken { + fence_generation: Some(generation), + ..claim.lease + }; + store + .freeze_destructive_storage_manifest(&token, &inventory.storage) + .await + .expect("freeze destructive storage"); + store.mark_drained(&token).await.expect("drain"); + store + .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) + .await + .expect("bindings"); + let deleted = store.purge_postgres(&token).await.expect("purge postgres"); + + assert_eq!(deleted.get("import_sessions"), Some(&1)); + assert_eq!(deleted.get("import_session_participants"), Some(&1)); + assert_eq!(counts(&db, community).await, (0, 0)); + assert_eq!(counts(&db, bystander).await, (1, 1)); + } + /// A database bootstrapped from `schema/schema.sql` (the pgschema /// desired-state path — no migrations) must carry the complete 0028 /// deletion surface and run a deletion through every stage. diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index bf80e302d44..8d62f962b4a 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -2007,15 +2007,23 @@ pub(crate) async fn insert_event_with_thread_metadata_tx( } } + // An imported reply carries its original time; it must not + // make a historical thread look freshly active. sqlx::query( r#" UPDATE thread_metadata - SET reply_count = reply_count + 1, last_reply_at = NOW() + SET reply_count = reply_count + 1, + last_reply_at = CASE + WHEN $3 THEN GREATEST(COALESCE(last_reply_at, $4), $4) + ELSE NOW() + END WHERE community_id = $1 AND event_id = $2 "#, ) .bind(community_id.as_uuid()) .bind(pid) + .bind(buzz_core::import::is_import_event(event)) + .bind(meta.event_created_at) .execute(tx.conn()) .await?; diff --git a/crates/buzz-db/src/store/feed.rs b/crates/buzz-db/src/store/feed.rs index 1094c948e82..762c5ce4660 100644 --- a/crates/buzz-db/src/store/feed.rs +++ b/crates/buzz-db/src/store/feed.rs @@ -37,8 +37,9 @@ use uuid::Uuid; use buzz_core::kind::{ KIND_FORUM_COMMENT, KIND_FORUM_POST, KIND_GIT_ISSUE, KIND_GIT_PR_UPDATE, KIND_GIT_PULL_REQUEST, KIND_GIT_STATUS_CLOSED, KIND_GIT_STATUS_DRAFT, KIND_GIT_STATUS_MERGED, KIND_GIT_STATUS_OPEN, - KIND_JOB_PROGRESS, KIND_JOB_REQUEST, KIND_JOB_RESULT, KIND_STREAM_MESSAGE, - KIND_STREAM_MESSAGE_V2, KIND_STREAM_REMINDER, KIND_TEXT_NOTE, KIND_WORKFLOW_APPROVAL_REQUESTED, + KIND_IMPORT_PROPOSAL, KIND_JOB_PROGRESS, KIND_JOB_REQUEST, KIND_JOB_RESULT, + KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_V2, KIND_STREAM_REMINDER, KIND_TEXT_NOTE, + KIND_WORKFLOW_APPROVAL_REQUESTED, }; use buzz_core::{CommunityId, StoredEvent}; @@ -108,7 +109,8 @@ fn build_mentions_query( " AND e.kind IN ({KIND_STREAM_MESSAGE}, {KIND_STREAM_MESSAGE_V2}, \ {KIND_TEXT_NOTE}, {KIND_FORUM_POST}, {KIND_FORUM_COMMENT}, {KIND_GIT_PULL_REQUEST}, \ {KIND_GIT_PR_UPDATE}, {KIND_GIT_ISSUE}, {KIND_GIT_STATUS_OPEN}, \ - {KIND_GIT_STATUS_MERGED}, {KIND_GIT_STATUS_CLOSED}, {KIND_GIT_STATUS_DRAFT})" + {KIND_GIT_STATUS_MERGED}, {KIND_GIT_STATUS_CLOSED}, {KIND_GIT_STATUS_DRAFT}, \ + {KIND_IMPORT_PROPOSAL})" )); push_visible_channel_filter(&mut qb, "e.channel_id", accessible_channel_ids); if let Some(s) = since { @@ -1131,6 +1133,33 @@ mod postgres_tests { ); } + #[test] + fn mentions_query_includes_import_proposals_only() { + use buzz_core::kind::{ + KIND_IMPORT_COMPLETE, KIND_IMPORT_CONSENT, KIND_IMPORT_PROPOSAL, KIND_IMPORT_WITHDRAW, + }; + let community = buzz_core::CommunityId::from_uuid(Uuid::new_v4()); + let mut qb = build_mentions_query(community, &[0x42; 32], &[], None, 10); + let query = qb.build(); + let sql_str = sqlx::Execute::sql(query); + let sql = sql_str.as_str(); + + assert!( + sql.contains(&KIND_IMPORT_PROPOSAL.to_string()), + "a waiting import proposal must reach its participants' mentions: {sql}" + ); + for kind in [ + KIND_IMPORT_CONSENT, + KIND_IMPORT_WITHDRAW, + KIND_IMPORT_COMPLETE, + ] { + assert!( + !sql.contains(&kind.to_string()), + "import control kind {kind} must stay out of mentions: {sql}" + ); + } + } + #[test] fn needs_action_query_is_tenant_scoped_and_joins_mentions_by_composite_key() { let community = buzz_core::CommunityId::from_uuid(Uuid::new_v4()); diff --git a/crates/buzz-db/src/store/import_session.rs b/crates/buzz-db/src/store/import_session.rs new file mode 100644 index 00000000000..be837b25f2b --- /dev/null +++ b/crates/buzz-db/src/store/import_session.rs @@ -0,0 +1,1351 @@ +//! NIP-CI conversation import sessions. +//! +//! A session is opened by a kind:42110 proposal and moved by 42111 consent, +//! 42112 withdraw and 42113 complete events. Each control event, its session +//! row change and the relay-signed kind:30623 snapshot commit in one admitted +//! transaction. Imported kind:9 and kind:7 events are inserted under a +//! `FOR UPDATE` lock on the session row, so the acceptance rules and the +//! per-participant counters cannot race. +//! +//! Status is derived lazily: an expired session is only marked `expired` the +//! next time one of these paths reads it, and that transition republishes the +//! snapshot. + +use std::collections::BTreeMap; + +use buzz_core::import::{ + self, reason, AuthorFacts, ImportCounts, ImportDecision, ImportProposalContent, ImportRange, + ImportSessionSnapshotContent, ImportSessionStatus, ImportTags, ParticipantState, SessionFacts, +}; +use buzz_core::kind::{KIND_IMPORT_SESSION_SNAPSHOT, KIND_REACTION}; +use buzz_core::{CommunityId, StoredEvent}; +use chrono::{DateTime, Utc}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use sqlx::{PgConnection, Row}; +use uuid::Uuid; + +use crate::event::{insert_event_with_thread_metadata_tx, ThreadMetadataParams}; +use crate::{AdmittedTx, Db, DbError, Result}; + +/// Outcome of an import control event (kinds 42110 to 42113). +#[derive(Debug)] +pub enum ImportControlOutcome { + /// The event violates a NIP-CI rule; nothing was written. + Rejected(&'static str), + /// The event was refused, but the check itself moved the session (for + /// example to `expired`); the republished snapshot still needs delivery. + RejectedAfterTransition { + /// Exact relay rejection reason. + reason: &'static str, + /// The republished kind:30623 snapshot. + snapshot: Box, + }, + /// The exact event was already stored; nothing changed. + Duplicate, + /// The event, the session change and the snapshot committed together. + Applied { + /// The stored control event. + stored_event: Box, + /// The republished kind:30623 snapshot. + snapshot: Box, + }, +} + +/// Outcome of inserting one imported kind:9 or kind:7 event. +#[derive(Debug)] +pub enum ImportInsertOutcome { + /// The event violates a NIP-CI acceptance rule. `snapshot` is set when + /// the check itself moved the session (for example to `expired`). + Rejected { + /// Exact relay rejection reason. + reason: &'static str, + /// Snapshot republished by a lazy status transition, if any. + snapshot: Option>, + }, + /// A reaction whose target is absent or soft-deleted. + TargetMissing, + /// The event (or the active reaction it represents) already exists. + Duplicate, + /// The event and its counter increment committed. + Inserted { + /// The stored imported event. + stored_event: Box, + /// Snapshot republished at a 50-event boundary, if any. + snapshot: Option>, + }, +} + +/// Reaction row parameters for an imported kind:7. +#[derive(Debug, Clone, Copy)] +pub struct ImportReaction<'a> { + /// Target event id bytes. + pub target_event_id: &'a [u8], + /// Reacting pubkey bytes. + pub actor_pubkey: &'a [u8], + /// Validated emoji content. + pub emoji: &'a str, +} + +/// Read-only view of a session for the relay's pre-insert rule check. +#[derive(Debug, Clone)] +pub struct ImportPreflight { + /// Destination channel of the session. + pub channel_id: Uuid, + /// Declared time range. + pub range: ImportRange, + /// Status derived at the time of the read. + pub status: ImportSessionStatus, + /// The event author's participant facts, `None` when not a participant. + pub author: Option, + /// The exact event is already stored; storage will report a duplicate. + pub already_stored: bool, + /// The proposal's declared source type. + pub source_type: String, +} + +struct SessionRow { + channel_id: Uuid, + proposer: Vec, + manifest: String, + source_type: String, + is_dm: bool, + range: ImportRange, + expires_at: i64, + requires_admin: bool, + admin_consent: Option, + status: ImportSessionStatus, +} + +struct ParticipantRow { + pubkey: Vec, + source_user: String, + declared: ImportCounts, + consent: Option, + published: ImportCounts, + completed: bool, +} + +fn invalid(what: &str) -> DbError { + DbError::InvalidData(format!("import session: {what}")) +} + +fn count(value: i64) -> u64 { + u64::try_from(value).unwrap_or(0) +} + +fn to_i64(value: u64) -> Result { + i64::try_from(value).map_err(|_| invalid("count out of range")) +} + +/// Whether any of `pubkeys` is an agent (a user with an owner). +async fn any_agent(tx: &mut AdmittedTx, pubkeys: &[Vec]) -> Result { + let community = tx.community(); + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM users \ + WHERE community_id = $1 AND pubkey = ANY($2) AND agent_owner_pubkey IS NOT NULL)", + ) + .bind(community.as_uuid()) + .bind(pubkeys) + .fetch_one(tx.conn()) + .await?) +} + +/// Whether a current member of `channel_id` is an agent. +async fn channel_has_agent_member(tx: &mut AdmittedTx, channel_id: Uuid) -> Result { + let community = tx.community(); + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM channel_members m \ + JOIN users u ON u.community_id = m.community_id AND u.pubkey = m.pubkey \ + WHERE m.community_id = $1 AND m.channel_id = $2 AND m.removed_at IS NULL \ + AND u.agent_owner_pubkey IS NOT NULL)", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .fetch_one(tx.conn()) + .await?) +} + +/// Why an active session's destination no longer admits imports: a DM whose +/// member set differs from the participant set, or a DM or private channel +/// that gained an agent member. +async fn destination_drift( + tx: &mut AdmittedTx, + session: &SessionRow, + participants: &[ParticipantRow], +) -> Result> { + let community = tx.community(); + let (visibility, members): (String, Vec>) = sqlx::query_as( + "SELECT c.visibility::text, \ + COALESCE(array_agg(m.pubkey) FILTER (WHERE m.pubkey IS NOT NULL), '{}') \ + FROM channels c \ + LEFT JOIN channel_members m ON m.community_id = c.community_id \ + AND m.channel_id = c.id AND m.removed_at IS NULL \ + WHERE c.community_id = $1 AND c.id = $2 \ + GROUP BY c.visibility", + ) + .bind(community.as_uuid()) + .bind(session.channel_id) + .fetch_one(tx.conn()) + .await?; + if session.is_dm { + let mut expected: Vec<&[u8]> = participants.iter().map(|p| p.pubkey.as_slice()).collect(); + let mut actual: Vec<&[u8]> = members.iter().map(Vec::as_slice).collect(); + expected.sort_unstable(); + actual.sort_unstable(); + if expected != actual { + return Ok(Some(reason::DM_PARTICIPANTS_MISMATCH)); + } + } + if (session.is_dm || visibility == "private") + && channel_has_agent_member(tx, session.channel_id).await? + { + return Ok(Some(reason::DESTINATION_HAS_AGENTS)); + } + Ok(None) +} + +fn decode_hex(value: &str) -> Result> { + hex::decode(value).map_err(|_| invalid("hex value")) +} + +fn parse_decision(value: Option) -> Result> { + value + .map(|v| ImportDecision::parse(&v).ok_or_else(|| invalid("consent value"))) + .transpose() +} + +async fn load_session( + tx: &mut AdmittedTx, + proposal_id: &[u8], + lock: bool, +) -> Result> { + let community = tx.community(); + read_session(tx.conn(), community, proposal_id, lock).await +} + +async fn read_session( + conn: &mut PgConnection, + community: CommunityId, + proposal_id: &[u8], + lock: bool, +) -> Result> { + let sql = if lock { + "SELECT channel_id, proposer, manifest, source_type, is_dm, range_from, range_to, \ + expires_at, requires_admin, admin_consent, status FROM import_sessions \ + WHERE community_id = $1 AND proposal_id = $2 FOR UPDATE" + } else { + "SELECT channel_id, proposer, manifest, source_type, is_dm, range_from, range_to, \ + expires_at, requires_admin, admin_consent, status FROM import_sessions \ + WHERE community_id = $1 AND proposal_id = $2" + }; + let Some(row) = sqlx::query(sql) + .bind(community.as_uuid()) + .bind(proposal_id) + .fetch_optional(conn) + .await? + else { + return Ok(None); + }; + let status: String = row.try_get("status")?; + Ok(Some(SessionRow { + channel_id: row.try_get("channel_id")?, + proposer: row.try_get("proposer")?, + manifest: row.try_get("manifest")?, + source_type: row.try_get("source_type")?, + is_dm: row.try_get("is_dm")?, + range: ImportRange { + from: row.try_get("range_from")?, + to: row.try_get("range_to")?, + }, + expires_at: row.try_get("expires_at")?, + requires_admin: row.try_get("requires_admin")?, + admin_consent: parse_decision(row.try_get("admin_consent")?)?, + status: ImportSessionStatus::parse(&status).ok_or_else(|| invalid("status value"))?, + })) +} + +async fn load_participants(tx: &mut AdmittedTx, proposal_id: &[u8]) -> Result> { + let community = tx.community(); + read_participants(tx.conn(), community, proposal_id).await +} + +async fn read_participants( + conn: &mut PgConnection, + community: CommunityId, + proposal_id: &[u8], +) -> Result> { + let rows = sqlx::query( + "SELECT pubkey, source_user, declared_messages, declared_reactions, consent, \ + published_messages, published_reactions, completed_at IS NOT NULL AS completed \ + FROM import_session_participants \ + WHERE community_id = $1 AND proposal_id = $2 ORDER BY pubkey", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .fetch_all(conn) + .await?; + rows.into_iter() + .map(|row| { + Ok(ParticipantRow { + pubkey: row.try_get("pubkey")?, + source_user: row.try_get("source_user")?, + declared: ImportCounts { + messages: count(row.try_get("declared_messages")?), + reactions: count(row.try_get("declared_reactions")?), + }, + consent: parse_decision(row.try_get("consent")?)?, + published: ImportCounts { + messages: count(row.try_get("published_messages")?), + reactions: count(row.try_get("published_reactions")?), + }, + completed: row.try_get("completed")?, + }) + }) + .collect() +} + +fn facts(session: &SessionRow, participants: &[ParticipantRow]) -> SessionFacts { + SessionFacts { + status: session.status, + is_dm: session.is_dm, + requires_admin: session.requires_admin, + admin_consent: session.admin_consent, + expires_at: session.expires_at, + participants: participants + .iter() + .map(|p| ParticipantState { + pubkey: hex::encode(&p.pubkey), + consent: p.consent, + completed: p.completed, + }) + .collect(), + } +} + +fn author_facts(participant: &ParticipantRow) -> AuthorFacts { + AuthorFacts { + consent: participant.consent, + completed: participant.completed, + declared: participant.declared, + published: participant.published, + } +} + +async fn store_status( + tx: &mut AdmittedTx, + proposal_id: &[u8], + status: ImportSessionStatus, +) -> Result<()> { + let community = tx.community(); + sqlx::query( + "UPDATE import_sessions SET status = $3, updated_at = now() \ + WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .bind(status.as_str()) + .execute(tx.conn()) + .await?; + Ok(()) +} + +/// Build the snapshot content from the session row and its participants. +fn snapshot_content( + session: &SessionRow, + participants: &[ParticipantRow], + status: ImportSessionStatus, +) -> ImportSessionSnapshotContent { + let mut required: Vec = participants + .iter() + .map(|p| hex::encode(&p.pubkey)) + .collect(); + let mut consents = BTreeMap::new(); + let mut published = BTreeMap::new(); + let mut completed = Vec::new(); + for p in participants { + let pubkey = hex::encode(&p.pubkey); + if let Some(decision) = p.consent { + consents.insert(pubkey.clone(), decision); + } + if p.completed { + completed.push(pubkey.clone()); + } + published.insert(pubkey, p.published); + } + if session.requires_admin { + required.push(import::ADMIN_CONSENT_SOURCE_USER.to_string()); + } + if let Some(decision) = session.admin_consent { + consents.insert(import::ADMIN_CONSENT_SOURCE_USER.to_string(), decision); + } + ImportSessionSnapshotContent { + v: import::IMPORT_PAYLOAD_VERSION, + status, + required, + consents, + published, + completed, + expires_at: session.expires_at, + } +} + +/// The relay clock in unix seconds, the clock snapshot `created_at` uses. +fn relay_now() -> u64 { + Utc::now().timestamp().max(0) as u64 +} + +/// `created_at` of the newest stored snapshot for `proposal_hex`, if any. +async fn snapshot_head_at( + tx: &mut AdmittedTx, + proposal_hex: &str, + keys: &Keys, +) -> Result> { + let community = tx.community(); + let previous: Option> = sqlx::query_scalar( + "SELECT max(created_at) FROM events \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4", + ) + .bind(community.as_uuid()) + .bind(KIND_IMPORT_SESSION_SNAPSHOT as i32) + .bind(keys.public_key().to_bytes().as_slice()) + .bind(proposal_hex) + .fetch_one(tx.conn()) + .await?; + Ok(previous.map(|at| at.timestamp().max(0) as u64)) +} + +/// Sign and store the kind:30623 snapshot for `proposal_id` in `tx`. +async fn publish_snapshot( + db: &Db, + tx: &mut AdmittedTx, + proposal_id: &[u8], + keys: &Keys, +) -> Result { + let session = load_session(tx, proposal_id, false) + .await? + .ok_or_else(|| invalid("session vanished"))?; + let participants = load_participants(tx, proposal_id).await?; + let content = snapshot_content(&session, &participants, session.status); + let proposal_hex = hex::encode(proposal_id); + let channel = session.channel_id.to_string(); + let mut values: Vec<[&str; 2]> = + vec![["d", &proposal_hex], ["e", &proposal_hex], ["h", &channel]]; + let pubkeys: Vec = participants + .iter() + .map(|p| hex::encode(&p.pubkey)) + .collect(); + values.extend(pubkeys.iter().map(|p| ["p", p.as_str()])); + let tags = values + .into_iter() + .map(|v| Tag::parse(v).map_err(|_| invalid("snapshot tag"))) + .collect::>>()?; + + let created_at = snapshot_head_at(tx, &proposal_hex, keys) + .await? + .map(|at| at.saturating_add(1)) + .unwrap_or(0) + .max(relay_now()); + + let event = EventBuilder::new( + Kind::Custom(KIND_IMPORT_SESSION_SNAPSHOT as u16), + serde_json::to_string(&content)?, + ) + .tags(tags) + .custom_created_at(Timestamp::from(created_at)) + .sign_with_keys(keys) + .map_err(|_| invalid("snapshot signing"))?; + let stored = db + .replace_parameterized_event_in_transaction( + tx, + &event, + &proposal_hex, + Some(session.channel_id), + crate::replaceable::ParameterizedReplacePrecondition::Unconditional, + ) + .await?; + if !matches!( + stored.status, + crate::replaceable::ParameterizedReplaceStatus::Inserted + | crate::replaceable::ParameterizedReplaceStatus::Duplicate + ) { + return Err(invalid("snapshot did not replace current head")); + } + Ok(stored.event) +} + +/// Derive the status at `now`, persist it when it moved, and report whether +/// it moved. +async fn refresh_status( + tx: &mut AdmittedTx, + proposal_id: &[u8], + session: &mut SessionRow, + participants: &[ParticipantRow], + now: i64, +) -> Result { + let next = import::derive_status(&facts(session, participants), now); + if next == session.status { + return Ok(false); + } + store_status(tx, proposal_id, next).await?; + session.status = next; + Ok(true) +} + +async fn insert_control_event( + tx: &mut AdmittedTx, + event: &Event, + channel_id: Uuid, +) -> Result> { + let (stored, inserted) = + insert_event_with_thread_metadata_tx(tx, event, Some(channel_id), None).await?; + if !inserted { + return Ok(None); + } + // Control records are live activity: a proposal mentions its participants + // and a consent its proposer. Only imported history is quiet. + crate::insert_mentions_in_transaction(tx, event, Some(channel_id)).await?; + Ok(Some(stored)) +} + +/// Which unended-session cap a new proposal would exceed, if any. +/// +/// Takes transaction-scoped advisory locks on the channel and the proposer +/// (always in that order) so concurrent proposals cannot both pass the count. +async fn session_cap_reached( + tx: &mut AdmittedTx, + channel_id: Uuid, + proposer: &[u8], + limits: import::ImportLimits, + now: i64, +) -> Result> { + let community = tx.community(); + for key in [ + format!("buzz_import_channel:{}:{channel_id}", community.as_uuid()), + format!( + "buzz_import_proposer:{}:{}", + community.as_uuid(), + hex::encode(proposer) + ), + ] { + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(key) + .execute(tx.conn()) + .await?; + } + let (in_channel, by_proposer): (i64, i64) = sqlx::query_as( + "SELECT count(*) FILTER (WHERE channel_id = $2), count(*) FILTER (WHERE proposer = $3) \ + FROM import_sessions \ + WHERE community_id = $1 AND (channel_id = $2 OR proposer = $3) \ + AND status IN ('proposed', 'active') AND expires_at > $4", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .bind(proposer) + .bind(now) + .fetch_one(tx.conn()) + .await?; + if count(in_channel) >= limits.max_active_sessions_per_channel { + return Ok(Some(reason::CHANNEL_SESSION_LIMIT)); + } + if count(by_proposer) >= limits.max_active_sessions_per_proposer { + return Ok(Some(reason::PROPOSER_SESSION_LIMIT)); + } + Ok(None) +} + +/// Whether `pubkey` is a current owner or admin of `channel_id`. +async fn is_channel_admin(tx: &mut AdmittedTx, channel_id: Uuid, pubkey: &[u8]) -> Result { + let community = tx.community(); + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 \ + AND removed_at IS NULL AND role IN ('owner', 'admin'))", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .bind(pubkey) + .fetch_one(tx.conn()) + .await?) +} + +impl Db { + /// Open a session from a validated kind:42110 proposal. + /// + /// `content` must already pass [`import::validate_proposal_content`] and + /// [`import::validate_proposal_tags`]; `expires_at` is the relay-capped + /// expiry. Inside the transaction this checks that the proposer and every + /// participant are active members of `channel_id`, that a DM's + /// participants equal its member set exactly, and whether a channel-admin + /// consent is required. The proposer's own participant entry starts as + /// accepted. The channel and the proposer may each hold at most the + /// `limits` number of unended (proposed or active, unexpired) sessions. + #[allow(clippy::too_many_arguments)] + pub async fn create_import_session( + &self, + community: CommunityId, + event: &Event, + content: &ImportProposalContent, + channel_id: Uuid, + expires_at: i64, + limits: import::ImportLimits, + keys: &Keys, + ) -> Result { + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + // Checked before the session caps so a resent stored proposal is + // answered as a duplicate even when the channel is at its cap. + if event_is_stored(tx.conn(), community, event).await? { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + } + let proposer = event.pubkey.to_bytes().to_vec(); + let participant_keys = content + .participants + .iter() + .map(|p| decode_hex(&p.pubkey)) + .collect::>>()?; + + let declared = content + .participants + .iter() + .map(|p| Ok((to_i64(p.messages)?, to_i64(p.reactions)?))) + .collect::>>(); + let Ok(declared) = declared else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::COUNTS_EXCEED_LIMIT)); + }; + + let channel: Option<(String, String)> = sqlx::query_as( + "SELECT channel_type::text, visibility::text FROM channels \ + WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .fetch_optional(tx.conn()) + .await?; + let Some((channel_type, visibility)) = channel else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::CHANNEL_MISMATCH)); + }; + let is_dm = channel_type == "dm"; + + if any_agent(&mut tx, &participant_keys).await? { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected( + reason::PARTICIPANTS_INCLUDE_AGENTS, + )); + } + if (is_dm || visibility == "private") + && channel_has_agent_member(&mut tx, channel_id).await? + { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected( + reason::DESTINATION_HAS_AGENTS, + )); + } + + let members = sqlx::query( + "SELECT pubkey, role::text AS role FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL \ + AND (pubkey = ANY($3) OR pubkey = $4)", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .bind(&participant_keys) + .bind(&proposer) + .fetch_all(tx.conn()) + .await?; + let mut roles: BTreeMap, String> = BTreeMap::new(); + for row in members { + roles.insert(row.try_get("pubkey")?, row.try_get("role")?); + } + if !roles.contains_key(&proposer) { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::PROPOSER_NOT_MEMBER)); + } + if participant_keys.iter().any(|p| !roles.contains_key(p)) { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected( + reason::PARTICIPANT_NOT_MEMBER, + )); + } + let (member_count, admin_count): (i64, i64) = sqlx::query_as( + "SELECT count(*), count(*) FILTER (WHERE role IN ('owner', 'admin')) \ + FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .fetch_one(tx.conn()) + .await?; + // Participants are distinct and all members, so equal counts mean + // equal sets. + if is_dm && usize::try_from(member_count).ok() != Some(participant_keys.len()) { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected( + reason::DM_PARTICIPANTS_MISMATCH, + )); + } + let proposer_is_admin = roles + .get(&proposer) + .is_some_and(|role| role == "owner" || role == "admin"); + let requires_admin = !is_dm && admin_count > 0 && !proposer_is_admin; + + if let Some(reason) = session_cap_reached( + &mut tx, + channel_id, + &proposer, + limits, + Utc::now().timestamp(), + ) + .await? + { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason)); + } + + let Some(stored_event) = insert_control_event(&mut tx, event, channel_id).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + }; + let proposal_id = event.id.as_bytes().as_slice(); + sqlx::query( + "INSERT INTO import_sessions (community_id, proposal_id, channel_id, proposer, \ + manifest, source_type, is_dm, range_from, range_to, expires_at, requires_admin, \ + status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .bind(channel_id) + .bind(&proposer) + .bind(&content.manifest) + .bind(&content.source.source_type) + .bind(is_dm) + .bind(content.range.from) + .bind(content.range.to) + .bind(expires_at) + .bind(requires_admin) + .bind(ImportSessionStatus::Proposed.as_str()) + .execute(tx.conn()) + .await?; + for ((participant, pubkey), (messages, reactions)) in content + .participants + .iter() + .zip(&participant_keys) + .zip(declared) + { + let consent = (*pubkey == proposer).then_some(ImportDecision::Accept.as_str()); + sqlx::query( + "INSERT INTO import_session_participants (community_id, proposal_id, pubkey, \ + source_user, declared_messages, declared_reactions, consent) \ + VALUES ($1, $2, $3, $4, $5, $6, $7)", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .bind(pubkey) + .bind(&participant.source_user) + .bind(messages) + .bind(reactions) + .bind(consent) + .execute(tx.conn()) + .await?; + } + let mut session = load_session(&mut tx, proposal_id, true) + .await? + .ok_or_else(|| invalid("session insert"))?; + let participants = load_participants(&mut tx, proposal_id).await?; + refresh_status( + &mut tx, + proposal_id, + &mut session, + &participants, + Utc::now().timestamp(), + ) + .await?; + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + Ok(ImportControlOutcome::Applied { + stored_event: Box::new(stored_event), + snapshot: Box::new(snapshot), + }) + } + + /// Record a kind:42111 consent. `manifest` is the event's `manifest` tag. + /// + /// A `source_user` of `"admin"` records a channel-admin consent and + /// requires the author to be a current owner or admin of the channel. + /// Otherwise the author must be a participant whose `source_user` + /// matches. A later consent replaces the earlier one. + #[allow(clippy::too_many_arguments)] + pub async fn record_import_consent( + &self, + community: CommunityId, + event: &Event, + proposal_id: &[u8], + channel_id: Uuid, + manifest: &str, + decision: ImportDecision, + source_user: &str, + keys: &Keys, + ) -> Result { + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let author = event.pubkey.to_bytes().to_vec(); + let Some(mut session) = load_session(&mut tx, proposal_id, true).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::PROPOSAL_NOT_FOUND)); + }; + if session.channel_id != channel_id { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::CHANNEL_MISMATCH)); + } + // Checked before the lazy status refresh so a resend after expiry is + // still answered as a duplicate. + if event_is_stored(tx.conn(), community, event).await? { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + } + if session.manifest != manifest || !names_only(event, &session.proposer) { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::CONSENT_MISMATCH)); + } + let mut participants = load_participants(&mut tx, proposal_id).await?; + let now = Utc::now().timestamp(); + if refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await? { + // Persist the lazy transition even though this consent is refused. + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + return Ok(ImportControlOutcome::RejectedAfterTransition { + reason: reason::SESSION_NOT_ACTIVE, + snapshot: Box::new(snapshot), + }); + } + if session.status.is_terminal() { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::SESSION_NOT_ACTIVE)); + } + + if source_user == import::ADMIN_CONSENT_SOURCE_USER { + if !is_channel_admin(&mut tx, channel_id, &author).await? { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::NOT_PARTICIPANT)); + } + sqlx::query( + "UPDATE import_sessions SET admin_consent = $3, updated_at = now() \ + WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .bind(decision.as_str()) + .execute(tx.conn()) + .await?; + session.admin_consent = Some(decision); + } else { + let Some(participant) = participants.iter_mut().find(|p| p.pubkey == author) else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::NOT_PARTICIPANT)); + }; + if participant.source_user != source_user { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::CONSENT_MISMATCH)); + } + sqlx::query( + "UPDATE import_session_participants SET consent = $4 \ + WHERE community_id = $1 AND proposal_id = $2 AND pubkey = $3", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .bind(&author) + .bind(decision.as_str()) + .execute(tx.conn()) + .await?; + participant.consent = Some(decision); + } + + let Some(stored_event) = insert_control_event(&mut tx, event, channel_id).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + }; + refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await?; + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + Ok(ImportControlOutcome::Applied { + stored_event: Box::new(stored_event), + snapshot: Box::new(snapshot), + }) + } + + /// Apply a kind:42112 withdraw from the proposer or a participant. + pub async fn withdraw_import_session( + &self, + community: CommunityId, + event: &Event, + proposal_id: &[u8], + channel_id: Uuid, + keys: &Keys, + ) -> Result { + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let author = event.pubkey.to_bytes().to_vec(); + let Some(mut session) = load_session(&mut tx, proposal_id, true).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::PROPOSAL_NOT_FOUND)); + }; + if session.channel_id != channel_id { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::CHANNEL_MISMATCH)); + } + // Checked before the lazy status refresh so a resend after expiry is + // still answered as a duplicate. + if event_is_stored(tx.conn(), community, event).await? { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + } + let participants = load_participants(&mut tx, proposal_id).await?; + if session.proposer != author && !participants.iter().any(|p| p.pubkey == author) { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::NOT_PARTICIPANT)); + } + let now = Utc::now().timestamp(); + if refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await? { + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + return Ok(ImportControlOutcome::RejectedAfterTransition { + reason: reason::SESSION_NOT_ACTIVE, + snapshot: Box::new(snapshot), + }); + } + if session.status.is_terminal() { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::SESSION_NOT_ACTIVE)); + } + let Some(stored_event) = insert_control_event(&mut tx, event, channel_id).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + }; + store_status(&mut tx, proposal_id, ImportSessionStatus::Withdrawn).await?; + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + Ok(ImportControlOutcome::Applied { + stored_event: Box::new(stored_event), + snapshot: Box::new(snapshot), + }) + } + + /// Apply a kind:42113 complete from an accepting participant. The session + /// becomes `completed` once every accepting participant has completed. + pub async fn complete_import_participant( + &self, + community: CommunityId, + event: &Event, + proposal_id: &[u8], + channel_id: Uuid, + keys: &Keys, + ) -> Result { + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let author = event.pubkey.to_bytes().to_vec(); + let Some(mut session) = load_session(&mut tx, proposal_id, true).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::PROPOSAL_NOT_FOUND)); + }; + if session.channel_id != channel_id { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::CHANNEL_MISMATCH)); + } + // Checked before the lazy status refresh so a resend after expiry is + // still answered as a duplicate. + if event_is_stored(tx.conn(), community, event).await? { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + } + let mut participants = load_participants(&mut tx, proposal_id).await?; + let now = Utc::now().timestamp(); + if refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await? { + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + return Ok(ImportControlOutcome::RejectedAfterTransition { + reason: reason::SESSION_NOT_ACTIVE, + snapshot: Box::new(snapshot), + }); + } + let Some(participant) = participants.iter_mut().find(|p| p.pubkey == author) else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::NOT_PARTICIPANT)); + }; + if session.status != ImportSessionStatus::Active || participant.completed { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::SESSION_NOT_ACTIVE)); + } + if participant.consent != Some(ImportDecision::Accept) { + tx.rollback().await?; + return Ok(ImportControlOutcome::Rejected(reason::NOT_CONSENTING)); + } + let Some(stored_event) = insert_control_event(&mut tx, event, channel_id).await? else { + tx.rollback().await?; + return Ok(ImportControlOutcome::Duplicate); + }; + sqlx::query( + "UPDATE import_session_participants SET completed_at = now() \ + WHERE community_id = $1 AND proposal_id = $2 AND pubkey = $3", + ) + .bind(community.as_uuid()) + .bind(proposal_id) + .bind(&author) + .execute(tx.conn()) + .await?; + participant.completed = true; + refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await?; + let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; + tx.commit().await?; + Ok(ImportControlOutcome::Applied { + stored_event: Box::new(stored_event), + snapshot: Box::new(snapshot), + }) + } + + /// Read a session for the relay's pre-insert rule check. Returns `None` + /// when no session exists for `proposal_id`. Does not write; the + /// authoritative check runs again in [`Db::insert_import_event`]. + pub async fn import_preflight( + &self, + community: CommunityId, + proposal_id: &[u8], + event: &Event, + ) -> Result> { + let author = event.pubkey.to_bytes(); + let mut conn = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let Some(session) = read_session(&mut conn, community, proposal_id, false).await? else { + return Ok(None); + }; + let participants = read_participants(&mut conn, community, proposal_id).await?; + let already_stored = event_is_stored(&mut conn, community, event).await?; + drop(conn); + let status = import::derive_status(&facts(&session, &participants), Utc::now().timestamp()); + Ok(Some(ImportPreflight { + channel_id: session.channel_id, + range: session.range, + status, + author: participants + .iter() + .find(|p| p.pubkey == author) + .map(author_facts), + already_stored, + source_type: session.source_type, + })) + } + + /// Insert one imported kind:9 or kind:7 event under its session. + /// + /// Re-checks rules 2 to 7 of NIP-CI under the session row lock, inserts + /// the event (and the reaction row for kind:7), and increments the + /// author's counter in the same transaction. The transaction never + /// enqueues push, and the mention writers skip import-tagged events. + #[allow(clippy::too_many_arguments)] + pub async fn insert_import_event( + &self, + community: CommunityId, + event: &Event, + tags: &ImportTags, + channel_id: Uuid, + thread_meta: Option>, + reaction: Option>, + keys: &Keys, + ) -> Result { + let proposal_id = tags.proposal_bytes.to_vec(); + let kind = u32::from(event.kind.as_u16()); + let author = event.pubkey.to_bytes().to_vec(); + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let reject = |reason| ImportInsertOutcome::Rejected { + reason, + snapshot: None, + }; + let Some(mut session) = load_session(&mut tx, &proposal_id, true).await? else { + tx.rollback().await?; + return Ok(reject(reason::PROPOSAL_NOT_FOUND)); + }; + if session.channel_id != channel_id { + tx.rollback().await?; + return Ok(reject(reason::CHANNEL_MISMATCH)); + } + if tags.source_type != session.source_type { + tx.rollback().await?; + return Ok(reject(reason::SOURCE_TYPE_MISMATCH)); + } + // A resend of a stored event is a duplicate even after the author's + // count is used up or the session has ended, so publishers can retry. + if event_is_stored(tx.conn(), community, event).await? { + tx.rollback().await?; + return Ok(ImportInsertOutcome::Duplicate); + } + let participants = load_participants(&mut tx, &proposal_id).await?; + let now = Utc::now().timestamp(); + if refresh_status(&mut tx, &proposal_id, &mut session, &participants, now).await? { + let snapshot = publish_snapshot(self, &mut tx, &proposal_id, keys).await?; + tx.commit().await?; + return Ok(ImportInsertOutcome::Rejected { + reason: reason::SESSION_NOT_ACTIVE, + snapshot: Some(Box::new(snapshot)), + }); + } + let author_row = participants.iter().find(|p| p.pubkey == author); + if let Err(reason) = import::evaluate_import_rules( + session.status, + session.range, + author_row.map(author_facts).as_ref(), + kind, + event.created_at.as_secs() as i64, + now, + ) { + tx.rollback().await?; + return Ok(reject(reason)); + } + let Some(author_row) = author_row else { + tx.rollback().await?; + return Ok(reject(reason::NOT_CONSENTING)); + }; + // An account linked to an owner after the proposal is an agent now. + if any_agent(&mut tx, std::slice::from_ref(&author)).await? { + tx.rollback().await?; + return Ok(reject(reason::PARTICIPANTS_INCLUDE_AGENTS)); + } + // Membership can change after activation. Membership writes do not + // take the session lock, so this is checked per event rather than + // once at activation. + if let Some(reason) = destination_drift(&mut tx, &session, &participants).await? { + tx.rollback().await?; + return Ok(reject(reason)); + } + + if kind == KIND_REACTION { + let Some(reaction) = reaction else { + return Err(invalid("imported reaction without target")); + }; + let target = sqlx::query( + "SELECT created_at, channel_id, tags FROM events \ + WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL \ + ORDER BY created_at DESC LIMIT 1", + ) + .bind(community.as_uuid()) + .bind(reaction.target_event_id) + .fetch_optional(tx.conn()) + .await?; + let Some(target) = target else { + tx.rollback().await?; + return Ok(ImportInsertOutcome::TargetMissing); + }; + let target_tags: serde_json::Value = target.try_get("tags")?; + let target_channel: Option = target.try_get("channel_id")?; + if target_channel != Some(channel_id) + || !carries_import_tag(&target_tags, &tags.proposal_id) + { + tx.rollback().await?; + return Ok(reject(reason::REACTION_TARGET_NOT_IMPORTED)); + } + let target_created_at: DateTime = target.try_get("created_at")?; + let added = crate::reaction::add_reaction_tx( + &mut tx, + reaction.target_event_id, + target_created_at, + reaction.actor_pubkey, + reaction.emoji, + Some(event.id.as_bytes()), + ) + .await?; + // The event itself is new (checked above), so an existing row is + // another reaction with the same actor, target and emoji. + if !added { + tx.rollback().await?; + return Ok(reject(reason::REACTION_CONFLICT)); + } + } + + let (stored_event, inserted) = + insert_event_with_thread_metadata_tx(&mut tx, event, Some(channel_id), thread_meta) + .await?; + if !inserted { + tx.rollback().await?; + return Ok(ImportInsertOutcome::Duplicate); + } + let mut published = author_row.published; + let column = if kind == KIND_REACTION { + published.reactions = published.reactions.saturating_add(1); + "published_reactions" + } else { + published.messages = published.messages.saturating_add(1); + "published_messages" + }; + let sql = format!( + "UPDATE import_session_participants SET {column} = {column} + 1 \ + WHERE community_id = $1 AND proposal_id = $2 AND pubkey = $3" + ); + sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(community.as_uuid()) + .bind(&proposal_id) + .bind(&author) + .execute(tx.conn()) + .await?; + // A boundary republish is skipped while the head snapshot is not yet + // behind the relay clock, so strictly increasing `created_at` values + // cannot run ahead of real time when many participants import at + // once. Control events still republish every time. + let republish = import::crosses_republish_boundary(published) + && snapshot_head_at(&mut tx, &hex::encode(&proposal_id), keys) + .await? + .is_none_or(|at| at < relay_now()); + let snapshot = if republish { + Some(Box::new( + publish_snapshot(self, &mut tx, &proposal_id, keys).await?, + )) + } else { + None + }; + // Imported history must not extend an ephemeral channel's lifetime. + tx.skip_ttl_refresh(); + tx.commit().await?; + Ok(ImportInsertOutcome::Inserted { + stored_event: Box::new(stored_event), + snapshot, + }) + } +} + +/// Whether the event's `p` tags are exactly one, naming `pubkey`. +fn names_only(event: &Event, pubkey: &[u8]) -> bool { + let mut values = event.tags.iter().filter_map(|tag| { + let slice = tag.as_slice(); + (slice.first().map(String::as_str) == Some("p")).then(|| slice.get(1)) + }); + let expected = hex::encode(pubkey); + matches!( + (values.next(), values.next()), + (Some(Some(value)), None) if *value == expected + ) +} + +/// Whether `event` is already stored (soft-deleted rows included). +async fn event_is_stored( + conn: &mut PgConnection, + community: CommunityId, + event: &Event, +) -> Result { + let created_at = DateTime::::from_timestamp(event.created_at.as_secs() as i64, 0) + .ok_or_else(|| invalid("event created_at"))?; + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM events \ + WHERE community_id = $1 AND created_at = $2 AND id = $3)", + ) + .bind(community.as_uuid()) + .bind(created_at) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(conn) + .await?) +} + +/// Whether stored event tags contain `["import", proposal_id]`. +fn carries_import_tag(tags: &serde_json::Value, proposal_id: &str) -> bool { + tags.as_array().is_some_and(|tags| { + tags.iter().any(|tag| { + tag.as_array().is_some_and(|tag| { + tag.first().and_then(|v| v.as_str()) == Some(import::IMPORT_TAG) + && tag.get(1).and_then(|v| v.as_str()) == Some(proposal_id) + }) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn import_tag_detection_on_stored_tags() { + let id = "a".repeat(64); + let tags = serde_json::json!([["h", "x"], ["import", id], ["source", "t", "1"]]); + assert!(carries_import_tag(&tags, &id)); + assert!(!carries_import_tag(&tags, &"b".repeat(64))); + assert!(!carries_import_tag(&serde_json::json!([["h", "x"]]), &id)); + assert!(!carries_import_tag(&serde_json::json!("import"), &id)); + } + + #[test] + fn snapshot_lists_admin_requirement_and_counts() { + let session = SessionRow { + channel_id: Uuid::nil(), + proposer: vec![1; 32], + manifest: "m".into(), + source_type: "test".into(), + is_dm: false, + range: ImportRange { from: 0, to: 1 }, + expires_at: 99, + requires_admin: true, + admin_consent: Some(ImportDecision::Accept), + status: ImportSessionStatus::Active, + }; + let participants = vec![ + ParticipantRow { + pubkey: vec![1; 32], + source_user: "s".into(), + declared: ImportCounts { + messages: 2, + reactions: 0, + }, + consent: Some(ImportDecision::Accept), + published: ImportCounts { + messages: 2, + reactions: 0, + }, + completed: true, + }, + ParticipantRow { + pubkey: vec![2; 32], + source_user: "s".into(), + declared: ImportCounts::default(), + consent: None, + published: ImportCounts::default(), + completed: false, + }, + ]; + let content = snapshot_content(&session, &participants, ImportSessionStatus::Active); + let first = hex::encode([1u8; 32]); + let second = hex::encode([2u8; 32]); + assert_eq!( + content.required, + vec![first.clone(), second.clone(), "admin".into()] + ); + assert_eq!(content.consents.get(&first), Some(&ImportDecision::Accept)); + assert_eq!(content.consents.get(&second), None); + assert_eq!(content.consents.get("admin"), Some(&ImportDecision::Accept)); + assert_eq!(content.published[&first].messages, 2); + assert_eq!(content.completed, vec![first]); + assert_eq!(content.expires_at, 99); + } +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/import_session/postgres_tests.rs b/crates/buzz-db/src/store/import_session/postgres_tests.rs new file mode 100644 index 00000000000..406d2a3eac5 --- /dev/null +++ b/crates/buzz-db/src/store/import_session/postgres_tests.rs @@ -0,0 +1,627 @@ +use super::*; +use buzz_core::import::{ImportParticipant, ImportSource, ImportSourceKind}; +use buzz_core::kind::{KIND_IMPORT_PROPOSAL, KIND_STREAM_MESSAGE}; + +const MANIFEST: &str = "1111111111111111111111111111111111111111111111111111111111111111"; +const CONVERSATION: &str = "2222222222222222222222222222222222222222222222222222222222222222"; + +/// Session caps high enough that only the cap test reaches them. +const LIMITS: import::ImportLimits = import::ImportLimits { + max_events_per_participant: 50_000, + max_events_per_session: 200_000, + max_active_sessions_per_channel: 100, + max_active_sessions_per_proposer: 100, +}; + +struct Fixture { + db: Db, + community: CommunityId, + relay: Keys, +} + +async fn fixture() -> Fixture { + let db = Db::new(&crate::DbConfig { + database_url: crate::test_support::database_url(), + ..crate::DbConfig::default() + }) + .await + .unwrap(); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.unwrap(); + } + let community = CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(format!("import-{}.test", community.as_uuid())) + .execute(&db.pool) + .await + .unwrap(); + Fixture { + db, + community, + relay: Keys::generate(), + } +} + +async fn channel(f: &Fixture, channel_type: &str, members: &[(&Keys, &str)]) -> Uuid { + let mut tx = crate::begin_community_write_transaction( + &f.db.pool, + f.community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + let id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) \ + VALUES ($1, $2, $3, $4::channel_type, 'private', $5)", + ) + .bind(id) + .bind(f.community.as_uuid()) + .bind(format!("c-{}", id.simple())) + .bind(channel_type) + .bind(members[0].0.public_key().to_bytes().as_slice()) + .execute(tx.conn()) + .await + .unwrap(); + for (keys, role) in members { + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role) \ + VALUES ($1, $2, $3, $4::member_role)", + ) + .bind(f.community.as_uuid()) + .bind(id) + .bind(keys.public_key().to_bytes().as_slice()) + .bind(*role) + .execute(tx.conn()) + .await + .unwrap(); + } + tx.commit().await.unwrap(); + id +} + +fn source_user(keys: &Keys) -> String { + use sha2::{Digest, Sha256}; + hex::encode(Sha256::digest(format!( + "test:{}", + keys.public_key().to_hex() + ))) +} + +fn proposal_content(participants: &[(&Keys, u64, u64)], now: i64) -> ImportProposalContent { + let mut participants: Vec = participants + .iter() + .map(|(keys, messages, reactions)| ImportParticipant { + pubkey: keys.public_key().to_hex(), + source_user: source_user(keys), + messages: *messages, + reactions: *reactions, + }) + .collect(); + participants.sort_by(|a, b| a.pubkey.cmp(&b.pubkey)); + ImportProposalContent { + v: 1, + source: ImportSource { + source_type: "test".into(), + conversation: CONVERSATION.into(), + kind: ImportSourceKind::Dm, + label: "Direct message".into(), + }, + range: ImportRange { + from: now - 10_000, + to: now - 100, + }, + participants, + excluded_authors: 0, + manifest: MANIFEST.into(), + expires_at: now + 3_600, + } +} + +fn sign(keys: &Keys, kind: u32, content: &str, tags: Vec>, created_at: i64) -> Event { + let tags: Vec = tags.into_iter().map(|t| Tag::parse(t).unwrap()).collect(); + // A proposal lists its proposer; the builder drops a self p tag unless told not to. + EventBuilder::new(Kind::Custom(kind as u16), content) + .tags(tags) + .allow_self_tagging() + .custom_created_at(Timestamp::from(created_at as u64)) + .sign_with_keys(keys) + .unwrap() +} + +fn proposal_event(keys: &Keys, channel: Uuid, content: &ImportProposalContent) -> Event { + let mut tags = vec![vec!["h".to_string(), channel.to_string()]]; + for p in &content.participants { + tags.push(vec!["p".into(), p.pubkey.clone()]); + } + tags.push(vec!["manifest".into(), content.manifest.clone()]); + tags.push(vec![ + "import-source".into(), + content.source.source_type.clone(), + ]); + sign( + keys, + KIND_IMPORT_PROPOSAL, + &serde_json::to_string(content).unwrap(), + tags, + Utc::now().timestamp(), + ) +} + +fn control(keys: &Keys, kind: u32, proposal: &Event, channel: Uuid, content: &str) -> Event { + sign( + keys, + kind, + content, + vec![ + vec!["e".into(), proposal.id.to_hex()], + vec!["h".into(), channel.to_string()], + ], + Utc::now().timestamp(), + ) +} + +fn consent_event(keys: &Keys, proposal: &Event, channel: Uuid, content: &str) -> Event { + sign( + keys, + 42111, + content, + vec![ + vec!["e".into(), proposal.id.to_hex()], + vec!["h".into(), channel.to_string()], + vec!["manifest".into(), MANIFEST.into()], + vec!["p".into(), proposal.pubkey.to_hex()], + ], + Utc::now().timestamp(), + ) +} + +fn imported(keys: &Keys, proposal: &Event, channel: Uuid, created_at: i64, n: u32) -> Event { + sign( + keys, + KIND_STREAM_MESSAGE, + &format!("message {n}"), + vec![ + vec!["h".into(), channel.to_string()], + vec!["import".into(), proposal.id.to_hex()], + vec!["source".into(), "test".into(), format!("ref-{n}")], + ], + created_at, + ) +} + +fn tags_of(event: &Event) -> ImportTags { + import::parse_import_tags(event).unwrap().unwrap() +} + +fn snapshot_of(stored: &StoredEvent) -> ImportSessionSnapshotContent { + serde_json::from_str(&stored.event.content).unwrap() +} + +async fn applied(outcome: Result) -> ImportSessionSnapshotContent { + match outcome.unwrap() { + ImportControlOutcome::Applied { snapshot, .. } => snapshot_of(&snapshot), + other => panic!("expected Applied, got {other:?}"), + } +} + +async fn consent( + f: &Fixture, + keys: &Keys, + proposal: &Event, + channel: Uuid, + decision: ImportDecision, + source_user: &str, +) -> Result { + let content = + serde_json::json!({"v": 1, "decision": decision.as_str(), "source_user": source_user}); + let event = consent_event(keys, proposal, channel, &content.to_string()); + f.db.record_import_consent( + f.community, + &event, + proposal.id.as_bytes(), + channel, + MANIFEST, + decision, + source_user, + &f.relay, + ) + .await +} + +async fn insert(f: &Fixture, event: &Event, channel: Uuid) -> ImportInsertOutcome { + f.db.insert_import_event( + f.community, + event, + &tags_of(event), + channel, + None, + None, + &f.relay, + ) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dm_participants_must_equal_members() { + let f = fixture().await; + let (alice, bob, carol) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = channel( + &f, + "dm", + &[(&alice, "member"), (&bob, "member"), (&carol, "member")], + ) + .await; + let now = Utc::now().timestamp(); + let content = proposal_content(&[(&alice, 1, 0), (&bob, 1, 0)], now); + let proposal = proposal_event(&alice, dm, &content); + let outcome = + f.db.create_import_session( + f.community, + &proposal, + &content, + dm, + content.expires_at, + LIMITS, + &f.relay, + ) + .await + .unwrap(); + assert!(matches!( + outcome, + ImportControlOutcome::Rejected(reason::DM_PARTICIPANTS_MISMATCH) + )); + + let outsider = Keys::generate(); + let content = proposal_content(&[(&alice, 1, 0), (&outsider, 1, 0)], now); + let proposal = proposal_event(&alice, dm, &content); + let outcome = + f.db.create_import_session( + f.community, + &proposal, + &content, + dm, + content.expires_at, + LIMITS, + &f.relay, + ) + .await + .unwrap(); + assert!(matches!( + outcome, + ImportControlOutcome::Rejected(reason::PARTICIPANT_NOT_MEMBER) + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn completion_and_expiry_move_the_session() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let now = Utc::now().timestamp(); + let content = proposal_content(&[(&alice, 1, 0), (&bob, 0, 0)], now); + let proposal = proposal_event(&alice, dm, &content); + applied( + f.db.create_import_session( + f.community, + &proposal, + &content, + dm, + content.expires_at, + LIMITS, + &f.relay, + ) + .await, + ) + .await; + applied( + consent( + &f, + &bob, + &proposal, + dm, + ImportDecision::Accept, + &source_user(&bob), + ) + .await, + ) + .await; + let done = r#"{"v":1,"published":{"messages":0,"reactions":0}}"#; + let snapshot = applied( + f.db.complete_import_participant( + f.community, + &control(&alice, 42113, &proposal, dm, done), + proposal.id.as_bytes(), + dm, + &f.relay, + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Active); + assert_eq!(snapshot.completed, vec![alice.public_key().to_hex()]); + let snapshot = applied( + f.db.complete_import_participant( + f.community, + &control(&bob, 42113, &proposal, dm, done), + proposal.id.as_bytes(), + dm, + &f.relay, + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Completed); + + // A session past its expiry is marked expired on the next read. + let content = proposal_content(&[(&alice, 1, 0), (&bob, 1, 0)], now); + let proposal = proposal_event(&alice, dm, &content); + applied( + f.db.create_import_session( + f.community, + &proposal, + &content, + dm, + now + 1, + LIMITS, + &f.relay, + ) + .await, + ) + .await; + sqlx::query( + "UPDATE import_sessions SET expires_at = $3 WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .bind(now - 1) + .execute(&f.db.pool) + .await + .unwrap(); + let outcome = insert(&f, &imported(&alice, &proposal, dm, now - 5_000, 1), dm).await; + match outcome { + ImportInsertOutcome::Rejected { + reason, + snapshot: Some(snapshot), + } => { + assert_eq!(reason, reason::SESSION_NOT_ACTIVE); + assert_eq!(snapshot_of(&snapshot).status, ImportSessionStatus::Expired); + } + other => panic!("expected expiry rejection, got {other:?}"), + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn import_writes_are_refused_once_deletion_starts() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let now = Utc::now().timestamp(); + let content = proposal_content(&[(&alice, 1, 0), (&bob, 1, 0)], now); + let proposal = proposal_event(&alice, dm, &content); + crate::test_support::quiesce_community_for_tests(&f.db.pool, f.community).await; + let error = + f.db.create_import_session( + f.community, + &proposal, + &content, + dm, + content.expires_at, + LIMITS, + &f.relay, + ) + .await + .expect_err("quiescing community must refuse import writes"); + assert!( + crate::test_support::is_admission_rejection(&error), + "{error}" + ); +} + +async fn propose( + f: &Fixture, + proposer: &Keys, + channel: Uuid, + participants: &[(&Keys, u64, u64)], +) -> (Event, Result) { + let content = proposal_content(participants, Utc::now().timestamp()); + let proposal = proposal_event(proposer, channel, &content); + let outcome = + f.db.create_import_session( + f.community, + &proposal, + &content, + channel, + content.expires_at, + LIMITS, + &f.relay, + ) + .await; + (proposal, outcome) +} + +fn control_rejection(outcome: Result) -> &'static str { + match outcome.unwrap() { + ImportControlOutcome::Rejected(reason) => reason, + other => panic!("expected a rejection, got {other:?}"), + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn control_events_mention_participants_and_resend_as_duplicates() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 1, 0)]).await; + applied(outcome).await; + + // The proposal is live activity: each participant gets a mention row. + let mentioned: Vec = sqlx::query_scalar( + "SELECT pubkey_hex FROM event_mentions \ + WHERE community_id = $1 AND event_id = $2 ORDER BY pubkey_hex", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .fetch_all(&f.db.pool) + .await + .unwrap(); + let mut expected = vec![alice.public_key().to_hex(), bob.public_key().to_hex()]; + expected.sort(); + assert_eq!(mentioned, expected); + let feed = + f.db.query_feed_mentions(f.community, &bob.public_key().to_bytes(), &[dm], None, 10) + .await + .unwrap(); + assert!( + feed.iter().any(|row| row.event.id == proposal.id), + "a waiting proposal must reach the participant's mentions feed" + ); + + // A consent must name the proposer in its single p tag. + let content = serde_json::json!({ + "v": 1, "decision": "accept", "source_user": source_user(&bob) + }) + .to_string(); + let record = |event: Event| { + let db = &f.db; + let relay = &f.relay; + let community = f.community; + let proposal_id = proposal.id; + let bob_source = source_user(&bob); + async move { + db.record_import_consent( + community, + &event, + proposal_id.as_bytes(), + dm, + MANIFEST, + ImportDecision::Accept, + &bob_source, + relay, + ) + .await + } + }; + let wrong_p = sign( + &bob, + 42111, + &content, + vec![ + vec!["e".into(), proposal.id.to_hex()], + vec!["h".into(), dm.to_string()], + vec!["manifest".into(), MANIFEST.into()], + vec!["p".into(), bob.public_key().to_hex()], + ], + Utc::now().timestamp(), + ); + assert_eq!( + control_rejection(record(wrong_p).await), + reason::CONSENT_MISMATCH + ); + + // A resend after expiry is a duplicate, not a status rejection. + let good = consent_event(&bob, &proposal, dm, &content); + applied(record(good.clone()).await).await; + sqlx::query( + "UPDATE import_sessions SET expires_at = $3 WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .bind(Utc::now().timestamp() - 1) + .execute(&f.db.pool) + .await + .unwrap(); + assert!(matches!( + record(good).await.unwrap(), + ImportControlOutcome::Duplicate + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn active_sessions_are_capped_per_channel_and_proposer() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let limits = import::ImportLimits { + max_active_sessions_per_channel: 1, + max_active_sessions_per_proposer: 2, + ..LIMITS + }; + // Distinct declared counts keep proposals signed in the same second from + // sharing an id, which would be answered as a duplicate. + let open = |channel: Uuid, messages: u64| { + let content = proposal_content( + &[(&alice, messages, 0), (&bob, 0, 0)], + Utc::now().timestamp(), + ); + let proposal = proposal_event(&alice, channel, &content); + let db = &f.db; + let community = f.community; + let relay = &f.relay; + async move { + let outcome = db + .create_import_session( + community, + &proposal, + &content, + channel, + content.expires_at, + limits, + relay, + ) + .await + .unwrap(); + (proposal, outcome) + } + }; + let rejection = |outcome: ImportControlOutcome| match outcome { + ImportControlOutcome::Rejected(reason) => Some(reason), + _ => None, + }; + let first = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let second = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let third = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + + let (held, outcome) = open(first, 1).await; + assert_eq!(rejection(outcome), None); + let (_, outcome) = open(first, 2).await; + assert_eq!(rejection(outcome), Some(reason::CHANNEL_SESSION_LIMIT)); + // A resend of the stored proposal is a duplicate, not a cap rejection. + let content: ImportProposalContent = serde_json::from_str(&held.content).unwrap(); + let outcome = + f.db.create_import_session( + f.community, + &held, + &content, + first, + content.expires_at, + limits, + &f.relay, + ) + .await + .unwrap(); + assert!(matches!(outcome, ImportControlOutcome::Duplicate)); + let (_, outcome) = open(second, 1).await; + assert_eq!(rejection(outcome), None); + let (_, outcome) = open(third, 1).await; + assert_eq!(rejection(outcome), Some(reason::PROPOSER_SESSION_LIMIT)); + + // An expired session no longer counts, even before its status is stored. + sqlx::query( + "UPDATE import_sessions SET expires_at = 1 \ + WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(held.id.as_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); + let (_, outcome) = open(first, 3).await; + assert_eq!(rejection(outcome), None); +} diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index bd2d709151b..1ea4464e23d 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -104,3 +104,6 @@ mod admission_postgres_tests; /// Durable NIP-FI verified-profile projection state. pub mod verified_profiles; + +/// NIP-CI conversation import sessions, consents and counters. +pub mod import_session; diff --git a/crates/buzz-db/src/store/operator_listener.rs b/crates/buzz-db/src/store/operator_listener.rs index 08983b36d2e..c1dc7b52613 100644 --- a/crates/buzz-db/src/store/operator_listener.rs +++ b/crates/buzz-db/src/store/operator_listener.rs @@ -90,13 +90,14 @@ fn event_targets(event: &Event) -> Vec> { /// Insert one outbox row for each registered listener matching the event's /// `p` tags. The caller owns the transaction and must commit it with the event. +/// NIP-CI imported events never wake listeners. pub(crate) async fn enqueue_mentions_in_transaction( tx: &mut AdmittedTx, event: &Event, ) -> Result { let community_id = tx.community(); let kind = u32::from(event.kind.as_u16()); - if !is_listener_mention_kind(kind) { + if !is_listener_mention_kind(kind) || buzz_core::import::is_import_event(event) { return Ok(0); } let targets = event_targets(event); diff --git a/crates/buzz-db/src/store/personal_read/projection.rs b/crates/buzz-db/src/store/personal_read/projection.rs index 54f2e828e49..b65427f1f3e 100644 --- a/crates/buzz-db/src/store/personal_read/projection.rs +++ b/crates/buzz-db/src/store/personal_read/projection.rs @@ -159,6 +159,10 @@ impl Db { LEFT JOIN personal_read_frontiers tf ON tf.community_id=$1 AND tf.actor=$2 AND tf.channel_id=r.id AND tf.root_id=e.root AND e.is_reply WHERE e.pubkey<>$2 AND NOT e.unresolved + -- NIP-CI imported history is never unread evidence. + AND NOT (jsonb_typeof(e.tags)='array' + AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) t(tag) + WHERE jsonb_typeof(tag)='array' AND tag->>0='import')) ), grouped AS ( SELECT CASE WHEN root IS NULL THEN NULL WHEN is_reply THEN encode(root,'hex') ELSE '' END AS root, diff --git a/migrations/0081_conversation_import_sessions.sql b/migrations/0081_conversation_import_sessions.sql new file mode 100644 index 00000000000..6d2cf7c82b5 --- /dev/null +++ b/migrations/0081_conversation_import_sessions.sql @@ -0,0 +1,44 @@ +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +-- NIP-CI conversation import sessions. One row per accepted kind:42110 +-- proposal; status is the relay-derived session state. +CREATE TABLE import_sessions ( + community_id UUID NOT NULL, + proposal_id BYTEA NOT NULL, + channel_id UUID NOT NULL, + proposer BYTEA NOT NULL, + manifest TEXT NOT NULL, + source_type TEXT NOT NULL, + is_dm BOOLEAN NOT NULL, + range_from BIGINT NOT NULL, + range_to BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + requires_admin BOOLEAN NOT NULL, + admin_consent TEXT, + status TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (community_id, proposal_id) +); + +CREATE INDEX idx_import_sessions_channel + ON import_sessions (community_id, channel_id); +CREATE INDEX idx_import_sessions_proposer + ON import_sessions (community_id, proposer); + +-- One row per proposal participant: declared counts, latest consent and the +-- counters of accepted imported events. +CREATE TABLE import_session_participants ( + community_id UUID NOT NULL, + proposal_id BYTEA NOT NULL, + pubkey BYTEA NOT NULL, + source_user TEXT NOT NULL, + declared_messages BIGINT NOT NULL, + declared_reactions BIGINT NOT NULL, + consent TEXT, + published_messages BIGINT NOT NULL DEFAULT 0, + published_reactions BIGINT NOT NULL DEFAULT 0, + completed_at TIMESTAMPTZ, + PRIMARY KEY (community_id, proposal_id, pubkey) +); diff --git a/schema/schema.sql b/schema/schema.sql index 710345e5275..96404984ba4 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -217,3 +217,5 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i seeds/storage_accounting_snapshots.sql \i tables/public/nip_fi_profile_heads.sql +\i tables/public/import_sessions.sql +\i tables/public/import_session_participants.sql diff --git a/schema/tables/public/import_session_participants.sql b/schema/tables/public/import_session_participants.sql new file mode 100644 index 00000000000..c29c285801f --- /dev/null +++ b/schema/tables/public/import_session_participants.sql @@ -0,0 +1,14 @@ +-- NIP-CI per-participant consent and counters (docs/nips/NIP-CI.md). +CREATE TABLE import_session_participants ( + community_id UUID NOT NULL, + proposal_id BYTEA NOT NULL, + pubkey BYTEA NOT NULL, + source_user TEXT NOT NULL, + declared_messages BIGINT NOT NULL, + declared_reactions BIGINT NOT NULL, + consent TEXT, + published_messages BIGINT NOT NULL DEFAULT 0, + published_reactions BIGINT NOT NULL DEFAULT 0, + completed_at TIMESTAMPTZ, + PRIMARY KEY (community_id, proposal_id, pubkey) +); diff --git a/schema/tables/public/import_sessions.sql b/schema/tables/public/import_sessions.sql new file mode 100644 index 00000000000..84c6343c860 --- /dev/null +++ b/schema/tables/public/import_sessions.sql @@ -0,0 +1,23 @@ +-- NIP-CI conversation import sessions (docs/nips/NIP-CI.md). +CREATE TABLE import_sessions ( + community_id UUID NOT NULL, + proposal_id BYTEA NOT NULL, + channel_id UUID NOT NULL, + proposer BYTEA NOT NULL, + manifest TEXT NOT NULL, + source_type TEXT NOT NULL, + is_dm BOOLEAN NOT NULL, + range_from BIGINT NOT NULL, + range_to BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + requires_admin BOOLEAN NOT NULL, + admin_consent TEXT, + status TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (community_id, proposal_id) +); +CREATE INDEX idx_import_sessions_channel + ON import_sessions (community_id, channel_id); +CREATE INDEX idx_import_sessions_proposer + ON import_sessions (community_id, proposer); From f69f9cc9830f8b0831364dda7c2a3f457d446899 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:43:30 -0600 Subject: [PATCH 3/5] feat(db): replica-fence floor exception for NIP-CI imports Imported events keep their original created_at, which is older than the buzz.created_at_floor guard (migration 0021). insert_import_event now blanks the floor for its own transaction only (set_config(.., true)); the pooled connection is armed again after COMMIT or ROLLBACK, and a test checks that a plain write on the same connection is still refused. Two rules keep covered replica reads sound: - guard_covered_route sends a covered channel or thread read to the writer while the replica snapshot shows an active session for that channel, until expires_at plus the accept delay. A thread root the snapshot lacks stays on the replica, since its replies commit only after it. - Imports commit only from the session's accepts_after: activated_at plus PROOF_MAX_AGE (the ring's 120 x 500 ms) plus a 15 s margin, computed once at activation and published as an accepts_after tag on the 30623 snapshot. Earlier imports get "invalid: import session warming". The fence now refuses ring entries older than PROOF_MAX_AGE, so a proved snapshot taken while imports can exist already contains the activation. The Postgres tests that store imported events (counts, ranges, agents, DM membership, concurrency, session matching) move here, since they need the exception. Migration 0021 is checksum-frozen, so the exception is recorded in 0081, the replica_fence module docs and docs/database.md. Reviewer ask: sign-off from a replica-fence owner on the floor exception and the warm-up bound. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- crates/buzz-db/src/runtime/replica_fence.rs | 50 +- crates/buzz-db/src/store/event.rs | 18 +- crates/buzz-db/src/store/import_session.rs | 220 +++- .../store/import_session/postgres_tests.rs | 1073 ++++++++++++++++- crates/buzz-db/src/store/thread.rs | 24 +- crates/buzz-db/src/store/thread_window.rs | 14 +- docs/database.md | 17 + .../0081_conversation_import_sessions.sql | 11 + schema/tables/public/import_sessions.sql | 2 + 9 files changed, 1370 insertions(+), 59 deletions(-) diff --git a/crates/buzz-db/src/runtime/replica_fence.rs b/crates/buzz-db/src/runtime/replica_fence.rs index 9ada84be262..674c068dec9 100644 --- a/crates/buzz-db/src/runtime/replica_fence.rs +++ b/crates/buzz-db/src/runtime/replica_fence.rs @@ -56,6 +56,22 @@ //! Operational bypasses (sessions without the GUC, `session_replication_role //! = replica` restores) are outside the proof by design and require holding //! the fence closed for their duration; see `migrations/0021`. +//! +//! **NIP-CI imports** are the one in-band exception. An imported event keeps +//! its original `created_at`, so `Db::insert_import_event` blanks the floor +//! for its own transaction (`set_config(.., true)`, transaction-local; the +//! connection is armed again after COMMIT or ROLLBACK). Soundness moves to +//! two rules instead. First, a covered read whose snapshot shows an active +//! import session for its channel goes to the writer +//! (`Db::guard_covered_route`). Second, imports commit only from the +//! session's `accepts_after`, which is activation plus [`PROOF_MAX_AGE`] plus +//! a margin. A reader session proves an entry at most [`PROOF_MAX_AGE`] old, +//! so a snapshot taken while imports can exist on the writer already contains +//! the activation, and the guard sees it. That argument needs the activation +//! to commit within the margin of the clock read that fixed `activated_at`; +//! a transaction that can activate a session sets `SET LOCAL lock_timeout` +//! and `statement_timeout` below the margin, so no single lock wait or +//! statement can use it up. use std::collections::VecDeque; use std::sync::{Arc, Mutex}; @@ -110,6 +126,16 @@ pub const PROBE_INTERVAL: Duration = Duration::from_millis(500); /// just stops spending reader checkouts once the probe is evidently dead. pub const FENCE_STALENESS: Duration = Duration::from_secs(30); +/// Oldest a retained entry may be and still prove a reader session: the +/// ring's nominal history, [`RING_CAPACITY`] probes at [`PROBE_INTERVAL`]. +/// +/// The ring is count-bounded, so slow probes would otherwise let it hold +/// older entries. Capping by age makes "a proved snapshot is at most this +/// far behind the writer" a hard bound, which the NIP-CI import warm-up +/// relies on (see the module docs). +pub const PROOF_MAX_AGE: Duration = + Duration::from_millis(RING_CAPACITY as u64 * PROBE_INTERVAL.as_millis() as u64); + /// How many `(token, fence_wall)` entries the fence retains. At one probe /// per [`PROBE_INTERVAL`] (500ms) this is ~60 seconds of history — a reader /// session lagging further than that behind the newest token fails closed @@ -176,8 +202,9 @@ pub enum ResolveOutcome { /// The observed epoch is not the ring's epoch — the session is on a /// different timeline (restore) or the ring was rotated under it. EpochMismatch, - /// The observed token is below every retained entry: the reader lags - /// further than the ring's history (or the ring is empty). + /// The observed token is below every retained entry, or the entry it + /// reaches is older than [`PROOF_MAX_AGE`]: the reader lags further than + /// the ring's history (or the ring is empty). TokenBehind, } @@ -243,8 +270,9 @@ impl ReplicaFence { /// Resolve the strongest proof a reader session's observation supports: /// the greatest retained entry with `entry.token <= observed_token`, - /// provided the observed epoch matches the ring's. Non-`Proved` outcomes - /// fail closed; they are distinguished only for route metrics. + /// provided the observed epoch matches the ring's and the entry is at + /// most [`PROOF_MAX_AGE`] old. Non-`Proved` outcomes fail closed; they + /// are distinguished only for route metrics. pub fn resolve(&self, observed_token: i64, observed_epoch: Uuid) -> ResolveOutcome { let inner = self.inner.lock().expect("fence lock poisoned"); match inner.epoch { @@ -258,6 +286,7 @@ impl ReplicaFence { .iter() .rev() .find(|entry| entry.token <= observed_token) + .filter(|entry| entry.committed_at.elapsed() <= PROOF_MAX_AGE) .copied() .map_or(ResolveOutcome::TokenBehind, ResolveOutcome::Proved) } @@ -870,6 +899,19 @@ mod postgres_tests { assert!(fence.heartbeat_age().expect("entry retained") > FENCE_STALENESS); } + /// An entry older than the proof age cap proves nothing, even when the + /// observed token reaches it. + #[test] + fn resolve_refuses_entries_older_than_the_proof_age_cap() { + let fence = ReplicaFence::new(); + let epoch = Uuid::new_v4(); + let old = Instant::now() - (PROOF_MAX_AGE + Duration::from_secs(1)); + fence.record(10, epoch, old, Utc::now()); + fence.record(20, epoch, Instant::now(), Utc::now()); + assert_eq!(fence.resolve(15, epoch), ResolveOutcome::TokenBehind); + assert_eq!(fence.resolve(20, epoch).proved().expect("proof").token, 20); + } + /// Resolve picks the greatest retained entry <= the observed token — /// a lagged reader proves from an older wall, never from thin air. #[test] diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index 8d62f962b4a..c52bb9b9a8a 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -2378,14 +2378,26 @@ impl Db { return answer; } let predicate = crate::RoutePredicate::for_query(q, self.replica_read_max_age.is_some()); - match self + let decision = self .route_read( path, predicate, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await - { + .await; + let decision = match q.channel_id { + Some(channel) => { + self.guard_covered_route( + path, + q.community_id, + crate::import_session::CoveredScope::Channel(channel), + decision, + ) + .await + } + None => decision, + }; + match decision { crate::RouteDecision::Replica(mut tx, _entry, reason) => { match crate::event::query_events_on(&mut tx, q).await { Ok(events) => { diff --git a/crates/buzz-db/src/store/import_session.rs b/crates/buzz-db/src/store/import_session.rs index be837b25f2b..27ae4368f93 100644 --- a/crates/buzz-db/src/store/import_session.rs +++ b/crates/buzz-db/src/store/import_session.rs @@ -27,6 +27,28 @@ use uuid::Uuid; use crate::event::{insert_event_with_thread_metadata_tx, ThreadMetadataParams}; use crate::{AdmittedTx, Db, DbError, Result}; +/// Seconds past the replica proof age cap before a newly active session +/// accepts imports. Absorbs the gap between `activated_at` and the +/// activation's commit, and clock skew between relay and database hosts. +const ACCEPT_DELAY_MARGIN_SECS: i64 = 15; + +/// Lock and statement deadline, in seconds, for a transaction that can +/// activate a session. Kept below [`ACCEPT_DELAY_MARGIN_SECS`] so no single +/// stalled lock wait or statement can use up the margin. +const ACTIVATION_TIMEOUT_SECS: i64 = 10; +const _: () = assert!(ACTIVATION_TIMEOUT_SECS < ACCEPT_DELAY_MARGIN_SECS); + +/// Seconds from activation until a session accepts imported events. +/// +/// A replica session proves a heartbeat at most +/// [`crate::replica_fence::PROOF_MAX_AGE`] old, so once this has passed every +/// covered snapshot already shows the session active and +/// [`Db::guard_covered_route`] sends its reads to the writer. The same span +/// keeps an expired session pinning its channel to the writer, so a lagging +/// snapshot cannot miss imports committed just before expiry. +pub const IMPORT_ACCEPT_DELAY_SECS: i64 = + crate::replica_fence::PROOF_MAX_AGE.as_secs() as i64 + ACCEPT_DELAY_MARGIN_SECS; + /// Outcome of an import control event (kinds 42110 to 42113). #[derive(Debug)] pub enum ImportControlOutcome { @@ -114,6 +136,11 @@ struct SessionRow { requires_admin: bool, admin_consent: Option, status: ImportSessionStatus, + /// Unix second from which imports are accepted; set at activation. + accepts_after: Option, + /// Database clock at the read, in whole unix seconds (floored). Every + /// expiry and warm-up decision on the session uses this clock. + db_now: i64, } struct ParticipantRow { @@ -231,11 +258,13 @@ async fn read_session( ) -> Result> { let sql = if lock { "SELECT channel_id, proposer, manifest, source_type, is_dm, range_from, range_to, \ - expires_at, requires_admin, admin_consent, status FROM import_sessions \ + expires_at, requires_admin, admin_consent, status, accepts_after, \ + floor(extract(epoch FROM clock_timestamp()))::bigint AS db_now FROM import_sessions \ WHERE community_id = $1 AND proposal_id = $2 FOR UPDATE" } else { "SELECT channel_id, proposer, manifest, source_type, is_dm, range_from, range_to, \ - expires_at, requires_admin, admin_consent, status FROM import_sessions \ + expires_at, requires_admin, admin_consent, status, accepts_after, \ + floor(extract(epoch FROM clock_timestamp()))::bigint AS db_now FROM import_sessions \ WHERE community_id = $1 AND proposal_id = $2" }; let Some(row) = sqlx::query(sql) @@ -261,6 +290,8 @@ async fn read_session( requires_admin: row.try_get("requires_admin")?, admin_consent: parse_decision(row.try_get("admin_consent")?)?, status: ImportSessionStatus::parse(&status).ok_or_else(|| invalid("status value"))?, + accepts_after: row.try_get("accepts_after")?, + db_now: row.try_get("db_now")?, })) } @@ -337,13 +368,44 @@ async fn store_status( status: ImportSessionStatus, ) -> Result<()> { let community = tx.community(); + // A session becomes active at most once; the first activation fixes + // `activated_at` and `accepts_after`. The clock is read once and floored, + // like `db_now`, so `accepts_after` is exactly the delay past + // `activated_at`. sqlx::query( - "UPDATE import_sessions SET status = $3, updated_at = now() \ - WHERE community_id = $1 AND proposal_id = $2", + "UPDATE import_sessions s SET status = $3, updated_at = now(), \ + activated_at = CASE WHEN $3 = 'active' \ + THEN COALESCE(s.activated_at, c.at) ELSE s.activated_at END, \ + accepts_after = CASE WHEN $3 = 'active' \ + THEN COALESCE(s.accepts_after, COALESCE(s.activated_at, c.at) + $4) \ + ELSE s.accepts_after END \ + FROM (SELECT floor(extract(epoch FROM clock_timestamp()))::bigint AS at) c \ + WHERE s.community_id = $1 AND s.proposal_id = $2", ) .bind(community.as_uuid()) .bind(proposal_id) .bind(status.as_str()) + .bind(IMPORT_ACCEPT_DELAY_SECS) + .execute(tx.conn()) + .await?; + Ok(()) +} + +/// Bound a transaction that can activate a session (a proposal that needs no +/// other consent, or a consent). +/// +/// `activated_at` is read when the activation's UPDATE runs, and covered +/// replica reads stay sound only if the activation commits within +/// [`ACCEPT_DELAY_MARGIN_SECS`] of that read (see [`crate::replica_fence`]). +/// `SET LOCAL` deadlines of [`ACTIVATION_TIMEOUT_SECS`] keep any single lock +/// wait or statement of the transaction from using up that margin. +async fn bound_activation(tx: &mut AdmittedTx) -> Result<()> { + let timeout = format!("{ACTIVATION_TIMEOUT_SECS}s"); + sqlx::query( + "SELECT set_config('lock_timeout', $1, true), \ + set_config('statement_timeout', $1, true)", + ) + .bind(timeout) .execute(tx.conn()) .await?; Ok(()) @@ -435,6 +497,10 @@ async fn publish_snapshot( .map(|p| hex::encode(&p.pubkey)) .collect(); values.extend(pubkeys.iter().map(|p| ["p", p.as_str()])); + let accepts_after = session.accepts_after.map(|at| at.to_string()); + if let Some(at) = &accepts_after { + values.push([import::ACCEPTS_AFTER_TAG, at.as_str()]); + } let tags = values .into_iter() .map(|v| Tag::parse(v).map_err(|_| invalid("snapshot tag"))) @@ -516,7 +582,6 @@ async fn session_cap_reached( channel_id: Uuid, proposer: &[u8], limits: import::ImportLimits, - now: i64, ) -> Result> { let community = tx.community(); for key in [ @@ -536,12 +601,12 @@ async fn session_cap_reached( "SELECT count(*) FILTER (WHERE channel_id = $2), count(*) FILTER (WHERE proposer = $3) \ FROM import_sessions \ WHERE community_id = $1 AND (channel_id = $2 OR proposer = $3) \ - AND status IN ('proposed', 'active') AND expires_at > $4", + AND status IN ('proposed', 'active') \ + AND expires_at > floor(extract(epoch FROM clock_timestamp()))::bigint", ) .bind(community.as_uuid()) .bind(channel_id) .bind(proposer) - .bind(now) .fetch_one(tx.conn()) .await?; if count(in_channel) >= limits.max_active_sessions_per_channel { @@ -568,7 +633,95 @@ async fn is_channel_admin(tx: &mut AdmittedTx, channel_id: Uuid, pubkey: &[u8]) .await?) } +/// What a covered replica read is scoped to, for [`Db::guard_covered_route`]. +pub(crate) enum CoveredScope<'a> { + /// A channel window or a channel-pinned query. + Channel(Uuid), + /// A thread page, keyed by its root event id. + ThreadRoot(&'a [u8]), +} + impl Db { + /// Send a covered replica read back to the writer while its channel has + /// an active import session. + /// + /// A covered page relies on the commit-time floor guard (migration 0021): + /// no row older than the fence wall commits after the proving token. + /// Imported events are the one sanctioned exception (see + /// [`Db::insert_import_event`]), and they commit only under an active + /// session. A reader snapshot that shows the session active may lack + /// imports the writer already has, so the page goes to the writer. A + /// snapshot that shows it terminal already holds every import, since the + /// terminal transition commits after the last import under the same row + /// lock. Bounded reads never rely on the floor and pass through. + /// + /// A snapshot that predates the activation sees no session, but then the + /// writer holds no imports either: imports commit only from + /// `accepts_after`, which is [`IMPORT_ACCEPT_DELAY_SECS`] past activation, + /// longer than any proved snapshot can lag + /// ([`crate::replica_fence::PROOF_MAX_AGE`]). A session past its expiry + /// keeps counting for the same span, so a lagging snapshot cannot miss + /// imports committed just before expiry, and then stops pinning the + /// channel even if its expiry was never stored. + pub(crate) async fn guard_covered_route( + &self, + path: &'static str, + community: CommunityId, + scope: CoveredScope<'_>, + decision: crate::RouteDecision, + ) -> crate::RouteDecision { + let crate::RouteDecision::Replica(mut tx, entry, reason) = decision else { + return decision; + }; + if reason != "covered" { + return crate::RouteDecision::Replica(tx, entry, reason); + } + let active = match scope { + CoveredScope::Channel(channel_id) => { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM import_sessions \ + WHERE community_id = $1 AND channel_id = $2 AND status = 'active' \ + AND expires_at > extract(epoch FROM now())::bigint - $3)", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .bind(IMPORT_ACCEPT_DELAY_SECS) + .fetch_one(&mut *tx) + .await + } + // A root the snapshot lacks stays on the replica: replies commit + // only after their parent, so the snapshot holds none of them, and + // the short page is re-run on the writer by the thread reader's + // own under-limit check. + CoveredScope::ThreadRoot(root) => { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM events e \ + JOIN import_sessions s ON s.community_id = e.community_id \ + AND s.channel_id = e.channel_id \ + WHERE e.community_id = $1 AND e.id = $2 AND s.status = 'active' \ + AND s.expires_at > extract(epoch FROM now())::bigint - $3)", + ) + .bind(community.as_uuid()) + .bind(root) + .bind(IMPORT_ACCEPT_DELAY_SECS) + .fetch_one(&mut *tx) + .await + } + }; + match active { + Ok(false) => crate::RouteDecision::Replica(tx, entry, reason), + Ok(true) => { + Self::record_route(path, "writer", "import_active"); + crate::RouteDecision::Writer + } + Err(e) => { + tracing::warn!(path, "replica import guard failed; routing to writer: {e}"); + Self::record_route(path, "writer", "replica_error"); + crate::RouteDecision::Writer + } + } + } + /// Open a session from a validated kind:42110 proposal. /// /// `content` must already pass [`import::validate_proposal_content`] and @@ -596,6 +749,8 @@ impl Db { crate::observability::WriterOperation::EventWrite, ) .await?; + // A proposal whose participants have all consented activates here. + bound_activation(&mut tx).await?; // Checked before the session caps so a resent stored proposal is // answered as a duplicate even when the channel is at its cap. if event_is_stored(tx.conn(), community, event).await? { @@ -695,15 +850,7 @@ impl Db { .is_some_and(|role| role == "owner" || role == "admin"); let requires_admin = !is_dm && admin_count > 0 && !proposer_is_admin; - if let Some(reason) = session_cap_reached( - &mut tx, - channel_id, - &proposer, - limits, - Utc::now().timestamp(), - ) - .await? - { + if let Some(reason) = session_cap_reached(&mut tx, channel_id, &proposer, limits).await? { tx.rollback().await?; return Ok(ImportControlOutcome::Rejected(reason)); } @@ -758,14 +905,8 @@ impl Db { .await? .ok_or_else(|| invalid("session insert"))?; let participants = load_participants(&mut tx, proposal_id).await?; - refresh_status( - &mut tx, - proposal_id, - &mut session, - &participants, - Utc::now().timestamp(), - ) - .await?; + let now = session.db_now; + refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await?; let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; tx.commit().await?; Ok(ImportControlOutcome::Applied { @@ -798,6 +939,7 @@ impl Db { crate::observability::WriterOperation::EventWrite, ) .await?; + bound_activation(&mut tx).await?; let author = event.pubkey.to_bytes().to_vec(); let Some(mut session) = load_session(&mut tx, proposal_id, true).await? else { tx.rollback().await?; @@ -818,7 +960,7 @@ impl Db { return Ok(ImportControlOutcome::Rejected(reason::CONSENT_MISMATCH)); } let mut participants = load_participants(&mut tx, proposal_id).await?; - let now = Utc::now().timestamp(); + let now = session.db_now; if refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await? { // Persist the lazy transition even though this consent is refused. let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; @@ -918,7 +1060,7 @@ impl Db { tx.rollback().await?; return Ok(ImportControlOutcome::Rejected(reason::NOT_PARTICIPANT)); } - let now = Utc::now().timestamp(); + let now = session.db_now; if refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await? { let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; tx.commit().await?; @@ -976,7 +1118,7 @@ impl Db { return Ok(ImportControlOutcome::Duplicate); } let mut participants = load_participants(&mut tx, proposal_id).await?; - let now = Utc::now().timestamp(); + let now = session.db_now; if refresh_status(&mut tx, proposal_id, &mut session, &participants, now).await? { let snapshot = publish_snapshot(self, &mut tx, proposal_id, keys).await?; tx.commit().await?; @@ -1041,7 +1183,7 @@ impl Db { let participants = read_participants(&mut conn, community, proposal_id).await?; let already_stored = event_is_stored(&mut conn, community, event).await?; drop(conn); - let status = import::derive_status(&facts(&session, &participants), Utc::now().timestamp()); + let status = import::derive_status(&facts(&session, &participants), session.db_now); Ok(Some(ImportPreflight { channel_id: session.channel_id, range: session.range, @@ -1081,6 +1223,16 @@ impl Db { crate::observability::WriterOperation::EventWrite, ) .await?; + // Imported events keep their original created_at, which is older than + // the replica-fence floor (migration 0021). Disarm the floor for this + // transaction only; it commits nothing but this event and its session + // bookkeeping, and only while the session is active and past + // `accepts_after`. Covered replica reads stay sound through + // Db::guard_covered_route, which sends a channel with an active + // session to the writer. + sqlx::query("SELECT set_config('buzz.created_at_floor', '', true)") + .execute(tx.conn()) + .await?; let reject = |reason| ImportInsertOutcome::Rejected { reason, snapshot: None, @@ -1104,7 +1256,7 @@ impl Db { return Ok(ImportInsertOutcome::Duplicate); } let participants = load_participants(&mut tx, &proposal_id).await?; - let now = Utc::now().timestamp(); + let now = session.db_now; if refresh_status(&mut tx, &proposal_id, &mut session, &participants, now).await? { let snapshot = publish_snapshot(self, &mut tx, &proposal_id, keys).await?; tx.commit().await?; @@ -1129,6 +1281,14 @@ impl Db { tx.rollback().await?; return Ok(reject(reason::NOT_CONSENTING)); }; + // Measured on the database clock, the clock `accepts_after` was set by. + if session + .accepts_after + .is_none_or(|accepts_after| session.db_now < accepts_after) + { + tx.rollback().await?; + return Ok(reject(reason::SESSION_WARMING)); + } // An account linked to an owner after the proposal is an agent now. if any_agent(&mut tx, std::slice::from_ref(&author)).await? { tx.rollback().await?; @@ -1306,6 +1466,8 @@ mod tests { requires_admin: true, admin_consent: Some(ImportDecision::Accept), status: ImportSessionStatus::Active, + accepts_after: Some(50), + db_now: 60, }; let participants = vec![ ParticipantRow { diff --git a/crates/buzz-db/src/store/import_session/postgres_tests.rs b/crates/buzz-db/src/store/import_session/postgres_tests.rs index 406d2a3eac5..5bf5f0dc43c 100644 --- a/crates/buzz-db/src/store/import_session/postgres_tests.rs +++ b/crates/buzz-db/src/store/import_session/postgres_tests.rs @@ -230,7 +230,23 @@ async fn consent( .await } +/// Move every active session in the fixture's community past its warm-up, so +/// a test can import right after activation. The warm-up itself is covered by +/// `imports_wait_for_accepts_after`. Rows already moved are not touched, so +/// this never waits on a session row lock. +async fn skip_warmup(f: &Fixture) { + sqlx::query( + "UPDATE import_sessions SET accepts_after = 0 \ + WHERE community_id = $1 AND accepts_after > 0", + ) + .bind(f.community.as_uuid()) + .execute(&f.db.pool) + .await + .unwrap(); +} + async fn insert(f: &Fixture, event: &Event, channel: Uuid) -> ImportInsertOutcome { + skip_warmup(f).await; f.db.insert_import_event( f.community, event, @@ -244,6 +260,149 @@ async fn insert(f: &Fixture, event: &Event, channel: Uuid) -> ImportInsertOutcom .unwrap() } +fn rejected_reason(outcome: &ImportInsertOutcome) -> Option<&'static str> { + match outcome { + ImportInsertOutcome::Rejected { reason, .. } => Some(reason), + _ => None, + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dm_session_lifecycle_enforces_consent_range_and_counts() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let now = Utc::now().timestamp(); + let content = proposal_content(&[(&alice, 2, 0), (&bob, 1, 0)], now); + let proposal = proposal_event(&alice, dm, &content); + + let snapshot = applied( + f.db.create_import_session( + f.community, + &proposal, + &content, + dm, + content.expires_at, + LIMITS, + &f.relay, + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Proposed); + assert_eq!( + snapshot.consents.get(&alice.public_key().to_hex()), + Some(&ImportDecision::Accept) + ); + + // Bob has not consented: the session is not active yet. + let early = imported(&alice, &proposal, dm, now - 5_000, 1); + assert_eq!( + rejected_reason(&insert(&f, &early, dm).await), + Some(reason::SESSION_NOT_ACTIVE) + ); + + // A consent bound to the wrong identity is refused. + let wrong = consent( + &f, + &bob, + &proposal, + dm, + ImportDecision::Accept, + CONVERSATION, + ) + .await + .unwrap(); + assert!(matches!( + wrong, + ImportControlOutcome::Rejected(reason::CONSENT_MISMATCH) + )); + + let snapshot = applied( + consent( + &f, + &bob, + &proposal, + dm, + ImportDecision::Accept, + &source_user(&bob), + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Active); + + assert!(matches!( + insert(&f, &early, dm).await, + ImportInsertOutcome::Inserted { .. } + )); + let outside = imported(&alice, &proposal, dm, now - 20_000, 2); + assert_eq!( + rejected_reason(&insert(&f, &outside, dm).await), + Some(reason::TIMESTAMP_OUT_OF_RANGE) + ); + let second = imported(&alice, &proposal, dm, now - 4_000, 3); + assert!(matches!( + insert(&f, &second, dm).await, + ImportInsertOutcome::Inserted { .. } + )); + let third = imported(&alice, &proposal, dm, now - 3_000, 4); + assert_eq!( + rejected_reason(&insert(&f, &third, dm).await), + Some(reason::COUNT_EXCEEDED) + ); + // A resend after the count is used up is a duplicate, not a refusal, and + // the preflight read agrees. + assert!(matches!( + insert(&f, &second, dm).await, + ImportInsertOutcome::Duplicate + )); + let preflight = + f.db.import_preflight(f.community, proposal.id.as_bytes(), &second) + .await + .unwrap() + .expect("session"); + assert!(preflight.already_stored); + let stranger = Keys::generate(); + let foreign = imported(&stranger, &proposal, dm, now - 3_000, 5); + assert_eq!( + rejected_reason(&insert(&f, &foreign, dm).await), + Some(reason::NOT_CONSENTING) + ); + + // Imported events never create mention rows. + let mentions: i64 = sqlx::query_scalar( + "SELECT count(*) FROM event_mentions WHERE community_id = $1 AND event_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(early.id.as_bytes().as_slice()) + .fetch_one(&f.db.pool) + .await + .unwrap(); + assert_eq!(mentions, 0); + + // Bob declines after accepting: a DM session ends. + let snapshot = applied( + consent( + &f, + &bob, + &proposal, + dm, + ImportDecision::Decline, + &source_user(&bob), + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Declined); + let after = imported(&bob, &proposal, dm, now - 2_000, 6); + assert_eq!( + rejected_reason(&insert(&f, &after, dm).await), + Some(reason::SESSION_NOT_ACTIVE) + ); +} + #[tokio::test] #[ignore = "requires Postgres"] async fn dm_participants_must_equal_members() { @@ -296,6 +455,137 @@ async fn dm_participants_must_equal_members() { )); } +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_session_requires_admin_and_withdraw_stops_acceptance() { + let f = fixture().await; + let (owner, alice, bob) = (Keys::generate(), Keys::generate(), Keys::generate()); + let chan = channel( + &f, + "stream", + &[(&owner, "owner"), (&alice, "member"), (&bob, "member")], + ) + .await; + let now = Utc::now().timestamp(); + let content = proposal_content(&[(&alice, 5, 1), (&bob, 5, 0)], now); + let proposal = proposal_event(&alice, chan, &content); + let snapshot = applied( + f.db.create_import_session( + f.community, + &proposal, + &content, + chan, + content.expires_at, + LIMITS, + &f.relay, + ) + .await, + ) + .await; + assert!(snapshot.required.contains(&"admin".to_string())); + + applied( + consent( + &f, + &bob, + &proposal, + chan, + ImportDecision::Accept, + &source_user(&bob), + ) + .await, + ) + .await; + // A non-admin cannot give the admin consent. + let refused = consent(&f, &bob, &proposal, chan, ImportDecision::Accept, "admin") + .await + .unwrap(); + assert!(matches!( + refused, + ImportControlOutcome::Rejected(reason::NOT_PARTICIPANT) + )); + let snapshot = + applied(consent(&f, &owner, &proposal, chan, ImportDecision::Accept, "admin").await).await; + assert_eq!(snapshot.status, ImportSessionStatus::Active); + + let message = imported(&alice, &proposal, chan, now - 5_000, 1); + assert!(matches!( + insert(&f, &message, chan).await, + ImportInsertOutcome::Inserted { .. } + )); + + // A reaction on a non-imported target is refused. + let plain = sign( + &bob, + KIND_STREAM_MESSAGE, + "live", + vec![vec!["h".into(), chan.to_string()]], + now, + ); + crate::event::insert_event_with_thread_metadata( + &f.db.pool, + f.community, + &plain, + Some(chan), + None, + ) + .await + .unwrap(); + let reaction = sign( + &alice, + KIND_REACTION, + "+", + vec![ + vec!["h".into(), chan.to_string()], + vec!["e".into(), plain.id.to_hex()], + vec!["import".into(), proposal.id.to_hex()], + vec!["source".into(), "test".into(), "ref-1".into()], + ], + now - 4_000, + ); + let actor = alice.public_key().to_bytes(); + skip_warmup(&f).await; + let outcome = + f.db.insert_import_event( + f.community, + &reaction, + &tags_of(&reaction), + chan, + None, + Some(ImportReaction { + target_event_id: plain.id.as_bytes(), + actor_pubkey: &actor, + emoji: "+", + }), + &f.relay, + ) + .await + .unwrap(); + assert_eq!( + rejected_reason(&outcome), + Some(reason::REACTION_TARGET_NOT_IMPORTED) + ); + + let withdraw = control(&bob, 42112, &proposal, chan, r#"{"v":1}"#); + let snapshot = applied( + f.db.withdraw_import_session( + f.community, + &withdraw, + proposal.id.as_bytes(), + chan, + &f.relay, + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Withdrawn); + let late = imported(&alice, &proposal, chan, now - 3_000, 2); + assert_eq!( + rejected_reason(&insert(&f, &late, chan).await), + Some(reason::SESSION_NOT_ACTIVE) + ); +} + #[tokio::test] #[ignore = "requires Postgres"] async fn completion_and_expiry_move_the_session() { @@ -423,6 +713,41 @@ async fn import_writes_are_refused_once_deletion_starts() { ); } +async fn make_agent(f: &Fixture, agent: &Keys, owner: &Keys) { + for (pubkey, owner) in [ + (owner.public_key().to_bytes(), None), + ( + agent.public_key().to_bytes(), + Some(owner.public_key().to_bytes()), + ), + ] { + sqlx::query( + "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) VALUES ($1, $2, $3) \ + ON CONFLICT (community_id, pubkey) DO UPDATE \ + SET agent_owner_pubkey = EXCLUDED.agent_owner_pubkey", + ) + .bind(f.community.as_uuid()) + .bind(pubkey.as_slice()) + .bind(owner.as_ref().map(|o| o.as_slice())) + .execute(&f.db.pool) + .await + .unwrap(); + } +} + +async fn add_member(f: &Fixture, channel: Uuid, keys: &Keys) { + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role) \ + VALUES ($1, $2, $3, 'member')", + ) + .bind(f.community.as_uuid()) + .bind(channel) + .bind(keys.public_key().to_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); +} + async fn propose( f: &Fixture, proposer: &Keys, @@ -445,6 +770,91 @@ async fn propose( (proposal, outcome) } +async fn accept(f: &Fixture, keys: &Keys, proposal: &Event, channel: Uuid) { + applied( + consent( + f, + keys, + proposal, + channel, + ImportDecision::Accept, + &source_user(keys), + ) + .await, + ) + .await; +} + +fn imported_with_source( + keys: &Keys, + proposal: &Event, + channel: Uuid, + created_at: i64, + source_type: &str, +) -> Event { + sign( + keys, + KIND_STREAM_MESSAGE, + "message", + vec![ + vec!["h".into(), channel.to_string()], + vec!["import".into(), proposal.id.to_hex()], + vec!["source".into(), source_type.into(), "ref".into()], + ], + created_at, + ) +} + +fn imported_reaction( + keys: &Keys, + proposal: &Event, + channel: Uuid, + target: &Event, + created_at: i64, +) -> Event { + sign( + keys, + KIND_REACTION, + "+", + vec![ + vec!["h".into(), channel.to_string()], + vec!["e".into(), target.id.to_hex()], + vec!["import".into(), proposal.id.to_hex()], + vec!["source".into(), "test".into(), "target".into()], + ], + created_at, + ) +} + +async fn insert_reaction( + f: &Fixture, + event: &Event, + channel: Uuid, + target: &Event, +) -> ImportInsertOutcome { + let actor = event.pubkey.to_bytes(); + skip_warmup(f).await; + f.db.insert_import_event( + f.community, + event, + &tags_of(event), + channel, + None, + Some(ImportReaction { + target_event_id: target.id.as_bytes(), + actor_pubkey: &actor, + emoji: "+", + }), + &f.relay, + ) + .await + .unwrap() +} + +fn is_inserted(outcome: &ImportInsertOutcome) -> bool { + matches!(outcome, ImportInsertOutcome::Inserted { .. }) +} + fn control_rejection(outcome: Result) -> &'static str { match outcome.unwrap() { ImportControlOutcome::Rejected(reason) => reason, @@ -454,25 +864,333 @@ fn control_rejection(outcome: Result) -> &'static str { #[tokio::test] #[ignore = "requires Postgres"] -async fn control_events_mention_participants_and_resend_as_duplicates() { +async fn imported_history_never_reaches_agents() { let f = fixture().await; - let (alice, bob) = (Keys::generate(), Keys::generate()); - let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; - let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 1, 0)]).await; - applied(outcome).await; + let (owner, alice, bot) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&f, &bot, &owner).await; - // The proposal is live activity: each participant gets a mention row. - let mentioned: Vec = sqlx::query_scalar( - "SELECT pubkey_hex FROM event_mentions \ - WHERE community_id = $1 AND event_id = $2 ORDER BY pubkey_hex", + // An agent cannot be a participant, in a channel or in a DM. + let private = channel( + &f, + "stream", + &[(&owner, "owner"), (&alice, "member"), (&bot, "member")], ) - .bind(f.community.as_uuid()) - .bind(proposal.id.as_bytes().as_slice()) - .fetch_all(&f.db.pool) - .await - .unwrap(); - let mut expected = vec![alice.public_key().to_hex(), bob.public_key().to_hex()]; - expected.sort(); + .await; + let (_, outcome) = propose(&f, &owner, private, &[(&owner, 1, 0), (&bot, 1, 0)]).await; + assert_eq!( + control_rejection(outcome), + reason::PARTICIPANTS_INCLUDE_AGENTS + ); + let dm = channel(&f, "dm", &[(&owner, "member"), (&bot, "member")]).await; + let (_, outcome) = propose(&f, &owner, dm, &[(&owner, 1, 0), (&bot, 1, 0)]).await; + assert_eq!( + control_rejection(outcome), + reason::PARTICIPANTS_INCLUDE_AGENTS + ); + + // A private destination with an agent member is refused; an open one is not. + let (_, outcome) = propose(&f, &owner, private, &[(&owner, 1, 0), (&alice, 1, 0)]).await; + assert_eq!(control_rejection(outcome), reason::DESTINATION_HAS_AGENTS); + sqlx::query("UPDATE channels SET visibility = 'open' WHERE community_id = $1 AND id = $2") + .bind(f.community.as_uuid()) + .bind(private) + .execute(&f.db.pool) + .await + .unwrap(); + let (_, outcome) = propose(&f, &owner, private, &[(&owner, 1, 0), (&alice, 1, 0)]).await; + assert!(matches!( + outcome.unwrap(), + ImportControlOutcome::Applied { .. } + )); + + // An agent that joins a private destination after activation stops imports. + let later = channel(&f, "stream", &[(&owner, "owner"), (&alice, "member")]).await; + let (proposal, outcome) = propose(&f, &owner, later, &[(&owner, 2, 0), (&alice, 1, 0)]).await; + applied(outcome).await; + accept(&f, &alice, &proposal, later).await; + let now = Utc::now().timestamp(); + assert!(is_inserted( + &insert( + &f, + &imported(&owner, &proposal, later, now - 5_000, 1), + later + ) + .await + )); + add_member(&f, later, &bot).await; + assert_eq!( + rejected_reason( + &insert( + &f, + &imported(&owner, &proposal, later, now - 4_000, 2), + later + ) + .await + ), + Some(reason::DESTINATION_HAS_AGENTS) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dm_membership_change_after_activation_stops_imports() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 2, 0), (&bob, 0, 0)]).await; + applied(outcome).await; + accept(&f, &bob, &proposal, dm).await; + let now = Utc::now().timestamp(); + assert!(is_inserted( + &insert(&f, &imported(&alice, &proposal, dm, now - 5_000, 1), dm).await + )); + // A member added to the DM (kind:9000 allows it) stops imports. + let carol = Keys::generate(); + add_member(&f, dm, &carol).await; + assert_eq!( + rejected_reason(&insert(&f, &imported(&alice, &proposal, dm, now - 4_500, 3), dm).await), + Some(reason::DM_PARTICIPANTS_MISMATCH) + ); + sqlx::query( + "DELETE FROM channel_members WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3", + ) + .bind(f.community.as_uuid()) + .bind(dm) + .bind(carol.public_key().to_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); + // So does a participant leaving it. + sqlx::query( + "UPDATE channel_members SET removed_at = now() \ + WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3", + ) + .bind(f.community.as_uuid()) + .bind(dm) + .bind(bob.public_key().to_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); + assert_eq!( + rejected_reason(&insert(&f, &imported(&alice, &proposal, dm, now - 4_000, 2), dm).await), + Some(reason::DM_PARTICIPANTS_MISMATCH) + ); + // The participant who left can still finish. + let done = r#"{"v":1,"published":{"messages":0,"reactions":0}}"#; + let snapshot = applied( + f.db.complete_import_participant( + f.community, + &control(&bob, 42113, &proposal, dm, done), + proposal.id.as_bytes(), + dm, + &f.relay, + ) + .await, + ) + .await; + assert_eq!(snapshot.completed, vec![bob.public_key().to_hex()]); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_inserts_never_exceed_the_declared_count() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 2, 0), (&bob, 0, 0)]).await; + applied(outcome).await; + accept(&f, &bob, &proposal, dm).await; + let now = Utc::now().timestamp(); + assert!(is_inserted( + &insert(&f, &imported(&alice, &proposal, dm, now - 5_000, 1), dm).await + )); + // One message remains; two different events race for it. + let (a, b) = ( + imported(&alice, &proposal, dm, now - 4_000, 2), + imported(&alice, &proposal, dm, now - 3_000, 3), + ); + // Hold the session row so both inserts are in flight before either can + // read the counter. + let mut blocker = f.db.pool.begin().await.unwrap(); + sqlx::query( + "SELECT 1 FROM import_sessions WHERE community_id = $1 AND proposal_id = $2 FOR UPDATE", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .execute(&mut *blocker) + .await + .unwrap(); + let release = async { + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + blocker.commit().await.unwrap(); + }; + let (first, second, ()) = tokio::join!(insert(&f, &a, dm), insert(&f, &b, dm), release); + let stored = [&first, &second] + .into_iter() + .filter(|o| is_inserted(o)) + .count(); + assert_eq!(stored, 1, "{first:?} / {second:?}"); + let refused = if is_inserted(&first) { &second } else { &first }; + assert_eq!(rejected_reason(refused), Some(reason::COUNT_EXCEEDED)); + let published: i64 = sqlx::query_scalar( + "SELECT published_messages FROM import_session_participants \ + WHERE community_id = $1 AND proposal_id = $2 AND pubkey = $3", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .bind(alice.public_key().to_bytes().as_slice()) + .fetch_one(&f.db.pool) + .await + .unwrap(); + assert_eq!(published, 2); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn imported_events_must_match_their_session() { + let f = fixture().await; + let (owner, alice, carol) = (Keys::generate(), Keys::generate(), Keys::generate()); + let chan = channel( + &f, + "stream", + &[(&owner, "owner"), (&alice, "member"), (&carol, "member")], + ) + .await; + let other = channel(&f, "stream", &[(&owner, "owner"), (&alice, "member")]).await; + let now = Utc::now().timestamp(); + + // Session A: owner and alice. Session B in the same channel: owner and carol. + // Session C in another channel: owner and alice. + let (a, outcome) = propose(&f, &owner, chan, &[(&owner, 1, 0), (&alice, 2, 3)]).await; + applied(outcome).await; + accept(&f, &alice, &a, chan).await; + let (b, outcome) = propose(&f, &owner, chan, &[(&owner, 1, 0), (&carol, 1, 0)]).await; + applied(outcome).await; + accept(&f, &carol, &b, chan).await; + let (c, outcome) = propose(&f, &owner, other, &[(&owner, 1, 0), (&alice, 1, 0)]).await; + applied(outcome).await; + accept(&f, &alice, &c, other).await; + + let in_a = imported(&alice, &a, chan, now - 9_000, 1); + assert!(is_inserted(&insert(&f, &in_a, chan).await)); + let in_b = imported(&carol, &b, chan, now - 9_000, 2); + assert!(is_inserted(&insert(&f, &in_b, chan).await)); + let in_c = imported(&alice, &c, other, now - 9_000, 3); + assert!(is_inserted(&insert(&f, &in_c, other).await)); + + // The session's channel, its source type and its participants bind. + assert_eq!( + rejected_reason(&insert(&f, &imported(&alice, &a, chan, now - 8_000, 4), other).await), + Some(reason::CHANNEL_MISMATCH) + ); + assert_eq!( + rejected_reason( + &insert( + &f, + &imported_with_source(&alice, &a, chan, now - 8_000, "other"), + chan + ) + .await + ), + Some(reason::SOURCE_TYPE_MISMATCH) + ); + assert_eq!( + rejected_reason(&insert(&f, &imported(&carol, &a, chan, now - 8_000, 5), chan).await), + Some(reason::NOT_CONSENTING) + ); + + // A reaction target imported under another proposal, or living in + // another channel, is refused. + let on_b = imported_reaction(&alice, &a, chan, &in_b, now - 7_000); + assert_eq!( + rejected_reason(&insert_reaction(&f, &on_b, chan, &in_b).await), + Some(reason::REACTION_TARGET_NOT_IMPORTED) + ); + let on_c = imported_reaction(&alice, &a, chan, &in_c, now - 7_000); + assert_eq!( + rejected_reason(&insert_reaction(&f, &on_c, chan, &in_c).await), + Some(reason::REACTION_TARGET_NOT_IMPORTED) + ); + + // A second imported reaction with the same actor, target and emoji + // conflicts; it is not reported as a duplicate. + let first = imported_reaction(&alice, &a, chan, &in_a, now - 7_000); + assert!(is_inserted(&insert_reaction(&f, &first, chan, &in_a).await)); + assert!(matches!( + insert_reaction(&f, &first, chan, &in_a).await, + ImportInsertOutcome::Duplicate + )); + let again = imported_reaction(&alice, &a, chan, &in_a, now - 6_000); + assert_eq!( + rejected_reason(&insert_reaction(&f, &again, chan, &in_a).await), + Some(reason::REACTION_CONFLICT) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn proposer_only_session_activates_and_admin_decline_withdraws() { + let f = fixture().await; + let (owner, alice) = (Keys::generate(), Keys::generate()); + let chan = channel(&f, "stream", &[(&owner, "owner"), (&alice, "member")]).await; + + // An owner importing only their own history needs nobody else. + let (_, outcome) = propose(&f, &owner, chan, &[(&owner, 1, 0)]).await; + assert_eq!(applied(outcome).await.status, ImportSessionStatus::Active); + + // A member's session needs the admin; an admin decline after activation + // withdraws it. + let (proposal, outcome) = propose(&f, &alice, chan, &[(&alice, 2, 0)]).await; + assert_eq!(applied(outcome).await.status, ImportSessionStatus::Proposed); + let snapshot = + applied(consent(&f, &owner, &proposal, chan, ImportDecision::Accept, "admin").await).await; + assert_eq!(snapshot.status, ImportSessionStatus::Active); + let now = Utc::now().timestamp(); + assert!(is_inserted( + &insert(&f, &imported(&alice, &proposal, chan, now - 5_000, 1), chan).await + )); + let snapshot = applied( + consent( + &f, + &owner, + &proposal, + chan, + ImportDecision::Decline, + "admin", + ) + .await, + ) + .await; + assert_eq!(snapshot.status, ImportSessionStatus::Withdrawn); + assert_eq!( + rejected_reason( + &insert(&f, &imported(&alice, &proposal, chan, now - 4_000, 2), chan).await + ), + Some(reason::SESSION_NOT_ACTIVE) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn control_events_mention_participants_and_resend_as_duplicates() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 1, 0)]).await; + applied(outcome).await; + + // The proposal is live activity: each participant gets a mention row. + let mentioned: Vec = sqlx::query_scalar( + "SELECT pubkey_hex FROM event_mentions \ + WHERE community_id = $1 AND event_id = $2 ORDER BY pubkey_hex", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .fetch_all(&f.db.pool) + .await + .unwrap(); + let mut expected = vec![alice.public_key().to_hex(), bob.public_key().to_hex()]; + expected.sort(); assert_eq!(mentioned, expected); let feed = f.db.query_feed_mentions(f.community, &bob.public_key().to_bytes(), &[dm], None, 10) @@ -543,6 +1261,234 @@ async fn control_events_mention_participants_and_resend_as_duplicates() { )); } +async fn covered(f: &Fixture, scope: CoveredScope<'_>, reason: &'static str) -> bool { + let tx = f.db.pool.begin().await.unwrap(); + let entry = crate::runtime::replica_fence::TokenEntry { + token: 1, + committed_at: std::time::Instant::now(), + fence_wall: Utc::now(), + }; + let decision = crate::RouteDecision::Replica(tx, entry, reason); + matches!( + f.db.guard_covered_route("test", f.community, scope, decision) + .await, + crate::RouteDecision::Replica(..) + ) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn covered_reads_go_to_the_writer_while_a_channel_imports() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let quiet = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let live = sign( + &alice, + KIND_STREAM_MESSAGE, + "live", + vec![vec!["h".into(), dm.to_string()]], + Utc::now().timestamp(), + ); + crate::event::insert_event_with_thread_metadata(&f.db.pool, f.community, &live, Some(dm), None) + .await + .unwrap(); + let missing = [7u8; 32]; + let root = CoveredScope::ThreadRoot(live.id.as_bytes()); + + // A proposed session does not admit imports yet. + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 0, 0)]).await; + applied(outcome).await; + assert!(covered(&f, CoveredScope::Channel(dm), "covered").await); + assert!(covered(&f, CoveredScope::ThreadRoot(&missing), "covered").await); + + accept(&f, &bob, &proposal, dm).await; + assert!(!covered(&f, CoveredScope::Channel(dm), "covered").await); + assert!(!covered(&f, root, "covered").await); + // A root the snapshot lacks keeps the replica: the thread reader re-runs + // the short page it gets on the writer. + assert!(covered(&f, CoveredScope::ThreadRoot(&missing), "covered").await); + // Other channels, and bounded reads, keep the replica. + assert!(covered(&f, CoveredScope::Channel(quiet), "covered").await); + assert!(covered(&f, CoveredScope::Channel(dm), "fresh").await); + + // A terminal session no longer holds the channel. + let withdraw = control(&bob, 42112, &proposal, dm, ""); + applied( + f.db.withdraw_import_session(f.community, &withdraw, proposal.id.as_bytes(), dm, &f.relay) + .await, + ) + .await; + assert!(covered(&f, CoveredScope::Channel(dm), "covered").await); + assert!(covered(&f, CoveredScope::ThreadRoot(live.id.as_bytes()), "covered").await); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn expired_sessions_stop_pinning_their_channel() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 0, 0)]).await; + applied(outcome).await; + accept(&f, &bob, &proposal, dm).await; + let expire = |at: i64| { + sqlx::query( + "UPDATE import_sessions SET expires_at = $3 \ + WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .bind(at) + .execute(&f.db.pool) + }; + let now = Utc::now().timestamp(); + + // Just past expiry the status is still stored as active and a lagging + // snapshot may lack the last imports, so the channel stays on the writer. + expire(now - 10).await.unwrap(); + assert!(!covered(&f, CoveredScope::Channel(dm), "covered").await); + // Past expiry plus the warm-up span, it no longer pins the channel. + expire(now - IMPORT_ACCEPT_DELAY_SECS - 10).await.unwrap(); + assert!(covered(&f, CoveredScope::Channel(dm), "covered").await); +} + +/// The snapshot's `accepts_after` tag value. +fn accepts_after_tag(stored: &StoredEvent) -> Option { + stored.event.tags.iter().find_map(|tag| { + let slice = tag.as_slice(); + (slice.first().map(String::as_str) == Some(import::ACCEPTS_AFTER_TAG)) + .then(|| slice.get(1).and_then(|v| v.parse().ok())) + .flatten() + }) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn imports_wait_for_accepts_after() { + let f = fixture().await; + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 0, 0)]).await; + let ImportControlOutcome::Applied { snapshot, .. } = outcome.unwrap() else { + panic!("proposal not applied"); + }; + assert_eq!(accepts_after_tag(&snapshot), None, "proposed has no tag"); + + // A reader snapshot taken before activation, as a lagging replica holds. + let mut before = f.db.pool.begin().await.unwrap(); + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *before) + .await + .unwrap(); + sqlx::query("SELECT 1 FROM import_sessions LIMIT 1") + .execute(&mut *before) + .await + .unwrap(); + + let content = serde_json::json!({ + "v": 1, "decision": "accept", "source_user": source_user(&bob) + }) + .to_string(); + let event = consent_event(&bob, &proposal, dm, &content); + let ImportControlOutcome::Applied { snapshot, .. } = + f.db.record_import_consent( + f.community, + &event, + proposal.id.as_bytes(), + dm, + MANIFEST, + ImportDecision::Accept, + &source_user(&bob), + &f.relay, + ) + .await + .unwrap() + else { + panic!("consent not applied"); + }; + let (activated_at, stored_accepts_after): (i64, i64) = sqlx::query_as( + "SELECT activated_at, accepts_after FROM import_sessions \ + WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .fetch_one(&f.db.pool) + .await + .unwrap(); + assert_eq!( + stored_accepts_after, + activated_at + IMPORT_ACCEPT_DELAY_SECS + ); + assert_eq!(accepts_after_tag(&snapshot), Some(stored_accepts_after)); + + // Inside the warm-up the import is refused, so the writer holds nothing + // the pre-activation snapshot could be missing. + let now = Utc::now().timestamp(); + let message = imported(&alice, &proposal, dm, now - 5_000, 1); + let outcome = + f.db.insert_import_event( + f.community, + &message, + &tags_of(&message), + dm, + None, + None, + &f.relay, + ) + .await + .unwrap(); + assert_eq!(rejected_reason(&outcome), Some(reason::SESSION_WARMING)); + let imported_rows: i64 = sqlx::query_scalar( + "SELECT count(*) FROM events WHERE community_id = $1 AND channel_id = $2 AND kind = 9", + ) + .bind(f.community.as_uuid()) + .bind(dm) + .fetch_one(&f.db.pool) + .await + .unwrap(); + assert_eq!(imported_rows, 0); + + // The pre-activation snapshot sees no active session and keeps the + // replica; a current snapshot sends the channel to the writer. + let entry = crate::runtime::replica_fence::TokenEntry { + token: 1, + committed_at: std::time::Instant::now(), + fence_wall: Utc::now(), + }; + let stale = crate::RouteDecision::Replica(before, entry, "covered"); + assert!(matches!( + f.db.guard_covered_route("test", f.community, CoveredScope::Channel(dm), stale) + .await, + crate::RouteDecision::Replica(..) + )); + assert!(!covered(&f, CoveredScope::Channel(dm), "covered").await); + + // Once accepts_after has passed, the same event is accepted. + sqlx::query( + "UPDATE import_sessions SET accepts_after = extract(epoch FROM now())::bigint - 1 \ + WHERE community_id = $1 AND proposal_id = $2", + ) + .bind(f.community.as_uuid()) + .bind(proposal.id.as_bytes().as_slice()) + .execute(&f.db.pool) + .await + .unwrap(); + let outcome = + f.db.insert_import_event( + f.community, + &message, + &tags_of(&message), + dm, + None, + None, + &f.relay, + ) + .await + .unwrap(); + assert!(is_inserted(&outcome)); +} + #[tokio::test] #[ignore = "requires Postgres"] async fn active_sessions_are_capped_per_channel_and_proposer() { @@ -625,3 +1571,98 @@ async fn active_sessions_are_capped_per_channel_and_proposer() { let (_, outcome) = open(first, 3).await; assert_eq!(rejection(outcome), None); } + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_participant_linked_to_an_owner_later_cannot_import() { + let f = fixture().await; + let (owner, alice) = (Keys::generate(), Keys::generate()); + let room = channel(&f, "stream", &[(&owner, "owner"), (&alice, "member")]).await; + let (proposal, outcome) = propose(&f, &owner, room, &[(&owner, 0, 0), (&alice, 2, 0)]).await; + applied(outcome).await; + accept(&f, &alice, &proposal, room).await; + let now = Utc::now().timestamp(); + assert!(is_inserted( + &insert(&f, &imported(&alice, &proposal, room, now - 5_000, 1), room).await + )); + make_agent(&f, &alice, &owner).await; + assert_eq!( + rejected_reason( + &insert(&f, &imported(&alice, &proposal, room, now - 4_000, 2), room).await + ), + Some(reason::PARTICIPANTS_INCLUDE_AGENTS) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_floor_is_armed_again_after_an_import_transaction() { + let f = fixture().await; + // One connection, so the plain write below reuses the import's session. + let db = Db::new(&crate::DbConfig { + database_url: crate::test_support::database_url(), + max_connections: 1, + min_connections: 0, + ..crate::DbConfig::default() + }) + .await + .unwrap(); + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = channel(&f, "dm", &[(&alice, "member"), (&bob, "member")]).await; + let (proposal, outcome) = propose(&f, &alice, dm, &[(&alice, 1, 0), (&bob, 0, 0)]).await; + applied(outcome).await; + accept(&f, &bob, &proposal, dm).await; + skip_warmup(&f).await; + + let backend = || async { + sqlx::query_scalar::<_, i32>("SELECT pg_backend_pid()") + .fetch_one(&db.pool) + .await + .unwrap() + }; + let pid = backend().await; + let now = Utc::now().timestamp(); + let message = imported(&alice, &proposal, dm, now - 5_000, 1); + let outcome = db + .insert_import_event( + f.community, + &message, + &tags_of(&message), + dm, + None, + None, + &f.relay, + ) + .await + .unwrap(); + assert!(is_inserted(&outcome)); + assert_eq!(backend().await, pid, "the pool reused its one connection"); + let floor: String = sqlx::query_scalar("SHOW buzz.created_at_floor") + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!( + floor, + crate::replica_fence::CREATED_AT_FLOOR_SECS.to_string() + ); + + // A plain channel write with an old created_at is still refused at commit. + let old = sign( + &alice, + KIND_STREAM_MESSAGE, + "old", + vec![vec!["h".into(), dm.to_string()]], + now - 5_000, + ); + let error = crate::event::insert_event_with_thread_metadata( + &db.pool, + f.community, + &old, + Some(dm), + None, + ) + .await + .expect_err("an old non-import row must not pass the floor"); + assert!(error.to_string().contains("replica-fence floor"), "{error}"); + assert_eq!(backend().await, pid); +} diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 7c617aba6a8..2b845a33340 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -893,14 +893,22 @@ impl Db { ), None => ("thread_head", RoutePredicate::Bounded), }; - if let RouteDecision::Replica(mut tx, entry, reason) = self + let decision = self .route_read( path, predicate, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await - { + .await; + let decision = self + .guard_covered_route( + path, + community_id, + crate::import_session::CoveredScope::ThreadRoot(root_event_id), + decision, + ) + .await; + if let RouteDecision::Replica(mut tx, entry, reason) = decision { match crate::thread::get_thread_replies_on( &mut tx, community_id, @@ -1076,12 +1084,20 @@ impl Db { } else { "channel_head" }; - match self + let decision = self .route_read( path, RoutePredicate::from_channel_cursor(channel_id, &cursor), crate::observability::ReaderOperation::SubscriptionHistory, ) + .await; + match self + .guard_covered_route( + path, + community_id, + crate::import_session::CoveredScope::Channel(channel_id), + decision, + ) .await { RouteDecision::Replica(mut tx, _entry, reason) => { diff --git a/crates/buzz-db/src/store/thread_window.rs b/crates/buzz-db/src/store/thread_window.rs index 926ffae8df0..7ca19ef11c7 100644 --- a/crates/buzz-db/src/store/thread_window.rs +++ b/crates/buzz-db/src/store/thread_window.rs @@ -217,14 +217,22 @@ impl Db { } else { "thread_window_head" }; - if let RouteDecision::Replica(mut tx, _, reason) = self + let decision = self .route_read( path, RoutePredicate::from_channel_cursor(request.channel, &cursor), crate::observability::ReaderOperation::SubscriptionHistory, ) - .await - { + .await; + let decision = self + .guard_covered_route( + path, + community, + crate::import_session::CoveredScope::Channel(request.channel), + decision, + ) + .await; + if let RouteDecision::Replica(mut tx, _, reason) = decision { let result = async { set_deadline(&mut tx).await?; select_window(&mut tx, community, request, budget).await diff --git a/docs/database.md b/docs/database.md index 0a3c9b58e70..c348aa34eb7 100644 --- a/docs/database.md +++ b/docs/database.md @@ -236,6 +236,23 @@ write-blocking lock. Scans that do not block writes, such as floor guard lets it through (`migrations/0021`). Its PR MUST document a reviewed procedure that keeps replica routing closed from before the first batch until its WAL has replayed on every replica. +- NIP-CI conversation imports are the one in-band writer of old channel rows. + `Db::insert_import_event` blanks `buzz.created_at_floor` for its own + transaction only (`set_config(.., true)`), so the pool connection is armed + again after COMMIT or ROLLBACK and every other write on it stays guarded. + This is safe without holding the fence closed for two reasons. First, a + covered read whose snapshot shows an active import session for its channel + (until `expires_at` plus the accept delay) is routed to the writer by + `Db::guard_covered_route`. Second, imports commit only from the session's + `accepts_after`, which is activation plus `replica_fence::PROOF_MAX_AGE` + plus a margin; a reader session never proves an entry older than + `PROOF_MAX_AGE`, so any replica snapshot trusted while imports can exist + already contains the activation and the guard sees it. This holds only if + the activation commits within the margin (15 s) of the clock read that + fixed `activated_at`, so a transaction that can activate a session sets + `SET LOCAL lock_timeout` and `statement_timeout` to 10 s, below the + margin, so no single lock wait or statement can use it up. No other code path + may blank the floor; a new one needs the same review. - A script MUST NOT disable triggers or set `session_replication_role`. - The normal write path that maintains the new invariant MUST be fully rolled out, with old writers drained, before the backfill starts. The backfill spec diff --git a/migrations/0081_conversation_import_sessions.sql b/migrations/0081_conversation_import_sessions.sql index 6d2cf7c82b5..e7481f90a14 100644 --- a/migrations/0081_conversation_import_sessions.sql +++ b/migrations/0081_conversation_import_sessions.sql @@ -3,6 +3,15 @@ SET LOCAL statement_timeout = '30s'; -- NIP-CI conversation import sessions. One row per accepted kind:42110 -- proposal; status is the relay-derived session state. +-- +-- Replica-fence floor (migration 0021): imported events keep their original +-- created_at, so the relay blanks buzz.created_at_floor for each import +-- transaction only (set_config(.., true)). 0021 is checksum-frozen, so the +-- exception is recorded here. It stays sound because imports commit only +-- under an active session and only from accepts_after (activated_at plus the +-- replica proof age cap plus a margin), and a covered replica read whose +-- snapshot shows an active, unexpired session for its channel is served by +-- the writer. See replica_fence.rs and docs/database.md. CREATE TABLE import_sessions ( community_id UUID NOT NULL, proposal_id BYTEA NOT NULL, @@ -17,6 +26,8 @@ CREATE TABLE import_sessions ( requires_admin BOOLEAN NOT NULL, admin_consent TEXT, status TEXT NOT NULL, + activated_at BIGINT, + accepts_after BIGINT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (community_id, proposal_id) diff --git a/schema/tables/public/import_sessions.sql b/schema/tables/public/import_sessions.sql index 84c6343c860..56a8803fed5 100644 --- a/schema/tables/public/import_sessions.sql +++ b/schema/tables/public/import_sessions.sql @@ -13,6 +13,8 @@ CREATE TABLE import_sessions ( requires_admin BOOLEAN NOT NULL, admin_consent TEXT, status TEXT NOT NULL, + activated_at BIGINT, + accepts_after BIGINT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (community_id, proposal_id) From 6cbaf015eb6e973c6dcaf840682d05dfc89a7a29 Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:43:36 -0600 Subject: [PATCH 4/5] feat(relay): accept consented conversation imports with original timestamps Routes NIP-CI control events to the session store, skips the drift check only for well-formed imported events that pass every session rule, charges imports to a new ImportEvents budget (BUZZ_RATE_LIMIT_IMPORT_EVENTS_PER_MIN, default 600), caps session lifetime with BUZZ_IMPORT_SESSION_MAX_DAYS (default 30), caps unended sessions with BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL (default 2) and BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER (default 8), and keeps imported events away from workflows and agent subscriptions. Import-tagged events are hidden from agent readers on REQ history, NIP-50 search and every HTTP /query mode, using the same agent predicate as live fan-out. Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- .env.example | 17 + crates/buzz-acp/src/filter.rs | 35 ++ crates/buzz-acp/src/pool.rs | 78 +++ crates/buzz-auth/src/rate_limit.rs | 12 + crates/buzz-relay/src/api/bridge.rs | 67 ++- crates/buzz-relay/src/config.rs | 73 +++ .../src/handlers/conversation_import.rs | 366 ++++++++++++ .../conversation_import_postgres_tests.rs | 287 ++++++++++ crates/buzz-relay/src/handlers/event.rs | 126 ++++- crates/buzz-relay/src/handlers/ingest.rs | 348 +++++++++++- crates/buzz-relay/src/handlers/mod.rs | 4 + .../src/handlers/put_user_postgres_tests.rs | 29 + crates/buzz-relay/src/handlers/req.rs | 16 + .../handlers/system_channel_postgres_tests.rs | 19 +- crates/buzz-relay/src/nip11.rs | 20 + crates/buzz-relay/src/rejection.rs | 39 +- .../buzz-relay/src/rejection/quota_tests.rs | 36 ++ .../tests/e2e_conversation_import.rs | 521 ++++++++++++++++++ 18 files changed, 2074 insertions(+), 19 deletions(-) create mode 100644 crates/buzz-relay/src/handlers/conversation_import.rs create mode 100644 crates/buzz-relay/src/handlers/conversation_import_postgres_tests.rs create mode 100644 crates/buzz-test-client/tests/e2e_conversation_import.rs diff --git a/.env.example b/.env.example index 7ededb48cc6..928528e9417 100644 --- a/.env.example +++ b/.env.example @@ -177,6 +177,23 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # BUZZ_RATE_LIMIT_AGENT_STANDARD_API_CALLS_PER_MIN=600 # BUZZ_RATE_LIMIT_AGENT_ELEVATED_MESSAGES_PER_MIN=300 # BUZZ_RATE_LIMIT_AGENT_PLATFORM_MESSAGES_PER_MIN=600 +# NIP-CI imported history events per pubkey, any tier. Charged instead of the +# messages limit. +# BUZZ_RATE_LIMIT_IMPORT_EVENTS_PER_MIN=600 + +# NIP-CI: longest import session lifetime in days; a proposal's expires_at is +# capped at now plus this value. +# BUZZ_IMPORT_SESSION_MAX_DAYS=30 + +# NIP-CI: caps on the counts a proposal may declare, per participant (messages +# plus reactions) and summed over the session. +# BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT=50000 +# BUZZ_IMPORT_MAX_EVENTS_PER_SESSION=200000 + +# NIP-CI: caps on unended (proposed or active, unexpired) import sessions per +# destination channel and per proposer. +# BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL=2 +# BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER=8 # ----------------------------------------------------------------------------- # Git (NIP-34 bare repositories) diff --git a/crates/buzz-acp/src/filter.rs b/crates/buzz-acp/src/filter.rs index 43edd969dd3..361bf25e054 100644 --- a/crates/buzz-acp/src/filter.rs +++ b/crates/buzz-acp/src/filter.rs @@ -371,6 +371,11 @@ pub async fn match_event( rules: &[SubscriptionRule], agent_pubkey_hex: &str, ) -> Option { + // NIP-CI imported history is past conversation; it never triggers an agent. + if buzz_core::import::is_import_event(event) { + return None; + } + let filter_ctx = FilterContext::from_event(event, channel_id); for (index, rule) in rules.iter().enumerate() { @@ -577,6 +582,36 @@ mod tests { assert!(result); } + #[tokio::test] + async fn test_match_event_skips_imported_history() { + let agent = Keys::generate().public_key().to_hex(); + let rules = vec![make_rule( + "mentions", + ChannelScope::All("all".into()), + vec![9], + true, + None, + None, + )]; + let live = make_event_with_p_tag(9, "hello", &agent); + assert!(match_event(&live, any_channel(), &rules, &agent) + .await + .is_some()); + + let tags = [ + Tag::parse(["p", agent.as_str()]).expect("tag parse"), + Tag::parse(["import", &"ab".repeat(32)]).expect("tag parse"), + Tag::parse(["source", "test", "1"]).expect("tag parse"), + ]; + let imported = EventBuilder::new(Kind::Custom(9), "hello") + .tags(tags) + .sign_with_keys(&Keys::generate()) + .unwrap(); + assert!(match_event(&imported, any_channel(), &rules, &agent) + .await + .is_none()); + } + #[tokio::test] async fn test_match_event_first_match_wins() { let event = make_event(9, "hello"); diff --git a/crates/buzz-acp/src/pool.rs b/crates/buzz-acp/src/pool.rs index 7a7e3229e70..b380cd1d73e 100644 --- a/crates/buzz-acp/src/pool.rs +++ b/crates/buzz-acp/src/pool.rs @@ -4672,6 +4672,11 @@ fn parse_dm_response(json: serde_json::Value, limit: u32) -> Option Option { + // Imported history (NIP-CI) is consented to by its human participants + // only, so it never enters an agent prompt. + if carries_import_tag(obj) { + return None; + } let content = obj.get("content").and_then(|v| v.as_str())?; let pubkey = obj .get("pubkey") @@ -4705,6 +4710,17 @@ fn json_to_context_message(obj: &serde_json::Value) -> Option { }) } +/// Whether a query-response event carries a NIP-CI `import` tag. +fn carries_import_tag(obj: &serde_json::Value) -> bool { + obj.get("tags") + .and_then(|tags| tags.as_array()) + .is_some_and(|tags| { + tags.iter().any(|tag| { + tag.get(0).and_then(|name| name.as_str()) == Some(buzz_core::import::IMPORT_TAG) + }) + }) +} + /// Parse a Nostr query response (array of events) into thread context. /// /// Separates the root event (matching `root_event_id`) from replies, then sorts @@ -6394,6 +6410,68 @@ pub(crate) mod tests { } } + #[tokio::test] + async fn test_context_fetchers_drop_imported_history() { + let agent = Keys::generate(); + let root_id = "1111111111111111111111111111111111111111111111111111111111111111"; + let channel_id = Uuid::new_v4(); + let mut imported = thread_event( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "humanpub", + "imported history", + 2000, + ); + imported["tags"] = json!([ + ["h", channel_id.to_string()], + [ + "import", + "2222222222222222222222222222222222222222222222222222222222222222" + ], + ["source", "test", "1"] + ]); + let live = thread_event( + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "humanpub", + "live reply", + 3000, + ); + let json = json!([ + thread_event(root_id, "rootpub", "root", 1000), + imported, + live + ]); + + let thread_json = json.clone(); + let thread = fetch_thread_context_with( + channel_id, + root_id, + 10, + agent.public_key(), + move |_| std::future::ready(Ok(thread_json.clone())), + |_| std::future::ready(Ok(json!({ "count": 0 }))), + ThreadContextSessionDelta { + overfetch: false, + delivered_ids: &HashSet::new(), + }, + ) + .await + .expect("thread context"); + let dm = fetch_dm_context_with(channel_id, 10, move |_| { + std::future::ready(Ok(json.clone())) + }) + .await + .expect("dm context"); + + for ctx in [thread, dm] { + let messages = match ctx { + ConversationContext::Thread { messages, .. } + | ConversationContext::Dm { messages, .. } => messages, + }; + assert!(messages.iter().any(|m| m.content == "live reply")); + assert!(messages.iter().all(|m| m.content != "imported history")); + } + } + #[tokio::test] async fn test_fetch_thread_context_uses_exact_count_when_above_sentinel_minimum() { let agent = Keys::generate(); diff --git a/crates/buzz-auth/src/rate_limit.rs b/crates/buzz-auth/src/rate_limit.rs index 9e64627404c..a217a18c851 100644 --- a/crates/buzz-auth/src/rate_limit.rs +++ b/crates/buzz-auth/src/rate_limit.rs @@ -66,6 +66,9 @@ pub enum LimitType { WsEvents, /// Concurrent WebSocket connections from a single IP address. IpConnections, + /// NIP-CI imported history events (kinds 9 and 7 carrying an `import` + /// tag). Charged instead of `Messages`. + ImportEvents, } impl LimitType { @@ -77,6 +80,7 @@ impl LimitType { Self::GifSearches => "gif", Self::WsEvents => "ws", Self::IpConnections => "conn", + Self::ImportEvents => "import", } } } @@ -112,6 +116,10 @@ pub struct RateLimitConfig { /// Maximum messages per minute for platform-tier agent tokens. Default: 600. #[serde(default = "default_agent_plat_msg")] pub agent_platform_messages_per_min: u64, + /// Maximum NIP-CI imported events per minute for each pubkey, any tier. + /// Default: 600. + #[serde(default = "default_import_events")] + pub import_events_per_min: u64, } fn default_human_msg() -> u64 { @@ -138,6 +146,9 @@ fn default_agent_elev_msg() -> u64 { fn default_agent_plat_msg() -> u64 { 600 } +fn default_import_events() -> u64 { + 600 +} impl Default for RateLimitConfig { fn default() -> Self { @@ -150,6 +161,7 @@ impl Default for RateLimitConfig { agent_standard_api_calls_per_min: default_agent_std_api(), agent_elevated_messages_per_min: default_agent_elev_msg(), agent_platform_messages_per_min: default_agent_plat_msg(), + import_events_per_min: default_import_events(), } } } diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 10c88e3697c..e56596c618d 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -128,6 +128,41 @@ pub(crate) async fn enforce_http_admission( } } +/// Charge one NIP-CI imported event to the pubkey's `ImportEvents` budget. +async fn enforce_import_admission( + state: &AppState, + tenant: &TenantContext, + pubkey: &nostr::PublicKey, +) -> Result<(), (StatusCode, Json)> { + let limit = state.auth.config().rate_limits.import_events_per_min; + match crate::admission::check_principal( + state.admission_rate_limiter.as_ref(), + tenant, + pubkey, + LimitType::ImportEvents, + 60, + limit, + ) + .await + { + Ok(()) => Ok(()), + Err(crate::admission::AdmissionError::Exceeded { .. }) => { + metrics::counter!("buzz_admission_rejections_total", "transport" => "http", "reason" => "quota", "bucket" => "import_events").increment(1); + Err(api_error( + StatusCode::TOO_MANY_REQUESTS, + buzz_core::import::reason::RATE_LIMITED, + )) + } + Err(crate::admission::AdmissionError::Unavailable) => { + metrics::counter!("buzz_admission_rejections_total", "transport" => "http", "reason" => "unavailable", "bucket" => "import_events").increment(1); + Err(api_error( + StatusCode::SERVICE_UNAVAILABLE, + "rate-limited: shared admission unavailable", + )) + } + } +} + /// Values retained from an already-verified bridge authentication event. #[derive(Debug)] pub(crate) struct VerifiedBridgeAuth { @@ -1209,6 +1244,15 @@ async fn submit_event_authed( let kind_u32 = buzz_core::kind::event_kind_u32(&event); let is_typing = kind_u32 == buzz_core::kind::KIND_TYPING_INDICATOR; + if buzz_core::import::is_import_event(&event) { + if let Err(e) = enforce_import_admission(state, tenant, &pubkey).await { + return SubmitOutcome::Err { + status: e.0, + response: e.into(), + }; + } + } + // Enforce relay membership (with NIP-OA fallback via x-auth-tag header). // Typing pulses arrive every few seconds per working agent, so their ban // check uses the same short-TTL cache as their write-restriction check. @@ -1492,7 +1536,28 @@ async fn query_events_authed( ) .await?; - Ok(query_member_events(state, tenant, body, pubkey).await?) + let Json(value) = query_member_events(state, tenant, body, pubkey).await?; + // Every /query mode funnels through here, so imported history is hidden + // from agent readers once, after the mode-specific reads. + let reader = pubkey.to_bytes(); + let mut import_gate = crate::handlers::conversation_import::ImportReadGate::new( + state, + tenant.community(), + &reader, + ); + let value = match value { + Value::Array(events) => Value::Array(import_gate.retain_json(events).await), + // Object-shaped pages carry their events in a nested `events` array. + Value::Object(mut page) => { + if let Some(Value::Array(events)) = page.get_mut("events") { + let all = std::mem::take(events); + *events = import_gate.retain_json(all).await; + } + Value::Object(page) + } + other => other, + }; + Ok(Json(value)) } /// The rest of [`query_events_authed`], once the caller is admitted as a relay member. diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index cbed06b641b..42b20bde06e 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -321,6 +321,21 @@ pub struct Config { /// Maximum media upload starts accepted from one pubkey per minute. pub media_uploads_per_minute: u32, + /// Longest lifetime of a NIP-CI import session, in days. A proposal's + /// requested `expires_at` is capped at now plus this many days. + /// `BUZZ_IMPORT_SESSION_MAX_DAYS`, default 30. + pub import_session_max_days: u32, + + /// Caps on NIP-CI proposals. + /// `BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT` (default 50000) bounds one + /// participant's messages plus reactions and + /// `BUZZ_IMPORT_MAX_EVENTS_PER_SESSION` (default 200000) bounds the sum. + /// `BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL` (default 2) and + /// `BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER` (default 8) bound the + /// unended (proposed or active, unexpired) sessions a destination channel + /// or a proposer may hold. + pub import_limits: buzz_core::import::ImportLimits, + /// Whether tamper-evident event/media audit logging is enabled. Defaults to true. /// This does not control the separate `moderation_actions` audit trail. /// Set `BUZZ_AUDIT_ENABLED=false` for deployments that do not require it. @@ -491,6 +506,10 @@ fn rate_limit_config_from_env() -> Result 0) .unwrap_or(2) .min(u32::try_from(media_max_concurrent_uploads).unwrap_or(u32::MAX)); + let import_session_max_days = u32::try_from(positive_u64_from_env( + "BUZZ_IMPORT_SESSION_MAX_DAYS", + 30, + )?) + .map_err(|_| { + ConfigError::InvalidValue("BUZZ_IMPORT_SESSION_MAX_DAYS must fit in 32 bits".into()) + })?; + let import_defaults = buzz_core::import::ImportLimits::default(); + let import_limits = buzz_core::import::ImportLimits { + max_events_per_participant: positive_u64_from_env( + "BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT", + import_defaults.max_events_per_participant, + )?, + max_events_per_session: positive_u64_from_env( + "BUZZ_IMPORT_MAX_EVENTS_PER_SESSION", + import_defaults.max_events_per_session, + )?, + max_active_sessions_per_channel: positive_u64_from_env( + "BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL", + import_defaults.max_active_sessions_per_channel, + )?, + max_active_sessions_per_proposer: positive_u64_from_env( + "BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER", + import_defaults.max_active_sessions_per_proposer, + )?, + }; let media_uploads_per_minute: u32 = std::env::var("BUZZ_MEDIA_UPLOADS_PER_MINUTE") .ok() .and_then(|v| v.parse().ok()) @@ -1471,6 +1516,8 @@ impl Config { media_max_concurrent_uploads, media_max_concurrent_uploads_per_pubkey, media_uploads_per_minute, + import_session_max_days, + import_limits, audit_enabled, ephemeral_ttl_override, git_repo_path, @@ -2599,8 +2646,20 @@ mod tests { std::env::set_var("BUZZ_RATE_LIMIT_GIF_SEARCHES_PER_MIN", "1004"); std::env::set_var("BUZZ_RATE_LIMIT_HUMAN_API_CALLS_PER_MIN", "1002"); std::env::set_var("BUZZ_RATE_LIMIT_HUMAN_WS_EVENTS_PER_SEC", "1003"); + std::env::set_var("BUZZ_RATE_LIMIT_IMPORT_EVENTS_PER_MIN", "1005"); + std::env::set_var("BUZZ_IMPORT_SESSION_MAX_DAYS", "7"); + std::env::set_var("BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT", "11"); + std::env::set_var("BUZZ_IMPORT_MAX_EVENTS_PER_SESSION", "22"); + std::env::set_var("BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL", "3"); + std::env::set_var("BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER", "4"); let config = Config::from_env().expect("config"); + std::env::remove_var("BUZZ_RATE_LIMIT_IMPORT_EVENTS_PER_MIN"); + std::env::remove_var("BUZZ_IMPORT_SESSION_MAX_DAYS"); + std::env::remove_var("BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT"); + std::env::remove_var("BUZZ_IMPORT_MAX_EVENTS_PER_SESSION"); + std::env::remove_var("BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL"); + std::env::remove_var("BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER"); std::env::remove_var("BUZZ_RATE_LIMIT_HUMAN_MESSAGES_PER_MIN"); std::env::remove_var("BUZZ_RATE_LIMIT_GIF_SEARCHES_PER_MIN"); @@ -2610,6 +2669,20 @@ mod tests { assert_eq!(config.auth.rate_limits.gif_searches_per_min, 1004); assert_eq!(config.auth.rate_limits.human_api_calls_per_min, 1002); assert_eq!(config.auth.rate_limits.human_ws_events_per_sec, 1003); + assert_eq!(config.auth.rate_limits.import_events_per_min, 1005); + assert_eq!(config.import_session_max_days, 7); + assert_eq!(config.import_limits.max_events_per_participant, 11); + assert_eq!(config.import_limits.max_events_per_session, 22); + assert_eq!(config.import_limits.max_active_sessions_per_channel, 3); + assert_eq!(config.import_limits.max_active_sessions_per_proposer, 4); + + let defaults = Config::from_env().expect("default config"); + assert_eq!(defaults.auth.rate_limits.import_events_per_min, 600); + assert_eq!(defaults.import_session_max_days, 30); + assert_eq!( + defaults.import_limits, + buzz_core::import::ImportLimits::default() + ); } #[test] diff --git a/crates/buzz-relay/src/handlers/conversation_import.rs b/crates/buzz-relay/src/handlers/conversation_import.rs new file mode 100644 index 00000000000..eeb7b770f57 --- /dev/null +++ b/crates/buzz-relay/src/handlers/conversation_import.rs @@ -0,0 +1,366 @@ +//! NIP-CI conversation import: session control events (kinds 42110 to 42113) +//! and the delivery of imported history and session snapshots. +//! +//! Control events and imported events reach this module only after ingest's +//! channel gates (token scope, membership, archived channel) have passed. + +use std::sync::Arc; + +use buzz_core::import::{ + self, reason, ImportCompleteContent, ImportConsentContent, ImportProposalContent, + ImportWithdrawContent, ADMIN_CONSENT_SOURCE_USER, IMPORT_PAYLOAD_VERSION, MANIFEST_TAG, + MAX_PROPOSAL_CONTENT_BYTES, MAX_WITHDRAW_REASON_CHARS, +}; +use buzz_core::kind::{ + KIND_IMPORT_COMPLETE, KIND_IMPORT_CONSENT, KIND_IMPORT_PROPOSAL, KIND_IMPORT_WITHDRAW, +}; +use buzz_core::{StoredEvent, TenantContext}; +use buzz_db::import_session::ImportControlOutcome; +use nostr::Event; +use uuid::Uuid; + +use super::ingest::{IngestError, IngestResult}; +use crate::state::AppState; + +/// Whether an agent-policy row marks its user as an agent: a user with an +/// `agent_owner_pubkey`. Live fan-out and every pull path share this test. +pub(crate) fn is_agent(policy: Option<&buzz_db::user::AgentChannelPolicy>) -> bool { + policy.is_some_and(|(_, owner)| owner.is_some()) +} + +/// Hides NIP-CI imported events from a reader that is an agent, on pull +/// paths (REQ, search, HTTP query and the bridge reads). The agent lookup +/// runs once, on the first imported event, and a failed lookup hides +/// imported events. +pub(crate) struct ImportReadGate<'a> { + state: &'a AppState, + community: buzz_core::CommunityId, + reader: &'a [u8], + hides: Option, +} + +impl<'a> ImportReadGate<'a> { + pub(crate) fn new( + state: &'a AppState, + community: buzz_core::CommunityId, + reader: &'a [u8], + ) -> Self { + Self { + state, + community, + reader, + hides: None, + } + } + + /// Whether `event` must be left out of this reader's results. + pub(crate) async fn hides(&mut self, event: &Event) -> bool { + self.hides_if(import::is_import_event(event)).await + } + + /// [`ImportReadGate::hides`] for an event already serialized to JSON. + pub(crate) async fn hides_json(&mut self, event: &serde_json::Value) -> bool { + let is_import = event["tags"].as_array().is_some_and(|tags| { + tags.iter().any(|tag| { + tag.get(0).and_then(serde_json::Value::as_str) == Some(import::IMPORT_TAG) + }) + }); + self.hides_if(is_import).await + } + + /// Keep the JSON events this reader may see, in order. + pub(crate) async fn retain_json( + &mut self, + events: Vec, + ) -> Vec { + let mut kept = Vec::with_capacity(events.len()); + for event in events { + if !self.hides_json(&event).await { + kept.push(event); + } + } + kept + } + + async fn hides_if(&mut self, is_import: bool) -> bool { + if !is_import { + return false; + } + if let Some(hides) = self.hides { + return hides; + } + let hides = match self + .state + .db + .get_agent_channel_policies(self.community, &[self.reader.to_vec()]) + .await + { + Ok(policies) => is_agent(policies.get(self.reader)), + Err(e) => { + tracing::warn!("import read gate: agent lookup failed: {e}"); + true + } + }; + self.hides = Some(hides); + hides + } +} + +fn malformed(detail: &str) -> IngestError { + IngestError::Rejected(format!("{}{detail}", reason::MALFORMED_PREFIX)) +} + +/// Client-facing reason for a failed import session write. +const STORAGE_FAILED: &str = "error: import session storage failed"; + +/// Client-facing reason for a failed import session read. +const READ_FAILED: &str = "error: import session read failed"; + +/// Map a failed import session write to a fixed client reason; the database +/// detail goes to the log only. +pub(crate) fn storage_failed(e: buzz_db::DbError) -> IngestError { + tracing::warn!(error = %e, "import session write failed"); + IngestError::Internal(STORAGE_FAILED.into()) +} + +/// Map a failed import session read to a fixed client reason; the database +/// detail goes to the log only. +pub(crate) fn read_failed(e: buzz_db::DbError) -> IngestError { + tracing::warn!(error = %e, "import session read failed"); + IngestError::Internal(READ_FAILED.into()) +} + +/// The value of the single tag named `name`. Missing or repeated tags are +/// malformed. +fn single_tag<'a>(event: &'a Event, name: &str) -> Result<&'a str, IngestError> { + let mut values = event.tags.iter().filter_map(|tag| { + let slice = tag.as_slice(); + (slice.first().map(String::as_str) == Some(name)).then(|| slice.get(1)) + }); + match (values.next(), values.next()) { + (Some(Some(value)), None) => Ok(value.as_str()), + _ => Err(malformed(&format!("expected exactly one {name} tag"))), + } +} + +/// Proposal id bytes from the single `e` tag of a 42111 to 42113. +fn proposal_id(event: &Event) -> Result, IngestError> { + let id = single_tag(event, "e")?; + if !import::is_lower_hex_64(id) { + return Err(malformed("e tag must be a 64 lowercase hex proposal id")); + } + hex::decode(id).map_err(|_| malformed("e tag must be a 64 lowercase hex proposal id")) +} + +fn decode(event: &Event, what: &str) -> Result { + serde_json::from_str(&event.content).map_err(|_| malformed(&format!("{what} content"))) +} + +fn check_version(v: u32) -> Result<(), IngestError> { + if v == IMPORT_PAYLOAD_VERSION { + Ok(()) + } else { + Err(malformed("unsupported version")) + } +} + +/// Apply one import control event to its session in `channel_id`. +pub(crate) async fn accept_control( + tenant: &TenantContext, + state: &Arc, + event: &Event, + kind: u32, + channel_id: Uuid, +) -> Result { + let community = tenant.community(); + let keys = &state.relay_keypair; + if let Some(name) = import::first_unexpected_control_tag(event, kind) { + return Err(malformed(&format!("unexpected tag {name}"))); + } + let outcome = match kind { + KIND_IMPORT_PROPOSAL => { + if event.content.len() > MAX_PROPOSAL_CONTENT_BYTES { + return Err(malformed("proposal content exceeds 16 KiB")); + } + let content: ImportProposalContent = decode(event, "proposal")?; + let now = chrono::Utc::now().timestamp(); + import::validate_proposal_content(&content, now, state.config.import_limits) + .map_err(|rejection| IngestError::Rejected(rejection.reason()))?; + import::validate_proposal_tags(event, &content).map_err(malformed)?; + let expires_at = import::cap_expires_at( + content.expires_at, + now, + state.config.import_session_max_days, + ); + state + .db + .create_import_session( + community, + event, + &content, + channel_id, + expires_at, + state.config.import_limits, + keys, + ) + .await + .map_err(storage_failed)? + } + KIND_IMPORT_CONSENT => { + let proposal = proposal_id(event)?; + let manifest = single_tag(event, MANIFEST_TAG)?; + let content: ImportConsentContent = decode(event, "consent")?; + check_version(content.v)?; + if content.source_user != ADMIN_CONSENT_SOURCE_USER + && !import::is_lower_hex_64(&content.source_user) + { + return Err(malformed("source_user must be 64 lowercase hex or admin")); + } + state + .db + .record_import_consent( + community, + event, + &proposal, + channel_id, + manifest, + content.decision, + &content.source_user, + keys, + ) + .await + .map_err(storage_failed)? + } + KIND_IMPORT_WITHDRAW => { + let proposal = proposal_id(event)?; + if !event.content.is_empty() { + let content: ImportWithdrawContent = decode(event, "withdraw")?; + check_version(content.v)?; + if content + .reason + .as_deref() + .is_some_and(|r| r.chars().count() > MAX_WITHDRAW_REASON_CHARS) + { + return Err(malformed("withdraw reason exceeds 200 characters")); + } + } + state + .db + .withdraw_import_session(community, event, &proposal, channel_id, keys) + .await + .map_err(storage_failed)? + } + KIND_IMPORT_COMPLETE => { + let proposal = proposal_id(event)?; + let content: ImportCompleteContent = decode(event, "complete")?; + check_version(content.v)?; + state + .db + .complete_import_participant(community, event, &proposal, channel_id, keys) + .await + .map_err(storage_failed)? + } + _ => return Err(IngestError::Rejected(reason::KIND_NOT_ALLOWED.into())), + }; + + let event_id = event.id.to_hex(); + match outcome { + ImportControlOutcome::Rejected(reason) => Err(IngestError::Rejected(reason.into())), + ImportControlOutcome::RejectedAfterTransition { reason, snapshot } => { + publish_snapshot(tenant, state, &snapshot).await; + Err(IngestError::Rejected(reason.into())) + } + ImportControlOutcome::Duplicate => Ok(IngestResult { + event_id, + accepted: true, + message: "duplicate:".into(), + }), + ImportControlOutcome::Applied { + stored_event, + snapshot, + } => { + let pubkey_hex = event.pubkey.to_hex(); + super::event::dispatch_persistent_event( + tenant, + state, + &stored_event, + kind, + &pubkey_hex, + None, + ) + .await; + publish_snapshot(tenant, state, &snapshot).await; + Ok(IngestResult { + event_id, + accepted: true, + message: String::new(), + }) + } + } +} + +/// Deliver a relay-signed kind:30623 snapshot to live channel subscribers. +/// +/// The snapshot is stored with the session's channel, so reads and fan-out +/// apply the channel's own access gate. Like other relay-maintained state it +/// carries no audit or workflow side effects. +pub(crate) async fn publish_snapshot( + tenant: &TenantContext, + state: &Arc, + snapshot: &StoredEvent, +) { + let Some(channel) = snapshot.channel_id else { + return; + }; + super::artifact_sync::publish_reliably( + state, + tenant, + buzz_pubsub::EventTopic::Channel(channel), + snapshot, + ) + .await; + super::event::fan_out_event_to_local_subscribers(state, tenant.community(), snapshot).await; +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + fn event_with_tags(tags: Vec>) -> Event { + let tags = tags + .into_iter() + .map(|t| Tag::parse(t).expect("tag")) + .collect::>(); + EventBuilder::new(Kind::Custom(42111), "") + .tags(tags) + .sign_with_keys(&Keys::generate()) + .expect("sign") + } + + #[test] + fn proposal_id_requires_one_lowercase_hex_e_tag() { + let id = "ab".repeat(32); + assert_eq!( + proposal_id(&event_with_tags(vec![vec!["e", &id]])).ok(), + Some(hex::decode(&id).expect("hex")) + ); + for tags in [ + vec![], + vec![vec!["e", &id], vec!["e", &id]], + vec![vec!["e", "AB"]], + ] { + assert!(proposal_id(&event_with_tags(tags)).is_err()); + } + let upper = id.to_uppercase(); + assert!(proposal_id(&event_with_tags(vec![vec!["e", &upper]])).is_err()); + } + + #[test] + fn malformed_reasons_carry_the_import_prefix() { + let IngestError::Rejected(message) = malformed("detail") else { + panic!("expected a rejection"); + }; + assert_eq!(message, "invalid: import event malformed: detail"); + } +} diff --git a/crates/buzz-relay/src/handlers/conversation_import_postgres_tests.rs b/crates/buzz-relay/src/handlers/conversation_import_postgres_tests.rs new file mode 100644 index 00000000000..6be6c732d75 --- /dev/null +++ b/crates/buzz-relay/src/handlers/conversation_import_postgres_tests.rs @@ -0,0 +1,287 @@ +//! Postgres-backed tests for NIP-CI control events through the ingest gates. + +use buzz_core::import::{ + ImportParticipant, ImportProposalContent, ImportRange, ImportSource, ImportSourceKind, +}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use uuid::Uuid; + +use crate::handlers::group_state_postgres_tests::{community, create_channel, http_auth, state}; +use crate::handlers::ingest::{ingest_event, IngestError}; + +const MANIFEST: &str = "1111111111111111111111111111111111111111111111111111111111111111"; + +fn sign(keys: &Keys, kind: u16, content: &str, tags: Vec>) -> Event { + EventBuilder::new(Kind::Custom(kind), content) + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .allow_self_tagging() + .sign_with_keys(keys) + .unwrap() +} + +fn proposal(proposer: &Keys, channel: Uuid, participants: &[(&Keys, &str)]) -> Event { + let now = chrono::Utc::now().timestamp(); + let mut participants: Vec = participants + .iter() + .map(|(keys, source_user)| ImportParticipant { + pubkey: keys.public_key().to_hex(), + source_user: (*source_user).to_string(), + messages: 1, + reactions: 0, + }) + .collect(); + participants.sort_by(|a, b| a.pubkey.cmp(&b.pubkey)); + let mut tags = vec![vec!["h".to_string(), channel.to_string()]]; + tags.extend( + participants + .iter() + .map(|p| vec!["p".to_string(), p.pubkey.clone()]), + ); + tags.push(vec!["manifest".into(), MANIFEST.into()]); + tags.push(vec!["import-source".into(), "test".into()]); + let content = ImportProposalContent { + v: 1, + source: ImportSource { + source_type: "test".into(), + conversation: "2".repeat(64), + kind: ImportSourceKind::PrivateChannel, + label: "Channel".into(), + }, + range: ImportRange { + from: now - 10_000, + to: now - 100, + }, + participants, + excluded_authors: 0, + manifest: MANIFEST.into(), + expires_at: now + 3_600, + }; + sign( + proposer, + 42110, + &serde_json::to_string(&content).unwrap(), + tags, + ) +} + +fn session_tags(proposal: &Event, channel: Uuid) -> Vec> { + vec![ + vec!["e".into(), proposal.id.to_hex()], + vec!["h".into(), channel.to_string()], + ] +} + +fn rejection(result: Result) -> String { + match result { + Err(IngestError::Rejected(reason)) => reason, + Err(other) => panic!("expected a rejection, got {other:?}"), + Ok(result) => panic!("expected a rejection, got OK {}", result.message), + } +} + +/// A participant who has left the channel can still send kind:42113, while +/// other control events keep the membership gate and the session store +/// still requires a participant. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_participant_who_left_can_still_complete() { + let state = state().await; + let tenant = community(&state, "import-complete").await; + let (owner, alice, stranger) = (Keys::generate(), Keys::generate(), Keys::generate()); + let channel = create_channel(&state, &tenant, &owner, &[&["visibility", "private"]]).await; + let put = sign( + &owner, + 9000, + "", + vec![ + vec!["h".into(), channel.to_string()], + vec!["p".into(), alice.public_key().to_hex()], + ], + ); + ingest_event(&state, &tenant, put, http_auth(&owner)) + .await + .expect("add alice"); + + let alice_user = "3".repeat(64); + let proposal = proposal( + &owner, + channel, + &[(&owner, &"4".repeat(64)), (&alice, &alice_user)], + ); + ingest_event(&state, &tenant, proposal.clone(), http_auth(&owner)) + .await + .expect("proposal"); + + let consent_content = + serde_json::json!({"v": 1, "decision": "accept", "source_user": alice_user}).to_string(); + let consent_tags = |p: &Keys| { + let mut tags = session_tags(&proposal, channel); + tags.push(vec!["manifest".into(), MANIFEST.into()]); + tags.push(vec!["p".into(), p.public_key().to_hex()]); + tags + }; + let wrong_p = sign(&alice, 42111, &consent_content, consent_tags(&alice)); + assert_eq!( + rejection(ingest_event(&state, &tenant, wrong_p, http_auth(&alice)).await), + "invalid: import consent does not match proposal" + ); + let consent = sign(&alice, 42111, &consent_content, consent_tags(&owner)); + ingest_event(&state, &tenant, consent, http_auth(&alice)) + .await + .expect("consent"); + + let leave = sign( + &alice, + 9022, + "", + vec![vec!["h".into(), channel.to_string()]], + ); + ingest_event(&state, &tenant, leave, http_auth(&alice)) + .await + .expect("leave"); + + let done = r#"{"v":1,"published":{"messages":0,"reactions":0}}"#; + let stranger_done = sign(&stranger, 42113, done, session_tags(&proposal, channel)); + assert_eq!( + rejection(ingest_event(&state, &tenant, stranger_done, http_auth(&stranger)).await), + "restricted: import author not a participant" + ); + let withdraw = sign(&alice, 42112, "", session_tags(&proposal, channel)); + assert_eq!( + rejection(ingest_event(&state, &tenant, withdraw, http_auth(&alice)).await), + "restricted: not a channel member" + ); + let complete = sign(&alice, 42113, done, session_tags(&proposal, channel)); + let result = ingest_event(&state, &tenant, complete, http_auth(&alice)) + .await + .expect("a participant who left completes"); + assert!(result.accepted, "{}", result.message); +} + +/// Imported history is invisible to agent readers on pull paths as well as +/// live fan-out: REQ, NIP-50 search and HTTP /query return it to humans only. +/// Mutation: drop the gate from the REQ history loop, the search loop or the +/// /query post-filter and this fails. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn imported_history_is_hidden_from_agent_readers() { + use super::system_channel_postgres_tests as reads; + use serde_json::json; + + let f = reads::fixture().await; + let (owner, alice, bot) = (Keys::generate(), Keys::generate(), Keys::generate()); + let channel = create_channel(&f.state, &f.tenant, &owner, &[]).await; + for member in [&alice, &bot] { + let put = sign( + &owner, + 9000, + "", + vec![ + vec!["h".into(), channel.to_string()], + vec!["p".into(), member.public_key().to_hex()], + ], + ); + ingest_event(&f.state, &f.tenant, put, http_auth(&owner)) + .await + .expect("add member"); + } + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect"); + sqlx::query( + "INSERT INTO users (community_id, pubkey) VALUES ($1, $2) \ + ON CONFLICT (community_id, pubkey) DO NOTHING", + ) + .bind(f.tenant.community().as_uuid()) + .bind(owner.public_key().to_bytes().as_slice()) + .execute(&pool) + .await + .expect("owner user row"); + sqlx::query( + "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) VALUES ($1, $2, $3) \ + ON CONFLICT (community_id, pubkey) DO UPDATE \ + SET agent_owner_pubkey = EXCLUDED.agent_owner_pubkey", + ) + .bind(f.tenant.community().as_uuid()) + .bind(bot.public_key().to_bytes().as_slice()) + .bind(owner.public_key().to_bytes().as_slice()) + .execute(&pool) + .await + .expect("make agent"); + + let alice_user = "3".repeat(64); + let proposal = proposal( + &owner, + channel, + &[(&owner, &"4".repeat(64)), (&alice, &alice_user)], + ); + ingest_event(&f.state, &f.tenant, proposal.clone(), http_auth(&owner)) + .await + .expect("proposal"); + let mut consent_tags = session_tags(&proposal, channel); + consent_tags.push(vec!["manifest".into(), MANIFEST.into()]); + consent_tags.push(vec!["p".into(), owner.public_key().to_hex()]); + let consent = sign( + &alice, + 42111, + &json!({"v": 1, "decision": "accept", "source_user": alice_user}).to_string(), + consent_tags, + ); + ingest_event(&f.state, &f.tenant, consent, http_auth(&alice)) + .await + .expect("consent"); + sqlx::query("UPDATE import_sessions SET accepts_after = 0 WHERE community_id = $1") + .bind(f.tenant.community().as_uuid()) + .execute(&pool) + .await + .expect("skip warm-up"); + + let word = format!("w{}", Uuid::new_v4().simple()); + let imported = EventBuilder::new(Kind::Custom(9), format!("imported {word}")) + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["import", &proposal.id.to_hex()]).unwrap(), + Tag::parse(["source", "test", "ref-1"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from( + (chrono::Utc::now().timestamp() - 5_000) as u64, + )) + .sign_with_keys(&alice) + .unwrap(); + let result = ingest_event(&f.state, &f.tenant, imported.clone(), http_auth(&alice)) + .await + .expect("imported message"); + assert!(result.accepted, "{}", result.message); + let live = sign( + &alice, + 9, + &format!("live {word}"), + vec![vec!["h".into(), channel.to_string()]], + ); + ingest_event(&f.state, &f.tenant, live.clone(), http_auth(&alice)) + .await + .expect("live message"); + + let (imported_id, live_id) = (imported.id.to_hex(), live.id.to_hex()); + let history = json!({"kinds": [9], "#h": [channel.to_string()]}); + let search = json!({"kinds": [9], "search": word}); + for (who, reader, sees_import) in [("human", &owner, true), ("agent", &bot, false)] { + for (path, ids) in [ + ("REQ", reads::req(&f, reader, history.clone()).await), + ("search", reads::req(&f, reader, search.clone()).await), + ( + "/query", + reads::bridge_ids( + reads::bridge(&f, reader, "/query", json!([history.clone()])).await, + ), + ), + ] { + assert!(ids.contains(&live_id), "{who} {path}: live missing {ids:?}"); + assert_eq!( + ids.contains(&imported_id), + sees_import, + "{who} {path}: imported visibility {ids:?}" + ); + } + } +} diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 76ffc21f7f3..9d63114227b 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -133,6 +133,43 @@ struct FanoutAccess { unverified: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, } +/// Drop matches whose connection is authenticated as an agent (a user with an +/// `agent_owner_pubkey`). A failed lookup drops every match. +async fn exclude_agent_connections( + state: &AppState, + community_id: CommunityId, + matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, +) -> Vec<(crate::subscription::ConnId, crate::subscription::SubId)> { + let with_pubkeys: Vec<_> = matches + .into_iter() + .filter_map(|(conn_id, sub_id)| { + state + .conn_manager + .pubkey_for_conn(conn_id) + .map(|pk| (conn_id, sub_id, pk)) + }) + .collect(); + let mut pubkeys: Vec> = with_pubkeys.iter().map(|(_, _, pk)| pk.clone()).collect(); + pubkeys.sort(); + pubkeys.dedup(); + let policies = match state + .db + .get_agent_channel_policies(community_id, &pubkeys) + .await + { + Ok(policies) => policies, + Err(e) => { + warn!("fan-out import gate: agent lookup failed: {e}"); + return Vec::new(); + } + }; + with_pubkeys + .into_iter() + .filter(|(_, _, pk)| !super::conversation_import::is_agent(policies.get(pk))) + .map(|(conn_id, sub_id, _)| (conn_id, sub_id)) + .collect() +} + /// `filter_fanout_by_access`, also reporting the recipients it dropped /// only because a lookup failed. async fn check_fanout_access( @@ -226,6 +263,16 @@ async fn check_fanout_access( matches }; + // NIP-CI imported history is consented to by human participants only, so + // it never streams to an agent connection. Fails closed: if the agent + // lookup errors, no connection receives the event live; history reads + // still serve it to members. + let matches = if buzz_core::import::is_import_event(&stored_event.event) { + exclude_agent_connections(state, community_id, matches).await + } else { + matches + }; + let Some(channel_id) = stored_event.channel_id else { return verified(matches); }; @@ -567,6 +614,7 @@ async fn dispatch_persistent_event_inner( && !buzz_core::kind::is_command_kind(kind_u32) && !is_relay_workflow_msg && kind_u32 != KIND_GIFT_WRAP + && !buzz_core::import::is_import_event(&stored_event.event) { let workflow_engine = Arc::clone(&state.workflow_engine); let workflow_event = stored_event.clone(); @@ -3105,6 +3153,18 @@ mod tests { } fn register_conn(state: &AppState, pubkey: Option>) -> Uuid { + register_conn_in( + state, + pubkey, + buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), + ) + } + + fn register_conn_in( + state: &AppState, + pubkey: Option>, + community_id: buzz_core::tenant::CommunityId, + ) -> Uuid { let conn_id = Uuid::new_v4(); let (tx, _rx) = mpsc::channel(1); let (ctrl_tx, _ctrl_rx) = mpsc::channel(1); @@ -3115,7 +3175,7 @@ mod tests { tokio::sync::mpsc::channel(1).0, None, CancellationToken::new(), - buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), + community_id, Arc::new(AtomicU8::new(0)), Arc::new(Mutex::new(HashMap::new())), 3, @@ -3210,6 +3270,70 @@ mod tests { assert_eq!(out, matches); } + /// Imported history streams to human connections only; a live event + /// in the same channel still reaches the agent. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn imported_events_skip_agent_connections() { + let state = test_state().await; + let pool = sqlx::PgPool::connect(&test_config().database_url) + .await + .expect("connect"); + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("{community}.import-fanout.test")) + .execute(&pool) + .await + .expect("community"); + let (human, agent) = (vec![1u8; 32], vec![2u8; 32]); + for (pubkey, owner) in [(&human, None), (&agent, Some(&human))] { + sqlx::query( + "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) \ + VALUES ($1, $2, $3)", + ) + .bind(community) + .bind(pubkey) + .bind(owner) + .execute(&pool) + .await + .expect("user"); + } + let community_id = buzz_core::tenant::CommunityId::from_uuid(community); + let channel_id = Uuid::new_v4(); + state + .channel_visibility_cache + .insert((community_id, channel_id), "open".to_string()); + let human_conn = register_conn_in(&state, Some(human), community_id); + let agent_conn = register_conn_in(&state, Some(agent), community_id); + let matches = vec![(human_conn, "s".to_string()), (agent_conn, "s".to_string())]; + let imported = EventBuilder::new(Kind::Custom(9), "old") + .tags([ + nostr::Tag::parse(["import", &"ab".repeat(32)]).expect("import"), + nostr::Tag::parse(["source", "test", "1"]).expect("source"), + ]) + .sign_with_keys(&Keys::generate()) + .expect("sign"); + let out = filter_fanout_by_access( + &state, + community_id, + &StoredEvent::new(imported, Some(channel_id)), + matches.clone(), + None, + ) + .await; + assert_eq!(out, vec![(human_conn, "s".to_string())]); + let live = filter_fanout_by_access( + &state, + community_id, + &channel_event(Some(channel_id)), + matches.clone(), + None, + ) + .await; + assert_eq!(live, matches); + } + #[tokio::test] async fn private_channel_keeps_member_drops_non_member_and_unknown() { let state = test_state().await; diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 9cae758646e..38c7d2a3f85 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -546,6 +546,8 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result Ok(Scope::UsersWrite), KIND_TEXT_NOTE | KIND_LONG_FORM | buzz_core::kind::KIND_ARTIFACT => Ok(Scope::MessagesWrite), + // NIP-CI session control events are member writes into the channel. + k if buzz_core::kind::is_import_control_kind(k) => Ok(Scope::MessagesWrite), KIND_CONTACT_LIST | KIND_READ_STATE | KIND_USER_STATUS | KIND_AGENT_ENGRAM | KIND_EVENT_REMINDER | KIND_PERSONA | KIND_TEAM | KIND_MANAGED_AGENT | KIND_PRIVATE_MANAGED_AGENT | KIND_TEAM_CATALOG | super::push_lease::KIND_PUSH_LEASE => { @@ -852,6 +854,11 @@ pub(crate) fn requires_h_channel_scope(kind: u32) -> bool { | KIND_HUDDLE_PARTICIPANT_LEFT | KIND_HUDDLE_ENDED | KIND_HUDDLE_GUIDELINES + // NIP-CI session control events + | buzz_core::kind::KIND_IMPORT_PROPOSAL + | buzz_core::kind::KIND_IMPORT_CONSENT + | buzz_core::kind::KIND_IMPORT_WITHDRAW + | buzz_core::kind::KIND_IMPORT_COMPLETE ) } @@ -2424,6 +2431,164 @@ pub(crate) async fn enforce_cached_write_restriction( write_restriction_denial(kind, &restriction, Utc::now()).map_or(Ok(()), Err) } +/// NIP-CI rules 2 to 6 against a read of the session. The event's `h` must +/// name the channel the gates above resolved (for a reaction, the target's +/// channel) and the session's channel. +async fn check_import_preflight( + tenant: &TenantContext, + state: &Arc, + event: &Event, + tags: &buzz_core::import::ImportTags, + channel_id: Option, +) -> Result<(), IngestError> { + use buzz_core::import::reason; + let reject = |reason: &str| IngestError::Rejected(reason.into()); + let h_channel = extract_channel_id(event); + let Some(ch_id) = channel_id.filter(|ch| h_channel == Some(*ch)) else { + return Err(reject(reason::CHANNEL_MISMATCH)); + }; + let preflight = state + .db + .import_preflight(tenant.community(), &tags.proposal_bytes, event) + .await + .map_err(super::conversation_import::read_failed)? + .ok_or_else(|| reject(reason::PROPOSAL_NOT_FOUND))?; + if preflight.channel_id != ch_id { + return Err(reject(reason::CHANNEL_MISMATCH)); + } + if tags.source_type != preflight.source_type { + return Err(reject(reason::SOURCE_TYPE_MISMATCH)); + } + if preflight.already_stored { + return Ok(()); + } + buzz_core::import::evaluate_import_rules( + preflight.status, + preflight.range, + preflight.author.as_ref(), + u32::from(event.kind.as_u16()), + event.created_at.as_secs() as i64, + chrono::Utc::now().timestamp(), + ) + .map_err(reject) +} + +/// The ±15 minute drift check, and NIP-CI rule 1. A well-formed imported +/// kind:9 or kind:7 skips the drift check and its parsed tags are returned; +/// rules 2 to 7 then decide it before and inside its storage transaction, so +/// a backdated event is stored only when every rule holds. +fn check_timestamp_drift( + event: &Event, + now: i64, +) -> Result, IngestError> { + const MAX_TIMESTAMP_DRIFT_SECS: i64 = 900; + let import_tags = buzz_core::import::parse_import_tags(event) + .map_err(|reason| IngestError::Rejected(reason.into()))?; + let event_ts = event.created_at.as_secs() as i64; + if import_tags.is_none() && (event_ts - now).abs() > MAX_TIMESTAMP_DRIFT_SECS { + return Err(IngestError::Rejected( + "invalid: event timestamp too far from server time".into(), + )); + } + Ok(import_tags) +} + +/// Store one imported kind:9 or kind:7 under its session and deliver it. +/// +/// Delivery is live fan-out, audit and search only: the import store skips +/// mention rows, the listener outbox, push and unread evidence, and +/// [`dispatch_persistent_event`] skips workflow triggers for import events. +#[allow(clippy::too_many_arguments)] +async fn store_import_event( + tenant: &TenantContext, + state: &Arc, + tracer: &Arc, + event: &Event, + tags: &buzz_core::import::ImportTags, + channel_id: Uuid, + thread_params: Option>, + reaction: Option>, + auth: &IngestAuth, + threaded_visibility: Option, +) -> Result { + use buzz_db::import_session::ImportInsertOutcome; + let event_id_hex = event.id.to_hex(); + let kind_u32 = u32::from(event.kind.as_u16()); + let outcome = state + .db + .insert_import_event( + tenant.community(), + event, + tags, + channel_id, + thread_params, + reaction, + &state.relay_keypair, + ) + .await + .map_err(super::conversation_import::storage_failed)?; + let (stored_event, snapshot) = match outcome { + ImportInsertOutcome::Rejected { reason, snapshot } => { + if let Some(snapshot) = snapshot { + super::conversation_import::publish_snapshot(tenant, state, &snapshot).await; + } + return Err(IngestError::Rejected(reason.into())); + } + ImportInsertOutcome::TargetMissing => { + return Err(IngestError::Rejected(format!( + "invalid: {REACTION_TARGET_NOT_FOUND}" + ))); + } + ImportInsertOutcome::Duplicate => { + emit( + tracer, + TraceAction::WriteDuplicate { + msg_id: msg_id_label(event.id.as_bytes()), + channel: channel_label(channel_id), + claimed_community: claimed_community_from_event(event), + }, + state_for_request(tenant, auth.pubkey()), + ); + return Ok(IngestResult { + event_id: event_id_hex, + accepted: true, + message: "duplicate:".into(), + }); + } + ImportInsertOutcome::Inserted { + stored_event, + snapshot, + } => (stored_event, snapshot), + }; + emit( + tracer, + TraceAction::WriteInsert { + msg_id: msg_id_label(event.id.as_bytes()), + channel: channel_label(channel_id), + claimed_community: claimed_community_from_event(event), + }, + state_for_request(tenant, auth.pubkey()), + ); + dispatch_persistent_event( + tenant, + state, + &stored_event, + kind_u32, + &auth.pubkey().to_hex(), + threaded_visibility, + ) + .await; + if let Some(snapshot) = snapshot { + super::conversation_import::publish_snapshot(tenant, state, &snapshot).await; + } + info!(event_id = %event_id_hex, kind = kind_u32, "Imported event ingested"); + Ok(IngestResult { + event_id: event_id_hex, + accepted: true, + message: String::new(), + }) +} + /// Ingest a signed Nostr event through the full validation pipeline. /// /// Shared by WebSocket and HTTP transports. The caller constructs [`IngestAuth`] @@ -2628,14 +2793,9 @@ async fn ingest_event_inner( }); } - const MAX_TIMESTAMP_DRIFT_SECS: i64 = 900; // ±15 minutes let now = chrono::Utc::now().timestamp(); let event_ts = event.created_at.as_secs() as i64; - if (event_ts - now).abs() > MAX_TIMESTAMP_DRIFT_SECS { - return Err(IngestError::Rejected( - "invalid: event timestamp too far from server time".into(), - )); - } + let import_tags = check_timestamp_drift(&event, now)?; // kind:40100 canvas events carry a tighter future ceiling — see // `validate_canvas_future_timestamp` for the rationale and invariant. @@ -2893,7 +3053,11 @@ async fn ingest_event_inner( // member/open gate here lets the owning human act on private agent channels // without being a member (OQ1 decision; see validate_edit_ownership / // validate_admin_event for per-kind enforcement). + // kind:42113 (import complete): the session store admits only an + // accepting participant of the active session, member or not, so a + // participant who has left can still let the session finish. let skip_membership = kind_u32 == KIND_NIP29_JOIN_REQUEST + || kind_u32 == buzz_core::kind::KIND_IMPORT_COMPLETE || kind_u32 == KIND_NIP29_CREATE_GROUP || kind_u32 == KIND_STREAM_MESSAGE_EDIT || kind_u32 == KIND_NIP29_EDIT_METADATA @@ -3117,6 +3281,41 @@ async fn ingest_event_inner( } } + // NIP-CI control events passed the channel write gates above; the session + // store decides the rest atomically. + if buzz_core::kind::is_import_control_kind(kind_u32) { + let ch_id = channel_id.ok_or_else(|| { + IngestError::Rejected("invalid: channel-scoped events must include an h tag".into()) + })?; + let result = + super::conversation_import::accept_control(tenant, state, &event, kind_u32, ch_id) + .await?; + let msg_id = msg_id_label(event.id.as_bytes()); + let channel = channel_label(ch_id); + let claimed_community = claimed_community_from_event(&event); + let action = if result.message.starts_with("duplicate:") { + TraceAction::WriteDuplicate { + msg_id, + channel, + claimed_community, + } + } else { + TraceAction::WriteInsert { + msg_id, + channel, + claimed_community, + } + }; + emit(tracer, action, state_for_request(tenant, auth.pubkey())); + return Ok(result); + } + + // NIP-CI rules 2 to 6, read before the remaining validation so a refused + // import fails fast. The storage transaction checks them again. + if let Some(tags) = &import_tags { + check_import_preflight(tenant, state, &event, tags, channel_id).await?; + } + // Artifact revisions passed the same home-channel write gates as kind 9 // above; they are stored and published without conversation side effects. if kind_u32 == buzz_core::kind::KIND_ARTIFACT { @@ -3462,6 +3661,31 @@ async fn ingest_event_inner( // the event in the same transaction. Ordering is load-bearing: active // duplicate reactions must return before storing a duplicate kind:7 event. let thread_params = thread_meta.as_ref().map(|m| m.as_params()); + if let Some(tags) = &import_tags { + let Some(ch_id) = channel_id else { + return Err(IngestError::Rejected( + buzz_core::import::reason::CHANNEL_MISMATCH.into(), + )); + }; + let reaction = buzz_db::import_session::ImportReaction { + target_event_id: &target_id, + actor_pubkey: &actor_bytes, + emoji, + }; + return store_import_event( + tenant, + state, + tracer, + &event, + tags, + ch_id, + thread_params, + Some(reaction), + &auth, + threaded_visibility, + ) + .await; + } let (stored_event, was_inserted) = match state .db .insert_reaction_event_with_thread_metadata( @@ -3547,6 +3771,37 @@ async fn ingest_event_inner( None }; + if let Some(tags) = &import_tags { + let Some(ch_id) = channel_id else { + return Err(IngestError::Rejected( + buzz_core::import::reason::CHANNEL_MISMATCH.into(), + )); + }; + let thread_params = thread_meta.as_ref().map(|m| m.as_params()); + let result = store_import_event( + tenant, + state, + tracer, + &event, + tags, + ch_id, + thread_params, + None, + &auth, + threaded_visibility, + ) + .await?; + if let Some(meta) = &thread_meta { + crate::handlers::side_effects::emit_live_thread_summary( + tenant, + state, + meta.channel_id, + meta.root_event_id.clone(), + ); + } + return Ok(result); + } + let workflow_deletion = crate::handlers::side_effects::is_workflow_deletion(&event); let mut message = String::new(); let (stored_event, was_inserted) = if let Some(create) = channel_create.as_ref() { @@ -4300,6 +4555,87 @@ mod postgres_tests { assert!(!requires_h_channel_scope(KIND_REACTION)); } + /// The drift bypass admits only a well-formed import-tagged kind:9 or + /// kind:7. Widening it to any other kind, or to an event without an + /// `import` tag, fails here. + #[test] + fn drift_bypass_is_limited_to_imported_messages_and_reactions() { + let now = 1_700_000_000; + let old = (now - 86_400) as u64; + let id = "ab".repeat(32); + let build = |kind: u16, tags: Vec>| { + EventBuilder::new(Kind::Custom(kind), "") + .tags(tags.into_iter().map(|t| nostr::Tag::parse(t).unwrap())) + .custom_created_at(nostr::Timestamp::from(old)) + .sign_with_keys(&nostr::Keys::generate()) + .unwrap() + }; + let import = |kind| { + build( + kind, + vec![ + vec!["h", "c"], + vec!["import", &id], + vec!["source", "test", "ref"], + ], + ) + }; + let reason = |result: Result<_, IngestError>| match result { + Err(IngestError::Rejected(reason)) => reason, + other => panic!( + "expected a rejection, got {:?}", + other.map(|t: Option<_>| t.is_some()) + ), + }; + + for kind in [9u16, 7] { + let tags = check_timestamp_drift(&import(kind), now) + .unwrap_or_else(|_| panic!("kind {kind} import bypasses drift")); + assert_eq!(tags.map(|t| t.proposal_id), Some(id.clone())); + } + for kind in [1u16, 40002, 45001, 42110, 30623] { + assert_eq!( + reason(check_timestamp_drift(&import(kind), now)), + buzz_core::import::reason::KIND_NOT_ALLOWED + ); + } + let too_old = "invalid: event timestamp too far from server time"; + for event in [ + build(9, vec![vec!["h", "c"]]), + build(7, vec![vec!["h", "c"], vec!["source", "test", "ref"]]), + build(9, vec![vec!["h", "c"], vec!["imported", &id]]), + ] { + assert_eq!(reason(check_timestamp_drift(&event, now)), too_old); + } + let malformed = build(9, vec![vec!["h", "c"], vec!["import", &id]]); + assert_eq!( + reason(check_timestamp_drift(&malformed, now)), + buzz_core::import::reason::TAGS_MALFORMED + ); + } + + #[test] + fn import_control_kinds_are_channel_scoped_member_writes() { + use buzz_core::kind::{ + KIND_IMPORT_COMPLETE, KIND_IMPORT_CONSENT, KIND_IMPORT_PROPOSAL, + KIND_IMPORT_SESSION_SNAPSHOT, KIND_IMPORT_WITHDRAW, + }; + let dummy = make_dummy_event(); + for kind in [ + KIND_IMPORT_PROPOSAL, + KIND_IMPORT_CONSENT, + KIND_IMPORT_WITHDRAW, + KIND_IMPORT_COMPLETE, + ] { + assert_eq!( + required_scope_for_kind(kind, &dummy).ok(), + Some(Scope::MessagesWrite) + ); + assert!(requires_h_channel_scope(kind)); + } + assert!(!requires_h_channel_scope(KIND_IMPORT_SESSION_SNAPSHOT)); + } + #[test] fn long_form_is_in_scope_allowlist() { let dummy = make_dummy_event(); diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index cb18b8525c8..c22578c23af 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -16,6 +16,10 @@ pub mod coalesced_refresh; pub mod command_executor; /// Relay-operator community provisioning HTTP support. pub mod community_provisioning; +/// NIP-CI conversation import control events and snapshot delivery. +pub mod conversation_import; +#[cfg(test)] +mod conversation_import_postgres_tests; /// NIP-45 COUNT handler. pub mod count; #[cfg(test)] diff --git a/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs b/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs index 637f7b42e64..6d3ac690d8c 100644 --- a/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs @@ -747,3 +747,32 @@ async fn put_user_refused_under_the_lock_stores_nothing() { assert!(retry.accepted, "{}", retry.message); assert_eq!(put_user_events(&state, &tenant, channel_id).await, 1); } + +/// An outsider cannot put themselves into a DM. A DM member can still add a +/// third person with kind:9000, so NIP-CI rechecks a DM's member set on every +/// imported event instead of relying on DM membership being fixed. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn put_user_self_add_is_refused_on_dm_channels() { + let state = state().await; + let tenant = community(&state, "put-user-dm").await; + let (alice, bob, carol) = (Keys::generate(), Keys::generate(), Keys::generate()); + let (dm, _) = state + .db + .open_dm( + tenant.community(), + &[&alice.public_key().to_bytes(), &bob.public_key().to_bytes()], + &alice.public_key().to_bytes(), + ) + .await + .expect("open dm"); + let carol_hex = carol.public_key().to_hex(); + let event = put_user(&carol, dm.id, &[&[&carol_hex]], &[]); + match ingest(&state, &tenant, event, &carol).await { + Err(IngestError::Rejected(message)) => { + assert_eq!(message, "restricted: not a channel member"); + } + other => panic!("expected a refusal, got {:?}", other.map(|r| r.message)), + } + assert_eq!(role_of(&state, &tenant, dm.id, &carol).await, None); +} diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index bddaa55e154..74bc49bb69e 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -425,6 +425,11 @@ pub async fn handle_req( // per-filter limits or non-overlapping time windows. let mut seen_ids: HashSet = HashSet::new(); let mut total_sent: usize = 0; + let mut import_gate = super::conversation_import::ImportReadGate::new( + &state, + conn.tenant.community(), + &pubkey_bytes, + ); // Phase 1 — pure query construction, in filter order. let filter_queries: Vec<(usize, Option, EventQuery)> = filters @@ -571,6 +576,9 @@ pub async fn handle_req( if !event_visible_to_reader(&stored.event, &pubkey_bytes) { continue; } + if import_gate.hides(&stored.event).await { + continue; + } // Dedup AFTER acceptance — an event that fails filter A's constraints // must remain eligible for filter B (NIP-01 OR semantics). @@ -794,6 +802,11 @@ async fn handle_search_req( } let mut seen_ids: HashSet = HashSet::new(); + let mut import_gate = super::conversation_import::ImportReadGate::new( + state, + tenant.community(), + reader_pubkey_bytes, + ); for filter in filters { let search_text = match &filter.search { @@ -999,6 +1012,9 @@ async fn handle_search_req( if !event_visible_to_reader(&stored.event, reader_pubkey_bytes) { continue; } + if import_gate.hides(&stored.event).await { + continue; + } // Dedup AFTER acceptance — an event that fails filter A's constraints // must remain eligible for filter B (NIP-01 OR semantics). if !seen_ids.insert(stored.event.id) { diff --git a/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs b/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs index 710fbdbe90b..1d69a8364e3 100644 --- a/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs @@ -14,13 +14,13 @@ use super::group_state_postgres_tests::{create_channel, edit_channel, http_auth, use crate::handlers::ingest::ingest_event; use crate::state::AppState; -struct Fixture { - state: Arc, - tenant: TenantContext, +pub(super) struct Fixture { + pub(super) state: Arc, + pub(super) tenant: TenantContext, host: String, } -async fn fixture() -> Fixture { +pub(super) async fn fixture() -> Fixture { let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() .await .expect("local Postgres and Redis"); @@ -78,7 +78,7 @@ async fn group_state_id(f: &Fixture, channel: Uuid, kind: i32) -> String { /// Run one historical REQ and return the event IDs sent before EOSE. A /// CLOSED reply counts as no events. -async fn req(f: &Fixture, reader: &Keys, filter: Value) -> Vec { +pub(super) async fn req(f: &Fixture, reader: &Keys, filter: Value) -> Vec { req_all(f, reader, json!([filter])).await } @@ -129,7 +129,12 @@ async fn count_all(f: &Fixture, reader: &Keys, filters: Value) -> u64 { /// POST `filters` to an HTTP bridge route as `reader`. Returns the JSON body /// of a 200, or `None` for a refusal. -async fn bridge(f: &Fixture, reader: &Keys, path: &str, filters: Value) -> Option { +pub(super) async fn bridge( + f: &Fixture, + reader: &Keys, + path: &str, + filters: Value, +) -> Option { use axum::body::Body; use axum::http::{header, Request}; use tower::ServiceExt; @@ -163,7 +168,7 @@ async fn bridge(f: &Fixture, reader: &Keys, path: &str, filters: Value) -> Optio } } -fn bridge_ids(body: Option) -> Vec { +pub(super) fn bridge_ids(body: Option) -> Vec { let Some(body) = body else { return Vec::new(); }; diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index 0f880fb5e56..4bf3526d50f 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -253,6 +253,9 @@ impl RelayInfo { // without it ignores the tag beside `visibility`, so a client // checks this before opening a channel as unlisted. "buzz-unlisted-channels".to_string(), + // NIP-CI: consented conversation import (kinds 42110 to 42113, + // relay snapshot 30623). Clients refuse to propose without it. + "nip-ci".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -706,6 +709,23 @@ mod tests { assert!(extensions.contains(&"buzz-unlisted-channels".to_string())); } + /// Clients refuse to propose a conversation import against a relay whose + /// document lacks `nip-ci`, so every document must advertise it. + #[test] + fn advertises_nip_ci_extension() { + let info = RelayInfo::build( + None, + None, + RelayCapabilityFlags::default(), + DEFAULT_MAX_FRAME_BYTES, + None, + None, + None, + ); + let extensions = info.supported_extensions.expect("extensions"); + assert!(extensions.contains(&"nip-ci".to_string())); + } + /// NIP-WP → NIP-11 mirror: a set workspace icon is served in the standard /// `icon` field; no icon (or a cleared, empty icon) omits the field /// entirely so the JSON matches pre-icon documents byte-for-byte. diff --git a/crates/buzz-relay/src/rejection.rs b/crates/buzz-relay/src/rejection.rs index 8af208d2d80..74fdc046bd0 100644 --- a/crates/buzz-relay/src/rejection.rs +++ b/crates/buzz-relay/src/rejection.rs @@ -88,6 +88,25 @@ pub(crate) async fn enforce_ws_admission( return false; } + // NIP-CI imported history is charged to its own budget, never `Messages`. + if let ClientMessage::Event(event) = msg { + if buzz_core::import::is_import_event(event) { + let result = crate::admission::check_principal( + state.admission_rate_limiter.as_ref(), + &conn.tenant, + &pubkey, + LimitType::ImportEvents, + 60, + limits.import_events_per_min, + ) + .await; + return send_admission_verdict(conn, state, result, msg, "import_events", |_| { + buzz_core::import::reason::RATE_LIMITED.to_owned() + }) + .await; + } + } + if matches!(msg, ClientMessage::Event(event) if !buzz_core::kind::is_ephemeral(event.kind.as_u16() as u32)) { let message_limit = if is_agent { @@ -127,13 +146,25 @@ async fn send_admission_result( result: Result<(), AdmissionError>, msg: &ClientMessage, bucket: &'static str, +) -> bool { + send_admission_verdict(conn, state, result, msg, bucket, |reset_in_secs| { + format!("rate-limited: quota exceeded; retry in {reset_in_secs}s") + }) + .await +} + +/// [`send_admission_result`] with a caller-chosen quota-exceeded reason. +async fn send_admission_verdict( + conn: &ConnectionState, + state: &AppState, + result: Result<(), AdmissionError>, + msg: &ClientMessage, + bucket: &'static str, + exceeded: impl FnOnce(u64) -> String, ) -> bool { let (reason, label) = match result { Ok(()) => return true, - Err(AdmissionError::Exceeded { reset_in_secs }) => ( - format!("rate-limited: quota exceeded; retry in {reset_in_secs}s"), - "quota", - ), + Err(AdmissionError::Exceeded { reset_in_secs }) => (exceeded(reset_in_secs), "quota"), Err(AdmissionError::Unavailable) => ( "rate-limited: shared admission unavailable".to_owned(), "unavailable", diff --git a/crates/buzz-relay/src/rejection/quota_tests.rs b/crates/buzz-relay/src/rejection/quota_tests.rs index 9f546469e2f..bd6711e38bd 100644 --- a/crates/buzz-relay/src/rejection/quota_tests.rs +++ b/crates/buzz-relay/src/rejection/quota_tests.rs @@ -248,3 +248,39 @@ async fn ephemeral_and_http_admission_still_fail_closed_when_redis_is_unavailabl ); assert_metric(&recorder, "http", "unavailable", "api_calls", 1); } + +#[tokio::test] +#[ignore = "requires explicit isolated BUZZ_TEST_REDIS_URL"] +async fn import_events_use_their_own_budget() { + let mut state = state_with_limits(1, 1, 100).await; + let mut auth = state.auth.config().clone(); + auth.rate_limits.import_events_per_min = 2; + state.auth = Arc::new(AuthService::new(auth)); + let (conn, mut rx) = connection(false); + let imported = || { + let tags = [ + nostr::Tag::parse(["import", &"ab".repeat(32)]).unwrap(), + nostr::Tag::parse(["source", "test", "1"]).unwrap(), + ]; + let event = EventBuilder::new(Kind::from(9), "") + .tags(tags) + .sign_with_keys(&Keys::generate()) + .unwrap(); + ClientMessage::parse(&serde_json::json!(["EVENT", event]).to_string()).unwrap() + }; + for expected in 1..=2 { + assert!(enforce_ws_admission(&imported(), &conn, &state).await); + assert_eq!( + counter(&state, &conn, LimitType::ImportEvents).await, + Some(expected) + ); + } + assert_eq!(counter(&state, &conn, LimitType::Messages).await, None); + let rejected = imported(); + assert!(!enforce_ws_admission(&rejected, &conn, &state).await); + let frame = read_frame(&mut rx); + assert_eq!(frame[2], false); + assert_eq!(frame[3], "rate-limited: import"); + // The ordinary message budget is still intact. + assert!(enforce_ws_admission(&event(9), &conn, &state).await); +} diff --git a/crates/buzz-test-client/tests/e2e_conversation_import.rs b/crates/buzz-test-client/tests/e2e_conversation_import.rs new file mode 100644 index 00000000000..a683756f014 --- /dev/null +++ b/crates/buzz-test-client/tests/e2e_conversation_import.rs @@ -0,0 +1,521 @@ +//! End-to-end tests for NIP-CI conversation import. +//! +//! These tests require a running relay and are `#[ignore]`d by default. +//! +//! ```text +//! cargo test -p buzz-test-client --test e2e_conversation_import -- --ignored +//! ``` +//! +//! Override the relay URL with `RELAY_URL`. All identifiers, hashes and +//! source references are synthetic. + +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use serde_json::{json, Value}; + +const SOURCE_TYPE: &str = "test"; + +fn relay_http_url() -> String { + std::env::var("RELAY_URL") + .unwrap_or_else(|_| "ws://localhost:3000".to_string()) + .replace("wss://", "https://") + .replace("ws://", "http://") + .trim_end_matches('/') + .to_string() +} + +fn now() -> u64 { + Timestamp::now().as_secs() +} + +fn hex64(byte: u8) -> String { + hex::encode([byte; 32]) +} + +fn sign(keys: &Keys, kind: u16, content: &str, tags: Vec>, created_at: u64) -> Event { + let tags = tags + .into_iter() + .map(|t| Tag::parse(t).expect("tag")) + .collect::>(); + // A proposal's `p` tags list every participant, the proposer included; + // the builder drops a self `p` tag unless told otherwise. + EventBuilder::new(Kind::Custom(kind), content) + .tags(tags) + .allow_self_tagging() + .custom_created_at(Timestamp::from(created_at)) + .sign_with_keys(keys) + .expect("sign") +} + +/// Submit an event over HTTP; returns `(accepted, message)`. A rejection is +/// `(false, )`. +async fn submit(keys: &Keys, event: &Event) -> (bool, String) { + let resp = reqwest::Client::new() + .post(format!("{}/events", relay_http_url())) + .header("X-Pubkey", keys.public_key().to_hex()) + .header("Content-Type", "application/json") + .body(serde_json::to_string(event).expect("event json")) + .send() + .await + .expect("submit event"); + let ok = resp.status().is_success(); + let body: Value = resp.json().await.expect("response json"); + if ok { + ( + body["accepted"].as_bool().unwrap_or(false), + body["message"].as_str().unwrap_or_default().to_string(), + ) + } else { + ( + false, + body["error"].as_str().unwrap_or_default().to_string(), + ) + } +} + +async fn accept(keys: &Keys, event: &Event) { + let (accepted, message) = submit(keys, event).await; + assert!( + accepted, + "kind:{} not accepted: {message}", + event.kind.as_u16() + ); +} + +async fn refused(keys: &Keys, event: &Event, reason: &str) { + let (accepted, message) = submit(keys, event).await; + assert!( + !accepted, + "kind:{} unexpectedly accepted", + event.kind.as_u16() + ); + assert_eq!(message, reason); +} + +async fn query(keys: &Keys, filter: Value) -> Vec { + let resp = reqwest::Client::new() + .post(format!("{}/query", relay_http_url())) + .header("X-Pubkey", keys.public_key().to_hex()) + .header("Content-Type", "application/json") + .body(json!([filter]).to_string()) + .send() + .await + .expect("query"); + assert!( + resp.status().is_success(), + "query failed: {}", + resp.status() + ); + resp.json::() + .await + .expect("query json") + .as_array() + .cloned() + .unwrap_or_default() +} + +/// Open a DM between `a` and `b` and return its channel id. +async fn create_dm(a: &Keys, b: &Keys) -> String { + let b_hex = b.public_key().to_hex(); + let event = sign(a, 41010, "", vec![vec!["p", &b_hex]], now() - 10); + let (accepted, message) = submit(a, &event).await; + assert!(accepted, "DM open not accepted: {message}"); + let payload = message.strip_prefix("response:").expect("response: prefix"); + let parsed: Value = serde_json::from_str(payload).expect("response JSON"); + parsed["channel_id"] + .as_str() + .expect("channel_id") + .to_string() +} + +struct Participant<'a> { + keys: &'a Keys, + source_user: String, + messages: u64, + reactions: u64, +} + +fn proposal(proposer: &Keys, channel: &str, participants: &[Participant<'_>]) -> Event { + let at = now(); + let mut pubkeys: Vec = participants + .iter() + .map(|p| p.keys.public_key().to_hex()) + .collect(); + pubkeys.sort(); + let manifest = hex64(0xab); + let content = json!({ + "v": 1, + "source": { + "type": SOURCE_TYPE, + "conversation": hex64(0xcd), + "kind": "dm", + "label": "Direct message", + }, + "range": { "from": at - 86_400, "to": at - 60 }, + "participants": participants.iter().map(|p| json!({ + "pubkey": p.keys.public_key().to_hex(), + "source_user": p.source_user, + "messages": p.messages, + "reactions": p.reactions, + })).collect::>(), + "excluded_authors": 0, + "manifest": manifest, + "expires_at": at + 3_600, + }) + .to_string(); + let mut tags = vec![vec!["h", channel]]; + tags.extend(pubkeys.iter().map(|p| vec!["p", p.as_str()])); + tags.push(vec!["manifest", &manifest]); + tags.push(vec!["import-source", SOURCE_TYPE]); + sign(proposer, 42110, &content, tags, at) +} + +fn consent( + keys: &Keys, + proposal: &Event, + channel: &str, + decision: &str, + source_user: &str, +) -> Event { + let proposal_id = proposal.id.to_hex(); + let proposer = proposal.pubkey.to_hex(); + let manifest = hex64(0xab); + let content = json!({ "v": 1, "decision": decision, "source_user": source_user }).to_string(); + sign( + keys, + 42111, + &content, + vec![ + vec!["e", &proposal_id], + vec!["h", channel], + vec!["manifest", &manifest], + vec!["p", &proposer], + ], + now(), + ) +} + +/// An imported kind:9 with tags in the canonical NIP-CI order. +fn imported_message( + keys: &Keys, + proposal: &Event, + channel: &str, + mentions: &[&Keys], + source_ref: &str, + created_at: u64, +) -> Event { + let proposal_id = proposal.id.to_hex(); + let mut mention_hex: Vec = mentions.iter().map(|k| k.public_key().to_hex()).collect(); + mention_hex.sort(); + let mut tags = vec![vec!["h", channel]]; + tags.extend(mention_hex.iter().map(|p| vec!["p", p.as_str()])); + tags.push(vec!["import", &proposal_id]); + tags.push(vec!["source", SOURCE_TYPE, source_ref]); + sign(keys, 9, &format!("imported {source_ref}"), tags, created_at) +} + +fn imported_reaction(keys: &Keys, proposal: &Event, channel: &str, target: &Event) -> Event { + let proposal_id = proposal.id.to_hex(); + let target_id = target.id.to_hex(); + sign( + keys, + 7, + "+", + vec![ + vec!["h", channel], + vec!["e", &target_id], + vec!["import", &proposal_id], + vec!["source", SOURCE_TYPE, "reaction-target"], + ], + target.created_at.as_secs() + 1, + ) +} + +async fn snapshot_event(keys: &Keys, proposal: &Event) -> Value { + let events = query( + keys, + json!({ "kinds": [30623], "#d": [proposal.id.to_hex()], "limit": 5 }), + ) + .await; + events + .into_iter() + .max_by_key(|e| e["created_at"].as_u64().unwrap_or(0)) + .expect("snapshot exists") +} + +async fn snapshot(keys: &Keys, proposal: &Event) -> Value { + let newest = snapshot_event(keys, proposal).await; + serde_json::from_str(newest["content"].as_str().expect("content")).expect("snapshot json") +} + +/// The snapshot's `accepts_after` tag, if present. +async fn accepts_after(keys: &Keys, proposal: &Event) -> Option { + let newest = snapshot_event(keys, proposal).await; + newest["tags"] + .as_array() + .expect("tags") + .iter() + .find(|t| t[0] == "accepts_after") + .map(|t| t[1].as_str().expect("value").parse().expect("unix seconds")) +} + +async fn mention_feed_ids(keys: &Keys) -> Vec { + query( + keys, + json!({ "#p": [keys.public_key().to_hex()], "feed_types": ["mentions"], "limit": 50 }), + ) + .await + .into_iter() + .filter_map(|e| e["id"].as_str().map(str::to_string)) + .collect() +} + +#[tokio::test] +#[ignore = "requires a running relay"] +async fn dm_import_session_end_to_end() { + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = create_dm(&alice, &bob).await; + let at = now(); + let (alice_user, bob_user) = (hex64(0x11), hex64(0x22)); + let proposal = proposal( + &alice, + &dm, + &[ + Participant { + keys: &alice, + source_user: alice_user, + messages: 2, + reactions: 0, + }, + Participant { + keys: &bob, + source_user: bob_user.clone(), + messages: 1, + reactions: 1, + }, + ], + ); + accept(&alice, &proposal).await; + assert_eq!(snapshot(&alice, &proposal).await["status"], "proposed"); + assert_eq!(accepts_after(&alice, &proposal).await, None); + assert!( + mention_feed_ids(&bob).await.contains(&proposal.id.to_hex()), + "waiting proposal missing from the participant's mentions feed" + ); + + // Before Bob consents nothing backdated is accepted. + let first = imported_message(&alice, &proposal, &dm, &[], "m1", at - 7_200); + refused(&alice, &first, "invalid: import session not active").await; + + accept(&bob, &consent(&bob, &proposal, &dm, "accept", &bob_user)).await; + assert_eq!(snapshot(&alice, &proposal).await["status"], "active"); + + // Imports wait for the snapshot's accepts_after; an early one is + // refused with a retryable reason and leaves no row behind. + let opens_at = accepts_after(&alice, &proposal) + .await + .expect("an active snapshot carries accepts_after"); + assert!(opens_at > now(), "accepts_after {opens_at} is not ahead"); + refused(&alice, &first, "invalid: import session warming").await; + // One extra second absorbs relay and test clocks rounding differently. + let wait = (opens_at + 1).saturating_sub(now()); + tokio::time::sleep(std::time::Duration::from_secs(wait)).await; + + // A message hours in the past is accepted under the active session. + accept(&alice, &first).await; + // Resending it is a duplicate, not a second count. + let (accepted, message) = submit(&alice, &first).await; + assert!(accepted && message.starts_with("duplicate"), "{message}"); + + let outside = imported_message(&alice, &proposal, &dm, &[], "m0", at - 200_000); + refused( + &alice, + &outside, + "invalid: import timestamp outside declared range", + ) + .await; + + // Bob's imported message mentions Alice; it must not reach her mentions. + let mention = imported_message(&bob, &proposal, &dm, &[&alice], "m2", at - 7_000); + accept(&bob, &mention).await; + // The source type is bound to the session. + let other_source = sign( + &bob, + 9, + "other source", + vec![ + vec!["h", &dm], + vec!["import", &proposal.id.to_hex()], + vec!["source", "other", "m9"], + ], + at - 6_950, + ); + refused( + &bob, + &other_source, + "invalid: import source type does not match the session", + ) + .await; + let over = imported_message(&bob, &proposal, &dm, &[], "m3", at - 6_900); + refused(&bob, &over, "invalid: import count exceeded").await; + + // A live mention does reach the feed, so the feed check below is live. + let live = sign( + &bob, + 9, + "live mention", + vec![vec!["h", &dm], vec!["p", &alice.public_key().to_hex()]], + now(), + ); + accept(&bob, &live).await; + let feed = mention_feed_ids(&alice).await; + assert!( + feed.contains(&live.id.to_hex()), + "live mention missing from feed" + ); + assert!( + !feed.contains(&mention.id.to_hex()), + "imported mention reached the feed" + ); + + // Reactions must target imported events of the same proposal. + let (live_id, proposal_hex) = (live.id.to_hex(), proposal.id.to_hex()); + let on_live = sign( + &bob, + 7, + "+", + vec![ + vec!["h", &dm], + vec!["e", &live_id], + vec!["import", &proposal_hex], + vec!["source", SOURCE_TYPE, "live"], + ], + at - 6_000, + ); + refused( + &bob, + &on_live, + "invalid: import reaction target not imported", + ) + .await; + accept(&bob, &imported_reaction(&bob, &proposal, &dm, &first)).await; + + // The imported message keeps its original timestamp. + let stored = query(&alice, json!({ "ids": [first.id.to_hex()], "kinds": [9] })).await; + assert_eq!(stored[0]["created_at"].as_u64(), Some(at - 7_200)); + + let snap = snapshot(&alice, &proposal).await; + let (a, b) = (alice.public_key().to_hex(), bob.public_key().to_hex()); + assert_eq!(snap["status"], "active"); + assert_eq!(accepts_after(&alice, &proposal).await, Some(opens_at)); + assert_eq!(snap["consents"][&a], "accept"); + assert_eq!(snap["consents"][&b], "accept"); + let mut required = vec![a.clone(), b.clone()]; + required.sort(); + assert_eq!(snap["required"], json!(required)); + + // Someone outside the DM reads neither the snapshot nor the history. + let stranger = Keys::generate(); + assert!( + query( + &stranger, + json!({ "kinds": [30623], "#d": [proposal.id.to_hex()], "limit": 5 }) + ) + .await + .is_empty(), + "a non-member read the snapshot" + ); + assert!( + query( + &stranger, + json!({ "ids": [first.id.to_hex()], "kinds": [9] }) + ) + .await + .is_empty(), + "a non-member read imported history" + ); + + // Control records carry only their spec tags. + let proposal_id = proposal.id.to_hex(); + let extra = sign( + &alice, + 42112, + r#"{"v":1}"#, + vec![vec!["e", &proposal_id], vec!["h", &dm], vec!["ms", "1"]], + now(), + ); + refused( + &alice, + &extra, + "invalid: import event malformed: unexpected tag ms", + ) + .await; + + // Withdraw ends the session; nothing further is accepted. + let withdraw = sign( + &alice, + 42112, + r#"{"v":1}"#, + vec![vec!["e", &proposal_id], vec!["h", &dm]], + now(), + ); + accept(&alice, &withdraw).await; + // Counters ride on control-event snapshots (and every 50 imports), so + // the withdraw snapshot carries the totals. + let snap = snapshot(&alice, &proposal).await; + assert_eq!(snap["status"], "withdrawn"); + assert_eq!( + snap["published"][&a], + json!({ "messages": 1, "reactions": 0 }) + ); + assert_eq!( + snap["published"][&b], + json!({ "messages": 1, "reactions": 1 }) + ); + let late = imported_message(&alice, &proposal, &dm, &[], "m4", at - 5_000); + refused(&alice, &late, "invalid: import session not active").await; +} + +#[tokio::test] +#[ignore = "requires a running relay"] +async fn dm_proposal_participants_must_equal_members() { + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = create_dm(&alice, &bob).await; + let only_alice = proposal( + &alice, + &dm, + &[Participant { + keys: &alice, + source_user: hex64(0x11), + messages: 1, + reactions: 0, + }], + ); + refused( + &alice, + &only_alice, + "invalid: import participants must equal the DM members", + ) + .await; +} + +#[tokio::test] +#[ignore = "requires a running relay"] +async fn import_tags_without_a_session_are_refused() { + let (alice, bob) = (Keys::generate(), Keys::generate()); + let dm = create_dm(&alice, &bob).await; + let missing = sign(&alice, 42110, "{}", vec![vec!["h", &dm]], now()); + let orphan = imported_message(&alice, &missing, &dm, &[], "m1", now() - 3_600); + refused(&alice, &orphan, "invalid: import proposal not found").await; + + let wrong_kind = sign( + &alice, + 1, + "note", + vec![ + vec!["import", &hex64(0x01)], + vec!["source", SOURCE_TYPE, "x"], + ], + now(), + ); + refused(&alice, &wrong_kind, "invalid: import kind not allowed").await; +} From db27b0b08d562b859771435bb29c567bdf618faa Mon Sep 17 00:00:00 2001 From: jaykurian <49807026+jaykurian@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:43:42 -0600 Subject: [PATCH 5/5] docs(nips): add NIP-CI conversation import Signed-off-by: jaykurian <49807026+jaykurian@users.noreply.github.com> --- ARCHITECTURE.md | 2 + NOSTR.md | 2 + README.md | 2 +- docs/nips/NIP-CI.md | 270 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 275 insertions(+), 1 deletion(-) create mode 100644 docs/nips/NIP-CI.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 23961d940c4..6478a22df8a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -182,8 +182,10 @@ The `kind` integer is the only dispatch switch. The relay routes, stores, and fa |------|------|-------------| | 7 | KIND_REACTION | Emoji reaction (standard NIP-25) | | 9 | KIND_STREAM_MESSAGE | Chat message in a Stream channel (NIP-29 group chat) | +| 30623 | KIND_IMPORT_SESSION_SNAPSHOT | Relay-signed import session state (NIP-CI) | | 40002 | KIND_STREAM_MESSAGE_V2 | Stream message v2 format | | 40003 | KIND_STREAM_MESSAGE_EDIT | Edit of a stream message | +| 42110 to 42113 | KIND_IMPORT_* | Conversation import proposal, consent, withdraw and complete (NIP-CI) | | 43001 | KIND_JOB_REQUEST | Agent job request | | 45001 | KIND_FORUM_POST | Forum thread root | | 45003 | KIND_FORUM_COMMENT | Forum thread reply | diff --git a/NOSTR.md b/NOSTR.md index b3d628786f4..967fa6af84b 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -73,6 +73,7 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **NIP-17 DMs (gift wrap)** | ✅ | kind:1059 accepted with ephemeral signing keys. Stored community-globally (`channel_id=None` inside the connected community). Delivered via `#p`-filtered subscriptions. Not indexed in search. | | **DM discovery** | ✅ | DM creation emits kind:39000 (with `hidden` tag) + kind:44100 membership notifications. NIP-29 clients discover DMs via standard group discovery flow. | | **Join request (kind:9021)** | ✅ | Open channels only. Adds the joiner with the channel's `join_role` (`member` by default), emits system message + group discovery events + kind:44100 membership notification. Private channels rejected at ingest. The same body joins new community members to [default channels](#default-channels). | +| **Conversation import (kinds 42110 to 42113, 30623)** | ✅ | [NIP-CI](docs/nips/NIP-CI.md). Each participant signs their own history as kind:9 and kind:7 with `import` and `source` tags; the relay accepts original timestamps only inside a session every participant consented to. Relay-signed kind:30623 snapshot (`d` = proposal id) carries status, consents and counts and is readable like the channel's messages. Imported events never notify, mention, mark unread, push or trigger workflows and agents. | | **Edits (kind:40003)** | ⚠️ | Works on the wire but Buzz-only — no standard NIP-29 client renders these | | **Rich content (kind:40002)** | ⚠️ | Works on the wire but Buzz-only — no standard NIP-29 client renders these | @@ -577,6 +578,7 @@ but only admins/owners can set it. Full spec: - **kind:7 derives channel from target.** Reactions look up the target event's channel via `#e` — client-supplied `#h` tags are ignored. Reactions to unknown events are rejected (fail-closed). - **kind:5 uses `#h` if present, but doesn't require it.** Deletions validate author-match against target events via `#e` tags. Only self-authored events can be deleted (admin deletions use kind:9005). - **Client-submitted kind:44100/44101 rejected.** Membership notifications can only be signed by the relay keypair. +- **Backdated kind:9 and kind:7 need a consented import session.** An `import` tag skips the timestamp drift check only when every [NIP-CI](docs/nips/NIP-CI.md) rule holds; client-submitted kind:30623 is rejected. --- diff --git a/README.md b/README.md index bdf218e57db..cd7aadafa55 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ Agents are part of the room, not haunted cron jobs. | Relay, channels, threads, DMs, canvases, media, search, audit log | Mobile clients (iOS + Android, Flutter) | Web-of-trust reputation across relays | | Desktop app (Tauri + React) | Workflow approval gates (infra exists, glue still drying) | Push notifications | | `buzz-cli` (agent-first, JSON in / JSON out) + ACP harness (Goose, Codex, Claude Code) | Huddle lifecycle events | Culture features | -| YAML workflows: message / reaction / schedule / webhook triggers | | | +| YAML workflows: message / reaction / schedule / webhook triggers | Consented conversation import with original timestamps (relay side, NIP-CI) | | | Git events (NIP-34: patches, repo announcements, status) | | | | Git hosting backend | | | diff --git a/docs/nips/NIP-CI.md b/docs/nips/NIP-CI.md new file mode 100644 index 00000000000..5028a6074ea --- /dev/null +++ b/docs/nips/NIP-CI.md @@ -0,0 +1,270 @@ +NIP-CI +====== + +Conversation Import +------------------- + +`draft` `optional` `relay` + +**Depends on**: NIP-01 (basic event format), NIP-10 (threads), NIP-11 (relay information document), NIP-25 (reactions), NIP-29 (relay-based groups) + +## Abstract + +This NIP lets the people in a conversation on another platform bring its history into a Buzz channel or DM, with the original timestamps, under explicit consent from every participant. Each participant signs and publishes their own past messages and reactions as ordinary `kind:9` and `kind:7` events carrying an `import` tag. The relay accepts those backdated events only inside a consented, time-bounded import session, and tracks the session in a relay-signed snapshot. + +The protocol has four user-signed control kinds and one relay-signed snapshot kind: + +- `kind:42110` Import Proposal, `kind:42111` Import Consent, `kind:42112` Import Withdraw, `kind:42113` Import Complete; +- `kind:30623` Import Session Snapshot (relay-signed, parameterized replaceable). + +No new content kinds are defined. Imported history uses the existing `kind:9` message and `kind:7` reaction kinds. + +## Motivation + +Moving a team to Buzz strands its history elsewhere. A relay-side bulk import would let one party publish words under other people's keys, and would need the relay to trust an external export. Neither fits Buzz: every event is signed by its author. + +NIP-CI keeps authorship intact. Each participant signs only their own messages, so an imported message carries the same proof of authorship as a live one. The relay's job is narrow: it relaxes its timestamp drift check for a bounded set of events, and only while everyone involved has agreed to the exact corpus being imported. + +## Non-Goals + +This NIP does not define how a client reads the source platform, maps source users to Buzz pubkeys, or computes the manifest. Those are client concerns; the manifest hash only lets every participant confirm they consented to the same corpus. + +This NIP does not import edits or deletions as history. A message is imported with its final text; a later delete of an imported message is a normal `kind:5` or `kind:9005` at the current time. + +This NIP does not let anyone publish on another participant's behalf. A participant who never consents is never imported, and their messages are not published by anyone else. + +This NIP does not change processing of events without an `import` tag. An active session changes nothing for normal traffic in its channel. + +## Terminology + +This document uses MUST, MUST NOT, SHOULD, SHOULD NOT, MAY, and RECOMMENDED as defined in RFC 2119. + +- **relay identity**: The relay signing pubkey advertised in its NIP-11 `self` field. +- **proposal**: A `kind:42110` event. Its event id is the **proposal id**, which names the session everywhere else. +- **participant**: A pubkey listed in the proposal. The proposer is normally a participant. +- **session**: The relay's state for one proposal: status, consents, declared and published counts. +- **imported event**: A `kind:9` or `kind:7` carrying an `import` tag. +- **admin consent**: A `kind:42111` whose `source_user` is the literal string `"admin"`, signed by a current owner or admin of the channel. + +## Kinds + +| Kind | Name | Signer | Storage | Purpose | +|------|------|--------|---------|---------| +| `42110` | Import Proposal | proposer | regular, channel `h` | Declares source, range, participants, counts and manifest hash | +| `42111` | Import Consent | participant or channel admin | regular, channel `h` | Accept or decline, bound to the proposal id and manifest hash | +| `42112` | Import Withdraw | proposer or participant | regular, channel `h` | Ends the session | +| `42113` | Import Complete | participant | regular, channel `h` | The participant finished publishing | +| `30623` | Import Session Snapshot | relay | parameterized replaceable, `d` = proposal id | Authoritative session state | + +`kind:30623` is relay-only: the relay rejects it from clients. + +## Event Formats + +### `kind:42110` Import Proposal + +```jsonc +{ + "kind": 42110, + "tags": [ + ["h", ""], + ["p", ""], // one per participant, sorted ascending + ["manifest", ""], + ["import-source", ""] + ], + "content": "{\"v\":1,\"source\":{...},\"range\":{...},\"participants\":[...],\"excluded_authors\":0,\"manifest\":\"...\",\"expires_at\":0}" +} +``` + +Content, with keys in this order: + +```jsonc +{ + "v": 1, + "source": { + "type": "", // [a-z0-9_-]{1,32}, for example "chat-export" + "conversation": "", + "kind": "dm" | "group_dm" | "private_channel" | "public_channel", + "label": "" + }, + "range": { "from": , "to": }, + "participants": [ + { "pubkey": "", "source_user": "", "messages": , "reactions": } + ], + "excluded_authors": , + "manifest": "", + "expires_at": +} +``` + +The relay rejects unknown keys. The content is at most 16 KiB. The `p` tags MUST equal the participant pubkeys sorted ascending, the single `manifest` tag MUST equal `content.manifest`, and the single `import-source` tag MUST equal `source.type`. + +### `kind:42111` Import Consent + +Tags: `["e", ""]`, `["h", ""]`, `["manifest", ""]`, `["p", ""]`. + +Content: `{"v":1,"decision":"accept"|"decline","source_user":""}`. A participant's `source_user` MUST equal their entry in the proposal. Admin consent uses `"source_user":"admin"`. + +### `kind:42112` Import Withdraw + +Tags: `["e", ""]`, `["h", ""]`. Content is empty or `{"v":1,"reason":""}`. + +### `kind:42113` Import Complete + +Tags: `["e", ""]`, `["h", ""]`. Content: `{"v":1,"published":{"messages":,"reactions":}}`. The counts are informational; the relay's own counters are authoritative. + +### Imported `kind:9` and `kind:7` + +An imported message carries, in this order: `h`, the NIP-10 `e` root and reply tags when it is a reply, one `p` per mentioned participant (sorted ascending), `["import", ""]`, `["source", "", ""]`, then optional `["source-edited", "1"]`, `["source-flag", "broadcast"]` and attachment tags. `created_at` is the source timestamp in whole seconds. + +An imported reaction carries, in this order: `h`, `["e", ""]`, `["import", ""]` and `["source", "", ""]`, with no `p` tag. Its target MUST itself be an imported event of the same proposal. + +Clients compute every imported event deterministically (fixed tag order and content normalization), so a participant can reference a partner's message id before the partner publishes it. + +### `kind:30623` Import Session Snapshot + +```jsonc +{ + "kind": 30623, + "pubkey": "", + "tags": [ + ["d", ""], + ["e", ""], + ["h", ""], + ["p", ""], // one per participant, sorted ascending + ["accepts_after", ""] // present once status is active + ], + "content": "{\"v\":1,\"status\":\"active\",\"required\":[...],\"consents\":{...},\"published\":{...},\"completed\":[...],\"expires_at\":0}" +} +``` + +Content: + +```jsonc +{ + "v": 1, + "status": "proposed" | "active" | "declined" | "withdrawn" | "expired" | "completed", + "required": ["", ..., "admin"], // "admin" only when admin consent is required + "consents": { "": "accept" | "decline", "admin": "accept" | "decline" }, + "published": { "": { "messages": , "reactions": } }, + "completed": ["", ...], + "expires_at": +} +``` + +`created_at` strictly increases across republications of one session, so the newest snapshot always replaces the previous one. + +Once the status is `active`, the snapshot carries `["accepts_after", ""]`: the earliest time the relay accepts imported events for the session. The relay computes it once, at activation, as the activation time plus its read-replica retention plus a margin (in this implementation, 60 seconds of ring retention plus a 15 second margin, 75 seconds in total), stores it, and repeats the same value in every later snapshot. It stays on terminal snapshots of a session that was active. + +## Relay Processing Algorithm + +### Control events + +Control events pass the normal channel write gates (token scope, membership, posting role, archived channel), except that `kind:42113` skips the membership gate so a participant who has left the channel can still finish. Each control event carries exactly the tags listed for its kind; any other tag is rejected with `invalid: import event malformed: unexpected tag `. Then: + +1. **Proposal.** The relay validates the content and tags above, requires `946684800 <= range.from < range.to <= now` (the range starts no earlier than 2000-01-01), 1 to 64 distinct participants, and caps `expires_at` at now plus `BUZZ_IMPORT_SESSION_MAX_DAYS` (default 30). The proposer and every participant MUST be active members of the channel, otherwise `restricted: import proposer not an active channel member` or `invalid: import participant not an active channel member`. In a DM the participant set MUST equal the DM member set. Admin consent is required when the channel is not a DM, has at least one owner or admin, and the proposer is neither. The proposer's consent is recorded as accept. Declared counts are capped per participant (`BUZZ_IMPORT_MAX_EVENTS_PER_PARTICIPANT`, default 50000, messages plus reactions) and per session (`BUZZ_IMPORT_MAX_EVENTS_PER_SESSION`, default 200000), rejected with `invalid: import counts exceed the relay limit`. Unended sessions (status `proposed` or `active` and not past `expires_at`) are capped per channel (`BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_CHANNEL`, default 2), rejected with `restricted: too many active import sessions in this channel`, and per proposer within the community (`BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER`, default 8), rejected with `restricted: too many active import sessions for this proposer`. Both caps are checked under per-channel and per-proposer locks, so concurrent proposals cannot exceed them. Imported history never reaches agents (see [Agents](#agents)): a participant that is an agent is rejected with `restricted: import participants cannot include agents`, and a DM or private channel with an agent member with `restricted: import destination has agent members`. +2. **Consent.** The `manifest` tag MUST equal the proposal's manifest and the single `p` tag MUST name the proposer, otherwise `invalid: import consent does not match proposal`. An admin consent MUST come from a current owner or admin. Otherwise the author MUST be a participant whose `source_user` matches. An author who is neither is rejected with `restricted: import author not a participant`. A later consent replaces the earlier one. Consents are refused once the session is terminal. +3. **Withdraw.** The author MUST be the proposer or a participant, otherwise `restricted: import author not a participant`. The session becomes `withdrawn`. +4. **Complete.** The author MUST be an accepting participant of an active session. An author who is not a participant is rejected with `restricted: import author not a participant`. + +The control event, the session change and a fresh snapshot commit in one transaction. A resend of a stored control event is answered `duplicate:` before the session caps and any lazy status change. A failed session write is answered `error: import session storage failed` and a failed session read `error: import session read failed`; both are retryable and carry no storage detail. Control events are live activity and create mention rows for their `p` tags like other channel events. A proposal (kind 42110) also appears in the mentions feed of each participant it tags; the other control kinds do not. + +### Session status + +Terminal statuses (`declined`, `withdrawn`, `expired`, `completed`) never change. A non-terminal session past `expires_at` becomes `expired`, detected lazily on the next write that touches the session. A required admin decline makes the session `declined` before activation and `withdrawn` after it. Any participant decline makes a DM session `declined`, and makes a channel session `declined` before activation. The session becomes `active` once every participant and any required admin have accepted. After activation, a channel participant who declines stops being accepted; the session becomes `withdrawn` when no accepting participant remains and `completed` when every accepting participant has sent `kind:42113`. + +### Imported events + +For any event carrying an `import` tag, every rule MUST hold, otherwise the relay rejects it with the listed reason: + +| Rule | Check | Rejection | +|------|-------|-----------| +| 1 | Kind is 9 or 7 | `invalid: import kind not allowed` | +| 1 | Exactly one well-formed `import` tag and one well-formed `source` tag | `invalid: import tags malformed` | +| 2 | The proposal exists in this community | `invalid: import proposal not found` | +| 2 | The event's `h`, the resolved channel and the session channel agree | `invalid: import channel mismatch` | +| 2 | `source[1]` equals the proposal's `source.type` | `invalid: import source type does not match the session` | +| 2 | A DM's members still equal the participants | `invalid: import participants must equal the DM members` | +| 2 | A DM or private destination still has no agent member | `restricted: import destination has agent members` | +| 3 | The session is `active` and the author has not completed | `invalid: import session not active` | +| 3 | The current time is at or after the session's `accepts_after` | `invalid: import session warming` | +| 4 | The author is a participant whose consent is accept | `invalid: import author not a consenting participant` | +| 4 | The author is not an agent | `restricted: import participants cannot include agents` | +| 5 | `range.from <= created_at <= range.to` and `created_at <= now + 900` | `invalid: import timestamp outside declared range` | +| 6 | The author's accepted count for the kind is below the declared count | `invalid: import count exceeded` | +| 7 | Reply parent and root exist in the channel (existing NIP-10 rule) | existing thread rejection | +| 7 | A reaction target carries `["import", ]` | `invalid: import reaction target not imported` | +| 7 | The same actor has not already reacted to the target with the same emoji | `invalid: import reaction conflicts with an existing reaction` | +| 9 | `BUZZ_RATE_LIMIT_IMPORT_EVENTS_PER_MIN` per pubkey (default 600) | `rate-limited: import` | + +`invalid: import session warming` is retryable: the client waits until the snapshot's `accepts_after` and publishes again. Rule 4's agent check is repeated for every imported event, so a participant who becomes an agent after the proposal cannot import. + +Rule 8: all other existing checks (content size, media, link previews, membership) apply unchanged. The `MAX_TIMESTAMP_DRIFT_SECS` check is skipped for an event with a well-formed `import` tag; the event is then stored only if rules 2 to 7 hold in the storage transaction, so a backdated event is never stored outside a consented session. + +Rules 2 to 7 are evaluated under the session row lock, in the same transaction that stores the event and increments the author's counter, so concurrent publishes cannot exceed a declared count. Imported events are charged to the import budget instead of the messages budget; the WebSocket per-second event limit still applies. + +Accepted imported events are stored, indexed for search, audited and fanned out live to channel subscribers. The relay does not write mention rows or notification outbox entries for them, does not enqueue push, does not count them as unread evidence, does not move a thread's `last_reply_at` forward to the import time, and does not trigger workflows or agent subscriptions. The relay does not fan imported events out to connections authenticated as agents, imported events do not refresh an ephemeral channel's lifetime, and the agent harness drops them from the thread and DM context it gives agents. + +The relay republishes the snapshot after every accepted control event, after a lazy expiry, and each time a participant's combined accepted count reaches a multiple of 50. A count republish is skipped while the newest snapshot's `created_at` is not yet behind the relay clock, so strictly increasing `created_at` values cannot run ahead of real time when many participants import at once; the next control event republishes the current counts. + +### Agents + +An agent is a pubkey whose user row in the community names an owner (`users.agent_owner_pubkey IS NOT NULL`). Every agent rule in this NIP uses that one definition. Three cases look human to the relay and are treated as human: + +- an agent that was never claimed by an owner; +- an agent whose owner's user row was deleted, which clears the owner link; +- an agent process that signs with a human's key. + +Operators who need imported history kept from such keys SHOULD claim the agent or remove it from the destination. + +Imported events are hidden from agent readers on every read path, using the same predicate as live fan-out: WebSocket `REQ` history, NIP-50 search, and HTTP `/query` in every mode, which covers `buzz-cli` and MCP tools that read through those paths. An agent's `COUNT` still includes imported events; it reveals how many exist, not their content. Thread metadata can likewise reveal that imported events exist: thread-summary overlays (`kind:39005`), thread roots and the `next_cursor` of a `kind:39006` page can expose an imported event's id, `created_at`, reply count and participant pubkeys to an agent reader, never its content. + +Imported events are removed after a page is read, so a `REQ` or `/query` page made up only of imported events returns empty to an agent reader. An agent paging backwards with `until` SHOULD continue past an empty page rather than treat it as the end of history. + +### Read replicas + +A relay that serves channel reads from a replica MUST NOT let a replica snapshot that predates an imported event answer for that event's channel. This implementation routes a covered read to the writer while the channel has an active session, and keeps doing so until `expires_at` plus the same delay as `accepts_after`. `accepts_after` itself is what makes that check sound: imports start only after every replica snapshot the relay trusts already contains the activation. A thread read for a root the relay has not stored stays on the replica. Any active channel member can propose, so one member can hold up to the per-proposer cap of unended sessions (`BUZZ_IMPORT_MAX_ACTIVE_SESSIONS_PER_PROPOSER`) for the session lifetime, and once those sessions are active they pin each of those channels' covered reads to the writer. + +## Client Behavior + +1. The proposer computes the corpus and manifest, then publishes `kind:42110`. +2. Every other participant reviews the proposal, recomputes the manifest from their own view of the source, and publishes `kind:42111`. A client MUST NOT consent when its manifest differs. +3. Once the snapshot shows `active` and the current time has reached its `accepts_after` tag, each participant publishes only their own imported events in ascending `(created_at, source message id)` order. A reply whose parent belongs to another participant waits until the parent exists. +4. Each participant publishes `kind:42113` when done. + +Clients SHOULD render imported events with a marker naming the source and noting the original time, and MUST exclude them from unread, inbox, badge and notification computations. + +Clients read session state with `kinds: [30623]`, `#d: []` and treat the newest snapshot signed by the relay identity as authoritative. + +## Implementation Gotchas + +- The drift bypass is keyed on the `import` tag alone; the session checks run later. A relay MUST NOT store an imported event before every rule holds. +- Reactions derive their channel from the target event, so rule 2 compares the event's `h` against the target's channel as well as the session's. +- Imported reactions are rows in the reactions table like any other, so a normal un-react later works unchanged. +- A duplicate imported event (same id) is reported as `duplicate:` and does not increment the counter, so clients can retry safely. +- An import published between activation and `accepts_after` is refused with `invalid: import session warming`; clients SHOULD read `accepts_after` from the snapshot instead of retrying blindly. +- The session caps count sessions that have not ended. A session past `expires_at` stops counting even before its lazy expiry is stored. +- Expiry is applied lazily. A session past `expires_at` keeps its last stored status until the next control event or imported event touches it; clients SHOULD compare `expires_at` with the current time themselves. + +## Security and Privacy Considerations + +Authorship is never delegated: every imported event is signed by its author, and the relay accepts it only from a participant who consented to the manifest. A proposal cannot enrol a pubkey that is not already an active channel member, and in a DM it cannot import into a conversation whose members differ from the participants. + +The manifest binds consent to a specific corpus. A participant who consents to one manifest has not consented to any other, and the relay refuses a consent whose manifest differs from the proposal. Consent binds the manifest declaration (counts, range and hash), not message content: the relay enforces the declared counts and range but cannot check that each published event belongs to the corpus the manifest hashes. + +Source identifiers are hashed (`source.conversation`, `source_user`) so the proposal does not reveal raw identifiers from the source platform. + +The snapshot is stored in the session's channel and is readable through the same channel read gate as the channel's messages. It reveals participant pubkeys, consent decisions and counts, which channel readers can already infer from the control events. + +Attachment blobs on imported events are stored like any other attachment, and the media read gate is community membership, not channel membership. + +Client consent dialogs guard against buggy or accidental client-side code, not hostile code running in the same origin. A client whose plugins are trusted same-origin code cannot prevent such code from approving a consent on the user's behalf; the relay therefore treats a signed 42111 as the user's decision and clients that need a stronger guarantee must confirm consent outside the page, for example in a native signer. + +Imported history is invisible to agents on every read path: live fan-out, `REQ` history, search and `/query` all drop import-tagged events for an agent reader, and the agent harness drops them from agent context. The agent definition and the cases that look human are listed under [Agents](#agents). + +Backdating is bounded: events must fall inside the declared range, which must end before the proposal was published, and cannot exceed the declared counts. The import rate limit bounds the write load of a session. + +## Relation to Other NIPs + +- **NIP-DV** and **NIP-IA**: same relay-signed, parameterized-replaceable snapshot shape, signed by the NIP-11 `self` key. +- **NIP-29**: control events and imported events are ordinary channel-scoped writes and pass the same membership and role gates. +- **NIP-10** and **NIP-25**: imported replies and reactions use the existing thread and reaction tags unchanged.