From 4a8539708ee81be722ba0cadcf5347e1433e002f Mon Sep 17 00:00:00 2001 From: damienrj Date: Wed, 18 Nov 2026 00:47:55 -0800 Subject: [PATCH 1/6] feat(cli): show and search verified identity in users get Where a community advertises NIP-FI verified profiles, users get attaches a verified object (username, display_name, full_name, issuer_label, verified_at) from the relay-signed kind:30382, trusting only the NIP-11 self key. --name now uses the relay profile search so verified usernames match, falling back to NIP-50 on relays without it. messages send also resolves @mentions by a channel member's verified username. Signed-off-by: damienrj --- Cargo.lock | 2 + crates/buzz-cli/Cargo.toml | 4 + crates/buzz-cli/README.md | 5 + crates/buzz-cli/src/commands/messages.rs | 145 +++++ crates/buzz-cli/src/commands/mod.rs | 1 + crates/buzz-cli/src/commands/users.rs | 503 ++++++++++++++++-- .../src/commands/verified_profiles.rs | 493 +++++++++++++++++ crates/buzz-cli/src/lib.rs | 7 +- 8 files changed, 1114 insertions(+), 46 deletions(-) create mode 100644 crates/buzz-cli/src/commands/verified_profiles.rs diff --git a/Cargo.lock b/Cargo.lock index 312d7068436..930c67502e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1136,6 +1136,8 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-tungstenite 0.29.0", + "unicode-normalization", + "unicode-properties", "url", "uuid", ] diff --git a/crates/buzz-cli/Cargo.toml b/crates/buzz-cli/Cargo.toml index fa08534db8b..550526868fe 100644 --- a/crates/buzz-cli/Cargo.toml +++ b/crates/buzz-cli/Cargo.toml @@ -84,6 +84,10 @@ buzz-ws-client = { path = "../buzz-ws-client" } # auto-select a provider. See crates/buzz-acp/Cargo.toml for the same dependency. rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } +# NFC and general-category checks for verified profile names, as in buzz-auth +unicode-normalization = "0.1.25" +unicode-properties = { version = "0.1.4", default-features = false, features = ["general-category"] } + # Random number generation — full jitter for exponential backoff in with_retry rand = { workspace = true } diff --git a/crates/buzz-cli/README.md b/crates/buzz-cli/README.md index 9e8be330fb3..2a0886166f0 100644 --- a/crates/buzz-cli/README.md +++ b/crates/buzz-cli/README.md @@ -117,6 +117,11 @@ buzz users get # your own profile buzz users get --pubkey # single user buzz users get --pubkey --pubkey # batch (max 200) buzz users get --name Honey --owner me # exact-name lookup in your managed agents +buzz users get --name alice # profile name or verified username (word prefix) +# Where the community advertises verified profiles, a person with a relay-signed +# kind:30382 also has "verified": {username, display_name, full_name?, issuer_label, verified_at}. +# Only a profile signed by the relay's NIP-11 `self` key counts. messages send also +# resolves @alice by a channel member's verified username. buzz users set-presence --status online buzz users set-status --text "heads down on the CLI" --emoji "🚀" buzz users set-status --text "lunch" --emoji "🥪" --expires 1h # clears itself; also a unix time diff --git a/crates/buzz-cli/src/commands/messages.rs b/crates/buzz-cli/src/commands/messages.rs index a8a82962500..001d3a703b9 100644 --- a/crates/buzz-cli/src/commands/messages.rs +++ b/crates/buzz-cli/src/commands/messages.rs @@ -7,6 +7,7 @@ use uuid::Uuid; use crate::client::{normalize_events, normalize_write_response, BuzzClient}; use crate::commands::event_output::{format_events, thread_markers}; use crate::commands::sent_from_thread; +use crate::commands::verified_profiles; use crate::error::CliError; use crate::validate::{ infer_language, parse_event_id, parse_uuid, read_or_stdin, truncate_diff, @@ -219,6 +220,21 @@ async fn resolve_content_mentions( display_names.push(name.to_string()); } + // Where the community advertises verified profiles, a member is also + // reachable by their verified username, e.g. `@alice`. + if let Some(authority) = verified_profiles::discover_authority(client).await? { + let verified = + verified_profiles::fetch_verified_profiles(client, &authority, &member_pubkeys).await?; + for (pubkey, profile) in verified { + let pubkeys = name_to_pubkeys.entry(profile.username.clone()).or_default(); + // A username equal to the member's own profile name is still one person. + if !pubkeys.contains(&pubkey) { + pubkeys.push(pubkey); + } + display_names.push(profile.username); + } + } + let known_refs: Vec<&str> = display_names.iter().map(String::as_str).collect(); let names = extract_at_mentions_with_known(&stripped, &known_refs); let resolved = resolve_names_to_pubkeys(&names, &name_to_pubkeys, has_explicit_mentions)?; @@ -2311,4 +2327,133 @@ mod tests { "must be top-level: {tags:?}" ); } + + // ── @mention resolution by verified username ────────────────────────── + + /// Fake relay for mention resolution: `/query` answers by event kind from + /// `events`; `/` serves `info` (NIP-11). + async fn fake_mention_relay(events: Vec, info: serde_json::Value) -> String { + let state = (events, info); + let app = AxumRouter::new() + .route( + "/query", + axum_post( + |AxumState((events, _)): AxumState<( + Vec, + serde_json::Value, + )>, + body: AxumBytes| async move { + let filters: Vec = + serde_json::from_slice(&body).unwrap(); + let kind = &filters[0]["kinds"][0]; + let found: Vec<_> = events.iter().filter(|e| &e["kind"] == kind).collect(); + ( + AxumStatusCode::OK, + [("content-type", "application/json")], + serde_json::to_string(&found).unwrap(), + ) + }, + ), + ) + .route( + "/", + axum::routing::get( + |AxumState((_, info)): AxumState<( + Vec, + serde_json::Value, + )>| async move { axum::Json(info) }, + ), + ) + .with_state(state); + let listener = TokioTcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr: StdSocketAddr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + fn signed(keys: &Keys, kind: u16, content: &str, tags: Vec>) -> serde_json::Value { + let tags: Vec = tags + .into_iter() + .map(|t| nostr::Tag::parse(t).unwrap()) + .collect(); + let event = nostr::EventBuilder::new(nostr::Kind::Custom(kind), content) + .tags(tags) + .sign_with_keys(keys) + .unwrap(); + serde_json::to_value(event).unwrap() + } + + fn verified_event(relay: &Keys, subject: &Keys, username: &str) -> serde_json::Value { + let pk = subject.public_key().to_hex(); + let pair = |k: &str, v: &str| vec![k.to_string(), v.to_string()]; + signed( + relay, + 30382, + "", + vec![ + pair("d", &pk), + pair("p", &pk), + pair("active", "true"), + pair("display_name", "Alice"), + pair("username", username), + pair("issuer_label", "Example"), + pair("verified_at", "100"), + ], + ) + } + + #[tokio::test] + async fn mentions_resolve_a_members_verified_username() { + let relay = Keys::generate(); + let impostor = Keys::generate(); + let alice = Keys::generate(); + let mallory = Keys::generate(); + let members = signed( + &relay, + 39002, + "", + [&alice, &mallory] + .iter() + .map(|k| vec!["p".to_string(), k.public_key().to_hex()]) + .collect(), + ); + let events = vec![ + members, + signed(&alice, 0, r#"{"display_name":"Al"}"#, vec![]), + signed(&mallory, 0, r#"{"display_name":"Mal"}"#, vec![]), + verified_event(&relay, &alice, "alice"), + // Signed by someone other than the advertised key: not a name. + verified_event(&impostor, &mallory, "carol"), + ]; + let info = serde_json::json!({ + "self": relay.public_key().to_hex(), + "federated_identity": { + "public_profile": {"kind": 30382, "multiple_issuers": false} + }, + }); + let url = fake_mention_relay(events, info).await; + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); + + let (_, resolved) = + super::resolve_content_mentions(&client, SEND_TEST_CHANNEL, "hi @alice", false) + .await + .unwrap(); + assert_eq!(resolved, vec![alice.public_key().to_hex()]); + + let err = super::resolve_content_mentions(&client, SEND_TEST_CHANNEL, "hi @carol", false) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + + // Profile names still resolve as before. + let (_, resolved) = + super::resolve_content_mentions(&client, SEND_TEST_CHANNEL, "hi @Mal", false) + .await + .unwrap(); + assert_eq!(resolved, vec![mallory.public_key().to_hex()]); + } } diff --git a/crates/buzz-cli/src/commands/mod.rs b/crates/buzz-cli/src/commands/mod.rs index 8578eeaaf3b..be0944337b5 100644 --- a/crates/buzz-cli/src/commands/mod.rs +++ b/crates/buzz-cli/src/commands/mod.rs @@ -33,6 +33,7 @@ mod sidebar_sync; pub mod social; pub mod upload; pub mod users; +pub(crate) mod verified_profiles; pub mod workflows; use crate::{client::normalize_write_response, error::CliError}; diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index 4b5a895a639..1d47e471443 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -5,13 +5,22 @@ use crate::client::{extract_d_tag, normalize_write_response, BuzzClient}; use crate::error::CliError; use crate::validate::validate_hex64; +use super::verified_profiles::{ + discover_authority, fetch_verified_profiles, verified_profiles_from_events, VerifiedProfile, +}; +use std::collections::HashMap; + // TODO(phase-4): Replace raw nostr::EventBuilder usage in cmd_set_presence with buzz-sdk builder /// Get user profiles (kind:0 metadata events). /// /// - 0 pubkeys, no name → query our own profile /// - 1+ pubkeys → query those users' profiles -/// - --name "foo" → NIP-50 search on kind:0, then client-side filter +/// - --name "foo" → relay profile search over profile names and, where the +/// community advertises them, verified names +/// +/// Where the community advertises NIP-FI verified profiles, each person with a +/// valid relay-signed kind:30382 also carries a `verified` object. pub async fn cmd_get_users( client: &BuzzClient, pubkeys: &[String], @@ -39,6 +48,27 @@ pub async fn cmd_get_users( return Err(CliError::Usage("--pubkey: maximum 200 pubkeys".into())); } + let profiles = get_profiles(client, pubkeys).await?; + let output = match format { + crate::OutputFormat::Compact => { + let compact: Vec = + profiles.iter().map(|p| compact_profile(p, &[])).collect(); + serde_json::to_string(&compact).unwrap_or_default() + } + crate::OutputFormat::Json | crate::OutputFormat::Agent => { + serde_json::to_string(&profiles).unwrap_or_default() + } + }; + println!("{output}"); + Ok(()) +} + +/// kind:0 profiles for `pubkeys` (our own when empty), each with its verified +/// profile where one exists. +async fn get_profiles( + client: &BuzzClient, + pubkeys: &[String], +) -> Result, CliError> { let my_pk = client.public_key().to_hex(); let authors: Vec<&str> = if pubkeys.is_empty() { vec![my_pk.as_str()] @@ -67,23 +97,137 @@ pub async fn cmd_get_users( Some(profile) }) .collect(); - let output = match format { - crate::OutputFormat::Compact => { - let compact: Vec = profiles - .iter() - .map(|p| serde_json::json!({ - "pubkey": p.get("pubkey").cloned().unwrap_or_default(), - "display_name": p.get("display_name").or_else(|| p.get("name")).cloned().unwrap_or_default(), - })) - .collect(); - serde_json::to_string(&compact).unwrap_or_default() - } - crate::OutputFormat::Json | crate::OutputFormat::Agent => { - serde_json::to_string(&profiles).unwrap_or_default() + let verified = match discover_authority(client).await? { + Some(authority) => { + let requested: Vec = authors.iter().map(|a| a.to_string()).collect(); + fetch_verified_profiles(client, &authority, &requested).await? } + None => HashMap::new(), }; - println!("{output}"); - Ok(()) + Ok(with_verified(profiles, &verified, &authors)) +} + +/// Attach each profile's `verified` object, then append a minimal entry for +/// every `requested` pubkey that is verified but has no kind:0 profile. +fn with_verified( + mut profiles: Vec, + verified: &HashMap, + requested: &[&str], +) -> Vec { + for profile in &mut profiles { + let pubkey = profile + .get("pubkey") + .and_then(|v| v.as_str()) + .map(str::to_ascii_lowercase); + if let (Some(found), Some(obj)) = ( + pubkey.as_deref().and_then(|p| verified.get(p)), + profile.as_object_mut(), + ) { + obj.insert("verified".to_string(), found.to_json()); + } + } + for pubkey in requested { + let pubkey = pubkey.to_ascii_lowercase(); + let listed = profiles.iter().any(|p| { + p.get("pubkey") + .and_then(|v| v.as_str()) + .is_some_and(|listed| listed.eq_ignore_ascii_case(&pubkey)) + }); + if let (false, Some(found)) = (listed, verified.get(&pubkey)) { + profiles.push(verified_only_profile(&pubkey, found)); + } + } + profiles +} + +/// A person with a verified profile but no kind:0. +fn verified_only_profile(pubkey: &str, verified: &VerifiedProfile) -> serde_json::Value { + serde_json::json!({ + "pubkey": pubkey, + "display_name": verified.display_name, + "verified": verified.to_json(), + }) +} + +/// People from a `/profiles/search` page: each person's newest kind:0 and, when +/// `authority` signed one, their verified profile, in the relay's order. A +/// person who matched only by verified name has no kind:0. +fn search_page_profiles( + events: &[serde_json::Value], + authority: Option<&str>, +) -> Vec { + let verified = authority + .map(|authority| verified_profiles_from_events(events, authority)) + .unwrap_or_default(); + let mut order: Vec = Vec::new(); + let mut profiles: HashMap)> = + HashMap::new(); + for event in events { + let kind = event.get("kind").and_then(|v| v.as_u64()); + let pubkey = if kind == Some(0) { + event + .get("pubkey") + .and_then(|v| v.as_str()) + .map(str::to_ascii_lowercase) + } else if kind == Some(u64::from(buzz_core::kind::KIND_VERIFIED_PROFILE)) { + // Only a valid projection by the advertised key finds anybody. + Some(extract_d_tag(event)).filter(|subject| verified.contains_key(subject)) + } else { + None + }; + let Some(pubkey) = pubkey else { + continue; + }; + if !order.contains(&pubkey) { + order.push(pubkey.clone()); + } + if kind == Some(0) { + let created_at = event + .get("created_at") + .and_then(|v| v.as_u64()) + .unwrap_or(0); + if profiles.get(&pubkey).is_none_or(|(at, _)| created_at > *at) { + profiles.insert(pubkey, (created_at, profile_content(event))); + } + } + } + order + .into_iter() + .filter_map(|pubkey| { + let found = verified.get(&pubkey); + match profiles.remove(&pubkey) { + Some((_, mut content)) => { + content.insert("pubkey".to_string(), serde_json::json!(pubkey)); + if let Some(found) = found { + content.insert("verified".to_string(), found.to_json()); + } + Some(serde_json::Value::Object(content)) + } + None => found.map(|found| verified_only_profile(&pubkey, found)), + } + }) + .collect() +} + +/// The compact form of a profile: pubkey, name, any `verified` object, and the +/// listed `extra` fields when present. +fn compact_profile(profile: &serde_json::Value, extra: &[&str]) -> serde_json::Value { + let mut value = serde_json::json!({ + "pubkey": profile.get("pubkey").cloned().unwrap_or_default(), + "display_name": profile + .get("display_name") + .or_else(|| profile.get("name")) + .cloned() + .unwrap_or_default(), + }); + if let Some(obj) = value.as_object_mut() { + for field in extra.iter().chain(&["verified"]) { + if let Some(field_value) = profile.get(*field) { + obj.insert(field.to_string(), field_value.clone()); + } + } + } + value } fn effective_owner(client: &BuzzClient) -> String { @@ -284,8 +428,49 @@ fn owner_scoped_profiles( .collect() } -/// Search for users by display name. Owner-scoped searches resolve managed-agent records -/// and verify their profiles; unscoped searches use NIP-50 and return [] if unsupported. +/// Unscoped name search. `POST /profiles/search` matches profile names and, +/// where the community advertises them, verified names, so a person is found +/// by their verified username too. Relays without the endpoint (404) fall back +/// to NIP-50 search over kind:0, filtered to name matches, with verified +/// profiles read for whoever it finds. +async fn search_profiles( + client: &BuzzClient, + query: &str, +) -> Result, CliError> { + let authority = discover_authority(client).await?; + let body = serde_json::json!({"query": query.trim(), "limit": 100}); + match client.post_json_authed("/profiles/search", &body).await { + Ok(raw) => { + let events: Vec = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; + Ok(search_page_profiles(&events, authority.as_deref())) + } + Err(CliError::Relay { status: 404, .. }) => { + let filter = serde_json::json!({ + "kinds": [0], + "search": query, + "limit": 100 + }); + let raw = client.query(&filter).await?; + let events: Vec = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; + let profiles = name_search_profiles(&events, query); + let Some(authority) = authority else { + return Ok(profiles); + }; + let pubkeys: Vec = profiles + .iter() + .filter_map(|p| p.get("pubkey")?.as_str().map(str::to_owned)) + .collect(); + let verified = fetch_verified_profiles(client, &authority, &pubkeys).await?; + Ok(with_verified(profiles, &verified, &[])) + } + Err(e) => Err(e), + } +} + +/// Search for users by name. Owner-scoped searches resolve managed-agent records +/// and verify their profiles; unscoped searches go through [`search_profiles`]. async fn search_by_name( client: &BuzzClient, query: &str, @@ -321,34 +506,13 @@ async fn search_by_name( }; owner_scoped_profiles(&events, &pubkeys, &owner, &effective_owner(client)) } else { - let filter = serde_json::json!({ - "kinds": [0], - "search": query, - "limit": 100 - }); - let raw = client.query(&filter).await?; - let events: Vec = serde_json::from_str(&raw) - .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; - name_search_profiles(&events, query) + search_profiles(client, query).await? }; let output = match format { crate::OutputFormat::Compact => { let compact: Vec = profiles .iter() - .map(|p| { - let mut value = serde_json::json!({ - "pubkey": p.get("pubkey").cloned().unwrap_or_default(), - "display_name": p.get("display_name").or_else(|| p.get("name")).cloned().unwrap_or_default(), - }); - if let Some(obj) = value.as_object_mut() { - for field in ["owner_pubkey", "owned_by_me", "verification"] { - if let Some(field_value) = p.get(field) { - obj.insert(field.to_string(), field_value.clone()); - } - } - } - value - }) + .map(|p| compact_profile(p, &["owner_pubkey", "owned_by_me", "verification"])) .collect(); serde_json::to_string(&compact).unwrap_or_default() } @@ -775,12 +939,15 @@ pub async fn dispatch( #[cfg(test)] mod tests { use super::{ - owned_agent_pubkeys_from_events, owner_scoped_profiles, owner_verification, - parse_expiration_tag, parse_expiry, presence_subject, publish_status, read_statuses, + compact_profile, get_profiles, owned_agent_pubkeys_from_events, owner_scoped_profiles, + owner_verification, parse_expiration_tag, parse_expiry, presence_subject, publish_status, + read_statuses, search_profiles, }; use crate::client::BuzzClient; use crate::error::CliError; - use axum::{body::Bytes, extract::State, routing::post, Json, Router}; + use axum::{ + body::Bytes, extract::State, http::StatusCode, routing::get, routing::post, Json, Router, + }; use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; use serde_json::{json, Value}; use std::sync::{Arc, Mutex}; @@ -793,6 +960,11 @@ mod tests { events: Vec, queries: Vec, raw_query_response: Option, + /// NIP-11 document served at `/`. + info: Value, + /// Body of `POST /profiles/search`; `None` answers 404 like an older relay. + profile_search: Option, + profile_searches: Vec, } type Shared = Arc>; @@ -822,6 +994,13 @@ mod tests { Some(authors) => authors.as_array().unwrap().contains(&e["pubkey"]), None => true, }) + .filter(|e| match filter.get("#d") { + Some(d) => d + .as_array() + .unwrap() + .contains(&json!(e["tags"][0][1].as_str().unwrap_or_default())), + None => true, + }) .filter(|e| match filter.get("search").and_then(|s| s.as_str()) { Some(q) => e["content"] .as_str() @@ -835,6 +1014,25 @@ mod tests { serde_json::to_string(&matching).unwrap() }), ) + .route( + "/", + get(|State(relay): State| async move { + Json(relay.lock().unwrap().info.clone()) + }), + ) + .route( + "/profiles/search", + post(|State(relay): State, body: Bytes| async move { + let mut relay = relay.lock().unwrap(); + relay + .profile_searches + .push(serde_json::from_slice(&body).unwrap()); + match relay.profile_search.clone() { + Some(events) => (StatusCode::OK, Json(events)), + None => (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))), + } + }), + ) .route( "/events", post(|State(relay): State, body: Bytes| async move { @@ -1160,6 +1358,223 @@ mod tests { .is_empty()); } + /// A NIP-11 document advertising verified profiles signed by `relay`. + fn advertising(relay: &Keys) -> Value { + json!({ + "self": relay.public_key().to_hex(), + "federated_identity": { + "public_profile": {"kind": 30382, "multiple_issuers": false, "searchable": true} + }, + }) + } + + /// Seed a relay-signed verified profile for `subject`. + fn seed_verified(relay: &Shared, signer: &Keys, subject: &Keys, username: &str, at: u64) { + let subject = subject.public_key().to_hex(); + seed( + relay, + signer, + 30382, + "", + vec![ + vec!["d", &subject], + vec!["p", &subject], + vec!["active", "true"], + vec!["display_name", "Alice"], + vec!["username", username], + vec!["full_name", "Alice Example"], + vec!["issuer_label", "Example"], + vec!["verified_at", "100"], + ], + at, + ); + } + + fn seed_profile(relay: &Shared, keys: &Keys, content: &str) { + seed(relay, keys, 0, content, vec![], 50); + } + + fn verified_json(username: &str) -> Value { + json!({ + "username": username, + "display_name": "Alice", + "full_name": "Alice Example", + "issuer_label": "Example", + "verified_at": 100, + }) + } + + #[tokio::test] + async fn get_by_pubkey_shows_the_verified_identity_the_relay_signed() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + let plain = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"al"}"#); + seed_profile(&relay, &plain, r#"{"name":"plain"}"#); + seed_verified(&relay, &authority, &alice, "alice", 100); + + let pubkeys = vec![alice.public_key().to_hex(), plain.public_key().to_hex()]; + let profiles = get_profiles(&client, &pubkeys).await.unwrap(); + assert_eq!(profiles.len(), 2); + assert_eq!(profiles[0]["name"], "al"); + assert_eq!(profiles[0]["verified"], verified_json("alice")); + assert!(profiles[1].get("verified").is_none()); + + let filter = relay.lock().unwrap().queries.last().cloned().unwrap(); + assert_eq!(filter["kinds"], json!([30382])); + assert_eq!(filter["authors"], json!([authority.public_key().to_hex()])); + + // Compact output keeps the verified object. + let compact = compact_profile(&profiles[0], &[]); + assert_eq!(compact["verified"]["username"], "alice"); + } + + #[tokio::test] + async fn get_by_pubkey_trusts_only_the_advertised_relay_key() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + let impostor = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"al"}"#); + seed_verified(&relay, &impostor, &alice, "alice", 100); + + let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) + .await + .unwrap(); + assert!(profiles[0].get("verified").is_none()); + } + + #[tokio::test] + async fn get_by_pubkey_ignores_verified_profiles_the_community_does_not_advertise() { + let (client, relay) = setup().await; + let signer = Keys::generate(); + relay.lock().unwrap().info = json!({"self": signer.public_key().to_hex()}); + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"al"}"#); + seed_verified(&relay, &signer, &alice, "alice", 100); + + let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) + .await + .unwrap(); + assert!(profiles[0].get("verified").is_none()); + assert!(relay + .lock() + .unwrap() + .queries + .iter() + .all(|q| q["kinds"] != json!([30382]))); + } + + #[tokio::test] + async fn get_by_pubkey_lists_a_verified_person_who_has_no_profile() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + seed_verified(&relay, &authority, &alice, "alice", 100); + + let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) + .await + .unwrap(); + assert_eq!( + profiles, + vec![json!({ + "pubkey": alice.public_key().to_hex(), + "display_name": "Alice", + "verified": verified_json("alice"), + })] + ); + } + + #[tokio::test] + async fn get_fails_rather_than_hide_a_malformed_advertisement() { + let (client, relay) = setup().await; + relay.lock().unwrap().info = json!({ + "self": "00".repeat(32), + "federated_identity": {"public_profile": {"kind": 7}}, + }); + let err = get_profiles(&client, &[]).await.unwrap_err(); + assert!(matches!(err, CliError::Other(_)), "{err:?}"); + } + + #[tokio::test] + async fn name_search_finds_a_person_by_verified_username() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + let bob = Keys::generate(); + // The kind:0 name does not contain the username; the relay matched the + // verified one and returned both events, plus an impostor's. + seed_profile(&relay, &alice, r#"{"name":"al","display_name":"Al"}"#); + seed_verified(&relay, &authority, &alice, "alice", 100); + seed_verified(&relay, &Keys::generate(), &bob, "alice", 100); + let events = relay.lock().unwrap().events.clone(); + relay.lock().unwrap().profile_search = Some(json!(events)); + + let found = search_profiles(&client, " alice ").await.unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); + assert_eq!(found[0]["name"], "al"); + assert_eq!(found[0]["verified"], verified_json("alice")); + assert_eq!( + relay.lock().unwrap().profile_searches, + vec![json!({"query": "alice", "limit": 100})] + ); + } + + #[tokio::test] + async fn name_search_returns_a_person_matched_only_by_verified_name() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + seed_verified(&relay, &authority, &alice, "alice", 100); + let events = relay.lock().unwrap().events.clone(); + relay.lock().unwrap().profile_search = Some(json!(events)); + + let found = search_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); + assert_eq!(found[0]["verified"]["username"], "alice"); + } + + #[tokio::test] + async fn name_search_without_verified_profiles_trusts_the_relay_page_as_is() { + let (client, relay) = setup().await; + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"alice"}"#); + // A 30382 from an unadvertised community finds nobody. + seed_verified(&relay, &Keys::generate(), &Keys::generate(), "zed", 100); + let events = relay.lock().unwrap().events.clone(); + relay.lock().unwrap().profile_search = Some(json!(events)); + + let found = search_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1); + assert!(found[0].get("verified").is_none()); + } + + #[tokio::test] + async fn name_search_falls_back_to_nip50_on_a_relay_without_profile_search() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"alice"}"#); + seed_profile(&relay, &Keys::generate(), r#"{"name":"bob"}"#); + seed_verified(&relay, &authority, &alice, "alice", 100); + + let found = search_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); + assert_eq!(found[0]["verified"]["username"], "alice"); + let queries = relay.lock().unwrap().queries.clone(); + assert_eq!(queries[0]["search"], "alice"); + } + #[test] fn owned_agent_lookup_matches_exact_name_case_insensitively() { let events = vec![ diff --git a/crates/buzz-cli/src/commands/verified_profiles.rs b/crates/buzz-cli/src/commands/verified_profiles.rs new file mode 100644 index 00000000000..d29525ef6b9 --- /dev/null +++ b/crates/buzz-cli/src/commands/verified_profiles.rs @@ -0,0 +1,493 @@ +//! NIP-FI verified profiles: relay-signed kind:30382 events that carry the +//! verified `username`, `display_name` and optional `full_name` of a pubkey. +//! +//! A community advertises them in NIP-11 (`federated_identity.public_profile`). +//! The only key trusted to sign them is the relay's NIP-11 `self` key, so a +//! kind:30382 signed by anyone else is ignored. Event and projection checks +//! mirror the Buzz mobile client (`verified_profile.dart`). + +use std::collections::HashMap; + +use nostr::Event; +use serde_json::{json, Value}; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; + +use crate::client::BuzzClient; +use crate::commands::agents::normalize_relay_self_hex; +use crate::error::CliError; + +/// Event kind of the relay-signed verified profile projection. +const KIND: u16 = buzz_core::kind::KIND_VERIFIED_PROFILE as u16; + +/// Subjects per query, keeping each REQ inside relay filter limits. +const SUBJECTS_PER_QUERY: usize = 128; + +/// Larger events (UTF-16 units of content and every tag element) are dropped +/// before any further work. A valid projection is well under 1 KiB. +const MAX_EVENT_SIZE: usize = 4096; + +/// A verified name as the relay last published it. Historical: it records the +/// issuer's name-to-key assertion at `verified_at`, never current access. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct VerifiedProfile { + pub display_name: String, + pub username: String, + pub full_name: Option, + pub issuer_label: String, + pub verified_at: u64, +} + +impl VerifiedProfile { + /// The `verified` object `buzz users get` prints. + pub(crate) fn to_json(&self) -> Value { + let mut value = json!({ + "username": self.username, + "display_name": self.display_name, + "issuer_label": self.issuer_label, + "verified_at": self.verified_at, + }); + if let Some(full_name) = &self.full_name { + value["full_name"] = json!(full_name); + } + value + } +} + +/// Read the relay key that signs verified profiles from a NIP-11 document. +/// +/// `Ok(None)`: the community does not advertise verified profiles, so every +/// kind:30382 is ignored. A malformed advertisement is an error rather than +/// "no verified profiles", so an agent never reads a failed check as an +/// authoritative absence. +pub(crate) fn parse_discovery(info: &Value) -> Result, CliError> { + let malformed = |what: &str| CliError::Other(format!("relay info document: {what}")); + let Some(federated) = info.get("federated_identity") else { + return Ok(None); + }; + let federated = federated + .as_object() + .ok_or_else(|| malformed("malformed federated_identity"))?; + let Some(profile) = federated.get("public_profile") else { + return Ok(None); + }; + let self_hex = info.get("self").and_then(Value::as_str); + let (Some(profile), Some(self_hex)) = (profile.as_object(), self_hex) else { + return Err(malformed("malformed public_profile discovery")); + }; + if profile.get("kind").and_then(Value::as_u64) != Some(u64::from(KIND)) + || !profile + .get("multiple_issuers") + .is_some_and(serde_json::Value::is_boolean) + { + return Err(malformed("malformed public_profile discovery")); + } + normalize_relay_self_hex(self_hex).map(Some) +} + +/// The key that signs this community's verified profiles, if it advertises any. +pub(crate) async fn discover_authority(client: &BuzzClient) -> Result, CliError> { + let raw = client + .get_public("/") + .await + .map_err(|e| CliError::Other(format!("failed to fetch relay info document: {e}")))?; + let info: Value = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("relay info document is not valid JSON: {e}")))?; + parse_discovery(&info) +} + +/// Verified profiles for `pubkeys`, keyed by lowercase pubkey. Pubkeys without +/// a valid, active, relay-signed profile are absent. +pub(crate) async fn fetch_verified_profiles( + client: &BuzzClient, + authority: &str, + pubkeys: &[String], +) -> Result, CliError> { + let mut subjects: Vec = pubkeys.iter().map(|p| p.to_ascii_lowercase()).collect(); + subjects.sort(); + subjects.dedup(); + let mut verified = HashMap::new(); + for chunk in subjects.chunks(SUBJECTS_PER_QUERY) { + let filter = json!({ + "kinds": [KIND], + "authors": [authority], + "#d": chunk, + "limit": chunk.len(), + }); + let raw = client.query(&filter).await?; + let events: Vec = serde_json::from_str(&raw).map_err(|e| { + CliError::Other(format!("failed to parse verified profile response: {e}")) + })?; + verified.extend( + verified_profiles_from_events(&events, authority) + .into_iter() + .filter(|(subject, _)| chunk.contains(subject)), + ); + } + Ok(verified) +} + +/// Every valid verified profile among `events`, keyed by subject pubkey. +/// +/// Anything not signed by `authority`, not of kind 30382, oversized, or with +/// a bad id or signature is ignored. Per subject the newest event is the head, +/// as for any addressable event; a head that is not a valid active projection +/// (including a retraction) leaves the subject with no verified profile, so a +/// stale older name never resurfaces. +pub(crate) fn verified_profiles_from_events( + events: &[Value], + authority: &str, +) -> HashMap { + let mut heads: HashMap = HashMap::new(); + for raw in events { + let Ok(event) = serde_json::from_value::(raw.clone()) else { + continue; + }; + let Some(subject) = subject(&event, authority) else { + continue; + }; + if event.verify().is_err() { + continue; + } + if heads + .get(&subject) + .is_none_or(|current| supersedes(&event, current)) + { + heads.insert(subject, event); + } + } + heads + .into_iter() + .filter_map(|(subject, event)| parse_projection(&event, &subject).map(|p| (subject, p))) + .collect() +} + +/// NIP-01 replaceable ordering: the later `created_at` wins; a tie goes to the +/// lower event id. +fn supersedes(candidate: &Event, current: &Event) -> bool { + candidate.created_at > current.created_at + || (candidate.created_at == current.created_at + && candidate.id.to_hex() < current.id.to_hex()) +} + +fn is_lower_hex64(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn event_size(event: &Event) -> usize { + let mut size = event.content.encode_utf16().count(); + for tag in event.tags.iter() { + size += 1; + for value in tag.as_slice() { + size += value.encode_utf16().count() + 1; + } + } + size +} + +/// The subject a kind:30382 event addresses: its first `d` tag, when the event +/// is by `authority`, within the size bound, and the tag is a lowercase hex +/// pubkey. Projection shape is not checked here. +fn subject(event: &Event, authority: &str) -> Option { + if event.kind.as_u16() != KIND + || event.pubkey.to_hex() != authority + || event_size(event) > MAX_EVENT_SIZE + { + return None; + } + let d = event + .tags + .iter() + .map(|tag| tag.as_slice()) + .find(|tag| tag.first().map(String::as_str) == Some("d"))?; + d.get(1).filter(|v| is_lower_hex64(v)).cloned() +} + +/// Strictly validate the projection NIP-FI defines: empty content; exactly +/// seven tags (eight with `full_name`), each of two elements with no repeated +/// name; `d` and `p` equal; `active` equal to `true`; well-formed names, +/// username and issuer label; and a `verified_at` no later than `created_at`. +fn parse_projection(event: &Event, subject: &str) -> Option { + if !event.content.is_empty() || !matches!(event.tags.len(), 7 | 8) { + return None; + } + let mut tags: HashMap<&str, &str> = HashMap::new(); + for tag in event.tags.iter() { + let [name, value] = tag.as_slice() else { + return None; + }; + if tags.insert(name, value).is_some() { + return None; + } + } + const REQUIRED: [&str; 7] = [ + "d", + "p", + "active", + "display_name", + "username", + "issuer_label", + "verified_at", + ]; + let full_name = tags.get("full_name").copied(); + if !REQUIRED.iter().all(|name| tags.contains_key(name)) + || tags.len() != REQUIRED.len() + usize::from(full_name.is_some()) + { + return None; + } + let (display_name, username, issuer_label) = + (tags["display_name"], tags["username"], tags["issuer_label"]); + let verified_at = tags["verified_at"]; + if tags["p"] != subject + || tags["active"] != "true" + || !full_name.is_none_or(valid_name) + || !valid_name(display_name) + || !valid_username(username) + || !valid_name(issuer_label) + || verified_at.is_empty() + || !verified_at.bytes().all(|b| b.is_ascii_digit()) + { + return None; + } + let verified_at: u64 = verified_at.parse().ok()?; + if verified_at > event.created_at.as_secs() { + return None; + } + Some(VerifiedProfile { + display_name: display_name.to_owned(), + username: username.to_owned(), + full_name: full_name.map(str::to_owned), + issuer_label: issuer_label.to_owned(), + verified_at, + }) +} + +/// A name or issuer label: 1 to 64 scalar values in NFC, no control, format, +/// surrogate, private-use, unassigned or line/paragraph separator characters, +/// and no whitespace at either end. +fn valid_name(value: &str) -> bool { + use GeneralCategory::{ + Control, Format, LineSeparator, ParagraphSeparator, PrivateUse, Surrogate, Unassigned, + }; + !value.is_empty() + && value.chars().count() <= 64 + && value.trim() == value + && unicode_normalization::is_nfc(value) + && !value.chars().any(|c| { + matches!( + c.general_category(), + Control + | Format + | Surrogate + | PrivateUse + | Unassigned + | LineSeparator + | ParagraphSeparator + ) + }) +} + +/// A username: 1 to 64 characters of lowercase ASCII letters, digits, `.`, `_` or `-`. +fn valid_username(value: &str) -> bool { + (1..=64).contains(&value.len()) + && value + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)) +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + const AT: u64 = 1_800_000_000; + + fn tag_pairs<'a>(subject: &'a str, extra: &[(&'a str, &'a str)]) -> Vec<(&'a str, &'a str)> { + let mut tags = vec![ + ("d", subject), + ("p", subject), + ("active", "true"), + ("display_name", "alice"), + ("username", "alice"), + ("issuer_label", "Example"), + ("verified_at", "1799999999"), + ]; + tags.extend_from_slice(extra); + tags + } + + fn sign(keys: &Keys, kind: u16, content: &str, tags: &[(&str, &str)], at: u64) -> Value { + let tags: Vec = tags + .iter() + .map(|(k, v)| Tag::parse([*k, *v]).unwrap()) + .collect(); + let event = EventBuilder::new(Kind::Custom(kind), content) + .tags(tags) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(keys) + .unwrap(); + serde_json::to_value(event).unwrap() + } + + #[test] + fn discovery_reads_the_relay_key_only_where_advertised() { + let key = "ab".repeat(32); + let advertised = |profile: Value| json!({"self": key, "federated_identity": {"public_profile": profile}}); + let good = json!({"kind": 30382, "multiple_issuers": false, "searchable": true}); + assert_eq!( + parse_discovery(&advertised(good)).unwrap(), + Some(key.clone()) + ); + // Not advertised: absent or without `public_profile`. + assert_eq!(parse_discovery(&json!({"self": key})).unwrap(), None); + assert_eq!( + parse_discovery(&json!({"self": key, "federated_identity": {}})).unwrap(), + None + ); + // Advertised but malformed is a failed check, not an absence. + for bad in [ + advertised(json!(null)), + advertised(json!({"kind": 30382})), + advertised(json!({"kind": 1, "multiple_issuers": true})), + advertised(json!({"kind": 30382, "multiple_issuers": "yes"})), + json!({"federated_identity": {"public_profile": {"kind": 30382, "multiple_issuers": true}}}), + json!({"self": "nothex", "federated_identity": {"public_profile": {"kind": 30382, "multiple_issuers": true}}}), + json!({"self": key, "federated_identity": "on"}), + ] { + assert!(parse_discovery(&bad).is_err(), "{bad}"); + } + } + + #[test] + fn a_relay_signed_active_projection_is_verified() { + let relay = Keys::generate(); + let subject = Keys::generate().public_key().to_hex(); + let tags = tag_pairs(&subject, &[("full_name", "Alice Example")]); + let event = sign(&relay, 30382, "", &tags, AT); + let found = verified_profiles_from_events(&[event], &relay.public_key().to_hex()); + assert_eq!( + found[&subject], + VerifiedProfile { + display_name: "alice".into(), + username: "alice".into(), + full_name: Some("Alice Example".into()), + issuer_label: "Example".into(), + verified_at: 1_799_999_999, + } + ); + assert_eq!( + found[&subject].to_json(), + json!({ + "username": "alice", + "display_name": "alice", + "full_name": "Alice Example", + "issuer_label": "Example", + "verified_at": 1_799_999_999, + }) + ); + } + + #[test] + fn full_name_is_omitted_when_absent() { + let relay = Keys::generate(); + let subject = Keys::generate().public_key().to_hex(); + let event = sign(&relay, 30382, "", &tag_pairs(&subject, &[]), AT); + let found = verified_profiles_from_events(&[event], &relay.public_key().to_hex()); + assert!(found[&subject].to_json().get("full_name").is_none()); + } + + #[test] + fn an_event_signed_by_any_other_key_is_ignored() { + let relay = Keys::generate(); + let impostor = Keys::generate(); + let subject = Keys::generate().public_key().to_hex(); + let forged = sign(&impostor, 30382, "", &tag_pairs(&subject, &[]), AT); + assert!(verified_profiles_from_events(&[forged], &relay.public_key().to_hex()).is_empty()); + } + + #[test] + fn a_tampered_or_wrong_kind_event_is_ignored() { + let relay = Keys::generate(); + let authority = relay.public_key().to_hex(); + let subject = Keys::generate().public_key().to_hex(); + let mut tampered = sign(&relay, 30382, "", &tag_pairs(&subject, &[]), AT); + tampered["tags"][4] = json!(["username", "mallory"]); + let wrong_kind = sign(&relay, 30383, "", &tag_pairs(&subject, &[]), AT); + assert!(verified_profiles_from_events(&[tampered, wrong_kind], &authority).is_empty()); + } + + #[test] + fn malformed_projections_are_ignored() { + let relay = Keys::generate(); + let authority = relay.public_key().to_hex(); + let subject = Keys::generate().public_key().to_hex(); + let other = Keys::generate().public_key().to_hex(); + let long = "a".repeat(65); + let cases: Vec<(&str, Vec<(&str, &str)>)> = vec![ + ("content", vec![]), + ("retracted", vec![("active", "false")]), + ("p mismatch", vec![("p", &other)]), + ("bad username", vec![("username", "Alice")]), + ("empty username", vec![("username", "")]), + ("padded name", vec![("display_name", " alice")]), + ("control name", vec![("display_name", "al\nice")]), + ("bidi name", vec![("full_name", "Al\u{202e}ice")]), + ("non-NFC name", vec![("full_name", "e\u{301}")]), + ("long name", vec![("display_name", &long)]), + ("future verified_at", vec![("verified_at", "1800000001")]), + ("signed verified_at", vec![("verified_at", "+5")]), + ("extra tag", vec![("extra", "x")]), + ]; + for (label, overrides) in cases { + let mut tags = tag_pairs(&subject, &[]); + for (key, value) in &overrides { + match tags.iter_mut().find(|(k, _)| k == key) { + Some(existing) => existing.1 = value, + None => tags.push((key, value)), + } + } + let content = if label == "content" { "hi" } else { "" }; + let event = sign(&relay, 30382, content, &tags, AT); + assert!( + verified_profiles_from_events(&[event], &authority).is_empty(), + "{label}" + ); + } + let repeated = tag_pairs(&subject, &[("username", "bob")]); + let event = sign(&relay, 30382, "", &repeated, AT); + assert!(verified_profiles_from_events(&[event], &authority).is_empty()); + } + + #[test] + fn the_newest_head_wins_and_a_retraction_clears_the_name() { + let relay = Keys::generate(); + let authority = relay.public_key().to_hex(); + let subject = Keys::generate().public_key().to_hex(); + let old = sign(&relay, 30382, "", &tag_pairs(&subject, &[]), AT); + let renamed = { + let mut tags = tag_pairs(&subject, &[]); + tags[4] = ("username", "alice2"); + sign(&relay, 30382, "", &tags, AT + 10) + }; + let retracted = { + let mut tags = tag_pairs(&subject, &[]); + tags[2] = ("active", "false"); + sign(&relay, 30382, "", &tags, AT + 20) + }; + let found = verified_profiles_from_events(&[old.clone(), renamed.clone()], &authority); + assert_eq!(found[&subject].username, "alice2"); + let found = verified_profiles_from_events(&[renamed, retracted, old], &authority); + assert!(found.is_empty(), "{found:?}"); + } + + #[test] + fn subject_comes_from_the_first_d_tag_and_must_be_lowercase_hex() { + let relay = Keys::generate(); + let authority = relay.public_key().to_hex(); + let upper = Keys::generate().public_key().to_hex().to_uppercase(); + let event = sign(&relay, 30382, "", &tag_pairs(&upper, &[]), AT); + assert!(verified_profiles_from_events(&[event], &authority).is_empty()); + } +} diff --git a/crates/buzz-cli/src/lib.rs b/crates/buzz-cli/src/lib.rs index e523890d258..af91ca566cf 100644 --- a/crates/buzz-cli/src/lib.rs +++ b/crates/buzz-cli/src/lib.rs @@ -1372,12 +1372,15 @@ pub enum DmsCmd { #[derive(Subcommand)] pub enum UsersCmd { - /// Look up user profiles by pubkey or name + /// Look up user profiles by pubkey or name. Where the community + /// advertises verified profiles, a person's relay-verified username, full + /// name and issuer appear in a `verified` object Get { /// User pubkey(s) to look up (64-char hex). Omit for your own profile #[arg(long = "pubkey")] pubkeys: Vec, - /// Search by display name (case-insensitive substring match) + /// Search by profile name or, where advertised, verified name + /// (e.g. a verified username). Case-insensitive; matches word prefixes #[arg(long = "name")] name: Option, /// Scope an exact-name agent lookup to its owner (`me`, hex, or npub) From b8b95d3a3390ace11fde5fcd03f0d6f6db63fb26 Mon Sep 17 00:00:00 2001 From: damienrj Date: Wed, 18 Nov 2026 01:19:00 -0800 Subject: [PATCH 2/6] refactor(cli): narrow verified profile support to users get Drop the messages send @mention change, the unicode name validation and strict projection checks, the 404 fallback and verified-only entries. Strip any verified key from kind:0 content so only a relay-signed kind:30382 can set it. Signed-off-by: damienrj --- Cargo.lock | 2 - crates/buzz-cli/Cargo.toml | 4 - crates/buzz-cli/README.md | 8 +- crates/buzz-cli/src/commands/messages.rs | 145 ----------- crates/buzz-cli/src/commands/users.rs | 214 ++++++---------- .../src/commands/verified_profiles.rs | 238 +++++------------- crates/buzz-cli/src/lib.rs | 4 +- 7 files changed, 140 insertions(+), 475 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 930c67502e3..312d7068436 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1136,8 +1136,6 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-tungstenite 0.29.0", - "unicode-normalization", - "unicode-properties", "url", "uuid", ] diff --git a/crates/buzz-cli/Cargo.toml b/crates/buzz-cli/Cargo.toml index 550526868fe..fa08534db8b 100644 --- a/crates/buzz-cli/Cargo.toml +++ b/crates/buzz-cli/Cargo.toml @@ -84,10 +84,6 @@ buzz-ws-client = { path = "../buzz-ws-client" } # auto-select a provider. See crates/buzz-acp/Cargo.toml for the same dependency. rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } -# NFC and general-category checks for verified profile names, as in buzz-auth -unicode-normalization = "0.1.25" -unicode-properties = { version = "0.1.4", default-features = false, features = ["general-category"] } - # Random number generation — full jitter for exponential backoff in with_retry rand = { workspace = true } diff --git a/crates/buzz-cli/README.md b/crates/buzz-cli/README.md index 2a0886166f0..9a4688f7b0e 100644 --- a/crates/buzz-cli/README.md +++ b/crates/buzz-cli/README.md @@ -117,11 +117,9 @@ buzz users get # your own profile buzz users get --pubkey # single user buzz users get --pubkey --pubkey # batch (max 200) buzz users get --name Honey --owner me # exact-name lookup in your managed agents -buzz users get --name alice # profile name or verified username (word prefix) -# Where the community advertises verified profiles, a person with a relay-signed -# kind:30382 also has "verified": {username, display_name, full_name?, issuer_label, verified_at}. -# Only a profile signed by the relay's NIP-11 `self` key counts. messages send also -# resolves @alice by a channel member's verified username. +# Where the community advertises verified profiles, `users get` adds a "verified" +# object ({username, display_name, full_name?, issuer_label, verified_at}) from a +# kind:30382 signed by the relay's NIP-11 `self` key, and --name also finds verified usernames. buzz users set-presence --status online buzz users set-status --text "heads down on the CLI" --emoji "🚀" buzz users set-status --text "lunch" --emoji "🥪" --expires 1h # clears itself; also a unix time diff --git a/crates/buzz-cli/src/commands/messages.rs b/crates/buzz-cli/src/commands/messages.rs index 001d3a703b9..a8a82962500 100644 --- a/crates/buzz-cli/src/commands/messages.rs +++ b/crates/buzz-cli/src/commands/messages.rs @@ -7,7 +7,6 @@ use uuid::Uuid; use crate::client::{normalize_events, normalize_write_response, BuzzClient}; use crate::commands::event_output::{format_events, thread_markers}; use crate::commands::sent_from_thread; -use crate::commands::verified_profiles; use crate::error::CliError; use crate::validate::{ infer_language, parse_event_id, parse_uuid, read_or_stdin, truncate_diff, @@ -220,21 +219,6 @@ async fn resolve_content_mentions( display_names.push(name.to_string()); } - // Where the community advertises verified profiles, a member is also - // reachable by their verified username, e.g. `@alice`. - if let Some(authority) = verified_profiles::discover_authority(client).await? { - let verified = - verified_profiles::fetch_verified_profiles(client, &authority, &member_pubkeys).await?; - for (pubkey, profile) in verified { - let pubkeys = name_to_pubkeys.entry(profile.username.clone()).or_default(); - // A username equal to the member's own profile name is still one person. - if !pubkeys.contains(&pubkey) { - pubkeys.push(pubkey); - } - display_names.push(profile.username); - } - } - let known_refs: Vec<&str> = display_names.iter().map(String::as_str).collect(); let names = extract_at_mentions_with_known(&stripped, &known_refs); let resolved = resolve_names_to_pubkeys(&names, &name_to_pubkeys, has_explicit_mentions)?; @@ -2327,133 +2311,4 @@ mod tests { "must be top-level: {tags:?}" ); } - - // ── @mention resolution by verified username ────────────────────────── - - /// Fake relay for mention resolution: `/query` answers by event kind from - /// `events`; `/` serves `info` (NIP-11). - async fn fake_mention_relay(events: Vec, info: serde_json::Value) -> String { - let state = (events, info); - let app = AxumRouter::new() - .route( - "/query", - axum_post( - |AxumState((events, _)): AxumState<( - Vec, - serde_json::Value, - )>, - body: AxumBytes| async move { - let filters: Vec = - serde_json::from_slice(&body).unwrap(); - let kind = &filters[0]["kinds"][0]; - let found: Vec<_> = events.iter().filter(|e| &e["kind"] == kind).collect(); - ( - AxumStatusCode::OK, - [("content-type", "application/json")], - serde_json::to_string(&found).unwrap(), - ) - }, - ), - ) - .route( - "/", - axum::routing::get( - |AxumState((_, info)): AxumState<( - Vec, - serde_json::Value, - )>| async move { axum::Json(info) }, - ), - ) - .with_state(state); - let listener = TokioTcpListener::bind("127.0.0.1:0").await.unwrap(); - let addr: StdSocketAddr = listener.local_addr().unwrap(); - tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); - format!("http://{addr}") - } - - fn signed(keys: &Keys, kind: u16, content: &str, tags: Vec>) -> serde_json::Value { - let tags: Vec = tags - .into_iter() - .map(|t| nostr::Tag::parse(t).unwrap()) - .collect(); - let event = nostr::EventBuilder::new(nostr::Kind::Custom(kind), content) - .tags(tags) - .sign_with_keys(keys) - .unwrap(); - serde_json::to_value(event).unwrap() - } - - fn verified_event(relay: &Keys, subject: &Keys, username: &str) -> serde_json::Value { - let pk = subject.public_key().to_hex(); - let pair = |k: &str, v: &str| vec![k.to_string(), v.to_string()]; - signed( - relay, - 30382, - "", - vec![ - pair("d", &pk), - pair("p", &pk), - pair("active", "true"), - pair("display_name", "Alice"), - pair("username", username), - pair("issuer_label", "Example"), - pair("verified_at", "100"), - ], - ) - } - - #[tokio::test] - async fn mentions_resolve_a_members_verified_username() { - let relay = Keys::generate(); - let impostor = Keys::generate(); - let alice = Keys::generate(); - let mallory = Keys::generate(); - let members = signed( - &relay, - 39002, - "", - [&alice, &mallory] - .iter() - .map(|k| vec!["p".to_string(), k.public_key().to_hex()]) - .collect(), - ); - let events = vec![ - members, - signed(&alice, 0, r#"{"display_name":"Al"}"#, vec![]), - signed(&mallory, 0, r#"{"display_name":"Mal"}"#, vec![]), - verified_event(&relay, &alice, "alice"), - // Signed by someone other than the advertised key: not a name. - verified_event(&impostor, &mallory, "carol"), - ]; - let info = serde_json::json!({ - "self": relay.public_key().to_hex(), - "federated_identity": { - "public_profile": {"kind": 30382, "multiple_issuers": false} - }, - }); - let url = fake_mention_relay(events, info).await; - let client = BuzzClient::new( - url, - crate::credentials::Credentials::from_keys(Keys::generate()), - ) - .unwrap(); - - let (_, resolved) = - super::resolve_content_mentions(&client, SEND_TEST_CHANNEL, "hi @alice", false) - .await - .unwrap(); - assert_eq!(resolved, vec![alice.public_key().to_hex()]); - - let err = super::resolve_content_mentions(&client, SEND_TEST_CHANNEL, "hi @carol", false) - .await - .unwrap_err(); - assert!(matches!(err, CliError::Usage(_)), "{err:?}"); - - // Profile names still resolve as before. - let (_, resolved) = - super::resolve_content_mentions(&client, SEND_TEST_CHANNEL, "hi @Mal", false) - .await - .unwrap(); - assert_eq!(resolved, vec![mallory.public_key().to_hex()]); - } } diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index 1d47e471443..d2af3dc674d 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -16,8 +16,7 @@ use std::collections::HashMap; /// /// - 0 pubkeys, no name → query our own profile /// - 1+ pubkeys → query those users' profiles -/// - --name "foo" → relay profile search over profile names and, where the -/// community advertises them, verified names +/// - --name "foo" → [`search_profiles`] /// /// Where the community advertises NIP-FI verified profiles, each person with a /// valid relay-signed kind:30382 also carries a `verified` object. @@ -89,6 +88,7 @@ async fn get_profiles( let content_str = e.get("content")?.as_str()?; let mut profile: serde_json::Value = serde_json::from_str(content_str).ok()?; if let Some(obj) = profile.as_object_mut() { + obj.remove("verified"); obj.insert( "pubkey".to_string(), serde_json::json!(e.get("pubkey").and_then(|v| v.as_str()).unwrap_or("")), @@ -104,15 +104,13 @@ async fn get_profiles( } None => HashMap::new(), }; - Ok(with_verified(profiles, &verified, &authors)) + Ok(with_verified(profiles, &verified)) } -/// Attach each profile's `verified` object, then append a minimal entry for -/// every `requested` pubkey that is verified but has no kind:0 profile. +/// Attach each profile's `verified` object where a relay-signed one exists. fn with_verified( mut profiles: Vec, verified: &HashMap, - requested: &[&str], ) -> Vec { for profile in &mut profiles { let pubkey = profile @@ -126,17 +124,6 @@ fn with_verified( obj.insert("verified".to_string(), found.to_json()); } } - for pubkey in requested { - let pubkey = pubkey.to_ascii_lowercase(); - let listed = profiles.iter().any(|p| { - p.get("pubkey") - .and_then(|v| v.as_str()) - .is_some_and(|listed| listed.eq_ignore_ascii_case(&pubkey)) - }); - if let (false, Some(found)) = (listed, verified.get(&pubkey)) { - profiles.push(verified_only_profile(&pubkey, found)); - } - } profiles } @@ -149,19 +136,13 @@ fn verified_only_profile(pubkey: &str, verified: &VerifiedProfile) -> serde_json }) } -/// People from a `/profiles/search` page: each person's newest kind:0 and, when +/// People from a `/profiles/search` page: each person's kind:0 and, when /// `authority` signed one, their verified profile, in the relay's order. A /// person who matched only by verified name has no kind:0. -fn search_page_profiles( - events: &[serde_json::Value], - authority: Option<&str>, -) -> Vec { - let verified = authority - .map(|authority| verified_profiles_from_events(events, authority)) - .unwrap_or_default(); +fn search_page_profiles(events: &[serde_json::Value], authority: &str) -> Vec { + let verified = verified_profiles_from_events(events, authority); let mut order: Vec = Vec::new(); - let mut profiles: HashMap)> = - HashMap::new(); + let mut profiles: HashMap> = HashMap::new(); for event in events { let kind = event.get("kind").and_then(|v| v.as_u64()); let pubkey = if kind == Some(0) { @@ -182,13 +163,7 @@ fn search_page_profiles( order.push(pubkey.clone()); } if kind == Some(0) { - let created_at = event - .get("created_at") - .and_then(|v| v.as_u64()) - .unwrap_or(0); - if profiles.get(&pubkey).is_none_or(|(at, _)| created_at > *at) { - profiles.insert(pubkey, (created_at, profile_content(event))); - } + profiles.insert(pubkey, profile_content(event)); } } order @@ -196,7 +171,7 @@ fn search_page_profiles( .filter_map(|pubkey| { let found = verified.get(&pubkey); match profiles.remove(&pubkey) { - Some((_, mut content)) => { + Some(mut content) => { content.insert("pubkey".to_string(), serde_json::json!(pubkey)); if let Some(found) = found { content.insert("verified".to_string(), found.to_json()); @@ -284,13 +259,17 @@ async fn owned_agent_pubkeys_by_name( Ok(owned_agent_pubkeys_from_events(&events, query)) } +/// The object in a kind:0 event's content. kind:0 is user-controlled, so any +/// `verified` key in it is dropped; only a relay-signed kind:30382 sets one. fn profile_content(event: &serde_json::Value) -> serde_json::Map { - event + let mut profile = event .get("content") .and_then(|value| value.as_str()) .and_then(|content| serde_json::from_str::(content).ok()) .and_then(|content| content.as_object().cloned()) - .unwrap_or_default() + .unwrap_or_default(); + profile.remove("verified"); + profile } fn name_search_profiles(events: &[serde_json::Value], query: &str) -> Vec { @@ -428,45 +407,31 @@ fn owner_scoped_profiles( .collect() } -/// Unscoped name search. `POST /profiles/search` matches profile names and, -/// where the community advertises them, verified names, so a person is found -/// by their verified username too. Relays without the endpoint (404) fall back -/// to NIP-50 search over kind:0, filtered to name matches, with verified -/// profiles read for whoever it finds. +/// Unscoped name search. Where the community advertises verified profiles, +/// `POST /profiles/search` matches profile names and verified names (word +/// prefixes), so a person is found by their verified username too. Otherwise +/// NIP-50 search over kind:0, filtered to name substring matches; returns [] +/// if unsupported. async fn search_profiles( client: &BuzzClient, query: &str, ) -> Result, CliError> { - let authority = discover_authority(client).await?; - let body = serde_json::json!({"query": query.trim(), "limit": 100}); - match client.post_json_authed("/profiles/search", &body).await { - Ok(raw) => { - let events: Vec = serde_json::from_str(&raw) - .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; - Ok(search_page_profiles(&events, authority.as_deref())) - } - Err(CliError::Relay { status: 404, .. }) => { - let filter = serde_json::json!({ - "kinds": [0], - "search": query, - "limit": 100 - }); - let raw = client.query(&filter).await?; - let events: Vec = serde_json::from_str(&raw) - .map_err(|e| CliError::Other(format!("failed to parse response: {e}")))?; - let profiles = name_search_profiles(&events, query); - let Some(authority) = authority else { - return Ok(profiles); - }; - let pubkeys: Vec = profiles - .iter() - .filter_map(|p| p.get("pubkey")?.as_str().map(str::to_owned)) - .collect(); - let verified = fetch_verified_profiles(client, &authority, &pubkeys).await?; - Ok(with_verified(profiles, &verified, &[])) - } - Err(e) => Err(e), + let parse = |raw: String| -> Result, CliError> { + serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse response: {e}"))) + }; + if let Some(authority) = discover_authority(client).await? { + let body = serde_json::json!({"query": query.trim(), "limit": 100}); + let raw = client.post_json_authed("/profiles/search", &body).await?; + return Ok(search_page_profiles(&parse(raw)?, &authority)); } + let filter = serde_json::json!({ + "kinds": [0], + "search": query, + "limit": 100 + }); + let events = parse(client.query(&filter).await?)?; + Ok(name_search_profiles(&events, query)) } /// Search for users by name. Owner-scoped searches resolve managed-agent records @@ -1431,22 +1396,6 @@ mod tests { assert_eq!(compact["verified"]["username"], "alice"); } - #[tokio::test] - async fn get_by_pubkey_trusts_only_the_advertised_relay_key() { - let (client, relay) = setup().await; - let authority = Keys::generate(); - let impostor = Keys::generate(); - relay.lock().unwrap().info = advertising(&authority); - let alice = Keys::generate(); - seed_profile(&relay, &alice, r#"{"name":"al"}"#); - seed_verified(&relay, &impostor, &alice, "alice", 100); - - let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) - .await - .unwrap(); - assert!(profiles[0].get("verified").is_none()); - } - #[tokio::test] async fn get_by_pubkey_ignores_verified_profiles_the_community_does_not_advertise() { let (client, relay) = setup().await; @@ -1468,38 +1417,6 @@ mod tests { .all(|q| q["kinds"] != json!([30382]))); } - #[tokio::test] - async fn get_by_pubkey_lists_a_verified_person_who_has_no_profile() { - let (client, relay) = setup().await; - let authority = Keys::generate(); - relay.lock().unwrap().info = advertising(&authority); - let alice = Keys::generate(); - seed_verified(&relay, &authority, &alice, "alice", 100); - - let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) - .await - .unwrap(); - assert_eq!( - profiles, - vec![json!({ - "pubkey": alice.public_key().to_hex(), - "display_name": "Alice", - "verified": verified_json("alice"), - })] - ); - } - - #[tokio::test] - async fn get_fails_rather_than_hide_a_malformed_advertisement() { - let (client, relay) = setup().await; - relay.lock().unwrap().info = json!({ - "self": "00".repeat(32), - "federated_identity": {"public_profile": {"kind": 7}}, - }); - let err = get_profiles(&client, &[]).await.unwrap_err(); - assert!(matches!(err, CliError::Other(_)), "{err:?}"); - } - #[tokio::test] async fn name_search_finds_a_person_by_verified_username() { let (client, relay) = setup().await; @@ -1543,36 +1460,63 @@ mod tests { } #[tokio::test] - async fn name_search_without_verified_profiles_trusts_the_relay_page_as_is() { + async fn name_search_without_advertised_profiles_uses_nip50() { let (client, relay) = setup().await; let alice = Keys::generate(); seed_profile(&relay, &alice, r#"{"name":"alice"}"#); - // A 30382 from an unadvertised community finds nobody. - seed_verified(&relay, &Keys::generate(), &Keys::generate(), "zed", 100); - let events = relay.lock().unwrap().events.clone(); - relay.lock().unwrap().profile_search = Some(json!(events)); + seed_profile(&relay, &Keys::generate(), r#"{"name":"bob"}"#); let found = search_profiles(&client, "alice").await.unwrap(); - assert_eq!(found.len(), 1); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); assert!(found[0].get("verified").is_none()); + assert!(relay.lock().unwrap().profile_searches.is_empty()); } + const FORGED: &str = + r#"{"name":"alice","verified":{"username":"forged","issuer_label":"Fake"}}"#; + #[tokio::test] - async fn name_search_falls_back_to_nip50_on_a_relay_without_profile_search() { + async fn a_verified_object_in_kind0_content_is_never_output() { + // (a) The community does not advertise verified profiles. let (client, relay) = setup().await; + let alice = Keys::generate(); + seed_profile(&relay, &alice, FORGED); + let pubkeys = vec![alice.public_key().to_hex()]; + let profiles = get_profiles(&client, &pubkeys).await.unwrap(); + assert_eq!(profiles[0]["name"], "alice"); + assert!(profiles[0].get("verified").is_none()); + let found = search_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1); + assert!(found[0].get("verified").is_none()); + + // (b) Advertised, but no valid projection exists for the subject. let authority = Keys::generate(); relay.lock().unwrap().info = advertising(&authority); - let alice = Keys::generate(); - seed_profile(&relay, &alice, r#"{"name":"alice"}"#); - seed_profile(&relay, &Keys::generate(), r#"{"name":"bob"}"#); - seed_verified(&relay, &authority, &alice, "alice", 100); + seed_verified(&relay, &Keys::generate(), &alice, "alice", 100); + let profiles = get_profiles(&client, &pubkeys).await.unwrap(); + assert!(profiles[0].get("verified").is_none()); + let events = relay.lock().unwrap().events.clone(); + relay.lock().unwrap().profile_search = Some(json!(events)); + let found = search_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1); + assert!(found[0].get("verified").is_none()); + let compact = compact_profile(&profiles[0], &[]); + assert!(compact.get("verified").is_none()); + // (c) A valid projection replaces the forgery. + seed_verified(&relay, &authority, &alice, "alice", 100); + let profiles = get_profiles(&client, &pubkeys).await.unwrap(); + assert_eq!(profiles[0]["verified"], verified_json("alice")); + let events = relay.lock().unwrap().events.clone(); + relay.lock().unwrap().profile_search = Some(json!(events)); let found = search_profiles(&client, "alice").await.unwrap(); - assert_eq!(found.len(), 1, "{found:?}"); - assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); - assert_eq!(found[0]["verified"]["username"], "alice"); - let queries = relay.lock().unwrap().queries.clone(); - assert_eq!(queries[0]["search"], "alice"); + assert_eq!(found[0]["verified"], verified_json("alice")); + + // The owner-scoped path takes kind:0 content too. + let event = json!({"pubkey": "aa", "content": FORGED, "tags": []}); + let owned = owner_scoped_profiles(&[event], &["aa".to_string()], "bb", "bb"); + assert!(owned[0].get("verified").is_none()); } #[test] diff --git a/crates/buzz-cli/src/commands/verified_profiles.rs b/crates/buzz-cli/src/commands/verified_profiles.rs index d29525ef6b9..3e8f49d70f1 100644 --- a/crates/buzz-cli/src/commands/verified_profiles.rs +++ b/crates/buzz-cli/src/commands/verified_profiles.rs @@ -3,14 +3,12 @@ //! //! A community advertises them in NIP-11 (`federated_identity.public_profile`). //! The only key trusted to sign them is the relay's NIP-11 `self` key, so a -//! kind:30382 signed by anyone else is ignored. Event and projection checks -//! mirror the Buzz mobile client (`verified_profile.dart`). +//! kind:30382 signed by anyone else is ignored. use std::collections::HashMap; use nostr::Event; use serde_json::{json, Value}; -use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; use crate::client::BuzzClient; use crate::commands::agents::normalize_relay_self_hex; @@ -22,10 +20,6 @@ const KIND: u16 = buzz_core::kind::KIND_VERIFIED_PROFILE as u16; /// Subjects per query, keeping each REQ inside relay filter limits. const SUBJECTS_PER_QUERY: usize = 128; -/// Larger events (UTF-16 units of content and every tag element) are dropped -/// before any further work. A valid projection is well under 1 KiB. -const MAX_EVENT_SIZE: usize = 4096; - /// A verified name as the relay last published it. Historical: it records the /// issuer's name-to-key assertion at `verified_at`, never current access. #[derive(Debug, Clone, PartialEq, Eq)] @@ -74,11 +68,7 @@ pub(crate) fn parse_discovery(info: &Value) -> Result, CliError> let (Some(profile), Some(self_hex)) = (profile.as_object(), self_hex) else { return Err(malformed("malformed public_profile discovery")); }; - if profile.get("kind").and_then(Value::as_u64) != Some(u64::from(KIND)) - || !profile - .get("multiple_issuers") - .is_some_and(serde_json::Value::is_boolean) - { + if profile.get("kind").and_then(Value::as_u64) != Some(u64::from(KIND)) { return Err(malformed("malformed public_profile discovery")); } normalize_relay_self_hex(self_hex).map(Some) @@ -128,11 +118,11 @@ pub(crate) async fn fetch_verified_profiles( /// Every valid verified profile among `events`, keyed by subject pubkey. /// -/// Anything not signed by `authority`, not of kind 30382, oversized, or with -/// a bad id or signature is ignored. Per subject the newest event is the head, -/// as for any addressable event; a head that is not a valid active projection -/// (including a retraction) leaves the subject with no verified profile, so a -/// stale older name never resurfaces. +/// Anything not signed by `authority`, not of kind 30382, or with a bad id or +/// signature is ignored. Per subject the newest event is the head, as for any +/// addressable event; a head that is not a valid active projection (including +/// a retraction) leaves the subject with no verified profile, so a stale older +/// name never resurfaces. pub(crate) fn verified_profiles_from_events( events: &[Value], authority: &str, @@ -142,153 +132,64 @@ pub(crate) fn verified_profiles_from_events( let Ok(event) = serde_json::from_value::(raw.clone()) else { continue; }; - let Some(subject) = subject(&event, authority) else { + let Some(subject) = signed_subject(&event, authority) else { continue; }; - if event.verify().is_err() { - continue; - } if heads .get(&subject) - .is_none_or(|current| supersedes(&event, current)) + .is_none_or(|current| event.created_at > current.created_at) { heads.insert(subject, event); } } heads .into_iter() - .filter_map(|(subject, event)| parse_projection(&event, &subject).map(|p| (subject, p))) + .filter_map(|(subject, event)| parse_projection(&event).map(|p| (subject, p))) .collect() } -/// NIP-01 replaceable ordering: the later `created_at` wins; a tie goes to the -/// lower event id. -fn supersedes(candidate: &Event, current: &Event) -> bool { - candidate.created_at > current.created_at - || (candidate.created_at == current.created_at - && candidate.id.to_hex() < current.id.to_hex()) -} - -fn is_lower_hex64(value: &str) -> bool { - value.len() == 64 - && value - .bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) -} - -fn event_size(event: &Event) -> usize { - let mut size = event.content.encode_utf16().count(); - for tag in event.tags.iter() { - size += 1; - for value in tag.as_slice() { - size += value.encode_utf16().count() + 1; - } - } - size -} - -/// The subject a kind:30382 event addresses: its first `d` tag, when the event -/// is by `authority`, within the size bound, and the tag is a lowercase hex -/// pubkey. Projection shape is not checked here. -fn subject(event: &Event, authority: &str) -> Option { - if event.kind.as_u16() != KIND - || event.pubkey.to_hex() != authority - || event_size(event) > MAX_EVENT_SIZE +/// The subject a kind:30382 event addresses (its first `d` tag, a lowercase hex +/// pubkey), when the event is validly signed by `authority`. +fn signed_subject(event: &Event, authority: &str) -> Option { + if event.kind.as_u16() != KIND || event.pubkey.to_hex() != authority || event.verify().is_err() { return None; } - let d = event + let subject = tag_value(event, "d")?; + (subject.len() == 64 + && subject + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) + .then(|| subject.to_owned()) +} + +fn tag_value<'a>(event: &'a Event, name: &str) -> Option<&'a str> { + event .tags .iter() .map(|tag| tag.as_slice()) - .find(|tag| tag.first().map(String::as_str) == Some("d"))?; - d.get(1).filter(|v| is_lower_hex64(v)).cloned() + .find(|tag| tag.first().map(String::as_str) == Some(name)) + .and_then(|tag| tag.get(1)) + .map(String::as_str) } -/// Strictly validate the projection NIP-FI defines: empty content; exactly -/// seven tags (eight with `full_name`), each of two elements with no repeated -/// name; `d` and `p` equal; `active` equal to `true`; well-formed names, -/// username and issuer label; and a `verified_at` no later than `created_at`. -fn parse_projection(event: &Event, subject: &str) -> Option { - if !event.content.is_empty() || !matches!(event.tags.len(), 7 | 8) { - return None; - } - let mut tags: HashMap<&str, &str> = HashMap::new(); - for tag in event.tags.iter() { - let [name, value] = tag.as_slice() else { - return None; - }; - if tags.insert(name, value).is_some() { - return None; - } - } - const REQUIRED: [&str; 7] = [ - "d", - "p", - "active", - "display_name", - "username", - "issuer_label", - "verified_at", - ]; - let full_name = tags.get("full_name").copied(); - if !REQUIRED.iter().all(|name| tags.contains_key(name)) - || tags.len() != REQUIRED.len() + usize::from(full_name.is_some()) - { - return None; - } - let (display_name, username, issuer_label) = - (tags["display_name"], tags["username"], tags["issuer_label"]); - let verified_at = tags["verified_at"]; - if tags["p"] != subject - || tags["active"] != "true" - || !full_name.is_none_or(valid_name) - || !valid_name(display_name) - || !valid_username(username) - || !valid_name(issuer_label) - || verified_at.is_empty() - || !verified_at.bytes().all(|b| b.is_ascii_digit()) - { - return None; - } - let verified_at: u64 = verified_at.parse().ok()?; - if verified_at > event.created_at.as_secs() { +/// Read the NIP-FI projection: `active` must be `true`, `username` well +/// formed, and the names and `verified_at` present. +fn parse_projection(event: &Event) -> Option { + let name = |name| tag_value(event, name).filter(|v| !v.is_empty()); + if tag_value(event, "active") != Some("true") { return None; } + let username = name("username").filter(|u| valid_username(u))?; Some(VerifiedProfile { - display_name: display_name.to_owned(), + display_name: name("display_name")?.to_owned(), username: username.to_owned(), - full_name: full_name.map(str::to_owned), - issuer_label: issuer_label.to_owned(), - verified_at, + full_name: name("full_name").map(str::to_owned), + issuer_label: name("issuer_label")?.to_owned(), + verified_at: name("verified_at")?.parse().ok()?, }) } -/// A name or issuer label: 1 to 64 scalar values in NFC, no control, format, -/// surrogate, private-use, unassigned or line/paragraph separator characters, -/// and no whitespace at either end. -fn valid_name(value: &str) -> bool { - use GeneralCategory::{ - Control, Format, LineSeparator, ParagraphSeparator, PrivateUse, Surrogate, Unassigned, - }; - !value.is_empty() - && value.chars().count() <= 64 - && value.trim() == value - && unicode_normalization::is_nfc(value) - && !value.chars().any(|c| { - matches!( - c.general_category(), - Control - | Format - | Surrogate - | PrivateUse - | Unassigned - | LineSeparator - | ParagraphSeparator - ) - }) -} - /// A username: 1 to 64 characters of lowercase ASCII letters, digits, `.`, `_` or `-`. fn valid_username(value: &str) -> bool { (1..=64).contains(&value.len()) @@ -335,9 +236,8 @@ mod tests { fn discovery_reads_the_relay_key_only_where_advertised() { let key = "ab".repeat(32); let advertised = |profile: Value| json!({"self": key, "federated_identity": {"public_profile": profile}}); - let good = json!({"kind": 30382, "multiple_issuers": false, "searchable": true}); assert_eq!( - parse_discovery(&advertised(good)).unwrap(), + parse_discovery(&advertised(json!({"kind": 30382}))).unwrap(), Some(key.clone()) ); // Not advertised: absent or without `public_profile`. @@ -349,11 +249,10 @@ mod tests { // Advertised but malformed is a failed check, not an absence. for bad in [ advertised(json!(null)), - advertised(json!({"kind": 30382})), - advertised(json!({"kind": 1, "multiple_issuers": true})), - advertised(json!({"kind": 30382, "multiple_issuers": "yes"})), - json!({"federated_identity": {"public_profile": {"kind": 30382, "multiple_issuers": true}}}), - json!({"self": "nothex", "federated_identity": {"public_profile": {"kind": 30382, "multiple_issuers": true}}}), + advertised(json!({})), + advertised(json!({"kind": 1})), + json!({"federated_identity": {"public_profile": {"kind": 30382}}}), + json!({"self": "nothex", "federated_identity": {"public_profile": {"kind": 30382}}}), json!({"self": key, "federated_identity": "on"}), ] { assert!(parse_discovery(&bad).is_err(), "{bad}"); @@ -363,20 +262,11 @@ mod tests { #[test] fn a_relay_signed_active_projection_is_verified() { let relay = Keys::generate(); + let authority = relay.public_key().to_hex(); let subject = Keys::generate().public_key().to_hex(); let tags = tag_pairs(&subject, &[("full_name", "Alice Example")]); let event = sign(&relay, 30382, "", &tags, AT); - let found = verified_profiles_from_events(&[event], &relay.public_key().to_hex()); - assert_eq!( - found[&subject], - VerifiedProfile { - display_name: "alice".into(), - username: "alice".into(), - full_name: Some("Alice Example".into()), - issuer_label: "Example".into(), - verified_at: 1_799_999_999, - } - ); + let found = verified_profiles_from_events(&[event], &authority); assert_eq!( found[&subject].to_json(), json!({ @@ -387,14 +277,9 @@ mod tests { "verified_at": 1_799_999_999, }) ); - } - - #[test] - fn full_name_is_omitted_when_absent() { - let relay = Keys::generate(); - let subject = Keys::generate().public_key().to_hex(); + // `full_name` is optional and omitted when absent. let event = sign(&relay, 30382, "", &tag_pairs(&subject, &[]), AT); - let found = verified_profiles_from_events(&[event], &relay.public_key().to_hex()); + let found = verified_profiles_from_events(&[event], &authority); assert!(found[&subject].to_json().get("full_name").is_none()); } @@ -419,44 +304,33 @@ mod tests { } #[test] - fn malformed_projections_are_ignored() { + fn unusable_projections_are_ignored() { let relay = Keys::generate(); let authority = relay.public_key().to_hex(); let subject = Keys::generate().public_key().to_hex(); - let other = Keys::generate().public_key().to_hex(); - let long = "a".repeat(65); let cases: Vec<(&str, Vec<(&str, &str)>)> = vec![ - ("content", vec![]), ("retracted", vec![("active", "false")]), - ("p mismatch", vec![("p", &other)]), ("bad username", vec![("username", "Alice")]), ("empty username", vec![("username", "")]), - ("padded name", vec![("display_name", " alice")]), - ("control name", vec![("display_name", "al\nice")]), - ("bidi name", vec![("full_name", "Al\u{202e}ice")]), - ("non-NFC name", vec![("full_name", "e\u{301}")]), - ("long name", vec![("display_name", &long)]), - ("future verified_at", vec![("verified_at", "1800000001")]), - ("signed verified_at", vec![("verified_at", "+5")]), - ("extra tag", vec![("extra", "x")]), + ("empty display_name", vec![("display_name", "")]), + ("non-numeric verified_at", vec![("verified_at", "soon")]), ]; for (label, overrides) in cases { let mut tags = tag_pairs(&subject, &[]); for (key, value) in &overrides { - match tags.iter_mut().find(|(k, _)| k == key) { - Some(existing) => existing.1 = value, - None => tags.push((key, value)), - } + tags.iter_mut().find(|(k, _)| k == key).unwrap().1 = value; } - let content = if label == "content" { "hi" } else { "" }; - let event = sign(&relay, 30382, content, &tags, AT); + let event = sign(&relay, 30382, "", &tags, AT); assert!( verified_profiles_from_events(&[event], &authority).is_empty(), "{label}" ); } - let repeated = tag_pairs(&subject, &[("username", "bob")]); - let event = sign(&relay, 30382, "", &repeated, AT); + let missing: Vec<_> = tag_pairs(&subject, &[]) + .into_iter() + .filter(|(k, _)| *k != "issuer_label") + .collect(); + let event = sign(&relay, 30382, "", &missing, AT); assert!(verified_profiles_from_events(&[event], &authority).is_empty()); } diff --git a/crates/buzz-cli/src/lib.rs b/crates/buzz-cli/src/lib.rs index af91ca566cf..0f325064b1c 100644 --- a/crates/buzz-cli/src/lib.rs +++ b/crates/buzz-cli/src/lib.rs @@ -1379,8 +1379,8 @@ pub enum UsersCmd { /// User pubkey(s) to look up (64-char hex). Omit for your own profile #[arg(long = "pubkey")] pubkeys: Vec, - /// Search by profile name or, where advertised, verified name - /// (e.g. a verified username). Case-insensitive; matches word prefixes + /// Search by display name (case-insensitive substring match). Where + /// verified profiles are advertised: profile or verified name, by word prefix #[arg(long = "name")] name: Option, /// Scope an exact-name agent lookup to its owner (`me`, hex, or npub) From c3760e0be08e8deb62d1acfbe52a75bb7011b8c7 Mon Sep 17 00:00:00 2001 From: damienrj Date: Wed, 18 Nov 2026 09:27:53 -0800 Subject: [PATCH 3/6] fix(cli): keep users get output when the verified check fails Warn on stderr instead of failing --pubkey lookups when relay info can't be read, and send --name queries over 100 characters to NIP-50 search. Signed-off-by: damienrj --- crates/buzz-cli/src/commands/users.rs | 77 +++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 9 deletions(-) diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index d2af3dc674d..784a6bada3a 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -10,6 +10,9 @@ use super::verified_profiles::{ }; use std::collections::HashMap; +/// Longest query `POST /profiles/search` accepts, in characters. +const PROFILE_SEARCH_MAX_CHARS: usize = 100; + // TODO(phase-4): Replace raw nostr::EventBuilder usage in cmd_set_presence with buzz-sdk builder /// Get user profiles (kind:0 metadata events). @@ -97,16 +100,36 @@ async fn get_profiles( Some(profile) }) .collect(); - let verified = match discover_authority(client).await? { - Some(authority) => { - let requested: Vec = authors.iter().map(|a| a.to_string()).collect(); - fetch_verified_profiles(client, &authority, &requested).await? + let requested: Vec = authors.iter().map(|a| a.to_string()).collect(); + let verified = match verified_for(client, &requested).await { + Ok(verified) => verified, + Err(e) => { + // The kind:0 output stands on its own; flag the missing check on + // stderr so it is never read as "not verified". + eprintln!( + "{}", + serde_json::json!({ + "warning": "verified_profiles_unavailable", + "message": e.to_string(), + }) + ); + HashMap::new() } - None => HashMap::new(), }; Ok(with_verified(profiles, &verified)) } +/// Verified profiles for `pubkeys`; empty where the community advertises none. +async fn verified_for( + client: &BuzzClient, + pubkeys: &[String], +) -> Result, CliError> { + match discover_authority(client).await? { + Some(authority) => fetch_verified_profiles(client, &authority, pubkeys).await, + None => Ok(HashMap::new()), + } +} + /// Attach each profile's `verified` object where a relay-signed one exists. fn with_verified( mut profiles: Vec, @@ -409,9 +432,9 @@ fn owner_scoped_profiles( /// Unscoped name search. Where the community advertises verified profiles, /// `POST /profiles/search` matches profile names and verified names (word -/// prefixes), so a person is found by their verified username too. Otherwise -/// NIP-50 search over kind:0, filtered to name substring matches; returns [] -/// if unsupported. +/// prefixes), so a person is found by their verified username too. Otherwise, +/// or for a query longer than that endpoint accepts, NIP-50 search over +/// kind:0, filtered to name substring matches; returns [] if unsupported. async fn search_profiles( client: &BuzzClient, query: &str, @@ -420,7 +443,12 @@ async fn search_profiles( serde_json::from_str(&raw) .map_err(|e| CliError::Other(format!("failed to parse response: {e}"))) }; - if let Some(authority) = discover_authority(client).await? { + let authority = if query.trim().chars().count() <= PROFILE_SEARCH_MAX_CHARS { + discover_authority(client).await? + } else { + None + }; + if let Some(authority) = authority { let body = serde_json::json!({"query": query.trim(), "limit": 100}); let raw = client.post_json_authed("/profiles/search", &body).await?; return Ok(search_page_profiles(&parse(raw)?, &authority)); @@ -1473,6 +1501,37 @@ mod tests { assert!(relay.lock().unwrap().profile_searches.is_empty()); } + #[tokio::test] + async fn get_by_pubkey_keeps_profiles_when_the_verified_check_fails() { + let (client, relay) = setup().await; + relay.lock().unwrap().info = json!({"federated_identity": "malformed"}); + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"al"}"#); + + let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) + .await + .unwrap(); + assert_eq!(profiles.len(), 1); + assert_eq!(profiles[0]["name"], "al"); + assert!(profiles[0].get("verified").is_none()); + } + + #[tokio::test] + async fn name_search_longer_than_profile_search_accepts_uses_nip50() { + let (client, relay) = setup().await; + relay.lock().unwrap().info = advertising(&Keys::generate()); + let long = "a".repeat(101); + seed_profile( + &relay, + &Keys::generate(), + &json!({"name": long}).to_string(), + ); + + let found = search_profiles(&client, &long).await.unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(relay.lock().unwrap().profile_searches.is_empty()); + } + const FORGED: &str = r#"{"name":"alice","verified":{"username":"forged","issuer_label":"Fake"}}"#; From 0db75cbd4381c43bab5b2d0abbc04d70377c1422 Mon Sep 17 00:00:00 2001 From: damienrj Date: Wed, 18 Nov 2026 11:21:20 -0800 Subject: [PATCH 4/6] fix(cli): find verified-only people by pubkey and honor searchable users get --pubkey returns requested people who have a verified profile but no kind:0. --name uses /profiles/search only when public_profile is searchable, otherwise NIP-50 with verified profiles attached. Restore the NIP-FI projection checks: empty content, exact tag set, p equal to d, verified_at not after created_at, well-formed names, and the lower id winning a same-second tie. Signed-off-by: damienrj --- crates/buzz-cli/README.md | 2 +- crates/buzz-cli/src/commands/users.rs | 127 ++++++++++--- .../src/commands/verified_profiles.rs | 169 +++++++++++++++--- 3 files changed, 256 insertions(+), 42 deletions(-) diff --git a/crates/buzz-cli/README.md b/crates/buzz-cli/README.md index 9a4688f7b0e..ab8f995be52 100644 --- a/crates/buzz-cli/README.md +++ b/crates/buzz-cli/README.md @@ -119,7 +119,7 @@ buzz users get --pubkey --pubkey # batch (max 200) buzz users get --name Honey --owner me # exact-name lookup in your managed agents # Where the community advertises verified profiles, `users get` adds a "verified" # object ({username, display_name, full_name?, issuer_label, verified_at}) from a -# kind:30382 signed by the relay's NIP-11 `self` key, and --name also finds verified usernames. +# kind:30382 signed by the relay's NIP-11 `self` key. Where it is also `searchable`, --name finds verified usernames. buzz users set-presence --status online buzz users set-status --text "heads down on the CLI" --emoji "🚀" buzz users set-status --text "lunch" --emoji "🥪" --expires 1h # clears itself; also a unix time diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index 784a6bada3a..91923fc2aad 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -66,7 +66,8 @@ pub async fn cmd_get_users( } /// kind:0 profiles for `pubkeys` (our own when empty), each with its verified -/// profile where one exists. +/// profile where one exists, then any requested person who has a verified +/// profile but no kind:0. async fn get_profiles( client: &BuzzClient, pubkeys: &[String], @@ -116,7 +117,21 @@ async fn get_profiles( HashMap::new() } }; - Ok(with_verified(profiles, &verified)) + let mut profiles = with_verified(profiles, &verified); + // A requested person with a verified profile but no kind:0 is still found, + // as a name search would find them. + let mut found: Vec = profiles + .iter() + .filter_map(|p| p.get("pubkey").and_then(|v| v.as_str())) + .map(str::to_ascii_lowercase) + .collect(); + for pubkey in requested.iter().map(|p| p.to_ascii_lowercase()) { + if let (false, Some(v)) = (found.contains(&pubkey), verified.get(&pubkey)) { + profiles.push(verified_only_profile(&pubkey, v)); + found.push(pubkey); + } + } + Ok(profiles) } /// Verified profiles for `pubkeys`; empty where the community advertises none. @@ -125,7 +140,7 @@ async fn verified_for( pubkeys: &[String], ) -> Result, CliError> { match discover_authority(client).await? { - Some(authority) => fetch_verified_profiles(client, &authority, pubkeys).await, + Some(authority) => fetch_verified_profiles(client, &authority.pubkey, pubkeys).await, None => Ok(HashMap::new()), } } @@ -430,11 +445,12 @@ fn owner_scoped_profiles( .collect() } -/// Unscoped name search. Where the community advertises verified profiles, -/// `POST /profiles/search` matches profile names and verified names (word -/// prefixes), so a person is found by their verified username too. Otherwise, -/// or for a query longer than that endpoint accepts, NIP-50 search over -/// kind:0, filtered to name substring matches; returns [] if unsupported. +/// Unscoped name search. Where the community advertises searchable verified +/// profiles, `POST /profiles/search` matches profile names and verified names +/// (word prefixes), so a person is found by their verified username too. +/// Otherwise, or for a query longer than that endpoint accepts, NIP-50 search +/// over kind:0, filtered to name substring matches (returns [] if +/// unsupported), with verified profiles attached where advertised. async fn search_profiles( client: &BuzzClient, query: &str, @@ -443,15 +459,12 @@ async fn search_profiles( serde_json::from_str(&raw) .map_err(|e| CliError::Other(format!("failed to parse response: {e}"))) }; - let authority = if query.trim().chars().count() <= PROFILE_SEARCH_MAX_CHARS { - discover_authority(client).await? - } else { - None - }; - if let Some(authority) = authority { + let authority = discover_authority(client).await?; + let fits = query.trim().chars().count() <= PROFILE_SEARCH_MAX_CHARS; + if let Some(authority) = authority.as_ref().filter(|a| a.searchable && fits) { let body = serde_json::json!({"query": query.trim(), "limit": 100}); let raw = client.post_json_authed("/profiles/search", &body).await?; - return Ok(search_page_profiles(&parse(raw)?, &authority)); + return Ok(search_page_profiles(&parse(raw)?, &authority.pubkey)); } let filter = serde_json::json!({ "kinds": [0], @@ -459,7 +472,16 @@ async fn search_profiles( "limit": 100 }); let events = parse(client.query(&filter).await?)?; - Ok(name_search_profiles(&events, query)) + let profiles = name_search_profiles(&events, query); + let Some(authority) = authority else { + return Ok(profiles); + }; + let pubkeys: Vec = profiles + .iter() + .filter_map(|p| p.get("pubkey").and_then(|v| v.as_str()).map(str::to_owned)) + .collect(); + let verified = fetch_verified_profiles(client, &authority.pubkey, &pubkeys).await?; + Ok(with_verified(profiles, &verified)) } /// Search for users by name. Owner-scoped searches resolve managed-agent records @@ -1042,13 +1064,14 @@ mod tests { } async fn setup() -> (BuzzClient, Shared) { + setup_as(Keys::generate()).await + } + + async fn setup_as(keys: Keys) -> (BuzzClient, Shared) { let relay = Shared::default(); let url = fake_relay(relay.clone()).await; - let client = BuzzClient::new( - url, - crate::credentials::Credentials::from_keys(Keys::generate()), - ) - .unwrap(); + let client = + BuzzClient::new(url, crate::credentials::Credentials::from_keys(keys)).unwrap(); (client, relay) } @@ -1532,6 +1555,68 @@ mod tests { assert!(relay.lock().unwrap().profile_searches.is_empty()); } + #[tokio::test] + async fn get_by_pubkey_returns_people_with_only_a_verified_profile() { + let me = Keys::generate(); + let (client, relay) = setup_as(me.clone()).await; + let authority = Keys::generate(); + relay.lock().unwrap().info = advertising(&authority); + let alice = Keys::generate(); + let bob = Keys::generate(); + seed_profile(&relay, &bob, r#"{"name":"bob"}"#); + seed_verified(&relay, &authority, &alice, "alice", 100); + let alice_hex = alice.public_key().to_hex(); + + // A single key. + let profiles = get_profiles(&client, std::slice::from_ref(&alice_hex)) + .await + .unwrap(); + assert_eq!(profiles.len(), 1, "{profiles:?}"); + assert_eq!(profiles[0]["pubkey"], alice_hex); + assert_eq!(profiles[0]["verified"], verified_json("alice")); + + // A batch: kind:0 people first, then verified-only ones, once each. + let batch = vec![ + alice_hex.clone(), + bob.public_key().to_hex(), + alice_hex.to_uppercase(), + ]; + let profiles = get_profiles(&client, &batch).await.unwrap(); + let pubkeys: Vec<&str> = profiles + .iter() + .map(|p| p["pubkey"].as_str().unwrap()) + .collect(); + assert_eq!(pubkeys, [bob.public_key().to_hex(), alice_hex.clone()]); + + // The default lookup of your own profile. + seed_verified(&relay, &authority, &me, "me", 100); + let profiles = get_profiles(&client, &[]).await.unwrap(); + assert_eq!(profiles.len(), 1, "{profiles:?}"); + assert_eq!(profiles[0]["verified"]["username"], "me"); + } + + #[tokio::test] + async fn name_search_on_a_relay_without_searchable_profiles_uses_nip50() { + let (client, relay) = setup().await; + let authority = Keys::generate(); + let mut info = advertising(&authority); + info["federated_identity"]["public_profile"] + .as_object_mut() + .unwrap() + .remove("searchable"); + relay.lock().unwrap().info = info; + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"alice"}"#); + seed_verified(&relay, &authority, &alice, "alice", 100); + relay.lock().unwrap().profile_search = Some(json!([])); + + let found = search_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); + assert_eq!(found[0]["verified"], verified_json("alice")); + assert!(relay.lock().unwrap().profile_searches.is_empty()); + } + const FORGED: &str = r#"{"name":"alice","verified":{"username":"forged","issuer_label":"Fake"}}"#; diff --git a/crates/buzz-cli/src/commands/verified_profiles.rs b/crates/buzz-cli/src/commands/verified_profiles.rs index 3e8f49d70f1..d82684049ff 100644 --- a/crates/buzz-cli/src/commands/verified_profiles.rs +++ b/crates/buzz-cli/src/commands/verified_profiles.rs @@ -47,13 +47,22 @@ impl VerifiedProfile { } } +/// Where a community publishes verified profiles. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Authority { + /// The relay key that signs them. + pub pubkey: String, + /// `public_profile.searchable`: `POST /profiles/search` matches verified names. + pub searchable: bool, +} + /// Read the relay key that signs verified profiles from a NIP-11 document. /// /// `Ok(None)`: the community does not advertise verified profiles, so every /// kind:30382 is ignored. A malformed advertisement is an error rather than /// "no verified profiles", so an agent never reads a failed check as an /// authoritative absence. -pub(crate) fn parse_discovery(info: &Value) -> Result, CliError> { +pub(crate) fn parse_discovery(info: &Value) -> Result, CliError> { let malformed = |what: &str| CliError::Other(format!("relay info document: {what}")); let Some(federated) = info.get("federated_identity") else { return Ok(None); @@ -71,11 +80,14 @@ pub(crate) fn parse_discovery(info: &Value) -> Result, CliError> if profile.get("kind").and_then(Value::as_u64) != Some(u64::from(KIND)) { return Err(malformed("malformed public_profile discovery")); } - normalize_relay_self_hex(self_hex).map(Some) + Ok(Some(Authority { + pubkey: normalize_relay_self_hex(self_hex)?, + searchable: profile.get("searchable") == Some(&Value::Bool(true)), + })) } /// The key that signs this community's verified profiles, if it advertises any. -pub(crate) async fn discover_authority(client: &BuzzClient) -> Result, CliError> { +pub(crate) async fn discover_authority(client: &BuzzClient) -> Result, CliError> { let raw = client .get_public("/") .await @@ -120,7 +132,7 @@ pub(crate) async fn fetch_verified_profiles( /// /// Anything not signed by `authority`, not of kind 30382, or with a bad id or /// signature is ignored. Per subject the newest event is the head, as for any -/// addressable event; a head that is not a valid active projection (including +/// addressable event (the lower id breaks a same-second tie); a head that is not a valid active projection (including /// a retraction) leaves the subject with no verified profile, so a stale older /// name never resurfaces. pub(crate) fn verified_profiles_from_events( @@ -135,10 +147,11 @@ pub(crate) fn verified_profiles_from_events( let Some(subject) = signed_subject(&event, authority) else { continue; }; - if heads - .get(&subject) - .is_none_or(|current| event.created_at > current.created_at) - { + // Newest wins; the lower id breaks a same-second tie. + if heads.get(&subject).is_none_or(|current| { + event.created_at > current.created_at + || (event.created_at == current.created_at && event.id < current.id) + }) { heads.insert(subject, event); } } @@ -173,23 +186,72 @@ fn tag_value<'a>(event: &'a Event, name: &str) -> Option<&'a str> { .map(String::as_str) } -/// Read the NIP-FI projection: `active` must be `true`, `username` well -/// formed, and the names and `verified_at` present. +/// Tags a projection carries, each exactly once; `full_name` is optional. +const PROJECTION_TAGS: [&str; 7] = [ + "d", + "p", + "active", + "display_name", + "username", + "issuer_label", + "verified_at", +]; + +/// Read the NIP-FI projection as the spec and the mobile client do: empty +/// content; exactly the projection tags, each once with one value; `p` equal +/// to `d`; `active` `true`; well-formed names; and a decimal `verified_at` no +/// later than `created_at`. Anything else is not a verified profile. fn parse_projection(event: &Event) -> Option { - let name = |name| tag_value(event, name).filter(|v| !v.is_empty()); - if tag_value(event, "active") != Some("true") { + if !event.content.is_empty() { + return None; + } + let mut tags: HashMap<&str, &str> = HashMap::new(); + for tag in event.tags.iter().map(|tag| tag.as_slice()) { + let [name, value] = tag else { + return None; + }; + let known = PROJECTION_TAGS.contains(&name.as_str()) || name == "full_name"; + if !known || tags.insert(name.as_str(), value.as_str()).is_some() { + return None; + } + } + let get = |name| tags.get(name).copied(); + if !PROJECTION_TAGS.iter().all(|name| tags.contains_key(name)) + || get("p") != get("d") + || get("active") != Some("true") + { + return None; + } + let name = |name| get(name).filter(|v| valid_name(v)); + let full_name = match get("full_name") { + Some(full_name) => Some(valid_name(full_name).then_some(full_name)?), + None => None, + }; + let verified_at = get("verified_at")?; + if verified_at.is_empty() || !verified_at.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let verified_at: u64 = verified_at.parse().ok()?; + if verified_at > event.created_at.as_secs() { return None; } - let username = name("username").filter(|u| valid_username(u))?; Some(VerifiedProfile { display_name: name("display_name")?.to_owned(), - username: username.to_owned(), - full_name: name("full_name").map(str::to_owned), + username: get("username").filter(|u| valid_username(u))?.to_owned(), + full_name: full_name.map(str::to_owned), issuer_label: name("issuer_label")?.to_owned(), - verified_at: name("verified_at")?.parse().ok()?, + verified_at, }) } +/// Display text: 1 to 64 characters, no surrounding whitespace, no control +/// characters. +fn valid_name(value: &str) -> bool { + (1..=64).contains(&value.chars().count()) + && value.trim() == value + && !value.chars().any(char::is_control) +} + /// A username: 1 to 64 characters of lowercase ASCII letters, digits, `.`, `_` or `-`. fn valid_username(value: &str) -> bool { (1..=64).contains(&value.len()) @@ -236,10 +298,12 @@ mod tests { fn discovery_reads_the_relay_key_only_where_advertised() { let key = "ab".repeat(32); let advertised = |profile: Value| json!({"self": key, "federated_identity": {"public_profile": profile}}); - assert_eq!( - parse_discovery(&advertised(json!({"kind": 30382}))).unwrap(), - Some(key.clone()) - ); + let found = |profile| parse_discovery(&advertised(profile)).unwrap().unwrap(); + assert_eq!(found(json!({"kind": 30382})).pubkey, key); + // `searchable` must be `true` for profile search to match verified names. + assert!(!found(json!({"kind": 30382})).searchable); + assert!(!found(json!({"kind": 30382, "searchable": "yes"})).searchable); + assert!(found(json!({"kind": 30382, "searchable": true})).searchable); // Not advertised: absent or without `public_profile`. assert_eq!(parse_discovery(&json!({"self": key})).unwrap(), None); assert_eq!( @@ -314,6 +378,17 @@ mod tests { ("empty username", vec![("username", "")]), ("empty display_name", vec![("display_name", "")]), ("non-numeric verified_at", vec![("verified_at", "soon")]), + ("signed verified_at", vec![("verified_at", "+1")]), + ( + "verified_at after created_at", + vec![("verified_at", "1800000001")], + ), + ("p is not d", vec![("p", "00")]), + ("padded display_name", vec![("display_name", " alice")]), + ( + "control char in issuer_label", + vec![("issuer_label", "Ex\u{7}ample")], + ), ]; for (label, overrides) in cases { let mut tags = tag_pairs(&subject, &[]); @@ -332,6 +407,60 @@ mod tests { .collect(); let event = sign(&relay, 30382, "", &missing, AT); assert!(verified_profiles_from_events(&[event], &authority).is_empty()); + + // Content, an unknown or repeated tag, or a tag with more than one value. + let content = sign(&relay, 30382, "hi", &tag_pairs(&subject, &[]), AT); + let extra = sign(&relay, 30382, "", &tag_pairs(&subject, &[("x", "1")]), AT); + let repeated = sign( + &relay, + 30382, + "", + &tag_pairs(&subject, &[("username", "bob")]), + AT, + ); + let mut tags: Vec = tag_pairs(&subject, &[]) + .iter() + .map(|(k, v)| Tag::parse([*k, *v]).unwrap()) + .collect(); + tags.push(Tag::parse(["full_name", "Alice", "extra"]).unwrap()); + let long_tag = EventBuilder::new(Kind::Custom(30382), "") + .tags(tags) + .custom_created_at(Timestamp::from(AT)) + .sign_with_keys(&relay) + .unwrap(); + let long_tag = serde_json::to_value(long_tag).unwrap(); + for (label, event) in [ + ("content", content), + ("extra", extra), + ("repeated", repeated), + ("long tag", long_tag), + ] { + assert!( + verified_profiles_from_events(&[event], &authority).is_empty(), + "{label}" + ); + } + } + + #[test] + fn the_lower_id_wins_a_same_second_tie() { + let relay = Keys::generate(); + let authority = relay.public_key().to_hex(); + let subject = Keys::generate().public_key().to_hex(); + let mut events: Vec = ["alice", "alice2"] + .iter() + .map(|username| { + let mut tags = tag_pairs(&subject, &[]); + tags[4] = ("username", username); + sign(&relay, 30382, "", &tags, AT) + }) + .collect(); + events.sort_by_key(|e| e["id"].as_str().unwrap().to_owned()); + let lower = events[0]["tags"][4][1].as_str().unwrap().to_owned(); + for order in [events.clone(), events.into_iter().rev().collect()] { + let found = verified_profiles_from_events(&order, &authority); + assert_eq!(found[&subject].username, lower); + } } #[test] From 39ba821dda3e1f0fa02596fd4cb5f59cb603c772 Mon Sep 17 00:00:00 2001 From: damienrj Date: Wed, 18 Nov 2026 11:29:39 -0800 Subject: [PATCH 5/6] test(cli): pin the verified check warning and search length limit Signed-off-by: damienrj --- crates/buzz-cli/src/commands/users.rs | 110 ++++++++++++++++++-------- 1 file changed, 79 insertions(+), 31 deletions(-) diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index 91923fc2aad..a5237c4ad23 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -68,10 +68,25 @@ pub async fn cmd_get_users( /// kind:0 profiles for `pubkeys` (our own when empty), each with its verified /// profile where one exists, then any requested person who has a verified /// profile but no kind:0. +/// +/// A failed verified-profile check never drops the kind:0 output; it is +/// reported as a warning on stderr so it is never read as "not verified". async fn get_profiles( client: &BuzzClient, pubkeys: &[String], ) -> Result, CliError> { + let (profiles, warning) = lookup_profiles(client, pubkeys).await?; + if let Some(warning) = warning { + eprintln!("{warning}"); + } + Ok(profiles) +} + +/// [`get_profiles`] with its warning returned instead of printed. +async fn lookup_profiles( + client: &BuzzClient, + pubkeys: &[String], +) -> Result<(Vec, Option), CliError> { let my_pk = client.public_key().to_hex(); let authors: Vec<&str> = if pubkeys.is_empty() { vec![my_pk.as_str()] @@ -102,20 +117,15 @@ async fn get_profiles( }) .collect(); let requested: Vec = authors.iter().map(|a| a.to_string()).collect(); - let verified = match verified_for(client, &requested).await { - Ok(verified) => verified, - Err(e) => { - // The kind:0 output stands on its own; flag the missing check on - // stderr so it is never read as "not verified". - eprintln!( - "{}", - serde_json::json!({ - "warning": "verified_profiles_unavailable", - "message": e.to_string(), - }) - ); - HashMap::new() - } + let (verified, warning) = match verified_for(client, &requested).await { + Ok(verified) => (verified, None), + Err(e) => ( + HashMap::new(), + Some(serde_json::json!({ + "warning": "verified_profiles_unavailable", + "message": e.to_string(), + })), + ), }; let mut profiles = with_verified(profiles, &verified); // A requested person with a verified profile but no kind:0 is still found, @@ -131,7 +141,7 @@ async fn get_profiles( found.push(pubkey); } } - Ok(profiles) + Ok((profiles, warning)) } /// Verified profiles for `pubkeys`; empty where the community advertises none. @@ -954,9 +964,9 @@ pub async fn dispatch( #[cfg(test)] mod tests { use super::{ - compact_profile, get_profiles, owned_agent_pubkeys_from_events, owner_scoped_profiles, - owner_verification, parse_expiration_tag, parse_expiry, presence_subject, publish_status, - read_statuses, search_profiles, + compact_profile, get_profiles, lookup_profiles, owned_agent_pubkeys_from_events, + owner_scoped_profiles, owner_verification, parse_expiration_tag, parse_expiry, + presence_subject, publish_status, read_statuses, search_profiles, }; use crate::client::BuzzClient; use crate::error::CliError; @@ -975,6 +985,8 @@ mod tests { events: Vec, queries: Vec, raw_query_response: Option, + /// Answer queries for this kind with invalid JSON. + broken_kind: Option, /// NIP-11 document served at `/`. info: Value, /// Body of `POST /profiles/search`; `None` answers 404 like an older relay. @@ -1000,6 +1012,11 @@ mod tests { if let Some(raw) = relay.raw_query_response.clone() { return raw; } + if relay.broken_kind.is_some() + && filter["kinds"][0].as_u64() == relay.broken_kind + { + return "not json".to_string(); + } let kind = &filter["kinds"][0]; let matching: Vec = relay .events @@ -1525,31 +1542,62 @@ mod tests { } #[tokio::test] - async fn get_by_pubkey_keeps_profiles_when_the_verified_check_fails() { - let (client, relay) = setup().await; - relay.lock().unwrap().info = json!({"federated_identity": "malformed"}); + async fn get_by_pubkey_keeps_profiles_and_warns_when_the_verified_check_fails() { let alice = Keys::generate(); - seed_profile(&relay, &alice, r#"{"name":"al"}"#); + let pubkeys = vec![alice.public_key().to_hex()]; + // Discovery fails (malformed NIP-11), or the kind:30382 query does. + for broken_lookup in [false, true] { + let (client, relay) = setup().await; + relay.lock().unwrap().info = if broken_lookup { + advertising(&Keys::generate()) + } else { + json!({"federated_identity": "malformed"}) + }; + relay.lock().unwrap().broken_kind = broken_lookup.then_some(30382); + seed_profile(&relay, &alice, r#"{"name":"al"}"#); + + let (profiles, warning) = lookup_profiles(&client, &pubkeys).await.unwrap(); + assert_eq!(profiles.len(), 1, "{broken_lookup}"); + assert_eq!(profiles[0]["name"], "al"); + assert!(profiles[0].get("verified").is_none()); + let warning = warning.expect("a failed check is reported"); + assert_eq!(warning["warning"], "verified_profiles_unavailable"); + assert!(warning["message"].as_str().is_some_and(|m| !m.is_empty())); + } - let profiles = get_profiles(&client, &[alice.public_key().to_hex()]) - .await - .unwrap(); - assert_eq!(profiles.len(), 1); - assert_eq!(profiles[0]["name"], "al"); - assert!(profiles[0].get("verified").is_none()); + // A working check reports nothing. + let (client, relay) = setup().await; + relay.lock().unwrap().info = advertising(&Keys::generate()); + seed_profile(&relay, &alice, r#"{"name":"al"}"#); + let (_, warning) = lookup_profiles(&client, &pubkeys).await.unwrap(); + assert!(warning.is_none()); } #[tokio::test] - async fn name_search_longer_than_profile_search_accepts_uses_nip50() { + async fn name_search_uses_profile_search_up_to_its_character_limit() { + // Counted in characters after trimming, as the relay counts them. + let within = [ + "a".repeat(100), + "é".repeat(100), + format!(" {} ", "a".repeat(100)), + ]; + for query in within { + let (client, relay) = setup().await; + relay.lock().unwrap().info = advertising(&Keys::generate()); + relay.lock().unwrap().profile_search = Some(json!([])); + search_profiles(&client, &query).await.unwrap(); + let searches = relay.lock().unwrap().profile_searches.clone(); + assert_eq!(searches, vec![json!({"query": query.trim(), "limit": 100})]); + } + let (client, relay) = setup().await; relay.lock().unwrap().info = advertising(&Keys::generate()); - let long = "a".repeat(101); + let long = "é".repeat(101); seed_profile( &relay, &Keys::generate(), &json!({"name": long}).to_string(), ); - let found = search_profiles(&client, &long).await.unwrap(); assert_eq!(found.len(), 1, "{found:?}"); assert!(relay.lock().unwrap().profile_searches.is_empty()); From 24a8cc6bb229ed9807d9a207295925752c25b468 Mon Sep 17 00:00:00 2001 From: damienrj Date: Wed, 18 Nov 2026 14:04:49 -0800 Subject: [PATCH 6/6] fix(cli): warn instead of failing --name when the verified check fails Matches the --pubkey path: kind:0 matches are kept and a verified_profiles_unavailable warning goes to stderr. Document that valid_name is looser than the relay's NFC and category rules. Signed-off-by: damienrj --- crates/buzz-cli/src/commands/users.rs | 86 +++++++++++++++---- .../src/commands/verified_profiles.rs | 14 ++- 2 files changed, 80 insertions(+), 20 deletions(-) diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index a5237c4ad23..2e1dca42534 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -119,13 +119,7 @@ async fn lookup_profiles( let requested: Vec = authors.iter().map(|a| a.to_string()).collect(); let (verified, warning) = match verified_for(client, &requested).await { Ok(verified) => (verified, None), - Err(e) => ( - HashMap::new(), - Some(serde_json::json!({ - "warning": "verified_profiles_unavailable", - "message": e.to_string(), - })), - ), + Err(e) => (HashMap::new(), Some(verified_unavailable(&e))), }; let mut profiles = with_verified(profiles, &verified); // A requested person with a verified profile but no kind:0 is still found, @@ -144,6 +138,14 @@ async fn lookup_profiles( Ok((profiles, warning)) } +/// The stderr warning for a verified-profile check that could not run. +fn verified_unavailable(error: &CliError) -> serde_json::Value { + serde_json::json!({ + "warning": "verified_profiles_unavailable", + "message": error.to_string(), + }) +} + /// Verified profiles for `pubkeys`; empty where the community advertises none. async fn verified_for( client: &BuzzClient, @@ -460,21 +462,37 @@ fn owner_scoped_profiles( /// (word prefixes), so a person is found by their verified username too. /// Otherwise, or for a query longer than that endpoint accepts, NIP-50 search /// over kind:0, filtered to name substring matches (returns [] if -/// unsupported), with verified profiles attached where advertised. +/// unsupported), with verified profiles attached where advertised. As for +/// [`get_profiles`], a failed verified check is a stderr warning, not an error. async fn search_profiles( client: &BuzzClient, query: &str, ) -> Result, CliError> { + let (profiles, warning) = find_profiles(client, query).await?; + if let Some(warning) = warning { + eprintln!("{warning}"); + } + Ok(profiles) +} + +/// [`search_profiles`] with its warning returned instead of printed. +async fn find_profiles( + client: &BuzzClient, + query: &str, +) -> Result<(Vec, Option), CliError> { let parse = |raw: String| -> Result, CliError> { serde_json::from_str(&raw) .map_err(|e| CliError::Other(format!("failed to parse response: {e}"))) }; - let authority = discover_authority(client).await?; + let (authority, warning) = match discover_authority(client).await { + Ok(authority) => (authority, None), + Err(e) => (None, Some(verified_unavailable(&e))), + }; let fits = query.trim().chars().count() <= PROFILE_SEARCH_MAX_CHARS; if let Some(authority) = authority.as_ref().filter(|a| a.searchable && fits) { let body = serde_json::json!({"query": query.trim(), "limit": 100}); let raw = client.post_json_authed("/profiles/search", &body).await?; - return Ok(search_page_profiles(&parse(raw)?, &authority.pubkey)); + return Ok((search_page_profiles(&parse(raw)?, &authority.pubkey), None)); } let filter = serde_json::json!({ "kinds": [0], @@ -484,14 +502,16 @@ async fn search_profiles( let events = parse(client.query(&filter).await?)?; let profiles = name_search_profiles(&events, query); let Some(authority) = authority else { - return Ok(profiles); + return Ok((profiles, warning)); }; let pubkeys: Vec = profiles .iter() .filter_map(|p| p.get("pubkey").and_then(|v| v.as_str()).map(str::to_owned)) .collect(); - let verified = fetch_verified_profiles(client, &authority.pubkey, &pubkeys).await?; - Ok(with_verified(profiles, &verified)) + match fetch_verified_profiles(client, &authority.pubkey, &pubkeys).await { + Ok(verified) => Ok((with_verified(profiles, &verified), None)), + Err(e) => Ok((profiles, Some(verified_unavailable(&e)))), + } } /// Search for users by name. Owner-scoped searches resolve managed-agent records @@ -964,9 +984,10 @@ pub async fn dispatch( #[cfg(test)] mod tests { use super::{ - compact_profile, get_profiles, lookup_profiles, owned_agent_pubkeys_from_events, - owner_scoped_profiles, owner_verification, parse_expiration_tag, parse_expiry, - presence_subject, publish_status, read_statuses, search_profiles, + compact_profile, find_profiles, get_profiles, lookup_profiles, + owned_agent_pubkeys_from_events, owner_scoped_profiles, owner_verification, + parse_expiration_tag, parse_expiry, presence_subject, publish_status, read_statuses, + search_profiles, }; use crate::client::BuzzClient; use crate::error::CliError; @@ -1573,6 +1594,39 @@ mod tests { assert!(warning.is_none()); } + #[tokio::test] + async fn name_search_keeps_kind0_matches_and_warns_when_the_verified_check_fails() { + // Discovery fails (malformed NIP-11), or the kind:30382 query does on + // a relay whose profile search does not match verified names. + for broken_lookup in [false, true] { + let (client, relay) = setup().await; + relay.lock().unwrap().info = if broken_lookup { + let mut info = advertising(&Keys::generate()); + info["federated_identity"]["public_profile"]["searchable"] = json!(false); + info + } else { + json!({"federated_identity": "malformed"}) + }; + relay.lock().unwrap().broken_kind = broken_lookup.then_some(30382); + let alice = Keys::generate(); + seed_profile(&relay, &alice, r#"{"name":"alice"}"#); + + let (found, warning) = find_profiles(&client, "alice").await.unwrap(); + assert_eq!(found.len(), 1, "{broken_lookup}: {found:?}"); + assert_eq!(found[0]["pubkey"], alice.public_key().to_hex()); + assert!(found[0].get("verified").is_none()); + let warning = warning.expect("a failed check is reported"); + assert_eq!(warning["warning"], "verified_profiles_unavailable"); + assert!(relay.lock().unwrap().profile_searches.is_empty()); + } + + // A working check reports nothing. + let (client, relay) = setup().await; + seed_profile(&relay, &Keys::generate(), r#"{"name":"alice"}"#); + let (_, warning) = find_profiles(&client, "alice").await.unwrap(); + assert!(warning.is_none()); + } + #[tokio::test] async fn name_search_uses_profile_search_up_to_its_character_limit() { // Counted in characters after trimming, as the relay counts them. diff --git a/crates/buzz-cli/src/commands/verified_profiles.rs b/crates/buzz-cli/src/commands/verified_profiles.rs index d82684049ff..c9841618022 100644 --- a/crates/buzz-cli/src/commands/verified_profiles.rs +++ b/crates/buzz-cli/src/commands/verified_profiles.rs @@ -197,10 +197,11 @@ const PROJECTION_TAGS: [&str; 7] = [ "verified_at", ]; -/// Read the NIP-FI projection as the spec and the mobile client do: empty +/// Read the NIP-FI projection with the spec's structural checks: empty /// content; exactly the projection tags, each once with one value; `p` equal -/// to `d`; `active` `true`; well-formed names; and a decimal `verified_at` no -/// later than `created_at`. Anything else is not a verified profile. +/// to `d`; `active` `true`; a decimal `verified_at` no later than +/// `created_at`; and names that pass [`valid_name`]. Anything else is not a +/// verified profile. fn parse_projection(event: &Event) -> Option { if !event.content.is_empty() { return None; @@ -245,7 +246,12 @@ fn parse_projection(event: &Event) -> Option { } /// Display text: 1 to 64 characters, no surrounding whitespace, no control -/// characters. +/// characters (Cc). +/// +/// Looser than the spec, the relay and the mobile client, which also require +/// NFC and reject the Cf, Cs, Co, Cn, Zl and Zp categories. The relay applies +/// those rules before it signs, so a name that passes here but fails there +/// would need a relay-signed event that breaks its own rules. fn valid_name(value: &str) -> bool { (1..=64).contains(&value.chars().count()) && value.trim() == value