Two-factor authentication
14 files2 packages1 dependency
This pack adds two-factor authentication to your API as JSON endpoints. It fits the guard your app authenticates with, access tokens or session, and enhances your existing login rather than replacing it.
- Enrollment endpoints that return the QR code and secret, confirmed with a six-digit code.
- One-time recovery codes returned once in the response, which the client can regenerate.
- A login that returns a short-lived, purpose-bound challenge token for a two-factor user, exchanged with a code at a rate-limited challenge endpoint.
- An email to the account owner whenever two-factor is turned on, turned off, or its recovery codes change.
Apply the two-factor pack with Flow. Start a new session in your selected coding agent and execute the following slash command inside it.
$ npx @adonisplus/flow apply --pack=two-factor --agent=claude
$ npx @adonisplus/flow apply --pack=two-factor --agent=codex
$ npx @adonisplus/flow apply --pack=two-factor --agent=cursor
$ npx @adonisplus/flow apply --pack=two-factor --agent=opencode
After applying, Flow will make the following changes to your app.
- Discover your default guard, access tokens or session, so the challenge finishes on the credential you already issue.
- Land the backend as shipped, from the migration and model mixin through the validators, the enrollment, recovery-codes, and challenge controllers, routes, and the change-notification mailer.
- Enhance your login to return a challenge token for a two-factor user instead of the credential.
- Run the tests, then drive the enrollment, recovery-codes, and challenge endpoints and show you the responses.
Delta will differ
Flow adapts the pack to your app, so the exact set of created and edited files depends on what you already have. This is the shape of an apply onto the API starter kit with the auth pack in place.
Migration
xxxx_add_totp_columns_to_users.tsdatabase/migrations/xxxx_add_totp_columns_to_users.tsAdds the TOTP and recovery-code columns to the users table.created
Model, transformer & validators
user.tsapp/models/user.tsAdds thewithTotpManagement()mixin.editeduser_transformer.tsapp/transformers/user_transformer.tsExposes the two-factor state and the remaining-codes count.editeduser.tsapp/validators/user.tsAdds the TOTP, recovery-code, and challenge validators.edited
Controllers
two_factor_enrollment_controller.tsapp/controllers/two_factor_enrollment_controller.tsReturns the QR and secret, verifies the first code, and disables two-factor.createdrecovery_codes_controller.tsapp/controllers/recovery_codes_controller.tsRegenerates and returns a fresh set of recovery codes.createdtwo_factor_challenge_controller.tsapp/controllers/two_factor_challenge_controller.tsVerifies the rate-limited challenge and issues your guard's credential.createdsession_controller.tsapp/controllers/session_controller.tsReturns a challenge token for a two-factor user instead of the credential.edited
Mailer & email template
two_factor_changed_notification.tsapp/mails/two_factor_changed_notification.tsThe change-notification email for enable, disable, and regenerate.createdtwo_factor_changed.edgeresources/views/emails/two_factor_changed.edgeBody of the change-notification email.created
Routes
routes.tsstart/routes.tsAdds the enrollment, recovery, and challenge endpoints.edited
Factory & tests
user_factory.tsdatabase/factories/user_factory.tsAdds thetwoFactorEnabledstate and the enable hook.editedenrollment.spec.tstests/functional/two_factor/enrollment.spec.tsEnrollment, disable, and regenerate specs.createdlogin_challenge.spec.tstests/functional/two_factor/login_challenge.spec.tsLogin-challenge specs for the discovered guard.created
Configuration
Section titled "Configuration"The withTotpManagement() mixin on the User model backs the whole feature. Pass an options object to change its defaults.
issuerstringAdonisJS App.windownumber1 accepts the previous, current, and next period, about 90 seconds. Defaults to 1.recoveryCodesCountnumber10.withTotpManagement(encryption, hash, { issuer: 'ACME', window: 2 }) Secrets are encrypted, recovery codes are hashed
Section titled "Secrets are encrypted, recovery codes are hashed"The confirmed TOTP secret is encrypted at rest and each recovery code is stored only as a hash. A leaked database row cannot be turned back into a working secret or a usable code.
Enrolling is two requests
Section titled "Enrolling is two requests"The client posts to start enrollment and receives the QR code and secret. Two-factor is not active until the client confirms it with a code from the authenticator, which the verify request checks before promoting the secret. A client that loses the pending secret can start again, which safely regenerates it.
Recovery codes are returned once
Section titled "Recovery codes are returned once"The recovery codes come back in the response body, on enable and on regenerate, and cannot be re-fetched. Regenerating replaces the whole set and retires the old codes.
Login returns a challenge token, not the credential
Section titled "Login returns a challenge token, not the credential"For a two-factor user, login answers { data: { status: 'mfaRequired', challengeToken } } instead of the credential. The client narrows on data.status against the authenticated arm your login already returns. The challenge token is encrypted with a five-minute expiry and bound to the two_factor_challenge purpose, so an expired or wrong-purpose token is rejected with 401.
const challengeToken = encryption.encrypt({ userId: user.id }, '5 minutes', 'two_factor_challenge')A used code cannot be replayed
Section titled "A used code cannot be replayed"Each accepted code's time step is recorded, so the same code cannot be used a second time inside its window.
The challenge is rate limited
Section titled "The challenge is rate limited"Failed challenge attempts run through two limiter keys, one scoped per IP and a stricter one per IP-and-user that adds a 20-minute block after five failures. Both run through penalize, so the budget is spent only when a code is wrong and a correct code is always free.
const ipKey = `two_factor_${request.ip()}`
const userKey = `two_factor_${request.ip()}_${decrypted.userId}`
const challengeLimiter = limiter.multi([
{ duration: '1 min', requests: 10, key: ipKey },
{ duration: '1 min', requests: 5, blockDuration: '20 mins', key: userKey },
])The challenge finishes on your guard
Section titled "The challenge finishes on your guard"The verified challenge issues the credential for your default guard. A tokens guard returns a fresh access token, a session guard establishes the session and sets the cookie.
Every change emails the account owner
Section titled "Every change emails the account owner"Turning two-factor on or off, or regenerating the recovery codes, sends the account owner an email out of band. If a compromised session quietly strips two-factor, the change is at least visible to the real owner.
Added in Flow 0.2.0.