Metadata-Version: 2.4
Name: fingerly
Version: 0.5.1
Summary: Server-side Fingerly SDK: event reads, webhook verification and a same-origin proxy
Project-URL: Documentation, https://docs.fingerly.io/docs/sdks/python
Project-URL: Source, https://github.com/fingerly-io/sdk-python
Author: Fingerly
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: bot-detection,device-fingerprinting,fingerly,fraud
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
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: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.27
Description-Content-Type: text/markdown

<p align="center">
  <a href="https://fingerly.io">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/logo-dark.svg">
      <img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/logo-light.svg" alt="Fingerly" height="44">
    </picture>
  </a>
</p>

<p align="center"><b>Fingerly for Python</b><br>Read events, verify webhooks and serve a first-party proxy from your Python backend, with sync and asyncio clients.</p>

<p align="center">
  <a href="https://pypi.org/project/fingerly/"><img src="https://img.shields.io/pypi/v/fingerly?style=flat-square" alt="PyPI version"></a>
  <a href="https://github.com/fingerly-io/sdk-python/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/fingerly-io/sdk-python/ci.yml?branch=main&style=flat-square&label=CI" alt="CI status"></a>
  <img src="https://img.shields.io/badge/python-3.9%2B-blue?style=flat-square" alt="Python 3.9 or newer">
  <a href="https://github.com/fingerly-io/sdk-python/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square" alt="Apache-2.0 licence"></a>
  <a href="https://docs.fingerly.io/docs/sdks/python"><img src="https://img.shields.io/badge/docs-docs.fingerly.io-blue?style=flat-square" alt="Documentation"></a>
</p>

<p align="center"><img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/banner.webp" alt="Fingerly" width="100%"></p>

## What is this

`fingerly` is the server-side Python package for [Fingerly](https://fingerly.io), which identifies the device behind every web and app session and scores how suspicious it is. Use it to protect signups, logins and payments: read the event the browser SDK produced with a server-only secret key, verify webhook signatures, relay the browser SDK's traffic through your own domain, and report the requests your server served so AI crawlers that never run JavaScript are seen.

Two clients share one API: `Fingerly` for synchronous code such as Django and Flask, and `AsyncFingerly` for asyncio code such as FastAPI and Starlette. Python 3.9 or newer. One runtime dependency, `httpx`. The proxy serves both ASGI and WSGI, so it mounts under either.

## Getting started

**1. Prerequisites.** A Fingerly account and a secret key (see [API keys and environments](https://docs.fingerly.io/docs/api-keys)). A webhook signing secret to verify webhooks, and a proxy key (see [Proxy integrations](https://docs.fingerly.io/docs/proxy-integrations)) for the proxy.

**2. Install.**

```sh
pip install "fingerly>=0.5.1"
```

**3. Read an event.**

```python
import os
from fingerly import Fingerly

fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
page = fingerly.events.list(level="high", limit=50)
event = fingerly.events.get(page.rows[0].request_id)
```

The same with `AsyncFingerly`:

```python
import asyncio
import os
from fingerly import AsyncFingerly


async def main() -> None:
    async with AsyncFingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"]) as fingerly:
        page = await fingerly.events.list(level="high", limit=50)
        for row in page.rows:
            print(row.request_id, row.suspect_score)


asyncio.run(main())
```

**4. Verify a webhook.**

```python
import os

from flask import Flask, abort, request

from fingerly import WebhookEventType, verify_webhook

app = Flask(__name__)


@app.post("/webhooks/fingerly")
def fingerly_webhook():
    if not verify_webhook(
        secret=os.environ["FINGERLY_WEBHOOK_SECRET"],
        payload=request.get_data(),
        timestamp=request.headers.get("x-fingerly-timestamp"),
        signature=request.headers.get("x-fingerly-signature"),
    ):
        abort(400)
    delivery = request.get_json()
    if delivery["type"] == WebhookEventType.VISITOR_SUSPECT:
        print(delivery["data"])
    return "", 204
```

In a web app, build the client once and reuse it: see [Framework guides](#framework-guides) for FastAPI, Django and Flask.

Full documentation: [docs.fingerly.io/docs/sdks/python](https://docs.fingerly.io/docs/sdks/python).

## Choose what you need

| I want to | Go to |
| --- | --- |
| Read an event | [Read events](#read-events) |
| Verify and consume an event before a backend action | [Verify a backend action](#verify-a-backend-action) |
| Read or write an iOS device's DeviceCheck bits | [Read and write Apple DeviceCheck bits](#read-and-write-apple-devicecheck-bits) |
| Check a webhook signature | [Verify webhooks](#verify-webhooks) |
| Keep identification working behind content blockers | [First-party proxy](#first-party-proxy) |
| See AI crawlers that never run your page's JavaScript | [Agent sightings](#agent-sightings) |
| Mount the proxy in FastAPI, Django or Flask | [Framework guides](#framework-guides) |
| Tune deadlines, pools and the API version | [Timeouts](#timeouts), [Connections](#connections), [API version](#api-version) |

## Contents

- [Read events](#read-events)
- [Read and write Apple DeviceCheck bits](#read-and-write-apple-devicecheck-bits)
- [Verify webhooks](#verify-webhooks)
- [First-party proxy](#first-party-proxy)
- [Agent sightings](#agent-sightings)
- [Framework guides](#framework-guides)
- [Timeouts](#timeouts)
- [Connections](#connections)
- [API version](#api-version)
- [Development and release preparation](#development-and-release-preparation)
- [Requirements](#requirements)
- [Documentation](#documentation)
- [Help](#help)
- [Licence](#licence)

## Read events

Event reads require `fly_sk_{production|staging|development}_…` keys. Requests go to `https://api.fingerly.io`; `endpoint` overrides that for a local API. `endpoint` takes a scheme, a host and an optional port and nothing else: a path, query, fragment, credentials, space or control character is refused when the client is built. It must be `https`. Plain `http` is accepted only for `127.0.0.1`, `localhost` or `[::1]`, and only with `allow_insecure_loopback=True`, which is meant for local development and tests. Public, proxy, management, malformed and unsupported keys are rejected before network access. Requests do not follow redirects. `get` and `list` each perform one request and never retry.

| | `Fingerly` | `AsyncFingerly` |
| --- | --- | --- |
| Calls | `fingerly.events.get(id)` | `await fingerly.events.get(id)` |
| Closing | `fingerly.close()` or `with Fingerly(...) as fingerly:` | `await fingerly.aclose()` or `async with AsyncFingerly(...) as fingerly:` |

Each client holds pooled connections. Build one and reuse it; build one per event loop for `AsyncFingerly`.

> **Never call `Fingerly` from `async def` code.** It blocks the event loop for the whole request, so every other request on that worker waits behind it: five reads against a slow API stall a FastAPI worker for five timeouts in a row. Use `AsyncFingerly` there, or a plain `def` route, which FastAPI and Starlette run in a thread. `Fingerly` raises a `RuntimeWarning`, once per process, when it finds itself on a running event loop.

### Read an event you just identified

Send the `requestId` the browser SDK returned to your server and read it there with `fingerly.events.get(request_id)`, or `await fingerly.events.get(request_id)` with `AsyncFingerly`. A `404` carries one of two codes:

| Code | Raises | Meaning |
| --- | --- | --- |
| `event_pending` | `FingerlyEventPendingError`, a `FingerlyAPIError` | The request id was accepted but its event is not recorded yet. It is not a verdict. Try again after `retry_after` seconds, or verify asynchronously, for example from a webhook. The SDK never retries on its own. |
| `event_not_found` | a plain `FingerlyAPIError` | The request id was never issued for this key's environment, or the event is past the 30-day retention. |

The archived `document` arrives moments after the event itself, so check `has_document` rather than assuming it is there, and call `event.parse_document()` when you want a typed `EventDocument`.

### Event fields

- `ip_network` is the network the request came from (an IPv4 /24 or an IPv6 /40, such as `203.0.113.0/24`); the API never returns the address.
- When a submission is unidentifiable (`event.identifiable is False`, such as insufficient entropy, a genuine embedded WebView, or an unmatched high-risk Web payload), `event.visitor_id` is `""`. There are no `deferred_token`, `deferred_signals` or `supplements` fields in `v: 3`.
- `document`, when available, is an allow-listed view of the archived request with no raw signals, user agent or address. `event.parse_document()` decodes it into a typed `EventDocument` (including `attestation: Optional[Attestation]`). A native `Attestation` also carries `attest_skipped` (the app's reason for sending no proof) and `downgrade` (the report named an install an attested device owns).
- `suspect_level`, `state`, `environment`, each trigger's `signal` and `confidence`, and an `Attestation`'s `state`, `status` and `attest_skipped` hold the string the API sent. Compare them with the matching enum: `SuspectLevel`, `EventState`, `Environment`, `Signal`, `Confidence`, `AttestationState`, `AttestationStatus` and `AttestSkippedReason`. Every member is a `str` equal to its value, so `event.suspect_level == SuspectLevel.HIGH` and `Signal.FINGERPRINT_SUPPRESSED in signals` work on plain strings, and a value a newer server adds still parses. Compare rather than convert: `SuspectLevel(value)` raises `ValueError` for a value this release does not know.
- `Signal` names every signal group and detector, including the `v: 3` anti-spoofing and integrity signals `ATTESTATION_FAILED`, `ATTESTATION_DOWNGRADE`, `DEVICE_INCONSISTENT`, `REPORT_INCOMPLETE`, `PROBE_ERRORS`, `FETCH_METADATA_MISSING`, `WEB_TICKET_MISSING`, `WEB_TICKET_INVALID`, `TAMPERING`, `CUSTOM_ROOT_CA` and `SECONDARY_USER_PROFILE`. `SIGNAL_NAMES` holds the same values as plain strings.

```python
from fingerly import Signal, SuspectLevel

signals = [trigger.signal for trigger in event.triggers]
if event.suspect_level == SuspectLevel.HIGH or Signal.FINGERPRINT_SUPPRESSED in signals:
    send_to_review(event)
```
- `suspect_score` is `None` when the request was not scored, and must not be treated as zero.
- `project_id` is the UUID string of the Fingerly project the event belongs to, on both `events.get` and the rows of `events.list`; it is `None` when an older server does not send it.
- `visitor_kind` says what sort of client made the request; compare it with `VisitorKind`. When it is `VisitorKind.AI_BOT`, `event.ai` is an `AIAgent`: `name` and `provider` (plain strings, such as `ChatGPT-User` and `OpenAI`), `purpose` (`AIPurpose`), `runtime` (`AIRuntime`), `declared`, and `verification` with `method` (`AIVerificationMethod`) and `result` (`AIVerificationResult`). On every other event `ai` is `None`. The agent is named by a Web Bot Auth signature when the request carried one, otherwise by its user agent. `verification` says how far that was checked: `AIVerificationMethod.SIGNATURE` (the operator's published key signed the request) or `AIVerificationMethod.IP_LIST` (the address is inside the operator's published ranges), with result `AIVerificationResult.PASS`, `AIVerificationResult.FAIL` (the name was borrowed), or `AIVerificationResult.NOT_ATTEMPTED` with method `AIVerificationMethod.NONE` (the operator publishes nothing to check against, or it could not be checked; the name is then only the client's claim). Only clients that run the browser SDK produce events, so a crawler that does not run JavaScript never appears. `events.list` narrows by `kind`, `ai_provider` (exact and case sensitive, as events name it) and `ai_purpose`, next to `visitor` and `level`:

```python
from fingerly import AIPurpose, VisitorKind

page = fingerly.events.list(kind=VisitorKind.AI_BOT, ai_purpose=AIPurpose.USER_FETCH)
for event in page.rows:
    if event.ai is not None:
        print(event.ai.provider, event.ai.name)
```
- `Event` declares every documented field as an attribute and falls back to the decoded body for fields added later, so a new server field needs no SDK upgrade.

### Errors

`FingerlyAPIError` provides `status`, and optional `code`, `details`, `request_id` and `retry_after`, the seconds a `429`, a `503` or a `404 event_pending` asks you to wait (`None` when the response did not say). The secret key is stripped from all of them. Every status outside 2xx raises it, a redirect included, since requests never follow one. `FingerlyTimeoutError` and `FingerlyConnectionError` cover a deadline and an unreachable API; all three derive from `FingerlyError`.

### Verify a backend action

Send the browser's `requestId` to your server and verify it there with a server-only key. `fingerly.events.verify` reads the event and runs these checks in order, stopping at the first that fails:

| Order | Reason | `VerifyReason` | Fails when |
| --- | --- | --- | --- |
| 1 | `not_found` | `NOT_FOUND` | The event does not exist for this key's environment. |
| 2 | `too_old` | `TOO_OLD` | It occurred more than `max_age_seconds` ago (300 by default). A missing or unreadable `occurred_at` fails too. |
| 3 | `tag_mismatch` | `TAG_MISMATCH` | You passed `tag` and the event's tag is not exactly that. |
| 4 | `unidentifiable` | `UNIDENTIFIABLE` | The event has no visitor id. |
| 5 | `unscored` | `UNSCORED` | The event has no `suspect_score`. |
| 6 | `already_consumed` | `ALREADY_CONSUMED` | The event was consumed before. |

Consumption comes last, only when every other check passed, so one event backs one decision: a replayed `requestId` answers `already_consumed`. Pass `consume=False` to check without consuming. The result is a `VerifyResult` with `ok`, `reason` (a `VerifyReason`, `VerifyReason.OK` or `""` when `ok`, and equal to the strings above otherwise) and `event` (`None` only for `not_found`).

`verify` never judges the score: that policy stays with you. Check `suspect_level` or `suspect_score` after `ok`.

```python
from fingerly import SuspectLevel, VerifyReason

result = fingerly.events.verify(request_id, tag="checkout")
event = result.event
if result.reason == VerifyReason.ALREADY_CONSUMED:
    refuse_replay()
elif not result.ok or event is None:
    refuse(result.reason)
elif event.suspect_level == SuspectLevel.HIGH:
    send_to_review(event)
else:
    allow()
```

`AsyncFingerly` has the same call as a coroutine. An invalid option (a `max_age_seconds` that is not a positive integer, an empty `tag`) raises `TypeError` before anything is sent. `fingerly.events.consume(request_id)` consumes an event on its own: the first call answers a `ConsumeResult` with `first=True`, and every later one raises `FingerlyEventAlreadyConsumedError`, a `FingerlyAPIError` whose `consumed_at` says when. Neither call is retried.

Do not authorize an action using scores or visitor identifiers supplied by the browser. Tags correlate events; they do not replace your application's authentication. A tag must never hold a personal identifier, such as a user ID, email, install ID or advertising ID, because the server keeps tags in long-lived rollups. `verify` raises every error other than `event_not_found` and `event_already_consumed`. A `FingerlyEventPendingError` means the server has not decided yet: retry after `retry_after` seconds or verify asynchronously, and do not refuse the action as fraud on that answer alone. The framework guides below answer it with `503` and `Retry-After`.

## Read and write Apple DeviceCheck bits

For an iOS identification whose App Attest evidence carried DeviceCheck tokens, Fingerly holds two tokens for one hour, a read token and a write token, and a secret key of the same project and environment can spend each once: the read token to read the device's two bits from Apple, the write token to set them. The bits mean what you decide; Fingerly never stores or reads them.

Apple treats a DeviceCheck token as single-use, so one identification supports one read and one write. A once-per-device free trial does both on the identification that asks for the trial:

1. Query the bits. If the bit says the device already had one, refuse it.
2. Otherwise grant the trial and record the grant in your own data.
3. Write the bit with the same request ID. Until the write lands, your own record of the grant is what stops a second trial.

```python
from fingerly import FingerlyDeviceCheckError

try:
    bits = fingerly.device_check.query(request_id)
    used_on_device = bits.found and bits.bit0
except FingerlyDeviceCheckError as error:
    if error.code not in ("device_check_not_held", "device_check_spent"):
        raise
    used_on_device = False  # no answer, not a verdict

if not used_on_device:
    # Grant the trial in your own data, then mark the device.
    fingerly.device_check.write(request_id, bit0=True)
```

`AsyncFingerly` has the same calls as coroutines. `write` sends only the bits you name; naming neither raises `TypeError` before anything is sent.

Every non-2xx answer raises `FingerlyDeviceCheckError` (a `FingerlyAPIError`); branch on `code`:

| Status | `code` |
| --- | --- |
| `404` | `device_check_not_held` |
| `409` | `device_check_spent`, `device_check_busy` or `credential_unavailable` |
| `422` | `bits_required` or `apple_rejected` (with Apple's HTTP status in `apple_status`) |
| `503` | `device_check_unavailable` |

A `503` or a transport failure leaves the token held, and the SDK retries the identical request, at most twice. A held token kept for a retry accepts only the request it was first used for: a second read, or a write with other bits, on that event answers `409 device_check_spent`. No other answer is retried.

## Verify webhooks

The example under [Getting started](#getting-started) verifies a delivery in Flask.

`identification.completed` and `visitor.suspect` deliveries carry the event's project as `data["project_id"]`; `identification.refused` carries it only when the refused request named a known key. The SDK passes the payload through unmodelled, so read it from the parsed JSON. Compare its `type` with `WebhookEventType` (`IDENTIFICATION_COMPLETED`, `IDENTIFICATION_REFUSED`, `VISITOR_SUSPECT`, `BILLING_STATUS_CHANGED`, `USAGE_DAILY_SETTLED`, and `WEBHOOK_TEST` from **Send test event**), and ignore types you do not handle.

Verify the exact raw bytes before JSON parsing. Signatures cover the timestamp and body. The default replay tolerance is 300 seconds; persist processed webhook IDs to deduplicate deliveries. During signing-secret rotation, any matching signature in the comma-separated header is accepted; only the first 32 are read. The function never raises for malformed input: bad input is a failed verification, not an exception.

## First-party proxy

Content blockers refuse browser requests to third-party APIs, and a refused identification is a visitor never identified. Mount the proxy on a path of your own site and those requests become first-party. The proxy key is what lets that hop declare the visitor's real address, origin and user agent; a public key alone never can, so nobody can spoof them.

Create a proxy in the dashboard (**Integration > Proxy keys**). It issues the proxy key and a random path, such as `/k7x2qm4a`, for you to serve it on. One `FingerlyProxy` holds the configuration and exposes both server standards, so a project running each gets the same behaviour from one instance.

```python
import os

from fingerly import FingerlyProxy

proxy = FingerlyProxy(
    proxy_key=os.environ["FINGERLY_PROXY_KEY"],
    path="/k7x2qm4a",
    client_ip=lambda request: (
        request.headers.get("cf-connecting-ip") or request.peer_host
    ),
)
```

Then point the browser SDK at the same path:

```ts
const fingerly = await load({ apiKey: 'fly_pk_…', endpoints: '/k7x2qm4a' })
```

### Which adapter to serve

| Your framework | Serve | Notes |
| --- | --- | --- |
| FastAPI, Starlette, Django's ASGI stack, Quart, Litestar | `proxy.asgi` | Under Starlette and FastAPI use `app.add_route`, not a `Mount`: Starlette answers a mount's bare path with a redirect to its slashed form, the browser SDK posts to the bare one, and the proxy does not answer the slashed one. |
| Flask, Django's WSGI stack, Pyramid | `proxy.wsgi` | |

The [framework guides](#framework-guides) show each in full.

### The path

`path` is the path the dashboard issued, within your application. With it set, the proxy answers that one path, exactly, and anything else gets `404`, including anything under it, a trailing slash, another letter case, a dot segment or a percent-encoded spelling of the same path. It excludes anything a sub-URI deployment adds, and a path the mount has already stripped works too, so the same configuration serves an app at the root and one served from `/shop`. It is optional: leave it out and the proxy answers whatever your framework routes to it, which is safe only where the framework routes that one path and nothing else. There is no default path. Use the one the dashboard issued rather than inventing one: blockers look for words such as `fingerprint`, `tracking` and `fingerly`.

### What the proxy does

Browser and proxied native client SDKs post a single `v: 3` identification envelope to that one path. The proxy forwards its raw request body bytes verbatim (without JSON decoding or re-serialising) to Fingerly's one ingest URL, `https://api.fingerly.io/api/v1/ingest`, and to nothing else. Event reads need a secret key and stay unreachable from a browser by construction.

| Situation | Answer |
| --- | --- |
| Path other than the configured one (`/supplement` subpaths included) | `404` |
| Method other than `POST` (plus `OPTIONS` when `allowed_origins` is configured), matched exactly, so `post` gets `405` too | `405` |
| No public key from the same environment as the proxy key | `401`, nothing forwarded |
| Neither `Origin` nor a validated `x-fingerly-sdk-platform` | `400` (`missing_origin`) |
| Body over 1 MiB (enforced while streaming rather than after buffering) | `413` |
| WSGI body the server cannot read, such as broken chunked framing | `400` |
| Fingerly cannot be reached in time | `504 Gateway timeout` |
| Any other upstream failure: a refused connection, a malformed or truncated response, one over 4 MiB, an upstream redirect or a status outside 200 to 599 | `502 Bad gateway` |
| `client_ip` callback returns no valid address | `500` with the one line `The client IP callback returned no valid address` |

Responses are marked `no-store`. A redirect is never followed, whatever transport you supply. The `504` and `502` answers are short plain text marked `no-store`, and each writes one line, with no stack trace, to the `fingerly.proxy` logger. The line names the kind of failure only, never the upstream address or a key.

### Keys and headers

`proxy_key` is required, and a missing or malformed one fails when the proxy is built. The caller must present a public key (`fly_pk_…`) from the same environment as the proxy key, or the request gets `401` and nothing is forwarded. Upstream, the proxy sends that public key as `X-API-Key` and its own proxy key as `X-Fingerly-Proxy-Key`; a secret key is never part of the proxy.

Incoming headers follow the sanitize-and-restore sequence: all incoming `x-fingerly-*`, `cookie` and `authorization` headers are stripped, restoring `x-fingerly-sdk-platform` only when it matches an exact lowercase native or bridge platform (`ios`, `android`, `react-native`, `react-native-ios`, `react-native-android`, `flutter`, `flutter-ios`, `flutter-android`, `lynx-ios`, `lynx-android`, `capacitor`, `kotlin-multiplatform`). Requests carrying neither `Origin` nor a validated `x-fingerly-sdk-platform` are rejected locally with `400` (`missing_origin`), and `x-fingerly-origin` is never synthesized from `Host`, `Referer` or the request URL. Exactly one channel goes upstream: a request with an `Origin` is forwarded as a browser call with `x-fingerly-origin` and without the platform header, as the API treats the same request sent to it directly.

Alongside verified proxy metadata (`x-fingerly-host` included), only `content-type`, `x-api-key`, `user-agent`, `idempotency-key`, `sec-fetch-*`, `sec-ch-ua-*` and the Web Bot Auth `signature`, `signature-input` and `signature-agent` (each dropped when over 4096 bytes) are forwarded. Customer cookies and authorization headers are never passed on. The proxy reports itself upstream as `python/0.5.1` in `x-fingerly-proxy-version`, which the dashboard shows per proxy, and sends `fingerly-python/0.5.1` as its user agent.

Back to the browser it relays only `content-type`, `x-request-id`, `ratelimit-limit`, `ratelimit-remaining` and `retry-after`, plus its own `cache-control: no-store` and a `content-length` for the decoded body. A content blocker can match a response header by name, so an allowlist is what keeps anything naming Fingerly off the page.

### Resolving the client IP

> **`client_ip` is the one thing you must get right.** Resolve it from a header your own infrastructure sets, such as your load balancer's or CDN's, and fall back to `peer_host`, the socket peer. Trust that header only when traffic can reach your app solely through that CDN or load balancer; otherwise a visitor can send it themselves. Never read the left-most `X-Forwarded-For` value: the visitor writes it. The callback is synchronous, because it is called under both standards.

The callback must return exactly one IPv4 or IPv6 address, such as `203.0.113.7` or `2001:db8::1`. Anything else, including `None`, an empty string, a list, an address with a port, or an exception, is treated as a configuration mistake: the request is not forwarded, the visitor gets `500` with the one line `The client IP callback returned no valid address`, and the `fingerly.proxy` logger reports it once per process.

`ProxyRequest` gives the callback `headers` (case-insensitive), `path`, `method`, `peer_host`, `mount` and `raw_path`. `peer_host` is the socket peer, which is your load balancer rather than the visitor whenever one sits in front of you.

<details>
<summary>A note on mount paths</summary>

Both adapters match the path as the mounted application sees it: `PATH_INFO` under WSGI, and under ASGI the `path` with `root_path` removed when it is still carrying it. Mounted at its own path, the proxy finds that path in the mount instead, `SCRIPT_NAME` or `root_path`, with nothing after it.

That last part needs care. ASGI servers disagree about what `path` holds under a mount: Starlette 0.47 and newer leave it whole and report the prefix separately in `root_path`, while older versions and some routers strip the prefix off it. Both are permitted by the spec, so the proxy detects which one it was given rather than assuming.

Taking the application-relative path rather than the whole one is what makes a sub-URI deployment work. There, `root_path` or `SCRIPT_NAME` carries a prefix that belongs to the deployment and that your `path` knows nothing about, so a proxy matching on the whole path would refuse every request. It is the same rule Rack's `PATH_INFO` and ASP.NET Core's `Request.Path` already follow.

`tests/test_frameworks.py` drives real Starlette and Flask apps, mounted plainly and again under a sub-URI, to keep all of it that way.

</details>

### Closing the proxy

The proxy opens its upstream connections on first use, one pool per standard. Close whichever you used when your app shuts down: `proxy.close()` for WSGI, `await proxy.aclose()` for ASGI. A WSGI process can simply exit.

### Testing against a local API

`upstream` replaces the API origin for testing against a local API. It takes a scheme, a host and an optional port and nothing else: a path, query, fragment, credentials, space or control character is refused when the proxy is built. It must be `https`. Plain `http` is accepted only for `127.0.0.1`, `localhost` or `[::1]`, and only with `allow_insecure_loopback=True`, which is meant for local development and tests:

```python
proxy = FingerlyProxy(
    proxy_key=os.environ["FINGERLY_PROXY_KEY"],
    path="/k7x2qm4a",
    client_ip=lambda request: request.peer_host,
    upstream="http://127.0.0.1:8080",
    allow_insecure_loopback=True,
)
```

## Agent sightings

AI crawlers and fetchers such as GPTBot or ClaudeBot usually fetch a page without running its JavaScript, so the browser SDK never sees them. `AgentSightings` reports the requests your server served to Fingerly, which decides what sent each one, and remembers the answers so your code can ask about a later request without waiting on the network. The console shows the counts with the agents your pages identified.

The SDK forwards raw input only. It never classifies a user agent, never checks an address against a list and never filters requests by what the visitor claims to be.

### Mount it

Wrap your application once per process. It needs a secret key client and the same kind of `client_ip` callback as the [proxy](#resolving-the-client-ip): one trusted address per request, never the left-most `X-Forwarded-For` value.

```python
import os

from fingerly import AgentSightings, Fingerly

fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
sightings = AgentSightings(
    fingerly,
    client_ip=lambda request: (
        request.headers.get("cf-connecting-ip") or request.peer_host
    ),
)

# Flask, Django's sync stack, any WSGI app:
app.wsgi_app = sightings.wsgi(app.wsgi_app)
```

For asyncio applications, use `AsyncAgentSightings` with an `AsyncFingerly` client and wrap the ASGI app:

```python
from fingerly import AsyncAgentSightings, AsyncFingerly

fingerly = AsyncFingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
sightings = AsyncAgentSightings(fingerly, client_ip=client_ip)
app = sightings.asgi(app)  # FastAPI, Starlette, Django ASGI
```

`AgentSightings.asgi` works too, with its flusher on a thread instead of a task. Where neither middleware fits, call `sightings.report(request, content_type)` after each response.

### Which responses are reported

By default, every response with a `Content-Type` of `text/html` or `application/xhtml+xml`, and every request for `/robots.txt`, `/llms.txt` or `/llms-full.txt`, whatever the status. Static files, API routes and health checks are left out. Widen or narrow that by your own resources, never by visitor:

```python
sightings = AgentSightings(
    fingerly,
    client_ip=client_ip,
    include_paths=["/feeds/"],  # reported whatever their content type
    exclude_paths=["/admin"],  # never reported; wins over everything
    content_types=["text/html", "application/rss+xml"],  # replaces the default
)
```

Paths are matched as the mounted application sees them, as for the proxy.

### Ask about a request

`lookup` answers from memory: never a network call, never an exception. It takes a `ProxyRequest`, an ASGI scope, a WSGI environ, or a Starlette, FastAPI, Django or Flask request. Until the server has answered for an earlier request with the same user agent, address and `Signature-Agent`, it returns `AGENT_UNKNOWN`. Serve that as usual.

```python
from fingerly import AGENT_UNKNOWN, AIVerificationResult, VisitorKind

answer = sightings.lookup(request)
if answer is AGENT_UNKNOWN:
    pass  # not answered yet: serve as usual
elif answer.visitor_kind == VisitorKind.AI_BOT and answer.ai is not None:
    if answer.ai.verification.result == AIVerificationResult.FAIL:
        ...  # it claims to be an agent its operator does not vouch for
```

Each answer holds `ttl`, `visitor_kind`, `agent` and, for an AI agent, `ai` with the same fields as on events. A signed request (Web Bot Auth) is checked by the server every time, so `lookup` never remembers it. A request the server could not use is answered `VisitorKind.UNKNOWN` with `ttl` 0, so `lookup` never remembers it either and keeps answering `AGENT_UNKNOWN`; the other requests of the report are answered as usual.

### What is sent

For each reported request: the `User-Agent` header, the address from `client_ip`, the `Host`, the method, the Web Bot Auth `Signature`, `Signature-Input` and `Signature-Agent` headers when present, and how many times that same request was seen. A request whose user agent or method is over 4096 bytes is not reported, a `Host` or signature header over 4096 bytes is left out, and a request whose address cannot be resolved is not reported.

Never sent, and never logged: the path, the query string, cookies, `Authorization`, any other header, the body or the response.

### Memory and failures

Answers live in a per-process LRU of 4096 entries by default (`cache_size`, at most 65536), a few hundred bytes each: about 1.5 MB at the default. Reports wait in a buffer of at most 1000 items, where repeats of the same request become one item with a count. It is sent in batches of up to 200 items, when it reaches 200 items or 64 KiB or 2 seconds after its oldest item, with one report in flight and a 5 second deadline. When the buffer is full, new requests are not reported and `sightings.dropped` counts them.

Every failure fails open: requests keep being served and `lookup` keeps answering from memory or with `AGENT_UNKNOWN`. A `429` pauses reporting for its `Retry-After`, held to between 1 second and 24 hours, while the buffer keeps counting, a `503` or an unreachable API is retried with backoff from 1 to 60 seconds, a rejected key pauses reporting for 60 seconds, and a `422` (no request in the report was usable) drops the report. Problems are logged on the `fingerly.agents` logger, at most once a minute each.

### Processes, threads and serverless

`AgentSightings` sends from a daemon thread, which never keeps the process alive. A forked worker (gunicorn, uWSGI, also with `--preload` or without lazy apps) starts with an empty buffer, its own thread and its own connections; answers already remembered are kept. `AsyncAgentSightings` sends from a task on the loop that serves your requests.

What is pending is sent on a graceful shutdown without any code of yours, within 5 seconds: the ASGI middleware sends it when the server's lifespan shutdown arrives (uvicorn, gunicorn's uvicorn worker, Django's ASGI handler included), and `AgentSightings` sends it when the interpreter exits, as a gunicorn or uWSGI worker does after `SIGTERM`. Call `close()` (or `await aclose()`) yourself where your app has a shutdown hook of its own. Where the process is frozen between invocations, build it with `background=False` and call `flush()` (or `await flush()`) before each invocation ends.

The call underneath is `fingerly.agents.sightings([...])`, taking `AgentSighting` items and returning `AgentSightingsResult`. A refusal raises `FingerlyAPIError` with `retry_after` and, on a `429`, `rate_limit_scope` (`daily` for the daily allowance).

## Framework guides

Each guide is a complete app. Replace `/k7x2qm4a` with the path the dashboard issued, and set `FINGERLY_SECRET_KEY` and `FINGERLY_PROXY_KEY`. The browser posts identifications to the proxy path and sends the `requestId` it gets back to `/verify/<request_id>`, where your server reads the event with its secret key.

| Framework | Client | Proxy mounted with |
| --- | --- | --- |
| [FastAPI](#fastapi) | `AsyncFingerly`, one per worker, built in the lifespan | `app.add_route` with `proxy.asgi` |
| [Django](#django) | `Fingerly`, one per process | A wrapper in `wsgi.py` or `asgi.py`, before URL routing |
| [Flask](#flask) | `Fingerly`, one per process | `DispatcherMiddleware` with `proxy.wsgi` |

### FastAPI

<details>
<summary>Complete app</summary>

```python
# main.py; run with: uvicorn main:app
import contextlib
import os

from fastapi import FastAPI, HTTPException, Request

from fingerly import (
    AsyncFingerly,
    FingerlyAPIError,
    FingerlyError,
    FingerlyEventPendingError,
    FingerlyProxy,
)

proxy = FingerlyProxy(
    proxy_key=os.environ["FINGERLY_PROXY_KEY"],
    path="/k7x2qm4a",
    client_ip=lambda request: (
        request.headers.get("cf-connecting-ip") or request.peer_host
    ),
)


@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
    # One read client per worker, built on the worker's own event loop.
    app.state.fingerly = AsyncFingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
    yield
    await app.state.fingerly.aclose()
    await proxy.aclose()


app = FastAPI(lifespan=lifespan)
app.add_route("/k7x2qm4a", proxy.asgi)


@app.get("/verify/{request_id}")
async def verify(request_id: str, request: Request):
    try:
        event = await request.app.state.fingerly.events.get(request_id)
    except FingerlyEventPendingError as error:
        # Not decided yet, not fraud: ask the caller to come back.
        retry_after = str(round(error.retry_after or 2))
        raise HTTPException(503, headers={"Retry-After": retry_after}) from None
    except FingerlyAPIError as error:
        raise HTTPException(404 if error.status == 404 else 502) from None
    except FingerlyError:
        # A timeout or an unreachable API: answer it, never a 500.
        raise HTTPException(503, headers={"Retry-After": "2"}) from None
    return {
        "identifiable": event.identifiable,
        "visitor_id": event.visitor_id,
        "suspect_score": event.suspect_score,
    }
```

</details>

The same works under `uvicorn --workers 4` or gunicorn's uvicorn worker: each worker runs the lifespan and gets its own client and pool.

### Django

Django has no `add_route`, so put the proxy in front of Django in `wsgi.py` or `asgi.py`, before any URL routing. In a project named `mysite`:

<details>
<summary>Complete app (identification.py, wsgi.py, asgi.py, views.py, urls.py)</summary>

```python
# mysite/identification.py
import os

from fingerly import Fingerly, FingerlyProxy

PROXY_PATH = "/k7x2qm4a"

proxy = FingerlyProxy(
    proxy_key=os.environ["FINGERLY_PROXY_KEY"],
    path=PROXY_PATH,
    client_ip=lambda request: (
        request.headers.get("cf-connecting-ip") or request.peer_host
    ),
)

# One read client per process, shared by every thread.
fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
```

```python
# mysite/wsgi.py, for gunicorn mysite.wsgi or runserver
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

from mysite.identification import PROXY_PATH, proxy  # noqa: E402

django_application = get_wsgi_application()


def application(environ, start_response):
    if environ.get("PATH_INFO") == PROXY_PATH:
        return proxy.wsgi(environ, start_response)
    return django_application(environ, start_response)
```

```python
# mysite/asgi.py, for uvicorn mysite.asgi:application
import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

from mysite.identification import PROXY_PATH, proxy  # noqa: E402

django_application = get_asgi_application()


async def application(scope, receive, send):
    if scope["type"] == "http" and scope["path"] == PROXY_PATH:
        await proxy.asgi(scope, receive, send)
    else:
        await django_application(scope, receive, send)
```

```python
# mysite/views.py
from django.http import JsonResponse

from fingerly import FingerlyAPIError, FingerlyError, FingerlyEventPendingError
from mysite.identification import fingerly


def verify(request, request_id):
    try:
        event = fingerly.events.get(request_id)
    except FingerlyEventPendingError as error:
        # Not decided yet, not fraud: ask the caller to come back.
        retry_after = str(round(error.retry_after or 2))
        return JsonResponse(
            {"error": error.code}, status=503, headers={"Retry-After": retry_after}
        )
    except FingerlyAPIError as error:
        status = 404 if error.status == 404 else 502
        return JsonResponse({"error": error.code}, status=status)
    except FingerlyError:
        # A timeout or an unreachable API: answer it, never a 500.
        return JsonResponse(
            {"error": "unavailable"}, status=503, headers={"Retry-After": "2"}
        )
    return JsonResponse(
        {
            "identifiable": event.identifiable,
            "visitor_id": event.visitor_id,
            "suspect_score": event.suspect_score,
        }
    )
```

```python
# mysite/urls.py
from django.urls import path

from mysite import views

urlpatterns = [path("verify/<str:request_id>", views.verify)]
```

</details>

`verify` is a plain view, so Django runs it in a thread under ASGI too. In an `async def` view use `AsyncFingerly` instead, built once per process.

### Flask

<details>
<summary>Complete app</summary>

```python
# app.py; run with: gunicorn app:app, or flask --app app run
import os

from flask import Flask, abort
from werkzeug.middleware.dispatcher import DispatcherMiddleware

from fingerly import (
    Fingerly,
    FingerlyAPIError,
    FingerlyError,
    FingerlyEventPendingError,
    FingerlyProxy,
)

app = Flask(__name__)
fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
proxy = FingerlyProxy(
    proxy_key=os.environ["FINGERLY_PROXY_KEY"],
    path="/k7x2qm4a",
    client_ip=lambda request: (
        request.headers.get("cf-connecting-ip") or request.peer_host
    ),
)
app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {"/k7x2qm4a": proxy.wsgi})


@app.get("/verify/<request_id>")
def verify(request_id):
    try:
        event = fingerly.events.get(request_id)
    except FingerlyEventPendingError as error:
        # Not decided yet, not fraud: ask the caller to come back.
        retry_after = str(round(error.retry_after or 2))
        return {"error": error.code}, 503, {"Retry-After": retry_after}
    except FingerlyAPIError as error:
        abort(404 if error.status == 404 else 502)
    except FingerlyError:
        # A timeout or an unreachable API: answer it, never a 500.
        return {"error": "unavailable"}, 503, {"Retry-After": "2"}
    return {
        "identifiable": event.identifiable,
        "visitor_id": event.visitor_id,
        "suspect_score": event.suspect_score,
    }
```

</details>

A `DispatcherMiddleware` mount answers everything under its path too, which is what `path` narrows back down to the one path.

## Timeouts

`timeout` is one deadline over the whole request: connecting, sending, the response headers and the body. An API that answers a byte at a time cannot stretch it. The default is 10 seconds for the clients and 5 for the proxy. Response bodies over 4 MiB are refused rather than buffered: the clients raise `FingerlyAPIError` with code `response_too_large`.

Under a thread or process server (gunicorn sync or gthread workers, Django or Flask under WSGI), size the pool for the slow case, not the average one: while Fingerly is slow, every proxied request holds its thread for the whole `timeout`. At 100 proxied requests a second with 1% of them running into a 5 second timeout, that is 5 threads busy on average, before any fast request is served. Run more threads than that, lower `timeout` for the proxy, or serve through `proxy.asgi`, where a waiting request holds no thread.

## Connections

Each client, and each proxy handler, keeps its connections open between requests and shares them across threads or tasks. Up to 256 concurrent requests per process reuse connections rather than opening one each; pass `limits=httpx.Limits(max_connections=…)` to change that. Connections are replaced every five minutes, so a changed DNS answer is picked up. Redirects are never followed and no cookies are kept.

## API version

Pass `api_version` to select a route version, for example `v1` (the default) or `v2`. The server must support the chosen version. The version applies to every API request; it is separate from the endpoint origin. On the proxy it selects the ingest URL, `/api/v2/ingest`, and nothing on your own site.

## Development and release preparation

```sh
uv sync                                     # 3.9 per .python-version, dev group included
uv run ruff check .
uv run ruff format --check .
uv run mypy
uv run pytest
uv run python scripts/sync_contract.py --check
uv build                                    # wheel and sdist
```

`uv sync` reads the `dev` dependency group, so there is nothing else to install. `.python-version` pins the development interpreter to 3.9, the oldest supported runtime, so the floor is exercised locally rather than only in CI. `uv.lock` is committed; CI installs with `uv sync --frozen`.

The vendored synthetic contract snapshot makes tests independent of sibling repositories. To update it from the integration workspace, set `FINGERLY_CONTRACT_DIR` to its `contract` directory and run `python scripts/sync_contract.py`. Checks verify the recorded hashes. Never put production secrets in fixtures.

<details>
<summary>Source structure</summary>

`_client.py` holds both clients and their event reads. `_http.py` is the connection pool both clients and the proxy send through, with its deadline and body cap. `_transport.py` builds requests and interprets responses, so the two clients share one definition of what a request is and what a failure means. `_models.py` owns `Event`, `EventPage` and their parsing. `_enums.py` holds the string enums the models and webhooks compare against. `_webhooks.py` verifies signatures. `_proxy.py` owns every proxy decision, with `_asgi.py` and `_wsgi.py` as thin adapters that only read a request and write a response, so the two standards cannot drift apart. `_config.py` validates every caller-supplied option: keys, origins, API versions and durations, all before any network access. `_errors.py` holds the exception hierarchy. `_version.py` holds the version everything else reads. `__init__.py` only exposes the public API.

</details>

## Requirements

- Python 3.9 or newer.
- One runtime dependency, `httpx` (`>=0.27,<1`).

## Documentation

- [Python SDK guide](https://docs.fingerly.io/docs/sdks/python)
- [Reading events](https://docs.fingerly.io/docs/reading-events) and [Webhooks](https://docs.fingerly.io/docs/webhooks)
- [Proxy integrations](https://docs.fingerly.io/docs/proxy-integrations)
- [API reference](https://docs.fingerly.io/reference/overview)

## Help

Open an issue on this repository, or write to [support@fingerly.io](mailto:support@fingerly.io). Security issues: [security@fingerly.io](mailto:security@fingerly.io).

## Licence

Apache-2.0. See [LICENSE](https://github.com/fingerly-io/sdk-python/blob/main/LICENSE).
