# AllowedBy for PHP # How it works Four parties take part: the **agent**, your **app**, the **person**, and a **node** that the person and your app trust. ## Three documents | Document | Who signs it | What it says | |---|---|---| | Passport | The node | Which agent this is, who operates it, and which key it holds | | Grant | The person (passkey) and the node | What the person approved, for which app, for how long, with which limits | | Proof | The agent | This request: method, address, body and time, with the agent's key | The agent sends the first two in `Allowed-By` and the proof in `AllowedBy-Proof`. ## What your app checks The SDK does all of this offline, on each request, in about a millisecond: 1. The passport or grant comes from a node you trust, is not expired, and is not withdrawn. 2. The person's passkey signed exactly this grant, and their identity level is enough for the route. 3. The proof is for this exact request, by the agent the grant names, and was never seen before. 4. The grant covers the action, the resource and the amount. 5. A serious action has an approval made for this request only, and it has not been used. Anything unknown, missing or unreadable is refused. See [error codes](https://docs.allowedby.com/errors) for each refusal. ## Levels: how sure you are of the person | Level | The person | Use it for | |---|---|---| | 0 | is not asked: only the agent is identified | Public or per-agent data | | 1 | tapped a passkey | Everyday actions | | 2 | has a verified legal identity, and tapped a passkey | Orders, contracts, anything hard to undo | | 3 | is verified at the highest level, with a hardware passkey | Payments and signatures of value | ## Classes: how serious the action is | Class | Example | Approval | |---|---|---| | `read` | List notes | Reused until it ends | | `write` | Add a note | Reused until it ends | | `write-hard` | Delete, publish | For that request, once | | `irreversible` | Pay, sign | For that request, once | For the last two, your app creates the approval itself. The agent cannot change what the person will read. ## The node A node issues passports, shows the approval page, and countersigns grants. It learns what was approved, never the data in your app. You choose which nodes to trust: one hosted node, your own, or a signed list. --- # 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 '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}`. | `:*` | | `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 '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 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 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 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 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 | 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 | 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. | | `tenant` | ?string | The tenant the route's `{tenant}` names, decoded (see Tenants); null on other routes. | | `actingFor` | null | Company mandates 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/`), 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/`. 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`). ## Tenants ORG-1 §3.3: when your API serves accounts of other companies, name them in the path (`/t/{tenant}/...`) and give each its rules with `new AllowedBy(..., tenants: [...])` (`tenants` in the Laravel and Symfony configuration), for example `['acme' => ['name' => 'Acme', 'routes' => ['orders:place' => ['amount_max' => '500.00', 'authn' => 'hardware']]]]`. An override only tightens the route of the map for that tenant: `level` (the higher counts), `authn` (the stronger), `require_link` (true wins), `max_lifetime` (the shorter), `amount_max` (the lower; above it `403 capability_denied`), `operators` (an allowlist of `operator.id`; any other operator gets `403 capability_denied`). A level-0 route (the passport only) has no capability, so no override or budget names it; `members_only` (below) covers it too. A tenant with no rule for a capability gets the route as you wrote it. The context's `tenant` names the tenant of the request. Everything else throws at construction, because a misspelt override would leave the route as loose as yours: an id outside `[A-Za-z0-9_-]{1,64}`, a key other than `name`, `routes`, `members_only`, `org` and `budgets`, a `name` that is not 1-200 characters, an `org` that is not an https origin with no path, a capability your map does not have, a value of another shape, and an override or a budget on a capability that has a route without `{tenant}` (it would never apply; the error names the route). `authority`, `authority_policy_revision` and the override `qes` belong to features this SDK does not have yet, so they throw too. `mandate: true`, and a `members_only` tenant with an `org`, ask for a company mandate on the tenant's routes. Until this SDK verifies mandates (CONTRACT: company mandates), such a tenant route refuses every request with `401 mandate_required`, without a challenge: no person is asked for an approval that could never succeed. `members_only` covers every route of the tenant, level 0 included. ## Tenant budgets ORG-1 §5.3: `tenants[t]['budgets'][capability] = ['max' => '5000.00', 'currency' => 'EUR', 'per' => 'month', 'tz' => 'Europe/Paris']` (per `day`, `week` or `month`; `tz` is UTC by default) caps what the tenant's agents may spend on that capability per calendar period. Every route with that capability needs an `amountField`, or the option throws. The SDK counts the amounts it accepts in the store, which your servers share, so the budget holds across all of them. A request whose amount is over what is left, or that has no amount in the budget's currency, is refused with `403 budget_exceeded`. That refusal comes before any challenge, so no person is asked to approve what the budget cannot pay. A refused request is not counted, and a refund (the SDK's own refusal after the check) gives the amount back. A store failure answers `503 status_stale` with `Retry-After`. --- # Error codes Every SDK answers the same codes with the same statuses; `tools/docs.py` checks this table and every language guide against the verifier. A refusal is `application/problem+json` with `type: https://allowedby.org/errors/`. A `401` that the agent can resolve also carries a challenge in `WWW-Authenticate: AllowedBy ...` (ABY-2 §6). `429` and `503` carry `Retry-After`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | 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 or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | ## How an agent reacts - **Asks the person, then retries once:** `grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`. - **Gets a new passport or rebinds:** `passport_required`, `actor_expired`. - **Waits, then retries:** `rate_limited`, `status_stale`. - **Signs again, once:** `invalid_signature` (a fresh proof; check the clock and the URL). - **Stops:** every other code. Retrying cannot succeed until someone changes something. --- # Build with an AI assistant Coding assistants integrate AllowedBy well when they read these pages rather than guess. Give them one of the following. ## The documentation as tools (MCP) ```bash claude mcp add --transport http allowedby-docs https://docs.allowedby.com/mcp ``` The assistant can then search the documentation, read a page, get a recipe in your language and look up an error. Any assistant that supports MCP over HTTP can use the same address. ## One file per language Everything needed to accept agents in one language, in one Markdown file: | Language | File | |---|---| | Python | [llms/python.txt](https://docs.allowedby.com/llms/python.txt) | | JavaScript | [llms/js.txt](https://docs.allowedby.com/llms/js.txt) | | Go | [llms/go.txt](https://docs.allowedby.com/llms/go.txt) | | Java | [llms/java.txt](https://docs.allowedby.com/llms/java.txt) | | C# | [llms/dotnet.txt](https://docs.allowedby.com/llms/dotnet.txt) | | PHP | [llms/php.txt](https://docs.allowedby.com/llms/php.txt) | | Ruby | [llms/ruby.txt](https://docs.allowedby.com/llms/ruby.txt) | | Rust | [llms/rust.txt](https://docs.allowedby.com/llms/rust.txt) | The index of every page is [llms.txt](https://docs.allowedby.com/llms.txt), and all guides together are [llms-full.txt](https://docs.allowedby.com/llms-full.txt). Any page is also Markdown at its own address with `.md` added. ## A prompt that works ```text Read https://docs.allowedby.com/llms/python.txt. Then add AllowedBy to this app: - list the routes an agent may call, and propose a capability, class and level for each; ask me before going on; - write the sentence a person will sign for each capability; - add the middleware, and key every query on the person's id from the context; - run the app, show me that a protected route answers 401, and write the tests from the "test" recipe. ``` Change `python` to your language. ## Rules an assistant must keep - Never take the person's identity from the agent's input: use the id in the verified context. - Never catch a refusal and continue. - Never log `Allowed-By`, `AllowedBy-Proof` or a request body. - Use a shared store as soon as there is more than one process, and a key file in production. - Put the middleware outside anything that rewrites the path or the method. A weekly test gives an assistant only these public pages, asks it to integrate AllowedBy in a new app, and runs the end-to-end scenarios on the result. --- # Recipes in PHP (each is run against a real node on every version) ## Quickstart A whole app that lets agents in with the person's approval. ```php require __DIR__.'/vendor/autoload.php'; use AllowedBy\AllowedBy; use function AllowedBy\route; $aby = new AllowedBy( origin: (string) getenv('ALLOWEDBY_ORIGIN'), // your app's public URL node: (string) getenv('ALLOWEDBY_NODE'), // the node you trust: people approve there org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'], routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')], templates: ['notes:read' => 'Read your notes'], // what the person approves keyFile: getenv('ALLOWEDBY_KEY_FILE') ?: throw new RuntimeException('set ALLOWEDBY_KEY_FILE'), // private ); $decision = $aby->processGlobals(); if (null !== $decision->response) { $decision->response->send(); // discovery documents, refusals and challenges exit; } if (null === $decision->context) { // not GET /notes: 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]); ``` ## See which agent is calling Know the agent and its verified operator, before any person is involved. ```php $routes[] = route('GET', '/me', level: 0, summary: 'Which agent is calling'); $app->get('/me', function (Request $request, Response $response) use ($json) { $context = $request->getAttribute('allowedby.context'); return $json($response, ['agent' => $context->agent, 'operator' => $context->operator]); }); ``` ## Let an agent read The person approves once with a passkey; the approval is reused until it expires or they withdraw it. ```php $routes[] = route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*', summary: 'List your notes'); $templates['notes:read'] = 'Read your notes'; $app->get('/notes', function (Request $request, Response $response) use ($json, $notes) { $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); return $json($response, ['notes' => $notes->list($person)]); }); ``` ## Let an agent write A change the person can undo: one approval, reused like a read. ```php $routes[] = route('POST', '/notes', 'notes:write', class: 'write', level: 1, resource: 'note:*', summary: 'Add a note', body: ['text' => 'the note']); $templates['notes:write'] = 'Add and change your notes'; $app->post('/notes', function (Request $request, Response $response) use ($json, $notes) { $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $input = json_decode((string) $request->getBody(), true); return $json($response, $notes->add($person, (string) ($input['text'] ?? '')), 201); }); ``` ## Ask before deleting A change that is hard to undo: your app asks the person for that exact request, and the approval works once. ```php $routes[] = route('DELETE', '/notes/{id}', 'notes:delete', class: 'write-hard', level: 2, resource: 'note:{id}', summary: 'Delete a note'); $templates['notes:delete'] = 'Delete {scope}'; $app->delete('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { // The person approved this exact request, and it works once. $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); if (!$notes->delete($person, $args['id'])) { return $json($response, ['error' => 'no such note'], 404); } return $json($response, ['deleted' => $args['id']]); }); ``` ## Take a payment The person approves the amount and the payee; any other amount or payee is refused. ```php $routes[] = route('POST', '/payees/{payee}/payments', 'payments:send', class: 'irreversible', level: 2, resource: 'payee:{payee}', amountField: '/amount', summary: 'Pay someone', body: ['amount' => 'a decimal string, e.g. 40.00', 'currency' => 'e.g. EUR']); $templates['payments:send'] = 'Pay {amount.max} {amount.currency} to {scope}'; $app->post('/payees/{payee}/payments', function (Request $request, Response $response, array $args) use ($json) { // The payee, the amount and the currency are the ones the person approved. $payment = json_decode((string) $request->getBody(), true); return $json($response, ['paid' => $payment['amount'], 'currency' => $payment['currency'], 'to' => $args['payee']], 201); }); ``` ## Take a high-value payment Level 3: a verified identity and a hardware passkey. Anything weaker is refused. ```php $routes[] = route('POST', '/payees/{payee}/transfers', 'transfers:send', class: 'irreversible', level: 3, authn: 'hardware', resource: 'payee:{payee}', amountField: '/amount', summary: 'Send a bank transfer', body: ['amount' => 'a decimal string, e.g. 4000.00', 'currency' => 'e.g. EUR']); $templates['transfers:send'] = 'Transfer {amount.max} {amount.currency} to {scope}'; $app->post('/payees/{payee}/transfers', function (Request $request, Response $response, array $args) use ($json) { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. $level = $request->getAttribute('allowedby.context')->level; $order = json_decode((string) $request->getBody(), true); return $json($response, ['sent' => $order['amount'], 'currency' => $order['currency'], 'to' => $args['payee'], 'level' => $level], 201); }); ``` ## Set a spending limit The person approves an amount per month once; the SDK keeps the total and refuses what goes over. ```php $routes[] = route('POST', '/orders', 'orders:place', class: 'write', level: 1, resource: 'order:new', amountField: '/total', summary: 'Place an order', body: ['total' => 'a decimal string, e.g. 60.00', 'currency' => 'e.g. EUR']); $templates['orders:place'] = 'Order for up to {amount.max} {amount.currency} per {amount.per}'; $app->post('/orders', function (Request $request, Response $response) use ($json) { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. $order = json_decode((string) $request->getBody(), true); return $json($response, ['ordered' => $order['total'], 'currency' => $order['currency']], 201); }); ``` ## Start and cancel a subscription The person approves the plan and its monthly price once; you charge it until they cancel. ```php $routes[] = route('POST', '/plans/{plan}/subscription', 'plans:subscribe', class: 'write-hard', level: 1, resource: 'plan:{plan}', amountField: '/monthly', summary: 'Subscribe to a plan', body: ['monthly' => 'the price per month, e.g. 12.00', 'currency' => 'EUR']); $routes[] = route('GET', '/subscription', 'plans:read', level: 1, resource: 'plan:*', summary: 'Your subscription'); $routes[] = route('DELETE', '/subscription', 'plans:cancel', class: 'write-hard', level: 1, resource: 'plan:mine', summary: 'Cancel your subscription'); $templates['plans:subscribe'] = 'Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel'; $templates['plans:read'] = 'See your subscription'; $templates['plans:cancel'] = 'Cancel your subscription'; $app->post('/plans/{plan}/subscription', function (Request $request, Response $response, array $args) use ( $json, $subscriptions ) { // Approved once, with the price: your billing charges it every month (Subscriptions.php) until it is cancelled. $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $input = json_decode((string) $request->getBody(), true); return $json($response, $subscriptions->start($person, $args['plan'], $input['monthly']), 201); }); $app->get('/subscription', function (Request $request, Response $response) use ($json, $subscriptions) { $subscription = $subscriptions->get($request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0')); return $subscription ? $json($response, $subscription) : $json($response, ['error' => 'no subscription'], 404); }); $app->delete('/subscription', function (Request $request, Response $response) use ($json, $subscriptions) { $subscription = $subscriptions->cancel($request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0')); return $subscription ? $json($response, $subscription) : $json($response, ['error' => 'no subscription'], 404); }); ``` ## Accept a sub-agent An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first. ```php $routes[] = route('GET', '/notes/{id}/summary', 'notes:read', level: 1, resource: 'note:{id}', summary: 'Summarise one note'); $app->get('/notes/{id}/summary', function (Request $request, Response $response, array $args) use ($json, $notes) { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and humanId is the same. $context = $request->getAttribute('allowedby.context'); $note = $notes->get($context->humanId ?? throw new LogicException('no person at level 0'), $args['id']); if (null === $note) { return $json($response, ['error' => 'no such note'], 404); } $words = count(preg_split('/\s+/u', $note['text'])); return $json($response, ['words' => $words, 'delegated' => count($context->chain) > 1]); }); ``` ## Let the person withdraw The person takes an approval back on their node; your app refuses it from the next refresh. ```php $routes[] = route('GET', '/export', 'notes:export', level: 1, resource: 'note:*', summary: 'Export your notes'); $templates['notes:export'] = 'Export your notes'; $app->get('/export', function (Request $request, Response $response) use ($json, $notes) { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. $context = $request->getAttribute('allowedby.context'); return $json($response, ['approval' => $context->gid, 'notes' => $notes->list($context->humanId ?? throw new LogicException('no person at level 0'))]); }); ``` ## Serve only the person's own data human_id is the same person every time at your app: look their data up with it. ```php $routes[] = route('GET', '/notes/{id}', 'notes:read', level: 1, resource: 'note:{id}', summary: 'Read one note'); $app->get('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { // humanId is this person's id at your app, always the same. Look up with it, never by note id alone. $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $note = $notes->get($person, $args['id']); return null === $note ? $json($response, ['error' => 'no such note'], 404) : $json($response, $note); }); ``` ## Refuse in your own handler Your rules still apply: the agent receives your status and your JSON, and can correct itself. ```php $routes[] = route('PUT', '/notes/{id}', 'notes:write', class: 'write', level: 1, resource: 'note:{id}', summary: 'Change a note', body: ['text' => '1 to 280 characters']); $app->put('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $text = (string) (json_decode((string) $request->getBody(), true)['text'] ?? ''); if (1 !== preg_match('/\A.{1,280}\z/su', $text)) { return $json($response, ['error' => 'text: 1 to 280 characters'], 422); // the agent gets this status and this JSON } $note = $notes->update($person, $args['id'], $text); return null === $note ? $json($response, ['error' => 'no such note'], 404) : $json($response, $note); }); ``` ## Test your app Run your app's tests without a browser, a phone or a node. ```php use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Slim\Psr7\Factory\ServerRequestFactory; final class AppTest extends TestCase { public function testARequestWithoutAPassportIsRefused(): void { $response = $this->get('/notes'); self::assertSame(401, $response->getStatusCode()); self::assertStringContainsString('passport_required', $response->getHeaderLine('WWW-Authenticate')); } public function testAgentsSeeTheSentenceThePersonApproves(): void { $discovery = json_decode((string) $this->get('/.well-known/allowedby')->getBody(), true); self::assertSame('Read your notes', $discovery['templates']['notes:read']['summary']['en']); } private function get(string $path): ResponseInterface { $app = require __DIR__.'/../app.php'; return $app->handle((new ServerRequestFactory())->createServerRequest('GET', $path)); } } ```