Two-Factor Authentication (2FA)
Enhance your app's security with two-factor authentication.
OTP TOTP Backup Codes Trusted Devices
Two-Factor Authentication (2FA) adds an extra security step when users log in. Instead of just using a password, they'll need to provide a second form of verification. This makes it much harder for unauthorized people to access accounts, even if they've somehow gotten the password.
This plugin offers two main methods to do a second factor verification:
- OTP (One-Time Password): A temporary code sent to the user's email or phone.
- TOTP (Time-based One-Time Password): A code generated by an app on the user's device.
Additional features include:
- Generating backup codes for account recovery
- Enabling/disabling 2FA
- Managing trusted devices
Installation
Add the plugin to your auth config
Add the two-factor plugin to your auth configuration and specify your app name as the issuer.
import { entroAuth } from "@entro314labs/entro-auth"
import { twoFactor } from "@entro314labs/entro-auth/plugins"
export const auth = entroAuth({
// ... other config options
appName: "My App", // provide your app name. It'll be used as an issuer.
plugins: [
twoFactor()
]
})Migrate the database
Run the migration or generate the schema to add the necessary fields and tables to the database.
npx @entro314labs/entro-auth-cli migrateSee the Schema section to add the fields manually.
Add the client plugin
Add the client plugin and Specify where the user should be redirected if they need to verify 2nd factor
import { createAuthClient } from "@entro314labs/entro-auth/client"
import { twoFactorClient } from "@entro314labs/entro-auth/client/plugins"
export const authClient = createAuthClient({
plugins: [
twoFactorClient()
]
})Usage
Enabling 2FA
To enable two-factor authentication, call twoFactor.enable. The user must provide their password if they have an email/password account. You can choose between two methods:
totp(default) — sets up an authenticator app. The user must verify a TOTP code before 2FA becomes active. Returns{ method: "totp", totpURI, backupCodes }, withoutbackupCodeswhen two-factor is already on and the account holds some.otp— enables email/SMS-based codes immediately, with no extra verification step. Returns{ method: "otp" }. RequiresotpOptions.sendOTPto be configured on the server.
By default, enabling 2FA requires a password. Users who signed up via OAuth, passkeys, magic links, or anonymous auth cannot enable 2FA unless you set allowPasswordless: true in the plugin config. This option does not change which sign-in methods are challenged for 2FA. Where no password is asked for, the request needs a fresh session instead. An account that cannot sign in again, such as an anonymous one, can therefore turn 2FA on only while its first session is still fresh.
const { data, error } = await authClient.twoFactor.enable({ password: "secure-password", // required, The user’s password. Required for email/password accounts. method: "totp", // The 2FA method to enable. issuer: "my-app-name", // Custom issuer for the TOTP URI. Defaults to the app name in your auth config.});passwordstringrequiredThe user’s password. Required for email/password accounts.
method"otp" | "totp"The 2FA method to enable.
issuerstringCustom issuer for the TOTP URI. Defaults to the app name in your auth config.
When method is "totp" (default):
- Returns
{ method: "totp", totpURI, backupCodes }. UsetotpURIto display a QR code. backupCodesis left out when two-factor is already on another way and the account holds backup codes. See backup codes.- By default,
twoFactorEnabledremainsfalseuntil the user verifies a TOTP code. When the server plugin is configured withskipVerificationOnEnable: true, TOTP is enabled without enrollment-code verification. See verifying TOTP.
Calling twoFactor.enable when the user already has a verified TOTP authenticator returns TOTP_ALREADY_ENABLED. Disable the current authenticator before starting a new enrollment.
When method is "otp":
- Returns
{ method: "otp" }.twoFactorEnabledis set totrueimmediately. - Requires
otpOptions.sendOTPto be configured on the server. - OTP codes are sent via the configured
sendOTPfunction at sign-in time. SettingtwoFactorEnableddirectly via a database hook achieves the same result.
Sign In with 2FA
When a user with 2FA enabled tries to sign in, the response object will contain twoFactorRedirect set to true and twoFactorMethods — an array of the 2FA methods available for the user (e.g. ["totp"], ["totp", "otp"]). Use twoFactorMethods to decide which verification UI to show.
Every way of signing in that ends in a session is held to the second step: a password, email OTP, magic link, social and SSO providers (through the OAuth proxy as well), One Tap, Sign-In with Ethereum, a phone code, and an email verification that signs in. Otherwise control of the mailbox, or of a provider account with the same verified address, would be enough to sign in to an account that turned 2FA on.
A method that answers in JSON answers twoFactorRedirect. A method that answers with a redirect (a provider's callback, a magic link) keeps its redirect and adds twoFactorRedirect=true to the address, with twoFactorMethods (the steps the account can take, separated by commas, as in twoFactorMethods=totp,otp). The page it leads to has to be one a signed-out visitor can reach, and has to ask for the second step when it sees those parameters. In an Expo app, signIn.social resolves with twoFactorRedirect: true in its data instead.
A passkey sign-in has a rule of its own: with passkey({ secondFactor: true }), a passkey sign in to an account with 2FA on must have verified its user (a PIN, a fingerprint or a face); see the passkey plugin. Anonymous sign-in has no account behind it and is not held back.
To hold back a password sign-in only, as earlier versions did, set enforceOn:
twoFactor({
enforceOn: "credentials",
})A Provider That Is Not Linked Yet
Signing in with a provider for the first time links it to the account whose address it gives, and that link is made before the second step. On an account with 2FA on it would add a way in on the provider's word alone, and leave it there if the second step is never passed.
So where a provider sign-in is held to the second step, it does not link a provider to an account that has 2FA on. The sign-in is refused with PROVIDER_NOT_LINKED (403): a redirecting sign-in ends at your error page with error=PROVIDER_NOT_LINKED, and one that hands over an ID token answers it in JSON. The person signs in a way the account already has, takes the second step, and links the provider from their account with linkSocial. That works as before, since it comes from a session that passed the second step.
So linking has to stay open. If /link-social is in disabledPaths while a provider is configured and provider sign-ins are held to the second step, an account with 2FA on has no way left to add a provider, and Entro Auth says so in a warning when it starts.
- It applies to social providers, One Tap and SSO, on any device, a trusted one included.
- An account without 2FA is linked as before, and so is any account under
enforceOn: "credentials". - A provider the account has linked signs in and is held to the second step, as above.
- The code is not
account_not_linked, which an error page may already handle for accounts that cannot be linked at all. Handle both.
When a 2FA-enabled user signs in, the plugin issues a 2FA challenge instead of completing the sign-in. As part of this, the pending session is discarded and ctx.context.newSession is reset to null — there is no authenticated session until the user verifies the second factor. Server-side hooks (e.g. after hooks on the sign-in endpoints) that read ctx.context.newSession must null-check it before accessing newSession.user, otherwise they will throw while a 2FA challenge is in flight. Plugin after hooks on these endpoints run after the 2FA check regardless of plugin order.
You can handle this in the onSuccess callback or by providing a onTwoFactorRedirect callback in the plugin config.
import { authClient } from "@/lib/auth-client"
await authClient.signIn.email({
email: "user@example.com",
password: "password123",
},
{
async onSuccess(context) {
if (context.data.twoFactorRedirect) {
const methods = context.data.twoFactorMethods // e.g. ["totp", "otp"]
// Show the appropriate 2FA verification UI based on available methods
}
},
}
)Using the onTwoFactorRedirect config:
import { createAuthClient } from "@entro314labs/entro-auth/client";
import { twoFactorClient } from "@entro314labs/entro-auth/client/plugins";
const authClient = createAuthClient({
plugins: [
twoFactorClient({
onTwoFactorRedirect({ twoFactorMethods }){
// twoFactorMethods is e.g. ["totp", "otp"]
// Handle the 2FA verification globally
},
}),
],
});Using the twoFactorPage config:
import { createAuthClient } from "@entro314labs/entro-auth/client";
import { twoFactorClient } from "@entro314labs/entro-auth/client/plugins";
const authClient = createAuthClient({
plugins: [
twoFactorClient({
twoFactorPage: "/two-factor", // the page to redirect if a user needs to verify their 2nd factor
}),
],
});Using the twoFactorPage option will cause a full page reload when redirecting users to the two-factor authentication page. If you want to avoid page reloads, consider using the onTwoFactorRedirect callback instead to handle the redirect programmatically within your application.
With auth.api
When you call auth.api.signInEmail on the server, and the user has 2FA enabled, it will return an object where twoFactorRedirect is set to true. This behavior isn’t inferred in TypeScript, which can be misleading. You can check using in instead to check if twoFactorRedirect is set to true.
authClient.twoFactor.* handles cookies automatically in the browser. If you continue the 2FA flow with auth.api.* on the server, you must pass the relevant headers so Entro Auth can read the current 2FA state and set the resulting 2FA/session cookies. The generated examples below use await headers() for this, but in other frameworks you should pass the equivalent incoming request headers.
If you chain multiple auth.api.* calls in the same server flow, make sure you forward the cookies from the previous auth response into the next call.
import { auth } from "@/lib/auth"
const { headers: responseHeaders, response } = await auth.api.signInEmail({
returnHeaders: true,
body: {
email: "test@test.com",
password: "test",
},
});
if ("twoFactorRedirect" in response) {
// response.twoFactorMethods is e.g. ["totp", "otp"]
// Forward the cookies from responseHeaders into the next auth.api 2FA call.
// Handle the 2FA verification in place
}Disabling 2FA
To disable two-factor authentication, call twoFactor.disable with the user's password (required for credential accounts). If you enable allowPasswordless, the password can be omitted for users without a credential account; their session must then be fresh, or the request is refused with SESSION_NOT_FRESH (403). A code checked with verifyTotp, verifyOtp or verifyBackupCode renews the session, so such a user does not have to sign in again.
const { data, error } = await authClient.twoFactor.disable({ password, // The user's password (required for credential accounts)});passwordstringThe user's password (required for credential accounts)
TOTP
TOTP (Time-Based One-Time Password) is an algorithm that generates a unique password for each login attempt using time as a counter. Every fixed interval (Entro Auth defaults to 30 seconds), a new password is generated. This addresses several issues with traditional passwords: they can be forgotten, stolen, or guessed. OTPs solve some of these problems, but their delivery via SMS or email can be unreliable (or even risky, considering it opens new attack vectors).
TOTP, however, generates codes offline, making it both secure and convenient. You just need an authenticator app on your phone.
Getting TOTP URI
After enabling 2FA, you can get the TOTP URI to display to the user. This URI is generated by the server using the secret and issuer and can be used to generate a QR code for the user to scan with their authenticator app.
const { data, error } = await authClient.twoFactor.getTotpUri({ password, // The user's password (required for credential accounts)});passwordstringThe user's password (required for credential accounts)
Treat the TOTP URI as a secret. It contains the user's email and the shared secret used to generate TOTP codes. Render the QR code locally in the browser rather than sending the URI to a third-party QR service.
Example: Using React
Once you have the TOTP URI, you can use it to generate a QR code for the user to scan with their authenticator app.
import { authClient } from "@/lib/auth-client"
import QRCode from "react-qr-code";
export default function UserCard({ password }: { password: string }){
const { data: session } = authClient.useSession();
const { data: qr } = useQuery({
queryKey: ["two-factor-qr"],
queryFn: async () => {
const res = await authClient.twoFactor.getTotpUri({ password });
return res.data;
},
enabled: !!session?.user.twoFactorEnabled,
});
return (
<QRCode value={qr?.totpURI || ""} />
)
}Verifying TOTP
After the user has entered their 2FA code, you can verify it using twoFactor.verifyTotp method. Entro Auth follows standard practice by accepting TOTP codes from one period before and one after the current code, ensuring users can authenticate even with minor time delays on their end.
const { data, error } = await authClient.twoFactor.verifyTotp({ code: "012345", // required, The otp code to verify. trustDevice: true, // If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.});codestringrequiredThe otp code to verify.
trustDevicebooleanIf true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.
Importing Existing TOTP Secrets
To import TOTP secrets from another provider, prefix each Base32 secret with base32:, encrypt it with your auth secret, and store it in the twoFactor table. Then set twoFactorEnabled: true on the user.
import { symmetricEncrypt } from "@entro314labs/entro-auth/crypto";
const ctx = await auth.$context;
const secret = await symmetricEncrypt({
key: ctx.secretConfig,
data: `base32:${importedSecret}`,
});Remove any spaces from the secret before storing it. Imported secrets must use SHA-1 and the same digits and period as your TOTP options.
OTP
OTP (One-Time Password) is similar to TOTP but a random code is generated and sent to the user's email or phone.
Before using OTP to verify the second factor, you need to configure sendOTP in your Entro Auth instance. This function is responsible for sending the OTP to the user's email, phone, or any other method supported by your application.
import { entroAuth } from "@entro314labs/entro-auth"
import { twoFactor } from "@entro314labs/entro-auth/plugins"
export const auth = entroAuth({
plugins: [
twoFactor({
otpOptions: {
async sendOTP({ user, otp }, ctx) {
// send otp to user
},
},
})
]
})Sending OTP
Sending an OTP is done by calling the authClient.twoFactor.sendOtp function on the client or auth.api.sendTwoFactorOTP on the server. This function will trigger your sendOTP implementation that you provided in the Entro Auth configuration.
const { data, error } = await authClient.twoFactor.sendOtp({ trustDevice: true, // If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.});if (data) { // redirect or show the user to enter the code}trustDevicebooleanIf true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.
Verifying OTP
After the user has entered their OTP code, you can verify it using authClient.twoFactor.verifyOtp on the client or auth.api.verifyTwoFactorOTP on the server.
const { data, error } = await authClient.twoFactor.verifyOtp({ code: "012345", // required, The otp code to verify. trustDevice: true, // If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.});codestringrequiredThe otp code to verify.
trustDevicebooleanIf true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.
Passkey
A passkey of the account, such as a security key, can take the second step. Enable it on the passkey plugin with passkey({ secondFactor: true }); the methods a sign in is answered with then include "passkey" for accounts that have one, and authClient.passkey.verifySecondFactor() takes the step. For an account whose only second step is a passkey, twoFactor.enable({ method: "passkey" }) starts the setup and answers backup codes, and using the passkey while signed in turns two-factor on. See the passkey plugin.
The sign-in answer also carries twoFactorBackupCodes: whether the account holds backup codes, which an account with only a sent code does not.
Backup Codes
Backup codes are generated and stored in the database. This can be used to recover access to the account if the user loses access to their phone or email.
An authenticator app setup that was started and never finished is discarded, with its backup codes, when two-factor is turned on another way (a sent code). Its codes would otherwise pass the second step of an account whose owner never saw them through. While two-factor is off no setup is in use, so whatever row is left is discarded.
Starting a setup on an account that already has two-factor on leaves the backup codes the account has as they are, and does not answer them: enable then returns no backupCodes. A setup that is left unfinished takes nothing away, and codes that were saved once are not shown a second time. To replace them, including codes that were all used, generate new ones.
Two setups started at the same moment do not both stand. userId is unique in the twoFactor table (the index twoFactor_userId_unique), so an account holds one row, and the call whose secret is not the stored one answers SETUP_ALREADY_STARTED (409): nobody scans a secret or keeps codes that were overwritten; start again. A call that answers 409 has left nothing of its own stored. When new backup codes were asked for at the same moment, the setup stands and answers without backupCodes, since the stored ones were shown to whoever asked. Run the migration to add the constraint to a database created before it. It fails if an account already holds two rows; delete the extra ones first. Until then such a race can leave two rows, as before. The same answer comes from verifyTotp when the setup its code belongs to was replaced meanwhile.
Changes to one account's two-factor happen one at a time. Starting a setup, finishing one, turning two-factor off and generating backup codes each claim the account for the moment they take, since whether two-factor is on and the row that proves it are written by two statements. A second request of the same person that arrives meanwhile answers SECOND_FACTOR_CHANGE_IN_PROGRESS (409): it changed nothing and can be sent again. Signing in is not claimed. The claim is a member of the account's own row, twoFactorClaim, taken by a write guarded on what it held before. The database decides who has it in one statement, whatever ids it uses and whatever storage is configured beside it. This is a schema change: run the migration, or regenerate your schema, before deploying, since every change to two-factor writes the member and fails without it. Taking and releasing the claim are writes to the user row, so its updatedAt moves. A claim whose request died expires after 30 seconds, so a claim is held for a time, not for as long as its request lives. A write that is still on its way when its claim has run out, and after another request has made its own change, changes nothing: whether two-factor is on is written with the claim checked by the write itself, a write to the two-factor row is guarded on what it was decided on, and a passkey's removal is announced in the claim before it is made, so that the request that takes the account over removes the passkey before it counts any. A change that ran out of time, or whose write found the claim gone, answers SECOND_FACTOR_CHANGE_TIMED_OUT (409): unlike the other answer, part of it may have been written, and what is left is a state the next request handles (a setup that has to be started again, for one). The second step of a sign in is never told to try again.
An adapter without incrementOne and consumeOne gets the same from a look followed by a guarded updateMany or deleteMany. The requirement is that those are one conditional write each and report how many rows they changed, which is what a database does.
Whether two-factor is on is read from the database, not from the session, wherever a setup is started, finished or discarded. While it is off, a row is a setup that was not finished, whatever it says of itself: a setup whose last write failed is started over by enable, and is not reported as already enabled. A setup is finished once. A row that was proved and then left behind with two-factor off, by a write that failed or by turning two-factor off, is not turned on again with a code from its app: verifyTotp answers TOTP_NOT_ENABLED, and enable, which asks for the password, starts over.
Generating Backup Codes
Generate backup codes for account recovery:
const { data, error } = await authClient.twoFactor.generateBackupCodes({ password, // The users password (required for credential accounts).});if (data) { // Show the backup codes to the user}passwordstringThe users password (required for credential accounts).
When you generate backup codes, the old backup codes will be deleted and new ones will be generated. Two-factor has to be on, by what the database says: a setup that is still waiting keeps the codes it was started with.
Using Backup Codes
You can now allow users to provide a backup code as an account recovery method.
const { data, error } = await authClient.twoFactor.verifyBackupCode({ code: "123456", // required, A backup code to verify. disableSession: false, // If true, the session cookie will not be set. trustDevice: true, // If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.});codestringrequiredA backup code to verify.
disableSessionbooleanIf true, the session cookie will not be set.
trustDevicebooleanIf true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time.
Once a backup code is used, it will be removed from the database and can't be used again.
Viewing Backup Codes
To display the backup codes to the user, you can call viewBackupCodes on the server. This will return the backup codes in the response. You should only do this if the user has a fresh session - a session that was just created.
const data = await auth.api.viewBackupCodes({ body: { userId: "user-id", // required, The ID of the user whose backup codes to return. },});userIdstringrequiredThe ID of the user whose backup codes to return.
Listing the Account's Second Steps
A signed-in client can ask which second steps its account has set up. The answer is the list a sign-in held to the second step carries as twoFactorMethods, and it is empty while two-factor is off.
const { data } = await authClient.twoFactor.listMethods();
// { methods: ["totp", "passkey"] }Use it to offer only the steps the account can take, for example when a screen asks the person to prove it is them. Backup codes are not listed: an account with two-factor on has them.
Checking a Code While Signed In
verifyTotp, verifyOtp and verifyBackupCode also take a request from a session that is already signed in. For an account with 2FA on, a right code there is proof that the person is present now, so the session is renewed: it gets a new token and is fresh again, which lets the user through endpoints that ask for a fresh session without signing in again:
// "Is it you?" before a sensitive change, for an account with 2FA on
const { data, error } = await authClient.twoFactor.verifyTotp({ code });
// On success the session cookie carries the new token, and data.token is that token.A wrong code leaves the session as it was and counts toward the account's lockout, the same as a wrong code at sign-in.
It stays the same session under a new token: its id and expiry are kept, and what was issued in it, such as an OAuth access token from the OAuth provider or mcp, stays valid. The old token stops working, so a client that stores the token itself takes the new one from the answer.
Turning 2FA on or off renews the session the same way: enable when it turns 2FA on at once, the first code that finishes a setup, and disable answer with a new token for the same session. A databaseHooks.session.update.before hook that refuses the renewal leaves the session on its token; the change to 2FA stands.
Checking a code is the only way an account with 2FA on makes its session fresh again. The endpoints that renew one for a single factor, /renew-session (a password) and /email-otp/renew-session (an emailed code), refuse an account with 2FA on with SECOND_FACTOR_REQUIRED (403).
Trusted Devices
You can mark a device as trusted by passing trustDevice to verifyTotp or verifyOtp.
const verify2FA = async (code: string) => {
const { data, error } = await authClient.twoFactor.verifyTotp({
code,
trustDevice: true, // Mark this device as trusted
})
if (data) {
// 2FA verified and device trusted
}
}When trustDevice is set to true, the current device will be remembered for 30 days. During this period, the user won't be prompted for 2FA on subsequent sign-ins from this device. The trust period is refreshed each time the user signs in successfully.
Issuer
By adding an issuer you can set your application name for the 2fa application.
For example, if your user uses Google Auth, the default appName will show up as Entro Auth. However, by using the following code, it will show up as my-app-name.
twoFactor({
issuer: "my-app-name"
})Schema
The plugin requires 1 additional field in the user table and 1 additional table to store the two factor authentication data.
Table: user
Table: twoFactor
The user table also gets twoFactorClaim, an optional string that is empty except while a request is changing the account's two-factor. It is not returned with the user and cannot be set through the API.
Options
Server
twoFactorTable: The name of the table that stores the two factor authentication data. Default: twoFactor.
issuer: Custom issuer name for the TOTP URI. Defaults to your appName.
skipVerificationOnEnable: Activate TOTP immediately without verifying an enrollment code. Defaults to false.
allowPasswordless: Allow enabling and managing 2FA without a password for users that do not have a credential account. Password is still required if a credential account exists. Without a password, enabling, disabling, reading the TOTP URI and generating backup codes need a fresh session (session.freshAge). This option does not change which sign-in methods are challenged for 2FA.
enforceOn: Which ways of signing in a pending second step is required on: "all" (every method that ends in a session, see Sign In with 2FA) or "credentials" (password sign-in by email, username or phone number only). Defaults to "all".
Issuer: The issuer is the name of your application. It's used to generate TOTP codes. It'll be displayed in the authenticator apps.
TOTP options
these are options for TOTP.
Prop
Type
OTP options
these are options for OTP.
Prop
Type
Backup Code Options
backup codes are generated and stored in the database when the user enabled two factor authentication. This can be used to recover access to the account if the user loses access to their phone or email.
Prop
Type
Account lockout
After repeated failed verifications during sign-in, the account is temporarily locked. The limit applies per account across sign-in challenges and across factors: TOTP, OTP, and backup codes share one counter, and a successful verification resets it. Locked attempts return 429 with the ACCOUNT_TEMPORARILY_LOCKED error code. Enabled by default.
Prop
Type
Client
To use the two factor plugin in the client, you need to add it on your plugins list.
import { createAuthClient } from "@entro314labs/entro-auth/client"
import { twoFactorClient } from "@entro314labs/entro-auth/client/plugins"
const authClient = createAuthClient({
plugins: [
twoFactorClient({
onTwoFactorRedirect({ twoFactorMethods }){
// twoFactorMethods is e.g. ["totp", "otp"]
window.location.href = "/2fa" // Handle the 2FA verification redirect
}
})
]
})Options
onTwoFactorRedirect: A callback that will be called when the user needs to verify their 2FA code. Receives a context object with twoFactorMethods — an array of enabled 2FA methods (e.g. ["totp", "otp"]). This can be used to redirect the user to the appropriate 2FA page.