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.
//! Passkey registration (settings, authenticated) and discoverable sign-in (login, public).
//!
//! These four endpoints return raw JSON (the client JS drives `navigator.credentials.create()` /
//! `.get()` and posts the result back), unlike the rest of this file's siblings which render
//! Inertia pages. They still go through the normal web router, so they get the same session and
//! CSRF protection as every other state-changing route.
//!
//! The ceremony state (`PasskeyRegistration` / `DiscoverableAuthentication`) is stashed in the
//! session and removed on first read, mirroring `social.rs`'s OAuth `state`: a replayed `*-finish`
//! call always finds nothing, before any cryptographic check even runs.
use super::AppError;
use crate::{AppState, models::user};
use axum::{
    Json, Router,
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
};
use ryuk::{
    auth::{self, Auth},
    inertia,
    passkey::{
        DiscoverableAuthentication, PasskeyRegistration, PublicKeyCredential,
        RegisterPublicKeyCredential,
    },
    proxy::ClientIp,
    session::Session,
    throttle::Throttle,
};
use sea_orm::EntityTrait;
use serde::Deserialize;
use serde_json::json;
use std::net::IpAddr;

const REG_KEY: &str = "passkey_reg";
const AUTH_KEY: &str = "passkey_auth";
const SECURITY_PAGE: &str = "/settings/security";

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/settings/passkeys/register-start", post(register_start))
        .route("/settings/passkeys/register-finish", post(register_finish))
        .route("/settings/security/passkeys/{id}/revoke", post(revoke))
        .route("/login/passkey-start", post(login_start))
        .route("/login/passkey-finish", post(login_finish))
}

fn error(status: StatusCode, msg: &str) -> Response {
    (status, Json(json!({ "message": msg }))).into_response()
}

fn bad(msg: &str) -> Response {
    error(StatusCode::BAD_REQUEST, msg)
}

fn locked(l: ryuk::throttle::Locked) -> Response {
    error(
        StatusCode::TOO_MANY_REQUESTS,
        &format!(
            "Too many attempts. Try again in {} seconds.",
            l.retry_after.as_secs()
        ),
    )
}

/// Per user+IP (5/15 min, the same budget `account::confirm_password` uses), behind the broader
/// per-IP gate: an authenticated ceremony is still new attack surface and must not be exempt from
/// the throttle story the rest of auth already has. `Some(_)` means "stop and answer this instead".
async fn registration_gate(s: &AppState, uid: i64, ip: Option<IpAddr>) -> Option<Response> {
    let key = Throttle::key(&format!("passkey-reg:{uid}"), ip);
    let gate = match super::auth::ip_gate(s, "passkey-reg", ip).await {
        Ok(()) => s.throttle.attempt(&key).await,
        Err(l) => Err(l),
    };
    gate.err().map(locked)
}

/// Only a per-IP gate (50/15 min): unlike password login there is no email to key a second,
/// tighter lock on until AFTER the ceremony resolves who is signing in.
/// shortcut: no per-identity throttle on login; raise `ip_throttle`'s limit if that proves too loose.
async fn login_gate(s: &AppState, ip: Option<IpAddr>) -> Option<Response> {
    super::auth::ip_gate(s, "passkey-login", ip)
        .await
        .err()
        .map(locked)
}

pub async fn register_start(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    Auth(uid): Auth,
    session: Session,
) -> Result<Response, AppError> {
    if let Some(resp) = registration_gate(&s, uid, ip).await {
        return Ok(resp);
    }
    let Some(u) = user::Entity::find_by_id(uid).one(&s.db).await? else {
        return Ok(bad("Account not found."));
    };
    let exclude = s.passkeys.credential_ids(uid).await?;
    let (challenge, reg_state) = match s
        .passkeys
        .start_registration(uid, &u.email, &u.name, &exclude)
    {
        Ok(v) => v,
        Err(_) => return Ok(bad("Passkey registration is unavailable.")),
    };
    if session.insert(REG_KEY, &reg_state).await.is_err() {
        tracing::error!("passkey: registration session write failed");
        return Ok(bad("Passkey registration is unavailable."));
    }
    Ok(Json(challenge).into_response())
}

#[derive(Deserialize)]
pub struct RegisterFinish {
    name: String,
    credential: RegisterPublicKeyCredential,
}

pub async fn register_finish(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    Auth(uid): Auth,
    session: Session,
    Json(body): Json<RegisterFinish>,
) -> Result<Response, AppError> {
    if let Some(resp) = registration_gate(&s, uid, ip).await {
        return Ok(resp);
    }
    // Consumed before verification: a replayed finish always finds nothing.
    let Some(reg_state) = session
        .remove::<PasskeyRegistration>(REG_KEY)
        .await
        .ok()
        .flatten()
    else {
        return Ok(bad(
            "The registration attempt expired or was already used; please try again.",
        ));
    };
    let name = body.name.trim();
    let name = if name.is_empty() { "Passkey" } else { name };
    match s
        .passkeys
        .finish_registration(uid, name, &reg_state, &body.credential)
        .await
    {
        Ok(()) => {
            s.throttle
                .clear(&Throttle::key(&format!("passkey-reg:{uid}"), ip))
                .await?;
            Ok(Json(json!({ "ok": true })).into_response())
        }
        Err(_) => Ok(bad("The passkey could not be verified.")),
    }
}

pub async fn revoke(
    State(s): State<AppState>,
    Auth(uid): Auth,
    Path(id): Path<i64>,
    session: Session,
) -> Result<Response, AppError> {
    if s.passkeys.delete(uid, id).await? {
        inertia::flash(&session, "success", "Passkey removed.").await;
    } else {
        inertia::flash(&session, "error", "Passkey not found.").await;
    }
    Ok(inertia::redirect(SECURITY_PAGE))
}

pub async fn login_start(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    session: Session,
) -> Result<Response, AppError> {
    if let Some(resp) = login_gate(&s, ip).await {
        return Ok(resp);
    }
    let (challenge, auth_state) = match s.passkeys.start_discoverable_authentication() {
        Ok(v) => v,
        Err(_) => return Ok(bad("Passkey sign-in is unavailable.")),
    };
    if session.insert(AUTH_KEY, &auth_state).await.is_err() {
        tracing::error!("passkey: login session write failed");
        return Ok(bad("Passkey sign-in is unavailable."));
    }
    Ok(Json(challenge).into_response())
}

pub async fn login_finish(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    session: Session,
    Json(response): Json<PublicKeyCredential>,
) -> Result<Response, AppError> {
    if let Some(resp) = login_gate(&s, ip).await {
        return Ok(resp);
    }
    // Consumed before verification: a replayed finish always finds nothing.
    let Some(auth_state) = session
        .remove::<DiscoverableAuthentication>(AUTH_KEY)
        .await
        .ok()
        .flatten()
    else {
        return Ok(bad(
            "The sign-in attempt expired or was already used; please try again.",
        ));
    };
    let owner_id = match s
        .passkeys
        .finish_discoverable_authentication(&auth_state, &response)
        .await
    {
        Ok(id) => id,
        Err(_) => return Ok(bad("The passkey could not be verified.")),
    };
    // Same session-establishment path password login uses (cycles the session id, mints a fresh
    // CSRF token): a passkey login is indistinguishable from a password one afterward.
    auth::login(&session, owner_id).await?;
    inertia::flash(&session, "success", "Welcome back!").await;
    Ok(Json(json!({ "redirect": "/dashboard" })).into_response())
}