# PHP SDK

The public API of `sdks/php`, with its doc comments. Guide: [docs/sdk/php.md](https://docs.allowedby.com/sdk/php).

178 public declarations, 113 with a doc comment.

## `src/AllowedBy.php`

`sdks/php/src/AllowedBy.php`

```php
final class AllowedBy
```

The AllowedBy service SDK: one object, built once per process from your configuration.

```
    $aby = new AllowedBy(
        origin: 'https://notes.example', node: 'https://node.example.org',
        org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'],
        routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')],
        templates: ['notes:read' => 'Read your notes'],
        keyFile: '/var/lib/notes/allowedby-keys.json', store: new ApcuStore());

```
What it does (specs 0.2.14, verifier profile): serves /.well-known/allowedby, /openapi.json and
/.well-known/api-catalog; verifies every request on the route map offline (ABY-2 §5); answers 401 with a
challenge, creating the approval itself for write-hard and irreversible routes (ABY-2 §7).
Plug it into your framework with `Psr15\AllowedByMiddleware`, the Laravel package or the Symfony bundle.

```php
public const VERSION = '0.1.0'
```



```php
public const SPEC_VERSION = '0.2.14'
```



```php
public const MAX_BODY = 1 << 20
```



```php
public const STARTUP_WAIT = 5
```

Seconds a long-running worker's constructor waits for the first refresh (CONTRACT §2 item 4).

```php
public readonly string $origin
```



```php
public readonly string $node
```



```php
public readonly string $host
```

`host[:port]` of the origin: the challenge's realm.

```php
public readonly array $routes
```

- var list&lt;Route>

```php
public readonly array $templates
```

- var array&lt;string, array{summary: array&lt;string, string>, lines: array&lt;string, string>}>

```php
public readonly Verifier $verifier
```



```php
public function __construct( string $origin, string $node, array $org, array $routes, array $templates, ?string $keyFile = null, ?Store $store = null, ?TrustList $trustList = null, int $refreshSeconds = 5, int $nodeMaxLevel = 3, ?callable $clock = null, ?string $title = null, public readonly string $version = '1.0.0', public readonly ?string $description = null, bool $rfc9421 = false, ?HttpClient $http = null, ?LoggerInterface $logger = null, ?bool $deferRefresh = null, ?SigningKey $signingKey = null, ?NodeSource $nodeSource = null, array $unprotected = [], public readonly string $accountParam = 'account', ?callable $linkAuthorize = null, private readonly int $maxLinks = 100000, bool $nonce = false, ?array $rate = null, )
```

- param array&lt;string, mixed>                            $org       ORG-1 §2: legal_name, country (ISO 3166-1 alpha-2),
optional website, support, privacy_policy, logo {uri, sha256}
- param list&lt;Route|array&lt;array-key, mixed>>             $routes    the route map: `route()` or arrays of its arguments
- param array&lt;string, string|array&lt;string, mixed>>      $templates the sentence the person signs per capability:
"Read your notes", or {summary: {en: ...}, lines: {en: ...}}
- param (callable(): int)|null                          $clock     epoch seconds (tests move time)
- param list&lt;mixed>                                     $unprotected your app's own pages that look like a protected route
(CONTRACT §2.10): a path or ['GET', path], exact
("/notes.json") or a template ("/notes/{id}/comments")
- param string                                          $accountParam ABY-3 §6: the path parameter that names one of your
accounts on a requireLink route (a route's own
accountParam wins)
- param (callable(string, Route, array&lt;string, string>): bool)|null $linkAuthorize ABY-3 §6: your own authorisation
of the linked account for the resource of a
requireLink route (account, route, decoded path
values): false refuses with 403 human_not_linked
- param int                                             $maxLinks  ABY-3 §6: the most accounts linked at once; at the
bound, linking another is refused (400) before any
approval, and no one's link is evicted
- param bool                                            $nonce     ABY-2 §3.2: AllowedBy-Nonce on every irreversible route and
on routes with `nonce` (default off; a route with `nonce`
needs it on)
- param array&lt;array-key, mixed>|null                    $rate      rate limits: ['actor' => [n, seconds], 'operator' => [n,
seconds]], each optional; by default 600 and 6000 calls per
60 s

```php
public static function startsAWorker(string $sapi, array $server): bool
```

Whether building the SDK here is a long-running process's start: the `cli` SAPI (RoadRunner, Octane, Swoole, a
console command) or a FrankenPHP worker script (`FRANKENPHP_WORKER`), not FrankenPHP's classic mode.

@internal

- param array&lt;array-key, mixed> $server

```php
public function process(string $method, string $path, array $headers, string $body = '', string $query = '', ?string $routePath = null, array $mounted = [], bool $routed = false): Decision
```

Everything for one request: the SDK's own endpoints, then the check on every route of the map. Adapters call
this; the body is read once by the adapter and handed back to the app unchanged.

$path is the request path as sent (what the agent signs); $routePath, when the app is served under a base
path, is the path its router matches (Symfony's and Laravel's path info): routes are matched on it.

- param array&lt;string, string|list&lt;string>> $headers
- param list&lt;string>                       $mounted the path with the prefix of the app: a map written so is refused
- param bool                               $routed  the adapter checks the route the framework chose (`refuses()`)

```php
public function processGlobals(): Decision
```

`process()` for plain PHP (no framework): the request from `$_SERVER` and `php://input`. Send
`$decision->response` when it is set, else serve the request with `$decision->context`.

```php
public function needsBody(string $method, string $routePath): bool
```

Whether a request needs its body read: only on a route of the map (adapters read nothing elsewhere, so a large
upload to another path never reaches memory here).

```php
public function couldReach(string $routePath, bool $wide = true): bool
```

Whether the app's router could read this path as a route of the map, for some method (CONTRACT §2.10). Where the
adapter does not see the route the router chooses, a parameter may also take several segments.

```php
public function refuses(array $methods, string $template, ?Context $context, array $prefixes = []): bool
```

CONTRACT §2.10, once the framework chose a route: whether its handler must not run. It must not when it serves a
route of the map (same template, whatever its parameters' names or patterns, and one of its methods) and the
request was not checked for that route. Every parameter counts as one segment, so a catch-all of the app runs;
"{page?}" at the end may be left out, so the route also serves the path without it.

- param list&lt;string> $methods  the methods of the framework's route; empty: every method
- param list&lt;string> $prefixes what the app is served under: a map written with it must not leave a handler open

```php
public static function refusedFor(array $serves, ?Context $context): bool
```

CONTRACT §2.10 (rule 2, point 8 of the plan): a handler runs only for a request checked for one of the routes of
the map that it serves ("DELETE /notes/{id}"). An empty list: it serves none.

- param list&lt;string> $serves

```php
public function servedBy(array $methods, string $template, array $prefixes = []): array
```

The routes of the map ("DELETE /notes/{id}") that a route of the framework serves: same template, whatever its
parameters' names or patterns, and one of its methods; see `refuses()`.

- param list&lt;string> $methods
- param list&lt;string> $prefixes

- return list&lt;string>

```php
public function handlerMap(array $framework, callable $match, array $prefixes = [], int $contexts = 1): HandlerMap
```

Builds the map of handlers and logs what it says (a route served only by a site-wide catch-all): when it is
built, that is once per deploy where the adapter caches it, not on every request.

@internal for the adapters that see the route the router chose (Laravel, Symfony), which cache what it returns

- param list&lt;array{template: string, methods: list&lt;string>, handler: ?string, siteWide: bool}> $framework
- param callable(string, string, int): ?int                                                    $match
- param list&lt;string>                                                                           $prefixes

```php
public static function notOnTheMap(bool $knownHandler = false): Response
```

The refusal for a protected route that the request was not checked for.

```php
public static function bodyTooLarge(): Response
```

The refusal for a body over 1 MiB on a route of the map, given before reading it (Content-Length).

```php
public function handle(string $method, string $path): ?Response
```

The endpoints the SDK serves itself (discovery), or null when the path is not one of them.

```php
public function check(string $method, string $path, array $headers, string $body = '', string $query = '', ?string $routePath = null, array $mounted = [], bool $routed = false): Decision
```

ABY-2 §5 on one request. Paths outside the route map get a Decision with neither context nor response: your
own authentication applies to them.

- param array&lt;string, string|list&lt;string>> $headers
- param list&lt;string>                       $mounted

```php
public function linkStart(string $account, int $ttl = Linking::DEFAULT_TTL): string
```

ABY-3 §6, account linking: a one-time code for one of your accounts. Your signed-in account page calls this and
shows the code; the person gives it to their agent, which sends it to `POST /allowedby/link` with an approval of
`aby:link`. The person's AllowedBy identity is then linked to `$account`, and a `requireLink` route accepts them
for that account only.

The code is single use and valid `$ttl` seconds (at most 30 days); using it revokes the account's other pending
codes. It is sealed, not stored: its account, expiry and the account's epoch, encrypted with a key derived from
the signing key. Each account's epoch and the links live in the store (shared between your servers, as for
replays). Throws a `RuntimeException` past 10 000 pending codes.

```php
public function unlink(string $account): bool
```

ABY-3 §6: removes the link of one of your accounts, when you delete the account or the person asks to be
forgotten: the stored pair (home node, pairwise id), its place under `maxLinks`, and the account's pending
linking codes. A `requireLink` route then refuses the person (403 `human_not_linked`) until they link again.
False when the account was not linked. Throws \InvalidArgumentException for an empty account, as linkStart does,
and `StoreException` when the store fails (call it again: a removal the store left halfway is completed
first).

```php
public function release(?Context $ctx): void
```

sdks/CONTRACT.md §2 item 10, Refund on the SDK's own refusal: the SDK refused this accepted request itself,
before its handler started (the handler guard of rule 5, a method or path changed after the check, the link
endpoint's refusals after the approval). Gives back exactly what the check spent for it, once: the single-use
mark and the grant's count and amount totals, from the receipt the check kept; the approval is usable again. A
refund the store does not take leaves the approval spent (fail closed), logged without request data. Nothing is
given back for a request whose handler started (`started()`). Adapters call it; an app need not.

```php
public function started(?Context $ctx): bool
```

The adapter is about to hand this accepted request to the router's handler: from now on `release()` gives
nothing back for it. False for a request the SDK refunded: a layer dispatching it again must not reach a
handler with an approval that is usable again (that would be a second use); the adapter refuses it. True for no
context (a path outside the map).

```php
public function refresh(): void
```

Fetch the node statements and status lists now: from a cron job, a worker's timer, or a test.

```php
public function wellKnown(): array
```

- return array&lt;string, mixed> `/.well-known/allowedby` (ABY-3 §4, ORG-1 §2)

```php
public function openapi(): array
```

- return array&lt;string, mixed> OpenAPI 3.1 for the route map (ABY-3 §5.1)

```php
public function apiCatalog(): array
```

- return array&lt;string, mixed> RFC 9727 API catalog: where this origin's APIs and their descriptions are

```php
public function orgProfile(): string
```

ORG-1 §2: the signed organisation profile (`aby-org+jwt`), valid one year.

```php
public function publicKey(): array
```

The service's public signing key (published under `keys`).

- return array&lt;string, string>

```php
public function challenge(HttpRequest $req, Reject $rej): Response
```

The refusal for a rejected request: plain problem JSON for policy refusals, a challenge (ABY-2 §6) when an
approval can fix it, and for write-hard and irreversible routes the approval the service creates itself (§7).

@internal public for the conformance runner

## `src/Config.php`

`sdks/php/src/Config.php`

```php
final class Config
```

Builds the SDK from a plain configuration array (the Laravel config file, the Symfony bundle's configuration):
the keys are the `AllowedBy` constructor's arguments in snake_case, plus `store`.

`store`: a `Store` instance, or "apcu", "memory", or "redis" (with `redis`: a connected \Redis or Predis client).
`trust_list`: a path to the signed trust list file, with `trust_list_key` (the public JWK that signed it).

```php
public static function build(array $c): AllowedBy
```

- param array&lt;array-key, mixed> $c

```php
public static function store(mixed $store, mixed $redis = null): ?Store
```



## `src/Context.php`

`sdks/php/src/Context.php`

```php
final class Context
```

What the handler learns from an accepted request (CONTRACT §2.7, ORG-1 §4.1, ABY-2 §5 step 10). Read-only.

On a level-0 route (the agent's passport only) there is no person: `humanId` is null and `level` is 0.

```php
public function __construct( public readonly string $agent, public readonly string $operator, public readonly ?string $humanId, public readonly int $level, public readonly array $capabilities, public readonly ?string $gid = null, public readonly ?int $rev = null, public readonly ?string $jti = null, public readonly ?array $display = null, public readonly ?array $actingFor = null, public readonly ?string $tenant = null, public readonly string $route = '', public readonly array $chain = [], public readonly ?string $proofJti = null, public readonly ?string $run = null, public readonly ?int $call = null, public readonly ?string $humanIss = null, public readonly array $params = [], public readonly ?string $linkedAccount = null,
```

- param list&lt;string>                                                 $capabilities the grant's capabilities
- param array{summary?: string, lines?: list&lt;string>, lang?: string}|null $display  what the person approved
- param list&lt;array{gid: string, rev: int|null}>                      $chain        the grant chain, leaf first
- param array&lt;string, mixed>|null                                    $actingFor
- param array&lt;string, string>                                        $params       the route's path values as checked

```php
public function toArray(): array
```

- return array&lt;string, mixed> every field, for logs and JSON

## `src/Decision.php`

`sdks/php/src/Decision.php`

```php
final class Decision
```

The outcome of `AllowedBy::process()` for one request, one of three:
- `response` set: send it as is (a discovery document, or a refusal with its challenge);
- `context` set: the request is on the route map and allowed; give the context to the handler;
- neither: the path is not on the route map (or not AllowedBy's): it reaches the app unchanged, with no context.

```php
public function __construct( public readonly ?Context $context = null, public readonly ?Response $response = null, )
```



```php
public function allowed(): bool
```



## `src/Http/CurlHttpClient.php`

`sdks/php/src/Http/CurlHttpClient.php`

```php
final class CurlHttpClient implements HttpClient
```

HTTP with ext-curl, the default when it is loaded: the timeout bounds the whole call (connecting, TLS, headers and
body; DNS too, with libcurl's threaded or c-ares resolver), which PHP's stream wrapper cannot do, so a worker's
start ends within AllowedBy::STARTUP_WAIT (CONTRACT §2 item 4). Same rules as `StreamHttpClient`: http and
https only, no redirects, certificates verified, a response size limit.

```php
public function request(string $method, string $url, ?string $body = null, array $headers = [], int $timeout = 5): array
```



## `src/Http/HttpClient.php`

`sdks/php/src/Http/HttpClient.php`

```php
interface HttpClient
```

The SDK's few outgoing calls: node statements and status lists (refresh) and the service-initiated approval
(ABY-2 §7). Replace it to add a proxy or your own HTTP stack.

```php
public function request(string $method, string $url, ?string $body = null, array $headers = [], int $timeout = 5): array
```

- param array&lt;string, string> $headers

- return array{status: int, body: string}

- throws \RuntimeException when the call fails (network, timeout, response too large)

## `src/Http/StreamHttpClient.php`

`sdks/php/src/Http/StreamHttpClient.php`

```php
final class StreamHttpClient implements HttpClient
```

HTTP with PHP's own stream wrapper (no extension needed): http and https only, no redirects, a timeout and a
response size limit (1 MiB), certificates verified. The default without ext-curl. Its limit: the wrapper applies
the timeout to connecting and to each read of the headers, not to the whole call, so a node that drips its
headers can hold a call longer (`CurlHttpClient` bounds the whole call).

```php
public const MAX_RESPONSE = 1 << 20
```



```php
public function request(string $method, string $url, ?string $body = null, array $headers = [], int $timeout = 5): array
```



## `src/KeyFile.php`

`sdks/php/src/KeyFile.php`

```php
final class KeyFile
```

The service's keys in one private JSON file, the same format as Python's `load_keys` (one file works in every
SDK): `{"signing": {"pem": PKCS#8 Ed25519}, "disclosure": {"pem": PKCS#8 P-256}}`.

Created on first use with mode 0600, atomically: the first writer wins and every process uses the keys on disk, so
instances started together agree; a file system without hard links is refused. The disclosure key (ECDH-ES+A256KW, ORG-1 §4) is created and kept for the
other SDKs and for later use; this SDK does not decrypt disclosures yet (README, "Implemented").

```php
public static function load(string $path): array
```

- return array{0: SigningKey, 1: string} the signing key and the disclosure key's PEM

## `src/Laravel/AllowedByServiceProvider.php`

`sdks/php/src/Laravel/AllowedByServiceProvider.php`

```php
final class AllowedByServiceProvider extends ServiceProvider
```

Laravel package (auto-discovered): the `AllowedBy` singleton from config/allowedby.php, the `allowedby`
middleware alias, and `$request->allowedby()` for the accepted `Context`. With `global` on (the default) the
middleware runs on every request, so the discovery documents are served without routes of your own.

```php
public function register(): void
```



```php
public function boot(): void
```



## `src/Laravel/Middleware.php`

`sdks/php/src/Laravel/Middleware.php`

```php
final class Middleware
```

The `allowedby` middleware: the SDK's endpoints first, then the check on every route of the map, then the app.
The accepted `Context` is `$request->allowedby()`; paths outside the map pass unchanged, without it.

```php
public const ATTRIBUTE = 'allowedby.context'
```



```php
public function __construct(private readonly AllowedBy $aby, private readonly bool $guarded = false)
```

- param bool $guarded the service provider checks the chosen route (RouteMatched)

```php
public function handle(Request $request, \Closure $next): mixed
```



```php
public static function guard(AllowedBy $aby, Route $route, Request $request): ?Refusal
```

@internal

The last check before the chosen route's handler: `refusal()`, and CONTRACT §2 item 10. A refusal of the
SDK's own gives back what the check spent for the request; otherwise the request is started (nothing is given
back after this), and a request the SDK refunded already never reaches a handler.

```php
public static function refusal(AllowedBy $aby, Route $route, Request $request): ?Refusal
```

@internal

CONTRACT §2.10 rule 5: the chosen route's handler runs only for a request checked for a route of the map it
serves, by its template, as the handler of another route, or as a catch-all that is a route's only handler
(see `HandlerMap`). A handler it cannot name, near the map: refused.

## `src/Psr15/AllowedByMiddleware.php`

`sdks/php/src/Psr15/AllowedByMiddleware.php`

```php
final class AllowedByMiddleware implements MiddlewareInterface
```

PSR-15 middleware (Slim, Mezzio, any PSR-15 stack): the SDK's endpoints first, then the check on every route of
the map, then your handler. An accepted request carries its `Context` in the request attribute
`allowedby.context`; paths outside the map reach the handler unchanged, without it.

```php
public const ATTRIBUTE = 'allowedby.context'
```



```php
public const SDK_ATTRIBUTE = 'allowedby.sdk'
```

The SDK that accepted the request: `RequireContext` gives back what the check spent when it refuses it.

```php
public function __construct( private readonly AllowedBy $aby, private readonly ResponseFactoryInterface $responses, private readonly StreamFactoryInterface $streams, private readonly string $basePath = '', )
```



```php
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
```



## `src/Psr15/RequireContext.php`

`sdks/php/src/Psr15/RequireContext.php`

```php
final class RequireContext implements MiddlewareInterface
```

Put it on your protected routes (a Slim route group, a Mezzio route pipeline): it refuses a request that
`AllowedByMiddleware` did not accept. PSR-15 does not say which route the router chose, so a pattern that
matches more than the route map (`{id:.+}`), or a base path, could otherwise run a protected handler unchecked.

Where it can read the route the router chose (Slim's `__route__` attribute, Mezzio's `RouteResult`), it also
refuses a request checked for another route of the map than that one (CONTRACT §2.10 rule 5): a catch-all
(`/{path:.+}`) it is put on does not run for a request checked for `/notes/{id}`, whose own handler is elsewhere.

```php
public function __construct( private readonly ResponseFactoryInterface $responses, private readonly StreamFactoryInterface $streams, private readonly array $segregated = [], )
```

- param list&lt;string> $segregated the prefixes your Mezzio pipelines take off the path (`$app->pipe('/api', ...)`
with RequireContext inside: `['/api']`), besides AllowedByMiddleware's base path,
which counts already. A request whose path lost one of them is still the request
that was checked; any other change after acceptance is refused.

```php
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
```



## `src/Reject.php`

`sdks/php/src/Reject.php`

```php
final class Reject extends \RuntimeException
```

A refused request: an ABY-2 §6 error code, its HTTP status, and for the codes an approval can fix, the route
(so the SDK can answer with a challenge). `why` is a short reason for logs and the problem's title; it never
holds a token, a key or personal data.

```php
public const STATUS = [ 'invalid_request' => 400, 'passport_required' => 401, 'invalid_signature' => 401, 'untrusted_node' => 401, 'insufficient_witnesses' => 401, 'grant_required' => 401, 'grant_insufficient' => 401, 'level_insufficient' => 401, 'qes_required' => 401, 'authority_required' => 401, 'mandate_required' => 401, 'expired' => 401, 'not_yet_valid' => 401, 'revoked' => 401, 'actor_expired' => 401, 'class_lifetime_exceeded' => 401, 'single_use_consumed' => 401, 'capability_denied' => 403, 'tier_insufficient' => 403, 'human_not_linked' => 403, 'budget_exceeded' => 403, 'rate_limited' => 429, 'envelope_too_large' => 431, 'status_stale' => 503, ]
```

ABY-2 §6: every code and its status, as the reference's verifier.STATUS.

```php
public const CHALLENGE_CODES = ['grant_required', 'grant_insufficient', 'level_insufficient', 'qes_required', 'expired', 'revoked', 'class_lifetime_exceeded', 'single_use_consumed', 'authority_required', 'mandate_required', 'actor_expired']
```

The codes a challenge (WWW-Authenticate: AllowedBy ...) may answer: an approval can fix them.

```php
public readonly int $status
```



```php
public function __construct( public readonly string $error, public readonly string $why = '', public readonly ?Route $route = null, public readonly ?string $actorSub = null, public readonly ?string $routeClass = null, public readonly ?string $nonce = null, )
```



## `src/Response.php`

`sdks/php/src/Response.php`

```php
final class Response
```

An answer the SDK sends itself: a discovery document, or a refusal (`application/problem+json`, RFC 9457, with
`WWW-Authenticate: AllowedBy ...` when an approval can fix it). Framework adapters turn it into their own response.

```php
public function __construct( public readonly int $status, public readonly array $headers, public readonly string $body, )
```

- param array&lt;string, string> $headers

```php
public static function json(int $status, array $doc, array $headers = []): self
```

- param array&lt;string, mixed>  $doc
- param array&lt;string, string> $headers

```php
public static function problem(string $code, int $status, ?string $title = null, array $headers = [], array $extra = []): self
```

RFC 9457 problem details with the AllowedBy error type.

- param array&lt;string, string> $headers
- param array&lt;string, mixed>  $extra

```php
public function send(): void
```

Send it with PHP's own functions (plain PHP; frameworks convert it instead).

```php
public function code(): ?string
```

The error code of a problem response (`type` .../errors/`), or null.

```php
public function data(): array
```

The decoded JSON body as PHP arrays.

- return array&lt;mixed>

## `src/Route.php`

`sdks/php/src/Route.php`

```php
final class Route
```

One line of the route map (ABY-3 §4.1): what a request on this method and path needs. Build it with
`route()` (or `Route::fromArray()` in a framework config file); invalid values fail here, with a
message that says what to fix.

```php
public const CLASSES = ['read', 'write', 'write-hard', 'irreversible']
```



```php
public const CLASS_RANK = ['read' => 0, 'write' => 1, 'write-hard' => 2, 'irreversible' => 3]
```



```php
public const CLASS_MAX = ['read' => 30 * 86400, 'write' => 7 * 86400, 'write-hard' => 86400, 'irreversible' => 3600]
```

ABY-1 §2: the longest a grant may last per class, in seconds.

```php
public const MAX_LIFETIME = 30 * 86400
```

ABY-1 §2: no grant outlives 30 days, whatever a route says.

```php
public const AUTHN_RANK = ['software' => 0, 'synced' => 1, 'hardware' => 2]
```



```php
public const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
```



```php
public const LINK_CAP = 'aby:link'
```

ABY-3 §6: the reserved capability of account linking, served by the SDK at POST /allowedby/link.

```php
public const UNSUPPORTED = ['mandate', 'disclose', 'discloseOptional', 'authority']
```

Route options the reference accepts that this SDK does not enforce yet: refused, never silently ignored.

```php
public function __construct( public readonly string $method, public readonly string $path, public readonly ?string $capability = null, public readonly string|array $class = 'read', public readonly int $level = 1, public readonly ?string $resource = null, public readonly ?string $amountField = null, public readonly string $currencyField = '/currency', public readonly ?string $authn = null, public readonly int $tier = 0, public readonly ?int $maxLifetime = null, public readonly ?string $summary = null, public readonly ?array $body = null, public readonly ?string $levelProfile = null, public readonly bool $qes = false, public readonly bool $requireLink = false, public readonly ?string $accountParam = null, public readonly bool $nonce = false, )
```

- param string|list&lt;array{up_to?: string, class: string}> $class a class, or amount thresholds
- param array&lt;string, string|array&lt;string, mixed>>|null   $body  JSON body members: description, or a JSON Schema

```php
public static function create( 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, bool $requireLink = false, ?string $accountParam = null, bool $nonce = false, ): self
```

The route helper's validation (Python's `route()`), plus a few checks it leaves to luck.

- param string|array&lt;mixed>                             $class a class, or [{up_to, class}, ..., {class}]
- param array&lt;string, string|array&lt;string, mixed>>|null $body

```php
public static function fromArray(array $a): self
```

A route from a config array (Laravel, Symfony): the keys are the arguments of `route()`.

- param array&lt;array-key, mixed> $a

```php
public static function link(): self
```

ABY-3 §6: the SDK's own `POST /allowedby/link` (aby:link, write, level 1, resource aby:link), which takes a
single-use grant only.

@internal

```php
public function topClass(): string
```

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

```php
public function classFor(?string $amount): string
```

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

```php
public static function trimSlash(string $path): string
```

A path without its trailing slashes ("/" stays "/").

```php
public function match(string $method, string $path): ?array
```

The path parameters of a concrete path, or null when the route does not match it.

- return array&lt;string, string>|null

```php
public function matchWide(array $segments, int &$steps, bool $template = false): bool
```

Whether a router that lets a parameter take several segments, or a format suffix follow a literal end, could take
this path for the route. One pass over the path per segment of the template, whatever the path holds: a regular
expression would backtrack, and PCRE's limit would then read as "no match".

- param list&lt;string> $segments of the path
- param int          $steps    counts the work (tests)
- param bool         $template the segments are a template: a "{parameter}" of it is any segment, and no suffix

```php
public function resourceFor(array $params): string
```

The resource this request acts on: `{param}` replaced by the path's values.

- param array&lt;string, string> $params

## `src/SigningKey.php`

`sdks/php/src/SigningKey.php`

```php
final class SigningKey
```

The service's Ed25519 signing key: it signs the organisation profile and the approvals the service asks for
(`initiator.kid`, ABY-2 §7). Published in `/.well-known/allowedby` under `keys`.

```php
public static function generate(): self
```



```php
public static function fromSeed(string $seed): self
```

From a 32-byte Ed25519 seed.

```php
public static function fromPem(string $pem): self
```

From a PKCS#8 PEM, the format of the key file's `signing.pem`.

```php
public function toPem(): string
```

PKCS#8 PEM, readable by Python's `load_keys` and every other AllowedBy SDK.

```php
public function kid(): string
```

RFC 7638 thumbprint of the public key.

```php
public function jwk(): array
```

- return array{kty: string, crv: string, x: string, kid: string} the public JWK

```php
public function sign(string $data): string
```



```php
public function derive(string $info): string
```

A 32-byte key for another use, derived from this one with domain separation: HKDF-SHA256 (RFC 5869), IKM the raw
private key, no salt, `info` naming the use ("allowedby/link/v1" seals linking codes). Never the signing key
itself, and one key per `info`.

```php
public function __debugInfo(): array
```

- return array&lt;string, never>

```php
public function __serialize(): array
```

- return array&lt;string, never>

## `src/Store/ApcuStore.php`

`sdks/php/src/Store/ApcuStore.php`

```php
final class ApcuStore implements ExpiringStore
```

The store in APCu shared memory: every PHP-FPM worker (or `php -S` worker) of one machine sees the same replay
set, single-use set, counters and node cache. Several machines: use `RedisStore`.

Expiry follows the SDK's clock (each entry carries its own deadline); APCu's TTL is only a hint for its garbage
collector. Writes that read first (a counter, an expired entry) run under one short APCu spin lock.

APCu clears its whole cache when it runs out of memory, which would forget the replay set: size `apc.shm_size`
for your traffic (about 300 bytes per request kept 300 s). This store refuses writes when less than
`minFreeRatio` of the memory is free, so a full cache fails closed instead of being wiped.

```php
public function __construct( private readonly string $prefix = 'allowedby:', private readonly float $minFreeRatio = 0.05, )
```



```php
public function add(array $key, int $until, int $now): bool
```



```php
public function get(array $key, int $now): string
```



```php
public function charge(array $charges, int $now): bool
```



```php
public function fetch(string $name): ?string
```



```php
public function save(string $name, string $value): void
```



```php
public function saveFor(string $name, string $value, int $ttl): void
```



```php
public function lock(string $name, int $ttl): bool
```



```php
public function unlock(string $name): void
```



## `src/Store/Charge.php`

`sdks/php/src/Store/Charge.php`

```php
final class Charge
```

One counter increment for `Store::charge()`: add `inc` to the counter `key` unless the
total would exceed `max`; keep the counter until `until` (epoch seconds; null: the verifier fills in the grant's
expiry).

```php
public function __construct( public readonly array $key, public readonly string $inc, public readonly ?string $max, public readonly ?int $until, )
```

- param list&lt;string|int> $key
- param string           $inc a decimal: non-negative, or negative for a refund (with no max)
- param string|null      $max a non-negative decimal, or null for no ceiling

```php
public function withUntil(int $until): self
```



## `src/Store/ExpiringStore.php`

`sdks/php/src/Store/ExpiringStore.php`

```php
interface ExpiringStore extends Store
```

A `Store` whose documents can expire: the rate limits keep one small document per agent and per operator, and
with this the store drops it once its window has passed (otherwise it stays until replaced). The three stores of
the SDK implement it; a store of your own may.

```php
public function saveFor(string $name, string $value, int $ttl): void
```

`Store::save()`, then the store may drop the document `ttl` seconds after this write (its own clock).

## `src/Store/MemoryStore.php`

`sdks/php/src/Store/MemoryStore.php`

```php
final class MemoryStore implements ExpiringStore
```

The store in this PHP process's memory, as the reference's MemoryStore. Under PHP-FPM, Apache or `php -S`
each request starts empty, so a replay would be accepted: use it for tests and long-running workers
(RoadRunner, Swoole, ReactPHP) with a single process only. Bounded: when full of live entries it refuses
rather than forgets (fail closed).

```php
public function __construct(private readonly int $maxKeys = 200000)
```



```php
public function add(array $key, int $until, int $now): bool
```



```php
public function get(array $key, int $now): string
```



```php
public function charge(array $charges, int $now): bool
```



```php
public function fetch(string $name): ?string
```



```php
public function saveFor(string $name, string $value, int $ttl): void
```



```php
public function save(string $name, string $value): void
```



```php
public function lock(string $name, int $ttl): bool
```



```php
public function unlock(string $name): void
```



## `src/Store/RedisStore.php`

`sdks/php/src/Store/RedisStore.php`

```php
final class RedisStore implements ExpiringStore
```

The store in Redis, shared by every instance of the service (CONTRACT §2.8): pass a connected phpredis `\Redis`
or a `Predis\ClientInterface`. Check-and-set uses `SET NX` and, where a value must be read first, optimistic
transactions (WATCH / MULTI / EXEC, retried on conflict), so amounts are added exactly in PHP, never as floats.

Each value carries its own deadline from the SDK's clock; the Redis TTL only lets Redis drop it afterwards.
Redis must not evict these keys: use `maxmemory-policy noeviction` (or `volatile-*` with room to spare), or a
replayed proof could be accepted after an eviction.

```php
public function __construct(object $redis, private readonly string $prefix = 'allowedby:')
```



```php
public function add(array $key, int $until, int $now): bool
```



```php
public function get(array $key, int $now): string
```



```php
public function charge(array $charges, int $now): bool
```



```php
public function fetch(string $name): ?string
```



```php
public function save(string $name, string $value): void
```



```php
public function saveFor(string $name, string $value, int $ttl): void
```



```php
public function lock(string $name, int $ttl): bool
```



```php
public function unlock(string $name): void
```



## `src/Store/Store.php`

`sdks/php/src/Store/Store.php`

```php
interface Store
```

Where the verifier keeps what must survive one request (CONTRACT §2.8, ABY-2 §3.3, ABY-1 §7, ABY-3 §3):
the replay set, single-use consumption and counters, and the cached node statements and status lists.

PHP shares nothing between requests, so this must be shared: `ApcuStore` on one machine, `RedisStore`
across machines. `MemoryStore` lives as long as one PHP process: tests and long-running workers only.

`now` always comes from the SDK's clock, never from the store's wall clock, so an injected clock governs expiry.
Any failure throws `StoreException`: the SDK then refuses the request (fail closed).

```php
public function add(array $key, int $until, int $now): bool
```

Add `key` unless it is present and live: false when it already was (a replay, a second use). Atomic.

- param list&lt;string|int> $key

```php
public function get(array $key, int $now): string
```

The counter's value, "0" when absent or expired.

- param list&lt;string|int> $key

```php
public function charge(array $charges, int $now): bool
```

All or nothing: add every increment when every total stays within its max. Atomic.

A negative increment is a refund (sdks/CONTRACT.md §2 item 10, the SDK's own refusal after the check): it has
no max and is applied exactly, so a counter may go below 0 (one that expired before its refund). A store keeps
and reads back negative counters ("-1").

- param list&lt;Charge> $charges

```php
public function fetch(string $name): ?string
```

A cached document (the node snapshot), or null.

```php
public function save(string $name, string $value): void
```

Keep a cached document until replaced; an empty value removes it (fetch() then gives null or "").

```php
public function lock(string $name, int $ttl): bool
```

Take a named lock for at most $ttl seconds: false when another process holds it.

```php
public function unlock(string $name): void
```



## `src/Store/StoreException.php`

`sdks/php/src/Store/StoreException.php`

```php
final class StoreException extends \RuntimeException
```

The store cannot answer (full, unreachable, locked too long): the request is refused, never let through.

## `src/Symfony/AllowedByBundle.php`

`sdks/php/src/Symfony/AllowedByBundle.php`

```php
final class AllowedByBundle extends AbstractBundle
```

Symfony bundle: configure it under `allowedby:` (config/packages/allowedby.yaml). It registers the `AllowedBy`
service, a kernel.request subscriber (the SDK's endpoints, then the check on every route of the map, before the
router) and an argument resolver: a controller argument typed `\AllowedBy\Context` (or marked
#[AllowedByContext]) receives the accepted request's context.

```php
public function configure(DefinitionConfigurator $definition): void
```



```php
public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
```

- param array&lt;string, mixed> $config

## `src/Symfony/AllowedByContext.php`

`sdks/php/src/Symfony/AllowedByContext.php`

```php
final class AllowedByContext
```

Marks a controller argument that receives the accepted request's `\AllowedBy\Context`:

```
    public function list(#[AllowedByContext] Context $ctx): JsonResponse

```
(an argument typed Context gets it too). On a route outside the map there is no context: a nullable argument
gets null, a non-nullable one refuses the request (403) rather than run without the check.

## `src/Symfony/ContextValueResolver.php`

`sdks/php/src/Symfony/ContextValueResolver.php`

```php
final class ContextValueResolver implements ValueResolverInterface
```

Gives a controller argument typed `Context` (or marked #[AllowedByContext]) the accepted request's context.

```php
public function resolve(Request $request, ArgumentMetadata $argument): iterable
```

- return iterable&lt;Context|null>

## `src/Symfony/RequestSubscriber.php`

`sdks/php/src/Symfony/RequestSubscriber.php`

```php
final class RequestSubscriber implements EventSubscriberInterface
```

Runs before the router (priority 256): the SDK's endpoints and refusals are answered here; an accepted request
carries its context in the request attribute `allowedby.context`.

```php
public const ATTRIBUTE = 'allowedby.context'
```



```php
public function __construct( private readonly AllowedBy $aby, private readonly ?RouterInterface $router = null, private readonly ?CacheInterface $cache = null, )
```



```php
public static function getSubscribedEvents(): array
```



```php
public function onRequest(RequestEvent $event): void
```



```php
public function onRouted(RequestEvent $event): void
```

Once routed: the handler of a route of the map runs only for a request that was checked for that route.

## `src/Trust/TrustList.php`

`sdks/php/src/Trust/TrustList.php`

```php
final class TrustList
```

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

```php
public readonly array $anchors
```

- var list&lt;JsonObject>

```php
public readonly array $denied
```

- var list&lt;string>

```php
public readonly array $programs
```

- var list&lt;JsonObject>

```php
public readonly JsonObject $vouching
```



```php
public readonly int $witnessesMin
```



```php
public readonly int $exp
```



```php
public function __construct(string $jws, array $serviceJwk)
```

- param array&lt;string, mixed> $serviceJwk the public JWK that signed the list (its `kid` included)

- throws \InvalidArgumentException when the signature, the key or the members are wrong

```php
public static function load(string $path, array $serviceJwk): self
```

- param array&lt;string, mixed> $serviceJwk
