lib

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

input.rs (8182B)


      1 //! Closed known-profile input admission. Domain construction remains the sole
      2 //! value invariant owner; no unknown field or unsupported feature is discarded.
      3 use super::PublishInput;
      4 use crate::command::{CommandError, check_frame, required_nullable};
      5 use crate::listing_values::{OptionInput, RawProduct};
      6 use alloc::{string::String, vec::Vec};
      7 use radroots_domain::{AuthorityRef, ListingOptionId, UnixSeconds, listing::*};
      8 use serde::Deserialize;
      9 
     10 #[derive(Deserialize)]
     11 #[serde(deny_unknown_fields)]
     12 struct Input {
     13     id: ListingId,
     14     title: String,
     15     summary: String,
     16     description_markdown: String,
     17     published_at: UnixSeconds,
     18     profile: Profile,
     19 }
     20 #[derive(Deserialize)]
     21 #[serde(deny_unknown_fields)]
     22 struct Profile {
     23     profile: String,
     24     version: u32,
     25     state: State,
     26     product: RawProduct,
     27     default_option: ListingOptionId,
     28     options: Vec<OptionInput>,
     29     fulfillment: Fulfillment,
     30     #[serde(deserialize_with = "required_nullable")]
     31     authority: Option<AuthorityRef>,
     32     media: Vec<RawMedia>,
     33 }
     34 #[derive(Deserialize)]
     35 #[serde(deny_unknown_fields)]
     36 struct RawMedia {
     37     url: String,
     38     sha256: String,
     39     mime: String,
     40     alt: String,
     41 }
     42 #[derive(Deserialize)]
     43 #[serde(rename_all = "snake_case")]
     44 enum State {
     45     Active,
     46     Paused,
     47     Withdrawn,
     48 }
     49 #[derive(Deserialize)]
     50 #[serde(deny_unknown_fields)]
     51 struct Fulfillment {
     52     modes: Vec<Mode>,
     53     area: String,
     54     lead_seconds: LeadSeconds,
     55 }
     56 #[derive(Deserialize)]
     57 #[serde(rename_all = "snake_case")]
     58 enum Mode {
     59     Pickup,
     60     Delivery,
     61 }
     62 
     63 fn invalid<T, E>(value: Result<T, E>) -> Result<T, CommandError> {
     64     value.map_err(|_| CommandError::InvalidInput)
     65 }
     66 impl Input {
     67     fn validate(self) -> Result<PublishInput, CommandError> {
     68         let terms = self.profile.terms()?;
     69         PublishInput::new(
     70             self.id,
     71             &self.title,
     72             &self.summary,
     73             &self.description_markdown,
     74             self.published_at,
     75             terms,
     76         )
     77         .map_err(|_| CommandError::InvalidInput)
     78     }
     79 }
     80 impl Profile {
     81     fn terms(self) -> Result<ListingTerms, CommandError> {
     82         let profile = self;
     83         if profile.profile != "radroots.listing" || profile.version != 1 {
     84             return Err(CommandError::UnsupportedProfile);
     85         }
     86         let product = profile.product.domain()?;
     87         if profile.options.is_empty() || profile.options.len() > 16 {
     88             return Err(CommandError::LimitExceeded);
     89         }
     90         let mut options = Vec::with_capacity(profile.options.len());
     91         for option in profile.options {
     92             options.push(option.domain()?);
     93         }
     94         let fulfillment = invalid(PublicFulfillment::new(
     95             profile
     96                 .fulfillment
     97                 .modes
     98                 .into_iter()
     99                 .map(|mode| match mode {
    100                     Mode::Pickup => FulfillmentMode::Pickup,
    101                     Mode::Delivery => FulfillmentMode::Delivery,
    102                 })
    103                 .collect(),
    104             &profile.fulfillment.area,
    105             profile.fulfillment.lead_seconds,
    106         ))?;
    107         invalid(ListingTerms::new(
    108             match profile.state {
    109                 State::Active => ListingState::Active,
    110                 State::Paused => ListingState::Paused,
    111                 State::Withdrawn => ListingState::Withdrawn,
    112             },
    113             product,
    114             profile.default_option,
    115             options,
    116             fulfillment,
    117             profile.authority,
    118             profile
    119                 .media
    120                 .into_iter()
    121                 .map(|media| {
    122                     invalid(Media::from_hex_digest(
    123                         &media.url,
    124                         &media.sha256,
    125                         &media.mime,
    126                         &media.alt,
    127                     ))
    128                 })
    129                 .collect::<Result<Vec<_>, _>>()?,
    130         ))
    131     }
    132 }
    133 impl PublishInput {
    134     /// Admits bounded closed sale-option input. Known unsupported features
    135     /// return an explicit refusal; they are never silently stripped or coerced.
    136     pub fn parse(raw: &[u8]) -> Result<Self, CommandError> {
    137         check_frame(raw)?;
    138         // This bounded peek only classifies unimplemented features. Acceptance
    139         // still requires the independent closed parser, including duplicates,
    140         // required nulls and all nested domain constructors.
    141         let value: serde_json::Value =
    142             serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
    143         if let Some(profile) = value.get("profile") {
    144             supported(profile)?;
    145         }
    146         object_shapes(&value)?;
    147         let input: Input = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
    148         input.validate()
    149     }
    150 }
    151 
    152 // Serde's derived struct decoder also accepts positional sequences. The wire
    153 // profile requires JSON objects; this bounded structural pass never supplies
    154 // acceptance without the independent duplicate/unknown-field-aware parser.
    155 fn object(value: &serde_json::Value) -> Result<(), CommandError> {
    156     if value.is_object() {
    157         Ok(())
    158     } else {
    159         Err(CommandError::InvalidInput)
    160     }
    161 }
    162 fn object_shapes(value: &serde_json::Value) -> Result<(), CommandError> {
    163     object(value)?;
    164     let profile = &value["profile"];
    165     object(profile)?;
    166     object(&profile["product"])?;
    167     object(&profile["fulfillment"])?;
    168     let media = profile["media"]
    169         .as_array()
    170         .ok_or(CommandError::InvalidInput)?;
    171     if media.len() > ListingTerms::MAX_MEDIA {
    172         return Err(CommandError::LimitExceeded);
    173     }
    174     for reference in media {
    175         object(reference)?;
    176     }
    177     if !profile["authority"].is_null() {
    178         object(&profile["authority"])?;
    179     }
    180     let options = profile["options"]
    181         .as_array()
    182         .ok_or(CommandError::InvalidInput)?;
    183     if options.is_empty() || options.len() > 16 {
    184         return Err(CommandError::LimitExceeded);
    185     }
    186     for option in options {
    187         crate::listing_values::option_shape(option)?;
    188     }
    189     Ok(())
    190 }
    191 
    192 fn supported(profile: &serde_json::Value) -> Result<(), CommandError> {
    193     if profile
    194         .get("profile")
    195         .is_some_and(|v| v != "radroots.listing")
    196         || profile.get("version").is_some_and(|v| v != 1)
    197     {
    198         return Err(CommandError::UnsupportedProfile);
    199     }
    200     if let Some(options) = profile.get("options").and_then(serde_json::Value::as_array) {
    201         for option in options {
    202             if option
    203                 .pointer("/price/type")
    204                 .and_then(serde_json::Value::as_str)
    205                 .is_some_and(|v| !matches!(v, "quote_required" | "fixed" | "variable_weight"))
    206                 || option
    207                     .pointer("/supply/type")
    208                     .and_then(serde_json::Value::as_str)
    209                     .is_some_and(|v| !matches!(v, "unknown" | "available" | "estimated"))
    210                 || option
    211                     .pointer("/unit/contents/type")
    212                     .and_then(serde_json::Value::as_str)
    213                     .is_some_and(|v| !matches!(v, "unspecified" | "fixed" | "estimated"))
    214             {
    215                 return Err(CommandError::UnsupportedProfile);
    216             }
    217         }
    218     }
    219     Ok(())
    220 }
    221 
    222 /// Decodes the canonical complete public profile without authenticating an event.
    223 /// Original tag order and signature admission belong to the concrete adapter.
    224 pub fn decode_profile(raw: &[u8]) -> Result<ListingTerms, CommandError> {
    225     check_frame(raw)?;
    226     let value: serde_json::Value =
    227         serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
    228     let wrapper = serde_json::json!({"profile": value});
    229     supported(&wrapper["profile"])?;
    230     object_shapes(&wrapper)?;
    231     let profile: Profile = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?;
    232     let terms = profile.terms()?;
    233     let mut canonical = String::new();
    234     super::canonical(
    235         &super::profile_value(&terms).map_err(|_| CommandError::InvalidInput)?,
    236         &mut canonical,
    237     )
    238     .map_err(|_| CommandError::InvalidInput)?;
    239     if canonical.as_bytes() != raw {
    240         return Err(CommandError::InvalidInput);
    241     }
    242     Ok(terms)
    243 }