ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
pub mod account;
pub mod api;
pub mod controllers;
pub mod events;
pub mod jobs;
pub mod mails;
pub mod mcp;
pub mod middleware;
pub mod migrations;
pub mod models;
pub mod notifications;
pub mod policies;
pub mod routes;
pub mod seeders;

use axum::extract::FromRef;
use migrations::Migrator;
use ryuk::{
    api::DbRateLimit,
    apikey::ApiKeys,
    app::{App, Config},
    db,
    inertia::{self, InertiaConfig},
    mail::Mailer,
    oauth_server::OAuthServer,
    passkey::{Passkeys, webauthn_from_env},
    push::Push,
    session::DbStore,
    tenancy::Tenancy,
    throttle::Throttle,
    tokens::Tokens,
};
use sea_orm::DatabaseConnection;
use sea_orm_migration::MigratorTrait;
use std::sync::Arc;
use std::time::Duration;

/// Shared application state.
#[derive(Clone)]
pub struct AppState {
    pub db: DatabaseConnection,
    pub inertia: InertiaConfig,
    pub mailer: Mailer,
    /// Per email+IP (5 per 15 min): login, re-checks of the password, forgot, resend, register.
    pub throttle: Throttle,
    /// Per IP only, a higher limit (50 per 15 min): login, register and forgot with many different emails.
    pub ip_throttle: Throttle,
    /// Per email only (10 per 15 min): mail-sending flows, so a victim's inbox cannot be flooded from many IPs.
    pub mail_throttle: Throttle,
    pub tokens: Tokens,
    pub api_keys: ApiKeys,
    pub oauth: OAuthServer,
    pub passkeys: Passkeys,
    pub tenancy: Tenancy,
    pub push: Push,
    /// The store passed to `App::sessions`: lets "log out everywhere" and account deletion end sessions.
    pub session_store: DbStore,
    pub ops: Ops,
}

/// Deployment settings read from the environment (see `.env.example`). `Ops::from_lookup` is pure, for tests.
#[derive(Clone, Debug)]
pub struct Ops {
    pub min_app_version_ios: Option<String>,
    pub min_app_version_android: Option<String>,
    /// `API_RATE_LIMIT=memory` counts per process; the default `db` is shared by all instances.
    pub rate_limit_memory: bool,
    pub rate_limit_max: u32,
    pub rate_limit_window_secs: u64,
    /// `APPLE_APP_ID` (`TEAMID.bundle.id`) and `APPLE_APP_PATHS` (comma separated, default `*`).
    pub apple_app_id: Option<String>,
    pub apple_app_paths: Vec<String>,
    pub android_package: Option<String>,
    pub android_cert_fingerprints: Vec<String>,
}

impl Ops {
    pub fn from_env() -> Self {
        Self::from_lookup(|k| std::env::var(k).ok())
    }

    pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Self {
        let text = |k: &str| get(k).map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
        let list = |k: &str| -> Vec<String> {
            text(k).map(|v| v.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect()).unwrap_or_default()
        };
        let num = |k: &str| text(k).and_then(|v| v.parse::<u64>().ok()).filter(|n| *n > 0);
        Ops {
            min_app_version_ios: text("MIN_APP_VERSION_IOS"),
            min_app_version_android: text("MIN_APP_VERSION_ANDROID"),
            rate_limit_memory: text("API_RATE_LIMIT").is_some_and(|v| v.eq_ignore_ascii_case("memory")),
            rate_limit_max: num("API_RATE_LIMIT_MAX").map_or(120, |n| n.min(u32::MAX as u64) as u32),
            rate_limit_window_secs: num("API_RATE_LIMIT_WINDOW_SECS").unwrap_or(60),
            apple_app_id: text("APPLE_APP_ID"),
            apple_app_paths: Some(list("APPLE_APP_PATHS")).filter(|p| !p.is_empty()).unwrap_or_else(|| vec!["*".into()]),
            android_package: text("ANDROID_PACKAGE"),
            android_cert_fingerprints: list("ANDROID_SHA256_CERT_FINGERPRINTS"),
        }
    }
}

impl Default for Ops {
    fn default() -> Self {
        Self::from_lookup(|_| None)
    }
}

impl FromRef<AppState> for InertiaConfig {
    fn from_ref(s: &AppState) -> Self {
        s.inertia.clone()
    }
}

impl FromRef<AppState> for Tenancy {
    fn from_ref(s: &AppState) -> Self {
        s.tenancy.clone()
    }
}

impl FromRef<AppState> for OAuthServer {
    fn from_ref(s: &AppState) -> Self {
        s.oauth.clone()
    }
}

/// Applies the user's saved theme before first paint (same key as `client/src/theme.js`), so there is no flash.
const THEME_SCRIPT: &str = r#"<script>try{var t=localStorage.getItem("ryuk-theme");if(t==="light"||t==="dark")document.documentElement.dataset.theme=t}catch(e){}</script>"#;

fn io(e: impl std::error::Error + Send + Sync + 'static) -> std::io::Error {
    std::io::Error::other(e)
}

/// Everything except binding the socket: connect, migrate, build state and routes.
/// `main` serves it; `tests/flows.rs` calls `.into_router()` on it.
pub async fn build(config: &Config) -> std::io::Result<App<AppState>> {
    build_with(config, Ops::from_env()).await
}

/// [`build`] with explicit deployment settings (tests use this instead of mutating the environment).
pub async fn build_with(config: &Config, ops: Ops) -> std::io::Result<App<AppState>> {
    Ok(routes_for(state(config, ops).await?))
}

/// Connect, migrate and create every table; no routes. Admin commands and tests use the state directly.
pub async fn state(config: &Config, ops: Ops) -> std::io::Result<AppState> {
    let db = db::connect(&config.database_url).await.map_err(io)?;
    // AUTO_MIGRATE=false: several replicas must not race, run `<name> migrate` once per release instead.
    if std::env::var("AUTO_MIGRATE").map(|v| v != "false" && v != "0").unwrap_or(true) {
        Migrator::up(&db, None).await.map_err(io)?;
    }
    mail_guard(&config.app_env, std::env::var("MAIL_DRIVER").ok().as_deref(), std::env::var("ALLOW_LOG_MAIL").ok().as_deref()).map_err(std::io::Error::other)?;
    let (throttle, tokens) = (Throttle::new(db.clone()), Tokens::new(db.clone()));
    let (ip_throttle, mail_throttle) = (throttle.clone().max_attempts(50), throttle.clone().max_attempts(10));
    throttle.ensure_tables().await.map_err(io)?;
    tokens.ensure_tables().await.map_err(io)?;
    let (api_keys, oauth) = (ApiKeys::new(db.clone()), OAuthServer::new(db.clone()));
    api_keys.ensure_tables().await.map_err(io)?;
    oauth.ensure_tables().await.map_err(io)?;
    // WebAuthn needs a real domain (not a bare IP) as the relying party id: point a browser at
    // `localhost`, not `127.0.0.1`, to use passkeys in local dev (see `webauthn_from_env`'s docs).
    let passkeys = Passkeys::new(db.clone(), Arc::new(webauthn_from_env().map_err(std::io::Error::other)?));
    passkeys.ensure_tables().await.map_err(io)?;
    let tenancy = Tenancy::new(db.clone());
    tenancy.ensure_tables().await.map_err(io)?;
    // The web process dispatches jobs too, so it needs the tables before a worker ever ran.
    ryuk::queue::Queue::new(db.clone()).ensure_tables().await.map_err(io)?;

    // Durable sessions in the app database (works on sqlite, postgres and mysql).
    let store = DbStore::new(db.clone());
    store.ensure_table().await.map_err(io)?;
    DbRateLimit::new(db.clone()).ensure_tables().await.map_err(io)?;
    let push = Push::from_env(db.clone()).await.map_err(io)?;
    push.devices().ensure_tables().await.map_err(io)?;
    // Other stores (enable the matching ryuk feature, then pass it to `.sessions(...)`):
    //   file:  ryuk::session::file::FileSessionStorage::new_in_folder(Path::new("storage/sessions"))   // feature "session-file"
    //   redis: ryuk::session::redis::RedisStore::new(fred_pool)                          // feature "session-redis"
    //   moka:  ryuk::session::moka::MokaStore::new(Some(10_000))                          // feature "session-moka"
    //   none:  in-memory default (lost on restart), just omit `.sessions(...)`

    let state = AppState {
        inertia: inertia::with_head(inertia::Config::from_env("{{name}}"), THEME_SCRIPT),
        mailer: Mailer::from_env().map_err(io)?,
        db: db.clone(),
        throttle,
        ip_throttle,
        mail_throttle,
        tokens,
        api_keys,
        oauth,
        passkeys,
        tenancy,
        push,
        session_store: store.clone(),
        ops,
    };
    // Housekeeping hourly (the web process only; run several instances and they just overlap harmlessly).
    let s2 = state.clone();
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(Duration::from_secs(3600)).await;
            prune(&s2).await;
        }
    });
    Ok(state)
}

/// Production must not "send" mail to the console (reset and verify links would sit in the logs and nobody
/// would get them). `ALLOW_LOG_MAIL=true` is the explicit opt-out. Pure, so a test can cover it.
pub fn mail_guard(app_env: &str, mail_driver: Option<&str>, allow_log_mail: Option<&str>) -> Result<(), String> {
    let log_driver = mail_driver.map(str::trim).is_none_or(|d| d.is_empty() || d.eq_ignore_ascii_case("log"));
    if ryuk::security::is_production_env(app_env) && log_driver && allow_log_mail.map(str::trim) != Some("true") {
        return Err("APP_ENV=production with the log mail driver: set MAIL_DRIVER=smtp (and MAIL_HOST...), or ALLOW_LOG_MAIL=true to accept that mails (links included) only go to the log".into());
    }
    Ok(())
}

/// `ryuk oauth:client` rule: only a first-party client may be granted `account` (it can delete the account).
pub fn client_scopes_ok(first_party: bool, scopes: &[String]) -> Result<(), String> {
    if !first_party && scopes.iter().any(|s| s == "account") {
        return Err("--scope account is only for --first-party clients (it allows deleting the account)".into());
    }
    Ok(())
}

/// `migrate:fresh` drops every table: refuse in production unless `--force`.
pub fn fresh_allowed(app_env: &str, force: bool) -> Result<(), String> {
    if ryuk::security::is_production_env(app_env) && !force {
        return Err("migrate:fresh drops every table; refusing with APP_ENV=production (pass --force to do it anyway)".into());
    }
    Ok(())
}

const DAY: Duration = Duration::from_secs(86_400);

/// The hourly maintenance task: delete expired sessions, tokens, keys, grants, throttle rows, dead
/// devices and finished rate-limit windows. Logs the counts at info; a failing step is logged and skipped.
/// Returns `(what, rows)` per step.
pub async fn prune(s: &AppState) -> Vec<(&'static str, u64)> {
    fn count<E: std::fmt::Display>(what: &'static str, r: Result<u64, E>) -> (&'static str, u64) {
        (what, r.unwrap_or_else(|e| {
            tracing::warn!(task = what, error = %e, "prune failed");
            0
        }))
    }
    let oauth = s.oauth.prune(30 * DAY).await.map(|r| r.codes + r.tokens);
    let rows = vec![
        count("sessions", s.session_store.delete_expired().await),
        count("one_time_tokens", s.tokens.prune().await),
        count("throttle", s.throttle.prune().await),
        count("oauth", oauth),
        count("api_keys", s.api_keys.prune(30 * DAY).await),
        count("push_devices", s.push.devices().prune(30 * DAY, 270 * DAY).await),
        count("api_rate_limits", DbRateLimit::new(s.db.clone()).prune().await),
        count("org_invites", s.tenancy.prune_invites().await),
    ];
    tracing::info!(pruned = ?rows, "maintenance");
    rows
}

fn routes_for(state: AppState) -> App<AppState> {
    let (db, store, ops) = (state.db.clone(), state.session_store.clone(), state.ops.clone());
    let (api_keys, oauth) = (state.api_keys.clone(), state.oauth.clone());
    // CSRF is on by default; exempt webhooks with `.csrf_except(&["/webhooks/*"])`.
    // Behind a reverse proxy set TRUSTED_PROXIES so ClientIp (throttling) sees the real client.
    let app_url = std::env::var("APP_URL").unwrap_or_else(|_| "http://localhost:3000".into());
    let mut app = App::new(state)
        .title("{{name}}")
        .version(env!("CARGO_PKG_VERSION"))
        .sessions(store)
        .database(&db)
        // Browser pages: session, CSRF, Inertia (src/routes.rs).
        .web(routes::router())
        // Machine API under /api: no session, no CSRF, API key or OAuth token (src/api.rs).
        .api(api::router())
        .api_verifier(api_keys)
        .api_verifier(oauth)
        // OAuth server: /oauth/token, /oauth/revoke, /oauth/introspect (stateless) and the consent screen (browser).
        .public(OAuthServer::token_routes())
        .web(OAuthServer::web_routes())
        // Universal links / app links files: plain public routes, no cookie, no CSRF.
        .public(controllers::well_known::router())
        // "Sign in with GitHub / Google" (set GITHUB_CLIENT_ID/SECRET, GOOGLE_CLIENT_ID/SECRET).
        .routes(controllers::social::social().routes(controllers::social::AppUsers::new(db.clone())))
        // Passkey registration (settings) and discoverable sign-in (login): src/controllers/passkeys.rs.
        .routes(controllers::passkeys::router())
        .oauth2_scheme(
            &format!("{app_url}/oauth/authorize"),
            &format!("{app_url}/oauth/token"),
            &[
                ("profile", "Read your name and email"),
                ("posts:read", "Read your posts"),
                ("posts:write", "Create, edit and delete your posts"),
                ("devices", "Register and remove push notification devices"),
                ("account", "Manage sessions and authorized apps, and delete the account"),
            ],
        )
        .api_rate_limit(ops.rate_limit_max, Duration::from_secs(ops.rate_limit_window_secs));
    if !ops.rate_limit_memory {
        app = app.api_rate_limit_store(DbRateLimit::new(db));
    }
    // Force-upgrade gate: an old `X-App-Version` on /api answers 426.
    for (platform, min) in [("ios", &ops.min_app_version_ios), ("android", &ops.min_app_version_android)] {
        if let Some(min) = min {
            app = app.min_app_version(platform, min);
        }
    }
    // Cross-origin browser access to /api is off. To allow a front end on another origin, add:
    //   .cors(ryuk::api::Cors::allow_origins(&["https://app.example.com"]))
    app
}

/// The queue worker's setup: connect and create the jobs tables if missing, so a fresh database works.
/// Register jobs on the returned queue: `queue.register::<jobs::MyJob>()`.
pub async fn worker(config: &Config) -> std::io::Result<ryuk::queue::Queue> {
    let queue = ryuk::queue::Queue::new(db::connect(&config.database_url).await.map_err(io)?);
    queue.ensure_tables().await.map_err(io)?;
    Ok(queue.register::<jobs::send_push::SendPush>())
}

#[cfg(test)]
mod tests {
    use super::{Ops, client_scopes_ok, fresh_allowed, mail_guard};

    fn ops(pairs: &[(&str, &str)]) -> Ops {
        Ops::from_lookup(|k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()))
    }

    #[test]
    fn ops_defaults_and_parsing() {
        let d = ops(&[]);
        assert_eq!((d.rate_limit_memory, d.rate_limit_max, d.rate_limit_window_secs), (false, 120, 60));
        assert_eq!((d.min_app_version_ios, d.apple_app_id, d.apple_app_paths), (None, None, vec!["*".to_string()]));
        let o = ops(&[("API_RATE_LIMIT", "Memory"), ("API_RATE_LIMIT_MAX", "5"), ("API_RATE_LIMIT_WINDOW_SECS", "0"), ("MIN_APP_VERSION_IOS", " 1.2 "), ("MIN_APP_VERSION_ANDROID", "")]);
        assert_eq!((o.rate_limit_memory, o.rate_limit_max, o.rate_limit_window_secs), (true, 5, 60), "zero or junk falls back");
        assert_eq!((o.min_app_version_ios.as_deref(), o.min_app_version_android), (Some("1.2"), None));
    }

    #[test]
    fn production_refuses_the_log_mail_driver() {
        for driver in [None, Some(""), Some("log"), Some("LOG")] {
            assert!(mail_guard("production", driver, None).is_err(), "{driver:?}");
            assert!(mail_guard("production", driver, Some("false")).is_err());
            assert!(mail_guard("production", driver, Some("true")).is_ok(), "explicit opt-out");
            assert!(mail_guard("local", driver, None).is_ok());
        }
        assert!(mail_guard("production", Some("smtp"), None).is_ok());
        // A typo or another casing is still production, never a silent development mode.
        for env in ["Production", " production ", "prod", "PRODUCTION"] {
            assert!(mail_guard(env, None, None).is_err(), "{env:?}");
            assert!(fresh_allowed(env, false).is_err(), "{env:?}");
        }
    }

    #[test]
    fn cli_guards() {
        let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
        assert!(client_scopes_ok(false, &s(&["profile", "account"])).is_err());
        assert!(client_scopes_ok(true, &s(&["account"])).is_ok() && client_scopes_ok(false, &s(&["profile"])).is_ok());
        assert!(fresh_allowed("production", false).is_err());
        assert!(fresh_allowed("production", true).is_ok() && fresh_allowed("local", false).is_ok());
    }
}