lib

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

commit 52e2a15a90aa4f07f053930be4dda203a0f6631a
parent efdc3db47881c95afc93beb3d05127cb837869d3
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 15:24:16 +0000

signing: Add bounded participant identity and private crypto providers

- Bind provider calls to the selected identity, deadline and cancellation input
- Keep private text zeroized and implement explicit local NIP-44 capabilities
- Verify primary vectors, payload bounds, sender recovery and native OS entropy
- Preserve portable host bounds, exact dependency graphs and reviewed public APIs

Diffstat:
MCargo.lock | 2++
MCargo.toml | 2+-
Mcontracts/api_baselines/radroots_nostr.txt | 9+++++++++
Mcontracts/api_baselines/radroots_signing.txt | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/coverage-profiles.toml | 2+-
Acontracts/signing/provider.v1.json | 25+++++++++++++++++++++++++
Mcrates/nostr/Cargo.toml | 7++++++-
Mcrates/nostr/README.md | 15+++++++++++++++
Acrates/nostr/examples/participant_private.rs | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/nostr/src/nip17.rs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/nostr/src/signing.rs | 19++++++++++++++++++-
Acrates/nostr/src/signing/private.rs | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/nostr/src/signing/private/tests.rs | 406+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/nostr/tests/fixtures/nip44_provider.v1.json | 14++++++++++++++
Mcrates/nostr/tests/package_boundary.rs | 2+-
Mcrates/secrets/Cargo.toml | 2+-
Mcrates/signing/Cargo.toml | 1+
Mcrates/signing/README.md | 22++++++++++++++++++++++
Mcrates/signing/src/lib.rs | 1+
Acrates/signing/src/provider.rs | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/signing/tests/package_boundary.rs | 6++++++
Acrates/signing/tests/provider.rs | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/sync/tests/fixtures/browser_host/Cargo.lock | 2++
Mcrates/sync/tests/fixtures/browser_host/Cargo.toml | 1+
Mcrates/sync/tests/host_bounds.rs | 49+++++++++++++++++++++++++++++++++++++++++++++++--
25 files changed, 1372 insertions(+), 8 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3233,6 +3233,7 @@ dependencies = [ "serde_json", "thiserror 2.0.18", "tokio", + "zeroize", ] [[package]] @@ -3516,6 +3517,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "zeroize", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml @@ -276,4 +276,4 @@ webpki-roots = { version = "0.26.11" } walkdir = { version = "2" } x509-parser = { version = "0.17", default-features = false } zstd = { version = "0.13", default-features = false } -zeroize = { version = "1" } +zeroize = { version = "1", default-features = false } diff --git a/contracts/api_baselines/radroots_nostr.txt b/contracts/api_baselines/radroots_nostr.txt @@ -269,11 +269,20 @@ impl radroots_nostr::signing::LocalSigner pub fn radroots_nostr::signing::LocalSigner::generate() -> core::result::Result<Self, radroots_nostr::Error> pub fn radroots_nostr::signing::LocalSigner::new(radroots_nostr::key::SecretKey) -> core::result::Result<Self, radroots_nostr::Error> pub const fn radroots_nostr::signing::LocalSigner::public_key(&self) -> radroots_identity::key::PublicKey +pub fn radroots_nostr::signing::LocalSigner::with_clock(radroots_nostr::key::SecretKey, fn() -> core::result::Result<u64, radroots_signing::error::Error>) -> core::result::Result<Self, radroots_nostr::Error> +pub fn radroots_nostr::signing::LocalSigner::with_nonce_source(self, radroots_signing::host::Shared<dyn radroots_signing::provider::NonceSource>) -> Self impl core::fmt::Debug for radroots_nostr::signing::LocalSigner pub fn radroots_nostr::signing::LocalSigner::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl radroots_signing::provider::ParticipantProvider for radroots_nostr::signing::LocalSigner +pub fn radroots_nostr::signing::LocalSigner::decrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCiphertext) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateText, radroots_signing::provider::ProviderError>> +pub fn radroots_nostr::signing::LocalSigner::encrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateText) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateCiphertext, radroots_signing::provider::ProviderError>> +pub fn radroots_nostr::signing::LocalSigner::provider_state(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError>> impl radroots_signing::signer::Signer for radroots_nostr::signing::LocalSigner pub fn radroots_nostr::signing::LocalSigner::sign(&self, radroots_signing::request::SignRequest) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::receipt::SignReceipt, radroots_signing::error::Error>> pub fn radroots_nostr::signing::LocalSigner::status(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::status::SignerStatus, radroots_signing::error::Error>> +pub struct radroots_nostr::signing::OsNonceSource +impl radroots_signing::provider::NonceSource for radroots_nostr::signing::OsNonceSource +pub fn radroots_nostr::signing::OsNonceSource::next_nonce(&self) -> core::result::Result<[u8; 32], radroots_signing::provider::ProviderError> pub mod radroots_nostr::tag pub enum radroots_nostr::tag::ResolveError pub radroots_nostr::tag::ResolveError::DecryptionError(alloc::string::String) diff --git a/contracts/api_baselines/radroots_signing.txt b/contracts/api_baselines/radroots_signing.txt @@ -145,6 +145,57 @@ pub fn radroots_signing::identity::SigningOperationId::new([u8; 16]) -> core::re pub fn radroots_signing::identity::SigningOperationId::to_hex(self) -> alloc::string::String impl core::fmt::Debug for radroots_signing::identity::SigningOperationId pub fn radroots_signing::identity::SigningOperationId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub mod radroots_signing::provider +pub enum radroots_signing::provider::PrivateCryptoCapability +pub radroots_signing::provider::PrivateCryptoCapability::Nip44V2 +pub radroots_signing::provider::PrivateCryptoCapability::Unavailable +#[non_exhaustive] pub enum radroots_signing::provider::ProviderError +pub radroots_signing::provider::ProviderError::AuthenticationFailed +pub radroots_signing::provider::ProviderError::Cancelled +pub radroots_signing::provider::ProviderError::CapabilityUnavailable +pub radroots_signing::provider::ProviderError::DeadlineExceeded +pub radroots_signing::provider::ProviderError::IdentityChanged +pub radroots_signing::provider::ProviderError::InvalidInput +pub radroots_signing::provider::ProviderError::LimitExceeded +pub radroots_signing::provider::ProviderError::ProviderFailure +pub radroots_signing::provider::ProviderError::UnsupportedVersion +impl radroots_signing::provider::ProviderError +pub const fn radroots_signing::provider::ProviderError::as_str(self) -> &'static str +impl core::error::Error for radroots_signing::provider::ProviderError +impl core::fmt::Display for radroots_signing::provider::ProviderError +pub fn radroots_signing::provider::ProviderError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_signing::provider::PrivateCiphertext(_) +impl radroots_signing::provider::PrivateCiphertext +pub fn radroots_signing::provider::PrivateCiphertext::as_str(&self) -> &str +pub fn radroots_signing::provider::PrivateCiphertext::parse(&str) -> core::result::Result<Self, radroots_signing::provider::ProviderError> +impl core::fmt::Debug for radroots_signing::provider::PrivateCiphertext +pub fn radroots_signing::provider::PrivateCiphertext::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_signing::provider::PrivateText(_) +impl radroots_signing::provider::PrivateText +pub fn radroots_signing::provider::PrivateText::expose(&self) -> &str +pub fn radroots_signing::provider::PrivateText::from_owned(alloc::string::String) -> core::result::Result<Self, radroots_signing::provider::ProviderError> +pub fn radroots_signing::provider::PrivateText::new(&str) -> core::result::Result<Self, radroots_signing::provider::ProviderError> +impl core::fmt::Debug for radroots_signing::provider::PrivateText +pub fn radroots_signing::provider::PrivateText::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_signing::provider::ProviderCall +impl radroots_signing::provider::ProviderCall +pub fn radroots_signing::provider::ProviderCall::check_before_effect(&self, radroots_identity::key::PublicKey, u64) -> core::result::Result<(), radroots_signing::provider::ProviderError> +pub const fn radroots_signing::provider::ProviderCall::identity(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_signing::provider::ProviderCall::new(radroots_identity::key::PublicKey, core::num::nonzero::NonZeroU64, radroots_signing::request::CancellationSignal) -> Self +pub struct radroots_signing::provider::ProviderState +impl radroots_signing::provider::ProviderState +pub const fn radroots_signing::provider::ProviderState::decryption(self) -> radroots_signing::provider::PrivateCryptoCapability +pub const fn radroots_signing::provider::ProviderState::encryption(self) -> radroots_signing::provider::PrivateCryptoCapability +pub const fn radroots_signing::provider::ProviderState::identity(self) -> radroots_identity::key::PublicKey +pub const fn radroots_signing::provider::ProviderState::new(radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCryptoCapability, radroots_signing::provider::PrivateCryptoCapability, radroots_signing::recovery::ReplayCapability) -> Self +pub const fn radroots_signing::provider::ProviderState::signing_replay(self) -> radroots_signing::recovery::ReplayCapability +pub const radroots_signing::provider::PRIVATE_CRYPTO_MAX_BYTES: usize +pub trait radroots_signing::provider::NonceSource: radroots_signing::host::HostBound +pub fn radroots_signing::provider::NonceSource::next_nonce(&self) -> core::result::Result<[u8; 32], radroots_signing::provider::ProviderError> +pub trait radroots_signing::provider::ParticipantProvider: radroots_signing::signer::Signer +pub fn radroots_signing::provider::ParticipantProvider::decrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCiphertext) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateText, radroots_signing::provider::ProviderError>> +pub fn radroots_signing::provider::ParticipantProvider::encrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateText) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::PrivateCiphertext, radroots_signing::provider::ProviderError>> +pub fn radroots_signing::provider::ParticipantProvider::provider_state(&self) -> radroots_signing::signer::BoxFuture<'_, core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError>> pub mod radroots_signing::receipt #[non_exhaustive] pub struct radroots_signing::receipt::AuthoredSignEvidence impl radroots_signing::receipt::AuthoredSignEvidence diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -20,7 +20,7 @@ test_threads = 1 [profiles.crates."radroots_nostr"] no_default_features = false -features = ["blossom"] +features = ["blossom", "signing", "nip17"] test_threads = 1 [profiles.crates."radroots_replica_sync"] diff --git a/contracts/signing/provider.v1.json b/contracts/signing/provider.v1.json @@ -0,0 +1,25 @@ +{ + "schema": "radroots.signing.participant_provider.v1", + "state": "native_local_implementation_in_qualification", + "identity": "Observed participant public key; neither an authenticated grant nor stock authority", + "crypto": "Bounded NIP-44 v2 primitives; executor authenticates carriers and applies stricter profile budgets", + "primitive_input_output_bytes": 65536, + "chat_and_record_limits_overridden": false, + "plaintext_ownership": "Bounded before copying; owned buffers zeroized on drop; no Clone or serialization; constant redacted Debug", + "nonce_entropy": "Explicit injected CSPRNG capability; trait and returned array supply no entropy qualification", + "native_nonce_transcription": "Exactly one 32-byte request into pinned codec RngCore; no CryptoRng claim; changed consumption refused before output", + "native_backend": { + "package": "nostr", + "version": "0.44.7", + "source": "crates.io", + "archive_sha256": "c7d3d987ea7078dc36947cde532637c472a229426702e4331dd7667325378bd9", + "scope": "Existing original-length codec within smaller Radroots profile limits; no extended-length capability claim" + }, + "admission": "Freeze expected provider identity and explicit deadline; reject cancelled/expired/mismatched calls before effects", + "obtained_results": "No post-effect deadline/cancellation check discards a returned result; executor retains preimages before signing", + "signing_replay": "Identity-scoped observation; never overrides retained unknown state or permits blind reissue", + "private_key_export": false, + "runtime_created": false, + "implicit_publication": false, + "remaining": ["Authenticated session attachment", "Durable command and obtained-result ownership", "Remote/platform/browser provider qualification", "Complete private chat and binding workflows"] +} 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"] +nip17 = ["events", "nostr/nip44", "nostr/nip59", "dep:base64"] signing = [ "events", "dep:radroots_signing", @@ -65,6 +65,7 @@ radroots_event_codec = { workspace = true, default-features = false } radroots_identity = { workspace = true, default-features = false } radroots_signing = { workspace = true, optional = true, default-features = false } nostr = { workspace = true, default-features = false, features = ["alloc"] } +zeroize = { workspace = true, default-features = false, features = ["alloc"] } serde = { workspace = true, default-features = false, features = [ "alloc", "derive", @@ -118,3 +119,7 @@ required-features = ["blossom"] [[test]] name = "nip17_conformance" required-features = ["nip17"] + +[[example]] +name = "participant_private" +required-features = ["signing", "nip17"] diff --git a/crates/nostr/README.md b/crates/nostr/README.md @@ -5,6 +5,21 @@ converts between canonical Radroots identity/event values and Nostr protocol values, provides typed NIP helpers, and supplies an optional concrete local implementation of the `radroots_signing` SPI. +With `signing`, `LocalSigner` also reports its actual participant identity. +With `nip17`, it decrypts bounded NIP-44 v2 payloads and can encrypt after +explicit nonce-source injection through `with_nonce_source`. Native hosts may +choose `OsNonceSource`; deterministic sources belong only in controlled tests. +Call identity/deadline/cancellation checks precede effects. Private text is +owned and redacted, and obtained outputs are not discarded by a later clock +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. + +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 +decrypts both results without persistence or network effects. + This crate owns no relay client. It owns no sockets, HTTP client, relay pool, database, account store, retry loop, scheduler, executor, or process-global state. Live Nostr transport belongs in `radroots_transport_nostr`; application diff --git a/crates/nostr/examples/participant_private.rs b/crates/nostr/examples/participant_private.rs @@ -0,0 +1,48 @@ +//! Native, nonpublishing provider smoke using published synthetic vector keys. +//! No persistent store, relay or real participant is used. + +use core::num::NonZeroU64; +use radroots_nostr::{ + key::parse_secret_key, + signing::{LocalSigner, OsNonceSource}, +}; +use radroots_signing::{ + host::Shared, + provider::{ParticipantProvider, PrivateText, ProviderCall}, + request::CancellationSignal, +}; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[tokio::main] +async fn main() -> Result<(), Box<dyn std::error::Error>> { + // Public NIP-44 interoperability identities; never use these for custody. + let alice = LocalSigner::new(parse_secret_key( + "0000000000000000000000000000000000000000000000000000000000000001", + )?)? + .with_nonce_source(Shared::new(OsNonceSource)); + let bob = LocalSigner::new(parse_secret_key( + "0000000000000000000000000000000000000000000000000000000000000002", + )?)?; + let now = u64::try_from(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis())?; + let deadline = NonZeroU64::new(now.checked_add(10_000).ok_or("deadline overflow")?) + .ok_or("deadline unavailable")?; + let call = |signer: &LocalSigner| { + ProviderCall::new(signer.public_key(), deadline, CancellationSignal::new()) + }; + let text = "synthetic local food inquiry"; + let first = alice + .encrypt_private(call(&alice), bob.public_key(), PrivateText::new(text)?) + .await?; + let second = alice + .encrypt_private(call(&alice), bob.public_key(), PrivateText::new(text)?) + .await?; + assert_ne!(first.as_str(), second.as_str()); + for ciphertext in [first, second] { + let opened = bob + .decrypt_private(call(&bob), alice.public_key(), ciphertext) + .await?; + assert_eq!(opened.expose(), text); + } + println!("Native participant provider: OS entropy and two decryptions passed"); + Ok(()) +} diff --git a/crates/nostr/src/nip17.rs b/crates/nostr/src/nip17.rs @@ -387,6 +387,55 @@ mod tests { } #[tokio::test] + async fn sender_recovery_uses_one_wrap_even_when_already_a_recipient() { + let sender = sender_keys(); + let receiver = receiver_keys(); + for already_included in [false, true] { + let mut recipients = vec![MessageRecipient { + public_key: receiver.public_key().to_string(), + relay_url: None, + }]; + if already_included { + recipients.push(MessageRecipient { + public_key: sender.public_key().to_string(), + relay_url: None, + }); + } + let message = Message { + recipients, + content: "synthetic sender recovery inquiry".to_owned(), + reply_to: None, + subject: None, + }; + let options = WrapOptions::default() + .with_rumor_created_at(1_700_000_002) + .with_gift_wrap_tags(vec![Vec::new(), vec!["client".into(), "fixture".into()]]); + assert!(options.includes_sender()); + assert_eq!(options.rumor_created_at(), Some(1_700_000_002)); + assert_eq!(options.gift_wrap_tags().len(), 2); + let events = wrap_message(&sender, &message, options).await.unwrap(); + assert_eq!(events.len(), 2); + for participant in [&sender, &receiver] { + let recipient = participant.public_key().to_string(); + let addressed: Vec<_> = events + .iter() + .filter(|event| { + event + .tags + .iter() + .any(|tag| tag.as_slice() == ["p".to_owned(), recipient.clone()]) + }) + .collect(); + assert_eq!(addressed.len(), 1); + match unwrap_gift_wrap(participant, addressed[0]).await.unwrap() { + Rumor::Message(metadata) => assert_eq!(metadata.data.content, message.content), + other => panic!("expected recovered message, got {other:?}"), + } + } + } + } + + #[tokio::test] async fn wrap_and_unwrap_message() { let sender = sender_keys(); let receiver = receiver_keys(); diff --git a/crates/nostr/src/signing.rs b/crates/nostr/src/signing.rs @@ -21,6 +21,9 @@ use radroots_signing::{ use crate::{Error as NostrError, key::SecretKey}; +mod private; +pub use private::OsNonceSource; + type Clock = fn() -> Result<u64, SigningError>; /// A local Nostr key-backed signer adapter. @@ -28,6 +31,8 @@ pub struct LocalSigner { keys: nostr::Keys, public_key: PublicKey, clock: Clock, + nonce_source: + Option<radroots_signing::host::Shared<dyn radroots_signing::provider::NonceSource>>, } impl LocalSigner { @@ -44,14 +49,26 @@ impl LocalSigner { self.public_key } - fn with_clock(secret_key: SecretKey, clock: Clock) -> Result<Self, crate::Error> { + /// Constructs the adapter with an explicit host clock. + pub fn with_clock(secret_key: SecretKey, clock: Clock) -> Result<Self, crate::Error> { let public_key = secret_key.public_key()?; Ok(Self { keys: secret_key.into_keys(), public_key, clock, + nonce_source: None, }) } + + /// Enables private encryption with explicitly injected nonce entropy. + /// Identity observation and decryption never export this provider's key. + pub fn with_nonce_source( + mut self, + source: radroots_signing::host::Shared<dyn radroots_signing::provider::NonceSource>, + ) -> Self { + self.nonce_source = Some(source); + self + } } impl fmt::Debug for LocalSigner { diff --git a/crates/nostr/src/signing/private.rs b/crates/nostr/src/signing/private.rs @@ -0,0 +1,227 @@ +use radroots_identity::PublicKey; +use radroots_signing::{ + provider::{ + NonceSource, ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, + ProviderCall, ProviderError, ProviderState, + }, + signer::BoxFuture, +}; + +use super::LocalSigner; + +/// Explicit OS CSPRNG nonce source for native host composition. Constructing +/// it performs no work; errors never return a partially filled nonce. +pub struct OsNonceSource; + +impl NonceSource for OsNonceSource { + fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { + use nostr::secp256k1::rand::{RngCore, rngs::OsRng}; + let mut nonce = [0; 32]; + OsRng + .try_fill_bytes(&mut nonce) + .map_err(|_| ProviderError::CapabilityUnavailable)?; + Ok(nonce) + } +} + +impl LocalSigner { + fn admit_crypto(&self, call: &ProviderCall) -> Result<(), ProviderError> { + if call.identity() != self.public_key { + return Err(ProviderError::IdentityChanged); + } + let now = (self.clock)().map_err(|_| ProviderError::ProviderFailure)?; + call.check_before_effect(self.public_key, now) + } +} + +impl ParticipantProvider for LocalSigner { + fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> { + Box::pin(async move { + let decryption = if cfg!(feature = "nip17") { + PrivateCryptoCapability::Nip44V2 + } else { + PrivateCryptoCapability::Unavailable + }; + let encryption = if cfg!(feature = "nip17") && self.nonce_source.is_some() { + PrivateCryptoCapability::Nip44V2 + } else { + PrivateCryptoCapability::Unavailable + }; + Ok(ProviderState::new( + self.public_key, + encryption, + decryption, + radroots_signing::recovery::ReplayCapability::LocalReplaySafe, + )) + }) + } + + fn encrypt_private( + &self, + call: ProviderCall, + recipient: PublicKey, + plaintext: PrivateText, + ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { + Box::pin(async move { + self.admit_crypto(&call)?; + #[cfg(feature = "nip17")] + { + encrypt(self, recipient, &plaintext) + } + #[cfg(not(feature = "nip17"))] + { + let _ = (recipient, plaintext); + Err(ProviderError::CapabilityUnavailable) + } + }) + } + + fn decrypt_private( + &self, + call: ProviderCall, + sender: PublicKey, + ciphertext: PrivateCiphertext, + ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { + Box::pin(async move { + self.admit_crypto(&call)?; + #[cfg(feature = "nip17")] + { + decrypt(self, sender, &ciphertext) + } + #[cfg(not(feature = "nip17"))] + { + let _ = (sender, ciphertext); + Err(ProviderError::CapabilityUnavailable) + } + }) + } +} + +#[cfg(feature = "nip17")] +fn encrypt( + signer: &LocalSigner, + recipient: PublicKey, + 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 = + crate::key::public_key_to_nostr(recipient).map_err(|_| ProviderError::InvalidInput)?; + // The pinned codec uses a two-byte length prefix. Keep all intermediate + // allocations within the public-event boundary before obtaining entropy. + let length = plaintext.expose().len(); + if length > 65_408 { + return Err(ProviderError::LimitExceeded); + } + let padded = if length <= 32 { + 32 + } else { + let power = length.next_power_of_two(); + let chunk = if power <= 256 { 32 } else { power / 8 }; + length.div_ceil(chunk) * chunk + }; + let encoded_length = (padded + 67).div_ceil(3) * 4; + if encoded_length > PRIVATE_CRYPTO_MAX_BYTES { + return Err(ProviderError::LimitExceeded); + } + let source = signer + .nonce_source + .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 mut transcript = NonceTranscript { + nonce, + consumed: false, + invalid: false, + }; + let payload = encrypt_to_bytes_with_rng(&mut transcript, &key, plaintext.expose().as_bytes()) + .map_err(normalize_crypto)?; + if transcript.invalid || !transcript.consumed { + return Err(ProviderError::ProviderFailure); + } + PrivateCiphertext::parse(&base64::engine::general_purpose::STANDARD.encode(payload)) +} + +#[cfg(feature = "nip17")] +fn decrypt( + signer: &LocalSigner, + sender: PublicKey, + ciphertext: &PrivateCiphertext, +) -> Result<PrivateText, ProviderError> { + use base64::Engine; + use nostr::nips::nip44::v2::{ConversationKey, decrypt_to_bytes}; + use zeroize::Zeroizing; + + let peer = crate::key::public_key_to_nostr(sender).map_err(|_| ProviderError::InvalidInput)?; + let payload = base64::engine::general_purpose::STANDARD + .decode(ciphertext.as_str()) + .map_err(|_| ProviderError::InvalidInput)?; + if payload.len() < 99 { + return Err(ProviderError::InvalidInput); + } + if payload.first() != Some(&2) { + return Err(ProviderError::UnsupportedVersion); + } + let key = ConversationKey::derive(signer.keys.secret_key(), &peer).map_err(normalize_crypto)?; + let plaintext = Zeroizing::new(decrypt_to_bytes(&key, &payload).map_err(normalize_crypto)?); + let text = core::str::from_utf8(&plaintext).map_err(|_| ProviderError::InvalidInput)?; + PrivateText::new(text) +} + +#[cfg(feature = "nip17")] +fn normalize_crypto(error: nostr::nips::nip44::Error) -> ProviderError { + use nostr::nips::nip44::{Error, v2::ErrorV2}; + match error { + Error::UnknownVersion(_) => ProviderError::UnsupportedVersion, + Error::V2(ErrorV2::InvalidHmac) => ProviderError::AuthenticationFailed, + Error::V2(ErrorV2::MessageTooLong) | Error::MessageTooLong => ProviderError::LimitExceeded, + _ => ProviderError::InvalidInput, + } +} + +// Transcribes one nonce already obtained from the injected source into the +// pinned codec's RngCore API. This is not an RNG and implements no CryptoRng +// claim. Any different consumption pattern is refused before returning output. +#[cfg(feature = "nip17")] +struct NonceTranscript { + nonce: [u8; 32], + consumed: bool, + invalid: bool, +} + +#[cfg(feature = "nip17")] +impl nostr::secp256k1::rand::RngCore for NonceTranscript { + fn next_u32(&mut self) -> u32 { + self.invalid = true; + 0 + } + fn next_u64(&mut self) -> u64 { + self.invalid = true; + 0 + } + fn fill_bytes(&mut self, output: &mut [u8]) { + if self.consumed || output.len() != 32 { + self.invalid = true; + output.fill(0); + return; + } + output.copy_from_slice(&self.nonce); + self.consumed = true; + } + fn try_fill_bytes(&mut self, output: &mut [u8]) -> Result<(), nostr::secp256k1::rand::Error> { + self.fill_bytes(output); + if self.invalid { + Err(nostr::secp256k1::rand::Error::from( + core::num::NonZeroU32::MIN, + )) + } else { + Ok(()) + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/nostr/src/signing/private/tests.rs b/crates/nostr/src/signing/private/tests.rs @@ -0,0 +1,406 @@ +use super::*; +#[cfg(feature = "nip17")] +use crate::test_fixtures::FIXTURE_CAROL; +use crate::{ + key::parse_secret_key, + test_fixtures::{FIXTURE_ALICE, FIXTURE_BOB}, +}; +use core::num::NonZeroU64; +#[cfg(feature = "nip17")] +use radroots_signing::provider::PRIVATE_CRYPTO_MAX_BYTES; +use radroots_signing::{host::Shared, recovery::ReplayCapability, request::CancellationSignal}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn clock() -> Result<u64, radroots_signing::Error> { + Ok(100) +} +#[cfg(feature = "nip17")] +fn unavailable_clock() -> Result<u64, radroots_signing::Error> { + Err(radroots_signing::Error::new( + radroots_signing::error::Kind::InternalError, + )) +} +fn signer(secret: &str) -> LocalSigner { + LocalSigner::with_clock(parse_secret_key(secret).unwrap(), clock).unwrap() +} +fn call(signer: &LocalSigner) -> ProviderCall { + ProviderCall::new( + signer.public_key(), + NonZeroU64::new(200).unwrap(), + CancellationSignal::new(), + ) +} + +struct FixedNonce { + calls: AtomicUsize, + fail: bool, + nonce: [u8; 32], +} +impl NonceSource for FixedNonce { + fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { + self.calls.fetch_add(1, Ordering::SeqCst); + if self.fail { + Err(ProviderError::CapabilityUnavailable) + } else { + Ok(self.nonce) + } + } +} +fn nonce_source(fail: bool) -> Shared<FixedNonce> { + let mut nonce = [0; 32]; + nonce[31] = 1; + Shared::new(FixedNonce { + calls: AtomicUsize::new(0), + fail, + nonce, + }) +} + +#[tokio::test] +async fn identity_and_caps_report_the_actual_configuration() { + let local = signer(FIXTURE_ALICE.secret_key_hex); + let state = local.provider_state().await.unwrap(); + assert_eq!(state.identity(), local.public_key()); + assert_eq!(state.encryption(), PrivateCryptoCapability::Unavailable); + assert_eq!( + state.decryption(), + if cfg!(feature = "nip17") { + PrivateCryptoCapability::Nip44V2 + } else { + PrivateCryptoCapability::Unavailable + } + ); + assert_eq!(state.signing_replay(), ReplayCapability::LocalReplaySafe); + let peer = signer(FIXTURE_BOB.secret_key_hex).public_key(); + assert_eq!( + local + .encrypt_private( + call(&local), + peer, + PrivateText::new("private question").unwrap() + ) + .await + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); + let local = local.with_nonce_source(nonce_source(false)); + assert_eq!( + local.provider_state().await.unwrap().encryption(), + if cfg!(feature = "nip17") { + PrivateCryptoCapability::Nip44V2 + } else { + PrivateCryptoCapability::Unavailable + } + ); + if !cfg!(feature = "nip17") { + let encoded = PrivateCiphertext::parse(&"A".repeat(132)).unwrap(); + assert_eq!( + local + .decrypt_private(call(&local), peer, encoded) + .await + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); + } +} + +#[cfg(feature = "nip17")] +#[tokio::test] +async fn exact_primary_vector_and_both_participant_directions() { + let vector: serde_json::Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/nip44_provider.v1.json" + )) + .unwrap(); + let encoded_nonce = vector["nonce"].as_str().unwrap(); + assert_eq!(encoded_nonce.len(), 64); + let mut nonce_bytes = [0; 32]; + for (index, byte) in nonce_bytes.iter_mut().enumerate() { + *byte = u8::from_str_radix(&encoded_nonce[index * 2..index * 2 + 2], 16).unwrap(); + } + let nonce = Shared::new(FixedNonce { + calls: AtomicUsize::new(0), + fail: false, + nonce: nonce_bytes, + }); + let alice = signer(vector["secret_a"].as_str().unwrap()).with_nonce_source(nonce.clone()); + let bob = signer(vector["secret_b"].as_str().unwrap()).with_nonce_source(nonce_source(false)); + let encrypted = alice + .encrypt_private( + call(&alice), + bob.public_key(), + PrivateText::new(vector["plaintext"].as_str().unwrap()).unwrap(), + ) + .await + .unwrap(); + assert_eq!(encrypted.as_str(), vector["ciphertext"].as_str().unwrap()); + assert_eq!(nonce.calls.load(Ordering::SeqCst), 1); + let opened = bob + .decrypt_private(call(&bob), alice.public_key(), encrypted) + .await + .unwrap(); + assert_eq!(opened.expose(), vector["plaintext"].as_str().unwrap()); + let reply = bob + .encrypt_private( + call(&bob), + alice.public_key(), + PrivateText::new("fresh tomatoes — pickup tomorrow").unwrap(), + ) + .await + .unwrap(); + assert_eq!( + alice + .decrypt_private(call(&alice), bob.public_key(), reply) + .await + .unwrap() + .expose(), + "fresh tomatoes — pickup tomorrow" + ); +} + +#[cfg(feature = "nip17")] +#[tokio::test] +async fn tampering_foreign_key_and_unsupported_version_remain_distinct() { + use base64::Engine; + let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(nonce_source(false)); + let bob = signer(FIXTURE_BOB.secret_key_hex); + let carol = signer(FIXTURE_CAROL.secret_key_hex); + let encrypted = alice + .encrypt_private( + call(&alice), + bob.public_key(), + PrivateText::new("private food inquiry").unwrap(), + ) + .await + .unwrap(); + let raw = base64::engine::general_purpose::STANDARD + .decode(encrypted.as_str()) + .unwrap(); + assert_eq!( + bob.decrypt_private( + call(&bob), + carol.public_key(), + PrivateCiphertext::parse(encrypted.as_str()).unwrap() + ) + .await + .unwrap_err(), + ProviderError::AuthenticationFailed + ); + let mut damaged = raw.clone(); + *damaged.last_mut().unwrap() ^= 1; + let encoded = base64::engine::general_purpose::STANDARD.encode(damaged); + assert_eq!( + bob.decrypt_private( + call(&bob), + alice.public_key(), + PrivateCiphertext::parse(&encoded).unwrap() + ) + .await + .unwrap_err(), + ProviderError::AuthenticationFailed + ); + let mut future = raw; + future[0] = 3; + let encoded = base64::engine::general_purpose::STANDARD.encode(future); + assert_eq!( + bob.decrypt_private( + call(&bob), + alice.public_key(), + PrivateCiphertext::parse(&encoded).unwrap() + ) + .await + .unwrap_err(), + ProviderError::UnsupportedVersion + ); +} + +#[cfg(feature = "nip17")] +#[tokio::test] +async fn identity_cancel_deadline_and_capacity_refuse_before_nonce_use() { + let entropy = nonce_source(false); + let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(entropy.clone()); + let bob = signer(FIXTURE_BOB.secret_key_hex); + let mismatched = ProviderCall::new( + bob.public_key(), + NonZeroU64::new(200).unwrap(), + CancellationSignal::new(), + ); + assert_eq!( + alice + .encrypt_private( + mismatched, + bob.public_key(), + PrivateText::new("private").unwrap() + ) + .await + .unwrap_err(), + ProviderError::IdentityChanged + ); + let cancelled = CancellationSignal::new(); + cancelled.cancel(); + let context = ProviderCall::new(alice.public_key(), NonZeroU64::new(200).unwrap(), cancelled); + assert_eq!( + alice + .encrypt_private( + context, + bob.public_key(), + PrivateText::new("private").unwrap() + ) + .await + .unwrap_err(), + ProviderError::Cancelled + ); + let expired = ProviderCall::new( + alice.public_key(), + NonZeroU64::new(100).unwrap(), + CancellationSignal::new(), + ); + assert_eq!( + alice + .encrypt_private( + expired, + bob.public_key(), + PrivateText::new("private").unwrap() + ) + .await + .unwrap_err(), + ProviderError::DeadlineExceeded + ); + let oversized = "x".repeat(PRIVATE_CRYPTO_MAX_BYTES); + assert_eq!( + alice + .encrypt_private( + call(&alice), + bob.public_key(), + PrivateText::new(&oversized).unwrap() + ) + .await + .unwrap_err(), + ProviderError::LimitExceeded + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 0); + let failed = LocalSigner::with_clock( + parse_secret_key(FIXTURE_ALICE.secret_key_hex).unwrap(), + unavailable_clock, + ) + .unwrap() + .with_nonce_source(entropy.clone()); + assert_eq!( + failed + .encrypt_private( + call(&failed), + bob.public_key(), + PrivateText::new("private").unwrap() + ) + .await + .unwrap_err(), + ProviderError::ProviderFailure + ); + assert_eq!(entropy.calls.load(Ordering::SeqCst), 0); +} + +#[cfg(feature = "nip17")] +#[tokio::test] +async fn bounded_full_rumor_and_entropy_failure_execute_the_real_codec() { + let entropy = nonce_source(false); + let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(entropy.clone()); + let bob = signer(FIXTURE_BOB.secret_key_hex); + for length in [1, 32, 33, 256, 257, 4096, 16384, 24576] { + let text = "a".repeat(length); + let encrypted = alice + .encrypt_private( + call(&alice), + bob.public_key(), + PrivateText::new(&text).unwrap(), + ) + .await + .unwrap(); + assert!(encrypted.as_str().len() <= PRIVATE_CRYPTO_MAX_BYTES); + assert_eq!( + bob.decrypt_private(call(&bob), alice.public_key(), encrypted) + .await + .unwrap() + .expose(), + text + ); + } + let failed_source = nonce_source(true); + let failed = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(failed_source.clone()); + assert_eq!( + failed + .encrypt_private( + call(&failed), + bob.public_key(), + PrivateText::new("private").unwrap() + ) + .await + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); + assert_eq!(failed_source.calls.load(Ordering::SeqCst), 1); +} + +#[cfg(feature = "nip17")] +#[tokio::test] +async fn malformed_payloads_and_encoded_size_refuse_without_entropy() { + let entropy = nonce_source(false); + let alice = signer(FIXTURE_ALICE.secret_key_hex).with_nonce_source(entropy.clone()); + let bob = signer(FIXTURE_BOB.secret_key_hex); + // This fits the codec's plaintext bound, but its encoded output would + // exceed the independent public-event boundary. + assert_eq!( + alice + .encrypt_private( + call(&alice), + bob.public_key(), + PrivateText::new(&"x".repeat(60_000)).unwrap(), + ) + .await + .unwrap_err(), + ProviderError::LimitExceeded + ); + for encoded in ["=".repeat(132), "A".repeat(130) + "=="] { + assert_eq!( + bob.decrypt_private( + call(&bob), + alice.public_key(), + PrivateCiphertext::parse(&encoded).unwrap(), + ) + .await + .unwrap_err(), + ProviderError::InvalidInput + ); + } + assert_eq!(entropy.calls.load(Ordering::SeqCst), 0); +} + +#[cfg(feature = "nip17")] +#[test] +fn codec_nonce_consumption_is_exact_and_has_no_rng_quality_claim() { + use nostr::secp256k1::rand::RngCore; + let mut source = NonceTranscript { + nonce: [7; 32], + consumed: false, + invalid: false, + }; + let mut bytes = [0; 32]; + source.try_fill_bytes(&mut bytes).unwrap(); + assert_eq!(bytes, [7; 32]); + assert!(source.try_fill_bytes(&mut bytes).is_err()); + for length in [0, 1, 31, 33, 64] { + let mut source = NonceTranscript { + nonce: [7; 32], + consumed: false, + invalid: false, + }; + source.fill_bytes(&mut vec![0; length]); + assert!(source.invalid); + } + let mut source = NonceTranscript { + nonce: [7; 32], + consumed: false, + invalid: false, + }; + assert_eq!(source.next_u32(), 0); + assert_eq!(source.next_u64(), 0); + assert!(source.invalid); +} diff --git a/crates/nostr/tests/fixtures/nip44_provider.v1.json b/crates/nostr/tests/fixtures/nip44_provider.v1.json @@ -0,0 +1,14 @@ +{ + "schema": "radroots.signing.nip44_provider_vector.v1", + "owning_package": "radroots_nostr", + "provenance": { + "source": "https://github.com/nostr-protocol/nips/blob/master/44.md#tests-and-code", + "classification": "Published synthetic interoperability vector; never a runtime identity or credential", + "purpose": "Independent exact ciphertext oracle for the source-owned local provider" + }, + "secret_a": "0000000000000000000000000000000000000000000000000000000000000001", + "secret_b": "0000000000000000000000000000000000000000000000000000000000000002", + "nonce": "0000000000000000000000000000000000000000000000000000000000000001", + "plaintext": "a", + "ciphertext": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb" +} diff --git a/crates/nostr/tests/package_boundary.rs b/crates/nostr/tests/package_boundary.rs @@ -395,7 +395,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\"]", + "nip17 = [\"events\", \"nostr/nip44\", \"nostr/nip59\", \"dep:base64\"]", ] { assert!( MANIFEST.contains(required), diff --git a/crates/secrets/Cargo.toml b/crates/secrets/Cargo.toml @@ -50,7 +50,7 @@ serde = { workspace = true, default-features = false, features = [ sha2 = { workspace = true, default-features = false } subtle = { workspace = true, default-features = false } tempfile = { workspace = true, optional = true } -zeroize = { workspace = true } +zeroize = { workspace = true, default-features = true } [dev-dependencies] futures-executor = { workspace = true } diff --git a/crates/signing/Cargo.toml b/crates/signing/Cargo.toml @@ -53,6 +53,7 @@ radroots_identity = { workspace = true, default-features = false } radroots_protocol = { workspace = true, default-features = false } hex = { version = "0.4", default-features = false, features = ["alloc"] } sha2 = { workspace = true, default-features = false } +zeroize = { workspace = true, default-features = false, features = ["alloc"] } serde = { workspace = true, default-features = false, features = [ "alloc", "derive", diff --git a/crates/signing/README.md b/crates/signing/README.md @@ -88,6 +88,28 @@ The complete externally implementable SPI example is ## Host SPI contract +The `provider` module adds a participant identity observation and separate +NIP-44 encryption/decryption capabilities. `ParticipantProvider` retains key +custody and exposes no secret key. `ProviderCall` freezes the observed key, +deadline and cancellation input without claiming authenticated command admission. +Private text is bounded before copying, zeroized when dropped and redacted in +diagnostics. The caller authenticates message carriers and applies the stricter +chat, record, rumor and complete-event limits before using these primitives. +Capability and replay observations do not replace actual provider qualification +or permit reissue of retained uncertain work. + +```compile_fail +use radroots_signing::provider::PrivateText; +let text = PrivateText::new("private inquiry").unwrap(); +let duplicate = text.clone(); +``` + +```compile_fail +use radroots_signing::provider::PrivateText; +let text = PrivateText::new("private inquiry").unwrap(); +let wire = serde_json::to_string(&text); +``` + `Signer` is externally implementable and object-safe. Native hosts retain `Send + Sync` and boxed `Future + Send`; WASM hosts and futures may remain local. `host::Shared` selects native `Arc` or browser `Rc` for signer and progress diff --git a/crates/signing/src/lib.rs b/crates/signing/src/lib.rs @@ -11,6 +11,7 @@ pub mod capability; pub mod error; pub mod host; pub mod identity; +pub mod provider; pub mod receipt; pub mod recovery; pub mod request; diff --git a/crates/signing/src/provider.rs b/crates/signing/src/provider.rs @@ -0,0 +1,275 @@ +//! Participant identity and custody-preserving private-message capabilities. +//! +//! Crypto primitives do not authorize a participant, verify a message carrier, +//! admit a command or establish durable execution. The composing executor must +//! authenticate the signed carrier before decryption and enforce its stricter +//! record/rumor/event budgets. Obtained results remain owned by that executor. + +#[cfg(not(feature = "std"))] +use alloc::string::String; +use core::{fmt, num::NonZeroU64}; +use radroots_identity::PublicKey; +#[cfg(feature = "std")] +use std::string::String; +use zeroize::Zeroizing; + +use crate::{Signer, host::HostBound, request::CancellationSignal, signer::BoxFuture}; + +/// Maximum bytes in one crypto boundary input or output. Profile budgets are +/// independently enforced before invoking this lower-level capability. +pub const PRIVATE_CRYPTO_MAX_BYTES: usize = 65_536; + +/// Fixed, source-redacted private-provider failures. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ProviderError { + /// Input representation is invalid. + InvalidInput, + /// The bounded crypto boundary cannot represent the input or output. + LimitExceeded, + /// The payload's encryption version is unsupported. + UnsupportedVersion, + /// Required provider support or entropy is unavailable. + CapabilityUnavailable, + /// The selected participant differs from this provider's current key. + IdentityChanged, + /// Authentication of the encrypted payload failed. + AuthenticationFailed, + /// Cancellation was observed before beginning work. + Cancelled, + /// The call's deadline expired before work began. + DeadlineExceeded, + /// A provider failed without returning private dependency diagnostics. + ProviderFailure, +} + +impl ProviderError { + /// Returns a stable diagnostic without private input or dependency prose. + pub const fn as_str(self) -> &'static str { + match self { + Self::InvalidInput => "invalid_input", + Self::LimitExceeded => "limit_exceeded", + Self::UnsupportedVersion => "unsupported_version", + Self::CapabilityUnavailable => "capability_unavailable", + Self::IdentityChanged => "identity_changed", + Self::AuthenticationFailed => "authentication_failed", + Self::Cancelled => "cancelled", + Self::DeadlineExceeded => "deadline_exceeded", + Self::ProviderFailure => "provider_failure", + } + } +} +impl fmt::Display for ProviderError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} +impl core::error::Error for ProviderError {} + +/// Owned private UTF-8 text with bounded construction and cleared storage on +/// drop. It has no serialization, cloning or input-bearing diagnostic surface. +pub struct PrivateText(Zeroizing<String>); + +impl PrivateText { + /// Checks the byte budget before copying borrowed input. + pub fn new(value: &str) -> Result<Self, ProviderError> { + if value.is_empty() { + return Err(ProviderError::InvalidInput); + } + if value.len() > PRIVATE_CRYPTO_MAX_BYTES { + return Err(ProviderError::LimitExceeded); + } + Ok(Self(Zeroizing::new(String::from(value)))) + } + + /// Takes already obtained private text without copying it. Failure also + /// clears the owned buffer; no rejected text is retained in an error. + pub fn from_owned(value: String) -> Result<Self, ProviderError> { + let value = Zeroizing::new(value); + if value.is_empty() { + return Err(ProviderError::InvalidInput); + } + if value.len() > PRIVATE_CRYPTO_MAX_BYTES { + return Err(ProviderError::LimitExceeded); + } + Ok(Self(value)) + } + + /// Explicitly borrows protected plaintext for its authorized consumer. + pub fn expose(&self) -> &str { + self.0.as_str() + } +} + +impl fmt::Debug for PrivateText { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PrivateText([redacted])") + } +} + +/// Owned bounded encoded ciphertext. Construction is structural only; it does +/// not verify its MAC, encryption version, author or signed-event carrier. +pub struct PrivateCiphertext(String); + +impl PrivateCiphertext { + /// Checks bounds before copying an untrusted provider or event payload. + pub fn parse(value: &str) -> Result<Self, ProviderError> { + if value.len() > PRIVATE_CRYPTO_MAX_BYTES { + return Err(ProviderError::LimitExceeded); + } + if value.starts_with('#') { + return Err(ProviderError::UnsupportedVersion); + } + if value.len() < 132 + || !value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=')) + { + return Err(ProviderError::InvalidInput); + } + Ok(Self(String::from(value))) + } + + /// Borrows encoded private evidence for storage or its authenticated carrier. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for PrivateCiphertext { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PrivateCiphertext([redacted])") + } +} + +/// One observed private-crypto method capability, not evidence of qualification. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PrivateCryptoCapability { + /// This provider cannot perform this method in its current configuration. + Unavailable, + /// The provider implements the bounded NIP-44 version-2 method. + Nip44V2, +} + +/// An identity/capability observation. It supplies neither a scoped grant nor +/// permission to sign, allocate stock or reinterpret a later identity change. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ProviderState { + identity: PublicKey, + encryption: PrivateCryptoCapability, + decryption: PrivateCryptoCapability, + signing_replay: crate::recovery::ReplayCapability, +} +impl ProviderState { + /// Reports capabilities actually implemented by the observing provider. + pub const fn new( + identity: PublicKey, + encryption: PrivateCryptoCapability, + decryption: PrivateCryptoCapability, + signing_replay: crate::recovery::ReplayCapability, + ) -> Self { + Self { + identity, + encryption, + decryption, + signing_replay, + } + } + /// Returns the observed participant key, independently of any hosted principal. + pub const fn identity(self) -> PublicKey { + self.identity + } + /// Returns current encryption support. + pub const fn encryption(self) -> PrivateCryptoCapability { + self.encryption + } + /// Returns current decryption support. + pub const fn decryption(self) -> PrivateCryptoCapability { + self.decryption + } + /// Returns signer replay behavior for this identity observation. This never + /// overrides retained uncertainty or permits blind signing reissue. + pub const fn signing_replay(self) -> crate::recovery::ReplayCapability { + self.signing_replay + } +} + +/// Explicit per-call identity, deadline and cooperative cancellation binding. +/// This value is not an authenticated command context or durable admission. +#[derive(Clone)] +pub struct ProviderCall { + identity: PublicKey, + deadline_unix_ms: NonZeroU64, + cancellation: CancellationSignal, +} +impl ProviderCall { + /// Freezes the identity observed by the owning session and its call budget. + pub const fn new( + identity: PublicKey, + deadline_unix_ms: NonZeroU64, + cancellation: CancellationSignal, + ) -> Self { + Self { + identity, + deadline_unix_ms, + cancellation, + } + } + /// Returns the participant key frozen by the owning session. + pub const fn identity(&self) -> PublicKey { + self.identity + } + /// Validates admission before an effect; never discard an obtained result + /// by repeating this check after the effect. + pub fn check_before_effect( + &self, + current_identity: PublicKey, + now_unix_ms: u64, + ) -> Result<(), ProviderError> { + if current_identity != self.identity { + return Err(ProviderError::IdentityChanged); + } + if self.cancellation.is_cancelled() { + return Err(ProviderError::Cancelled); + } + if now_unix_ms == 0 { + return Err(ProviderError::ProviderFailure); + } + if now_unix_ms >= self.deadline_unix_ms.get() { + return Err(ProviderError::DeadlineExceeded); + } + Ok(()) + } +} + +/// Injected nonce entropy. Production implementations must supply fresh, +/// uniformly random 32-byte output from a qualified CSPRNG. The trait and a +/// returned array do not themselves prove entropy quality or uniqueness. +pub trait NonceSource: HostBound { + /// Obtains one nonce or reports failure before encryption begins. + fn next_nonce(&self) -> Result<[u8; 32], ProviderError>; +} + +/// Custody-preserving participant provider. Native futures/handles retain their +/// thread guarantees; browser implementations may retain local UI/key handles. +/// No method exposes a private key or implicitly publishes a message. +pub trait ParticipantProvider: Signer { + /// Observes the actual key and currently available methods without signing. + fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>>; + /// Encrypts private text using provider-owned custody and qualified entropy. + /// The executor retains the returned preimage before any signing request. + fn encrypt_private( + &self, + call: ProviderCall, + recipient: PublicKey, + plaintext: PrivateText, + ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>>; + /// Decrypts an authenticated carrier's ciphertext. The executor must verify + /// its event ID/signature and bind its author before invoking this primitive. + fn decrypt_private( + &self, + call: ProviderCall, + sender: PublicKey, + ciphertext: PrivateCiphertext, + ) -> BoxFuture<'_, Result<PrivateText, ProviderError>>; +} diff --git a/crates/signing/tests/package_boundary.rs b/crates/signing/tests/package_boundary.rs @@ -44,6 +44,7 @@ fn manifest_has_final_identity_features_and_dependencies() { "radroots_protocol", "serde", "sha2", + "zeroize", ]) ); assert_eq!( @@ -76,6 +77,7 @@ fn crate_root_declares_the_approved_module_skeleton() { "error", "host", "identity", + "provider", "recovery", "request", "receipt", @@ -97,6 +99,7 @@ fn crate_root_declares_the_approved_module_skeleton() { "error", "host", "identity", + "provider", "receipt", "recovery", "request", @@ -195,6 +198,7 @@ fn every_public_module_has_crate_level_documentation() { "error", "host", "identity", + "provider", "recovery", "request", "receipt", @@ -255,6 +259,8 @@ fn production_sources_publish_only_the_approved_traits_and_no_host_stack() { [ "CurrentAuthoringAuthority", "HostBound", + "NonceSource", + "ParticipantProvider", "ProgressObserver", "Signer" ] diff --git a/crates/signing/tests/provider.rs b/crates/signing/tests/provider.rs @@ -0,0 +1,143 @@ +use radroots_identity::PublicKey; +use radroots_signing::{provider::*, recovery::ReplayCapability, request::CancellationSignal}; +use std::{error::Error as _, num::NonZeroU64, str::FromStr}; + +fn identity() -> PublicKey { + PublicKey::from_str("585591529da0bab31b3b1b1f986611cf5f435dca84f978c89ee8a40cca7103df").unwrap() +} +fn other() -> PublicKey { + PublicKey::from_str("e0266e3cfb0d2886f91c73f5f868f3b98273713e5fcd97c081663f5518a4b3af").unwrap() +} + +#[test] +fn private_values_admit_exact_byte_bounds_without_diagnostic_or_wire_exposure() { + let private = "private buyer question — do not log"; + let text = PrivateText::new(private).unwrap(); + assert_eq!(text.expose(), private); + assert_eq!(format!("{text:?}"), "PrivateText([redacted])"); + assert!(matches!( + PrivateText::new(""), + Err(ProviderError::InvalidInput) + )); + assert!(matches!( + PrivateText::from_owned(String::new()), + Err(ProviderError::InvalidInput) + )); + for text in [ + "a".repeat(PRIVATE_CRYPTO_MAX_BYTES), + "é".repeat(PRIVATE_CRYPTO_MAX_BYTES / 2), + ] { + assert_eq!( + PrivateText::new(&text).unwrap().expose().len(), + PRIVATE_CRYPTO_MAX_BYTES + ); + assert_eq!( + PrivateText::from_owned(text).unwrap().expose().len(), + PRIVATE_CRYPTO_MAX_BYTES + ); + } + let too_long = "a".repeat(PRIVATE_CRYPTO_MAX_BYTES + 1); + assert!(matches!( + PrivateText::new(&too_long), + Err(ProviderError::LimitExceeded) + )); + assert!(matches!( + PrivateText::from_owned(too_long), + Err(ProviderError::LimitExceeded) + )); + for bad in ["", "abc", "!", "a".repeat(131).as_str()] { + assert!(matches!( + PrivateCiphertext::parse(bad), + Err(ProviderError::InvalidInput) + )); + } + assert!(matches!( + PrivateCiphertext::parse("#future"), + Err(ProviderError::UnsupportedVersion) + )); + assert!(matches!( + PrivateCiphertext::parse(&"a".repeat(PRIVATE_CRYPTO_MAX_BYTES + 1)), + Err(ProviderError::LimitExceeded) + )); + assert!(matches!( + PrivateCiphertext::parse(&(String::from("!") + &"a".repeat(132))), + Err(ProviderError::InvalidInput) + )); + let encoded = "a".repeat(PRIVATE_CRYPTO_MAX_BYTES); + let ciphertext = PrivateCiphertext::parse(&encoded).unwrap(); + assert_eq!(ciphertext.as_str(), encoded); + assert_eq!(format!("{ciphertext:?}"), "PrivateCiphertext([redacted])"); +} + +#[test] +fn call_binding_is_not_interchangeable_with_another_identity_or_expired_budget() { + let signal = CancellationSignal::new(); + let call = ProviderCall::new(identity(), NonZeroU64::new(200).unwrap(), signal.clone()); + assert_eq!(call.identity(), identity()); + assert_eq!(call.check_before_effect(identity(), 100), Ok(())); + assert_eq!( + call.check_before_effect(other(), 100), + Err(ProviderError::IdentityChanged) + ); + assert_eq!( + call.check_before_effect(identity(), 0), + Err(ProviderError::ProviderFailure) + ); + assert_eq!( + call.check_before_effect(identity(), 200), + Err(ProviderError::DeadlineExceeded) + ); + assert_eq!( + call.check_before_effect(identity(), 201), + Err(ProviderError::DeadlineExceeded) + ); + signal.cancel(); + assert_eq!( + call.check_before_effect(identity(), 100), + Err(ProviderError::Cancelled) + ); + assert_eq!( + call.clone().check_before_effect(identity(), 100), + Err(ProviderError::Cancelled) + ); +} + +#[test] +fn capabilities_are_separate_method_observations_and_errors_retain_no_cause() { + for encryption in [ + PrivateCryptoCapability::Unavailable, + PrivateCryptoCapability::Nip44V2, + ] { + for decryption in [ + PrivateCryptoCapability::Unavailable, + PrivateCryptoCapability::Nip44V2, + ] { + for replay in [ + ReplayCapability::ExactReplayByRequestId, + ReplayCapability::LocalReplaySafe, + ReplayCapability::NonReplayable, + ] { + let state = ProviderState::new(identity(), encryption, decryption, replay); + assert_eq!(state.identity(), identity()); + assert_eq!(state.encryption(), encryption); + assert_eq!(state.decryption(), decryption); + assert_eq!(state.signing_replay(), replay); + } + } + } + for error in [ + ProviderError::InvalidInput, + ProviderError::LimitExceeded, + ProviderError::UnsupportedVersion, + ProviderError::CapabilityUnavailable, + ProviderError::IdentityChanged, + ProviderError::AuthenticationFailed, + ProviderError::Cancelled, + ProviderError::DeadlineExceeded, + ProviderError::ProviderFailure, + ] { + assert_eq!(error.to_string(), error.as_str()); + assert!(error.source().is_none()); + assert!(format!("{error:?}").len() < 32); + } +} diff --git a/crates/sync/tests/fixtures/browser_host/Cargo.lock b/crates/sync/tests/fixtures/browser_host/Cargo.lock @@ -498,6 +498,7 @@ dependencies = [ "futures", "radroots_event", "radroots_event_codec", + "radroots_identity", "radroots_signing", "radroots_storage", "radroots_sync", @@ -571,6 +572,7 @@ dependencies = [ "radroots_identity", "radroots_protocol", "sha2", + "zeroize", ] [[package]] diff --git a/crates/sync/tests/fixtures/browser_host/Cargo.toml b/crates/sync/tests/fixtures/browser_host/Cargo.toml @@ -9,6 +9,7 @@ license = "MIT OR Apache-2.0" [workspace] [dependencies] +radroots_identity = { path = "../../../../identity", version = "=0.1.0-alpha", default-features = false } radroots_sync = { path = "../../..", version = "=0.1.0-alpha", default-features = false } radroots_signing = { path = "../../../../signing", version = "=0.1.0-alpha", default-features = false } radroots_storage = { path = "../../../../storage", version = "=0.1.0-alpha", default-features = false } diff --git a/crates/sync/tests/host_bounds.rs b/crates/sync/tests/host_bounds.rs @@ -8,6 +8,8 @@ fn every_native_port_retains_its_thread_guarantees() { fn send_sync<T: Send + Sync + ?Sized>() {} fn send<T: Send + ?Sized>() {} send_sync::<dyn radroots_signing::Signer>(); + send_sync::<dyn radroots_signing::provider::ParticipantProvider>(); + send_sync::<dyn radroots_signing::provider::NonceSource>(); send_sync::<dyn radroots_signing::CurrentAuthoringAuthority>(); send_sync::<dyn radroots_signing::request::ProgressObserver>(); send_sync::<dyn radroots_transport::EventSource>(); @@ -65,6 +67,44 @@ mod browser { self.failed(signing::Error::new(signing::error::Kind::SignerUnavailable)) } } + impl signing::provider::NonceSource for Local { + fn next_nonce(&self) -> Result<[u8; 32], signing::provider::ProviderError> { + self.0.set(self.0.get() + 1); + Err(signing::provider::ProviderError::CapabilityUnavailable) + } + } + impl signing::provider::ParticipantProvider for Local { + fn provider_state( + &self, + ) -> signing::signer::BoxFuture< + '_, + Result<signing::provider::ProviderState, signing::provider::ProviderError>, + > { + self.failed(signing::provider::ProviderError::CapabilityUnavailable) + } + fn encrypt_private( + &self, + _: signing::provider::ProviderCall, + _: radroots_identity::PublicKey, + _: signing::provider::PrivateText, + ) -> signing::signer::BoxFuture< + '_, + Result<signing::provider::PrivateCiphertext, signing::provider::ProviderError>, + > { + self.failed(signing::provider::ProviderError::CapabilityUnavailable) + } + fn decrypt_private( + &self, + _: signing::provider::ProviderCall, + _: radroots_identity::PublicKey, + _: signing::provider::PrivateCiphertext, + ) -> signing::signer::BoxFuture< + '_, + Result<signing::provider::PrivateText, signing::provider::ProviderError>, + > { + self.failed(signing::provider::ProviderError::CapabilityUnavailable) + } + } impl signing::request::ProgressObserver for Local { fn on_progress(&self, _: &signing::status::SignProgress) { self.0.set(self.0.get() + 1); @@ -190,6 +230,10 @@ mod browser { fn browser_ports_accept_real_local_callback_and_future_state() { let state = Rc::new(Cell::new(0)); let signer: signing::signer::DynSigner = SignerHandle::new(Local(state.clone())); + let participant: SignerHandle<dyn signing::provider::ParticipantProvider> = + SignerHandle::new(Local(state.clone())); + let nonces: SignerHandle<dyn signing::provider::NonceSource> = + SignerHandle::new(Local(state.clone())); let source: transport::host::Shared<dyn EventSource> = Rc::new(Local(state.clone())); let sink: transport::host::Shared<dyn EventSink> = Rc::new(Local(state.clone())); let subscriber: transport::host::Shared<dyn EventSubscriber> = @@ -200,13 +244,14 @@ mod browser { let authority: Rc<dyn signing::CurrentAuthoringAuthority> = Rc::new(Local(state.clone())); let clock: transport::host::Shared<dyn Clock> = Rc::new(Local(state.clone())); let ids: transport::host::Shared<dyn IdSource> = Rc::new(Local(state.clone())); - drop((sink, subscriber, observer, authority, clock, ids)); + drop((sink, subscriber, observer, authority, clock, ids, nonces)); futures::executor::block_on(async { assert!(signer.status().await.is_err()); + assert!(participant.provider_state().await.is_err()); assert!(source.status().await.is_err()); assert!(store.status().await.is_err()); }); - assert_eq!(state.get(), 3); + assert_eq!(state.get(), 4); fn owned_subscription( request: transport::SubscriptionRequest, state: Rc<Cell<usize>>,