Metadata-Version: 2.5
Name: korzen-bot-protection
Version: 2.0.1
Summary: Korzen Bot Protection for Python: asks POST /v1/decide before a protected action, and fails open.
Project-URL: Homepage, https://korzen.dev/bot-protection
Project-URL: Documentation, https://korzen.dev/bot-protection/docs/python
Author: Korzen
License-Expression: LicenseRef-Proprietary
License-File: LICENSE
Keywords: asgi,bot detection,bot protection,middleware,wsgi
Classifier: Framework :: Django
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# Korzen Bot Protection for Python

`korzen-bot-protection` asks [Korzen Bot Protection](https://korzen.dev/bot-protection)
about a request before a protected action (`POST /v1/decide`), reports events and feedback
after it (`POST /v1/events`, `POST /v1/feedback`), on API v1, and **fails open**: when Bot
Protection is slow, down, refuses the key or answers anything but a decision, the visitor
goes through. The standard library alone, no framework imported; a WSGI and an ASGI
middleware.

## Install

```sh
pip install korzen-bot-protection
```

## Use

Flask:

```python
import os
from flask import Flask, request
from korzen_bot_protection import Client, KorzenWSGI, last_forwarded_ip

app = Flask(__name__)
client = Client(os.environ["KORZEN_API_KEY"])  # one for the process
app.wsgi_app = KorzenWSGI(
    app.wsgi_app,
    client=client,
    prefixes=["/checkout", "/signup"],  # every path when left out
    ip=last_forwarded_ip,  # behind your own load balancer or nginx
)


@app.post("/checkout")
def checkout():
    decision = request.environ["korzen.decision"]  # a Decision, or None
    ...
```

The middleware answers a block with 403, sends a challenged page load (GET or HEAD) to the
challenge page and back, refuses any other challenged request with 403, and otherwise runs
your app with the decision in `environ["korzen.decision"]`, `None` when there is none.
Back from the challenge page, it keeps the token as the `_kz` cookie and sends the visitor
to the same address without it, the rest of its query byte for byte (a presigned or an
OAuth address still verifies). The way there is the address's path and query alone, a
relative `Location`, unless you set `public_url` or `return_to`: a host a request names
(`X-Forwarded-Host`, which a visitor may write) never goes in it, and a path that opens
with `//` or `/\` is one slash, so the visitor stays on your site. Of two `_kz` cookies,
the first in the `Cookie` header is the token, as the tag and the server read it: set no
`_kz` for a parent domain.

The token is read from the `x-korzen-token` header when the page sends one
(`korzen.token()` to an API on another origin, or from a frame, where the cookie does not
travel), else from the `_kz` cookie: you add nothing on the server. A header that is empty
or no token leaves the cookie (`read_token`).

### Django

In `wsgi.py`:

```python
application = KorzenWSGI(get_wsgi_application(), client=client, prefixes=["/checkout/"])
```

or in `asgi.py`:

```python
application = KorzenASGI(get_asgi_application(), client=client, prefixes=["/checkout/"])
```

The decision is then `request.META["korzen.decision"]` under WSGI and
`request.scope["korzen.decision"]` under ASGI. Both adapters send the request's header
order: `KorzenWSGI` from the environ's `HTTP_*` keys, which gunicorn adds in the order the
headers came (behind nginx or a load balancer, the order that hop forwards in).

### FastAPI and Starlette

```python
app.add_middleware(KorzenASGI, client=client, prefixes=["/checkout"])


@app.post("/checkout")
async def checkout(request: Request):
    decision = request.scope["korzen.decision"]
```

`KorzenASGI` makes the call, which blocks, on threads of its own, never on the event loop,
and sends the request's header order with it. It leaves WebSocket and lifespan events
alone.

### Payment, login and sign-up routes

Turn on `require_token` on the routes a script goes after: the post that charges a card or
places an order, the one that checks a password, the one that creates an account. A script
that never loads your page (card testing from a new residential IP for each try) runs no
tag and is answered `unknown`, which is allowed. With the option, the action needs a token
the tag earned in that browser. Without one, `token_required` is true. In block mode
`action` is then `challenge`, or `allow` when the challenge cannot be issued (fail-open);
in monitor mode `action` stays `allow`. A `block` stays a `block`, and the class does not
change. `token_required` is false while the protection is paused. A page load spends no
token, so guard the form's page too.

```python
app.wsgi_app = KorzenWSGI(
    app.wsgi_app,
    client=client,
    prefixes=["/checkout", "/login", "/signup"],
    require_token=True,  # on actions only: GET, HEAD and OPTIONS spend no token
)
```

Start in monitor mode, and watch the share of decisions without a token before you turn on
block mode: a visitor whose browser does not run the tag (an ad blocker, a DNS filter,
JavaScript off) holds no token, and cannot pass the challenge page on these routes. Leave
the option off the routes no page of yours leads to (webhooks, a mobile app's API). More:
https://korzen.dev/bot-protection/docs/protecting-a-checkout.

### The call alone

```python
decision = client.decide(from_wsgi(request.environ, path="/signup"))
if decision is not None and decision.action in ("block", "challenge"):
    ...
```

On sign-in, sign-up and checkout, refuse a `challenge` as a `block` unless your own check
(a CAPTCHA, an email or phone code) or the challenge page runs: never let it through. Most
scripts that send a browser's User-Agent are answered `challenge`, not `block`.

`Client.decide` takes a `DecideRequest` (a dict of the API's fields) and returns the
`Decision`, or `None` on any failure; it never raises. It sends its timeout as
`Korzen-Deadline-Ms`. Every call names the SDK in `Korzen-Sdk: python/<__version__>`.
`from_wsgi` and `from_asgi` build the request from a WSGI environ or an ASGI scope.

A `Decision` carries the v1 answer's eight members: `request_id`, `class_`, `bot_score`,
`action` (apply it alone), `mode` (`monitor`, `block` or `paused`), `challenge` (a
`ChallengePage` with `url` and `passed`, or `None`), `token_required` and `decoy` (`True`
only on a block or a challenge Korzen would rather answer with your decoy, see
`on_decoy`). Any other member of the answer is read past; `raw` holds the whole answer.

### The context

`context` is what your server knows of the person behind the request: `decide` normalises
it and sends only hashes and the fields in clear, so the raw email, phone, card
fingerprint and ids never leave your server. A value that does not read as its kind is
left out, never an error; an absent field is never evidence of a bot.

```python
decision = client.decide(
    {
        "ip": ip,
        "path": "/signup",
        "context": {
            "email": email,  # its domain sent, the address hashed
            "phone": phone,  # E.164, spaces, dashes, dots and brackets allowed
            "phone_country": "NL",
            "phone_type": "mobile",
            "card_bin": card_bin,  # the first 6 to 8 digits; past 8 left out, and logged once
            "card_fingerprint": fingerprint,  # Stripe's card.fingerprint
            "account_id": account_id,
            "resource_id": order_id,
        },
    }
)
```

On an action with `require_token`, the context's `identity_id` (the account, a verified
email, a fan id) with `places_per_identity` (1 to 10, 1 when left out) is how many
sessions of one identity may take the path in an hour. Past them, no challenge page is
offered. In block mode `action` is then `challenge`; in monitor mode `action` stays
`allow`. A `block` stays a `block`, and the class does not change. While the protection is
paused, no place is counted.

Every Korzen SDK keys the context alike and passes the cases of the API's `contract.json`:
the email's domain an A-label, the address in NFC and lower case, its `+tag` cut,
`gmail.com`'s dots taken out. The standard library has no UTS #46, so an email whose
domain holds a character outside the Latin, Greek, Cyrillic, Japanese, Chinese and Korean
letters (a full-width letter, a ligature) is left out rather than hashed apart from the
other SDKs. `context_fields`, `normal_email` and `normal_phone` show what is sent.

### Events and feedback

```python
client.feedback([{"request_id": decision.request_id, "outcome": "chargeback"}])
client.events([{"kind": "page", "path": "/pricing", "method": "GET"}], idempotency_key=order_id)
```

Each sends 1 to 1000 items and returns a `BatchAnswer` (`accepted`, `duplicates`,
`rejected`, `errors`), or `None` when nothing was recorded; neither raises. The call has
an `Idempotency-Key`, a UUID v7 unless you give one, and is sent again under it on no
answer, a 409, a 429 or a 5xx: `retries` times (2), after `Retry-After` or `retry_delay`
doubled each time (30 times at most), within `batch_timeout` (5 s) in all: a wait past
what is left of it ends the batch at once, and nothing is recorded. They block: call them
off the request, from a thread or a task queue.

### What each call ended with

```python
def log(answer):  # status, request_id (Korzen-Request-Id), rate_limit, replayed, problem
    logger.info("korzen %s %s %s", answer.route, answer.status, answer.request_id)


client = Client(os.environ["KORZEN_API_KEY"], on_answer=log)
```

`on_answer` is told of each call's answer: an error's `application/problem+json` body as a
`Problem` (`code`, `detail`, `request_id`…), the `RateLimit-Policy` and `RateLimit`
headers as a `RateLimit` (`parse_rate_limit` reads them alone). It runs on a thread of its
own, waited on only within the call's budget: a slow one goes on alone, and one that
raises costs the call nothing (logged once). At most `MAX_HOOKS` (64) run at once.

## First-party mode

A DNS filter, an ad blocker or a network that blocks `korzen.dev` stops the tag, its
beacon and the challenge page, so those visitors are judged with less, and on a
`require_token` route they cannot pass. First-party mode serves all three from your own
domain, under `/kz` by default, and forwards them to Bot Protection with the visitor's
address. Turn it on in the middleware, and the page loads the tag from it:

```python
app.wsgi_app = KorzenWSGI(app.wsgi_app, client=client, ip=last_forwarded_ip, first_party=True)
app.add_middleware(KorzenASGI, client=client, ip=last_forwarded_ip, first_party=True)
```

```html
<script src="/kz/tag.js" data-site-key="sk_..." async></script>
```

- **What it serves.** `GET /kz/tag.js`, `GET /kz/n`, `POST /kz/s` (a body of at most 64
  KiB), `GET /kz/ping` (answered `204` by the middleware itself, never forwarded),
  `GET`/`POST /kz/challenge` (a post of at most 16 KiB), `GET /kz/challenge/wait` and
  `GET /kz/static/<file>`. Any other path under `/kz` is a `404`, a known one with another
  method a `405`; neither reaches Bot Protection. A body past its cap is a `413`. The
  requests under the path are never judged and never reach your app, whatever `prefixes`
  says; every other path is judged as before.
- **What it sends.** The browser's `User-Agent`, `Accept`, `Accept-Language`,
  `Content-Type`, `Origin`, `Sec-Fetch-*`, `Sec-CH-*` and `If-None-Match`, your key as the
  bearer, the visitor's address in `Korzen-Visitor-Ip` (read by `ip`, as a decision reads
  it) and the path in `Korzen-Forwarded-Prefix`. Never a `Cookie`, the browser's
  `Authorization` or an `X-Forwarded-*`. What comes back keeps Korzen's caching and
  security headers, never a `Set-Cookie`; a redirect goes back to the browser, never
  followed.
- **The challenge page.** A challenged page load goes to `/kz/challenge?c=…&r=…` on your
  domain instead of `korzen.dev`, so a visitor who cannot reach `korzen.dev` still solves
  it. An `on_challenge` hook that sends the visitor itself gives your path to
  `challenge_redirect(decision, return_to, prefix="/kz")`: Korzen's `/challenge` goes
  under it with its query, a page elsewhere is kept, and a path that does not read is
  none.
- **The path.** `first_party_path` names another one, for example once a block list learns
  `/kz`: it starts with `/`, ends without one, and is at most 64 characters of
  `A-Z a-z 0-9 . _ ~ -` segments. One that does not read is logged once, and the mode
  stays off.
- **The raw path.** The middleware routes the path as the visitor wrote it, escapes and
  all, from `RAW_URI` (gunicorn) or `REQUEST_URI` (uWSGI) under WSGI and `raw_path` under
  ASGI; a WSGI server that keeps neither gives it decoded.
- **Behind the Cloudflare Worker.** The
  [Node SDK's Worker](../node/README.md#first-party-mode) with `KORZEN_FIRST_PARTY` and a
  route for `/kz/*` answers the path itself, so the middleware never sees it;
  `first_party=True` here, with the same path, sends challenged visitors to
  `/kz/challenge`, which the Worker serves. Without the Worker in front of `/kz/*`, the
  middleware serves it, with `ip=cloudflare_ip` behind Cloudflare.
- **Fail open.** Bot Protection slow (past 1 s for a GET, 2.5 s for a POST, the visitor's
  body included), down or answering garbage, no visitor address, no key, an error in the
  forwarder: a `503` with an empty body and `Cache-Control: no-store`. The tag drops that
  signal and the page goes on; your other routes wait on nothing. Bot Protection's own
  `4xx` and `5xx` pass through. The first error is logged once, and so is a visitor's
  address on your own network (set `ip` then).
- **The transport.** Forwards go through the client's `transport` when it is an
  `HTTPTransport` (or has its `request` method, a `ForwardTransport`), else through the
  shared one; of an answer they read at most 4 MiB.
- **How to tell it works.** In the browser's network tab, the tag's requests go to your
  own `/kz/tag.js`, `/kz/n`, `/kz/ping` and `/kz/s`, none to `korzen.dev`; `/kz/ping`
  answers `204`.

## Options

| Option             | What it does                                                                                                                                   |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `client`           | the `Client`: `Client(api_key, url=..., timeout=0.2, on_answer=..., logger=...)`                                                               |
| `ip`               | reads the visitor's IP: `remote_ip` (default), `last_forwarded_ip`, `cloudflare_ip`; the scheme (`http`/`https`) is read from the same edge    |
| `path`             | names the action in the decision, instead of the request's path                                                                                |
| `on_decoy`         | answers a block or a challenge marked `decoy` with your decoy, first; when it writes nothing, the default decoy (`202` with `{}` on an action) |
| `on_block`         | answers a blocked request instead of the 403                                                                                                   |
| `on_challenge`     | answers a challenged request instead of the redirect                                                                                           |
| `public_url`       | the origin your visitors see, behind a proxy that forwards `Host: localhost`                                                                   |
| `return_to`        | builds the address to come back to from the challenge page                                                                                     |
| `prefixes`         | the paths guarded, each a prefix; every path by default                                                                                        |
| `require_token`    | sends `require_token` on an action (not GET, HEAD or OPTIONS): it needs the tag's token                                                        |
| `first_party`      | [first-party mode](#first-party-mode): serves `first_party_path` and forwards it; `False` by default                                           |
| `first_party_path` | the path first-party mode serves, `/kz` by default                                                                                             |
| `cdn`              | [the CDN your server stands behind](#behind-a-cdn), whose headers carry the visitor's JA4; none by default                                     |
| `max_workers`      | `KorzenASGI` only: the threads that make the call, 64                                                                                          |

A block or a challenge marked `decoy` (you turned the decoy on for its class on Set-up)
goes to your decoy handler when you give one. Without it, an action (`POST`, `PUT`,
`PATCH`, `DELETE`) is answered `202` with `{}` as `application/json`, an empty success
with no header of Korzen's, and your handler never runs; a page load (`GET`, `HEAD`) is
refused as any other, a `403` or the challenge page, because a blank page would break your
site for a person judged a bot by mistake. Your handler replaces the default.

`decoy` is true only when you turned the decoy on for the class (`bot`, `bot_high`),
`action` is `block` or `challenge`, and what the visitor itself showed is enough for `bot`
or `bot_high`, leaving out what Bot Protection learned from your traffic as a whole and
any absent signal. It is never true for a verified crawler, for `token_required`, for an
identity past its places, for a session that passed the challenge page in the last 30
minutes or could not be checked for it, nor in monitor or paused mode.

A hook takes `(environ, start_response, decision)` under WSGI and returns the body, or
`None` to let the request go on; under ASGI it is a coroutine of
`(scope, receive, send, decision)` that returns whether it answered. The timeout bounds
the whole decide call, in seconds, the name's lookup included; `batch_timeout`, `retries`
and `retry_delay` bound events and feedback. A `transport` of yours is raced against the
same budgets on a thread (256 calls in flight at most, one more fails open at once), so
one that never answers costs no more than the timeout, and what it answers later is
dropped; the client keeps up to 256 connections open between calls, and is safe to share
between threads.

The client checks its settings when it is made. The API key is trimmed of the spaces and
line breaks around it. `url` is an `https` URL, or `http` on loopback (`localhost`,
`127.0.0.0/8`, `[::1]`) for a test on your machine; `timeout` is more than 0 and at most
`MAX_TIMEOUT` (1 s); `batch_timeout` and `retry_delay` are more than 0 and at most
`MAX_WAIT` (about 24 days); `retries` is a whole number from 0. A setting that does not
read is logged once and left at its default: a URL that would send the key in clear, or
nowhere, is `https://korzen.dev`. An empty key is logged too, and every call fails open.
No setting raises, and none makes a call raise.

The client warns once, through its logger (`korzen_bot_protection` by default), when the
IP it sends is on your own network, as it is behind a load balancer: set `ip` then; and
once for each setting it did not take.

Fail open: a hook of yours that raises, a challenge page that is no `http(s)` URL of
visible ASCII within 2048 characters, an answer the server refuses: each lets the request
through to your app, with the decision, and is logged once through the client's logger. A
WSGI hook's `start_response` is held until it returns, so one that raises has sent
nothing; once a hook has written part of its answer, nothing more is sent.

## Behind a CDN

Several CDNs forward the visitor's JA4 (their TLS fingerprint) to your server in their own
headers, and CloudFront also the order the visitor sent their headers in and their HTTP
version. Name your CDN with the `cdn` option (on `KorzenWSGI`, `KorzenASGI`, `from_wsgi`,
`from_asgi` and `from_incoming`) and the SDK sends them with each decision:

```python
app.wsgi_app = KorzenWSGI(app.wsgi_app, client=client, ip=last_forwarded_ip, cdn="cloudfront")
```

| `cdn`              | The header, and how to turn it on                                                                                                           |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `cloudfront`       | add `CloudFront-Viewer-JA4-Fingerprint`, `CloudFront-Viewer-Header-Order` and `CloudFront-Viewer-Http-Version` to the origin request policy |
| `azure_front_door` | `X-Azure-JA4-Fingerprint`, on already                                                                                                       |
| `vercel`           | `x-vercel-ja4-digest`, on already                                                                                                           |
| `bunny`            | `CDN-JA4` (bunny.net), on already                                                                                                           |
| `google_cloud`     | Google Cloud's load balancer: add the custom request header `X-Client-JA4:{tls_ja4_fingerprint}` on the backend service                     |
| `fastly`           | `set req.http.X-Client-JA4 = tls.client.ja4;` in `vcl_recv`                                                                                 |

`CDNS` names them; `cdn_fields(incoming, cdn)` reads them from a request alone. A value
that does not read (a JA4 outside its pattern, a header sent twice, an order with a name
that is no header's) is left out, and a field you set yourself on the decision's request
wins. Behind a CDN the order your server received the headers in is the CDN's, not the
visitor's, so with `cdn` set it is never sent.

**Name a CDN only when your server takes traffic from it alone.** Anyone can send these
headers to a server reachable around its CDN, so they are never read unless you name it,
as `cloudflare_ip` reads `CF-Connecting-IP`.

## Supported versions

Python 3.11, 3.12, 3.13, 3.14 and 3.15.

The guide: https://korzen.dev/bot-protection/docs/python.

## Licence

Proprietary, see [the licence](https://korzen.dev/bot-protection/sdk/license): you may use
it only to integrate with Korzen while you hold an account.
