# Python SDK

Public classes and functions of the `allowedby` package (`sdks/python/src/allowedby`). Guide: [Deploy AllowedBy in your SaaS app](https://docs.allowedby.com/guides/accept-agents).

SDK guide: [python.md](https://docs.allowedby.com/sdk/python).

## `allowedby.sdk`

`sdks/python/src/allowedby/sdk.py`

AllowedBy SDK for services (Python): accept AI agents in a few lines.

```
from allowedby.sdk import AllowedBy, route
```

```
aby = AllowedBy(
    origin="https://notes.example", node="https://node.example.org",
    org={"legal_name": "Notes Ltd", "country": "FR"},
    routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*"),
            route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new")],
    templates={"notes:read": "Read your notes", "notes:write": "Write notes"})
```

```
app = aby.wsgi(app)              # any WSGI app: Flask, Django, Falcon, ...
# in a handler: ctx = environ["allowedby.context"]  -> ctx.human_id, ctx.level, ctx.acting_for, ...
```

What the SDK does for you (specs 0.2.6):
- serves /.well-known/allowedby (vocabulary, templates, keys, signed organisation profile, disclosure key);
- describes your API in standard formats: OpenAPI 3.1 at /openapi.json (each operation says the capability and
  level it needs, in `security` and `x-allowedby`), listed in the RFC 9727 catalog /.well-known/api-catalog;
- verifies every request offline (ABY-2 §5) against your route map;
- answers 401 with a challenge, and creates the approval itself for write-hard and irreversible routes;
- receives the node's callback and decrypts the personal data you declared (ORG-1 §4);
- enforces tenant overrides and tenant budgets (ORG-1 §3.3, §5.3);
- organisational authority: publishes a signed authority policy, per tenant too, and checks co-approvers and rule
  budgets (ABY-1 §5);
- account linking (`aby:link`, ABY-3 §6) at /allowedby/link, `require_link` routes, `human_hint` in approvals;
- optional: a store shared by instances (SqliteStore), a signed trust list (OAID-5), AllowedBy-Nonce on irreversible
  routes, the RFC 9421 Web Bot Auth profile, per-agent rate limits, an audit sink of JSON lines (ORG-1 §7.6);
- serves an admin console at /allowedby/admin (token printed at start).

### `explain_route`

```python
explain_route(r, tenants=None)
```

The rule of one route, in sentences an admin can check at a glance.

### `route`

```python
route(method: str, path: str, capability: "str | None" = None, cls: "str | list[dict[str, str]]" = "read", level: int = 1, resource: "str | None" = None, amount_field: "str | None" = None, currency_field: str = "/currency", authn: "str | None" = None, mandate: bool = False, disclose: "Iterable[str]" = (), disclose_optional: "Iterable[str]" = (), summary: "str | None" = None, body: "dict[str, Any] | None" = None, tier: int = 0, qes: bool = False, authority: bool = False, max_lifetime: "int | None" = None, require_link: bool = False, nonce: bool = False, level_profile: "str | None" = None) -> "dict[str, Any]"
```

One line of the route map (ABY-3 §4.1). level 0 = the agent's passport is enough (no human). cls: a class, or for payments a list of amount thresholds [{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}] read at amount_field. max_lifetime: seconds, at most 30 days. tier: custody tier. qes: a qualified signature (OAID-7 §10; the verifier needs an EU trusted-list snapshot). authority: co-approvers under the authority policy (ABY-1 §5). require_link: the person's account must be linked (ABY-3 §6). nonce: AllowedBy-Nonce. summary and body describe the route to agents (OpenAPI): what it does, and each JSON body member.

### `Handler`

```python
class Handler(store: "dict[str, Any]", resolve: "Callable[[str, str], Any]", current: Any, rules: "Callable[[], Iterable[tuple[Any, str, Any]]] | None" = None, matched: "str | None" = None, wildcard: "Callable[[str, str], bool] | None" = None) -> None
```

What an adapter that sees the chosen handler knows: the handler about to run (`current`), and how its router resolves a path (`resolve(method, path)`: the handler, or None). `store` is the adapter's own dict, kept across requests: the handler of each route of the map, resolved once with sample values, then learnt from checked requests. A route may have several handlers (a router may choose by value: `<int:id>`, `<uuid:id>`): every one found is kept. `rules`, when the router lists what it has: () -> [(methods or None for any, path with each parameter as {}, handler)], the rules registered with it. A rule of the same shape as a route of the map, its converters aside, is that route's own handler: known even when no sample value reaches it (`<int(min=1000):id>`).

matched: the shape (each parameter as {}) of the router rule that matched this request, when the framework names it (Flask request.url_rule, Django resolver_match): the strongest evidence of whose handler runs. wildcard(method, path): whether the router chose its handler for that path through a site-wide wildcard rule (/&lt;path:p>, /{p:path}, a re_path ^(?P&lt;p>.\*)$); None when the router cannot say.

| Method |  |
|---|---|
| `claim(aby: "AllowedBy", method: str, template: str, allowed: "Callable[[], bool]", by_rule: bool = False) -> bool` | Decide and record in one locked step: the handler about to run becomes this route's when no other route owns it and `allowed()` (the covers condition) still holds, checked under the lock. Two requests for two routes that run one unknown handler at the same moment: at most one is accepted, and the handler belongs to one route. A catch-all is never learnt: a checked request that would run one (a value the route's converter refuses, falling through to an SPA fallback) is refused, unless the rule that matched has the route's own shape (by_rule): then it is the route's own handler; or the route's own handler is not known, that catch-all is the only handler found for it (a front controller, a router mounted at / or /api/), and the route covers every other route for which that catch-all is protected: it runs for this checked request, and nothing is learnt, so the route stays not known. |
| `is_known(aby: "AllowedBy", method: str, template: str) -> bool` | The handler about to run is a known handler of this route. |
| `unknown_routes(aby: "AllowedBy", method: str, template: str) -> "list[dict[str, Any]]"` | The other routes of the map, of any method (a handler runs the same code whatever the method), whose own handler is not known. |
| `uncovered(aby: "AllowedBy", r: "dict[str, Any]") -> "dict[str, Any] \| None"` | Another route of the map that the handler about to run serves too, which `r` does not cover (CONTRACT rule 5): one for which it is protected as a catch-all (a checked request for r never lifts that protection), or one whose known handler it is, of any shape (one function on DELETE /notes/{id} at level 3 and DELETE /items/{id} at level 1: a request checked for /items/7 must not run the delete of note 7). The one exception is a route of another method, on any path, served by a class view that dispatches by method to separate code (a GET runs only get()); a route of the same method on another path runs the same code, and needs covering. |
| `of_another_route(aby: "AllowedBy", method: str, template: str) -> bool` | The handler about to run for a request checked for this route is a known handler of another route of the map, of any method, and not of this one: an alias on this route's path (/notes/purge, checked as /notes/{id}, that runs the handler of DELETE /notes/{id}/archive). A handler shared by two routes is known for both. |
| `owners(aby: "AllowedBy") -> "list[tuple[str, str]]"` | The routes of the map (method, template) the handler about to run is a known handler of. |
| `protected(aby: "AllowedBy", method: str, path: str) -> "bool \| None"` | True: the handler of a route of the map, of any method (it runs the same code: a GET alias of a protected POST handler is refused). None: cannot tell, as the handler of a route of the map near this path, of any method, is not known. False: neither. |

### `only_handlers`

```python
only_handlers(view_cls: type, framework: str, base: type) -> bool
```

For an OPTIONS the framework answers itself (CONTRACT §2.10 rule 5), over the view's whole MRO:
- the class is built by `type` itself: a metaclass's __call__ would run when the framework builds the view;
- every entry point that can run for OPTIONS (_OPTIONS_ENTRY_POINTS: options, dispatch, setup, __new__, __init__,
  http_method_not_allowed, method_not_allowed, __call__, __await__, attribute access and assignment, __del__)
  resolves to `base` itself (Django's View, Starlette's HTTPEndpoint) or to object: a framework subclass with
  its own options() (RedirectView calls get()) or a mixin anywhere ends it;
- every class other than object and those of the framework's own modules (`framework`, such as "django.")
  defines nothing but its HTTP handlers (never options), each a plain function (the framework looks them up to
  list the allowed methods: a property or another descriptor would run), and plain class metadata or data
  (plain_data). Class creation hooks (__init_subclass__, __set_name__, class decorators) run at import, not for a
  request; what they leave in the class is what this checks.

### `plain_data`

```python
plain_data(value: Any, depth: int = 0) -> bool
```

A value whose use runs no code of the app: None, a bool, number, string or bytes, or a tuple, list, set or dict of them, each of exactly that type (a subclass can define __contains__, __iter__ or __eq__).

### `org_profile`

```python
org_profile(key, origin, org, node_name)
```

ORG-1 §2: the signed organisation profile. Raises ValueError for one a wallet would refuse: no legal name, a country that is not ISO 3166-1 alpha-2, links that are not URLs, a logo without its hash, over a year.

### `load_keys`

```python
load_keys(path: str) -> "tuple[core.Key, Any]"
```

(signing Key, disclosure EC key) from `path`, created with fresh keys if missing. Write it once (atomically, 0600) so instances started together end up with the same file.

### `AllowedBy`

```python
class AllowedBy(origin: str, node: str, routes: "Iterable[dict[str, Any]]", templates: "dict[str, Any]", org: "dict[str, Any]", disclosure: "dict[str, Any] | None" = None, tenants: "dict[str, Any] | None" = None, node_max_level: int = 3, refresh_seconds: float = 5, admin_token: "str | None" = None, clock: "Callable[[], int] | None" = None, title: "str | None" = None, version: str = "1.0.0", description: "str | None" = None, authority_policy: "dict[str, Any] | None" = None, store: Any = None, trust_list: Any = None, nonce: bool = False, rfc9421: bool = False, rate: "dict[str, tuple[int, int]] | None" = None, audit_sink: Any = None, require_link: "Iterable[str]" = (), account_param: str = "account", link_authorize: "Callable[..., bool] | None" = None, qes_trusted_list: Any = None, key_file: "str | None" = None, max_body: int = 1 << 20, background_refresh: bool = True, serve_openapi: bool = True, unprotected: "Iterable[Any]" = (), authority_policy_revision: int = 0) -> None
```

authority_policy: {"rules": [...], "groups": {...}} (ABY-1 §5), signed and published by the SDK; a tenant may carry its own under tenants[t]["authority"]. authority_policy_revision (and tenants[t] ["authority_policy_revision"]): an integer the operator raises only to take control back from an override set at run time (set_authority_policy), which stays in force until the config's revision is above the one it was set over. An edited config needs no revision: it applies on the instances built from it. store: verifier.SqliteStore(path) to share replay set, single use and counters between instances. trust_list: verifier.TrustList (OAID-5), default trust on first use. nonce: AllowedBy-Nonce on irreversible routes (ABY-2 §3.2); rfc9421: accept the Web Bot Auth profile. rate: {"actor": (n, seconds), "operator": (n, seconds)}. audit_sink: "stdout-json" or a callable(dict). require_link: classes whose routes need a linked account, e.g. ("write-hard", "irreversible"). account_param: the path parameter naming one of your accounts (for `human_hint`); link_authorize(account, route, params) -> bool: your own authorisation of a linked account for a resource, asked only for a linked person: anything but True refuses with 403 human_not_linked. ctx.linked_account is that account. key_file: a private JSON file keeping the signing key and the disclosure key across restarts and shared by every instance (created on first use, mode 0600). Without it both keys are new at each start: agents then re-fetch /.well-known/allowedby, and personal data encrypted to the old disclosure key cannot be read. max_body: the largest request body (bytes) the middleware reads on a route of the map (1 MiB by default); a larger one is refused with 400 invalid_request before it is read. background_refresh: False in tests that call `aby.verifier.refresh()` themselves (no thread). serve_openapi: False when the framework serves its own /openapi.json, enriched with `describe()` (allowedby.fastapi does this). unprotected: pages of your own whose path looks like a variant of a protected route or extends one, e.g. "/notes/new/" or ("GET", "/notes/{id}/comments") next to "/notes/{id}": exact paths, or (method, path). Without it such a path is refused (400), never served unchecked.

| Method |  |
|---|---|
| `sign_policy(org, policy)` | ABY-1 §5: sign an authority policy for `org` with our key and hold it in the verifier. -> compact JWS. |
| `refresh_policies(initial=False)` | sdks/CONTRACT.md (Authority policies): hold, for each scope, the API override when one is in force, else the config's policy, both as stored, renewed past half their life. Runs at construction (initial: the decision is logged where an override exists) and at every verifier refresh. A store error keeps what is held (logged); the next refresh tries again. |
| `set_authority_policy(policy: "dict[str, Any] \| None", tenant: "str \| None" = None) -> "str \| None"` | ABY-1 §5, ORG-1 §3.3: override the authority policy, the service's or one tenant's, at run time: signed anew (a new jti), held by the verifier and published at once. Approvals that carry the previous policy then get authority_required. policy None, for a tenant: no policy of its own (its authority, the policy we published and the one the verifier holds go), and its routes use the service's. revert_authority_policy goes back to the config. Raises ValueError for a malformed policy or an unknown tenant. -> the policy JWS (None). The override is written to the verifier's store: every instance that shares the store takes it at its next refresh (refresh_seconds), and it outlives restarts until the config's authority_policy_revision is raised above the revision it was set over. Without a key_file it stays on this instance and is lost on restart (said once): a key made at each start signs nothing another instance, or a restart, can verify. A store error raises status_stale (Reject) and changes nothing. |
| `revert_authority_policy(tenant: "str \| None" = None) -> None` | Remove the override set_authority_policy made for the service, or one tenant: the config's policy applies again, on every instance at its next refresh. Raises ValueError for an unknown tenant. |
| `link_start(account: str, ttl: int = 600) -> str` | Your signed-in account page calls this: a one-time code the person gives their agent, which sends it to /allowedby/link. The agent's approval (aby:link, single use) then links their identity to `account`. Raises ValueError for an account that is not a non-empty str: no require_link route could ever take that link. |
| `unlink(account: str) -> bool` | ABY-3 §6 (Removing a link): remove the link of one of your accounts, when you delete the account or the person asks to be forgotten: the stored pair (home node, pairwise id) and the account's pending linking codes. A require_link route then refuses the person (403 human_not_linked) until they link again with a new code. -> False when the account was not linked (nothing else changes but its pending codes). Raises ValueError for an account that is not a non-empty str, as link_start does. |
| `well_known(prefix: str = "") -> "dict[str, Any]"` | The discovery document; its links are those of the app mounted at `prefix` ("" at the origin's root). |
| `tenant_well_known(tid)` | ORG-1 §3.3: a tenant's authority policy, signed by us, at /.well-known/allowedby/tenants/&lt;tenant>. |
| `openapi(prefix: str = "") -> "dict[str, Any]"` | OpenAPI 3.1 for the route map (ABY-3 §5.1). Each operation's `security` names the capability it needs (a role of the AllowedBy scheme); `x-allowedby` adds class, level, amount and personal data. |
| `describe(method: str, path: str) -> "dict[str, Any] \| None"` | The OpenAPI members of the route `method path` (path as declared, e.g. /notes/{id}): `security` (the capability it needs) and `x-allowedby` (class, level, amount, personal data). None when not in the map. Framework integrations add them to the framework's own OpenAPI document (allowedby.fastapi). |
| `api_catalog(prefix: str = "") -> "dict[str, Any]"` | RFC 9727 API catalog: where this origin's APIs and their descriptions are. |
| `check(method: str, path: str, headers: "dict[str, str]", body: bytes = b"", query: str = "", prefix: str = "", raw_path: "str \| None" = None ) -> "tuple[Context \| None, Response \| None]"` | -> (Context, None) when the request is allowed, or (None, (status, body, headers)) to send back. Paths that are not in the route map are allowed with ctx None (your own auth applies). path: the decoded path the app routes on (ASGI path without root_path, WSGI PATH_INFO). raw_path: the same path as sent, still percent-encoded, when the server gives it (ASGI raw_path); else `path` is percent-encoded again. The route map and the signed URL use that encoded form: a decoded "?" or "#" can never cut the path short. prefix: where the app is mounted (ASGI root_path, WSGI SCRIPT_NAME), "" at the origin's root; the URL the agent signed (htu, @target-uri, request_digest) is origin + prefix + path. |
| `admin_ok(headers)` | The site admin's token, from the X-Admin-Token header only (never the URL: it ends up in logs). |
| `public_audit(n=60)` | The activity feed for a public page: what was asked and the answer, never who (no person, agent or approval ids, no personal data, no rejection details). |
| `personal_data(ctx: "Context \| None") -> "dict[str, Any]"` | The attributes the human chose to share with this request's grant (ORG-1 §4), or {}. |
| `budget_status()` | Every tenant budget with what is used this period: for dashboards and the admin console. A status read never raises: when the store does not answer, a budget has "stale": true and no "used" (logged once a call), and a check() on its route answers 503 status_stale meanwhile. |
| `activity(now=None)` | Numbers for the console: last 24 hours and last 7 days, per hour and per day. |
| `handle(method: str, path: str, headers: "dict[str, str]", body: bytes = b"", query: str = "", prefix: str = "", raw_path: "str \| None" = None) -> "Response \| None"` | Endpoints the SDK serves itself. -> (status, body, headers) or None when the path is not ours. query, prefix, raw_path: see check(); every URL the SDK publishes or checks a proof against includes the prefix. |
| `protect(app, method, pattern, handler)` | Register `handler(req, ctx, **params)` on a demo core.App, behind the check. |
| `release(ctx: "Context \| None") -> None` | sdks/CONTRACT.md, Refund on the SDK's own refusal: the SDK refused this accepted request itself before its handler ran (rule 5, the method or the path changed after the check). Gives back exactly what the check spent for it, once: the single-use mark, the grant's totals, the tenant budget. When the store cannot take it, the approval stays spent (fail closed), logged without request data. Nothing is given back once the handler started (started()), even when a layer dispatches the same request again and the SDK refuses that second pass. |
| `started(ctx: "Context \| None") -> bool` | The adapter is about to hand this accepted request to the router or the view: from now on release() gives nothing back for it (sdks/CONTRACT.md, Refund on the SDK's own refusal: nothing is refunded once the handler started). False for a context already given back: a layer dispatching the same request again must not reach a handler with an approval that was refunded (a second use); the adapter refuses it (dispatch_refusal()). |
| `refund(ctx: "Context \| None") -> None` | The handler refused an accepted request (a wrong total, an unknown invoice): give the tenant budget back. |
| `mount(app)` | Serve the SDK's endpoints (well-known, callback, admin console) on a demo core.App. |
| `owns(method: str, path: str, headers: "dict[str, str] \| None" = None, query: str = "", guarded: bool = False, prefix: str = "") -> bool` | True when the SDK handles this request: one of its own endpoints, a route of the map, or a variant of one (see `variant`). Adapters buffer the body of these requests only; every other request reaches the app untouched (streaming kept). guarded: the adapter checks the method and the path again at dispatch (see `may_dispatch`). prefix: where the app is mounted (SCRIPT_NAME, root_path). |
| `may_dispatch(method: str, path: str, checked: "tuple[str, str] \| None", params: "Iterable[Any] \| None" = None, prefix: str = "", same: "Callable[[list[str]], bool \| None] \| None" = None, handler: "Handler \| None" = None) -> bool` | The last look, where a framework runs a handler (sdks/CONTRACT.md §2.10): whatever a layer behind the SDK did to the method or the path (a `_method` field in any spelling, a header, a rewrite), a handler of a route of the map runs only for the very request the SDK accepted. checked: what checked_as() gave then, or None. prefix: as for owns(). For a path the map does not match, and a declared page: params: the values the framework took from the path for this handler. One that holds a "/" (a wildcard, a path converter) must not make a protected handler run for a longer path. None: unknown, all longer paths are refused. same(paths): whether the handler about to run is the one the framework would choose for any of these paths (None when it has none for them). None: unknown, a declared page that is a route of the map but for its last "/" is refused. handler: the handler about to run, on an adapter that sees it: the handler of a route of the map runs only for a request checked for that route, whatever the path (an alias, a catch-all), and a declared page does not change that. |
| `variant(method: str, path: str, headers: "dict[str, str] \| None" = None, query: str = "", guarded: bool = False, prefix: str = "") -> "str \| None"` | sdks/CONTRACT.md §2.10: a request a framework may dispatch to a protected handler although the route map does not match it as sent: a trailing or doubled "/", a format suffix (/notes.json), a method in another case, or a method override (X-HTTP-Method-Override, X-HTTP-Method, X-Method-Override, `_method` in the query). A form may carry an override in any spelling: without a guard at dispatch, a form on a path the map protects under another method is one too. -> why, or None. Such requests are refused (400), never passed on unchecked, except on a path the app declares as its own (AllowedBy(unprotected=[...])). |
| `process(method: str, path: str, headers: "dict[str, str]", body: bytes = b"", query: str = "", prefix: str = "", raw_path: "str \| None" = None ) -> "tuple[Context \| None, Response \| None]"` | What every framework adapter does, in one call: the SDK's endpoints first, then the check. -> (None, response) to send back as it is (see `render`); (Context, None) for an accepted request on a route of the map; (None, None) for a path outside the map (your own auth applies). prefix, raw_path: see check(). A request whose decoded path is a route of the map but whose path as sent is not (an encoded "/", "?" or "#", dot segments) is refused: the app would route it to a protected handler unchecked. |
| `wsgi(app: "Callable[..., Any]", guarded: bool = False) -> "Callable[..., Any]"` | WSGI middleware: the SDK's endpoints, then the check on every route of the map, then your app. The accepted Context is in environ["allowedby.context"]. guarded: True when `app` ends in wsgi_guard() (the Flask extension has its own), so that forms on a path protected under another method reach the app. Without a guard, a path that matches a route of the map if a parameter takes several segments (/notes/7/x, for /notes/{id}) is refused unless declared in `unprotected`, as a wildcard pattern may serve it. A proxy that strips a prefix must set SCRIPT_NAME. |
| `wsgi_guard(app: "Callable[..., Any]") -> "Callable[..., Any]"` | Innermost WSGI middleware, right around the router, for apps with layers that change the method or the path between `wsgi()` and the router: `aby.wsgi(layer(aby.wsgi_guard(router)), guarded=True)`. See may_dispatch(). |

### `checked_as`

```python
checked_as(method: str, path: str) -> "tuple[str, str]"
```

What was checked, for may_dispatch(): the method (HEAD is checked as GET) and the decoded path.

### `dispatch_refusal`

```python
dispatch_refusal() -> "Response"
```

The refusal of may_dispatch(); when it refused a protected route's handler reached by another method, the title names the fix (route templates only: never a value of the request).

### `render`

```python
render(out: "Response | tuple[int, Any]") -> "tuple[int, list[tuple[str, str]], bytes]"
```

A response of the SDK, (status, body, headers), as bytes: a dict or list is JSON (problem+json for refusals), a str is HTML. -> (status, [(header, value)], body bytes), Content-Length included.

### `openapi_components`

```python
openapi_components() -> "dict[str, Any]"
```

The OpenAPI `components` every AllowedBy API shares: the two security schemes, the problem schema, the challenge header and the 401/403/503 responses the operations refer to.

### `admin_page`

```python
admin_page(aby, mount="")
```

The provider's admin console: overview, access rules per route, people, agents, activity log, personal data.

## `allowedby.verifier`

`sdks/python/src/allowedby/verifier.py`

AllowedBy demo verifier: ABY-2 §5, one profile, offline on the request path.

Node statements, status lists, trust programs, vouches, checkpoints and the keys of organisations that sign mandates are fetched by a background thread, never while handling a request (OAID-5 §3, CONF-1): with an empty cache a request is rejected (`untrusted_node`). The replay set, single-use consumption and counters live in a store (MemoryStore, or SqliteStore shared by every instance and process, ABY-2 §3.3).

### `clip`

```python
clip(s, n=80)
```

An attacker-supplied value, safe to put in a message: printable and bounded.

### `Reject`

```python
class Reject(code, why="", route=None, actor_sub=None, **extra)
```

### `Context`

```python
class Context(agent: str, operator: "str | None", human_id: "str | None", level: int, capabilities: "list[str]", gid: "str | None" = None, rev: "int | None" = None, jti: "str | None" = None, display: "dict[str, Any] | None" = None, acting_for: "dict[str, Any] | None" = None, tenant: "str | None" = None, disclosure_hash: "str | None" = None, route: "dict[str, Any] | None" = None, chain: "list[tuple[str, int | None]] | None" = None, human_iss: "str | None" = None, proof_jti: "str | None" = None, run: "str | None" = None, call: "int | str | None" = None, params: "dict[str, str] | None" = None, linked_account: "str | None" = None) -> None
```

What a service learns from an accepted request (ORG-1 §4.1), with the audit fields of ABY-2 §5 step 10.

Read-only (sdks/CONTRACT.md §2.7): setting a field raises AttributeError, and the dicts and lists are its own copies. The one exception is `charged`, the tenant budget the SDK charged for this request, which it clears again on a refund.

| Method |  |
|---|---|
| `as_dict() -> "dict[str, Any]"` | The context as a plain dict (for logs or templates: it holds no secret, but `human_id` is personal data under the GDPR, a pseudonym). |

### `match_route`

```python
match_route(routes: "list[dict[str, Any]]", method: str, path: str) -> "tuple[dict[str, Any] | None, dict[str, str] | None]"
```

The first route of the map that matches (ABY-3 §4.1). refuse_shadowed() keeps the order unambiguous.

### `refuse_shadowed`

```python
refuse_shadowed(routes)
```

The first match decides, so of two routes that overlap the first must be the more specific one: any other would be checked in its place, at its level, while a framework may dispatch the other. Raises ValueError.

### `top_class`

```python
top_class(r)
```

The most serious class a route can have (a payment route classed by amount: its last threshold).

### `resolve_class`

```python
resolve_class(route, body)
```

ABY-3 §4, §4.1: a route classed by amount, [{up_to, class}, ..., {class}], takes its class from the request before anything that depends on the class. No readable amount: the last, most serious class.

### `effective_route`

```python
effective_route(route, params, tenants)
```

ORG-1 §3.1 `overridable`, §3.3: a tenant can only tighten the provider's route (level, authn, qes, authority, mandate, account linking, shorter lifetime, lower amount ceiling, an operator allowlist). `members_only`: every route of the tenant needs a mandate from its organisation.

### `decoded`

```python
decoded(params)
```

Path parameters as the application knows them (tenant and account ids). Routes match, and resources are built, on the encoded segments: a decoded "/" or ":" must never add a level to a scope.

### `resource_of`

```python
resource_of(route, params)
```

### `scope_ok`

```python
scope_ok(pattern, resource)
```

### `satisfies`

```python
satisfies(cap, route, body, resource, gid, counters=None, now=None)
```

ABY-3 §3 matching against the actual request. -> the counter charges [(key, increment, max, keep_until)] when the capability matches, else None. `count` and cumulative `amount` are kept under the root `gid`; the store checks and applies the charges atomically (keep_until None: until the grant expires). `counters` is unused.

### `attenuates`

```python
attenuates(child, parent)
```

ABY-3 §3: a child capability is equal to or narrower than its parent (ABY-1 §4).

### `MemoryStore`

```python
class MemoryStore(max_keys=200000)
```

Replay set, single-use consumption and counters for one process (ABY-2 §3.3, ABY-1 §7, ABY-3 §3). Entries live until their own deadline: 300 s for proofs, the grant's `exp` or the period's end otherwise.

| Method |  |
|---|---|
| `key(k)` |  |
| `add(key, until, now)` | Add `key` unless present: False when it already was (a replay, a second use). |
| `get(key, now)` |  |
| `charge(charges, now)` | All or nothing: add every increment when every total stays within its max. -> bool. |
| `put_doc(key, version, doc, now)` | Store `doc` (a str) at `key` with `version` when it is above the stored one: atomic. -> stored. |
| `get_doc(key, now)` | -> (version, doc), or None when nothing is stored at `key`. |

### `SqliteStore`

```python
class SqliteStore(path)
```

The same store in one SQLite file, shared by every instance and process on a machine (or a network file system that locks): each operation is one IMMEDIATE transaction, so check-and-set is atomic.

| Method |  |
|---|---|
| `add(key, until, now)` |  |
| `get(key, now)` |  |
| `charge(charges, now)` |  |
| `put_doc(key, version, doc, now)` |  |
| `get_doc(key, now)` |  |

### `TrustList`

```python
class TrustList(jws, key)
```

OAID-5 §2: a signed trust list (`oaid-trust+jwt`) instead of trust on first use. `key` is the service's own public key that signed it (configuration integrity). Raises ValueError.

| Method |  |
|---|---|
| `load(path, key)` |  |
| `sign(key, payload)` |  |

### `Verifier`

```python
class Verifier(public_origin, routes, trusted_nodes, service_kids, dev_webauthn_origins=None, refresh_seconds=10, clock=None, tenants=None, orgs=(), store=None, trust_list=None, templates=None, service_keys=None, nonce_key=None, rfc9421=False, rate=None, linked=None, qes_trusted_list=None, background_refresh=True)
```

trusted_nodes: {node origin: max_level}, each node's `node` key pinned on first fetch (TOFU, the development default); trust_list: a TrustList (OAID-5), which then replaces trusted_nodes. tenants: {tenant: {"org": origin, "routes": {capability: overrides}}}. orgs: origins whose mandates we accept. store: MemoryStore (default) or SqliteStore. templates: our own, for grants naming several audiences. service_keys: our public JWKs (authority policies). nonce_key: bytes, to require AllowedBy-Nonce on irreversible routes. rfc9421: accept the Web Bot Auth profile. rate: {"actor": (n, s), "operator": (n, s)}. linked(iss, human_id, route, params) -> the linked account (a non-empty str), or None: the account linking of ABY-3 §6. Any other answer, True included (a hook written for the former bool contract), is no link. qes_trusted_list: the EU trusted-list snapshot (allowedby.qes.TrustedList) qes routes verify against. background_refresh: False for tests that call refresh() themselves (no thread, no fetch of their own). With it, the first refresh is done before the constructor returns (at most STARTUP_WAIT seconds), so a service that starts cold (a new instance, a service that scales to zero) holds node keys and status lists before its first request: nothing is fetched at request time (ARCH-1 §4, SDK contract §2 item 4).

| Method |  |
|---|---|
| `refresh()` | Fetch node statements (TOFU or trust list), status lists and mandate issuers' keys, then run the refresh hooks (the SDK's shared authority policies). Background only. |
| `any_node()` |  |
| `node_key(kid, role)` |  |
| `policy_payload(org, jws, dated=True)` | An authority policy (ABY-1 §5) for `org` signed by one of our keys, with integer iat and exp when `dated`. -> its payload. Raises ValueError. |
| `set_policy(org, jws, previous=None)` | Hold an authority policy (ABY-1 §5) for `org` (our origin, or &lt;origin>/tenants/&lt;tenant>): signed by one of our keys. Raises ValueError. (One without a valid exp is held, and never in force: _authority checks it.) previous: the policy a renewal replaced (the SDK takes it from the stored state), acceptable until its own exp when ours, for `org`, with the same rules and groups; else none. One previous policy per scope at most. |
| `drop_policy(org)` | No authority policy of its own for `org` any more: the current one and a previous one go together. |
| `new_nonce()` | ABY-2 §3.2: a service nonce, stateless (time and MAC), valid 300 s on every instance sharing nonce_key (the SDK derives it from the key_file's signing key). |
| `authority_budget_refusal(route, params, body)` | ORG-1 §5.3, before a challenge: a request on an authority route whose rule budget cannot take it is refused (403 budget_exceeded), so no approver taps a passkey for an approval that cannot succeed. route: the effective route. -> the Reject, or None (no policy, no rule or no budget: the challenge decides). A store error raises status_stale. |
| `verify(req)` | ABY-2 §5 for one request. -> Context. Raises Reject. A document that is signed but malformed (no `custody`, no `operator`, a wrong type, absurd nesting) is refused like any other invalid one. |
| `refund(charged, now)` | sdks/CONTRACT.md, Refund on the SDK's own refusal: gives back exactly what step 9 charged for one request (the single-use mark, the totals, an authority budget). Raises Reject when the store does not take it: the approval then stays spent (fail closed). |

## `allowedby.agent`

`sdks/python/src/allowedby/agent.py`

AllowedBy demo runtime (the agent side): passport, proofs (or RFC 9421 signatures), challenges, long-polling, retry, rebind, renewal, and delegation to sub-agents.

Usage:

```text
  a = Agent("http://localhost:8700", tell=print)
  status, body = a.call("POST", "http://localhost:8701/t/initech/invoices/4711/approve",
                        {"total": "4200.00", "currency": "EUR"}, action="invoices:approve")
```

### `Agent`

```python
class Agent(node_origin: str, operator: str = "acme", runtime: str = "acme.example/assistant", tell: "Callable[[dict[str, Any]], None]" = print, poll_timeout: float = 300, operator_domain: "str | None" = None, operator_key: "core.Key | None" = None, http_sig: bool = False, renew: bool = True) -> None
```

operator_domain + operator_key: an operator with a verified domain (OAID-2 §6). Its approvals survive a new passport (rebind, ABY-1 §6). Without them the operator id is node-scoped and approvals end with the passport (one hour at tier 0). http_sig: sign requests to sites with RFC 9421 (Web Bot Auth profile) instead of the proof JWT (ABY-2 §3.1). renew: ask the person to renew a standing grant when a quarter of its period remains (ABY-1 §8).

| Method |  |
|---|---|
| `ensure_passport(force: bool = False, min_life: float = 120) -> str` | A passport with more than `min_life` seconds left, issued (tier 0) or renewed when needed. |
| `renew_passport()` | OAID-3 §6, tier 1 and 2: a new passport for the same key, chained to this one by `prev`; live grants then move without the operator's signature (ABY-1 §6). Tier 0 passports never renew. -> True when renewed. |
| `rebind(gid, operator_sig=True)` | ABY-1 §6: move a grant to the current passport: the operator signs the move, or (operator_sig=False) the node follows the passport's `prev` chain. -> new revision or None. |
| `delegate(sub_agent, capabilities, origin=None, exp=None, ab=None)` | Derive a narrower child grant for a sub-agent, which signs with its own key, and hand it the chain. ab: the root grant to narrow, by default our newest standing root grant for `origin`. A chain is a root and one child (ABY-1 §4: depth 1), so a child is never narrowed again: by default none is chosen, and an explicit one raises ValueError before the node is asked. -> chain or None. |
| `adopt(chain)` | A chain from the runtime that delegated to us: its leaf is from our node, for our key, and is a child of the next grant. -> None when kept, else why. A chain is a root and one child (ABY-1 §4, ABY-2 §2: depth 1), so one a verifier would refuse is never kept. |
| `node_url(url: "str \| None", kind: str) -> "str \| None"` | An approval link or poll URL from a site's challenge: only on our own node, on the node's own paths, or (an approval link) under the approval page the node names in its signed statement, which may be on another host (OAID-2 §3 `endpoints.approval_page`). -> aid, or None. Anything else is never opened or polled. Compared as text, never parsed: `/x/../a/<aid>`, white space, credentials, a query or another spelling of the host are not the node's link, whatever a URL parser makes of them. |
| `ids_ok(aid: object, code: object) -> bool` | AMH-1 §3: an approval id is 26 and a binding code 4 Crockford base32 characters (no I, L, O, U). An approval whose ids are malformed is not shown to the person. |
| `node_keys(refresh=False)` | The node's keys, from its signed statement (/.well-known/oaid), kept after the first fetch. |
| `check_grant(t, origin=None)` | A grant from the node, before we keep or use it: signed by our node, for our key (and the site). -> None when good, else why. |
| `call(method: str, url: str, body: Any = None, action: "str \| None" = None, standing: int = 7 * 86400, limits: "dict[str, Any] \| None" = None) -> "tuple[int, Any]"` | Do the request; when a human's yes is missing, get it and retry once. -> (status, json) limits: the amount the agent asks for on routes with an amount, e.g. {"max": "300.00", "currency": "EUR", "per": "month"} (ABY-3 §2). |
| `wait_for(poll_url: str, expires: Any = None, what: "tuple[str, str] \| None" = None, passport: "str \| None" = None) -> "str \| None"` | Long-poll the node: it answers the moment the human decides. A node that does not hold the request is asked no more than every 5 s, and never sooner than its Retry-After; polling stops at the approval's `expires` (ABY-2 §8, AMH-1 §5). what: (site origin, action), remembered on "not me". passport: the one that asked (default: the current one); every poll is signed for it, so the wait ends before it expires. |

## `allowedby.asgi`

`sdks/python/src/allowedby/asgi.py`

ASGI middleware (Starlette, FastAPI, Quart, any ASGI app): the SDK's endpoints, then the check on every route of the map, then your app (sdks/CONTRACT.md §2.10).

```
from allowedby.asgi import AllowedByMiddleware
app = AllowedByMiddleware(app, aby)            # any ASGI app
app.add_middleware(AllowedByMiddleware, aby=aby)  # Starlette / FastAPI
```

The accepted Context is in `scope["state"]["allowedby"]` (Starlette: `request.state.allowedby`) and in `scope["allowedby.context"]`; it is None on paths outside the route map, which reach the app untouched (their body is not read). On a route of the map the body is read once (at most `aby.max_body` bytes) and given back to the app intact.

The event loop is never blocked: the check (signatures, and for write-hard and irreversible routes a call to the node that creates the approval) runs in a worker thread. Measured on a laptop (Python 3.14, Ed25519 passport): the check takes about 0.5 ms and the thread hand-off adds about 0.3 ms; tests/test_asgi.py checks that the loop keeps running while 20 requests are checked.

### `AllowedByMiddleware`

```python
class AllowedByMiddleware(app: ASGIApp, aby: AllowedBy, *, threaded: bool = True, openapi_cors: bool = True, on_startup: Callable[[], None] | None = None, guarded: bool = False) -> None
```

Pure ASGI middleware; `threaded=False` runs the check on the loop (only for tests and benchmarks).

### `DispatchGuard`

```python
class DispatchGuard(app: ASGIApp, aby: AllowedBy, sees_params: bool = False) -> None
```

Innermost ASGI middleware, right around the router: refuses a request that a layer behind the check turned into one for a protected route (AllowedBy.may_dispatch). Installed by itself on a Starlette or FastAPI router; for another ASGI app: `AllowedByMiddleware(layer(DispatchGuard(router, aby)), aby, guarded=True)`.

## `allowedby.core`

`sdks/python/src/allowedby/core.py`

AllowedBy demo: shared primitives (JCS, JWS, keys, WebAuthn, status lists, display, HTTP).

Implements the wire formats of specs 0.2.5-draft for the demo node, service and agent. Only dependency: `cryptography`.

### `now`

```python
now() -> int
```

### `b64u`

```python
b64u(b)
```

### `b64u_dec`

```python
b64u_dec(s)
```

### `sha256`

```python
sha256(b)
```

### `jcs`

```python
jcs(v)
```

RFC 8785 JSON Canonicalization Scheme.

### `jcs_bytes`

```python
jcs_bytes(v)
```

### `ulid`

```python
ulid()
```

### `aid`

```python
aid()
```

AMH-1 §3: an approval id is 128 random bits in Crockford base32 (26 characters), not a ULID.

### `binding_code`

```python
binding_code()
```

### `rand_id`

```python
rand_id(n: int = 16) -> str
```

### `thumbprint`

```python
thumbprint(jwk)
```

### `Key`

```python
class Key(priv)
```

A signing key: Ed25519 (EdDSA) or P-256 (ES256).

| Method |  |
|---|---|
| `generate(kind="Ed25519")` |  |
| `to_json()` |  |
| `from_json(d: "dict[str, Any]") -> "Key"` |  |
| `sign(data)` |  |

### `public_key`

```python
public_key(jwk)
```

### `alg_for`

```python
alg_for(jwk)
```

### `verify_raw`

```python
verify_raw(alg, jwk, data, sig)
```

JWS signature check. Only EdDSA and ES256 exist outside human_sig (OAID-1 §3.1).

### `json_unique`

```python
json_unique(text)
```

A JSON text, refused (ValueError) when an object names a member twice: two readers could each take a different value. Absurd nesting is a ValueError too.

### `jws_sign`

```python
jws_sign(key, typ, payload, extra=None)
```

### `jws_parse`

```python
jws_parse(t)
```

-> (header, payload, signing input bytes, signature). Raises ValueError.

### `jws_payload`

```python
jws_payload(t: str) -> "dict[str, Any]"
```

### `spki_to_jwk`

```python
spki_to_jwk(spki_der)
```

### `webauthn_signature_ok`

```python
webauthn_signature_ok(jwk, auth_data, cdj, sig)
```

Signature over authenticatorData || SHA-256(clientDataJSON), WebAuthn encoding (DER for ES256).

### `check_assertion`

```python
check_assertion(a, *, challenge, origin, rp_id, jwk, typ="webauthn.get")
```

Every WebAuthn check of ABY-1 §3.3. `a` = {authenticator_data, client_data_json, signature} (base64url). Returns None when valid, else the reason. The signature is checked against `jwk`, always; only a registration (typ="webauthn.create", which carries no signature) passes jwk=REGISTRATION. No key at all is a refusal.

### `cbor_dec`

```python
cbor_dec(b, i=0, depth=0)
```

Minimal CBOR (RFC 8949) for WebAuthn attestation objects and COSE keys. -> (value, next offset).

### `cbor_enc`

```python
cbor_enc(v)
```

The encoder matching cbor_dec (tests build attestation objects with it).

### `cose_to_jwk`

```python
cose_to_jwk(c)
```

COSE_Key (RFC 9053) of a passkey -> JWK.

### `packed_attestation`

```python
packed_attestation(att_obj, cdj, roots)
```

WebAuthn attestation object (OAID-7 §4). roots: {aaguid hex: [root certificate DER]} (a local allowlist; FIDO MDS in production). -> {fmt, aaguid, cred_id, jwk, auth_data, verified}; verified only for a `packed` statement with an x5c chain to a root allowlisted for that AAGUID. Raises ValueError when malformed.

### `sd_jwt_claims`

```python
sd_jwt_claims(token, key_for)
```

Read an SD-JWT VC (`vc+sd-jwt`, OAID-7 §7): the issuer JWT, then one disclosure per `~`. key_for(header, payload) -> the issuer's JWK. -> the payload with every disclosed claim in place. Raises ValueError.

### `grant_core`

```python
grant_core(g)
```

ABY-1 §3.1: what the human signs.

### `request_digest`

```python
request_digest(htm, htu, query, body)
```

### `make_proof`

```python
make_proof(key, htm, htu, allowed_by=None, body=None, extra=None)
```

ABY-2 §3 proof JWT. `body` is bytes as transmitted, or None.

### `pairwise`

```python
pairwise(home_secret, internal_id, audience)
```

OAID-1 §2.5.

### `core_hash`

```python
core_hash(g)
```

base64url SHA-256(JCS(grant core)): the WebAuthn challenge of one grant (ABY-1 §3.2).

### `batch_challenge`

```python
batch_challenge(hashes)
```

ABY-1 §3.2 / AMH-1 §11: SHA-256(JCS({"batch": [h1, ..., hn]})), each hi a core hash string.

### `norm_path`

```python
norm_path(p: "str | None") -> str
```

RFC 3986 §6.2.2 for a path: percent-encoding normalised (unreserved decoded, hex upper), dot segments gone.

### `htu`

```python
htu(url)
```

ABY-2 §3 `htu`: the URL without query and fragment, normalised per RFC 3986 §6.2.2 (lowercase scheme and host, default port removed, percent-encoding and dot segments normalised).

### `json_leaves`

```python
json_leaves(doc, prefix="")
```

The JSON Pointers of every leaf member of an object (RFC 6901 escaping): what `fields` constrains.

### `zone`

```python
zone(tz)
```

An IANA zone for `amount.tz` and `window.tz` (ABY-3 §2), or None when this machine does not know it: callers then fail closed. Windows ships no zone database (`pip install tzdata`); UTC always works.

### `in_window`

```python
in_window(w, t)
```

ABY-3 §2 `window`: time t on the verifier's clock is in [from, to) in the window's zone (a window may wrap midnight, e.g. 22:00-06:00). An unknown zone never matches.

### `content_digest`

```python
content_digest(body)
```

RFC 9530 Content-Digest: sha-256 of the content as transmitted.

### `sig_base`

```python
sig_base(components, values, params)
```

RFC 9421 §2.5 signature base: one line per covered component, then @signature-params.

### `parse_sig_input`

```python
parse_sig_input(s)
```

Signature-Input `sig1=(...);k=v...` -> (components, params dict, raw params). Raises ValueError.

### `sign_9421`

```python
sign_9421(key, method, target_uri, allowed_by, agent_origin, body=None, ttl=60, service_nonce=None)
```

ABY-2 §3.1, the Web Bot Auth profile: the headers that replace AllowedBy-Proof. `target_uri` includes the query; `agent_origin` is the issuing node. service_nonce: the service's AllowedBy-Nonce (§3.2), sent in that header and covered by the signature (the `nonce` parameter is the signature's own replay nonce).

### `status_lst`

```python
status_lst(bits)
```

### `status_bit`

```python
status_bit(lst, idx)
```

### `constraints_ok`

```python
constraints_ok(c)
```

ABY-3 §2 grammar for values that end up in the signed text.

### `render_display`

```python
render_display(caps, lang, templates)
```

AMH-1 §4 / ABY-3 §5: the only source of the text the human signs. Raises ValueError.

### `enc_key_generate`

```python
enc_key_generate()
```

P-256 key for ECDH-ES+A256KW (a service's `disclosure_key`).

### `enc_jwk`

```python
enc_jwk(priv, kid="d1")
```

### `jwe_encrypt`

```python
jwe_encrypt(jwk, plaintext, cty=None)
```

RFC 7516 compact JWE, alg ECDH-ES+A256KW, enc A256GCM (OAID-7 §7).

### `jwe_decrypt`

```python
jwe_decrypt(priv, token)
```

### `dec`

```python
dec(v)
```

An amount as text: at most 15 digits before the point and 6 after (a megabyte of zeros is not an amount).

### `money`

```python
money(d)
```

Two decimals, in decimal arithmetic (a float would round 999999999999999.99 up).

### `period_id`

```python
period_id(per, t, tz=None)
```

Calendar period holding time t in `tz` (IANA, default UTC): day, ISO week from Monday, or month (ABY-3 §2). Raises ValueError for a zone this machine does not know.

### `period_bounds`

```python
period_bounds(per, t, tz=None)
```

(start, end) of that period, in epoch seconds; local midnights, so a DST day lasts 23 or 25 hours.

### `periods_overlapping`

```python
periods_overlapping(per, start, end, tz=None)
```

### `exposure`

```python
exposure(grant, currency, window)
```

ORG-1 §5.1: the most a grant could commit in `currency` inside window (start, end). None = unbounded. grant = {capabilities, nbf, exp, single_use}.

### `budget_check`

```python
budget_check(budget, live, new, now)
```

Reserve `new` against `budget` {max, currency, per} given live grants. -> dict with used, after, ok.

### `Request`

```python
class Request(method, target, headers, body, origin)
```

| Method |  |
|---|---|
| `client()` | The caller's IP, for rate limits. Behind Cloud Run's front end, the last X-Forwarded-For entry is the one it added; earlier entries come from the client and can be forged. |
| `header(name)` |  |
| `arg(name, default=None)` |  |
| `json()` |  |

### `RateLimit`

```python
class RateLimit(n, per, keys=10000)
```

At most `n` calls per `per` seconds per key (a sliding window: a call at t sees those at x with t - x &lt; per), with a bounded number of keys. `now`: the caller's clock (a verifier passes its own), else time.monotonic().

| Method |  |
|---|---|
| `ok(key, now=None)` | Room for one more call: counts it and answers True; full: answers False, and the call does not count. |
| `full(key, now)` |  |
| `add(key, now)` |  |

### `Unavailable`

```python
class Unavailable
```

What the node cannot do right now (no free status index, OAID-2 §7): a 503, never a 500.

### `problem`

```python
problem(err: str, status: int, title: "str | None" = None, headers: "dict[str, str] | None" = None, **extra: Any) -> "tuple[int, dict[str, Any], dict[str, str]]"
```

### `App`

```python
class App(origin)
```

Tiny router on the standard library server.

| Method |  |
|---|---|
| `route(method, pattern, locked=True)` | locked=False for handlers that call another server which may call back (avoids deadlocks). |
| `handle(req)` |  |
| `serve(port)` | Listen on 127.0.0.1 and on ::1, so `localhost` connects at once whichever address a client tries first (Windows waits about 2 s on a refused ::1 before falling back to IPv4). |

### `serve_hosts`

```python
serve_hosts(port, apps)
```

Serve several apps on one port, chosen by the Host header: {"globex.localhost": app, ...}. An app is an App, or a WsgiApp. Browsers and this module's http() resolve \*.localhost to the loopback.

### `WsgiApp`

```python
class WsgiApp(origin, wsgi)
```

Lets serve_hosts() run a WSGI app (Flask, Django, the SDK's wrapper) next to App instances.

| Method |  |
|---|---|
| `handle(req)` |  |

### `is_local`

```python
is_local(hostname)
```

localhost and \*.localhost are the loopback (RFC 6761): browsers do this, Windows' resolver does not.

### `EgressRefused`

```python
class EgressRefused
```

A URL the node must not call: callers handle it like any unreachable host.

### `http`

```python
http(method: str, url: str, body: Any = None, headers: "dict[str, str] | None" = None, timeout: float = 10) -> "tuple[int, dict[str, str], bytes]"
```

-> (status, headers dict lower-case, body bytes). Keeps one connection per host per thread.

### `get_json`

```python
get_json(url)
```

### `parse_www_authenticate`

```python
parse_www_authenticate(h)
```

## `allowedby.django`

`sdks/python/src/allowedby/django.py`

Django middleware: the SDK's endpoints, then the check on every route of the map, then your views.

settings.py::

```
from allowedby import route
```

```
MIDDLEWARE = [..., "allowedby.django.AllowedByMiddleware"]
ALLOWEDBY = {
    "origin": "https://notes.example", "node": "https://node.example.org",
    "org": {"legal_name": "Notes Ltd", "country": "FR"},
    "routes": [route("GET", "/notes", "notes:read", level=1, resource="note:*")],
    "templates": {"notes:read": "Read your notes"},
    "key_file": "/run/secrets/allowedby-keys.json",
}
```

`ALLOWEDBY` holds the arguments of `allowedby.AllowedBy` (a route may also be a dict of `route()` arguments), or a dotted path to an `AllowedBy` instance ("myproject.agents.aby"). In a view, `request.allowedby` is the accepted Context, None on paths outside the route map.

A request the SDK accepted is exempt from Django's CSRF check: it carries no ambient credential, every request is signed by the agent's key for this exact method, URL and body (ABY-2 §3). Requests outside the map keep it.

### `build`

```python
build(config: Any) -> AllowedBy
```

An AllowedBy from a settings value: an instance, a dotted path to one, or a dict of its arguments.

### `from_settings`

```python
from_settings() -> AllowedBy
```

The project's AllowedBy, built once from settings.ALLOWEDBY.

### `AllowedByMiddleware`

```python
class AllowedByMiddleware(get_response: Callable[[HttpRequest], HttpResponse]) -> None
```

Django middleware (sync; Django adapts it under ASGI).

| Method |  |
|---|---|
| `process_view(request: HttpRequest, view: Any, args: Any, kwargs: Any) -> HttpResponse \| None` | Right before the view, after every middleware's request phase: see AllowedBy.may_dispatch. |

## `allowedby.epassport`

`sdks/python/src/allowedby/epassport.py`

AllowedBy: server-side verification of eMRTD (ePassport / eID card) chip reads (OAID-7 §5, 0.2.6-draft).

A phone reads the chip over NFC (after BAC/PACE) and uploads the raw LDS files; the home node checks them here: \* DG1 MRZ parsing + check digits ............................ Doc 9303-3 §4.9, 9303-4 (TD3), 9303-5 (TD1), 9303-6 (TD2) \* Passive Authentication (EF.SOD, CMS SignedData, DSC->CSCA) . Doc 9303-11 §5.1, 9303-10 §4.6.2, 9303-12, RFC 5652 \* CSCA Master List loading .................................. Doc 9303-12 §8 (CscaMasterList), RFC 5652 \* Active Authentication (DG15, ECDSA plain / ISO 9796-2 DS1) .. Doc 9303-11 §6.1, BSI TR-03111, ISO/IEC 9796-2 \* Explicit EC domain parameters (brainpool, NIST) ............. RFC 3279 §2.3.5, RFC 5639, BSI TR-03110 / TR-03111 Chip Authentication (DG14 + live key agreement) needs the secure-messaging session on the phone and is out of scope here: `chip_auth: "none"` means clone detection is NOT proven (OAID-7 caps such evidence at L2). Only dependency: `cryptography`. Every failure raises ValueError with a short reason (fail closed).

### `icao_to_alpha2`

```python
icao_to_alpha2(code, extra=None)
```

ICAO 9303-3 state code (fillers stripped) -> ISO alpha-2; `extra` lets the operator add mappings.

### `TLV`

```python
class TLV(tag, t0, raw, val, depth, der)
```

One decoded TLV. `der=True` enforces minimal length encodings (CMS/X.509); LDS files use BER-TLV (9303-10 §4) where only definite lengths are allowed but non-minimal ones are tolerated.

| Method |  |
|---|---|
| `constructed()` |  |
| `kids(n=None, lo=None, hi=None)` |  |

### `der_parse`

```python
der_parse(b, der=True, tag=None)
```

Exactly one TLV, no trailing bytes; optional expected tag.

### `asn1_int`

```python
asn1_int(node)
```

### `asn1_oid`

```python
asn1_oid(node)
```

### `asn1_octets`

```python
asn1_octets(node)
```

### `tlv`

```python
tlv(tag, content)
```

Encode one TLV (tag as int, e.g. 0x5F1F); DER minimal length.

### `der_seq`

```python
der_seq(*p)
```

### `der_set`

```python
der_set(*p)
```

### `der_int`

```python
der_int(v)
```

### `der_oct`

```python
der_oct(b)
```

### `der_null`

```python
der_null()
```

### `der_oid`

```python
der_oid(s)
```

### `alg_id`

```python
alg_id(oid, params=None)
```

### `load_spki`

```python
load_spki(spki_der)
```

SubjectPublicKeyInfo DER -> public key. Explicit prime-field EC parameters matching a curve in EC_CURVES give a key on that named curve; unknown explicit parameters, other field types and unsupported keys raise ValueError.

### `cert_public_key`

```python
cert_public_key(cert)
```

The certificate's subject public key, including keys with explicit EC parameters (see load_spki).

### `check_digit`

```python
check_digit(s)
```

Doc 9303-3 §4.9: weights 7,3,1 repeating; A-Z = 10..35; '&lt;' = 0.

### `parse_mrz_dg1`

```python
parse_mrz_dg1(dg1_bytes, now=None)
```

DG1 (tag 0x61 { 0x5F1F MRZ }, Doc 9303-10 §4.7.1) -> MRZ fields; TD1 3x30, TD2 2x36, TD3 2x44.

### `parse_lds_so`

```python
parse_lds_so(econtent)
```

LDSSecurityObject (Doc 9303-10 §4.6.2.3): {version 0|1, hashAlgorithm, dataGroupHashValues, ldsVersionInfo?}.

### `verify_sod`

```python
verify_sod(sod_bytes, data_groups, csca_ders, now=None, crl_check=None, country_map=None)
```

Passive Authentication (Doc 9303-11 §5.1). EF.SOD = 0x77 { ContentInfo(SignedData(LDSSecurityObject)) }. Checks: CMS signature by the DSC in SignedData.certificates; DSC directly issued by a CSCA in `csca_ders`, both valid at `now`; optional `crl_check(dsc, csca) -> bool` (False = revoked; no revocation check if None); every supplied DG hash present and equal in the LDS SO; DG1 supplied and hashed; DSC/CSCA country == MRZ issuing state. Returns {dsc_subject, csca_subject, issuing_state (alpha-2), hash_alg, dg_numbers}.

### `load_master_list`

```python
load_master_list(ml_bytes, signer_anchor_ders, now=None, rejected=None)
```

ICAO CSCA Master List (Doc 9303-12 §8): SignedData(id-icao-cscaMasterList, CscaMasterList {version 0, certList SET OF Certificate}), signed by a Master List Signer (EKU id-icao-cscaMasterListSigningKey) directly issued by one of the operator-pinned anchors (e.g. the BSI CSCA). Returns the CSCA certificates as DER (deduplicated). Every CSCA must parse and carry a usable public key (named curve, explicit parameters of a known curve, or RSA). A bad entry raises ValueError, unless `rejected` is a list: then the entry is left out (not trusted) and (reason, der) is appended to it, so one exotic certificate does not block the whole list.

### `verify_active_auth`

```python
verify_active_auth(dg15_bytes, challenge8, response_bytes, dg14_bytes=None)
```

Active Authentication (Doc 9303-11 §6.1). DG15 = 0x6F { SubjectPublicKeyInfo }. Returns True/False for the signature; raises ValueError on malformed input. ECDSA: plain r||s (BSI TR-03111 §5.2.1) over the challenge, hash from DG14 ActiveAuthenticationInfo when given, else SHA-256. RSA: ISO/IEC 9796-2 scheme 1 (see _iso9796_2_ds1). SHA-1 is accepted here only: AA signs a fresh verifier nonce, so collision resistance is not relied upon. The caller MUST generate `challenge8` itself (single-use) and check DG15/DG14 via Passive Authentication.

### `verify_chip`

```python
verify_chip(dgs, sod, aa=None, challenge=None, csca_ders=None, now=None, crl_check=None, country_map=None)
```

Full server-side check of an uploaded chip read -> OAID-7 §5 identity evidence. Passive Authentication is mandatory; Active Authentication runs when `aa` (the chip's response to the node-issued `challenge`) is given and then DG15 must be present and covered by the SOD. chip_auth "none" = clone detection not proven (cap L2). Refuses expired documents (expiry date is the last valid day).

## `allowedby.fastapi`

`sdks/python/src/allowedby/fastapi.py`

FastAPI integration: the ASGI middleware, a dependency that hands the Context to a handler, and FastAPI's own OpenAPI document enriched with what each operation needs (`security` and `x-allowedby`, ABY-3 §5.1).

```
from fastapi import Depends, FastAPI
from allowedby import Context
from allowedby.fastapi import allowedby_context, install
```

```
app = FastAPI()
install(app, aby)                         # once, before the app starts
```

```
@app.get("/notes")
def notes(ctx: Context = Depends(allowedby_context)):
    return {"notes": NOTES.get(ctx.human_id, [])}
```

`install` serves FastAPI's /openapi.json (the SDK's own is turned off: one document, with your models), adds the AllowedBy security schemes and, on every operation of the route map, its capability and level. At startup it checks that every route of the map has a FastAPI operation, so a typo in a path fails at start, not in production.

### `optional_allowedby_context`

```python
optional_allowedby_context(request: Request) -> Context | None
```

The Context of an accepted request, or None on a path outside the route map.

### `allowedby_context`

```python
allowedby_context(request: Request) -> Context
```

The Context of an accepted request. The middleware has already refused anything else, so a missing Context means the route is not in the map: refused (403 capability_denied), never served without a check.

### `enrich_openapi`

```python
enrich_openapi(app: FastAPI, aby: AllowedBy) -> dict[str, Any]
```

FastAPI's OpenAPI document with the AllowedBy members on each operation of the route map.

### `install`

```python
install(app: FastAPI, aby: AllowedBy, *, threaded: bool = True) -> None
```

Add the middleware, FastAPI's enriched OpenAPI at /openapi.json, and the start-up check of the route map.

### `check_routes`

```python
check_routes(app: FastAPI, aby: AllowedBy) -> None
```

Every route of the map has a FastAPI operation with the same method and path. Raises RuntimeError naming the missing ones (run at start-up by `install`).

## `allowedby.flask`

`sdks/python/src/allowedby/flask.py`

Flask extension: `AllowedBy(app)` wraps the app's WSGI pipeline with the SDK; handlers read `g.allowedby`.

```
from flask import Flask, g
from allowedby import route
from allowedby.flask import AllowedBy
```

```
app = Flask(__name__)
app.config["ALLOWEDBY"] = {
    "origin": "https://notes.example", "node": "https://node.example.org",
    "org": {"legal_name": "Notes Ltd", "country": "FR"},
    "routes": [route("GET", "/notes", "notes:read", level=1, resource="note:*")],
    "templates": {"notes:read": "Read your notes"},
}
AllowedBy(app)                     # or AllowedBy(app, aby=an_allowedby_instance), or ext.init_app(app)
```

```
@app.get("/notes")
def notes():
    return {"notes": NOTES.get(g.allowedby.human_id, [])}
```

`g.allowedby` is the accepted Context, None on paths outside the route map. `current_app.extensions["allowedby"]` is the service's `allowedby.AllowedBy`.

### `AllowedBy`

```python
class AllowedBy(app: Flask | None = None, aby: sdk.AllowedBy | None = None) -> None
```

The Flask extension. `aby`: an `allowedby.AllowedBy`; without it, app.config["ALLOWEDBY"] holds its arguments (a route may also be a dict of `route()` arguments).

| Method |  |
|---|---|
| `init_app(app: Flask) -> None` |  |

## `allowedby.idsources`

`sdks/python/src/allowedby/idsources.py`

Identity sources of OAID-7 §5: one registry of providers and the ceilings of §5.1, applied by the node.

A provider starts a verification (a redirect, a wallet presentation request or a chip challenge) and finishes it with a normalised result `{claims, source}`. The level is never taken from the provider: `decide` derives it from the source type and what was verified (notification, wallet certification, chip authentication, liveness rating), then the node checks the passkey (`hardware` for level 3). Fails closed: anything unproven lowers the level.

Bought and built side by side (OAID-7 §5.7). A provider is `primary` (offered to people, sets the level) or `pilot` (an in-house source offered only to people already verified by a primary, compared with their record, never sets the level). A primary may carry a `shadow`: an in-house verifier that re-checks the same evidence the provider returned (for example the chip data groups a bought chip-and-liveness service read) and never sets the level either. Every comparison is kept in a cross-check log of field names and verdicts only, never attribute values; `gate` says when an in-house verifier has earned promotion to primary.

### `VerificationFailed`

```python
class VerificationFailed(code, why)
```

The source could not support any level; `code` is a short machine reason.

### `decide`

```python
decide(source)
```

OAID-7 §5.1 ceilings -> (level, level_source) where level_source = {type, loa[, profile]} for `human.reg`. `source` is what the node itself verified: {type, notified_loa, loa, wallet_certified, chip_auth, liveness, country, framework}. level 0 means the evidence supports no level.

### `l3_needs`

```python
l3_needs(level_source, authn, synced)
```

Level 3 also needs a hardware, non-synced passkey (OAID-7 §2): -> None or why not.

### `record`

```python
record(result, provider_id, evidence)
```

The identity verification record kept by the home node outside the log (OAID-7 §5.2, §8): attributes only as the source gave them, each tagged with that source, plus a digest of the evidence.

### `norm`

```python
norm(v)
```

Compare names and dates as people write them: accents, case, hyphens, apostrophes and spacing do not count (an MRZ has no accents and turns hyphens into spaces).

### `compare`

```python
compare(a, b, fields)
```

-> names of `fields` both sides have and that differ. A field one side lacks is not a difference.

### `Sources`

```python
class Sources(providers, roles=None, shadows=None, on_disagreement="log", certified=None)
```

The node's `level_providers` (OAID-2): provider id `<type>:<name>` -> adapter. Adapters implement `start(level, ctx) -> (public, private)` and `finish(private, body) -> {claims, source}`.

roles: {provider id: "primary" | "pilot"} (default primary). shadows: {primary id: (verifier id, check)} where `check(result) -> {claims, source}` re-verifies the evidence in `result["raw"]`. on_disagreement: "log" keeps the provider's result and records the finding; "refuse" fails the verification. certified: {verifier id: label} for in-house verifiers that passed their certification (needed by `gate`).

| Method |  |
|---|---|
| `primaries()` |  |
| `pilots()` |  |
| `listed()` | `level_providers` for the node statement: the primaries for level 2, those whose type can reach 3. Pilots are not listed: they never set a level. |
| `start(provider_id, level, hid, extra)` |  |
| `finish(vid, hid, body)` | -> (pending entry, normalised result). One use per verification, bound to the human who started it. |
| `pilot(p, res, record_attrs, record_provider)` | A pilot source run for someone a primary already verified: compare with their record, change nothing. |
| `stats()` | Per (kind, primary, verifier): runs, agreements, security findings, and which fields differed. |
| `gate(verifier, min_runs=500, min_agreement=0.995)` | May the in-house `verifier` become primary? Enough runs against a bought provider, agreement at least `min_agreement`, no security finding left, and a certification on record. -> {ready, why[], ...}. |

### `EidBroker`

```python
class EidBroker(broker)
```

OAID-7 §5.5: notified eIDs through an OIDC broker (allowedby.oidc_broker.Broker).

| Method |  |
|---|---|
| `start(level, ctx)` |  |
| `finish(pending, body)` |  |

### `WalletPresentation`

```python
class WalletPresentation(verifier, kind)
```

OAID-7 §5.4: EUDI Wallet PID (`wallet`) or an ISO 18013-5 mDL (`mdl`), verified in house over OpenID4VP (allowedby.oid4vp.Verifier).

| Method |  |
|---|---|
| `start(level, ctx)` |  |
| `finish(pending, body)` |  |

### `Epassport`

```python
class Epassport(epassport_mod, csca, liveness)
```

OAID-7 §5.6: an eMRTD chip read by the human's phone. `csca`: CSCA DERs; `liveness(face, dg2) -> "high" | "substantial" | None` is the liveness and face comparison component whose rating sets the ceiling.

| Method |  |
|---|---|
| `start(level, ctx)` |  |
| `finish(pending, body)` |  |
| `shadow(result)` | Shadow check (§5.7) of chip data a bought provider read: passive authentication, the MRZ, and active authentication when the provider passes its challenge and the chip's answer. Liveness stays the provider's. |

### `Vendor`

```python
class Vendor(client, name, kind="epassport", liveness_rating="substantial", framework="etsi-119-461")
```

OAID-7 §5.7: a bought identity verification service (document and selfie, or chip and liveness) reached by a session API. The person runs the provider's flow; the node then fetches the result server to server with its own credentials, never from the page. `client` implements `create_session(kind, ref) -> {id, url}` and `result(id) -> dict` (see allowedby.idv_vendor). `liveness_rating` is what the provider's liveness component is certified at under contract (BSI TR-03147 or a CAB assessment): a per-session label from the provider is not used.

| Method |  |
|---|---|
| `start(level, ctx)` |  |
| `finish(pending, body)` |  |

### `plain_reason`

```python
plain_reason(v)
```

### `load_json`

```python
load_json(path)
```

## `allowedby.idv_vendor`

`sdks/python/src/allowedby/idv_vendor.py`

Clients for bought identity verification services (OAID-7 §5.7), normalised for `idsources.Vendor`:

```
create_session(kind, ref) -> {"id", "url"}
result(id) -> {"session", "status": "approved" | "rejected" | "pending", "reason",
               "person": {"given_name", "family_name", "birth_date", "nationality"},
               "document": {"type", "country" (alpha-2), "expired",
                            "chip": {"read", "passive_auth", "active_auth", "chip_auth"}},
               "liveness": {"passed", "face_match"}, "raw": None | {...}}
```

SignicatAssure: Signicat's Assure API with the ReadID provider (NFC chip read) and the iProov add-on (liveness and face comparison against the chip portrait). Wire format from developer.signicat.com (assure-api quick start, signicat-readid integration guide and service details) and the Assure OpenAPI document, read 2026-11-19:

- token: POST https://api.signicat.com/auth/open/connect/token, HTTP Basic client_id:client_secret,
  grant_type=client_credentials&scope=signicat-api (expires_in 600);
- POST /assure/dossiers {"externalReference"} -> dossierId; POST /assure/dossiers/{id}/processes
  {"provider": "readid", "processType": "ready"} -> processId, universalLink (mobile), base64QRCode (desktop);
  the person returns through `&callback=` appended to the universal link;
- GET /assure/dossiers/{d}/processes/{p}: status pending | processing | accepted | rejected | inconclusive |
  canceled | failed; identity in providerSpecific.consolidatedIdentityData (finalResult only when accepted), country
  codes ICAO alpha-3; chipVerification SUCCEEDED | FAILED (passive authentication), chipCloneDetection SUCCEEDED |
  FAILED | NOT_AVAILABLE (active or chip authentication: the API does not say which); iproovSession.passed covers
  liveness and the face comparison together (no separate face-match result).

Not available by default: the raw chip data. Without it the node's shadow chip verifier cannot re-check the read (the cross-check log says "not re-checked"); Signicat's "get raw result" endpoint is enabled on request.

### `SignicatAssure`

```python
class SignicatAssure(config, transport=default_transport, now=time.time)
```

config: client_id, client_secret, callback (the URL the person returns to, appended to the universal link), api (default https://api.signicat.com), assurance_types (iProov assurance types accepted; default GENUINE_PRESENCE only).

| Method |  |
|---|---|
| `create_session(kind, ref)` |  |
| `result(sid)` |  |
| `normalise(sid, r, assurance_types=("GENUINE_PRESENCE",), now=None)` |  |

## `allowedby.langchain`

`sdks/python/src/allowedby/langchain.py`

LangChain integration: `AllowedByRequestsTool`, a tool that makes HTTP requests as the person's agent.

```
from allowedby import Agent
from allowedby.langchain import AllowedByDiscoverTool, AllowedByRequestsTool
from allowedby.tools import Wallet
```

```
wallet = Wallet(Agent("https://node.example.org"), tell=lambda m: print(m.get("text", "")))
tools = [AllowedByRequestsTool(wallet=wallet), AllowedByDiscoverTool(wallet=wallet)]
```

The tool pauses while the person approves (up to `wait_seconds`); `tell` receives the approval link and the binding code to show in the conversation. If the person takes longer, the tool returns the sentence to show them and a `job` id; calling the tool again with that `job` keeps waiting.

### `RequestArgs`

```python
class RequestArgs
```

### `DiscoverArgs`

```python
class DiscoverArgs
```

### `AllowedByRequestsTool`

```python
class AllowedByRequestsTool
```

An HTTP request to an AllowedBy site, signed as the person's agent, with their approval when needed.

### `AllowedByDiscoverTool`

```python
class AllowedByDiscoverTool
```

What an AllowedBy site offers agents (its operations and the approval each needs).

## `allowedby.mcp`

`sdks/python/src/allowedby/mcp.py`

The AllowedBy agent as an MCP server (Model Context Protocol, over stdio): an AI assistant such as Claude can use any AllowedBy site from its URL, with the person's approval for each thing it does.

```
allowedby-mcp --node https://node.example.org                       # installed with the package
claude mcp add allowedby -- allowedby-mcp --node https://node.example.org
python -m allowedby.mcp --node http://localhost --no-browser
```

The assistant gets four tools (allowedby.tools.TOOLS): allowedby_discover(url), allowedby_call(method, url, body, spend_limit), allowedby_wait(job) and allowedby_approvals(). When a call needs the person's yes, the approval page opens in their browser (unless --no-browser) and the call waits for the passkey tap; if the tap takes longer, the tool returns the sentence to tell the person, verbatim, with the link and the code, and `allowedby_wait` resumes.

Standard library only: JSON-RPC 2.0, one message per line on stdin and stdout. Logs go to stderr.

### `wallet_for`

```python
wallet_for(node: str, *, operator: str = "agent", runtime: str = "allowedby/mcp", operator_domain: str | None = None, operator_key: core.Key | None = None, state: str | None = None, open_browser: bool = True, log: Callable[[str], None] | None = None, allowed_origins: Sequence[str] | None = None) -> Wallet
```

A Wallet for an MCP session: approval pages open in the person's browser (only pages of the agent's own node, AMH-1 §5), and the result says so.

### `Server`

```python
class Server(wallet: Wallet, name: str = "allowedby-agent", version: str = "0.1.0") -> None
```

MCP over stdio for a Wallet: initialize, ping, tools/list, tools/call.

| Method |  |
|---|---|
| `send(msg: dict[str, Any]) -> None` |  |
| `handle(msg: Any) -> None` |  |
| `answer(msg: Any) -> dict[str, Any] \| None` | The JSON-RPC answer to one message, or None for a notification. Shared with the hosted server (demo/agent_mcp.py), which carries the same messages over streamable HTTP. |
| `run() -> None` |  |

### `main`

```python
main(argv: Sequence[str] | None = None, *, operator: str = "agent", runtime: str = "allowedby/mcp", default_state: str | None = None, default_operator_key: str | None = None, default_operator_domain: Callable[[str], str | None] | None = None, load_operator_key: Callable[[str], core.Key] | None = None) -> None
```

The `allowedby-mcp` command. The keyword arguments let a host (such as demo/mcp_agent.py) set its own operator, defaults and key loader.

## `allowedby.mdoc`

`sdks/python/src/allowedby/mdoc.py`

ISO/IEC 18013-5 mdoc verification (OAID-7 §5, 0.2.6-draft): DeviceResponse (§8.3.2.1.2.2), issuer data authentication with the MSO (§9.1.2), device authentication by signature (§9.1.3), and the OpenID4VP 1.0 session transcripts (OpenID4VP 1.0 Appendix B.2.6). Used for the EUDI PID in `mso_mdoc` and for mobile driving licences.

Has its own CBOR codec (RFC 8949): unlike core.cbor_dec it keeps tags (24 encoded CBOR data item, 0 tdate, 1004 full-date) and the exact bytes of each tag-24 item, which the MSO digests and the signatures cover.

### `Tag`

```python
class Tag(tag, value, raw=None)
```

A CBOR tag (RFC 8949 §3.4). For tag 24, `raw` keeps the bytes as received: #6.24(bstr) re-encoded by another encoder need not be byte-identical, and the digests are over the received bytes.

### `tag24`

```python
tag24(v)
```

#6.24(bstr .cbor v): an embedded CBOR data item.

### `loads`

```python
loads(b)
```

One CBOR data item, nothing after it. Raises ValueError.

### `dumps`

```python
dumps(v)
```

Definite-length, preferred-serialisation encoder (RFC 8949 §4.1); a Tag 24 with `raw` is copied as is.

### `embedded`

```python
embedded(t)
```

The data item inside a #6.24(bstr .cbor ...).

### `plain`

```python
plain(v)
```

Element value for callers: full-date (1004) and tdate (0) as text, other tags unwrapped.

### `tdate`

```python
tdate(v)
```

tdate (#6.0 RFC 3339) or epoch (#6.1) -> epoch seconds (ISO 18013-5 §9.1.2.4).

### `verify_sig`

```python
verify_sig(pub, alg, data, sig)
```

JOSE/COSE ECDSA (r||s, RFC 7518 §3.4 / RFC 9053 §2.1) or EdDSA. The curve must be the one of the alg. Raises ValueError.

### `jwk_to_pub`

```python
jwk_to_pub(jwk)
```

EC P-256/384/521 or Ed25519 JWK -> public key (the point is checked to be on the curve).

### `pub_to_jwk`

```python
pub_to_jwk(pub)
```

### `cose_key_to_jwk`

```python
cose_key_to_jwk(c)
```

COSE_Key (RFC 9053 §7.1) EC2 or OKP/Ed25519 -> JWK, checked by loading it.

### `jwk_to_cose_key`

```python
jwk_to_cose_key(jwk)
```

### `verify_chain`

```python
verify_chain(chain_der, anchors_der, t, eku=None)
```

chain (leaf first; may end with the anchor) -> (leaf certificate, anchor DER). Each certificate valid at t, each signed by the next, the last by a trust anchor (RFC 5280 §6, without policies or revocation). When the leaf has an extended key usage it must include `eku`. Raises ValueError.

### `session_transcript_redirect`

```python
session_transcript_redirect(client_id, nonce, jwk_thumbprint, response_uri)
```

OpenID4VP 1.0 Appendix B.2.6.1: [null, null, ["OpenID4VPHandover", SHA-256(cbor(OpenID4VPHandoverInfo))]] with OpenID4VPHandoverInfo = [clientId, nonce, jwkThumbprint (bstr, RFC 7638, of the response encryption key; null when the response is not encrypted), responseUri]. A base64url thumbprint is accepted and decoded.

### `session_transcript_dcapi`

```python
session_transcript_dcapi(origin, nonce, jwk_thumbprint)
```

OpenID4VP 1.0 Appendix B.2.6.2 (DC API): [null, null, ["OpenID4VPDCAPIHandover", SHA-256(cbor([origin, nonce, jwkThumbprint]))]].

### `verify_issuer_auth`

```python
verify_issuer_auth(issuer_auth, anchors_der, t)
```

IssuerAuth (ISO 18013-5 §9.1.2.4) -> (MSO, DS certificate, anchor DER). The alg is in the protected header, the x5chain (label 33) in the unprotected header (a protected one is accepted too).

### `verify_device_response`

```python
verify_device_response(device_response_bytes, session_transcript, trust_anchors_der, now=None, expected_doctype=None)
```

DeviceResponse (ISO 18013-5 §8.3.2.1.2.2) -> [{doctype, issuer_cert_subject, anchor_subject, anchor_der, anchor_country, claims {namespace: {element: value}}, device_key_jwk, valid_from, valid_until}]. Every document: issuerAuth signed by a DS certificate chaining to a trust anchor (IACA), MSO valid at `now`, each disclosed element's digest in the MSO, device signature over the session transcript. Raises ValueError.

## `allowedby.mds`

`sdks/python/src/allowedby/mds.py`

FIDO Metadata Service v3 (MDS3) for the passkey class `authn` (OAID-7 §4).

`authn: hardware` is decided against the MDS3 BLOB, never a local allowlist: the BLOB verifies to a pinned root, the packed attestation chains to the entry's `attestationRootCertificates`, the entry declares hardware key protection and carries no compromise report, and the credential is not backup-eligible (BE = 0). Everything else is `synced` (BE = 1) or `software`. Fails closed: malformed input raises ValueError; anything unproven is not `hardware`.

### `root_fingerprint`

```python
root_fingerprint(der)
```

Lowercase hex SHA-256 of a certificate DER (to compare with a pinned value).

### `Metadata`

```python
class Metadata(no, next_update, entries, stale=False, legal_header=None, raw=None)
```

A verified MDS3 BLOB: `no` (serial), `next_update` (date), `stale` (nextUpdate reached, within grace), `entries` keyed by AAGUID hex (lowercase, no dashes). `raw` is the verified JWS (for this node's cache only).

| Method |  |
|---|---|
| `entry(aaguid_hex)` |  |

### `local_metadata`

```python
local_metadata(roots_by_aaguid, key_protection=("hardware", "secure_element"), fido="L1")
```

TEST AND DEMO ONLY: a Metadata built from a local {aaguid hex: [root DER]} allowlist, so a node without the MDS3 BLOB runs the same classification code. `no` is 0 and `source` says it is not MDS3.

### `load_blob`

```python
load_blob(jwt_text, root_ders, now=None, grace_days=0, crl_check=None)
```

Verify an MDS3 BLOB (OAID-7 §4): a JWS (ES256 or RS256) whose `x5c` chain reaches one of `root_ders` (pinned root DERs; production: GlobalSign Root CA - R3). Checks validity periods, CA on intermediates and the signature. `crl_check(chain)` (optional, [leaf, …, root] x509 objects) must return True; this module never fetches CRLs. nextUpdate is a date: from that day the BLOB is `stale`; more than `grace_days` days after it, it is rejected. -> Metadata. Raises ValueError.

### `fetch`

```python
fetch(url, cache_path, root_ders, http_get, now=None, grace_days=0, crl_check=None)
```

Load the MDS3 BLOB for this node (OAID-7 §4). Licence rule: each node fetches the BLOB itself, under its own relying-party acceptance of the FIDO Alliance MDS terms, and never re-serves or redistributes it; `cache_path` is a private file for this node only.

The cache is used while its nextUpdate has not been reached. Otherwise `http_get(url) -> bytes` downloads a new BLOB, which is verified (load_blob) before it replaces the cache; a serial `no` lower than the cached one is a rollback and raises. If the download itself fails, a cached BLOB still within grace is returned. Raises ValueError.

### `verify_attestation`

```python
verify_attestation(att_obj_bytes, client_data_json_bytes, metadata, now=None)
```

WebAuthn attestation object against MDS3 (OAID-7 §4). -> {fmt, aaguid, cred_id, jwk, auth_data, attested, chain_ok, reason, mds_no}. `attested`: a full (x5c) packed attestation whose leaf passes the WebAuthn checks and signs authData || SHA-256(clientDataJSON); `chain_ok`: that chain reaches the MDS entry's roots. Packed self attestation, `none`, `fido-u2f` (zero AAGUID: no MDS entry by AAGUID) and other formats are not attested. Raises ValueError when malformed.

### `fido_level`

```python
fido_level(entry)
```

Highest FIDO_CERTIFIED_&lt;level> in the entry's statusReports, or None.

### `fips`

```python
fips(entry)
```

Heuristic: True when a statusReport's certificationDescriptor, certificateNumber, certificationPolicyVersion or certificationRequirementsVersion mentions "FIPS". MDS has no structured FIPS field; informative only.

### `classify`

```python
classify(verified, flags_byte, entry)
```

Authenticator class (OAID-7 §4) -> (authn, detail). `synced` when BE = 1, whatever else holds. `hardware` only when attested and chain_ok against an MDS entry for this AAGUID whose keyProtection includes hardware or secure_element and which has no compromise or REVOKED statusReport (a later FIDO_CERTIFIED\* or UPDATE_AVAILABLE does not clear one). `software` otherwise. detail = {aaguid, mds_no, fido_level, fips, reason}.

### `uv_required`

```python
uv_required(flags_byte)
```

L1 rule (OAID-7 §2, §4): user verification (UV) must be set. Backup state (BS) is never a condition.

## `allowedby.oid4vp`

`sdks/python/src/allowedby/oid4vp.py`

OpenID4VP 1.0 verifier (OAID-7 §5, 0.2.6-draft): the home node verifies identity itself. It asks the holder's wallet with a DCQL query for the EUDI PID (`dc+sd-jwt` or `mso_mdoc`) or an ISO 18013-5 mDL, receives an encrypted response (`direct_post.jwt`, or `dc_api.jwt` through the W3C Digital Credentials API, OpenID4VP 1.0 Appendix A), and checks it: JWE (RFC 7516/7518 ECDH-ES), SD-JWT VC with key binding (RFC 9901, SD-JWT VC), mdoc (mdoc.py). The result is normalised to a few claims; attributes the credential does not carry stay absent.

With a RequestSigner the authorization request is a signed request object (JAR, RFC 9101): a JWS `typ` `oauth-authz-req+jwt`, ES256, the verifier's certificate chain in `x5c`, and the Client Identifier `x509_san_dns:<host>` naming a dNSName SAN of the leaf certificate (OpenID4VP 1.0 §5.9.3). Same-device/cross-device (direct_post.jwt): passed by reference, `client_id` + `request_uri`, the node serving the JWS once as `application/oauth-authz-req+jwt` (RFC 9101 §5.2, method GET). DC API: passed by value, `{"request": JWS}` under protocol `openid4vp-v1-signed`, with `expected_origins` in the request object (OpenID4VP 1.0 Appendix A.3).

### `concat_kdf`

```python
concat_kdf(z, enc, apu=b"", apv=b"")
```

RFC 7518 §4.6.2 for ECDH-ES direct key agreement: AlgorithmID = enc, keydatalen = the enc key size.

### `jwe_encrypt`

```python
jwe_encrypt(jwk, plaintext, enc="A128GCM", apu=b"", apv=b"")
```

Compact JWE, alg ECDH-ES, enc A128GCM/A256GCM, to `jwk` (what a wallet does, OpenID4VP 1.0 §8.3).

### `jwe_decrypt`

```python
jwe_decrypt(priv, token, enc_allowed=tuple(ENC), kid=None)
```

Compact JWE with alg ECDH-ES (direct key agreement, empty encrypted key) -> plaintext. Raises ValueError.

### `verify_sd_jwt_vc`

```python
verify_sd_jwt_vc(token, issuer_key, *, aud, nonce, now=None, status_check=None)
```

SD-JWT VC presentation `<issuer-jwt>~<disclosure>~...~<kb-jwt>` -> (claims, issuer header, issuer payload). issuer_key(header, payload) -> public key (raises ValueError when untrusted). Key binding is required (HAIP): KB-JWT `kb+jwt` signed by cnf.jwk, with aud, nonce, iat within ±5 min, sd_hash over the presentation. status_check(status claim) -> bool, called when the credential has a `status` (never fetched here).

### `dcql`

```python
dcql(kind)
```

The DCQL query for `pid` (SD-JWT VC or mdoc, PID Rulebook names) or `mdl` (ISO 18013-5 elements).

### `claims_from_sd_jwt`

```python
claims_from_sd_jwt(c)
```

PID Rulebook SD-JWT VC names (birthdate, age_equal_or_over, nationalities, address) and older ones.

### `claims_from_mdoc`

```python
claims_from_mdoc(c)
```

PID mdoc (eu.europa.ec.eudi.pid.1) or mDL (org.iso.18013.5.1) elements.

### `san_dns_names`

```python
san_dns_names(cert)
```

### `RequestSigner`

```python
class RequestSigner(key, chain_der)
```

The verifier's request-signing key and certificate chain for `x509_san_dns` (OpenID4VP 1.0 §5.9.3). key: EC P-256 private key (or core.Key) -> ES256. chain_der: [leaf, intermediates...] DER, leaf first; leave the trust anchor out (the wallet has it). The leaf must certify the key and carry the host as a dNSName SAN.

| Method |  |
|---|---|
| `from_pem(key_pem, chain_pem)` | PEM private key (PKCS#8 or SEC1, unencrypted) and PEM chain, leaf first (bytes). |
| `sign(payload)` |  |

### `Verifier`

```python
class Verifier(client_id, response_uri_or_origin, enc_key, trust, pid_wallet_certified=None, status_check=None, kid="vp-enc-1", signer=None, request_uri_base=None)
```

An OpenID4VP 1.0 verifier for the home node.

client_id: the Client Identifier, prefix included (e.g. `x509_san_dns:node.example`); unused for unsigned DC API requests. response_uri_or_origin: the `response_uri` for direct_post.jwt, or the web origin for the DC API. enc_key: EC P-256 private key for response encryption. trust: {"pid_issuers": [{iss, country, jwks?, anchors?}], "iaca": [DER]}. pid_wallet_certified: list of PID issuers, or callable(iss) -> bool, saying whether the provider only issues to certified wallet units (None: unknown). status_check: callable(status) -> bool. signer: a RequestSigner; requests are then signed by default (client_id must be `x509_san_dns:<SAN>`). request_uri_base: where request objects are served (default &lt;response_uri origin>/oid4vp/request/); the node routes GET &lt;base>&lt;id> to serve_request_object(id), e.g. with mount(app).

| Method |  |
|---|---|
| `client_metadata()` | OpenID4VP 1.0 §5.1/§11.1: the response encryption key and the formats this verifier accepts. |
| `request(query_kind, nonce=None, *, dc_api=None, signed=None, now=None)` | -> (authorization request, pending state to keep server-side, single use). dc_api defaults to True when constructed with an origin; signed defaults to True when a signer is configured (signed=False: the unsigned request, for tests and the demo). Signed, the request is {"client_id", "request_uri"} (direct_post.jwt; the JWS is fetched once from request_uri) or {"request": JWS} (DC API); unsigned, the parameters themselves. |
| `request_object(rid, now=None)` | The signed request object for `rid`, once (a second fetch, or one after REQUEST_TTL, gets None). |
| `serve_request_object(rid, now=None)` | -> (status, body, headers) for GET &lt;request_uri_base>&lt;rid> (RFC 9101 §5.2). |
| `mount(app)` | Route GET &lt;path of request_uri_base>&lt;id> on a core.App to serve_request_object. |
| `dc_api_request(req)` | The entry for navigator.credentials.get({digital: {requests: [...]}}) (OpenID4VP 1.0 Appendix A.2/A.3). |
| `verify_response(pending, response, now=None)` | The wallet's response ({"response": JWE} as posted, or the JWE) -> {format, kind, claims, issuer, source}. The caller deletes `pending` after one use. Raises ValueError. |

## `allowedby.oidc_broker`

`sdks/python/src/allowedby/oidc_broker.py`

OIDC eID broker connector: OAID-7 §5 step-up to L2/L3 through an eIDAS eID broker (first target: Signicat eID & Wallet Hub; Idura or any other OpenID Provider by configuration) until certified EUDI wallets exist.

Authorization code flow (OIDC Core §3.1) with PKCE S256 (RFC 7636), `state`, `nonce`, `prompt=login` and `acr_values` (OIDC Core §3.1.2.1); the RFC 9207 `iss` response parameter; an ID token checked per OIDC Core §3.1.3.7.

The level is decided here, fail closed: the broker's `acr` says what LoA the user's eID reached, but only a scheme the operator lists as \*notified\* under eIDAS at high can give level 3. A vendor-mapped LoA (a bank ID the broker calls "high") or an unknown scheme never gives 3. The node still requires a hardware passkey for level 3 (§5) and MUST use `result["level"]`, never the level it asked for.

Nothing here logs or returns the ID token, the access token or the `sub`.

### `default_transport`

```python
default_transport(method, url, headers, body)
```

core.http, with its SSRF guards when hosted.

### `verify_jws`

```python
verify_jws(alg, jwk, data, sig)
```

RS256 / PS256 (RFC 7518 §3.3, §3.5; RSA >= 2048 bits) and ES256 (core.verify_raw).

### `Broker`

```python
class Broker(config, transport=default_transport, now=time.time)
```

One configured OpenID Provider. config:

id, issuer, client_id, redirect_uri, scopes (["openid", ...]); client auth: client_secret (client_secret_basic) or client_key (core.Key ES256 or its to_json(), private_key_jwt, OIDC Core §9); acr_map {acr value: "low"|"substantial"|"high"}; scheme_claim (the claim naming the eID method, broker-specific: no default); country_claim (optional); notified {scheme: {"country": "BE", "notified_loa": "high"|"substantial"| None, "when": {claim: value}} or a list of such variants}; claim_map (defaults CLAIM_MAP); accept_unnotified_substantial (default True); acr_param (default "acr_values"); prompt (default "login").

| Method |  |
|---|---|
| `discover(force=False)` | OpenID Connect Discovery 1.0 §4: metadata (issuer must match exactly, §4.3) and the JWKS. Cached. |
| `start(level)` | -> (redirect_url, pending). `pending` holds the PKCE verifier and nonce: keep it server side, bound to the human's session, and pass it to finish() once. |
| `finish(pending, query)` | The redirect back: query = the callback's query parameters (dict). -> {level, claims, source}. |

### `signicat_config`

```python
signicat_config(domain, client_id, client_secret, redirect_uri, notified, provider_id="eid:signicat")
```

Broker config for the Signicat eID Hub (developer.signicat.com, docs/eid-hub/oidc): issuer https://&lt;domain>/auth/open; `acr_values=loa:substantial|loa:high` (the hub fails the login below that level); `acr` returns "low" | "substantial" | "high"; `idp` names the eID used; `birthdate`, `nationality` (alpha-2) and `address` need the scopes below. Set "ID Token User data = All" on the Signicat client so they are in the ID token. Tokens are RS256. `notified` maps Signicat `idp` names to {"country", "notified_loa"}, from the Commission's list of notified schemes: an `idp` not in it is treated as not notified (level 2 at most).

## `allowedby.openai_agents`

`sdks/python/src/allowedby/openai_agents.py`

OpenAI Agents SDK integration: the AllowedBy tools as `FunctionTool`s.

```
from agents import Agent as LLMAgent
from allowedby import Agent
from allowedby.openai_agents import allowedby_tools
from allowedby.tools import Wallet
```

```
wallet = Wallet(Agent("https://node.example.org"), tell=lambda m: print(m.get("text", "")))
assistant = LLMAgent(name="assistant", instructions="...", tools=allowedby_tools(wallet))
```

`allowedby_call` pauses while the person approves (up to `wait_seconds`); `tell` receives the approval link and the binding code to show in the conversation. The HTTP work runs in a worker thread: the event loop keeps going.

### `allowedby_tools`

```python
allowedby_tools(wallet: Wallet, *, wait_seconds: float = 300) -> list[FunctionTool]
```

allowedby_discover, allowedby_call, allowedby_wait and allowedby_approvals for an OpenAI Agents SDK agent. wait_seconds: how long allowedby_call waits for the person by default (the model may pass less).

## `allowedby.qes`

`sdks/python/src/allowedby/qes.py`

Qualified electronic signature over a grant core (OAID-7 §10, 0.2.6-draft).

No QTSP documents JAdES output, so the home node assembles the JAdES itself: 1. read the signer chain with CSC API v2 `credentials/info`; 2. build the JAdES protected header (ETSI TS 119 182-1) and hash the JWS signing input; 3. bind that hash to an OAuth2 `credential` authorization (CSC v2 §8.4, SCAL2); 4. obtain the raw signature with `signatures/signHash` (CSC v2 §11.10); 5. fetch OCSP for the signer certificate itself (RFC 6960); 6. put `qes: {jades, ocsp, tl, class, ra}` in the grant root. A verifier checks it offline against a node-configured trusted-list snapshot (ETSI TS 119 612). Every network call goes through an injected `transport(method, url, headers, body) -> (status, headers, body)`. Everything fails closed with ValueError and a short reason.

### `der`

```python
der(tag, content)
```

### `der_oid`

```python
der_oid(dotted)
```

### `der_read`

```python
der_read(b, i=0)
```

-> (tag, content, next index). Definite lengths, single-byte tags only (X.690 DER).

### `der_items`

```python
der_items(content)
```

### `oid_dec`

```python
oid_dec(c)
```

### `fmt_time`

```python
fmt_time(t)
```

### `parse_time`

```python
parse_time(s)
```

### `alg_for_cert`

```python
alg_for_cert(cert, rsa_alg="PS256")
```

JWS alg for the signer key (RFC 7518 §3): P-256 -> ES256, P-384 -> ES384, RSA >= 2048 -> PS256 (or RS256).

### `ecdsa_to_jose`

```python
ecdsa_to_jose(sig, n)
```

CSC signHash returns ECDSA as DER Ecdsa-Sig-Value (RFC 3279 §2.2.3); JWS needs r||s (RFC 7518 §3.4).

### `verify_jws_sig`

```python
verify_jws_sig(alg, pk, data, sig)
```

### `CscClient`

```python
class CscClient(base_url, transport, access_token=None, oauth2_url=None)
```

Cloud Signature Consortium API v2.0 (v2.0.0.2) remote signing client.

`access_token` is the service-scope token (CSC v2 §8.3) used for info/credentials; the OAuth2 `credential` scope token (CSC v2 §8.4.2, SCAL2: bound to credentialID + hashes) authorises signHash.

| Method |  |
|---|---|
| `info()` | CSC v2 §11.1 `info`. |
| `credentials_list()` | CSC v2 §11.4 `credentials/list` -> [credentialID]. |
| `credentials_info(credential_id)` | CSC v2 §11.5 `credentials/info` with certificates=chain, certInfo, authInfo. |
| `authorize_url(credential_id, hash_bytes, hash_oid, client_id, redirect_uri, state, code_challenge=None, num_signatures=1, description=None, lang=None)` | CSC v2 §8.4.2 `oauth2/authorize`, scope=credential. `hashes` = base64url hash values (comma-separated), binding the authorization to exactly these hashes (SCAL2). hash_bytes=None asks only for identification (one-shot certificate issuance) and cannot authorise a signature. |
| `follow_authorize(url, state=None)` | Open the authorize URL through the transport (tests/simulator: the human's browser does this in production) and return the redirect's query parameters. |
| `token(code, client_id, client_secret, redirect_uri, code_verifier=None)` | CSC v2 §8.4.3 `oauth2/token` (RFC 6749 §4.1.3) -> credential access token (used as Bearer on signHash). |
| `sign_hash(credential_id, sad_or_token, hash_bytes, hash_oid, sign_algo_oid, sign_algo_params=None, key_len=None, use_sad=False)` | CSC v2 §11.10 `signatures/signHash` for one hash -> raw signature (ECDSA normalised to JOSE r\|\|s). Default: `sad_or_token` is the OAuth2 credential token (Bearer). use_sad=True sends it as `SAD` with the service token (explicit authorization, CSC v2 §11.6). |

### `signer_for`

```python
signer_for(client, credential_id, token, alg)
```

-> signer(hash_bytes) -> raw JOSE signature, wrapping CscClient.sign_hash for a JWS alg.

### `jades_protected_header`

```python
jades_protected_header(cert_chain_der, signing_time, alg)
```

JAdES baseline B protected header (ETSI TS 119 182-1 §5.1, §5.2.1 sigT). x5c is standard base64 (RFC 7515 §4.1.6), x5t#S256 the base64url SHA-256 of the signer certificate (RFC 7515 §4.1.8).

### `jades_signing_input`

```python
jades_signing_input(header, payload_bytes)
```

### `signing_hash`

```python
signing_hash(core_json_bytes, cert_chain_der, signing_time, alg=None)
```

-> (alg, hash of the JWS signing input) — the value bound at authorize and sent to signHash.

### `assemble`

```python
assemble(core_json_bytes, cert_chain_der, signer, signing_time, alg=None)
```

-> compact detached JAdES `header..signature`. signer(hash_bytes) -> raw signature (the CSC call); the hash handed to the QTSP is the hash of the JWS signing input, with the hash of `alg`.

### `remote_sign`

```python
remote_sign(client, credential_id, core_json_bytes, *, client_id, client_secret, redirect_uri, user_agent, signing_time=None, rsa_alg="PS256", description=None)
```

Whole CSC v2 flow -> (jades, cert_chain_der). user_agent(url) -> redirect query dict (the human's browser at the QTSP). credential_id=None = one-shot: a first, identification-only authorization makes the QTSP issue the short-lived certificate; the hash (which covers x5c) is bound by a second authorization.

### `fetch_ocsp`

```python
fetch_ocsp(cert_der, issuer_der, transport, nonce=True)
```

RFC 6960 §4.1 request (SHA-1 CertID, as RFC 5019 profiles), POSTed as application/ocsp-request (RFC 6960 Appendix A.1) to the certificate's AIA OCSP URL -> DER OCSP response.

### `check_ocsp`

```python
check_ocsp(ocsp_der, cert_der, issuer_der, signing_time, max_skew=600, nonce=None)
```

RFC 6960 §3.2 acceptance: successful; signed by the issuer or by a delegated responder certificate issued directly by the issuer with id-kp-OCSPSigning (§4.2.2.2); exactly one SingleResponse for this cert, status good; |producedAt - signing time| &lt;= max_skew (OAID-7 §10: 10 minutes).

### `qc_statements`

```python
qc_statements(cert)
```

EN 319 412-5 QCStatements (RFC 3739 §3.2.6), parsed from the extension DER -> {oid: [qcType oids]}.

### `subject_identity`

```python
subject_identity(cert)
```

Natural-person identity from a qualified certificate (EN 319 412-2 §4.2.4; semantics identifier in serialNumber per EN 319 412-1 §5.1.3) plus QC statements (EN 319 412-5 §4.2.1-4.2.3).

### `subject_matches`

```python
subject_matches(cert_identity, identity_record)
```

OAID-7 §10.2: the certificate subject must match the identity record behind L2/L3. Names: NFKD, marks stripped, casefolded, spaces collapsed; surname equal; the record's first given name must be one of the certificate's given names. A record document/national id with type+country must agree with the certificate's semantics identifier (absent in the cert = no match).

### `TrustedList`

```python
class TrustedList(uri, sha256, sequence, issued, services)
```

Node-configured snapshot of an EU trusted list (ETSI TS 119 612): {uri, sha256 (hex of the TL XML fetched), sequence, issued, services: [{name, cert_der, type "CA/QC", status "granted"|"withdrawn", status_start, qualifiers [...], history [{status, status_start}]?}]}.

Fetching and validating the real LOTL -> national TL XML (XMLDSig, ETSI TS 119 612 §5.7, TS 119 615) is a later step. The grant records the snapshot's uri + sha256 + sequence as `qes.tl`, so a verifier with the same snapshot reproduces the decision offline.

| Method |  |
|---|---|
| `from_dict(d)` |  |
| `ref()` |  |
| `status_at(svc, t)` | Status in force at t: the latest of current + history entries whose status_start &lt;= t (TS 119 612 §5.5.4-5.5.5). |
| `lookup(issuer_der, at_time)` | -> the CA/QC service whose digital identity is this issuer and whose status at at_time is granted. |

### `build_qes_member`

```python
build_qes_member(jades, ocsp_der, tl, signature_class="eu_qes", ra="qtsp")
```

-> grant root `qes` member (OAID-7 §10.3): {jades, ocsp (base64), tl: {uri, sha256, seq}, class, ra}.

### `parse_jades`

```python
parse_jades(jades)
```

-> (header, header b64, signature). Compact detached only; b64 must stay default (no `b64` member).

### `verify_qes_member`

```python
verify_qes_member(member, core_json_bytes, tl, now=None, require_class="eu_qes", max_skew=600)
```

OAID-7 §10.4 offline verification -> identity dict (with `class`, `ra`, `sig_time`), or ValueError. require_class=None returns any well-formed class to the caller (a `qes: true` route requires eu_qes).

## `allowedby.redis_store`

`sdks/python/src/allowedby/redis_store.py`

A Store shared by every instance and machine: Redis (sdks/CONTRACT.md §2.8, ABY-2 §3.3).

```
from allowedby import AllowedBy
from allowedby.redis_store import RedisStore
```

```
aby = AllowedBy(..., store=RedisStore.from_url("redis://redis.internal:6379/0"))
```

Check-and-set is atomic across instances with WATCH/MULTI/EXEC (optimistic transactions): a concurrent change to a key aborts the transaction, which is retried. Amounts are decimals, added in Python with `decimal.Decimal` (Lua numbers are binary floats and would round money). Expiry follows the SDK's clock (`now`, `until`), never Redis' own: each key holds its deadline; Redis' TTL, set relative to `now`, only removes keys once they are dead.

Any Redis error propagates: the verifier turns it into a refusal (503 status_stale), never an acceptance.

### `RedisStore`

```python
class RedisStore(client: redis.Redis, prefix: str = "allowedby:", retries: int = 50) -> None
```

`client`: a redis.Redis (or compatible) connection; `prefix` namespaces the keys of one service.

| Method |  |
|---|---|
| `from_url(url: str, prefix: str = "allowedby:", **kw: Any) -> RedisStore` | A store on `url` (redis:// or rediss://), with short timeouts: a slow Redis refuses, it does not hang. |
| `add(key: StoreKey, until: int, now: int) -> bool` | Add `key` unless present and live: False when it already was (a replay, a second use). |
| `get(key: StoreKey, now: int) -> Number` |  |
| `charge(charges: Sequence[Charge], now: int) -> bool` | All or nothing: add every increment when every total stays within its maximum. |
| `put_doc(key: StoreKey, version: int, doc: str, now: int) -> bool` | Store `doc` with `version` when it is above the stored one (no expiry): a signed authority policy. |
| `get_doc(key: StoreKey, now: int) -> tuple[int, str] \| None` |  |

## `allowedby.sources_config`

`sdks/python/src/allowedby/sources_config.py`

The hosted node's identity sources from the environment (OAID-7 §5.7): bought providers primary, in-house verifiers in shadow. Nothing configured -> None (the node keeps its simulated demo providers only).

Signicat eID Hub (national eIDs, OIDC): ALLOWEDBY_SIGNICAT_DOMAIN         e.g. yourname.sandbox.signicat.com ALLOWEDBY_SIGNICAT_CLIENT_ID / ALLOWEDBY_SIGNICAT_CLIENT_SECRET ALLOWEDBY_SIGNICAT_NOTIFIED       path to JSON {idp: {"country": "BE", "notified_loa": "high"}} from the Commission's list of notified schemes; an idp not listed gives level 2 at most Signicat Assure, ReadID + iProov (passport and ID-card chips with liveness): ALLOWEDBY_ASSURE_CLIENT_ID / ALLOWEDBY_ASSURE_CLIENT_SECRET ALLOWEDBY_ASSURE_LIVENESS         high | substantial (default): the rating of the liveness component under the contract, high only with its certificate on file In-house shadow and policy: ALLOWEDBY_CSCA                    path to a PEM file of CSCA certificates: enables the node's chip verifier as a shadow of the chip vendor (it re-checks only when the vendor returns raw chip data) ALLOWEDBY_CROSSCHECK              log (default) | refuse The redirect URI to register at Signicat is &lt;node>/verify/return.

### `identity_from_env`

```python
identity_from_env(origin, env=None)
```

## `allowedby.tlog`

`sdks/python/src/allowedby/tlog.py`

AllowedBy demo: the transparency log (OAID-4).

RFC 6962 Merkle tree over salted commitments, C2SP signed-note checkpoints, tlog-cosignature/v1, the tlog-witness add-checkpoint body and tlog-tiles. Hashing as in vectors/log.json: commitment = SHA-256(salt || document), leaf = SHA-256(0x00 || commitment), node = SHA-256(0x01 || left || right).

### `H`

```python
H(b)
```

### `std64`

```python
std64(b)
```

### `unstd64`

```python
unstd64(s)
```

### `commitment`

```python
commitment(salt, document)
```

OAID-4 §2.

### `leaf_hash`

```python
leaf_hash(c)
```

### `node_hash`

```python
node_hash(a, b)
```

### `Tree`

```python
class Tree(commitments=())
```

Merkle tree hashes over a growing list of commitments. Appends come from one writer (under the node lock); readers only ever look at a prefix, which never changes.

| Method |  |
|---|---|
| `extend(commitments)` |  |
| `size()` |  |
| `sub(start, n)` | Hash of leaves [start, start + n). |
| `root(size)` |  |
| `inclusion(m, size, start=0)` | RFC 6962 §2.1.1 audit path of leaf m in the tree of `size` leaves. |
| `consistency(m, size, start=0, b=True)` | RFC 6962 §2.1.2 consistency proof between sizes m and `size`. |

### `root_from_inclusion`

```python
root_from_inclusion(idx, size, leaf, proof)
```

RFC 9162 §2.1.3.2: the root a leaf commitment and its audit path lead to, or None.

### `consistent`

```python
consistent(m, n, old_root, new_root, proof)
```

RFC 9162 §2.1.4.2.

### `keyhash`

```python
keyhash(name, sigtype, raw_pub)
```

### `checkpoint_body`

```python
checkpoint_body(origin, size, root)
```

C2SP tlog-checkpoint: origin line, tree size, base64 root hash.

### `sign_note`

```python
sign_note(body, name, key)
```

The checkpoint signed with an Ed25519 key under the key name `name` (OAID-4 §4: `log.origin`).

### `cosign`

```python
cosign(body, name, key, ts)
```

C2SP tlog-cosignature/v1 line by witness `name`.

### `parse_note`

```python
parse_note(text)
```

-> (body, {origin, size, root}, [(key name, signature bytes)]). Raises ValueError.

### `note_signed`

```python
note_signed(body, lines, name, jwks)
```

True when one signature line by `name` verifies with one of the Ed25519 keys (type 0x01).

### `cosig_time`

```python
cosig_time(body, lines, name, jwks)
```

The timestamp of a valid cosignature by witness `name`, or None.

### `witness_request`

```python
witness_request(old, proof, note)
```

C2SP tlog-witness add-checkpoint body: `old N`, the consistency proof, a blank line, the checkpoint.

### `parse_witness_request`

```python
parse_witness_request(text)
```

### `tile_path`

```python
tile_path(n)
```

C2SP tile index: groups of three digits, all but the last prefixed with x (1234067 -> x001/x234/067).

### `parse_tile_path`

```python
parse_tile_path(p)
```

-> (index, width) or None. A partial tile names its width (1-255).

### `tile`

```python
tile(tree, size, level, n, w)
```

Hashes of tile (level, n) of width w in the tree of `size` leaves, or None when it does not exist yet.

### `entries`

```python
entries(commitments)
```

Entry bundle: each entry (the 32-byte commitment) prefixed by its 16-bit big-endian length.

### `parse_entries`

```python
parse_entries(data)
```

## `allowedby.tools`

`sdks/python/src/allowedby/tools.py`

The agent side as tools for agent frameworks: what MCP, LangChain and the OpenAI Agents SDK integrations share.

A `Wallet` holds an `Agent` (passport, proofs, approvals) and runs each protected HTTP call as a job: the call is signed and sent; when the site asks for a person's approval, `tell` receives the link and the binding code (to show in the conversation, verbatim), the job waits for the passkey tap, then retries once. A job that outlives one tool call is continued with `wait(job)`.

```
from allowedby import Agent
from allowedby.tools import Wallet
```

```
wallet = Wallet(Agent("https://node.example.org"), tell=lambda m: print(m["text"]))
wallet.call("GET", "https://notes.example/notes")   # -> {"status": 200, "body": {...}}
```

Sites are found from their URL: /.well-known/allowedby, then their OpenAPI document (ABY-3 §5.1) names the capability of each operation, so the agent reuses a standing approval instead of asking again.

### `tell_the_person`

```python
tell_the_person(a: Message) -> str
```

ABY-2 §8 item 2, CONF-1: the summary and the binding code reach the person verbatim, in a fixed sentence.

### `Wallet`

```python
class Wallet(agent: Agent, tell: Tell | None = None, *, state: str | None = None, allowed_origins: Sequence[str] | None = None, log: Callable[[str], None] | None = None) -> None
```

The agent runtime plus what a conversation needs: jobs that outlive one tool call, saved approvals.

tell(message): called with {"type": "approval_needed", "summary", "code", "link", "level", "text"} when the person must approve (`text` is the sentence to show them verbatim), and with {"type": "approved" | "refused" | "timeout", ...} afterwards. It runs on the job's thread: post the message to the conversation, do not block. allowed_origins: when given, the only sites the tools may call (anything else is refused before any request). Every request of the wallet, discovery included, goes through the agent's `_http`: a host that must bound where the agent reaches (a hosted server, demo/agent_mcp.py) checks each URL there. state: a file keeping the agent's standing approvals across restarts (they are bound to the passport key, so they survive only with an operator that can rebind them, ABY-1 §6).

| Method |  |
|---|---|
| `discover(url: str) -> dict[str, Any]` | What the site at `url` offers agents: organisation, operations, personal data it may ask for. |
| `call(method: str, url: str, body: Any = None, spend_limit: dict[str, Any] \| None = None, wait_seconds: float = 90) -> dict[str, Any]` | Do the request as the person's agent. -> {"status", "body"} when done within `wait_seconds`, else {"status": "waiting_for_approval", "job", "link", "code", "tell_the_person"}: continue with wait(job). |
| `wait(jid: str, wait_seconds: float = 90) -> dict[str, Any]` | Wait for a job up to `wait_seconds` (at most 600). -> its result, or the waiting state again. |
| `approvals() -> dict[str, Any]` | The approvals the agent holds: what each allows, for which site, until when. |
| `tool(name: str, args: dict[str, Any]) -> dict[str, Any]` | Dispatch one of TOOLS by name (MCP and other hosts). Raises KeyError on an unknown name or argument. |

## `allowedby.types`

`sdks/python/src/allowedby/types.py`

Types shared by the SDK's public API and its integrations.

### `Store`

```python
class Store
```

The replay set, single-use consumption and counters (sdks/CONTRACT.md §2.8, ABY-2 §3.3, ABY-1 §7).

`now` always comes from the SDK's clock, never from the store's own wall clock, so an injected clock governs expiry too. Every method raises on a storage error: the verifier then refuses the request (fail closed).

put_doc and get_doc are optional: without them, a policy set with set_authority_policy is held per instance (said once, at construction, when an authority policy is configured), and nothing calls them.

| Method |  |
|---|---|
| `add(key: StoreKey, until: int, now: int) -> bool` | Atomically add `key` until `until`. False when it is already there and unexpired (a replay). |
| `get(key: StoreKey, now: int) -> Number` | The number at `key`, 0 when absent or expired. |
| `charge(charges: Sequence[Charge], now: int) -> bool` | All or nothing: add every increment when every total stays within its max, atomically. An increment may be negative, with no max: the SDK refunds what a request it refused itself was charged (sdks/CONTRACT.md, Refund on the SDK's own refusal); the store applies it exactly. -> bool. |
| `put_doc(key: StoreKey, version: int, doc: str, now: int) -> bool` | Optional. Atomically store `doc` at `key` with `version` when it is above the stored version (never expires): an authority policy's state (the config's, or an override), one JWS signed by the service key, shared by every instance (sdks/CONTRACT.md). The SDK verifies it on read, so a forged one is ignored. A store writer can delete it, which reverts to the config, or put back an older signed one, which brings that policy back until its exp: the store is trusted for this, as for replay and budgets. -> stored. |
| `get_doc(key: StoreKey, now: int) -> tuple[int, str] \| None` | Optional. (version, doc) stored at `key`, or None. |
