lib

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

edit.rs (10257B)


      1 //! Complete-profile replacement with exact verified-baseline and media fences.
      2 
      3 #[cfg(not(feature = "std"))]
      4 use alloc::{
      5     boxed::Box,
      6     collections::BTreeMap,
      7     string::{String, ToString},
      8     vec::Vec,
      9 };
     10 #[cfg(feature = "std")]
     11 use std::{boxed::Box, collections::BTreeMap, string::String, vec::Vec};
     12 
     13 use core::fmt;
     14 use radroots_event::{
     15     contract::{
     16         ContractId, ContractKey, RegistryVersion, registry_v8::PROFILE_METADATA_EDIT_CONTRACT_ID,
     17     },
     18     profile::{
     19         AuthoredProfile, Nip05Identifier, RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES,
     20         edit::{ProfileEdit, ProfileFieldChange, ProfileMediaChange},
     21     },
     22     wire::Nip01EventWireParts,
     23 };
     24 use radroots_identity::PublicKey;
     25 use serde::Serialize;
     26 use serde_json::value::RawValue;
     27 
     28 use super::{admission::RadrootsAdmittedProfileEvent, inbound::parse_inbound_profile_metadata};
     29 use crate::authoring::{
     30     AuthoredEventBody, AuthoredEventPlan, AuthoredPlanError, PLAN_WIRE_MAX_BYTES, PlanWireV1,
     31 };
     32 
     33 #[non_exhaustive]
     34 #[derive(Clone, Debug, PartialEq, Eq)]
     35 pub enum ProfileEditError {
     36     StaleBaseline,
     37     AuthorMismatch,
     38     BaselineTagsUnsupported,
     39     TimestampNotAdvancing,
     40     InvalidName,
     41     ContentTooLarge { max: usize, actual: usize },
     42     DurableWireTooLarge { max: usize, actual: usize },
     43     MediaVerificationRequired { field: &'static str },
     44     MediaVerificationMismatch { field: &'static str },
     45     InvalidMetadata,
     46     Plan(AuthoredPlanError),
     47 }
     48 
     49 impl ProfileEditError {
     50     pub const fn code(&self) -> &'static str {
     51         match self {
     52             Self::StaleBaseline => "stale_profile_baseline",
     53             Self::AuthorMismatch => "profile_author_mismatch",
     54             Self::BaselineTagsUnsupported => "profile_baseline_tags_unsupported",
     55             Self::TimestampNotAdvancing => "profile_timestamp_not_advancing",
     56             Self::InvalidName => "invalid_name",
     57             Self::ContentTooLarge { .. } => "content_too_large",
     58             Self::DurableWireTooLarge { .. } => "profile_durable_wire_too_large",
     59             Self::MediaVerificationRequired { .. } => "profile_media_verification_required",
     60             Self::MediaVerificationMismatch { .. } => "profile_media_verification_mismatch",
     61             Self::InvalidMetadata => "profile_edit_invalid_metadata",
     62             Self::Plan(error) => error.code(),
     63         }
     64     }
     65 }
     66 
     67 impl fmt::Display for ProfileEditError {
     68     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     69         match self {
     70             Self::ContentTooLarge { max, actual } | Self::DurableWireTooLarge { max, actual } => {
     71                 write!(formatter, "{}: {actual} bytes exceeds {max}", self.code())
     72             }
     73             Self::MediaVerificationRequired { field }
     74             | Self::MediaVerificationMismatch { field } => {
     75                 write!(formatter, "{}: {field}", self.code())
     76             }
     77             Self::Plan(error) => write!(formatter, "{error}"),
     78             _ => formatter.write_str(self.code()),
     79         }
     80     }
     81 }
     82 
     83 #[cfg(feature = "std")]
     84 impl std::error::Error for ProfileEditError {}
     85 
     86 type RawFields = BTreeMap<String, Box<RawValue>>;
     87 
     88 impl AuthoredEventPlan {
     89     /// Builds a complete replacement from the exact verified canonical head.
     90     ///
     91     /// The runtime must read the real canonical head, persist its baseline id,
     92     /// and recheck it before signing/side effects. This pure comparison is not
     93     /// a storage CAS. Kept media proof is not upload-completion evidence.
     94     pub fn from_profile_edit(
     95         baseline: &RadrootsAdmittedProfileEvent,
     96         current_head: &RadrootsAdmittedProfileEvent,
     97         edit: &ProfileEdit,
     98         created_at: u64,
     99         expected_author: impl AsRef<str>,
    100     ) -> Result<Self, ProfileEditError> {
    101         let author = PublicKey::from_hex(expected_author.as_ref())
    102             .map_err(|_| ProfileEditError::AuthorMismatch)?;
    103         if baseline.event().author() != &author || current_head.event().author() != &author {
    104             return Err(ProfileEditError::AuthorMismatch);
    105         }
    106         if baseline.event().id() != current_head.event().id() {
    107             return Err(ProfileEditError::StaleBaseline);
    108         }
    109         if !baseline.event().tags_as_vec().is_empty() {
    110             return Err(ProfileEditError::BaselineTagsUnsupported);
    111         }
    112         if created_at <= baseline.event().created_at_u64() {
    113             return Err(ProfileEditError::TimestampNotAdvancing);
    114         }
    115         for change in [&edit.name, &edit.display_name, &edit.about] {
    116             if let ProfileFieldChange::Set(value) = change {
    117                 check_content_size(value.len())?;
    118             }
    119         }
    120         if let ProfileFieldChange::Set(name) = &edit.name {
    121             AuthoredProfile::new(name).map_err(|_| ProfileEditError::InvalidName)?;
    122         }
    123         let mut fields: RawFields = serde_json::from_str(baseline.metadata().raw_content())
    124             .map_err(|_| ProfileEditError::InvalidMetadata)?;
    125         apply_field(&mut fields, "name", &edit.name)?;
    126         apply_field(&mut fields, "display_name", &edit.display_name)?;
    127         apply_field(&mut fields, "about", &edit.about)?;
    128         apply_media(&mut fields, "picture", &edit.picture)?;
    129         apply_media(&mut fields, "banner", &edit.banner)?;
    130         apply_nip05(&mut fields, &edit.nip05)?;
    131         apply_field(&mut fields, "bot", &edit.bot)?;
    132         let content =
    133             serde_json::to_string(&fields).map_err(|_| ProfileEditError::InvalidMetadata)?;
    134         check_content_size(content.len())?;
    135         let contract = ContractKey::new(
    136             RegistryVersion::V8,
    137             ContractId::parse(PROFILE_METADATA_EDIT_CONTRACT_ID).map_err(|error| {
    138                 ProfileEditError::Plan(AuthoredPlanError::ContractIdentity(error))
    139             })?,
    140         )
    141         .map_err(|error| ProfileEditError::Plan(AuthoredPlanError::ContractIdentity(error)))?;
    142         let body = AuthoredEventBody::from_profile_edit_parts(
    143             contract,
    144             Nip01EventWireParts {
    145                 kind: 0,
    146                 tags: Vec::new(),
    147                 content,
    148             },
    149         )
    150         .map_err(ProfileEditError::Plan)?;
    151         let plan = Self::bind(body, created_at, author.to_hex()).map_err(ProfileEditError::Plan)?;
    152         let bytes = PlanWireV1::from_plan(&plan)
    153             .to_json()
    154             .map_err(|_| ProfileEditError::InvalidMetadata)?;
    155         if bytes.len() > PLAN_WIRE_MAX_BYTES {
    156             return Err(ProfileEditError::DurableWireTooLarge {
    157                 max: PLAN_WIRE_MAX_BYTES,
    158                 actual: bytes.len(),
    159             });
    160         }
    161         Ok(plan)
    162     }
    163 }
    164 
    165 fn check_content_size(actual: usize) -> Result<(), ProfileEditError> {
    166     if actual > RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES {
    167         return Err(ProfileEditError::ContentTooLarge {
    168             max: RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES,
    169             actual,
    170         });
    171     }
    172     Ok(())
    173 }
    174 
    175 fn set_value<T: Serialize + ?Sized>(
    176     fields: &mut RawFields,
    177     name: &str,
    178     value: &T,
    179 ) -> Result<(), ProfileEditError> {
    180     let raw =
    181         serde_json::value::to_raw_value(value).map_err(|_| ProfileEditError::InvalidMetadata)?;
    182     check_content_size(raw.get().len())?;
    183     fields.insert(name.to_string(), raw);
    184     Ok(())
    185 }
    186 
    187 fn apply_field<T: Serialize>(
    188     fields: &mut RawFields,
    189     name: &str,
    190     change: &ProfileFieldChange<T>,
    191 ) -> Result<(), ProfileEditError> {
    192     match change {
    193         ProfileFieldChange::Keep => Ok(()),
    194         ProfileFieldChange::Set(value) => set_value(fields, name, value),
    195         ProfileFieldChange::Clear => {
    196             fields.remove(name);
    197             Ok(())
    198         }
    199     }
    200 }
    201 
    202 fn apply_nip05(
    203     fields: &mut RawFields,
    204     change: &ProfileFieldChange<Nip05Identifier>,
    205 ) -> Result<(), ProfileEditError> {
    206     match change {
    207         ProfileFieldChange::Keep => Ok(()),
    208         ProfileFieldChange::Set(value) => set_value(fields, "nip05", value.as_str()),
    209         ProfileFieldChange::Clear => {
    210             fields.remove("nip05");
    211             Ok(())
    212         }
    213     }
    214 }
    215 
    216 fn apply_media(
    217     fields: &mut RawFields,
    218     name: &'static str,
    219     change: &ProfileMediaChange,
    220 ) -> Result<(), ProfileEditError> {
    221     match change {
    222         ProfileMediaChange::Clear => {
    223             fields.remove(name);
    224             Ok(())
    225         }
    226         ProfileMediaChange::Set(image) => {
    227             set_value(fields, name, image.descriptor().url().as_str())
    228         }
    229         ProfileMediaChange::Keep | ProfileMediaChange::KeepVerified(_) => {
    230             let existing = fields
    231                 .get(name)
    232                 .and_then(|raw| serde_json::from_str::<String>(raw.get()).ok());
    233             match (existing, change) {
    234                 (Some(value), ProfileMediaChange::KeepVerified(image))
    235                     if value == image.descriptor().url().as_str() =>
    236                 {
    237                     Ok(())
    238                 }
    239                 (Some(_), ProfileMediaChange::KeepVerified(_)) => {
    240                     Err(ProfileEditError::MediaVerificationMismatch { field: name })
    241                 }
    242                 (Some(_), _) => Err(ProfileEditError::MediaVerificationRequired { field: name }),
    243                 (None, ProfileMediaChange::KeepVerified(_)) => {
    244                     Err(ProfileEditError::MediaVerificationMismatch { field: name })
    245                 }
    246                 (None, _) => Ok(()),
    247             }
    248         }
    249     }
    250 }
    251 
    252 pub(crate) fn validate_historical(tags: &[Vec<String>], content: &str) -> Result<(), String> {
    253     if !tags.is_empty() {
    254         return Err("profile_tags_forbidden".to_string());
    255     }
    256     let profile =
    257         parse_inbound_profile_metadata(content).map_err(|error| error.code().to_string())?;
    258     if profile
    259         .picture()
    260         .into_iter()
    261         .chain(profile.banner())
    262         .any(|media| radroots_blossom::BlobUrl::parse(media.as_str()).is_err())
    263     {
    264         return Err("profile_media_url_invalid".to_string());
    265     }
    266     let fields: RawFields =
    267         serde_json::from_str(content).map_err(|_| "profile_json_decode".to_string())?;
    268     let canonical =
    269         serde_json::to_string(&fields).map_err(|_| "profile_json_encode".to_string())?;
    270     if canonical != content {
    271         return Err("profile_edit_noncanonical".to_string());
    272     }
    273     Ok(())
    274 }