laracaptcha 0.1.0

Driver-based captcha for Laravel Rust: Cloudflare Turnstile and Google reCAPTCHA v2 and v3 behind one API.
Documentation
use laravel::config::{Env, Section};

/// The credentials of one provider.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DriverConfig {
    /// The public key, rendered into the widget.
    pub key: String,
    /// The secret, sent to the provider with every verification.
    pub secret: String,
}

/// The credentials of reCAPTCHA v3, which adds the score threshold.
#[derive(Debug, Clone, PartialEq)]
pub struct RecaptchaV3Config {
    /// The public key, rendered into the widget.
    pub key: String,
    /// The secret, sent to the provider with every verification.
    pub secret: String,
    /// Verifications with a score below this threshold fail even if Google reports success.
    /// Range 0.0 (bot) to 1.0 (human).
    pub min_score: f64,
}

impl Default for RecaptchaV3Config {
    fn default() -> Self {
        Self {
            key: String::new(),
            secret: String::new(),
            min_score: 0.5,
        }
    }
}

/// The configured drivers, `drivers` in PHP's `config/laracaptcha.php`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Drivers {
    /// `turnstile`.
    pub turnstile: DriverConfig,
    /// `recaptcha_v2`.
    pub recaptcha_v2: DriverConfig,
    /// `recaptcha_v3`.
    pub recaptcha_v3: RecaptchaV3Config,
}

/// What the visitor is told when the rule refuses a token.
///
/// Deliberately coarse, since naming the exact reason helps whoever is probing the form. PHP keeps
/// these in `lang/`; Laravel Rust 0.1 has no translations, so they are configuration. Use
/// [`Messages::spanish`] or write your own.
#[derive(Debug, Clone, PartialEq)]
pub struct Messages {
    /// The field was empty.
    pub required: String,
    /// The provider refused the token.
    pub invalid: String,
    /// The token was already used.
    pub used: String,
    /// The provider could not be reached.
    pub unreachable: String,
}

impl Default for Messages {
    fn default() -> Self {
        Self {
            required: "Please complete the captcha challenge.".to_owned(),
            invalid: "The captcha verification failed. Please try again.".to_owned(),
            used: "This captcha has already been used. Please refresh the page and try again.".to_owned(),
            unreachable: "The captcha could not be checked right now. Please try again in a moment.".to_owned(),
        }
    }
}

impl Messages {
    /// The Spanish messages the PHP package ships in `lang/es`.
    pub fn spanish() -> Self {
        Self {
            required: "Por favor, completa el desafío captcha.".to_owned(),
            invalid: "La verificación del captcha ha fallado. Inténtalo de nuevo.".to_owned(),
            used: "Este captcha ya se ha usado. Recarga la página e inténtalo de nuevo.".to_owned(),
            unreachable: "No se ha podido comprobar el captcha ahora mismo. Inténtalo de nuevo en un momento."
                .to_owned(),
        }
    }
}

/// The package's configuration, the equivalent of `config/laracaptcha.php`.
///
/// ```ignore
/// .with_config(|config, _| {
///     let captcha = config.section_mut::<LaracaptchaConfig>();
///
///     captcha.default = "recaptcha_v3".to_owned();
///     captcha.drivers.recaptcha_v3.min_score = 0.7;
/// })
/// ```
#[derive(Debug, Clone, Section)]
pub struct LaracaptchaConfig {
    /// The driver used when none is named: `turnstile`, `recaptcha_v2` or `recaptcha_v3`.
    #[env("CAPTCHA_DRIVER", default = "turnstile")]
    pub default: String,

    /// A verified token is remembered in the cache for `reuse_ttl` minutes and rejected if it is
    /// submitted again (replay protection).
    #[env("CAPTCHA_PREVENT_REUSE", default = true)]
    pub prevent_reuse: bool,

    /// Minutes a verified token is remembered.
    #[section(default = 5)]
    pub reuse_ttl: u64,

    /// Write every refusal to the log with the provider's own error codes. Off by default: the
    /// package writes nothing anywhere unless you ask it to.
    #[env("CAPTCHA_LOG_FAILURES", default = false)]
    pub log_failures: bool,

    /// Seconds to wait for the provider before giving up. Giving up counts as a failed
    /// verification, never as a pass.
    #[section(default = 5)]
    pub timeout: u64,

    /// The sites a token may have been solved on. Empty means no check, which is the default
    /// because Cloudflare's test keys report `example.com` whatever page they ran on.
    #[env("CAPTCHA_HOSTNAMES", separator = ",")]
    pub hostnames: Vec<String>,

    /// The credentials of each driver.
    #[env(with = drivers_from_env)]
    pub drivers: Drivers,

    /// What the visitor is told when the rule refuses a token.
    pub messages: Messages,
}

fn text(env: &Env, key: &str) -> Option<String> {
    env.get::<String>(key)
}

fn drivers_from_env(env: &Env) -> Option<Drivers> {
    let recaptcha_key = text(env, "RECAPTCHA_KEY");
    let recaptcha_secret = text(env, "RECAPTCHA_SECRET");

    Some(Drivers {
        turnstile: DriverConfig {
            key: text(env, "TURNSTILE_KEY").unwrap_or_default(),
            secret: text(env, "TURNSTILE_SECRET").unwrap_or_default(),
        },
        recaptcha_v2: DriverConfig {
            key: recaptcha_key.clone().unwrap_or_default(),
            secret: recaptcha_secret.clone().unwrap_or_default(),
        },
        recaptcha_v3: RecaptchaV3Config {
            key: text(env, "RECAPTCHA_V3_KEY").or(recaptcha_key).unwrap_or_default(),
            secret: text(env, "RECAPTCHA_V3_SECRET")
                .or(recaptcha_secret)
                .unwrap_or_default(),
            min_score: env.get::<f64>("RECAPTCHA_V3_MIN_SCORE").unwrap_or(0.5),
        },
    })
}