# Korzen Bot Protection: set-up guide for coding agents

You are adding Korzen Bot Protection to a project. It tells the server, in one call,
whether the visitor behind a sign-up, a sign-in or a checkout is a person or a bot. Follow
these steps exactly, change nothing else, and show the user the diff.

- API: https://eu.korzen.dev
- Site key (public, goes in the page): YOUR_SITE_KEY
- API key (secret): read it from the `KORZEN_API_KEY` environment variable. Never write
  the key into the code, a commit or a log.

If the site key above is `YOUR_SITE_KEY`, ask the user for theirs: it is on
https://korzen.dev/app/setup.

## 1. The tag

Add this to the `<head>` of the home page and of every page where a sign-up, a sign-in or
a checkout starts (the layout that renders those pages, if there is one). Korzen looks for
it on the home page of the host the visitor was on, or of its bare domain, to prove the
domain is the user's: without it there, the domain is never listed as theirs.

```html
<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>
```

It loads asynchronously and sets a first-party cookie, `_kz`, that the server sends on
step 2. Before the protected form is sent, call `await window.korzen?.ready()` (if the
form is a plain HTML form, send it from a submit handler after that call): it reports
what the visitor did since the tag last reported, and always resolves within a few
seconds.

## 2. The call from the server

In the server code that handles the protected action, before the account is created (or
the sign-in accepted, or the order placed), ask Bot Protection for a decision. If the
project has no sign-up, sign-in or checkout, name the forms and requests its pages send (a
contact form, a vote, a free tool's API) and ask the user which to protect.

Use Korzen's SDK where the project's language has one (Node, Go, Python, PHP, Java, .NET,
Rust; the packages are in step 4): it makes the call below, keeps every rule after it and
fails open, and the stack's guide shows where it goes. Only where the language has none
(Ruby), make the call with the platform's HTTP client, as below and as the stack's guide
shows:

```
POST https://eu.korzen.dev/v1/decide
Authorization: Bearer $KORZEN_API_KEY
Content-Type: application/json
Korzen-Deadline-Ms: <the timeout for the server's region, from https://korzen.dev/bot-protection/docs/server-call#latency>

{
  "ip": "<the visitor's IP, as the project's proxy or CDN reports it>",
  "ip_from": "<where the IP was read: peer, cloudflare or last_forwarded>",
  "user_agent": "<the User-Agent header>",
  "headers": {"<header name, lower-cased>": "<its value>", …},
  "token": "<the _kz cookie, if present>",
  "path": "<the action's path, such as /signup>",
  "method": "POST"
}
```

Rules that must hold:

- **The timeout for the server's region**, from the table at
  https://korzen.dev/bot-protection/docs/server-call#latency (200 ms in Europe and
  the US east), sent as `Korzen-Deadline-Ms`. Use the HTTP client's timeout or an abort
  signal; the header tells Bot Protection how long the call waits, and the decision takes
  half of it. Ask the user where the server runs when the project does not show it.
- **One HTTP client for the process**, kept open (keep-alive): Bot Protection runs in
  Germany, and a new TLS connection per call adds one or two round trips.
- **Fail open.** On a timeout, a network error, a non-200 status (401, 402, 503 …) or a
  body that does not parse, treat the answer as `allow`. An error's body is an RFC 9457
  problem (`application/problem+json`) whose `code` says why (`invalid_field` names a
  field of the wrong type): log it, never show it. Never let Bot Protection stop a
  sign-up by being down.
- **Server side only.** Never call `/v1/decide` from the browser; the API key must not
  reach it.
- **The headers.** In `headers`, forward each of these the request carries, under its
  lower-cased name, as it came: `accept`, `accept-encoding`, `accept-language`, `host`,
  `sec-ch-ua`, `sec-ch-ua-mobile`, `sec-ch-ua-platform`, `sec-fetch-dest`, `sec-fetch-mode`,
  `sec-fetch-site`, `upgrade-insecure-requests`; leave out the ones it does not carry.
  `host` names the domain the request was made to: a decision proves that domain the
  user's with it, so without it the domain is never listed. From
  Node, also send `header_order`: the names of the request's headers in the order they came,
  lower-cased (every other entry of `req.rawHeaders`); where the order is lost (Go's
  `net/http`, the Fetch API's `Headers`), leave it out.
- **The visitor's real IP.** Take it from what the project's proxy or CDN sets
  (`CF-Connecting-IP` on Cloudflare; `x-forwarded-for` on Vercel, which overwrites it;
  Express's `req.ip` with `trust proxy` set), never from a header the visitor could have
  written: a bot would pick its own IP. Nor the connection's address behind a load
  balancer: a private address (`10.x`, `172.16–31.x`, `192.168.x`, `100.64–127.x`,
  `fc00::/7`) is the project's own network's, and Bot Protection judges it as no IP. Send
  where it was read as `ip_from`: `peer` (the connection), `cloudflare`
  (`CF-Connecting-IP`), `last_forwarded` (the last `X-Forwarded-For` entry, the project's
  own proxy's) or `custom`.

The answer:

```json
{
  "request_id": "AQEAo3k9Zx4VbQ…",
  "decided_by": "bot_engine",
  "class": "bot",
  "bot_score": 72,
  "action": "allow",
  "mode": "monitor",
  "token_required": false
}
```

### Payment, login and sign-up: require the tag's token

A script that never loads the page (card testing, credential stuffing) runs no tag and is
answered `unknown`, which is allowed. So ask the user which routes are payment, login or
sign-up actions, and suggest the ones you found: the post that charges a card or places an
order, the one that checks a password, the one that creates an account. On those:

- With Korzen's SDK it is an option, which sends nothing on a page load:
  `protectedAction: true` (Node, PHP), `protected_action=True` (Python), `ProtectedAction`
  (Go, .NET), `.protectedAction(true)` (Java), `.protected_action(true)` (Rust). In a call
  of your own, add `"protected_action": true` to the body.
- Without a valid token from the tag, the answer has `token_required` true. In block mode
  `action` is then `block`; in monitor mode `action` stays `allow`. The class does not
  change.
  Put the tag on the page each of these actions starts from.
- Leave it off routes no page of the site leads to: webhooks, a mobile app's API, a
  partner's server. No tag runs there, so block mode would block every request.

The account starts in monitor mode, so this stops nobody until the user turns block mode
on. A visitor whose browser does not run the tag (an ad blocker, JavaScript off) holds no
token and is refused on these actions in block mode: tell the user to watch the share of
decisions without a token in monitor mode first. The details:
https://korzen.dev/bot-protection/docs/protecting-a-checkout.md

If the user wants those visitors to pass too, offer first-party mode. It needs one of
Korzen's SDKs or a Cloudflare Worker: their first-party option (`firstParty: true` in Node
and PHP, `first_party=True` in Python, `FirstParty` in Go and .NET, `.firstParty(true)` in
Java, `.first_party(true)` in Rust, `KORZEN_FIRST_PARTY = "1"` in the Worker) serves the tag and its beacon
under `/kz` on the site's own domain, and the tag's `src` becomes `/kz/tag.js`. Set it
up only when the user asks for it:
https://korzen.dev/bot-protection/docs/first-party.md

## 3. Apply the action

Read only `action`:

- `allow`: go on.
- `block`: refuse with the same error the action shows when it fails for any other
  reason (such as "We could not create your account"), so a bot learns nothing.

The account starts in monitor mode, where `action` is always `allow`: the integration
changes nothing for visitors until the user turns block mode on in the dashboard.

## 4. Configuration

- Add `KORZEN_API_KEY=` to the project's example environment file (`.env.example` or
  similar), with no value.
- Add Korzen's SDK for the project's language. Each fails open, and the stack's guide
  shows it:
  - Node: `npm install @korzen/bot-protection`, with no dependencies.
  - Go: `go get korzen.dev/bot-protection/go/v3`, on golang.org/x/net and golang.org/x/text.
  - Python: `pip install korzen-bot-protection`, the standard library alone.
  - PHP: `composer require korzen/bot-protection` (and `symfony/http-foundation` without a
    framework).
  - Java: `dev.korzen:bot-protection` from Maven Central, with no runtime dependency.
  - .NET: `dotnet add package Korzen.BotProtection`, with no package dependency.
  - Rust: `cargo add korzen-bot-protection`.
- In Ruby, which has no SDK, add no dependency: Ruby's own `Net::HTTP` makes the call, as
  the Rails guide shows.

## Examples

Next.js (App Router), with Korzen's npm package, called from the route handler or server
action that creates the account:

```js
import { headers } from "next/headers";
import { createClient, fromHeaders, ipFrom } from "@korzen/bot-protection";

// The timeout for the server's region: https://korzen.dev/bot-protection/docs/server-call#latency
const client = createClient({ apiKey: process.env.KORZEN_API_KEY, url: "https://eu.korzen.dev", timeoutMs: 200 });

// The answer, or null on any error: go on as on allow (fail open).
export async function decide(path) {
  // ipFrom.vercel on Vercel; behind Cloudflare alone, ipFrom.cloudflare
  return client.decide(fromHeaders(await headers(), { path, ip: ipFrom.vercel, protectedAction: true }));
}
```

Express, as middleware on the route; the answer is on `req.korzen`, or `null`:

```js
import { createClient, protect } from "@korzen/bot-protection";

// The timeout for the server's region: https://korzen.dev/bot-protection/docs/server-call#latency
const korzen = createClient({ apiKey: process.env.KORZEN_API_KEY, url: "https://eu.korzen.dev", timeoutMs: 200 });
app.set("trust proxy", 1); // the number of proxies in front, never true

const guard = protect({
  client: korzen,
  ip: (_get, req) => req.ip,
  protectedAction: true,
  onBlock: (req, res) => res.status(403).send("We could not create your account."),
});
app.post("/signup", guard, createAccount);
```

Flask, with Korzen's Python package; the answer is in `request.environ["korzen.decision"]`,
or `None`:

```python
import os
from korzen_bot_protection import Client, KorzenWSGI, last_forwarded_ip

# The timeout for the server's region: https://korzen.dev/bot-protection/docs/server-call#latency
korzen = Client(os.environ["KORZEN_API_KEY"], url="https://eu.korzen.dev", timeout=0.2)
app.wsgi_app = KorzenWSGI(app.wsgi_app, client=korzen, prefixes=["/signup"],
                          ip=last_forwarded_ip,  # behind one proxy of the project's own
                          protected_action=True)
```

Guides per stack, with where the tag goes, the visitor's real IP on that platform and the
common mistakes: read the one that matches the project before you change it.

- Next.js: https://korzen.dev/bot-protection/docs/nextjs.md
- Express: https://korzen.dev/bot-protection/docs/express.md
- Fastify and NestJS: https://korzen.dev/bot-protection/docs/fastify-nestjs.md
- Hono, Bun, Deno, React Router and Remix, Astro, SvelteKit and Nuxt (the Fetch API's
  `Request`): https://korzen.dev/bot-protection/docs/web-request.md
- Django and Flask: https://korzen.dev/bot-protection/docs/django-flask.md
- FastAPI: https://korzen.dev/bot-protection/docs/fastapi.md
- Rails: https://korzen.dev/bot-protection/docs/rails.md
- Laravel: https://korzen.dev/bot-protection/docs/laravel.md
- PHP without a framework, and Symfony: https://korzen.dev/bot-protection/docs/php.md
- Go net/http: https://korzen.dev/bot-protection/docs/go.md
- Spring Boot: https://korzen.dev/bot-protection/docs/spring-boot.md
- ASP.NET Core: https://korzen.dev/bot-protection/docs/aspnet-core.md
- Rust, Axum and Actix Web (Korzen's crate: a Tower layer, the same call in Actix Web):
  https://korzen.dev/bot-protection/docs/rust.md
- Supabase Auth (sign-ups through the server, and a Before User Created hook):
  https://korzen.dev/bot-protection/docs/supabase.md
- Clerk (one decision on a new account's first page): https://korzen.dev/bot-protection/docs/clerk.md
- Auth0 (a pre-user-registration Action): https://korzen.dev/bot-protection/docs/auth0.md
- Better Auth (a database hook before any user is created):
  https://korzen.dev/bot-protection/docs/better-auth.md
- WordPress and WooCommerce (a plugin, no code): https://korzen.dev/bot-protection/docs/wordpress.md
- Kubernetes (the key as a Secret, the visitor's IP through the ingress):
  https://korzen.dev/bot-protection/docs/kubernetes.md
- Cloudflare Workers (the decision at the edge, before the origin):
  https://korzen.dev/bot-protection/docs/cloudflare-workers.md
- Payment, login and sign-up routes (`protected_action` for every stack, and who it stops):
  https://korzen.dev/bot-protection/docs/protecting-a-checkout.md
- First-party mode (the tag and its beacon served from the site's own
  domain, by an SDK or the Cloudflare Worker), for visitors whose network blocks
  Korzen's host: https://korzen.dev/bot-protection/docs/first-party.md

## 5. Tell the user

When done, tell the user to:

1. Set `KORZEN_API_KEY` where the server runs (the key is on https://korzen.dev/app/setup).
2. Deploy. There is no list of origins to fill in and no DNS record: the server's first
   decision on a visitor of a page on a domain, one that is not a bot, adds that domain
   under "Your domains" on the same page (`www.`, the bare name and every other subdomain
   count as one), once Korzen finds the tag on that host's home page or the bare domain's. Pages on localhost always work and are never listed. A domain there that is not
   theirs, such as a copy of the site, can be dropped, and stays dropped for 30 days; one
   of theirs can be added by hand on the same page (it is protected once the server's
   first decision on a person there proves it).
3. Watch the first decisions on https://korzen.dev/app/decisions. The free trial starts at the first
   call to `/v1/decide` and lasts 14 days or 20,000 decisions; then the free plan gives
   1,000 decisions a month. The account stays in monitor mode until they turn block mode
   on.
4. If `protected_action` is on for some routes: before turning block mode on, read the share
   "Without a token" in the integration health on https://korzen.dev/app/setup. Those visitors
   would be refused on those routes.

More: https://korzen.dev/bot-protection/docs
