### Install @cap.js/server with npm
Source: https://trycap.dev/guide/server
Install the server-side library using npm.
```bash
npm i @cap.js/server
```
--------------------------------
### Install @cap.js/server with Bun
Source: https://trycap.dev/guide/server
Install the server-side library using Bun.
```bash
bun add @cap.js/server
```
--------------------------------
### Install @cap.js/server with pnpm
Source: https://trycap.dev/guide/server
Install the server-side library using pnpm.
```bash
pnpm i @cap.js/server
```
--------------------------------
### Install @cap.js/solver with Bun
Source: https://trycap.dev/guide/solver
Use this command to add the solver library to your project when using Bun.
```bash
bun add @cap.js/solver
```
--------------------------------
### Initialize Cap Server with Postgres DB
Source: https://trycap.dev/guide/server
Set up Cap server with a Postgres database using Bun's SQL module. This example demonstrates creating tables for challenges and tokens and initializing the Cap instance with custom storage functions.
```javascript
import Cap from "@cap.js/server";
import { SQL } from "bun";
const db = new SQL(`postgres://user:password@localhost:5432/dbname`);
await db`
CREATE TABLE IF NOT EXISTS challenges (
token TEXT PRIMARY KEY,
data JSONB NOT NULL,
expires BIGINT NOT NULL
);
`;
await db`
CREATE TABLE IF NOT EXISTS tokens (
key TEXT PRIMARY KEY,
expires BIGINT NOT NULL
);
`;
const cap = new Cap({
storage: {
challenges: {
store: async (token, challengeData) => {
await db`
INSERT INTO challenges (token, data, expires)
VALUES (${token}, ${challengeData}, ${challengeData.expires})
ON CONFLICT (token)
DO UPDATE SET
data = EXCLUDED.data,
expires = EXCLUDED.expires
`;
},
read: async (token) => {
const [row] = await db`
SELECT data, expires
FROM challenges
WHERE token = ${token}
AND expires > ${Date.now()}
LIMIT 1
`;
return row ? { challenge: row.data, expires: Number(row.expires) } : null;
},
delete: async (token) => {
await db`
DELETE FROM challenges
WHERE token = ${token}
`;
},
deleteExpired: async () => {
await db`
DELETE FROM challenges
WHERE expires <= ${Date.now()}
`;
},
},
tokens: {
store: async (tokenKey, expires) => {
await db`
INSERT INTO tokens (key, expires)
VALUES (${tokenKey}, ${expires})
ON CONFLICT (key)
DO UPDATE SET
expires = EXCLUDED.expires
`;
},
get: async (tokenKey) => {
const [row] = await db`
SELECT expires
FROM tokens
WHERE key = ${tokenKey}
AND expires > ${Date.now()}
LIMIT 1
`;
return row ? Number(row.expires) : null;
},
delete: async (tokenKey) => {
await db`
DELETE FROM tokens
WHERE key = ${tokenKey}
`;
},
deleteExpired: async () => {
await db`
DELETE FROM tokens
WHERE expires <= ${Date.now()}
`;
},
},
},
});
export default cap;
```
--------------------------------
### Install Cap Widget with bun
Source: https://trycap.dev/guide/widget
Use this command to add the cap-widget package to your project when using bun.
```sh
bun add cap-widget
```
--------------------------------
### Start Cap Standalone Docker Containers
Source: https://trycap.dev/guide/standalone/index.html
Command to launch the Cap Standalone and Valkey services defined in the docker-compose.yml file.
```bash
docker compose up -d
```
--------------------------------
### Install Cap Widget with npm
Source: https://trycap.dev/guide/widget
Use this command to add the cap-widget package to your project when using npm.
```sh
npm i cap-widget
```
--------------------------------
### Instantiate Cap and Solve Challenge
Source: https://trycap.dev/guide/programmatic
Use `new Cap()` to create an instance and `solve()` to get the challenge token. Ensure the `apiEndpoint` is correctly configured.
```javascript
const cap = new Cap({
apiEndpoint: "/api/",
});
const solution = await cap.solve();
console.log(solution.token);
```
--------------------------------
### Install Cap Widget with pnpm
Source: https://trycap.dev/guide/widget
Use this command to add the cap-widget package to your project when using pnpm.
```sh
pnpm add cap-widget
```
--------------------------------
### Integrate Cap with Fastify
Source: https://trycap.dev/guide/server
Set up Cap routes for challenge creation and redemption using the Fastify framework. This example includes basic error handling for missing request body parameters.
```javascript
import Fastify from "fastify";
import cap from "../cap.js";
const fastify = Fastify();
fastify.post("/cap/challenge", async (req, res) => {
res.send(await cap.createChallenge());
});
fastify.post("/cap/redeem", async (req, res) => {
const { token, solutions } = req.body;
if (!token || !solutions) {
return res.code(400).send({ success: false });
}
res.send(await cap.redeemChallenge({ token, solutions }));
});
fastify.listen({ port: 3000 });
```
--------------------------------
### Solver Output Example
Source: https://trycap.dev/guide/solver
The output from the solver function when processing challenges is an array of numbers, representing the solutions.
```json
[
67302, 64511, 40440, 27959, 71259 /* ... */
]
```
--------------------------------
### Set Docker Volume Permissions
Source: https://trycap.dev/guide/standalone/options
Ensure the data directory is writable by UID 1000 for the Docker container. This example creates a directory and sets ownership.
```bash
mkdir -p ./cap-data
sudo chown 1000:1000 ./cap-data
```
--------------------------------
### Docker Compose Volume Mount
Source: https://trycap.dev/guide/standalone/options
Example Docker Compose configuration to mount a host directory to the container's data path.
```yaml
services:
cap:
image: tiago2/cap:latest
volumes:
- ./cap-data:/usr/src/app/data
# ...
```
--------------------------------
### Vanilla JavaScript Usage
Source: https://trycap.dev/guide/widget
Integrate the Cap widget into a form using Vanilla JavaScript. The widget automatically handles token submission when inside a form. Listen for the 'solve' event to get the challenge token.
```html
```
--------------------------------
### Vue Usage
Source: https://trycap.dev/guide/widget
Integrate the Cap widget into a Vue.js application. Use '@solve', '@progress', and '@error' for event handling. If you encounter 'unknown-component' warnings, configure Vite to recognize custom elements starting with 'cap-'.
```vue
```
```js
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: { isCustomElement: (tag) => tag.startsWith("cap-") },
},
}),
],
});
```
--------------------------------
### Instantiate Cap and Solve Challenge
Source: https://trycap.dev/guide/programmatic
Demonstrates how to create a Cap instance with a specified API endpoint and solve a challenge.
```APIDOC
## POST /api/solve (Implicit)
### Description
Creates a Cap instance and solves a challenge using the provided API endpoint.
### Method
POST (Implicitly used by `cap.solve()`)
### Endpoint
`/api/` (specified during instantiation)
### Parameters
#### Constructor Arguments
- **apiEndpoint** (string) - Required - The API endpoint for solving challenges.
- **workers** (number) - Optional - The number of worker threads to use. Defaults to `navigator.hardwareConcurrency || 8`.
### Request Example
```javascript
const cap = new Cap({
apiEndpoint: "/api/"
});
const solution = await cap.solve();
console.log(solution.token);
```
### Response
#### Success Response (200)
- **token** (string) - The solution token for the challenge.
```
--------------------------------
### Import Cap Library and Floating Script (Standalone Server)
Source: https://trycap.dev/guide/floating
Use these script tags to load the Cap widget and floating mode scripts from your standalone server. Replace `` with your server's address.
```html
```
--------------------------------
### Event Listeners
Source: https://trycap.dev/guide/programmatic
Shows how to set up event listeners for the Cap instance to track progress.
```APIDOC
## Event Listener for Progress
### Description
Attaches an event listener to the Cap instance to receive progress updates during the challenge solving process.
### Method
`cap.addEventListener(type, listener)`
### Endpoint
N/A (Instance method)
### Parameters
#### Event Listener Arguments
- **type** (string) - Required - The name of the event to listen for (e.g., "progress").
- **listener** (function) - Required - The callback function to execute when the event is triggered.
- **event** (object) - The event object containing details.
- **detail.progress** (number) - The current progress percentage.
### Request Example
```javascript
const cap = new Cap({
apiEndpoint: "/api/"
});
cap.addEventListener("progress", (event) => {
console.log(`Solving... ${event.detail.progress}% done`);
});
```
### Response
N/A (This method handles events, it does not return a direct response.)
```
--------------------------------
### Cap Instance Methods
Source: https://trycap.dev/guide/programmatic
Details on the available methods for interacting with a Cap instance.
```APIDOC
## Cap Instance Methods
### Description
Provides an overview of the methods available on a Cap instance for managing challenges and tokens.
### Methods
#### `new Cap({ apiEndpoint, workers })`
- **Description**: Creates a new Cap instance. Optionally accepts an element to use instead of creating one in memory.
- **Arguments**:
- **apiEndpoint** (string) - Required - The API endpoint for solving challenges.
- **workers** (number) - Optional - The number of worker threads to use. Defaults to `navigator.hardwareConcurrency || 8`.
#### `cap.solve()`
- **Description**: Requests and solves a challenge.
- **Output**: `{ token }`
#### `cap.token`
- **Description**: Returns the token from the latest solve.
#### `cap.reset()`
- **Description**: Resets `cap.token`.
#### `cap.addEventListener(type, listener)`
- **Description**: Listens for an event for the cap widget. See supported events.
```
--------------------------------
### Cap Initialization
Source: https://trycap.dev/guide/server
Initialize a new Cap instance with custom configuration options. The configuration object allows for customization of storage, state, and other behaviors.
```APIDOC
## `new Cap({ ... })`
### Description
Initializes a new Cap instance with optional configuration.
### Arguments
`config` (object) - Configuration options for the Cap instance.
#### Configuration Options
- **`disableAutoCleanup`** (boolean) - Optional - If true, automatic cleanup of expired challenges and tokens will be disabled. Defaults to `false`.
- **`storage`** (object) - Optional - Defines custom storage mechanisms for challenges and tokens. Each storage type (e.g., `challenges`, `tokens`) can have `store`, `read`, `delete`, and `deleteExpired` async methods.
- **`storage.challenges.store`** (function) - Async function to store challenge data.
- **`storage.challenges.read`** (function) - Async function to read challenge data.
- **`storage.challenges.delete`** (function) - Async function to delete challenge data.
- **`storage.challenges.deleteExpired`** (function) - Async function to delete expired challenge data.
- **`storage.tokens.store`** (function) - Async function to store token data.
- **`storage.tokens.get`** (function) - Async function to retrieve token data.
- **`storage.tokens.delete`** (function) - Async function to delete token data.
- **`storage.tokens.deleteExpired`** (function) - Async function to delete expired token data.
- **`state`** (object) - Optional - An object to hold the current state of challenges and tokens.
- **`state.challengesList`** (object) - Stores challenge data.
- **`state.tokensList`** (object) - Stores token data.
### Accessing Configuration
Configuration can be accessed and modified via `cap.config`.
### Example
```javascript
const cap = new Cap({
disableAutoCleanup: true,
storage: {
tokens: {
store: async (tokenKey, expires) => { /* custom store logic */ },
get: async (tokenKey) => { /* custom get logic */ },
delete: async (tokenKey) => { /* custom delete logic */ },
deleteExpired: async () => { /* custom delete expired logic */ }
}
}
});
```
```
--------------------------------
### Initialize Cap with Options
Source: https://trycap.dev/guide/server
Configure the Cap class with various options for storage, state management, and cleanup behavior. The `cap.config` object can be used to access or modify these options after initialization.
```json
{
"disableAutoCleanup": false,
"storage": {
"challenges": {
"store": "async (token, challengeData) => {}",
"read": "async (token) => {}",
"delete": "async (token) => {}",
"deleteExpired": "async () => {}"
},
"tokens": {
"store": "async (tokenKey, expires) => {}",
"get": "async (tokenKey) => {}",
"delete": "async (tokenKey) => {}",
"deleteExpired": "async () => {}"
}
},
"state": {
"challengesList": {},
"tokensList": {}
}
// deprecated:
// used for json keyval storage
// "tokens_store_path": ".data/tokensList.json",
// disables all filesystem operations, usually used alongside editing the state
// "noFSState": false,
}
```
--------------------------------
### Cap Event Listener for Progress
Source: https://trycap.dev/guide/programmatic
Set up an event listener for the 'progress' event to monitor the challenge solving process. The event detail includes the current progress percentage.
```javascript
const cap = new Cap({
apiEndpoint: "/api/",
});
cap.addEventListener("progress", (event) => {
console.log(`Solving... ${event.detail.progress}% done`);
});
```
--------------------------------
### Custom Fetch Function for Cap Widget
Source: https://trycap.dev/guide/widget
Configure a custom fetch function by assigning it to `window.CAP_CUSTOM_FETCH`. This allows for custom network request handling.
```js
window.CAP_CUSTOM_FETCH = (url, params) => fetch(url, params);
```
--------------------------------
### Import Cap Library and Floating Script (JSDelivr)
Source: https://trycap.dev/guide/floating
Include these script tags in your HTML to enable the Cap widget and its floating mode functionality when using JSDelivr.
```html
```
--------------------------------
### Cap Constructor Arguments
Source: https://trycap.dev/guide/programmatic
Configure the Cap instance using an options object. The `apiEndpoint` is required, and `workers` can be specified to control the number of worker threads.
```json
{
apiEndpoint: ..., // api endpoint, similar to the widget `data-cap-api-endpoint` attribute
workers: navigator.hardwareConcurrency || 8 // number of worker threads to use
}
```
--------------------------------
### Solve Cap Challenges from Seeded Tokens
Source: https://trycap.dev/guide/solver
Import and use the solver function with a challenge token and configuration object. The configuration specifies challenge count, salt size, and difficulty.
```javascript
import solver from "@cap.js/solver";
console.log(
await solver("challenge token", {
c: 50, // challenge count
s: 32, // salt size
d: 4, // difficulty
}),
);
```
--------------------------------
### Create a Challenge
Source: https://trycap.dev/guide/server
Generate a new challenge with specified parameters such as count, size, difficulty, and expiration time. The response includes the challenge details and a token.
```json
{
"challengeCount": 50,
"challengeSize": 32,
"challengeDifficulty": 4,
"expiresMs": 600000
}
```
--------------------------------
### Integrate Cap with Elysia
Source: https://trycap.dev/guide/server
Expose Cap challenge and redeem routes using the Elysia framework. This snippet shows how to set up POST endpoints for creating challenges and redeeming tokens.
```javascript
import { Elysia } from "elysia";
import cap from "./cap.js";
new Elysia()
.post("/cap/challenge", async () => {
return await cap.createChallenge();
})
.post("/cap/redeem", async ({ body, set }) => {
const { token, solutions } = body;
if (!token || !solutions) {
set.status = 400;
return { success: false };
}
return await cap.redeemChallenge({ token, solutions });
})
.listen(3000);
```
--------------------------------
### Include Widget Script
Source: https://trycap.dev/guide/standalone/options
Use this script tag to include the Cap widget in your application. Replace with your server's address.
```html
```
--------------------------------
### Accessing API Documentation
Source: https://trycap.dev/guide/standalone/api
You can view a list of all available API endpoints and their required request bodies by navigating to the Swagger UI at this address.
```http
http://localhost:3000/swagger
```
--------------------------------
### Docker Compose for Cap Standalone
Source: https://trycap.dev/guide/standalone/index.html
Defines services for Cap and Valkey in Docker Compose. Ensure ADMIN_KEY is kept secret and consider changing the default port if necessary.
```yaml
services:
cap:
image: tiago2/cap:latest
container_name: cap
ports:
- "3000:3000"
environment:
ADMIN_KEY: your_secret_password
REDIS_URL: redis://valkey:6379
depends_on:
valkey:
condition: service_healthy
restart: unless-stopped
valkey:
image: valkey/valkey:9-alpine
container_name: cap-valkey
volumes:
- valkey-data:/data
command: valkey-server --save 60 1 --loglevel warning --maxmemory-policy noeviction
healthcheck:
test: ["CMD", "valkey-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
restart: unless-stopped
volumes:
valkey-data:
```
--------------------------------
### SolidJS Usage
Source: https://trycap.dev/guide/widget
Add the Cap widget to a SolidJS application. Event handlers are passed using the 'on:' prefix, such as 'on:solve'.
```jsx
import "cap-widget";
export default function ContactForm() {
return (
);
}
```
--------------------------------
### Solve Cap Challenges from a List
Source: https://trycap.dev/guide/solver
Provide an array of challenge tokens and their corresponding salts to the solver function. This is useful for batch processing multiple challenges.
```javascript
import solver from "@cap.js/solver";
const challenges = [
["a5b6fda4aaed97cf61d7dd9259f733b5", "d455"],
["286bcc39249f9ee698314b600c32e40f", "f0ff"],
["501350aa7c46573cb604284554045703", "4971"],
["a55c02f3b9b4cd088a5a7ee3d4941c14", "eab7"],
["5f3362c12e2779f56f4ef75b4494f5e6", "999f"],
/* ... */
];
console.log(await solver(challenges));
```
--------------------------------
### Include Cap Widget via CDN
Source: https://trycap.dev/guide/widget
Include the Cap widget script in your HTML using a CDN. It's recommended to pin a specific version for production. Note that cdn.jsdelivr.net might be blocked in some regions.
```html
```
--------------------------------
### Include Floating Widget Script
Source: https://trycap.dev/guide/standalone/options
Use this script tag for the floating mode of the Cap widget. Replace with your server's address.
```html
```
--------------------------------
### Verify CAPTCHA Token with cURL
Source: https://trycap.dev/guide.html
Use this cURL command to send a POST request to your instance's /siteverify endpoint to verify a CAPTCHA token. Ensure you replace placeholders with your actual instance URL, site key, secret key, and the CAPTCHA token.
```sh
curl "https:////siteverify" \
-X POST \
-H "Content-Type: application/json" \
-d '{ "secret": "", "response": "" }'
```
--------------------------------
### Create Challenge API
Source: https://trycap.dev/guide/server
Creates a new challenge with specified parameters. This is used to generate a challenge that the client must solve.
```APIDOC
## `await cap.createChallenge({ ... })`
### Description
Creates a new challenge with specified parameters.
### Method
`await`
### Arguments
`options` (object) - Parameters for creating the challenge.
#### Options
- **`challengeCount`** (number) - Optional - The number of items in the challenge. Defaults to 50.
- **`challengeSize`** (number) - Optional - The size of each item in the challenge. Defaults to 32.
- **`challengeDifficulty`** (number) - Optional - The difficulty level of the challenge. Defaults to 4.
- **`expiresMs`** (number) - Optional - The expiration time of the challenge in milliseconds. Defaults to 600000 (10 minutes).
### Response
Returns an object containing the challenge details.
#### Success Response
- **`challenge`** (string) - The challenge data.
- **`token`** (string) - A token associated with the challenge.
- **`expires`** (number) - The expiration timestamp of the challenge.
### Example
```javascript
const result = await cap.createChallenge({
challengeCount: 100,
challengeSize: 64,
challengeDifficulty: 5,
expiresMs: 300000
});
console.log(result); // { challenge: '...', token: '...', expires: 1678886400000 }
```
```
--------------------------------
### Redeem a Challenge
Source: https://trycap.dev/guide/server
Submit solutions to redeem a challenge. This requires the token and the solutions provided.
```json
{
token,
solutions
}
```
--------------------------------
### API Authentication Header
Source: https://trycap.dev/guide/standalone/api
Include this Authorization header in your API requests to authenticate with your Cap Standalone server. Replace YOUR_API_KEY with your actual API key.
```http
Authorization: Bot YOUR_API_KEY
```
--------------------------------
### Integrate Cap with Express
Source: https://trycap.dev/guide/server
Integrate Cap with an Express backend by defining POST routes for challenge creation and token redemption. Ensure JSON parsing is enabled.
```javascript
import express from "express";
import cap from "./cap.js";
const app = express();
app.use(express.json());
app.post("/cap/challenge", async (req, res) => {
res.json(await cap.createChallenge());
});
app.post("/cap/redeem", async (req, res) => {
const { token, solutions } = req.body;
if (!token || !solutions) {
return res.status(400).json({ success: false });
}
res.json(await cap.redeemChallenge({ token, solutions }));
});
app.listen(3000);
```
--------------------------------
### Svelte 5 Usage
Source: https://trycap.dev/guide/widget
Incorporate the Cap widget into a Svelte 5 application. Use 'on:solve', 'on:progress', and 'on:error' for event listeners.
```svelte
```
--------------------------------
### Handle Cap Token with JavaScript
Source: https://trycap.dev/guide.html
Listens for the 'solve' event on the Cap widget to capture the generated token. This token can then be used for form submission or other verification processes.
```js
const widget = document.querySelector("cap-widget");
widget.addEventListener("solve", function (e) {
const token = e.detail.token;
// Handle the token as needed
});
```
--------------------------------
### Cap Widget Integration
Source: https://trycap.dev/guide/standalone/index.html
HTML snippet to embed the Cap widget. Set the data-cap-api-endpoint to your Cap Standalone instance URL and site key.
```html
```
--------------------------------
### Integrate Cap Widget in Qwik Component
Source: https://trycap.dev/guide/widget
Use this snippet to embed the Cap Widget within a Qwik application. It demonstrates how to handle solve, progress, and error events.
```tsx
import { component$ } from "@builder.io/qwik";
import "cap-widget";
export default component$(() => {
return (
);
});
```
--------------------------------
### Successful Siteverify Response
Source: https://trycap.dev/guide/standalone/index.html
JSON response indicating successful CAPTCHA token verification.
```json
{ "success": true }
```
--------------------------------
### Include Cap Widget Script
Source: https://trycap.dev/guide.html
Adds the Cap widget script to your HTML. It's recommended to pin a specific version in production.
```html
```
--------------------------------
### Set Custom WASM URL
Source: https://trycap.dev/guide/standalone/options
Configure the custom URL for the WASM file by setting window.CAP_CUSTOM_WASM_URL. Replace with your server's address.
```javascript
window.CAP_CUSTOM_WASM_URL = "https:///assets/cap_wasm.js";
```
--------------------------------
### React Usage
Source: https://trycap.dev/guide/widget
Use the Cap widget within a React application. Event handlers like 'onsolve', 'onprogress', and 'onerror' can be passed as props. React 19 or later is recommended for improved custom element event handling.
```jsx
import "cap-widget";
export default function ContactForm() {
return (
);
}
```
--------------------------------
### Verify CAPTCHA Token with Python
Source: https://trycap.dev/guide.html
This Python code uses the requests library to verify a CAPTCHA token. It sends a POST request to the /siteverify endpoint and checks the 'success' field in the JSON response.
```py
import requests
success = requests.post(
"https:////siteverify",
json={"secret": "", "response": ""}
).json().get("success")
print(success)
```
--------------------------------
### Verify Captcha Token with Cap Standalone
Source: https://trycap.dev/guide/standalone/index.html
Server-side request to verify a CAPTCHA token. Requires your site's secret key and the token provided by the widget.
```bash
curl "https:////siteverify" \
-X POST \
-H "Content-Type: application/json" \
-d '{ "secret": "", "response": "" }'
```
--------------------------------
### Add Cap Widget Component
Source: https://trycap.dev/guide.html
Embeds the Cap widget into your HTML, pointing to your Cap API endpoint and site key. Replace placeholders with your actual instance URL and site key.
```html
```
--------------------------------
### Verify CAPTCHA Token with JavaScript (Node.js/Browser)
Source: https://trycap.dev/guide.html
This JavaScript snippet demonstrates how to verify a CAPTCHA token using the fetch API. It sends a POST request to the /siteverify endpoint with the secret key and response token in JSON format.
```js
const { success } = await (
await fetch("https:////siteverify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ secret: "", response: "" }),
})
).json();
```
--------------------------------
### Cap Widget Programmatic Mode
Source: https://trycap.dev/guide/widget
Utilize programmatic mode for background actions like post submissions when a visible widget is not desired. This requires importing the Cap class and instantiating it with your API endpoint.
```js
import Cap from "cap-widget";
const cap = new Cap({
apiEndpoint: "https:////",
});
const { token } = await cap.solve();
```
--------------------------------
### Astro Usage
Source: https://trycap.dev/guide/widget
Embed the Cap widget in an Astro project. For client-side interactivity with the widget, ensure the script is loaded on the client using 'client:load'.
```astro
---
// ContactForm.astro
---
```
--------------------------------
### Redeem Challenge API
Source: https://trycap.dev/guide/server
Redeems a challenge by providing the token and solutions. This is used to verify if the client has correctly solved the challenge.
```APIDOC
## `cap.redeemChallenge({ ... })`
### Description
Redeems a challenge by providing the token and solutions.
### Method
`cap.redeemChallenge`
### Arguments
`options` (object) - Contains the token and solutions for the challenge.
#### Options
- **`token`** (string) - Required - The token associated with the challenge.
- **`solutions`** (array) - Required - An array of solutions provided by the client.
### Response
Returns an object indicating the success of the redemption.
#### Success Response
- **`success`** (boolean) - `true` if the challenge was redeemed successfully, `false` otherwise.
- **`token`** (string) - The token, potentially updated or re-issued.
### Example
```javascript
const result = cap.redeemChallenge({
token: 'challenge-token-123',
solutions: ['solution1', 'solution2']
});
console.log(result); // { success: true, token: 'new-token-or-same' }
```
```
--------------------------------
### Verify CAPTCHA Token with PHP
Source: https://trycap.dev/guide.html
This PHP script verifies a CAPTCHA token by making a POST request to the /siteverify endpoint. It uses stream contexts to configure the HTTP request and decodes the JSON response to check for success.
```php
//siteverify",
false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Content-Type: application/json",
"content" => json_encode(["secret"=>"","response"=>""])
]
])
), true);
var_dump($data['success'] ?? false);
```
--------------------------------
### Disable Haptic Feedback in Cap Widget
Source: https://trycap.dev/guide/widget
Globally disable haptic feedback by setting `window.CAP_DISABLE_HAPTICS` to `true`. Alternatively, use the `data-cap-disable-haptics` attribute on individual widgets.
```js
window.CAP_DISABLE_HAPTICS = true;
```
```html
```
--------------------------------
### Cleanup API
Source: https://trycap.dev/guide/server
Cleans up all expired challenges and tokens. This operation is usually performed automatically.
```APIDOC
## `await cap.cleanup()`
### Description
Cleans up all expired challenges and tokens. This is usually done automatically by default.
### Method
`await`
### Example
```javascript
await cap.cleanup();
console.log('Expired challenges and tokens have been cleaned up.');
```
```
--------------------------------
### Cleanup Expired Challenges and Tokens
Source: https://trycap.dev/guide/server
Manually trigger the cleanup of all expired challenges and tokens. This function is typically executed automatically.
```javascript
await cap.cleanup()
```
--------------------------------
### Cap Widget Internationalization Attributes
Source: https://trycap.dev/guide/widget
Customize widget labels for different languages using `data-cap-i18n-*` attributes. These attributes allow overriding default English text for various states and messages.
```html
```
--------------------------------
### Implement Floating Mode Trigger
Source: https://trycap.dev/guide/floating
Use the `data-cap-floating` attribute on a button to trigger the floating CAPTCHA widget. Specify the target widget using a CSS selector and optionally set the widget's position.
```html
```
--------------------------------
### Validate Cap Token on Backend
Source: https://trycap.dev/guide/server
Validate a token received from the frontend using the Cap library. If the token is invalid, an error is thrown, allowing you to proceed with your application logic only upon successful validation.
```javascript
const { success } = await cap.validateToken("...");
if (!success) throw new Error("invalid cap token");
// ...your logic
```
--------------------------------
### Cap Widget CSS Styling Variables
Source: https://trycap.dev/guide/widget
Customize the appearance of the Cap Widget by overriding CSS variables directly on the `cap-widget` element. This allows for fine-grained control over colors, dimensions, and fonts.
```css
cap-widget {
--cap-background: #fdfdfd;
--cap-border-color: #dddddd8f;
--cap-border-radius: 14px;
--cap-widget-height: 30px;
--cap-widget-width: 230px;
--cap-widget-padding: 14px;
--cap-gap: 15px;
--cap-color: #212121;
--cap-checkbox-size: 25px;
--cap-checkbox-border: 1px solid #aaaaaad1;
--cap-checkbox-border-radius: 6px;
--cap-checkbox-background: #fafafa91;
--cap-checkbox-margin: 2px;
--cap-font: system-ui, -apple-system, sans-serif;
--cap-spinner-color: #000;
--cap-spinner-background-color: #eee;
--cap-spinner-thickness: 5px;
}
```
--------------------------------
### Validate Token API
Source: https://trycap.dev/guide/server
Validates a given token. This is typically used to ensure the token is still valid and has not expired.
```APIDOC
## `await cap.validateToken("...", { ... })`
### Description
Validates a given token.
### Method
`await`
### Arguments
- **`token`** (string) - Required - The token to validate.
- **`options`** (object) - Optional - Configuration for token validation.
- **`keepToken`** (boolean) - Optional - If `true`, the token will not be deleted after validation, even if it's expired. Defaults to `false`.
### Response
Returns an object indicating the success of the token validation.
#### Success Response
- **`success`** (boolean) - `true` if the token is valid, `false` otherwise.
### Example
```javascript
const isValid = await cap.validateToken('user-session-token', {
keepToken: true
});
console.log(isValid); // { success: true }
```
```
--------------------------------
### Validate a Token
Source: https://trycap.dev/guide/server
Validate a given token. Optionally, you can choose to keep the token after validation by setting `keepToken` to true.
```json
{
"keepToken": false
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.