Packages

Self-hosted Cap CAPTCHA for Phoenix controllers and LiveView with a bundled WebAssembly solver

Current section

Files

Jump to
phoenix_cap README.md
Raw

README.md

# PhoenixCap

Protect a Phoenix controller or LiveView action with [Cap](https://github.com/tiagozip/cap).
Phoenix serves the widget and its WebAssembly solver, issues challenges, and
verifies one-time tokens. The Hex package includes all browser assets.

I built this because I was tired of wiring the same reCAPTCHA-style flow into
Phoenix apps. Cap has a lovely widget and proof-of-work protocol, but for small
Phoenix projects I did not want to host the full standalone Cap service just to
protect a form. With PhoenixCap I can use the Cap frontend and verify the
result inside Phoenix.

## Installation

To install from GitHub, add this dependency to `mix.exs`.

```elixir
def deps do
  [
    {:phoenix_cap, github: "elchemista/phoenix_cap"}
  ]
end
```

Once version 0.1.0 is available on Hex, you can use `{:phoenix_cap, "~> 0.1.0"}`.
Run `mix deps.get`. The examples below use Elixir 1.19 or later and a Phoenix app
with `phoenix_live_view` for the HEEx components.

## Phoenix setup

In `lib/my_app_web/endpoint.ex`, insert `plug PhoenixCap` immediately before
the existing router plug. PhoenixCap handles `/cap` and its subpaths, including
the widget and WASM assets. All other requests continue to the router.

```elixir
plug PhoenixCap
plug MyAppWeb.Router
```

Load the widget and its stylesheet once in the `<head>` of your root layout.

```heex
<PhoenixCap.Components.assets />
```

For shorter template names, add `alias PhoenixCap.Components, as: Cap` inside
the `quote` in `MyAppWeb.html_helpers/0` in `lib/my_app_web.ex`. You can then
write `<Cap.assets />` and `<Cap.widget id="signup-captcha" />`.

These HEEx helpers use your app's existing `phoenix_live_view` dependency.
For a custom mount, use `plug PhoenixCap, at: "/security/cap"` and pass
`endpoint="/security/cap"` to both `assets` and `widget`. Apps that mount Cap
through their router can use `forward "/cap", PhoenixCap.Plug` outside the
`:browser` pipeline as an alternative to the endpoint plug.

The widget is transparent and inherits the page's text color. Set `--cap-*`
CSS properties to customize it. For example, give a widget an opaque background
by setting these variables in your application stylesheet.

```css
#signup-captcha {
  --cap-background: #162337;
  --cap-color: #f3f6fa;
}
```

### Inside a form

Place the widget inside a Phoenix `<.form>` or an HTML `<form>`. The widget
requires a solve by default and submits the token as the top-level
`cap-token` parameter. Use a unique widget ID for each instance.

```heex
<.form for={@form} action={~p"/signup"} method="post">
  <PhoenixCap.Components.widget id="signup-captcha" />
  <button type="submit">Sign up</button>
</.form>
```

### Controller verification

Add `use PhoenixCap` after your controller setup. Use `:only` when the same
controller displays a form and handles its submission.

```elixir
defmodule MyAppWeb.SignupController do
  use MyAppWeb, :controller
  use PhoenixCap, only: [:create]

  def new(conn, _params) do
    render(conn, :new, form: Phoenix.Component.to_form(%{}, as: :signup))
  end

  def create(conn, _params) do
    # Run your signup logic here. PhoenixCap has already consumed the token.
    send_resp(conn, 200, "Signup verified")
  end
end
```

In the app's `:browser` scope, route `GET /signup` to `:new` and `POST /signup`
to `:create`.

Plain `use PhoenixCap` protects every action in that controller. A failed
check returns HTTP 422. A successful check consumes the token before the
action runs. A declaration in the shared `MyAppWeb.controller/0` quote
applies to every controller that uses it.

For custom error handling or to verify after validating the other fields,
leave the action out of the automatic check and consume the token yourself.

```elixir
case PhoenixCap.verify(conn, params["cap-token"]) do
  :ok -> create_account(conn, params)
  {:error, _reason} -> send_resp(conn, 422, "Complete the CAPTCHA and try again.")
end
```

### LiveView form

A form with `phx-submit` sends `cap-token` to the LiveView automatically.
This example displays a confirmation after the server accepts the token.
The widget gets a fresh DOM ID after a failed check so the user can retry.

```heex
<form :if={!@confirmed?} id="confirm-form" phx-submit="confirm">
  <PhoenixCap.Components.widget id={"confirm-captcha-#{@attempt}"} />
  <button type="submit">Confirm</button>
</form>
<p :if={@confirmed?} role="status">Confirmed.</p>
```

```elixir
def mount(_params, _session, socket) do
  {:ok, assign(socket, confirmed?: false, attempt: 0)}
end

def handle_event("confirm", params, socket) do
  case PhoenixCap.verify(socket, params["cap-token"]) do
    :ok ->
      {:noreply, assign(socket, :confirmed?, true)}

    {:error, _reason} ->
      socket = socket |> update(:attempt, &(&1 + 1)) |> put_flash(:error, "Please verify again.")
      {:noreply, socket}
  end
end
```

Validate any other fields before consuming the token on submit. A `phx-change`
patch preserves the solved widget. If you keep the widget on screen after
consuming the token, call `reset()` before the next submission.

### Outside a form

Pass the form's HTML ID to position the widget separately from the form.

```heex
<.form id="signup-form" for={@form} action={~p"/signup"} method="post">
  <button type="submit">Sign up</button>
</.form>

<PhoenixCap.Components.widget id="signup-captcha" form="signup-form" />
```

### Standalone widget

A widget can also trigger an action directly. Its `solve` event carries
the token in `event.detail.token`. The [JavaScript and LiveView hooks guide](guides/javascript.md)
shows how to send it with `fetch` or `pushEvent`, verify it server-side, and
reset the widget after the response.

In plain HTML, load the assets and render the web component directly.

```html
<link rel="stylesheet" href="/cap/assets/phoenix_cap.css">
<script type="module" src="/cap/assets/phoenix_cap.js"></script>
<phoenix-cap id="signup-captcha" data-cap-api-endpoint="/cap" required></phoenix-cap>
```

The browser loads the WASM solver from the same route. PhoenixCap serves
SHA-256 challenges. If you load the upstream widget from your app bundle,
import `assets/cap.min.js` and include the stylesheet for the adaptive theme.
Cap retired the `cap.compat.min.js` build in widget `0.1.59`.

## Updating bundled assets

Run the following in a PhoenixCap checkout to update the bundled widget
and WASM files to the latest npm releases.

```bash
mix phoenix_cap.update
```

Pass explicit versions to pin the assets.

```bash
mix phoenix_cap.update --widget 0.1.65 --wasm 0.0.8
```

The task records the bundled versions in `assets/VERSIONS`. Pass `--no-wasm`
to refresh only the widget.

## Deployment

Challenges expire after 10 minutes and verification tokens expire after 20
minutes. Both are stored in ETS on the node that issued them. If you run
multiple Phoenix nodes, configure session affinity so the challenge, its
redemption, and the protected request or LiveView connection reach the same
node. A node restart clears its outstanding challenges and tokens.

## Configuration

PhoenixCap uses Elixir's `JSON` module and the Phoenix endpoint's
`Phoenix.Token` signing configuration by default. Use these settings to
override either option.

```elixir
config :phoenix_cap,
  json_library: Jason,
  token_module: Phoenix.Token,
  token_salt: "phoenix-cap-token"
```

Configure a token context to call `PhoenixCap.verify(token)` with a single
argument.

```elixir
config :phoenix_cap,
  token_context: MyAppWeb.Endpoint
```

`token_salt` defaults to `"phoenix-cap-token"`. Changing it invalidates any
Cap verification tokens that have already been issued but not yet verified.

Custom token modules implement the `PhoenixCap.Token` behaviour. Its callbacks
document the return values for signing and verification.

## Credits And License

PhoenixCap is released under the MIT License.

Huge thanks to Tiago and all contributors to the Cap project. This library only
exists because Cap already did the hard, thoughtful work: the widget, the
proof-of-work protocol, the solver, and the clean self-hosted CAPTCHA idea.
PhoenixCap is a small Phoenix-side adapter around that work, not a replacement
for it.

The bundled frontend widget and WASM files in `assets/` come from
`@cap.js/widget` and `@cap.js/wasm`.
Cap is licensed under Apache-2.0; its license is included at
`assets/CAP_WIDGET_LICENSE`.