View as Markdown

PHP SDK#

The public API of sdks/php, with its doc comments. Guide: docs/sdk/php.md.

178 public declarations, 113 with a doc comment.

src/AllowedBy.php#

sdks/php/src/AllowedBy.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.

public const VERSION = '0.1.0'
public const SPEC_VERSION = '0.2.14'
public const MAX_BODY = 1 << 20
public const STARTUP_WAIT = 5

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

public readonly string $origin
public readonly string $node
public readonly string $host

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

public readonly array $routes
  • var list<Route>
public readonly array $templates
  • var array<string, array{summary: array<string, string>, lines: array<string, string>}>
public readonly Verifier $verifier
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<string, mixed> $org ORG-1 §2: legal_name, country (ISO 3166-1 alpha-2), optional website, support, privacy_policy, logo {uri, sha256}
  • param list<Route|array<array-key, mixed>> $routes the route map: route() or arrays of its arguments
  • param array<string, string|array<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<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<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<array-key, mixed>|null $rate rate limits: ['actor' => [n, seconds], 'operator' => [n, seconds]], each optional; by default 600 and 6000 calls per 60 s
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<array-key, mixed> $server
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<string, string|list<string>> $headers
  • param list<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())
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.

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).

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.

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<string> $methods the methods of the framework's route; empty: every method
  • param list<string> $prefixes what the app is served under: a map written with it must not leave a handler open
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<string> $serves
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<string> $methods

  • param list<string> $prefixes

  • return list<string>

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<array{template: string, methods: list<string>, handler: ?string, siteWide: bool}> $framework
  • param callable(string, string, int): ?int $match
  • param list<string> $prefixes
public static function notOnTheMap(bool $knownHandler = false): Response

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

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).

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.

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<string, string|list<string>> $headers
  • param list<string> $mounted
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.

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).

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.

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).

public function refresh(): void

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

public function wellKnown(): array
  • return array<string, mixed> /.well-known/allowedby (ABY-3 §4, ORG-1 §2)
public function openapi(): array
  • return array<string, mixed> OpenAPI 3.1 for the route map (ABY-3 §5.1)
public function apiCatalog(): array
  • return array<string, mixed> RFC 9727 API catalog: where this origin's APIs and their descriptions are
public function orgProfile(): string

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

public function publicKey(): array

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

  • return array<string, string>
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

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).

public static function build(array $c): AllowedBy
  • param array<array-key, mixed> $c
public static function store(mixed $store, mixed $redis = null): ?Store

src/Context.php#

sdks/php/src/Context.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.

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<string> $capabilities the grant's capabilities
  • param array{summary?: string, lines?: list<string>, lang?: string}|null $display what the person approved
  • param list<array{gid: string, rev: int|null}> $chain the grant chain, leaf first
  • param array<string, mixed>|null $actingFor
  • param array<string, string> $params the route's path values as checked
public function toArray(): array
  • return array<string, mixed> every field, for logs and JSON

src/Decision.php#

sdks/php/src/Decision.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.
public function __construct( public readonly ?Context $context = null, public readonly ?Response $response = null, )
public function allowed(): bool

src/Http/CurlHttpClient.php#

sdks/php/src/Http/CurlHttpClient.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.

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

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.

public function request(string $method, string $url, ?string $body = null, array $headers = [], int $timeout = 5): array
  • param array<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

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).

public const MAX_RESPONSE = 1 << 20
public function request(string $method, string $url, ?string $body = null, array $headers = [], int $timeout = 5): array

src/KeyFile.php#

sdks/php/src/KeyFile.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").

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

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.

public function register(): void
public function boot(): void

src/Laravel/Middleware.php#

sdks/php/src/Laravel/Middleware.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.

public const ATTRIBUTE = 'allowedby.context'
public function __construct(private readonly AllowedBy $aby, private readonly bool $guarded = false)
  • param bool $guarded the service provider checks the chosen route (RouteMatched)
public function handle(Request $request, \Closure $next): mixed
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.

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

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.

public const ATTRIBUTE = 'allowedby.context'
public const SDK_ATTRIBUTE = 'allowedby.sdk'

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

public function __construct( private readonly AllowedBy $aby, private readonly ResponseFactoryInterface $responses, private readonly StreamFactoryInterface $streams, private readonly string $basePath = '', )
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

src/Psr15/RequireContext.php#

sdks/php/src/Psr15/RequireContext.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.

public function __construct( private readonly ResponseFactoryInterface $responses, private readonly StreamFactoryInterface $streams, private readonly array $segregated = [], )
  • param list<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.
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

src/Reject.php#

sdks/php/src/Reject.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.

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.

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.

public readonly int $status
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

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.

public function __construct( public readonly int $status, public readonly array $headers, public readonly string $body, )
  • param array<string, string> $headers
public static function json(int $status, array $doc, array $headers = []): self
  • param array<string, mixed> $doc
  • param array<string, string> $headers
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<string, string> $headers
  • param array<string, mixed> $extra
public function send(): void

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

public function code(): ?string

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

public function data(): array

The decoded JSON body as PHP arrays.

  • return array<mixed>

src/Route.php#

sdks/php/src/Route.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.

public const CLASSES = ['read', 'write', 'write-hard', 'irreversible']
public const CLASS_RANK = ['read' => 0, 'write' => 1, 'write-hard' => 2, 'irreversible' => 3]
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.

public const MAX_LIFETIME = 30 * 86400

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

public const AUTHN_RANK = ['software' => 0, 'synced' => 1, 'hardware' => 2]
public const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
public const LINK_CAP = 'aby:link'

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

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

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

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<array{up_to?: string, class: string}> $class a class, or amount thresholds
  • param array<string, string|array<string, mixed>>|null $body JSON body members: description, or a JSON Schema
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<mixed> $class a class, or [{up_to, class}, ..., {class}]
  • param array<string, string|array<string, mixed>>|null $body
public static function fromArray(array $a): self

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

  • param array<array-key, mixed> $a
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

public function topClass(): string

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

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.

public static function trimSlash(string $path): string

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

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<string, string>|null
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<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
public function resourceFor(array $params): string

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

  • param array<string, string> $params

src/SigningKey.php#

sdks/php/src/SigningKey.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.

public static function generate(): self
public static function fromSeed(string $seed): self

From a 32-byte Ed25519 seed.

public static function fromPem(string $pem): self

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

public function toPem(): string

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

public function kid(): string

RFC 7638 thumbprint of the public key.

public function jwk(): array
  • return array{kty: string, crv: string, x: string, kid: string} the public JWK
public function sign(string $data): string
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.

public function __debugInfo(): array
  • return array<string, never>
public function __serialize(): array
  • return array<string, never>

src/Store/ApcuStore.php#

sdks/php/src/Store/ApcuStore.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.

public function __construct( private readonly string $prefix = 'allowedby:', private readonly float $minFreeRatio = 0.05, )
public function add(array $key, int $until, int $now): bool
public function get(array $key, int $now): string
public function charge(array $charges, int $now): bool
public function fetch(string $name): ?string
public function save(string $name, string $value): void
public function saveFor(string $name, string $value, int $ttl): void
public function lock(string $name, int $ttl): bool
public function unlock(string $name): void

src/Store/Charge.php#

sdks/php/src/Store/Charge.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).

public function __construct( public readonly array $key, public readonly string $inc, public readonly ?string $max, public readonly ?int $until, )
  • param list<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
public function withUntil(int $until): self

src/Store/ExpiringStore.php#

sdks/php/src/Store/ExpiringStore.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.

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

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).

public function __construct(private readonly int $maxKeys = 200000)
public function add(array $key, int $until, int $now): bool
public function get(array $key, int $now): string
public function charge(array $charges, int $now): bool
public function fetch(string $name): ?string
public function saveFor(string $name, string $value, int $ttl): void
public function save(string $name, string $value): void
public function lock(string $name, int $ttl): bool
public function unlock(string $name): void

src/Store/RedisStore.php#

sdks/php/src/Store/RedisStore.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.

public function __construct(object $redis, private readonly string $prefix = 'allowedby:')
public function add(array $key, int $until, int $now): bool
public function get(array $key, int $now): string
public function charge(array $charges, int $now): bool
public function fetch(string $name): ?string
public function save(string $name, string $value): void
public function saveFor(string $name, string $value, int $ttl): void
public function lock(string $name, int $ttl): bool
public function unlock(string $name): void

src/Store/Store.php#

sdks/php/src/Store/Store.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).

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<string|int> $key
public function get(array $key, int $now): string

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

  • param list<string|int> $key
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<Charge> $charges
public function fetch(string $name): ?string

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

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

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

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

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

public function unlock(string $name): void

src/Store/StoreException.php#

sdks/php/src/Store/StoreException.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

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.

public function configure(DefinitionConfigurator $definition): void
public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
  • param array<string, mixed> $config

src/Symfony/AllowedByContext.php#

sdks/php/src/Symfony/AllowedByContext.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

final class ContextValueResolver implements ValueResolverInterface

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

public function resolve(Request $request, ArgumentMetadata $argument): iterable
  • return iterable<Context|null>

src/Symfony/RequestSubscriber.php#

sdks/php/src/Symfony/RequestSubscriber.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.

public const ATTRIBUTE = 'allowedby.context'
public function __construct( private readonly AllowedBy $aby, private readonly ?RouterInterface $router = null, private readonly ?CacheInterface $cache = null, )
public static function getSubscribedEvents(): array
public function onRequest(RequestEvent $event): void
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

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.

public readonly array $anchors
  • var list<JsonObject>
public readonly array $denied
  • var list<string>
public readonly array $programs
  • var list<JsonObject>
public readonly JsonObject $vouching
public readonly int $witnessesMin
public readonly int $exp
public function __construct(string $jws, array $serviceJwk)
  • param array<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

public static function load(string $path, array $serviceJwk): self
  • param array<string, mixed> $serviceJwk