# Verify signed agents

Put the Identify middleware in front of your Express, Fastify or Next.js app, or any fetch handler, so every request gets a verdict decided in-process from a cached policy bundle.

Run the Identify middleware in front of your site so every request gets a [traffic assessment](https://provenanceauth.com/docs/identify/concepts/traffic-assessment.md) without a network call per request. The middleware verifies Web Bot Auth signatures, applies your traffic policy and reports decisions in batches.

**Before you begin:** create a secret key for your account in the console, and install the package.

**This package isn't on npm yet. This package isn't on PyPI yet.** Until then, every request in these docs runs over HTTP against the [sandbox](https://provenanceauth.com/docs/get-started/sandbox.md).

With access to the private Provenance repository, which your Provenance contact grants, install from it:

```bash
git clone https://github.com/michaelnbane-jpg/provenance.git provenance
cd provenance && pnpm install && pnpm build
node scripts/check-publishable.mjs --out ../provenance-packs
cd ../your-project
npm install ../provenance-packs/provenanceauth-sdk-1.0.0.tgz ../provenance-packs/provenanceauth-rails-1.0.0.tgz ../provenance-packs/provenanceauth-identify-1.0.0.tgz
```

```bash
git clone https://github.com/michaelnbane-jpg/provenance.git provenance
pip install ./provenance/python/sdk ./provenance/python/identify
```

**Availability:** `@provenanceauth/identify` and `provenanceauth-identify` are available to beta customers. The Node package runs in Node 18 and later, Cloudflare Workers and Vercel Edge; the Python package in Python 3.10 and later.

**Pricing:** the middleware is free on every plan. The policy bundle, the local rules and the decisions it reports aren't billed and don't count toward an allowance. Only [hosted checks](#5-check-from-your-server-instead) are metered; prices and allowances are on the [pricing page](https://provenanceauth.com/pricing).

## 1. Load the policy bundle at boot

The bundle holds your route map, traffic policy and lists, Provenance's token keys and the directories of agents registered with Provenance. The middleware refreshes it with its ETag every five minutes and keeps the last good copy when a refresh fails.

```ts
import { Identify } from "@provenanceauth/identify";

export const identify = new Identify({ apiKey: process.env.PROVENANCE_KEY });
await identify.ready();
```

Each bundle request and report batch carries a `Provenance-Origin` header naming the sites the middleware has served (scheme, host and port only), so your account's usage shows where Identify runs.

Before any bundle has loaded, the middleware answers `503` (`failMode: "closed"`, the default). Pass `failMode: "open"` to serve and log instead, or pass a `bundle` you saved at deploy time.

## 2. Add the middleware

**Express**

```ts
import { identifyExpress } from "@provenanceauth/identify/express";

app.set("trust proxy", true); // so req.ip is the client, not your load balancer
app.use(identifyExpress(identify, { orderFor: (req) => cartToOrder(req) }));
app.get("/products/:id", (req, res) => res.json({ verdict: req.identify }));
```

**Fastify**

```ts
import { identifyFastify } from "@provenanceauth/identify/fastify";

app.addHook("onRequest", identifyFastify(identify, { orderFor: (req) => cartToOrder(req) }));
```

**Next.js**

```ts
// middleware.ts
import { identifyNext } from "@provenanceauth/identify/next";

export const middleware = identifyNext(identify);
```

**fetch**

```ts
import { withIdentify } from "@provenanceauth/identify/fetch";

export default { fetch: withIdentify(identify, (request, verdict) => handle(request, verdict)) };
```

**FastAPI**

```python
from provenanceauth_identify import Identify
from provenanceauth_identify.asgi import IdentifyMiddleware

identify = Identify(api_key=os.environ["PROVENANCE_KEY"])
identify.ready()
app.add_middleware(IdentifyMiddleware, identify=identify)  # request.state.identify is the verdict
```

**Django**

```python
# settings.py
MIDDLEWARE = ["provenanceauth_identify.django.IdentifyMiddleware", *MIDDLEWARE]
PROVENANCE_IDENTIFY = {"api_key": os.environ["PROVENANCE_KEY"]}  # request.identify is the verdict
```

The middleware answers three outcomes itself and passes everything else on with the verdict attached:

| Decision | Your site answers |
| --- | --- |
| `block` | `403` with an `application/problem+json` body naming the rule |
| `rate_limit`, over the window | `429` with `Retry-After` |
| `require_intent`, no valid approval yet | `401` with `WWW-Authenticate: ProvenanceIntent` ([Require a human](https://provenanceauth.com/docs/identify/guides/require-a-human.md)) |

A `challenge` decision calls your `onChallenge` hook, so you can hand the request to the challenge you already run.

### Middleware options

Every adapter (Express, Fastify, Next.js, fetch and both edge templates) takes the same options; the Python middleware takes them in snake_case.

| Option | What it does |
| --- | --- |
| `orderFor(req)` | The order for a checkout request (your own cart), so `require_intent` binds the exact order. |
| `approvals` | `"protocol"` (default): the `ProvenanceIntent` 401 only. `"hosted"`: on an order that needs approval, assess it, open the approval and answer every agent with `approve_url`, `status_url` and a plain `message` ([five-minute checkout](https://provenanceauth.com/docs/authorize/guides/five-minute-checkout.md)). |
| `customerFor(req)` | With `"hosted"`: your signed-in customer's `{ phone }` or `{ email }`, so we send them the approval instead of the agent relaying it. |
| `merchantName` | The store name the shopper sees (default: your Identify settings, else the host). |
| `onUnavailable` | With `"hosted"`, when the API can't be reached: `"protocol"` (default) answers the `ProvenanceIntent` 401, `"block"` answers 503. Never an allow; the verdict's `decision.reason` is `approvals_unavailable`. |
| `newPasskey` | What a new passkey needs on approvals this middleware opens: `"step_up_contact"`, `"accept"`, `"require_existing"`, or `{ setting, minPasskeyAge, noContact }` (default: your checkout rules). |
| `onChallenge`, `onVerdict`, `skip`, `ipOf`, `urlOf`, `bodyOf` | Hooks for a `challenge` decision, every verdict, requests to leave alone, the client address, the URL and a protocol route's body. |
| `networkDirectories` | The card network agent programs' key directories you trust: `[{ program, url, type? }]`. [Card network agents](#card-network-agents) verify only against these. |
| `operatorKind(req)` | Reads how a signed agent is run (`direct` or `intermediary`) from what your edge passes, when your edge provider labels it. Return null when you don't know. |

## 3. Read the verdict

```ts
app.post("/checkout", (req, res) => {
  const v = req.identify;
  if (v.class === "signed_agent") log.info({ agent: v.agent.name, operator: v.agent.operator, person: v.human?.pseudonym });
  // …
});
```

A verified signature names the agent. For an agent registered with Provenance you also get its `id`, `category` and operator; for any other directory, `operator` is the directory's host.

## 4. Set your route map and origins

The route map turns paths into the actions your policy reads. Origins are the sites an agent's approval may name as its audience.

**curl**

```bash
export PROVENANCE_API=https://sandbox-api.provenanceauth.com
export PROVENANCE_KEY=prv_test_acct_P9xN2vQ7bT4mW8sYd3cFjLh6gAe1kR5

curl -s -X PUT $PROVENANCE_API/v1/identify/settings/site \
  -H "Authorization: Bearer $PROVENANCE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "origins": ["https://quillstack.example"],
    "display_name": "Quillstack",
    "route_map": [
      { "path": "/checkout*", "action": "checkout" },
      { "method": "POST", "path": "/account/*", "action": "account_change" },
      { "path": "/*", "action": "browse" }
    ]
  }'
```

**Node**

```ts
await fetch(`${process.env.PROVENANCE_API}/v1/identify/settings/site`, {
  method: "PUT",
  headers: { Authorization: `Bearer ${process.env.PROVENANCE_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    origins: ["https://quillstack.example"],
    display_name: "Quillstack",
    route_map: [
      { path: "/checkout*", action: "checkout" },
      { method: "POST", path: "/account/*", action: "account_change" },
      { path: "/*", action: "browse" },
    ],
  }),
});
```

**Python**

```python
import os, httpx

httpx.put(f"{os.environ['PROVENANCE_API']}/v1/identify/settings/site",
          headers={"Authorization": f"Bearer {os.environ['PROVENANCE_KEY']}"},
          json={"origins": ["https://quillstack.example"], "display_name": "Quillstack",
                "route_map": [{"path": "/checkout*", "action": "checkout"},
                              {"method": "POST", "path": "/account/*", "action": "account_change"},
                              {"path": "/*", "action": "browse"}]})
```

```json
{
  "object": "identify_config",
  "origins": ["https://quillstack.example"],
  "display_name": "Quillstack",
  "fail_mode": "closed",
  "decisions_ttl_days": 30,
  "pseudonyms": "on",
  "is_default": false
}
```

## 5. Check from your server instead

When you can't run the middleware, check each request with [`POST /v1/identify/assessments`](https://provenanceauth.com/docs/api/traffic-checks.md#post-v1-identify-assessments). Send the client address in `ip` if you have a per-address rule; it is used for that check and never stored. The verdict carries `response`, the answer to send instead of serving the request, or null.

Hosted checks are metered per 1,000 past your monthly allowance, and each one adds the server-side signals: the network's record of a verified agent, your risk providers' answers and the person's revocation check.

## Card network agents

Card network agent programs sign their agents' requests with HTTP message signatures (RFC 9421) under their own tags. Identify verifies three of them beside Web Bot Auth's `web-bot-auth`:

| Tag | `agent.program.name` | `agent.purpose` |
| --- | --- | --- |
| `agent-browser-auth` | `visa_tap` | `browse` |
| `agent-payer-auth` | `visa_tap` | `pay` |
| `agent-pay-auth` (any case) | `mastercard_agent_pay` | `pay` |

These signatures verify only against the key directories you configure, never a URL the request names. With no directory for a program, its signatures read `unverified` with `network_directory_unconfigured`; a covered `Signature-Agent` that names another host is `signature_invalid` with `network_directory_mismatch`.

- **Window:** `created` and `expires` at most 8 minutes (480 seconds) apart, instead of Web Bot Auth's 60-second age. All six fields are required, the nonce included; a repeated nonce inside the window is `signature_replayed`.
- **Algorithms:** `ed25519` or `rsa-pss-sha256` (RSA keys of 2048 bits or more).
- **Directories:** with the middleware, pass `networkDirectories`. `type` is `directory` (an origin), `jwks_uri` (a JWK Set) or `key_lookup` (a key store answering `GET <url>?keyID=<keyid>`). A [self-hosted API](https://provenanceauth.com/docs/self-host/configuration.md) reads the same list from its configuration.

```ts
const identify = new Identify({
  apiKey: process.env.PROVENANCE_KEY,
  networkDirectories: [{ program: "mastercard_agent_pay", url: "https://keys.network.example/" }],
});
```

A verified card network signature adds `agent.program`: the program, what it signed for, and whether the program's body objects carry the signature's nonce (`objects.consumer`, `objects.payment`: `match`, `mismatch` or null). Their contents are never read or kept. `signature.method` is `network`. A program isn't an agent platform, so `request.agent.platform` stays as it was.

Every verified signature also carries `agent.purpose`, and one whose key came from a Signature Agent card carries `agent.card` (its name and site).

| Traffic policy fact | What it reads |
| --- | --- |
| `agent.network_program` | The card network agent program |
| `agent.signed_for` | What the agent signed for |
| `agent.card_name` | The name on its Signature Agent card |
| `agent.operator_kind` | How it is run, when your edge passes it |

A [traffic backtest](https://provenanceauth.com/docs/identify/guides/backtest-traffic-rules.md) counts a decision recorded before these facts as unscored for a rule that names one.

A signature under any other tag stays out of verification and adds the signal `signature_unrecognized_tag`.

## Errors you might see

| Symptom | Cause | Fix |
| --- | --- | --- |
| Every request answers `503` | No bundle has loaded yet and the fail mode is closed | Await `identify.ready()` at boot, check the key, or set `failMode: "open"`. |
| `signals` has `unknown_signature_agent` | The agent's directory didn't resolve or doesn't list its key | Nothing to fix on your side: the request isn't attributed. The description says why. |
| `signals` has `signature_invalid` behind a proxy | The proxy rewrote the host or path the agent signed | Forward the original `Host` and path, or verify at the proxy. |
| `401` [`authentication_required`](https://provenanceauth.com/docs/platform/errors.md#authentication_required) on the bundle | The middleware has no secret key | Pass `apiKey` from your secret store. |
| `402` [`trial_ended`](https://provenanceauth.com/docs/platform/errors.md#trial_ended) on a hosted check | A Free account used its trial API calls, or the trial ended | Choose a plan in **Settings → Plan & usage**. The middleware and its reports keep working. |

## See also

- [Sign your agent's requests](https://provenanceauth.com/docs/identify/guides/sign-agent-requests.md)
- [Write a traffic policy](https://provenanceauth.com/docs/identify/guides/traffic-policy.md)
- [Traffic assessment](https://provenanceauth.com/docs/identify/concepts/traffic-assessment.md)
