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::{Map, Value};

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

const ENDPOINT: &str = "https://www.google.com/recaptcha/api/siteverify";

/// Google reCAPTCHA v2, the "I am not a robot" checkbox.
///
/// Pass or fail, with no score involved. Config keys: `key` and `secret`.
#[derive(Debug, Clone)]
pub struct RecaptchaV2Driver {
    config: DriverConfig,
}

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

    /// Turn Google's payload into a [`VerificationResult`].
    ///
    /// The provider's own `success` flag is taken at face value; the score is carried over when
    /// present but is not weighed. The hostname is, when `hostnames` lists any.
    fn to_result(data: &Map<String, Value>) -> VerificationResult {
        check_hostname(interpret(data), data)
    }

    async fn ask(secret: &str, token: &str, ip: Option<&str>) -> Result<Map<String, Value>, VerificationResult> {
        ask_provider(ENDPOINT, secret, token, ip)
            .await
            .ok_or_else(|| VerificationResult::failure("unreachable"))
    }
}

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

    /// Post the token to Google's siteverify endpoint.
    ///
    /// Fails closed, like every driver: a non-JSON reply and an unreachable Google both end up as
    /// an unsuccessful result.
    async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
        match Self::ask(&self.config.secret, token, ip).await {
            Ok(data) => Self::to_result(&data),
            Err(unreachable) => unreachable,
        }
    }

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

    fn script_url(&self) -> String {
        "https://www.google.com/recaptcha/api.js".to_owned()
    }

    fn response_field(&self) -> String {
        "g-recaptcha-response".to_owned()
    }
}

/// Google reCAPTCHA v3, the invisible one.
///
/// Same credentials and same endpoint as v2, so only the judging differs: v3 returns a score from
/// 0.0 (almost certainly a bot) to 1.0 and never blocks anything by itself, which means the
/// threshold is the whole point of the driver. Config keys: `key`, `secret` and `min_score`
/// (default 0.5).
#[derive(Debug, Clone)]
pub struct RecaptchaV3Driver {
    config: RecaptchaV3Config,
    expected_action: Option<String>,
}

impl RecaptchaV3Driver {
    /// A driver for these credentials and this threshold.
    pub fn new(config: RecaptchaV3Config) -> Self {
        Self {
            config,
            expected_action: None,
        }
    }

    /// A v3 response has to clear two more checks than a v2 one before it counts as a pass.
    ///
    /// First the action, when one is expected: Google stamps every token with the action the
    /// widget asked for, and without comparing it a token minted on a cheap form is good for an
    /// expensive one. A response with no action at all is treated as a mismatch, so the check
    /// fails closed.
    ///
    /// Then the score: below the configured threshold the verification fails even though Google
    /// reports success, because v3 never blocks anything by itself and leaves the threshold to
    /// the application.
    fn to_result(&self, data: &Map<String, Value>) -> VerificationResult {
        let result = RecaptchaV2Driver::to_result(data);

        if !result.success {
            return result;
        }

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

        if result.score.is_some_and(|score| score < self.config.min_score) {
            return result.refused("low-score");
        }

        result
    }
}

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

    async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
        match RecaptchaV2Driver::ask(&self.config.secret, token, ip).await {
            Ok(data) => self.to_result(&data),
            Err(unreachable) => unreachable,
        }
    }

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

    fn script_url(&self) -> String {
        "https://www.google.com/recaptcha/api.js".to_owned()
    }

    fn response_field(&self) -> String {
        "g-recaptcha-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),
        }))
    }
}