Nov 23, 202611 min read

Add TOTP Two-Factor Authentication to a Backend

How TOTP codes work under RFC 6238, generating and storing secrets, the otpauth URI for authenticator apps, verifying with a drift window, blocking code replay, recovery codes, rate limits on guesses, and a two-factor service with encrypted secrets in Postgres built with Encore.

Illustration for Add TOTP Two-Factor Authentication to a Backend

Password logins get a second factor eventually, often after the first credential stuffing incident, and TOTP works with every authenticator app without SMS costs. The algorithm fits in fifty lines, and the bugs live around it, in plaintext secrets, replayable codes and unlimited guesses.

This guide builds TOTP in TypeScript with node:crypto, then the service around it.

How does a TOTP code work?

RFC 6238 defines TOTP as HOTP from RFC 4226 with a counter derived from time. The server and the app share a secret, both divide the Unix time by 30 to get the current step, compute an HMAC-SHA1 of that step and keep six digits of it through a step called dynamic truncation. Both sides compute the same value independently, so the server needs no connection to the phone, only the secret and a clock.

ParameterCommon valueNotes
Secret20 random bytes, base32 encodedRFC 4226 recommends 160 bits
AlgorithmHMAC-SHA1SHA-256 is allowed by the RFC, but many apps ignore it
Digits68 is allowed, again with uneven app support
Period30 secondsMost apps assume 30

Sticking to SHA1, six digits and 30 seconds is the safe choice. HMAC-SHA1 is not affected by the collision attacks on SHA-1, and changing the parameters mostly produces codes that some users' apps silently get wrong.

What does the implementation look like?

Base32 encoding, HOTP and verification with a drift window, using only node:crypto:

// mfa/totp.ts import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; export function base32Encode(buf: Buffer): string { let bits = 0; let value = 0; let out = ""; for (const byte of buf) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { out += ALPHABET[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31]; return out; } export function base32Decode(s: string): Buffer { let bits = 0; let value = 0; const out: number[] = []; for (const ch of s.replace(/=+$/, "").toUpperCase()) { const idx = ALPHABET.indexOf(ch); if (idx === -1) throw new Error("invalid base32"); value = (value << 5) | idx; bits += 5; if (bits >= 8) { out.push((value >>> (bits - 8)) & 255); bits -= 8; } } return Buffer.from(out); } export function newSecret(): string { return base32Encode(randomBytes(20)); // 160 bits, as RFC 4226 recommends } // HOTP from RFC 4226: HMAC-SHA1 over the 8-byte counter, then dynamic truncation. export function hotp(secret: Buffer, counter: number, digits = 6): string { const msg = Buffer.alloc(8); msg.writeBigUInt64BE(BigInt(counter)); const mac = createHmac("sha1", secret).update(msg).digest(); const offset = mac[mac.length - 1] & 0x0f; const bin = (mac.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits; return bin.toString().padStart(digits, "0"); } export const STEP_SECONDS = 30; export function currentStep(nowMs = Date.now()): number { return Math.floor(nowMs / 1000 / STEP_SECONDS); } // Returns the matching time step within one step of drift, or null. export function verify(secretB32: string, code: string, nowMs = Date.now()): number | null { if (!/^\d{6}$/.test(code)) return null; const secret = base32Decode(secretB32); const now = currentStep(nowMs); for (const step of [now - 1, now, now + 1]) { const expected = Buffer.from(hotp(secret, step)); if (timingSafeEqual(expected, Buffer.from(code))) return step; } return null; } export function otpauthURI(secretB32: string, account: string, issuer: string): string { const label = encodeURIComponent(`${issuer}:${account}`); const params = new URLSearchParams({ secret: secretB32, issuer, algorithm: "SHA1", digits: "6", period: "30" }); return `otpauth://totp/${label}?${params.toString()}`; }

verify returns the time step that matched instead of true, which the replay check below needs. The comparison uses timingSafeEqual so response timing does not reveal how many digits were right. Check these functions against the SHA1 test vectors in RFC 6238 and RFC 4226 in your own test suite, since a wrong byte order in the counter produces codes that look plausible and never match.

How does the user enroll?

Enrollment generates a secret, shows it as a QR code of an otpauth:// URI and asks the user to type the first code before 2FA is switched on. The URI format comes from Google Authenticator's key URI spec, which other apps follow. Confirming with a first code proves the app has the secret and the clocks agree, so a user who scanned the wrong QR code is not locked out on their next login.

The secret has to be stored encrypted rather than hashed like a password, since the server must compute codes from it, so the protection is an encryption key that lives outside the database.

How do you stop replay and brute force?

A code is valid for up to 90 seconds with a one-step window, and someone who watches a user type it, or a phishing page that relays it, can use it again in that time. Recording the last accepted step per user and rejecting anything equal or older makes each code single use. The check and the update have to be one statement, or two parallel logins with the same code both pass.

Six digits means one in a million per guess, and an attacker with unlimited attempts gets through in hours. Lock the factor after a handful of failures, such as five in a row, for a few minutes, and alert on repeated lockouts. OWASP's MFA cheat sheet covers the surrounding flows, including resets.

What about recovery codes?

Users lose phones, and a 2FA setup without recovery turns that into a support ticket where someone has to verify identity by hand. Generate about ten random single-use codes when 2FA is confirmed, show them once, and store only their hashes. They are random with enough entropy that a fast hash such as SHA-256 is fine, unlike passwords, which need a slow one.

How do you build the two-factor service with Encore?

Encore

Encore is a backend framework with built-in infrastructure, so the two-factor service declares its Postgres database and its encryption key as a secret in the same code as the endpoints. The endpoints below are internal, called by the account service after it has checked the password, so the user ID comes from code you control rather than from the request body.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create accounts --example=ts/hello-world$ cd accounts && mkdir -p mfa/migrations

Declare the service:

// mfa/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("mfa");

Store the encrypted secret and the last used time step per user:

-- mfa/migrations/1_totp.up.sql CREATE TABLE totp_factors ( user_id TEXT PRIMARY KEY, secret_enc BYTEA NOT NULL, confirmed_at TIMESTAMPTZ, last_step BIGINT, failed_attempts INT NOT NULL DEFAULT 0, locked_until TIMESTAMPTZ ); CREATE TABLE recovery_codes ( user_id TEXT NOT NULL REFERENCES totp_factors (user_id) ON DELETE CASCADE, code_hash TEXT NOT NULL, used_at TIMESTAMPTZ, PRIMARY KEY (user_id, code_hash) );

The secret is encrypted with AES-256-GCM under a key from an Encore secret, with a fresh nonce per secret and the user ID bound in as additional data, so a ciphertext copied to another user's row fails to decrypt:

// mfa/crypto.ts import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; import { secret } from "encore.dev/config"; const encryptionKey = secret("TOTPEncryptionKey"); // 32 random bytes, base64 function key(): Buffer { const k = Buffer.from(encryptionKey(), "base64"); if (k.length !== 32) throw new Error("TOTPEncryptionKey must be 32 bytes"); return k; } export function seal(plaintext: string, userID: string): Buffer { const iv = randomBytes(12); const cipher = createCipheriv("aes-256-gcm", key(), iv); cipher.setAAD(Buffer.from(userID)); const body = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), body]); } export function open(sealed: Buffer, userID: string): string { const decipher = createDecipheriv("aes-256-gcm", key(), sealed.subarray(0, 12)); decipher.setAAD(Buffer.from(userID)); decipher.setAuthTag(sealed.subarray(12, 28)); return Buffer.concat([decipher.update(sealed.subarray(28)), decipher.final()]).toString("utf8"); }

The endpoints enroll a user, confirm the first code and return recovery codes, and verify a code at login with the lockout and replay check in one UPDATE:

// mfa/mfa.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { createHash, randomBytes } from "node:crypto"; import { newSecret, otpauthURI, verify } from "./totp"; import { open, seal } from "./crypto"; const db = new SQLDatabase("mfa", { migrations: "./migrations" }); const MAX_FAILURES = 5; const hashCode = (code: string) => createHash("sha256").update(code).digest("hex"); export const enroll = api( { expose: false, method: "POST", path: "/mfa/enroll" }, async (p: { userID: string; email: string }): Promise<{ otpauthURI: string; secret: string }> => { const secret = newSecret(); const row = await db.queryRow` INSERT INTO totp_factors (user_id, secret_enc) VALUES (${p.userID}, ${seal(secret, p.userID)}) ON CONFLICT (user_id) DO UPDATE SET secret_enc = EXCLUDED.secret_enc, last_step = NULL WHERE totp_factors.confirmed_at IS NULL RETURNING user_id `; if (!row) throw APIError.alreadyExists("two-factor authentication is already enabled"); return { otpauthURI: otpauthURI(secret, p.email, "Acme"), secret }; }, ); async function check(userID: string, code: string, requireConfirmed: boolean): Promise<boolean> { const f = await db.queryRow<{ secret_enc: Buffer; confirmed_at: Date | null; locked: boolean }>` SELECT secret_enc, confirmed_at, COALESCE(locked_until > now(), false) AS locked FROM totp_factors WHERE user_id = ${userID} `; if (!f || (requireConfirmed && !f.confirmed_at)) throw APIError.failedPrecondition("no active factor"); if (f.locked) throw APIError.resourceExhausted("too many attempts, try again later"); const step = verify(open(f.secret_enc, userID), code); if (step !== null) { const ok = await db.queryRow` UPDATE totp_factors SET last_step = ${step}, failed_attempts = 0 WHERE user_id = ${userID} AND (last_step IS NULL OR last_step < ${step}) RETURNING user_id `; if (ok) return true; } await db.exec` UPDATE totp_factors SET failed_attempts = failed_attempts + 1, locked_until = CASE WHEN failed_attempts + 1 >= ${MAX_FAILURES} THEN now() + interval '5 minutes' ELSE locked_until END WHERE user_id = ${userID} `; return false; } export const confirm = api( { expose: false, method: "POST", path: "/mfa/confirm" }, async (p: { userID: string; code: string }): Promise<{ recoveryCodes: string[] }> => { if (!(await check(p.userID, p.code, false))) throw APIError.invalidArgument("invalid code"); const codes = Array.from({ length: 10 }, () => randomBytes(10).toString("hex")); // 80 bits each await using tx = await db.begin(); await tx.exec`UPDATE totp_factors SET confirmed_at = now() WHERE user_id = ${p.userID}`; await tx.exec`DELETE FROM recovery_codes WHERE user_id = ${p.userID}`; for (const c of codes) { await tx.exec`INSERT INTO recovery_codes (user_id, code_hash) VALUES (${p.userID}, ${hashCode(c)})`; } await tx.commit(); return { recoveryCodes: codes }; }, ); export const verifyCode = api( { expose: false, method: "POST", path: "/mfa/verify" }, async (p: { userID: string; code: string }): Promise<{ ok: boolean }> => { if (/^[0-9a-f]{20}$/.test(p.code)) { // Recovery codes share the factor's lockout, so their guesses count too. const f = await db.queryRow<{ locked: boolean }>` SELECT COALESCE(locked_until > now(), false) AS locked FROM totp_factors WHERE user_id = ${p.userID} `; if (f?.locked) throw APIError.resourceExhausted("too many attempts, try again later"); const used = await db.queryRow` UPDATE recovery_codes SET used_at = now() WHERE user_id = ${p.userID} AND code_hash = ${hashCode(p.code)} AND used_at IS NULL RETURNING user_id `; if (used) { // A good recovery code starts a fresh attempt window. await db.exec`UPDATE totp_factors SET failed_attempts = 0, locked_until = NULL WHERE user_id = ${p.userID}`; } else { await db.exec` UPDATE totp_factors SET failed_attempts = failed_attempts + 1, locked_until = CASE WHEN failed_attempts + 1 >= ${MAX_FAILURES} THEN now() + interval '5 minutes' ELSE locked_until END WHERE user_id = ${p.userID} `; } return { ok: !!used }; } return { ok: await check(p.userID, p.code, true) }; }, );

Generate the encryption key and set it as a secret:

~/accounts
$ openssl rand -base64 32$ encore secret set --type dev,local TOTPEncryptionKey$ encore run

Paste the generated value when encore secret set prompts for it. encore run starts Postgres locally and applies the migration, and the local development dashboard can call the internal endpoints directly to walk through enroll, confirm and verify with an authenticator app. The encryption key is set per environment with encore secret set and is not stored in the repository, so a coding agent working in the code cannot read or leak it, and a database backup on its own does not expose any secret. On deploy to your own cloud, the database runs on RDS or Cloud SQL and the key comes from the cloud's secret store. The account service calls these endpoints as typed functions through service-to-service calls.

An agent asked to add WebAuthn as a second factor type can add a table and endpoints to the same service and test them locally next to the TOTP flow, without access to the key that protects existing secrets.

Best fit: Apps adding a second factor to password logins that want secrets encrypted with a key outside the database, single-use codes and lockouts in one service.

TOTP checklist

  • Use 160-bit random secrets with SHA1, six digits and 30-second steps.
  • Encrypt secrets with a key kept outside the database.
  • Require a confirmed first code before turning 2FA on.
  • Accept one step of drift and reject replayed steps in one conditional update.
  • Lock the factor after a few failures.
  • Issue hashed single-use recovery codes and show them once.
  • Test against the RFC 6238 vectors.

Frequently asked questions

How does TOTP two-factor authentication work?

The server and the authenticator app share a secret, and both compute an HMAC-SHA1 of the current 30-second time step with that secret and truncate it to a 6-digit code, as RFC 6238 defines, so the server can check the code the user types without any network call to the app.

How should I store TOTP secrets in the database?

Encrypt them, for example with AES-256-GCM and a key kept in a secret manager, since the server needs the plaintext secret to compute codes and cannot hash it like a password. A leaked database without the key then does not let an attacker generate valid codes.

How do I prevent TOTP code replay?

Store the last time step that was accepted for each user and reject any code whose step is equal or older. Do the check and the update in one conditional UPDATE so two requests with the same code cannot both succeed.

How many TOTP codes should a server accept for clock drift?

Accept the current step plus one step before and after, which covers about 30 seconds of drift either way. RFC 6238 recommends allowing at most one step of network delay, and wider windows mostly help attackers guess.

Where should an Encore service keep the TOTP encryption key?

Declare it as a secret in the service, so Encore stores the value outside the repository, injects it at runtime, and provisions an IAM role for the service, or a service account on GCP. The TOTP secrets in the database stay encrypted with that key.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders