lib

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

opening.rs (8624B)


      1 //! Bounded opening for the existing protocol-only NIP-17 adapter.
      2 use super::{Error, Event, Kind, NostrSigner, PublicKey, UnsignedEvent};
      3 use alloc::{string::String, vec::Vec};
      4 use base64::Engine as _;
      5 use nostr::JsonUtil;
      6 use radroots_event::wire::EventWireLimits;
      7 use radroots_protocol::{
      8     chat::{RUMOR_MAX_BYTES, SIGNED_MAX_BYTES},
      9     nip01::{EventFields, signed_json_len},
     10 };
     11 use serde::Deserialize;
     12 use serde_json::value::RawValue;
     13 use zeroize::{Zeroize as _, Zeroizing};
     14 
     15 pub(super) struct OpenedRumor(pub(super) UnsignedEvent);
     16 impl Drop for OpenedRumor {
     17     fn drop(&mut self) {
     18         self.0.content.zeroize();
     19         for tag in core::mem::take(&mut self.0.tags) {
     20             tag.to_vec().zeroize();
     21         }
     22     }
     23 }
     24 
     25 fn ciphertext(value: &str) -> Result<(), Error> {
     26     if value.len() > SIGNED_MAX_BYTES {
     27         return Err(Error::GiftWrap);
     28     }
     29     let raw = base64::engine::general_purpose::STANDARD
     30         .decode(value)
     31         .map_err(|_| Error::GiftWrap)?;
     32     if raw.first() != Some(&2) || raw.len() < 99 || (raw.len() - 67) % 32 != 0 {
     33         return Err(Error::GiftWrap);
     34     }
     35     Ok(())
     36 }
     37 
     38 fn frame(raw: &str, limit: usize) -> Result<(), Error> {
     39     if raw.len() > limit || !raw.trim_start().starts_with('{') {
     40         return Err(Error::GiftWrap);
     41     }
     42     let (mut quoted, mut escaped, mut depth) = (false, false, 0u8);
     43     for byte in raw.bytes() {
     44         if quoted {
     45             if escaped {
     46                 escaped = false;
     47             } else if byte == b'\\' {
     48                 escaped = true;
     49             } else if byte == b'"' {
     50                 quoted = false;
     51             }
     52         } else {
     53             match byte {
     54                 b'"' => quoted = true,
     55                 b'{' | b'[' => {
     56                     depth = depth
     57                         .checked_add(1)
     58                         .filter(|n| *n <= 16)
     59                         .ok_or(Error::GiftWrap)?;
     60                 }
     61                 b'}' | b']' => {
     62                     depth = depth.checked_sub(1).ok_or(Error::GiftWrap)?;
     63                 }
     64                 _ => {}
     65             }
     66         }
     67     }
     68     if quoted || depth != 0 {
     69         return Err(Error::GiftWrap);
     70     }
     71     Ok(())
     72 }
     73 
     74 #[derive(Deserialize)]
     75 #[serde(deny_unknown_fields)]
     76 struct RawRumor<'a> {
     77     id: String,
     78     pubkey: String,
     79     created_at: u64,
     80     kind: u16,
     81     #[serde(borrow)]
     82     tags: &'a RawValue,
     83     #[serde(borrow)]
     84     content: &'a RawValue,
     85 }
     86 
     87 fn rumor(raw: &str, author: PublicKey, recipient: PublicKey) -> Result<OpenedRumor, Error> {
     88     frame(raw, RUMOR_MAX_BYTES)?;
     89     let fields: RawRumor<'_> = serde_json::from_str(raw).map_err(|_| Error::GiftWrap)?;
     90     if fields.created_at > 253_402_300_799
     91         || fields.pubkey != author.to_hex()
     92         || !fields.tags.get().trim_start().starts_with('[')
     93         || !fields.content.get().trim_start().starts_with('"')
     94     {
     95         return Err(Error::GiftWrap);
     96     }
     97     let declared = nostr::EventId::from_hex(&fields.id).map_err(|_| Error::GiftWrap)?;
     98     if declared.to_hex() != fields.id {
     99         return Err(Error::GiftWrap);
    100     }
    101     let opened = OpenedRumor(UnsignedEvent::from_json(raw).map_err(|_| Error::GiftWrap)?);
    102     let value = &opened.0;
    103     if value.id != Some(declared) || value.kind.as_u16() != fields.kind {
    104         return Err(Error::GiftWrap);
    105     }
    106     value.verify_id().map_err(|_| Error::GiftWrap)?;
    107     if !matches!(fields.kind, 14 | 15) {
    108         return Ok(opened);
    109     }
    110     let mut addressed = author == recipient;
    111     let mut peers = Vec::new();
    112     for tag in value.tags.as_slice() {
    113         let fields = tag.as_slice();
    114         if fields.first().map(String::as_str) == Some("p") {
    115             if !(2..=3).contains(&fields.len()) {
    116                 return Err(Error::InvalidRecipient);
    117             }
    118             let peer = PublicKey::from_hex(&fields[1]).map_err(|_| Error::InvalidRecipient)?;
    119             if peer.to_hex() != fields[1] || peers.contains(&peer) {
    120                 return Err(Error::InvalidRecipient);
    121             }
    122             peers.push(peer);
    123             addressed |= peer == recipient;
    124         }
    125     }
    126     if !addressed || peers.is_empty() {
    127         return Err(Error::InvalidRecipient);
    128     }
    129     Ok(opened)
    130 }
    131 
    132 fn signed(raw: &str) -> Result<radroots_event::envelope::EventEnvelope, Error> {
    133     crate::event_verify::signed_json(raw).map_err(|_| Error::GiftWrap)
    134 }
    135 
    136 fn outer(event: &Event) -> Result<(), Error> {
    137     let limits = EventWireLimits::default();
    138     if event.kind != Kind::GiftWrap
    139         || event.content.len() > SIGNED_MAX_BYTES
    140         || event.tags.len() > limits.max_tag_count
    141     {
    142         return Err(Error::GiftWrap);
    143     }
    144     let mut elements = 0usize;
    145     let mut bytes = 0usize;
    146     for tag in event.tags.as_slice() {
    147         for field in tag.as_slice() {
    148             elements += 1;
    149             bytes = bytes.checked_add(field.len()).ok_or(Error::GiftWrap)?;
    150             if elements > limits.max_total_tag_elements
    151                 || bytes > limits.max_total_tag_bytes
    152                 || field.len() > limits.max_tag_element_bytes
    153             {
    154                 return Err(Error::GiftWrap);
    155             }
    156         }
    157     }
    158     let tags = event
    159         .tags
    160         .iter()
    161         .map(|t| t.as_slice().to_vec())
    162         .collect::<Vec<_>>();
    163     let author = radroots_identity::PublicKey::from_hex(&event.pubkey.to_hex())
    164         .map_err(|_| Error::GiftWrap)?;
    165     signed_json_len(
    166         &EventFields {
    167             author,
    168             created_at: event.created_at.as_secs(),
    169             kind: u32::from(event.kind.as_u16()),
    170             tags: &tags,
    171             content: &event.content,
    172         },
    173         SIGNED_MAX_BYTES,
    174     )
    175     .map_err(|_| Error::GiftWrap)?;
    176     signed(&event.as_json())?;
    177     Ok(())
    178 }
    179 
    180 async fn identity<T: NostrSigner>(signer: &T, expected: PublicKey) -> Result<(), Error> {
    181     if signer.get_public_key().await? != expected {
    182         return Err(Error::Signer);
    183     }
    184     Ok(())
    185 }
    186 
    187 pub(super) async fn open<T: NostrSigner>(signer: &T, event: &Event) -> Result<OpenedRumor, Error> {
    188     outer(event)?;
    189     let recipient = signer.get_public_key().await?;
    190     let mut selected = None;
    191     for tag in event.tags.as_slice() {
    192         let fields = tag.as_slice();
    193         if fields.first().map(String::as_str) == Some("p") {
    194             if selected.is_some()
    195                 || !(2..=3).contains(&fields.len())
    196                 || fields[1] != recipient.to_hex()
    197             {
    198                 return Err(Error::InvalidRecipient);
    199             }
    200             selected = Some(recipient);
    201         }
    202     }
    203     if selected.is_none() {
    204         return Err(Error::InvalidRecipient);
    205     }
    206     ciphertext(&event.content)?;
    207     let raw = Zeroizing::new(signer.nip44_decrypt(&event.pubkey, &event.content).await?);
    208     identity(signer, recipient).await?;
    209     frame(&raw, SIGNED_MAX_BYTES)?;
    210     let seal = signed(&raw)?;
    211     if seal.kind_u32() != 13 || !seal.tags_as_vec().is_empty() {
    212         return Err(Error::GiftWrap);
    213     }
    214     let author = crate::key::public_key_to_nostr(*seal.author()).map_err(|_| Error::GiftWrap)?;
    215     ciphertext(seal.content())?;
    216     let raw = Zeroizing::new(signer.nip44_decrypt(&author, seal.content()).await?);
    217     identity(signer, recipient).await?;
    218     rumor(&raw, author, recipient)
    219 }
    220 
    221 #[cfg(test)]
    222 mod tests {
    223     use super::*;
    224 
    225     #[test]
    226     fn frame_bounds_include_escaped_string_delimiters_and_exact_depth() {
    227         for raw in [
    228             r#"{"text":"\"\\{[}]"}"#.into(),
    229             format!("{{\"value\":{}0{}}}", "[".repeat(15), "]".repeat(15)),
    230         ] {
    231             assert!(frame(&raw, raw.len()).is_ok());
    232             assert!(frame(&raw, raw.len() - 1).is_err());
    233         }
    234         for raw in [
    235             "[]".into(),
    236             "{".into(),
    237             "}".into(),
    238             "{\"unterminated".into(),
    239             format!("{{\"value\":{}0{}}}", "[".repeat(16), "]".repeat(16)),
    240         ] {
    241             assert!(frame(&raw, SIGNED_MAX_BYTES).is_err());
    242         }
    243     }
    244 
    245     #[test]
    246     fn only_bounded_structural_v2_ciphertext_reaches_a_signer() {
    247         let mut valid = vec![0; 99];
    248         valid[0] = 2;
    249         let encoded = base64::engine::general_purpose::STANDARD.encode(&valid);
    250         assert!(ciphertext(&encoded).is_ok());
    251         for raw in [
    252             "#future".into(),
    253             "!".repeat(132),
    254             "a".repeat(SIGNED_MAX_BYTES + 1),
    255             base64::engine::general_purpose::STANDARD.encode([2; 98]),
    256             base64::engine::general_purpose::STANDARD.encode([3; 99]),
    257             base64::engine::general_purpose::STANDARD.encode([2; 100]),
    258         ] {
    259             assert!(ciphertext(&raw).is_err());
    260         }
    261     }
    262 }