> For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt.

# Events

The auth service reports what happens to accounts and sessions as events: logins, failures, sessions created and revoked, reused refresh tokens. Use them for an audit log, security alerts, or an outbox.

```ts
createAuth({
  dataProvider: {
    ...methods,
    // Durable: in the transaction of the step.
    recordEvent: (event) => db.insertInto('audit_log').values(toRow(event)).execute(),
  },
  // Best effort: after the step.
  onEvent: (event) => metrics.increment(`auth.${event.type}`),
})
```

- `dataProvider.recordEvent(event)` stores the event inside the transaction of its step, with `dataProvider.transaction()`: the login and its audit row are written together, or not at all. An error fails the step.
- `onEvent(event)` is called after the step is committed: logs, metrics. Its errors are logged and ignored.

`onLoginSuccess`, `onLoginFailed` and `onRefreshTokenReuse` are also available, as shortcuts.

## Transactions

With `transaction(fn)`, the steps that write several records (login, refresh token rotation, logout, revocations) run in one database transaction, and every call of the step goes to the data provider `fn` receives:

```ts
const createProvider = (db: Kysely<DB> | Transaction<DB>): DataProvider => ({
  ...methodsOver(db),
  transaction: (fn) => db.transaction().execute((tx) => fn(createProvider(tx))),
  recordEvent: (event) => insertAuditRow(db, event),
})
```

Without it, each method of the data provider must be atomic on its own.

## Fields

Every event has a `type`, an `occurredAt` date, and when they apply, `userId`, `sessionId` (the `sid` claim of the tokens) and `meta`: the request (`ipAddress`, `userAgent`, `requestId`, `clientId`). Service calls outside a request, like `revokeUserSessions()`, have no `meta`. Events never carry a password, a token or a code.

| Event                                    | Fields                                                                                                                                                                                                                                                              |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `login.succeeded`                        | `method`, `clientId`                                                                                                                                                                                                                                                |
| `login.failed`                           | `method`, `reason` (`unknown_user`, `invalid_password`, `invalid_role`, `locked`, `account_suspended`, `account_disabled`, `email_not_verified`, `sso_required`), `identifierHash`                                                                                  |
| `login.locked`                           | `identifierHash`: a login rate limit counter crossed its limit                                                                                                                                                                                                      |
| `password.rehashed`                      | `fromHasher`, `toHasher`: a hash upgraded at login                                                                                                                                                                                                                  |
| `session.created`                        | `method` (`password`, `magic_link`, `passkey`, `oauth`, `sso`, `impersonation`, or `token` for `generateTokensForUser()` without method), `amr`, `actorId` for an impersonation, `expiresAt` with an absolute timeout                                               |
| `session.revoked`                        | `reason` (`logout`, `user_revoked`, `token_reuse`, `account_disabled`, `admin`, `impersonation_ended`…)                                                                                                                                                             |
| `session.revoked_all`                    | `reason` (`logout_all`, `revoked_others`, `admin` by `revokeUserSessions()`, `account_disabled`, `password_changed`, `password_reset`, `email_changed`, `email_verified`, `account_claimed`, `mfa_enabled`…), with the sessions store `count` and `exceptSessionId` |
| `session.token_reuse_detected`           | `accessTokenId`: a used refresh token came back, its session is revoked                                                                                                                                                                                             |
| `user.signed_up`                         | `method`: an account created by [sign-up](https://dotpress.dev/auth/sign-up.md), with `provider` for a [social login](https://dotpress.dev/auth/oauth.md) or an [SSO](https://dotpress.dev/auth/sso.md) login (`sso:<connectionId>`)                                |
| `user.email_verified`                    | —                                                                                                                                                                                                                                                                   |
| `password.reset_requested`               | —: a reset link sent, for existing accounts only                                                                                                                                                                                                                    |
| `password.reset`                         | —                                                                                                                                                                                                                                                                   |
| `password.changed`                       | `via` (`change`, `reset`)                                                                                                                                                                                                                                           |
| `user.email_change_requested`            | `newEmailHash`: SHA-256 of the new address                                                                                                                                                                                                                          |
| `user.email_changed`                     | —: the addresses are the data of the app                                                                                                                                                                                                                            |
| `magic_link.requested`                   | —: a login link sent; without `userId` for an address without account                                                                                                                                                                                               |
| `mfa.challenge_created`                  | `kind` (`login`, `step_up`): a second factor asked                                                                                                                                                                                                                  |
| `mfa.succeeded`                          | `method` (`totp`, `email`, `sms`, `recovery_code`, `passkey`), `factorId`                                                                                                                                                                                           |
| `mfa.failed`                             | `method`, `factorId`: a wrong code                                                                                                                                                                                                                                  |
| `mfa.factor_added`, `mfa.factor_removed` | `factorId`, `factorType`                                                                                                                                                                                                                                            |
| `mfa.primary_changed`                    | `factorId`                                                                                                                                                                                                                                                          |
| `mfa.recovery_code_used`                 | `remaining`                                                                                                                                                                                                                                                         |
| `mfa.recovery_codes_regenerated`         | —                                                                                                                                                                                                                                                                   |
| `trusted_device.created`                 | `deviceId`                                                                                                                                                                                                                                                          |
| `trusted_device.revoked`                 | `deviceId` (one device), `count`, `reason` (`user`, `factors_changed`, `password_changed`)                                                                                                                                                                          |
| `session.step_up`                        | `method` (`password`, or the method of the second factor): a [step-up](https://dotpress.dev/auth/step-up.md) of the session                                                                                                                                         |
| `passkey.registered`                     | `passkeyId`, `deviceType`, `backedUp`: a [passkey](https://dotpress.dev/auth/passkeys.md) added                                                                                                                                                                     |
| `passkey.removed`                        | `passkeyId`                                                                                                                                                                                                                                                         |
| `passkey.counter_invalid`                | `passkeyId`: a [cloned passkey](https://dotpress.dev/auth/passkeys.md#cloned-passkeys), refused                                                                                                                                                                     |
| `identity.linked`                        | `identityId`, `provider`: a provider account [linked](https://dotpress.dev/auth/oauth.md#linking), by a link flow or by its verified address                                                                                                                        |
| `identity.unlinked`                      | `identityId`, `provider`                                                                                                                                                                                                                                            |
| `sso.login_succeeded`                    | `connectionId`: an [SSO](https://dotpress.dev/auth/sso.md) login                                                                                                                                                                                                    |
| `sso.login_failed`                       | `connectionId`, `reason`: the error code of a refused SSO login (`SSO_ASSERTION_INVALID`, `SSO_REJECTED`…)                                                                                                                                                          |

`identifierHash` is the SHA-256 of the normalized username: it correlates the attempts on an account without storing what was typed.

`AuthEvent` is a discriminated union on `type`:

```ts
import type { AuthEvent } from '@dotpress/auth'

const describe = (event: AuthEvent) => {
  switch (event.type) {
    case 'login.failed':
      return `login failed: ${event.reason}`
    case 'session.token_reuse_detected':
      return `token reuse in session ${event.sessionId}`
    default:
      return event.type
  }
}
```
