# HTTP Server CLI — Authentication

Bootgly HTTP authentication is split into small layers:

- **Request credentials** parse Basic `Authorization` headers without trusting them.
- **Request token metadata** exposes Bearer transport as `$Request->token`.
- **Authentication guards** verify credentials and emit protocol-aware challenges.
- **The `Authentication` middleware** runs one or more guards around protected routes.

Supported mechanisms in HTTP Server CLI are:

| Mechanism | Use case | Transport |
| --- | --- | --- |
| Basic | Compatibility, development, simple protected endpoints | `Authorization: Basic ...` |
| Bearer | Opaque API tokens and access tokens | `Authorization: Bearer <token>` |
| JWT | Signed compact tokens verified by Bootgly | `Authorization: Bearer <jwt>` |
| Session | Browser flows backed by `$Request->Session` | Session cookie |

> Digest authentication is intentionally not part of this first implementation.

## Request credentials

`$Request->authenticate()` parses Basic HTTP `Authorization` credentials and returns a credentials object or `null`:

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request\Authentications\Basic;

$Credentials = $Request->authenticate();

if ($Credentials instanceof Basic) {
   $username = $Credentials->username;
   $password = $Credentials->password;
}
```

The parser does not verify credentials. Verification belongs to guards and application resolvers. Bearer and JWT tokens stay inside `Router\Middlewares`: read `$Request->token` or use the Bearer/JWT guards.

The request also exposes lazy authentication metadata:

```php
$Request->username; // Basic username
$Request->password; // Basic password
$Request->token;    // Bearer token
```

## Response challenges

Use `$Response->authenticate()` to return a Basic `401 Unauthorized` challenge. Bearer challenges are emitted by the Bearer/JWT guards so their definitions stay inside `Router\Middlewares`.

### Basic challenge

```php
use Bootgly\WPI\Modules\HTTP\Server\Response\Authentication\Basic;

return $Response->authenticate(new Basic(
   realm: 'Bootgly Protected Area'
));
```

Emits:

```http
WWW-Authenticate: Basic realm="Bootgly Protected Area"
```

The realm is written as an RFC 9110 quoted-string: `"` and `\` are escaped with a backslash, so `realm: 'Team "Ops"'` becomes `realm="Team \"Ops\""`. A horizontal tab is sent as is; the `Basic` guard refuses a realm holding any other control character (CR, LF, NUL, DEL…) with `InvalidArgumentException` when it is configured. Calling `$Response->authenticate()` directly does not check the realm: keep control characters out of it — a realm holding NUL or DEL leaves the `401` without its `WWW-Authenticate` header.

### Bearer challenge

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Bearer;

$Bearer = new Bearer(
   Resolver: fn (string $token): bool => $token === 'demo-bearer-token',
   realm: 'Bootgly API',
   error: 'invalid_token',
   description: 'The access token is missing or invalid.',
   URI: 'https://docs.bootgly.com/manual/WPI/HTTP/HTTP_Server_CLI/Authentication',
   scope: 'demo:read',
   metadata: 'https://api.example.com/.well-known/oauth-protected-resource'
);
```

When the request sent a Bearer token that the guard refused, the challenge carries the RFC 6750 error attributes:

```http
WWW-Authenticate: Bearer realm="Bootgly API", error="invalid_token", error_description="The access token is missing or invalid.", error_uri="https://docs.bootgly.com/manual/WPI/HTTP/HTTP_Server_CLI/Authentication", scope="demo:read", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource"
```

When the request sent no Bearer token at all — no `Authorization` header, an empty one, or another scheme such as `Basic` — the client was not told yet that a token is needed, so the challenge carries no error information (RFC 6750 §3.1): `error`, `error_description` and `error_uri` are left out, `realm`, `scope` and `resource_metadata` stay.

```http
WWW-Authenticate: Bearer realm="Bootgly API", scope="demo:read", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource"
```

`metadata` is the RFC 9728 protected-resource-metadata URL. It is sent as `resource_metadata="…"` after the other attributes so OAuth clients (MCP clients among them) can discover which authorization server issues tokens for this resource. Leave it empty (the default) to omit it. Empty attributes are always omitted.

Every attribute value is written as an RFC 9110 quoted-string: `"` and `\` are escaped with a backslash, so `realm: 'Team "Ops" \ API'` becomes `realm="Team \"Ops\" \\ API"`. A value holding a control character (CR, LF, NUL, HTAB, DEL…) can never be quoted safely, so the `Bearer` (and `JWT`) constructor refuses it with `InvalidArgumentException` — a misconfigured challenge fails at boot, never at request time.

The RFC 6750 attributes are narrower than a quoted-string, and the constructor enforces their character sets (RFC 6750 §3), naming the parameter in the exception message:

| Argument | Attribute | Allowed characters |
|---|---|---|
| `error` | `error` | printable ASCII and space, without `"` and `\` (`%x20-21 / %x23-5B / %x5D-7E`) |
| `description` | `error_description` | the same as `error` |
| `URI` | `error_uri` | a URI-reference of printable ASCII without space, `"` and `\` (`%x21 / %x23-5B / %x5D-7E`) |
| `scope` | `scope` | scope-tokens (printable ASCII without space, `"` and `\`) separated by one space |

So `description: 'The "token" expired'` or `scope: 'files:read  files:write'` (two spaces) throw `InvalidArgumentException`, while `realm` and `metadata` keep the quoted-string rule above (quotes, backslashes and bytes `0x80`–`0xFF` allowed). Empty values are omitted, never refused.

## Authentication middleware

The middleware receives an `Authenticating` strategy object. The strategy stores guards in evaluation order.

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
```

When any guard authenticates successfully, the route handler runs. When all guards fail, the middleware uses the first guard to build the challenge response.

`Authentication` requires at least one guard. Creating it with an empty `Authenticating` strategy throws `InvalidArgumentException` so protected routes cannot fail closed silently because of misconfiguration.

Custom fallback callbacks may render a body or extra headers for denied requests, but the middleware normalizes the returned response to `401 Unauthorized` before and after the callback. This prevents accidental `200 OK` responses on authentication failure. Redirecting fallbacks are the one exception: a callback result that is already a redirect (3xx status + `Location` header) is returned untouched, so browser/session flows can send guests to a sign-in page with a real `303`.

```php
$Auth = new Authentication(
   Authenticating: $Bearer,
   Fallback: function (Request $Request, Response $Response): Response {
      return $Response(body: 'Custom unauthorized body');
   }
);
```

Authentication guards expose metadata through declared `Request` properties: `$Request->identity` for the authenticated principal and `$Request->claims` for verified token claims. Request doubles should declare those properties too, or use `stdClass` in lightweight tests.

## Hardening notes

- Pair Basic and Bearer routes with `RateLimit` to reduce brute-force attempts.
- Resolver callbacks should compare secrets with `hash_equals()` when checking passwords, API tokens, or shared secrets.
- Place CSRF protection before state-changing authenticated browser routes; token/API routes that do not use cookies can be exempted by route policy.
- JWT is transported as a Bearer token and shares the `$Request->token` hook with opaque Bearer credentials.

## Bearer token guard

Use the Bearer guard for opaque API tokens. The resolver receives the token and the `Request`.

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Response;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Bearer;

$Bearer = new Authenticating(
   new Bearer(function (string $token, Request $Request): bool {
      return $token === 'demo-bearer-token';
   })
);

yield $Router->route('/auth/bearer', function (Request $Request, Response $Response) {
   return $Response->JSON->send([
      'authorized' => true,
      'guard' => 'Bearer',
   ]);
}, GET, middlewares: [new Authentication($Bearer)]);
```

Try it:

```bash :toolbar="true";
curl -H 'Authorization: Bearer demo-bearer-token' http://localhost:8082/auth/bearer
```

A resolver may return:

- `false` or `null` to deny.
- `true` to expose the token as `$Request->identity`.
- any custom value to expose that value as `$Request->identity`.

## JWT guard

Bootgly includes a native JWT signer/verifier in `Bootgly\API\Security\JWT`. JWT is not a separate HTTP scheme; it uses Bearer transport. Create the JWT object once at application boot and share it across requests instead of rebuilding the key set per request.

```php
use Bootgly\API\Security\JWT;
use Bootgly\API\Security\JWT\Policies;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Response;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\JWT as JWTGuard;

$Token = new JWT('bootgly-demo-authentication-secret');

yield $Router->route('/auth/jwt/issue', function (Request $Request, Response $Response) use ($Token) {
   $token = $Token->sign([
      'sub' => 'demo-user',
      'scope' => 'demo:read',
      'exp' => time() + 3600,
   ]);

   return $Response->JSON->send([
      'token' => $token,
      'authorization' => "Bearer {$token}",
   ]);
}, GET);

$Policies = new Policies(
   issuers: 'https://issuer.bootgly.dev',
   audiences: 'api://bootgly-demo',
   subject: true
);
$JWT = new Authenticating(new JWTGuard($Token, $Policies));

yield $Router->route('/auth/jwt', function (Request $Request, Response $Response) {
   return $Response->JSON->send([
      'authorized' => true,
      'guard' => 'JWT',
   ]);
}, GET, middlewares: [new Authentication($JWT)]);
```

JWT signing throws `RuntimeException` when claims or headers cannot be JSON encoded. JWT verification rejects malformed tokens, unsupported algorithms, unsupported `typ` values, invalid signatures, expired `exp`, future `nbf`, and future `iat`. The HS256 secret must be at least 32 bytes. `Policies` can require exact `iss`, matching `aud`, non-empty `sub`, and non-empty `jti` claims. The guard still returns only a generic Bearer `invalid_token` challenge to the client (or, when no token was sent, the challenge without an error code).

The default `JWT->leeway` is `0`, so time claim verification is strict. Set a small value such as `5` seconds when your servers can have minor clock drift.

For deterministic tests, use `JWT->freeze($timestamp)` and then `JWT->resume()` to return to the wall clock.

When the `sub` claim is present, the guard exposes `Bootgly\API\Security\Identity` as `$Request->identity`. It always exposes verified claims as `$Request->claims` and verified protected headers as `$Request->tokenHeaders`. A space-separated JWT `scope` claim or an array/string `scp` claim is normalized into `Identity->scopes`, so `$Request->identity->check('demo:read')` works for JWT users. When both are present, `scope` takes precedence over `scp`.

### RS256, JWKS, and key rotation

Use `Bootgly\API\Security\JWT\Key` for explicit key ids and `Bootgly\API\Security\JWT\KeysJWKS` for local JWKS documents:

```php
use Bootgly\API\Security\JWT;
use Bootgly\API\Security\JWT\Key;
use Bootgly\API\Security\JWT\KeysJWKS;

$Signer = new JWT($privatePem, 'RS256');
$Signer->select(new Key($privatePem, 'RS256', 'current'));

$Verifier = new JWT($publicPem, 'RS256');
$Verifier->trust(KeysJWKS::parse($jwks, 'RS256'));
```

`KeysJWKS::parse()` keeps every supported RS256 key and skips unsupported siblings — encryption keys, other algorithms — as RFC 7517 asks, so an IdP publishing a mixed document never poisons verification; a document with zero supported keys still fails loudly. Always set `kid` when rotating JWT keys. A no-`kid` key set is intentionally single-slot for backwards-compatible tokens; adding a second default key fails loudly instead of letting the verifier guess.

For external OAuth/OIDC issuers, use `Bootgly\API\Security\JWT\Remote` with the provider's `jwks_uri`:

```php
use Bootgly\API\Security\JWT;
use Bootgly\API\Security\JWT\Policies;
use Bootgly\API\Security\JWT\Remote;
use Bootgly\API\Security\JWT\Vault;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\JWT as JWTGuard;

$Remote = new Remote('https://issuer.example/.well-known/jwks.json');
$Remote->TTL = 900; // public property is uppercase; constructor argument remains ttl:
$Remote->cache(new Vault);
$Verifier = new JWT($Remote, 'RS256');

$Policies = new Policies(
   issuers: 'https://issuer.example',
   audiences: 'api://bootgly-demo',
   subject: true
);

$JWT = new Authenticating(new JWTGuard($Verifier, $Policies));
```

`Remote` keeps a process-local `KeySet` and can use `Vault` to share versioned JWKS records across workers. The mutable public `$TTL` property (uppercase) is the operator ceiling, from `0` through `31,536,000` seconds; the constructor's named argument remains `ttl:`. Construction and later `$TTL` assignments reject negative or larger values without replacing the last valid setting. The former lowercase `$ttl` property is no longer public.

Redirects are followed one hop at a time, and every target must remain HTTPS unless `insecure: true` was explicitly selected for tests or a controlled local environment. `Location` URI references are resolved according to RFC 3986 by the shared [`URI`](/manual/ABI/Data/URI/) resolver: dot segments are removed without collapsing meaningful consecutive slashes, fragments are never sent in the request target, and a target that is not an absolute URI with a host (`g:h`, `https:keys`) ends the fetch. Only the final response supplies the accepted status and cache headers. Its effective lifetime is the shortest `Cache-Control: max-age`, reduced by `Age` and capped by `$TTL`; `no-store`, `no-cache`, and `max-age=0` make the response stale at once and prevent a shared-cache write (the floor below still holds it in memory). Shared readers inherit the writer's absolute expiry instead of starting a new TTL. `Remote` refreshes on an unknown `kid` and fails closed for fetch errors, invalid redirect targets, final non-2xx responses, invalid JSON, or invalid JWKS. OIDC Discovery, `ETag`/`Last-Modified`, and exponential backoff remain future layers.

**Redirect destinations.** The native fetch resolves every hop once and dials the addresses it resolved, in resolver order: an address that takes the request ends the hop, and a refused, unreachable or TLS-failed one hands over to the next within what is left of the hop's `timeout` — the hop's name stays the `Host` header and the name the TLS certificate is verified against — so a second DNS answer cannot move the request. Once a hop was answered from a public address, a later hop that resolves to any non-public address (loopback, private, link-local, shared/CGNAT, reserved, multicast, the NAT64 local-use prefix; an IPv4-mapped address, or one in the NAT64 well-known prefix `64:ff9b::/96`, is judged as the IPv4 address it carries — a network-specific NAT64 prefix is not recognized) is refused before any request is sent: the fetch fails with `Failures::Network` and `$Remote->message` names the refusal. The configured `$URI` is never refused, so an intranet IdP on a private address keeps working and its redirects to other private addresses are followed; when it answers from a public address, its redirects stay public. Without the `sockets` extension, a hop's IPv6 addresses come from DNS (the hosts file is not read for them) after its IPv4 ones, one extra lookup outside `timeout` — install `ext-sockets` to resolve as PHP itself does. A custom `$Fetcher` owns its transport and is not subject to this check. Since 1.0.10.

**An origin floor.** The key is resolved before the signature is checked, so without a floor every token — forged ones included — would make a stale `Remote` fetch the JWKS, blocking the worker while it waits. Each worker process bounds how often it asks the origin, whatever the IdP's cache headers say:

- a key set the origin confirmed is **held** — served — for one window: `cooldown` (default `60` seconds), or `$TTL` when that is positive and shorter. It is held even when the IdP answers `no-store`, `no-cache` or `max-age=0`, and even with `ttl: 0` (which therefore holds for the whole `cooldown`); such a set still never enters the shared `Vault`;
- a failed fetch is **replayed** — the same failure, fail closed — for one `cooldown`, so one transient IdP error costs up to one `cooldown` of rejections on that worker; once the hold is over, an expired set is never served while the IdP fails, and a call made while a fetch is in flight fails with `Network`;
- an unknown `kid` still triggers one immediate refresh — at most one per `cooldown` per worker, and one for the whole fleet while the set is fresh and shared through a `Vault` — so a key the IdP adds is accepted at once on the worker that refreshes, unless another unknown `kid` already spent that refresh; behind a `Vault`, the other workers pick up a cacheable rotation when their own set expires. A key the IdP removes is rejected once the set's lifetime and its hold have both passed;
- a resolver pinned to `RS256` refuses a token with another `alg` without fetching.

`refresh()` is never floored. Build `Remote` once — at route-file scope, as above — never per request: the floor lives in the instance. `cooldown: 0` disables it and makes a `no-store` IdP cost one fetch per verification — keep it for tests.

The floor runs on the monotonic `$tick` of the resolver's [`Clock`](/manual/ABI/Clock/overview/), and a set's freshness on its wall `$time` — the system Clock unless one is passed as `Clock:`. A test walks a whole `cooldown` without sleeping: `new Remote($URI, $Fetcher, cooldown: 60, Clock: $Clock)` with a `Bootgly\ACI\Tests\Doubles\Fake\Clock`, then `$Clock->advance(60)`. A hop's network `timeout` always runs on the system clock.

`Vault` stores its records on the Bootgly `Cache` facade. By default it uses the `file` driver (shared across workers on the same filesystem); passing a Redis-backed `Cache` shares JWKS, refresh-token state, and revocations across hosts — and then requires a shared HMAC secret (≥ 32 bytes), so every host can verify the records. Without one, each host would sign with a secret of its own and read the others' records as misses (a revocation would not reach them): an injected backend other than `file`, `memory` or `shared` without `secret:` throws at construction. Moving a deployment that ran on a derived secret, pass the contents of its `{path}{prefix}.secret` file to keep the existing records:

```php
use Bootgly\ABI\Resources\Cache;
use Bootgly\API\Security\JWT\Vault;

$Vault = new Vault(
   new Cache(['driver' => 'redis', 'host' => 'redis.internal']),
   secret: getenv('JWT_VAULT_SECRET')
);
```

Every record carries an HMAC-SHA256 envelope, so an entry altered in the storage backend fails verification and reads as a miss.

`Vault::lock()` stays host-local. Fleet safety comes from the order of `Tokens`' writes around the store's atomic `take()` on ONE linearizable store — a single Redis primary, no replica reads, `noeviction`; a `file` store on a directory several hosts mount is not a fleet store. Keep host clocks synchronized (within 60 seconds). Each rotation leaves a tombstone that lives about one refresh lifetime, and under `noeviction` a full store refuses every write on every host — rate-limit the refresh endpoint per subject and size `maxmemory` for the active sessions plus the refreshes one lifetime holds.

### Custom key resolvers

`KeySet`, `KeysJWKS` and `Remote` are the shipped resolvers, but the slot `trust()` fills is an interface — `Bootgly\API\Security\JWT\KeyResolver`. Implement it when the keys live somewhere Bootgly cannot know about: your own `jwt_keys` table, a KMS, an HSM, a per-tenant key registry.

The contract has two methods. `resolve()` is called once per verification, after the header was decoded and its `alg` accepted, and **before** the signature is checked: it receives the protected header's `kid` (`null` when the token carries none) and the token's algorithm, and returns the one `Key` allowed to verify that token — or `null` to refuse. `fail()` is consulted only after a `null`, and its `Failures` case becomes the `Verification` failure; returning `null` there means "no detail", and the caller sees the generic `Failures::Key`.

```php
namespace Demo\Blog\Security;

use function is_array;
use function is_string;

use Bootgly\ADI\Databases\SQL;
use Bootgly\ADI\Databases\SQL\Builder\Auxiliaries\Operators;
use Bootgly\ADI\Databases\SQL\Builder\Identifier;
use Bootgly\API\Security\JWT;
use Bootgly\API\Security\JWT\Failures;
use Bootgly\API\Security\JWT\Key;
use Bootgly\API\Security\JWT\KeyResolver;

class Keys implements KeyResolver
{
   // * Data
   private SQL $Database;
   /**
    * Keys already read from the table, by `kid`.
    *
    * @var array<string,Key>
    */
   private array $Keys = [];

   // * Metadata
   private null|Failures $failure = null;


   public function __construct (SQL $Database)
   {
      $this->Database = $Database;
   }

   public function resolve (null|string $id, string $algorithm): null|Key
   {
      // ! One outcome per call: clear the previous verification's failure
      $this->failure = null;

      // ? Rotation requires an explicit `kid` — never guess a key
      if ($id === null) {
         $this->failure = Failures::Key;
         return null;
      }

      $Key = $this->Keys[$id] ?? null;

      if ($Key === null) {
         $Builder = $this->Database
            ->table(new Identifier('jwt_keys'))
            ->select(new Identifier('algorithm'), new Identifier('material'))
            ->filter(new Identifier('kid'), Operators::Equal, $id)
            ->filter(new Identifier('retired'), Operators::Equal, 0)
            ->limit(1);

         $row = $this->Database->query($Builder)->rows[0] ?? null;
         if (is_array($row) === false || is_string($row['material'] ?? null) === false) {
            $this->failure = Failures::Key;
            return null;
         }

         $Key = new Key($row['material'], (string) $row['algorithm'], $id);
         $this->Keys[$id] = $Key;
      }

      // ? The token's `alg` must be the one this key was enrolled for
      if ($Key->algorithm !== $algorithm) {
         $this->failure = Failures::Algorithm;
         return null;
      }

      return $Key;
   }

   public function fail (): null|Failures
   {
      return $this->failure;
   }
}

$Verifier = new JWT($currentSecret, 'HS256');
$Verifier->trust(new Keys($Database));
```

Rotation is then a row: insert the new key with a fresh `kid`, sign with it, and set `retired = 1` on the old row once no live token still carries it. Tokens signed by a retired key stop resolving, and `inspect()` answers `Failures::Key` — the resolver never falls back to "the only key it has", which is exactly what makes rotation safe.

Three rules the example follows, and yours should too:

- **Never ignore `$algorithm`.** Returning a key enrolled for a different algorithm is how algorithm-confusion attacks land. `KeySet` refuses the same way.
- **Refuse a `null` `$id` unless you really have a single-slot legacy key.** Guessing between candidates is the failure mode `KeySet` was designed to avoid — it returns `null` whenever a no-`kid` token matches more than one key.
- **Reset the failure at the top of `resolve()`.** `fail()` is read right after a `null` resolve, so a stale case from an earlier verification would mislabel this one. `Remote` clears its own on every successful resolve for the same reason.

Cache resolved keys in the resolver, as above: `resolve()` runs on every verified request, and a database round trip per request is a hot-path cost. Keep the cache process-local unless the material is already protected — `Vault` exists for the shared case.

### Refresh tokens and `jti` usage

For first-party fullstack apps, keep access tokens short-lived and rotate opaque refresh tokens through `Bootgly\API\Security\JWT\Tokens`:

```php
use Bootgly\API\Security\JWT\Replay;
use Bootgly\API\Security\JWT\Token;
use Bootgly\API\Security\JWT\Tokens;
use Bootgly\API\Security\JWT\Usage;
use Bootgly\API\Security\JWT\Vault;

$Vault = new Vault;
$Tokens = new Tokens($Vault);

$Issued = $Tokens->mint('user-42', 60 * 60 * 24 * 30, [
   'role' => 'admin',
]);

$Rotated = $Tokens->rotate($Issued->refresh, 60 * 60 * 24 * 30);
if ($Rotated instanceof Replay) {
   // incident: log subject/family and force logout for sibling sessions
}
elseif ($Rotated instanceof Token) {
   // issue the new refresh token to the client
}
```

`Tokens` stores refresh state under token hashes, consumes the old refresh token on rotation, leaves a tombstone with `subject`/claims for audit, and returns `Replay` if a consumed refresh token is reused. Replay revokes the whole family — until its newest token would expire — and should be treated as an incident.

`rotate()` has four outcomes: the successor `Token`; a `Replay`; `null` for an unknown or expired token or one of a revoked family; or a `RuntimeException` when the store refuses a write — the presented token then stays valid for a retry, unless the store had already consumed it. Two concurrent rotations of one token, on one host or on two hosts sharing the store, yield at most one `Token`: the other caller gets a `Replay` or `null` and the family is revoked, so a client must not send two refreshes at once. A logout (`revoke()`) racing a refresh returns `true` and leaves no successor alive.

Use `Usage` when access-token `jti` values need persistent revocation or single-use replay protection:

```php
$Usage = new Usage($Vault);
$Verifier->track($Usage);

$Usage->block('access-token-jti', 300);

$SingleUse = new Usage($Vault, single: true);
$Verifier->track($SingleUse);

$OptionalJTI = new Usage($Vault, required: false);
```

`Usage` runs only after signature, temporal claim validation, and optional `Policies` pass. By default it requires the `jti` claim; use `required: false` only when tokens without an identifier should pass without persistent revocation. Single-use mode requires an `exp` claim so the seen `jti` marker expires automatically.

## Basic guard

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Response;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Basic as BasicGuard;

$Basic = new Authenticating(
   new BasicGuard(function (string $username, string $password, Request $Request): bool {
      return $username === 'demo' && $password === 'secret';
   })
);

yield $Router->route('/auth/basic', function (Request $Request, Response $Response) {
   return $Response->JSON->send([
      'authorized' => true,
      'guard' => 'Basic',
   ]);
}, GET, middlewares: [new Authentication($Basic)]);
```

Try it:

```bash :toolbar="true";
curl -u demo:secret http://localhost:8082/auth/basic
```

## Session guard

Use the Session guard when authentication state lives in `$Request->Session`. It checks a session key and exposes the stored value as `$Request->identity`.

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Session as SessionGuard;

$Session = new Authenticating(new SessionGuard(key: 'identity'));

yield $Router->route('/account', function ($Request, $Response) {
   return $Response->JSON->send([
      'authorized' => true,
   ]);
}, GET, middlewares: [new Authentication($Session)]);
```

Session failures return a generic `401 Unauthorized` response without a `WWW-Authenticate` header.

## Remember guard

Use the Remember guard to revive sessions from a persistent trusted-device cookie (remember-me). It validates and rotates the token through the `Bootgly\API\Security\Tokens\Trust` store, regenerates the session id (fixation defense), installs the identity in the session and re-emits the rotated cookie.

```php
use Bootgly\API\Security\Tokens\Trust;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Remember;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Session as SessionGuard;

$Trust = new Trust($Response->Database->Database);
$Auth = new Authentication(new Authenticating(
   new SessionGuard,          // cheap session check wins
   new Remember($Trust)       // cookie revival only on session miss
));
```

The guard owns the remember cookie: login flows call `emit()` after `Trust->issue()` and logout flows call `forget()`. The cookie policy is framework-owned through statics (`Remember::$name`, `$lifetime`, `$secure`, `$httpOnly`, `$sameSite`) — hardened defaults that php.ini cannot downgrade.

`Trust` keeps only the immediately previous validator digest for a fixed,
private five-second grace window. When an in-flight duplicate presents that
exact validator during the window, the guard declines without authenticating,
clearing the cookie or revoking devices. A replay after the window, or any
unrelated wrong validator for a known series, is the stolen-cookie signature:
the store reports `Theft` and the guard clears the cookie only after every
device has been successfully revoked. If that revocation fails, `rotate()`
returns `null` instead of fabricating a theft incident.

`Tokens->revoke()` and `Trust->revoke()` return `null|int`: `0` means the
statement succeeded without matching a row, while `null` means a recorded
database failure. Callers that promise logout-everywhere or credential
invalidation must treat `null` as an infrastructure failure.

The action-token `tokens` table must enforce `UNIQUE (user_id, purpose)`.
`mint()` uses one atomic upsert, so two concurrent callers can both receive a
token while only the winning value remains valid. Apply the Auth scaffold's
`20260822000200_unique_tokens_user_purpose` migration before deploying this
code. Pause action-token writers while MySQL performs the non-transactional
deduplication/index transition. For rollback, restore and drain the old code
first, then optionally remove the unique index after no new worker remains.

The underlying `trusts` table must provide nullable `previous VARCHAR(64)` and
`rotated BIGINT` columns; apply both additive migrations before deploying and
restart or drain all workers as one cohort.

Credential, action-token and trusted-device verdicts are always read from the
primary database, even when replicas are configured. Transaction-backed stores
use `SELECT ... FOR UPDATE` on MySQL/PostgreSQL; PostgreSQL Repeatable Read can
fail closed with SQLSTATE `40001` and requires rollback plus a whole-transaction
retry. SQLite uses a zero-row writer barrier and can fail closed with
`database is locked` for a stale snapshot. Locks last until commit/rollback,
read-only transactions fail closed, and these transactions should remain
short. Constructor signatures do not change; revocation return types are
nullable as described above. See the
**[Authentication guide](/guide/authentication/overview/)** for the complete
session/cookie scaffold and upgrade sequence.

## Multiple guards

You can compose guards in order:

```php
$API = new Authenticating(new JWTGuard($Token));
$API->add(new Bearer(function (string $token, Request $Request): bool {
   return $token === 'legacy-api-token';
}));

yield $Router->route('/api/private', $Handler, GET, middlewares: [new Authentication($API)]);
```

In this example Bootgly tries JWT first, then the opaque Bearer token. If both fail, the JWT guard defines the challenge because it is the first guard.

## Protecting an MCP endpoint

An MCP server exposed over Streamable HTTP is an OAuth protected resource: an unauthenticated call must answer `401` with a challenge that points to the resource metadata, a token without enough scope must answer `403 insufficient_scope`, and browser clients must be able to read the session and challenge headers. The three middlewares cover it together:

```php
use Bootgly\API\Security\Identity;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Bearer;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authorizing;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authorization;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authorization\Scope;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\CORS;

$Bearer = new Bearer(
   Resolver: function (string $token): null|Identity {
      // Look the access token up in your token store.
      return $token === 'demo-mcp-token'
         ? new Identity(id: 'mcp-client', scopes: ['mcp:read'])
         : null;
   },
   realm: 'mcp',
   metadata: 'https://mcp.example.com/.well-known/oauth-protected-resource'
);

yield $Router->route('/mcp', $Handler, [GET, POST, DELETE, OPTIONS], middlewares: [
   new CORS(
      origins: ['https://app.example.com'],
      headers: ['Content-Type', 'Authorization', 'Mcp-Session-Id', 'Mcp-Protocol-Version'],
      expose: ['Mcp-Session-Id', 'WWW-Authenticate']
   ),
   new Authentication(new Authenticating($Bearer)),
   new Authorization(new Authorizing(
      new Scope('mcp:tools', Bearer: $Bearer)
   )),
]);
```

What each request gets back:

- No token → `401 Unauthorized` with `WWW-Authenticate: Bearer realm="mcp", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"` — the client reads the metadata URL and fetches a token.
- An unknown token → `401 Unauthorized` with `WWW-Authenticate: Bearer realm="mcp", error="invalid_token", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"`.
- A token whose identity lacks `mcp:tools` → `403 Forbidden` with `WWW-Authenticate: Bearer realm="mcp", error="insufficient_scope", scope="mcp:tools", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"`, so the client can ask for a token with that scope.
- A preflight (`OPTIONS`) from `https://app.example.com` → `204` from `CORS`, before Authentication runs.

Keep `CORS` first: the `401`/`403` responses then still carry `Access-Control-Allow-Origin` and `Access-Control-Expose-Headers: Mcp-Session-Id, WWW-Authenticate`, which is what lets browser JavaScript read the challenge. A request from an origin outside the allowlist is answered `403` by `CORS` with neither header.

The `JWT` guard is a `Bearer`, so it accepts the same `metadata:` argument and can be passed to `Scope` the same way. See the [Authorization](/manual/WPI/HTTP/HTTP_Server_CLI/Authorization/) page for the `Scope` gate and the [Middlewares](/manual/WPI/HTTP/HTTP_Server_CLI/Middlewares/) page for `CORS`.

## Demo project

The repository includes working examples in `projects/Demo/HTTP_Server_CLI`:

- `router/routes/Authentication.routes.php`

Add `'Authentication'` to `router/router.index.php`, start the demo server, then open `GET /auth` to see runnable commands for Bearer, JWT, and Basic routes.

For the session/cookie flows (registration, e-mail verification, login + remember-me, password reset), see the exportable **Auth** demo in `bootgly-web/projects/Demo/Auth` and the **[Authentication guide](/guide/authentication/overview/)**.

## Reference

### Bootgly\API\Security\JWT\KeyResolver

```php
public function resolve (null|string $id, string $algorithm): null|Key
```

Returns the single `Key` allowed to verify a token, or `null` to refuse it. `JWT::inspect()` calls it once per verification — after the protected header was decoded and its `alg` and `typ` accepted, and before the signature is checked — so a key it returns is the key the signature is then verified with. `$id` is the header's `kid`, already validated as a string, or `null` when the token carries none; `$algorithm` is the token's `alg`. The resolver owns the algorithm check: a key enrolled for a different algorithm must be refused, not returned. A `null` ends the verification immediately — the signature is never checked and no claim is read.

```php
public function fail (): null|Failures
```

Returns the reason the last `resolve()` refused, or `null` when the resolver keeps no failure state. It is consulted **only** after `resolve()` returned `null`, and the result is used as `fail() ?? Failures::Key`, so `null` degrades to the generic "JWT key could not be resolved." message. Any `Failures` case is accepted — `Network`, `Status` and `JWKS` are what `Remote` reports for a JWKS fetch that failed — and the chosen case surfaces to the caller as `Verification->failure`, with `Verification->message` filled from the framework's description of it. Clear the stored failure at the start of `resolve()` so one verification never reads the previous one's reason. Failures are internal diagnostics: HTTP guards still answer the client with a generic Bearer error.

### Bootgly\API\Security\JWT\Remote

```php
public function __construct (string $URI, null|callable $Fetcher = null, null|string $algorithm = 'RS256', int $ttl = 3600, int $cooldown = 60, int $size = 1048576, bool $insecure = false)
```

Creates a resolver for the JWKS at `$URI` (HTTPS, or HTTP only with `insecure: true`). `$Fetcher` replaces the native HTTPS GET and returns the body string or a `Remote\Response`. `$algorithm` pins the resolver to `RS256` (`null` accepts any supported key). `$ttl` caps the lifetime of a fetched set; `$cooldown` sets the origin floor; `$size` bounds the response body in bytes. With the native fetch, each hop is dialed by its resolved addresses and a hop to a non-public address after a public one fails with `Network` (see *Redirect destinations*). Throws `InvalidArgumentException` for an empty or non-HTTPS `$URI`, an unsupported algorithm, a `$ttl` or `$cooldown` outside `0`–`31,536,000`, or a `$size` below `1`.

```php
public int $TTL
```

The operator ceiling on a fetched set's freshness and shared-cache lifetime, in seconds (`0`–`31,536,000`). Cache headers can only shorten it; a positive value shorter than `cooldown` also shortens how long a set the origin confirmed is held (`0` still holds it for one `cooldown`). An invalid assignment throws and keeps the last valid value.

```php
public int $cooldown
```

The origin floor, in seconds (`0`–`31,536,000`, default `60`): a failed fetch is replayed for one `cooldown`, and a set the origin confirmed is held for one — or for `$TTL`, when that is positive and shorter. It also spaces the refresh on an unknown `kid`. `0` disables both. A new value shapes the next origin attempt; an invalid assignment throws and keeps the last valid value.

```php
public function fetch (): KeySet|Failures
```

Returns the key set while it is fresh or held, reads a live shared `Vault` record, or asks the origin — unless the origin is still paused after a failed fetch (one `cooldown`) or an attempt in flight, in which case the last failure (or `Network`) is returned again.

```php
public function refresh (): KeySet|Failures
```

Asks the origin now, bypassing freshness and the origin floor.

### Bootgly\API\Security\JWT\Tokens

```php
public function rotate (string $refresh, int $ttl): null|Replay|Token
```

Consumes `$refresh` and returns its successor, valid for `$ttl` seconds. Returns a `Replay` when the token was already consumed — the family is then revoked until its newest token would expire — and `null` when the token is unknown, expired (also when it expires during this rotation, within the clock skew tolerated between hosts) or of a revoked family — it is not consumed then, unless a revocation lands during the rotation, in which case a retry is a `Replay`. Of concurrent rotations of one token, on one host or across a fleet sharing the store, at most one gets a `Token`; the others get a `Replay` or `null`, with the family revoked. Throws `InvalidArgumentException` for a `$ttl` below `1`, and `RuntimeException` when the store refuses a write or the evict (`'JWT refresh token could not be consumed.'`): the presented token stays valid for a retry, unless the store had already consumed it.

```php
public function revoke (string $refresh): bool
```

Revokes the family of `$refresh` — an active or an already consumed token — until its newest token would expire. Returns `false` only for an unknown or expired token; a logout racing a rotation of the same token returns `true` and leaves no successor alive. Throws `RuntimeException` when the store refuses a write: a retry with the same token completes the revocation.

### Bootgly\API\Security\JWT\Vault

```php
public function __construct (null|string|\Bootgly\ABI\Resources\Cache $storage = null, string $prefix = 'jwt_', null|string $secret = null)
```

Creates the JWT store on a directory (the `file` driver) or on a prepared `Cache` whose driver is atomic. `$secret` (≥ 32 bytes) signs every record; without one, each host derives its own in `{path}{prefix}.secret` — allowed only for the host-local `file`, `memory` and `shared` drivers. Throws `InvalidArgumentException` for an empty prefix or one with a directory separator, a short secret, a non-atomic driver (APCu), or an injected backend other hosts can reach (`redis`, a custom driver) without a secret.

### Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Bearer

```php
public function __construct (Closure $Resolver, string $realm = 'Protected area', string $error = 'invalid_token', string $description = '', string $URI = '', string $scope = '', string $metadata = '')
```

Creates an opaque Bearer guard. `$Resolver` receives `(string $token, Request $Request)` and returns `false`/`null` to deny, `true` to expose the token as `$Request->identity`, or any other value to expose that value. The other arguments fill the `401` challenge: `realm`, `error`, `error_description`, `error_uri`, `scope` and, last, `resource_metadata`; empty values are omitted. On the HTTP server, a request that carries no Bearer token gets the same challenge without `error`, `error_description` and `error_uri` (RFC 6750 §3.1); the WebSocket upgrade still sends the error challenge. Every value is written as an RFC 9110 quoted-string; one holding a control character throws `InvalidArgumentException`, and so does an `error`, `description`, `URI` or `scope` outside its RFC 6750 §3 character set (see the table above). The `JWT` guard takes the same challenge arguments after its `$Token` and `$Policies`.

```php
public private(set) string $metadata
```

The RFC 9728 protected-resource-metadata URL sent as `resource_metadata="…"` in both the `401` challenge and the `403` challenge written by `forbid()`. Empty (the default) omits it.

```php
public function forbid (object $Response, array $scopes): object
```

Writes `403 Forbidden` and `WWW-Authenticate: Bearer realm="…", error="insufficient_scope", scope="…"` (RFC 6750 §3.1) on `$Response`, followed by `resource_metadata="…"` when `metadata` is set. `$scopes` are the scopes the resource requires, sent space-separated; the guard's own `error`, `description`, `URI` and `scope` are not used here. An empty list omits the `scope` attribute. The `Scope` gate calls it when it is given a `Bearer:`. Throws `InvalidArgumentException` when a scope is not an RFC 6750 scope-token (printable ASCII without space, `"` and `\`; empty is refused too).

### Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating\Challenge

```php
public static function quote (string $value): string
```

Returns `$value` as an RFC 9110 quoted-string: wrapped in double quotes, with `\` and `"` escaped by a backslash; bytes `0x80`–`0xFF` pass unchanged. Throws `InvalidArgumentException` when the value holds a control character (any byte `0x00`–`0x1F`, HTAB included, or `0x7F`). Guards use it for every challenge attribute.

```php
public static function announce (object $Response, string $challenge, int $code = 401): object
```

Writes `$challenge` as the `WWW-Authenticate` header and marks the response with `$code`: `401` (the default) for a missing or invalid credential, `403` for a valid one that lacks scope. A response without a `Header` object but invocable is called as `$Response($code, ['WWW-Authenticate' => $challenge], 'Unauthorized'|'Forbidden')`. Throws `InvalidArgumentException` when `$code` is neither `401` nor `403`, before anything is written.

```php
public static function mark (object $Response, int $code = 401): object
```

Marks `$Response` with the status `$code` — through its `code()` method, or its `code` property — and returns it. `$code` is `401` (the default) for a missing or invalid credential, or `403` for an `insufficient_scope` challenge (RFC 6750 §3.1). Throws `InvalidArgumentException` for any other status.

```php
public static function reject (object $Response, int $code = 401): object
```

Produces the plain failure response without a challenge: an invocable `$Response` is called as `$Response($code, [], 'Unauthorized'|'Forbidden')`, any other is marked like `mark()`. `$code` is `401` (the default) or `403`; any other status throws `InvalidArgumentException`.
