1use alloc::string::{String, ToString};
29use core::fmt;
30use core::marker::PhantomData;
31
32pub trait Context {
34 const NAME: &'static str;
36}
37
38macro_rules! contexts {
39 ($($(#[$doc:meta])* $marker:ident => $name:literal),* $(,)?) => {$(
40 $(#[$doc])*
41 #[derive(Clone, Copy, Debug)]
42 pub enum $marker {}
43 impl Context for $marker {
44 const NAME: &'static str = $name;
45 }
46 )*};
47}
48
49contexts! {
50 UrlContext => "url",
52 SrcsetContext => "srcset",
54 ScriptContext => "script",
56 StyleContext => "style",
58 DocumentContext => "document",
60 NavigationContext => "navigation",
62 ResourceContext => "resource",
64 AnimationContext => "animation",
66}
67
68#[diagnostic::on_unimplemented(
73 message = "`{Self}` is not a checked URL, so it cannot be the whole value of a URL attribute",
74 label = "a string could hold a `javascript:` URL",
75 note = "parse it with `hemplate::Url::parse(..)` and handle the error, or start the attribute with fixed text such as `/`, `?`, `#` or `https://`",
76 note = "for a scheme such as `data:` or `sms:`, vouch for it explicitly with `hemplate::TrustedUrl::new_unchecked(..)`"
77)]
78pub trait UrlValue: fmt::Display {}
79
80#[diagnostic::on_unimplemented(
82 message = "`{Self}` cannot be interpolated into a `srcset` attribute",
83 label = "every candidate in a srcset must be a checked URL",
84 note = "build a `hemplate::Srcset` from checked `hemplate::Url` values",
85 note = "or vouch for a list explicitly with `hemplate::TrustedSrcset::new_unchecked(..)`"
86)]
87pub trait SrcsetValue: fmt::Display {}
88
89#[diagnostic::on_unimplemented(
91 message = "`{Self}` cannot be interpolated into an event-handler attribute (`on*`)",
92 label = "this value would be run as JavaScript",
93 note = "HTML escaping does not make a value safe as code: the browser decodes the attribute before running it",
94 note = "pass data in a `data-*` attribute and read it from a script, or use a Hemx handle",
95 note = "code you wrote yourself can be vouched for with `hemplate::TrustedScript::new_unchecked(..)`"
96)]
97pub trait ScriptValue: fmt::Display {}
98
99#[diagnostic::on_unimplemented(
101 message = "`{Self}` cannot be interpolated into a `style` attribute",
102 label = "this value would be read as CSS",
103 note = "a `;` ends the property, so a value can add others such as `background: url(..)` that fetch a URL",
104 note = "choose among fixed styles with `+class=\"..\"`, or implement `hemplate::StyleValue` for a type that can only build valid values",
105 note = "or vouch for CSS explicitly with `hemplate::TrustedStyle::new_unchecked(..)`"
106)]
107pub trait StyleValue: fmt::Display {}
108
109#[diagnostic::on_unimplemented(
111 message = "`{Self}` cannot be interpolated into a `srcdoc` attribute",
112 label = "this value would be parsed as a whole HTML document",
113 note = "serve the document from its own URL and use `src`, or vouch for it with `hemplate::TrustedDocument::new_unchecked(..)`"
114)]
115pub trait DocumentValue: fmt::Display {}
116
117#[diagnostic::on_unimplemented(
119 message = "`{Self}` cannot be interpolated into `<base href>` or `<meta http-equiv>`",
120 label = "this value changes how the whole page navigates or behaves",
121 note = "use fixed text, or vouch for the value with `hemplate::TrustedNavigation::new_unchecked(..)`"
122)]
123pub trait NavigationValue: fmt::Display {}
124
125#[diagnostic::on_unimplemented(
127 message = "`{Self}` cannot be interpolated into a URL that loads script, styles or plug-ins",
128 label = "even an `https:` URL would run code or styles from wherever it points",
129 note = "use a fixed URL, or a type implementing `hemplate::ResourceValue` that can only name files you serve",
130 note = "or vouch for the URL with `hemplate::TrustedResource::new_unchecked(..)`"
131)]
132pub trait ResourceValue: fmt::Display {}
133
134#[diagnostic::on_unimplemented(
136 message = "`{Self}` cannot be interpolated into an SVG animation attribute",
137 label = "an animation can set `href` to a `javascript:` URL",
138 note = "use fixed values, or vouch for them with `hemplate::TrustedAnimation::new_unchecked(..)`"
139)]
140pub trait AnimationValue: fmt::Display {}
141
142macro_rules! forward_refs {
143 ($($trait:ident),* $(,)?) => {$(
144 #[diagnostic::do_not_recommend]
145 impl<T: $trait + ?Sized> $trait for &T {}
146 )*};
147}
148
149forward_refs!(
150 UrlValue,
151 SrcsetValue,
152 ScriptValue,
153 StyleValue,
154 DocumentValue,
155 NavigationValue,
156 ResourceValue,
157 AnimationValue,
158);
159
160#[derive(Clone, PartialEq, Eq, Hash)]
165pub struct Trusted<C: Context> {
166 value: String,
167 context: PhantomData<fn() -> C>,
168}
169
170impl<C: Context> Trusted<C> {
171 pub fn new_unchecked(value: impl Into<String>) -> Self {
176 Self {
177 value: value.into(),
178 context: PhantomData,
179 }
180 }
181
182 pub fn as_str(&self) -> &str {
184 &self.value
185 }
186}
187
188impl<C: Context> fmt::Display for Trusted<C> {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 f.write_str(&self.value)
191 }
192}
193
194impl<C: Context> fmt::Debug for Trusted<C> {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 write!(f, "Trusted<{}>({:?})", C::NAME, self.value)
197 }
198}
199
200pub type TrustedUrl = Trusted<UrlContext>;
202pub type TrustedSrcset = Trusted<SrcsetContext>;
204pub type TrustedScript = Trusted<ScriptContext>;
206pub type TrustedStyle = Trusted<StyleContext>;
208pub type TrustedDocument = Trusted<DocumentContext>;
210pub type TrustedNavigation = Trusted<NavigationContext>;
212pub type TrustedResource = Trusted<ResourceContext>;
214pub type TrustedAnimation = Trusted<AnimationContext>;
216
217#[diagnostic::do_not_recommend]
218impl UrlValue for Trusted<UrlContext> {}
219#[diagnostic::do_not_recommend]
220impl SrcsetValue for Trusted<SrcsetContext> {}
221#[diagnostic::do_not_recommend]
222impl ScriptValue for Trusted<ScriptContext> {}
223#[diagnostic::do_not_recommend]
224impl StyleValue for Trusted<StyleContext> {}
225#[diagnostic::do_not_recommend]
226impl DocumentValue for Trusted<DocumentContext> {}
227#[diagnostic::do_not_recommend]
228impl NavigationValue for Trusted<NavigationContext> {}
229#[diagnostic::do_not_recommend]
230impl ResourceValue for Trusted<ResourceContext> {}
231#[diagnostic::do_not_recommend]
232impl AnimationValue for Trusted<AnimationContext> {}
233
234#[derive(Clone, Debug, PartialEq, Eq)]
236pub enum UrlError {
237 DisallowedScheme(String),
239 ControlCharacter,
241 NotSrcsetSafe,
243 InvalidDensity,
245}
246
247impl fmt::Display for UrlError {
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 match self {
250 Self::DisallowedScheme(scheme) => write!(
251 f,
252 "URL scheme `{scheme}` is not allowed (http, https, mailto and tel are)"
253 ),
254 Self::ControlCharacter => f.write_str("URL contains a control character"),
255 Self::NotSrcsetSafe => f.write_str("URL contains whitespace or a comma"),
256 Self::InvalidDensity => f.write_str("srcset density must be a positive finite number"),
257 }
258 }
259}
260
261impl core::error::Error for UrlError {}
262
263const ALLOWED_SCHEMES: [&str; 4] = ["http", "https", "mailto", "tel"];
265
266#[derive(Clone, PartialEq, Eq, Hash)]
278pub struct Url(String);
279
280impl Url {
281 pub fn parse(input: &str) -> Result<Self, UrlError> {
283 let stripped: String = input
284 .chars()
285 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
286 .collect();
287 let trimmed = stripped.trim_matches(|c: char| c <= ' ');
288 if trimmed.chars().any(|c| c.is_ascii_control()) {
289 return Err(UrlError::ControlCharacter);
290 }
291 if let Some(scheme) = scheme_of(trimmed) {
292 let scheme = scheme.to_ascii_lowercase();
293 if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
294 return Err(UrlError::DisallowedScheme(scheme));
295 }
296 }
297 Ok(Self(trimmed.to_string()))
298 }
299
300 pub fn as_str(&self) -> &str {
302 &self.0
303 }
304}
305
306fn scheme_of(url: &str) -> Option<&str> {
309 let mut chars = url.char_indices();
310 match chars.next() {
311 Some((_, first)) if first.is_ascii_alphabetic() => {}
312 _ => return None,
313 }
314 for (index, c) in chars {
315 match c {
316 ':' => return Some(&url[..index]),
317 c if c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.') => {}
318 _ => return None,
319 }
320 }
321 None
322}
323
324impl fmt::Display for Url {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.write_str(&self.0)
327 }
328}
329
330impl fmt::Debug for Url {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 write!(f, "Url({:?})", self.0)
333 }
334}
335
336impl core::str::FromStr for Url {
337 type Err = UrlError;
338
339 fn from_str(input: &str) -> Result<Self, UrlError> {
340 Self::parse(input)
341 }
342}
343
344impl TryFrom<&str> for Url {
345 type Error = UrlError;
346
347 fn try_from(input: &str) -> Result<Self, UrlError> {
348 Self::parse(input)
349 }
350}
351
352#[diagnostic::do_not_recommend]
353impl UrlValue for Url {}
354
355#[derive(Clone, Copy, Debug, PartialEq)]
357pub enum Descriptor {
358 Width(u32),
360 Density(f32),
362}
363
364#[derive(Clone, Default, PartialEq, Eq, Hash)]
366pub struct Srcset(String);
367
368impl Srcset {
369 pub fn new() -> Self {
371 Self::default()
372 }
373
374 pub fn candidate(
377 mut self,
378 url: &Url,
379 descriptor: Option<Descriptor>,
380 ) -> Result<Self, UrlError> {
381 if url.as_str().chars().any(|c| c.is_whitespace() || c == ',') {
382 return Err(UrlError::NotSrcsetSafe);
383 }
384 if let Some(Descriptor::Density(density)) = descriptor
385 && (!density.is_finite() || density <= 0.0)
386 {
387 return Err(UrlError::InvalidDensity);
388 }
389 if !self.0.is_empty() {
390 self.0.push_str(", ");
391 }
392 self.0.push_str(url.as_str());
393 match descriptor {
394 Some(Descriptor::Width(width)) => {
395 self.0.push(' ');
396 self.0.push_str(&width.to_string());
397 self.0.push('w');
398 }
399 Some(Descriptor::Density(density)) => {
400 self.0.push(' ');
401 self.0.push_str(&density.to_string());
402 self.0.push('x');
403 }
404 None => {}
405 }
406 Ok(self)
407 }
408
409 pub fn as_str(&self) -> &str {
411 &self.0
412 }
413}
414
415impl fmt::Display for Srcset {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 f.write_str(&self.0)
418 }
419}
420
421impl fmt::Debug for Srcset {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 write!(f, "Srcset({:?})", self.0)
424 }
425}
426
427#[diagnostic::do_not_recommend]
428impl SrcsetValue for Srcset {}