lib

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

private.rs (9268B)


      1 use radroots_identity::PublicKey;
      2 use radroots_signing::{
      3     provider::{
      4         NonceSource, ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText,
      5         ProviderCall, ProviderError, ProviderState,
      6     },
      7     signer::BoxFuture,
      8 };
      9 
     10 use super::LocalSigner;
     11 
     12 /// Explicit OS CSPRNG nonce source for native host composition. Constructing
     13 /// it performs no work; errors never return a partially filled nonce.
     14 pub struct OsNonceSource;
     15 
     16 impl NonceSource for OsNonceSource {
     17     fn next_nonce(&self) -> Result<[u8; 32], ProviderError> {
     18         use nostr::secp256k1::rand::{RngCore, rngs::OsRng};
     19         let mut nonce = [0; 32];
     20         OsRng
     21             .try_fill_bytes(&mut nonce)
     22             .map_err(|_| ProviderError::CapabilityUnavailable)?;
     23         Ok(nonce)
     24     }
     25 }
     26 
     27 impl LocalSigner {
     28     fn admit_crypto(&self, call: &ProviderCall) -> Result<(), ProviderError> {
     29         if call.identity() != self.public_key {
     30             return Err(ProviderError::IdentityChanged);
     31         }
     32         let now = (self.clock)().map_err(|_| ProviderError::ProviderFailure)?;
     33         call.check_before_effect(self.public_key, now)
     34     }
     35 }
     36 
     37 impl ParticipantProvider for LocalSigner {
     38     fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> {
     39         Box::pin(async move {
     40             let decryption = if cfg!(any(feature = "nip17", feature = "private_ingress")) {
     41                 PrivateCryptoCapability::Nip44V2
     42             } else {
     43                 PrivateCryptoCapability::Unavailable
     44             };
     45             let encryption = if cfg!(any(feature = "nip17", feature = "private_ingress"))
     46                 && self.nonce_source.is_some()
     47             {
     48                 PrivateCryptoCapability::Nip44V2
     49             } else {
     50                 PrivateCryptoCapability::Unavailable
     51             };
     52             Ok(ProviderState::new(
     53                 self.public_key,
     54                 encryption,
     55                 decryption,
     56                 radroots_signing::recovery::ReplayCapability::LocalReplaySafe,
     57             )
     58             .with_exact_issuance(Some(
     59                 radroots_signing::recovery::ReplayCapability::NonReplayable,
     60             ))
     61             .with_exact_recovery(
     62                 radroots_signing::issuance::ExactRecoveryCapability::LocalExactReplay,
     63             ))
     64         })
     65     }
     66 
     67     fn sign_exact(
     68         &self,
     69         intent: radroots_signing::issuance::SigningIntent,
     70     ) -> BoxFuture<'_, radroots_signing::issuance::SigningOutcome> {
     71         self.issue_exact(intent)
     72     }
     73 
     74     fn recover_exact(
     75         &self,
     76         request: radroots_signing::issuance::ExactRecoveryRequest,
     77     ) -> BoxFuture<'_, radroots_signing::issuance::ExactRecoveryOutcome> {
     78         self.recover_original(request)
     79     }
     80 
     81     fn encrypt_private(
     82         &self,
     83         call: ProviderCall,
     84         recipient: PublicKey,
     85         plaintext: PrivateText,
     86     ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> {
     87         Box::pin(async move {
     88             self.admit_crypto(&call)?;
     89             #[cfg(any(feature = "nip17", feature = "private_ingress"))]
     90             {
     91                 encrypt(self, recipient, &plaintext)
     92             }
     93             #[cfg(not(any(feature = "nip17", feature = "private_ingress")))]
     94             {
     95                 let _ = (recipient, plaintext);
     96                 Err(ProviderError::CapabilityUnavailable)
     97             }
     98         })
     99     }
    100 
    101     fn decrypt_private(
    102         &self,
    103         call: ProviderCall,
    104         sender: PublicKey,
    105         ciphertext: PrivateCiphertext,
    106     ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> {
    107         Box::pin(async move {
    108             self.admit_crypto(&call)?;
    109             #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    110             {
    111                 decrypt(self, sender, &ciphertext)
    112             }
    113             #[cfg(not(any(feature = "nip17", feature = "private_ingress")))]
    114             {
    115                 let _ = (sender, ciphertext);
    116                 Err(ProviderError::CapabilityUnavailable)
    117             }
    118         })
    119     }
    120 }
    121 
    122 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    123 fn encrypt(
    124     signer: &LocalSigner,
    125     recipient: PublicKey,
    126     plaintext: &PrivateText,
    127 ) -> Result<PrivateCiphertext, ProviderError> {
    128     use base64::Engine;
    129     use radroots_signing::provider::PRIVATE_CRYPTO_MAX_BYTES;
    130 
    131     let peer =
    132         crate::key::public_key_to_nostr(recipient).map_err(|_| ProviderError::InvalidInput)?;
    133     // The pinned codec uses a two-byte length prefix. Keep all intermediate
    134     // allocations within the public-event boundary before obtaining entropy.
    135     let length = plaintext.expose().len();
    136     if length > 65_408 {
    137         return Err(ProviderError::LimitExceeded);
    138     }
    139     let padded = if length <= 32 {
    140         32
    141     } else {
    142         let power = length.next_power_of_two();
    143         let chunk = if power <= 256 { 32 } else { power / 8 };
    144         length.div_ceil(chunk) * chunk
    145     };
    146     let encoded_length = (padded + 67).div_ceil(3) * 4;
    147     if encoded_length > PRIVATE_CRYPTO_MAX_BYTES {
    148         return Err(ProviderError::LimitExceeded);
    149     }
    150     let source = signer
    151         .nonce_source
    152         .as_ref()
    153         .ok_or(ProviderError::CapabilityUnavailable)?;
    154     let nonce = source.next_nonce()?;
    155     let payload = encrypt_payload(signer.keys.secret_key(), &peer, plaintext.expose(), nonce)?;
    156     PrivateCiphertext::parse(&base64::engine::general_purpose::STANDARD.encode(payload))
    157 }
    158 
    159 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    160 pub(super) fn encrypt_payload(
    161     secret: &nostr::SecretKey,
    162     recipient: &nostr::PublicKey,
    163     plaintext: &str,
    164     nonce: [u8; 32],
    165 ) -> Result<alloc::vec::Vec<u8>, ProviderError> {
    166     use nostr::nips::nip44::v2::{ConversationKey, encrypt_to_bytes_with_rng};
    167     let key = ConversationKey::derive(secret, recipient).map_err(normalize_crypto)?;
    168     let mut transcript = NonceTranscript {
    169         nonce,
    170         consumed: false,
    171         invalid: false,
    172     };
    173     let payload = encrypt_to_bytes_with_rng(&mut transcript, &key, plaintext.as_bytes())
    174         .map_err(normalize_crypto)?;
    175     if transcript.invalid || !transcript.consumed {
    176         return Err(ProviderError::ProviderFailure);
    177     }
    178     Ok(payload)
    179 }
    180 
    181 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    182 fn decrypt(
    183     signer: &LocalSigner,
    184     sender: PublicKey,
    185     ciphertext: &PrivateCiphertext,
    186 ) -> Result<PrivateText, ProviderError> {
    187     use base64::Engine;
    188     use nostr::nips::nip44::v2::{ConversationKey, decrypt_to_bytes};
    189     use zeroize::Zeroizing;
    190 
    191     let peer = crate::key::public_key_to_nostr(sender).map_err(|_| ProviderError::InvalidInput)?;
    192     let payload = base64::engine::general_purpose::STANDARD
    193         .decode(ciphertext.as_str())
    194         .map_err(|_| ProviderError::InvalidInput)?;
    195     if payload.len() < 99 {
    196         return Err(ProviderError::InvalidInput);
    197     }
    198     if payload.first() != Some(&2) {
    199         return Err(ProviderError::UnsupportedVersion);
    200     }
    201     let key = ConversationKey::derive(signer.keys.secret_key(), &peer).map_err(normalize_crypto)?;
    202     let plaintext = Zeroizing::new(decrypt_to_bytes(&key, &payload).map_err(normalize_crypto)?);
    203     let text = core::str::from_utf8(&plaintext).map_err(|_| ProviderError::InvalidInput)?;
    204     PrivateText::new(text)
    205 }
    206 
    207 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    208 fn normalize_crypto(error: nostr::nips::nip44::Error) -> ProviderError {
    209     use nostr::nips::nip44::{Error, v2::ErrorV2};
    210     match error {
    211         Error::UnknownVersion(_) => ProviderError::UnsupportedVersion,
    212         Error::V2(ErrorV2::InvalidHmac) => ProviderError::AuthenticationFailed,
    213         Error::V2(ErrorV2::MessageTooLong) | Error::MessageTooLong => ProviderError::LimitExceeded,
    214         _ => ProviderError::InvalidInput,
    215     }
    216 }
    217 
    218 // Transcribes one nonce already obtained from the injected source into the
    219 // pinned codec's RngCore API. This is not an RNG and implements no CryptoRng
    220 // claim. Any different consumption pattern is refused before returning output.
    221 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    222 struct NonceTranscript {
    223     nonce: [u8; 32],
    224     consumed: bool,
    225     invalid: bool,
    226 }
    227 
    228 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    229 impl Drop for NonceTranscript {
    230     fn drop(&mut self) {
    231         use zeroize::Zeroize;
    232         self.nonce.zeroize();
    233     }
    234 }
    235 
    236 #[cfg(any(feature = "nip17", feature = "private_ingress"))]
    237 impl nostr::secp256k1::rand::RngCore for NonceTranscript {
    238     fn next_u32(&mut self) -> u32 {
    239         self.invalid = true;
    240         0
    241     }
    242     fn next_u64(&mut self) -> u64 {
    243         self.invalid = true;
    244         0
    245     }
    246     fn fill_bytes(&mut self, output: &mut [u8]) {
    247         if self.consumed || output.len() != 32 {
    248             self.invalid = true;
    249             output.fill(0);
    250             return;
    251         }
    252         output.copy_from_slice(&self.nonce);
    253         self.consumed = true;
    254     }
    255     fn try_fill_bytes(&mut self, output: &mut [u8]) -> Result<(), nostr::secp256k1::rand::Error> {
    256         self.fill_bytes(output);
    257         if self.invalid {
    258             Err(nostr::secp256k1::rand::Error::from(
    259                 core::num::NonZeroU32::MIN,
    260             ))
    261         } else {
    262             Ok(())
    263         }
    264     }
    265 }
    266 
    267 #[cfg(test)]
    268 mod tests;