From 2b8d4f62611d7e0663912ae0be7a3165507989cd Mon Sep 17 00:00:00 2001 From: Tirthraj Chavan Date: Thu, 3 Dec 2026 22:07:13 +0530 Subject: [PATCH] fix(admin): accept and decode NIP-19 npub in moderation pubkey actions --- .changeset/moderation-ban-npub.md | 4 + crates/nostream-admin/src/utils/moderation.rs | 90 ++++++++++++++++--- crates/nostream-admin/tests/write_path.rs | 68 ++++++++++++++ 3 files changed, 149 insertions(+), 13 deletions(-) create mode 100644 .changeset/moderation-ban-npub.md diff --git a/.changeset/moderation-ban-npub.md b/.changeset/moderation-ban-npub.md new file mode 100644 index 000000000..3e57ceb58 --- /dev/null +++ b/.changeset/moderation-ban-npub.md @@ -0,0 +1,4 @@ +--- +--- + +fix(admin): accept and decode NIP-19 npub in moderation pubkey actions and limits (#1321) diff --git a/crates/nostream-admin/src/utils/moderation.rs b/crates/nostream-admin/src/utils/moderation.rs index f311e02b3..db7d7c2be 100644 --- a/crates/nostream-admin/src/utils/moderation.rs +++ b/crates/nostream-admin/src/utils/moderation.rs @@ -5,11 +5,9 @@ //! capture does (`applyLimitsToUserSettings`) and what keeps the kind rules — numbers or //! `[start, end]` pairs — byte-identical through a round trip. //! -//! **A narrowing, recorded rather than hidden:** pubkeys are accepted in the 64-character hex -//! form only. shortcut: hex pubkeys only, upgrade when `nostream-core` grows a bech32 decoder. -//! The capture also accepts an `npub`, and this tree has no bech32 decoder -//! (`crates/nostream-relay/src/handlers/subscribe.rs:152-153` refuses the same form for the -//! same reason). An `npub` is a `400` here, never silently stored. +//! Pubkeys accept either 64 hex characters (normalized to lowercase) or a NIP-19 `npub1…` bech32 +//! string decoded via [`nostream_core::nip19::decode_npub_hex`]; anything else answers `400`, +//! never silently stored. use std::net::IpAddr; use std::str::FromStr; @@ -234,10 +232,28 @@ pub fn is_hex_pubkey(value: &str) -> bool { .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) } +/// Normalizes a moderation pubkey target: accepts a 64-character hex pubkey (lowercased) or a +/// NIP-19 `npub1…` bech32 pubkey decoded to lowercase hex. +pub fn normalize_pubkey(raw: &str) -> Result { + let candidate = raw.trim(); + if candidate.is_empty() { + return Err(ModerationError::Message(PUBKEY_REQUIRED.to_owned())); + } + let lower = candidate.to_ascii_lowercase(); + if is_hex_pubkey(&lower) { + return Ok(lower); + } + if lower.starts_with("npub1") { + return nostream_core::nip19::decode_npub_hex(candidate) + .map_err(|_| ModerationError::Message(PUBKEY_REQUIRED.to_owned())); + } + Err(ModerationError::Message(PUBKEY_REQUIRED.to_owned())) +} + fn require_pubkey(fields: &ActionFields) -> Result { match fields.pubkey.as_deref() { - Some(pubkey) if is_hex_pubkey(pubkey) => Ok(pubkey.to_owned()), - _ => Err(ModerationError::Message(PUBKEY_REQUIRED.to_owned())), + Some(pubkey) => normalize_pubkey(pubkey), + None => Err(ModerationError::Message(PUBKEY_REQUIRED.to_owned())), } } @@ -350,13 +366,13 @@ pub fn normalize(limits: &ModerationLimits) -> Result Result, ModerationError> { let mut normalized = Vec::new(); for raw in values { - if !is_hex_pubkey(raw) { - return Err(ModerationError::Message(format!( + let pubkey = normalize_pubkey(raw).map_err(|_| { + ModerationError::Message(format!( "{label} must contain 64-character hex pubkeys or npubs" - ))); - } - if !normalized.contains(raw) { - normalized.push(raw.clone()); + )) + })?; + if !normalized.contains(&pubkey) { + normalized.push(pubkey); } } Ok(normalized) @@ -453,6 +469,54 @@ mod tests { ); } + #[test] + fn an_npub_is_decoded_for_ban_unban_and_normalize() { + let npub = "npub1yt5qf5nw694k3k6jt8ncgj0fdk4463jv3arshk37kxnsgeljc7fsmhwffw"; + let hex = "22e804d26ed16b68db5259e78449e96dab5d464c8f470bda3eb1a70467f2c793"; + + let banned = apply_action( + &ModerationLimits::default(), + ModerationAction::BanPubkey, + &ActionFields { + pubkey: Some(format!(" {npub} ")), + ..ActionFields::default() + }, + ) + .unwrap(); + assert_eq!(banned.pubkey.blacklist, vec![hex.to_owned()]); + + let unbanned = apply_action( + &banned, + ModerationAction::UnbanPubkey, + &ActionFields { + pubkey: Some(npub.to_owned()), + ..ActionFields::default() + }, + ) + .unwrap(); + assert!(unbanned.pubkey.blacklist.is_empty()); + + let mut raw_limits = ModerationLimits::default(); + raw_limits.pubkey.blacklist.push(npub.to_owned()); + raw_limits.pubkey.blacklist.push(hex.to_owned()); + let normalized = normalize(&raw_limits).unwrap(); + assert_eq!(normalized.pubkey.blacklist, vec![hex.to_owned()]); + } + + #[test] + fn a_malformed_npub_is_refused() { + let error = apply_action( + &ModerationLimits::default(), + ModerationAction::BanPubkey, + &ActionFields { + pubkey: Some("npub1invalid".to_owned()), + ..ActionFields::default() + }, + ) + .unwrap_err(); + assert!(matches!(error, ModerationError::Message(message) if message == PUBKEY_REQUIRED)); + } + #[test] fn writing_limits_leaves_other_keys_alone() { let user: serde_yaml::Value = serde_yaml::from_str("info:\n name: Example\n").unwrap(); diff --git a/crates/nostream-admin/tests/write_path.rs b/crates/nostream-admin/tests/write_path.rs index 7f5cad9b1..b2c053ca7 100644 --- a/crates/nostream-admin/tests/write_path.rs +++ b/crates/nostream-admin/tests/write_path.rs @@ -7,6 +7,8 @@ //! | `every_concurrent_settings_save_lands` | six overlapping `PATCH /settings` requests each keep their change | //! | `a_moderation_action_enqueues_the_settings_changed_row` | the action queues `settings.changed`, not an event the operator cannot toggle | //! | `a_limits_patch_enqueues_the_settings_changed_row` | the limits route goes through the same save flow and queues one too | +//! | `a_moderation_ban_with_a_valid_npub_bans_the_pubkey` | `POST /admin/moderation/actions` decodes a valid `npub1…` and stores its hex pubkey | +//! | `the_ban_form_label_and_refusal_name_the_accepted_forms` | the console form label, client prompt and `400` refusal each name both hex and npub | //! | `a_container_write_redacts_its_secrets_in_the_echo_and_the_row` | a write above a target's secrets, padded path included, echoes and queues `***` but saves the values (#1193) | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -212,6 +214,72 @@ async fn a_limits_patch_enqueues_the_settings_changed_row() { ); } +#[tokio::test] +async fn a_moderation_ban_with_a_valid_npub_bans_the_pubkey() { + let server = TestServer::start().await; + let cookie = server.login().await; + let npub = "npub1yt5qf5nw694k3k6jt8ncgj0fdk4463jv3arshk37kxnsgeljc7fsmhwffw"; + let expected_hex = "22e804d26ed16b68db5259e78449e96dab5d464c8f470bda3eb1a70467f2c793"; + + let response = server + .send_json( + "POST", + "/admin/moderation/actions", + &cookie, + json!({ "action": "ban-pubkey", "pubkey": npub }), + ) + .await; + assert_eq!(response.status, 200, "{}", response.text()); + assert_eq!( + response.json()["limits"]["pubkey"]["blacklist"], + json!([expected_hex]), + "the response carries the decoded lowercase hex pubkey" + ); + assert_eq!( + user_settings(&server)["limits"]["event"]["pubkey"]["blacklist"][0], + serde_yaml::Value::String(expected_hex.to_owned()), + "the persisted blacklist holds the decoded hex pubkey" + ); +} + +#[tokio::test] +async fn the_ban_form_label_and_refusal_name_the_accepted_forms() { + let server = TestServer::start().await; + let cookie = server.login().await; + + let html = server.get("/admin/").await.text(); + assert!( + html.contains( + r#""# + ), + "the ban field label names both accepted forms" + ); + assert!( + html.contains(r#"id="moderation-ban-pubkey" class="form-control console-input form-control-sm" placeholder="hex or npub""#), + "the ban field placeholder names both accepted forms" + ); + + let js = server.get("/admin/assets/admin-moderation.js").await.text(); + assert!( + js.contains("Enter a pubkey or npub to ban."), + "the client ban prompt names both accepted forms" + ); + + let refused = server + .send_json( + "POST", + "/admin/moderation/actions", + &cookie, + json!({ "action": "ban-pubkey", "pubkey": "npub1invalid" }), + ) + .await; + assert_eq!(refused.status, 400); + assert_eq!( + refused.json()["error"], + "pubkey is required and must be a 64-character hex pubkey or npub" + ); +} + const TARGET_SECRETS: [&str; 4] = [ "tg-bot-token-value", "slack-hook-value",