use crate::{AppError, Result};
use serde::{Deserialize, Serialize};
#[derive(Clone, Default, Deserialize, Serialize)]
#[serde(transparent)]
pub struct MailSecret(String);
impl MailSecret {
pub fn expose(&self) -> &str {
&self.0
}
}
impl From<String> for MailSecret {
fn from(value: String) -> Self {
Self(value)
}
}
impl std::fmt::Debug for MailSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[REDACTED]")
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct MailSettings {
pub driver: String,
pub capture_directory: std::path::PathBuf,
pub from_address: String,
pub from_name: Option<String>,
pub timeout_seconds: u64,
pub max_message_bytes: usize,
pub queue: String,
pub smtp: SmtpSettings,
}
impl Default for MailSettings {
fn default() -> Self {
Self {
driver: "log".into(),
capture_directory: ".capy/mail".into(),
from_address: "hello@localhost.test".into(),
from_name: Some("Capy".into()),
timeout_seconds: 15,
max_message_bytes: 10 * 1024 * 1024,
queue: "mail".into(),
smtp: SmtpSettings::default(),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct SmtpSettings {
pub host: String,
pub port: u16,
pub encryption: String,
pub username: MailSecret,
pub password: MailSecret,
}
impl Default for SmtpSettings {
fn default() -> Self {
Self {
host: "localhost".into(),
port: 587,
encryption: "starttls".into(),
username: MailSecret::default(),
password: MailSecret::default(),
}
}
}
impl MailSettings {
pub fn validate(&self) -> Result<()> {
if !matches!(self.driver.as_str(), "smtp" | "log" | "capture")
|| self.capture_directory.as_os_str().is_empty()
|| !(1..=300).contains(&self.timeout_seconds)
|| !(1..=25 * 1024 * 1024).contains(&self.max_message_bytes)
|| self.queue.is_empty()
|| self.queue.len() > 128
|| !self
.queue
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
{
return Err(AppError::Configuration("Invalid mail settings: a nonempty capture_directory, driver smtp/log/capture, timeout_seconds 1..=300, max_message_bytes 1..=26214400, and a valid queue name are required.".into()));
}
if self.smtp.host.is_empty()
|| self.smtp.host.len() > 253
|| !self
.smtp
.host
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b".-:".contains(&c))
|| self.smtp.port == 0
|| !matches!(self.smtp.encryption.as_str(), "starttls" | "tls" | "none")
|| self.smtp.username.expose().is_empty() != self.smtp.password.expose().is_empty()
{
return Err(AppError::Configuration("Invalid SMTP settings: use a host, nonzero port, starttls/tls/none encryption and paired credentials.".into()));
}
if self.smtp.encryption == "none" && !self.smtp.password.expose().is_empty() {
return Err(AppError::Configuration(
"SMTP authentication requires TLS, including in development.".into(),
));
}
Ok(())
}
}