# Managing Authenticators

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

## Introduction

A [factor](https://keyringauth.com/docs/0.x/go/factors) is a kind of sign-in method, such as an authenticator app or a passkey. An authenticator is one a user has set up. One set of routes adds, renames and removes authenticators for every factor, as in the PHP package. Turn them on with `Features.ManageAuthenticators`:

```go
k := keyring.New[models.User](func(cfg *keyring.Config) {
	cfg.Features.ManageAuthenticators = true
})
```

Without it, users can't set up a sign-in method beyond their password. The rules for adding, removing and freezing are the PHP package's `AuthenticatorChanges`, so an account behaves the same on either side.

The factors a user can add are an authenticator app (`totp`), recovery codes (`recovery`), passkeys (`passkey`, while `Factors.Passkeys` is on), emailed codes (`email-code`, while `Factors.EmailCodes` is set), your own [code factors](https://keyringauth.com/docs/0.x/go/factors#writing-a-code-factor), and links to identity providers (`sso`, while `Factors.SingleSignOn` is on, see [Single Sign-On](https://keyringauth.com/docs/0.x/go/sso)). There are no security keys yet.

A sign-in method of a factor Keyring for Go doesn't have, such as a security key a PHP application added, isn't listed, renamed or removed here: its routes are a `404`, as the PHP package's are for a factor it doesn't register. It still counts against the account: added recently, it freezes the account, and removing the last factor Go knows keeps the recovery codes. See [Differences From PHP](https://keyringauth.com/docs/0.x/go/differences#managing-authenticators).

## Email Verification

With `Features.EmailVerification` on, a user must verify their address before beginning or confirming an enrollment, as a PHP user model that implements `MustVerifyEmail` must. Until they do, they get a `403`.

With `Features.Registration` on, anyone can type any address, so addresses have to be verified at all. `Register` refuses registration with `Features.ManageAuthenticators` on and `Features.EmailVerification` off, unless `AllowEnrollmentWhen` decides who may enroll. The PHP package throws its `EmailVerificationRequired` at the first enrollment instead. Without registration, accounts come from you, so verification isn't required.

### Who May Enroll

If you prove addresses another way, decide who may enroll yourself, with `AllowEnrollmentWhen`:

```go
k.AllowEnrollmentWhen(func(ctx context.Context, user *models.User) bool {
	return user.ApprovedAt != nil
})
```

It replaces the verified-email rule. A user it refuses gets the same `403`. `k.AllowsEnrollment(ctx, user)` asks it from your own code.

## Adding an Authenticator

Adding an authenticator takes two steps, as in the PHP package. Nothing is saved until the second one succeeds.

### Beginning

`POST /user/authenticators/{factor}` starts an enrollment: a new base32 `secret`, `algorithm`, the `otpauth://` `url` and the `qr` code as SVG for an authenticator app, the new `codes` for recovery codes, `options` for `navigator.credentials.create()` for a passkey (excluding every key the user has), or `{ "length", "sent": true }` for a code factor, once its first code is sent. It's kept in the session for `EnrollmentsFor` (15 minutes), encrypted, for the account that began it. Starting again replaces it, and signing in forgets it.

The QR code is drawn with `rsc.io/qr`, 192 pixels across with no margin, as the PHP package's is. The markup differs, the code doesn't.

Beginning counts against `Limits.Forms`, where the PHP package doesn't limit it: beginning sends codes and does a key's work.

### The Password for a First Second Factor

As in the PHP package: the first second factor of an account with an established password and no established second factor takes the password, typed when it begins (`password`) and checked under the password's rate limits. So does a code factor that proves the address (`SentToAnAddress`). A factor saved without it is marked `added_without_password`. See the [PHP docs](https://keyringauth.com/docs/0.x/authenticators#the-password-for-a-first-second-factor) for why.

A wrong password dispatches `FactorFailed`, and `EnrollmentRefused` with `password`. It doesn't run the [pipeline](https://keyringauth.com/docs/0.x/go/sign-in-flow#the-verification-pipeline).

### Confirming

`POST /user/authenticators/{factor}/confirm` proves it works (`code`, nothing for recovery codes, `credential` for a passkey, or a code factor's `code`, and an optional `name`) and saves it, once, whichever copy of the session it comes back in. The first sign-in method is the default. The first extra factor, or one added once the codes have run out, comes with recovery codes. Confirming counts the new method as verified in this session, which moves to a new session ID and record and raises its level.

Each change runs under the lock on the user's sessions as well as the user's row, adding one only while the session that asked is still signed in. The PHP package takes the row lock alone, which SQLite doesn't have. A key already registered to anyone isn't added again, and a posted credential whose `id` or `rawId` isn't the attested credential ID is refused, which webauthn-lib doesn't check.

The first factor's recovery codes are decided and made under the lock. If another request made a set meanwhile, that set is kept, and the answer has no `recoveryCodes`.

## Recovery Codes

As in the PHP package: recovery codes need a factor to back up, new ones replace the old, and `remaining` and `replace` say when to make a new set. `POST /user/authenticators/recovery` then `/confirm` makes a set. See [Recovery Codes](https://keyringauth.com/docs/0.x/go/factors#recovery-codes).

## Renaming and Choosing the Default

`PATCH /user/authenticators/{authenticator}` renames it (`name`) or makes it the default (`default`, never for recovery codes or a single sign-on link). The URL names the authenticator by its ID. The URLs are the PHP package's.

Making the default the default again keeps it. The PHP package unsets it there, so the account is left with no default. Renaming one, or making one the default, that was removed meanwhile is a `404`, decided under the lock.

## Removing Authenticators

`DELETE /user/authenticators/{authenticator}` removes the authenticator named by its ID. As in the PHP package, removing what would leave no way to sign in, or a policy without `IfEnrolled()` unmet, is refused (`last_factor`), and removing the last second factor takes the password, long enough to stand alone (`Passwords.MinWithoutMFA`), and the recovery codes go with it. A removal or replacement stops trusting the user's devices, and forgets the failures in a row counted against what went. If the devices can't be distrusted, nothing is removed and nothing is announced.

## Frozen Sign-In Methods

The freeze is the PHP package's: for `EstablishedAfter` (7 days) after a factor that isn't established yet was added, or after something established was removed or replaced, removing, replacing or renaming an established authenticator, or recovery codes with codes left, is refused with a `422` on `authenticator` saying how long is left, and `frozen` `{ "reason": "new-authenticator" | "recent-change", "until", "skip" }`. New ones can always go. The changes are kept in `keyring_sign_in_changes`. See the [PHP docs](https://keyringauth.com/docs/0.x/authenticators#frozen-sign-in-methods) for why.

### Established Authenticators

An authenticator is established once the account has had it for `EstablishedAfter`. [`SignInMethods`](https://keyringauth.com/docs/0.x/go/authenticators#from-go) marks the ones the freeze holds with `Frozen`.

### Making a Change With an Established Key

The owner can make one change anyway with an established passkey added before the session signed in, or an authenticator app, with `SkipFreezeWithTotp`. `POST /user/authenticators/{factor}/proof-options` `{ "action": "remove" | "rename" | "replace", "target", "name" }` answers options for that change alone, and the change's own request sends the answer as `proof` `{ "factor", "credential" }` (or `code`, and `authenticator` for one of two apps). A challenge is answered once, in any copy of the session, and the change still freezes the account.

### Getting Past the Freeze

As in the [PHP docs](https://keyringauth.com/docs/0.x/authenticators#getting-past-the-freeze): wait it out, make the change with an established key, or reset the password. Setting `EstablishedAfter` to zero turns the freeze off.

## Signing Out Other Sessions

Confirming an enrollment and removing an authenticator both take `sign_out_others`. When it's `true` and the change goes through, Keyring signs the user out everywhere else, as [`DELETE /user/sessions`](https://keyringauth.com/docs/0.x/go/devices-and-sessions#listing-and-ending-sessions) does.

## From JavaScript

The browser package's helpers (`enroll()`, `beginEnrollment()`, `confirmEnrollment()`, `renameAuthenticator()`, `makeDefault()`, `removeAuthenticator()` and `proveWithKey()`) work with Keyring for Go unchanged, since the routes and JSON are the same. See the [PHP docs](https://keyringauth.com/docs/0.x/authenticators#from-javascript) and [Frontend](https://keyringauth.com/docs/0.x/go/frontend#managing-authenticators).

## From Go

There's no `$user->keyring` in Go: authenticators are rows in `keyring_authenticators`, with `secret` encrypted. For a settings page, `SignInMethods` gives what such a page shows, as the Rust crate's `sign_in_methods()`:

```go
func security(r *web.Request) *web.Response {
	user := auth.User[models.User](r)

	methods, err := keyring.From[models.User](r).SignInMethods(r, user)
	if err != nil {
		return web.Fail(err)
	}

	return inertia.Render("settings/security", inertia.Props{"methods": methods})
}
```

`SignInMethods` encodes with the keys a frontend reads:

| Field | Key | |
|---|---|---|
| `Authenticators` | `authenticators` | The user's authenticators, the password left out, each a `SignInMethod` as the routes present one (`factor`, `id`, `name`, `createdAt`, `lastUsedAt`, and `remaining`, `replace` or `hint` where the factor has them), with `isDefault`, and `frozen` when the freeze holds it. |
| `Enrollable` | `enrollable` | The keys of the factors the user can add. Recovery codes only once the account has a factor for them to stand in for. |
| `PasswordToAdd` | `passwordToAdd` | The keys of those that take the current password to add. |
| `Frozen` | `frozen` | The freeze's `reason`, `until` (ISO 8601) and `message`, or `null`. |
| `HasSecondFactor` | `hasSecondFactor` | Whether the account has a second factor. Recovery codes and emailed codes don't count. |

An emailed code's `hint` masks its address. `k.GenerateRecoveryCodes(ctx)` makes a set of codes without saving it, as the PHP package's `RecoveryCodes::generate()`, and `k.UserHandle(ctx, user)` is the handle a new passkey knows the user by. The PHP package's `UserKeyring` methods (`all()`, `ofFactor()`, `canMeet()` and the rest) aren't ported.

## Routes

| Method | URI | Does |
|---|---|---|
| `POST` | `/user/authenticators/{factor}` | Begins an enrollment. May check the password. |
| `POST` | `/user/authenticators/{factor}/confirm` | Finishes the enrollment. |
| `POST` | `/user/authenticators/{factor}/proof-options` | Returns the challenge for one change to a frozen account. |
| `PATCH` | `/user/authenticators/{authenticator}` | Renames the authenticator with that ID, or makes it the default. |
| `DELETE` | `/user/authenticators/{authenticator}` | Removes the authenticator with that ID. |

Every route needs a signed-in user and runs `ChangesMiddleware`, a fresh verification within 15 minutes by default (see [Fresh Verification](https://keyringauth.com/docs/0.x/go/step-up#fresh-verification)), and a browser [impersonating](https://keyringauth.com/docs/0.x/go/impersonation#whats-refused-while-impersonating) the user is refused.

`Limits.Forms` (six a minute) limits beginning, confirming, removing and the proof options, and the routes that change the session take the session lock (`BlockSession`). Someone else's authenticator is the `404` a missing one gets (`{"message":"Not Found"}`, where the PHP package names its model), and goes on record (`AccessRefused`).

## Responses

The status responses are the PHP package's: `enrollment-started` with `factor` and `enrollment`, `authenticator-added` with `authenticator`, `recoveryCodes` when made and `continue` when set, `authenticator-updated` with `authenticator`, and `authenticator-removed`. A browser that doesn't ask for JSON goes back with the status flashed, and the rest flashed encrypted under `keyring.result` in the session, as the PHP package's `StatusResponse::RESULT`, which `keyring.FlashedResult(r)` reads.

## Events

These are Keyring's own, as in the PHP package: `AuthenticatorAdded`, `AuthenticatorRemoved`, `RecoveryCodesGenerated`, `RecoveryCodeUsed`, `EnrollmentRefused` (`invalid`, `not_allowed`, `frozen` or `password`), `AuthenticatorRemovalRefused` (`last_factor` or `frozen`) and `AccessRefused`. Each is generic over the user type, such as `keyring.AuthenticatorAdded[models.User]`, and carries the authenticator as plain values (its `ID`, `Factor` and `Name`) rather than a model. See [Events](https://keyringauth.com/docs/0.x/go/events).
