# Events

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

## Introduction

Every event is a struct in the `keyring` package, dispatched through Laravel Go's `event` package where the PHP package dispatches them, so you listen for them as for any event. Those about a user are generic over your user type, so a listener names it:

```go
laravel.Options{
    Listeners: []laravel.Listener{
        laravel.Listen(func(ctx context.Context, e keyring.Authenticated[models.User]) error {
            // e.User, e.DeviceID, e.Factors
            return nil
        }),
    },
}
```

Keyring registers its own listeners, for the security log and the security emails, and Laravel Go runs a package's listeners ahead of the application's, so a listener of yours that fails can't keep an entry off the log. You don't need your own copies. Keyring fires events whether or not a feature that uses them is on.

A listener of yours that fails fails the request with its error, once the change behind the event is done, as in the PHP package. A listener for `RegisteredSessionEnded` that fails is reported and stops nothing (see [Hearing About Ended Sessions](https://keyringauth.com/docs/0.x/go/devices-and-sessions#hearing-about-ended-sessions)).

Events carry plain values where the PHP package's carry models, and never the request: what Keyring read from the request is on the event instead. A sign-in method is its `AuthenticatorID` (and `Factor` and `Name` where the event has them), and a device its `DeviceID`.

## Queued Listeners

`laravel.Listen` runs a listener in the request, after the outermost transaction it was dispatched in commits. `laravel.ListenAtDispatch` runs it at once, inside that transaction. For slow work, `laravel.ListenQueued` turns the event into a job of your own and pushes it onto the queue, as a queued listener does in Laravel.

No event carries a password, code or token, but for the registry IDs in the `Handle` and `Handles` of `SessionResumed`, `RememberMeReused` and `SessionContested`. `ProviderIdentityAccepted`'s identity has its request's state, nonce and code verifier left out already. Keep the handles out of your logs and jobs.

## Signing In and Confirming

| Event | When | Fields |
|---|---|---|
| `Attempting` | A factor is about to be checked. | `Factor`, `Purpose` |
| `FactorChallenged[U]` | The challenge or confirm page showed a factor. | `User`, `Purpose`, `Factor`, `AuthenticatorID` |
| `FactorVerified[U]` | A factor's proof was right. | `User`, `Factor` |
| `ProviderIdentityAccepted[U]` | An [identity provider](https://keyringauth.com/docs/0.x/go/sso#hearing-about-accepted-identities) account was accepted as the user's link. | `User`, `AuthenticatorID`, `Identity`, `Purpose` |
| `FactorFailed[U]` | A factor's proof was wrong, or the user wasn't found. | `User` (nil when not found), `Factor`, `Username` (what was typed), `Purpose`, `AuthenticatorID`, `FirstFactor`, `Identifying` |
| `Lockout` | A rate limit refused a sign in. It fires for every refused request. | `Factor`, `RetryAfter` |
| `AccountLocked[U]` | Failed attempts got a sign-in factor refused until a reset or `Keyring.Unlock`. | `User`, `Factor` |
| `Authenticated[U]` | A sign in completed. | `User`, `DeviceID`, `Factors` |
| `Confirmed[U]` | A [step-up](https://keyringauth.com/docs/0.x/go/step-up) completed. | `User`, `Factors` |
| `LoggedOut[U]` | The user signed out with `POST /logout`. | `User` |

`Purpose` is `login` or `confirm` (`keyring.PurposeLogin` and `PurposeConfirm`). `FactorFailed`'s `AfterFirstFactor()` and `AfterPassword()` say whether a later step of a sign in failed, as the PHP package's methods do, and `Identifying` is a passkey alone, which named its own account. `Lockout`'s `RetryAfter` is `nil` when waiting won't help, because the failures in a row reached the cap.

When each fires is the PHP package's, as its [table](https://keyringauth.com/docs/0.x/events#signing-in-and-confirming) describes, with one difference: `FactorFailed` fires after the failure is counted, so a listener that fails can't keep it from counting, where the PHP package dispatches it before. `CloneSuspected` likewise, ahead of `FactorFailed`. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#events).

## Sessions and Devices

| Event | Fields |
|---|---|
| `NewDeviceSignedIn[U]` | `User`, `DeviceID`, `DeviceName`, `DeviceLocation` |
| `UnrecordedDeviceSignedIn[U]` | `User`, `Handle`, `DeviceName` |
| `DeviceRevoked[U]` | `User`, `Device` (a `keyring.Device`), `Reported` |
| `SessionsRevoked[U]` | `User`, `Count` |
| `SessionEnded[U]` | `User`, `Reason` |
| `RegisteredSessionEnded` | `Handle`, `Handles`, `UserID`, `UserType`, `Guard`, `DeviceID`, `EndedAt`, `Reason` |
| `EveryoneSignedOut` | `At` |
| `SessionResumed[U]` | `User`, `Handle`, `Handles`, `DeviceID`, `IP`, `UserAgent` |
| `ImpersonationStarted[U]` | `Impersonator`, `User`, `Handle` |
| `ImpersonationEnded[U]` | `Impersonator`, `User`, `Reason`, `Returned`, `Handle` |
| `RememberMeReused[U]` | `User`, `Handle`, `Handles`, `DeviceID`, `UserAgent` |
| `SessionContested[U]` | `User`, `Handle`, `Handles`, `DeviceID`, `UserAgent` |

When each fires is the PHP package's, as its [table](https://keyringauth.com/docs/0.x/events#sessions-and-devices) describes. `Handles` has one handle per application key, the current key's first.

`ImpersonationEnded`'s `Reason` is `stopped`, `expired`, `revoked`, `impersonator_session_ended`, `lost` or `signed_out`, and either user is `nil` once their account can't be loaded. Its `Handle`, like `ImpersonationStarted`'s, is the impersonated session's. Keyring logs a start itself before the browser changes hands, so a listener of yours that fails can't leave it unlogged. See [Impersonation](https://keyringauth.com/docs/0.x/go/impersonation#security-log-and-events).

`EveryoneSignedOut` is dispatched once when `keyring:sign-out --all` signs every user out, in place of a `RegisteredSessionEnded` for each session. `At` is a Unix timestamp: every session that signed in up to then has ended. It's a cut-off on when sessions signed in, not the moment it was sent: when the first dispatch is lost, `keyring:sweep` sends it again, up to a day later.

### Why a Registered Session Ended

`RegisteredSessionEnded` fires for every registered session that ends, in any request, with plain values. Its `Reason` is a string, with the PHP package's reasons: `logged_out`, `signed_out_everywhere`, `revoked`, `signed_in_again`, `device_revoked`, `device_reported`, `device_limit`, `session_limit`, `password_changed`, `password_reset`, `email_changed`, `email_change_undone`, `risk`, `idle`, `expired`, `other_user`, `reused`, `contested`, `not_allowed` and `impersonation_ended`. When each is given is in the [PHP table](https://keyringauth.com/docs/0.x/events#why-a-registered-session-ended). A record that moved to a new one isn't announced, since its session carried on there.

Two differences: your own `auth.Logout` always gives `logged_out`, as there's no `Sessions::because()`, and `account_deleted` isn't given yet. Keyring notes in `keyring_sessions` which announcements went out, for the sweep: with [the sweep](https://keyringauth.com/docs/0.x/go/devices-and-sessions#sweeping-ended-sessions) on, the event is at least once.

## Authenticators

`AuthenticatorAdded[U]` and `AuthenticatorRemoved[U]` (`User`, `ID`, `Factor`, `Name`), `RecoveryCodesGenerated[U]` (`User`, `ID`), `RecoveryCodeUsed[U]` (`User`, `AuthenticatorID`, `Remaining`) and `CloneSuspected[U]` (`User`, `Factor`, `AuthenticatorID`, `Name`), as in the PHP package. A password reset's unlinking of identity providers dispatches `AuthenticatorRemoved` for each. See [Managing Authenticators](https://keyringauth.com/docs/0.x/go/authenticators#events).

## Account Changes

| Event | Fields |
|---|---|
| `Registered[U]` | `User` |
| `Verified[U]` | `User` |
| `EmailChangeRequested[U]` | `User`, `Change` |
| `EmailChanged[U]` | `User`, `Change` |
| `EmailChangeReverted[U]` | `User`, `Change` |
| `PasswordChanged[U]` | `User` |
| `PasswordReset[U]` | `User` |
| `PasswordChangeRequired[U]` | `User`, `Reason` |
| `ProtectionBypassed[U]` | `Actor`, `Reason` |

`Change` is a `keyring.EmailChange`, the PHP package's `PendingChange` without its tokens. `ProtectionBypassed` is dispatched before the change runs. Its `Actor` is whoever is signed in on the request making the change, or nil outside one, as the PHP package's listener reads it from the guard. See [Protected Changes](https://keyringauth.com/docs/0.x/go/protected-changes#events).

`Registered` and `Verified` stand in for Laravel's events of those names, which Laravel Go's `auth` doesn't have. Where registration hides who has an account, `Registered` is dispatched off the request's goroutine, so how long a free address took doesn't show. Its listeners get a context without the request's cancellation, and what they fail with is reported.

## Risk

`RiskAssessed[U]` fires when an assessment's action did something, with `User`, the `Risk`, the `Action` and the `Checkpoint`. See [Risk](https://keyringauth.com/docs/0.x/go/risk#events-and-logging).

## Refusals

| Event | When |
|---|---|
| `AccessRefused[U]` | A session handle, device or authenticator that isn't the user's, or a verification link that's someone else's. `Resource` says which, and `ID` what the request named it by. |
| `RateLimited[U]` | The `keyring-login-options`, `keyring-session-changes`, `keyring` or `keyring-pages` limiter refused a request. `Limiter`, `Route` and `RetryAfter` say which, where and for how long. |
| `EnrollmentRefused[U]` | A sign-in method wasn't added: `invalid`, `not_allowed`, `frozen` or `password`. |
| `AuthenticatorRemovalRefused[U]` | A sign-in method was kept: `last_factor` or `frozen`. |
| `LinkRefused[U]` | An emailed link was refused. `Link` is the link's route name, or `password_reset`, `email_change_confirm`, `email_change_revert` or `sign_in_link`, and `Reason` why, such as `signature`, `expired` or `token`. |
| `VerificationRefused[U]` | A verification was refused at the end, because a mandatory step hadn't run. `Skipped` names the steps whose checks weren't made. |

None of these changes what the refused person sees, as in the PHP package. Keyring keeps no metrics of its own, so count from these events with a listener:

```go
laravel.Options{
    Listeners: []laravel.Listener{
        laravel.Listen(func(ctx context.Context, e keyring.FactorFailed[models.User]) error {
            metrics.Increment("auth.failed", e.Factor)
            return nil
        }),
        laravel.Listen(func(ctx context.Context, e keyring.Lockout) error {
            metrics.Increment("auth.locked_out", e.Factor)
            return nil
        }),
    },
}
```

`metrics` stands for whatever your application reports to.

## Laravel's Auth Events

Laravel Go's `auth` dispatches no events: there's no `Login`, `Logout`, `Failed` or `Lockout`. Listen for `keyring.Authenticated`, `LoggedOut`, `FactorFailed` and `Lockout` instead. Keyring dispatches `Registered[U]`, `Verified[U]` and `PasswordReset[U]` of its own, where Laravel would dispatch its own events of those names. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#events).

## How It Works

An event's fields are its values: anything that reads them sees them all, including a `%+v` print. Keep the registry handles of `SessionResumed`, `RememberMeReused` and `SessionContested` out of your logs, as the [PHP docs](https://keyringauth.com/docs/0.x/events#how-it-works) say.
