laracaptcha 0.1.0

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

Laracaptcha for Laravel Rust

Laracaptcha for Laravel Rust

Driver-based captcha for Laravel Rust. One API for Cloudflare Turnstile and Google reCAPTCHA v2/v3: switch providers by changing one env variable, no code changes.

It is the port of Laracaptcha, the PHP package, to Laravel Rust. It targets Laravel Rust 0.1, which is in beta, and its API follows the framework's changes until 1.0. The behaviour, the names and this document follow the PHP package. Where Laravel Rust has no equivalent, the section says so, and the differences are collected at the end.

Installation

cargo add laracaptcha

Register the service provider in src/app.rs:

use laracaptcha::LaracaptchaServiceProvider;

pub fn configure() -> ApplicationBuilder {
    Application::configure().with_providers(|providers| {
        providers.add(LaracaptchaServiceProvider::new());
    })
}

Set your driver and keys in .env, the same variables as the PHP package:

CAPTCHA_DRIVER=turnstile

TURNSTILE_KEY=0x4AAA...
TURNSTILE_SECRET=0x4AAA...

# Or for reCAPTCHA (v2 / v3):
# CAPTCHA_DRIVER=recaptcha_v2
# RECAPTCHA_KEY=...
# RECAPTCHA_SECRET=...

Everything else is the LaracaptchaConfig section, set in src/app.rs with with_config (there is no file to publish). The keys are the ones of config/laracaptcha.php, with the same defaults:

Key Variable Default
default CAPTCHA_DRIVER turnstile
prevent_reuse CAPTCHA_PREVENT_REUSE true
reuse_ttl 5 (minutes)
log_failures CAPTCHA_LOG_FAILURES false
timeout 5 (seconds)
hostnames CAPTCHA_HOSTNAMES (comma-separated) none
drivers.turnstile TURNSTILE_KEY, TURNSTILE_SECRET empty
drivers.recaptcha_v2 RECAPTCHA_KEY, RECAPTCHA_SECRET empty
drivers.recaptcha_v3 RECAPTCHA_V3_KEY, RECAPTCHA_V3_SECRET, each falling back to RECAPTCHA_KEY and RECAPTCHA_SECRET empty
drivers.recaptcha_v3.min_score RECAPTCHA_V3_MIN_SCORE 0.5
.with_config(|config, _| {
    let captcha = config.section_mut::<LaracaptchaConfig>();

    captcha.default = "recaptcha_v3".to_owned();
    captcha.drivers.recaptcha_v3.min_score = 0.7;
})

Usage

In a form

Drop the widget function inside any form. It renders the right markup and loads the provider script for the configured driver:

<form method="POST" action="/register">
    {{ csrf_field() }}
    ...
    {{ laracaptcha_widget() }}
    <button type="submit">Register</button>
</form>

laracaptcha_widget() is the <x-laracaptcha::widget /> component: the same arguments, by name or by position in this order: driver, action, theme, size, language, defer. Any other argument becomes an attribute of the element, and a class is merged after the provider's own.

For reCAPTCHA v3 the widget is invisible and tokens are generated on submit; tag the action so the token is bound to this form: {{ laracaptcha_widget(action='register') }}. The default is submit.

Other options: theme (auto, light, dark), size, and for Turnstile action and language (the browser's when left out).

The widget is drawn by the package's own script, not by the provider scanning the page on load, so it also appears when markup is revealed after the page has loaded. The script is the PHP package's, unchanged, and it is written once after the first widget of a page however many there are.

One submit, not two. If the challenge has not resolved by the time the visitor presses the button, the submit is held back and sent again as soon as it does, so the form is never posted with an empty token for the server to refuse. If the challenge fails or times out instead, the submit goes through and the server explains why, because a button that does nothing is worse than an error message.

Deferring a hidden widget

A widget in markup that is present but hidden, inside a modal for instance, is drawn like any other: the provider's script is fetched for every visitor, when only the few who open the modal need it. Mark it defer and draw it when it is revealed:

<div id="gameplay-modal" hidden>
    <form method="POST" action="/gameplays">
        {{ csrf_field() }}
        ...
        {{ laracaptcha_widget(defer=true) }}
        <button type="submit">Add</button>
    </form>
</div>
// On opening the modal. Takes the widget, or anything containing it.
Laracaptcha.draw('#gameplay-modal');

Nothing else changes: once drawn it resolves in the background while the form is filled in, and the submit gate above still applies. A deferred widget that is never drawn leaves the token empty, and the rule refuses it.

In React, Vue or Svelte

For an Inertia app, or any front end that does not use the templates, laracaptcha::props() gives the component what the widget function works out for itself: the provider, the site key, the script and the response field. It serializes with the keys the components read (provider, siteKey, script, field, action), so pass it to the page as a prop:

let captcha = laracaptcha::props(None, Some("login")).await?;

The Captcha components for React, Vue and Svelte are the PHP package's resources/js, which do not depend on PHP: copy them into your front end, or point a Vite alias at a checkout, and use them as that README describes. The token arrives when the challenge is solved and goes back to an empty string when it expires or fails. Validate it with the same rule as any form.

A provider accepts each token once, so when the server refuses the submit and the form stays on the page, ask for a new one with the component's reset().

Validating the token

Use the validation rule on the token field. The field name depends on the provider (cf-turnstile-response for Turnstile, g-recaptcha-response for reCAPTCHA), and laracaptcha::response_field() gives it. Laravel Rust names a field after the struct's field, so rename it for the request:

use laracaptcha::Captcha;

#[derive(serde::Deserialize, Validate)]
#[validate(anyone)]
struct SignUp {
    #[validate(required)]
    name: String,

    #[serde(rename = "cf-turnstile-response", default)]
    #[validate(required, Captcha::new())]
    captcha: String,
}

async fn register(Valid(form): Valid<SignUp>) -> laravel::Result<Redirect> {
    // ...
}

Captcha is a Laravel Rust ValidationRule, and an async one: it asks the provider while the form is validated, and Laravel Rust awaits a field's rules one at a time. It works the same through Valid<T>, ValidRequest<T>, request.validate() and Rules::field(.., [Rule::custom(Captcha::new())]). Without a request (a bare Rules::validate), the rule works but sends no IP to the provider.

The rule includes replay protection: a token that already passed once is rejected (configurable via prevent_reuse / reuse_ttl), through the application's cache.

What the visitor is told is deliberately coarse, since naming the exact reason helps whoever is probing the form: the challenge was not completed, it failed, it was already used, or it could not be checked right now. That last one is its own message because an outage at the provider is not the visitor getting the challenge wrong, and "try again in a moment" is the only useful thing to say. The messages are messages in the configuration, and Messages::spanish() is the Spanish set of the PHP package.

The real reason can go to the log, where only you read it. It is off by default, since a validation rule should not leave records nobody asked for; set CAPTCHA_LOG_FAILURES=true to switch it on. The line goes through tracing, at warn, on the laracaptcha target:

WARN laracaptcha: Captcha verification failed context={"driver":"turnstile","errors":["invalid-input-secret"],"ip":"203.0.113.7","hostname":"example.com"}

Worth switching on while chasing a report of "I cannot sign up", and off again afterwards: from the outside every failure looks the same, and a wrong secret, a token solved on another host, an outage and an actual bot are told apart only by the codes the provider sent back. Left on, a flood of attempts against a public form writes a line each.

Binding a token to its action (reCAPTCHA v3)

A v3 token carries the action the widget minted it for. Without checking it, a token harvested from a low value form is good for a critical one, so pass the same action to the rule that you gave the widget:

#[serde(rename = "g-recaptcha-response", default)]
#[validate(required, Captcha::make(Some("recaptcha_v3"), Some("register")))]
captcha: String,

A token minted for anything else is rejected with the action-mismatch error code, and so is a response that carries no action at all. Leave the action out and nothing is checked, which is the default. Turnstile signs the action too: give the widget and the rule the same one. reCAPTCHA v2 has no action and ignores it.

Binding a token to your site

Every provider reports the hostname the challenge was solved on. List yours and a token solved anywhere else is refused with hostname-mismatch:

CAPTCHA_HOSTNAMES=example.com,www.example.com

Empty by default, because Cloudflare's test keys report example.com whatever page they run on.

Outside the rule, ask the driver directly:

let driver = laracaptcha::driver(Some("recaptcha_v3")).await?;
let driver = driver.expecting_action(Some("register")).expect("v3 binds actions");

driver.verify(&token, None).await;

Verifying manually

let result = laracaptcha::verify(&token, Some(&request.ip().to_string())).await?;

result.success;      // bool
result.score;        // Option<f64> (reCAPTCHA v3)
result.error_codes;  // Vec<String>

result.passed() and result.failed() are there too. Use a specific driver regardless of the default: laracaptcha::driver(Some("recaptcha_v3")).await?.verify(&token, None).await.

A driver of your own implements CaptchaDriver and is registered by name, in the provider or while the application runs:

LaracaptchaServiceProvider::new().extend("hcaptcha", || HCaptchaDriver::new(...))

laracaptcha::extend("hcaptcha", || HCaptchaDriver::new(...)).await?;

Testing

The provider is called with Laravel Rust's HTTP client, so client::fake() answers it, as in this crate's own tests. Or swap the drivers for the fake:

let fake = laracaptcha::fake(true, None).await?;     // all verifications pass
let fake = laracaptcha::fake(false, None).await?;    // all verifications fail
let fake = laracaptcha::fake(true, Some(0.9)).await?; // pass with a score

fake.attempts(); // recorded Attempt { token, ip } values

No HTTP requests are made while faked, and the widget renders nothing. A form post in a test then carries any token:

#[laravel::test(app = app)]
async fn registers(app: Application) {
    let fake = laracaptcha::fake(true, None).await.unwrap();

    app.post("/register")
        .form([("name", "Edu"), ("cf-turnstile-response", "any-token")])
        .await
        .assert_ok();

    assert_eq!(fake.attempts().len(), 1);
}

Bind the HTTP fake to a name (let http = client::fake();): dropping it restores real requests.

Dev keys

Cloudflare publishes always-pass test keys for local development: sitekey 1x00000000000000000000AA, secret 1x0000000000000000000000000000000AA.

Differences from the PHP package

  • Names that are free functions. The facade is the crate root: laracaptcha::driver(name), verify(token, ip), fake(success, score), props(driver, action), site_key(), script_url(), response_field() and extend(name, closure). They are async because Laravel Rust resolves services asynchronously. The rule is laracaptcha::Captcha, with Captcha::new() for PHP's new Captcha and Captcha::make(driver, action).
  • No named arguments. Captcha::fake(success: false) is laracaptcha::fake(false, None), and Captcha::make('recaptcha_v3', 'register') is Captcha::make(Some("recaptcha_v3"), Some("register")). In templates, laracaptcha_widget() does take names.
  • The widget is a MiniJinja function, laracaptcha_widget(), the name of the component with :: and - replaced, since neither is allowed in a function name. A dotted wire:model argument has no equivalent.
  • No Livewire. Laravel Rust has none, so there is no WithCaptcha trait, no wire:model binding and no verifyCaptchaOnce. The loader script still carries the Livewire hooks, unchanged, and they do nothing without it.
  • ExpectsAction is a method. CaptchaDriver::expecting_action(action) returns a copy bound to the action, or None for a driver that cannot (reCAPTCHA v2, the fake), instead of a second interface.
  • The configuration is a section, not a file: LaracaptchaConfig, read from the environment first and changed with with_config. drivers is a struct of the three shipped drivers, and a driver of your own is registered with extend and takes its credentials from its closure. There is no vendor:publish.
  • The messages are configuration. PHP keeps them in lang/en and lang/es, translated by the app locale. Laravel Rust 0.1 has no translations, so messages holds the four texts, English by default, and Messages::spanish() is the other set. That is also why the package needs no locale: neither does the PHP widget, whose Turnstile language is an argument and not the app locale.
  • The log goes through tracing, at warn, with the context as one JSON field. The same context is laracaptcha::rule::failure_context().
  • The rule needs the request for the IP. Inside Valid<T>, ValidRequest<T> and request.validate() it forwards it as remoteip; with a bare Rules::validate there is no request and no IP is sent.
  • Spent tokens are cached under a SHA-256 hash, not MD5, with the laracaptcha| prefix, in the application's default cache store.
  • fake() also covers the drivers you registered with extend, besides the three shipped ones and the default.
  • array_filter is only for empty values. PHP drops every falsy value from the request to the provider, including a token that is the string 0; this crate drops empty ones only.
  • The React, Vue and Svelte components are not shipped here. They are the PHP package's, and props() feeds them the same values.

Sponsors

Laracaptcha for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:

Author

Created by Edu Lazaro

License

Laracaptcha for Laravel Rust is open-sourced software licensed under the MIT license.