From e63319413e09100e8dbc69402300c06a5ba94b04 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:46:08 +0000 Subject: [PATCH 1/4] fix(auth): a TOTP code is accepted once; a later presentation gets the wrong-code answer A TOTP code the two-factor plugin accepts is remembered for its user and secret for as long as the verifier's window could accept it, and any later presentation at /two-factor/verify-totp is refused, on another challenge, from another client and on the session lane (RFC 6238 section 5.2). A code from a step at or before the last accepted step is refused too. The refusal is the answer, and the failure count, a wrong code gets. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/auth-manager-auth-instance.ts | 6 +- .../src/totp-code-single-use.test.ts | 382 ++++++++++++++++++ .../plugin-auth/src/totp-code-single-use.ts | 266 ++++++++++++ 3 files changed, 653 insertions(+), 1 deletion(-) create mode 100644 packages/plugins/plugin-auth/src/totp-code-single-use.test.ts create mode 100644 packages/plugins/plugin-auth/src/totp-code-single-use.ts diff --git a/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts b/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts index 5d25f2a4ea6..e33d71ac488 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts @@ -80,6 +80,7 @@ import { createBetterAuthLogSink } from './sso-oidc-refusal-cause.js'; import { withSystemReadContext } from './objectql-adapter.js'; import { refuseSsoAccountOutsideProvenDomain, refuseSsoAccountWithoutAddress } from './sso-account-at-proven-domain.js'; import { refuseSamlAccountKeyContradiction } from './sso-saml-account-key.js'; +import { acceptEachTotpCodeOnce } from './totp-code-single-use.js'; /** The path better-auth declares for the email sign-up endpoint. */ const SIGN_UP_EMAIL_PATH = '/sign-up/email'; @@ -196,7 +197,10 @@ export interface AuthInstanceHost { export async function createAuthInstance(this: AuthInstanceHost): Promise> { const { betterAuth } = await import('better-auth'); const { createAuthMiddleware, setShouldSkipSessionRefresh } = await import('better-auth/api'); - const plugins = await this.buildPluginList(); + // A TOTP code the two-factor plugin accepts is accepted once (RFC 6238 + // §5.2): a before-hook on its `/two-factor/verify-totp`, appended to the + // plugin object in place. See `totp-code-single-use.ts`. + const plugins = await acceptEachTotpCodeOnce(await this.buildPluginList()); // ADR-0069 D2: the verifier refuses a locked account by better-auth's own // wrong-password path; the WebContainer hasher, when there is one, is the // pair it wraps (`sign-in-lockout-refusal.ts`). diff --git a/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts b/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts new file mode 100644 index 00000000000..ba71d41741d --- /dev/null +++ b/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts @@ -0,0 +1,382 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// The rule under test: a TOTP code the two-factor plugin accepts is accepted +// once. Any later presentation of it is refused, on another sign-in challenge, +// from another client and on the session lane; so is a code from a time step at +// or before the last accepted one; and the refusal is the answer a wrong code +// gets. A code from a later step is accepted. +// +// Real stack throughout: `AuthManager` over `ObjectQL` + `@objectstack/driver-sql` +// on better-sqlite3 `:memory:`, requests in as `Request` objects through +// `AuthManager.handleRequest`, the secret the vendor handed out in its otpauth:// +// URI, and the codes computed here from that secret by an RFC 6238 generator of +// this file's own. A real store is the point: the single use rests on the +// store refusing a second row under one primary key. +// +// The clock is pinned (`Date` only; timers stay real) one second into a time +// step, and moved a whole step forward where a case needs a later step, so no +// case depends on where in a 30-second step it happens to run. + +import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest'; +import { createHmac } from 'node:crypto'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AuthManager } from './auth-manager.js'; +import { authIdentityObjects } from './manifest.js'; +import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; +import { + NEVER_ACCEPTED_TOTP_CODE, + TOTP_ACCEPTANCE_WINDOW, + TOTP_VERIFY_PATH, + TWO_FACTOR_PLUGIN_ID, + acceptEachTotpCodeOnce, + hotp, + matchedTotpStep, + spentTotpStepIdentifier, +} from './totp-code-single-use.js'; +// Vendor modules paid at module load, never inside a clocked case. +import 'better-auth'; +import 'better-auth/api'; +import 'better-auth/crypto'; +import 'better-auth/plugins'; +import 'better-auth/plugins/bearer'; +import 'better-auth/plugins/two-factor'; +import '@better-auth/core/context'; + +const SECRET = 'test-secret-at-least-32-chars-long-totp-once'; +const PASSWORD = 'S3cure!Passw0rd-totp-once'; +const ORIGIN = 'http://localhost:3000'; +const BASE = `${ORIGIN}/api/v1/auth`; +const EMAIL = 'totp-once@example.com'; +const PERIOD_MS = 30_000; + +// ── RFC 6238 TOTP (the vendor defaults: SHA-1, 6 digits, 30 s) ──────────── +function base32Decode(input: string): Buffer { + const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + let bits = 0; + let value = 0; + const out: number[] = []; + for (const char of input.replace(/=+$/, '').toUpperCase()) { + const idx = ALPHABET.indexOf(char); + if (idx === -1) throw new Error(`invalid base32 character: ${char}`); + value = (value << 5) | idx; + bits += 5; + if (bits >= 8) { + out.push((value >>> (bits - 8)) & 0xff); + bits -= 8; + } + } + return Buffer.from(out); +} + +/** The 6-digit TOTP of `secret` for time step `step`. */ +function totpAt(secret: Buffer, step: number): string { + const buf = Buffer.alloc(8); + buf.writeBigUInt64BE(BigInt(step)); + const digest = createHmac('sha1', secret).update(buf).digest(); + const offset = digest[digest.length - 1] & 0x0f; + const code = + ((digest[offset] & 0x7f) << 24) | + ((digest[offset + 1] & 0xff) << 16) | + ((digest[offset + 2] & 0xff) << 8) | + (digest[offset + 3] & 0xff); + return String(code % 1_000_000).padStart(6, '0'); +} + +/** A 6-digit code equal to no code of `secret` in the steps around `step`. */ +function wrongCodeAt(secret: Buffer, step: number): string { + const live = new Set([-2, -1, 0, 1, 2].map((d) => totpAt(secret, step + d))); + for (let n = 0; ; n++) { + const candidate = String(n).padStart(6, '0'); + if (!live.has(candidate)) return candidate; + } +} + +// ── The clock ───────────────────────────────────────────────────────────── +/** A time step comfortably in the future of the real clock, so no real step boundary is near. */ +const FIRST_STEP = Math.floor(Date.now() / PERIOD_MS) + 10; +/** Move the clock to one second into time step `step`. */ +const atStep = (step: number) => vi.setSystemTime(step * PERIOD_MS + 1_000); + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'], shouldAdvanceTime: true }); + atStep(FIRST_STEP); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +const scrypt = memoizeScrypt(); +afterAll(scrypt.restore); + +const engines: ObjectQL[] = []; +afterAll(async () => { + while (engines.length) { + try { + await engines.pop()!.destroy(); + } catch { + /* noop */ + } + } +}); + +// ── The arrangement ─────────────────────────────────────────────────────── +const cookieHeader = (res: Response): string => + (res.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).join('; '); + +/** Whether the response installs a session cookie with a value. */ +const setsSession = (res: Response): boolean => + (res.headers.getSetCookie?.() ?? []).some((c) => /session_token=[^;]+/.test(c.split(';')[0])); + +/** + * A user with TOTP enrolled and confirmed on the session lane with the code of + * {@link FIRST_STEP}, on a fresh real store. + */ +const arrangeEnrolled = async () => { + const engine = new ObjectQL(); + engines.push(engine); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + for (const object of authIdentityObjects) engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); + await engine.syncSchemas(); + + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine, + plugins: { twoFactor: true }, + } as any); + + const post = (path: string, body: unknown, headers: Record = {}) => + manager.handleRequest( + new Request(`${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body ?? {}), + }), + ); + + /** Rows of `object` as the SQL driver stores them, below every read mask. */ + const rows = async (object: string): Promise[]> => { + const driver = ( + engine as unknown as { getDriver(o: string): { find(o: string, q: unknown): Promise } } + ).getDriver(object); + const found = await driver.find(object, { where: {} }); + return (Array.isArray(found) ? found : [found]).filter(Boolean) as Record[]; + }; + + const signedUp = await post('/sign-up/email', { email: EMAIL, password: PASSWORD, name: 'Totp Once' }); + expect(signedUp.status, `sign-up/email: ${await signedUp.clone().text()}`).toBe(200); + const signUpCookie = cookieHeader(signedUp); + const userId = String((await rows('sys_user')).find((r) => r.email === EMAIL)?.id); + + const enabled = await post('/two-factor/enable', { password: PASSWORD }, { cookie: signUpCookie }); + expect(enabled.status, `two-factor/enable: ${await enabled.clone().text()}`).toBe(200); + const { totpURI } = (await enabled.json()) as { totpURI: string }; + const secret = base32Decode(String(new URL(totpURI.replace('otpauth://', 'https://')).searchParams.get('secret'))); + + const confirmed = await post(TOTP_VERIFY_PATH, { code: totpAt(secret, FIRST_STEP) }, { cookie: signUpCookie }); + expect(confirmed.status, `verify-totp (enrolment): ${await confirmed.clone().text()}`).toBe(200); + const sessionCookie = cookieHeader(confirmed); + + /** A password sign-in that stops at the two-factor challenge; its cookie is the challenge. */ + const challenge = async (): Promise => { + const res = await post('/sign-in/email', { email: EMAIL, password: PASSWORD }); + expect(res.status, `sign-in/email: ${await res.clone().text()}`).toBe(200); + expect(((await res.clone().json()) as { twoFactorRedirect?: boolean }).twoFactorRedirect).toBe(true); + return cookieHeader(res); + }; + + const verify = (cookie: string, code: string) => post(TOTP_VERIFY_PATH, { code }, { cookie }); + + const sessionCount = async () => (await rows('sys_session')).filter((r) => String(r.user_id) === userId).length; + + const failedVerificationCount = async () => + Number((await rows('sys_two_factor')).find((r) => String(r.user_id) === userId)?.failed_verification_count ?? 0); + + return { manager, post, rows, userId, secret, sessionCookie, challenge, verify, sessionCount, failedVerificationCount }; +}; + +/** The status and error body a refusal answers with. */ +const answerOf = async (res: Response) => ({ + status: res.status, + body: (await res.clone().json()) as { code?: string; message?: string }, +}); + +// ── At the door ─────────────────────────────────────────────────────────── +describe('a TOTP code is accepted once, at /two-factor/verify-totp', () => { + it('a code accepted at one sign-in challenge is refused at another client’s challenge', async () => { + const rig = await arrangeEnrolled(); + atStep(FIRST_STEP + 1); + const code = totpAt(rig.secret, FIRST_STEP + 1); + + const first = await rig.verify(await rig.challenge(), code); + expect(first.status, `first presentation: ${await first.clone().text()}`).toBe(200); + expect(setsSession(first)).toBe(true); + + const sessionsBefore = await rig.sessionCount(); + const second = await rig.verify(await rig.challenge(), code); + const answer = await answerOf(second); + expect(answer.status).toBe(401); + expect(answer.body.code).toBe('INVALID_CODE'); + expect(setsSession(second), 'a refused presentation installs no session').toBe(false); + expect(await rig.sessionCount(), 'a refused presentation mints no session row').toBe(sessionsBefore); + }); + + it('a code spent confirming the enrolment is refused at the sign-in challenge', async () => { + const rig = await arrangeEnrolled(); + + const res = await rig.verify(await rig.challenge(), totpAt(rig.secret, FIRST_STEP)); + const answer = await answerOf(res); + expect(answer.status).toBe(401); + expect(answer.body.code).toBe('INVALID_CODE'); + expect(setsSession(res)).toBe(false); + }); + + it('a code accepted on the session lane is refused on the session lane again', async () => { + const rig = await arrangeEnrolled(); + atStep(FIRST_STEP + 1); + const code = totpAt(rig.secret, FIRST_STEP + 1); + + const first = await rig.verify(rig.sessionCookie, code); + expect(first.status, `first presentation: ${await first.clone().text()}`).toBe(200); + + const second = await rig.verify(rig.sessionCookie, code); + const answer = await answerOf(second); + expect(answer.status).toBe(401); + expect(answer.body.code).toBe('INVALID_CODE'); + }); + + it('a code from a step before the last accepted step is refused', async () => { + const rig = await arrangeEnrolled(); + atStep(FIRST_STEP + 1); + + // The next step's code is inside the verifier's window and is accepted first. + const later = await rig.verify(await rig.challenge(), totpAt(rig.secret, FIRST_STEP + 2)); + expect(later.status, `later step: ${await later.clone().text()}`).toBe(200); + + // The current step's code was never presented, and its step is before the accepted one. + const earlier = await rig.verify(await rig.challenge(), totpAt(rig.secret, FIRST_STEP + 1)); + const answer = await answerOf(earlier); + expect(answer.status).toBe(401); + expect(answer.body.code).toBe('INVALID_CODE'); + expect(setsSession(earlier)).toBe(false); + }); + + it('a code from a later step is accepted, at the challenge that refused a spent code', async () => { + const rig = await arrangeEnrolled(); + atStep(FIRST_STEP + 1); + const spent = totpAt(rig.secret, FIRST_STEP + 1); + expect((await rig.verify(await rig.challenge(), spent)).status).toBe(200); + + const pending = await rig.challenge(); + expect((await rig.verify(pending, spent)).status).toBe(401); + + atStep(FIRST_STEP + 2); + const fresh = await rig.verify(pending, totpAt(rig.secret, FIRST_STEP + 2)); + expect(fresh.status, `fresh code: ${await fresh.clone().text()}`).toBe(200); + expect(setsSession(fresh)).toBe(true); + }); + + it('a spent code gets the answer, and the failure count, a wrong code gets', async () => { + const rig = await arrangeEnrolled(); + atStep(FIRST_STEP + 1); + const spent = totpAt(rig.secret, FIRST_STEP + 1); + expect((await rig.verify(await rig.challenge(), spent)).status).toBe(200); + + const countBefore = await rig.failedVerificationCount(); + const wrong = await answerOf(await rig.verify(await rig.challenge(), wrongCodeAt(rig.secret, FIRST_STEP + 1))); + const countAfterWrong = await rig.failedVerificationCount(); + const replayed = await answerOf(await rig.verify(await rig.challenge(), spent)); + const countAfterReplay = await rig.failedVerificationCount(); + + expect(replayed).toEqual(wrong); + expect(countAfterWrong).toBe(countBefore + 1); + expect(countAfterReplay).toBe(countAfterWrong + 1); + }); + + it('two presentations of one code that arrive together admit exactly one', async () => { + const rig = await arrangeEnrolled(); + atStep(FIRST_STEP + 1); + const code = totpAt(rig.secret, FIRST_STEP + 1); + const [a, b] = [await rig.challenge(), await rig.challenge()]; + + const statuses = (await Promise.all([rig.verify(a, code), rig.verify(b, code)])).map((r) => r.status); + expect(statuses.sort()).toEqual([200, 401]); + }); + + it('the vendor accepts no step outside the window whose steps are reserved', async () => { + // The reservation covers `current ± TOTP_ACCEPTANCE_WINDOW`. A vendor whose + // verifier accepted a wider window would accept codes this guard never + // records, so the window is pinned at the door. + const rig = await arrangeEnrolled(); + // Far enough past the enrolment that neither probe is a spent step. + const now = FIRST_STEP + 3; + atStep(now); + for (const step of [now - TOTP_ACCEPTANCE_WINDOW - 1, now + TOTP_ACCEPTANCE_WINDOW + 1]) { + const res = await rig.verify(await rig.challenge(), totpAt(rig.secret, step)); + expect(res.status, `step ${step - now} from now`).toBe(401); + } + }); +}); + +// ── The seams ───────────────────────────────────────────────────────────── +describe('a TOTP code is accepted once — the seams', () => { + it('HOTP equals the RFC 4226 Appendix D test values', () => { + const rfcSecret = '12345678901234567890'; + const expected = ['755224', '287082', '359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; + expect(expected.map((_, counter) => hotp(rfcSecret, counter, 6))).toEqual(expected); + }); + + it('the matched step is the newest step of the window whose code is presented', () => { + const secret = 'abcdefghijklmnopqrstuvwxyz012345'; + const current = 1_000; + for (const step of [current - 1, current, current + 1]) { + expect(matchedTotpStep(secret, hotp(secret, step, 6), { current, window: 1, digits: 6 })).toBe(step); + } + expect(matchedTotpStep(secret, hotp(secret, current + 2, 6), { current, window: 1, digits: 6 })).toBeUndefined(); + expect(matchedTotpStep(secret, NEVER_ACCEPTED_TOTP_CODE, { current, window: 1, digits: 6 })).toBeUndefined(); + }); + + it('a step is reserved per user and per secret', () => { + const a = spentTotpStepIdentifier('user_a', 'secret-one', 7); + expect(spentTotpStepIdentifier('user_a', 'secret-one', 7)).toBe(a); + expect(spentTotpStepIdentifier('user_b', 'secret-one', 7)).not.toBe(a); + expect(spentTotpStepIdentifier('user_a', 'secret-two', 7)).not.toBe(a); + expect(spentTotpStepIdentifier('user_a', 'secret-one', 8)).not.toBe(a); + expect(a).not.toContain('secret-one'); + }); + + it('the build refuses a two-factor plugin that serves no /two-factor/verify-totp', async () => { + const drifted = { id: TWO_FACTOR_PLUGIN_ID, endpoints: { verifyTOTP: { path: '/two-factor/verify-code' } } }; + await expect(acceptEachTotpCodeOnce([drifted])).rejects.toThrow(/serves no \/two-factor\/verify-totp endpoint/); + }); + + it('one before-hook is appended to the two-factor plugin, matched on the door, once', async () => { + const plugin: any = { id: TWO_FACTOR_PLUGIN_ID, endpoints: { verifyTOTP: { path: TOTP_VERIFY_PATH } }, hooks: { after: [] } }; + const other: any = { id: 'bearer', hooks: { before: [] } }; + const list = [other, plugin]; + expect(await acceptEachTotpCodeOnce(list)).toBe(list); + await acceptEachTotpCodeOnce(list); + expect(plugin.hooks.before).toHaveLength(1); + expect(plugin.hooks.after).toEqual([]); + expect(other.hooks.before).toEqual([]); + const [entry] = plugin.hooks.before; + expect(entry.matcher({ path: TOTP_VERIFY_PATH })).toBe(true); + expect(entry.matcher({ path: '/two-factor/verify-otp' })).toBe(false); + expect(entry.matcher({ path: '/two-factor/verify-backup-code' })).toBe(false); + }); + + it('a list with no two-factor plugin is handed back untouched', async () => { + const other: any = { id: 'bearer', hooks: { before: [] } }; + const list = [other]; + expect(await acceptEachTotpCodeOnce(list)).toBe(list); + expect(other.hooks.before).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-auth/src/totp-code-single-use.ts b/packages/plugins/plugin-auth/src/totp-code-single-use.ts new file mode 100644 index 00000000000..2ac3e87dbb0 --- /dev/null +++ b/packages/plugins/plugin-auth/src/totp-code-single-use.ts @@ -0,0 +1,266 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A TOTP code is accepted once. + * + * ## The rule + * + * A TOTP code the two-factor plugin accepts is remembered for its user, for as + * long as the verifier's window could still accept it, and every later + * presentation of it is refused: on another sign-in challenge, from another + * client, on another node, and on the session lane (RFC 6238 §5.2). A code + * whose time step is at or before the last step accepted for that user and + * secret is refused too. The refusal is the answer a wrong code gets. + * + * ## The door + * + * `/two-factor/verify-totp` is the one route that takes a TOTP code. It is the + * sign-in challenge (no session, the pending two-factor cookie), the enrolment + * confirmation (a session, an unconfirmed factor) and the session-lane check + * (a session, a confirmed factor). `/two-factor/enable`, `/two-factor/disable` + * and `/two-factor/get-totp-uri` take a password; `/two-factor/verify-otp` + * and `/two-factor/verify-backup-code` take codes that are not TOTP codes. The + * route ledger (`auth-route-ledger.ts`) pins the published route set, so a new + * code-taking route is a reviewed ledger change. + * + * ## How it is applied + * + * One before-hook, appended IN PLACE to the two-factor plugin object, matched + * on that path. Before the vendor verifies, it: + * + * 1. resolves the user the vendor will verify for, in the vendor's own order: + * the session first, then the pending challenge cookie's verification row; + * 2. finds the time step the presented code belongs to, inside the window the + * vendor's verifier accepts (the newest matching step wins); + * 3. reserves that step for the user and the secret in `sys_verification` + * through better-auth's own single-use reservation + * (`internalAdapter.reserveVerificationValue`), whose row id is derived + * from the identifier, so a second reservation of the same step fails at + * the store's primary key — across clients, processes and nodes, and for + * two presentations that arrive together; + * 4. reserves every earlier step of the window as well, so a code from a step + * at or before an accepted one finds its step already held. + * + * A step that is already held turns the request into a wrong-code request: the + * hook hands the vendor a code no generated TOTP equals, so the per-challenge + * attempt budget, the account lockout counter and the answer are exactly the + * ones a wrong code gets. A code that matches no step of the window is left to + * the vendor, which refuses it on its own. + * + * A reservation is keyed by the user AND a digest of the secret, because a + * code is a function of the secret and its step: a re-enrolled secret's codes + * are new codes, and its first code may share a step with the old secret's + * last one. A row lives one period past the last moment the vendor's window + * could accept its step, a margin for clocks that differ between nodes. + * + * A store failure while reserving fails the request (the error propagates): + * a code the store could not record as spent is not accepted. + * + * ## Fail closed on vendor drift + * + * {@link acceptEachTotpCodeOnce} throws when the two-factor plugin it is handed + * serves no `/two-factor/verify-totp` endpoint: a build that went ahead would + * accept TOTP codes at a door this hook does not match. The failure is the + * build's, at boot. + */ + +import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; + +/** The route that takes a TOTP code. */ +export const TOTP_VERIFY_PATH = '/two-factor/verify-totp'; + +/** The id better-auth's two-factor plugin declares. */ +export const TWO_FACTOR_PLUGIN_ID = 'two-factor'; + +/** + * The steps on either side of the current one the vendor's verifier accepts: + * `/two-factor/verify-totp` calls `createOTP(...).verify(code)` with no + * options, and `verifyTOTP` defaults `window` to 1 (`@better-auth/utils/otp`). + */ +export const TOTP_ACCEPTANCE_WINDOW = 1; + +/** + * The pending sign-in challenge cookie the vendor sets (`TWO_FACTOR_COOKIE_NAME` + * in better-auth's two-factor plugin, not exported by the package). The door + * pins in `totp-code-single-use.test.ts` drive the challenge lane, so a renamed + * cookie turns them red rather than leaving that lane unguarded. + */ +const TWO_FACTOR_CHALLENGE_COOKIE = 'two_factor'; + +/** The vendor's TOTP defaults (`totp2fa`: `digits || 6`, `period || 30`). */ +const DEFAULT_PERIOD_SECONDS = 30; +const DEFAULT_DIGITS = 6; + +/** + * A code no generated TOTP equals: every generated code has exactly `digits` + * digits, and the vendor's comparison refuses a length mismatch first. + */ +export const NEVER_ACCEPTED_TOTP_CODE = '-'; + +/** The identifier prefix of a spent-step reservation row in `sys_verification`. */ +export const SPENT_TOTP_STEP_IDENTIFIER_PREFIX = 'totp-step:'; + +/** A better-auth hook entry, as far as this module writes it. */ +interface HookEntry { + matcher: (context: any) => boolean; + handler: (...args: any[]) => unknown; +} + +/** A plugin object, as far as this module reads and extends it. */ +interface TwoFactorPluginShape { + id?: unknown; + endpoints?: Record; + hooks?: { before?: HookEntry[]; after?: HookEntry[]; [key: string]: unknown }; + [key: string]: unknown; +} + +/** RFC 4226 HOTP over the secret's UTF-8 bytes, as the vendor computes it. */ +export function hotp(secret: string, counter: number, digits: number): string { + const message = Buffer.alloc(8); + message.writeBigUInt64BE(BigInt(counter)); + const mac = createHmac('sha1', Buffer.from(secret, 'utf8')).update(message).digest(); + const offset = mac[mac.length - 1] & 0x0f; + const binary = + ((mac[offset] & 0x7f) << 24) | + ((mac[offset + 1] & 0xff) << 16) | + ((mac[offset + 2] & 0xff) << 8) | + (mac[offset + 3] & 0xff); + return String(binary % 10 ** digits).padStart(digits, '0'); +} + +/** + * The newest time step in `[current - window, current + window]` whose code + * equals `code`, or `undefined`. Every step of the window is compared, in + * constant time per comparison, whichever matches. + */ +export function matchedTotpStep( + secret: string, + code: string, + options: { current: number; window: number; digits: number }, +): number | undefined { + const presented = Buffer.from(code, 'utf8'); + let matched: number | undefined; + for (let step = options.current - options.window; step <= options.current + options.window; step++) { + const expected = Buffer.from(hotp(secret, step, options.digits), 'utf8'); + const equal = presented.length === expected.length && timingSafeEqual(presented, expected); + if (equal) matched = step; + } + return matched; +} + +/** + * The reservation identifier of one time step of one user's secret. The secret + * enters only as a truncated SHA-256 digest, so the row names which secret + * spent the step without carrying anything that verifies a code. + */ +export function spentTotpStepIdentifier(userId: string, secret: string, step: number): string { + const digest = createHash('sha256').update(`${SPENT_TOTP_STEP_IDENTIFIER_PREFIX}${secret}`).digest('base64url'); + return `${SPENT_TOTP_STEP_IDENTIFIER_PREFIX}${userId}:${digest.slice(0, 22)}:${step}`; +} + +/** The user the vendor will verify the code for, or `undefined` when it will refuse before verifying. */ +async function verifyingUserId(ctx: any): Promise { + const { getSessionFromCtx } = await import('better-auth/api'); + const session: any = await getSessionFromCtx(ctx).catch(() => null); + const sessionUserId = session?.user?.id; + if (typeof sessionUserId === 'string' && sessionUserId !== '') return sessionUserId; + + const cookieName = ctx.context.createAuthCookie(TWO_FACTOR_CHALLENGE_COOKIE).name; + const challenge = await ctx.getSignedCookie(cookieName, ctx.context.secret); + if (typeof challenge !== 'string' || challenge === '') return undefined; + const row: any = await ctx.context.internalAdapter.findVerificationValue(challenge); + const challengedUserId = row?.value; + return typeof challengedUserId === 'string' && challengedUserId !== '' ? challengedUserId : undefined; +} + +/** The plaintext TOTP secret enrolled for `userId`, or `undefined` when the vendor will refuse before verifying. */ +async function enrolledSecret(ctx: any, userId: string): Promise { + const row: any = await ctx.context.adapter.findOne({ + model: 'twoFactor', + where: [{ field: 'userId', value: userId }], + }); + if (typeof row?.secret !== 'string' || row.secret === '') return undefined; + const { symmetricDecrypt } = await import('better-auth/crypto'); + try { + return await symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret }); + } catch { + // The vendor decrypts the same column with the same key and fails the + // request the same way; it stays the owner of that answer. + return undefined; + } +} + +/** + * The before-hook body. Answers nothing when the code may go on to the vendor + * as presented, and `{ context: { body } }` carrying a code that never verifies + * when its step is already spent. + */ +export async function refuseSpentTotpStep(ctx: any): Promise<{ context: { body: Record } } | void> { + const code = ctx?.body?.code; + if (typeof code !== 'string' || code === '') return; + + const totpOptions = ctx.context.getPlugin?.(TWO_FACTOR_PLUGIN_ID)?.options?.totpOptions; + const period: number = totpOptions?.period || DEFAULT_PERIOD_SECONDS; + const digits: number = totpOptions?.digits || DEFAULT_DIGITS; + if (code.length !== digits) return; + + const userId = await verifyingUserId(ctx); + if (!userId) return; + const secret = await enrolledSecret(ctx, userId); + if (!secret) return; + + const window = TOTP_ACCEPTANCE_WINDOW; + const current = Math.floor(Date.now() / (period * 1000)); + const step = matchedTotpStep(secret, code, { current, window, digits }); + if (step === undefined) return; + + const reserve = (spent: number): Promise => + ctx.context.internalAdapter.reserveVerificationValue({ + identifier: spentTotpStepIdentifier(userId, secret, spent), + value: userId, + expiresAt: new Date((spent + window + 2) * period * 1000), + }); + + if (!(await reserve(step))) { + return { context: { body: { ...ctx.body, code: NEVER_ACCEPTED_TOTP_CODE } } }; + } + for (let earlier = current - window; earlier < step; earlier++) await reserve(earlier); +} + +/** Whether `endpoint` is served at the TOTP door. */ +function servesTotpDoor(endpoint: unknown): boolean { + return (endpoint as { path?: unknown } | null | undefined)?.path === TOTP_VERIFY_PATH; +} + +const extended = new WeakSet(); + +/** + * Make every TOTP code the two-factor plugin accepts single-use, in place on + * the plugin object in `plugins`, and hand the same list back. A list with no + * two-factor plugin is handed back untouched. + * + * @throws Error when the two-factor plugin serves no `/two-factor/verify-totp` + * endpoint: fail closed rather than build a TOTP door this hook does not match. + */ +export async function acceptEachTotpCodeOnce(plugins: T): Promise { + const target = plugins.find( + (plugin) => (plugin as TwoFactorPluginShape | null | undefined)?.id === TWO_FACTOR_PLUGIN_ID, + ) as TwoFactorPluginShape | undefined; + if (!target || extended.has(target)) return plugins; + if (!Object.values(target.endpoints ?? {}).some(servesTotpDoor)) { + throw new Error( + `[AuthManager] The two-factor plugin serves no ${TOTP_VERIFY_PATH} endpoint, so its TOTP codes ` + + 'cannot be made single-use where they are accepted. Refusing to build the auth instance: a TOTP ' + + 'code must be refused on any use after the first. Update totp-code-single-use.ts for the ' + + 'installed better-auth two-factor plugin.', + ); + } + const { createAuthMiddleware } = await import('better-auth/api'); + const entry: HookEntry = { + matcher: (context: any) => context?.path === TOTP_VERIFY_PATH, + handler: createAuthMiddleware(async (ctx: any) => refuseSpentTotpStep(ctx)), + }; + target.hooks = { ...target.hooks, before: [...(target.hooks?.before ?? []), entry] }; + extended.add(target); + return plugins; +} From dbdfc4dd0ef9f0528de22adab70fc8caa8a54004 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:47:08 +0000 Subject: [PATCH 2/4] fix(auth): a two-factor plugin that serves no route takes no TOTP code; the lockout dogfood signs in with a fresh step each time The build still refuses a two-factor plugin whose routes leave out /two-factor/verify-totp. The dogfood fixture gains freshTotp(), which hands out a code from a later step than the last one it handed out for the secret, because the server accepts a TOTP code once. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/totp-code-single-use.test.ts | 10 +++- .../plugin-auth/src/totp-code-single-use.ts | 21 +++++--- packages/qa/dogfood/test/totp.ts | 48 ++++++++++++++++++- .../test/two-factor-lockout.dogfood.test.ts | 26 +++++----- 4 files changed, 83 insertions(+), 22 deletions(-) diff --git a/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts b/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts index ba71d41741d..c41a3b8c013 100644 --- a/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts +++ b/packages/plugins/plugin-auth/src/totp-code-single-use.test.ts @@ -353,9 +353,9 @@ describe('a TOTP code is accepted once — the seams', () => { expect(a).not.toContain('secret-one'); }); - it('the build refuses a two-factor plugin that serves no /two-factor/verify-totp', async () => { + it('the build refuses a two-factor plugin whose routes do not include /two-factor/verify-totp', async () => { const drifted = { id: TWO_FACTOR_PLUGIN_ID, endpoints: { verifyTOTP: { path: '/two-factor/verify-code' } } }; - await expect(acceptEachTotpCodeOnce([drifted])).rejects.toThrow(/serves no \/two-factor\/verify-totp endpoint/); + await expect(acceptEachTotpCodeOnce([drifted])).rejects.toThrow(/none at \/two-factor\/verify-totp/); }); it('one before-hook is appended to the two-factor plugin, matched on the door, once', async () => { @@ -373,6 +373,12 @@ describe('a TOTP code is accepted once — the seams', () => { expect(entry.matcher({ path: '/two-factor/verify-backup-code' })).toBe(false); }); + it('a two-factor plugin that serves no route takes no code and gets no hook', async () => { + const plugin: any = { id: TWO_FACTOR_PLUGIN_ID, hooks: { after: [] } }; + expect(await acceptEachTotpCodeOnce([plugin])).toEqual([plugin]); + expect(plugin.hooks.before).toBeUndefined(); + }); + it('a list with no two-factor plugin is handed back untouched', async () => { const other: any = { id: 'bearer', hooks: { before: [] } }; const list = [other]; diff --git a/packages/plugins/plugin-auth/src/totp-code-single-use.ts b/packages/plugins/plugin-auth/src/totp-code-single-use.ts index 2ac3e87dbb0..04b306877c8 100644 --- a/packages/plugins/plugin-auth/src/totp-code-single-use.ts +++ b/packages/plugins/plugin-auth/src/totp-code-single-use.ts @@ -59,9 +59,10 @@ * ## Fail closed on vendor drift * * {@link acceptEachTotpCodeOnce} throws when the two-factor plugin it is handed - * serves no `/two-factor/verify-totp` endpoint: a build that went ahead would - * accept TOTP codes at a door this hook does not match. The failure is the - * build's, at boot. + * serves routes but none at `/two-factor/verify-totp`: a build that went ahead + * would accept TOTP codes at a door this hook does not match. The failure is + * the build's, at boot. A plugin object that serves no route at all takes no + * code, and is handed back as it is. */ import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; @@ -239,17 +240,23 @@ const extended = new WeakSet(); * the plugin object in `plugins`, and hand the same list back. A list with no * two-factor plugin is handed back untouched. * - * @throws Error when the two-factor plugin serves no `/two-factor/verify-totp` - * endpoint: fail closed rather than build a TOTP door this hook does not match. + * @throws Error when the two-factor plugin serves routes but none at + * `/two-factor/verify-totp`: fail closed rather than build a TOTP door this + * hook does not match. */ export async function acceptEachTotpCodeOnce(plugins: T): Promise { const target = plugins.find( (plugin) => (plugin as TwoFactorPluginShape | null | undefined)?.id === TWO_FACTOR_PLUGIN_ID, ) as TwoFactorPluginShape | undefined; if (!target || extended.has(target)) return plugins; - if (!Object.values(target.endpoints ?? {}).some(servesTotpDoor)) { + // better-auth mounts a plugin's routes from `endpoints`: a plugin that serves + // none takes no code anywhere, so there is no door to guard. One that serves + // routes, none of them this door, has moved the door. + const endpoints = Object.values(target.endpoints ?? {}); + if (endpoints.length === 0) return plugins; + if (!endpoints.some(servesTotpDoor)) { throw new Error( - `[AuthManager] The two-factor plugin serves no ${TOTP_VERIFY_PATH} endpoint, so its TOTP codes ` + + `[AuthManager] The two-factor plugin serves routes but none at ${TOTP_VERIFY_PATH}, so its TOTP codes ` + 'cannot be made single-use where they are accepted. Refusing to build the auth instance: a TOTP ' + 'code must be refused on any use after the first. Update totp-code-single-use.ts for the ' + 'installed better-auth two-factor plugin.', diff --git a/packages/qa/dogfood/test/totp.ts b/packages/qa/dogfood/test/totp.ts index f5b906f5575..f552daa4113 100644 --- a/packages/qa/dogfood/test/totp.ts +++ b/packages/qa/dogfood/test/totp.ts @@ -39,11 +39,55 @@ export function base32Decode(input: string): Buffer { return Buffer.from(out); } +/** The TOTP period, in milliseconds (the RFC's and better-auth's default 30 s). */ +const PERIOD_MS = 30_000; + /** The 6-digit TOTP for `secret` at the current 30-second step. */ export function totp(secret: Buffer): string { - const counter = Math.floor(Date.now() / 30_000); + return totpAt(secret, Math.floor(Date.now() / PERIOD_MS)); +} + +/** + * How long a code {@link freshTotp} hands out must stay inside the verifier's + * window: the time between handing it out and the request reaching the server. + */ +const FRESH_CODE_MARGIN_MS = 5_000; + +/** The last time step {@link freshTotp} handed out, per secret. */ +const lastStepHandedOut = new Map(); + +/** + * A 6-digit TOTP for `secret` that the server has not accepted before. + * + * The server accepts a TOTP code once (RFC 6238 section 5.2) and refuses a code + * from a step at or before the last one it accepted, so a fixture that signs in + * with TOTP more than once needs a code from a later step each time. Its + * verifier accepts the steps one either side of its current one: this hands out + * the earliest step after the last one handed out for this secret that is still + * inside that window {@link FRESH_CODE_MARGIN_MS} from now, and waits for the + * clock when the next such step is not inside it yet (at most one period). + * Every accepted code of a secret must come from here for the bookkeeping to hold. + */ +export async function freshTotp(secret: Buffer): Promise { + const key = secret.toString('hex'); + for (;;) { + const now = Date.now(); + const earliest = Math.floor((now + FRESH_CODE_MARGIN_MS) / PERIOD_MS) - 1; + const latest = Math.floor(now / PERIOD_MS) + 1; + const step = Math.max(earliest, (lastStepHandedOut.get(key) ?? earliest - 1) + 1); + if (step <= latest) { + lastStepHandedOut.set(key, step); + return totpAt(secret, step); + } + // `step` enters the window once step - 1 is the current step. + await new Promise((resolve) => setTimeout(resolve, (step - 1) * PERIOD_MS - now + 50)); + } +} + +/** The 6-digit TOTP for `secret` at time step `step`. */ +function totpAt(secret: Buffer, step: number): string { const buf = Buffer.alloc(8); - buf.writeBigUInt64BE(BigInt(counter)); + buf.writeBigUInt64BE(BigInt(step)); const digest = createHmac('sha1', secret).update(buf).digest(); const offset = digest[digest.length - 1] & 0x0f; const code = diff --git a/packages/qa/dogfood/test/two-factor-lockout.dogfood.test.ts b/packages/qa/dogfood/test/two-factor-lockout.dogfood.test.ts index 2c256bcafc1..25c68ff5870 100644 --- a/packages/qa/dogfood/test/two-factor-lockout.dogfood.test.ts +++ b/packages/qa/dogfood/test/two-factor-lockout.dogfood.test.ts @@ -47,7 +47,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; import { assertArmed, authSettingArmed } from './armed.js'; -import { secretFromTotpUri, totp } from './totp.js'; +import { freshTotp, secretFromTotpUri } from './totp.js'; const SYS = { context: { isSystem: true } }; const ADMIN_PASSWORD = 'admin123'; @@ -147,7 +147,7 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { // lockout bookkeeping. Confirm it through the SESSION path first — this // call is `isSignIn: false`, so it deliberately touches no counter. const confirmed = await stack.apiAs(token, 'POST', '/auth/two-factor/verify-totp', { - code: totp(secret), + code: await freshTotp(secret), }); expect(confirmed.status, `verify-totp (enrolment): ${await confirmed.clone().text()}`).toBe(200); }, 120_000); @@ -188,6 +188,10 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { return cookie; } + // Every correct code below comes from `freshTotp`: the server accepts a TOTP + // code once, so each sign-in needs a code from a later step than the last, + // and a case that needs one the clock has not reached yet waits for it (at + // most one 30 s period) — hence the longer timeouts on those cases. function verifyWithCookie(cookie: string, code: string): Promise { return stack.api('/auth/two-factor/verify-totp', { method: 'POST', @@ -228,7 +232,7 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { expect(before.count, 'precondition: a non-zero failure count to clear').toBeGreaterThan(0); const cookie = await beginChallenge(); - const ok = await verifyWithCookie(cookie, totp(secret)); + const ok = await verifyWithCookie(cookie, await freshTotp(secret)); expect(ok.status, `verify-totp (correct code): ${await ok.clone().text()}`).toBe(200); const after = await lockoutState(); @@ -237,7 +241,7 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { 'a successful verification must clear the budget — otherwise it counts non-consecutive failures and locks out a legitimate user', ).toBe(0); expect(after.lockedUntil ?? null).toBeNull(); - }); + }, 60_000); it('locks the account once the operator-configured budget is spent, and refuses even a correct code', async () => { // Two budgets stack here, and the test has to respect both. better-auth @@ -286,12 +290,12 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { // The lock has to bite BEFORE the code is checked — otherwise it is not a // lockout, just a slower guess loop. const cookie = await beginChallenge(); - const rejected = await verifyWithCookie(cookie, totp(secret)); + const rejected = await verifyWithCookie(cookie, await freshTotp(secret)); expect( rejected.status, `a locked account must refuse even a valid code: ${await rejected.clone().text()}`, ).toBe(429); - }); + }, 60_000); it('lazily clears an expired lock on the next attempt', async () => { const before = await lockoutState(); @@ -315,13 +319,13 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { // columns: a driver that mishandled it would leave the user locked out // forever with no error anywhere. const cookie = await beginChallenge(); - const ok = await verifyWithCookie(cookie, totp(secret)); + const ok = await verifyWithCookie(cookie, await freshTotp(secret)); expect(ok.status, `expired lock was not cleared: ${await ok.clone().text()}`).toBe(200); const after = await lockoutState(); expect(after.lockedUntil ?? null, 'the expired lock must be cleared, not merely ignored').toBeNull(); expect(after.count, 'clearing an expired lock must reset the failure budget too').toBe(0); - }); + }, 60_000); // [#3690] The admin escape hatch. `Unlock Account` used to clear only // `sys_user`, so a user locked at the SECOND factor had no way out but to @@ -333,7 +337,7 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { // Take a fresh one through the full two-factor sign-in BEFORE re-locking — // afterwards there is no way to obtain one, which is exactly why the admin // escape hatch has to exist. - const bootstrap = await verifyWithCookie(await beginChallenge(), totp(secret)); + const bootstrap = await verifyWithCookie(await beginChallenge(), await freshTotp(secret)); expect(bootstrap.status, `sign-in for the admin session: ${await bootstrap.clone().text()}`).toBe(200); const adminSession = ((await bootstrap.json()) as { token?: string }).token; expect(adminSession, 'two-factor sign-in returned no session token').toBeTruthy(); @@ -364,7 +368,7 @@ describe('#3624 follow-up: better-auth 2FA lockout counts wrong codes', () => { // And the user can actually sign in again, which is the point of unlocking. const cookie = await beginChallenge(); - const ok = await verifyWithCookie(cookie, totp(secret)); + const ok = await verifyWithCookie(cookie, await freshTotp(secret)); expect(ok.status, `still locked out after unlock: ${await ok.clone().text()}`).toBe(200); - }); + }, 90_000); }); From b12982785fad6fd81515b04f17b3758bd7a58684 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:03:04 +0000 Subject: [PATCH 3/4] chore(changeset): a TOTP code is accepted once Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/totp-code-accepted-once.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/totp-code-accepted-once.md diff --git a/.changeset/totp-code-accepted-once.md b/.changeset/totp-code-accepted-once.md new file mode 100644 index 00000000000..9859498ad73 --- /dev/null +++ b/.changeset/totp-code-accepted-once.md @@ -0,0 +1,12 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(auth): a TOTP code is accepted once + +Clause-②: no +Metadata-protocol: none + +A TOTP code that `/api/v1/auth/two-factor/verify-totp` accepts is remembered for its user and secret for as long as the verifier's window could still accept it. Any later presentation of that code is refused, whether it arrives on another sign-in challenge, from another client, on another server node or on the session lane (RFC 6238 §5.2). A code from a time step at or before the last accepted step for that user and secret is refused too. A refused code gets the answer a wrong code gets (`401 INVALID_CODE`) and counts toward the challenge's attempt budget and the account lockout in the same way. The same rule covers the code that confirms an enrolment, and every later code. A code from a later time step is accepted as before. + +The spent steps are kept as short-lived `sys_verification` rows, one per step, reserved under a primary key derived from the user, the secret and the step. Two presentations of one code that arrive together therefore admit exactly one, across processes and nodes. A store error while recording a step fails that verification. A client that signs in with TOTP more than once inside the same 30-second step needs the code of a later step for its second sign-in. From 3f95e6b9e540576849b8cb91447cf384a4599d6a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:42:17 +0000 Subject: [PATCH 4/4] refactor(auth): the verify-totp body field is named, so the one-time code never reads as an error-code stamp Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../plugins/plugin-auth/src/totp-code-single-use.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-auth/src/totp-code-single-use.ts b/packages/plugins/plugin-auth/src/totp-code-single-use.ts index 04b306877c8..8a9e29c9771 100644 --- a/packages/plugins/plugin-auth/src/totp-code-single-use.ts +++ b/packages/plugins/plugin-auth/src/totp-code-single-use.ts @@ -98,6 +98,13 @@ const DEFAULT_DIGITS = 6; */ export const NEVER_ACCEPTED_TOTP_CODE = '-'; +/** + * The request-body field `/two-factor/verify-totp` reads the TOTP code from + * (its body schema: `{ code, trustDevice? }`). Named, and written as a computed + * key below, because it is a one-time code, never an error code. + */ +const TOTP_CODE_BODY_FIELD = 'code'; + /** The identifier prefix of a spent-step reservation row in `sys_verification`. */ export const SPENT_TOTP_STEP_IDENTIFIER_PREFIX = 'totp-step:'; @@ -197,7 +204,7 @@ async function enrolledSecret(ctx: any, userId: string): Promise } } | void> { - const code = ctx?.body?.code; + const code = ctx?.body?.[TOTP_CODE_BODY_FIELD]; if (typeof code !== 'string' || code === '') return; const totpOptions = ctx.context.getPlugin?.(TWO_FACTOR_PLUGIN_ID)?.options?.totpOptions; @@ -223,7 +230,7 @@ export async function refuseSpentTotpStep(ctx: any): Promise<{ context: { body: }); if (!(await reserve(step))) { - return { context: { body: { ...ctx.body, code: NEVER_ACCEPTED_TOTP_CODE } } }; + return { context: { body: { ...ctx.body, [TOTP_CODE_BODY_FIELD]: NEVER_ACCEPTED_TOTP_CODE } } }; } for (let earlier = current - window; earlier < step; earlier++) await reserve(earlier); }