1use std::{fmt::Write as _, sync::Arc};
2
3use phoenix_http::CspNonce;
4use serde::Serialize;
5use thiserror::Error;
6
7use crate::{PageEnvelope, PageHead};
8
9type DocumentRender = dyn for<'a> Fn(DocumentContext<'a>) -> Result<DocumentSlots, DocumentTemplateError>
10 + Send
11 + Sync;
12
13#[derive(Clone, Copy, Debug)]
15pub struct DocumentContext<'a> {
16 envelope: &'a PageEnvelope,
17 nonce: Option<&'a CspNonce>,
18}
19
20impl<'a> DocumentContext<'a> {
21 pub(crate) const fn new(envelope: &'a PageEnvelope, nonce: Option<&'a CspNonce>) -> Self {
22 Self { envelope, nonce }
23 }
24
25 #[must_use]
26 pub const fn envelope(self) -> &'a PageEnvelope {
27 self.envelope
28 }
29
30 #[must_use]
31 pub const fn nonce(self) -> Option<&'a CspNonce> {
32 self.nonce
33 }
34
35 #[must_use]
37 pub fn nonce_attribute(self) -> String {
38 nonce_attribute(self.nonce)
39 }
40}
41
42#[derive(Clone, Debug, Default, Eq, PartialEq)]
47pub struct TrustedHtml(String);
48
49impl TrustedHtml {
50 #[must_use]
51 pub fn new(html: impl Into<String>) -> Self {
52 Self(html.into())
53 }
54
55 #[must_use]
56 pub fn as_str(&self) -> &str {
57 &self.0
58 }
59}
60
61#[derive(Clone, Debug, Default, Eq, PartialEq)]
63pub struct DocumentSlots {
64 html_attributes: Vec<(String, String)>,
65 body_attributes: Vec<(String, String)>,
66 root_attributes: Vec<(String, String)>,
67 head: TrustedHtml,
68 before_root: TrustedHtml,
69 after_root: TrustedHtml,
70}
71
72impl DocumentSlots {
73 #[must_use]
74 pub fn new() -> Self {
75 Self::default()
76 }
77
78 #[must_use]
80 pub fn language(mut self, language: impl Into<String>) -> Self {
81 set_attribute(&mut self.html_attributes, "lang", language.into());
82 self
83 }
84
85 pub fn html_attribute(
91 mut self,
92 name: impl Into<String>,
93 value: impl Into<String>,
94 ) -> Result<Self, DocumentTemplateError> {
95 let name = checked_attribute_name(name.into())?;
96 set_attribute(&mut self.html_attributes, &name, value.into());
97 Ok(self)
98 }
99
100 pub fn body_attribute(
106 mut self,
107 name: impl Into<String>,
108 value: impl Into<String>,
109 ) -> Result<Self, DocumentTemplateError> {
110 let name = checked_attribute_name(name.into())?;
111 set_attribute(&mut self.body_attributes, &name, value.into());
112 Ok(self)
113 }
114
115 pub fn root_attribute(
124 mut self,
125 name: impl Into<String>,
126 value: impl Into<String>,
127 ) -> Result<Self, DocumentTemplateError> {
128 let name = checked_attribute_name(name.into())?;
129 if matches!(
130 name.to_ascii_lowercase().as_str(),
131 "id" | "data-render-mode"
132 ) {
133 return Err(DocumentTemplateError::ReservedRootAttribute(name));
134 }
135 set_attribute(&mut self.root_attributes, &name, value.into());
136 Ok(self)
137 }
138
139 #[must_use]
141 pub fn head(mut self, html: TrustedHtml) -> Self {
142 self.head = html;
143 self
144 }
145
146 #[must_use]
148 pub fn before_root(mut self, html: TrustedHtml) -> Self {
149 self.before_root = html;
150 self
151 }
152
153 #[must_use]
155 pub fn after_root(mut self, html: TrustedHtml) -> Self {
156 self.after_root = html;
157 self
158 }
159}
160
161#[derive(Clone)]
166pub struct DocumentTemplate {
167 render: Arc<DocumentRender>,
168}
169
170impl DocumentTemplate {
171 #[must_use]
173 pub fn new(slots: DocumentSlots) -> Self {
174 Self::from_fn(move |_| slots.clone())
175 }
176
177 #[must_use]
179 pub fn from_fn<F>(render: F) -> Self
180 where
181 F: for<'a> Fn(DocumentContext<'a>) -> DocumentSlots + Send + Sync + 'static,
182 {
183 Self {
184 render: Arc::new(move |context| Ok(render(context))),
185 }
186 }
187
188 #[must_use]
190 pub fn try_from_fn<F>(render: F) -> Self
191 where
192 F: for<'a> Fn(DocumentContext<'a>) -> Result<DocumentSlots, DocumentTemplateError>
193 + Send
194 + Sync
195 + 'static,
196 {
197 Self {
198 render: Arc::new(render),
199 }
200 }
201
202 pub(crate) fn render(
203 &self,
204 context: DocumentContext<'_>,
205 ) -> Result<DocumentSlots, DocumentTemplateError> {
206 (self.render)(context)
207 }
208}
209
210impl Default for DocumentTemplate {
211 fn default() -> Self {
212 Self::new(DocumentSlots::default())
213 }
214}
215
216impl std::fmt::Debug for DocumentTemplate {
217 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218 formatter.write_str("DocumentTemplate(<function>)")
219 }
220}
221
222#[derive(Clone, Debug, Error, Eq, PartialEq)]
223pub enum DocumentTemplateError {
224 #[error("invalid HTML attribute name `{0}`")]
225 InvalidAttributeName(String),
226 #[error("Phoenix owns the root attribute `{0}`")]
227 ReservedRootAttribute(String),
228 #[error("document template failed: {0}")]
229 Render(String),
230}
231
232impl DocumentTemplateError {
233 #[must_use]
234 pub fn render(message: impl Into<String>) -> Self {
235 Self::Render(message.into())
236 }
237}
238
239pub(crate) fn document_prefix(
240 envelope: &PageEnvelope,
241 stylesheets: &[String],
242 nonce: Option<&CspNonce>,
243 slots: &DocumentSlots,
244) -> String {
245 let nonce_attribute = nonce_attribute(nonce);
246 let styles = stylesheets
247 .iter()
248 .fold(String::new(), |mut styles, source| {
249 let _ = write!(
250 styles,
251 "<link rel=\"stylesheet\" href=\"{}\"{nonce_attribute}>",
252 html_attribute(source),
253 );
254 styles
255 });
256 let head = document_head(&envelope.head);
257 let nonce_meta = nonce.map_or_else(String::new, |_| {
258 format!("<meta property=\"csp-nonce\"{nonce_attribute}>")
259 });
260 let html_attributes = render_attributes(&slots.html_attributes);
261 let body_attributes = render_attributes(&slots.body_attributes);
262 let root_attributes = render_attributes(&slots.root_attributes);
263 format!(
264 "<!doctype html><html{html_attributes}><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">{nonce_meta}{head}{styles}{custom_head}</head><body{body_attributes}>{before_root}<div id=\"phoenix-root\" data-render-mode=\"{mode}\"{root_attributes}>",
265 custom_head = slots.head.as_str(),
266 before_root = slots.before_root.as_str(),
267 mode = envelope.render_mode.as_str(),
268 )
269}
270
271pub(crate) fn document_suffix(
272 envelope: &PageEnvelope,
273 script_src: &str,
274 nonce: Option<&CspNonce>,
275 slots: &DocumentSlots,
276) -> Result<String, serde_json::Error> {
277 let payload = json_for_html(envelope)?;
278 let script_src = html_attribute(script_src);
279 let nonce_attribute = nonce_attribute(nonce);
280 Ok(format!(
281 "</div>{after_root}<script id=\"phoenix-page\" type=\"application/json\"{nonce_attribute}>{payload}</script><script type=\"module\" src=\"{script_src}\"{nonce_attribute}></script></body></html>",
282 after_root = slots.after_root.as_str(),
283 ))
284}
285
286fn document_head(head: &PageHead) -> String {
287 let mut output = String::new();
288 if let Some(title) = &head.title {
289 let _ = write!(
290 output,
291 "<title data-phoenix-head>{}</title>",
292 html_text(title)
293 );
294 }
295 if let Some(description) = &head.description {
296 push_meta(&mut output, "name", "description", description);
297 }
298 if let Some(canonical) = &head.canonical {
299 let _ = write!(
300 output,
301 "<link rel=\"canonical\" href=\"{}\" data-phoenix-head>",
302 html_attribute(canonical)
303 );
304 }
305 if let Some(robots) = &head.robots {
306 push_meta(&mut output, "name", "robots", robots);
307 }
308 if let Some(open_graph) = &head.open_graph {
309 if let Some(value) = &open_graph.title {
310 push_meta(&mut output, "property", "og:title", value);
311 }
312 if let Some(value) = &open_graph.description {
313 push_meta(&mut output, "property", "og:description", value);
314 }
315 if let Some(value) = &open_graph.image {
316 push_meta(&mut output, "property", "og:image", value);
317 }
318 if let Some(value) = &open_graph.kind {
319 push_meta(&mut output, "property", "og:type", value);
320 }
321 }
322 output
323}
324
325fn push_meta(output: &mut String, key: &str, name: &str, content: &str) {
326 let _ = write!(
327 output,
328 "<meta {key}=\"{}\" content=\"{}\" data-phoenix-head>",
329 html_attribute(name),
330 html_attribute(content)
331 );
332}
333
334fn checked_attribute_name(name: String) -> Result<String, DocumentTemplateError> {
335 let mut characters = name.chars();
336 let valid_start = characters
337 .next()
338 .is_some_and(|character| character.is_ascii_alphabetic() || matches!(character, '_' | ':'));
339 if !valid_start
340 || !characters.all(|character| {
341 character.is_ascii_alphanumeric() || matches!(character, '_' | ':' | '.' | '-')
342 })
343 {
344 return Err(DocumentTemplateError::InvalidAttributeName(name));
345 }
346 Ok(name)
347}
348
349fn set_attribute(attributes: &mut Vec<(String, String)>, name: &str, value: String) {
350 if let Some((_, current)) = attributes
351 .iter_mut()
352 .find(|(current, _)| current.eq_ignore_ascii_case(name))
353 {
354 *current = value;
355 } else {
356 attributes.push((name.to_owned(), value));
357 }
358}
359
360fn render_attributes(attributes: &[(String, String)]) -> String {
361 attributes
362 .iter()
363 .fold(String::new(), |mut output, (name, value)| {
364 let _ = write!(output, " {name}=\"{}\"", html_attribute(value));
365 output
366 })
367}
368
369fn nonce_attribute(nonce: Option<&CspNonce>) -> String {
370 nonce.map_or_else(String::new, |nonce| {
371 format!(" nonce=\"{}\"", html_attribute(nonce.as_str()))
372 })
373}
374
375fn html_attribute(value: &str) -> String {
376 value
377 .replace('&', "&")
378 .replace('"', """)
379 .replace('<', "<")
380 .replace('>', ">")
381}
382
383fn html_text(value: &str) -> String {
384 value
385 .replace('&', "&")
386 .replace('<', "<")
387 .replace('>', ">")
388}
389
390fn json_for_html(value: &impl Serialize) -> Result<String, serde_json::Error> {
391 serde_json::to_string(value).map(|json| {
392 json.replace('&', "\\u0026")
393 .replace('<', "\\u003c")
394 .replace('>', "\\u003e")
395 .replace('\u{2028}', "\\u2028")
396 .replace('\u{2029}', "\\u2029")
397 })
398}
399
400#[cfg(test)]
401mod tests {
402 use serde_json::json;
403
404 use super::*;
405 use crate::PageEnvelope;
406
407 #[test]
408 fn custom_slots_escape_attributes_and_preserve_framework_elements() {
409 let envelope = PageEnvelope::new_for_test(json!({ "safe": "</script>" }));
410 let nonce = CspNonce::new("0123456789abcdef0123456789abcdef").unwrap();
411 let slots = DocumentSlots::new()
412 .language("zh-CN")
413 .body_attribute("data-theme", "dark\" data-bad=\"1")
414 .unwrap()
415 .root_attribute("class", "application-root")
416 .unwrap()
417 .head(TrustedHtml::new(
418 "<meta name=\"application\" content=\"custom\">",
419 ))
420 .before_root(TrustedHtml::new("<header>Brand</header>"))
421 .after_root(TrustedHtml::new("<footer>Footer</footer>"));
422
423 let prefix = document_prefix(
424 &envelope,
425 &["/assets/app.css".to_owned()],
426 Some(&nonce),
427 &slots,
428 );
429 let suffix = document_suffix(&envelope, "/assets/app.js", Some(&nonce), &slots).unwrap();
430
431 assert!(prefix.contains("<html lang=\"zh-CN\">"));
432 assert!(prefix.contains("<body data-theme=\"dark" data-bad="1\">"));
433 assert!(prefix.contains("<header>Brand</header><div id=\"phoenix-root\""));
434 assert!(prefix.contains("class=\"application-root\""));
435 assert!(prefix.contains("<meta name=\"application\" content=\"custom\">"));
436 assert!(prefix.contains("nonce=\"0123456789abcdef0123456789abcdef\""));
437 assert!(suffix.starts_with("</div><footer>Footer</footer>"));
438 assert!(suffix.contains("\\u003c/script\\u003e"));
439 assert!(suffix.contains("id=\"phoenix-page\""));
440 assert!(suffix.contains("type=\"module\""));
441 }
442
443 #[test]
444 fn template_functions_receive_page_and_nonce_context() {
445 let envelope = PageEnvelope::new_for_test(json!({}));
446 let nonce = CspNonce::new("fedcba9876543210fedcba9876543210").unwrap();
447 let template = DocumentTemplate::from_fn(|context| {
448 DocumentSlots::new().head(TrustedHtml::new(format!(
449 "<script{}>window.page={:?}</script>",
450 context.nonce_attribute(),
451 context.envelope().page,
452 )))
453 });
454
455 let slots = template
456 .render(DocumentContext::new(&envelope, Some(&nonce)))
457 .unwrap();
458 let prefix = document_prefix(&envelope, &[], Some(&nonce), &slots);
459
460 assert!(prefix.contains("window.page=\"test/page\""));
461 assert!(prefix.contains("<script nonce=\"fedcba9876543210fedcba9876543210\">"));
462 }
463
464 #[test]
465 fn invalid_and_framework_owned_attributes_fail_closed() {
466 assert!(matches!(
467 DocumentSlots::new().body_attribute("on load", "bad"),
468 Err(DocumentTemplateError::InvalidAttributeName(_))
469 ));
470 assert!(matches!(
471 DocumentSlots::new().root_attribute("ID", "replacement"),
472 Err(DocumentTemplateError::ReservedRootAttribute(_))
473 ));
474 }
475}