# Events

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

## Introduction

Every event is in the `Keyring\Events` namespace. Keyring fires one for each thing that happens, such as a sign in, a failed factor or a password change. Listen for them the way you would any Laravel event. The data is in public readonly properties, and `user` is always your user model. This listener saves the time of each sign in:

```php
use Illuminate\Support\Facades\Event;
use Keyring\Events\Authenticated;

Event::listen(function (Authenticated $event) {
    $event->user->update(['last_signed_in_at' => now()]);
});
```

Keyring fires events whether or not a feature that uses them is on. The [security log](https://keyringauth.com/docs/0.x/security-log-and-emails) and the [security emails](https://keyringauth.com/docs/0.x/security-log-and-emails#security-emails) listen to the same events, so you don't need your own copies.

A listener in the request that throws fails the request with its exception. The change behind the event still finishes first. After a password change, an applied email change, or a sign-in method added or removed, the other sessions are still signed out when asked, and this session still gets its new ID and [registry record](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-registry). The change stays saved.

## Queued Listeners

Most events are safe to queue. Check these before you queue one:

> [!WARNING]
> Don't queue a listener for `Attempting`, `FactorFailed` or `Lockout`, or for Laravel's `Failed`. They carry the request as it arrived, including what the user typed, or your user model as it is. Don't log or serialise the whole request.

- No event carries a password, code or token, except the registry ID in the `session` of `SessionResumed`, `RememberMeReused` and `SessionContested`, and the state, nonce and code verifier in `ProviderIdentityAccepted`'s `identity->request`. A listener in the request sees these. A queued one gets them blank.
- A queued listener gets `user` reloaded by its ID, as with any Laravel event that uses `SerializesModels`.
- An `attempt` is queued as plain data. `attempt->user()` or `attempt->keyring()` throws `AttemptExpired` if the user has since been deleted. That happens inside your listener, after the job is restored, so `deleteWhenMissingModels` doesn't cover it. Catch the exception, or let the job fail.
- `AuthenticatorRemoved` queues the authenticator without its `secret`. `FactorChallenged` and `FactorVerified` queue a stored authenticator by ID. An unsaved one, such as the password's, is queued as it is, without its `secret` or its user loaded.
- `ProviderIdentityAccepted` is queued with the request's state, nonce and PKCE verifier blank, and without the `nonce`, `at_hash` and `c_hash` claims.
- Its `identity->claims` hold everything the provider sent about the user, so treat them like the user's profile.
- `SessionResumed`, `RememberMeReused` and `SessionContested` carry a `RegisteredSession`. A queued listener gets it with a blank `id`, and with `replacedBy` and `origin` null. Use `handle` instead. It's always present, and it's the same one the [sessions list](https://keyringauth.com/docs/0.x/devices-and-sessions#listing-and-ending-sessions) shows. `Sessions::find($user, $event->handle)` returns the session while it's active. Don't call `Sessions::handle()` on the queued record, since it throws a `LogicException`.

## Signing In and Confirming

| Event | When | Properties |
|---|---|---|
| `Attempting` | A factor is about to be checked. | `request`, `factor` (its key), `purpose` |
| `FactorChallenged` | The challenge page showed a factor. | `attempt`, `authenticator` |
| `FactorVerified` | A factor's proof was right. | `attempt`, `authenticator`, `verification` |
| `ProviderIdentityAccepted` | An [identity provider](https://keyringauth.com/docs/0.x/sso#hearing-about-accepted-identities) account was accepted as the user's link. For a sign in or confirm, it fires before the rest of the pipeline, so a second factor may still be asked for. | `user`, `authenticator`, `identity` (`Keyring\Sso\Identity`), `purpose` (`login`, `confirm` or `link`) |
| `FactorFailed` | A factor's proof was wrong, or the user wasn't found. It also fires, with a `Confirm` attempt, for a wrong proof sent to [make a change while sign-in methods are frozen](https://keyringauth.com/docs/0.x/authenticators#making-a-change-with-an-established-key), a wrong [password when adding a first second factor](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor), and a wrong password for [removing the last method](https://keyringauth.com/docs/0.x/authenticators#removing-authenticators). | `attempt` (null when the user wasn't found), `authenticator` (nullable), `factor`, `request` |
| `Lockout` | A rate limit refused a request, including an account's own limit refusing a sign in. It fires for every refused request. | `request`, `factor`, `retryAfter` (in seconds, or `null` when waiting won't help) |
| `AccountLocked` | Failed attempts got a sign-in factor refused for the account until a password reset or `Keyring::unlock()`. Browsers the account has signed in from may still get in. | `user`, `factor` |
| `Authenticated` | A login completed. | `user`, `attempt`, `device` (null without `Features::devices()`) |
| `Confirmed` | A [step-up](https://keyringauth.com/docs/0.x/step-up) completed. | `user`, `attempt` |
| `LoggedOut` | The user signed out. | `user` |

`purpose` is a `Keyring\Enums\Purpose`: `Login` or `Confirm`. `FactorChallenged`, `FactorVerified` and `FactorFailed` fire for both, so check `$event->attempt?->purpose` to react only to sign ins. On `FactorFailed`, `afterFirstFactor()` says whether the login's first step had passed, `afterPassword()` whether that step was the password, and `firstFactor()` returns its `Verification`. See [The Sign In Flow](https://keyringauth.com/docs/0.x/sign-in-flow#events).

## Sessions and Devices

| Event | When | Properties |
|---|---|---|
| `NewDeviceSignedIn` | A sign in from a device the account hasn't used before. | `user`, `device`, and `revokeUrl($days = null)`, the ["this wasn't me" link](https://keyringauth.com/docs/0.x/devices-and-sessions#the-this-wasnt-me-link). It's valid for `devices.report_link_for` unless you pass a number of days. |
| `UnrecordedDeviceSignedIn` | ["Remember me"](https://keyringauth.com/docs/0.x/devices-and-sessions#remember-me) signed in an unknown browser while the account was at [`devices.limit`](https://keyringauth.com/docs/0.x/devices-and-sessions#devices), so no device was recorded. It's logged as `new_device` and emailed, without a "this wasn't me" link. | `user`, `handle`, `device` (a readable name, such as "Firefox on Windows") |
| `DeviceRevoked` | A device was signed out. | `user`, `device`, `reported` (true from the "this wasn't me" link) |
| `SessionsRevoked` | Sessions were signed out: "sign out everywhere else", one session ended from the list, `keyring:sign-out` for a user, or a first request refused for an account [the app keeps out](https://keyringauth.com/docs/0.x/sign-in-flow#who-may-sign-in). | `user`, `count` |
| `SessionEnded` | Keyring signed a session out on its own. | `user`, `reason`: `revoked`, `expired`, `idle`, `other_user`, `reused`, `risk` or `not_allowed` |
| `RegisteredSessionEnded` | A registered session ended, in any request. There's one for each record the registry revoked. | `handle`, `handles`, `userId`, `userType`, `guard`, `deviceId`, `endedAt`, `reason` (see [below](https://keyringauth.com/docs/0.x/events#why-a-registered-session-ended)) |
| `EveryoneSignedOut` | Every user's sessions ended at once, with `keyring:sign-out --all` or `revokeEveryone()`. | `at`, a Unix timestamp. Every session that signed in up to it ended. The event can arrive late from the sweep. See [Hearing About Ended Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions#hearing-about-ended-sessions). |
| `SessionResumed` | ["Remember me"](https://keyringauth.com/docs/0.x/devices-and-sessions#remember-me) signed a browser back in after its session went unused. Nothing was proved. | `user`, `session` (the `RegisteredSession` it carries on as), `handle` |
| `ImpersonationStarted` | Someone signed in as another user. The user's own `Login` and `Authenticated` don't fire. See [Impersonation](https://keyringauth.com/docs/0.x/impersonation#security-log-and-events). | `impersonator`, `user`, `handle` (the impersonated session's handle) |
| `ImpersonationEnded` | An impersonation ended, in the request of the impersonating browser. It fires once, however many requests find it over. | `impersonator` (null once deleted), `user` (null once it can't be loaded), `reason` (a `Keyring\Enums\ImpersonationEndReason`: `stopped`, `expired`, `revoked`, `impersonator_session_ended`, `lost` or `signed_out`; `failed` is only logged), `returned` (whether the browser went back to the impersonator's session), `handle` (`null` when unknown) |
| `RememberMeReused` | A ["remember me" cookie was used twice](https://keyringauth.com/docs/0.x/devices-and-sessions#a-cookie-used-twice), so the session ended for both browsers. It fires once, when there was still a session to end, or when the session it carried on to has timed out since. | `user`, `session` (the ended `RegisteredSession`; its device, IP address and user agent belong to whoever used the cookie first), `handle` |
| `SessionContested` | Two requests holding one session both moved its record, so the [session ended for both](https://keyringauth.com/docs/0.x/devices-and-sessions#a-contested-session). | `user`, `session` (the ended `RegisteredSession`, wherever it had moved to), `handle` |

A user who signs out on purpose triggers `LoggedOut`, not `SessionEnded`. A request that brings a used cookie also gets a `SessionEnded` with `reused`. See [Devices & Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions#events).

### Why a Registered Session Ended

`SessionEnded` only fires in the request of the browser that was signed out. `RegisteredSessionEnded` fires for every registered session that ends, in any request, so listen for it to hear about each one. A single sign-on provider built on Keyring uses it to sign the user out of client applications. See [Hearing About Ended Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions#hearing-about-ended-sessions) for what it promises.

Its properties are plain values, so it's safe to queue:

| Property | Holds |
|---|---|
| `handle` | The session's [handle](https://keyringauth.com/docs/0.x/devices-and-sessions#listing-and-ending-sessions) under the current `APP_KEY`. |
| `handles` | The handle under the current key and each key in `APP_PREVIOUS_KEYS`, so a handle stored before a key rotation still matches. |
| `userId` | The user's ID, as a string. |
| `userType` | The connection and table the ID is unique in, such as `mysql:users`. Not a class name; compare with `RegisteredSession::typeOf($user)`. |
| `guard` | The guard the session signed in on. |
| `deviceId` | The session's device ID, or `null`. |
| `endedAt` | When it was revoked, as a Unix timestamp. |
| `reason` | A `Keyring\Enums\SessionEndReason`. |

It never carries the registry ID, which is what the "remember me" cookie holds.

Laravel stops calling listeners at the first that throws or returns `false`, so a listener registered earlier can stop yours. A handle also stops matching when the app key is rotated without `APP_PREVIOUS_KEYS`. Don't rely on this event alone to end sessions elsewhere.

| Reason | Given When |
|---|---|
| `logged_out` | The user signed out with `POST /logout`, or ended their current session from the list. Also `Auth::logout()` or `Auth::logoutCurrentDevice()` on Keyring's guard, unless wrapped in `app(Sessions::class)->because(...)`. Laravel's `auth.session` middleware signs out this way when the password changed elsewhere. |
| `signed_out_everywhere` | "Sign out everywhere else", or adding or removing a sign-in method with `sign_out_others`. `keyring:sign-out` for one user gives it too. |
| `revoked` | One session was ended from the list. Also any revocation Keyring didn't name, such as a call to `Sessions::signOutEverywhere()`. A sign in refused at its last step ends its new session with this reason. |
| `signed_in_again` | The browser signed in again while signed in, and left the session it was on. |
| `device_revoked` | The session's device was signed out from the devices list. |
| `device_reported` | The session's device was reported with the "this wasn't me" link. |
| `device_limit` | Its device was forgotten to keep the account within [`devices.limit`](https://keyringauth.com/docs/0.x/devices-and-sessions#devices). |
| `session_limit` | A new sign in took the account past [`sessions.max`](https://keyringauth.com/docs/0.x/devices-and-sessions#how-many-sessions), and this session had gone unused longest. |
| `account_deleted` | The user was deleted, soft deleted or for good. |
| `password_changed` | The password was changed, and other sessions were signed out. |
| `password_reset` | The password was reset from a reset link. |
| `email_changed` | The email address changed, and other sessions were signed out (`email_changes.sign_out_others`). |
| `email_change_undone` | The old address undid an email change. |
| `risk` | A [risk response](https://keyringauth.com/docs/0.x/risk#actions) ended the session, or every session of the account. |
| `idle` | The session went unused for too long, or [`keyring:sweep`](https://keyringauth.com/docs/0.x/devices-and-sessions#sweeping-ended-sessions) ended it for that. |
| `expired` | The session passed its absolute limit, or the sweep ended it for that. With `sessions.end_on_lapse`, a "remember me" cookie that can't carry the session on gives it too. |
| `other_user` | The session's record belongs to another user, who the event names. |
| `reused` | The session's ["remember me" cookie was used twice](https://keyringauth.com/docs/0.x/devices-and-sessions#a-cookie-used-twice). |
| `contested` | Another request moved the session's record first, and it was [ended for both](https://keyringauth.com/docs/0.x/devices-and-sessions#a-contested-session). |
| `not_allowed` | The app stopped letting the user sign in, with [`Keyring::allowSignInWhen`](https://keyringauth.com/docs/0.x/sign-in-flow#who-may-sign-in). |
| `impersonation_ended` | An [impersonation](https://keyringauth.com/docs/0.x/impersonation) ended, for the session that was impersonated, or the impersonator's parked session when the browser was signed out. |

The event is at least once. With [the sweep](https://keyringauth.com/docs/0.x/devices-and-sessions#sweeping-ended-sessions) on, a session whose event was lost is announced again, and so is one a listener failed for. A session announced again has the reason it ended for, or `revoked` when that wasn't kept. Make listeners idempotent by handle.

When one action ends sessions for several reasons, each session gets the reason closest to the code that ended it. A risk response that signs out everywhere gives `risk`, not `revoked`.

## Authenticators

| Event | When | Properties |
|---|---|---|
| `AuthenticatorAdded` | The user added a sign-in method. | `user`, `authenticator` |
| `AuthenticatorRemoved` | The user removed one. | `user`, `authenticator` |
| `RecoveryCodesGenerated` | New recovery codes were made, and the old ones stopped working. | `user`, `authenticator` |
| `RecoveryCodeUsed` | A recovery code was used. | `authenticator`, `remaining` |
| `CloneSuspected` | A passkey or security key's counter went backwards, so the sign in was refused. | `authenticator` |

Confirming the `recovery` factor dispatches `RecoveryCodesGenerated` instead of `AuthenticatorAdded`. When an event has no `user` property, use `$event->authenticator->user()`. See [Managing Authenticators](https://keyringauth.com/docs/0.x/authenticators#events) and [Counters and Cloned Keys](https://keyringauth.com/docs/0.x/passkeys#counters-and-cloned-keys).

## Account Changes

| Event | When | Properties |
|---|---|---|
| `EmailChangeRequested` | An email change was requested, and its links were sent. | `user`, `change` |
| `EmailChanged` | The email address changed. The old address can still revert it for a while. | `user`, `change` |
| `EmailChangeReverted` | The old address undid a change. Every session was signed out. | `user`, `change` |
| `PasswordChanged` | The user changed their password. | `user` |
| `PasswordReset` | The password was reset from a reset link. Every session was signed out. | `user` |
| `PasswordChangeRequired` | A user was [held until they choose a new password](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change). | `user`, `reason` (nullable) |
| `ProtectionBypassed` | Protected attributes were changed with [`Keyring::withoutProtection`](https://keyringauth.com/docs/0.x/protected-changes#bypassing-protection). | `reason` (nullable) |

The `change` property is a `Keyring\Models\PendingChange`, whose tokens and addresses are hidden when serialised. See [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes#events).

## Risk

| Event | When | Properties |
|---|---|---|
| `RiskAssessed` | Keyring assessed the risk, and the action did something. | `user`, `risk`, `action`, `checkpoint` (`Checkpoint::Login` or `Checkpoint::Request`) |

An assessment that ends in `Action::allow` dispatches nothing. See [Risk](https://keyringauth.com/docs/0.x/risk#events-and-logging).

## Refusals

| Event | When | Properties |
|---|---|---|
| `AccessRefused` | A signed-in user asked for an authenticator, device or session that isn't theirs, or doesn't exist. Both get the same 404. Also fires when someone opens an email verification link made for another account. | `user`, `resource` (`authenticator`, `device`, `session` or `email_verification`), `id` (what was asked for, as it was sent; for a session, its handle) |
| `RateLimited` | The form limiter refused a request to one of Keyring's routes, outside the sign-in limits: registration, a reset, a change, an emailed link or its page, or passkey options. | `user` (whoever is signed in, otherwise null), `limiter` (`keyring`, `keyring-session-changes`, `keyring-pages` or `keyring-login-options`), `route` (its name, or `null`), `retryAfter` (in seconds) |
| `EnrollmentRefused` | A sign-in method wasn't added. | `user`, `factor`, `reason`: `invalid` (the factor turned the confirmation down, such as with a wrong code), `not_allowed` (the account may not add one yet), `frozen` (it would have replaced recovery codes or a method while they're [frozen](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods)), or `password` (the [password](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor) was wrong) |
| `AuthenticatorRemovalRefused` | A sign-in method was kept, because removing it would break the user's sign-in policy, or the methods are [frozen](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods). | `user`, `authenticator`, `reason` (`last_factor` or `frozen`) |
| `LinkRefused` | An emailed link was refused: a change that doesn't exist, a wrong or ended token, or a bad signature. | `link`, `reason` (see [Refused Links](https://keyringauth.com/docs/0.x/security-log-and-emails#refused-links)), `user` (whose email change it was, otherwise null) |
| `VerificationRefused` | A sign in or step-up was refused at the end, because a [mandatory step](https://keyringauth.com/docs/0.x/sign-in-flow#mandatory-steps) hadn't run. | `attempt`, `factor`, `skipped` (the steps' class names) |

None of these changes what the refused person sees, and each fires every time. Only the [security log](https://keyringauth.com/docs/0.x/security-log-and-emails#refusals-that-repeat) limits what it writes. A form that fails ordinary validation fires nothing.

Keyring keeps no metrics of its own, so count from these events with a listener:

```php
use Illuminate\Support\Facades\Event;
use Keyring\Events\FactorFailed;
use Keyring\Events\Lockout;
use Keyring\Events\RateLimited;

Event::listen(fn (FactorFailed $event) => Metrics::increment('auth.failed', ['factor' => $event->factor]));
Event::listen(fn (Lockout $event) => Metrics::increment('auth.locked_out', ['factor' => $event->factor]));
Event::listen(fn (RateLimited $event) => Metrics::increment('auth.rate_limited', ['route' => $event->route ?? 'unnamed']));
```

`Metrics` stands for whatever your application reports to. To act on credential stuffing at sign in instead, turn on the [`CredentialStuffing`](https://keyringauth.com/docs/0.x/risk#built-in-signals) risk signal.

## Laravel's Auth Events

Keyring signs users in and out through the guard, so Laravel's `Login`, `Logout`, `Registered` and `Verified` events fire as usual. A sign in is all or nothing: a `Login` listener in the request that throws leaves the user signed out, with no session or "remember me" cookies. `Registered` is dispatched after the response, unless [`registration.reveal_taken`](https://keyringauth.com/docs/0.x/sign-in-flow#registration) is on.

Keyring also dispatches these alongside its own events:

| Laravel Event | Dispatched With |
|---|---|
| `Illuminate\Auth\Events\Failed` | `FactorFailed`. Its credentials hold only the username field, never the password or code: the user's own when one was found, otherwise what was typed for a factor that asks for a username, and `null` for one that doesn't, such as an identity provider's callback. |
| `Illuminate\Auth\Events\Lockout` | `Lockout`, so once for every refused request. |
| `Illuminate\Auth\Events\PasswordReset` | Keyring's `PasswordReset`. |

## How It Works

Only serialising an event removes the sensitive values from it. Anything that reads the properties directly still sees them, including Telescope's event watcher, `dump()` and `json_encode()`:

- The registry IDs of `SessionResumed`, `RememberMeReused` and `SessionContested`.
- The state, nonce, PKCE verifier and claims of `ProviderIdentityAccepted`. Its `identity->claims` hold everything the provider sent about the user, so treat them like the user's profile. Escape `providerAcr` and `providerAmr` wherever you print them.
