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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,16 @@ system channels out of these reads unless the filter asks for them (see
[evalexpr](https://docs.rs/evalexpr) for condition evaluation. Keep expressions
simple and testable.

Workflow mention candidates include ordinary display names and verified
`display_name`, `username`, and `full_name` aliases for destination-channel
members in the same community. Matching and collision detection lowercase and
canonically normalize aliases. Verified aliases take precedence over ordinary
names with the same normalized value. Collisions across distinct verified keys,
or across ordinary keys when no verified alias matches, produce no recipient or
delegated agent-wake tag. Keep the highest verification level even when it is
ambiguous, so an ordinary name cannot break a verified tie. Verified-only profiles
do not require a separate kind:0 profile.

**Thread counters**: `reply_count` and `descendant_count` are materialized on
thread root events. Any code that inserts replies must update these counters —
check existing reply handlers for the pattern.
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/buzz-db/src/runtime/observability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1619,7 +1619,7 @@ mod tests {
.get_members_for_event_write(test_scope, Uuid::new_v4())
.await;
let _ = writer_db
.get_users_bulk_for_event_write(test_scope, &[vec![11; 32]])
.get_mention_names_for_event_write(test_scope, &[vec![11; 32]], true)
.await;
let _ = writer_db
.huddle_started_link_exists_for_event_write(
Expand Down
77 changes: 69 additions & 8 deletions crates/buzz-db/src/store/channel_members.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ pub use buzz_core::channel::MemberRole;
/// `(pubkey, channel_id)` membership rows.
pub type PubkeyChannels = Vec<(Vec<u8>, Uuid)>;

/// A community-local profile alias used to resolve workflow mentions.
#[derive(Debug, Clone)]
pub struct MentionName {
/// Display name, username, or full name as stored in the profile.
pub name: String,
/// Hex-encoded public key of the channel member.
pub pubkey: String,
/// Whether the alias comes from a relay-verified profile.
pub verified: bool,
}

/// A channel membership row as returned from the database.
#[derive(Debug, Clone)]
pub struct MemberRecord {
Expand Down Expand Up @@ -2969,20 +2980,70 @@ impl Db {
get_users_bulk(&self.pool, community_id, pubkeys).await
}

/// Bulk-fetch user names while constructing an event and its mention tags.
#[datastore_span(name = "get_users_bulk_for_event_write", system = "postgresql")]
pub async fn get_users_bulk_for_event_write(
/// Fetch ordinary display names and, when `include_verified`, verified
/// name aliases for mention tags.
///
/// Preserve alias provenance so the caller can prefer verified names and
/// reject collisions between distinct keys at the same verification level.
#[datastore_span(name = "get_mention_names_for_event_write", system = "postgresql")]
pub async fn get_mention_names_for_event_write(
&self,
community_id: CommunityId,
pubkeys: &[Vec<u8>],
) -> Result<Vec<UserRecord>> {
get_users_bulk_with_operation(
include_verified: bool,
) -> Result<Vec<MentionName>> {
if pubkeys.is_empty() {
return Ok(Vec::new());
}
let mut connection = crate::observability::acquire_writer(
&self.pool,
community_id,
pubkeys,
crate::observability::WriterOperation::EventWrite,
)
.await
.await?;
let rows = sqlx::query(
r#"
SELECT member.pubkey, u.display_name,
jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "display_name")[1]', '{}', true) #>> '{}' AS verified_display_name,
jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "username")[1]', '{}', true) #>> '{}' AS verified_username,
jsonb_path_query_first(v.event, 'strict $.tags[*] ? (@[0] == "full_name")[1]', '{}', true) #>> '{}' AS verified_full_name
FROM unnest($2::bytea[]) AS member(pubkey)
LEFT JOIN users u ON u.community_id = $1 AND u.pubkey = member.pubkey
LEFT JOIN nip_fi_profile_heads v
Comment thread
cshtdd marked this conversation as resolved.
Resolved
ON $3 AND v.community_id = $1 AND v.pubkey = encode(member.pubkey, 'hex')
"#,
)
.bind(community_id.as_uuid())
.bind(pubkeys)
.bind(include_verified)
.fetch_all(&mut *connection)
.await?;
drop(connection);

// Keep provenance even when a member's ordinary and verified names
// agree, or an ordinary alias could hide the verified claim.
let mut seen = std::collections::HashSet::new();
let mut names = Vec::new();
for row in rows {
let pubkey = hex::encode(row.try_get::<Vec<u8>, _>("pubkey")?);
for column in [
"display_name",
"verified_display_name",
"verified_username",
"verified_full_name",
] {
if let Some(name) = row.try_get::<Option<String>, _>(column)? {
let verified = column != "display_name";
if seen.insert((name.to_lowercase(), pubkey.clone(), verified)) {
names.push(MentionName {
name,
pubkey: pubkey.clone(),
verified,
});
}
}
}
}
Ok(names)
}

/// Returns the count of active members in a channel.
Expand Down
15 changes: 12 additions & 3 deletions crates/buzz-db/src/store/verified_profiles.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
//! Durable output-only NIP-FI verified profiles. Authorization never reads
//! these tables.
//! Durable relay-verified NIP-FI profiles. Stored profiles do not authorize
//! admission. Workflow mentions read their name aliases for destination-channel
//! members, including delegated agent-wake tags when the workflow's authored
//! template names an unambiguous member and its authority checks allow it.
//!
//! A profile is a historical record ("verified as Alice at T"). It is never
//! retracted: on a relay that enforces NIP-FI, a key cannot post without a
//! fresh issuer assertion, so a stale name labels only past activity.
//! fresh issuer assertion, regardless of its stored profile.
//!
//! Alias reassignment is not reconciled across keys. If an issuer gives a
//! username or full name to a new key, workflow mentions can still resolve to
//! the old holder when only that holder is a channel member. If both holders
//! are members and retain that verified alias, the mention is silently dropped.
//! Retraction or supersession of conflicting heads belongs in the profile writer,
//! not an age bound in mention lookup, which would still leave a stale window.

use crate::{AdmittedTx, Db, DbError, Result};
use buzz_core::CommunityId;
Expand Down
4 changes: 2 additions & 2 deletions crates/buzz-db/tests/observability_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() {
assert!(channel_members.contains("async fn get_members_with_operation("));
assert!(channel_members.contains("pub async fn get_members_for_event_write("));
assert!(channel_members.contains("async fn get_users_bulk_with_operation("));
assert!(channel_members.contains("pub async fn get_users_bulk_for_event_write("));
assert!(channel_members.contains("pub async fn get_mention_names_for_event_write("));

let huddle_link = event
.split_once("async fn huddle_started_link_exists_with_operation(")
Expand All @@ -340,7 +340,7 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() {

let workflow_sink = include_str!("../../buzz-relay/src/workflow_sink.rs");
assert!(workflow_sink.contains(".get_members_for_event_write("));
assert!(workflow_sink.contains(".get_users_bulk_for_event_write("));
assert!(workflow_sink.contains(".get_mention_names_for_event_write("));

for write_caller in [
include_str!("../../buzz-relay/src/handlers/side_effects.rs"),
Expand Down
1 change: 1 addition & 0 deletions crates/buzz-relay/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ metrics-exporter-prometheus = { workspace = true }
metrics-util = { workspace = true }
pulldown-cmark = { version = "0.13.4", default-features = false, features = ["html"] }
async-compression = { version = "0.4.42", features = ["tokio", "gzip"] }
unicode-normalization = "0.1.25"

[features]
dev = ["buzz-auth/dev"]
Expand Down
18 changes: 13 additions & 5 deletions crates/buzz-relay/src/verified_profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ pub(crate) async fn discovery(
state: &AppState,
tenant: &TenantContext,
) -> Option<serde_json::Value> {
try_discovery(state, tenant).await.ok().flatten()
}

/// [`discovery`], but a failed binding lookup is an error rather than
/// "not advertised", for callers that must not mistake an outage for the
/// feature being off.
pub(crate) async fn try_discovery(
state: &AppState,
tenant: &TenantContext,
) -> Result<Option<serde_json::Value>, buzz_db::DbError> {
let mut count = 0;
for policy in enabled_policies(state) {
let authorized = match state.config.nip_fi.source {
Expand All @@ -130,17 +140,15 @@ pub(crate) async fn discovery(
CommunitySource::Database => state
.db
.lookup_nip_fi_binding_by_host(tenant.host())
.await
.ok()
.flatten()
.await?
.is_some_and(|b| b.active && b.issuers.contains(&policy.issuer)),
};
if authorized {
count += 1;
}
}
// `searchable`: `POST /profiles/search` also matches and returns these.
(count > 0).then(
Ok((count > 0).then(
|| serde_json::json!({"kind": 30382, "multiple_issuers": count > 1, "searchable": true}),
)
))
}
Loading
Loading