PHPackages                             oliweb/laravel-cap - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. oliweb/laravel-cap

ActiveLibrary[Security](/categories/security)

oliweb/laravel-cap
==================

Laravel wrapper for Cap (tiagozip/cap) — self-hosted CAPTCHA alternative

v1.8.4(1mo ago)1571MITPHPPHP ^8.2

Since May 7Pushed 2mo agoCompare

[ Source](https://github.com/oli217/laravel-cap)[ Packagist](https://packagist.org/packages/oliweb/laravel-cap)[ RSS](/packages/oliweb-laravel-cap/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (8)Versions (21)Used By (1)

laravel-cap
===========

[](#laravel-cap)

A Laravel wrapper for [Cap](https://github.com/tiagozip/cap) — the self-hosted, privacy-friendly CAPTCHA alternative based on Proof-of-Work.

Cap works without tracking, cookies, or third-party services. This package integrates server-side token verification into Laravel through a service, a facade, a middleware, a validation rule, and Blade directives.

Requirements
------------

[](#requirements)

- PHP **^8.2**
- Laravel **11, 12, or 13**
- A running [Cap instance](https://trycap.dev/guide/) (self-hosted via Docker)

Installation
------------

[](#installation)

```
composer require oliweb/laravel-cap
```

The service provider and facade are registered automatically via Laravel's package auto-discovery.

Publish the configuration file:

```
php artisan vendor:publish --tag=cap-config
```

Publish the JS, CSS, and WASM assets (required for `@capScripts` and `@capStyles`):

```
php artisan vendor:publish --tag=cap-assets
```

This publishes the following files to `public/vendor/cap/`:

FileDescription`cap-widget.js`Cap widget (custom element + programmatic API)`cap-widget.css`Default widget styles`cap_wasm_bg.wasm`WebAssembly module for proof-of-work (served locally, no CDN required)Publish the translation files (optional — to override messages):

```
php artisan vendor:publish --tag=cap-lang
```

Configuration
-------------

[](#configuration)

Add the following variables to your `.env` file:

```
CAP_ENDPOINT=https://cap.example.com/your-site-key/
CAP_SECRET=your-secret-key
CAP_TOKEN_FIELD=cap-token
CAP_TIMEOUT=5
CAP_FAIL_OPEN=false
```

VariableDescriptionDefault`CAP_ENDPOINT`Full URL of your Cap instance including the site key (trailing slash required)—`CAP_SECRET`Secret key from your Cap dashboard—`CAP_TOKEN_FIELD`Name of the hidden field injected by the Cap widget`cap-token``CAP_TIMEOUT`HTTP timeout in seconds for the `/siteverify` request`5``CAP_FAIL_OPEN`When `true`, let requests through on network/server errors (see below)`false`### Fail-open mode

[](#fail-open-mode)

By default, any communication error with the Cap instance (network failure, timeout, HTTP 5xx) blocks the request, just like an invalid token would.

Setting `CAP_FAIL_OPEN=true` inverts this: communication errors silently pass, so a Cap outage does not take your forms down with it.

**An explicitly invalid token (`success: false`) is always rejected regardless of this setting.** Fail-open only covers infrastructure failures, not verification failures.

Translations
------------

[](#translations)

Server-side messages (validation rule, middleware) are translatable. English and French are included out of the box.

To override or add a language, publish the translation files and edit `lang/vendor/cap/{locale}/messages.php`:

```
php artisan vendor:publish --tag=cap-lang
```

```
// lang/vendor/cap/fr/messages.php
return [
    'validation_failed' => 'La vérification :attribute a échoué. Veuillez réessayer.',
    'middleware_failed'  => 'La vérification Cap a échoué.',
];
```

Laravel selects the right file automatically based on `App::getLocale()`.

Widget styling
--------------

[](#widget-styling)

Edit `public/vendor/cap/cap-widget.css` to override the CSS custom properties exposed by the widget:

```
cap-widget {
    --cap-color-primary:  #6366f1;
    --cap-color-success:  #22c55e;
    --cap-border-radius:  0.5rem;
    --cap-font-family:    inherit;
    /* ... */
}
```

Usage
-----

[](#usage)

### Blade directives

[](#blade-directives)

DirectiveDescription`@cap`Renders `` with the configured endpoint`@capScripts`Injects `window.CAP_CUSTOM_WASM_URL` + `` for the widget`@capStyles``` loading the theme from `public/vendor/cap/cap-widget.css``@capConfig``` exposing `window.CAP_API_ENDPOINT` and `window.CAP_TOKEN_FIELD`#### Standard widget mode

[](#standard-widget-mode)

Include the Cap widget in any Blade form:

```
@capStyles
@capScripts

    @csrf
    @cap
    Submit

```

The widget automatically injects a hidden `cap-token` field (or the value of `CAP_TOKEN_FIELD`) into its parent form upon successful verification.

`@capScripts` always injects `window.CAP_CUSTOM_WASM_URL` pointing to the locally published WASM, so no external CDN is contacted at runtime.

#### Programmatic mode

[](#programmatic-mode)

Use `@capConfig` to expose the endpoint to JavaScript, then instantiate `Cap` directly without rendering a visible widget:

```
@capConfig
@capScripts

    @csrf

    Submit

document.getElementById('submit-btn').addEventListener('click', async (e) => {
    e.preventDefault();

    const cap = new Cap({ apiEndpoint: window.CAP_API_ENDPOINT });
    const { token } = await cap.solve();

    document.getElementById('cap-token').value = token;
    e.target.closest('form').submit();
});

```

`Cap` creates a hidden `cap-widget` element in the background and exposes a `solve()` method that returns `{ token }`. No visible widget is rendered.

`window.CAP_API_ENDPOINT` and `window.CAP_TOKEN_FIELD` are set by `@capConfig` from your PHP configuration, so you never need to hard-code the endpoint in JavaScript.

#### CSP nonce support

[](#csp-nonce-support)

All directives accept an optional nonce for strict Content Security Policies:

```
@capConfig(Vite::cspNonce())
@capScripts(Vite::cspNonce())
@cap(Vite::cspNonce())
```

`@cap` passes the nonce as `data-cap-csp-nonce` on the widget element, which Cap uses internally for its workers and inline scripts.

#### CSP headers

[](#csp-headers)

Cap's widget relies on Web Workers and WebAssembly. A strict CSP must account for this:

```
Content-Security-Policy:
  script-src 'nonce-{nonce}' 'strict-dynamic';
  worker-src blob:;
  wasm-unsafe-eval;
  connect-src 'self';

```

`worker-src blob:` — required because the widget spawns workers via `Blob` URLs. `wasm-unsafe-eval` — required for the WebAssembly hash computation. `connect-src 'self'` — sufficient for WASM since assets are served locally after `vendor:publish`.

### Middleware

[](#middleware)

Protect any route by applying the `cap.verify` middleware:

```
Route::post('/contact', [ContactController::class, 'store'])
    ->middleware('cap.verify');
```

Returns HTTP `422` with the message `Cap verification failed.` if the token is missing or invalid.

### Validation rule

[](#validation-rule)

Use `CapRule` inside a Form Request or an inline validator:

```
use LaravelCap\Rules\CapRule;

public function rules(): array
{
    return [
        'cap-token' => ['required', new CapRule],
        // other fields...
    ];
}
```

### Facade

[](#facade)

```
use LaravelCap\Facades\Cap;

if (Cap::verify($request->input('cap-token'))) {
    // token is valid
}
```

### Service (dependency injection)

[](#service-dependency-injection)

```
use LaravelCap\Cap;

class ContactController extends Controller
{
    public function __construct(private readonly Cap $cap) {}

    public function store(Request $request): RedirectResponse
    {
        $this->cap->verifyOrFail($request->input('cap-token'));
        // ...
    }
}
```

`verifyOrFail()` throws a `CapVerificationException` if the token is invalid.

Testing
-------

[](#testing)

```
composer install
./vendor/bin/phpunit
```

License
-------

[](#license)

MIT

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance88

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

20

Last Release

38d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/48fcf1e2370bf67b2856e949261d339ac202fd5cc67235225f9297bd39faef84?d=identicon)[oliweb](/maintainers/oliweb)

---

Top Contributors

[![oli217](https://avatars.githubusercontent.com/u/83109898?v=4)](https://github.com/oli217 "oli217 (2 commits)")

---

Tags

laravelcaptchaspam protectionproof-of-workcap

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/oliweb-laravel-cap/health.svg)

```
[![Health](https://phpackages.com/badges/oliweb-laravel-cap/health.svg)](https://phpackages.com/packages/oliweb-laravel-cap)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77922.3M186](/packages/laravel-mcp)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
