1#![deny(missing_docs)]
8#![allow(clippy::module_name_repetitions)]
9
10use std::{
13 collections::{BTreeMap, HashSet},
14 sync::Arc,
15};
16
17use anyhow::Context as _;
18use arc_swap::ArcSwap;
19use camino::{Utf8Path, Utf8PathBuf};
20use mas_i18n::Translator;
21use mas_router::UrlBuilder;
22use mas_spa::ViteManifest;
23use minijinja::{UndefinedBehavior, Value};
24use rand::Rng;
25use serde::Serialize;
26use thiserror::Error;
27use tokio::task::JoinError;
28use tracing::{debug, info};
29use walkdir::DirEntry;
30
31mod context;
32mod forms;
33mod functions;
34
35#[macro_use]
36mod macros;
37
38pub use self::{
39 context::{
40 AccountInactiveContext, ApiDocContext, AppContext, CompatSsoContext, ConsentContext,
41 DeviceConsentContext, DeviceLinkContext, DeviceLinkFormField, DeviceNameContext,
42 EmailRecoveryContext, EmailVerificationContext, EmptyContext, ErrorContext,
43 FormPostContext, IndexContext, LoginContext, LoginFormField, NotFoundContext,
44 PasswordRegisterContext, PolicyViolationContext, PostAuthContext, PostAuthContextInner,
45 RecoveryExpiredContext, RecoveryFinishContext, RecoveryFinishFormField,
46 RecoveryProgressContext, RecoveryStartContext, RecoveryStartFormField, RegisterContext,
47 RegisterFormField, RegisterStepsDisplayNameContext, RegisterStepsDisplayNameFormField,
48 RegisterStepsEmailInUseContext, RegisterStepsRegistrationTokenContext,
49 RegisterStepsRegistrationTokenFormField, RegisterStepsVerifyEmailContext,
50 RegisterStepsVerifyEmailFormField, SiteBranding, SiteConfigExt, SiteFeatures,
51 TemplateContext, UpstreamExistingLinkContext, UpstreamRegister, UpstreamRegisterFormField,
52 UpstreamSuggestLink, WithCaptcha, WithCsrf, WithLanguage, WithOptionalSession, WithSession,
53 },
54 forms::{FieldError, FormError, FormField, FormState, ToFormState},
55};
56use crate::context::SampleIdentifier;
57
58#[must_use]
62pub fn escape_html(input: &str) -> String {
63 v_htmlescape::escape(input).to_string()
64}
65
66#[derive(Debug, Clone)]
69pub struct Templates {
70 environment: Arc<ArcSwap<minijinja::Environment<'static>>>,
71 translator: Arc<ArcSwap<Translator>>,
72 url_builder: UrlBuilder,
73 branding: SiteBranding,
74 features: SiteFeatures,
75 vite_manifest_path: Option<Utf8PathBuf>,
76 translations_path: Utf8PathBuf,
77 path: Utf8PathBuf,
78 strict: bool,
81}
82
83#[derive(Error, Debug)]
85pub enum TemplateLoadingError {
86 #[error(transparent)]
88 IO(#[from] std::io::Error),
89
90 #[error("failed to read the assets manifest")]
92 ViteManifestIO(#[source] std::io::Error),
93
94 #[error("invalid assets manifest")]
96 ViteManifest(#[from] serde_json::Error),
97
98 #[error("failed to load the translations")]
100 Translations(#[from] mas_i18n::LoadError),
101
102 #[error("failed to traverse the filesystem")]
104 WalkDir(#[from] walkdir::Error),
105
106 #[error("encountered non-UTF-8 path")]
108 NonUtf8Path(#[from] camino::FromPathError),
109
110 #[error("encountered non-UTF-8 path")]
112 NonUtf8PathBuf(#[from] camino::FromPathBufError),
113
114 #[error("encountered invalid path")]
116 InvalidPath(#[from] std::path::StripPrefixError),
117
118 #[error("could not load and compile some templates")]
120 Compile(#[from] minijinja::Error),
121
122 #[error("error from async runtime")]
124 Runtime(#[from] JoinError),
125
126 #[error("missing templates {missing:?}")]
128 MissingTemplates {
129 missing: HashSet<String>,
131 loaded: HashSet<String>,
133 },
134}
135
136fn is_hidden(entry: &DirEntry) -> bool {
137 entry
138 .file_name()
139 .to_str()
140 .is_some_and(|s| s.starts_with('.'))
141}
142
143impl Templates {
144 #[tracing::instrument(
155 name = "templates.load",
156 skip_all,
157 fields(%path),
158 )]
159 pub async fn load(
160 path: Utf8PathBuf,
161 url_builder: UrlBuilder,
162 vite_manifest_path: Option<Utf8PathBuf>,
163 translations_path: Utf8PathBuf,
164 branding: SiteBranding,
165 features: SiteFeatures,
166 strict: bool,
167 ) -> Result<Self, TemplateLoadingError> {
168 let (translator, environment) = Self::load_(
169 &path,
170 url_builder.clone(),
171 vite_manifest_path.as_deref(),
172 &translations_path,
173 branding.clone(),
174 features,
175 strict,
176 )
177 .await?;
178 Ok(Self {
179 environment: Arc::new(ArcSwap::new(environment)),
180 translator: Arc::new(ArcSwap::new(translator)),
181 path,
182 url_builder,
183 vite_manifest_path,
184 translations_path,
185 branding,
186 features,
187 strict,
188 })
189 }
190
191 async fn load_(
192 path: &Utf8Path,
193 url_builder: UrlBuilder,
194 vite_manifest_path: Option<&Utf8Path>,
195 translations_path: &Utf8Path,
196 branding: SiteBranding,
197 features: SiteFeatures,
198 strict: bool,
199 ) -> Result<(Arc<Translator>, Arc<minijinja::Environment<'static>>), TemplateLoadingError> {
200 let path = path.to_owned();
201 let span = tracing::Span::current();
202
203 let vite_manifest = if let Some(vite_manifest_path) = vite_manifest_path {
205 let raw_vite_manifest = tokio::fs::read(vite_manifest_path)
206 .await
207 .map_err(TemplateLoadingError::ViteManifestIO)?;
208
209 serde_json::from_slice::<ViteManifest>(&raw_vite_manifest)
210 .map_err(TemplateLoadingError::ViteManifest)?
211 } else {
212 ViteManifest::sample()
213 };
214
215 let translations_path = translations_path.to_owned();
218 let translator =
219 tokio::task::spawn_blocking(move || Translator::load_from_path(&translations_path))
220 .await??;
221 let translator = Arc::new(translator);
222
223 debug!(locales = ?translator.available_locales(), "Loaded translations");
224
225 let (loaded, mut env) = tokio::task::spawn_blocking(move || {
226 span.in_scope(move || {
227 let mut loaded: HashSet<_> = HashSet::new();
228 let mut env = minijinja::Environment::new();
229 env.set_undefined_behavior(if strict {
231 UndefinedBehavior::Strict
232 } else {
233 UndefinedBehavior::SemiStrict
237 });
238 let root = path.canonicalize_utf8()?;
239 info!(%root, "Loading templates from filesystem");
240 for entry in walkdir::WalkDir::new(&root)
241 .min_depth(1)
242 .into_iter()
243 .filter_entry(|e| !is_hidden(e))
244 {
245 let entry = entry?;
246 if entry.file_type().is_file() {
247 let path = Utf8PathBuf::try_from(entry.into_path())?;
248 let Some(ext) = path.extension() else {
249 continue;
250 };
251
252 if ext == "html" || ext == "txt" || ext == "subject" {
253 let relative = path.strip_prefix(&root)?;
254 debug!(%relative, "Registering template");
255 let template = std::fs::read_to_string(&path)?;
256 env.add_template_owned(relative.as_str().to_owned(), template)?;
257 loaded.insert(relative.as_str().to_owned());
258 }
259 }
260 }
261
262 Ok::<_, TemplateLoadingError>((loaded, env))
263 })
264 })
265 .await??;
266
267 env.add_global("branding", Value::from_object(branding));
268 env.add_global("features", Value::from_object(features));
269
270 self::functions::register(
271 &mut env,
272 url_builder,
273 vite_manifest,
274 Arc::clone(&translator),
275 );
276
277 let env = Arc::new(env);
278
279 let needed: HashSet<_> = TEMPLATES.into_iter().map(ToOwned::to_owned).collect();
280 debug!(?loaded, ?needed, "Templates loaded");
281 let missing: HashSet<_> = needed.difference(&loaded).cloned().collect();
282
283 if missing.is_empty() {
284 Ok((translator, env))
285 } else {
286 Err(TemplateLoadingError::MissingTemplates { missing, loaded })
287 }
288 }
289
290 #[tracing::instrument(
296 name = "templates.reload",
297 skip_all,
298 fields(path = %self.path),
299 )]
300 pub async fn reload(&self) -> Result<(), TemplateLoadingError> {
301 let (translator, environment) = Self::load_(
302 &self.path,
303 self.url_builder.clone(),
304 self.vite_manifest_path.as_deref(),
305 &self.translations_path,
306 self.branding.clone(),
307 self.features,
308 self.strict,
309 )
310 .await?;
311
312 self.environment.store(environment);
314 self.translator.store(translator);
315
316 Ok(())
317 }
318
319 #[must_use]
321 pub fn translator(&self) -> Arc<Translator> {
322 self.translator.load_full()
323 }
324}
325
326#[derive(Error, Debug)]
328pub enum TemplateError {
329 #[error("missing template {template:?}")]
331 Missing {
332 template: &'static str,
334
335 #[source]
337 source: minijinja::Error,
338 },
339
340 #[error("could not render template {template:?}")]
342 Render {
343 template: &'static str,
345
346 #[source]
348 source: minijinja::Error,
349 },
350}
351
352register_templates! {
353 pub fn render_not_found(WithLanguage<NotFoundContext>) { "pages/404.html" }
355
356 pub fn render_app(WithLanguage<AppContext>) { "app.html" }
358
359 pub fn render_swagger(ApiDocContext) { "swagger/doc.html" }
361
362 pub fn render_swagger_callback(ApiDocContext) { "swagger/oauth2-redirect.html" }
364
365 pub fn render_login(WithLanguage<WithCsrf<LoginContext>>) { "pages/login.html" }
367
368 pub fn render_register(WithLanguage<WithCsrf<RegisterContext>>) { "pages/register/index.html" }
370
371 pub fn render_password_register(WithLanguage<WithCsrf<WithCaptcha<PasswordRegisterContext>>>) { "pages/register/password.html" }
373
374 pub fn render_register_steps_verify_email(WithLanguage<WithCsrf<RegisterStepsVerifyEmailContext>>) { "pages/register/steps/verify_email.html" }
376
377 pub fn render_register_steps_email_in_use(WithLanguage<RegisterStepsEmailInUseContext>) { "pages/register/steps/email_in_use.html" }
379
380 pub fn render_register_steps_display_name(WithLanguage<WithCsrf<RegisterStepsDisplayNameContext>>) { "pages/register/steps/display_name.html" }
382
383 pub fn render_register_steps_registration_token(WithLanguage<WithCsrf<RegisterStepsRegistrationTokenContext>>) { "pages/register/steps/registration_token.html" }
385
386 pub fn render_consent(WithLanguage<WithCsrf<WithSession<ConsentContext>>>) { "pages/consent.html" }
388
389 pub fn render_policy_violation(WithLanguage<WithCsrf<WithSession<PolicyViolationContext>>>) { "pages/policy_violation.html" }
391
392 pub fn render_sso_login(WithLanguage<WithCsrf<WithSession<CompatSsoContext>>>) { "pages/sso.html" }
394
395 pub fn render_index(WithLanguage<WithCsrf<WithOptionalSession<IndexContext>>>) { "pages/index.html" }
397
398 pub fn render_recovery_start(WithLanguage<WithCsrf<RecoveryStartContext>>) { "pages/recovery/start.html" }
400
401 pub fn render_recovery_progress(WithLanguage<WithCsrf<RecoveryProgressContext>>) { "pages/recovery/progress.html" }
403
404 pub fn render_recovery_finish(WithLanguage<WithCsrf<RecoveryFinishContext>>) { "pages/recovery/finish.html" }
406
407 pub fn render_recovery_expired(WithLanguage<WithCsrf<RecoveryExpiredContext>>) { "pages/recovery/expired.html" }
409
410 pub fn render_recovery_consumed(WithLanguage<EmptyContext>) { "pages/recovery/consumed.html" }
412
413 pub fn render_recovery_disabled(WithLanguage<EmptyContext>) { "pages/recovery/disabled.html" }
415
416 pub fn render_form_post<#[sample(EmptyContext)] T: Serialize>(WithLanguage<FormPostContext<T>>) { "form_post.html" }
418
419 pub fn render_error(ErrorContext) { "pages/error.html" }
421
422 pub fn render_email_recovery_txt(WithLanguage<EmailRecoveryContext>) { "emails/recovery.txt" }
424
425 pub fn render_email_recovery_html(WithLanguage<EmailRecoveryContext>) { "emails/recovery.html" }
427
428 pub fn render_email_recovery_subject(WithLanguage<EmailRecoveryContext>) { "emails/recovery.subject" }
430
431 pub fn render_email_verification_txt(WithLanguage<EmailVerificationContext>) { "emails/verification.txt" }
433
434 pub fn render_email_verification_html(WithLanguage<EmailVerificationContext>) { "emails/verification.html" }
436
437 pub fn render_email_verification_subject(WithLanguage<EmailVerificationContext>) { "emails/verification.subject" }
439
440 pub fn render_upstream_oauth2_link_mismatch(WithLanguage<WithCsrf<WithSession<UpstreamExistingLinkContext>>>) { "pages/upstream_oauth2/link_mismatch.html" }
442
443 pub fn render_upstream_oauth2_login_link(WithLanguage<WithCsrf<UpstreamExistingLinkContext>>) { "pages/upstream_oauth2/login_link.html" }
445
446 pub fn render_upstream_oauth2_suggest_link(WithLanguage<WithCsrf<WithSession<UpstreamSuggestLink>>>) { "pages/upstream_oauth2/suggest_link.html" }
448
449 pub fn render_upstream_oauth2_do_register(WithLanguage<WithCsrf<UpstreamRegister>>) { "pages/upstream_oauth2/do_register.html" }
451
452 pub fn render_device_link(WithLanguage<DeviceLinkContext>) { "pages/device_link.html" }
454
455 pub fn render_device_consent(WithLanguage<WithCsrf<WithSession<DeviceConsentContext>>>) { "pages/device_consent.html" }
457
458 pub fn render_account_deactivated(WithLanguage<WithCsrf<AccountInactiveContext>>) { "pages/account/deactivated.html" }
460
461 pub fn render_account_locked(WithLanguage<WithCsrf<AccountInactiveContext>>) { "pages/account/locked.html" }
463
464 pub fn render_account_logged_out(WithLanguage<WithCsrf<AccountInactiveContext>>) { "pages/account/logged_out.html" }
466
467 pub fn render_device_name(WithLanguage<DeviceNameContext>) { "device_name.txt" }
469}
470
471impl Templates {
472 pub fn check_render<R: Rng + Clone>(
485 &self,
486 now: chrono::DateTime<chrono::Utc>,
487 rng: &R,
488 ) -> anyhow::Result<BTreeMap<(&'static str, SampleIdentifier), String>> {
489 check::all(self, now, rng)
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use rand::SeedableRng;
496
497 use super::*;
498
499 #[tokio::test]
500 async fn check_builtin_templates() {
501 #[allow(clippy::disallowed_methods)]
502 let now = chrono::Utc::now();
503 let rng = rand_chacha::ChaCha8Rng::from_seed([42; 32]);
504
505 let path = Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("../../templates/");
506 let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
507 let branding = SiteBranding::new("example.com");
508 let features = SiteFeatures {
509 password_login: true,
510 password_registration: true,
511 password_registration_email_required: true,
512 account_recovery: true,
513 login_with_email_allowed: true,
514 };
515 let vite_manifest_path =
516 Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("../../frontend/dist/manifest.json");
517 let translations_path =
518 Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("../../translations");
519
520 for use_real_vite_manifest in [true, false] {
521 let templates = Templates::load(
522 path.clone(),
523 url_builder.clone(),
524 use_real_vite_manifest.then_some(vite_manifest_path.clone()),
527 translations_path.clone(),
528 branding.clone(),
529 features,
530 true,
532 )
533 .await
534 .unwrap();
535
536 let render1 = templates.check_render(now, &rng).unwrap();
538 let render2 = templates.check_render(now, &rng).unwrap();
539
540 assert_eq!(render1, render2);
541 }
542 }
543}