lib

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

commit eebc57b3235bb80660d157129fdecae29ea9e951
parent 14c5cd539d388fa3a835449679cb8ccbed8942fe
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 09:31:59 +0000

nostr: wrap retained seals without participant reissuance

- bound exact retained representations before obtaining entropy
- create temporary-key envelopes with explicit protocol randomness
- preserve opaque originals for protected capture and recovery
- verify crypto, portability, APIs and unchanged coverage gates

Diffstat:
Mcontracts/api_baselines/radroots_nostr.txt | 21+++++++++++++++++++++
Mcontracts/api_baselines/radroots_protocol.txt | 5+++++
Mcontracts/protocol/chat.v1.json | 17+++++++++++++++++
Mcrates/nostr/Cargo.toml | 3++-
Mcrates/nostr/README.md | 12++++++++++++
Mcrates/nostr/src/signing.rs | 2++
Acrates/nostr/src/signing/gift_wrap.rs | 237+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/nostr/src/signing/gift_wrap/tests.rs | 358+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/nostr/src/signing/private.rs | 27+++++++++++++++++++++++----
Mcrates/nostr/tests/package_boundary.rs | 14+++++++++++---
Mcrates/protocol/README.md | 5+++++
Mcrates/protocol/src/chat.rs | 2++
Acrates/protocol/src/chat/gift_wrap.rs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/gift_wrap_budget.rs | 44++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 788 insertions(+), 8 deletions(-)

diff --git a/contracts/api_baselines/radroots_nostr.txt b/contracts/api_baselines/radroots_nostr.txt @@ -264,6 +264,27 @@ pub async fn radroots_nostr::nip17::unwrap_gift_wrap<T>(&T, &nostr::event::Event pub async fn radroots_nostr::nip17::wrap_message<T>(&T, &radroots_event::social::message::Message, radroots_nostr::nip17::WrapOptions) -> core::result::Result<alloc::vec::Vec<nostr::event::Event>, radroots_nostr::nip17::Error> where T: nostr::signer::NostrSigner pub async fn radroots_nostr::nip17::wrap_message_file<T>(&T, &radroots_event::social::message_file::MessageFile, radroots_nostr::nip17::WrapOptions) -> core::result::Result<alloc::vec::Vec<nostr::event::Event>, radroots_nostr::nip17::Error> where T: nostr::signer::NostrSigner pub mod radroots_nostr::signing +pub mod radroots_nostr::signing::gift_wrap +pub enum radroots_nostr::signing::gift_wrap::WrapError +pub radroots_nostr::signing::gift_wrap::WrapError::CryptoFailure +pub radroots_nostr::signing::gift_wrap::WrapError::EntropyUnavailable +pub radroots_nostr::signing::gift_wrap::WrapError::InvalidSeal +pub radroots_nostr::signing::gift_wrap::WrapError::InvalidTime +pub radroots_nostr::signing::gift_wrap::WrapError::LimitExceeded +impl core::error::Error for radroots_nostr::signing::gift_wrap::WrapError +impl core::fmt::Display for radroots_nostr::signing::gift_wrap::WrapError +pub fn radroots_nostr::signing::gift_wrap::WrapError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_nostr::signing::gift_wrap::PendingGiftWrap +impl radroots_nostr::signing::gift_wrap::PendingGiftWrap +pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::event_id(&self) -> [u8; 32] +pub const fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::seal_digest(&self) -> [u8; 32] +pub const fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::seal_event_id(&self) -> [u8; 32] +pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::signed_json(&self) -> &str +pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::with_wrapping_key<T>(&self, impl core::ops::function::FnOnce(&[u8; 32]) -> T) -> T +impl core::fmt::Debug for radroots_nostr::signing::gift_wrap::PendingGiftWrap +pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub fn radroots_nostr::signing::gift_wrap::wrap_retained_seal(&str, radroots_identity::key::PublicKey, core::num::nonzero::NonZeroU64, &dyn radroots_signing::provider::NonceSource) -> core::result::Result<radroots_nostr::signing::gift_wrap::PendingGiftWrap, radroots_nostr::signing::gift_wrap::WrapError> pub struct radroots_nostr::signing::LocalSigner impl radroots_nostr::signing::LocalSigner pub fn radroots_nostr::signing::LocalSigner::generate() -> core::result::Result<Self, radroots_nostr::Error> diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -128,6 +128,11 @@ pub fn radroots_protocol::chat::DmRelayAdvertisement::from_tags(radroots_identit pub const fn radroots_protocol::chat::DmRelayAdvertisement::participant(&self) -> radroots_identity::key::PublicKey impl core::fmt::Debug for radroots_protocol::chat::DmRelayAdvertisement pub fn radroots_protocol::chat::DmRelayAdvertisement::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::chat::GiftWrapBudget +impl radroots_protocol::chat::GiftWrapBudget +pub const fn radroots_protocol::chat::GiftWrapBudget::ciphertext_bytes(self) -> usize +pub fn radroots_protocol::chat::GiftWrapBudget::for_seal(usize, radroots_identity::key::PublicKey) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub const fn radroots_protocol::chat::GiftWrapBudget::signed_max_bytes(self) -> usize pub const radroots_protocol::chat::PLAN_MAX_BYTES: usize pub const radroots_protocol::chat::RUMOR_MAX_BYTES: usize pub const radroots_protocol::chat::SIGNED_MAX_BYTES: usize diff --git a/contracts/protocol/chat.v1.json b/contracts/protocol/chat.v1.json @@ -166,5 +166,22 @@ "reporting": "Owned message only with scoped actual installation report; independent original installation and recipient work transactions; delivery pending and zero inferred relay observations", "qualification": "Separate exact-source executed evidence; declarations and data constructors are not qualification", "remaining": "Exact outer-envelope retention and per-target D observations, ordinary library-owned inbox jobs, browser/bindings, supported consumer adoption and all final gates" + }, + "outer_wrapping": { + "state": "retained_seal_crypto_component_implemented", + "owner": "radroots_nostr::signing::gift_wrap", + "budget_owner": "radroots_protocol::chat::GiftWrapBudget", + "source": "Exact seven-field, depth-bounded, ID and BIP-340 verified original kind13 event; empty tags and supported NIP44v2 payload shape; actual operation/recipient/capture linkage remains the composing journal responsibility", + "representation": "Encrypt original UTF8 bytes, including whitespace, not a canonical replacement; size complete nested output before requesting entropy", + "entropy": "Explicit qualified NonceSource for independent temporary key, unbiased randomized past timestamp, NIP44 nonce and BIP340 auxiliary randomness; no ambient clock or participant signer call. Upstream secp256k1 context blinding retains its own initialization contract; no ambient artifact-entropy fallback.", + "qualification": "Separate exact-source executed evidence; this declaration does not qualify durable capture, transport, a custom entropy source or a host runtime", + "temporary_material": "Opaque noncloneable pending outer holds zeroizing original 32-byte key and permits a scoped verification borrow. Known author and recipient keys are refused. The pinned upstream erases Keys/SecretKey on Drop using non_secure_erase; no total memory-erasure guarantee is claimed for upstream intermediate values.", + "bounds": { + "signed_event_bytes": 65536, + "past_timestamp_seconds": 172800, + "entropy_rejection_draws_per_selection": 16 + }, + "authority": "Construction authenticates a seal and creates an outer representation; it proves no grant, route, operation linkage, durable capture, scheduling lease or delivery", + "remaining": "Protected native exact-envelope and target-intent retention before transport, bound observations, ordinary owned inbox jobs, browser/binding runtime and final acceptance" } } diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml @@ -49,7 +49,7 @@ events = [ "radroots_event/serde", "radroots_event_codec/json", ] -nip17 = ["events", "nostr/nip44", "nostr/nip59", "dep:base64"] +nip17 = ["events", "nostr/nip44", "nostr/nip59", "dep:base64", "dep:radroots_protocol"] signing = [ "events", "dep:radroots_signing", @@ -64,6 +64,7 @@ radroots_event = { workspace = true, default-features = false } radroots_event_codec = { workspace = true, default-features = false } radroots_identity = { workspace = true, default-features = false } radroots_signing = { workspace = true, optional = true, default-features = false } +radroots_protocol = { workspace = true, optional = true, default-features = false, features = ["chat"] } nostr = { workspace = true, default-features = false, features = ["alloc"] } zeroize = { workspace = true, default-features = false, features = ["alloc"] } serde = { workspace = true, default-features = false, features = [ diff --git a/crates/nostr/README.md b/crates/nostr/README.md @@ -15,6 +15,18 @@ or cancellation check. These are crypto primitives: the composing executor authenticates carriers, enforces profile budgets and retains preimages before signing or transport. No private key is exported or message published. +With both `signing` and `nip17`, `signing::gift_wrap::wrap_retained_seal` +authenticates an already obtained kind-13 seal and wraps its exact original +bytes. It accepts an explicit positive time and qualified entropy source, +creates a separate temporary key, and never invokes the participant signer. +The complete nested budget is checked before entropy; randomized timestamps, +nonce generation and signing auxiliary randomness use the injected source. +`PendingGiftWrap` retains the exact outer bytes and temporary key for independent +protected-capture verification, with redacted diagnostics and no cloning or +automatic serialization. The caller must retain the envelope and its original +operation, recipient and route binding before transport. This primitive grants +no scheduling authority and proves no durable capture or relay observation. + Run `cargo extbuild run -- cargo run -p radroots_nostr --example participant_private --features signing,nip17 --locked` for the native OS-entropy smoke. It uses published synthetic vector identities, encrypts twice and diff --git a/crates/nostr/src/signing.rs b/crates/nostr/src/signing.rs @@ -21,6 +21,8 @@ use radroots_signing::{ use crate::{Error as NostrError, key::SecretKey}; +#[cfg(feature = "nip17")] +pub mod gift_wrap; mod issuance; mod private; pub use private::OsNonceSource; diff --git a/crates/nostr/src/signing/gift_wrap.rs b/crates/nostr/src/signing/gift_wrap.rs @@ -0,0 +1,237 @@ +//! Wrap an already obtained seal without invoking a participant signer. +//! The caller must retain the result before transport; construction proves no +//! admission, recipient authorization, route approval or durable capture. + +use alloc::vec; +use base64::Engine; +use core::{fmt, num::NonZeroU64}; +use nostr::{ + JsonUtil, + hashes::{Hash, sha256}, +}; +use radroots_event::{ + SignedEvent, + wire::{EventWireLimits, Nip01EventWire}, +}; +use radroots_identity::PublicKey; +use radroots_protocol::chat::{GiftWrapBudget, SIGNED_MAX_BYTES}; +use radroots_signing::provider::NonceSource; +use zeroize::Zeroizing; + +const MAX_TIME: u64 = 253_402_300_799; +const PAST_SECONDS: u64 = 172_800; +const ENTROPY_DRAWS: usize = 16; + +/// Fixed failures without input, ciphertext, key or dependency diagnostics. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum WrapError { + /// The original representation is not an authentic supported kind-13 seal. + InvalidSeal, + /// The exact nested representation exceeds the supported event budget. + LimitExceeded, + /// The supplied current time is outside the supported positive range. + InvalidTime, + /// The injected entropy source failed or exhausted bounded rejection draws. + EntropyUnavailable, + /// Cryptography or exact output validation failed. + CryptoFailure, +} +impl fmt::Display for WrapError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidSeal => "invalid retained seal", + Self::LimitExceeded => "gift wrap byte limit exceeded", + Self::InvalidTime => "invalid wrapping time", + Self::EntropyUnavailable => "wrapping entropy unavailable", + Self::CryptoFailure => "gift wrapping failed", + }) + } +} +impl core::error::Error for WrapError {} + +/// One obtained outer representation awaiting protected durable capture. +/// It is neither cloneable nor automatically serializable. Temporary wrapping +/// material belongs to this attempt, never to a participant identity. +pub struct PendingGiftWrap { + event: SignedEvent, + recipient: PublicKey, + seal_digest: [u8; 32], + seal_event_id: [u8; 32], + wrapping_key: Zeroizing<[u8; 32]>, +} +impl fmt::Debug for PendingGiftWrap { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PendingGiftWrap(<redacted>)") + } +} +impl PendingGiftWrap { + /// Exact complete signed bytes; retry these bytes after durable capture. + pub fn signed_json(&self) -> &str { + self.event.raw_json() + } + /// Actual outer event ID, distinct from seal and logical message IDs. + pub fn event_id(&self) -> [u8; 32] { + *self.event.envelope().id().as_bytes() + } + /// Selected recipient. This is not proof of the original operation binding. + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + /// SHA-256 of the exact original seal representation, including whitespace. + pub const fn seal_digest(&self) -> [u8; 32] { + self.seal_digest + } + /// Original independently verified seal event ID. + pub const fn seal_event_id(&self) -> [u8; 32] { + self.seal_event_id + } + /// Borrows this attempt's temporary key for independent capture verification. + /// The callback must not log, publish or retain this key as participant custody. + pub fn with_wrapping_key<T>(&self, verify: impl FnOnce(&[u8; 32]) -> T) -> T { + verify(&self.wrapping_key) + } +} + +fn entropy(source: &dyn NonceSource) -> Result<Zeroizing<[u8; 32]>, WrapError> { + source + .next_nonce() + .map(Zeroizing::new) + .map_err(|_| WrapError::EntropyUnavailable) +} + +fn past_time(now: u64, source: &dyn NonceSource) -> Result<u64, WrapError> { + let range = now.min(PAST_SECONDS + 1); + let threshold = range.wrapping_neg() % range; + for _ in 0..ENTROPY_DRAWS { + let bytes = entropy(source)?; + let mut selected = [0; 8]; + selected.copy_from_slice(&bytes[..8]); + let draw = u64::from_be_bytes(selected); + if draw >= threshold { + return Ok(now - draw % range); + } + } + Err(WrapError::EntropyUnavailable) +} + +fn wrapping_keys( + source: &dyn NonceSource, + author: PublicKey, + recipient: PublicKey, +) -> Result<(Zeroizing<[u8; 32]>, nostr::Keys), WrapError> { + for _ in 0..ENTROPY_DRAWS { + let bytes = entropy(source)?; + let Ok(secret) = nostr::SecretKey::from_slice(bytes.as_ref()) else { + continue; + }; + let keys = nostr::Keys::new(secret); + let public = keys.public_key().to_bytes(); + if public != *author.as_bytes() && public != *recipient.as_bytes() { + return Ok((bytes, keys)); + } + } + Err(WrapError::EntropyUnavailable) +} + +fn exact_event(raw: &str) -> Result<SignedEvent, WrapError> { + let limits = EventWireLimits { + max_raw_json_bytes: SIGNED_MAX_BYTES, + ..Default::default() + }; + let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits) + .map_err(|_| WrapError::InvalidSeal)?; + let event = + SignedEvent::from_wire_verified_id(wire, raw).map_err(|_| WrapError::InvalidSeal)?; + if crate::event_verify::verify_event(event.envelope()) + != crate::event_verify::Verification::Verified + { + return Err(WrapError::InvalidSeal); + } + Ok(event) +} + +/// Authenticates the bounded original seal and encrypts its exact bytes into a +/// signed kind-1059 envelope with one `p` tag. No participant signer, ambient +/// clock, transport, database or background task is accessed. Envelope key, +/// timestamp, nonce and signing auxiliary randomness use the injected source; +/// upstream secp256k1 context blinding retains its own initialization contract. +/// The source must provide qualified CSPRNG output; deterministic sources are test-only. +pub fn wrap_retained_seal( + raw_seal: &str, + recipient: PublicKey, + now: NonZeroU64, + source: &dyn NonceSource, +) -> Result<PendingGiftWrap, WrapError> { + if now.get() > MAX_TIME { + return Err(WrapError::InvalidTime); + } + if raw_seal.len() > SIGNED_MAX_BYTES { + return Err(WrapError::LimitExceeded); + } + let budget = GiftWrapBudget::for_seal(raw_seal.len(), recipient).map_err(|e| match e { + radroots_protocol::nip01::WireError::LimitExceeded => WrapError::LimitExceeded, + radroots_protocol::nip01::WireError::InvalidInput => WrapError::InvalidSeal, + })?; + let seal = exact_event(raw_seal)?; + let fields = seal.envelope(); + if fields.kind_u32() != 13 + || !fields.tags_as_vec().is_empty() + || fields.created_at_u64() == 0 + || fields.created_at_u64() > now.get() + || fields.created_at_u64() > MAX_TIME + { + return Err(WrapError::InvalidSeal); + } + let sealed_payload = base64::engine::general_purpose::STANDARD + .decode(fields.content()) + .map_err(|_| WrapError::InvalidSeal)?; + if sealed_payload.len() < 99 + || sealed_payload.first() != Some(&2) + || (sealed_payload.len() - 67) % 32 != 0 + { + return Err(WrapError::InvalidSeal); + } + let created_at = past_time(now.get(), source)?; + let (wrapping_key, keys) = wrapping_keys(source, *fields.author(), recipient)?; + let peer = crate::key::public_key_to_nostr(recipient).map_err(|_| WrapError::InvalidSeal)?; + let nonce = entropy(source)?; + let payload = super::private::encrypt_payload(keys.secret_key(), &peer, raw_seal, *nonce) + .map_err(|_| WrapError::CryptoFailure)?; + let content = base64::engine::general_purpose::STANDARD.encode(payload); + if content.len() != budget.ciphertext_bytes() { + return Err(WrapError::CryptoFailure); + } + let tags = nostr::Tags::from_list(vec![nostr::Tag::public_key(peer)]); + let mut unsigned = nostr::UnsignedEvent { + id: None, + pubkey: keys.public_key(), + created_at: nostr::Timestamp::from_secs(created_at), + kind: nostr::Kind::GiftWrap, + tags, + content, + }; + let aux = entropy(source)?; + let message = nostr::secp256k1::Message::from_digest(unsigned.id().to_bytes()); + let mut signing_key = + nostr::secp256k1::Keypair::from_secret_key(nostr::SECP256K1, keys.secret_key()); + let signature = nostr::SECP256K1.sign_schnorr_with_aux_rand(&message, &signing_key, &aux); + signing_key.non_secure_erase(); + let outer = unsigned + .add_signature(signature) + .map_err(|_| WrapError::CryptoFailure)?; + let raw = Zeroizing::new(outer.as_json()); + if raw.len() > budget.signed_max_bytes() { + return Err(WrapError::CryptoFailure); + } + let event = exact_event(&raw).map_err(|_| WrapError::CryptoFailure)?; + Ok(PendingGiftWrap { + event, + recipient, + seal_digest: sha256::Hash::hash(raw_seal.as_bytes()).to_byte_array(), + seal_event_id: *fields.id().as_bytes(), + wrapping_key, + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/nostr/src/signing/gift_wrap/tests.rs b/crates/nostr/src/signing/gift_wrap/tests.rs @@ -0,0 +1,358 @@ +use super::*; +use alloc::{string::String, vec::Vec}; +use nostr::nips::nip44::v2::{ConversationKey, decrypt_to_bytes}; +use radroots_signing::provider::ProviderError; +use std::sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, +}; + +const NOW: u64 = 1_700_200_000; +fn time(value: u64) -> NonZeroU64 { + NonZeroU64::new(value).unwrap() +} +fn keys(value: u8) -> nostr::Keys { + let mut key = [0; 32]; + key[31] = value; + nostr::Keys::new(nostr::SecretKey::from_slice(&key).unwrap()) +} +fn identity(keys: &nostr::Keys) -> PublicKey { + PublicKey::from_hex(&keys.public_key().to_hex()).unwrap() +} +#[derive(Default)] +struct Entropy { + calls: AtomicUsize, + fail_at: Option<usize>, + draws: Mutex<Vec<[u8; 32]>>, +} +impl NonceSource for Entropy { + fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { + let call = self.calls.fetch_add(1, Ordering::SeqCst); + if self.fail_at == Some(call) { + return Err(ProviderError::CapabilityUnavailable); + } + let mut draws = self.draws.lock().unwrap(); + if !draws.is_empty() { + Ok(draws.remove(0)) + } else { + Ok([42 + call as u8; 32]) + } + } +} +fn seal_with( + author: &nostr::Keys, + peer: &nostr::Keys, + kind: u16, + at: u64, + tags: Vec<nostr::Tag>, + content: Option<String>, +) -> (String, String) { + let mut rumor = nostr::UnsignedEvent { + id: None, + pubkey: author.public_key(), + created_at: nostr::Timestamp::from_secs(1_700_000_000), + kind: nostr::Kind::PrivateDirectMessage, + tags: nostr::Tags::from_list(vec![nostr::Tag::public_key(peer.public_key())]), + content: "original café 🌱\u{0000} message".into(), + }; + let _ = rumor.id(); + let original = rumor.as_json(); + let content = content.unwrap_or_else(|| { + base64::engine::general_purpose::STANDARD.encode( + super::super::private::encrypt_payload( + author.secret_key(), + &peer.public_key(), + &original, + [31; 32], + ) + .unwrap(), + ) + }); + let seal = nostr::EventBuilder::new(nostr::Kind::Custom(kind), content) + .tags(tags) + .custom_created_at(nostr::Timestamp::from_secs(at)) + .sign_with_keys(author) + .unwrap(); + (seal.as_json(), original) +} +fn seal(author: &nostr::Keys, peer: &nostr::Keys) -> (String, String) { + seal_with(author, peer, 13, 1_699_999_990, vec![], None) +} +fn decrypt(peer: &nostr::Keys, outer: &nostr::Event) -> Vec<u8> { + let key = ConversationKey::derive(peer.secret_key(), &outer.pubkey).unwrap(); + decrypt_to_bytes( + &key, + &base64::engine::general_purpose::STANDARD + .decode(&outer.content) + .unwrap(), + ) + .unwrap() +} + +#[tokio::test] +async fn peer_and_self_wrap_exact_retained_seals_without_participant_signing() { + let author = keys(1); + let peer = keys(2); + for recipient in [&peer, &author] { + let (raw, rumor) = seal(&author, recipient); + // Whitespace belongs to obtained representation, though not NIP-01 ID. + let original = format!(" \n{raw}\t"); + let entropy = Entropy::default(); + let pending = + wrap_retained_seal(&original, identity(recipient), time(NOW), &entropy).unwrap(); + let outer = nostr::Event::from_json(pending.signed_json()).unwrap(); + outer.verify().unwrap(); + assert_eq!(outer.id.to_bytes(), pending.event_id()); + assert_eq!(outer.kind, nostr::Kind::GiftWrap); + assert_eq!( + outer.tags.as_slice(), + &[nostr::Tag::public_key(recipient.public_key())] + ); + assert_ne!(outer.pubkey, author.public_key()); + assert_ne!(outer.pubkey, recipient.public_key()); + assert!((NOW - PAST_SECONDS..=NOW).contains(&outer.created_at.as_secs())); + assert_eq!(decrypt(recipient, &outer), original.as_bytes()); + let recovered = nostr::nips::nip59::extract_rumor(recipient, &outer) + .await + .unwrap(); + assert_eq!(recovered.sender, author.public_key()); + assert_eq!(recovered.rumor.as_json(), rumor); + assert_eq!(pending.recipient(), identity(recipient)); + assert_eq!( + pending.seal_digest(), + sha256::Hash::hash(original.as_bytes()).to_byte_array() + ); + assert_eq!( + pending.seal_event_id(), + nostr::Event::from_json(&raw).unwrap().id.to_bytes() + ); + pending.with_wrapping_key(|key| { + assert_eq!(keys_from(key).public_key(), outer.pubkey); + }); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 4); + assert_eq!(format!("{pending:?}"), "PendingGiftWrap(<redacted>)"); + assert!(pending.signed_json().len() <= SIGNED_MAX_BYTES); + } +} +fn keys_from(key: &[u8; 32]) -> nostr::Keys { + nostr::Keys::new(nostr::SecretKey::from_slice(key).unwrap()) +} + +#[test] +fn malformed_oversized_and_wrong_profile_seals_refuse_before_entropy() { + let author = keys(1); + let peer = keys(2); + let recipient = identity(&peer); + let (raw, _) = seal(&author, &peer); + let mut altered: serde_json::Value = serde_json::from_str(&raw).unwrap(); + altered["sig"] = serde_json::Value::String("0".repeat(128)); + let mut extra: serde_json::Value = serde_json::from_str(&raw).unwrap(); + extra["extra"] = 1.into(); + let mut bad_id: serde_json::Value = serde_json::from_str(&raw).unwrap(); + bad_id["id"] = "0".repeat(64).into(); + let mut malformed_payload = vec![2; 98]; + malformed_payload[0] = 3; + let cases = vec![ + ("".into(), WrapError::InvalidSeal), + ("{}".into(), WrapError::InvalidSeal), + ("x".repeat(SIGNED_MAX_BYTES + 1), WrapError::LimitExceeded), + ( + format!("{{\"kind\":13,{}", &raw[1..]), + WrapError::InvalidSeal, + ), + (altered.to_string(), WrapError::InvalidSeal), + (extra.to_string(), WrapError::InvalidSeal), + (bad_id.to_string(), WrapError::InvalidSeal), + ( + seal_with(&author, &peer, 1059, NOW, vec![], None).0, + WrapError::InvalidSeal, + ), + ( + seal_with(&author, &peer, 13, 0, vec![], None).0, + WrapError::InvalidSeal, + ), + ( + seal_with(&author, &peer, 13, NOW + 1, vec![], None).0, + WrapError::InvalidSeal, + ), + ( + seal_with( + &author, + &peer, + 13, + NOW, + vec![nostr::Tag::public_key(peer.public_key())], + None, + ) + .0, + WrapError::InvalidSeal, + ), + ( + seal_with(&author, &peer, 13, NOW, vec![], Some("not base64".into())).0, + WrapError::InvalidSeal, + ), + ( + seal_with( + &author, + &peer, + 13, + NOW, + vec![], + Some(base64::engine::general_purpose::STANDARD.encode(&malformed_payload)), + ) + .0, + WrapError::InvalidSeal, + ), + ]; + for (raw, expected) in cases { + let entropy = Entropy::default(); + assert_eq!( + wrap_retained_seal(&raw, recipient, time(NOW), &entropy).unwrap_err(), + expected + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 0); + } + let entropy = Entropy::default(); + assert_eq!( + wrap_retained_seal(&raw, recipient, time(MAX_TIME + 1), &entropy).unwrap_err(), + WrapError::InvalidTime + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 0); +} + +#[test] +fn exact_large_representation_cannot_hide_behind_small_canonical_seal() { + let author = keys(1); + let peer = keys(2); + let (raw, _) = seal(&author, &peer); + let original = format!("{}{raw}", " ".repeat(60_000)); + assert!(original.len() < SIGNED_MAX_BYTES); + let entropy = Entropy::default(); + assert_eq!( + wrap_retained_seal(&original, identity(&peer), time(NOW), &entropy).unwrap_err(), + WrapError::LimitExceeded + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 0); +} + +#[test] +fn large_supported_representation_and_latest_profile_time_execute_real_crypto() { + let author = keys(1); + let peer = keys(2); + let (raw, _) = seal(&author, &peer); + let original = format!("{}{raw}", " ".repeat(40_960 - raw.len())); + let pending = wrap_retained_seal( + &original, + identity(&peer), + time(MAX_TIME), + &Entropy::default(), + ) + .unwrap(); + let outer = nostr::Event::from_json(pending.signed_json()).unwrap(); + outer.verify().unwrap(); + assert_eq!(decrypt(&peer, &outer), original.as_bytes()); + assert!((MAX_TIME - PAST_SECONDS..=MAX_TIME).contains(&outer.created_at.as_secs())); + assert!( + pending.signed_json().len() + <= GiftWrapBudget::for_seal(original.len(), identity(&peer)) + .unwrap() + .signed_max_bytes() + ); +} + +#[test] +fn failure_at_each_entropy_boundary_preserves_original_input() { + let author = keys(1); + let peer = keys(2); + let (raw, _) = seal(&author, &peer); + let before = raw.clone(); + for fail_at in 0..4 { + let entropy = Entropy { + fail_at: Some(fail_at), + ..Default::default() + }; + assert_eq!( + wrap_retained_seal(&raw, identity(&peer), time(NOW), &entropy).unwrap_err(), + WrapError::EntropyUnavailable + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), fail_at + 1); + assert_eq!(raw, before); + } +} + +#[test] +fn rejection_sampling_is_bounded_and_never_uses_participant_keys() { + let author = keys(1); + let peer = keys(2); + let mut one = [0; 32]; + one[31] = 1; + let mut two = [0; 32]; + two[31] = 2; + let entropy = Entropy { + draws: Mutex::new(vec![[0; 32], [255; 32], one, two, [3; 32]]), + ..Default::default() + }; + let (_, generated) = wrapping_keys(&entropy, identity(&author), identity(&peer)).unwrap(); + assert_ne!(generated.public_key(), author.public_key()); + assert_ne!(generated.public_key(), peer.public_key()); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 5); + let entropy = Entropy { + draws: Mutex::new(vec![[0; 32]; ENTROPY_DRAWS]), + ..Default::default() + }; + assert!(matches!( + wrapping_keys(&entropy, identity(&author), identity(&peer)), + Err(WrapError::EntropyUnavailable) + )); + assert_eq!(entropy.calls.load(Ordering::SeqCst), ENTROPY_DRAWS); + let entropy = Entropy { + draws: Mutex::new(vec![[0; 32]; ENTROPY_DRAWS]), + ..Default::default() + }; + assert_eq!( + past_time(NOW, &entropy).unwrap_err(), + WrapError::EntropyUnavailable + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), ENTROPY_DRAWS); + assert_eq!(past_time(1, &Entropy::default()).unwrap(), 1); + let entropy = Entropy { + draws: Mutex::new(vec![[0; 32], [255; 32]]), + ..Default::default() + }; + let at = past_time(NOW, &entropy).unwrap(); + assert!((NOW - PAST_SECONDS..=NOW).contains(&at)); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 2); +} + +#[test] +fn temporary_wraps_are_separate_and_wrong_recipient_cannot_decrypt() { + let author = keys(1); + let peer = keys(2); + let (raw, _) = seal(&author, &peer); + let entropy = Entropy::default(); + let first = wrap_retained_seal(&raw, identity(&peer), time(NOW), &entropy).unwrap(); + let second = wrap_retained_seal(&raw, identity(&peer), time(NOW), &entropy).unwrap(); + assert_ne!(first.event_id(), second.event_id()); + assert_eq!(first.seal_digest(), second.seal_digest()); + let outer = nostr::Event::from_json(first.signed_json()).unwrap(); + let key = ConversationKey::derive(author.secret_key(), &outer.pubkey).unwrap(); + assert!( + decrypt_to_bytes( + &key, + &base64::engine::general_purpose::STANDARD + .decode(&outer.content) + .unwrap() + ) + .is_err() + ); + for error in [ + WrapError::InvalidSeal, + WrapError::LimitExceeded, + WrapError::InvalidTime, + WrapError::EntropyUnavailable, + WrapError::CryptoFailure, + ] { + assert!(error.to_string().len() < 40); + assert!(!error.to_string().contains(&raw)); + } +} diff --git a/crates/nostr/src/signing/private.rs b/crates/nostr/src/signing/private.rs @@ -114,7 +114,6 @@ fn encrypt( plaintext: &PrivateText, ) -> Result<PrivateCiphertext, ProviderError> { use base64::Engine; - use nostr::nips::nip44::v2::{ConversationKey, encrypt_to_bytes_with_rng}; use radroots_signing::provider::PRIVATE_CRYPTO_MAX_BYTES; let peer = @@ -141,18 +140,30 @@ fn encrypt( .as_ref() .ok_or(ProviderError::CapabilityUnavailable)?; let nonce = source.next_nonce()?; - let key = ConversationKey::derive(signer.keys.secret_key(), &peer).map_err(normalize_crypto)?; + let payload = encrypt_payload(signer.keys.secret_key(), &peer, plaintext.expose(), nonce)?; + PrivateCiphertext::parse(&base64::engine::general_purpose::STANDARD.encode(payload)) +} + +#[cfg(feature = "nip17")] +pub(super) fn encrypt_payload( + secret: &nostr::SecretKey, + recipient: &nostr::PublicKey, + plaintext: &str, + nonce: [u8; 32], +) -> Result<alloc::vec::Vec<u8>, ProviderError> { + use nostr::nips::nip44::v2::{ConversationKey, encrypt_to_bytes_with_rng}; + let key = ConversationKey::derive(secret, recipient).map_err(normalize_crypto)?; let mut transcript = NonceTranscript { nonce, consumed: false, invalid: false, }; - let payload = encrypt_to_bytes_with_rng(&mut transcript, &key, plaintext.expose().as_bytes()) + let payload = encrypt_to_bytes_with_rng(&mut transcript, &key, plaintext.as_bytes()) .map_err(normalize_crypto)?; if transcript.invalid || !transcript.consumed { return Err(ProviderError::ProviderFailure); } - PrivateCiphertext::parse(&base64::engine::general_purpose::STANDARD.encode(payload)) + Ok(payload) } #[cfg(feature = "nip17")] @@ -203,6 +214,14 @@ struct NonceTranscript { } #[cfg(feature = "nip17")] +impl Drop for NonceTranscript { + fn drop(&mut self) { + use zeroize::Zeroize; + self.nonce.zeroize(); + } +} + +#[cfg(feature = "nip17")] impl nostr::secp256k1::rand::RngCore for NonceTranscript { fn next_u32(&mut self) -> u32 { self.invalid = true; diff --git a/crates/nostr/tests/package_boundary.rs b/crates/nostr/tests/package_boundary.rs @@ -62,7 +62,7 @@ fn manifest_has_final_identity_features_and_radroots_dependencies() { "`{required}` must be required" ); } - for optional in ["radroots_signing", "radroots_blossom"] { + for optional in ["radroots_signing", "radroots_blossom", "radroots_protocol"] { let declaration = table_value(MANIFEST, "[dependencies]", optional) .unwrap_or_else(|| panic!("missing optional dependency `{optional}`")); assert!( @@ -81,6 +81,7 @@ fn manifest_has_final_identity_features_and_radroots_dependencies() { "radroots_event", "radroots_event_codec", "radroots_identity", + "radroots_protocol", "radroots_signing", ]) ); @@ -395,7 +396,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\"]", + "nip17 = [\"events\", \"nostr/nip44\", \"nostr/nip59\", \"dep:base64\", \"dep:radroots_protocol\"]", ] { assert!( MANIFEST.contains(required), @@ -565,7 +566,14 @@ fn superseded_surface_retirement_is_explicit_and_release_bounded() { assert_eq!( public_modules, BTreeSet::from([ - "blossom", "event", "filter", "key", "nip17", "signing", "tag" + "blossom", + "event", + "filter", + "key", + "nip17", + "signing", + "signing::gift_wrap", + "tag" ]), "reviewed API baseline must expose only chartered modules" ); diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -1,5 +1,10 @@ # radroots_protocol +The chat profile's `GiftWrapBudget` measures the complete kind-1059 envelope +for the exact already obtained seal representation. Whitespace in retained +signed JSON still consumes encryption and event budget; canonical event +identity does not permit replacing those bytes during recovery. + `radroots_protocol` defines the passive, versioned wire contracts shared by Radroots processes and language bindings. It is a `no_std + alloc` foundation crate: it validates schema identities and contract catalogs, but performs no diff --git a/crates/protocol/src/chat.rs b/crates/protocol/src/chat.rs @@ -25,6 +25,8 @@ mod plan; pub use plan::{ChatReplay, ChatSigningPlan, PLAN_MAX_BYTES}; mod routes; pub use routes::{CapturedDmRoute, DmRelayAdvertisement}; +mod gift_wrap; +pub use gift_wrap::GiftWrapBudget; fn payload_shape(plaintext_bytes: usize) -> Result<(usize, usize), WireError> { // The qualified small-payload profile uses the two-byte length prefix. diff --git a/crates/protocol/src/chat/gift_wrap.rs b/crates/protocol/src/chat/gift_wrap.rs @@ -0,0 +1,49 @@ +use super::{MAX_TIME, SIGNED_MAX_BYTES, nip44_v2_payload_len}; +use crate::nip01::{EventFields, WireError, signed_json_len}; +use alloc::{string::String, vec}; +use radroots_domain::PublicKey; + +/// Complete kind-1059 budget for an already obtained seal's exact UTF-8 bytes. +/// A canonical reserialization cannot stand in for the original representation. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct GiftWrapBudget { + ciphertext_bytes: usize, + signed_max_bytes: usize, +} + +impl GiftWrapBudget { + /// Counts padding, base64 and the complete one-recipient signed envelope. + /// This validates size only, without authenticating the seal or recipient. + pub fn for_seal(seal_bytes: usize, recipient: PublicKey) -> Result<Self, WireError> { + if seal_bytes >= SIGNED_MAX_BYTES { + return Err(WireError::LimitExceeded); + } + let ciphertext_bytes = nip44_v2_payload_len(seal_bytes)?; + let tags = [vec![String::from("p"), recipient.to_hex()]]; + let fields = EventFields { + author: recipient, + created_at: MAX_TIME, + kind: 1059, + tags: &tags, + content: "", + }; + let signed_max_bytes = signed_json_len(&fields, SIGNED_MAX_BYTES)? + ciphertext_bytes; + if signed_max_bytes > SIGNED_MAX_BYTES { + return Err(WireError::LimitExceeded); + } + Ok(Self { + ciphertext_bytes, + signed_max_bytes, + }) + } + + /// Exact encoded ciphertext size for this seal representation. + pub const fn ciphertext_bytes(self) -> usize { + self.ciphertext_bytes + } + + /// Complete signed JSON upper bound using the largest supported timestamp. + pub const fn signed_max_bytes(self) -> usize { + self.signed_max_bytes + } +} diff --git a/crates/protocol/tests/gift_wrap_budget.rs b/crates/protocol/tests/gift_wrap_budget.rs @@ -0,0 +1,44 @@ +#![cfg(feature = "chat")] + +use radroots_domain::PublicKey; +use radroots_protocol::{ + chat::{GiftWrapBudget, SIGNED_MAX_BYTES, nip44_v2_payload_len}, + nip01::WireError, +}; + +#[test] +fn complete_budget_matches_independent_json_serialization_and_refuses_excess() { + let key = + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(); + for size in [1, 32, 33, 257, 1024, 16_384, 32_768, 45_000, 65_535] { + let ciphertext_bytes = nip44_v2_payload_len(size).unwrap(); + let json = serde_json::json!({ + "id": "0".repeat(64), "pubkey": key.to_hex(), "created_at": 253_402_300_799_u64, + "kind": 1059, "tags": [["p", key.to_hex()]], "content": "A".repeat(ciphertext_bytes), + "sig": "0".repeat(128), + }) + .to_string(); + if json.len() <= SIGNED_MAX_BYTES { + let budget = GiftWrapBudget::for_seal(size, key).unwrap(); + assert_eq!(budget.ciphertext_bytes(), ciphertext_bytes); + assert_eq!(budget.signed_max_bytes(), json.len()); + assert!(format!("{budget:?}").contains("GiftWrapBudget")); + } else { + assert_eq!( + GiftWrapBudget::for_seal(size, key), + Err(WireError::LimitExceeded) + ); + } + } + assert_eq!( + GiftWrapBudget::for_seal(0, key), + Err(WireError::InvalidInput) + ); + for size in [65_536, 65_537, usize::MAX] { + assert_eq!( + GiftWrapBudget::for_seal(size, key), + Err(WireError::LimitExceeded) + ); + } +}