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.
use app::{api, build, client_scopes_ok, fresh_allowed, migrations::Migrator, routes, seeders, worker};
use ryuk::{apikey::ApiKeys, app::Config, db, oauth_server::{ClientSpec, OAuthServer}, push::{Notification, Push}};
use sea_orm_migration::MigratorTrait;
use std::time::Duration;

/// All values of every occurrence of `name` (so `--scope a --scope b` and `--scope a b` both work).
fn flags(args: &[String], name: &str) -> Vec<String> {
    let mut out = vec![];
    let mut on = false;
    for a in args {
        if a.starts_with("--") {
            on = a == name;
        } else if on {
            out.push(a.clone());
        }
    }
    out
}

fn one(args: &[String], name: &str) -> std::io::Result<String> {
    flags(args, name)
        .into_iter()
        .next()
        .ok_or_else(|| std::io::Error::other(format!("missing {name} <value>")))
}

fn io(e: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> std::io::Error {
    std::io::Error::other(e)
}

fn refs(v: &[String]) -> Vec<&str> {
    v.iter().map(String::as_str).collect()
}

/// `oauth:client`, `apikey:*`, `push:test` and `device:list`: admin commands that need no running server.
async fn admin(cmd: &str, args: &[String], config: &Config) -> std::io::Result<()> {
    let db = db::connect(&config.database_url).await.map_err(io)?;
    match cmd {
        "push:test" | "device:list" => {
            let push = Push::from_env(db).await.map_err(io)?;
            push.devices().ensure_tables().await.map_err(io)?;
            let user = one(args, "--user")?.parse::<i64>().map_err(|_| io("--user must be a user id"))?;
            if cmd == "device:list" {
                // Tokens are never printed.
                for d in push.devices().list(user).await.map_err(io)? {
                    let state = if d.invalid_at.is_some() { "invalid" } else { "valid" };
                    println!("{:<6} {:<8} {:<8} {:<30} {}", d.id, d.platform.as_str(), state, d.app_id.unwrap_or_default(), d.name.unwrap_or_default());
                }
                return Ok(());
            }
            let mut n = Notification::new();
            if let Ok(t) = one(args, "--title") {
                n = n.title(t);
            }
            if let Ok(b) = one(args, "--body") {
                n = n.body(b);
            }
            for kv in flags(args, "--data") {
                let (k, v) = kv.split_once('=').ok_or_else(|| io("--data takes key=value"))?;
                n = n.data(k, v);
            }
            let r = push.send_to_user(user, &n).await.map_err(io)?;
            println!("sent: {}  failed: {}  invalidated: {}", r.sent, r.failed, r.invalidated);
            println!("(with the log driver, the default, nothing leaves this machine; set FCM_* / APNS_* to deliver)");
        }
        "oauth:client" => {
            let oauth = OAuthServer::new(db);
            oauth.ensure_tables().await.map_err(io)?;
            let (redirects, scopes) = (flags(args, "--redirect"), flags(args, "--scope"));
            let first_party = args.iter().any(|a| a == "--first-party");
            if first_party && redirects.is_empty() {
                return Err(io("--first-party needs at least one --redirect <uri> (e.g. https://app.example.com/cb)"));
            }
            client_scopes_ok(first_party, &scopes).map_err(io)?;
            let mut spec = ClientSpec::new(&one(args, "--name")?);
            for r in &redirects {
                spec = spec.redirect(r);
            }
            for sc in &scopes {
                spec = spec.scope(sc);
            }
            if !args.iter().any(|a| a == "--public") {
                spec = spec.confidential();
            }
            if first_party {
                spec = spec.first_party();
            }
            let c = oauth.create_client_spec(spec).await.map_err(io)?;
            println!("client_id:     {}", c.client_id);
            match c.client_secret {
                Some(s) => println!("client_secret: {s}\n(shown once; only its hash is stored)"),
                None => println!("public client: no secret (PKCE required)"),
            }
            if first_party {
                println!("first-party: logged-in users skip the consent screen ONLY for https redirect URIs (verified app links); a custom scheme like myapp:// always shows it, because any app on the device can claim the scheme. Use https app links for silent sign-in; prompt=consent forces the screen.");
            }
        }
        _ => {
            let keys = ApiKeys::new(db);
            keys.ensure_tables().await.map_err(io)?;
            let user = || one(args, "--user")?.parse::<i64>().map_err(|_| io("--user must be a user id"));
            match cmd {
                "apikey:create" => {
                    let owner = if args.iter().any(|a| a == "--system") { None } else { Some(user()?) };
                    let scopes = flags(args, "--scope");
                    let days = flags(args, "--expires-days").first().and_then(|d| d.parse::<u64>().ok());
                    let k = keys
                        .issue(owner, &one(args, "--name")?, &refs(&scopes), days.map(|d| Duration::from_secs(d * 86400)))
                        .await
                        .map_err(io)?;
                    println!("id:  {}\nkey: {}\n(shown once; only its hash is stored)", k.id, k.plaintext);
                }
                "apikey:list" => {
                    for k in keys.list(user()?).await.map_err(io)? {
                        let state = if k.revoked_at.is_some() { "revoked" } else { "active" };
                        println!("{:<6} {:<8} ryk_{}_...  {:<24} {}", k.id, state, k.prefix, k.scopes.join(","), k.name);
                    }
                }
                _ => {
                    // `apikey:revoke --user 1 5` or `apikey:revoke 5 --user 1`
                    let id = flags(args, "--user").get(1).or(args.first().filter(|a| !a.starts_with("--")))
                        .and_then(|s| s.parse::<i64>().ok())
                        .ok_or_else(|| io("usage: apikey:revoke --user <id> <key_id>"))?;
                    let done = keys.revoke(user()?, id).await.map_err(io)?;
                    println!("{}", if done { "revoked" } else { "no such active key for that user" });
                }
            }
        }
    }
    Ok(())
}

// Doubles as the artisan-style entry point: `ryuk migrate` runs `cargo run -- migrate`.
#[tokio::main]
async fn main() -> std::io::Result<()> {
    let config = Config::from_env();
    let args: Vec<String> = std::env::args().skip(1).collect();
    let cmd = args.first().cloned().unwrap_or_default();


    if cmd == "routes" {
        // The api group is mounted under /api (its handlers declare short paths).
        let groups = [("", routes::router()), ("/api", api::router())];
        for (prefix, router) in groups {
            let (_, spec) = router.split_for_parts();
            for (path, item) in spec.paths.paths.iter() {
                let methods = [
                    ("GET", item.get.is_some()),
                    ("POST", item.post.is_some()),
                    ("PUT", item.put.is_some()),
                    ("PATCH", item.patch.is_some()),
                    ("DELETE", item.delete.is_some()),
                ];
                let m: Vec<_> = methods.iter().filter(|(_, on)| *on).map(|(n, _)| *n).collect();
                println!("{:<24} {prefix}{path}", m.join("|"));
            }
        }
        return Ok(());
    }

    match cmd.as_str() {
        "db:seed" => {
            let db = db::connect(&config.database_url).await.map_err(io)?;
            seeders::run(&db).await.map_err(io)
        }
        "queue:work" => {
            // `serve` installs the log subscriber; a worker does not serve, and without this its failures are silent.
            ryuk::app::init_tracing();
            worker(&config).await?.work().await;
            Ok(())
        }
        "oauth:client" | "apikey:create" | "apikey:list" | "apikey:revoke" | "push:test" | "device:list" => admin(&cmd, &args[1..], &config).await,
        "migrate" | "migrate:rollback" | "migrate:fresh" => {
            let db = db::connect(&config.database_url).await.map_err(io)?;
            match cmd.as_str() {
                "migrate" => Migrator::up(&db, None).await.map_err(io)?,
                "migrate:rollback" => Migrator::down(&db, Some(1)).await.map_err(io)?,
                _ => {
                    fresh_allowed(&config.app_env, args.iter().any(|a| a == "--force")).map_err(io)?;
                    Migrator::fresh(&db).await.map_err(io)?
                }
            }
            // A silent success is indistinguishable from a command that did nothing.
            println!("{cmd}: done");
            Ok(())
        }
        _ => build(&config).await?.serve(&config).await,
    }
}