laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use laravel::http::client;
use laravel::time::ToSpan;
use serde_json::{Map, Value};

use crate::result::VerificationResult;
use crate::support::{config, float, truthy};

/// Post the token to the provider and hand back its decoded payload.
///
/// Returns `None` when the provider could not be reached at all: a refused connection, a DNS
/// failure, or a request that ran past the timeout. The caller turns that into a failed
/// verification, because a captcha that could not be checked is not a captcha that passed.
///
/// A reply that arrives but is not a JSON object, an error page for instance, is not a connection
/// failure: it decodes to an empty payload, which carries no `success` key and therefore fails too.
///
/// Like PHP's `array_filter`, empty values are left out of the form: a missing secret or IP is not
/// sent as an empty field.
pub(crate) async fn ask_provider(
    endpoint: &str,
    secret: &str,
    token: &str,
    ip: Option<&str>,
) -> Option<Map<String, Value>> {
    let fields: Vec<(&str, &str)> = [
        ("secret", secret),
        ("response", token),
        ("remoteip", ip.unwrap_or_default()),
    ]
    .into_iter()
    .filter(|(_, value)| !value.is_empty())
    .collect();

    let response = client::post(endpoint)
        .timeout((config().timeout as i64).seconds())
        .form(fields)
        .await
        .ok()?;

    Some(match response.json::<Value>() {
        Ok(Value::Object(payload)) => payload,
        _ => Map::new(),
    })
}

/// Refuse a passing result whose token was solved on a site not listed in `hostnames`.
///
/// Fails closed: with a list configured, a response that names no hostname at all is a mismatch
/// too. With no list, the result goes back untouched.
pub(crate) fn check_hostname(result: VerificationResult, data: &Map<String, Value>) -> VerificationResult {
    let allowed: Vec<String> = config().hostnames.iter().map(|host| host.to_lowercase()).collect();

    if !result.success || allowed.is_empty() {
        return result;
    }

    let hostname = data
        .get("hostname")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_lowercase();

    if allowed.contains(&hostname) {
        return result;
    }

    result.refused("hostname-mismatch")
}

/// The success flag, score and error codes of a provider payload, before any check of ours.
pub(crate) fn interpret(data: &Map<String, Value>) -> VerificationResult {
    let error_codes = match data.get("error-codes") {
        Some(Value::Array(codes)) => codes
            .iter()
            .map(|code| code.as_str().map_or_else(|| code.to_string(), str::to_owned))
            .collect(),
        _ => Vec::new(),
    };

    VerificationResult {
        success: truthy(data.get("success")),
        score: float(data.get("score")),
        error_codes,
        raw: data.clone(),
    }
}