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, Mutex, PoisonError};

use async_trait::async_trait;
use serde_json::{Map, Value};

use crate::contracts::CaptchaDriver;
use crate::result::VerificationResult;

/// One token the fake was asked about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
    /// The token.
    pub token: String,
    /// The IP address passed along with it.
    pub ip: Option<String>,
}

/// Driver that answers without talking to anyone, for tests.
///
/// Install it with [`fake`](crate::fake()), which points every configured driver name at one
/// instance, then assert on what reached it:
///
/// ```ignore
/// let fake = laracaptcha::fake(true, None).await?;   // every token passes
/// let fake = laracaptcha::fake(false, None).await?;  // every token is refused
/// assert_eq!(fake.attempts().len(), 1);
/// ```
///
/// `script_url()` is deliberately empty so the widget renders no external script in a test run.
#[derive(Debug, Clone)]
pub struct FakeDriver {
    success: bool,
    score: Option<f64>,
    attempts: Arc<Mutex<Vec<Attempt>>>,
}

impl FakeDriver {
    /// A fake that passes or refuses every token, with this score.
    pub fn new(success: bool, score: Option<f64>) -> Self {
        Self {
            success,
            score,
            attempts: Arc::default(),
        }
    }

    /// Every token this fake was asked about, oldest first.
    pub fn attempts(&self) -> Vec<Attempt> {
        self.attempts.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }
}

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

    /// Records the attempt, then answers with whatever the fake was built with.
    async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult {
        self.attempts
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(Attempt {
                token: token.to_owned(),
                ip: ip.map(str::to_owned),
            });

        VerificationResult {
            success: self.success,
            score: self.score,
            error_codes: if self.success {
                Vec::new()
            } else {
                vec!["fake-failure".to_owned()]
            },
            raw: Map::from_iter([("fake".to_owned(), Value::Bool(true))]),
        }
    }

    fn site_key(&self) -> String {
        "fake-site-key".to_owned()
    }

    fn script_url(&self) -> String {
        String::new()
    }

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