Laracaptcha Rust

Laracaptcha Rust puts Cloudflare Turnstile, reCAPTCHA v2 and reCAPTCHA v3 behind one widget, one validation rule and one set of functions in Laravel Rust. Your code never names the provider: CAPTCHA_DRIVER in .env does, so moving from Google to Cloudflare is a change of keys and nothing else.
Written against version 0.1, which targets Laravel Rust 0.1 (in beta). Its API follows the framework's changes until 1.0.
This is the port of Laracaptcha, the PHP package, and its behaviour and names follow it. This page is about using it: the widget, the rule, the config and testing without the network. The crate is on crates.io and its API reference is on docs.rs. For a step-by-step tutorial in Spanish, see Cómo proteger un formulario con captcha en Laravel Rust on Neoguias.
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 the driver and the keys in .env, the same variables as the PHP package:
CAPTCHA_DRIVER=turnstile # or recaptcha_v2, recaptcha_v3 TURNSTILE_KEY=0x4AAA... TURNSTILE_SECRET=0x4AAA...
reCAPTCHA reads RECAPTCHA_KEY and RECAPTCHA_SECRET, and v3 can have its own RECAPTCHA_V3_KEY and RECAPTCHA_V3_SECRET. For local work, Cloudflare's test keys always pass: site key 1x00000000000000000000AA, secret 1x0000000000000000000000000000000AA.
Everything else is the LaracaptchaConfig section, with no file to publish. Set it in src/app.rs with with_config:
.with_config(|config, _| { let captcha = config.section_mut::<LaracaptchaConfig>(); captcha.default = "recaptcha_v3".to_owned(); captcha.drivers.recaptcha_v3.min_score = 0.7; })
| 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 the v2 variable |
empty |
drivers.recaptcha_v3.min_score |
RECAPTCHA_V3_MIN_SCORE |
0.5 |
The two halves
Every captcha has a browser half and a server half, and the crate gives you one piece for each:
| Piece | What it does | |
|---|---|---|
| Browser | laracaptcha_widget() |
Draws the challenge and loads the provider's script once per page |
| Server | Captcha rule, or laracaptcha::verify() |
Sends the token to the provider and gives you a pass or a fail |
A form with a widget
Drop the widget function inside any MiniJinja form. It renders the right markup and loads the script for the configured driver:
<form method="POST" action="/register"> {{ csrf_field() }} <input name="name"> {{ laracaptcha_widget() }} <button type="submit">Register</button> </form>
laracaptcha_widget() takes driver, action, theme (auto, light, dark), size, language and defer, by name or by position in that order. 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 the token is generated on submit, so tag the action: {{ laracaptcha_widget(action='register') }}.
The widget is drawn by the package's own script, so it also appears when markup is revealed after the page has loaded, and the script is written once however many widgets a page has. One submit, not two: if the challenge has not resolved when the visitor presses the button, the submit is held back and sent again as soon as it does.
A widget inside a modal can be drawn when the modal opens. Mark it defer and call Laracaptcha.draw('#modal') when it is revealed, so the provider's script is only fetched by the visitors who need it.
Validating the token
Use the rule on the token field. The field is cf-turnstile-response for Turnstile and 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 an async Laravel Rust ValidationRule: it asks the provider while the form is validated, through Valid<T>, ValidRequest<T>, request.validate() or Rules::field. Inside a request it forwards the visitor's IP as remoteip.
A token that already passed once is rejected, through the application's cache (prevent_reuse, reuse_ttl). What the visitor is told is deliberately coarse: the challenge was not completed, it failed, it was already used, or it could not be checked right now. The texts are messages in the configuration, and Messages::spanish() is the Spanish set of the PHP package.
The real reason can go to the log, off by default. Set CAPTCHA_LOG_FAILURES=true and the line goes through tracing, at warn, on the laracaptcha target, with the driver, the provider's error codes, the IP and the hostname. Switch it on while chasing a report of "I cannot sign up", and off again afterwards.
Making a stolen token worth less
A v3 token carries the action its widget minted it for. Pass the same action to the rule, and a token harvested from a low value form is no good for a critical one:
#[serde(rename = "g-recaptcha-response", default)] #[validate(required, Captcha::make(Some("recaptcha_v3"), Some("register")))] captcha: String,
A token minted for anything else, or a response with no action, is rejected with action-mismatch. Turnstile signs the action too, so give the widget and the rule the same one. reCAPTCHA v2 has no action and ignores it.
Every provider also 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
It is empty by default, because Cloudflare's test keys report example.com whatever page they run on.
The result
Outside the rule, ask the driver directly:
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. A specific driver, whatever the default: laracaptcha::driver(Some("recaptcha_v3")).await?.verify(&token, None).await. A driver of your own implements CaptchaDriver and is registered by name with LaracaptchaServiceProvider::new().extend("hcaptcha", || HCaptchaDriver::new(...)), or while the application runs with laracaptcha::extend.
React, Vue and Svelte
For an Inertia app, laracaptcha::props() gives the component what the widget function works out for itself: the provider, the site key, the script and the response field, serialized with the keys the components read. The Captcha components are the PHP package's resources/js, which do not depend on PHP: copy them into your front end and pass them the props.
let captcha = laracaptcha::props(None, Some("login")).await?;
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().
In tests
The provider is called with Laravel Rust's HTTP client, so client::fake() answers it. 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 request is made while faked, and the widget renders nothing, so pages keep loading. 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.
Differences from the PHP package
- The facade is the crate root.
laracaptcha::driver(name),verify(token, ip),fake(success, score),props(driver, action),site_key(),script_url(),response_field()andextend(name, closure), allasync. The rule isCaptcha::new()andCaptcha::make(driver, action). - No named arguments in Rust.
Captcha::fake(success: false)islaracaptcha::fake(false, None). In templates,laracaptcha_widget()does take names. - The widget is a MiniJinja function, not a Blade component. A dotted
wire:modelargument has no equivalent. - No Livewire. There is no
WithCaptchatrait and nowire:modelbinding. The loader script still carries the Livewire hooks, unchanged, and they do nothing without it. ExpectsActionis a method.CaptchaDriver::expecting_action(action)returns a copy bound to the action, orNonefor a driver that cannot.- The configuration is a section, not a file:
LaracaptchaConfig, read from the environment first and changed withwith_config. There is novendor:publish. - The messages are configuration, English by default, because Laravel Rust 0.1 has no translations.
- The log goes through
tracing, atwarn, with the context as one JSON field. - Spent tokens are cached under a SHA-256 hash, not MD5, in the application's default cache store.
- The React, Vue and Svelte components are not shipped here. They are the PHP package's, and
props()feeds them the same values.
built and maintained by Edu Lazaro · MIT license