# Deploy AllowedBy in your SaaS app

For SaaS and API teams (the relying party) who want AI agents to call their API on behalf of a person, with that person's approval.
You add the Python SDK to your app, describe your routes, and the SDK verifies every agent request offline.
This guide is complete on its own. It describes the code in this repository (`sdks/python/src/allowedby/sdk.py`, specs 0.2.14-draft).

---

## 1. What you get

- **Verification on every request.** Each agent request carries the agent's passport, the person's signed approval (the *grant*) and a proof for this exact request. The SDK checks all three offline, in about a millisecond. It makes no network call on the request path.
- **The approval flow.** When the person's yes is missing, the SDK answers `401` with an `AllowedBy` challenge. The agent asks its node, the person taps a passkey on the node's approval page, and the agent retries. For serious actions (`write-hard`, `irreversible`) your app creates the approval itself, bound to the exact request and usable once.
- **Levels per route.** You choose the assurance level for each route:

  | Level | Meaning |
  |---|---|
  | L0 | The agent's passport only. No person approves. |
  | L1 | The person taps a passkey. |
  | L2 | The person's legal identity was verified (eIDAS substantial). |
  | L3 | Verified at eIDAS high, on a hardware passkey. |

- **Optional:** personal data with consent and a stated purpose, customers (tenants) with their own rules and budgets, company mandates, account linking.
- **Published descriptions:** `/.well-known/allowedby`, `/openapi.json` (OpenAPI 3.1) and `/.well-known/api-catalog` (RFC 9727). An agent given only your address can find every operation.
- **An admin console** at `/allowedby/admin`.

You never handle passwords, API keys or OAuth tokens for agents. The person never gives the agent personal data.

## 2. Prerequisites

- Your API served over **https** in production.
- **Python 3.10+**.
- The **`cryptography`** package. It is the SDK's only dependency.
- A **node** you trust. The node issues agent passports, runs the approval page and countersigns grants (section 7).

## 3. Install the SDK

The SDK is the `allowedby` package in `sdks/python/` (guide: `docs/sdk/python.md`). It is not published on PyPI yet: install it from a clone of this repository.

```bash
pip install "./sdks/python"          # from a clone of this repository (not on PyPI yet)
```

Then import it:

```python
from allowedby import AllowedBy, SqliteStore, route
```

## 4. Describe your routes

Converting an API you already have? [Convert an existing API](https://docs.allowedby.com/guides/convert-an-api) sorts your endpoints first: which ones agents may call, their class and level, what to reshape, where the middleware goes and where it must not.

One line per route. Each line gives the **capability** (`namespace:action`), its **class**, the **level** you require and the **resource** it acts on.

```python
routes = [
    route("GET",    "/notes",      "notes:read",   level=1, resource="note:*", summary="List your notes"),
    route("POST",   "/notes",      "notes:write",  cls="write", level=1, resource="note:new",
          summary="Add a note", body={"text": "the note"}),
    route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}",
          summary="Delete a note"),
]
```

| Argument | Meaning | Default |
|---|---|---|
| `capability` | What the person allows, `namespace:action`. Leave it out (with `level=0`) for routes where the agent's passport is enough. | none |
| `cls` | `read` (no visible change), `write` (reversible), `write-hard` (hard to undo, or visible to others), `irreversible` (payments, contracts, deletions). For `write-hard` and `irreversible`, the SDK creates the approval, bound to that exact request, used once. For payments, `cls` can be a list of amount thresholds: `[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}]`, read at `amount_field`. | `read` |
| `level` | 0, 1, 2 or 3 (table above). | `1` |
| `resource` | The resource id, with `{param}` from the path. `note:{id}` means "this note". The person may widen it to `note:*` on the approval page. | `<namespace>:*` |
| `amount_field` | JSON Pointer to an amount in the body, e.g. `/total`. Approvals then carry a limit per call, day, week, month or in total. | none |
| `authn` | `"hardware"` refuses synced passkeys. | any |
| `mandate` | `True`: the person must approve **for their company**, under a mandate the company signed. | `False` |
| `disclose`, `disclose_optional` | Personal data this route needs (section 9). | none |
| `summary`, `body` | What the route does and each JSON body member. They go into `/openapi.json`. | none |
| `max_lifetime` | Seconds an approval for this route may last, at most 30 days. | class default |
| `require_link` | The person's account must be linked first (`aby:link`). | `False` |
| `nonce` | Require an `AllowedBy-Nonce` on this route. | `False` |
| `qes`, `authority`, `tier` | Qualified signature, co-approvers under an authority policy, minimum custody tier of the agent. Advanced; see the specs. | off |

### The sentence the person reads

The person signs exactly this sentence. Only you write it, and it may use only values the approval enforces:

```python
templates = {
    "notes:read":   "Read your notes",
    "notes:write":  "Write new notes",
    "notes:delete": "Delete note {scope}",
}
```

Allowed placeholders: `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{count.max}`, `{fields}`. No free text from the agent. For several languages, use the long form:

```python
templates["notes:read"] = {"summary": {"en": "Read your notes", "fr": "Lire vos notes"},
                           "lines":   {"en": "Read your notes", "fr": "Lire vos notes"}}
```

### Example route map

| Route | Capability | Class | Level | Sentence |
|---|---|---|---|---|
| `GET /me` | none | read | 0 | none (agent only) |
| `GET /notes` | `notes:read` | read | 1 | "Read your notes" |
| `POST /notes` | `notes:write` | write | 1 | "Write new notes" |
| `DELETE /notes/{id}` | `notes:delete` | write-hard | 2 | "Delete note {scope}" |
| `POST /t/{tenant}/invoices/{id}/approve` | `invoices:approve` | write-hard | 2 | your sentence with `{amount.max} {amount.currency}` |
| `POST /contracts/{id}/sign` | `contracts:sign` | irreversible | 2 or 3 | your sentence |

The SDK also adds one route itself: `POST /allowedby/link` (`aby:link`, level 1) for account linking.

## 5. Wrap your app

```python
aby = AllowedBy(
    origin=os.environ["ALLOWEDBY_ORIGIN"],  # your public origin, https in production; no default: it fails to start
    node=os.environ["ALLOWEDBY_NODE"],  # the node you trust, never guessed
    org={"legal_name": "Notes Ltd", "country": "FR"},  # country: ISO 3166-1 alpha-2
    routes=routes, templates=templates,
    admin_token=os.environ["ALLOWEDBY_ADMIN_TOKEN"],  # from your secret manager (section 11)
    title="Notes API", version="1.0.0", description="Notes for people and their agents",
    **options)  # tenants, disclosure and store: sections 8, 9 and 12
```

The wrapper:
1. serves its own endpoints: `/.well-known/allowedby`, `/.well-known/allowedby/tenants/<tenant>`, `/openapi.json`, `/.well-known/api-catalog`, `/allowedby/callback`, `/allowedby/link`, `/allowedby/admin`, `/allowedby/admin/api*`;
2. checks every request whose method and path are in your route map, and answers `401`, `403`, `429` or `503` itself when needed;
3. calls your app only when the request is allowed. Paths outside the route map reach your app unchanged, with your own authentication. A path that only looks like a protected route is refused with 400, as a lenient router could run the protected handler for it: a variant (`/notes.json` next to `/notes`), or a longer path (`GET /notes/7/comments` next to `GET /notes/{id}`). Declare such pages of your own with `AllowedBy(..., unprotected=["/notes.json", ("GET", "/notes/{id}/comments")])`: exact paths, or templates with their method. With Flask, Django, Starlette and FastAPI a declared page never runs a protected handler, and one that differs from a protected route by its last `/` only (`/notes/new/` next to `/notes/{id}`) works. A bare WSGI or ASGI app passes a declared page to your app as it is, so no wildcard route of a protected handler may reach it, and a page that differs by its last `/` stays refused ([Python guide](https://docs.allowedby.com/sdk/python)). With Flask, Django, Starlette and FastAPI the handler of a protected route runs only for that route, whatever the path (an alias, a catch-all). A bare WSGI or ASGI app cannot tell: next to a protected route that ends in a word (`DELETE /notes/{id}/archive`), a catch-all of yours that also takes longer paths runs `DELETE /notes/7/archive/x` without a check.

### Plain WSGI

```python
app = aby.wsgi(notes_app)
```

In your handler, read `environ["allowedby.context"]`. The whole app is `sdks/python/examples/frameworks/wsgi/app.py`.

### Frameworks

| Framework | One line | Context |
|---|---|---|
| FastAPI | `allowedby.fastapi.install(app, aby)` | `Depends(allowedby_context)` |
| Starlette, any ASGI app | `AllowedByMiddleware(app, aby)` | `request.state.allowedby` |
| Flask | `allowedby.flask.AllowedBy(app, aby)` | `g.allowedby` |
| Django | `"allowedby.django.AllowedByMiddleware"` and `settings.ALLOWEDBY` | `request.allowedby` |

Whole apps: [the Python guide](https://docs.allowedby.com/sdk/python#framework-recipes). Each one is run against a real node, an agent and a person
in CI.

### Use the context

`ctx` is already verified:

| Field | Meaning |
|---|---|
| `ctx.human_id` | The person, as a pseudonymous id: stable for your app, different in every app. Use it as the data owner, or link it to your account once (section 8). `None` on level 0 routes: never keep or read data under `None` or `""`, as every anonymous agent would share it. |
| `ctx.level` | The level reached: 0 to 3. At 0 the request carries the agent's passport only: there is no person, and `ctx.human_id` is `None`. A handler that keeps one person's data refuses a request without a person, or keeps nothing for it. |
| `ctx.agent`, `ctx.operator` | The agent's id and the company that runs it. |
| `ctx.capabilities`, `ctx.display` | What was allowed, and the exact sentence the person signed. |
| `ctx.gid`, `ctx.rev` | The approval id and its revision. Put them in your audit log. |
| `ctx.acting_for` | `{"org", "name", "role"}` when the person approved for their company. |
| `ctx.tenant` | Your customer, when the path has `{tenant}`. |

If your handler refuses a request the SDK accepted (unknown invoice, wrong total), call `aby.refund(ctx)` so the tenant budget is given back.

## 6. Publish your discovery documents

The wrapper serves these for you. Check that your reverse proxy forwards them and does not require your own authentication on them.

| Address | What it is |
|---|---|
| `/.well-known/allowedby` | Capabilities, sentences, your signing key, your signed company profile, the disclosure key, links to `openapi` and `/allowedby/link`. Also sends an RFC 8631 `Link` header. Answers `GET` and `HEAD`. |
| `/openapi.json` | OpenAPI 3.1 built from the route map. Each operation names its capability in `security` (`AllowedBy: ["notes:write"]`) and its level, class and amount field in `x-allowedby`. Served with `Access-Control-Allow-Origin: *`. |
| `/.well-known/api-catalog` | RFC 9727 catalog that points to `/openapi.json` and `/.well-known/allowedby`. |
| `/.well-known/allowedby/tenants/<tenant>` | A tenant's signed authority policy, when it has one. |

Check them after each deploy:

```bash
curl -sS "$ORIGIN/.well-known/allowedby" | python -m json.tool
curl -sS "$ORIGIN/openapi.json" | python -m json.tool
curl -sSI "$ORIGIN/.well-known/api-catalog"
```

## 7. Which node to trust

The `node=` argument names the one node you trust. The SDK fetches its statement and keys and pins the node key on first fetch (trust on first use). It refreshes the node's revocation status list in the background (at most every 60 s). `node_max_level=` (default 3) caps the level you accept from that node.

For a stricter setup, pass a signed trust list instead: `trust_list=verifier.TrustList(jws, key)` (OAID-5), where `key` is the public JWK you signed the list with. The trust list then replaces `node=` as the source of trusted nodes.

**The hosted node** is https://demo.allowedby.com. It approves for its own demo sites (`https://NAME.demo.allowedby.com`) and for the services onboarded on it: their origins are listed in the node's `ALLOWEDBY_AUDIENCES`. Any other service gets `400 this demo node only approves for its own demo sites`. To onboard your app, send your production origin (for example `https://app.example.com`) to the node operator; it is added to that list and the node restarts. To run your own node, see the settings below.

**How a node is configured.** A node is started by `demo/run.py`. The settings that matter to you:

| Env var / flag | Effect |
|---|---|
| `--domain` / `ALLOWEDBY_DOMAIN` | Hosted mode: the node at `https://DOMAIN`, the example sites at `https://NAME.DOMAIN`. |
| `ALLOWEDBY_ABOUT_DOMAIN` | Optional host name that also serves the presentation site at its root. Must not be a demo site's host name. |
| `ALLOWEDBY_DOCS_DOMAIN` | Optional host name that serves the documentation, its live runs and its MCP endpoint. Must not be a demo site's or the presentation site's. |
| `ALLOWEDBY_LIVE` | `off` closes the documentation's live runs. |
| `ALLOWEDBY_ADMIN_TOKEN` | Required in hosted mode. Every console token is derived from it. |
| `ALLOWEDBY_AUDIENCES` | Comma-separated origins of the services this hosted node approves for, besides its demo sites. `*` allows any https service. |
| `ALLOWEDBY_MDS_ROOT` | PEM file of the pinned GlobalSign Root CA - R3. The node then fetches the FIDO MDS3 BLOB at start, verifies it, and caches it in its data folder: this is how passkeys are graded `hardware` in production. Fetching the BLOB means the node operator accepts the FIDO Alliance MDS terms. If the BLOB cannot be loaded, the node logs it and level 3 is unavailable (fail closed). |
| `ALLOWEDBY_PASSKEY_ROOTS` | Local alternative to MDS3 for tests: JSON file `{aaguid: [root PEM]}` of authenticators that prove a hardware key. Without MDS3 or this file no passkey reaches L3. |
| `ALLOWEDBY_SIGNICAT_DOMAIN`, `ALLOWEDBY_SIGNICAT_CLIENT_ID`, `ALLOWEDBY_SIGNICAT_CLIENT_SECRET` | Signicat eID Hub: national eIDs (OIDC). |
| `ALLOWEDBY_SIGNICAT_NOTIFIED` | JSON file `{idp: {"country": "BE", "notified_loa": "high", "when": {claim: value}}}` from the Commission's list of notified schemes. A list of variants is allowed; `when` matches claims of the ID token, for eIDs whose `idp` also covers a non-notified variant (Norwegian BankID biometric, ID Austria basic). An eID not listed gives level 2 at most. The repository ships `demo/trust/signicat-notified.json`, with the source of each entry. |
| `ALLOWEDBY_ASSURE_CLIENT_ID`, `ALLOWEDBY_ASSURE_CLIENT_SECRET` | Signicat Assure (ReadID + iProov): passport and ID-card chip with liveness. |
| `ALLOWEDBY_ASSURE_LIVENESS` | `substantial` (default) or `high`. Use `high` only with the liveness certificate on file. |
| `ALLOWEDBY_CSCA` | PEM file of CSCA certificates: the node re-checks chip data itself, as a shadow. |
| `ALLOWEDBY_CROSSCHECK` | `log` (default) or `refuse` when the shadow check disagrees. |

The redirect URI to register at Signicat is `<node>/verify/return`. With no Signicat variable set, the node offers only its simulated identity provider.

What the node grants, from Signicat results (`allowedby/idsources.py`):

| Source | Level |
|---|---|
| National eID, notified at high, login at high | L3 (with a hardware passkey) |
| National eID, substantial or high, notified | L2 |
| Passport/ID chip + liveness `high` + chip authentication | L3 (with a hardware passkey) |
| Passport/ID chip + liveness `substantial` | L2 |
| Chip without liveness | none |

## 8. Tenants (multi-tenant SaaS)

Put the tenant in the path and at the start of the resource. Each tenant can only **tighten** your rules, and may have budgets:

```python
routes.append(
    route("POST", "/t/{tenant}/invoices/{id}/approve", "invoices:approve", cls="write-hard", level=2,
          resource="tenant:{tenant}:invoice:{id}", amount_field="/total",
          summary="Approve an invoice", body={"total": "invoice total", "currency": "EUR"}))
templates["invoices:approve"] = "Approve {scope}, up to {amount.max} {amount.currency}"

options["tenants"] = {
    "initech": {"name": "Initech SA",
                "org": os.environ.get("INITECH", "https://initech.example"),  # who signs its staff's mandates
                "routes":  {"invoices:approve": {"mandate": True, "level": 2}},
                "budgets": {"invoices:approve": {"max": "6000.00", "currency": "EUR", "per": "month"}}},
}
```

- Because the tenant starts the resource id, an approval for one customer never works for another.
- A tenant's `routes` override your route for one capability, and can only tighten it:
  - `level` and `authn` (the stricter one counts);
  - `mandate`, `qes`, `authority` and `require_link`;
  - a shorter `max_lifetime`, a lower `amount_max`;
  - `operators`, the agent operators allowed.

  `"members_only": True` with `org` needs a mandate from that organisation on every route of the tenant. Any other
  key, or a value of another shape, stops the app at start: a misspelt override would leave the route as loose as
  yours.
- A budget, `{"max", "currency", "per": "day" | "week" | "month", "tz"}` (`tz` defaults to UTC), counts the
  amounts the SDK accepts on that capability, per calendar period:
  - Its route needs `amount_field`.
  - When the budget is used up, the SDK answers `403 budget_exceeded` before anyone is asked. It does the same for a
    request without an amount in the budget's currency, since amounts are never converted.
  - The count is kept in the verifier's store: give every instance the same `store` so they share it.
- A tenant may carry its own authority policy under `"authority"`. The SDK signs it and publishes it at `/.well-known/allowedby/tenants/<tenant>`. Your config is the source of truth: edit a policy there and redeploy, and it applies on the new instances, with nothing else to do; the instances of one config share one signed policy through the verifier's store, and old and new instances of a rolling deploy each keep their own. `aby.set_authority_policy(policy, tenant=None)` overrides yours, or a tenant's, while the app runs (`policy=None` leaves a tenant with no policy of its own), and `aby.revert_authority_policy(tenant=None)` removes the override. The instance that calls it holds it at once, every other instance that shares the store at its next refresh, within `refresh_seconds`, and it outlives restarts: approvals made under the old policy stop working everywhere within the refresh interval. To take control back from an override through your config, raise its revision, `authority_policy_revision=` for yours or `"authority_policy_revision"` in the tenant for a tenant's (both 0 by default): the config wins over an override set at a lower revision. The log says, at start, which one applies and why. A store that every instance shares (Redis, or SQLite on one machine), and a `key_file` they share, are what make it shared: a store of your own without `put_doc` and `get_doc` keeps policies per instance (the log says so once), and without a `key_file` a run-time change stays on the instance that made it and is lost on restart (the log says so at the first one). A policy is signed for 365 days and renewed by the SDK past half of that, the approvals made under the one it replaced staying valid, so it never lapses while the app runs or restarts.
- Tenants are edited live in the admin console.

**Account linking.** When agents act on accounts shared by several people, link the person to your account first. Your signed-in account page calls `aby.link_start(account)` and shows the code. The person gives the code to their agent, which sends it to `POST /allowedby/link`. Pass `require_link=("write-hard", "irreversible")` to `AllowedBy` to require it on those classes, and `link_authorize(account, route, params)` for your own check. When you delete an account, or the person asks to be forgotten, call `aby.unlink(account)`: the person links again with a new code. Users who sign in through Auth0, Okta, Cognito or another provider: read [Apps that use a sign-in provider](https://docs.allowedby.com/guides/existing-sign-in) for what changes, and how to keep the links in your database.

## 9. Personal data, purpose and the disclosure key

A grant carries no name, email or phone. To get them, declare each attribute with a purpose and a retention period, then name them on the routes that need them:

```python
options["disclosure"] = {
    "legal_name": {"purpose": {"en": "Name on the signed contract"}, "retention_days": 3650},
    "email":      {"purpose": {"en": "Send you the receipt"},        "retention_days": 365},
}
routes.append(
    route("POST", "/contracts/{id}/sign", "contracts:sign", cls="irreversible", level=2,
          resource="contract:{id}", disclose=["legal_name"], disclose_optional=["email"]))
templates["contracts:sign"] = "Sign {scope}"
```

How it works:
1. The SDK publishes `disclosure` and a `disclosure_key` (public encryption key) in `/.well-known/allowedby`.
2. The approval page shows each attribute, its purpose and how long you keep it. Optional ones start unticked.
3. The node encrypts what the person chooses to your `disclosure_key` (JWE, ECDH-ES+A256KW, A256GCM) and posts it to `/allowedby/callback`, signed, before the agent retries.
4. You read it in the handler:

   ```python
   who = aby.personal_data(ctx)  # {"legal_name": "Claire Martin", "email": "..."} or {}
   ```

The agent never sees it.

| Available from | Attributes |
|---|---|
| L1 | `email`, `phone` |
| L2 | `legal_name`, `given_name`, `family_name`, `birth_date`, `age_over_18` (`age_over_13` to `age_over_99`), `nationality`, `address`, `verified_by` |

Ask for `age_over_18` rather than `birth_date` when that is enough. Store what you receive under the retention you declared, and delete it on time.

## 10. Company mandates and budgets

With `mandate=True` on a route, or on a tenant's route, the person must approve **for their company**. The company's organisation node gives them a mandate: signed by the company, tied to their passkey, at most 30 days, optionally capped (for example "invoices up to 10,000 EUR"). The SDK checks it offline against the keys the company publishes at its `org` origin (`https://<company>/.well-known/allowedby`). You get:

```python
company = ctx.acting_for  # {"org": "https://initech.example", "name": "Initech SA", "role": "Accounts clerk"}
```

(`ctx` is the context of the accepted request.) Budgets can apply at several places. You control only the first one:

| Budget | Set by | Enforced by |
|---|---|---|
| Tenant budget per capability | You, in `tenants[...]["budgets"]` | Your SDK: `403 budget_exceeded` before anyone is asked |
| Organisation, team, member, operator budgets | The company, in its organisation console | The node: Allow is disabled on the approval page |
| Personal budget | The person, in their wallet | The node |
| Per-approval limit (`amount_field`) | The person, on the approval page | Your SDK, on every request |

## 11. Admin console and its token

`/allowedby/admin` comes with the SDK. It shows and edits:
- **Overview:** requests, new people, sign-ins, approvals asked and answered, per hour or per day.
- **Access rules:** each route's rule in plain words. Class, level (0–3), passkey type and mandate per route. A change applies to the next request and to what you publish.
- **Tenants:** overrides and budgets, with what is used this period.
- **People** and **Agents:** pseudonymous ids, first and last seen.
- **Activity log:** every request, accepted or refused, with filters and CSV export.
- **Personal data:** what you may ask for, what you received, and when to delete it.
- **Trust and keys:** the node you trust, how fresh its revocation list is, and your signing key.

**The token.**
1. Generate a long random token and keep it in your secret manager (GCP Secret Manager, AWS Secrets Manager, Vault).
2. Pass it at start: `AllowedBy(..., admin_token=os.environ["ALLOWEDBY_ADMIN_TOKEN"])`. Without it, the SDK generates a random one at each start (`aby.admin_token`); do not rely on that in production.
3. Open the console with the token in the URL fragment, which browsers never send to the server: `https://notes.example/allowedby/admin#token=...`.
4. Never log it. The API accepts it only in the `X-Admin-Token` header, never in the query string.

The console API, for scripts:

```bash
curl -sS "$ORIGIN/allowedby/admin/api" -H "X-Admin-Token: $TOKEN"
curl -sS -X POST "$ORIGIN/allowedby/admin/api/routes" -H "X-Admin-Token: $TOKEN" -H "Content-Type: application/json" \
  -d '{"index": 0, "level": 2}'
curl -sS -X POST "$ORIGIN/allowedby/admin/api/tenants" -H "X-Admin-Token: $TOKEN" -H "Content-Type: application/json" \
  -d '{"tenant": "initech", "capability": "invoices:approve", "budget": {"max": "8000.00", "currency": "EUR", "per": "month"}}'
```

For a SIEM, pass `audit_sink="stdout-json"` (or a callable that takes a dict) to get every decision as a JSON line.

## 12. Storage for replay and single-use state

By default the SDK keeps the replay set, the single-use set and the counters in memory. That is right for **one process only**. With several workers or instances, a replayed proof or a reused one-time approval could pass on another process.

Use the SQLite store, shared by every process on a machine (or on a network file system that locks), or `RedisStore`:

```python
options["store"] = SqliteStore(os.environ["ALLOWEDBY_DB"])  # an absolute path all processes share: /var/lib/notes/a.db
```

Each operation is one `BEGIN IMMEDIATE` transaction in WAL mode, so check-and-set is atomic. For instances on several machines, you need the same semantics in a shared database (Redis or a database with compare-and-set). The package also has `RedisStore` (extra `redis`).

**What the store does not cover today.** These stay in each process's memory: tenant budget spend, the admin console's audit and activity, received personal data, account links and pending link codes, callback replay ids, and the signing and disclosure keys (section 13). With several processes, run one process per public origin, or plan to extend these before scaling out.

Other per-route protections you can turn on: `rate={"actor": (600, 60), "operator": (6000, 60)}` (requests per seconds; these are the defaults), `nonce=True` (AllowedBy-Nonce on irreversible routes), `rfc9421=True` (accept the RFC 9421 Web Bot Auth profile).

## 13. Key management and rotation

The SDK holds two keys:

| Key | Used for | Published in |
|---|---|---|
| Signing key (`aby.key`) | Signs approval requests your app creates, your company profile and authority policies | `keys` in `/.well-known/allowedby` |
| Disclosure key (`aby.enc`) | Personal data is encrypted to it | `disclosure_key` in `/.well-known/allowedby` |

**Keep them with `key_file=`.** Pass `AllowedBy(..., key_file="/secrets/allowedby-keys.json")`. The SDK creates the file with fresh keys on first start (mode 0600; the folder needs hard links, so that instances starting together end up with the same keys, else the start fails) and loads it afterwards, so every restart and every instance uses the same keys. Put the file on a private volume, or write it from your secret manager before the app starts.

Without `key_file`, both keys are **new at each start**:
- every restart publishes new keys;
- personal data encrypted to the old disclosure key, and approvals your app created but that were not yet used, are lost at restart, and the agent asks again;
- each process has different keys, so callbacks with personal data must reach the process that published the key the node used.

To rotate, start with a new file and keep the old app instance running for a short overlap. The node's own keys are rotated through the node admin API (`/oaid/v1/admin/...`, header `X-Admin-Token`); companies rotate their mandate key in their organisation console (`/org/<oid>/api/keys/rotate`, needs a second admin).

## 14. Going-live checklist

Change each of these before you accept real agents. Items marked *demo* are shortcuts the hosted demo takes.

| # | Change | Why |
|---|---|---|
| 1 | Serve over **https**. *Demo: plain http on `*.localhost`.* | Proofs bind the exact URL; the approval page needs a secure origin. |
| 2 | Trust a **production node**, or your own, and have your origin onboarded on it (`ALLOWEDBY_AUDIENCES`). | Section 7. |
| 3 | Keep your signing and disclosure keys across restarts and instances with `key_file=` on a private volume or from your secret manager. *Demo: generated at start.* | Section 13. |
| 4 | **Share the replay set, single-use set and counters** between instances (`SqliteStore`, or a shared database with compare-and-set). *Demo: memory, or SQLite.* | Section 12. |
| 5 | Keep the **admin token** in a secret manager and pass `admin_token=`. | Section 11. |
| 6 | Store **received personal data** under the retention you declared, and delete it on time. | Section 9. |
| 7 | **Link accounts** (`aby:link`, `require_link=`) before accepting `write-hard` or `irreversible` actions on accounts shared by several people. | Section 8. |
| 8 | Have your **organisation profile verified**, with a qualified seal or by your node. *Demo: verified by a node vouch.* Until then, the approval page shows only your hostname and "organisation not verified". | Trust on the approval page. |
| 9 | Make sure your node does **real identity verification** (Signicat env vars, section 7). *Demo: the "Verify" buttons are simulated; the typed name becomes the legal name.* | L2/L3 mean nothing otherwise. |
| 10 | Make sure your node verifies **passkey attestation** against the FIDO Metadata Service (`ALLOWEDBY_MDS_ROOT`). *Demo: a local allowlist, `ALLOWEDBY_PASSKEY_ROOTS`.* | Without it no passkey reaches L3. |
| 11 | Do not rely on **unverified email**. *Demo: the node accepts the email typed.* | Treat `email` as user-supplied. |
| 12 | Expect **independent witnesses** for the node's log. *Demo: one node is home, organisation and countersigning node, with no independent witness.* | Section 7, trust lists with `witnesses_min`. |
| 13 | **Agents** in production should carry tier 1+ passports (TPM, Secure Enclave, cloud KMS). *Demo: tier 0; the operator key is a file in `demo/.data/`.* Use `tier=` on routes that need it. | Custody of agent keys. |
| 14 | **QES** routes need a qualified trust service provider and an EU trusted-list snapshot (`qes_trusted_list=`). *Not built in the demo.* | Otherwise `qes_required`. |
| 15 | Run the **conformance vectors** (`vectors/`) against your deployment. | CONF-1. |
| 16 | Check that `/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog` and `/allowedby/callback` are reachable without your own auth. | Section 6. |

## 15. Testing with an agent

### Against the hosted node (to see the flow)

Until your origin is in the node's `ALLOWEDBY_AUDIENCES`, use the hosted node to see the flow on its own sites:

1. Install the agent for Claude Code:

   ```bash
   claude mcp add allowedby -- allowedby-mcp --node https://demo.allowedby.com
   ```

2. Ask Claude: "Add a note 'Buy milk' on https://notes.demo.allowedby.com, then show my notes."
3. Approve on the page that opens (see `docs/deploy-user.md`).

### Against your own app (locally)

The local node accepts any service.

1. Start the demo node and sites: `python demo/run.py --reset`. The node is `http://localhost`.
2. Point your app at it: `AllowedBy(origin="http://myapp.localhost", node="http://localhost", ...)`.
3. Serve your app under a `*.localhost` name next to the demo, as `demo/run.py` does with `core.serve_hosts` and `core.WsgiApp`. Or run it on its own port.
4. Call it from Python:

   ```python
   import os

   from allowedby import Agent

   agent = Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost"), tell=print)  # prints the link and the code
   app = os.environ.get("APP_URL", "http://myapp.localhost")
   status, body = agent.call("POST", app + "/notes", {"text": "Buy milk"}, action="notes:write")
   print(status, body)
   ```

   Or give the address to Claude with the MCP agent (default node `http://localhost`).
5. For automated tests without a browser, copy `SoftPasskey` and `Human` from `demo/e2e.py`. Run the full suite with `python demo/e2e.py`.

**Agent vendors:** publish `https://<your-domain>/.well-known/oaid-operator` with your keys and nodes (see `demo/agent_operator.py`), and pass `operator_domain=` and `operator_key=` to `Agent`. Your agents' approvals then survive their hourly key change. Without a verified domain, the person is asked again every hour.

## 16. Troubleshooting

Refusals are `application/problem+json` with `type: https://allowedby.org/errors/<code>`. Challenges also carry `WWW-Authenticate: AllowedBy ...`. The admin console's Activity log shows the same code in plain words.

| Status | Code | Meaning | What to do |
|---|---|---|---|
| 400 | `invalid_request` | Malformed request, or the body is not a JSON object. | Send a JSON object body. |
| 401 | `passport_required` | The agent sent no passport. | The caller is not an AllowedBy agent, or calls a protected route without one. |
| 401 | `grant_required` | No approval for this action. The challenge says what is needed. | Normal first call. The agent asks the person. |
| 401 | `grant_insufficient` | The approval does not cover this resource, amount or request (or a one-time approval is for another request). | The agent asks for a wider approval. |
| 401 | `level_insufficient` | The person's level is below the route's. | The person verifies their identity on the approval page. |
| 401 | `mandate_required` | The route needs a company mandate, or the mandate does not cover this. | The person approves "for" their company; check the tenant's `org`. |
| 401 | `expired`, `actor_expired` | The approval, or the agent's passport, expired. | The agent rebinds or asks again. |
| 401 | `revoked` | The person withdrew the approval. | The agent asks again. |
| 401 | `single_use_consumed` | A one-time approval was already used. | Expected on retries of a serious action. |
| 401 | `class_lifetime_exceeded` | The approval lasts longer than this class allows. | Lower the requested period. |
| 401 | `invalid_signature` | Bad, expired or replayed proof; tampered grant; or bad admin token. | Check the agent's clock (proofs must be within -120 s/+60 s) and the URL your app sees (scheme, host, port must match `origin`). |
| 401 | `untrusted_node` | The approval comes from a node you do not trust. | Check `node=` or your trust list. |
| 401 | `qes_required`, `authority_required` | A qualified signature, or the organisation's co-approvers, are needed. | See the specs. |
| 403 | `budget_exceeded` | A tenant budget is used up. Nobody is asked. | Raise the budget in the admin console, or wait for the next period. |
| 403 | `capability_denied` | No such route, or the account refuses this operator or amount. | Check the route map. |
| 403 | `tier_insufficient` | The passkey is not of the required kind (e.g. `authn="hardware"`). | The person uses a hardware passkey. |
| 403 | `human_not_linked` | The route needs a linked account. | Section 8, account linking. |
| 429 | `rate_limited` | Too many requests from this agent or operator. `Retry-After: 60`. | Wait, or raise `rate=`. |
| 431 | `envelope_too_large` | The `Allowed-By` header is too large. | Usually a delegation chain too deep. |
| 503 | `status_stale` | Your copy of the node's revocation list is too old; serious actions are paused. `Retry-After: 5`. | Check that your app can reach the node; look for `[verifier] refresh failed` in your logs. |

Other common issues:
- **"organisation not verified" on the approval page.** Your profile is not verified by a seal or by the node.
- **`400 this demo node only approves for its own demo sites`.** Your origin is not onboarded on the node. Ask the node operator to add it to `ALLOWEDBY_AUDIENCES`, or use a local node.
- **Proof fails behind a proxy.** The SDK rebuilds the URL from `origin` and the path your app sees. Make sure the proxy does not rewrite the path.
- **Personal data is empty.** The callback did not reach `/allowedby/callback`, or reached another process whose disclosure key differs (section 13).

## Reference

- SDK: `sdks/python/src/allowedby/sdk.py`; verifier and stores: `sdks/python/src/allowedby/verifier.py`; agent runtime: `sdks/python/src/allowedby/agent.py`. Python guide: `docs/sdk/python.md`.
- Example apps: `demo/examples/notes_app.py`, `shop_app.py` (B2C), `supply_app.py` (B2B, tenants and mandates), `saas_app.py` (plans).
- Walkthrough: `demo/INTEGRATE.md`. Specs: `specs/README.md`; for services read OAID-1, ABY-2, ABY-1, OAID-7 §4, OAID-5, ABY-3, and ORG-1 §2–§3.
