capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use serde::{Deserialize, Serialize};

/// A configuration credential. Debug is redacted; serialization is for config merging.
#[derive(Clone, Default, Deserialize, Serialize)]
#[serde(transparent)]
pub struct MailSecret(String);
impl MailSecret {
    /// Explicitly access the credential for transport initialization.
    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]")
    }
}

/// Conventional outbound mail settings; activated by `App::mail`.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct MailSettings {
    /// `log` (metadata only), `capture` (local development inbox), or `smtp`.
    pub driver: String,
    /// Private local inbox directory for the development capture driver (default `.capy/mail`).
    pub capture_directory: std::path::PathBuf,
    /// Parsed by the mail subsystem before startup/delivery.
    pub from_address: String,
    /// Optional display name.
    pub from_name: Option<String>,
    /// Total transport deadline, including connection establishment (1..=300 seconds).
    pub timeout_seconds: u64,
    /// Maximum unencoded message content bytes (1..=26214400); default 10 MiB.
    pub max_message_bytes: usize,
    /// Logical queue for ordinary, explicitly queueable mail.
    pub queue: String,
    /// SMTP connection and authentication.
    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(),
        }
    }
}
/// SMTP settings. TLS is mandatory in production; no opportunistic downgrade.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct SmtpSettings {
    /// Hostname validated without network access.
    pub host: String,
    /// Server port.
    pub port: u16,
    /// `starttls`, `tls` (implicit TLS), or development-only `none`.
    pub encryption: String,
    /// Optional username; must be paired with password.
    pub username: MailSecret,
    /// Optional password; never include it in diagnostics.
    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 {
    /// Validate the configuration shape offline. Address parsing is done by capy-mail.
    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(())
    }
}