laravel-rust-devtools 0.2.1

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! `/_devtools/login`: the page where someone who isn't on the application's machine enters the
//! key, which a cookie then carries.

use axum::http::HeaderValue;
use laravel::container::Inject;
use laravel::cookie::{Cookie, SameSite};
use laravel::hash::Password;
use laravel::http::{Redirect, Request, Response, StatusCode, header};
use laravel::rate_limit::{self, Limit};
use laravel::time::ToSpan;
use laravel::validation::ValidRequest;

use super::access::{self, Access, COOKIE, COOKIE_HOURS};

/// How many wrong keys a client may enter a minute.
const ATTEMPTS: u32 = 5;

/// What the login form sends.
#[laravel::input]
#[validate(anyone)]
pub(crate) struct Login {
    #[validate(required)]
    key: Password,
}

/// `GET /_devtools/login`: the form. The route exists only when the application has a key.
pub(crate) async fn show(request: Request) -> laravel::Result<Response> {
    page(&request, StatusCode::OK, None)
}

/// `POST /_devtools/login`: a cookie that lets in, if it is the key; wrong keys are limited for each
/// address a connection comes from, whatever client a proxy names.
pub(crate) async fn store(access: Inject<Access>, login: ValidRequest<Login>) -> laravel::Result<Response> {
    let request = login.request();
    let peer = access::peer(request).map_or_else(String::new, |peer| peer.to_string());
    let attempts = format!("devtools-login:{peer}");
    let limit = Limit::per_minute(ATTEMPTS);

    if rate_limit::check(&attempts, limit).await?.is_err() {
        return page(request, StatusCode::TOO_MANY_REQUESTS, Some(Notice::TooMany));
    }
    if !access.is_key(login.key.as_str()) {
        rate_limit::hit(&attempts, limit).await?;
        return page(request, StatusCode::UNPROCESSABLE_ENTITY, Some(Notice::Wrong));
    }
    rate_limit::clear(&attempts).await?;

    let Some(value) = access.cookie(request.encrypter()?.key()) else {
        laravel::abort!(500);
    };
    let cookie = Cookie::new(COOKIE, value)
        .path("/")
        .same_site(SameSite::Strict)
        .secure(request.is_secure())
        .max_age(COOKIE_HOURS.hours());

    Ok(Response::new(Redirect::to("/").with_cookie(cookie)))
}

/// `POST /_devtools/logout`: the cookie, gone.
pub(crate) async fn destroy() -> Redirect {
    Redirect::to("/").without_cookie(Cookie::new(COOKIE, "").path("/"))
}

/// Why the form is shown again.
#[derive(Clone, Copy)]
enum Notice {
    Wrong,
    TooMany,
}

/// The page's texts, in German or English.
struct Texts {
    lang: &'static str,
    title: &'static str,
    label: &'static str,
    submit: &'static str,
    wrong: &'static str,
    too_many: &'static str,
}

const ENGLISH: Texts = Texts {
    lang: "en",
    title: "Developer tools",
    label: "Key",
    submit: "Open",
    wrong: "That isn't the key.",
    too_many: "Too many wrong keys. Try again in a minute.",
};

const GERMAN: Texts = Texts {
    lang: "de",
    title: "Entwicklerwerkzeuge",
    label: "Schlüssel",
    submit: "Öffnen",
    wrong: "Das ist nicht der Schlüssel.",
    too_many: "Zu viele falsche Schlüssel. Versuch es in einer Minute noch einmal.",
};

/// The texts in the language the browser lists first, of the two; quality values aren't weighed.
fn texts(request: &Request) -> &'static Texts {
    let german = request
        .header("accept-language")
        .and_then(|languages| languages.split(',').next())
        .is_some_and(|first| first.trim().to_ascii_lowercase().starts_with("de"));
    if german { &GERMAN } else { &ENGLISH }
}

fn page(request: &Request, status: StatusCode, notice: Option<Notice>) -> laravel::Result<Response> {
    let texts = texts(request);
    let token = laravel::session::csrf_token()?;
    let notice = match notice {
        None => String::new(),
        Some(Notice::Wrong) => format!("<p role=\"alert\">{}</p>", texts.wrong),
        Some(Notice::TooMany) => format!("<p role=\"alert\">{}</p>", texts.too_many),
    };
    let html = format!(
        "<!DOCTYPE html>\n<html lang=\"{lang}\">\n<head>\n<meta charset=\"utf-8\">\n\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
         <meta name=\"color-scheme\" content=\"light dark\">\n\
         <meta name=\"robots\" content=\"noindex\">\n<title>{title}</title>\n</head>\n<body>\n\
         <main>\n<h1>{title}</h1>\n{notice}\n<form method=\"POST\" action=\"{prefix}/login\">\n\
         <input type=\"hidden\" name=\"_token\" value=\"{token}\">\n\
         <label for=\"key\">{label}</label>\n\
         <input id=\"key\" name=\"key\" type=\"password\" autocomplete=\"current-password\" required autofocus>\n\
         <button type=\"submit\">{submit}</button>\n</form>\n</main>\n</body>\n</html>\n",
        lang = texts.lang,
        title = texts.title,
        label = texts.label,
        submit = texts.submit,
        prefix = super::PREFIX,
        token = escape(&token),
    );

    // The page holds the session's CSRF token.
    let mut response = Response::new(laravel::view::Html::raw(html)).with_status(status);
    response
        .headers_mut()
        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
    Ok(response)
}

/// `value` as HTML attribute text.
fn escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}