mirror of
https://github.com/block/buzz.git
synced 2026-11-25 10:42:26 +00:00
feat(cli): show and search verified identity in users get (#9647)
## Summary `buzz users get` reads only kind:0 profiles, so the CLI can't find or confirm a person by their verified username. This adds relay-verified profiles (kind:30382) to `users get`. - `--pubkey` adds a `verified` object (`username`, `display_name`, `full_name`, `issuer_label`, `verified_at`) for subjects that have one. A requested person with a verified profile but no kind:0 is still returned. - `--name` uses the relay's `POST /profiles/search` when the community advertises verified profiles with `searchable: true`, so it matches verified names (word prefix). Otherwise, or for queries over the endpoint's 100-character limit, it runs the existing NIP-50 substring search and attaches verified profiles where the community advertises them. Verified profiles are read only when NIP-11 advertises `federated_identity.public_profile`. A projection is trusted only if it is kind 30382, signed by the relay's `self` key with a valid signature, and follows the NIP-FI projection rules the mobile client applies: empty content, exactly the projection tags (each once with one value), `p` equal to `d`, `active` set to `true`, a valid username, names of 1–64 characters with no surrounding whitespace or control characters (looser than mobile, which also requires NFC and rejects more Unicode categories), and a decimal `verified_at` no later than `created_at`. The newest projection per subject wins (the lower id breaks a same-second tie), so a retraction clears the verified name. Any `verified` key in user-authored kind:0 content is dropped on every path, so only a relay-signed projection can set it. `users get` now makes one NIP-11 request. If that request fails, the advertisement is malformed, or the kind:30382 lookup fails, it still prints the kind:0 results and writes a `verified_profiles_unavailable` warning to stderr. This applies to `--pubkey`, no args, and `--name`. ### Related issue Related: #8745 (verified profile spec), #9624 (verified-name mentions in workflows). ### Testing - `cargo test -p buzz-cli` passes, with tests for trust checks, retraction, both lookup paths, search without the advertisement, and a forged `verified` object in kind:0 (no advertisement, impostor-only projection, and a valid projection replacing it). - `cargo fmt` and `cargo clippy -p buzz-cli -D warnings` are clean. - An earlier revision of the built CLI was run against a live community with verified profiles: `--name <verified username>` found a user whose kind:0 name differs, and `--pubkey` returned the expected `verified` objects. --------- Signed-off-by: damienrj <damien@squareup.com>
This commit is contained in:
@@ -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};
|
||||
|
||||
@@ -5,13 +5,24 @@ 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;
|
||||
|
||||
/// 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).
|
||||
///
|
||||
/// - 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" → [`search_profiles`]
|
||||
///
|
||||
/// 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 +50,43 @@ 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<serde_json::Value> =
|
||||
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, 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<Vec<serde_json::Value>, 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<serde_json::Value>, Option<serde_json::Value>), CliError> {
|
||||
let my_pk = client.public_key().to_hex();
|
||||
let authors: Vec<&str> = if pubkeys.is_empty() {
|
||||
vec![my_pk.as_str()]
|
||||
@@ -59,6 +107,7 @@ pub async fn cmd_get_users(
|
||||
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("")),
|
||||
@@ -67,23 +116,143 @@ pub async fn cmd_get_users(
|
||||
Some(profile)
|
||||
})
|
||||
.collect();
|
||||
let output = match format {
|
||||
crate::OutputFormat::Compact => {
|
||||
let compact: Vec<serde_json::Value> = 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 requested: Vec<String> = 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(verified_unavailable(&e))),
|
||||
};
|
||||
println!("{output}");
|
||||
Ok(())
|
||||
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<String> = 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, 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,
|
||||
pubkeys: &[String],
|
||||
) -> Result<HashMap<String, VerifiedProfile>, CliError> {
|
||||
match discover_authority(client).await? {
|
||||
Some(authority) => fetch_verified_profiles(client, &authority.pubkey, pubkeys).await,
|
||||
None => Ok(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach each profile's `verified` object where a relay-signed one exists.
|
||||
fn with_verified(
|
||||
mut profiles: Vec<serde_json::Value>,
|
||||
verified: &HashMap<String, VerifiedProfile>,
|
||||
) -> Vec<serde_json::Value> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
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 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: &str) -> Vec<serde_json::Value> {
|
||||
let verified = verified_profiles_from_events(events, authority);
|
||||
let mut order: Vec<String> = Vec::new();
|
||||
let mut profiles: HashMap<String, serde_json::Map<String, serde_json::Value>> = 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) {
|
||||
profiles.insert(pubkey, 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 {
|
||||
@@ -140,13 +309,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<String, serde_json::Value> {
|
||||
event
|
||||
let mut profile = event
|
||||
.get("content")
|
||||
.and_then(|value| value.as_str())
|
||||
.and_then(|content| serde_json::from_str::<serde_json::Value>(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<serde_json::Value> {
|
||||
@@ -284,8 +457,65 @@ 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. 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. As for
|
||||
/// [`get_profiles`], a failed verified check is a stderr warning, not an error.
|
||||
async fn search_profiles(
|
||||
client: &BuzzClient,
|
||||
query: &str,
|
||||
) -> Result<Vec<serde_json::Value>, 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<serde_json::Value>, Option<serde_json::Value>), CliError> {
|
||||
let parse = |raw: String| -> Result<Vec<serde_json::Value>, CliError> {
|
||||
serde_json::from_str(&raw)
|
||||
.map_err(|e| CliError::Other(format!("failed to parse response: {e}")))
|
||||
};
|
||||
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), None));
|
||||
}
|
||||
let filter = serde_json::json!({
|
||||
"kinds": [0],
|
||||
"search": query,
|
||||
"limit": 100
|
||||
});
|
||||
let events = parse(client.query(&filter).await?)?;
|
||||
let profiles = name_search_profiles(&events, query);
|
||||
let Some(authority) = authority else {
|
||||
return Ok((profiles, warning));
|
||||
};
|
||||
let pubkeys: Vec<String> = profiles
|
||||
.iter()
|
||||
.filter_map(|p| p.get("pubkey").and_then(|v| v.as_str()).map(str::to_owned))
|
||||
.collect();
|
||||
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
|
||||
/// and verify their profiles; unscoped searches go through [`search_profiles`].
|
||||
async fn search_by_name(
|
||||
client: &BuzzClient,
|
||||
query: &str,
|
||||
@@ -321,34 +551,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::Value> = 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<serde_json::Value> = 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 +984,16 @@ pub async fn dispatch(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
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;
|
||||
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 +1006,13 @@ mod tests {
|
||||
events: Vec<Value>,
|
||||
queries: Vec<Value>,
|
||||
raw_query_response: Option<String>,
|
||||
/// Answer queries for this kind with invalid JSON.
|
||||
broken_kind: Option<u64>,
|
||||
/// NIP-11 document served at `/`.
|
||||
info: Value,
|
||||
/// Body of `POST /profiles/search`; `None` answers 404 like an older relay.
|
||||
profile_search: Option<Value>,
|
||||
profile_searches: Vec<Value>,
|
||||
}
|
||||
type Shared = Arc<Mutex<Relay>>;
|
||||
|
||||
@@ -813,6 +1033,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<Value> = relay
|
||||
.events
|
||||
@@ -822,6 +1047,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 +1067,25 @@ mod tests {
|
||||
serde_json::to_string(&matching).unwrap()
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/",
|
||||
get(|State(relay): State<Shared>| async move {
|
||||
Json(relay.lock().unwrap().info.clone())
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/profiles/search",
|
||||
post(|State(relay): State<Shared>, 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<Shared>, body: Bytes| async move {
|
||||
@@ -851,13 +1102,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)
|
||||
}
|
||||
|
||||
@@ -1160,6 +1412,359 @@ 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_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 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_advertised_profiles_uses_nip50() {
|
||||
let (client, relay) = setup().await;
|
||||
let alice = Keys::generate();
|
||||
seed_profile(&relay, &alice, r#"{"name":"alice"}"#);
|
||||
seed_profile(&relay, &Keys::generate(), r#"{"name":"bob"}"#);
|
||||
|
||||
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!(found[0].get("verified").is_none());
|
||||
assert!(relay.lock().unwrap().profile_searches.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_by_pubkey_keeps_profiles_and_warns_when_the_verified_check_fails() {
|
||||
let alice = Keys::generate();
|
||||
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()));
|
||||
}
|
||||
|
||||
// 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_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.
|
||||
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 = "é".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());
|
||||
}
|
||||
|
||||
#[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"}}"#;
|
||||
|
||||
#[tokio::test]
|
||||
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);
|
||||
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[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]
|
||||
fn owned_agent_lookup_matches_exact_name_case_insensitively() {
|
||||
let events = vec![
|
||||
|
||||
502
crates/buzz-cli/src/commands/verified_profiles.rs
Normal file
502
crates/buzz-cli/src/commands/verified_profiles.rs
Normal file
@@ -0,0 +1,502 @@
|
||||
//! 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.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use nostr::Event;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
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;
|
||||
|
||||
/// 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<String>,
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Option<Authority>, 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)) {
|
||||
return Err(malformed("malformed public_profile discovery"));
|
||||
}
|
||||
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<Option<Authority>, 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<HashMap<String, VerifiedProfile>, CliError> {
|
||||
let mut subjects: Vec<String> = 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<Value> = 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, or with a bad id or
|
||||
/// signature is ignored. Per subject the newest event is the head, as for any
|
||||
/// 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(
|
||||
events: &[Value],
|
||||
authority: &str,
|
||||
) -> HashMap<String, VerifiedProfile> {
|
||||
let mut heads: HashMap<String, Event> = HashMap::new();
|
||||
for raw in events {
|
||||
let Ok(event) = serde_json::from_value::<Event>(raw.clone()) else {
|
||||
continue;
|
||||
};
|
||||
let Some(subject) = signed_subject(&event, authority) else {
|
||||
continue;
|
||||
};
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
heads
|
||||
.into_iter()
|
||||
.filter_map(|(subject, event)| parse_projection(&event).map(|p| (subject, p)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
if event.kind.as_u16() != KIND || event.pubkey.to_hex() != authority || event.verify().is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
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(name))
|
||||
.and_then(|tag| tag.get(1))
|
||||
.map(String::as_str)
|
||||
}
|
||||
|
||||
/// 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 with the spec's structural checks: empty
|
||||
/// content; exactly the projection tags, each once with one value; `p` equal
|
||||
/// 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<VerifiedProfile> {
|
||||
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;
|
||||
}
|
||||
Some(VerifiedProfile {
|
||||
display_name: name("display_name")?.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,
|
||||
})
|
||||
}
|
||||
|
||||
/// Display text: 1 to 64 characters, no surrounding whitespace, no control
|
||||
/// 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
|
||||
&& !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())
|
||||
&& 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<Tag> = 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 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!(
|
||||
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!({})),
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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], &authority);
|
||||
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,
|
||||
})
|
||||
);
|
||||
// `full_name` is optional and omitted when absent.
|
||||
let event = sign(&relay, 30382, "", &tag_pairs(&subject, &[]), AT);
|
||||
let found = verified_profiles_from_events(&[event], &authority);
|
||||
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 unusable_projections_are_ignored() {
|
||||
let relay = Keys::generate();
|
||||
let authority = relay.public_key().to_hex();
|
||||
let subject = Keys::generate().public_key().to_hex();
|
||||
let cases: Vec<(&str, Vec<(&str, &str)>)> = vec![
|
||||
("retracted", vec![("active", "false")]),
|
||||
("bad username", vec![("username", "Alice")]),
|
||||
("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, &[]);
|
||||
for (key, value) in &overrides {
|
||||
tags.iter_mut().find(|(k, _)| k == key).unwrap().1 = value;
|
||||
}
|
||||
let event = sign(&relay, 30382, "", &tags, AT);
|
||||
assert!(
|
||||
verified_profiles_from_events(&[event], &authority).is_empty(),
|
||||
"{label}"
|
||||
);
|
||||
}
|
||||
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());
|
||||
|
||||
// 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> = 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<Value> = ["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]
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1375,12 +1375,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<String>,
|
||||
/// Search by display name (case-insensitive substring match)
|
||||
/// 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<String>,
|
||||
/// Scope an exact-name agent lookup to its owner (`me`, hex, or npub)
|
||||
|
||||
Reference in New Issue
Block a user