Metadata-Version: 2.4
Name: aifinpay-gate
Version: 0.11.1
Summary: Accept AIFP-1 payments from AI agents in a Python API — ASGI (FastAPI, Starlette) and WSGI (Flask, Django) middleware. Port of @aifinpay/gate.
Author-email: "CoinSecurities (SECCO)" <contact@aifinpay.io>
License-Expression: MIT
Project-URL: Homepage, https://aifinpay.io
Project-URL: Repository, https://github.com/AiFinPay/sdk
Project-URL: Issues, https://github.com/AiFinPay/sdk/issues
Keywords: ai-agents,agent-payments,http-402,paywall,fastapi,flask,asgi,wsgi,middleware,aifinpay
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyNaCl>=1.5
Provides-Extra: redis
Requires-Dist: redis>=4.2; extra == "redis"
Dynamic: license-file

# aifinpay-gate (Python)

Accept payments from AI agents in a Python API. When an agent calls a paid
route without paying, the gate answers **HTTP 402** with everything it needs to
buy a batch of calls; the agent settles on-chain from its own wallet straight to
yours (non-custodial; the protocol fee is included in the quoted price and the
quote shows the exact split) and retries with an `AIFP-Receipt`.
The gate verifies that receipt **locally** — an Ed25519 signature against the
AiFinPay JWKS, no call to AiFinPay per request — and meters the batch.

A port of [`@aifinpay/gate`](https://www.npmjs.com/package/@aifinpay/gate): the
same 402 body, the same checks and the same refusal sentences, held to the Node
package by recorded fixtures (`tests/test_parity.py`).

```bash
pip install aifinpay-gate            # PyNaCl is the only dependency
pip install "aifinpay-gate[redis]"   # shared counters across processes
```

## Register

```bash
curl -s -X POST https://api.aifinpay.io/v1/merchants -H 'content-type: application/json' \
  -d '{"name":"My API","pay_to":{"evm":"0xYourPayoutWallet"},"settlement_version":"1.4"}'
```

Keep `merchant_id` and the one-time `merchant_secret`, then claim the merchant
at https://dash.aifinpay.io with the secret to see payments. One `pay_to.evm`
receives on every EVM network.

## FastAPI / Starlette (ASGI)

```python
from fastapi import FastAPI, Request
from aifinpay_gate import AifpGateMiddleware, Gate, Route

gate = Gate("mrch_…", routes=[
    Route("/create", "premium", methods={"POST"}),   # $0.005 per call
    Route("/api/*"),                                  # the section and everything under it
])
app = FastAPI()
app.add_middleware(AifpGateMiddleware, gate=gate)

@app.post("/create")
async def create(request: Request):
    paid = request.state.aifp      # {"agent", "receipt_id", "used", "remaining", ...}
    return {"ok": True, "remaining": paid["remaining"]}
```

## Flask / Django (WSGI)

```python
from aifinpay_gate import AifpGateWSGI, Gate, Route

app.wsgi_app = AifpGateWSGI(app.wsgi_app, Gate("mrch_…", routes=[Route("/api/*")]))
# in a view: request.environ["aifp"]
```

Both adapters also serve `/.well-known/x402.json` so agents discover the paid
routes before they hit one (`serve_discovery=False` to turn it off).

## Any other framework

```python
from aifinpay_gate import Gate, SimpleRequest

result = gate.decide(SimpleRequest(path, headers, method))
if result is None:        # not a paid route
    ...
elif not result.ok:       # 402 / 403 / 503 — send result.status, result.headers, result.body as JSON
    ...
else:                     # paid: add result.headers to your response; result.aifp is the metering context
    ...
```

## Unproven pays

Who reads for free is one of three modes:

| Mode | `should_charge` | Who pays |
|---|---|---|
| **AI agents only** | `known_ai_agent` | Clients that say they are AI agents pay. Everyone else reads. |
| **Strict** | `unproven_pays(…)` | Only readers who passed a silent check and verified search engines read. Everyone else pays. |
| **Everyone pays** | `None` | Every request without a receipt pays. For APIs, catalogs and data feeds. |

`known_ai_agent` charges whoever names itself an agent. `unproven_pays` charges
whoever has not proven it may read free: a reader with a signed cookie, or a
search crawler confirmed by DNS. Everyone else gets the 402 with the price.

```python
from aifinpay_gate import Gate, ReaderProof, unproven_pays

reader_proof = ReaderProof(os.environ["AIFP_READER_KEY"])  # 32+ bytes
gate = Gate(merchant_id, resource="/articles", should_charge=unproven_pays(reader_proof))

# After your own browser check passes:
response.headers["Set-Cookie"] = reader_proof.set_cookie(reader_proof.issue(request.headers.get("user-agent")))
```

- **Reader cookie** `__aifp_human` = `<exp>.<sig>`: HMAC-SHA-256 of
  `<exp>\n<user-agent>`, base64url without padding, valid 30 days for the
  User-Agent it was issued to; the same bytes as `@aifinpay/gate`
  ([`conformance/vectors/reader-proof-v1.json`](../conformance/vectors/reader-proof-v1.json)).
  This package does not run the browser check.
- **Verified search crawler** (`verify_search_bot`): forward-confirmed reverse
  DNS against `SEARCH_BOT_TABLE`, cached per operator and address 24 h verified
  and 1 h refused, at most `SEARCH_BOT_CACHE_MAX` entries, 1 s timeout. A DNS
  error or timeout is not verified: the crawler pays. The lookup blocks; the
  ASGI middleware already runs the gate in a thread.
- **The client address** is `req.ip`: `REMOTE_ADDR` under WSGI, `scope["client"]`
  under ASGI. Behind a proxy that is the proxy's address unless the server
  rewrites it: `uvicorn --proxy-headers --forwarded-allow-ips=<proxy>`,
  werkzeug's `ProxyFix`, or your own middleware for Django. A `SimpleRequest`
  takes `ip=`. Without an address no crawler is verified and all of them pay.
- `AIFP-Receipt` or `AIFP-Agent-Id` on the request is charged whatever else it
  carries, so a receipt is always metered.

## Tell agents what a page is

`about` lets the 402 say what the page is, so an agent can decide whether it is
worth buying:

```python
def about(req):
    page = pages.by_path(req.path)  # your own lookup; None when it is not one page
    return {"title": page.title, "description": page.summary} if page else None

gate = Gate(merchant_id, routes=[Route("/articles/*")], about=about)
```

The 402 then carries `"about": {"title": "…", "description": "…"}` right after
`resource`. Return a dict with `title` and/or `description`, or `None`. Use the
page's own title and a summary you wrote, never an excerpt of the paid text.
The gate makes it plain text (tags stripped, entities decoded, control
characters removed, whitespace collapsed, title cut at 200 and description at
300 characters, nothing added), byte for byte as `@aifinpay/gate`
([`conformance/vectors/about-v1.json`](../conformance/vectors/about-v1.json)).
It is information only: the quote, the receipt, the meter and the events do not
depend on it. A function that raises or returns another shape leaves the 402 as
it would be without it; without the option the 402 does not change. Shadow
does not call it, nor does a reader who reads free.

## Routes

`Route(pattern, tier="standard", weight=None, methods=None, paywall=True)`

- `pattern` is exact, or ends in `/*` — `/api/*` covers `/api` and everything
  under `/api/`. The longest matching pattern wins. This is the hosted
  gateway's matcher; wildcards in the middle (`/backtest/*/bid`) are refused.
- `tier`: `standard` $0.0005, `complex` $0.002, `premium` $0.005 per call
  (weights 1, 4, 10 billing units). `weight` overrides the units per call.
- `paywall=False` serves the route free and meters nothing.
- Paths no route matches pass through untouched.

`Gate(merchant_id, resource="/api/search", tier="complex")` is the single-mount
form: every request handed to it is charged against that one resource.

## Production: share the counters

The default `MemoryStore` meters per process. Under gunicorn/uvicorn with
several workers, or several pods, each gets a full copy of every batch — a
200-unit batch serves up to 200 × workers calls. Use Redis:

```python
import redis
from aifinpay_gate import Gate, RedisStore

gate = Gate("mrch_…", routes=[...], store=RedisStore(redis.Redis.from_url(REDIS_URL)))
```

The store increments atomically and compares **after** the increment, so
concurrent requests can never overspend a batch; the counter's TTL is set once
and expires with the receipt.

## Options

| Option | Default | |
|---|---|---|
| `should_charge` | everyone pays | `known_ai_agent` for content sites: human browsers read free and never see a 402; self-identifying AI crawlers and anything speaking AIFP pay. A predicate that raises charges. |
| `allow(ctx)` | — | Your veto after verification, before metering (a refused call costs nothing). Return `False` → 403. |
| `on_store_error` | `"closed"` | `"open"` serves un-metered calls when the store is down (`AIFP-Meter: degraded`). |
| `require_agent_match` | `True` | Refuse a caller whose `AIFP-Agent-Id` names someone other than the receipt's payer; a caller naming nobody is served (anti-accident, not anti-theft). |
| `case_sensitive` | `False` | Paths and patterns are compared in lower case, as most origins serve them. `True` for an origin where `/A` and `/a` are two pages. |
| `network_mode` | a testnet receipt is refused | `"live"` or `"test"`, or a callable returning it: a testnet receipt does not open a live site or the reverse. From `GET /v1/merchants/:id`: `record.get("network_mode", "live")`, since the field is stored only for a test site. |
| `replay` | `"auto"` | Single-use receipts get a one-shot nonce check. |
| `jwks` | fetched | Pin the key set and skip network I/O (redeploy on key rotation). |
| `on_event(e)` | — | `402` / `serve` / `403` / `meter_error` events for your metrics. |
| `refund_on_error` (adapters) | `False` | Give the units back when your handler answers 5xx. |

## How a path is read

A route is matched against the path as an origin could resolve it: percent-decoded, `;params` dropped, empty segments and a trailing slash dropped, in lower case. So `/PAID/a` and `/%70aid/a` are `/paid/a`, whatever your framework does with them. A path with a dot segment means different things to different servers, so in enforce an agent gets a 400 `noncanonical_path` and a reader gets the page. In shadow a good receipt is verified and reported and nothing is spent.

## Shared caches

A 402, a 403, a 503, a paid response and a shadow would-be refusal carry
`Cache-Control: private, no-store, max-age=0`, and a handler's own value does not
replace it on a paid response. An exempt reader's page keeps whatever your app
sets, so a CDN in front of this process can answer an agent with a copy it stored
for a reader, and the gate never runs. Keep protected paths out of that cache.

## What it guarantees

- Fails **closed**: if the JWKS cannot be reached, paid routes answer 503, never free.
- Only EdDSA receipts from `https://api.aifinpay.io` with `aud` = your merchant id.
- Only quota receipts are spendable; per-call billing receipts are refused.
- An expired receipt gets a 402 (buy again), a wrong one a 403 with a reason.
- Stricter than the Node gate in two places: a receipt without a numeric `exp`,
  or without a usable `unit_quota`, is refused.

Not included, on purpose: free allowances, daily caps and per-agent blocks live
in the AiFinPay dashboard, so there is one source of truth for each rule.


## Opt-in dashboard request reporting

Use one `GateReporter` per merchant per worker, created **after worker fork**.
It uses only Python's standard library. Add its callback to your existing gate;
keep the gate's shared Redis quota store and verification settings.

```python
import os
from aifinpay_gate import GateReporter, Gate, Route, RedisStore

merchant_id = os.environ["AIFP_MERCHANT_ID"]
reporter = GateReporter(
    merchant_id=merchant_id,
    merchant_secret=os.environ["AIFP_MERCHANT_SECRET"],
)
gate = Gate(
    merchant_id=merchant_id,
    routes=[Route(pattern="/api/agent/genres/list", tier="standard")],
    store=RedisStore(redis_client),
    on_event=reporter.on_event,
)
# In your existing worker shutdown hook, after stopping new requests:
reporter.close(timeout=10.0)
```

Register the identical static or prefix route pattern in the dashboard first.
Routes mode emits the matched `Route.pattern`; a single-resource gate must set
`resource` explicitly. Full URLs, queries, fragments, encoded or invalid paths
are rejected instead of rewritten. The API rejects unregistered patterns.
Keep the merchant secret server-side. Share the reporter across mounts; do not
report the same event through multiple reporters or through both hosted and
self-hosted analytics. If you already have a callback, compose the two hooks.

Only `402` and gate-admitted `serve` events are reported; exempt humans and
other event kinds are excluded. `serve` is admission **before your handler**,
not proof of successful HTTP response or delivered content. The payload has
only UUID, kind, registered path and UTC timestamp; no headers, receipts,
payer IDs, IPs or customer content. This populates request counters, not
geographic/user-agent charts or general website visits. Settlements still
supply payments/revenue; purchased quota is never backfilled as actual usage.

`api_base` accepts an HTTPS origin only (default `https://api.aifinpay.io`);
the reporting API must be deployed before enabling this hook. Redirects are
blocked before a second request, including302, so secrets stay at that origin.
`on_event` is synchronous enqueue only. The background daemon thread sends
batches of at most 50 with a 3 second socket I/O timeout; it never performs HTTP
on the gate thread. The memory queue includes in-flight events, holds at most
1000, and drops new events when full. UUIDs and timestamps stay identical on
transient retries (at most 5 attempts/15 minutes). Permanent 4xx except 408/429,
or redirects, stop reporting and discard the queue. Fix configuration or
credentials before creating a replacement reporter.

`reporter.stats` returns `queued`, `delivered` (API acknowledgements including
retry duplicates), `dropped`, `retries`, `last_error` (sanitized code), `stopped`
and `closed`. Monitor these in your own service. An abrupt process stop loses
unsent telemetry; reporting failures never alter verification or quotas.
`reporter.flush(timeout=10.0)` requests one attempt per queued event and waits
at most the deadline; transient failures remain for background retries.
`reporter.close(timeout=10.0)` stops acceptance, flushes within that deadline,
drops unsent events and tells the worker to stop. An already in-flight socket
operation may finish later, but it cannot start another request. Neither method
promises delivery. A reporter inherited across fork refuses to report and
exposes `wrong_process`; construct a fresh reporter in each worker.

### Receipt use

The same reporter tells AiFinPay how much of each receipt your gate has spent,
so the agent, the dashboard and AiFinPay's receipt record show what your
counter shows. After every paid `serve` it holds the receipt id (never the
receipt itself) and the units left, keeping only the lowest per receipt, and a
second daemon thread posts them on the same schedule to
`POST /v1/merchants/:id/receipt-use`:

```json
{ "uses": [{ "receipt_id": "rcpt_0123456789abcdef", "remaining": 34 }] }
```

Batches hold at most 100 receipts, ordered by id. This is accounting, not
request reporting: it carries no reader data. A 404 (an API that predates the
route), a refusal or a redirect drops what is held and the next spend tries
again; a network error, timeout, 408, 429 or 5xx keeps it for the next attempt
(at most 5). Gate events are untouched either way, and no outcome reaches a
request. `reporter.stats["uses"]` has `queued`, `delivered`, `dropped` and
`last_error`; `flush` and `close` cover it within the same deadline. The bodies
are byte for byte `conformance/vectors/receipt-use-v1.json`.

## What the gate tells AiFinPay

Every request the gate makes with your merchant secret names the gate. That is
gate events, receipt use, reporting v2 and traffic summaries. Two headers
carry it:

```text
User-Agent: aifinpay-gate-py/<version>
AIFP-Gate: pkg=py; ver=<version>; platform=asgi; mode=enforce; charge=agents
```

`platform` is `asgi` under `AifpGateMiddleware`, `wsgi` under `AifpGateWSGI`
and `python` for a bare `Gate`. `charge` is `agents` for `known_ai_agent`,
`unproven` for `unproven_pays`, `everyone` without `should_charge`, and
`custom` for your own rule.

What each request contains:

| Request | Contains |
|---|---|
| Identity | Package, version, platform, mode and charge rule. |
| Events | Challenges and admissions on registered routes, with the operator and class. Never a reader's page view. |
| Receipt use | Receipt id and the units left. |
| Traffic | Counts per five minutes, described below. |

Traffic summaries go out whenever a reporter is wired to the gate. Every
request the gate sees is counted once, by class (`human`, `ai_crawler`, and so
on) and outcome (`served`, `challenged`, `paid`, `blocked`, `error`). A path
outside every route counts as served. Readers are counted too, though they are
never sent as events. A script, image or font served free is not counted. A request carrying
`AIFP-Edge-Counted: 1` was already counted by the site's edge gate and is left
out of this summary, and only out of it. For
agents the summary also counts the operator and the section: the first segment
of the path, such as `/blog`. A language prefix like `/en` is skipped.

Country comes from the `cf-ipcountry` header by default. Name another header
with `country_header`, or pass `country_header=None` to send none. The caller's
network comes only from a header you name with `network_header`, and it is
never sent for readers. Both must be set by your own CDN: the gate never looks
an address up.

The summary is counted in memory and sent by its own daemon thread, at most
once per five minutes. It has its own state. A 404 from an API without the
route pauses it for 6 hours, any other refusal for 24 hours; events and receipt
use carry on. `reporter.flush_traffic()` closes the current window and sends
it, and `close()` does the same. `reporter.stats["traffic"]` shows what is
held, sent and dropped.

What never leaves your site: IP addresses, full paths and query strings,
User-Agents, headers, cookies, receipts and agent ids.

Turn traffic summaries off with `traffic=False` on the gate:

```python
gate = Gate("mrch_…", routes=[Route("/api/*")], on_event=reporter.on_event, traffic=False)
```

The identity headers are always sent.
