standalone@2.0.13: better ratelimiting & docs

This commit is contained in:
tiago
2025-10-25 11:04:14 +01:00
parent 563ab48415
commit 1e796a310e
9 changed files with 217 additions and 166 deletions
+11 -13
View File
@@ -159,25 +159,23 @@ export default withMermaid({
sidebar: [
{ text: "Quickstart", link: "/guide/index.md" },
{ text: "Feature comparison", link: "/guide/alternatives.md" },
{ text: "Community libraries", link: "/guide/community.md" },
{
text: "Standalone",
collapsed: false,
items: [
{ text: "Quickstart", link: "/guide/standalone/index.md" },
{ text: "API", link: "/guide/standalone/api.md" },
{ text: "Options", link: "/guide/standalone/options.md" },
],
},
{
text: "Libraries",
collapsed: false,
collapsed: true,
items: [
{ text: "Server", link: "/guide/server.md" },
{ text: "Widget", link: "/guide/widget.md" },
{ text: "Solver", link: "/guide/solver.md" },
],
},
{
text: "Standalone",
collapsed: true,
items: [
{ text: "About", link: "/guide/standalone/index.md" },
{ text: "Installation", link: "/guide/standalone/installation.md" },
{ text: "Usage", link: "/guide/standalone/usage.md" },
{ text: "API", link: "/guide/standalone/api.md" },
{ text: "Options", link: "/guide/standalone/options.md" },
{ text: "Community libraries", link: "/guide/community.md" },
],
},
{
+105 -2
View File
@@ -2,8 +2,111 @@
Cap Standalone is a self-hosted version of Cap's backend that allows you to spin up a server to validate and create challenges so you can use it with languages other than JS.
It's simple yet amazingly powerful, allowing you to use Cap in any language that can make HTTP requests. It's mostly compatible with reCAPTCHA and hCaptcha's siteverify enpoints, so you can use it as a drop-in replacement for them.
It's simple yet powerful, allowing you to use Cap in any language that can make HTTP requests. It's mostly compatible with reCAPTCHA and hCaptcha's siteverify enpoints, so you can use it as a drop-in replacement for them.
It also offers API key support, a built-in assets server, a dashboard with statistics, and more. To get started, follow [the instructions to install it on your server](installation.md).
It also offers API key support, a built-in assets server, a dashboard with statistics, and more.
![Screenshot of Cap's standalone mode](/standalone_screenshot.png)
## Installation
### Requirements
You'll need to have [Docker Engine 20.10 or higher](https://docs.docker.com/get-docker/) installed on your server. Both `x86_64` (amd64) and `arm64` architectures are supported.
---
Run the following command to pull the Cap Standalone Docker image from Docker Hub:
```bash
docker pull tiago2/cap:latest
```
Then, to run the server, use the following command:
```bash
docker run -d \
-p 3000:3000 \
-v cap-data:/usr/src/app/.data \
-e ADMIN_KEY=your_secret_password \
--name cap-standalone \
tiago2/cap:latest
```
Make sure to replace `your_secret_password` with a strong password, as anyone with it will be able to log into the dashboard and create keys. It'll need to be at least 30 characters long.
Then, you can access the dashboard at `http://localhost:3000`, log in, and create a key. You'll get a site key and a secret key which you'll be able to use on your widget.
On Debian and other OSes that don't use `iptables`, if you can't open the dashboard, try setting `--network=host` in the run command. Thanks to [Boro Vukovic](https://github.com/tiagozip/cap/issues/70#issuecomment-3086464282) for letting me know about this.
You'll also need to make the server publicly accessible from the internet, as the widget needs to be able to reach it. If you're using a reverse proxy, make sure to check [the options guide](/guide/standalone/options.md) to configure rate-limiting properly.
## Usage
### Client-side
Let's configure your widget to use your self-hosted Cap Standalone server. To do this, set the widget's API endpoint option to:
```
https://<instance_url>/<site_key>/
```
Make sure to replace:
- `<instance_url>`: The actual URL where your Cap Standalone instance is running. This URL must be publicly accessible from the internet.
- `<site_key>`: Your site key from this dashboard.
Example:
```html
<cap-widget
data-cap-api-endpoint="https://cap.example.com/d9256640cb53/"
></cap-widget>
```
### Server-side
After a user completes the CAPTCHA on your site, your backend needs to verify their token using this server's API.
You can do this by sending a `POST` request from your server to the following endpoint:
```
https://<instance_url>/<site_key>/siteverify
```
Your request needs to include the following data:
- `secret`: Your key secret from this dashboard. This is **not** the admin key, but rather your site key's secret.
- `response`: The CAPTCHA token generated by the widget on the client-side
Example using `curl`:
```bash
curl "https://<instance_url>/<site_key>/siteverify" \
-X POST \
-H "Content-Type: application/json" \
-d '{ "secret": "<key_secret>", "response": "<captcha_token>" }'
```
The response should look like this:
```json
{
"success": true
}
```
Or, if the captcha token is invalid or expired, it will return:
```json
{
"success": false
}
```
If `success` is true, you can proceed with your app logic.
### Client-side library storage
Cap Standalone can also serve the widget and floating client-side library files. [Learn more](options.md#asset-server).
+1 -32
View File
@@ -1,34 +1,3 @@
# Installation
### Requirements
You'll need to have [Docker Engine 20.10 or higher](https://docs.docker.com/get-docker/) installed on your server. Both `x86_64` (amd64) and `arm64` architectures are supported.
---
Run the following command to pull the Cap Standalone Docker image from Docker Hub:
```bash
docker pull tiago2/cap:latest
```
Then, to run the server, use the following command:
```bash
docker run -d \
-p 3000:3000 \
-v cap-data:/usr/src/app/.data \
-e ADMIN_KEY=your_secret_password \
--name cap-standalone \
tiago2/cap:latest
```
Make sure to replace `your_secret_password` with a strong password, as anyone with it will be able to log into the dashboard and create keys. It'll need to be at least 30 characters long.
Then, you can access the dashboard at `http://localhost:3000`, log in, and create a key. You'll get a site key and a secret key which you'll be able to use on your widget.
On Debian and other OSes that don't use `iptables`, if you can't open the dashboard, try setting `--network=host` in the run command. Thanks to [Boro Vukovic](https://github.com/tiagozip/cap/issues/70#issuecomment-3086464282) for letting me know about this.
You'll also need to make the server publicly accessible from the internet, as the widget needs to be able to reach it.
Done! Now, read the [usage guide](/guide/standalone/usage.md) to learn how to use it.
This section has moved to [Standalone](/guide/standalone/index.md).
+3 -1
View File
@@ -43,7 +43,9 @@ By default, Standalone will use Elysia's built-in `server.requestIP` function to
If so, you can change the IP extraction logic to simply read from a header set in `RATELIMIT_IP_HEADER` in your env. For example, if you were using Cloudflare, you might set `RATELIMIT_IP_HEADER` to `cf-connecting-ip`. On most setups, this is `x-forwarded-for`.
The `/siteverify` endpoint is intended for server-to-server use, so each request checks if your key's secret is valid. If it is, the request is allowed. If not, the request is denied and the client's IP is temporarily blocked for a few hundred milliseconds. This prevents database strain without affecting legitimate requests.
If you're interested in an option to fully disable ratelimiting, let us know using GitHub issues.
## Custom data path
If you would like the data to be stored in a custom path inside the container, you can set the `DATA_PATH` environment variable to the desired path. Note that this only works in Standalone 2.0.9 or above. Added by [#100](https://github.com/tiagozip/cap/issues/100)
If you would like the data to be stored in a custom path inside the container, you can set the `DATA_PATH` environment variable to the desired path. Note that this only works in Standalone 2.0.9 or above.
+2 -72
View File
@@ -1,73 +1,3 @@
# Usage
# Installation
First, make sure Cap Standalone is installed and running by following [the installation guide](installation.md).
Then, you can get to using Cap Standalone:
### Client-side
Let's configure your widget to use your self-hosted Cap Standalone server. To do this, set the widget's API endpoint option to:
```
https://<instance_url>/<site_key>/
```
Make sure to replace:
- `<instance_url>`: The actual URL where your Cap Standalone instance is running. This URL must be publicly accessible from the internet.
- `<site_key>`: Your site key from this dashboard.
Example:
```html
<cap-widget
data-cap-api-endpoint="https://cap.example.com/d9256640cb53/"
></cap-widget>
```
### Server-side
After a user completes the CAPTCHA on your site, your backend needs to verify their token using this server's API.
You can do this by sending a `POST` request from your server to the following endpoint:
```
https://<instance_url>/<site_key>/siteverify
```
Your request needs to include the following data:
- `secret`: Your key secret from this dashboard. This is **not** the admin key, but rather your site key's secret.
- `response`: The CAPTCHA token generated by the widget on the client-side
Example using `curl`:
```bash
curl "https://<instance_url>/<site_key>/siteverify" \
-X POST \
-H "Content-Type: application/json" \
-d '{ "secret": "<key_secret>", "response": "<captcha_token>" }'
```
The response should look like this:
```json
{
"success": true
}
```
Or, if the captcha token is invalid or expired, it will return:
```json
{
"success": false
}
```
If `success` is true, you can proceed with your app logic.
### Client-side library storage
To learn more about using the client-side library, check out the [guide on it](options.md#asset-server).
This section has moved to [Standalone](/guide/standalone/index.md).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cap-standalone",
"version": "2.0.12",
"version": "2.0.13",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "bun run --watch src/index.js",
-45
View File
@@ -9,9 +9,6 @@ import { ratelimitGenerator } from "./ratelimit.js";
const getSitekeyConfigQuery = db.query(
`SELECT (config) FROM keys WHERE siteKey = ?`,
);
const getSitekeyWithSecretQuery = db.query(
`SELECT * FROM keys WHERE siteKey = ?`,
);
const insertChallengeQuery = db.query(`
INSERT INTO challenges (siteKey, token, data, expires)
@@ -28,12 +25,6 @@ const insertTokenQuery = db.query(`
INSERT INTO tokens (siteKey, token, expires)
VALUES (?, ?, ?)
`);
const getTokenQuery = db.query(`
SELECT * FROM tokens WHERE siteKey = ? AND token = ?
`);
const deleteTokenQuery = db.query(`
DELETE FROM tokens WHERE siteKey = ? AND token = ?
`);
const upsertSolutionQuery = db.query(`
INSERT INTO solutions (siteKey, bucket, count)
@@ -138,40 +129,4 @@ export const capServer = new Elysia({
token,
expires,
};
})
.post("/:siteKey/siteverify", async ({ body, set, params }) => {
const sitekey = params.siteKey;
const { secret, response } = body;
if (!sitekey || !secret || !response) {
set.status = 400;
return { error: "Missing required parameters" };
}
const keyHash = getSitekeyWithSecretQuery.get(sitekey)?.secretHash;
if (!keyHash) {
set.status = 404;
return { error: "Invalid site key or secret" };
}
if (!(await Bun.password.verify(secret, keyHash))) {
set.status = 403;
return { error: "Invalid site key or secret" };
}
const token = getTokenQuery.get(params.siteKey, response);
if (!token) {
set.status = 404;
return { error: "Token not found" };
}
if (token.expires < Date.now()) {
deleteTokenQuery.run(params.siteKey, response);
set.status = 403;
return { error: "Token expired" };
}
deleteTokenQuery.run(params.siteKey, response);
return { success: true };
});
+2
View File
@@ -5,6 +5,7 @@ import { assetsServer } from "./assets.js";
import { auth } from "./auth.js";
import { capServer } from "./cap.js";
import { server } from "./server.js";
import { siteverifyServer } from "./siteverify.js";
const serverPort = process.env.SERVER_PORT || 3000;
const serverHostname = process.env.SERVER_HOSTNAME || "0.0.0.0";
@@ -71,6 +72,7 @@ new Elysia({
.use(server)
.use(assetsServer)
.use(capServer)
.use(siteverifyServer)
.listen(serverPort);
console.log(`🧢 Cap running on http://${serverHostname}:${serverPort}`);
+92
View File
@@ -0,0 +1,92 @@
import { cors } from "@elysiajs/cors";
import { Elysia } from "elysia";
import { db } from "./db.js";
import { ratelimitGenerator } from "./ratelimit.js";
const getSitekeyWithSecretQuery = db.query(
`SELECT * FROM keys WHERE siteKey = ?`,
);
const getTokenQuery = db.query(`
SELECT * FROM tokens WHERE siteKey = ? AND token = ?
`);
const deleteTokenQuery = db.query(`
DELETE FROM tokens WHERE siteKey = ? AND token = ?
`);
const blockedIPs = new Map();
setInterval(() => {
const now = Date.now();
for (const [ip, unblockTime] of blockedIPs.entries()) {
if (now >= unblockTime) {
blockedIPs.delete(ip);
}
}
}, 2000);
export const siteverifyServer = new Elysia({
detail: {
tags: ["Challenges"],
},
})
.use(
cors({
origin: process.env.CORS_ORIGIN?.split(",") || true,
methods: ["POST"],
}),
)
.post("/:siteKey/siteverify", async ({ body, set, params, request, server }) => {
const ip = ratelimitGenerator(request, server);
const now = Date.now();
const unblockTime = blockedIPs.get(ip);
if (unblockTime && now < unblockTime) {
const retryAfter = Math.ceil((unblockTime - now) / 1000);
set.status = 429;
set.headers["Retry-After"] = retryAfter.toString();
set.headers["X-RateLimit-Limit"] = "1";
set.headers["X-RateLimit-Remaining"] = "0";
set.headers["X-RateLimit-Reset"] = Math.ceil(unblockTime / 1000).toString();
return { error: "You were temporarily for using an invalid secret key. Please try again later." };
}
const sitekey = params.siteKey;
const { secret, response } = body;
if (!sitekey || !secret || !response) {
set.status = 400;
return { error: "Missing required parameters" };
}
const keyHash = getSitekeyWithSecretQuery.get(sitekey)?.secretHash;
if (!keyHash) {
set.status = 404;
return { error: "Invalid site key or secret" };
}
const isValidSecret = await Bun.password.verify(secret, keyHash);
if (!isValidSecret) {
blockedIPs.set(ip, now + 250);
set.status = 403;
return { error: "Invalid site key or secret" };
}
const token = getTokenQuery.get(params.siteKey, response);
if (!token) {
set.status = 404;
return { error: "Token not found" };
}
if (token.expires < Date.now()) {
deleteTokenQuery.run(params.siteKey, response);
set.status = 403;
return { error: "Token expired" };
}
deleteTokenQuery.run(params.siteKey, response);
return { success: true };
});