Turn on the second factor
For: an app developer whose users want a second step after the password, the magic link, or social.
What it does: a sign-in or a reset of a user with the factor on answers a challenge. The session opens only with a method of the challenge.
Before you start
Section titled “Before you start”- Sign in with a password works in your app. The enable of each method proves the password.
- Users with a verified address. The enable refuses an unverified user. The claim rule tells what verifies an address.
- For the passkey method, Sign in with a passkey works in your app.
- Keep
totpon. It is on by default whenpasswordis set.totp: falseturns it off. With nopassword, settotp: {}: the setup then takes an email code. - Set
totp.issuerto the name that the authenticator app shows.createAuthrefuses a colon in the issuer.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
export function createSecondFactorAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, // The enable of each method proves the password, so the factor needs `password`. password: {}, totp: { // The name that the authenticator app shows. 1 to 80 characters, no colon. issuer: "Example", // The backup codes that the first method answers, 5 to 20. The default is 10. backupCodes: 10, // The days that a trusted device skips the factor, 1 to 365. The default is 30. trustDays: 30, // The gate on the other sign-in methods. Each is on by default: a method // with no gate lets the holder of a mailbox past the factor. gate: { magicLink: true, emailOtp: true, social: true }, }, });}- On a settings page, ask for the password.
- For TOTP, send the password with
client.totp.setup({ password }). Show theurias a QR code. For a user with no password, callclient.reauth.requestEmailCode(), ask for the mailed code, and callclient.totp.setup({ emailCode }). - Call
client.totp.enable({ code })with a current code from the authenticator app, within 15 minutes. - For a passkey, call
client.secondFactor.passkey.enable({ password }). The browser asks for a passkey of the user. - For an email code, call
client.secondFactor.email.enable({ password }). - Show the backup codes once. The first method answers them, and no later call shows them again.
- On each sign-in form, read the answer. An answer with
twoFactorholds achallengeand itsmethods. - Pass the challenge with one method of
methods:totp: callclient.totp.verify({ challenge, code }).passkey: callclient.secondFactor.passkey.verify({ challenge }).email: callclient.secondFactor.email.send({ challenge }), thenclient.totp.verify({ challenge, emailCode }).backup: callclient.totp.verify({ challenge, backupCode }).
- For a trusted device, add
trustDevice: trueto the verify. - In a browser form flow, core sends the person to
/auth/totp/challengein place of steps 9 to 11.
import { base32Decode, totpCode } from "@authtempo/core/testing";import { describe, expect, it } from "vitest";import { call, type Harness, harness, linkIn, sessionCookieOf, signIn,} from "../support/harness.ts";import { createSecondFactorAuth } from "./second-factor.ts";
const PASSWORD = "correct horse battery";
/** A verified user with a password and the TOTP method on. Answers the cookie and the key. */async function enrolled(h: Harness, auth: ReturnType<typeof createSecondFactorAuth>) { // A verified user with a password: a magic link sign-in, then a first password. const ada = await signIn(auth, h, "ada@example.com"); await call(auth, "POST", "/auth/password/change", { newPassword: PASSWORD }, { cookie: ada }); const setup = await call( auth, "POST", "/auth/totp/setup", { password: PASSWORD }, { cookie: ada }, ); const { secret, uri, backupCodes } = (await setup.json()) as { secret: string; uri: string; backupCodes: string[]; }; const key = base32Decode(secret); const enable = await call( auth, "POST", "/auth/totp/enable", { code: await totpCode(key, new Date()) }, { cookie: ada }, ); // The email method: a code to the user's address, offered after a password sign-in only. await call( auth, "POST", "/auth/second-factor/email/enable", { password: PASSWORD }, { cookie: ada }, ); return { ada, key, uri, backupCodes, enable };}
describe("turn on the second factor", () => { it("sets up a factor, gates the password sign-in, and opens the session with a code", async () => { const h = harness(); const auth = createSecondFactorAuth(h); const { key, uri, backupCodes, enable } = await enrolled(h, auth); expect(uri.startsWith("otpauth://totp/")).toBe(true); expect(new URL(uri).searchParams.get("issuer")).toBe("Example"); expect(backupCodes.length).toBe(10); // A backup code holds 23 characters in groups: 113.9 bits, above the 112 of ASVS 5.0 6.5.2. expect(backupCodes[0]?.replaceAll("-", "").length).toBe(23); expect(((await enable.json()) as { enabled: boolean }).enabled).toBe(true);
const signInAnswer = await call(auth, "POST", "/auth/password/sign-in", { email: "ada@example.com", password: PASSWORD, }); const { twoFactor } = (await signInAnswer.json()) as { twoFactor: { challenge: string; methods: string[] }; }; expect(twoFactor.challenge.startsWith("tf_")).toBe(true); expect(twoFactor.methods).toEqual(["totp", "email", "backup"]); // A code passes once: the enable spent the code of this step, so use the next step's code. const next = await totpCode(key, new Date(Date.now() + 30_000)); const verify = await call(auth, "POST", "/auth/totp/verify", { challenge: twoFactor.challenge, code: next, }); expect(((await verify.json()) as { token: string }).token.startsWith("ts_")).toBe(true); });
it("asks a magic link and a reset for the factor, and the reset still sets the password", async () => { const h = harness(); const auth = createSecondFactorAuth(h); const { ada } = await enrolled(h, auth);
await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com" }); const token = linkIn(h, "ada@example.com").searchParams.get("token") ?? ""; const link = await call(auth, "POST", "/auth/magic-link/verify", { token }); expect(sessionCookieOf(link)).toBe(""); // The mailbox proved the address, so the email method is not offered. expect(((await link.json()) as { twoFactor: { methods: string[] } }).twoFactor.methods).toEqual( ["totp", "backup"], );
await call(auth, "POST", "/auth/password/reset/request", { email: "ada@example.com" }); const resetToken = linkIn(h, "ada@example.com").searchParams.get("token") ?? ""; const reset = await call(auth, "POST", "/auth/password/reset", { token: resetToken, password: "a brand new long password", }); expect(reset.status).toBe(200); expect(sessionCookieOf(reset)).toBe(""); expect( ((await reset.json()) as { twoFactor: { challenge: string } }).twoFactor.challenge, ).toMatch(/^tf_/); // The reset ended the old session, and the new password is the one that signs in. expect((await call(auth, "GET", "/auth/session", undefined, { cookie: ada })).status).toBe(401); const again = await call(auth, "POST", "/auth/password/sign-in", { email: "ada@example.com", password: "a brand new long password", }); expect("twoFactor" in ((await again.json()) as object)).toBe(true); });});How it behaves
Section titled “How it behaves”- Five routes answer a challenge with no cookie for a user with the factor on.
- They are the password sign-in, the magic link, the email code sign-in, social, and the reset.
- A reset still sets the new password and ends every session. Then the person passes the challenge.
- A passkey sign-in has no gate. A passkey is a factor of its own.
totp.gate.magicLink,totp.gate.emailOtp,totp.gate.social, andtotp.gate.phoneturn one gate off. Each is on by default.- The
emailmethod appears only after a password sign-in. After a magic link, the mailbox was the first factor. - The TOTP code is RFC 6238: SHA-1, 6 digits, 30 seconds, one step before and after now. A code passes once.
- A backup code has 23 characters in groups. It holds 113.9 bits, above the 112 bits of ASVS 5.0 6.5.2.
- The first method ends every other session of the user, and deletes the user’s trusted devices and challenges.
- A challenge lives 5 minutes and takes 5 wrong codes. An email code lives with its challenge.
- A trusted device skips the factor for
totp.trustDays. Its cookie istempo_totp_truston the path/auth/. - The code checks share two limits:
totp-code:user:<userId>10 per 15 minutes, andtotp-code:user-day:<userId>30 per 24 hours. - The email sends have the limits
second-factor-email:user:<userId>5 per 15 minutes,totp:email-day:<email>20 per 24 hours, and 3 sends per challenge. - The passkey and the email method turn off with the password and a fresh session. TOTP turns off only with a code.
- The factor on and off need a fresh session. New backup codes need one too. A stale one answers
session_not_fresh. - Wrap these calls in
client.withFresh. A stale session counts no try on the code limits. api.totp.disableWithCodeandapi.totp.regenerateBackupCodesWithCodetake a user, so they apply no fresh rule. Callapi.session.requireFreshfirst.- No per-account lockout exists. The threat model gives the odds.
If it fails
Section titled “If it fails”invalid_credentials: the password of an enable is wrong. Core writes no row.email_unverified: the user must prove the address first.invalid_code: the code is wrong, or it passed once already.invalid_body: a verify, a send, or the passkey options used a method that the challenge does not offer.passkey_failed: the assertion is not by a passkey of the user.too_many_attempts: the challenge took its fifth wrong code. Sign in again.invalid_token: the challenge is unknown, spent, or older than 5 minutes.totp_enabledandtotp_not_enabled: TOTP is already on, or the method is off, or the TOTP setup is older than 15 minutes: set up again.second_factor_last_method: the passkey is the last passkey of the user, and the passkey method is on.rate_limited: a limit of the code checks or of the sends is full.conflict: two writes to the factor ran at the same time. Retry.session_not_fresh: the session is older than the fresh window. Re-authenticate, then send it again.