capy-mail 0.10.0

Conventional SMTP mail, typed templates, and mail notifications for Capy.
Documentation
use crate::{DeliveryReceipt, Mail, MailError, MailResult, MailTransport, Mailbox, PreparedMail};
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::{
    fs::{self, File, OpenOptions},
    future::Future,
    io::{Read, Write},
    path::{Path, PathBuf},
    pin::Pin,
    time::{SystemTime, UNIX_EPOCH},
};
const MAX_BYTES: u64 = 64 * 1024 * 1024;
const MAX_MESSAGES: usize = 100;

#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct CaptureContent {
    from: Mailbox,
    text: Option<String>,
    html: Option<String>,
    headers: Vec<(String, String)>,
}
impl CaptureContent {
    pub(crate) fn new(mail: &Mail, default_from: &Mailbox) -> Self {
        Self {
            from: mail.from.clone().unwrap_or_else(|| default_from.clone()),
            text: mail.text.clone(),
            html: mail.html.clone(),
            headers: mail.headers.clone(),
        }
    }
}
/// Explicitly inspectable message, redacted in Debug. Never include contents in logs.
#[derive(Clone, Serialize, Deserialize)]
pub struct CapturedMail {
    id: String,
    message_id: String,
    message_type: String,
    subject: String,
    recipients: Vec<Mailbox>,
    content: CaptureContent,
    mime: String,
    timestamp_ms: u64,
}
impl CapturedMail {
    pub(crate) fn from_prepared(mail: PreparedMail) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            mime: String::from_utf8_lossy(&mail.message.formatted()).into_owned(),
            message_id: mail.message_id,
            message_type: mail.message_type,
            subject: mail.subject,
            recipients: mail.recipients,
            content: mail.content,
            timestamp_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis() as u64,
        }
    }
    pub(crate) fn bytes(&self) -> usize {
        self.mime.len()
            + self.content.text.as_ref().map_or(0, String::len)
            + self.content.html.as_ref().map_or(0, String::len)
            + self.subject.len()
            + self.recipients.len() * 512
            + 8192
    }
    /// Local inbox UUID, distinct from the possibly replayed MIME Message-ID.
    pub fn id(&self) -> &str {
        &self.id
    }
    /// MIME Message-ID (stable for queued retries).
    pub fn message_id(&self) -> &str {
        &self.message_id
    }
    /// Capture time in Unix milliseconds.
    pub fn timestamp_ms(&self) -> u64 {
        self.timestamp_ms
    }
    /// Sender, explicitly accessible for private assertions/development inspection.
    pub fn sender(&self) -> &Mailbox {
        &self.content.from
    }
    /// All envelope recipients, including Bcc; treat this as private data.
    pub fn recipients(&self) -> &[Mailbox] {
        &self.recipients
    }
    /// Original subject.
    pub fn subject(&self) -> &str {
        &self.subject
    }
    /// Unencoded text alternative.
    pub fn text(&self) -> Option<&str> {
        self.content.text.as_deref()
    }
    /// Unencoded HTML alternative. The CLI displays source and never executes it.
    pub fn html(&self) -> Option<&str> {
        self.content.html.as_deref()
    }
    /// Application custom headers; standard headers are available in `raw_message`.
    pub fn headers(&self) -> &[(String, String)] {
        &self.content.headers
    }
    /// Full rendered MIME bytes for parser-based assertions.
    pub fn raw_message(&self) -> Vec<u8> {
        self.mime.as_bytes().to_vec()
    }
    /// Compare a recipient without printing PII on assertion failure.
    pub fn was_sent_to(&self, address: &str) -> bool {
        self.recipients.iter().any(|r| r.address() == address)
    }
    /// Compare a subject without printing it.
    pub fn has_subject(&self, subject: &str) -> bool {
        self.subject == subject
    }
    /// Compare a typed mailable name.
    pub fn is_type<M: crate::Mailable>(&self) -> bool {
        self.message_type == M::NAME
    }
}
impl std::fmt::Debug for CapturedMail {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("CapturedMail([REDACTED])")
    }
}
/// Private disk-backed development inbox shared by HTTP, workers and `capy mail`.
/// Retains at most 100 messages/64 MiB until explicitly cleared; a full inbox fails
/// delivery instead of silently evicting. No network listener or HTML renderer exists.
/// Files contain plaintext development secrets: never use production recipient data.
#[derive(Clone)]
pub struct DevelopmentInbox {
    directory: PathBuf,
}
impl DevelopmentInbox {
    /// Choose a local directory (normally config.mail.capture_directory).
    /// No filesystem access until a command/send; production Mailer rejects this transport.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self {
            directory: path.into(),
        }
    }
    fn lock(&self) -> MailResult<File> {
        let mut builder = fs::DirBuilder::new();
        builder.recursive(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::DirBuilderExt;
            builder.mode(0o700);
        }
        builder
            .create(&self.directory)
            .map_err(|_| MailError::CaptureStorage)?;
        let metadata =
            fs::symlink_metadata(&self.directory).map_err(|_| MailError::CaptureStorage)?;
        if !metadata.is_dir() || metadata.file_type().is_symlink() {
            return Err(MailError::CaptureStorage);
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if metadata.permissions().mode() & 0o077 != 0 {
                return Err(MailError::CaptureStorage);
            }
        }
        let path = self.directory.join(".lock");
        reject_symlink(&path)?;
        let mut options = OpenOptions::new();
        options.read(true).write(true).create(true).truncate(false);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let lock = options.open(path).map_err(|_| MailError::CaptureStorage)?;
        lock.lock_exclusive()
            .map_err(|_| MailError::CaptureStorage)?;
        Ok(lock)
    }
    fn files(&self) -> MailResult<Vec<PathBuf>> {
        let mut files = Vec::new();
        for entry in fs::read_dir(&self.directory).map_err(|_| MailError::CaptureStorage)? {
            let entry = entry.map_err(|_| MailError::CaptureStorage)?;
            let path = entry.path();
            if path.extension().is_some_and(|v| v == "json") {
                reject_symlink(&path)?;
                files.push(path);
            }
        }
        if files.len() > MAX_MESSAGES {
            return Err(MailError::CaptureFull);
        }
        Ok(files)
    }
    fn read(path: &Path) -> MailResult<CapturedMail> {
        reject_symlink(path)?;
        let file = File::open(path).map_err(|_| MailError::CaptureStorage)?;
        if file
            .metadata()
            .map_err(|_| MailError::CaptureStorage)?
            .len()
            > MAX_BYTES
        {
            return Err(MailError::CaptureFull);
        }
        let mut bytes = Vec::new();
        file.take(MAX_BYTES + 1)
            .read_to_end(&mut bytes)
            .map_err(|_| MailError::CaptureStorage)?;
        if bytes.len() as u64 > MAX_BYTES {
            return Err(MailError::CaptureFull);
        }
        serde_json::from_slice(&bytes).map_err(|_| MailError::CaptureStorage)
    }
    /// Inspect messages in timestamp/UUID order. Blocking local I/O; use outside HTTP
    /// handlers or in spawn_blocking. CLI contents are deliberately private output.
    pub fn list(&self) -> MailResult<Vec<CapturedMail>> {
        let _lock = self.lock()?;
        let files = self.files()?;
        let total = files
            .iter()
            .try_fold(0u64, |total, p| {
                fs::metadata(p).map(|m| total.saturating_add(m.len()))
            })
            .map_err(|_| MailError::CaptureStorage)?;
        if total > MAX_BYTES {
            return Err(MailError::CaptureFull);
        }
        let mut messages = files
            .iter()
            .map(|p| Self::read(p))
            .collect::<MailResult<Vec<_>>>()?;
        messages.sort_by(|a, b| (a.timestamp_ms, &a.id).cmp(&(b.timestamp_ms, &b.id)));
        Ok(messages)
    }
    /// Read one UUID; arbitrary paths and symlinks are rejected.
    pub fn show(&self, id: &str) -> MailResult<CapturedMail> {
        let id = uuid::Uuid::parse_str(id).map_err(|_| MailError::CaptureStorage)?;
        let _lock = self.lock()?;
        Self::read(&self.directory.join(format!("{id}.json")))
    }
    /// Delete captured JSON messages under the inbox lock, preserving unrelated files.
    pub fn clear(&self) -> MailResult<usize> {
        let _lock = self.lock()?;
        let files = self.files()?;
        for file in &files {
            fs::remove_file(file).map_err(|_| MailError::CaptureStorage)?;
        }
        Ok(files.len())
    }
    fn store(&self, mail: CapturedMail) -> MailResult<()> {
        let _lock = self.lock()?;
        let bytes = serde_json::to_vec(&mail).map_err(|_| MailError::CaptureStorage)?;
        let files = self.files()?;
        let retained = files
            .iter()
            .try_fold(0u64, |total, p| {
                fs::metadata(p).map(|m| total.saturating_add(m.len()))
            })
            .map_err(|_| MailError::CaptureStorage)?;
        if files.len() >= MAX_MESSAGES || retained.saturating_add(bytes.len() as u64) > MAX_BYTES {
            return Err(MailError::CaptureFull);
        }
        let mut file = tempfile::NamedTempFile::new_in(&self.directory)
            .map_err(|_| MailError::CaptureStorage)?;
        file.write_all(&bytes)
            .map_err(|_| MailError::CaptureStorage)?;
        file.as_file()
            .sync_all()
            .map_err(|_| MailError::CaptureStorage)?;
        file.persist_noclobber(self.directory.join(format!("{}.json", mail.id)))
            .map_err(|_| MailError::CaptureStorage)?;
        tracing::debug!(event = "mail.capture.stored");
        Ok(())
    }
}
fn reject_symlink(path: &Path) -> MailResult<()> {
    match fs::symlink_metadata(path) {
        Ok(m) if m.file_type().is_symlink() || !m.is_file() => Err(MailError::CaptureStorage),
        Ok(_) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(_) => Err(MailError::CaptureStorage),
    }
}
impl MailTransport for DevelopmentInbox {
    fn name(&self) -> &'static str {
        "capture"
    }
    fn development_only(&self) -> bool {
        true
    }
    fn send(
        &self,
        mail: PreparedMail,
    ) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>> {
        Box::pin(async move {
            let inbox = self.clone();
            let receipt = DeliveryReceipt {
                message_id: mail.message_id.clone(),
                provider_id: None,
            };
            tokio::task::spawn_blocking(move || inbox.store(CapturedMail::from_prepared(mail)))
                .await
                .map_err(|_| MailError::CaptureStorage)??;
            Ok(receipt)
        })
    }
}