
# Laracaptcha for Laravel Rust
<p align="center">
<a href="https://github.com/edulazaro/laracaptcha-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laracaptcha-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
<a href="https://crates.io/crates/laracaptcha"><img src="https://img.shields.io/crates/v/laracaptcha" alt="Crates.io"></a>
<a href="https://crates.io/crates/laracaptcha"><img src="https://img.shields.io/crates/d/laracaptcha" alt="Downloads"></a>
<a href="https://docs.rs/laracaptcha"><img src="https://img.shields.io/docsrs/laracaptcha" alt="Docs.rs"></a>
<a href="https://github.com/edulazaro/laracaptcha-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laracaptcha" alt="License"></a>
</p>
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](https://github.com/edulazaro/laracaptcha), the PHP package, to
[Laravel Rust](https://laravel.com/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](#differences-from-the-php-package) are collected at the end.
## Installation
```bash
cargo add laracaptcha
```
Register the service provider in `src/app.rs`:
```rust
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:
```env
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:
| `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` |
```rust
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:
```html
<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:
```html
<div id="gameplay-modal" hidden>
<form method="POST" action="/gameplays">
{{ csrf_field() }}
...
{{ laracaptcha_widget(defer=true) }}
<button type="submit">Add</button>
</form>
</div>
```
```js
// 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:
```rust
let captcha = laracaptcha::props(None, Some("login")).await?;
```
The `Captcha` components for React, Vue and Svelte are the PHP package's [`resources/js`](https://github.com/edulazaro/laracaptcha/tree/main/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:
```rust
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:
```rust
#[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`:
```env
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:
```rust
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
```rust
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:
```rust
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:
```rust
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:
```rust
#[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:
<p>
<a href="https://kenodo.com"><img src="art/logo-kenodo.png" width="24" alt="Kenodo"></a> <a href="https://kenodo.com">Kenodo</a>
<a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a> <a href="https://andorradev.com">AndorraDev</a>
<a href="https://duracionde.com"><img src="art/logo-duracionde.png" width="34" alt="DuracionDe"></a> <a href="https://duracionde.com">DuracionDe</a>
</p>
## Author
Created by [Edu Lazaro](https://edulazaro.com)
## License
Laracaptcha for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).