Two-factor authentication, as a realm setting

This application contains no authentication code. It registers AlephaApiUsers and sets mfa.totp: "optional" on its realm. Everything below is what those two lines produce.

Enroll
/account/security
Scan the QR code with any authenticator app, confirm one code, and keep the ten recovery codes. The QR is rendered server-side as SVG, so nothing in the browser needs a QR library.
Sign in
/auth/login
The password alone no longer returns a session. It returns a signed five-minute challenge, and the code step exchanges it for one. A recovery code works here too, once each.
Recover
/admin
Lost the phone and the recovery codes? An administrator clears the second factor from the user's security tab, and the account signs in on its password again.

Things worth trying

  • Reuse a code within its 30-second window. It is refused: a time step is burned once accepted.
  • Let a code age past the window. Verification allows one step either side for clock drift, and no more.
  • Spend a recovery code, then spend it again. The second attempt fails.
  • Get the code wrong repeatedly. Second-factor attempts have their own rate-limit counter, separate from the password one, so failing here does not spend the budget protecting the password.
  • Turn it off from the account page. It asks for a current code, not just a confirmation: an unattended signed-in browser is not proof.

There is no password reset and no email verification, because this realm has no email provider. That is the constraint the whole configuration answers, and the reason the second factor is an authenticator app rather than a mailed code: a realm whose reset channel is email gains much less from a second factor that is also email.

An Alepha example. Everything here is a realm setting, not application code.