# AllowedBy PHP SDK guide

The PHP service SDK lets AI agents call your API for a person, with that person's approval, and checks every
request offline. The concepts (routes, classes, levels, the approval flow, the context) are explained once in
[docs/deploy-saas.md](https://docs.allowedby.com/guides/accept-agents); this guide shows them in PHP. Every runnable example here is a file under
`sdks/php/examples/` that CI runs or analyses, named above each snippet.

Terms used below: a **node** issues agent passports and runs the approval page; a **grant** is the person's signed
approval; a **proof** is the agent's signature over one request; **JWS** is a signed JSON token (RFC 7515);
**TOFU** is trust on first use.

## Install

The package needs PHP 8.2 or later and a shared store (APCu or Redis). It is not published yet: point Composer at a
clone of this repository (`@dev` because there is no released version yet).

```bash
composer config repositories.allowedby path ../allowedby/sdks/php
composer require "allowedby/allowedby:@dev"
```

Or in `composer.json`:

```json
{
    "repositories": [{"type": "path", "url": "../allowedby/sdks/php"}],
    "require": {"allowedby/allowedby": "@dev"}
}
```

| Requirement | Why |
|---|---|
| PHP 8.2, 8.3 or 8.4 | readonly properties, named arguments; CI tests all three |
| `ext-sodium` | Ed25519 signatures (bundled with PHP since 7.2) |
| `ext-openssl` | ES256 (P-256) signatures, RSA passkeys, the disclosure key |
| `ext-zlib` | status lists are zlib-compressed |
| `ext-curl` (recommended) | outgoing calls bounded as a whole (`CurlHttpClient`, the default when loaded); without it, PHP's stream wrapper bounds each step of a call, not the call |
| `ext-apcu`, or Redis through `ext-redis` (phpredis) or `predis/predis` | the shared store: PHP keeps nothing between requests, so the replay set and the node cache live there |

Runtime dependencies are PSR interfaces only: `psr/http-message`, `psr/http-factory`, `psr/http-server-handler`,
`psr/http-server-middleware` (the middleware) and `psr/log` (logging). Laravel and Symfony are not required; their
adapters load only when you use them.

Linux and macOS:

```bash
sudo apt-get install -y php-apcu      # Debian/Ubuntu; macOS: pecl install apcu
php -m | grep -E 'sodium|openssl|zlib|apcu'
```

Windows (PowerShell):

```powershell
php -m | Select-String -Pattern 'sodium|openssl|zlib|apcu'
# APCu: download php_apcu.dll for your PHP build from PECL, then add "extension=apcu" to php.ini
```

Docker:

```dockerfile
FROM php:8.4.14-cli
RUN pecl install apcu-5.1.27 && docker-php-ext-enable apcu
RUN echo "apc.enable_cli=1" >> /usr/local/etc/php/conf.d/docker-php-ext-apcu.ini
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
```

## Quick start

`new AllowedBy(...)` with your origin, node, organisation, routes and templates, then `processGlobals()` on each
request. From `examples/quickstart/app.php` (CI runs it as written):

```php
<?php

declare(strict_types=1);

require __DIR__.'/vendor/autoload.php';

use AllowedBy\AllowedBy;

use function AllowedBy\route;

$aby = new AllowedBy(
    origin: 'http://localhost:8000',
    node: 'http://localhost:18780',
    org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'],
    routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')],
    templates: ['notes:read' => 'Read your notes'],
    keyFile: __DIR__.'/allowedby-keys.json',  // in production: outside the web root
);

$decision = $aby->processGlobals();
if (null !== $decision->response) {
    $decision->response->send();  // discovery documents, refusals and challenges
    exit;
}
if (null === $decision->context) {  // not a route of the map: nothing was checked, so nothing is served
    http_response_code(404);
    exit;
}
header('Content-Type: application/json');
echo json_encode(['notes' => [], 'person' => $decision->context->humanId]);
```

Run it (Linux, macOS and Windows alike):

```bash
php -d apc.enable_cli=1 -S 127.0.0.1:8000 app.php
curl -i http://localhost:8000/.well-known/allowedby
curl -i http://localhost:8000/notes
```

The second call answers `401` with `WWW-Authenticate: AllowedBy realm="localhost:8000", error="passport_required"`.

To see agents get through end to end, run the framework examples ([Testing](#testing)): each starts a real node, the
app and the reference agent, and plays the person with a software passkey (approvals, a write-hard deletion at level
2, replay, revocation). To try a local node by hand, see the repository's [README](https://docs.allowedby.com/).

The hosted demo node is `https://demo.allowedby.com`; use it as `node` when your app is reachable over https.

## Routes and templates

`route(method, path, capability, class:, level:, resource:, ...)` describes one route; a template is the sentence the
person signs. Arguments (the same as Python's `route()`, in PHP's naming):

| Argument | Meaning | Default |
|---|---|---|
| `capability` | What the person allows, `namespace:action`. Leave it out (with `level: 0`) where the agent's passport is enough. | none |
| `class` | `read`, `write`, `write-hard`, `irreversible`; or amount thresholds `[['up_to' => '1000.00', 'class' => 'write-hard'], ['class' => 'irreversible']]` read at `amountField`. For `write-hard` and `irreversible` the SDK creates the approval itself, bound to the exact request, used once. | `read` |
| `level` | 0 agent only, 1 passkey, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey. | `1` |
| `resource` | The resource id, `{param}` from the path: `note:{id}`. | `<namespace>:*` |
| `amountField`, `currencyField` | JSON Pointers to the amount and currency in the body. Approvals then carry a limit per call, per day, week or month, or in total. | none, `/currency` |
| `authn` | `hardware` refuses synced passkeys; `synced` refuses software ones. | any |
| `tier` | Minimum custody tier of the agent's key (0-2). | `0` |
| `maxLifetime` | Seconds an approval for this route may last, 60 s to 30 days. | the class's maximum |
| `levelProfile` | `eu` or `na`, on level-3 routes (OAID-7 §5.3). | none |
| `qes` | A qualified signature: this SDK has no EU trusted list, so such routes always answer `qes_required` (as the reference without one). | `false` |
| `requireLink` | The person must have linked their AllowedBy identity to one of your accounts ([Account linking](#account-linking)); otherwise 403 `human_not_linked`. | `false` |
| `accountParam` | The path parameter that names one of your accounts on a `requireLink` route: a person linked to another account is refused. | the service's, `account` |
| `nonce` | The proof must carry a current AllowedBy-Nonce of the service (ABY-2 §3.2); needs `nonce: true` on the service. | `false` |
| `summary`, `body` | What the route does, and each JSON body member: they go into `/openapi.json`. | none |

`mandate`, `disclose`, `discloseOptional` and `authority` belong to features this SDK does
not have yet: passing one throws at construction (never accepted and ignored).

From `examples/routes/routes.php` (CI runs it):

```php
<?php

declare(strict_types=1);

require __DIR__.'/vendor/autoload.php';

use AllowedBy\AllowedBy;
use AllowedBy\Store\MemoryStore;

use function AllowedBy\route;

$routes = [
    route('GET', '/me', level: 0),                                       // the agent's passport is enough
    route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*'),  // a passkey tap, once
    route('DELETE', '/notes/{id}', 'notes:delete', class: 'write-hard', level: 2, resource: 'note:{id}'),
    route('POST', '/pay', 'pay:send', class: [['up_to' => '1000.00', 'class' => 'write-hard'], ['class' => 'irreversible']],
        level: 2, amountField: '/total'),
];
$templates = ['notes:read' => 'Read your notes', 'notes:delete' => 'Delete note {scope}',
    'pay:send' => 'Pay up to {amount.max} {amount.currency}'];

$aby = new AllowedBy(origin: 'https://notes.example', node: 'https://node.example.org',
    org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'], routes: $routes, templates: $templates,
    store: new MemoryStore(), deferRefresh: true);  // a check of the map: nothing fetched from the node
echo count($routes), " routes, valid\n";  // $aby->routes also holds the SDK's own POST /allowedby/link
```

**The sentence the person signs** comes only from your templates (AMH-1 §4): the node fills `{scope}`,
`{amount.max}`, `{amount.currency}`, `{amount.per}` and `{fields}` from the approval and shows it on the approval page;
the grant carries it in `display`. A string is shorthand for English; give several languages as
`['summary' => ['en' => ..., 'fr' => ...], 'lines' => ['en' => ..., 'fr' => ...]]`. Every capability of the route map
needs a template: a missing one fails at construction.

In a framework config file, a route is an array of the same arguments:
`['method' => 'GET', 'path' => '/notes', 'capability' => 'notes:read', 'level' => 1]` or
`['GET', '/notes', 'notes:read', 'level' => 1]`.

## Framework recipes

One middleware or adapter per framework: the SDK's endpoints first, then the check on every route of the map, then
your handler. Paths outside the map reach your app unchanged, without a context. Every example below is a complete
app, the same notes API each time; CI runs each against a real node, agent and person, 26 of 26 interop scenarios
(`examples/frameworks.json` lists them with their versions and servers).

### PSR-15 (Slim, Mezzio, any PSR-15 stack)

Slim 4, from `examples/frameworks/slim/app.php` (run with PHP's
server, under PHP-FPM and nginx, and under RoadRunner with the Redis store):

```php
<?php

declare(strict_types=1);

/*
 * The notes API in Slim 4: the PSR-15 middleware in front of a PSR-15 app. index.php serves it (php -S, PHP-FPM),
 * worker.php keeps it in memory (RoadRunner; its processes share nothing, so they use Redis: set REDIS_URL).
 */

require_once __DIR__.'/vendor/autoload.php';

use AllowedBy\AllowedBy;
use AllowedBy\Psr15\AllowedByMiddleware;
use AllowedBy\Psr15\RequireContext;
use AllowedBy\Store\ApcuStore;
use AllowedBy\Store\RedisStore;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Psr7\Factory\ResponseFactory;
use Slim\Psr7\Factory\StreamFactory;

use function AllowedBy\route;

$redis = false === getenv('REDIS_URL') ? null : new Predis\Client((string) getenv('REDIS_URL'));
$notes = null === $redis ? new Notes() : new RedisNotes($redis);
$json = static function (Response $response, array $data, int $status = 200): Response {
    $response->getBody()->write((string) json_encode($data));

    return $response->withStatus($status)->withHeader('Content-Type', 'application/json');
};

$app = AppFactory::create();
$checked = new RequireContext(new ResponseFactory(), new StreamFactory());  // on every protected route
$app->get('/health', fn (Request $request, Response $response) => $json($response, ['ok' => true]));

$app->get('/me', function (Request $request, Response $response) use ($json) {
    $context = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE);

    return $json($response, ['agent' => $context->agent, 'operator' => $context->operator, 'level' => $context->level]);
})->add($checked);

$app->get('/notes', function (Request $request, Response $response) use ($json, $notes) {
    $person = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE)->humanId ?? throw new LogicException('no person at level 0');

    return $json($response, ['notes' => $notes->list($person)]);
})->add($checked);

$app->post('/notes', function (Request $request, Response $response) use ($json, $notes) {
    $person = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE)->humanId ?? throw new LogicException('no person at level 0');
    $text = json_decode((string) $request->getBody(), true)['text'] ?? null;
    if (!is_string($text) || 1 !== preg_match('/\A.{1,2000}\z/su', $text)) {
        return $json($response, ['error' => 'text: a string of 1 to 2000 characters'], 400);
    }

    return $json($response, ['id' => $notes->add($person, $text)['id']], 201);
})->add($checked);

$app->delete('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) {
    $person = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE)->humanId ?? throw new LogicException('no person at level 0');
    $notes->delete($person, $args['id']);

    return $json($response, ['deleted' => $args['id']]);
})->add($checked);

$aby = new AllowedBy(
    origin: (string) getenv('ALLOWEDBY_ORIGIN'),
    node: (string) getenv('ALLOWEDBY_NODE'),
    org: ['legal_name' => 'Notes Interop Ltd', 'country' => 'FR'],
    routes: [
        route('GET', '/me', level: 0, summary: 'Who is calling'),
        route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*', summary: 'List your notes'),
        route('POST', '/notes', 'notes:write', class: 'write', level: 1, resource: 'note:new', summary: 'Add a note',
            body: ['text' => 'the note']),
        route('DELETE', '/notes/{id}', 'notes:delete', class: 'write-hard', level: 2, resource: 'note:{id}',
            summary: 'Delete a note'),
    ],
    templates: ['notes:read' => 'Read your notes', 'notes:write' => 'Write new notes',
        'notes:delete' => 'Delete note {scope}'],
    keyFile: getenv('ALLOWEDBY_KEY_FILE') ?: throw new RuntimeException('set ALLOWEDBY_KEY_FILE'),  // private
    store: null === $redis ? new ApcuStore() : new RedisStore($redis),
    title: 'Notes Interop API',
    refreshSeconds: (int) (getenv('ALLOWEDBY_REFRESH_SECONDS') ?: 5),
);
$app->addErrorMiddleware(false, false, false);  // 404 and 405 as responses
$app->add(new AllowedByMiddleware($aby, new ResponseFactory(), new StreamFactory()));  // added last: runs first

return $app;
```

Mezzio 3: pipe the middleware before routing, as
`examples/frameworks/mezzio/` does.

### Laravel 12

The package is auto-discovered. Publish the config, fill it, and the middleware runs on every request (`global`):

```bash
php artisan vendor:publish --tag=allowedby-config
```

From `examples/frameworks/laravel/config/allowedby.php`:

```php
<?php

declare(strict_types=1);

/* config/allowedby.php of the notes API: php artisan vendor:publish --tag=allowedby-config, then edit. */
return [
    'origin' => env('ALLOWEDBY_ORIGIN'),
    'node' => env('ALLOWEDBY_NODE'),
    'org' => ['legal_name' => 'Notes Interop Ltd', 'country' => 'FR'],
    'routes' => [
        ['GET', '/me', 'level' => 0, 'summary' => 'Who is calling'],
        ['GET', '/notes', 'notes:read', 'level' => 1, 'resource' => 'note:*', 'summary' => 'List your notes'],
        ['POST', '/notes', 'notes:write', 'class' => 'write', 'level' => 1, 'resource' => 'note:new',
            'summary' => 'Add a note', 'body' => ['text' => 'the note']],
        ['DELETE', '/notes/{id}', 'notes:delete', 'class' => 'write-hard', 'level' => 2, 'resource' => 'note:{id}',
            'summary' => 'Delete a note'],
    ],
    'templates' => [
        'notes:read' => 'Read your notes',
        'notes:write' => 'Write new notes',
        'notes:delete' => 'Delete note {scope}',
    ],
    'key_file' => env('ALLOWEDBY_KEY_FILE', storage_path('app/allowedby-keys.json')),
    'store' => env('ALLOWEDBY_STORE', 'apcu'),  // "redis" on several servers
    'redis_connection' => 'default',
    'refresh_seconds' => (int) env('ALLOWEDBY_REFRESH_SECONDS', 5),
    'title' => 'Notes Interop API',
    'global' => true,
];
```

The example serves `routes/api.php` without Laravel's `/api` prefix (`apiPrefix: ''` in `bootstrap/app.php`). With
the default prefix, write `/api/notes` in the map: the map holds the paths the router matches. From `examples/frameworks/laravel/routes/api.php`:

```php
<?php

declare(strict_types=1);

/*
 * routes/api.php of the notes API (bootstrap/app.php serves it without the /api prefix: `apiPrefix: ''`). The
 * package checked each request on the route map before routing: $request->allowedby() is the accepted context, null
 * outside the map. A protected handler refuses without one, so a route left off the map fails closed.
 */

use AllowedBy\AllowedBy;
use AllowedBy\Context;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

// the SDK's own refusal (400 invalid_request), as everywhere else: not a challenge an agent would answer
$refuse = static function (): never {
    $r = AllowedBy::notOnTheMap();
    abort(response($r->body, $r->status, $r->headers));
};
$context = static fn (Request $request): Context => $request->allowedby() ?? $refuse();

Route::get('/health', static fn (): array => ['ok' => true]);

Route::get('/me', static function (Request $request) use ($context): array {
    $context = $context($request);

    return ['agent' => $context->agent, 'operator' => $context->operator, 'level' => $context->level];
});

Route::get('/notes', static fn (Request $request, Notes $notes): array => [
    'notes' => $notes->list($context($request)->humanId ?? throw new LogicException('no person at level 0')),
]);

Route::post('/notes', static function (Request $request, Notes $notes) use ($context): JsonResponse {
    $text = $request->json('text');
    if (!is_string($text) || 1 !== preg_match('/\A.{1,2000}\z/su', $text)) {
        return response()->json(['error' => 'text: a string of 1 to 2000 characters'], 400);
    }

    return response()->json(['id' => $notes->add($context($request)->humanId ?? throw new LogicException('no person at level 0'), $text)['id']], 201);
});

Route::delete('/notes/{id}', static function (Request $request, Notes $notes, string $id) use ($context): array {
    $notes->delete($context($request)->humanId ?? throw new LogicException('no person at level 0'), $id);

    return ['deleted' => $id];
});
```

With `'global' => false`, add the middleware alias yourself: `Route::middleware('allowedby')->group(...)`. The
routes of the map must then all be inside that group; the discovery documents are served only on the paths the
middleware covers.

### Symfony 7 and 8

Register `AllowedBy\Symfony\AllowedByBundle` in `config/bundles.php`, then configure it. `ALLOWEDBY_REFRESH_SECONDS` has a default in the example's `framework.yaml` (`env(ALLOWEDBY_REFRESH_SECONDS): '5'`);
without it, set the variable or write a number. From
`examples/frameworks/symfony/config/packages/allowedby.yaml`:

```yaml
# config/packages/allowedby.yaml of the notes API (bundle: AllowedBy\Symfony\AllowedByBundle)
allowedby:
    origin: '%env(ALLOWEDBY_ORIGIN)%'
    node: '%env(ALLOWEDBY_NODE)%'
    org: { legal_name: Notes Interop Ltd, country: FR }
    routes:
        - { method: GET, path: /me, level: 0, summary: Who is calling }
        - { method: GET, path: /notes, capability: 'notes:read', level: 1, resource: 'note:*', summary: List your notes }
        - { method: POST, path: /notes, capability: 'notes:write', class: write, level: 1, resource: 'note:new', summary: Add a note, body: { text: the note } }
        - { method: DELETE, path: '/notes/{id}', capability: 'notes:delete', class: write-hard, level: 2, resource: 'note:{id}', summary: Delete a note }
    templates:
        'notes:read': Read your notes
        'notes:write': Write new notes
        'notes:delete': Delete note {scope}
    key_file: '%env(ALLOWEDBY_KEY_FILE)%'   # private, outside public/
    store: apcu                             # or the id of a service implementing AllowedBy\Store\Store (a RedisStore)
    refresh_seconds: '%env(int:ALLOWEDBY_REFRESH_SECONDS)%'
    title: Notes Interop API
```

From `examples/frameworks/symfony/src/Controller/NotesController.php`:

```php
<?php

declare(strict_types=1);

namespace App\Controller;

use AllowedBy\Context;
use AllowedBy\Symfony\AllowedByContext;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

/** The bundle checked the request before routing; the resolver gives the accepted context. */
final class NotesController
{
    public function __construct(private readonly \Notes $notes)
    {
    }

    #[Route('/health', methods: ['GET'])]
    public function health(): JsonResponse
    {
        return new JsonResponse(['ok' => true]);
    }

    #[Route('/me', methods: ['GET'])]
    public function me(#[AllowedByContext] Context $ctx): JsonResponse
    {
        return new JsonResponse(['agent' => $ctx->agent, 'operator' => $ctx->operator, 'level' => $ctx->level]);
    }

    #[Route('/notes', methods: ['GET'])]
    public function list(#[AllowedByContext] Context $ctx): JsonResponse
    {
        return new JsonResponse(['notes' => $this->notes->list($ctx->humanId ?? throw new \LogicException('no person at level 0'))]);
    }

    #[Route('/notes', methods: ['POST'])]
    public function add(#[AllowedByContext] Context $ctx, Request $request): JsonResponse
    {
        $text = json_decode($request->getContent(), true)['text'] ?? null;
        if (!\is_string($text) || 1 !== preg_match('/\A.{1,2000}\z/su', $text)) {
            return new JsonResponse(['error' => 'text: a string of 1 to 2000 characters'], 400);
        }

        return new JsonResponse(['id' => $this->notes->add($ctx->humanId ?? throw new \LogicException('no person at level 0'), $text)['id']], 201);
    }

    #[Route('/notes/{id}', methods: ['DELETE'])]
    public function delete(#[AllowedByContext] Context $ctx, string $id): JsonResponse
    {
        $this->notes->delete($ctx->humanId ?? throw new \LogicException('no person at level 0'), $id);

        return new JsonResponse(['deleted' => $id]);
    }
}
```

The bundle's subscriber runs on `kernel.request` before the router (priority 256). A controller argument typed
`Context` or marked `#[AllowedByContext]` receives the context; a non-nullable one on a request without a context
is refused with 403, so a handler never runs unchecked.

### Plain PHP

`$aby->processGlobals()` reads `$_SERVER` and `php://input`; `$decision->response->send()` answers. `context` is null
outside the route map: nothing was checked there, so serve only your own public paths. There is no router: dispatch
on `$context->route`, and take the path's values from `$context->params`, never from `$_SERVER['REQUEST_URI']`: the
example's `case 'DELETE /notes/{id}':` deletes `$context->params['id']`, the id the SDK checked. See [Quick start](#quick-start) and `examples/frameworks/plain/`.

## The context

An accepted request on the route map carries an `AllowedBy\Context`, read-only:

| Field | Type | Meaning |
|---|---|---|
| `agent` | string | The agent: its passport's `sub` (`did:oaid:...`). |
| `operator` | string | Who runs the agent: its verified domain, or a node-scoped id. |
| `humanId` | ?string | The person's pairwise id for your origin: stable, different at every service. Null at level 0. |
| `level` | int | 0 agent only, 1 passkey, 2 verified identity, 3 eIDAS high: the lowest of the grant, the registration and the node's cap. |
| `capabilities` | list<string> | The grant's capabilities. |
| `display` | ?array | What the person approved: `summary`, `lines`, `lang`. |
| `gid`, `rev`, `jti` | ?string, ?int, ?string | The grant's id, revision and document id. |
| `chain` | list | `[{gid, rev}]`, leaf first, for delegated (sub-agent) grants. |
| `route` | string | The route of the map that matched, `"DELETE /notes/{id}"`. |
| `params` | array<string, string> | The route's path values as the SDK checked them: each `{name}` of the template, from the normalised path, percent-decoded once (`/t/acme%20co` gives `['tenant' => 'acme co']`; `%2520` gives `%20`). Bytes that are not UTF-8 (`%FF`) give U+FFFD. Empty for a route without parameters. Act on these, never on your own reading of the raw path, which can differ (`/t/%61cme%2a` is checked as `/t/acme%2A`, and gives `acme*`; dot segments are refused). |
| `proofJti`, `run`, `call` | ?string, ?string, ?int | The proof's id and the agent's own run and call ids, for your audit log. |
| `humanIss` | ?string | The person's home node. |
| `linkedAccount` | ?string | On a `requireLink` route, the account the person is linked to (the one the path names, when it names one); null on other routes. Act for this account only. |
| `actingFor`, `tenant` | null | Company mandates and tenants are not supported by this SDK yet. |

Where to read it: `$decision->context` (plain PHP), the request attribute `allowedby.context` (PSR-15),
`$request->allowedby()` (Laravel), a `Context` controller argument (Symfony).

## Production

Use a key file, a shared store, https, and refresh the node cache on a timer if your traffic has quiet periods.

**Keys (`keyFile`).** The signing key signs your organisation profile and the approvals your service asks for; the
grant then records its `kid` as `initiator`, so it must stay the same across requests and servers. `keyFile` is
created on first use with mode 0600, atomically (the first writer wins), in the same JSON format as Python's
`load_keys`: one file serves every SDK. The folder needs hard links: on a file system without them the first start
fails and says so; create the file elsewhere and point `keyFile` at it, or write it from your secret manager. An
existing file works anywhere. Keep it outside the web root, back it up, share it between servers (a
secret manager mounted as a file). `keyFile` is required, except with a `MemoryStore` (tests, one process),
where a key is created for the process's lifetime.

**Shared store.** PHP shares nothing between requests, so the replay set, single-use consumption, counters and the
node cache must be shared:

| Store | When | Notes |
|---|---|---|
| `new ApcuStore()` | one machine (PHP-FPM, `php -S` with workers: both run in CI) | the default when APCu is enabled; size `apc.shm_size` (about 300 bytes per request kept 300 s); it refuses writes when nearly full rather than let APCu wipe the replay set |
| `new RedisStore($redis)` | several machines | phpredis `\Redis` or `Predis\Client`; set `maxmemory-policy noeviction` |
| `new MemoryStore()` | tests, single-process long-running servers | only when you pass it: several workers would each keep their own replay set, so it is never a default |

Without `store`, the SDK uses `ApcuStore` when APCu is enabled and otherwise fails at construction. A store error
refuses the request with `503 status_stale` and `Retry-After` (fail closed).

**Refunds** (CONTRACT §2 item 10, ABY-2 §5 step 9). The check spends the approval: a single-use grant's mark and its
`count` and `amount` totals. When the SDK itself then refuses that accepted request before its handler starts, it
gives back exactly what the request spent, once, from a receipt the check kept, so the approval serves the request on
its own route afterwards. That covers the route guard of Laravel (`RouteMatched`, and the `allowedby` route
middleware), Symfony's listener after the router, and PSR-15's `RequireContext`: the handler guard of rule 5 and a
method or path changed after the check. It also covers the account-linking endpoint's refusals after the approval
(a code already used, links full or busy, no person). Nothing is refunded once the handler was reached, for a refusal
of your own (a handler, a middleware or a listener that answers), or when the endpoint may have linked (a store
failure while the link was written). A refunded request never reaches a handler, even dispatched again. A refund the
store does not take leaves the approval spent, and is logged without request data. A store refunds with `Charge`s of
negative increments and no `max`, applied exactly, so a counter may read below 0 (`Store::charge`). Adapters call
`$aby->release($context)` and `$aby->started($context)`; an app does not need to.

**Refresh.** Node statements and status lists are fetched in the background, never on the request path (ARCH-1).
PHP has no background thread, so the SDK refreshes lazily: a request that finds the cache older than
`refreshSeconds` (default 5, at most 60) schedules a refresh after its response (a shutdown function; Symfony and
Laravel flush the response first with `fastcgi_finish_request()`). One process at a time refreshes, under a lock in
the store; all others keep serving from the cached copy. Only an empty cache is filled inline, once. The trade-off
against a background thread (CONTRACT §2.6): after a quiet period the first request sees an old status list. That
stays safe, since lists carry their own time and a list older than its class allows is refused (`status_stale`,
60 s for write-hard and irreversible, 3600 s otherwise), but serious routes then answer 503 once. To avoid it,
call `$aby->refresh()` on a timer: a console command run by cron every minute (or every few seconds from a loop)
that builds your `AllowedBy` the way your app does and calls `refresh()`; it writes to the same shared store.
In long-running workers (Octane, RoadRunner, Swoole, FrankenPHP), where shutdown functions do not run per request, the
refresh is inline under the lock; that is automatic on the `cli` and `frankenphp` SAPIs, and `deferRefresh`
(`defer_refresh` in Laravel and Symfony) forces either mode. CI runs PHP's server with workers, PHP-FPM with nginx,
and RoadRunner; Octane, Swoole and FrankenPHP are not run.

**Startup (a cold cache, CONTRACT §2 item 4).** A service that starts cold (a new instance, one that scales to zero,
an emptied store) must hold node statements and status lists before its first request, without fetching at request
time (ARCH-1 §4). What that means depends on how PHP runs:

| Mode | What the SDK does at start | What you do |
|---|---|---|
| Long-running worker (the `cli` SAPI: RoadRunner, Octane, Swoole; or a FrankenPHP worker script, `FRANKENPHP_WORKER`) | `new AllowedBy(...)` runs the first refresh before it returns: over, done or failed, within `AllowedBy::STARTUP_WAIT` (5 s: with ext-curl each fetch, from connecting to its last byte, gets what is left of it; without it, PHP's stream wrapper bounds connecting and each read of the headers separately, so a node that drips its headers can hold the start longer). A cache another process refreshed less than `refreshSeconds` ago is used as it is; while another worker holds the refresh lock, it serves a stale copy at once, and waits for that worker's copy only when the cache is empty, so workers that start cold together fetch once. A node that does not answer delays the start by at most 5 s, and the worker then serves from what it has (fail closed); a refresh cut short there never replaces a complete cached copy, and a first fill cut short stays stale, so the next refresh completes it. | Build the SDK when the worker starts, before its request loop, as `slim/worker.php` does through `app.php`. Laravel Octane: list `AllowedBy\AllowedBy::class` in `config/octane.php` `warm`. A framework that builds its services on the first request (Symfony's runtime in worker mode) builds the SDK then, and that request waits. |
| PHP-FPM, Apache `mod_php`, PHP's server, FrankenPHP's classic mode | Nothing: every request builds the SDK, so there is no start to wait at, and no request waits for another one's refresh. | Fill the cache before traffic: run your refresh command (the cron job above) once in the deploy, after the store is up and before the instance takes requests. With `RedisStore` it fills the cache every instance reads. (That command runs on the `cli` SAPI, where building the SDK refreshes a stale cache: build it there with `deferRefresh: true`, since `refresh()` fetches anyway.) |

What is left of a cold start. With `ApcuStore` under PHP-FPM no step before traffic can fill the cache: APCu memory
belongs to the FPM master, and a CLI process (`php refresh.php`) has its own. The first request after an FPM restart
then fills the empty cache inline, under the lock, and requests that arrive while it does are refused
(`untrusted_node`, fail closed). That fill, and the inline refresh of a long-running worker whose request finds the
cache stale (above), are the fetches at request time this SDK keeps, since PHP has no thread to move them to; use
Redis when cold starts are frequent (a service that scales to zero). In tests, pass `deferRefresh: true`
(`defer_refresh: true` in Laravel and Symfony), so that building the SDK on the `cli` SAPI does not fetch from the node.

**Trust.** By default the SDK trusts the one `node` you configure, pinning its key on first use (TOFU); a changed
key is refused and logged. For several nodes, programs and vouching, pass a signed OAID-5 trust list:
`trustList: TrustList::load('/etc/allowedby/trust.jwt', $yourPublicJwk)`.

**Logging.** Pass a PSR-3 `logger:`. It gets one `info` line per checked request (`[host] GET /notes -> accepted`)
and a `warning` on each failed refresh (`[verifier] refresh failed: ...`). Without one, warnings go to
`error_log()`. No token, key or body is ever logged.

**Several instances** need the same `keyFile`, the same Redis store, and the same `origin` (what agents sign).
Behind a proxy the SDK ignores `Forwarded` and `X-Forwarded-*`: the URL is always built from `origin`.

**Path and method variants (CONTRACT §2.10).** Routers decode the path before matching, and some apply method
overrides, so a variant could reach a protected handler around the route map. The SDK refuses with 400 a request that
could: dot segments (percent-encoded or not), an encoded `/` or `\` (`%2F`, `%5C`), a doubled `/`, or an encoded
spelling whose decoded path is a route of the map; and, on a path of the map, `X-HTTP-Method-Override`,
`X-HTTP-Method`, `X-Method-Override`, a `_method` query parameter, or (PSR-15) a `_method` form field. Other requests
pass unchanged. Under Laravel and Symfony the method checked is the one the router dispatches (`getMethod()`). A
trailing `/` is the same route (checked). Neither adds format suffixes (`/notes.json`) unless your routes declare
`{_format}`: list such paths in the route map.

**Base paths and wide patterns.** The proof is checked against the full path the agent signed; routes are matched on
the path your router sees, so the map never holds the prefix the app is served under: such a map is refused with 400.
Laravel and Symfony give the prefix; plain PHP uses `PATH_INFO` when the server sets it; with PSR-15, give the prefix
your router strips (Slim's `setBasePath`) as the middleware's `basePath`.

A router can send a path that is not on the map to a protected handler (`{id:.*}` takes `/notes/7/x`). Laravel and
Symfony see the route the router chose: when it is a route of the map (same template and method, whatever the patterns)
and the request was not checked for it, the answer is 400. A handler for several methods counts for each of them, and the handler of a mapped route is refused under any other route
(`/notes/{id}/archive/{rest}` with `where('rest', '.*')` next to a mapped `/notes/{id}/archive`). PSR-15
and plain PHP do not see it, so in the mapped method they refuse a path that matches a template when a parameter takes
several segments, or a format suffix (`/notes.json`). `/notes/7` is served when only `/notes` is mapped. List your own
such pages, which the log also names: `unprotected: ['/notes.json', ['GET', '/notes/{id}/comments']]` (in the
configuration of Laravel and Symfony too). An entry is exact, or a template of whole-segment parameters with a
literal segment, which names its method when a mapped route could reach it; one that overlaps the map, or that a
router may read as another path, fails at construction. Laravel and Symfony never let an entry run the handler of a
mapped route. Under PSR-15, also put `RequireContext` on protected routes: it covers a pattern
that leaves a segment out (`/notes[/{id}]`). Under PSR-15 and plain PHP, a wide route after a protected route that ends
in a literal (`/notes/{id}/archive/{rest:.*}` running the handler of `/notes/{id}/archive`) is not refused: the SDK
cannot see the handler, so do not give such a route the handler of a protected one, or put `RequireContext` on it. Control characters in a protected path are refused everywhere.

Catch-alls (CONTRACT §2.10 rule 5). Laravel and Symfony also ask the router which rule it picks for sample paths of
each mapped route (`/notes/1`, `/notes/a`, `/notes/<uuid>`), and refuse a handler of a mapped route in any method,
OPTIONS included (an OPTIONS request Laravel answers itself, with no rule of yours, runs no code of yours and is
served). A handler that also serves the sample path with one of its words replaced is a catch-all: site-wide when the
router picks it for the path with its first word replaced through a rule that takes the whole path
(`Route::fallback()`, `/{any}` with `where('any', '.*')`, `/{path<.+>}`), under the route's prefix otherwise
(`/notes/{id}/{rest}`). A route's own handler is known from a rule of its shape, or from a handler a sample reaches
that is no catch-all. Once it is known, a site-wide catch-all keeps serving your other pages and one under the prefix
stays protected; a request checked for the route that the router sends through either is refused. While it is not
known, every request near the route is refused unless checked, and a catch-all found for it is protected; when one
catch-all is its only handler (a front controller), a request checked for the route runs it only if the route covers
every other route that catch-all is protected for (same capability, resource and amount fields, a level, tier and
class at least theirs, a grant no longer, every option they require), and the log says `route X is served only by a
site-wide catch-all` when the map is built. One handler (a closure, or a controller method) for two mapped routes, the
same path in two methods (`Route::match(['GET', 'POST'], ...)`, `methods: ['GET', 'POST']`) or two paths
(`DELETE /notes/{id}` and `DELETE /items/{id}`), runs only for a request checked for a route that covers the other;
otherwise the answer is 400, "map both at the same capability and level, or give each its own handler", and the log
names the pair when the map is built. Separate closures or controller methods are not affected. Nothing is learnt
from requests (PHP keeps nothing between them): give each mapped route its own rule. A site-wide catch-all that
dispatches actions itself, on paths no route maps (`/{any}` reading `?action=delete`), is not seen: map those actions,
or give them rules of their own. Under PSR-15, `RequireContext` reads the route Slim (`__route__`) or Mezzio
(`RouteResult`) chose, and refuses a request checked for a route of another shape, so on a catch-all it runs for no
checked request; a router it cannot read is the limit above.

After acceptance. The SDK records the method and the normalised path an accepted request was checked for. A rewrite
rule or a method override placed after it that moves the request (`GET /me` to `GET /health`, or to `HEAD /me`) would
run a handler on values the person never approved, so the request is refused with 400 before any handler runs. The
path is never repeated in the refusal. Laravel checks it when the router picks the route, Symfony once its router has
run, and PSR-15 in `RequireContext`. Another spelling of the same path (`/%6De` for `/me`) is the same request, and
so is a Mezzio pipeline that only took its prefix off the path (`pipe('/api', ...)`: `/me` for `/api/me`), when you
declare that prefix (`AllowedByMiddleware`'s base path counts; another one: `new RequireContext($responses, $streams, ['/api'])`). Nothing on the request shows which
middleware took a prefix off, so an undeclared one is refused as a move. The
limits: under PSR-15 without `RequireContext` nothing sees the request after the SDK. Plain PHP has no router after
the SDK, and your code dispatches on `$context->route` and `$context->params`, so do not rewrite the request there.
A Symfony listener that runs after the router (priority below 16) is not seen either.

## Agents

The PHP SDK is a service SDK only. To build an agent, use the Python or TypeScript agent SDK
([docs/sdk/python.md](https://docs.allowedby.com/sdk/python), [docs/sdk/js.md](https://docs.allowedby.com/sdk/js)); they work against any service, PHP included.

## Errors

Every refusal is `application/problem+json` (RFC 9457) with `type` `https://allowedby.org/errors/<code>`. Codes and
statuses are the same in every SDK (ABY-2 §6):

| Code | Status | Meaning | What to do |
|---|---|---|---|
| `invalid_request` | 400 | Malformed headers, a body that is not a JSON object on a route of the map, or a typ mix. | Fix the request. |
| `passport_required` | 401 | No `Allowed-By` header. | The agent gets a passport from its node and retries. |
| `invalid_signature` | 401 | A signature, proof, chain link or WebAuthn check failed, or the proof was replayed. | Never retried as is; the agent signs a new proof. |
| `untrusted_node` | 401 | Signed by a node this service does not trust (or the node cache is empty). | Check `node` / the trust list; wait for the first refresh. |
| `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses. | The node operator fixes its witnesses. |
| `grant_required` | 401 | A person's approval is needed: the challenge says what to ask for. | The agent asks the person (service-initiated: the `approve` link). |
| `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, single-use digest, initiator). | Ask for a wider approval. |
| `level_insufficient` | 401 | The person's identity level is too low. | The person verifies their identity on the node. |
| `qes_required` | 401 | The route needs a qualified signature. | Not available with this SDK. |
| `authority_required` | 401 | Co-approvers are needed. | Not used by this SDK. |
| `mandate_required` | 401 | A company mandate is needed, or the grant acts for a company. | Not supported by this SDK. |
| `expired` | 401 | The grant has expired. | Ask again. |
| `not_yet_valid` | 401 | The grant's `nbf` is in the future. | Check clocks. |
| `revoked` | 401 | The person withdrew the approval (status list). | Ask again. |
| `actor_expired` | 401 | The agent's key expired; the problem says `rebind: true`. | The agent rebinds its grant (ABY-2 §9). |
| `class_lifetime_exceeded` | 401 | The grant lasts longer than the route's class allows. | Ask for a shorter approval. |
| `single_use_consumed` | 401 | A one-time approval was already used. | Ask again. |
| `capability_denied` | 403 | Not allowed here (no such route for credentials). | Nothing to retry. |
| `tier_insufficient` | 403 | The agent's key custody or the passkey class is too weak. | Use a stronger key or passkey. |
| `human_not_linked` | 403 | The person is not linked to the account the route names (`requireLink`). | Link the account ([Account linking](#account-linking)). |
| `budget_exceeded` | 403 | A budget is used up. | Not used by this SDK. |
| `rate_limited` | 429 | Too many calls from this agent or its operator (see Rate limits); `Retry-After` is set. | Retry after a minute. |
| `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (depth 1: a root and one child, ABY-2 §2). | Send a shorter chain. |
| `status_stale` | 503 | The revocation list is too old; `Retry-After` is set. | Retry after a few seconds. |

A shared store that cannot answer is also `status_stale` (503, `Retry-After: 5`): the request is refused, never let
through. A body over 1 MiB on a route of the map is `invalid_request` with 413.

## Testing

`php tests/run-vectors.php` runs the 453 CONF-1 vectors; `vendor/bin/phpunit` the unit and framework tests; the
framework examples run against a real node.

```bash
cd sdks/php
composer install
php tests/run-vectors.php          # 453/453 cases passed
vendor/bin/phpunit
vendor/bin/phpstan analyse && vendor/bin/php-cs-fixer check
```

The framework examples against a real node (Linux and macOS: PHP's built-in server has no workers on Windows, use WSL
there), from the repository root. `frameworks.py` without a name runs all of them; that also needs nginx, PHP-FPM,
RoadRunner and Redis:

```bash
pip install -r requirements.txt
python sdks/php/examples/frameworks.py plain
```

**Testing your own app without a browser.** In unit tests, give the SDK a fixed clock and a `MemoryStore`, and send
it requests signed like the vectors do: `tests/Support/Fixture.php` builds a service from `vectors/service.json` and
replays signed requests from the vector files (a passport on `GET /me`, a grant on a comment route). Your handlers
then receive a real `Context`. For an end-to-end test, run your app against the local node and the reference agent
as the interop test does: the harness plays the person with a software passkey.

## Reference

Namespace `AllowedBy`. Classes marked internal are not part of the public API.

| Name | What |
|---|---|
| `route(string $method, string $path, ?string $capability = null, string\|array $class = 'read', int $level = 1, ?string $resource = null, ?string $amountField = null, string $currencyField = '/currency', ?string $authn = null, int $tier = 0, ?int $maxLifetime = null, ?string $summary = null, ?array $body = null, ?string $levelProfile = null, bool $qes = false): Route` | One line of the route map. |
| `Route::fromArray(array $a): Route` | The same from a config array (positional `method, path, capability` allowed). |
| `new AllowedBy(origin, node, org, routes, templates, keyFile?, store?, trustList?, refreshSeconds = 5, nodeMaxLevel = 3, clock?, title?, version = '1.0.0', description?, rfc9421 = false, http?, logger?, deferRefresh?, signingKey?)` | The SDK. Throws `InvalidArgumentException` on bad configuration. |
| `AllowedBy::process(method, path, headers, body = '', query = ''): Decision` | Discovery, then the check: what adapters call. |
| `AllowedBy::processGlobals(): Decision` | `process()` from `$_SERVER` and `php://input`. |
| `AllowedBy::check(...)`, `AllowedBy::handle(method, path): ?Response` | The check alone; the discovery endpoints alone. |
| `AllowedBy::refresh(): void` | Fetch node statements and status lists now. |
| `AllowedBy::wellKnown()`, `openapi()`, `apiCatalog()`, `orgProfile()`, `publicKey()` | The published documents. |
| `Decision` | `?Context $context`, `?Response $response`, `allowed(): bool`. |
| `Response` | `int $status`, `array $headers`, `string $body`, `send()`, `code()`, `data()`. |
| `Context` | [The context](#the-context). |
| `Reject` | A refusal inside the verifier: `error` (the code), `status`, `why`. `Reject::STATUS` maps codes to statuses. |
| `Config::build(array $config): AllowedBy` | The SDK from a snake_case config array (Laravel, Symfony). |
| `KeyFile::load(string $path)` | Read or create the key file. |
| `SigningKey` | `generate()`, `fromSeed()`, `fromPem()`, `toPem()`, `kid()`, `jwk()`. |
| `Store\Store` | `add`, `get`, `charge` (with `Store\Charge`), `fetch`, `save`, `lock`, `unlock`. |
| `Store\MemoryStore`, `Store\ApcuStore`, `Store\RedisStore` | The stores ([Production](#production)). `Store\StoreException` on failure. |
| `Trust\TrustList` | `new TrustList($jws, $serviceJwk)`, `TrustList::load($path, $serviceJwk)` (OAID-5). |
| `Http\HttpClient`, `Http\CurlHttpClient`, `Http\StreamHttpClient` | Outgoing calls (refresh, approvals): curl when it is loaded, the stream wrapper otherwise; replace for a proxy. |
| `Psr15\AllowedByMiddleware` | PSR-15 middleware; attribute `allowedby.context`. |
| `Laravel\AllowedByServiceProvider`, `Laravel\Middleware` | Laravel package; alias `allowedby`; `$request->allowedby()`. |
| `Symfony\AllowedByBundle`, `Symfony\AllowedByContext`, `Symfony\RequestSubscriber`, `Symfony\ContextValueResolver` | Symfony bundle. |
| `Verifier`, `Trust\*` (except `TrustList`), `Internal\*` | Internal. |

## Account linking

ABY-3 §6: a person links their AllowedBy identity (their home node and their pairwise id for your origin) to one of
your own accounts, and a `requireLink` route then accepts them for that account only.

1. Your signed-in account page asks for a code and shows it: `$code = $aby->linkStart($accountId)` (valid 600 s, or
   `linkStart($accountId, $ttl)`, up to 30 days; single use; a 192-bit random nonce, sealed).
2. The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "..."}`. The SDK
   serves this route itself (capability `aby:link`, write, level 1): don't map it. An unknown, used, revoked or expired
   code is refused with 400 `invalid_request` before anything is asked of the person. Otherwise the SDK asks for a
   single-use approval of `aby:link` (it creates the approval, as for write-hard), and once it is given it links the
   person to the code's account and answers `{"linked": true}`.
3. Using a code revokes the account's other pending codes, and linking an account again moves it to the new person.
   A link names both the home node and the pairwise id: the same id from another node is another person.

Routes: `route('GET', '/accounts/{account}/notes', 'notes:read', resource: 'account:{account}', requireLink: true)`
refuses a person who is not linked, or who is linked to another account than `{account}` (403 `human_not_linked`).
Name the parameter with `accountParam` on the route, or once for the service (`new AllowedBy(..., accountParam:
'acct')`, `account_param` in the Laravel and Symfony configuration). Approvals the SDK creates for a linked account
name the person (`human_hint`, `human_home`).

A route whose path names no account (`/documents/{id}`) checks only that the person is linked. The context's
`linkedAccount` says to which account: act for that account only, for instance by loading the document only when that
account owns it. Alternatively, decide in the SDK with `new AllowedBy(..., linkAuthorize: fn (string $account, Route
$route, array $params): bool => $documents->ownedBy($params['id'], $account))`, which receives the decoded path values.
When it returns anything other than `true`, or throws, the request is refused with 403 `human_not_linked` before your handler runs. In the
Laravel configuration, `link_authorize` is an invokable class (resolved from the container); in Symfony's, the id of
such a service. `max_links` sets `maxLinks` in both.

A code is sealed (XSalsa20-Poly1305 with a 192-bit random nonce) with a key of its own, derived from your signing key
by HKDF-SHA256 (RFC 5869, info `allowedby/link/v1`; the key file every server shares), so nothing is kept per code.
Links and each account's epoch (a random token that using a code replaces, under the store's lock) live in the store,
shared by your servers as the replay set is: APCu on one machine, Redis across several. A store that loses them (a
restart, a flush, an eviction) never revives a code: the account's next epoch is new and random, so codes issued
before are unknown, and links must be made again. Pending codes are bounded: past 10 000 issued in the last ten to twenty
minutes, `linkStart` throws (a `RuntimeException`) rather than revoke a code someone holds. Links are bounded too: at `maxLinks` linked
accounts (`new AllowedBy(..., maxLinks: 100000)`, the default), linking another account is refused with 400
`invalid_request` before any approval is asked for. No one's link is evicted, and the code stays pending. Each
account has one person and each person one account: linking an account again removes the previous person's entry,
and a person who links another account unlinks the old one. `$aby->unlink($accountId)` removes an account's link when you
delete the account or the person asks to be forgotten: the stored pair, its place under `maxLinks` and the account's
pending codes (false when it was not linked; an empty account throws, as for `linkStart`). Every change of the links is journaled, so a store failure partway is
completed by the next one and never leaves a wrong count. Under Laravel the global middleware (the default) serves `POST /allowedby/link`; under Symfony and
PSR-15 the SDK answers it before the router runs. A tested app: `examples/interop_ext/`.

## AllowedBy-Nonce

ABY-2 §3.2: with `new AllowedBy(..., nonce: true)` (`nonce` in the Laravel and Symfony configuration), every
`irreversible` route, and every route with `nonce: true`, refuses a proof without a current nonce of the service with
`401 invalid_signature` and a fresh nonce in its `AllowedBy-Nonce` header; the agent retries once with it. A route with
`nonce: true` while the service has nonces off throws at construction. With the RFC 9421 proof, the nonce is the
request's `AllowedBy-Nonce` header, covered by the signature; a covered value that is not base64url is refused (401).

A nonce is stateless: base64url(`t` ‖ HMAC-SHA256(key, `t`)[0:16]), `t` its issue time in seconds (8 bytes, big
endian), current for 300 s from its issue. The key is HKDF-SHA256 of your signing key (RFC 5869: the 32-byte Ed25519
seed, no salt, info `allowedby/nonce/v1`), used for nothing else, so every server that shares the key file takes the
others' nonces, and a restart keeps them current. Nothing is stored per nonce: a nonce is single use through the
proof's own replay set (its `jti`), as every proof is.

## Level profiles

OAID-7 §5.3: a level-3 route with `levelProfile: 'eu'` or `'na'` accepts only a person whose registration's
`level_source.profile` is that profile, and refuses any other, or none, with `401 level_insufficient`. A level-3 route
without `levelProfile` accepts any level-3 registration. `levelProfile` on a route below level 3 throws at
construction.

## Rate limits

Every call is counted, per agent (the passport's `sub`) and per operator (`operator.id`), in a sliding window on the
SDK's clock: a call at `t` sees those at `x` with `t - x < seconds`. The defaults are 600 calls a minute per agent and
6000 per operator; set them with `new AllowedBy(..., rate: ['actor' => [20, 60], 'operator' => [1000, 60]])` (`rate`
in the Laravel and Symfony configuration), either or both. Any other key, or a value that is not two positive
integers, throws at construction: a misspelt limit would leave the default in place. A call over either limit is
refused with `429 rate_limited` and `Retry-After: 60`. A call counts once its proof is verified and is no replay,
whatever is decided after it (a call later refused as `grant_required` counts); a call refused by the limit counts for
neither limit.

The counts live in the store, shared by your servers as the replay set is: one small document per agent and per
operator (its calls per second over the last window), changed under the store's locks, so both limits are checked and
counted as one step. The store drops it a window after its last call (`ExpiringStore`, which `ApcuStore`, `RedisStore`
and `MemoryStore` implement; a store of your own that does not keeps it until it is replaced). A store failure refuses the call (`503 status_stale`).
