# Configuration

Source: https://keyringauth.com/docs/0.x/configuration

## Introduction

You configure Keyring in two places:

- `config/keyring.php` holds values: features, timeouts, limits and route options.
- `app/Providers/KeyringServiceProvider.php` holds behaviour: factors, the policy, risk responses, swapped responses and pages. Put these calls in the provider's `boot()` method.

`keyring:install` publishes a short config file with the options most apps change: `guard`, `username`, `home`, `features`, `registration`, `enrollment_url`, `authenticators_url` and `support_contact`. Every other option keeps its default until you copy it in. Keyring merges your file over its defaults key by key, so `'sessions' => ['absolute' => '7d']` changes only that setting. For the full file, run `php artisan vendor:publish --tag=keyring-config`.

## Durations

Options that take a duration accept seconds, or a string such as `"30s"`, `"15m"`, `"12h"` or `"7d"`. Anything else throws an `InvalidArgumentException`. `timebox` and `webauthn.timeout` also accept milliseconds, such as `"250ms"`, and need a unit.

## Guard and Users

```php
'guard' => 'web',

'username' => 'email',

'email' => 'email',
```

- `guard` is the stateful guard users sign in with. Keyring keeps pending logins, step-up state and enrollments in the session, so it needs a guard that uses sessions.
- `username` is the attribute users type at login. The login form posts it as a field with this name. Keyring lowercases input before it looks users up, so store it in lowercase.
- `email` holds the user's address. The [email change flow](https://keyringauth.com/docs/0.x/protected-changes#changing-the-email-address) changes it, the password reset forms post to it, and email codes take their hint from it. Change it only if users sign in with something else, such as a handle. Then set `username` to that attribute and keep `email` on the address.

## Features

```php
use Keyring\Features;

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updatePasswords(),
    Features::securityLog(),
    // Features::manageAuthenticators(),
    // Features::devices(),
    // Features::emailChanges(),
    // Features::impersonation(),
],
```

Signing in and out, challenges and step-up are always on. Everything else is a feature, which adds its routes only once it's in this list. An unknown feature stops the application from booting. Without a config file, Keyring turns on registration, password resets, email verification, password changes and the security log, which are also the installer's defaults. Your list replaces that default list as a whole, so keep `Features::securityLog()` in it unless you want those events in [your app's log](https://keyringauth.com/docs/0.x/security-log-and-emails#without-the-table). See [Adding Features](https://keyringauth.com/docs/0.x/quick-start#adding-features).

`Features::enabled(Features::devices())` checks one feature in your own code, and `Features::all()` lists them all.

## Registration

```php
'registration' => [
    'reveal_taken' => false,
],
```

By default, registering gives the same answer whether or not the address has an account. New users sign in once they've followed the link emailed to them. An address that already has an account is emailed that someone tried to register with it. This needs `Features::emailVerification()` and a `MustVerifyEmail` user model. The app won't boot with registration hiding addresses and email verification off.

With `reveal_taken` set to `true`, the form says "has already been taken", and new users sign in straight away. That lets anyone check whether an address has an account. See [Registration](https://keyringauth.com/docs/0.x/sign-in-flow#registration) for what each setting reveals.

## Redirects

```php
'home' => '/dashboard',
```

`home` is where users go after signing in or confirming, when there's no intended URL or the intended URL is on another site. See [Where They Go Next](https://keyringauth.com/docs/0.x/sign-in-flow#where-they-go-next). It's also used after email verification, with `?verified=1` added, and after confirming an email change while signed in. It may be a full URL, such as a page on a [frontend of your own](https://keyringauth.com/docs/0.x/headless#where-each-answer-goes). Signed-out users go to the route named `login`.

## Routes

```php
'routes' => true,

'prefix' => '',

'domain' => null,

'middleware' => ['web', AddSecurityHeaders::class],
```

Keyring registers its routes in a group with this prefix, domain and middleware.

`AddSecurityHeaders` sends `Cache-Control: no-store, private`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and `Cross-Origin-Opener-Policy: same-origin-allow-popups` on every Keyring response, with `Referrer-Policy: same-origin`, or `no-referrer` on pages that emailed links open. It leaves `X-Frame-Options` off a response that already says who may frame it, so a middleware listed after it can allow framing. See [Links and Headers](https://keyringauth.com/docs/0.x/security#links-and-headers).

> [!WARNING]
> If your app sets these headers itself, you may remove `AddSecurityHeaders`. You still need to keep emailed-link URLs out of `Referer` headers some other way, since they carry their token.

If `domain` is a host of Keyring's own, such as `auth.example.com`, a user who stopped on `APP_URL`'s host still goes back to it after signing in or confirming, since both hosts are the app's own origins. Any other host isn't gone back to.

To register nothing and place the routes yourself, set `routes` to `false` and call `Keyring::routes()`:

```php
Route::prefix('account')->middleware('throttle:60,1')->group(fn () => Keyring::routes());
```

`Keyring::routes()` adds the `middleware` option, but not `prefix` or `domain`, so your group sets those. If the group is on its own host, set `domain` to that host too. To change the routes themselves, copy `vendor/keyring/keyring/routes/keyring.php` into your app and keep the route names. Keyring's controllers, emails and middleware link to routes by name, such as `login` and `keyring.devices.report`. The browser package uses the default paths. If you change the prefix, tell it with [`configureRoutes({ prefix })`](https://keyringauth.com/docs/0.x/frontend#changing-routes).

## Pages

```php
'pages' => true,
```

Keyring renders its [pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages) as Inertia components or Blade views. A JSON request for a page gets its name and props. Set `pages` to `false` when every page lives in a frontend Laravel doesn't serve, such as Nuxt. Keyring then answers anything but JSON with a `404`, and never throws `MissingPage`. Pages rendered with a closure through `Keyring::page()` still render. See [Headless Frontends](https://keyringauth.com/docs/0.x/headless).

## WebAuthn

```php
'webauthn' => [
    'relying_party' => [
        'id' => env('KEYRING_WEBAUTHN_RP_ID'),
    ],
    'origins' => [],
    'timeout' => '60s',
    'login_options_for' => '5m',
    'attestation_roots' => [],
    'algorithms' => ['ES256', 'EdDSA'],
    'minimum_rsa_bits' => 2048,
],
```

`relying_party.id` defaults to your `APP_URL` host, and `origins` to `APP_URL`. See [Relying Party and Origins](https://keyringauth.com/docs/0.x/passkeys#relying-party-and-origins).

- `timeout` is how long the browser waits for a passkey or security key.
- `login_options_for` is how long the challenge for a [usernameless sign-in](https://keyringauth.com/docs/0.x/passkeys#signing-in-without-a-username) can be answered. The login page requests one on load for autofill. It's never shorter than `timeout`.
- `attestation_roots` lists the root certificates a key's attestation must chain to, as PEM text or paths to PEM files. Only a factor set up with [`requireAttestation()`](https://keyringauth.com/docs/0.x/passkeys#requiring-attestation) reads it, and that refuses every key while the list is empty.
- `algorithms` lists the signatures keys may use, in order of preference: `ES256`, `EdDSA` and `RS256`. `EdDSA` needs the `sodium` extension. `RS256` is off by default, since OWASP ASVS doesn't approve it, though some Windows Hello setups sign with it. With it on, `minimum_rsa_bits` sets the shortest RSA key accepted, never under 2048. See [Signature Algorithms](https://keyringauth.com/docs/0.x/passkeys#signature-algorithms).

## Single Sign-On

```php
'sso' => [
    'providers' => [],
    'request_for' => '10m',
    'cache_for' => '1h',
    'store' => null,
],
```

`providers` lists the identity providers users can sign in with, by name. Keyring registers the `/auth/{provider}` routes whenever this isn't empty. They answer `404` until the `SingleSignOn` factor is registered. `request_for` is how long a user sent to a provider has to come back. `cache_for` is how long discovery documents and signing keys are cached in `store`, where `null` is your default store. Both are [durations](https://keyringauth.com/docs/0.x/configuration#durations). Each provider's own options, such as `driver`, `client_id` and `freshness`, are in [Single Sign-On](https://keyringauth.com/docs/0.x/sso#configuration).

## Account Changes and Enrollment

```php
'changes_middleware' => ['keyring.fresh:15m'],

'authenticator_changes' => [
    'established_after' => '7d',
    'skip_with_totp' => false,
],

'enrollment_url' => null,

'enrollment_except' => [],

'authenticators_url' => null,

'password_change_url' => null,

'password_change_except' => [],

'support_contact' => null,

'enrollments' => [
    'keep_for' => '15m',
],
```

| Key | Meaning |
|---|---|
| `changes_middleware` | Extra middleware for adding, renaming and removing sign-in methods, ending sessions, revoking devices, changing the password and starting an email change. It's added to `auth:{guard}`, so don't list `auth` here. By default these need a verification from the last 15 minutes ([Step-Up](https://keyringauth.com/docs/0.x/step-up#fresh-verification)). They also refuse a browser [impersonating](https://keyringauth.com/docs/0.x/impersonation#whats-refused-while-impersonating) the user, whatever this says. |
| `authenticator_changes.established_after` | How long an account must have had an authenticator, or a set of recovery codes, before it's [established](https://keyringauth.com/docs/0.x/authenticators#established-authenticators). Until then a new passkey doesn't make `noDowngrade()` ask for one. It also sets how long sign-in methods stay [frozen](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods) after one is added, or after an established one is removed or replaced, and how long a second factor added to an account with no older one needs [the password](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor). At `0` the first two are off, so a stolen session that has just signed in could lock the owner out again. Separate from `email_changes.established_after`. |
| `authenticator_changes.skip_with_totp` | While an account is frozen, the owner can still make one change by proving, in the same request, a passkey or security key the account has had for `established_after`, from before the session signed in ([Making a Change With an Established Key](https://keyringauth.com/docs/0.x/authenticators#making-a-change-with-an-established-key)). `true` lets an established authenticator app do that too. It's off because a six-digit code can be phished as it's typed. |
| `enrollment_url` | Where the `keyring.enrolled` middleware sends users who still need a second factor, and where step-up sends users who lack what a route needs. `null` answers with a `403`. The installer sets `/settings/security` when you require a second factor. See [Requiring a Second Factor](https://keyringauth.com/docs/0.x/policies#requiring-a-second-factor). |
| `enrollment_except` | More route names those users may reach meanwhile, with `*` as a wildcard, such as `['billing.*', 'support']`. The enrollment page, Keyring's own routes, signing out, email verification and changing the password are always allowed, and so is `password_change_url` while the user has to choose a new password. |
| `authenticators_url` | Your page for seeing and removing sign-in methods. The `authenticator_added` and `recovery_codes_generated` emails link to it. A path is put after `APP_URL`, or the root from `Keyring::linkRootUsing()`, and a full URL is used as it is. `null` leaves the link out. See [Email Types](https://keyringauth.com/docs/0.x/security-log-and-emails#email-types). |
| `password_change_url` | Where a user who must choose a new password is sent from every other page, until they do. `null` answers with a `403`. A held user gets past `keyring.enrolled` there, so serve only the change-password page at this path. See [Requiring a Password Change](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change). |
| `password_change_except` | More route names those users may reach meanwhile, with `*` as a wildcard. Only route names are matched. The change-password page, `PUT /user/password`, the confirm routes, signing out and email verification are always allowed. Only list routes that are safe to reach while the password may be compromised. |
| `support_contact` | A page's URL, or an email address, where users can reach you. Every notification receives it as `$contact`, and the security notices, the emailed code and the email change notice end with a line pointing to it. `null` leaves that line out. See [Security Emails](https://keyringauth.com/docs/0.x/security-log-and-emails#a-support-contact). |
| `enrollments.keep_for` | How long a user has to finish adding a sign-in method once started. See [Adding an Authenticator](https://keyringauth.com/docs/0.x/authenticators#adding-an-authenticator). |

> [!WARNING]
> Listing `keyring.*` in `password_change_except` would let whoever has the password add sign-in methods, change the email address and sign out sessions. A passkey added during the hold would also keep working after the password changes.

## Devices

```php
'devices' => [
    'cookie' => null,
    'cookie_lifetime' => '400d',
    'limit' => 50,
    'trust_for' => '30d',
    'report_link_for' => '7d',
    'keep_revoked_for' => '30d',
    'keep_unseen_for' => '365d',
    'locator' => NullLocator::class,
],
```

`cookie` names the device cookie. `null` gives `known_device`, prefixed `__Host-` over HTTPS, or `__Secure-` when `session.domain` is set or `session.path` isn't `/`. See [Keyring's Cookies](https://keyringauth.com/docs/0.x/devices-and-sessions#keyrings-cookies). A name you set is used exactly. `cookie_lifetime` is how long the browser keeps it. 400 days is the most browsers allow.

`limit` is how many devices an account keeps. A sign-in from a new browser past that limit forgets, and signs out, the device seen longest ago. Only a sign-in that proved something makes room this way. A browser returning on ["remember me"](https://keyringauth.com/docs/0.x/devices-and-sessions#remember-me) never pushes another device out. At the limit, a remembered browser the account hasn't used gets no device, and the owner is told anyway. `null` means no limit.

`trust_for` is how long "don't ask again on this device" lasts. `null` hides that option. A trusted device is an input to your policy, never a factor. `report_link_for` is how long a ["this wasn't me" link](https://keyringauth.com/docs/0.x/devices-and-sessions#the-this-wasnt-me-link) works.

[`keyring:prune`](https://keyringauth.com/docs/0.x/devices-and-sessions#pruning) deletes a device `keep_revoked_for` after it's revoked, or `keep_unseen_for` after it was last seen. `locator` is the class that works out a request's location.

## Sessions

```php
'sessions' => [
    'driver' => env('KEYRING_SESSION_DRIVER', 'database'),
    'connection' => null,
    'table' => 'keyring_sessions',
    'store' => null,
    'max' => 100,
    'idle' => '2h',
    'remember_idle' => '14d',
    'absolute' => '30d',
    'levels' => [
        'aal2' => ['idle' => '1h', 'absolute' => '24h'],
        'aal3' => ['idle' => '15m', 'absolute' => '12h'],
    ],
    'end_on_lapse' => false,
    'middleware' => true,
    'overlapping_requests' => true,
    'remember_cookie' => null,
    'remember_grace' => '10s',
    'continue_as_guest' => [],
    'sweep_every' => null,
    'sweep_limit' => 1000,
],
```

Keyring keeps its own registry of signed-in sessions, so they can be listed and revoked on any session driver. See [The Session Registry](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-registry).

| Key | Meaning |
|---|---|
| `driver` | `database`, `cache`, or a driver you've added. |
| `connection`, `table` | Used by the `database` driver. |
| `store` | The cache store for the `cache` driver. `null` is your default. Pick a store that keeps keys until they expire. One that evicts under memory pressure can drop a user's session list, so a sign-out everywhere would miss sessions. |
| `max` | Sessions one account may have at once. A sign-in past that ends the session unused longest. `null` means no limit. See [How Many Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions#how-many-sessions). |
| `idle` | How long a session may sit unused before it ends. `null` leaves that to Laravel's session lifetime. |
| `remember_idle` | The same, for a browser that ticked "remember me": how long it may stay away and still be signed back in, with nothing proved. `null` allows the whole `absolute` limit. See [Inactivity and "Remember Me"](https://keyringauth.com/docs/0.x/devices-and-sessions#inactivity-and-remember-me). |
| `absolute` | The longest a session can last, however active. |
| `levels` | How long each assurance level keeps counting, keyed `aal1`, `aal2` or `aal3`, with `idle` and `absolute` limits. The defaults follow NIST: AAL2 is 1h and 24h, AAL3 is 15m and 12h. Past them, routes that need the level ask the user to verify again. |
| `end_on_lapse` | Whether a session ends when its level runs out. Otherwise it carries on at a lower level. See [Ending a Session With Its Level](https://keyringauth.com/docs/0.x/devices-and-sessions#ending-a-session-with-its-level). |
| `middleware` | Whether Keyring adds its session middleware to the `web` group. With `false`, add `keyring.session` yourself, to Keyring's own routes, `POST /logout` above all. See [The Session Middleware](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-middleware). |
| `overlapping_requests` | Whether Keyring's `StartSession` replaces Laravel's, so a request already in flight when a sign-in, step-up or sign-out replaced the session can't write the old one back. This covers every route that starts a session, Sanctum's stateful API included. `false` keeps Laravel's. See [Requests That Overlap a Sign In](https://keyringauth.com/docs/0.x/devices-and-sessions#requests-that-overlap-a-sign-in). |
| `remember_cookie` | The cookie that ties "remember me" to its session. `null` is `remembered_session`, prefixed over HTTPS like the device cookie. |
| `remember_grace` | After the "remember me" cookie is used, the browser's other requests sent with it still get in for this long. Each cookie works once. Sending a used one after the grace period ends the session. `0` leaves no room, so requests sent together end it. See [a cookie used twice](https://keyringauth.com/docs/0.x/devices-and-sessions#a-cookie-used-twice). |
| `continue_as_guest` | Route names, as `Request::routeIs()` takes them, such as `docs.*`. A page visit whose session ended is asked again as a guest, with the `signed-out` status flashed, instead of being sent to log in. JSON requests still get a `401`. See [Pages That Also Serve Guests](https://keyringauth.com/docs/0.x/devices-and-sessions#pages-that-also-serve-guests). |
| `sweep_every` | How often [`keyring:sweep`](https://keyringauth.com/docs/0.x/devices-and-sessions#sweeping-ended-sessions) runs on the `database` driver, such as `'5m'`. It ends sessions that timed out with no request, and announces again any ended session whose event was lost. A bare number counts seconds. Anything longer than 12 hours runs every 12 hours, with a warning. `null` leaves the sweep off. `0` and anything that isn't a duration also turn it off, with a warning in your log. |
| `sweep_limit` | The most sessions one run announces again, and the most it ends. A value that isn't a positive number is taken as `1000`, and the limit is capped at `10000`. |

## Impersonation

```php
'impersonation' => [
    'lifetime' => '1h',
    'show_in_sessions' => true,
    'show_in_activity' => true,
    'middleware' => ['keyring:aal2', 'keyring.fresh:15m'],
    'redirect_url' => null,
    'return_url' => null,
],
```

These only matter with `Features::impersonation()` on and [`Keyring::allowImpersonationWhen()`](https://keyringauth.com/docs/0.x/impersonation#who-may-impersonate-whom) set.

| Key | Meaning |
|---|---|
| `lifetime` | How long an impersonation lasts before it ends and returns the impersonator. It's never longer than `sessions.absolute`. `null` is an hour. With the feature on, a value that isn't a duration, or is `0`, throws an `InvalidArgumentException` naming the option when the app boots. See [The Time Limit](https://keyringauth.com/docs/0.x/impersonation#the-time-limit). |
| `show_in_sessions` | Whether the impersonated session shows in the user's [sessions list](https://keyringauth.com/docs/0.x/impersonation#the-sessions-list), marked with who is in it, so they can end it. With `false` it's left out, except from the list the impersonated session asks for. It still ends with the other sessions, and still counts in "sign out everywhere else". |
| `show_in_activity` | Whether `impersonation_started` and `impersonation_ended` appear in [`Keyring::activity()`](https://keyringauth.com/docs/0.x/security-log-and-emails#showing-recent-activity) on both accounts. With `false` they're listed in `Keyring::unlistedActivityTypes()`, and still written. This is the only way to hide Keyring's own types. It doesn't keep the session secret either: what the impersonator does, such as signing out, stays in the user's activity. See [The Security Log and Events](https://keyringauth.com/docs/0.x/impersonation#security-log-and-events). |
| `middleware` | What starting an impersonation takes, on top of being signed in and not already impersonating. By default, two factors proved in the last 15 minutes. An empty list asks for nothing more. |
| `redirect_url` | Where starting goes. `null` is `home`. |
| `return_url` | Where stopping, or running out, goes. `null` is `home`. |

## Protected Attributes and Email Changes

```php
'protected' => [],

'email_changes' => [
    'confirmable_for' => '24h',
    'revertable_for' => '7d',
    'established_after' => '7d',
    'sign_out_others' => true,
    'keep_ended_for' => '30d',
],
```

`protected` lists attributes that only change through Keyring's flows. Any other change throws, unless wrapped in `Keyring::withoutProtection()`. `Features::updatePasswords()` adds `password`, and `Features::emailChanges()` adds the [`email` attribute](https://keyringauth.com/docs/0.x/configuration#guard-and-users). List others here. See [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes).

`email_changes.confirmable_for` is how long the emailed confirmation link works. `revertable_for` is how long the old address can undo the change. `established_after` is how long an account must have had a second factor before proving it lets a change skip the old address's confirmation. It also sets how far back undoing a change removes sign-in methods. See [Confirming](https://keyringauth.com/docs/0.x/protected-changes#confirming). This is separate from [`authenticator_changes.established_after`](https://keyringauth.com/docs/0.x/configuration#account-changes-and-enrollment).

When a change applies, `sign_out_others` ends the account's other sessions. `keep_ended_for` is how long a finished change is kept before `keyring:prune` deletes it.

## Passwords

```php
'passwords' => [
    'min_with_mfa' => 8,
    'min_without_mfa' => 15,
    'max' => 128,
    'uncompromised' => null,
    'refuse_unchecked' => false,
    'context' => [],
    'broker' => null,
],
```

For the rules, see [Password Rules](https://keyringauth.com/docs/0.x/protected-changes#password-rules).

`min_with_mfa` and `min_without_mfa` are counted in characters. Neither can go below 8, the shortest that OWASP ASVS 5.0.0 (6.2.1) and NIST SP 800-63B-4 (Sec. 3.1.1.2) allow. A lower value throws a `LogicException` when the app boots, and wherever the option is read. Keyring never quietly uses 8 instead.

`max` is counted in characters, but the hasher decides how many you get. Bcrypt, Laravel's default, reads only the first 72 bytes, so with bcrypt Keyring refuses anything longer instead of ignoring the end. That's 72 plain characters, 36 accented or Cyrillic ones, 24 Chinese, Japanese or Korean ones, or 18 emoji. OWASP ASVS 5.0.0 (6.2.9) asks for at least 64 characters, which bcrypt can't promise.

To accept every password up to `max`, hash with argon2id. Users who still have bcrypt hashes are rehashed as they sign in, so keep `HASH_VERIFY` off while some remain:

```bash
HASH_DRIVER=argon2id
HASH_VERIFY=false
```

The [conformance suite](https://keyringauth.com/docs/0.x/testing#the-conformance-suite) fails on bcrypt until you switch, or say you're keeping it.

`context` lists words a password mustn't be made of: your organisation, products, systems, projects, departments and roles, as OWASP ASVS 5.0.0 (6.1.2) asks. Keyring always adds your app's name and what it knows about the user. See [Context-Specific Words](https://keyringauth.com/docs/0.x/protected-changes#context-specific-words).

`uncompromised` checks new passwords against Have I Been Pwned. `null`, the default, runs the check in production only, so local and test runs make no network calls. `true` or `false` chooses for every environment.

Laravel's check fails open. When Have I Been Pwned can't be reached, times out or errors, the password is let through, and only the [bundled list](https://keyringauth.com/docs/0.x/protected-changes#password-rules) of common passwords stands in the way. Set `refuse_unchecked` to `true` to refuse instead. Keyring makes the request itself, sending only the first five characters of the password's SHA-1. A password with no answer is refused with `keyring::keyring.password_unchecked`, which asks the user to try again. The cost is that nobody can register, change or reset a password while the service is unreachable. Keyring waits up to 10 seconds and asks only `api.pwnedpasswords.com`. It only applies where `uncompromised` runs.

Laravel's check uses the `UncompromisedVerifier` bound in the container, so you may bind your own. `refuse_unchecked` doesn't use that binding. With your own verifier, leave the option off and have it answer `false` when it can't check.

`broker` is the password broker for resets. `null` is your default.

## Risk

```php
'risk' => [
    'levels' => ['medium' => 30, 'high' => 60, 'critical' => 90],
    'recent_change' => '7d',
    'store' => null,
],
```

Signal scores add up to a level from 0 to 100. `levels` sets the thresholds. `recent_change` is how long after an email change the `RecentlyChangedRecovery` signal fires. `store` is the cache store for risk locks, where `null` is your default. Use a database or Redis store, not Octane's `octane` store. See [Octane's Cache Store](https://keyringauth.com/docs/0.x/security#octanes-cache-store) and [Risk](https://keyringauth.com/docs/0.x/risk).

## Security Log

```php
'security_log' => [
    'keep_for' => '180d',
    'channel' => env('KEYRING_LOG_CHANNEL'),
    'context_key' => 'trace_id',
    'refusals' => 20,
    'refusals_per' => '1h',
    'alerts' => ['second_factor_failed', 'device_reported', 'email_change_reverted', 'clone_suspected', 'remember_me_reused', 'session_contested'],
    'unlisted' => [],
],

'prune_at' => '03:00',
```

`keep_for` is how long entries are kept before [`keyring:prune`](https://keyringauth.com/docs/0.x/devices-and-sessions#pruning) deletes them.

`channel` is where events go when `Features::securityLog()` is off. `null` is your default channel. Without the table, "was this you?" alerts and the `RepeatedFactorFailures`, `SuccessAfterFailures` and `CredentialStuffing` risk signals don't work, since they read the table. See [Without the Table](https://keyringauth.com/docs/0.x/security-log-and-emails#without-the-table).

`context_key` is the key in Laravel's Context where your app keeps a request's ID. Each entry the request writes carries it. Without one, Keyring makes an ID per request. `null` leaves the ID out. See [Request IDs](https://keyringauth.com/docs/0.x/security-log-and-emails#request-ids).

`refusals` caps how many refused entries of one type are written about one account, or about one IP address when no account is known, in each `refusals_per` period. `null` writes them all. See [Refusals That Repeat](https://keyringauth.com/docs/0.x/security-log-and-emails#refusals-that-repeat).

`alerts` lists the entry types shown once as ["was this you?" alerts](https://keyringauth.com/docs/0.x/security-log-and-emails#was-this-you-alerts) at the next sign in.

`unlisted` lists entry types that `Keyring::activity` leaves out, for entries about a user that aren't something they did. Strings only, and Keyring's own types are ignored. To hide the impersonation entries, use [`impersonation.show_in_activity`](https://keyringauth.com/docs/0.x/configuration#impersonation). See [Showing Recent Activity](https://keyringauth.com/docs/0.x/security-log-and-emails#showing-recent-activity).

`prune_at` is the time of day [`keyring:prune`](https://keyringauth.com/docs/0.x/devices-and-sessions#pruning) is scheduled for. It deletes everything past its time, not only log entries. `null` leaves scheduling to you.

## Pending Logins, Timebox and Rate Limits

```php
'pending_logins' => [
    'keep_for' => '10m',
],

'timebox' => '500ms',

'limits' => [
    'per_account' => 5,
    'per_ip' => 20,
    'consecutive' => 100,
    'consecutive_elsewhere' => 80,
    'remember_names_for' => '30d',
    'longest_lock' => '24h',
    'longest_ip_lock' => '15m',
    'lock_after' => null,
    'codes' => 3,
    'codes_per' => '10m',
    'notices' => 5,
    'notices_per' => '1h',
],
```

`pending_logins.keep_for` is how long a half-finished login or confirmation stays valid. It's also the `expiresAt` the challenge page shows.

`timebox` is the minimum time a refused verification takes. Every refusal waits, including ones refused by a rate limit or validation, registrations and refused password resets, so timing doesn't reveal whether an account exists. Verifications that pass return straight away. The timebox only hides work shorter than it. Keep it comfortably longer than one password hash takes on your servers, since an account's password is checked at the cost of its stored hash. Bcrypt at 12 rounds takes around 200ms on current hardware. When a refusal takes longer than `timebox`, Keyring logs a warning, at most once an hour. The [conformance suite](https://keyringauth.com/docs/0.x/testing#the-conformance-suite) also times a hash in your tests.

`per_account` and `per_ip` are the default attempts per minute, for each factor, per account and per IP address. `consecutive` is how many failures in a row one of an account's authenticators allows before it's refused for that account. `null` means no cap. 100 is the most NIST SP 800-63B-4 allows (Sec. 3.2.2). These are counted in `keyring_failure_counts`, and nothing lifts a refusal by itself. See [At the Cap](https://keyringauth.com/docs/0.x/security#at-the-cap). `consecutive_elsewhere` is how many of those may come from browsers the account hasn't signed in from. The rest are kept for the owner's own sign-ins. It only applies with `Features::devices()` on, and `null` keeps nothing back.

`remember_names_for` is how long the cache keeps failures counted under each typed username, from the first one. A sign-in doesn't clear them.

Each lockout lasts twice as long as the last, up to `longest_lock`, or `longest_ip_lock` for a whole IP address. `lock_after` refuses an account as it would be at the cap, once it has been locked out that many times in a day. It stays refused until a password reset. See [Locking Until a Reset](https://keyringauth.com/docs/0.x/security#locking-until-a-reset).

`codes` and `codes_per` cap how many codes an account can be sent for one factor in each period, in each of three buckets: sign-ins from browsers that never signed in to the account, sign-ins from browsers that did, and step-ups and enrollments. So an account is sent at most three times `codes` per factor in each period. See [Rate Limiting](https://keyringauth.com/docs/0.x/security#rate-limiting). `notices` and `notices_per` cap security notices of one kind, or email change requests, per account or address. Registration mails an address at that rate too. See [Rate Limiting](https://keyringauth.com/docs/0.x/security#rate-limiting).

Keyring keeps its counts and locks in the cache store Laravel's rate limiter uses: `cache.limiter` in `config/cache.php`, or your default store. Point it at a database or Redis store. Octane's `octane` store is in memory, isn't atomic across workers, and is emptied by a restart. See [Octane's Cache Store](https://keyringauth.com/docs/0.x/security#octanes-cache-store).

Each of Keyring's four limiters answers with `TooManyAttempts`: a `429` that dispatches `Keyring\Events\RateLimited`, which the security log records as [`rate_limited`](https://keyringauth.com/docs/0.x/security-log-and-emails#entry-types). To change one, define a limiter of the same name in a service provider's `boot()` method.

| Limiter | Covers | Default |
|---|---|---|
| `keyring` | Registration, password resets, enrollment, email changes, verification emails, and the buttons on pages opened from emailed links | 6 a minute per user, or per IP address for guests |
| `keyring-session-changes` | `PUT /user/password`, `DELETE /user/sessions` and `DELETE /user/devices` | 6 a minute per session, and 30 a minute for all of the user's sessions together |
| `keyring-login-options` | `GET /login/{factor}/options` and the identity provider redirects | 60 a minute per IP address |
| `keyring-pages` | The pages opened from emailed links | 60 a minute per IP address |

Routes that use `keyring` apply it with `keyring.throttle`, which runs after the session middleware and the route's other checks, so requests that are signed out aren't counted. `keyring.throttle:{name}` uses another limiter. For example, to allow 10 requests a minute:

```php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Keyring\Support\TooManyAttempts;

RateLimiter::for('keyring', fn (Request $request) => Limit::perMinute(10)
    ->by($request->user() ? $request->user()->getMorphClass().':'.$request->user()->getKey() : $request->ip())
    ->response(new TooManyAttempts('keyring')));
```

The 30 in `keyring-session-changes` is the ceiling for guesses at `current_password` from someone signed in on many sessions. A limiter may return a list of limits, as Keyring's does.

## Messages and Translations

Keyring's text lives in two translation files, under the `keyring::` namespace:

| File | What It Holds |
|---|---|
| `lang/en/keyring.php` | Validation and error messages, such as `keyring::keyring.invalid`. |
| `lang/en/status.php` | The message for each status slug, such as `keyring::status.password-updated`. See [Status Responses](https://keyringauth.com/docs/0.x/sign-in-flow#status-responses). |

Publish them to change the wording or add languages. Email wording lives in [your notification classes](https://keyringauth.com/docs/0.x/security-log-and-emails#security-emails).

```bash
php artisan vendor:publish --tag=keyring-lang
```

## The Keyring Facade

The `Keyring\Facades\Keyring` facade is the entry point for what you set in code:

| Method | What It Does |
|---|---|
| `Keyring::factors([...])` | Sets the factors users can use. See [Factors](https://keyringauth.com/docs/0.x/factors). |
| `Keyring::extend($key, $resolver)` | Adds one factor from a closure. Its `key()` must match `$key`. |
| `Keyring::require($requirement)` | Sets the policy. See [Policies](https://keyringauth.com/docs/0.x/policies). |
| `Keyring::pipeline($callback)` | Changes the verification steps. See [The Pipeline](https://keyringauth.com/docs/0.x/sign-in-flow#the-verification-pipeline). |
| `Keyring::respondWith($contract, $implementation)` | Swaps a response. See [Responses](https://keyringauth.com/docs/0.x/sign-in-flow#responses). |
| `Keyring::page($name, $component)` | Changes the component a page renders. See [Pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages). |
| `Keyring::risk()->signals([...])->respond(...)` | Configures risk signals and actions. `push(...)` adds to the signals already on. See [Risk](https://keyringauth.com/docs/0.x/risk). |
| `Keyring::notifications([...])` | Replaces a type's notification with your class, or `null` to send none. Unknown types throw an `InvalidArgumentException`. See [Security Emails](https://keyringauth.com/docs/0.x/security-log-and-emails#security-emails). |
| `Keyring::createUsersUsing($action)` | Sets the registration action. See [Registration](https://keyringauth.com/docs/0.x/sign-in-flow#registration). |
| `Keyring::resetUserPasswordsUsing($action)` | Sets the password reset action. See [Resetting the Password](https://keyringauth.com/docs/0.x/protected-changes#resetting-the-password). |
| `Keyring::updateUserPasswordsUsing($action)` | Sets the password change action. See [Changing the Password](https://keyringauth.com/docs/0.x/protected-changes#changing-the-password). |
| `Keyring::validateEmailChangesUsing($action)` | Sets the email change validation action. See [Requesting a Change](https://keyringauth.com/docs/0.x/protected-changes#requesting-a-change). |
| `Keyring::routes()` | Registers Keyring's routes yourself, when `routes` is `false`. See [Routes](https://keyringauth.com/docs/0.x/configuration#routes). |
| `Keyring::useAuthenticatorModel($model)`, `useDeviceModel`, `usePendingChangeModel`, `useSecurityEventModel` and `useFailureCountModel` | Use your subclass of the matching `Keyring\Models` class. See [Your Own Device Model](https://keyringauth.com/docs/0.x/devices-and-sessions#your-own-device-model). |
| `Keyring::attempt($request, $factor)` | Starts a sign-in from a route of your own, through the login form's pipeline. See [Starting a Sign In Yourself](https://keyringauth.com/docs/0.x/sign-in-flow#starting-a-sign-in-yourself). |
| `Keyring::requirePasswordChange($user, $reason = null)` | Holds a user until they choose a new password. `requiresPasswordChange($user)` asks if they're held. `cancelPasswordChange($user)` releases them and forgets the password the hold was placed over. See [Requiring a Password Change](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change). |
| `Keyring::unlock($user, $factor = null)` | Lets a locked-out user try again without a reset. It lifts their risk lock and clears limits, locks and failures in a row on the factors that can start a sign-in, such as the password and passkeys. A second factor refused at the cap needs its name: `Keyring::unlock($user, 'totp')`. See [At the Cap](https://keyringauth.com/docs/0.x/security#at-the-cap). |
| `Keyring::allowSignInWhen($callback)` | Decides who may be signed in at all, such as accounts that aren't banned. See [Who May Sign In](https://keyringauth.com/docs/0.x/sign-in-flow#who-may-sign-in). |
| `Keyring::allowEnrollmentWhen($callback)` | Decides who may add a sign-in method, in place of the verified email rule. See [Who May Enroll](https://keyringauth.com/docs/0.x/authenticators#who-may-enroll). |
| `Keyring::allowImpersonationWhen($callback)` | Decides who may sign in as whom. Nobody may until it's called. See [Who May Impersonate Whom](https://keyringauth.com/docs/0.x/impersonation#who-may-impersonate-whom). |
| `Keyring::impersonate($request, $user)` | Signs in as another user from your own controller. `Keyring::stopImpersonating($request)` goes back. See [From Your Own Code](https://keyringauth.com/docs/0.x/impersonation#from-your-own-code). |
| `Keyring::linkRootUsing($callback)` | Where emailed links start, in place of `APP_URL`. See [Emailed Links](https://keyringauth.com/docs/0.x/security#emailed-links). |
| `Keyring::sso()` | The providers in `sso.providers`. `extend($driver, $resolver)` adds a [driver](https://keyringauth.com/docs/0.x/sso#custom-drivers). `start()` and `complete()` sign in [from your own routes](https://keyringauth.com/docs/0.x/sso#signing-up-with-a-provider). |
| `Keyring::recordIpsUsing($callback)` | What Keyring stores as a request's IP address. See [What's Stored](https://keyringauth.com/docs/0.x/security-log-and-emails#whats-stored). |
| `Keyring::describeDevicesUsing($callback)` | Names devices your own way, in place of "Firefox on Windows". See [Device Names](https://keyringauth.com/docs/0.x/devices-and-sessions#device-names). |
| `Keyring::findUsersUsing($callback)` | Finds the user a typed username belongs to, for a password sign-in. See [Finding the User](https://keyringauth.com/docs/0.x/sign-in-flow#finding-the-user). |
| `Keyring::normalizeUsernamesUsing($callback)` | Normalises usernames your own way. See [Finding the User](https://keyringauth.com/docs/0.x/sign-in-flow#finding-the-user). |
| `Keyring::signInAfterRegistering($when)` | Whether registering signs the user in, where `registration.reveal_taken` allows it. See [Saying When an Address Is Taken](https://keyringauth.com/docs/0.x/sign-in-flow#saying-when-an-address-is-taken). |
| `Keyring::findUser($request)` | The user a password sign-in is for, for a primary factor of your own. |
| `Keyring::signsInAfterRegistering($user, $request)` | Whether registering signs this user in, for a registration flow of your own. |
| `Keyring::hidesRegisteredAddresses()` | Whether registration answers the same for a taken address, which it does unless `registration.reveal_taken` is on. |
| `Keyring::withoutProtection($callback, reason: ...)` | Changes protected attributes outside Keyring's flows. See [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes#bypassing-protection). |
| `Keyring::activity($user, $limit = 25)` | Recent security log entries, without the types in `security_log.unlisted` or, with `impersonation.show_in_activity` off, the impersonation entries. See [Showing Recent Activity](https://keyringauth.com/docs/0.x/security-log-and-emails#showing-recent-activity). |
| `Keyring::unlistedActivityTypes()` | The entry types `Keyring::activity` leaves out, for an activity query of your own. |
| `Keyring::for($user)` | The user's keyring, the same as `$user->keyring`. |
| `Keyring::user()` | The user signed in to Keyring's guard. Throws an `AuthenticationException` when nobody is. |
| `Keyring::fake()` | Passes or fails factors in tests. See [Testing](https://keyringauth.com/docs/0.x/testing). |

These answer questions about your setup, and are useful in your own controllers, factors and steps:

| Method | Returns |
|---|---|
| `Keyring::registered()` | The registered factors, keyed by their key. |
| `Keyring::factor($key)` | One registered factor. `Keyring::hasFactor($key)` says whether there is one. |
| `Keyring::guard()` | Keyring's guard. `Keyring::provider()` is its user provider. |
| `Keyring::username()` | The username field, `email` by default. |
| `Keyring::normalizeUsername($username)` | A username as Keyring stores and looks it up. See [Finding the User](https://keyringauth.com/docs/0.x/sign-in-flow#finding-the-user). |
| `Keyring::requirementFor($user, $attempt)` | What this user must prove to finish the attempt. See [Checking Requirements in Code](https://keyringauth.com/docs/0.x/policies#checking-requirements-in-code). |
| `Keyring::statusMessage($status)` | The translated message for a status slug, or `null`. See [Flash Messages and Alerts](https://keyringauth.com/docs/0.x/frontend#flash-messages-and-alerts). |
| `Keyring::render($name, $props)` | Renders one of Keyring's [pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages) from a route of your own. |
| `Keyring::result($key = null, $default = null)` | What the last status response flashed, such as new recovery codes, or one key of it in dot notation. |
| `Keyring::hasNotification($type)` | Whether a notification is sent for a [type](https://keyringauth.com/docs/0.x/security-log-and-emails#email-types). |
| `Keyring::protectedAttributes($user = null)` | The attributes that only change through Keyring's flows. See [Protected Attributes](https://keyringauth.com/docs/0.x/protected-changes#protected-attributes). |
| `Keyring::response($contract, ...$with)` | Builds one of Keyring's [responses](https://keyringauth.com/docs/0.x/sign-in-flow#responses), or yours when you swapped it. |
| `Keyring::describeDevice($userAgent)` | A user agent as a name people recognise, or `null`. |
| `Keyring::linkRoot()` | Where emailed links start. |
| `Keyring::email()` | The attribute holding the user's address, `email` by default. |
| `Keyring::policy($user, $attempt)` | What the policy asks of this user, before considering what they've enrolled. |
| `Keyring::steps()` | The pipeline's steps, in order. `Keyring::dangerouslyChangedSteps()` lists the mandatory ones an application removed. |
| `Keyring::notification($type, $arguments)` | The notification for a type, or `null` when it's turned off. `Keyring::requiredNotification()` throws instead. |
| `Keyring::belongsToGuard($user)` | Whether Keyring's guard would load this user back, so they can be signed in. |
| `Keyring::recordedIp($request)` | The request's IP address as Keyring stores it. |
| `Keyring::allowsSignIn($user)` | Whether the application lets this user be signed in. See [Who May Sign In](https://keyringauth.com/docs/0.x/sign-in-flow#who-may-sign-in). |
| `Keyring::allowsEnrollment($user)` | Whether the user may add a sign-in method. See [Who May Enroll](https://keyringauth.com/docs/0.x/authenticators#who-may-enroll). |
| `Keyring::allowsImpersonation($impersonator, $user)` | Whether one user may impersonate another. `Keyring::impersonationRefusal()` says why not. |
| `Keyring::impersonating()` | Whether the session is impersonating someone. `Keyring::impersonator()` is who, and `Keyring::impersonation()` is what a [banner](https://keyringauth.com/docs/0.x/impersonation#showing-a-banner) needs. |
| `Keyring::authenticatorModel()` | The authenticator model's class. `deviceModel()`, `pendingChangeModel()`, `securityEventModel()` and `failureCountModel()` do the same for theirs. |
