@botbye/cloudflare-worker
v2.2.0
Published
BotBye! integration for Cloudflare Workers
Downloads
24
Readme
@botbye/cloudflare-worker
BotBye! integration for Cloudflare Workers.
Full documentation: https://botbye.com/docs/edge-servers/cloudflare-workers
Install
npm i @botbye/cloudflare-workeryarn add @botbye/cloudflare-workerRequires @cloudflare/workers-types >= 4 as a peer dependency.
Configuration
Call init at module load time, before the fetch handler runs:
import { init } from "@botbye/cloudflare-worker";
init({
// Use your project server-key
serverKey: "00000000-0000-0000-0000-000000000000",
});
export default {
async fetch(request, env, ctx) {
// ...
},
};init() itself makes no network calls — it only stores configuration. The connection handshake with BotBye is deferred to the first evaluate() call, which is required by the Cloudflare Workers runtime (network calls are not allowed at module initialization).
init options
| Option | Type | Required | Description |
|---|---|---|---|
| serverKey | string | Yes | Server key from your BotBye project |
| url | string | No | Override BotBye API endpoint (default: https://verify.botbye.com) |
| logger.level | "error" \| "warn" \| "info" \| "debug" \| "log" | No | Log level (default: "info") |
| logger.logger | TLogger | No | Custom logger instance implementing { error, warn, info, debug, log } |
| timeouts.evaluate | number | No | Timeout in milliseconds for each evaluate call |
Usage
Call evaluate inside the fetch handler where bot protection is needed. It accepts an event object describing what you know about the request and the context around it, and returns a promise that resolves to a decision.
There are three event types — validate, risk, and full — each suited for a different layer of your application.
validate — edge-level bot check
Use at the edge of your Worker when you just want to know: was this request made by a bot? No user or domain context needed.
Event fields:
{
type: "validate";
request:
// Option A: pass the CF Workers Request object directly — SDK extracts everything automatically
| { request: Request; token?: string | null }
// Option B: construct request info manually
| { ip: string; headers: Record<string, string>; requestMethod?: string | null; requestUri?: string | null; token?: string | null };
customFields?: Record<string, string>;
}The SDK extracts IP, headers, method, and URI from the CF Workers Request object automatically. You can also pass request info manually — see Option B above. The token is a one-time token generated by the BotBye client-side SDK that contains information about the user's device. Pass whatever the client sent; if no token is received, the decision will be "BLOCK".
import { evaluate } from "@botbye/cloudflare-worker";
export default {
async fetch(request, env, ctx) {
const result = await evaluate({
type: "validate",
request: {
request,
// "x-botbye-token" is an example — pass the token from wherever you store it
token: request.headers.get("x-botbye-token"),
},
});
if (result.decision === "BLOCK") {
return new Response(JSON.stringify({ error: "Forbidden" }), {
status: 403,
headers: { "Content-Type": "application/json" },
});
}
// proceed normally
},
};risk — domain-level risk scoring
Use when you can read user context from the request — for example, on a login endpoint you can extract credentials from the body and send them to BotBye before proxying to your origin. At this stage the outcome is not yet known, so event.status is "ATTEMPTED".
Event fields:
{
type: "risk";
request:
// Only ip is needed at this level
| { ip: string; headers?: Record<string, string>; requestMethod?: string | null; requestUri?: string | null; token?: string | null }
// CF Workers Request also accepted if convenient
| { request: Request };
event: {
type: string; // e.g. "login", "password_change", "checkout"
status: "ATTEMPTED" | "SUCCESSFUL" | "FAILED" | "UNKNOWN";
};
user: {
accountId: string;
username?: string | null;
email?: string | null;
phone?: string | null;
};
customFields?: Record<string, string>;
botbyeResult?: string;
}event and user are the key fields here — they define what action is being performed and who is performing it, which is what drives the risk score. ip is equally important: BotBye tracks which IPs access the account to detect patterns like account sharing, credential stuffing, and suspicious geo logins. Pass it directly as { ip }, or pass the CF Workers Request object if that's more convenient.
import { evaluate } from "@botbye/cloudflare-worker";
export default {
async fetch(request, env, ctx) {
const { email } = await request.clone().json();
const result = await evaluate({
type: "risk",
request: { request },
event: {
type: "login",
status: "ATTEMPTED",
},
user: {
accountId: email,
email,
},
});
if (result.decision === "BLOCK") {
return new Response(JSON.stringify({ error: "Forbidden" }), {
status: 403,
headers: { "Content-Type": "application/json" },
});
}
// proxy to origin
return fetch(request);
},
};Linking validate and risk events
When the same request is evaluated at two layers — for example, once at the edge (type: "validate") and then again inside a domain service (type: "risk") — BotBye can link both events and display them as a single event in the dashboard.
Step 1 — CF Worker (edge): run validate and capture botbye_result:
export default {
async fetch(request, env, ctx) {
const edgeResult = await evaluate({
type: "validate",
request: {
request,
// "x-botbye-token" is an example — pass the token from wherever you store it
token: request.headers.get("x-botbye-token"),
},
});
const edgeBotbyeResult = edgeResult.botbye_result;
// Pass edgeBotbyeResult downstream — a custom request header, KV, function argument, etc.
},
};Step 2 — domain service (auth, payment, account management): pass it as botbyeResult in the risk call:
const riskResult = await evaluate({
type: "risk",
request: { request },
event: {
type: "login",
status: "ATTEMPTED",
},
user: {
accountId: email,
email,
},
botbyeResult: edgeBotbyeResult,
});botbye_result is optional in the response — if it is absent, omit botbyeResult and the events will be recorded independently.
full — edge check and domain scoring in one call
Use when the Worker itself is the endpoint and you have all context at once: the raw request with token, the user extracted from the body, and the outcome of the action. For example, a login Worker that reads credentials from the body, checks them against a data store (D1, KV, external API), and knows the result before responding.
Event fields:
{
type: "full";
request:
| { request: Request; token?: string | null }
| { ip: string; headers: Record<string, string>; requestMethod?: string | null; requestUri?: string | null; token?: string | null };
event: {
type: string;
status: "ATTEMPTED" | "SUCCESSFUL" | "FAILED" | "UNKNOWN";
};
user: {
accountId: string;
username?: string | null;
email?: string | null;
phone?: string | null;
};
customFields?: Record<string, string>;
}Equivalent to running validate and risk in a single call.
import { evaluate } from "@botbye/cloudflare-worker";
export default {
async fetch(request, env, ctx) {
const { email, password } = await request.json();
const user = await findUser(email, env); // e.g. query Cloudflare D1
const loginSucceeded = user && (await checkPassword(user, password));
const result = await evaluate({
type: "full",
request: {
request,
token: request.headers.get("x-botbye-token"), // "x-botbye-token" is an example — pass the token from wherever you store it
},
event: {
type: "login",
status: loginSucceeded ? "SUCCESSFUL" : "FAILED",
},
user: {
accountId: user?.id ?? email,
email,
},
});
if (result.decision === "BLOCK") {
return new Response(JSON.stringify({ error: "Forbidden" }), {
status: 403,
headers: { "Content-Type": "application/json" },
});
}
// proceed normally
},
};Response
evaluate always returns a Promise<TEvaluationResult>:
type TEvaluationResult =
| {
decision: "ALLOW" | "BLOCK" | "CHALLENGE";
request_id: string;
risk_score: number;
scores: Record<string, number>;
signals: string[];
botbye_result?: string;
}
| {
decision: "ALLOW" | "BLOCK" | "CHALLENGE";
botbye_result?: string;
error: { message: string };
};Check result.decision to decide how to handle the request:
"ALLOW"— request appears legitimate, proceed normally"BLOCK"— bot or suspicious activity detected, block the request"CHALLENGE"— uncertain, consider issuing a CAPTCHA, MFA, or additional verification step
When the response contains an error field, BotBye could not evaluate the request (e.g. invalid server key). In that case decision defaults to "ALLOW" so that a misconfiguration does not block real users — but you should monitor and fix the underlying error.
Response examples
Blocked (bot detected):
{
"request_id": "f77b2abd-c5d7-44f0-be4f-174b04876583",
"decision": "BLOCK",
"risk_score": 0.95,
"scores": { "bot": 0.95 },
"signals": ["AutomationTool"]
}Allowed:
{
"request_id": "f77b2abd-c5d7-44f0-be4f-174b04876583",
"decision": "ALLOW",
"risk_score": 0.05,
"scores": { "bot": 0.05, "ato": 0.02 },
"signals": []
}Challenge:
{
"request_id": "f77b2abd-c5d7-44f0-be4f-174b04876583",
"decision": "CHALLENGE",
"risk_score": 0.65,
"scores": { "bot": 0.65 },
"signals": ["SuspiciousFingerprint"],
"challenge": { "type": "CAPTCHA", "token": "..." }
}Invalid serverKey:
{
"decision": "ALLOW",
"error": { "message": "[BotBye] Bad Request: Invalid Server Key" }
}Advanced: multiple instances
Use factory to create independent SDK instances (useful when protecting multiple projects from one Worker):
import { factory } from "@botbye/cloudflare-worker";
const sdk = factory();
sdk.init({
// Use your project server-key
serverKey: "00000000-0000-0000-0000-000000000000",
});
const result = await sdk.evaluate({
type: "validate",
request: { request, token },
});Dev utilities
import { dev } from "@botbye/cloudflare-worker";
dev.setLoggerLevel("debug"); // "error" | "warn" | "info" | "debug" | "log"Anti-Phishing
BotBye's anti-phishing detects look-alike sites that clone your pages to steal credentials. This integration serves the detection catcher from your own origin, so the BotBye domain stays hidden from the client.
Anti-phishing is identified by its own clientKey (available in your Phishing Project in the Dashboard), not the server key used by evaluate, so it is configured separately.
Init
Call phishing.init at module load time, before the fetch handler runs.
import { phishing } from "@botbye/cloudflare-worker";
phishing.init({
// clientKey from your Phishing Project on the Admin Dashboard
clientKey: "00000000-0000-0000-0000-000000000000",
});
export default {
async fetch(request, env, ctx) {
// ...
},
};Configuration
| Option | Type | Required | Description |
|---|---|---|---|
| clientKey | string | Yes | clientKey from your Phishing Project on the Admin Dashboard |
| url | string | No | Override BotBye API endpoint (default: https://verify.botbye.com) |
| logger.level | "error" \| "warn" \| "info" \| "debug" \| "log" | No | Log level (default: "info") |
| logger.logger | TLogger | No | Custom logger instance implementing { error, warn, info, debug, log } |
| timeouts.fetchCatcher | number | No | Timeout in milliseconds for each fetchCatcher call |
Usage
Anti-phishing needs two routes on your own origin, each proxied through fetchCatcher:
- SVG route — serves the SVG catcher. This is the URL your client passes to
getCatcher({ url }). - PNG route — serves the PNG that the SVG references (via
innerPngUrl).
The paths are arbitrary — name the routes however you like. Pass the raw request as request and the format. For the SVG, innerPngUrl must be the absolute URL of your PNG route — the browser loads that PNG directly from your origin.
import { phishing } from "@botbye/cloudflare-worker";
// Absolute URL of your PNG endpoint — the SVG catcher references it through innerPngUrl.
const PNG_CATCHER_URL = "https://your-site.example/botbye-catcher.png";
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// Endpoint 1 — SVG catcher (this URL goes into the catcher element on your pages)
if (url.pathname === "/botbye-catcher.svg") {
const catcher = await phishing.fetchCatcher({
request,
format: "svg",
innerPngUrl: PNG_CATCHER_URL, // absolute URL of the PNG endpoint below
});
return new Response(catcher.body, { status: catcher.status, headers: catcher.headers });
}
// Endpoint 2 — companion PNG the SVG above references via innerPngUrl (PNG_CATCHER_URL)
if (url.pathname === "/botbye-catcher.png") {
const catcher = await phishing.fetchCatcher({ request, format: "png" });
return new Response(catcher.body, { status: catcher.status, headers: catcher.headers });
}
/* your other routing */
},
};We recommend embedding the SVG catcher: it is designed to keep tracking even when a phishing site copies all of your assets to its own infrastructure (the PNG route exists because the SVG catcher relies on it).
Multiple instances
phishing is a ready default instance. Use phishingFactory() to create isolated instances for multiple projects.
import { phishingFactory } from "@botbye/cloudflare-worker";
const phishing = phishingFactory();
phishing.init({ clientKey: "00000000-0000-0000-0000-000000000000" });Documentation
- Web: https://botbye.com/docs/edge-servers/cloudflare-workers
- Markdown (for AI tools and agents): https://botbye.com/docs/edge-servers/cloudflare-workers.md
