# Security Log & Emails

Source: https://keyringauth.com/docs/0.x/security-log-and-emails

## Introduction

Keyring writes a security log of what happens to your users' accounts, and it emails them when something important changes. This page covers reading the log, showing recent activity, the "was this you?" alerts, and the security emails and how to change them.

## The Security Log

Keyring writes each entry as a `Keyring\Models\SecurityEvent` row in the `keyring_events` table. The log is on by default, through `Features::securityLog()`. Configure it in the `security_log` section of `config/keyring.php`:

```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' => [],
],
```

A row has a `type`, a `severity`, the user (`authenticatable_type` and `authenticatable_id`), a `factor`, a `device_id`, an `ip`, a `user_agent`, a `request_id`, `meta`, `seen_at` and `created_at`. The log never holds passwords, codes, tokens, signatures, session IDs or anything else from the request body.

While someone is [impersonating](https://keyringauth.com/docs/0.x/impersonation#security-log-and-events) a user, the requests are the impersonator's. So any entry written on the user's account in those requests has no IP address or user agent, and neither do the user's `impersonation_started` and `impersonation_ended` entries. The impersonator's own entries keep them.

The log never stops a sign in. If a write fails, Keyring reports the error, writes the entry to [your application's log](https://keyringauth.com/docs/0.x/security-log-and-emails#without-the-table) instead, and carries on. The one exception is `protection_bypassed`. If that entry can't be written, [`Keyring::withoutProtection()`](https://keyringauth.com/docs/0.x/protected-changes#bypassing-protection) throws before it runs your callback, so a bypass is never unlogged.

### Without the Table

Without `Features::securityLog()`, nothing is written to `keyring_events`. Each event becomes a line in your application's log instead, written as `Keyring: {type}` at the entry's [severity](https://keyringauth.com/docs/0.x/security-log-and-emails#severity). The context holds `at` (the time, [with its offset](https://keyringauth.com/docs/0.x/security-log-and-emails#times)), `user` (as `{morph class}:{id}`), `factor`, `device_id`, `ip`, `user_agent`, `request_id` and `meta`.

Set `security_log.channel` to the channel to use. Leave it empty for your default channel:

```php
// config/logging.php
'security' => ['driver' => 'daily', 'path' => storage_path('logs/security.log'), 'days' => 180],
```

```bash
KEYRING_LOG_CHANNEL=security
```

The channel decides how long lines are kept and who can read them.

> [!WARNING]
> The "was this you?" alerts, [`Keyring::activity()`](https://keyringauth.com/docs/0.x/security-log-and-emails#showing-recent-activity) and the `RepeatedFactorFailures`, `SuccessAfterFailures` and `CredentialStuffing` risk signals all read the table. Without it, they find nothing.

### Request IDs

Every entry a request writes gets the same `request_id`, so you can read them together:

```php
SecurityEvent::query()->where('request_id', $event->request_id)->oldest('id')->get();
```

The ID comes from Laravel's [Context](https://laravel.com/docs/context) feature. If your app already sets one, such as `trace_id`, Keyring uses it:

```php
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;

// A middleware of yours
Context::add('trace_id', (string) Str::uuid());
```

Set `security_log.context_key` to your key. Your log lines and any queued job from the request then carry the same ID. Without one, Keyring makes a UUID and keeps it hidden. An ID over 64 characters is cut. Set the key to `null` to leave `request_id` empty.

### Times

`created_at` is a plain timestamp in `app.timezone`, with no offset. Leave `app.timezone` as `UTC`, the Laravel default and what OWASP ASVS 5.0.0 (16.2.2) recommends. Lines in [your application's log](https://keyringauth.com/docs/0.x/security-log-and-emails#without-the-table) carry an offset, as `at`, instead.

### Refusals That Repeat

Refused users can ask again as often as they like, so Keyring limits how often refusals are written:

- **A lock is logged when it starts.** `locked_out` is written once per factor and IP address, until the lock's wait is over. `rate_limited` is written once per route, until that limiter has room again. Every refused request still dispatches its event, [`Lockout`](https://keyringauth.com/docs/0.x/events#signing-in-and-confirming) or [`RateLimited`](https://keyringauth.com/docs/0.x/events#refusals), so your listeners see each one.
- **Refusals are counted.** `locked_out`, `rate_limited`, `access_refused`, `enrollment_refused`, `authenticator_removal_refused`, `link_refused`, `verification_refused`, `impersonation_refused`, and `factor_failed` for an unknown name are each written at most `security_log.refusals` times per `refusals_per`. The default is 20 an hour. The count is per account, or per IP address when no account is named.
- **The log says where it stopped.** The first entry left out is replaced by one `refusals_limited` entry.

A failed factor for a real account isn't limited this way. The account's own [rate limits](https://keyringauth.com/docs/0.x/security#rate-limiting) bound it instead.

Set `refusals` to `null` to write every refusal. The counts live in the rate limiter's cache store.

### Refused Links

The `link_refused` entry covers each emailed link Keyring checks:

| `link` | `reason` |
|---|---|
| `email_change_confirm`, `email_change_revert` | `token` when the token was wrong. `ended` when the change is over (expired, cancelled, used or undone). `unknown` when there's no such change. Only pressing the page's button is logged. |
| `password_reset` | `token` when the token wasn't sent to that address or has expired. The entry holds neither the token nor the address. |
| `sign_in_link` | `token` when the link's token isn't one Keyring made. A link that has ended (used, replaced, expired) isn't logged, since mail scanners open links after they're used. |
| A signed route's name, such as `verification.verify` | `signature` when the signature didn't match. `expired` when it matched but is out of date. |

Signed links are checked by the `keyring.signed` middleware. It works like Laravel's `signed` middleware, with the refusal logged. To log refusals on a route of your own, add the middleware to it:

```php
Route::get('/invitations/{invitation}', AcceptInvitation::class)->middleware('keyring.signed:relative')->name('invitations.accept');
```

### Showing Recent Activity

`Keyring::activity()` returns a user's most recent entries, newest first. It takes an optional limit, which defaults to `25`:

```php
use Keyring\Facades\Keyring;

return Inertia::render('settings/security', [
    'activity' => Keyring::activity($request->user())->map(fn ($event) => [
        'type' => $event->type,
        'factor' => $event->factor,
        'ip' => $event->ip,
        'at' => $event->created_at->toIso8601String(),
    ]),
]);
```

Some entries are about a user without being something they did, such as a token a package issued to another app's server. List those types in `security_log.unlisted`, and `Keyring::activity()` leaves them out:

```php
'security_log' => [
    // ...
    'unlisted' => ['acme.token_issued'],
],
```

A package can add its own types when it boots:

```php
config()->push('keyring.security_log.unlisted', 'acme.token_issued');
```

Start each type with the package's name so it can't clash with another. Your own service provider can push too, with `config()->push()`. Don't assign the option there, since that replaces what packages have pushed. Keep the option a list, even for one type. A string leaves nothing out, and the first package to push to it throws an error.

Keyring's own types are never left out, even if you list them. The impersonation entries are the exception. `Keyring::activity()` leaves out `impersonation_started` and `impersonation_ended` when [`impersonation.show_in_activity`](https://keyringauth.com/docs/0.x/configuration#impersonation) is `false`, and `impersonation_refused` is never hidden.

Unlisted entries still belong to the user. Only `Keyring::activity()` leaves them out. If you build your own activity page, add `->whereNotIn('type', Keyring::unlistedActivityTypes())` to the query. That's the list `Keyring::activity()` uses, including the two impersonation types when `impersonation.show_in_activity` is `false`.

### Pruning

`keyring:prune` deletes entries older than `security_log.keep_for`, which is 180 days by default. Keyring [schedules it daily](https://keyringauth.com/docs/0.x/devices-and-sessions#pruning).

When a user is force deleted, their entries go with them. A soft deleted user keeps theirs.

### What's Stored

Entries keep the request's IP address and user agent. To store less, tell Keyring what to keep. Rate limits always use the real address, but the `ip` in security emails follows this too:

```php
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\IpUtils;

// The network, not the machine. Or return null to keep none.
Keyring::recordIpsUsing(fn (Request $request) => IpUtils::anonymize((string) $request->ip()));
```

For everything Keyring keeps, see [What Keyring Keeps](https://keyringauth.com/docs/0.x/security#what-keyring-keeps).

### Severity

Each entry has one of four severities, stored in the `severity` column as a `Keyring\Enums\Severity` case. They're PSR-3 log levels, so a [log channel](https://keyringauth.com/docs/0.x/security-log-and-emails#without-the-table) filters them with its usual `level` setting.

| Severity | Means |
|---|---|
| `info` | Someone did what they were allowed to do. |
| `notice` | How the account signs in has changed, or something is worth a look. |
| `warning` | Something failed or was refused, or looks like someone else at work. |
| `critical` | A sign-in method or a safeguard can't be relied on. |

`Severity::of()` returns the severity of a type. Your own types are `info` unless you say otherwise:

```php
use Keyring\Activity\SecurityLog;
use Keyring\Enums\Severity;

app(SecurityLog::class)->record('exported_data', $user, severity: Severity::Notice);
```

To watch the most serious entries, query for them, or send the log to a channel that raises alerts:

```php
use Keyring\Enums\Severity;
use Keyring\Models\SecurityEvent;

SecurityEvent::query()->where('severity', Severity::Critical)->where('created_at', '>', now()->subDay())->get();
```

### Entry Types

| Type | Severity | When | `meta` |
|---|---|---|---|
| `signed_in` | info | A login completed. | `factors` |
| `confirmed` | info | A step-up completed. | `factors` |
| `factor_failed` | warning | A factor failed. | |
| `second_factor_failed` | warning | A factor failed after the password, or after another first step such as an [identity provider](https://keyringauth.com/docs/0.x/sso) sign in. | |
| `locked_out` | warning | A rate limit started refusing an IP address for a factor. Logged once per lock, and not linked to a user. | `retry_after` |
| `rate_limited` | warning | The [form limiter](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits) refused one of Keyring's other routes. Logged once per route for each wait. | `limiter`, `route`, `retry_after` |
| `account_locked` | warning | Failed attempts got the password or a passkey refused until a password reset. | |
| `signed_out` | info | The user signed out. | |
| `authenticator_added`, `authenticator_removed` | notice | A sign-in method was added or removed. | `name` |
| `recovery_codes_generated` | info | New recovery codes were made. | |
| `recovery_code_used` | notice | A recovery code was used. | `remaining` |
| `new_device` | notice | A sign in from a new device. | `device` |
| `device_revoked` | info | A device was signed out. | `device` |
| `device_reported` | warning | A device was signed out from the "this wasn't me" link. | `device` |
| `sessions_revoked` | info | Sessions were signed out. | `count` |
| `session_ended` | info | Keyring signed a session out on its own. | `reason`: `revoked`, `expired`, `idle`, `other_user`, `reused`, `risk` or `not_allowed` |
| `session_resumed` | info | ["Remember me"](https://keyringauth.com/docs/0.x/devices-and-sessions#remember-me) signed a browser back in. Nothing was proved. | |
| `remember_me_reused` | warning | A ["remember me" cookie was used twice](https://keyringauth.com/docs/0.x/devices-and-sessions#a-cookie-used-twice), and the session ended for both browsers. | `device` |
| `session_contested` | warning | Two requests holding one session both moved it, so the [session ended for both](https://keyringauth.com/docs/0.x/devices-and-sessions#a-contested-session). | `device` |
| `email_change_requested` | info | An email change was requested. | |
| `email_changed` | notice | An email change was applied. | |
| `email_change_reverted` | warning | An email change was undone. | |
| `password_changed` | notice | The password was changed. | |
| `password_reset` | notice | A reset completed. It cleared the account's [sign-in lockouts](https://keyringauth.com/docs/0.x/security#rate-limiting). | `sign_in_locks_cleared` |
| `protection_bypassed` | warning | [`Keyring::withoutProtection`](https://keyringauth.com/docs/0.x/protected-changes#bypassing-protection) was used, by the signed-in user. | `reason` |
| `clone_suspected` | critical | A passkey or security key's counter went backwards. | `name` |
| `risk_step_up`, `risk_reauthenticate`, `risk_notified`, `risk_password_change` | notice | A risk action did something. `risk_password_change` holds the user until [they choose a new password](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change). | `checkpoint`, `score`, `reasons` |
| `risk_denied`, `risk_locked`, `risk_revoked_sessions` | warning | A risk action refused, locked or signed out. | `checkpoint`, `score`, `reasons` |
| `access_refused` | warning | A user asked for an authenticator, device or session that isn't theirs or doesn't exist. Also written when they open another account's verification link. | `resource` (`authenticator`, `device`, `session` or `email_verification`), `id` (cut to 64 characters; a session's [handle](https://keyringauth.com/docs/0.x/devices-and-sessions#listing-and-ending-sessions), never its registry ID) |
| `enrollment_refused` | warning | A sign-in method wasn't added. | `reason`: `invalid`, `not_allowed` (the account [may not add one yet](https://keyringauth.com/docs/0.x/authenticators#who-may-enroll)), `frozen` (see [frozen sign-in methods](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) |
| `authenticator_removal_refused` | warning | 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). | `name`, `reason` (`last_factor` or `frozen`) |
| `link_refused` | warning | An emailed link was refused. | `link` and `reason`, [below](https://keyringauth.com/docs/0.x/security-log-and-emails#refused-links) |
| `verification_refused` | critical | 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. | `skipped`, the steps |
| `refusals_limited` | warning | Entries of a refused kind stopped being written for a while. See [Refusals That Repeat](https://keyringauth.com/docs/0.x/security-log-and-emails#refusals-that-repeat). | `type`, the entry type left out |
| `impersonation_started` | notice | Someone signed in as another user. Logged on both accounts. See [Impersonation](https://keyringauth.com/docs/0.x/impersonation#security-log-and-events). | `impersonator` and `user` (the two IDs), `role` (`impersonator` or `impersonated`) |
| `impersonation_ended` | info | An impersonation ended. Logged on both accounts, or on the other alone once one is deleted. | `impersonator`, `user`, `role`, `reason` (`stopped`, `expired`, `revoked`, `impersonator_session_ended`, `lost`, `signed_out` or `failed`), `returned` |
| `impersonation_refused` | warning | A start of an [impersonation](https://keyringauth.com/docs/0.x/impersonation#security-log-and-events) was refused. Logged on the impersonator's account. | `reason` (an [`ImpersonationRefusal`](https://keyringauth.com/docs/0.x/impersonation#from-your-own-code) value, such as `not_allowed`, or `not_found` for an ID nobody has), `user` (the ID asked for, cut to 64 characters) |

A wrong password for an unknown account is logged as `factor_failed`, with no user. Form validation errors aren't logged.

## "Was This You?" Alerts

After a successful sign in, Keyring flashes `keyring.alerts` to the session. These are unseen log entries worth asking the user about.

```json
[
  { "type": "second_factor_failed", "factor": "totp", "at": "2026-11-08T09:12:00+00:00", "ip": "198.51.100.4" }
]
```

With `Features::devices()` on, a browser only gets alerts for entries logged after the account first used that browser. A browser first used after an alert was logged doesn't get it either, since it could belong to whoever caused the event.

The types that become alerts are listed in `security_log.alerts`. Any [entry type](https://keyringauth.com/docs/0.x/security-log-and-emails#entry-types) can be added. A `second_factor_failed` alert is the classic sign that someone else knows the password.

To read alerts yourself, call `pullAlerts()`. It returns the unseen alerts, newest first, and marks them seen, so each comes back once. Pass `since:` to get only the entries logged after a time:

```php
use Keyring\Activity\SecurityLog;

$alerts = app(SecurityLog::class)->pullAlerts($request->user());
```

A JSON sign in returns them too, as `alerts` on the `200` `authenticated` answer. The list is empty when there's nothing to ask about. Alerts are also flashed for JSON requests, so a page loaded afterwards can read them. A frontend Laravel doesn't serve should show the ones in the answer, and not also read the flash, or it'll show them twice. See [Where Each Answer Goes](https://keyringauth.com/docs/0.x/headless#where-each-answer-goes).

To show a banner, share the alerts through your Inertia middleware:

```php
// app/Http/Middleware/HandleInertiaRequests.php
public function share(Request $request): array
{
    return [
        ...parent::share($request),
        'keyringAlerts' => fn () => $request->session()->get('keyring.alerts', []),
    ];
}
```

## Security Emails

Keyring's emails are ordinary Laravel notifications in the `Keyring\Notifications` namespace, sent through your mailer. Nothing to publish or register. To replace one, or turn it off, pass a class or `null` to `Keyring::notifications()`, usually from your `KeyringServiceProvider`:

```php
use Keyring\Notifications\CloneSuspected;

Keyring::notifications([
    'new_device' => \App\Notifications\NewDevice::class,   // yours instead of Keyring's
    'recovery_code_used' => null,                            // not sent
    'clone_suspected' => CloneSuspected::class,              // the one notice that starts off
]);
```

Types you leave out keep Keyring's notification. Every security notice starts on except `clone_suspected`, which you turn on by listing it as above. A notice is only sent when its event happens, so these need their feature on:

- `new_device` needs `Features::devices()`.
- `second_factor_failed` needs a sign-in method besides the password.
- `email_changed` and `email_change_reverted` need `Features::emailChanges()`.

Calling `Keyring::notifications()` again adds to earlier calls. An unknown type throws an `InvalidArgumentException`.

An account gets each kind of notice at most `limits.notices` times every `limits.notices_per` (5 an hour by default), so nobody can make your app mail one person without end. The [security log](https://keyringauth.com/docs/0.x/security-log-and-emails#the-security-log) records every event either way.

A `MustVerifyEmail` user gets no security emails until the address is verified. The one exception is `password_changed` after a reset, since the reset link went to that address.

To reword an email, translate its strings. Each goes through `__`, so a line in `lang/en.json` replaces it. To restyle them all, publish Laravel's mail template with `php artisan vendor:publish --tag=laravel-mail`.

### Email Types

The security notices, each sent to the user. Each notice receives the named constructor arguments in the Passes column, built through the container.

| Type | Sent When | Passes |
|---|---|---|
| `new_device` | A sign in from a new device. | `url`, the ["this wasn't me" link](https://keyringauth.com/docs/0.x/devices-and-sessions#the-this-wasnt-me-link). None for a ["remember me"](https://keyringauth.com/docs/0.x/devices-and-sessions#remember-me) browser on an account at `devices.limit`. |
| `password_changed` | The password was changed or reset. | |
| `authenticator_added` | A sign-in method was added. | `name`, and `url` when [`authenticators_url`](https://keyringauth.com/docs/0.x/configuration#account-changes-and-enrollment) is set |
| `authenticator_removed` | A sign-in method was removed. | `name` |
| `second_factor_failed` | The password, or an identity provider sign in, was right, but the next factor failed. | `name`, the first step's method, when it wasn't the password |
| `recovery_code_used` | A recovery code was used. | `remaining` |
| `recovery_codes_generated` | A new set of recovery codes was made, including the set that comes with a first extra sign-in method. | `url`, when `authenticators_url` is set |
| `account_locked` | Failed attempts got the password or a passkey refused until a reset. | `url` (the `password.request` route, when the app has one), `device`, `ip` |
| `suspicious_activity` | A [risk action](https://keyringauth.com/docs/0.x/risk#actions) with `notify()` ran. | `reasons` |
| `clone_suspected` | A passkey or security key looked cloned. | `name` |
| `email_changed` | An email change was applied. Sent to both addresses. | |
| `email_change_reverted` | An email change was undone. | |

Every notice also gets `when` (the time as text, in your app's timezone), `at` (the same moment as a date, for formatting in the user's timezone), `device`, `ip` and `contact`, your [support contact](https://keyringauth.com/docs/0.x/security-log-and-emails#a-support-contact). The copy of `email_change_reverted` sent to the new address leaves out `device` and `ip`, since that address may belong to whoever took over the account.

Most notices tell the user who didn't do it to change their password and check their sign-in methods. `authenticator_added` and `recovery_codes_generated` also say to sign out everywhere, since someone else may be signed in. With `authenticators_url` set, both have a "Review your sign-in methods" button. The link is built from `APP_URL`, carries no token, and does nothing until the owner is signed in on that page.

Values such as `name`, `device` and `reasons` can contain what a user or browser sent. Keyring cuts each to one line of at most 500 characters. Its own emails pass them through `Keyring\Support\MailText::plain`, since Laravel reads mail lines as Markdown, and a name could otherwise add a link. Do the same in your own `MailMessage` lines, and escape them anywhere else you show them.

### A Support Contact

NIST SP 800-63B-4 (Sec. 4.6) asks that a notice tell a recipient who says it wasn't them how to get help. Keyring can't know your support team, so set it:

```php
// config/keyring.php
'support_contact' => 'https://example.com/support',   // or 'support@example.com'
```

Every notification Keyring builds gets it as `contact`, flow emails included. The security notices, `VerificationCode` and `EmailChangeNotice` end with "If this wasn't you and you need help, contact us", followed by the contact, as a link when it's a URL or an email address. The default is `null`, which leaves the line out. Set it before you say your notices follow NIST.

Section 4.6 also asks for notices to go to every address an account has, at least two. Keyring only knows the `email` attribute. To send to more, return them from your user model:

```php
// app/Models/User.php
public function routeNotificationForMail(): array
{
    return array_filter([$this->email, $this->backup_email]);
}
```

This also changes where Laravel's own mail goes. Keeping and verifying a second address is up to your app. See [Known Limitations](https://keyringauth.com/docs/0.x/security#known-limitations). The [OWASP ASVS](https://keyringauth.com/docs/0.x/owasp-asvs) page lists what each level expects.

### Emails a Flow Needs

Five emails are part of a flow, not notices, and the flow can't work without them. Each is built the same way, with `contact` included. If you set one to `null`, the flow throws a `Keyring\Exceptions\MissingNotification` that names the type:

| Type | Sent To | Passes |
|---|---|---|
| `verification_code` | The user, with an [email code](https://keyringauth.com/docs/0.x/factors#email-codes). | `code`, `minutes`, `enrolling` (true when it confirms a new email code sign-in method), and `url`, the [sign-in link](https://keyringauth.com/docs/0.x/factors#signing-in-from-the-email), when the factor sends one |
| `confirm_email_change` | The new address. | `url`, `expiresAt` |
| `email_change_notice` | The current address. | `email` (the new address, mostly hidden), `revertUrl`, and `confirmUrl` when this address must confirm too |
| `email_address_in_use` | An address someone tried to change to, when it already has an account. | |
| `already_registered` | An address someone tried to [register](https://keyringauth.com/docs/0.x/sign-in-flow#without-revealing-who-has-an-account) with, when it already has an account. | `loginUrl`, and `resetUrl` when password resets are on |

Keyring's `verification_code` puts the code in its body as one run of digits beside the word "code", and not in its subject, so mail apps can offer to copy it without the code reaching mail logs. A replacement should do the same (see [Email Codes](https://keyringauth.com/docs/0.x/factors#email-codes)). One that takes `url` should show it as a button beside the code, and say it only signs in from the browser where the sign in started.

The email change emails and `already_registered` are sent after the response, so timing doesn't reveal whether an address has an account. An email change is refused before saving if one of its three emails is off, and registration is refused without `already_registered`, unless `registration.reveal_taken` is on.

The email change emails, `already_registered`, and any copy sent to an address the account no longer has go to a bare address. Their `$notifiable` is an `AnonymousNotifiable`, so keep `via` and `toMail` in your own classes from reading user attributes.

Password resets and verification use Laravel's own notifications, and you change them the usual Laravel way. See [Resetting the Password](https://keyringauth.com/docs/0.x/protected-changes#resetting-the-password).

### Your Own Templates

Keyring builds each notice with the arguments above, then sends it. To write every security notice's email from your own views, such as Maizzle templates, give `SecurityNotice` a callback in your `KeyringServiceProvider`. It receives the notice and the person it's for:

```php
use Illuminate\Notifications\Messages\MailMessage;
use Keyring\Notifications\SecurityNotice;

SecurityNotice::toMailUsing(fn (SecurityNotice $notice, object $notifiable) => (new MailMessage)
    ->subject($notice->subject())
    ->view('emails.keyring.notice', [
        'intro' => $notice->intro(),
        'when' => $notice->when,
        'device' => $notice->device,
        'ip' => $notice->ip,
        'actionText' => $notice->action(),
        'actionUrl' => $notice->action() === null ? null : $notice->url,
        'contact' => $notice->contact,
    ]));
```

Blade's `{{ }}` escapes those values. The callback may return a `Mailable` instead. [Emails With Maizzle](https://keyringauth.com/docs/0.x/recipes#emails-with-maizzle) walks through this approach. `toMailUsing` doesn't reach the [emails a flow needs](https://keyringauth.com/docs/0.x/security-log-and-emails#emails-a-flow-needs).

Keyring's notices extend the abstract `Keyring\Notifications\SecurityNotice` class. It defines `subject`, `intro`, and `action` when it has a button, and may override `ifNotYou`. Notices are queued once any open database transaction commits, so a rolled-back change is never announced.

For a single notice, extend Keyring's class and register yours:

```php
namespace App\Notifications;

use Illuminate\Notifications\Messages\MailMessage;
use Keyring\Notifications\PasswordChanged as KeyringPasswordChanged;

class PasswordChanged extends KeyringPasswordChanged
{
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject($this->subject())
            ->view('emails.password-changed', ['when' => $this->when, 'device' => $this->device, 'ip' => $this->ip]);
    }
}
```

```php
Keyring::notifications(['password_changed' => \App\Notifications\PasswordChanged::class]);
```

Any class whose constructor takes the arguments it wants will do. It needn't extend Keyring's.

### Slack, SMS and Other Channels

A notification can go to any channel Laravel supports. Choose the channels in `via`, per user if you like, and add a method for each:

```php
namespace App\Notifications;

use Illuminate\Notifications\Slack\SlackMessage;
use Keyring\Notifications\NewDevice as KeyringNewDevice;

class NewDevice extends KeyringNewDevice
{
    public function via(object $notifiable): array
    {
        return $notifiable->slack_webhook ? ['mail', 'slack'] : ['mail'];
    }

    public function toSlack(object $notifiable): SlackMessage
    {
        // Slack reads <...> as a link, and a user agent is whatever the browser sent.
        return (new SlackMessage)->text(htmlspecialchars($this->subject().': '.$this->device, ENT_NOQUOTES));
    }
}
```

Register it with `Keyring::notifications(['new_device' => \App\Notifications\NewDevice::class])`. Slack needs Laravel's `laravel/slack-notification-channel` package. For `database` or `broadcast`, add a `toArray` method.

### Sending Something Else Entirely

Keyring dispatches an [event](https://keyringauth.com/docs/0.x/events) for every notice, whether or not it's on. To do something other than email, set the type to `null` and listen for the event.

## Laravel's Auth Events

Keyring also dispatches Laravel's `Illuminate\Auth\Events\Failed`, `Lockout` and `PasswordReset` events, so your existing listeners keep working. See [Events](https://keyringauth.com/docs/0.x/events#laravels-auth-events).
