1use crate::{AppError, Result};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Default, Deserialize, Serialize)]
6#[serde(transparent)]
7pub struct MailSecret(String);
8impl MailSecret {
9 pub fn expose(&self) -> &str {
11 &self.0
12 }
13}
14impl From<String> for MailSecret {
15 fn from(value: String) -> Self {
16 Self(value)
17 }
18}
19impl std::fmt::Debug for MailSecret {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 f.write_str("[REDACTED]")
22 }
23}
24
25#[derive(Clone, Debug, Deserialize, Serialize)]
27#[serde(default, deny_unknown_fields)]
28pub struct MailSettings {
29 pub driver: String,
31 pub from_address: String,
33 pub from_name: Option<String>,
35 pub timeout_seconds: u64,
37 pub max_message_bytes: usize,
39 pub queue: String,
41 pub smtp: SmtpSettings,
43}
44impl Default for MailSettings {
45 fn default() -> Self {
46 Self {
47 driver: "log".into(),
48 from_address: "hello@localhost.test".into(),
49 from_name: Some("Capy".into()),
50 timeout_seconds: 15,
51 max_message_bytes: 10 * 1024 * 1024,
52 queue: "mail".into(),
53 smtp: SmtpSettings::default(),
54 }
55 }
56}
57#[derive(Clone, Debug, Deserialize, Serialize)]
59#[serde(default, deny_unknown_fields)]
60pub struct SmtpSettings {
61 pub host: String,
63 pub port: u16,
65 pub encryption: String,
67 pub username: MailSecret,
69 pub password: MailSecret,
71}
72impl Default for SmtpSettings {
73 fn default() -> Self {
74 Self {
75 host: "localhost".into(),
76 port: 587,
77 encryption: "starttls".into(),
78 username: MailSecret::default(),
79 password: MailSecret::default(),
80 }
81 }
82}
83impl MailSettings {
84 pub fn validate(&self) -> Result<()> {
86 if !matches!(self.driver.as_str(), "smtp" | "log")
87 || !(1..=300).contains(&self.timeout_seconds)
88 || !(1..=25 * 1024 * 1024).contains(&self.max_message_bytes)
89 || self.queue.is_empty()
90 || self.queue.len() > 128
91 || !self
92 .queue
93 .bytes()
94 .all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
95 {
96 return Err(AppError::Configuration("Invalid mail settings: driver smtp/log, timeout_seconds 1..=300, max_message_bytes 1..=26214400, and a valid queue name are required.".into()));
97 }
98 if self.smtp.host.is_empty()
99 || self.smtp.host.len() > 253
100 || !self
101 .smtp
102 .host
103 .bytes()
104 .all(|c| c.is_ascii_alphanumeric() || b".-:".contains(&c))
105 || self.smtp.port == 0
106 || !matches!(self.smtp.encryption.as_str(), "starttls" | "tls" | "none")
107 || self.smtp.username.expose().is_empty() != self.smtp.password.expose().is_empty()
108 {
109 return Err(AppError::Configuration("Invalid SMTP settings: use a host, nonzero port, starttls/tls/none encryption and paired credentials.".into()));
110 }
111 if self.smtp.encryption == "none" && !self.smtp.password.expose().is_empty() {
112 return Err(AppError::Configuration(
113 "SMTP authentication requires TLS, including in development.".into(),
114 ));
115 }
116 Ok(())
117 }
118}