ryuk-cli 0.1.0

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! The emails the auth flows send. The wording is in files, not here:
//!
//! | email | HTML part | plain-text part |
//! | --- | --- | --- |
//! | verify your email | `templates/mail/verify_email.html` | `templates/mail/verify_email.txt` |
//! | reset your password | `templates/mail/reset_password.html` | `templates/mail/reset_password.txt` |
//! | account already exists | `templates/mail/account_exists.html` | `templates/mail/account_exists.txt` |
//!
//! `layout.html` is the frame the HTML ones extend and `macros.html` holds the shared button. Templates are compiled into the binary (Askama):
//! a misspelled variable is a build error, not a blank in production, and `.html` files escape every
//! value for you (a user named `<b>x</b>` cannot inject markup). `.txt` files are not escaped.
//! This file only holds each email's subject and the variables its templates may use.
//! Subjects are matched by the flow tests (`tests/flows.rs`), so change them in both places.
use ryuk::mail::{Mail, MailError, Template};
use std::time::Duration;

/// "24 hours", "1 hour", "15 minutes": the lifetime a link is mailed with, from the same value the token uses.
pub fn human(d: Duration) -> String {
    let (n, unit) = match d.as_secs() {
        s if s >= 172_800 && s % 86_400 == 0 => (s / 86_400, "day"),
        s if s >= 3_600 && s % 3_600 == 0 => (s / 3_600, "hour"),
        s => ((s / 60).max(1), "minute"),
    };
    format!("{n} {unit}{}", if n == 1 { "" } else { "s" })
}

#[derive(Template)]
#[template(path = "mail/verify_email.html", askama = ryuk::mail::askama)]
struct VerifyEmailHtml<'a> {
    name: &'a str,
    link: &'a str,
    life: &'a str,
}

#[derive(Template)]
#[template(path = "mail/verify_email.txt", askama = ryuk::mail::askama)]
struct VerifyEmailText<'a> {
    name: &'a str,
    link: &'a str,
    life: &'a str,
}

/// Sent after registering; `ttl` is how long the link works (`VERIFY_TTL` in `controllers/auth.rs`).
/// `link` is the full `https://.../verify-email/<token>` URL.
pub fn verify_email(name: &str, to: &str, link: &str, ttl: Duration) -> Result<Mail, MailError> {
    let life = human(ttl);
    Mail::new()
        .to(to)
        .subject("Verify your email")
        .text_template(&VerifyEmailText { name, link, life: &life })?
        .html_template(&VerifyEmailHtml { name, link, life: &life })
}

#[derive(Template)]
#[template(path = "mail/reset_password.html", askama = ryuk::mail::askama)]
struct ResetPasswordHtml<'a> {
    name: &'a str,
    link: &'a str,
    life: &'a str,
}

#[derive(Template)]
#[template(path = "mail/reset_password.txt", askama = ryuk::mail::askama)]
struct ResetPasswordText<'a> {
    name: &'a str,
    link: &'a str,
    life: &'a str,
}

/// Sent by "forgot password"; `ttl` is `RESET_TTL` in `controllers/auth.rs` (the link is single use).
/// `link` is `https://.../reset-password/<token>`.
pub fn reset_password(name: &str, to: &str, link: &str, ttl: Duration) -> Result<Mail, MailError> {
    let life = human(ttl);
    Mail::new()
        .to(to)
        .subject("Reset your password")
        .text_template(&ResetPasswordText { name, link, life: &life })?
        .html_template(&ResetPasswordHtml { name, link, life: &life })
}

#[derive(Template)]
#[template(path = "mail/account_exists.html", askama = ryuk::mail::askama)]
struct AccountExistsHtml<'a> {
    name: &'a str,
    forgot_url: &'a str,
}

#[derive(Template)]
#[template(path = "mail/account_exists.txt", askama = ryuk::mail::askama)]
struct AccountExistsText<'a> {
    name: &'a str,
    forgot_url: &'a str,
}

/// Sent to an existing account when someone registers with its address (so registering never reveals
/// whether an email is taken). `forgot_url` is `https://.../forgot-password`.
pub fn account_exists(name: &str, to: &str, forgot_url: &str) -> Result<Mail, MailError> {
    Mail::new()
        .to(to)
        .subject("Someone tried to register with your email")
        .text_template(&AccountExistsText { name, forgot_url })?
        .html_template(&AccountExistsHtml { name, forgot_url })
}

#[cfg(test)]
mod tests {
    use super::*;

    const DAY: Duration = Duration::from_secs(24 * 3600);

    #[test]
    fn html_part_escapes_the_name_and_text_part_keeps_the_link() {
        let m = verify_email("<b>Ann</b> & \"co\"", "a@x.test", "https://x.test/verify-email/tok?a=1&b=2", DAY).unwrap();
        let html = m.html.unwrap();
        assert!(!html.contains("<b>Ann"), "{html}");
        assert!(html.contains("&#60;b&#62;Ann&#60;/b&#62; &#38; &#34;co&#34;"), "{html}");
        assert!(html.contains("href=\"https://x.test/verify-email/tok?a=1&#38;b=2\""), "{html}");
        assert!(html.contains(">Verify email</a>"), "{html}");
        let text = m.text.unwrap();
        assert!(text.contains("https://x.test/verify-email/tok?a=1&b=2"), "{text}");
        assert!(text.contains("<b>Ann</b> & \"co\""), "the text part is not HTML: nothing to escape");
        assert_eq!(m.subject, "Verify your email");
    }

    #[test]
    fn the_mailed_lifetime_follows_the_token_lifetime() {
        for (secs, text) in [(86_400, "24 hours"), (24 * 3600 * 2, "2 days"), (3 * 86_400, "3 days"), (3600, "1 hour"), (48 * 3600 + 3600, "49 hours"), (900, "15 minutes"), (60, "1 minute"), (30, "1 minute")] {
            assert_eq!(human(Duration::from_secs(secs)), text, "{secs}s");
        }
        let m = reset_password("A", "a@x.test", "https://x.test/r/t", Duration::from_secs(900)).unwrap();
        assert!(m.text.unwrap().contains("works for 15 minutes and only once"));
        assert!(m.html.unwrap().contains("works for 15 minutes and only once"));
    }

    #[test]
    fn subjects_match_the_flow_tests() {
        assert_eq!(reset_password("A", "a@x.test", "l", Duration::from_secs(60)).unwrap().subject, "Reset your password");
        assert_eq!(account_exists("A", "a@x.test", "l").unwrap().subject, "Someone tried to register with your email");
    }

    #[test]
    fn every_email_has_both_parts() {
        for m in [
            verify_email("A", "a@x.test", "https://x.test/l", DAY).unwrap(),
            reset_password("A", "a@x.test", "https://x.test/l", DAY).unwrap(),
            account_exists("A", "a@x.test", "https://x.test/f").unwrap(),
        ] {
            assert!(m.text.as_deref().is_some_and(|t| t.contains("https://x.test/")), "{}", m.subject);
            assert!(m.html.as_deref().is_some_and(|h| h.contains("href=\"https://x.test/")), "{}", m.subject);
        }
    }
}