Skip to main content

zaun_community_protocol/command/object/
embed.rs

1//! Rich embeds on a message (specification §8.5).
2//!
3//! An embed is plain data the author writes: a title, text, fields, and pictures. A picture is
4//! never a remote URL. `image`, `thumbnail` and the icons name attachments of the same message,
5//! so their bytes travel the attachment path and no client ever fetches a third-party URL on
6//! its own (which would show the reader's network address to that server). URLs are links a
7//! reader may choose to open, never loaded automatically.
8
9use serde::{Deserialize, Serialize};
10
11use crate::command::{BodyError, check};
12use crate::ids::AttachmentId;
13use crate::limits::{
14    COLOR_MAX, EMBED_AUTHOR_NAME, EMBED_DESCRIPTION, EMBED_FIELD_NAME, EMBED_FIELD_VALUE,
15    EMBED_FIELDS, EMBED_FOOTER_TEXT, EMBED_TEXT_TOTAL, EMBED_TITLE, EMBED_URL_MAX,
16    EMBEDS_PER_MESSAGE,
17};
18
19/// An embed (§8.5). Every text is optional, but an embed shows something: a title, a
20/// description, an author, a footer, a picture or a field (`color`, `timestamp` and `url`
21/// alone do not count).
22#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
23pub struct Embed {
24    /// 1–256 scalars.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub title: Option<String>,
27    /// 1–4 096 scalars.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub description: Option<String>,
30    /// The title's link: `https://` only, ≤ 2 048 bytes, no whitespace or control
31    /// characters. Needs a `title`.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub url: Option<String>,
34    /// `0x000000`–`0xFFFFFF`.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub color: Option<u32>,
37    /// A time the embed shows, ms since the epoch (< 2^53).
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub timestamp: Option<u64>,
40    /// The author line.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub author: Option<EmbedAuthor>,
43    /// The footer line.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub footer: Option<EmbedFooter>,
46    /// The large picture: one of the message's attachments.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub image: Option<AttachmentId>,
49    /// The small picture: one of the message's attachments.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub thumbnail: Option<AttachmentId>,
52    /// Up to 25 fields, in order.
53    #[serde(default, skip_serializing_if = "Vec::is_empty")]
54    pub fields: Vec<EmbedField>,
55}
56
57/// `author: {name, url?, icon?}` of an embed.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct EmbedAuthor {
60    /// 1–256 scalars.
61    pub name: String,
62    /// The name's link, under the same rules as [`Embed::url`].
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub url: Option<String>,
65    /// A small picture: one of the message's attachments.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub icon: Option<AttachmentId>,
68}
69
70/// `footer: {text, icon?}` of an embed.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct EmbedFooter {
73    /// 1–2 048 scalars.
74    pub text: String,
75    /// A small picture: one of the message's attachments.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub icon: Option<AttachmentId>,
78}
79
80/// `fields: [{name, value, inline}]` of an embed.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct EmbedField {
83    /// 1–256 scalars.
84    pub name: String,
85    /// 1–1 024 scalars.
86    pub value: String,
87    /// Shown next to the neighbouring inline fields rather than on its own line; absent
88    /// means `false`.
89    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
90    pub inline: bool,
91}
92
93impl Embed {
94    /// The attachments this embed shows, with the field that names each: `embeds.image`,
95    /// `embeds.thumbnail`, `embeds.author.icon`, `embeds.footer.icon`.
96    pub fn attachments(&self) -> impl Iterator<Item = (&'static str, AttachmentId)> + '_ {
97        [
98            ("embeds.image", self.image),
99            ("embeds.thumbnail", self.thumbnail),
100            (
101                "embeds.author.icon",
102                self.author.as_ref().and_then(|a| a.icon),
103            ),
104            (
105                "embeds.footer.icon",
106                self.footer.as_ref().and_then(|f| f.icon),
107            ),
108        ]
109        .into_iter()
110        .filter_map(|(field, id)| id.map(|id| (field, id)))
111    }
112
113    /// Whether the embed shows nothing but a colour, a time or a bare link.
114    #[must_use]
115    pub fn is_empty(&self) -> bool {
116        self.title.is_none()
117            && self.description.is_none()
118            && self.author.is_none()
119            && self.footer.is_none()
120            && self.image.is_none()
121            && self.thumbnail.is_none()
122            && self.fields.is_empty()
123    }
124
125    /// The scalars this embed counts towards [`EMBED_TEXT_TOTAL`].
126    fn text_len(&self) -> usize {
127        let opt = |s: Option<&String>| s.map_or(0, |s| s.chars().count());
128        opt(self.title.as_ref())
129            + opt(self.description.as_ref())
130            + opt(self.author.as_ref().map(|a| &a.name))
131            + opt(self.footer.as_ref().map(|f| &f.text))
132            + self
133                .fields
134                .iter()
135                .map(|f| f.name.chars().count() + f.value.chars().count())
136                .sum::<usize>()
137    }
138
139    /// The state-free rules of one embed.
140    fn check(&self) -> Result<(), BodyError> {
141        check::opt_text("embeds.title", self.title.as_deref(), EMBED_TITLE)?;
142        check::opt_text(
143            "embeds.description",
144            self.description.as_deref(),
145            EMBED_DESCRIPTION,
146        )?;
147        if let Some(url) = &self.url {
148            link("embeds.url", url)?;
149            if self.title.is_none() {
150                return Err(BodyError::bad("embeds.url", "needs a title"));
151            }
152        }
153        if let Some(color) = self.color {
154            check::range("embeds.color", color, 0, COLOR_MAX)?;
155        }
156        if let Some(timestamp) = self.timestamp {
157            check::json_safe("embeds.timestamp", timestamp)?;
158        }
159        if let Some(author) = &self.author {
160            check::text("embeds.author.name", &author.name, EMBED_AUTHOR_NAME)?;
161            if let Some(url) = &author.url {
162                link("embeds.author.url", url)?;
163            }
164        }
165        if let Some(footer) = &self.footer {
166            check::text("embeds.footer.text", &footer.text, EMBED_FOOTER_TEXT)?;
167        }
168        check::count("embeds.fields", self.fields.len(), EMBED_FIELDS)?;
169        for field in &self.fields {
170            check::text("embeds.fields.name", &field.name, EMBED_FIELD_NAME)?;
171            check::text("embeds.fields.value", &field.value, EMBED_FIELD_VALUE)?;
172        }
173        if self.is_empty() {
174            return Err(BodyError::bad("embeds", "an embed shows nothing"));
175        }
176        Ok(())
177    }
178}
179
180/// A link in an embed: `https://` (scheme in any case) and a host, at most
181/// [`EMBED_URL_MAX`] bytes, with no whitespace, control character or bidirectional
182/// formatting character (which could disguise where the link goes).
183pub(crate) fn link(field: &str, url: &str) -> Result<(), BodyError> {
184    if url.len() > EMBED_URL_MAX {
185        return Err(BodyError::too_large(field, EMBED_URL_MAX));
186    }
187    let rest = url
188        .get(..8)
189        .filter(|scheme| scheme.eq_ignore_ascii_case("https://"))
190        .map(|_| &url[8..]);
191    let Some(rest) = rest else {
192        return Err(BodyError::bad(field, "must be an https:// link"));
193    };
194    if rest.is_empty() || rest.starts_with(['/', '?', '#']) {
195        return Err(BodyError::bad(field, "has no host"));
196    }
197    // The authority ends at the first `/`, `?` or `#` (and `\`, which browsers read as `/`).
198    // A user name or password in it (`https://user:pass@host`) is refused: it can carry a
199    // credential, and `https://trusted.example@evil.example` disguises where the link goes.
200    let authority = rest.split(['/', '?', '#', '\\']).next().unwrap_or_default();
201    if authority.contains('@') {
202        return Err(BodyError::bad(field, "has a user name or password"));
203    }
204    if url
205        .chars()
206        .any(|c| c.is_whitespace() || c.is_control() || is_bidi(c))
207    {
208        return Err(BodyError::bad(
209            field,
210            "contains whitespace or a control character",
211        ));
212    }
213    Ok(())
214}
215
216/// Unicode bidirectional formatting characters (marks, embeddings, overrides, isolates).
217const fn is_bidi(c: char) -> bool {
218    matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
219}
220
221/// The bytes of a message's `content` and `embeds` as JSON, counted against
222/// [`MESSAGE_JSON_MAX`](crate::limits::MESSAGE_JSON_MAX).
223///
224/// Writing a parsed value never takes more bytes than the text it was read from (strings,
225/// numbers and keys come out in their shortest form, absent and default fields stay absent),
226/// so the content and embeds of one `message.send` are always within the limit.
227#[must_use]
228pub fn message_json_len(content: &str, embeds: &[Embed]) -> usize {
229    let len = |r: serde_json::Result<String>| r.map_or(usize::MAX, |s| s.len());
230    len(serde_json::to_string(content)).saturating_add(len(serde_json::to_string(embeds)))
231}
232
233/// [`message_json_len`] plus the message's components (§8.14), which count against the same
234/// [`MESSAGE_JSON_MAX`](crate::limits::MESSAGE_JSON_MAX).
235#[must_use]
236pub fn message_json_len_with(
237    content: &str,
238    embeds: &[Embed],
239    components: &[super::Component],
240) -> usize {
241    let extra = if components.is_empty() {
242        0
243    } else {
244        serde_json::to_string(components).map_or(usize::MAX, |s| s.len())
245    };
246    message_json_len(content, embeds).saturating_add(extra)
247}
248
249/// The state-free rules of a message's embeds (§8.5): at most 10, each valid and showing
250/// something, at most 6 000 scalars of text in all. With `attachments`, every picture an
251/// embed shows must be one of them ([`check_pictures`]).
252///
253/// # Errors
254/// `PAYLOAD_TOO_LARGE` for a text, link or list over its limit (`embeds` with limit 6 000 for
255/// the total text); `BAD_REQUEST` for any other broken rule.
256pub fn check_embeds(
257    embeds: &[Embed],
258    attachments: Option<&[AttachmentId]>,
259) -> Result<(), BodyError> {
260    check::count("embeds", embeds.len(), EMBEDS_PER_MESSAGE)?;
261    let mut total = 0usize;
262    for embed in embeds {
263        embed.check()?;
264        total += embed.text_len();
265    }
266    if total > EMBED_TEXT_TOTAL {
267        return Err(BodyError::too_large("embeds", EMBED_TEXT_TOTAL));
268    }
269    match attachments {
270        Some(listed) => check_pictures(embeds, listed),
271        None => Ok(()),
272    }
273}
274
275/// Every picture an embed shows (`image`, `thumbnail`, `author.icon`, `footer.icon`) is one of
276/// the message's `attachments`, so it travels the attachment path like any file and nobody
277/// fetches it from elsewhere.
278///
279/// # Errors
280/// `BAD_REQUEST` naming the field of the first picture that is not.
281pub fn check_pictures(embeds: &[Embed], attachments: &[AttachmentId]) -> Result<(), BodyError> {
282    for embed in embeds {
283        for (field, id) in embed.attachments() {
284            if !attachments.contains(&id) {
285                return Err(BodyError::bad(
286                    field,
287                    "is not one of the message's attachments",
288                ));
289            }
290        }
291    }
292    Ok(())
293}