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 crate::result::VerificationResult;

/// A captcha provider, as seen by the rest of the package.
///
/// Implement it to add a provider the package does not ship, then register it with
/// [`LaracaptchaServiceProvider::extend`](crate::LaracaptchaServiceProvider::extend) or
/// [`extend`](crate::extend), where the closure decides where the credentials come from.
///
/// A driver covers both halves of the flow: telling the widget how to render itself
/// ([`site_key`](Self::site_key), [`script_url`](Self::script_url),
/// [`response_field`](Self::response_field)) and checking the token the widget produces
/// ([`verify`](Self::verify)).
///
/// Implementations must fail closed. A driver that cannot reach its provider returns an
/// unsuccessful result, it does not panic and it never lets the request through by default.
#[async_trait]
pub trait CaptchaDriver: Send + Sync {
    /// Driver identifier, such as `turnstile`.
    ///
    /// For the caller's benefit only: logging, or branching in a view. The package resolves drivers
    /// by their configured name, never by this.
    fn name(&self) -> &str;

    /// Verify a challenge token against the provider.
    ///
    /// Never fails: a refused token, an expired one, a malformed response and an unreachable
    /// provider all come back as a failed [`VerificationResult`]. The IP is forwarded to providers
    /// that use it as an extra signal.
    async fn verify(&self, token: &str, ip: Option<&str>) -> VerificationResult;

    /// Public site key rendered into the widget.
    fn site_key(&self) -> String;

    /// Provider JavaScript API url, without the site key. Empty when the driver needs no script,
    /// which is what the fake driver does in tests.
    fn script_url(&self) -> String;

    /// Name of the request field carrying the token, such as `cf-turnstile-response`.
    ///
    /// It is the name the provider's own script gives the hidden input, so it is dictated by the
    /// provider, and it is the field the validation rule expects to find in the request.
    fn response_field(&self) -> String;

    /// A copy of this driver that only accepts tokens minted for `action`, or `None` when the
    /// driver does not bind tokens to an action.
    ///
    /// This is PHP's `ExpectsAction` interface: Turnstile and reCAPTCHA v3 return a copy, reCAPTCHA
    /// v2 and the fake return `None`. Implementations must not mutate: the manager hands out one
    /// instance for the whole application.
    fn expecting_action(&self, action: Option<&str>) -> Option<Arc<dyn CaptchaDriver>> {
        let _ = action;

        None
    }
}