rstml_component/
sanitize.rs

1use crate::{HtmlContent, HtmlFormatter};
2use ammonia::Builder;
3use std::{fmt, io, sync::OnceLock};
4
5pub type SanitizeConfig = Builder<'static>;
6
7static DEFAULT_SANITIZER: OnceLock<SanitizeConfig> = OnceLock::new();
8
9fn default_sanitizer() -> &'static SanitizeConfig {
10	DEFAULT_SANITIZER.get_or_init(Builder::default)
11}
12
13#[derive(Clone, Copy)]
14enum Sanitizer {
15	/// Use the default sanitizer.
16	Default,
17
18	/// Use the given sanitizer.
19	Builder(&'static SanitizeConfig),
20}
21
22impl Default for Sanitizer {
23	fn default() -> Self {
24		Self::Default
25	}
26}
27
28impl AsRef<SanitizeConfig> for Sanitizer {
29	fn as_ref(&self) -> &SanitizeConfig {
30		match self {
31			Self::Default => default_sanitizer(),
32			Self::Builder(builder) => builder,
33		}
34	}
35}
36
37/// A wrapper struct for adding potentially unsanitized HTML content that will be sanitized before rendering.
38///
39/// The `Sanitized` struct allows you to include HTML content that might be potentially unsafe,
40/// and ensures that it's properly sanitized before being rendered within your HTML components.
41/// This is particularly useful when you want to include user-generated content or any content
42/// that might contain unsafe HTML elements or scripts.
43#[derive(Clone)]
44pub struct Sanitized<V>(V, Sanitizer);
45
46impl<V: fmt::Debug> fmt::Debug for Sanitized<V> {
47	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48		f.debug_tuple("Sanitized").field(&self.0).finish()
49	}
50}
51
52impl<V> Sanitized<V>
53where
54	V: AsRef<[u8]>,
55{
56	/// Creates a new `Sanitized` instance with the HTML content to be sanitized before rendering.
57	///
58	/// # Arguments
59	///
60	/// - `value`: The HTML content to be sanitized as a byte slice.
61	///
62	/// # Returns
63	///
64	/// A `Sanitized` instance wrapping the HTML content that will be sanitized before rendering.
65	pub fn new(value: V) -> Self {
66		Self(value, Sanitizer::default())
67	}
68
69	/// Creates a new `Sanitized` instance with the HTML content and a custom sanitizer.
70	///
71	/// # Arguments
72	///
73	/// - `value`: The HTML content to be sanitized as a byte slice.
74	/// - `sanitizer`: The custom sanitizer to be used for this specific instance.
75	///
76	/// # Returns
77	///
78	/// A `Sanitized` instance wrapping the HTML content that will be sanitized using the specified sanitizer.
79	pub fn new_with_sanitizer(value: V, sanitizer: &'static SanitizeConfig) -> Self {
80		Self(value, Sanitizer::Builder(sanitizer))
81	}
82
83	/// Sets a custom sanitizer for this `Sanitized` instance.
84	///
85	/// This method allows you to override the default sanitizer for a specific `Sanitized` instance.
86	///
87	/// # Arguments
88	///
89	/// - `sanitizer`: The custom sanitizer to be used for this specific instance.
90	///
91	/// # Returns
92	///
93	/// A new `Sanitized` instance with the specified sanitizer.
94	pub fn with_sanitizer(self, sanitizer: &'static SanitizeConfig) -> Self {
95		Self(self.0, Sanitizer::Builder(sanitizer))
96	}
97}
98
99impl<V: AsRef<[u8]>> HtmlContent for Sanitized<V> {
100	fn fmt(self, formatter: &mut HtmlFormatter) -> fmt::Result {
101		let bytes = self.0.as_ref();
102		let bytes = self
103			.1
104			.as_ref()
105			.clean_from_reader(bytes)
106			.map_err(|_| fmt::Error)?;
107		bytes.write_to(IoWrite(formatter)).map_err(|_| fmt::Error)
108	}
109}
110
111struct IoWrite<'a, 'b>(&'a mut HtmlFormatter<'b>);
112
113impl<'a, 'b> io::Write for IoWrite<'a, 'b> {
114	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
115		self.0.write_bytes(buf);
116		Ok(buf.len())
117	}
118
119	fn flush(&mut self) -> io::Result<()> {
120		Ok(())
121	}
122}