6.8 KiB · text History 263b40b
//! Paired devices: minting, listing, renaming and revoking the tokens the
//! Android app authenticates with (movie_monster's `handlers/devices.rs`).
//!
//! A new token is shown exactly once, on its own page, as text and as a QR of
//! `recourse://pair?base=<origin>&token=<token>`, so the phone scans it
//! instead of someone retyping 73 characters. Only its hash is stored (see
//! [`crate::auth::api_tokens`]), so unlike movie_monster it can't be shown
//! again: a lost phone is a revoke and a new pairing.
use axum::extract::{Form, Path, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{Html, Redirect};
use minijinja::context;
use qrcode::render::svg;
use qrcode::QrCode;
use serde::Deserialize;
use tracing::error;
use uuid::Uuid;

use super::render;
use crate::auth;
use crate::middleware::UserContext;
use crate::AppState;

/// The URI scheme the app registers. Opening the QR from any camera app or
/// browser hands both fields to the app.
pub const PAIR_SCHEME: &str = "recourse";

fn map500(e: anyhow::Error) -> StatusCode {
    error!(error = %e, "device token operation failed");
    StatusCode::INTERNAL_SERVER_ERROR
}

/// GET /devices — every device (token) on this account.
pub async fn show_devices(State(state): State<AppState>, user: UserContext) -> Result<Html<String>, StatusCode> {
    let tokens = auth::list_api_tokens(state.db.as_ref(), user.user.id).await.map_err(map500)?;
    let now = chrono::Utc::now();
    let rows: Vec<minijinja::Value> = tokens
        .into_iter()
        .map(|t| {
            context! {
                id => t.id,
                label => t.label,
                created => crate::timeutil::abs(t.created_at),
                last_used => t.last_used_at.map(crate::timeutil::rel),
                expires => t.expires_at.map(crate::timeutil::abs),
                expired => t.expires_at.is_some_and(|e| e < now),
            }
        })
        .collect();
    render(
        &state,
        "devices/list.html",
        context! {
            title => "Devices",
            app_name => state.config.app_name,
            user => user.user,
            devices => rows,
            sliding_days => auth::api_tokens::SLIDING_DAYS,
        },
    )
}

/// `GET /api-tokens` from before there was an app: the same page.
pub async fn legacy_tokens_page() -> Redirect {
    Redirect::permanent("/devices")
}

#[derive(Debug, Deserialize)]
pub struct PairForm {
    pub label: Option<String>,
}

/// POST /devices — mint a token and show its pairing QR, once.
pub async fn handle_pair(
    State(state): State<AppState>,
    headers: HeaderMap,
    user: UserContext,
    Form(form): Form<PairForm>,
) -> Result<Html<String>, StatusCode> {
    let (row, token) =
        auth::create_api_token(state.db.as_ref(), user.user.id, form.label, None).await.map_err(map500)?;

    let origin = base_url(&headers, &state.config.public_url);
    let pair_uri = pair_uri(&origin, &token);
    // A failed QR costs the convenience, not the page: the fields are text too.
    let qr_svg = render_qr_svg(&pair_uri).unwrap_or_else(|e| {
        error!(error = %e, "QR render failed");
        String::new()
    });
    render(
        &state,
        "devices/pair.html",
        context! {
            title => "Pair a device",
            app_name => state.config.app_name,
            user => user.user,
            label => row.label,
            token => token,
            pair_uri => pair_uri,
            base_url => origin,
            qr_svg => minijinja::Value::from_safe_string(qr_svg),
            sliding_days => auth::api_tokens::SLIDING_DAYS,
        },
    )
}

#[derive(Debug, Deserialize)]
pub struct RenameForm {
    pub label: Option<String>,
}

/// POST /devices/{id}/rename
pub async fn handle_rename(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
    Form(form): Form<RenameForm>,
) -> Result<Redirect, StatusCode> {
    if !auth::rename_api_token(state.db.as_ref(), user.user.id, id, form.label).await.map_err(map500)? {
        return Err(StatusCode::NOT_FOUND);
    }
    Ok(Redirect::to("/devices"))
}

/// POST /devices/{id}/delete — revoke. The device's next request is a 401.
pub async fn handle_revoke(
    State(state): State<AppState>,
    user: UserContext,
    Path(id): Path<Uuid>,
) -> Result<Redirect, StatusCode> {
    auth::delete_api_token(state.db.as_ref(), user.user.id, id).await.map_err(map500)?;
    Ok(Redirect::to("/devices"))
}

/// `recourse://pair?base=…&token=…`
pub fn pair_uri(origin: &str, token: &str) -> String {
    format!(
        "{PAIR_SCHEME}://pair?base={}&token={}",
        super::focus::urlencode(origin.trim_end_matches('/')),
        super::focus::urlencode(token),
    )
}

/// The origin a phone should dial: `PUBLIC_URL` when it was set explicitly,
/// else what the browser is already talking to (forwarded headers, then
/// Host) — so pairing over the LAN encodes the LAN address and pairing
/// through the proxy the public one. A phone can only dial what it can reach.
fn base_url(headers: &HeaderMap, public_url: &str) -> String {
    if std::env::var("PUBLIC_URL").is_ok_and(|v| !v.trim().is_empty()) {
        return public_url.trim_end_matches('/').to_string();
    }
    let first = |name: &str| {
        headers
            .get(name)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.split(',').next().unwrap_or(s).trim().to_string())
            .filter(|s| !s.is_empty())
    };
    let scheme = first("x-forwarded-proto").unwrap_or_else(|| "http".into());
    match first("x-forwarded-host").or_else(|| first("host")) {
        Some(host) => format!("{scheme}://{host}"),
        None => public_url.trim_end_matches('/').to_string(),
    }
}

fn render_qr_svg(payload: &str) -> Result<String, qrcode::types::QrError> {
    Ok(QrCode::new(payload.as_bytes())?
        .render::<svg::Color>()
        .min_dimensions(280, 280)
        .quiet_zone(true)
        .build())
}

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

    #[test]
    fn the_pair_uri_carries_both_fields_encoded() {
        let uri = pair_uri("https://forum.example/", "recourse_abc");
        assert_eq!(uri, "recourse://pair?base=https%3A%2F%2Fforum.example&token=recourse_abc");
    }

    #[test]
    fn the_base_follows_the_browser_without_public_url() {
        let mut h = HeaderMap::new();
        h.insert("host", "192.168.1.5:3000".parse().unwrap());
        if std::env::var("PUBLIC_URL").is_err() {
            assert_eq!(base_url(&h, "http://localhost:3000"), "http://192.168.1.5:3000");
            h.insert("x-forwarded-proto", "https".parse().unwrap());
            h.insert("x-forwarded-host", "forum.example".parse().unwrap());
            assert_eq!(base_url(&h, "http://localhost:3000"), "https://forum.example");
        }
    }

    #[test]
    fn the_qr_renders() {
        assert!(render_qr_svg(&pair_uri("http://x", "recourse_0")).unwrap().contains("<svg"));
    }
}