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 HtmlContext => "html",
68}
69
70#[diagnostic::on_unimplemented(
75 message = "`{Self}` is not a checked URL, so it cannot be the whole value of a URL attribute",
76 label = "a string could hold a `javascript:` URL",
77 note = "parse it with `hemplate::Url::parse(..)` and handle the error, or start the attribute with fixed text such as `/`, `?`, `#` or `https://`",
78 note = "for a scheme such as `data:` or `sms:`, vouch for it explicitly with `hemplate::TrustedUrl::new_unchecked(..)`"
79)]
80pub trait UrlValue: fmt::Display {}
81
82#[diagnostic::on_unimplemented(
84 message = "`{Self}` cannot be interpolated into a `srcset` attribute",
85 label = "every candidate in a srcset must be a checked URL",
86 note = "build a `hemplate::Srcset` from checked `hemplate::Url` values",
87 note = "or vouch for a list explicitly with `hemplate::TrustedSrcset::new_unchecked(..)`"
88)]
89pub trait SrcsetValue: fmt::Display {}
90
91#[diagnostic::on_unimplemented(
93 message = "`{Self}` cannot be interpolated into an event-handler attribute (`on*`)",
94 label = "this value would be run as JavaScript",
95 note = "HTML escaping does not make a value safe as code: the browser decodes the attribute before running it",
96 note = "pass data in a `data-*` attribute and read it from a script",
97 note = "code you wrote yourself can be vouched for with `hemplate::TrustedScript::new_unchecked(..)`"
98)]
99pub trait ScriptValue: fmt::Display {}
100
101#[diagnostic::on_unimplemented(
103 message = "`{Self}` cannot be interpolated into a `style` attribute",
104 label = "this value would be read as CSS",
105 note = "a `;` ends the property, so a value can add others such as `background: url(..)` that fetch a URL",
106 note = "choose among fixed styles with `+class=\"..\"`, or implement `hemplate::StyleValue` for a type that can only build valid values",
107 note = "or vouch for CSS explicitly with `hemplate::TrustedStyle::new_unchecked(..)`"
108)]
109pub trait StyleValue: fmt::Display {}
110
111#[diagnostic::on_unimplemented(
113 message = "`{Self}` cannot be interpolated into a `srcdoc` attribute",
114 label = "this value would be parsed as a whole HTML document",
115 note = "serve the document from its own URL and use `src`, or vouch for it with `hemplate::TrustedDocument::new_unchecked(..)`"
116)]
117pub trait DocumentValue: fmt::Display {}
118
119#[diagnostic::on_unimplemented(
121 message = "`{Self}` cannot be interpolated into `<base href>` or `<meta http-equiv>`",
122 label = "this value changes how the whole page navigates or behaves",
123 note = "use fixed text, or vouch for the value with `hemplate::TrustedNavigation::new_unchecked(..)`"
124)]
125pub trait NavigationValue: fmt::Display {}
126
127#[diagnostic::on_unimplemented(
129 message = "`{Self}` cannot be interpolated into a URL that loads script, styles or plug-ins",
130 label = "even an `https:` URL would run code or styles from wherever it points",
131 note = "use a fixed URL, or a type implementing `hemplate::ResourceValue` that can only name files you serve",
132 note = "or vouch for the URL with `hemplate::TrustedResource::new_unchecked(..)`"
133)]
134pub trait ResourceValue: fmt::Display {}
135
136#[diagnostic::on_unimplemented(
138 message = "`{Self}` cannot be interpolated into an SVG animation attribute",
139 label = "an animation can set `href` to a `javascript:` URL",
140 note = "use fixed values, or vouch for them with `hemplate::TrustedAnimation::new_unchecked(..)`"
141)]
142pub trait AnimationValue: fmt::Display {}
143
144#[diagnostic::on_unimplemented(
152 message = "`{Self}` is not trusted HTML, so raw interpolation `{{+= .. =+}}` cannot insert it",
153 label = "raw output is inserted unescaped; a string could hold a `<script>` from user input",
154 note = "for text use escaped interpolation `{{+ .. +}}`, and for a child template `{{+ child +}}`",
155 note = "for markup someone vouches for, use `hemplate::TrustedHtml::new_unchecked(..)` or a type implementing `hemplate::HtmlValue`"
156)]
157pub trait HtmlValue: fmt::Display {}
158
159macro_rules! forward_refs {
160 ($($trait:ident),* $(,)?) => {$(
161 #[diagnostic::do_not_recommend]
162 impl<T: $trait + ?Sized> $trait for &T {}
163 )*};
164}
165
166forward_refs!(
167 UrlValue,
168 SrcsetValue,
169 ScriptValue,
170 StyleValue,
171 DocumentValue,
172 NavigationValue,
173 ResourceValue,
174 AnimationValue,
175 HtmlValue,
176);
177
178#[derive(Clone, PartialEq, Eq, Hash)]
183pub struct Trusted<C: Context> {
184 value: String,
185 context: PhantomData<fn() -> C>,
186}
187
188impl<C: Context> Trusted<C> {
189 pub fn new_unchecked(value: impl Into<String>) -> Self {
194 Self {
195 value: value.into(),
196 context: PhantomData,
197 }
198 }
199
200 pub fn as_str(&self) -> &str {
202 &self.value
203 }
204}
205
206impl<C: Context> fmt::Display for Trusted<C> {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 f.write_str(&self.value)
209 }
210}
211
212impl<C: Context> fmt::Debug for Trusted<C> {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 write!(f, "Trusted<{}>({:?})", C::NAME, self.value)
215 }
216}
217
218pub type TrustedUrl = Trusted<UrlContext>;
220pub type TrustedSrcset = Trusted<SrcsetContext>;
222pub type TrustedScript = Trusted<ScriptContext>;
224pub type TrustedStyle = Trusted<StyleContext>;
226pub type TrustedDocument = Trusted<DocumentContext>;
228pub type TrustedNavigation = Trusted<NavigationContext>;
230pub type TrustedResource = Trusted<ResourceContext>;
232pub type TrustedAnimation = Trusted<AnimationContext>;
234pub type TrustedHtml = Trusted<HtmlContext>;
236
237#[diagnostic::do_not_recommend]
238impl UrlValue for Trusted<UrlContext> {}
239#[diagnostic::do_not_recommend]
240impl SrcsetValue for Trusted<SrcsetContext> {}
241#[diagnostic::do_not_recommend]
242impl ScriptValue for Trusted<ScriptContext> {}
243#[diagnostic::do_not_recommend]
244impl StyleValue for Trusted<StyleContext> {}
245#[diagnostic::do_not_recommend]
246impl DocumentValue for Trusted<DocumentContext> {}
247#[diagnostic::do_not_recommend]
248impl NavigationValue for Trusted<NavigationContext> {}
249#[diagnostic::do_not_recommend]
250impl ResourceValue for Trusted<ResourceContext> {}
251#[diagnostic::do_not_recommend]
252impl AnimationValue for Trusted<AnimationContext> {}
253#[diagnostic::do_not_recommend]
254impl HtmlValue for Trusted<HtmlContext> {}
255
256#[derive(Clone, Debug, PartialEq, Eq)]
258pub enum UrlError {
259 DisallowedScheme(String),
261 ControlCharacter,
263 NotSrcsetSafe,
265 InvalidDensity,
267}
268
269impl fmt::Display for UrlError {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 match self {
272 Self::DisallowedScheme(scheme) => write!(
273 f,
274 "URL scheme `{scheme}` is not allowed (http, https, mailto and tel are)"
275 ),
276 Self::ControlCharacter => f.write_str("URL contains a control character"),
277 Self::NotSrcsetSafe => f.write_str("URL contains whitespace or a comma"),
278 Self::InvalidDensity => f.write_str("srcset density must be a positive finite number"),
279 }
280 }
281}
282
283impl core::error::Error for UrlError {}
284
285const ALLOWED_SCHEMES: [&str; 4] = ["http", "https", "mailto", "tel"];
287
288#[derive(Clone, PartialEq, Eq, Hash)]
300pub struct Url(String);
301
302impl Url {
303 pub fn parse(input: &str) -> Result<Self, UrlError> {
305 let stripped: String = input
306 .chars()
307 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
308 .collect();
309 let trimmed = stripped.trim_matches(|c: char| c <= ' ');
310 if trimmed.chars().any(|c| c.is_ascii_control()) {
311 return Err(UrlError::ControlCharacter);
312 }
313 if let Some(scheme) = scheme_of(trimmed) {
314 let scheme = scheme.to_ascii_lowercase();
315 if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
316 return Err(UrlError::DisallowedScheme(scheme));
317 }
318 }
319 Ok(Self(trimmed.to_string()))
320 }
321
322 pub fn as_str(&self) -> &str {
324 &self.0
325 }
326}
327
328fn scheme_of(url: &str) -> Option<&str> {
331 let mut chars = url.char_indices();
332 match chars.next() {
333 Some((_, first)) if first.is_ascii_alphabetic() => {}
334 _ => return None,
335 }
336 for (index, c) in chars {
337 match c {
338 ':' => return Some(&url[..index]),
339 c if c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.') => {}
340 _ => return None,
341 }
342 }
343 None
344}
345
346impl fmt::Display for Url {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 f.write_str(&self.0)
349 }
350}
351
352impl fmt::Debug for Url {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 write!(f, "Url({:?})", self.0)
355 }
356}
357
358impl core::str::FromStr for Url {
359 type Err = UrlError;
360
361 fn from_str(input: &str) -> Result<Self, UrlError> {
362 Self::parse(input)
363 }
364}
365
366impl TryFrom<&str> for Url {
367 type Error = UrlError;
368
369 fn try_from(input: &str) -> Result<Self, UrlError> {
370 Self::parse(input)
371 }
372}
373
374#[diagnostic::do_not_recommend]
375impl UrlValue for Url {}
376
377#[derive(Clone, Copy, Debug, PartialEq)]
379pub enum Descriptor {
380 Width(u32),
382 Density(f32),
384}
385
386#[derive(Clone, Default, PartialEq, Eq, Hash)]
388pub struct Srcset(String);
389
390impl Srcset {
391 pub fn new() -> Self {
393 Self::default()
394 }
395
396 pub fn candidate(
399 mut self,
400 url: &Url,
401 descriptor: Option<Descriptor>,
402 ) -> Result<Self, UrlError> {
403 if url.as_str().chars().any(|c| c.is_whitespace() || c == ',') {
404 return Err(UrlError::NotSrcsetSafe);
405 }
406 if let Some(Descriptor::Density(density)) = descriptor
407 && (!density.is_finite() || density <= 0.0)
408 {
409 return Err(UrlError::InvalidDensity);
410 }
411 if !self.0.is_empty() {
412 self.0.push_str(", ");
413 }
414 self.0.push_str(url.as_str());
415 match descriptor {
416 Some(Descriptor::Width(width)) => {
417 self.0.push(' ');
418 self.0.push_str(&width.to_string());
419 self.0.push('w');
420 }
421 Some(Descriptor::Density(density)) => {
422 self.0.push(' ');
423 self.0.push_str(&density.to_string());
424 self.0.push('x');
425 }
426 None => {}
427 }
428 Ok(self)
429 }
430
431 pub fn as_str(&self) -> &str {
433 &self.0
434 }
435}
436
437impl fmt::Display for Srcset {
438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439 f.write_str(&self.0)
440 }
441}
442
443impl fmt::Debug for Srcset {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 write!(f, "Srcset({:?})", self.0)
446 }
447}
448
449#[diagnostic::do_not_recommend]
450impl SrcsetValue for Srcset {}