laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::Value;

use crate::config::DriverConfig;
use crate::contracts::CaptchaDriver;
use crate::provider_client::{ask_provider, check_hostname, interpret};
use crate::result::VerificationResult;

const ENDPOINT: &str = "https://challenges.cloudflare.com/turnstile/v0/siteverify";

/// Cloudflare Turnstile.
///
/// The siteverify endpoint answers with a plain pass or fail and there is no score to weigh. What
/// it does report is the action the widget was rendered with and the hostname it ran on, and both
/// can be held to what the form expects. Config keys: `key` (public, rendered into the widget) and
/// `secret` (server side).
#[derive(Debug, Clone)]
pub struct TurnstileDriver {
    config: DriverConfig,
    expected_action: Option<String>,
}

impl TurnstileDriver {
    /// A driver for these credentials.
    pub fn new(config: DriverConfig) -> Self {
        Self {
            config,
            expected_action: None,
        }
    }
}

#[async_trait]
impl CaptchaDriver for TurnstileDriver {
    fn name(&self) -> &str {
        "turnstile"
    }

    /// Post the token to Cloudflare's siteverify endpoint.
    ///
    /// Fails closed in both directions: an error page decodes to an empty payload and so carries
    /// no `success`, and an unreachable Cloudflare comes back as the `unreachable` error code. An
    /// outage blocks submissions, it neither waves them through nor breaks the form.
    async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
        let Some(data) = ask_provider(ENDPOINT, &self.config.secret, token, ip).await else {
            return VerificationResult::failure("unreachable");
        };

        let result = VerificationResult {
            score: None,
            ..interpret(&data)
        };

        if result.success
            && let Some(expected) = &self.expected_action
            && data.get("action").and_then(Value::as_str) != Some(expected.as_str())
        {
            return result.refused("action-mismatch");
        }

        check_hostname(result, &data)
    }

    fn site_key(&self) -> String {
        self.config.key.clone()
    }

    fn script_url(&self) -> String {
        "https://challenges.cloudflare.com/turnstile/v0/api.js".to_owned()
    }

    fn response_field(&self) -> String {
        "cf-turnstile-response".to_owned()
    }

    fn expecting_action(&self, action: Option<&str>) -> Option<Arc<dyn CaptchaDriver>> {
        Some(Arc::new(Self {
            config: self.config.clone(),
            expected_action: action.map(str::to_owned),
        }))
    }
}