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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use super::AppError;
use crate::{
    AppState,
    models::{post, user},
};
use axum::{
    extract::{Path, Query, State},
    http::HeaderMap,
    response::Response,
};
use ryuk::{
    auth::{self, Auth, OptionalAuth},
    inertia::{self, Inertia},
    mail::{Mail, MailError},
    proxy::ClientIp,
    throttle::Throttle,
    tokens::{RESET_PASSWORD, VERIFY_EMAIL},
    validation::Form,
};
use sea_orm::{ActiveModelTrait, ActiveValue::{Set, Unchanged}, ColumnTrait, EntityTrait, QueryFilter};
use serde::Deserialize;
use serde_json::json;
use std::{collections::BTreeMap, net::IpAddr, time::Duration};
use ryuk::session::Session;
use utoipa::ToSchema;
use validator::Validate;

#[derive(Deserialize, Validate, ToSchema)]
pub struct RegisterForm {
    #[validate(length(min = 1, message = "Name is required"))]
    name: String,
    #[validate(email(message = "Enter a valid email"))]
    email: String,
    #[validate(length(min = 8, message = "Password must be at least 8 characters"))]
    password: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct LoginForm {
    #[validate(email(message = "Enter a valid email"))]
    email: String,
    #[validate(length(min = 1, message = "Password is required"))]
    password: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct ForgotForm {
    #[validate(email(message = "Enter a valid email"))]
    email: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct ResendForm {
    #[validate(email(message = "Enter a valid email"))]
    email: String,
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct ResetForm {
    token: String,
    #[validate(length(min = 8, message = "Password must be at least 8 characters"))]
    #[validate(must_match(other = "password_confirmation", message = "Passwords do not match"))]
    password: String,
    password_confirmation: String,
}

fn field_error(field: &str, msg: &str) -> BTreeMap<String, String> {
    BTreeMap::from([(field.to_string(), msg.to_string())])
}

/// The login error for an unverified account. The extra `unverified` key is what the Login page keys the
/// "resend" button on, so rewording the message cannot silently remove the button.
fn unverified_error() -> BTreeMap<String, String> {
    BTreeMap::from([
        ("email".to_string(), "Verify your email first.".to_string()),
        ("unverified".to_string(), "true".to_string()),
    ])
}

/// How long an emailed link works. The emails state these lifetimes themselves (from these values),
/// so changing a constant is the only edit needed.
const VERIFY_TTL: Duration = Duration::from_secs(24 * 3600);
const RESET_TTL: Duration = Duration::from_secs(3600);

fn app_url() -> String {
    std::env::var("APP_URL").unwrap_or_else(|_| "http://127.0.0.1:3000".into()).trim_end_matches('/').to_string()
}

/// Per-IP gate (a higher limit than the per-email one): one client cannot grind through many emails.
/// No client address (no ConnectInfo) means no IP gate. Successes are not cleared: signing in elsewhere
/// must not reset the counter. shortcut: clients behind one NAT share the 50 per 15 min, raise `ip_throttle` if needed.
pub(crate) async fn ip_gate(s: &AppState, flow: &str, ip: Option<IpAddr>) -> Result<(), ryuk::throttle::Locked> {
    match ip {
        Some(ip) => s.ip_throttle.attempt(&Throttle::key(&format!("{flow}-ip"), Some(ip))).await,
        None => Ok(()),
    }
}

/// Per-email gate for flows that send mail: stops flooding one victim's inbox from many IPs.
async fn mail_gate(s: &AppState, flow: &str, email: &str) -> bool {
    s.mail_throttle.attempt(&Throttle::key(&format!("{flow}:{email}"), None)).await.is_ok()
}

/// Issue a token and mail the link. Mail failures are logged, not shown (no delivery oracle).
/// `build(name, email, link)` is one of the functions in `src/mails/auth.rs`: that file owns the wording.
async fn mail_link(s: &AppState, u: &user::Model, purpose: &str, ttl: Duration, path: &str, build: fn(&str, &str, &str, Duration) -> Result<Mail, MailError>) -> Result<(), AppError> {
    let token = s.tokens.issue(u.id, purpose, ttl).await?;
    let link = format!("{}/{path}/{token}", app_url());
    let mail = build(&u.name, &u.email, &link, ttl)?;
    if std::env::var("APP_ENV").as_deref() != Ok("production") {
        // The log mail driver quoted-printable wraps long lines, so print the link intact for development.
        tracing::info!("{}: {link}", mail.subject);
    }
    if let Err(e) = s.mailer.send(mail).await {
        tracing::error!("mail to user {}: {e}", u.id);
    }
    Ok(())
}

async fn send_verification(s: &AppState, u: &user::Model) -> Result<(), AppError> {
    mail_link(s, u, VERIFY_EMAIL, VERIFY_TTL, "verify-email", crate::mails::auth::verify_email).await
}

#[utoipa::path(get, path = "/", responses((status = 200, description = "Welcome page")))]
pub async fn welcome(inertia: Inertia, OptionalAuth(uid): OptionalAuth) -> Response {
    inertia.render("Welcome", json!({ "authenticated": uid.is_some() }))
}

#[utoipa::path(get, path = "/login", responses((status = 200, description = "Login page")))]
pub async fn show_login(inertia: Inertia, Query(q): Query<LoginQuery>, session: Session) -> Response {
    // Remember where to go after login (the OAuth server sends logged-out users here with ?next=).
    if let Some(n) = q.next.as_deref().and_then(safe_next) {
        let _ = session.insert("login_next", n).await;
    }
    inertia.render("Auth/Login", json!({ "social": super::social::enabled(&super::social::social()) }))
}

#[derive(Deserialize)]
pub struct LoginQuery {
    next: Option<String>,
}

/// Where to go after login: a local path only. `//host`, `https://..`, backslashes and control
/// characters are dropped so `?next=` can never become an open redirect.
fn safe_next(next: &str) -> Option<String> {
    let ok = next.starts_with('/')
        && !next.starts_with("//")
        && !next.contains('\\')
        && !next.chars().any(char::is_control)
        && next.len() <= 2048;
    ok.then(|| next.to_string())
}

#[utoipa::path(post, path = "/login", request_body = LoginForm,
    responses((status = 303, description = "Redirect to dashboard or back to login")))]
pub async fn login(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    session: Session,
    Form(f): Form<LoginForm>,
) -> Result<Response, AppError> {
    let key = Throttle::key(&f.email, ip);
    // `attempt` counts first and compares after, so parallel guesses cannot overshoot the limit.
    let gate = match ip_gate(&s, "login", ip).await {
        Ok(()) => s.throttle.attempt(&key).await,
        locked => locked,
    };
    if let Err(locked) = gate {
        let msg = format!("Too many attempts. Try again in {} seconds.", locked.retry_after.as_secs());
        inertia::flash_errors(&session, field_error("email", &msg)).await;
        return Ok(inertia::redirect("/login"));
    }
    let found = user::Entity::find()
        .filter(user::Column::Email.eq(f.email.as_str()))
        .one(&s.db)
        .await?;
    // Unknown emails still pay for one argon2 verification so timing does not reveal them.
    let ok = match &found {
        Some(u) => auth::verify_password_async(f.password.clone(), u.password.clone()).await,
        None => {
            auth::verify_password_async(f.password.clone(), crate::account::dummy_hash().await).await;
            false
        }
    };
    match found {
        Some(u) if ok && u.email_verified_at.is_none() => {
            // Password is correct, so naming the problem leaks nothing; the client offers a resend.
            s.throttle.clear(&key).await?;
            inertia::flash_errors(&session, unverified_error()).await;
            Ok(inertia::redirect("/login"))
        }
        Some(u) if ok => {
            s.throttle.clear(&key).await?;
            auth::login(&session, u.id).await?;
            inertia::flash(&session, "success", "Welcome back!").await;
            let next = session.remove::<String>("login_next").await.ok().flatten();
            Ok(inertia::redirect(&next.as_deref().and_then(safe_next).unwrap_or_else(|| "/dashboard".into())))
        }
        _ => {
            let msg = "These credentials do not match our records.";
            inertia::flash_errors(&session, field_error("email", msg)).await;
            Ok(inertia::redirect("/login"))
        }
    }
}

#[utoipa::path(get, path = "/register", responses((status = 200, description = "Register page")))]
pub async fn show_register(inertia: Inertia) -> Response {
    inertia.render("Auth/Register", json!({ "social": super::social::enabled(&super::social::social()) }))
}

#[utoipa::path(post, path = "/register", request_body = RegisterForm,
    responses((status = 303, description = "Always the same redirect to /login, whether or not the email exists")))]
pub async fn register(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    session: Session,
    Form(f): Form<RegisterForm>,
) -> Result<Response, AppError> {
    // Throttled per IP and per email+IP; when locked we silently skip so the response never differs.
    let key = Throttle::key(&format!("register:{}", f.email), ip);
    if ip_gate(&s, "register", ip).await.is_err() || s.throttle.attempt(&key).await.is_err() {
        inertia::flash(&session, "success", "Check your email to finish creating your account.").await;
        return Ok(inertia::redirect("/login"));
    }
    // Hash in both cases so timing does not reveal whether the email exists.
    let hash = auth::hash_password_async(f.password.clone()).await?;
    let taken = user::Entity::find().filter(user::Column::Email.eq(f.email.as_str())).one(&s.db).await?;
    let existing = match taken {
        Some(u) => Some(u),
        None => {
            let email = f.email.clone();
            match (user::ActiveModel { name: Set(f.name), email: Set(f.email), password: Set(hash), has_usable_password: Set(true), ..Default::default() })
                .insert(&s.db)
                .await
            {
                Ok(u) => {
                    if mail_gate(&s, "register", &u.email).await {
                        send_verification(&s, &u).await?;
                    }
                    s.throttle.clear(&key).await?;
                    None
                }
                // A concurrent registration of the same email loses the unique race: treat as existing.
                Err(e) => {
                    tracing::warn!("register insert failed: {e}");
                    user::Entity::find().filter(user::Column::Email.eq(email.as_str())).one(&s.db).await?
                }
            }
        }
    };
    if let Some(u) = existing
        && mail_gate(&s, "register-notice", &u.email).await
    {
        let mail = crate::mails::auth::account_exists(&u.name, &u.email, &format!("{}/forgot-password", app_url()))?;
        if let Err(e) = s.mailer.send(mail).await {
            tracing::error!("mail to user {}: {e}", u.id);
        }
    }
    inertia::flash(&session, "success", "Check your email to finish creating your account.").await;
    Ok(inertia::redirect("/login"))
}

#[utoipa::path(post, path = "/logout", responses((status = 303, description = "Redirect home")))]
pub async fn logout(session: Session) -> Response {
    auth::logout(&session).await;
    inertia::redirect("/")
}

#[utoipa::path(get, path = "/dashboard",
    responses((status = 200, description = "Dashboard page"), (status = 303, description = "Not logged in")))]
pub async fn dashboard(
    State(s): State<AppState>,
    Auth(uid): Auth,
    inertia: Inertia,
) -> Result<Response, AppError> {
    let u = user::Entity::find_by_id(uid).one(&s.db).await?;
    let posts = post::Entity::find()
        .filter(post::Column::UserId.eq(uid))
        .all(&s.db)
        .await?;
    let verified = u.as_ref().is_some_and(|u| u.email_verified_at.is_some());
    Ok(inertia.render("Dashboard", json!({ "user": u, "posts": posts, "verified": verified })))
}

/// The emailed link lands here. It only renders a confirm button: consuming the token on GET would let
/// mail scanners that prefetch links burn it before the user clicks.
#[utoipa::path(get, path = "/verify-email/{token}", params(("token" = String, Path, description = "Verification token")),
    responses((status = 200, description = "Confirm page; the token is consumed only by POST /verify-email")))]
pub async fn show_verify_email(inertia: Inertia, Path(token): Path<String>) -> Response {
    inertia.render("Auth/VerifyEmail", json!({ "token": token }))
}

#[derive(Deserialize, Validate, ToSchema)]
pub struct VerifyForm {
    #[validate(length(min = 1, message = "Missing token"))]
    token: String,
}

#[utoipa::path(post, path = "/verify-email", request_body = VerifyForm,
    responses((status = 303, description = "Redirect to login")))]
pub async fn verify_email(State(s): State<AppState>, session: Session, Form(f): Form<VerifyForm>) -> Result<Response, AppError> {
    match s.tokens.consume(&f.token, VERIFY_EMAIL).await? {
        Some(uid) => {
            user::ActiveModel { id: Unchanged(uid), email_verified_at: Set(Some(chrono::Utc::now())), ..Default::default() }
                .update(&s.db)
                .await?;
            inertia::flash(&session, "success", "Email verified. Log in to continue.").await;
        }
        None => inertia::flash(&session, "error", "This verification link is invalid or has expired.").await,
    }
    Ok(inertia::redirect("/login"))
}

#[utoipa::path(post, path = "/email/resend", request_body = ResendForm,
    responses((status = 303, description = "Always the same response; mails only for an existing unverified account")))]
pub async fn resend_verification(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    session: Session,
    headers: HeaderMap,
    Form(f): Form<ResendForm>,
) -> Result<Response, AppError> {
    // When throttled we silently skip so the response never differs.
    let key = Throttle::key(&format!("resend:{}", f.email), ip);
    if s.throttle.attempt(&key).await.is_ok() && mail_gate(&s, "resend", &f.email).await {
        let found = user::Entity::find().filter(user::Column::Email.eq(f.email.as_str())).one(&s.db).await?;
        if let Some(u) = found.filter(|u| u.email_verified_at.is_none()) {
            send_verification(&s, &u).await?;
        }
    }
    inertia::flash(&session, "success", "If that account needs verification, a new link is on its way.").await;
    Ok(inertia::redirect_back(&headers))
}

#[utoipa::path(get, path = "/forgot-password", responses((status = 200, description = "Forgot password page")))]
pub async fn show_forgot(inertia: Inertia) -> Response {
    inertia.render("Auth/ForgotPassword", json!({}))
}

#[utoipa::path(post, path = "/forgot-password", request_body = ForgotForm,
    responses((status = 303, description = "Always the same response, whether or not the email exists")))]
pub async fn forgot(
    State(s): State<AppState>,
    ClientIp(ip): ClientIp,
    session: Session,
    Form(f): Form<ForgotForm>,
) -> Result<Response, AppError> {
    // Throttled per IP, per email+IP and per email (mail flood); when locked we silently skip so the response never differs.
    // shortcut: timing differs slightly (a mail is sent only for real users); queue the mail to equalize.
    let key = Throttle::key(&format!("forgot:{}", f.email), ip);
    if ip_gate(&s, "forgot", ip).await.is_ok() && s.throttle.attempt(&key).await.is_ok() && mail_gate(&s, "forgot", &f.email).await {
        let found = user::Entity::find().filter(user::Column::Email.eq(f.email.as_str())).one(&s.db).await?;
        if let Some(u) = found {
            mail_link(&s, &u, RESET_PASSWORD, RESET_TTL, "reset-password", crate::mails::auth::reset_password).await?;
        }
    }
    inertia::flash(&session, "success", "If that email is registered, a reset link is on its way.").await;
    Ok(inertia::redirect("/forgot-password"))
}

#[utoipa::path(get, path = "/reset-password/{token}", params(("token" = String, Path, description = "Reset token")),
    responses((status = 200, description = "Reset password page")))]
pub async fn show_reset_form(inertia: Inertia, Path(token): Path<String>) -> Response {
    inertia.render("Auth/ResetPassword", json!({ "token": token }))
}

#[utoipa::path(post, path = "/reset-password", request_body = ResetForm,
    responses((status = 303, description = "Redirect to login, or back with an error")))]
pub async fn reset(
    State(s): State<AppState>,
    session: Session,
    headers: HeaderMap,
    Form(f): Form<ResetForm>,
) -> Result<Response, AppError> {
    let Some(uid) = s.tokens.consume(&f.token, RESET_PASSWORD).await? else {
        // Same generic error for unknown, used and expired tokens.
        inertia::flash_errors(&session, field_error("password", "This reset link is invalid or has expired.")).await;
        return Ok(inertia::redirect_back(&headers));
    };
    user::ActiveModel {
        id: Unchanged(uid),
        password: Set(auth::hash_password_async(f.password.clone()).await?),
        has_usable_password: Set(true), // a social-only user proved control of the mailbox
        ..Default::default()
    }
    .update(&s.db)
    .await?;
    // A reset signs the user out everywhere (whoever knew the old password loses their access).
    crate::account::sign_out_everywhere(&s, uid).await?;
    // Unlike a password CHANGE, a reset also kills API keys: whoever held the old password may have made one.
    s.api_keys.revoke_all(uid).await?;
    inertia::flash(&session, "success", "Password updated. Log in with your new password.").await;
    Ok(inertia::redirect("/login"))
}

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

    #[test]
    fn next_is_a_local_path_or_nothing() {
        assert_eq!(safe_next("/oauth/authorize?client_id=x").as_deref(), Some("/oauth/authorize?client_id=x"));
        for bad in ["https://evil.example", "//evil.example", "/\\evil.example", "evil", "", "/a\r\nb"] {
            assert_eq!(safe_next(bad), None, "{bad:?}");
        }
        assert_eq!(safe_next(&format!("/{}", "a".repeat(3000))), None);
    }
}