lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit a87f148658c2ebab7546c1e7eff00d2497e8de3c
parent 688c80832f84db16b398f64ec1b8d3ee89fa0a68
Author: triesap <tyson@radroots.org>
Date:   Fri, 23 Oct 2026 06:20:40 +0000

nostr: Authenticate bounded private message opening

- Verify outer recipients and exact signed seals before projecting messages.
- Reject wide kinds, false rumor identities and malformed bounded private data.
- Preserve peer and self copies plus unsupported-kind classification.
- Qualify feature gates, browser compilation, public APIs and coverage limits.

Diffstat:
Acontracts/protocol/private_opening.v1.json | 29+++++++++++++++++++++++++++++
Mcrates/nostr/Cargo.toml | 1+
Mcrates/nostr/README.md | 25++++++++++++++++++++-----
Mcrates/nostr/src/nip17.rs | 9+++++++--
Acrates/nostr/src/nip17/opening.rs | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/nostr/src/nip17/opening_tests.rs | 496+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/nostr/tests/package_boundary.rs | 38++++++++++++++++++++++++++++++++++++--
Mcrates/protocol/src/plan.rs | 1+
8 files changed, 865 insertions(+), 9 deletions(-)

diff --git a/contracts/protocol/private_opening.v1.json b/contracts/protocol/private_opening.v1.json @@ -0,0 +1,29 @@ +{ + "schema": "radroots.nostr.private_opening.v1", + "contract_version": 1, + "state": "existing_nip17_protocol_opening", + "feature": "nip17", + "outer_kind": 1059, + "seal_kind": 13, + "supported_rumor_kinds": [14, 15], + "signed_max_utf8_bytes": 65536, + "rumor_max_utf8_bytes": 24576, + "json_max_depth": 16, + "event_tag_budgets": "Reuse the owning EventWireLimits defaults, with the complete signed-event bound applied independently.", + "order": [ + "Bound the typed outer and verify its exact ID/signature before any signer callback.", + "Bind exactly one canonical p recipient to the current signer identity; preserve unrelated bounded outer tags and optional relay hints.", + "Check NIP-44 v2 framing, decrypt, and recheck the selected identity.", + "Bound the complete raw seal and require exact duplicate-safe seven-field signed-event admission, kind13, empty tags, ID and signature.", + "Check seal ciphertext v2 framing, decrypt, and recheck identity again.", + "Bound the complete raw rumor and parse a closed object with a required canonical ID and raw u16 kind before upstream conversion.", + "Recompute the rumor ID and bind seal author and rumor author. Authentic unknown kinds return unsupported before chat-tag interpretation; known message kinds additionally bind the peer/self recipient before decoding." + ], + "rumor_required_fields": ["id", "pubkey", "created_at", "kind", "tags", "content"], + "private_temporary_retention": "Decrypted frames are zeroizing; the temporary parsed rumor clears owned content and tags on drop. Existing returned message/file DTOs remain ordinary owned application data. No whole-process zeroization guarantee is made.", + "limits": [ + "Protocol-only existing message/file adapter; no commerce authoring, durable storage, consent, inventory or history authority.", + "Typed upstream outer input cannot recover malformed original raw fields already lost before this API; raw outer ingress closure remains separately required.", + "Actual same-library encrypted regression and existing conformance do not replace full independent nested commerce qualification." + ] +} diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml @@ -74,6 +74,7 @@ serde = { workspace = true, default-features = false, features = [ ] } serde_json = { workspace = true, default-features = false, features = [ "alloc", + "raw_value", ] } thiserror = { version = "2", default-features = false } diff --git a/crates/nostr/README.md b/crates/nostr/README.md @@ -126,11 +126,13 @@ local signing only. It never opens a network connection, writes a file or database, selects an account, publishes an event, or installs a runtime. Some cryptographic adapters are async because their upstream protocol -operations are async. Dropping one of those futures cancels local computation -and creates no external durable effect. The crate has no remote publication or -persistence commit point: the only successful result is the value returned to -the caller. A transport or host that later publishes or stores that value owns -its own cancellation and commit semantics. +operations are async. Local key-backed work returns an in-memory result, while +an injected upstream signer may invoke external custody. Dropping its observer +does not prove that no artifact was obtained remotely. The protocol-only +multi-recipient helper is not a durable issuance journal: an earlier recipient +may already have an obtained seal when a later request fails. The composing +executor must retain each disposition and exact obtained result. Transport and +storage owners supply their own publication and durable commit semantics. The `blossom` module converts exact, verified signer output into and from signed `Authorization: Nostr` values but never sends an HTTP request. BUD-11 @@ -138,6 +140,19 @@ plans remain distinct from relay-authored plans. The `nip17` module creates and opens gift-wrap events. It does not select relays, deliver events, retry operations, or persist message state. +Opening verifies the bounded outer event and its single recipient before any +signer callback, then authenticates a closed empty-tag kind13 seal. It checks +NIP-44 v2 framing, identity continuity, complete24KiB rumors and depth16, raw +u16 kinds before upstream conversion, required canonical IDs and author/recipient +bindings. The original rumor ID is recomputed rather than trusted. Peer and +sender self copies retain the same logical message. Decrypted frames and the +temporary parsed rumor are cleared on drop; returned legacy message/file DTOs +remain ordinary owned application data. This helper supplies no commerce, +durability, consent, stock or current-history authority. Its typed outer input +does not recover malformed raw fields already lost by an earlier decoder. +Authentic unknown rumor kinds return unsupported after header/ID/author checks; +their content and tags are not interpreted as known chat data. + ## Serialization contract - Canonical durable Radroots data should be serialized through diff --git a/crates/nostr/src/nip17.rs b/crates/nostr/src/nip17.rs @@ -24,6 +24,8 @@ use radroots_event_codec::decode::{EventParseError, message as message_decode}; use radroots_event_codec::encode::message_file as message_file_encode; use radroots_event_codec::encode::{EventEncodeError, message as message_encode}; +mod opening; + /// Stable, source-redacted failures from the focused NIP-17 adapter. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -277,8 +279,8 @@ pub async fn unwrap_gift_wrap<T>(signer: &T, gift_wrap: &Event) -> Result<Rumor, where T: NostrSigner, { - let unwrapped = nip59::extract_rumor(signer, gift_wrap).await?; - let mut rumor = unwrapped.rumor; + let mut opened = opening::open(signer, gift_wrap).await?; + let rumor = &mut opened.0; let id = rumor.id().to_string(); let author = rumor.pubkey.to_string(); let published_at = rumor.created_at.as_secs(); @@ -313,6 +315,9 @@ where } #[cfg(all(test, feature = "nip17"))] +mod opening_tests; + +#[cfg(all(test, feature = "nip17"))] mod tests { use super::*; use crate::test_fixtures::{FIXTURE_ALICE, FIXTURE_BOB}; diff --git a/crates/nostr/src/nip17/opening.rs b/crates/nostr/src/nip17/opening.rs @@ -0,0 +1,275 @@ +//! Bounded opening for the existing protocol-only NIP-17 adapter. +use super::{Error, Event, Kind, NostrSigner, PublicKey, UnsignedEvent}; +use alloc::{string::String, vec::Vec}; +use base64::Engine as _; +use nostr::JsonUtil; +use radroots_event::wire::{EventWireLimits, Nip01EventWire}; +use radroots_protocol::{ + chat::{RUMOR_MAX_BYTES, SIGNED_MAX_BYTES}, + nip01::{EventFields, signed_json_len}, +}; +use serde::Deserialize; +use serde_json::value::RawValue; +use zeroize::{Zeroize as _, Zeroizing}; + +pub(super) struct OpenedRumor(pub(super) UnsignedEvent); +impl Drop for OpenedRumor { + fn drop(&mut self) { + self.0.content.zeroize(); + for tag in core::mem::take(&mut self.0.tags) { + tag.to_vec().zeroize(); + } + } +} + +fn ciphertext(value: &str) -> Result<(), Error> { + if value.len() > SIGNED_MAX_BYTES { + return Err(Error::GiftWrap); + } + let raw = base64::engine::general_purpose::STANDARD + .decode(value) + .map_err(|_| Error::GiftWrap)?; + if raw.first() != Some(&2) || raw.len() < 99 || (raw.len() - 67) % 32 != 0 { + return Err(Error::GiftWrap); + } + Ok(()) +} + +fn frame(raw: &str, limit: usize) -> Result<(), Error> { + if raw.len() > limit || !raw.trim_start().starts_with('{') { + return Err(Error::GiftWrap); + } + let (mut quoted, mut escaped, mut depth) = (false, false, 0u8); + for byte in raw.bytes() { + if quoted { + if escaped { + escaped = false; + } else if byte == b'\\' { + escaped = true; + } else if byte == b'"' { + quoted = false; + } + } else { + match byte { + b'"' => quoted = true, + b'{' | b'[' => { + depth = depth + .checked_add(1) + .filter(|n| *n <= 16) + .ok_or(Error::GiftWrap)?; + } + b'}' | b']' => { + depth = depth.checked_sub(1).ok_or(Error::GiftWrap)?; + } + _ => {} + } + } + } + if quoted || depth != 0 { + return Err(Error::GiftWrap); + } + Ok(()) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawRumor<'a> { + id: String, + pubkey: String, + created_at: u64, + kind: u16, + #[serde(borrow)] + tags: &'a RawValue, + #[serde(borrow)] + content: &'a RawValue, +} + +fn rumor(raw: &str, author: PublicKey, recipient: PublicKey) -> Result<OpenedRumor, Error> { + frame(raw, RUMOR_MAX_BYTES)?; + let fields: RawRumor<'_> = serde_json::from_str(raw).map_err(|_| Error::GiftWrap)?; + if fields.created_at > 253_402_300_799 + || fields.pubkey != author.to_hex() + || !fields.tags.get().trim_start().starts_with('[') + || !fields.content.get().trim_start().starts_with('"') + { + return Err(Error::GiftWrap); + } + let declared = nostr::EventId::from_hex(&fields.id).map_err(|_| Error::GiftWrap)?; + if declared.to_hex() != fields.id { + return Err(Error::GiftWrap); + } + let opened = OpenedRumor(UnsignedEvent::from_json(raw).map_err(|_| Error::GiftWrap)?); + let value = &opened.0; + if value.id != Some(declared) || value.kind.as_u16() != fields.kind { + return Err(Error::GiftWrap); + } + value.verify_id().map_err(|_| Error::GiftWrap)?; + if !matches!(fields.kind, 14 | 15) { + return Ok(opened); + } + let mut addressed = author == recipient; + let mut peers = Vec::new(); + for tag in value.tags.as_slice() { + let fields = tag.as_slice(); + if fields.first().map(String::as_str) == Some("p") { + if !(2..=3).contains(&fields.len()) { + return Err(Error::InvalidRecipient); + } + let peer = PublicKey::from_hex(&fields[1]).map_err(|_| Error::InvalidRecipient)?; + if peer.to_hex() != fields[1] || peers.contains(&peer) { + return Err(Error::InvalidRecipient); + } + peers.push(peer); + addressed |= peer == recipient; + } + } + if !addressed || peers.is_empty() { + return Err(Error::InvalidRecipient); + } + Ok(opened) +} + +fn signed(raw: &str) -> Result<radroots_event::envelope::EventEnvelope, Error> { + let wire = Nip01EventWire::parse_json_exact_with_limits( + raw, + EventWireLimits { + max_raw_json_bytes: SIGNED_MAX_BYTES, + max_content_bytes: SIGNED_MAX_BYTES, + ..Default::default() + }, + ) + .map_err(|_| Error::GiftWrap)?; + let event = wire.into_envelope().map_err(|_| Error::GiftWrap)?; + if crate::event_verify::verify_event(&event) != crate::event_verify::Verification::Verified { + return Err(Error::GiftWrap); + } + Ok(event) +} + +fn outer(event: &Event) -> Result<(), Error> { + let limits = EventWireLimits::default(); + if event.kind != Kind::GiftWrap + || event.content.len() > SIGNED_MAX_BYTES + || event.tags.len() > limits.max_tag_count + { + return Err(Error::GiftWrap); + } + let mut elements = 0usize; + let mut bytes = 0usize; + for tag in event.tags.as_slice() { + for field in tag.as_slice() { + elements += 1; + bytes = bytes.checked_add(field.len()).ok_or(Error::GiftWrap)?; + if elements > limits.max_total_tag_elements + || bytes > limits.max_total_tag_bytes + || field.len() > limits.max_tag_element_bytes + { + return Err(Error::GiftWrap); + } + } + } + let tags = event + .tags + .iter() + .map(|t| t.as_slice().to_vec()) + .collect::<Vec<_>>(); + let author = radroots_identity::PublicKey::from_hex(&event.pubkey.to_hex()) + .map_err(|_| Error::GiftWrap)?; + signed_json_len( + &EventFields { + author, + created_at: event.created_at.as_secs(), + kind: u32::from(event.kind.as_u16()), + tags: &tags, + content: &event.content, + }, + SIGNED_MAX_BYTES, + ) + .map_err(|_| Error::GiftWrap)?; + signed(&event.as_json())?; + Ok(()) +} + +async fn identity<T: NostrSigner>(signer: &T, expected: PublicKey) -> Result<(), Error> { + if signer.get_public_key().await? != expected { + return Err(Error::Signer); + } + Ok(()) +} + +pub(super) async fn open<T: NostrSigner>(signer: &T, event: &Event) -> Result<OpenedRumor, Error> { + outer(event)?; + let recipient = signer.get_public_key().await?; + let mut selected = None; + for tag in event.tags.as_slice() { + let fields = tag.as_slice(); + if fields.first().map(String::as_str) == Some("p") { + if selected.is_some() + || !(2..=3).contains(&fields.len()) + || fields[1] != recipient.to_hex() + { + return Err(Error::InvalidRecipient); + } + selected = Some(recipient); + } + } + if selected.is_none() { + return Err(Error::InvalidRecipient); + } + ciphertext(&event.content)?; + let raw = Zeroizing::new(signer.nip44_decrypt(&event.pubkey, &event.content).await?); + identity(signer, recipient).await?; + frame(&raw, SIGNED_MAX_BYTES)?; + let seal = signed(&raw)?; + if seal.kind_u32() != 13 || !seal.tags_as_vec().is_empty() { + return Err(Error::GiftWrap); + } + let author = crate::key::public_key_to_nostr(*seal.author()).map_err(|_| Error::GiftWrap)?; + ciphertext(seal.content())?; + let raw = Zeroizing::new(signer.nip44_decrypt(&author, seal.content()).await?); + identity(signer, recipient).await?; + rumor(&raw, author, recipient) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn frame_bounds_include_escaped_string_delimiters_and_exact_depth() { + for raw in [ + r#"{"text":"\"\\{[}]"}"#.into(), + format!("{{\"value\":{}0{}}}", "[".repeat(15), "]".repeat(15)), + ] { + assert!(frame(&raw, raw.len()).is_ok()); + assert!(frame(&raw, raw.len() - 1).is_err()); + } + for raw in [ + "[]".into(), + "{".into(), + "}".into(), + "{\"unterminated".into(), + format!("{{\"value\":{}0{}}}", "[".repeat(16), "]".repeat(16)), + ] { + assert!(frame(&raw, SIGNED_MAX_BYTES).is_err()); + } + } + + #[test] + fn only_bounded_structural_v2_ciphertext_reaches_a_signer() { + let mut valid = vec![0; 99]; + valid[0] = 2; + let encoded = base64::engine::general_purpose::STANDARD.encode(&valid); + assert!(ciphertext(&encoded).is_ok()); + for raw in [ + "#future".into(), + "!".repeat(132), + "a".repeat(SIGNED_MAX_BYTES + 1), + base64::engine::general_purpose::STANDARD.encode([2; 98]), + base64::engine::general_purpose::STANDARD.encode([3; 99]), + base64::engine::general_purpose::STANDARD.encode([2; 100]), + ] { + assert!(ciphertext(&raw).is_err()); + } + } +} diff --git a/crates/nostr/src/nip17/opening_tests.rs b/crates/nostr/src/nip17/opening_tests.rs @@ -0,0 +1,496 @@ +use super::*; +use nostr::JsonUtil; +use nostr::{ + signer::{SignerBackend, SignerError}, + util::BoxedFuture, +}; +use serde_json::{Value, json}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +struct ObservedSigner { + keys: nostr::Keys, + switch_at: usize, + observations: AtomicUsize, + decryptions: AtomicUsize, +} +impl core::fmt::Debug for ObservedSigner { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("ObservedSigner") + } +} +impl NostrSigner for ObservedSigner { + fn backend(&self) -> SignerBackend<'_> { + SignerBackend::Keys + } + fn get_public_key(&self) -> BoxedFuture<'_, Result<PublicKey, SignerError>> { + Box::pin(async move { + let n = self.observations.fetch_add(1, Ordering::SeqCst); + Ok(if n >= self.switch_at { + keys(4).public_key() + } else { + self.keys.public_key() + }) + }) + } + fn sign_event(&self, value: UnsignedEvent) -> BoxedFuture<'_, Result<Event, SignerError>> { + self.keys.sign_event(value) + } + fn nip04_encrypt<'a>( + &'a self, + key: &'a PublicKey, + text: &'a str, + ) -> BoxedFuture<'a, Result<String, SignerError>> { + self.keys.nip04_encrypt(key, text) + } + fn nip04_decrypt<'a>( + &'a self, + key: &'a PublicKey, + text: &'a str, + ) -> BoxedFuture<'a, Result<String, SignerError>> { + self.keys.nip04_decrypt(key, text) + } + fn nip44_encrypt<'a>( + &'a self, + key: &'a PublicKey, + text: &'a str, + ) -> BoxedFuture<'a, Result<String, SignerError>> { + self.keys.nip44_encrypt(key, text) + } + fn nip44_decrypt<'a>( + &'a self, + key: &'a PublicKey, + text: &'a str, + ) -> BoxedFuture<'a, Result<String, SignerError>> { + self.decryptions.fetch_add(1, Ordering::SeqCst); + self.keys.nip44_decrypt(key, text) + } +} + +fn keys(value: u8) -> nostr::Keys { + let mut secret = [0; 32]; + secret[31] = value; + nostr::Keys::new(nostr::SecretKey::from_slice(&secret).unwrap()) +} +async fn envelope(sender: &nostr::Keys, recipient: &nostr::Keys, raw: &str) -> Event { + let encrypted = sender + .nip44_encrypt(&recipient.public_key(), raw) + .await + .unwrap(); + let seal = EventBuilder::new(Kind::Seal, encrypted) + .custom_created_at(Timestamp::from_secs(1_700_000_001)) + .sign_with_keys(sender) + .unwrap(); + EventBuilder::gift_wrap_from_seal(&recipient.public_key(), &seal, []).unwrap() +} + +#[tokio::test] +async fn raw_rumor_kinds_and_identity_never_normalize_into_an_accepted_message() { + let sender = keys(1); + let recipient = keys(2); + let message = Message { + recipients: vec![radroots_event::social::message::MessageRecipient { + public_key: recipient.public_key().to_hex(), + relay_url: None, + }], + content: "Synthetic bounded opening regression".into(), + reply_to: None, + subject: None, + }; + let parts = message_encode::to_wire_parts(&message).unwrap(); + let mut rumor = rumor_from_parts(parts, sender.public_key(), Some(1_700_000_000)).unwrap(); + let _ = rumor.id(); + let original: Value = serde_json::from_str(&rumor.as_json()).unwrap(); + let valid = envelope(&sender, &recipient, &original.to_string()).await; + assert!(unwrap_gift_wrap(&recipient, &valid).await.is_ok()); + let mut accepted = Vec::new(); + for (name, field, value) in [ + ("u16 overflow kind", "kind", json!(65_550)), + ("u32 overflow kind", "kind", json!(4_294_967_310u64)), + ("wrong rumor identity", "id", json!("00".repeat(32))), + ("unknown rumor field", "future_private_field", json!(true)), + ] { + let mut changed = original.clone(); + changed[field] = value; + let outer = envelope(&sender, &recipient, &changed.to_string()).await; + if unwrap_gift_wrap(&recipient, &outer).await.is_ok() { + accepted.push(name); + } + } + assert!( + accepted.is_empty(), + "accepted malformed representations: {accepted:?}" + ); +} + +fn rumor(sender: &nostr::Keys, recipient: &nostr::Keys, content: &str) -> UnsignedEvent { + let mut rumor = UnsignedEvent { + id: None, + pubkey: sender.public_key(), + created_at: Timestamp::from_secs(1_700_000_000), + kind: Kind::PrivateDirectMessage, + tags: nostr::Tags::from_list(vec![Tag::public_key(recipient.public_key())]), + content: content.into(), + }; + let _ = rumor.id(); + rumor +} + +async fn wrap_raw_seal(recipient: &nostr::Keys, raw: &str, tags: Vec<Tag>) -> Event { + let ephemeral = keys(3); + let content = ephemeral + .nip44_encrypt(&recipient.public_key(), raw) + .await + .unwrap(); + EventBuilder::new(Kind::GiftWrap, content) + .tags(tags) + .custom_created_at(Timestamp::from_secs(1_700_000_002)) + .sign_with_keys(&ephemeral) + .unwrap() +} + +#[tokio::test] +async fn authenticated_outer_recipient_and_closed_seal_are_required() { + let sender = keys(1); + let recipient = keys(2); + let original = rumor(&sender, &recipient, "Synthetic carrier validation"); + let content = sender + .nip44_encrypt(&recipient.public_key(), &original.as_json()) + .await + .unwrap(); + let seal = EventBuilder::new(Kind::Seal, content.clone()) + .custom_created_at(Timestamp::from_secs(1_700_000_001)) + .sign_with_keys(&sender) + .unwrap(); + let valid = wrap_raw_seal( + &recipient, + &seal.as_json(), + vec![Tag::public_key(recipient.public_key())], + ) + .await; + assert!(unwrap_gift_wrap(&recipient, &valid).await.is_ok()); + for tags in [ + vec![], + vec![Tag::public_key(sender.public_key())], + vec![ + Tag::public_key(recipient.public_key()), + Tag::public_key(sender.public_key()), + ], + ] { + let outer = wrap_raw_seal(&recipient, &seal.as_json(), tags).await; + assert!(matches!( + unwrap_gift_wrap(&recipient, &outer).await, + Err(Error::InvalidRecipient) + )); + } + let mut invalid_id = valid.clone(); + invalid_id.id = nostr::EventId::from_hex(&"00".repeat(32)).unwrap(); + assert!(matches!( + unwrap_gift_wrap(&recipient, &invalid_id).await, + Err(Error::GiftWrap) + )); + let mut invalid_sig = valid; + invalid_sig.sig = nostr::secp256k1::schnorr::Signature::from_slice(&[0; 64]).unwrap(); + assert!(matches!( + unwrap_gift_wrap(&recipient, &invalid_sig).await, + Err(Error::GiftWrap) + )); + for (kind, tags) in [ + (Kind::TextNote, vec![]), + (Kind::Seal, vec![Tag::public_key(recipient.public_key())]), + ] { + let wrong = EventBuilder::new(kind, content.clone()) + .tags(tags) + .custom_created_at(Timestamp::from_secs(1_700_000_001)) + .sign_with_keys(&sender) + .unwrap(); + let outer = wrap_raw_seal( + &recipient, + &wrong.as_json(), + vec![Tag::public_key(recipient.public_key())], + ) + .await; + assert!(matches!( + unwrap_gift_wrap(&recipient, &outer).await, + Err(Error::GiftWrap) + )); + } + for changed in [format!("{{\"kind\":13,{}", &seal.as_json()[1..]), { + let mut value: Value = serde_json::from_str(&seal.as_json()).unwrap(); + value["extra"] = json!(true); + value.to_string() + }] { + let outer = wrap_raw_seal( + &recipient, + &changed, + vec![Tag::public_key(recipient.public_key())], + ) + .await; + assert!(matches!( + unwrap_gift_wrap(&recipient, &outer).await, + Err(Error::GiftWrap) + )); + } +} + +#[tokio::test] +async fn known_rumor_shape_author_id_recipient_and_complete_size_are_checked() { + let sender = keys(1); + let recipient = keys(2); + let other = keys(4); + let original = rumor(&sender, &recipient, "Synthetic rumor validation"); + let raw = original.as_json(); + let mut missing: Value = serde_json::from_str(&raw).unwrap(); + missing.as_object_mut().unwrap().remove("id"); + for raw in [ + missing.to_string(), + format!("{{\"kind\":14,{}", &raw[1..]), + "[]".into(), + rumor(&other, &recipient, "Wrong author").as_json(), + rumor(&sender, &other, "Wrong recipient").as_json(), + rumor( + &sender, + &recipient, + &"a".repeat(radroots_protocol::chat::RUMOR_MAX_BYTES), + ) + .as_json(), + ] { + let outer = envelope(&sender, &recipient, &raw).await; + assert!(unwrap_gift_wrap(&recipient, &outer).await.is_err()); + } + let peer = envelope(&sender, &recipient, &original.as_json()).await; + let self_copy = envelope(&sender, &sender, &original.as_json()).await; + for (participant, event) in [(&recipient, peer), (&sender, self_copy)] { + let Rumor::Message(message) = unwrap_gift_wrap(participant, &event).await.unwrap() else { + panic!("expected chat") + }; + assert_eq!(message.id, original.id.unwrap().to_hex()); + assert_eq!(message.data.content, original.content); + assert_eq!( + message.data.recipients[0].public_key, + recipient.public_key().to_hex() + ); + } +} + +#[tokio::test] +async fn identity_changes_stop_opening_and_invalid_outer_never_invokes_the_signer() { + let sender = keys(1); + let recipient = keys(2); + let original = rumor(&sender, &recipient, "Synthetic scoped identity"); + let outer = envelope(&sender, &recipient, &original.as_json()).await; + for switch_at in [1, 2, usize::MAX] { + let observed = ObservedSigner { + keys: keys(2), + switch_at, + observations: AtomicUsize::new(0), + decryptions: AtomicUsize::new(0), + }; + let result = unwrap_gift_wrap(&observed, &outer).await; + if switch_at == usize::MAX { + assert!(result.is_ok()); + } else { + assert!(matches!(result, Err(Error::Signer))); + } + assert_eq!( + observed.decryptions.load(Ordering::SeqCst), + switch_at.min(2) + ); + } + let observed = ObservedSigner { + keys: keys(2), + switch_at: usize::MAX, + observations: AtomicUsize::new(0), + decryptions: AtomicUsize::new(0), + }; + let mut invalid = outer; + invalid.id = nostr::EventId::from_hex(&"00".repeat(32)).unwrap(); + assert!(matches!( + unwrap_gift_wrap(&observed, &invalid).await, + Err(Error::GiftWrap) + )); + assert_eq!(observed.observations.load(Ordering::SeqCst), 0); + assert_eq!(observed.decryptions.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn authentic_unknown_kind_is_unsupported_before_chat_tag_interpretation() { + let sender = keys(1); + let recipient = keys(2); + let mut value = rumor(&sender, &recipient, "Future private protocol content"); + value.kind = Kind::Custom(u16::MAX); + value.tags = nostr::Tags::default(); + value.id = None; + let _ = value.id(); + let outer = envelope(&sender, &recipient, &value.as_json()).await; + assert!(matches!( + unwrap_gift_wrap(&recipient, &outer).await, + Err(Error::UnsupportedRumorKind { kind: 65535 }) + )); +} + +#[tokio::test] +async fn invalid_outer_tag_structure_is_rejected_before_provider_callbacks() { + let sender = keys(1); + let recipient = keys(2); + let original = rumor(&sender, &recipient, "Synthetic structural admission"); + let content = sender + .nip44_encrypt(&recipient.public_key(), &original.as_json()) + .await + .unwrap(); + let seal = EventBuilder::new(Kind::Seal, content) + .custom_created_at(Timestamp::from_secs(1_700_000_001)) + .sign_with_keys(&sender) + .unwrap(); + let outer = wrap_raw_seal( + &recipient, + &seal.as_json(), + vec![ + Tag::public_key(recipient.public_key()), + Tag::parse(["", "invalid tag key"]).unwrap(), + ], + ) + .await; + outer.verify().unwrap(); + let observed = ObservedSigner { + keys: keys(2), + switch_at: usize::MAX, + observations: AtomicUsize::new(0), + decryptions: AtomicUsize::new(0), + }; + assert!(matches!( + unwrap_gift_wrap(&observed, &outer).await, + Err(Error::GiftWrap) + )); + assert_eq!(observed.observations.load(Ordering::SeqCst), 0); + assert_eq!(observed.decryptions.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn opening_admission_scalar_and_participant_negatives_are_not_normalized() { + let sender = keys(1); + let recipient = keys(2); + let original = rumor(&sender, &recipient, "Synthetic exact scalar checks"); + let original_value: Value = serde_json::from_str(&original.as_json()).unwrap(); + for (field, value) in [ + ("created_at", json!(253_402_300_800u64)), + ("tags", json!({})), + ("content", json!(0)), + ("id", json!(original.id.unwrap().to_hex().to_uppercase())), + ] { + let mut changed = original_value.clone(); + changed[field] = value; + let outer = envelope(&sender, &recipient, &changed.to_string()).await; + assert!( + matches!( + unwrap_gift_wrap(&recipient, &outer).await, + Err(Error::GiftWrap) + ), + "{field}" + ); + } + for tags in [ + vec![Tag::parse(["p"]).unwrap()], + vec![Tag::parse(["p", &recipient.public_key().to_hex(), "relay", "extra"]).unwrap()], + vec![Tag::parse(["p", &recipient.public_key().to_hex().to_uppercase()]).unwrap()], + vec![ + Tag::public_key(recipient.public_key()), + Tag::public_key(recipient.public_key()), + ], + vec![], + ] { + let mut changed = original.clone(); + changed.tags = nostr::Tags::from_list(tags); + changed.id = None; + let _ = changed.id(); + let outer = envelope(&sender, &recipient, &changed.as_json()).await; + assert!(matches!( + unwrap_gift_wrap(&recipient, &outer).await, + Err(Error::InvalidRecipient) + )); + } + let mut self_without_peers = original; + self_without_peers.tags = nostr::Tags::default(); + self_without_peers.id = None; + let _ = self_without_peers.id(); + let outer = envelope(&sender, &sender, &self_without_peers.as_json()).await; + assert!(matches!( + unwrap_gift_wrap(&sender, &outer).await, + Err(Error::InvalidRecipient) + )); +} + +#[tokio::test] +async fn opening_admission_outer_budgets_reject_before_provider_callbacks() { + let recipient = keys(2); + let ephemeral = keys(3); + let limits = radroots_event::wire::EventWireLimits::default(); + let empty = String::new(); + let large_content = "a".repeat(radroots_protocol::chat::SIGNED_MAX_BYTES + 1); + let too_many_tags = vec![Tag::parse(["x"]).unwrap(); limits.max_tag_count + 1]; + let too_many_fields = vec![Tag::parse(vec!["x"; limits.max_total_tag_elements + 1]).unwrap()]; + let too_many_bytes = vec![ + Tag::parse(vec![ + "x".repeat(limits.max_tag_element_bytes); + limits.max_total_tag_bytes + / limits.max_tag_element_bytes + + 1 + ]) + .unwrap(), + ]; + let large_field = + vec![Tag::parse(["x".into(), "a".repeat(limits.max_tag_element_bytes + 1)]).unwrap()]; + let mut long_p = vec!["p".into(), recipient.public_key().to_hex()]; + long_p.extend(["relay".into(), "extra".into()]); + let cases = [ + ( + Kind::TextNote, + &empty, + vec![Tag::public_key(recipient.public_key())], + ), + ( + Kind::GiftWrap, + &large_content, + vec![Tag::public_key(recipient.public_key())], + ), + (Kind::GiftWrap, &empty, too_many_tags), + (Kind::GiftWrap, &empty, too_many_fields), + (Kind::GiftWrap, &empty, too_many_bytes), + (Kind::GiftWrap, &empty, large_field), + ]; + for (kind, content, tags) in cases { + let outer = EventBuilder::new(kind, content) + .tags(tags) + .custom_created_at(Timestamp::from_secs(1_700_000_002)) + .sign_with_keys(&ephemeral) + .unwrap(); + outer.verify().unwrap(); + let observed = ObservedSigner { + keys: keys(2), + switch_at: usize::MAX, + observations: AtomicUsize::new(0), + decryptions: AtomicUsize::new(0), + }; + assert!(matches!( + unwrap_gift_wrap(&observed, &outer).await, + Err(Error::GiftWrap) + )); + assert_eq!(observed.observations.load(Ordering::SeqCst), 0); + assert_eq!(observed.decryptions.load(Ordering::SeqCst), 0); + } + let outer = EventBuilder::new(Kind::GiftWrap, empty) + .tags([Tag::parse(long_p).unwrap()]) + .custom_created_at(Timestamp::from_secs(1_700_000_002)) + .sign_with_keys(&ephemeral) + .unwrap(); + let observed = ObservedSigner { + keys: keys(2), + switch_at: usize::MAX, + observations: AtomicUsize::new(0), + decryptions: AtomicUsize::new(0), + }; + assert!(matches!( + unwrap_gift_wrap(&observed, &outer).await, + Err(Error::InvalidRecipient) + )); + assert_eq!(observed.decryptions.load(Ordering::SeqCst), 0); +} diff --git a/crates/nostr/tests/package_boundary.rs b/crates/nostr/tests/package_boundary.rs @@ -17,6 +17,9 @@ const EVENT_MODULE: &str = include_str!("../src/event.rs"); const FILTER_MODULE: &str = include_str!("../src/filter.rs"); const KEY_MODULE: &str = include_str!("../src/key.rs"); const NIP17_MODULE: &str = include_str!("../src/nip17.rs"); +const NIP17_OPENING: &str = include_str!("../src/nip17/opening.rs"); +const PRIVATE_OPENING_CONTRACT: &str = + include_str!("../../../contracts/protocol/private_opening.v1.json"); const BLOSSOM_MODULE: &str = include_str!("../src/blossom.rs"); const README: &str = include_str!("../README.md"); const SIGNING_MODULE: &str = include_str!("../src/signing.rs"); @@ -396,7 +399,7 @@ fn local_signer_consumes_only_the_opaque_secret_boundary() { fn focused_nip_and_blossom_features_own_no_network_operations() { for required in [ "blossom = [\"events\", \"dep:base64\", \"dep:radroots_blossom\"]", - "nip17 = [\"events\", \"nostr/nip44\", \"nostr/nip59\", \"dep:base64\", \"dep:radroots_protocol\"]", + "nip17 = [\"events\", \"nostr/nip44\", \"nostr/nip59\", \"dep:base64\", \"radroots_protocol/chat\"]", ] { assert!( MANIFEST.contains(required), @@ -424,7 +427,11 @@ fn focused_nip_and_blossom_features_own_no_network_operations() { "Blossom adapter is missing `{required}`" ); } - for (name, source) in [("NIP-17", NIP17_MODULE), ("Blossom", BLOSSOM_MODULE)] { + for (name, source) in [ + ("NIP-17", NIP17_MODULE), + ("NIP-17 opening", NIP17_OPENING), + ("Blossom", BLOSSOM_MODULE), + ] { for forbidden in [ "nostr_sdk", "reqwest::", @@ -461,6 +468,33 @@ fn focused_nip_and_blossom_features_own_no_network_operations() { } } +#[cfg(feature = "nip17")] +#[test] +fn private_opening_contract_preserves_bounded_protocol_only_scope() { + let contract: serde_json::Value = serde_json::from_str(PRIVATE_OPENING_CONTRACT).unwrap(); + assert_eq!( + contract["signed_max_utf8_bytes"], + radroots_protocol::chat::SIGNED_MAX_BYTES + ); + assert_eq!( + contract["rumor_max_utf8_bytes"], + radroots_protocol::chat::RUMOR_MAX_BYTES + ); + assert_eq!( + contract["supported_rumor_kinds"], + serde_json::json!([14, 15]) + ); + assert!(!NIP17_MODULE.contains("nip59::extract_rumor(signer, gift_wrap)")); + assert!(NIP17_MODULE.contains("opening::open(signer, gift_wrap)")); + assert!( + contract["limits"] + .as_array() + .unwrap() + .iter() + .any(|v| v.as_str().unwrap().contains("raw outer ingress")) + ); +} + #[test] fn production_api_declares_no_traits_or_host_runtime_implementations() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); diff --git a/crates/protocol/src/plan.rs b/crates/protocol/src/plan.rs @@ -121,6 +121,7 @@ pub enum SigningReplay { /// The actual provider independently binds exact replay to request identity. ExactReplayByRequestId, } +#[cfg(feature = "listing")] impl SigningReplay { pub(crate) const fn code(self) -> u8 { match self {