Usage | laravel-honeypot-rust | Spatie       

 SPATIE  

laravel-honeypot-rust
=====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-honeypot-rust](https://spatie.be/docs/laravel-honeypot-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-honeypot-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-honeypot-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-honeypot-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-honeypot-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-honeypot-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-honeypot-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-honeypot-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Configure a form ](#content-configure-a-form)
2. [ Configuration from the environment ](#content-configuration-from-the-environment)
3. [ Register middleware and templates ](#content-register-middleware-and-templates)
4. [ Use the validation rule ](#content-use-the-validation-rule)
5. [ Handle rejected forms ](#content-handle-rejected-forms)
6. [ Custom checkers, responders, and events ](#content-custom-checkers-responders-and-events)
7. [ Inertia forms ](#content-inertia-forms)

Configure a form
--------------------------------------------------------------------------------------------------------

1. Start with the default protection, then replace the settings as needed:

```
use std::time::Duration;
use spatie_honeypot::{Config, Honeypot};

let honeypot = Honeypot::new(encrypter).configure(Config {
    name_field: "contact_name".into(),
    timing_field: "form_time".into(),
    scope: "register".into(),
    minimum_age: Duration::from_secs(2),
    maximum_age: Duration::from_secs(3600),
    ..Config::default()
})?;
```

2. Choose field names and a time window:

- Names must begin with an ASCII letter, contain only ASCII letters, digits, or underscores, and be at most 64 bytes long.
- The names must differ and neither may start with the other's underscore prefix. Their exact names, underscore prefixes, and bracketed forms are reserved for protection. Ordinary fields such as `name`, `newsletter`, and `my_nameish` are not reserved by the defaults.
- The maximum age must be positive and at least the minimum age. Both boundaries are inclusive, compared in nanoseconds without whole-second rounding.
- Precision is limited by the framework's platform clock; Windows `SystemTime` uses 100-nanosecond ticks. Clock rollback rejects the token until its minimum age is reached. Keep server clocks synchronized.

3. Change only the switches your form needs:

- `enabled: false` disables generation and checking.
- `randomize_name: false` uses the exact configured trap name but still authenticates it in the timing token.
- `required: false` permits a request only when both protection fields are absent; a partially supplied pair still fails. Keep `required: true` on registration routes.
- `check_timing: false` checks only the empty trap. The trap remains required unless `required` is also false. Missing, malformed, or future timing tokens are ignored in this mode. Rendered fields keep the same shape.

Configuration from the environment
--------------------------------------------------------------------------------------------------------------------------------------------------------------

1. Register the service provider to load a typed config section from the framework's environment:

```
use laravel::Application;
use spatie_honeypot::{Config, service_provider};

let app = Application::configure()
    .with_providers(|providers| {
        providers.add(service_provider());
    })
    .create();
let settings = app.config().section::<Config>().clone();
```

2. Override defaults in `with_config` and pass the section to `Honeypot::configure` for each independent form. The provider also binds a shared injectable `Honeypot`. Without the provider, call `config.set(Config::from_env(env))` yourself. The framework validates malformed environment values at startup.
3. Set any of these environment options:

- `HONEYPOT_ENABLED` sets `enabled`, default `true`.
- `HONEYPOT_FIELDS_REQUIRED` sets `required`, default `true`. Set `false` for middleware covering forms without honeypot fields.
- `HONEYPOT_NAME` sets `name_field`, default `my_name`.
- `HONEYPOT_RANDOMIZE` sets `randomize_name`, default `true`.
- `HONEYPOT_VALID_FROM_TIMESTAMP` sets `check_timing`, default `true`.
- `HONEYPOT_VALID_FROM` sets `timing_field`, default `valid_from`.
- `HONEYPOT_SECONDS` sets `minimum_age` in seconds, default `1`.
- `HONEYPOT_MAX_SECONDS` sets `maximum_age` in seconds, default `7200`.
- `HONEYPOT_SCOPE` sets `scope`, default `honeypot`.

Register middleware and templates
-----------------------------------------------------------------------------------------------------------------------------------------------------------

1. Attach `ProtectAgainstSpam::new(honeypot.clone())` to the POST route. Register the MiniJinja helper through `views.minijinja(move |environment| honeypot.register(environment))`. The [README](../README) has a complete registration example.
2. Render `{{ honeypot_fields() }}` and `{{ csrf_field() }}` inside the form. Each render generates a fresh token and randomized name. The helper returns already-escaped, safe HTML. It needs no `|safe` filter and uses no inline styles or scripts. Inputs are inside a `hidden` container with `aria-hidden="true"` and have `tabindex="-1"`.
3. For a custom template, call `honeypot.fields()?` in a request or application scope. Pass the serializable `Fields` to your template. Its fields are `enabled`, `name_field`, `timing_field`, and `token`. `Fields::html()` returns a MiniJinja safe value. Escape attributes when writing your own markup; never turn arbitrary user HTML into a safe value.

- `Honeypot::fields()` returns `Result<Fields, laravel::crypt::EncryptError>`. Use `?` in framework handlers to convert it into a native application error. Template errors retain the encryption error as their source.
- Middleware reads through `Request::load_input()`, respecting the framework's body and field-count limits. URL-encoded and JSON bodies are checked before normalization can hide duplicate protection names or whitespace. Cached input and raw bytes remain readable downstream. Query parameters cannot replace body fields.
- Multipart requests use native upload decoding and validation, including uploaded files. A file cannot replace a trap or timing token. Multipart values have already passed through the application's normal trimming/null conversion and duplicate handling. Configure input normalization separately if your application must distinguish raw whitespace in multipart fields.

Use the validation rule
-----------------------------------------------------------------------------------------------------------------------------

1. Attach `Honeypot` as an implicit `ValidationRule` to your configured timing field:

```
async fn register(request: Request, honeypot: Honeypot) -> laravel::Result<String> {
    let form = request.validate_with::<Registration>(|rules| {
        rules.field("valid_from", [Rule::custom(honeypot)])
    }).await?;

    Ok(format!("Received {}", form.name))
}
```

2. Use middleware for untrusted browser forms:

- The rule runs when the timing field is absent or blank and checks the complete input tree. Arrays, objects, numbers, booleans, and uploaded files cannot stand in for a trap or token. Null and exactly empty text are accepted in the trap.
- A rule sees values after framework normalization. It cannot recover duplicate scalar fields already discarded by a parser or distinguish whitespace that earlier middleware converted to null. Use `ProtectAgainstSpam` when those distinctions matter.
- Rule failures use the framework's normal validation response, including redirects for session forms and 422 JSON responses for API clients. Operational errors retain their own status.

Handle rejected forms
-----------------------------------------------------------------------------------------------------------------------

- The default `BlankPageResponder` returns an empty 200 response without running the handler.
- Add `.respond_with(spatie_honeypot::RejectSpam)` for 422 with `This form could not be accepted. Reload the page and try again.` Neither built-in responder flashes input or reveals the rejection reason.
- Body parsing failures may return 400 or 413; unsupported POST content types return 415 through the framework's error handler. Other HTTP methods are not protected.
- `Honeypot::check(&InputObject)` returns a typed `Spam` reason without changing input. Do not log raw requests, timing tokens, or encryption keys to diagnose spam.
- Exclude forms containing these fields from shared response caches. Tokens are stateless and can be replayed within their lifetime, so use CSRF and throttling separately. Rotating keys invalidates existing forms unless their key remains in the framework's previous-key configuration.

Custom checkers, responders, and events
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1. Implement `SpamProtection` to replace the checker and `SpamResponder` to replace the response. Pass application-owned instances to `ProtectAgainstSpam::new(checker).respond_with(responder)`. Constructors can carry application-specific options or services. Cloning middleware shares the checker; it does not require the checker to implement `Clone`.

```
use laravel::http::{Next, Request, Response};
use spatie_honeypot::SpamResponder;

struct CustomResponder;

impl SpamResponder for CustomResponder {
    async fn respond(&self, _request: Request, _next: Next) -> laravel::Result<Response> {
        Ok(Response::new("Please reload this form.").with_status(403))
    }
}
```

2. Register listeners with the application's `with_events` callback:

- A responder receives the request and `Next`; it may deliberately continue the pipeline.
- Every failed middleware check first awaits `laravel::event::dispatch(SpamDetectedEvent { ... })`. Listener errors propagate.
- The event contains `method`, `path`, and typed `reason`, not the body, query string, encryption key, or token.
- Direct `Honeypot::check` calls and the validation rule do not dispatch middleware events.

Inertia forms
-----------------------------------------------------------------------------------------------

1. Enable this package's `inertia` feature alongside your application's native Inertia middleware. Pass the serializable fields as a page prop:

```
use laravel::inertia::{self, props};

let page = inertia::render("Contact", props! {
    honeypot => honeypot.fields()?,
});
```

2. Initialize the client form key named by `honeypot.name_field` to `""` and the key named by `honeypot.timing_field` to `honeypot.token`.
3. Submit those values with the normal JSON form data to a POST route using the same protection settings. Do not regenerate the token during submission.
4. Use `RejectSpam` or an application responder if the frontend needs an explicit failure status.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
