Skip to content

takeshape/use-cap

Repository files navigation

use-cap

A React hook that makes it easy to use the Cap.js proof-of-work abuse prevention library in React projects.

Rationale

This hook adapts and implements the Cap.js widget and worker code and interfaces to make them easier to use in a React application where more control over the UI and implementation are desired. The adapted code replaces the need for workarounds that reference the global Cap.js instance that the widget creates.

Installation and use

npm i @takeshape/use-cap

Below is usage similar to invisible mode.

import { useEffect } from 'react';
import { useCap } from '@takeshape/use-cap';

function MyComponent() {
  const { solve, reset, solving, progress, error, token } = useCap({
    endpoint: "https://my-cap-server.com/api/",
  });

  useEffect(() => {
    if (!token && !error) {
      void solve();
    }
  }, [solve, token, error]);

  return (
    <form onSubmit>
      <h1>use-cap</h1>
      <div>Solving: {solving ? 'true' : 'false'}</div>
      <div>Progress: {progress ?? '???'}</div>
      <div>Token: {token?.token ?? '???'}</div>
      <div>Expires: {token?.expires ?? '???'}</div>

      <button type="button" onClick={() => reset()}>
        Reset
      </button>
    </div>
  );
}

Content Security Policy

You'll likely need the following statements in your CSP:

script-src ... 'wasm-unsafe-eval';
worker-src ... blob:;

Vite Config

If you're using Vite v3 or above, you'll need to prevent it from optimizing this package. It's already optimized!

optimizeDeps: {
  exclude: ['@takeshape/use-cap'],
},

Development

  1. Run a Cap.js standalone server:
docker run -d \
  -p 3000:3000 \
  -v cap-data:/usr/src/app/.data \
  -e ADMIN_KEY=your_secret_key_must_be_30_chars \
  --name cap-standalone \
  tiago2/cap:latest
  1. Go to the Cap dashboard and get your Site Key

  2. Create an environment file:

cp .env.example .env
  1. Set the Cap endpoint in the .env file

  2. Run the development app:

npm run dev

Related & Prior Art

About

Use the Cap.js proof-of-work library easily in React projects. CAPTCHA alternative.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages