feat: 2fa backup codes
Tier 2 hard typescript · local · real merged PR from calcom/cal.com #10600
Ground-truth defects
Backup code validation is case-sensitive due to the use of indexOf(). This causes validation to fail if a user enters uppercase hex characters, as backup codes should be case-insensitive for a better user experience.
Because backupCodes are decrypted and mutated in memory before being written back, two concurrent login requests using the same backupCode could both pass this check and update, so a single backup code may effectively be accepted more than once if used concurrently, weakening the intended one-time-use semantics.
The diff replaces the TOTP branch with `if (user.twoFactorEnabled && credentials.backupCode)`, which takes priority over TOTP verification, while the unchanged password gate above it verifies the password only when `totpCode` is falsy (`if (user.password && !credentials.totpCode)`). Posting an email, any non-empty `totpCode`, and a stolen backup code therefore skips the password check and authenticates on the backup code alone, without the password and without ever reaching TOTP verification.
The change under review
diff (truncated — full diff)
new file mode 100644 @@ -0,0 +1,29 @@ +import React from "react"; +import { useFormContext } from "react-hook-form"; + +import { useLocale } from "@calcom/lib/hooks/useLocale"; +import { Label, TextField } from "@calcom/ui"; + +export default function TwoFactor({ center = true }) { + const { t } = useLocale(); + const methods = useFormContext(); + + return ( + <div className={center ? "mx-auto !mt-0 max-w-sm" : "!mt-0 max-w-sm"}> + <Label className="mt-4">{t("backup_code")}</Label> + + <p className="text-subtle mb-4 text-sm">{t("backup_code_instructions")}</p> + + <TextField + id="backup-code" + label="" + defaultValue="" + placeholder="XXXXX-XXXXX" + minLength={10} // without dash + maxLength={11} // with dash + required + {...methods.register("backupCode")} + /> + </div> + ); +} @@ -5,7 +5,7 @@ import { useFormContext } from "react-hook-form"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { Label, Input } from "@calcom/ui"; -export default function TwoFactor({ center = true }) { +export default function TwoFactor({ center = true, autoFocus = true }) { const [value, onChange] = useState(""); const { t } = useLocale(); const methods = useFormContext(); @@ -40,7 +40,7 @@ export default function TwoFactor({ center = true }) { name={`2fa${index + 1}`} inputMode="decimal" {...digit} - autoFocus={index === 0} + autoFocus={autoFocus && index === 0} autoComplete="one-time-code" /> ))} @@ -5,6 +5,7 @@ import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { Button, Dialog, DialogContent, DialogFooter, Form, PasswordField } from "@calcom/ui"; +import BackupCode from "@components/auth/BackupCode"; import TwoFactor from "@components/auth/TwoFactor"; import TwoFactorAuthAPI from "./TwoFactorAuthAPI"; @@ -20,6 +21,7 @@ interface DisableTwoFactorAuthModalProps { } interface DisableTwoFactorValues { + backupCode: string; totpCode: string; password: string; } @@ -33,11 +35,19 @@ const DisableTwoFactorAuthModal = ({ }: DisableTwoFactorAuthModalProps) => { const [isDisabling, setIsDisabling] = useState(false); const [errorMessage, setErrorMessage] = useState<string | null>(null); + const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false); const { t } = useLocale(); const form = useForm<DisableTwoFactorValues>(); - async function handleDisable({ totpCode, password }: DisableTwoFactorValues) { + const resetForm = (clearPassword = true) => { + if (clearPassword) form.setValue("password", ""); + form.setValue("backupCode", ""); + form.setValue("totpCode", ""); + setErrorMessage(null); + }; + + async function handleDisable({ password, totpCode, backupCode }: DisableTwoFactorValues) { if (isDisabling) { return; } @@ -45,8 +55,10 @@ const DisableTwoFactorAuthModal = ({ setErrorMessage(null); try { - const response = await TwoFactorAuthAPI.disable(password, totpCode); + const response = await TwoFactorAuthAPI.disable(password, totpCode, backupCode); if (response.status === 200) { + setTwoFactorLostAccess(false); + resetForm(); onDisable(); return; } @@ -54,12 +66,14 @@ const DisableTwoFactorAuthModal = ({ const body = await response.json(); if (body.error === ErrorCode.IncorrectPassword) { setErrorMessage(t("incorrect_password")); - } - if (body.error === ErrorCode.SecondFactorRequired) { + } else if (body.error === ErrorCode.SecondFactorRequired) { setErrorMessage(t("2fa_required")); - } - if (body.error === ErrorCode.IncorrectTwoFactorCode) { + } else if (body.error === ErrorCode.IncorrectTwoFactorCode) { setErrorMessage(t("incorrect_2fa")); + } else if (body.error === ErrorCode.IncorrectBackupCode) { + setErrorMessage(t("incorrect_backup_code")); + } else if (body.error === ErrorCode.MissingBackupCodes) { + setErrorMessage(t("missing_backup_codes")); } else { setErrorMessage(t("something_went_wrong")); } @@ -78,6 +92,7 @@ const DisableTwoFactorAuthModal = ({ <div className="mb-8"> {!disablePassword && ( <PasswordField + required labelProps={{ className: "block text-sm font-medium text-default", }} @@ -85,12 +100,25 @@ const DisableTwoFactorAuthModal = ({ className="border-default mt-1 block w-full rounded-md border px-3 py-2 text-sm focus:border-black focus:outline-none focus:ring-black" /> )} - <TwoFactor center={false} /> + {twoFactorLostAccess ? ( + <BackupCode center={false} /> + ) : ( + <TwoFactor center={false} autoFocus={false} /> + )} {errorMessage && <p className="mt-1 text-sm text-red-700">{errorMessage}</p>} </div> <DialogFooter showDivider className="relative mt-5"> + <Button + color="minimal" + className="mr-auto" + onClick={() => { + setTwoFactorLostAccess(!twoFactorLostAccess); + resetForm(false); + }}> + {twoFactorLostAccess ? t("go_back") : t("lost_access")} + </Button> <Button color="secondary" onClick={onCancel}> {t("cancel")} </Button> @@ -5,7 +5,7 @@ import { useForm } from "react-hook-form"; import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode"; import { useCallbackRef } from "@calcom/lib/hooks/useCallbackRef"; import { useLocale } from "@calcom/lib/hooks/useLocale"; -import { Button, Dialog, DialogContent, DialogFooter, Form, TextField } from "@calcom/ui"; +import { Button, Dialog, DialogContent, DialogFooter, Form, PasswordField, showToast } from "@calcom/ui"; import TwoFactor from "@components/auth/TwoFactor"; @@ -28,6 +28,7 @@ interface EnableTwoFactorModalProps { enum SetupStep { ConfirmPassword, + DisplayBackupCodes, DisplayQrCode, EnterTotpCode, } @@ -54,16 +55,25 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable const setupDescriptions = { [SetupStep.ConfirmPassword]: t("2fa_confirm_current_password"), + [SetupStep.DisplayBackupCodes]: t("backup_code_instructions"), [SetupStep.DisplayQrCode]: t("2fa_scan_image_or_use_code"), [SetupStep.EnterTotpCode]: t("2fa_enter_six_digit_code"), }; const [step, setStep] = useState(SetupStep.ConfirmPassword); const [password, setPassword] = useState(""); + const [backupCodes, setBackupCodes] = useState([]); + const [backupCodesUrl, setBackupCodesUrl] = useState(""); const [dataUri, setDataUri] = useState(""); const [secret, setSecret] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); const [errorMessage, setErrorMessage] = useState<string | null>(null); + const resetState = () => { + setPassword(""); + setErrorMessage(null); + setStep(SetupStep.ConfirmPassword); + }; + async function handleSetup(e: React.FormEvent) { e.preventDefault(); @@ -79,6 +89,15 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable const body = await response.json(); if (response.status === 200) { + setBackupCodes(body.backupCodes); + + // create backup codes download url + const textBlob = new Blob([body.backupCodes.map(formatBackupCode).join("\n")], { + type: "text/plain", + }); + if (backupCodesUrl) URL.revokeObjectURL(backupCodesUrl); + setBackupCodesUrl(URL.createObjectURL(textBlob)); + setDataUri(body.dataUri); setSecret(body.secret); setStep(SetupStep.DisplayQrCode); @@ -113,7 +132,7 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable const body = await response.json(); if (response.status === 200) { - onEnable(); + setStep(SetupStep.DisplayBackupCodes); return; } @@ -141,13 +160,18 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable } }, [form, handleEnableRef, totpCode]); + const formatBackupCode = (code: string) => `${code.slice(0, 5)}-${code.slice(5, 10)}`; + return ( <Dialog open={open} onOpenChange={onOpenChange}> - <DialogContent title={t("enable_2fa")} description={setupDescriptions[step]} type="creation"> + <DialogContent + title={step === SetupStep.DisplayBackupCodes ? t("backup_codes") : t("enable_2fa")} + description={setupDescriptions[step]} + type="creation"> <WithStep step={SetupStep.ConfirmPassword} current={step}> <form onSubmit={handleSetup}> <div className="mb-4"> - <TextField + <PasswordField label={t("password")} type="password" name="password" @@ -173,6 +197,15 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable </p> </> </WithStep> + <WithStep step={SetupStep.DisplayBackupCodes} current={step}> + <> + <div className="mt-5 grid grid-cols-2 gap-1 text-center font-mono md:pl-10 md:pr-10"> + {backupCodes.map((code) => ( + <div key={code}>{formatBackupCode(code)}</div> + ))} + </div> + </> + </WithStep> <Form handleSubmit={handleEnable} form={form}> <WithStep step={SetupStep.EnterTotpCode} current={step}> <div className="-mt-4 pb-2"> @@ -186,9 +219,16 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable </div> </WithStep> <DialogFooter className="mt-8" showDivider> - <Button color="secondary" onClick={onCancel}> - {t("cancel")} - </Button> + {step !== SetupStep.DisplayBackupCodes ? ( + <Button + color="secondary" + onClick={() => { + onCancel(); + resetState(); + }}> + {t("cancel")} + </Button> + ) : null} <WithStep step={SetupStep.ConfirmPassword} current={step}> <Button type="submit" @@ -218,6 +258,35 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable {t("enable")} </Button> </WithStep> + <WithStep step={SetupStep.DisplayBackupCodes} current={step}> + <> + <Button + color="secondary" + data-testid="backup-codes-close" + onClick={(e) => { + e.preventDefault(); + resetState(); + onEnable(); + }}> + {t("close")} + </Button> + <Button + color="secondary" + data-testid="backup-codes-copy" + onClick={(e) => { + e.preventDefault(); + navigator.clipboard.writeText(backupCodes.map(formatBackupCode).join("\n")); + showToast(t("backup_codes_copied"), "success"); + }}> + {t("copy")} + </Button> + <a download="cal-backup-codes.txt" href={backupCodesUrl}> + <Button color="primary" data-testid="backup-codes-download"> + {t("download")} + </Button> + </a> + </> + </WithStep> </DialogFooter> </Form> </DialogContent> @@ -19,10 +19,10 @@ const TwoFactorAuthAPI = { }); }, - async disable(password: string, code: string) { + async disable(password: string, code: string, backupCode: string) { return fetch("/api/auth/two-factor/totp/disable", { method: "POST", - body: JSON.stringify({ password, code }), + body: JSON.stringify({ password, code, backupCode }), headers: { "Content-Type": "application/json", }, @@ -43,8 +43,30 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) return res.status(400).json({ error: ErrorCode.IncorrectPassword }); } } - // if user has 2fa - if (user.twoFactorEnabled) { + + // if user has 2fa and using backup code + if (user.twoFactorEnabled && req.body.backupCode) { + if (!process.env.CALENDSO_ENCRYPTION_KEY) { + console.error("Missing encryption key; cannot proceed with backup code login."); + throw new Error(ErrorCode.InternalServerError); + } + + if (!user.backupCodes) { + return res.status(400).json({ error: ErrorCode.MissingBackupCodes }); + } + + const backupCodes = JSON.parse(symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY)); + + // check if user-supplied code matches one + const index = backupCodes.indexOf(req.body.backupCode.replaceAll("-", "")); + if (index === -1) { + return res.status(400).json({ error: ErrorCode.IncorrectBackupCode }); + } + + // we delete all stored backup codes at the end, no need to do this here + + // if user has 2fa and NOT using backup code, try totp + } else if (user.twoFactorEnabled) { if (!req.body.code) { return res.status(400).json({ error: ErrorCode.SecondFactorRequired }); // throw new Error(ErrorCode.SecondFactorRequired); @@ -82,6 +104,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) id: session.user.id, }, data: { + backupCodes: null, twoFactorEnabled: false, twoFactorSecret: null, }, @@ -1,3 +1,4 @@ +import crypto from "crypto"; import type { NextApiRequest, NextApiResponse } from "next"; import { authenticator } from "otplib"; import qrcode from "qrcode"; @@ -56,11 +57,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) // bytes without updating the sanity checks in the enable and login endpoints. const secret = authenticator.generateSecret(20); + // generate backup codes with 10 character length + const backupCodes = Array.from(Array(10), () => crypto.randomBytes(5).toString("hex")); + await prisma.user.update({ where: { id: session.user.id, }, data: { + backupCodes: symmetricEncrypt(JSON.stringify(backupCodes), process.env.CALENDSO_ENCRYPTION_KEY), twoFactorEnabled: false, twoFactorSecret: symmetricEncrypt(secret, process.env.CALENDSO_ENCRYPTION_KEY), }, @@ -70,5 +75,5 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const keyUri = authenticator.keyuri(name, "Cal", secret); const dataUri = await qrcode.toDataURL(keyUri); - return res.json({ secret, keyUri, dataUri }); + return res.json({ secret, keyUri, dataUri, backupCodes }); } @@ -21,7 +21,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale"; import { collectPageParameters, telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry"; import prisma from "@calcom/prisma"; import { Alert, Button, EmailField, PasswordField } from "@calcom/ui"; -import { ArrowLeft } from "@calcom/ui/components/icon"; +import { ArrowLeft, Lock } from "@calcom/ui/components/icon"; import type { inferSSRProps } from "@lib/types/inferSSRProps"; import type { WithNonceProps } from "@lib/withNonce"; @@ -29,6 +29,7 @@ import withNonce from "@lib/withNonce"; import AddToHomescreen from "@components/AddToHomescreen"; import PageWrapper from "@components/PageWrapper"; +import BackupCode from "@components/auth/BackupCode"; import TwoFactor from "@components/auth/TwoFactor"; import AuthContainer from "@components/ui/AuthContainer"; @@ -39,6 +40,7 @@ interface LoginValues { email: string; password: string; totpCode: string; + backupCode: string; csrfToken: string; } export default function Login({ @@ -65,6 +67,7 @@ export default function Login({ const methods = useForm<LoginValues>({ resolver: zodResolver(formSchema) }); const { register, formState } = methods; const [twoFactorRequired, setTwoFactorRequired] = useState(!!totpEmail || false); + const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false); const [errorMessage, setErrorMessage] = useState<string | null>(null); const errorMessages: { [key: string]: string } = { @@ -98,15 +101,35 @@ export default function Login({ ); const TwoFactorFooter = ( - <Button - onClick={() => { - setTwoFactorRequired(false); - methods.setValue("totpCode", ""); - }} - StartIcon={ArrowLeft} - color="minimal"> - {t("go_back")} - </Button> + <> + <Button + onClick={() => { + if (twoFactorLostAccess) { + setTwoFactorLostAccess(false); + methods.setValue("backupCode", ""); + } else { + setTwoFactorRequired(false); + methods.setValue("totpCode", ""); + } + setErrorMessage(null); + }} + StartIcon={ArrowLeft} + color="minimal"> + {t("go_back")} + </Button> + {!twoFactorLostAccess ? ( + <Button + onClick={() => { + setTwoFactorLostAccess(true); + setErrorMessage(null); + methods.setValue("totpCode", ""); + }} + StartIcon={Lock} + color="minimal"> + {t("lost_access")} + </Button>
Leaderboard for this case
hard · 2 of 9 bots fully caught it (22% solve rate) · 52% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | cursor | solved | 3/3 | 100.0% | 4 | 0 |
| 2 | Drape (Deep Review) | solved | 3/3 | 100.0% | 5 | 0 |
| 3 | Drape (Review) | partial | 2/3 | 81.8% | 7 | 0 |
| 4 | greptile | partial | 2/3 | 81.8% | 3 | 0 |
| 5 | Cubic | partial | 2/3 | 81.8% | 10 | 1 |
| 6 | Claude Code (Opus 5.5) | partial | 1/3 | 9.1% | 4 | 0 |
| 7 | qodo | partial | 1/3 | 9.1% | 5 | 0 |
| 8 | Mjolnir (Opus 5.5) | miss | 0/3 | 0.0% | 2 | 0 |
| 9 | Mjolnir (Sonnet 5.5) | miss | 0/3 | 0.0% | 2 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✓ | off by one |
| d5 | critical | ✗ | — |
2FA is now enabled on the server before the codes step. Only the Close button calls onEnable and resetState. The parent's onOpenChange only toggles open, the modal stays mounted, and its step state persists, so closing with Escape or an outside click leaves viewer.me stale and keeps step at DisplayBackupCodes. [grounded: diff] [consensus 3/3: valid=3]
A truthy non-string backupCode in the JSON body has no replaceAll method, so the call throws a TypeError and the handler returns 500 instead of 400. Only an authenticated user can reach this, so impact is low. [grounded: diff] [consensus 3/3: valid=3]
This is a naming complaint. Every caller uses the default import, so nothing behaves incorrectly. [grounded: diff] [consensus 3/3: minor=3]
raw comments (4)
Login reads the backup codes, checks the submitted code with indexOf, then writes the list back with that code set to null. The write is unconditional and not done in a transaction, so two concurrent logins with the same code both pass the check and both succeed, which breaks the single-use guarantee. Two overlapping consumptions of different codes can also overwrite each other's update, which brings an already-used code back. Use an optimistic check, e.g. updateMany where backupCodes equals the value that was read, and fail if no row is updated, or lock the row.
2FA is now enabled on the server before the backup codes are shown. onEnable only runs from the new Close button. If the user closes the dialog with Escape or a click outside, onOpenChange closes it without calling onEnable, so `viewer.me` is never invalidated and the settings page still says 2FA is off. The modal is not unmounted, so `step` stays at DisplayBackupCodes: reopening it shows the old codes with no Cancel button instead of starting the setup flow again.
`req.body.backupCode.replaceAll` assumes backupCode is a string. Any other truthy JSON value (a number, array or object) throws a TypeError and the endpoint returns a 500 instead of a 400. The same applies to the decrypted JSON, which is never checked to be an array. Validate the input type first.
The new BackupCode component is exported under the name `TwoFactor`, copied from TwoFactor.tsx. That is misleading in stack traces and React DevTools, and invites import mistakes.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✓ | wrong severity |
| d5 | critical | ✓ | off by one |
The copy handler calls showToast right after writeText without awaiting it, so the toast appears even if the copy fails. The test therefore can't detect a broken clipboard copy, as its own TODO admits. [grounded: tree apps/web/playwright/login.2fa.e2e.ts] [consensus 5/5: valid=5]
The diff adds tabIndex={-1} to the show/hide password button. That takes it out of the keyboard tab order, so keyboard-only users can't reach it. [grounded: diff] [consensus 5/5: valid=5]
The form uses noValidate and the schema passes backupCode through unchecked, so an empty backup code gets submitted. The server then takes the TOTP branch and returns SecondFactorRequired, which only calls setTwoFactorRequired(true) and shows no error. [grounded: tree apps/web/pages/auth/login.tsx] [consensus 5/5: valid=5]
External-IdP users come in through the totpEmail flow, which shows ExternalTotpFooter instead of TwoFactorFooter. They never get the 'Lost access' button, so the UI can't send them down the backup-code path. Without that path, the guard behaviour is a missing feature, not a bug the change created. [invalid: contradiction] [consensus 5/5: invalid=5]
Before this change, onEnable ran as soon as enabling succeeded. Now it only runs from the Close button. Closing with Escape or an overlay click goes through onOpenChange, which only toggles the dialog's open state, so the user query is never invalidated and the switch shows stale state. [grounded: diff] [consensus 5/5: valid=5]
The handler doesn't check the type of req.body.backupCode. A truthy non-string such as a number or object makes replaceAll throw, which gives a 500 instead of a 400. [grounded: diff] [consensus 5/5: valid=5]
The visible Label has no htmlFor and the TextField is given label="", so the input has no accessible name tied to the visible label. [grounded: diff] [consensus 5/5: valid=5]
The modal stays mounted, and both onCancel and onOpenChange only toggle the parent's open state. twoFactorLostAccess is reset only after a successful disable, so reopening the dialog after a cancel still shows the backup-code form. [grounded: diff] [consensus 5/5: valid=5]
raw comments (11)
<!-- cubic:v=4699d178-dc38-443d-a54f-28ddeadcbb8b -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":9} -->
P1: Concurrent login requests can redeem the same backup code more than once because this update has no compare-and-swap condition. Use an atomic conditional update on the previously read `backupCodes` value, or equivalent locking, and reject the request when another redemption wins.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/auth/lib/next-auth-options.ts, line 149:
<comment>Concurrent login requests can redeem the same backup code more than once because this update has no compare-and-swap condition. Use an atomic conditional update on the previously read `backupCodes` value, or equivalent locking, and reject the request when another redemption wins.</comment>
<file context>
@@ -126,7 +128,33 @@ const providers: Provider[] = [
+
+ // delete verified backup code and re-encrypt remaining
+ backupCodes[index] = null;
+ await prisma.user.update({
+ where: {
+ id: user.id,
</file context>
```
</details>
<!-- cubic:v=52857c32-eaeb-49e2-9bbc-c651e5e8d809 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":9} -->
P1: A password-backed CAL user can bypass the password by sending a valid backup code with any non-empty `totpCode`; the earlier password check is skipped, and this branch does not validate that TOTP value. Verify the password independently for CAL users before accepting a backup code, while retaining the IdP-specific flow separately.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/auth/lib/next-auth-options.ts, line 131:
<comment>A password-backed CAL user can bypass the password by sending a valid backup code with any non-empty `totpCode`; the earlier password check is skipped, and this branch does not validate that TOTP value. Verify the password independently for CAL users before accepting a backup code, while retaining the IdP-specific flow separately.</comment>
<file context>
@@ -126,7 +128,33 @@ const providers: Provider[] = [
}
- if (user.twoFactorEnabled) {
+ if (user.twoFactorEnabled && credentials.backupCode) {
+ if (!process.env.CALENDSO_ENCRYPTION_KEY) {
+ console.error("Missing encryption key; cannot proceed with backup code login.");
</file context>
```
</details>
<!-- cubic:v=98174a8e-47a4-40c5-9faa-5786ce04c0e2 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":6} -->
P2: This copy assertion can pass while the copy is broken: the handler calls `navigator.clipboard.writeText(...)` without awaiting it and calls `showToast` unconditionally, so the toast appears even when the clipboard write rejects. In headless Chromium, clipboard-write is not granted by default, so the test gives false confidence that copy works. Grant `clipboard-read`/`clipboard-write` permissions on the browser context and assert the clipboard content (e.g. `page.evaluate(() => navigator.clipboard.readText())`) instead of only waiting for the toast.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/playwright/login.2fa.e2e.ts, line 120:
<comment>This copy assertion can pass while the copy is broken: the handler calls `navigator.clipboard.writeText(...)` without awaiting it and calls `showToast` unconditionally, so the toast appears even when the clipboard write rejects. In headless Chromium, clipboard-write is not granted by default, so the test gives false confidence that copy works. Grant `clipboard-read`/`clipboard-write` permissions on the browser context and assert the clipboard content (e.g. `page.evaluate(() => navigator.clipboard.readText())`) instead of only waiting for the toast.</comment>
<file context>
@@ -103,6 +107,23 @@ test.describe("2FA Tests", async () => {
+ // TODO: check file content
+
+ // click copy button
+ await page.getByTestId("backup-codes-copy").click();
+ await page.getByTestId("toast-success").waitFor();
+ // TODO: check clipboard content
</file context>
```
</details>
<!-- cubic:v=037a6648-414c-437c-807c-78036c141365 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":8} -->
P2: This change removes the show/hide password button from the keyboard tab order (tabIndex={-1}), so keyboard-only users who tab through the form can focus the input but never reach the visibility toggle. There is no keyboard shortcut to activate it, leaving the control unusable without a pointing device, which fails WCAG 2.1.1/2.4.3. If the intent is to avoid an extra tab stop after the input, keep the button reachable (e.g. leave it in tab order rather than removing it).
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/ui/components/form/inputs/Input.tsx, line 49:
<comment>This change removes the show/hide password button from the keyboard tab order (tabIndex={-1}), so keyboard-only users who tab through the form can focus the input but never reach the visibility toggle. There is no keyboard shortcut to activate it, leaving the control unusable without a pointing device, which fails WCAG 2.1.1/2.4.3. If the intent is to avoid an extra tab stop after the input, keep the button reachable (e.g. leave it in tab order rather than removing it).</comment>
<file context>
@@ -44,7 +44,11 @@ export const PasswordField = forwardRef<HTMLInputElement, InputFieldProps>(funct
- <button className="text-emphasis h-9" type="button" onClick={() => toggleIsPasswordVisible()}>
+ <button
+ className="text-emphasis h-9"
+ tabIndex={-1}
+ type="button"
+ onClick={() => toggleIsPasswordVisible()}>
</file context>
```
</details>
<!-- cubic:v=4696337a-0444-46f3-8422-6d2a8da68b81 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":9} -->
P2: When the backup-code screen is submitted empty, the form sends the request despite `required`, because this form disables native validation and the schema does not validate `backupCode`. The server returns `SecondFactorRequired`, which leaves the backup screen unchanged without feedback; validate the backup code before calling `signIn`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/pages/auth/login.tsx, line 221:
<comment>When the backup-code screen is submitted empty, the form sends the request despite `required`, because this form disables native validation and the schema does not validate `backupCode`. The server returns `SecondFactorRequired`, which leaves the backup screen unchanged without feedback; validate the backup code before calling `signIn`.</comment>
<file context>
@@ -194,7 +218,7 @@ export default function Login({
</div>
- {twoFactorRequired && <TwoFactor center />}
+ {twoFactorRequired ? !twoFactorLostAccess ? <TwoFactor center /> : <BackupCode center /> : null}
{errorMessage && <Alert severity="error" title={errorMessage} />}
</file context>
```
</details>
<!-- cubic:v=0693430c-0fe0-4270-a78a-6f6ef72a60e3 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":10} -->
P2: When an external-IdP user chooses “Lost access” and submits a backup code, the earlier IdP checks reject the request before this branch because `totpCode` is empty. Allow `backupCode` as an alternative second-factor credential in both preceding guards.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/auth/lib/next-auth-options.ts, line 131:
<comment>When an external-IdP user chooses “Lost access” and submits a backup code, the earlier IdP checks reject the request before this branch because `totpCode` is empty. Allow `backupCode` as an alternative second-factor credential in both preceding guards.</comment>
<file context>
@@ -126,7 +128,33 @@ const providers: Provider[] = [
}
- if (user.twoFactorEnabled) {
+ if (user.twoFactorEnabled && credentials.backupCode) {
+ if (!process.env.CALENDSO_ENCRYPTION_KEY) {
+ console.error("Missing encryption key; cannot proceed with backup code login.");
</file context>
```
</details>
<!-- cubic:v=791f9c19-b71f-45aa-b8bd-6062ab809f38 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":10} -->
P2: When the user dismisses the backup-code step with Escape or by clicking the overlay, the server has already enabled 2FA but `onEnable` never runs, so the page keeps stale user data and leaves the switch disabled until a refresh. Notify the parent whenever a successfully enabled dialog closes, not only from the backup-code Close button.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/components/settings/EnableTwoFactorModal.tsx, line 135:
<comment>When the user dismisses the backup-code step with Escape or by clicking the overlay, the server has already enabled 2FA but `onEnable` never runs, so the page keeps stale user data and leaves the switch disabled until a refresh. Notify the parent whenever a successfully enabled dialog closes, not only from the backup-code Close button.</comment>
<file context>
@@ -113,7 +132,7 @@ const EnableTwoFactorModal = ({ onEnable, onCancel, open, onOpenChange }: Enable
if (response.status === 200) {
- onEnable();
+ setStep(SetupStep.DisplayBackupCodes);
return;
}
</file context>
```
</details>
<!-- cubic:v=8dfe1735-34c1-46da-ab51-c14d2e29f120 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":9} -->
P2: A truthy non-string `backupCode` makes this handler throw because `req.body` accepts arbitrary JSON. Validate that `backupCode` is a string before calling `replaceAll`, and return `IncorrectBackupCode` for malformed input.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/pages/api/auth/two-factor/totp/disable.ts, line 61:
<comment>A truthy non-string `backupCode` makes this handler throw because `req.body` accepts arbitrary JSON. Validate that `backupCode` is a string before calling `replaceAll`, and return `IncorrectBackupCode` for malformed input.</comment>
<file context>
@@ -43,8 +43,30 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
+ const backupCodes = JSON.parse(symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY));
+
+ // check if user-supplied code matches one
+ const index = backupCodes.indexOf(req.body.backupCode.replaceAll("-", ""));
+ if (index === -1) {
+ return res.status(400).json({ error: ErrorCode.IncorrectBackupCode });
</file context>
```
</details>
```suggestion
if (typeof req.body.backupCode !== "string") {
return res.status(400).json({ error: ErrorCode.IncorrectBackupCode });
}
const index = backupCodes.indexOf(req.body.backupCode.replaceAll("-", ""));
```
<!-- cubic:v=fc91fb4a-2ada-4c4f-8009-2f95aec7246e -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":10} -->
P2: The backup-code input is not associated with its visible label because the label has no `htmlFor`, while `TextField` uses a different generated ID for its internal label. Add `htmlFor="backup-code"` to the visible label so screen readers announce the field correctly.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/components/auth/BackupCode.tsx, line 13:
<comment>The backup-code input is not associated with its visible label because the label has no `htmlFor`, while `TextField` uses a different generated ID for its internal label. Add `htmlFor="backup-code"` to the visible label so screen readers announce the field correctly.</comment>
<file context>
@@ -0,0 +1,29 @@
+
+ return (
+ <div className={center ? "mx-auto !mt-0 max-w-sm" : "!mt-0 max-w-sm"}>
+ <Label className="mt-4">{t("backup_code")}</Label>
+
+ <p className="text-subtle mb-4 text-sm">{t("backup_code_instructions")}</p>
</file context>
```
</details>
<!-- cubic:v=f6516ed2-93e5-477d-8468-b1efd13f7e07 -->
<!-- cubic:review-run=641cda0f-e21e-526e-8177-ee9f12cbb31e -->
<!-- metadata:{"confidence":9} -->
P2: After a user selects `Lost access` and cancels or closes the dialog, reopening it still shows the backup-code form because `twoFactorLostAccess` persists while the modal remains mounted. Reset this mode whenever the dialog closes so each new disable attempt starts with the TOTP form.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/components/settings/DisableTwoFactorModal.tsx, line 38:
<comment>After a user selects `Lost access` and cancels or closes the dialog, reopening it still shows the backup-code form because `twoFactorLostAccess` persists while the modal remains mounted. Reset this mode whenever the dialog closes so each new disable attempt starts with the TOTP form.</comment>
<file context>
@@ -33,33 +35,45 @@ const DisableTwoFactorAuthModal = ({
}: DisableTwoFactorAuthModalProps) => {
const [isDisabling, setIsDisabling] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
+ const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false);
const { t } = useLocale();
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**10 issues found** across 16 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/web/playwright/login.2fa.e2e.ts">
<violation number="1" location="apps/web/playwright/login.2fa.e2e.ts:120">
P2: This copy assertion can pass while the copy is broken: the handler calls `navigator.clipboard.writeText(...)` without awaiting it and calls `showToast` unconditionally, so the toast appears even when the clipboard write rejects. In headless Chromium, clipboard-write is not granted by default, so the test gives false confidence that copy works. Grant `clipboard-read`/`clipboard-write` permissions on the browser context and assert the clipboard content (e.g. `page.evaluate(() => navigator.clipboard.readText())`) instead of only waiting for the toast.</violation>
</file>
<file name="packages/ui/components/form/inputs/Input.tsx">
<violation number="1" location="packages/ui/components/form/inputs/Input.tsx:49">
P2: This change removes the show/hide password button from the keyboard tab order (tabIndex={-1}), so keyboard-only users who tab through the form can focus the input but never reach the visibility toggle. There is no keyboard shortcut to activate it, leaving the control unusable without a pointing device, which fails WCAG 2.1.1/2.4.3. If the intent is to avoid an extra tab stop after the input, keep the button reachable (e.g. leave it in tab order rather than removing it).</violation>
</file>
<file name="apps/web/pages/auth/login.tsx">
<violation number="1" location="apps/web/pages/auth/login.tsx:221">
P2: When the backup-code screen is submitted empty, the form sends the request despite `required`, because this form disables native validation and the schema does not validate `backupCode`. The server returns `SecondFactorRequired`, which leaves the backup screen unchanged without feedback; validate the backup code before calling `signIn`.</violation>
</file>
<file name="packages/features/auth/lib/next-auth-options.ts">
<violation number="1" location="packages/features/auth/lib/next-auth-options.ts:131">
P2: When an external-IdP user chooses “Lost access” and submits a backup code, the earlier IdP checks reject the request before this branch because `totpCode` is empty. Allow `backupCode` as an alternative second-factor credential in both preceding guards.</violation>
<violation number="2" location="packages/features/auth/lib/next-auth-options.ts:131">
P1: A password-backed CAL user can bypass the password by sending a valid backup code with any non-empty `totpCode`; the earlier password check is skipped, and this branch does not validate that TOTP value. Verify the password independently for CAL users before accepting a backup code, while retaining the IdP-specific flow separately.</violation>
<violation number="3" location="packages/features/auth/lib/next-auth-options.ts:149">
P1: Concurrent login requests can redeem the same backup code more than once because this update has no compare-and-swap condition. Use an atomic conditional update on the previously read `backupCodes` value, or equivalent locking, and reject the request when another redemption wins.</violation>
</file>
<file name="apps/web/components/settings/EnableTwoFactorModal.tsx">
<violation number="1" location="apps/web/components/settings/EnableTwoFactorModal.tsx:135">
P2: When the user dismisses the backup-code step with Escape or by clicking the overlay, the server has already enabled 2FA but `onEnable` never runs, so the page keeps stale user data and leaves the switch disabled until a refresh. Notify the parent whenever a successfully enabled dialog closes, not only from the backup-code Close button.</violation>
</file>
<file name="apps/web/pages/api/auth/two-factor/totp/disable.ts">
<violation number="1" location="apps/web/pages/api/auth/two-factor/totp/disable.ts:61">
P2: A truthy non-string `backupCode` makes this handler throw because `req.body` accepts arbitrary JSON. Validate that `backupCode` is a string before calling `replaceAll`, and return `IncorrectBackupCode` for malformed input.</violation>
</file>
<file name="apps/web/components/auth/BackupCode.tsx">
<violation number="1" location="apps/web/components/auth/BackupCode.tsx:13">
P2: The backup-code input is not associated with its visible label because the label has no `htmlFor`, while `TextField` uses a different generated ID for its internal label. Add `htmlFor="backup-code"` to the visible label so screen readers announce the field correctly.</violation>
</file>
<file name="apps/web/components/settings/DisableTwoFactorModal.tsx">
<violation number="1" location="apps/web/components/settings/DisableTwoFactorModal.tsx:38">
P2: After a user selects `Lost access` and cancels or closes the dialog, reopening it still shows the backup-code form because `twoFactorLostAccess` persists while the modal remains mounted. Reset this mode whenever the dialog closes so each new disable attempt starts with the TOTP form.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/16/ai_pr_review_github_delivery_3354a022a59aa4bd9dc5d311c3170d348aecf3ab83168393469d9183383431f9?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F16)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_3354a022a59aa4bd9dc5d311c3170d348aecf3ab83168393469d9183383431f9:e5a07fe1ee243a1b7e0212e68fe7c5fb889dd588:641cda0f-e21e-526e-8177-ee9f12cbb31e -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✓ | exact |
| d4 | low | ✓ | off by one |
| d5 | critical | ✓ | off by one |
Before the change, a successful enable called onEnable() right away, which invalidated viewer.me. Now success only moves the dialog to the backup-codes step, and onEnable runs only from the Close button. If the dialog is dismissed through the Dialog's onOpenChange (Escape or clicking the overlay), the page just toggles enableModalOpen and never invalidates viewer.me, so the switch stays off even though 2FA is on. The claim that the codes are permanently lost is overstated, because the modal's state seems to persist while it stays mounted, but the stale switch is a real regression. [grounded: diff] [consensus 5/5: valid=5]
raw comments (5)
### Backup codes skip password checks
**High Severity**
<!-- DESCRIPTION START -->
Password verification runs only when `totpCode` is empty, while a truthy `backupCode` takes precedence over TOTP and never validates that code. A request with any dummy `totpCode`, a valid backup code, and a wrong or empty password logs in. Backup codes then replace both factors instead of only the authenticator.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 8088444b-ebbc-4450-a304-056f52c66ea4 -->
<!-- LOCATIONS START
packages/features/auth/lib/next-auth-options.ts#L120-L157
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjU1YzkxOGQ0LTUyY2EtNGE5Mi05MDVkLTU4ODQyYjJkMzE4ZSIsImVuY3J5cHRpb25LZXkiOiJ2N2NIdjFUR2lzeDNDbmx1cnFfRzRLZUdaeWlPM0lQT3NXellDYU55cGRBIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjU1YzkxOGQ0LTUyY2EtNGE5Mi05MDVkLTU4ODQyYjJkMzE4ZSIsImVuY3J5cHRpb25LZXkiOiJ2N2NIdjFUR2lzeDNDbmx1cnFfRzRLZUdaeWlPM0lQT3NXellDYU55cGRBIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE2LCJjb21taXRTaGEiOiI5MWM5MDBmNjBiNzI5ZjEwMTQ4YTA5NDEyZjRlYjc3YzRjZDgxZjYwIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91c900f60b729f10148a09412f4eb77c4cd81f60. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Dismissing backup dialog skips enable
**Medium Severity**
<!-- DESCRIPTION START -->
Successful enable now only moves to the backup-codes step. `onEnable` runs solely from Close, so overlay or Escape closes the dialog without invalidating viewer data. The switch can stay off while 2FA is already on, and users who leave the page never see those one-time codes again.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: cc0d7309-4881-46be-8afd-8e87e5953d0b -->
<!-- LOCATIONS START
apps/web/components/settings/EnableTwoFactorModal.tsx#L133-L136
apps/web/components/settings/EnableTwoFactorModal.tsx#L265-L269
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`apps/web/components/settings/EnableTwoFactorModal.tsx#L265-L269`](https://github.com/drape-io/crbench-cursor-2026-09/blob/91c900f60b729f10148a09412f4eb77c4cd81f60/apps/web/components/settings/EnableTwoFactorModal.tsx#L265-L269)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmY0YmI3ZjY2LWFjY2YtNDE0MS1iNDgzLTcyNTM3NWI0Mzg0YSIsImVuY3J5cHRpb25LZXkiOiJua0RmVnAtOEo3Vm03cV9NRVI5eU9wejZoaGlqa1NMTDc0b2NmX1k0aVpnIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmY0YmI3ZjY2LWFjY2YtNDE0MS1iNDgzLTcyNTM3NWI0Mzg0YSIsImVuY3J5cHRpb25LZXkiOiJua0RmVnAtOEo3Vm03cV9NRVI5eU9wejZoaGlqa1NMTDc0b2NmX1k0aVpnIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE2LCJjb21taXRTaGEiOiI5MWM5MDBmNjBiNzI5ZjEwMTQ4YTA5NDEyZjRlYjc3YzRjZDgxZjYwIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91c900f60b729f10148a09412f4eb77c4cd81f60. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Backup code comparison is case-sensitive
**Medium Severity**
<!-- DESCRIPTION START -->
Codes are lowercase hex, but login and disable compare the submitted value only after stripping dashes, with no case folding. Typing or pasting an uppercase code, which the `XXXXX-XXXXX` placeholder encourages, fails as `IncorrectBackupCode` even when the code is valid.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 7e404476-93ef-409d-9f11-d86e6e540e2a -->
<!-- LOCATIONS START
packages/features/auth/lib/next-auth-options.ts#L143-L144
apps/web/pages/api/auth/two-factor/totp/disable.ts#L60-L61
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`apps/web/pages/api/auth/two-factor/totp/disable.ts#L60-L61`](https://github.com/drape-io/crbench-cursor-2026-09/blob/91c900f60b729f10148a09412f4eb77c4cd81f60/apps/web/pages/api/auth/two-factor/totp/disable.ts#L60-L61)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjA3Y2UxMGM5LWMzMTktNGUzMC05NjNlLWYxYTcyMjVhZjFjMiIsImVuY3J5cHRpb25LZXkiOiJlYWFnbm1VUTlxaUpQLXhGbkFoVFNXVzBvOXEzZURVT2hTN0trYXhQSjlRIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjA3Y2UxMGM5LWMzMTktNGUzMC05NjNlLWYxYTcyMjVhZjFjMiIsImVuY3J5cHRpb25LZXkiOiJlYWFnbm1VUTlxaUpQLXhGbkFoVFNXVzBvOXEzZURVT2hTN0trYXhQSjlRIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE2LCJjb21taXRTaGEiOiI5MWM5MDBmNjBiNzI5ZjEwMTQ4YTA5NDEyZjRlYjc3YzRjZDgxZjYwIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91c900f60b729f10148a09412f4eb77c4cd81f60. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Backup codes are not consumed atomically
**Medium Severity**
<!-- DESCRIPTION START -->
Login decrypts backup codes, finds a match, then writes that slot as `null` in a separate update with no transaction or compare-and-swap. Two concurrent sign-ins with the same code can both succeed before either write lands, so a one-time recovery code can be used twice.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 143be307-556f-49b3-9626-b7e304ed771e -->
<!-- LOCATIONS START
packages/features/auth/lib/next-auth-options.ts#L142-L156
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjRlZGM1YTBkLWQwY2MtNDBiOC05MDM4LTA4YTkzZDQ2ZjE1NiIsImVuY3J5cHRpb25LZXkiOiJIb2drTTQ1MDgxOFhZbnpqUlh6TXptVThOTXBPcE92UGs1aTBEZGxNdGNnIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjRlZGM1YTBkLWQwY2MtNDBiOC05MDM4LTA4YTkzZDQ2ZjE1NiIsImVuY3J5cHRpb25LZXkiOiJIb2drTTQ1MDgxOFhZbnpqUlh6TXptVThOTXBPcE92UGs1aTBEZGxNdGNnIiwiYnJhbmNoIjoidDItY2FsLWNvbS0xMDYwMCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE2LCJjb21taXRTaGEiOiI5MWM5MDBmNjBiNzI5ZjEwMTQ4YTA5NDEyZjRlYjc3YzRjZDgxZjYwIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91c900f60b729f10148a09412f4eb77c4cd81f60. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 4 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTpmNDAzNzE3MC01OWI2LTRlMGQtOTg1My1jZTQzNzQxZmIzMTEiLCJlbmNyeXB0aW9uS2V5IjoibVY1TF85MGZCMlJqQlZxU2s1Q2lpQVl5eW1FYmJFZlMzN1dIM0p3VFZnZyIsImJyYW5jaCI6InQyLWNhbC1jb20tMTA2MDAiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91c900f60b729f10148a09412f4eb77c4cd81f60. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✓ | off by one |
| d4 | low | ✓ | off by one |
| d5 | critical | ✓ | exact |
The new code checks only that req.body.backupCode is truthy and then calls replaceAll on it. A truthy non-string value, such as a number or an object, throws a TypeError, so the endpoint returns a 500 instead of IncorrectBackupCode. Only authenticated users can reach this endpoint, so the impact is low. [grounded: diff] [consensus 3/3: valid=3]
Before this change, a successful enable called onEnable() right away. Now onEnable() and resetState() run only from the Close button. Dismissing the dialog with Escape or an outside click goes through onOpenChange, which only toggles the dialog's open state. As a result, utils.viewer.me is not invalidated (so the switch still shows 2FA as off), and the step stays on DisplayBackupCodes when the dialog is reopened. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
**Uppercase backup codes are rejected**
Codes are stored as lowercase hex, but the input is only stripped of dashes, not lowercased or trimmed. The `XXXXX-XXXXX` placeholder invites uppercase entry, which then fails. Normalize input with `.trim().toLowerCase()` before matching here and in the disable endpoint.
```
packages/features/auth/lib/next-auth-options.ts:144 const index = backupCodes.indexOf(credentials.backupCode.replaceAll("-", ""));
apps/web/components/auth/BackupCode.tsx:21 placeholder="XXXXX-XXXXX"
apps/web/pages/api/auth/two-factor/totp/setup.ts:61 const backupCodes = Array.from(Array(10), () => crypto.randomBytes(5).toString("hex"));
```
**Non-string backupCode crashes disable endpoint**
`req.body.backupCode` comes straight from the JSON body. If it is a number, array or object, `replaceAll` throws and the request returns a 500 instead of an error saying the code is wrong. Check `typeof req.body.backupCode === "string"` before using it.
```
apps/web/pages/api/auth/two-factor/totp/disable.ts:48 if (user.twoFactorEnabled && req.body.backupCode) {
apps/web/pages/api/auth/two-factor/totp/disable.ts:49 if (!process.env.CALENDSO_ENCRYPTION_KEY) {
apps/web/pages/api/auth/two-factor/totp/disable.ts:50 console.error("Missing encryption key; cannot proceed with backup code login.");
apps/web/pages/api/auth/two-factor/totp/disable.ts:51 throw new Error(ErrorCode.InternalServerError);
apps/web/pages/api/auth/two-factor/totp/disable.ts:61 const index = backupCodes.indexOf(req.body.backupCode.replaceAll("-", ""));
```
**Backup code alone logs in without the password**
With any non-empty `totpCode` plus a valid `backupCode`, the password check is skipped and the backup-code branch never checks TOTP, so one backup code takes over the account. Always verify the password in the backup-code branch, or reject requests carrying both codes.
```
packages/features/auth/lib/next-auth-options.ts:131 if (user.twoFactorEnabled && credentials.backupCode) {
packages/features/auth/lib/next-auth-options.ts:132 if (!process.env.CALENDSO_ENCRYPTION_KEY) {
packages/features/auth/lib/next-auth-options.ts:133 console.error("Missing encryption key; cannot proceed with backup code login.");
packages/features/auth/lib/next-auth-options.ts:134 throw new Error(ErrorCode.InternalServerError);
packages/features/auth/lib/next-auth-options.ts:121 if (user.password && !credentials.totpCode) {
packages/features/auth/lib/next-auth-options.ts:122 if (!user.password) {
packages/features/auth/lib/next-auth-options.ts:123 throw new Error(ErrorCode.IncorrectEmailPassword);
packages/features/auth/lib/next-auth-options.ts:124 }
packages/features/auth/lib/next-auth-options.ts:125 const isCorrectPassword = await verifyPassword(credentials.password, user.password);
packages/features/auth/lib/next-auth-options.ts:126 if (!isCorrectPassword) {
```
**Same backup code works for concurrent logins**
The code is matched, then nulled in a separate unconditional update, so parallel logins with the same code both pass before either write lands. Make the update conditional on the old `backupCodes` ciphertext and fail if no row changed.
```
packages/features/auth/lib/next-auth-options.ts:139 const backupCodes = JSON.parse(
packages/features/auth/lib/next-auth-options.ts:140 symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY)
packages/features/auth/lib/next-auth-options.ts:141 );
packages/features/auth/lib/next-auth-options.ts:143 // check if user-supplied code matches one
packages/features/auth/lib/next-auth-options.ts:144 const index = backupCodes.indexOf(credentials.backupCode.replaceAll("-", ""));
packages/features/auth/lib/next-auth-options.ts:145 if (index === -1) throw new Error(ErrorCode.IncorrectBackupCode);
packages/features/auth/lib/next-auth-options.ts:147 // delete verified backup code and re-encrypt remaining
packages/features/auth/lib/next-auth-options.ts:148 backupCodes[index] = null;
packages/features/auth/lib/next-auth-options.ts:149 await prisma.user.update({
packages/features/auth/lib/next-auth-options.ts:150 where: {
```
**Dismissing backup-codes dialog leaves 2FA shown off**
Only the Close button calls `onEnable`. Escape or an outside click goes through `onOpenChange`, so the user isn't refreshed and the step stays on the backup codes, which show again on reopen. Call `onEnable` and `resetState` whenever the dialog closes from the backup-codes step.
```
apps/web/components/settings/EnableTwoFactorModal.tsx:132 const body = await response.json();
apps/web/components/settings/EnableTwoFactorModal.tsx:134 if (response.status === 200) {
apps/web/components/settings/EnableTwoFactorModal.tsx:135 setStep(SetupStep.DisplayBackupCodes);
apps/web/components/settings/EnableTwoFactorModal.tsx:136 return;
apps/web/pages/settings/security/two-factor-auth.tsx:64 onOpenChange={() => setEnableModalOpen(!enableModalOpen)}
apps/web/pages/settings/security/two-factor-auth.tsx:65 onEnable={() => {
apps/web/pages/settings/security/two-factor-auth.tsx:66 setEnableModalOpen(false);
apps/web/pages/settings/security/two-factor-auth.tsx:67 utils.viewer.me.invalidate();
apps/web/pages/settings/security/two-factor-auth.tsx:68 }}
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✓ | off by one |
| d5 | critical | ✓ | off by one |
Previously onEnable ran right after a successful enable. Now it only runs from the Close button. Escape or an overlay click only calls onOpenChange, which toggles the modal closed without invalidating the user query. The switch stays stale, and the always-mounted modal keeps step=DisplayBackupCodes. [grounded: diff] [consensus 3/3: valid=3]
Backup codes are only created in setup.ts, which refuses to run while 2FA is enabled. Existing 2FA users therefore have null backupCodes, and the new message tells them to generate codes in settings, which has no such action. [grounded: diff] [consensus 3/3: valid=3]
twoFactorLostAccess and the form values are only reset on a successful disable. Cancel calls onCancel only, and the modal stays mounted in two-factor-auth.tsx, so reopening it shows backup-code mode with the old input and error still there. [grounded: diff] [consensus 3/3: valid=3]
backupCode is only checked for truthiness. A truthy non-string in the JSON body, such as a number, throws a TypeError, so the server returns a 500 instead of a 400. [grounded: diff] [consensus 3/3: valid=3]
resetState only clears password, error and step. backupCodes, secret and dataUri stay in state, and the blob URL is only revoked when setup runs again, never on close or unmount. That is a small resource/data lingering issue. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
**Backup codes can be reused under concurrency**
The code is read, matched and written back in separate steps with no lock. Two simultaneous logins with the same code both pass, and two different codes used at once overwrite each other's removal. Consume the code with a conditional update on the value read; fail if no row matched.
```
packages/features/auth/lib/next-auth-options.ts:139 const backupCodes = JSON.parse(
packages/features/auth/lib/next-auth-options.ts:140 symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY)
packages/features/auth/lib/next-auth-options.ts:141 );
packages/features/auth/lib/next-auth-options.ts:143 // check if user-supplied code matches one
```
**Dismissing backup-codes dialog leaves UI stale**
2FA is already enabled once the TOTP is verified, but `onEnable()` only runs from the Close button. Escape or an overlay click only calls `onOpenChange`, so the page never refetches and the step stays on `DisplayBackupCodes`. Run `onEnable()` and reset state whenever the dialog closes at the backup-codes step.
```
apps/web/components/settings/EnableTwoFactorModal.tsx:134 if (response.status === 200) {
apps/web/components/settings/EnableTwoFactorModal.tsx:135 setStep(SetupStep.DisplayBackupCodes);
apps/web/components/settings/EnableTwoFactorModal.tsx:136 return;
apps/web/components/settings/EnableTwoFactorModal.tsx:137 }
apps/web/pages/settings/security/two-factor-auth.tsx:62 <EnableTwoFactorModal
apps/web/pages/settings/security/two-factor-auth.tsx:63 open={enableModalOpen}
apps/web/pages/settings/security/two-factor-auth.tsx:64 onOpenChange={() => setEnableModalOpen(!enableModalOpen)}
apps/web/pages/settings/security/two-factor-auth.tsx:65 onEnable={() => {
apps/web/pages/settings/security/two-factor-auth.tsx:66 setEnableModalOpen(false);
apps/web/pages/settings/security/two-factor-auth.tsx:67 utils.viewer.me.invalidate();
```
**Older 2FA users have no backup codes**
Pre-existing 2FA users have null backupCodes, and `setup.ts` won't run while 2FA is on. 'Lost access' always fails for them, and the message points to a nonexistent settings action. Add a regenerate option or tell users to re-enable 2FA.
```
apps/web/pages/api/auth/two-factor/totp/setup.ts:60 // generate backup codes with 10 character length
apps/web/pages/api/auth/two-factor/totp/setup.ts:61 const backupCodes = Array.from(Array(10), () => crypto.randomBytes(5).toString("hex"));
apps/web/pages/api/auth/two-factor/totp/setup.ts:63 await prisma.user.update({
apps/web/pages/api/auth/two-factor/totp/setup.ts:64 where: {
```
**Backup code login can skip the password check**
The password check is skipped whenever `credentials.totpCode` is non-empty. The new backup-code branch runs first and never validates `totpCode`, so a made-up `totpCode` plus a valid `backupCode` logs in with no password. Always verify the password unless the totpCode is validated; only accept backupCode after the password check.
```
packages/features/auth/lib/next-auth-options.ts:131 if (user.twoFactorEnabled && credentials.backupCode) {
packages/features/auth/lib/next-auth-options.ts:132 if (!process.env.CALENDSO_ENCRYPTION_KEY) {
packages/features/auth/lib/next-auth-options.ts:133 console.error("Missing encryption key; cannot proceed with backup code login.");
packages/features/auth/lib/next-auth-options.ts:134 throw new Error(ErrorCode.InternalServerError);
packages/features/auth/lib/next-auth-options.ts:121 if (user.password && !credentials.totpCode) {
```
**Disable dialog reopens in backup-code mode**
`twoFactorLostAccess` is only reset after a successful disable. Clicking Cancel or dismissing the dialog while in 'Lost access' mode keeps it set, and the entered backup code and error message are left in place. Reset `twoFactorLostAccess` and the form when the dialog is cancelled or closed.
```
apps/web/components/settings/DisableTwoFactorModal.tsx:38 const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false);
apps/web/components/settings/DisableTwoFactorModal.tsx:59 if (response.status === 200) {
apps/web/components/settings/DisableTwoFactorModal.tsx:60 setTwoFactorLostAccess(false);
apps/web/components/settings/DisableTwoFactorModal.tsx:61 resetForm();
```
**Non-string backupCode causes a 500**
`req.body.backupCode` is only checked for truthiness, then `.replaceAll` is called on it. A JSON body with a number, object or array there throws a TypeError. Check `typeof backupCode === "string"` and return a 400 otherwise.
```
apps/web/pages/api/auth/two-factor/totp/disable.ts:48 if (user.twoFactorEnabled && req.body.backupCode) {
apps/web/pages/api/auth/two-factor/totp/disable.ts:61 const index = backupCodes.indexOf(req.body.backupCode.replaceAll("-", ""));
```
**Backup codes and blob URL linger after closing**
`resetState` doesn't clear `backupCodes`, `secret` or `dataUri`, and the blob URL from `URL.createObjectURL` is revoked only on the next setup, never on close or unmount. Clear the codes and revoke the blob URL in resetState.
```
apps/web/components/settings/EnableTwoFactorModal.tsx:71 const resetState = () => {
apps/web/components/settings/EnableTwoFactorModal.tsx:72 setPassword("");
apps/web/components/settings/EnableTwoFactorModal.tsx:73 setErrorMessage(null);
apps/web/components/settings/EnableTwoFactorModal.tsx:74 setStep(SetupStep.ConfirmPassword);
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✓ | wrong severity |
| d5 | critical | ✓ | off by one |
The diff adds tabIndex={-1} to the show/hide button in the shared PasswordField, which takes it out of the Tab order everywhere PasswordField is used. Keyboard-only users can no longer reach the show/hide control. This is an accessibility regression introduced by this change. [grounded: diff] [consensus 5/5: valid=5]
raw comments (4)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Backup code bypasses password**
When a credentials request supplies both a nonempty `totpCode` and a valid `backupCode`, the TOTP value causes password verification to be skipped, while the backup-code branch takes precedence and never validates that TOTP value. The request therefore authenticates without the account password, reducing recovery login from two required credentials to one.
**How this was verified:** The password gate tests only whether `totpCode` is present, and the subsequent branch validates only `backupCode` whenever both fields are supplied.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Backup codes allow concurrent reuse**
Backup-code consumption performs a separate read, in-memory check, and update using only the user ID. Two concurrent login requests can read the same valid code before either update completes, both pass verification, and both receive authenticated sessions, violating the stated one-time-use guarantee. Consumption needs to be atomic, such as by conditionally updating the previously read value or otherwise serializing verification and removal.
**How this was verified:** Both requests can validate the same encrypted-code snapshot, and the update predicates only on the user ID without checking that the stored snapshot is unchanged.
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Password toggle blocks keyboard access**
Setting `tabIndex={-1}` removes the shared password-visibility button from sequential keyboard navigation. Keyboard-only users can no longer reach the show/hide control anywhere `PasswordField` is used. The button is already a non-submitting `type="button"`, so it should retain normal keyboard focus.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
<h3>Greptile Summary</h3>
This PR adds encrypted one-time backup codes to two-factor setup, login recovery, and 2FA disabling, together with the required schema migration and settings UI.
- Generates and presents ten downloadable or copyable backup codes during setup.
- Accepts and consumes backup codes during credential authentication.
- Adds backup-code recovery to login and disable-2FA flows.
- Contains authentication branching and atomic-consumption defects that must be addressed before merge.
<h3>Confidence Score: 1/5</h3>
This PR is not safe to merge until backup-code authentication requires the intended password check and consumes each code atomically.
A crafted combined-factor request can bypass password verification, and concurrent requests can authenticate more than once with the same one-time backup code; the modal also issues premature enable requests and misses state synchronization on standard dismissal.
**Files Needing Attention:** packages/features/auth/lib/next-auth-options.ts, apps/web/components/settings/EnableTwoFactorModal.tsx, packages/ui/components/form/inputs/Input.tsx
<details open><summary><h3>Security Review</h3></summary>
Two security issues were identified. A crafted credentials request can combine a dummy TOTP value with a valid backup code to bypass password verification, and backup-code consumption is non-atomic, allowing concurrent reuse of a nominally one-time code.
</details>
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| packages/features/auth/lib/next-auth-options.ts | Adds backup-code authentication and consumption, but permits password bypass with combined fields and non-atomic reuse under concurrent requests. |
| apps/web/components/settings/EnableTwoFactorModal.tsx | Adds backup-code presentation and export, but step controls submit premature enable requests and standard dismissal skips successful-state synchronization. |
| apps/web/pages/api/auth/two-factor/totp/setup.ts | Generates ten random backup codes and stores their encrypted representation alongside the pending TOTP secret. |
| apps/web/pages/api/auth/two-factor/totp/disable.ts | Allows a valid backup code to authorize disabling 2FA and clears all stored second-factor material afterward. |
| packages/prisma/schema.prisma | Adds a nullable encrypted backup-code storage field consistent with the accompanying PostgreSQL migration. |
| packages/ui/components/form/inputs/Input.tsx | Excludes the password-visibility control from keyboard navigation. |
</details>
<details open><summary><h3>Sequence Diagram</h3></summary>
```mermaid
sequenceDiagram
actor User
participant UI as Login UI
participant Auth as Credentials authorize
participant DB as User database
User->>UI: Submit password and second factor
UI->>Auth: password, totpCode, backupCode
Auth->>DB: Read user and encrypted backup codes
alt Backup code supplied
Auth->>Auth: Decrypt and verify backup code
Auth->>DB: Replace encrypted code list by user ID
Auth-->>UI: Authenticated session
else TOTP supplied
Auth->>Auth: Verify decrypted TOTP secret
Auth-->>UI: Authenticated session
end
```
</details>
<!-- greptile_failed_comments -->
<details><summary><h3>Comments Outside Diff (2)</h3></summary>
1. `apps/web/components/settings/EnableTwoFactorModal.tsx`, line 232-249 ([link](https://github.com/drape-io/crbench-greptile-2026-09/blob/6c888767b41944976e50217c23f775d2b276966b/apps/web/components/settings/EnableTwoFactorModal.tsx#L232-L249))
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Continue submits invalid enable requests**
These Continue controls are submit buttons inside the form handled by `handleEnable`. On the password step, clicking Continue invokes both `handleSetup` and `handleEnable(undefined)`; on the QR step, it submits another undefined code while moving to the OTP screen. These premature requests can show an incorrect-code error before the user has entered a code. Make the navigation and setup controls non-submit buttons, or place them in the form they are intended to submit.
2. `apps/web/components/settings/EnableTwoFactorModal.tsx`, line 165-166 ([link](https://github.com/drape-io/crbench-greptile-2026-09/blob/6c888767b41944976e50217c23f775d2b276966b/apps/web/components/settings/EnableTwoFactorModal.tsx#L165-L166))
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Dialog dismissal leaves stale state**
Successful TOTP confirmation persists `twoFactorEnabled`, but only the custom backup-code Close button calls `onEnable`. If the user dismisses the dialog through its standard backdrop or close control, the parent does not invalidate its settings query and can continue showing 2FA as disabled even though the server enabled it. The successful-state dismissal path should notify the parent through `onOpenChange` as well.
</details>
<!-- /greptile_failed_comments -->
<sub>Reviews (1): Last reviewed commit: ["Update apps/web/components/auth/BackupCo..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/6c888767b41944976e50217c23f775d2b276966b) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284210)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✗ | — |
| d5 | critical | ✗ | — |
The change replaced onEnable() with a step change, so onEnable/resetState now run only from the Close button. Closing with Escape or an outside click goes through onOpenChange, which only toggles enableModalOpen (two-factor-auth.tsx:64). The user data is never invalidated, so the page shows 2FA as off, and the step stays on DisplayBackupCodes. [grounded: diff] [consensus 3/3: valid=3]
This is the same issue as finding 0. Dismissing the dialog without the Close button skips both onEnable (no invalidate) and resetState, so the page is stale and the modal reopens on the backup-codes step. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
[P2] Closing the modal on the backup-codes step skips `onEnable`, so 2FA looks disabled even though it is on
apps/web/components/settings/EnableTwoFactorModal.tsx:135 After this change, a successful `handleEnable` no longer calls `onEnable()`. It only moves to `SetupStep.DisplayBackupCodes`, and `onEnable()` now runs only from the new "Close" button. 2FA is already enabled on the server at this point. If the user closes the dialog any other way (Escape, a click outside, or the dialog's own close control), only the parent's `onOpenChange` toggle runs (`apps/web/pages/settings/security/two-factor-auth.tsx:64`). That means `utils.viewer.me.invalidate()` is never called, and the settings page keeps showing the switch as unchecked with a "Disabled" badge while 2FA is actually on. `resetState()` also never runs, so the modal stays on the `DisplayBackupCodes` step: the next time the user clicks the switch, the dialog opens straight to the backup codes instead of the password step. Before this change, `onEnable()` ran as soon as the TOTP code was verified, so the page state was correct. A fix is to refresh the user data on enable success, or to call `onEnable`/`resetState` whenever the dialog closes while on this step.
[P2] Closing the backup-codes step without the Close button leaves the settings page stale ·
After a valid TOTP code, the server has already enabled 2FA, but the modal now moves to `SetupStep.DisplayBackupCodes` and calls `onEnable()` only from the new "Close" button. The dialog can also be dismissed with Escape, an outside click or the dialog's own close control. Those go through `onOpenChange`, which on `pages/settings/security/two-factor-auth.tsx` only toggles `enableModalOpen` and never calls `utils.viewer.me.invalidate()`. In that case the switch and badge still say 2FA is disabled even though it is enabled. `resetState()` is also skipped, so the next click on the stale switch reopens the enable modal on the backup-codes step with the old codes instead of starting over. Before this change, `onEnable()` ran right after a successful enable, so this didn't happen.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✗ | — |
| d5 | critical | ✗ | — |
Before this change, a successful enable called onEnable() right away. It now moves to the DisplayBackupCodes step instead, and only the Close button calls resetState()/onEnable(). Escape or an overlay click goes through onOpenChange, which in two-factor-auth.tsx only toggles enableModalOpen. So viewer.me is never invalidated, and step stays at DisplayBackupCodes when the dialog is reopened. [grounded: diff] [consensus 3/3: valid=3]
Same root cause as finding 0. Dismissing the dialog on the new backup-codes step bypasses onEnable/resetState, so the UI keeps showing 2FA as off and the step is never reset. The claim that the codes are lost is overstated: the component state keeps them, so reopening shows them again. The core failure still holds. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
[P2] Dismissing the backup-codes step skips `onEnable`
After the TOTP is verified, 2FA is already enabled server-side and the dialog moves to `DisplayBackupCodes`. Only the "Close" button calls `resetState()` and `onEnable()`. Escape or an overlay click goes through `onOpenChange`. In `pages/settings/security/two-factor-auth.tsx` that only toggles `enableModalOpen`, so `viewer.me` is never invalidated. The settings switch then keeps showing 2FA as off even though it is on. `step` also stays at `DisplayBackupCodes`, so reopening the dialog shows the old codes instead of the password step. The backup-codes step should be made non-dismissable, or `onOpenChange` should also run the `onEnable` and reset path.
[P2] Closing the dialog on the backup-codes step leaves the UI stale and the codes lost
The backup-codes step is reached only after the enable request has succeeded, so 2FA is already on in the database. The only paths that call `onEnable()` (which closes the modal and invalidates `viewer.me`) and `resetState()` are the Close button. The dialog can also be dismissed with Escape, an overlay click or the X button. Those go through `onOpenChange`, which in `two-factor-auth.tsx` only toggles `enableModalOpen`. In that case `viewer.me` is never invalidated, so the page keeps showing 2FA as disabled even though it is enabled. `step` also stays at `DisplayBackupCodes`, so the next open shows the old codes instead of the password step. The user never saw or saved the codes, and they are not shown again. The fix is to treat any close from this step like the Close button, or to block dismissal until the user has acknowledged the codes.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d3 | medium | ✗ | — |
| d4 | low | ✓ | wrong severity |
| d5 | critical | ✗ | — |
The promise returned by writeText is neither awaited nor caught, and the success toast always fires on the next line. A denied or unavailable clipboard therefore still reports success. [grounded: diff] [consensus 3/3: valid=3]
The visible Label has no htmlFor. InputField renders its own label with htmlFor={useId()}, but that label is empty because label="" is passed, and the explicit id="backup-code" replaces the input's id. So no label is associated with the input; only the placeholder is left as a fallback name. [grounded: tree apps/web/components/auth/BackupCode.tsx] [consensus 3/3: valid=3]
tabIndex={-1} takes the show/hide password button out of the tab order in the shared PasswordField, so keyboard-only users can no longer reach it. [grounded: diff] [consensus 3/3: valid=3]
Before this change, onEnable ran as soon as the enable call succeeded. Now it runs only from the backup-codes Close button. Closing the dialog through onOpenChange (Escape or clicking the backdrop) skips the viewer invalidation and the resetState call, so the settings page shows stale data and the modal keeps its old step. [grounded: diff] [consensus 3/3: valid=3]
raw comments (7)
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
2\. Failed copies still report success <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
The backup-code Copy handler starts <b><i>navigator.clipboard.writeText</i></b> without awaiting or handling its
promise and immediately emits a success toast. Missing clipboard support or a denied clipboard
permission therefore produces a rejection while telling the user that their recovery codes were
copied.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The backup-code copy action reports success before the asynchronous clipboard write has succeeded and does not handle rejection.
## Fix Focus Areas
- apps/web/components/settings/EnableTwoFactorModal.tsx[273-280]
## Recommended Fix
Make the click handler asynchronous, await `navigator.clipboard.writeText`, and show the success toast only after fulfillment. Handle unavailable clipboard support and rejected writes with an error toast.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
3\. Screen readers cannot name backup codes <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>BackupCode</i></b> renders its visible <b><i>Label</i></b> without an association and passes an empty label to
<b><i>TextField</i></b>. Because the explicit <b><i>id="backup-code"</i></b> also replaces the field's generated input ID,
assistive technology receives no useful accessible name in either the login or disable flow.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The shared backup-code input has a visible label but no programmatic label association, leaving it unnamed for assistive technology.
## Fix Focus Areas
- apps/web/components/auth/BackupCode.tsx[12-25]
## Recommended Fix
Provide `backup_code` as the `TextField` label and remove the separate unassociated label, or connect that label to the final input ID with `htmlFor`. Do not pass an empty field label.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
4\. Keyboard users cannot reveal passwords <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>PasswordField</i></b> now assigns <b><i>tabIndex={-1}</i></b> to its visibility toggle, removing the control from
sequential keyboard navigation. Keyboard-only users consequently cannot focus the eye button to
inspect passwords in every form using this shared component, including the modified two-factor setup
flow.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The password visibility control is removed from the keyboard tab order even though it remains an interactive button.
## Fix Focus Areas
- packages/ui/components/form/inputs/Input.tsx[44-52]
## Recommended Fix
Remove `tabIndex={-1}` so the native button remains keyboard-focusable. Preserve its `type="button"` behavior to prevent form submission.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. One backup code can authenticate twice <code>🐞 Bug</code> <code>⛨ Security</code>
<pre>
The backup-code branch in <b><i>authorize</i></b> validates a decrypted local snapshot, nulls the matched entry
in memory, and replaces the entire encrypted <b><i>backupCodes</i></b> value using an update conditioned only on
the user ID. Concurrent requests can therefore validate the same code before either write commits,
while requests using different codes can overwrite each other’s consumption updates and restore a
previously used code.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Backup-code validation and consumption use an unprotected, non-atomic read-modify-write sequence, allowing concurrent requests to authenticate with the same code or overwrite another request’s consumed-code update.
## Fix Focus Areas
- packages/features/auth/lib/next-auth-options.ts[139-156]
## Recommended Fix
Consume the backup code using an optimistic compare-and-swap or a serializable transaction. Make the database update conditional on the encrypted `backupCodes` value originally read, or lock the user row, and verify that exactly one row was updated. Only return the authenticated user after atomic consumption succeeds; if a concurrent write changed the stored value, reload and revalidate, retry as appropriate, or reject the request.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
5\. The settings page still shows two-factor off <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
On successful TOTP verification, <b><i>handleEnable</i></b> advances only to <b><i>DisplayBackupCodes</i></b> and defers
<b><i>onEnable</i></b>, the parent callback that closes the modal and invalidates the viewer query, until the
dedicated Close button is clicked. If the dialog is instead dismissed through Escape, the backdrop,
or its normal close control, the server has already enabled two-factor authentication while the
settings page retains its previous cached value and the still-mounted modal retains its step and
backup-code state when reopened.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
After the enable API succeeds, the modal postpones parent data invalidation and local-state cleanup until the dedicated backup-code Close button is clicked. Other supported dialog dismissal paths bypass that completion flow, leaving cached account data stale and preserving the modal's completed step and backup-code state, while cancellation before successful enablement must remain distinct.
## Fix Focus Areas
- apps/web/components/settings/EnableTwoFactorModal.tsx[134-170]
- apps/web/components/settings/EnableTwoFactorModal.tsx[261-270]
- apps/web/pages/settings/security/two-factor-auth.tsx[62-71]
## Recommended Fix
Track whether enablement has succeeded and wrap `onOpenChange` so every subsequent close path performs the same completion cleanup as the backup-code Close button while preserving the backup-code screen until dismissal. On closing a confirmed-enable modal, reset its local state and invalidate the viewer data; keep pre-success dismissal on the cancellation path, and separate query invalidation from the callback that closes the modal if necessary to avoid conflating those responsibilities.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<h3>PR Summary by Qodo</h3>
Add backup-code recovery for two-factor authentication
<code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Generate encrypted one-time backup codes when users enable two-factor authentication.
>• Allow backup-code login and 2FA disablement when authenticators are unavailable.
>• Display, copy, download, validate, and test backup-code recovery workflows.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
sequenceDiagram
actor U as User
participant UI as Auth UI
participant API as 2FA APIs
participant Auth as Auth Provider
participant Crypto as Crypto
participant DB as Users DB
U->>UI: Enable 2FA
UI->>API: Setup request
API->>Crypto: Generate and encrypt
API->>DB: Store codes
API-->>UI: Return backup codes
UI-->>U: Show copy download
U->>UI: Submit backup code
alt Login recovery
UI->>Auth: Sign-in credentials
Auth->>DB: Load encrypted codes
Auth->>Crypto: Decrypt and validate
Auth->>DB: Consume code
Auth-->>UI: Authenticated
else Disable 2FA
UI->>API: Disable request
API->>DB: Clear 2FA data
API-->>UI: Disabled
end
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Store keyed hashes</b></summary>
<dl>
<dd>
- ➕ Prevents recovery of usable codes from a database disclosure
- ➕ Retains the existing single-column persistence model
- ➖ Requires hashing each submitted code before comparison
- ➖ Still rewrites the complete code collection when consuming a code
</dd>
</dl>
</details>
<details>
<summary><b>2. Dedicated backup-code records</b></summary>
<dl>
<dd>
- ➕ Supports atomic one-time code consumption
- ➕ Allows hashed storage, regeneration, and future audit metadata
- ➖ Adds a table, relations, queries, and migration complexity
- ➖ Expands the implementation beyond the current compact 2FA model
</dd>
</dl>
</details>
>**Recommendation:** Prefer dedicated, keyed-hash backup-code records for robust one-time semantics and atomic consumption, especially because concurrent login attempts can validate the same encrypted-list entry before either update completes. The PR's encrypted JSON column is simpler and consistent with existing secret storage, but it trades away atomic consumption and exposes every remaining code if the encryption key is compromised.
</dd>
</dl>
</details>
<details>
<summary> Files changed (16) <code> +280 / -36 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (10) <code> +243 / -35 </code></summary>
<dl>
<dd>
<details>
<summary>BackupCode.tsx<code>Add reusable backup-code form input</code> <code>+29/-0</code></summary>
<br/>
>Add reusable backup-code form input
>
><pre>
>• Introduces a localized, form-connected input for formatted 10-character backup codes. The component supports centered and inline layouts for login and settings workflows.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-9685941f53518b52a0df53e19f02b8fc3c9b732eabc97565129b1e42f00fc1d2'>apps/web/components/auth/BackupCode.tsx</a>
</details>
<details>
<summary>TwoFactor.tsx<code>Make TOTP autofocus configurable</code> <code>+2/-2</code></summary>
<br/>
>Make TOTP autofocus configurable
>
><pre>
>• Adds an 'autoFocus' prop so embedded TOTP inputs do not unexpectedly steal focus from password fields or modal controls.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-ce02551a7a34dec5e997c2d68e59caccc5f2a571c6bd13b52cd29497414d56ea'>apps/web/components/auth/TwoFactor.tsx</a>
</details>
<details>
<summary>DisableTwoFactorModal.tsx<code>Support disabling 2FA with a backup code</code> <code>+35/-7</code></summary>
<br/>
>Support disabling 2FA with a backup code
>
><pre>
>• Adds a lost-access mode that switches between TOTP and backup-code verification. It submits the selected credential, resets stale form state, and displays backup-code-specific errors.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-3dc1a03d1e8aa911b248498e0ff0b0c68d99525653778c973f7d108cd48c35f8'>apps/web/components/settings/DisableTwoFactorModal.tsx</a>
</details>
<details>
<summary>EnableTwoFactorModal.tsx<code>Present backup codes after enabling 2FA</code> <code>+76/-7</code></summary>
<br/>
>Present backup codes after enabling 2FA
>
><pre>
>• Extends setup with a final backup-code screen offering copy and text-file download actions. It also resets modal state on completion or cancellation and uses the shared password field.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-bebe4bf2a7ced0af5675743bb75af731fc763e2a2503b1162f771c5f3af5a333'>apps/web/components/settings/EnableTwoFactorModal.tsx</a>
</details>
<details>
<summary>TwoFactorAuthAPI.ts<code>Send backup codes to the disable endpoint</code> <code>+2/-2</code></summary>
<br/>
>Send backup codes to the disable endpoint
>
><pre>
>• Extends the 2FA disable client request with an optional form-provided backup code alongside the password and TOTP code.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-55ea85ecf13ab94c7f5038e743296e2b4ec529a5e2457a0753a9dd60b9d28ac2'>apps/web/components/settings/TwoFactorAuthAPI.ts</a>
</details>
<details>
<summary>disable.ts<code>Validate backup codes when disabling 2FA</code> <code>+25/-2</code></summary>
<br/>
>Validate backup codes when disabling 2FA
>
><pre>
>• Decrypts and validates a submitted backup code as an alternative to TOTP. Successful disablement now clears both the TOTP secret and all stored backup codes.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-ffbb87c6cac30c30d633f69ee0a53efcddd5a5fd93d44a8a811cceb761b59077'>apps/web/pages/api/auth/two-factor/totp/disable.ts</a>
</details>
<details>
<summary>setup.ts<code>Generate and persist encrypted backup codes</code> <code>+6/-1</code></summary>
<br/>
>Generate and persist encrypted backup codes
>
><pre>
>• Generates ten cryptographically random backup codes during 2FA setup. The endpoint encrypts them for persistence and returns the original codes for one-time presentation.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-bf921afcefc3ba7dfcfc8185c854103230a28a1295086f30951c45fed2a327f4'>apps/web/pages/api/auth/two-factor/totp/setup.ts</a>
</details>
<details>
<summary>login.tsx<code>Add backup-code login recovery</code> <code>+36/-12</code></summary>
<br/>
>Add backup-code login recovery
>
><pre>
>• Adds a lost-access path that replaces the TOTP input with the reusable backup-code input. It submits backup-code credentials and handles invalid or unavailable code errors.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-d375d403d178baa1229f926b7d2de762c1e2e7e4e2c013834270e1f961ff63c1'>apps/web/pages/auth/login.tsx</a>
</details>
<details>
<summary>ErrorCode.ts<code>Define backup-code authentication errors</code> <code>+2/-0</code></summary>
<br/>
>Define backup-code authentication errors
>
><pre>
>• Adds shared error identifiers for incorrect backup codes and accounts without generated backup codes.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-af78d62e2bea120727a0a2c96f80d5b19079c28993e11419c6359d785f44eef2'>packages/features/auth/lib/ErrorCode.ts</a>
</details>
<details>
<summary>next-auth-options.ts<code>Authenticate and consume backup codes</code> <code>+30/-2</code></summary>
<br/>
>Authenticate and consume backup codes
>
><pre>
>• Extends credential authentication to accept encrypted backup codes as an alternative second factor. A successfully matched code is invalidated and the remaining collection is re-encrypted.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-7ef688f60d6f93fa0eee89348a1e0a565c362ad1e278f540849505dc495d815b'>packages/features/auth/lib/next-auth-options.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Bug fix (1) <code> +5 / -1 </code></summary>
<dl>
<dd>
<details>
<summary>Input.tsx<code>Remove password visibility control from tab order</code> <code>+5/-1</code></summary>
<br/>
>Remove password visibility control from tab order
>
><pre>
>• Sets the password visibility toggle to 'tabIndex={-1}', preventing it from interrupting keyboard focus progression through authentication forms.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-81bcd4a4451f9e94b8bf86f92909396dd2dd9dd0598ae8ff185b7d0a29f9320c'>packages/ui/components/form/inputs/Input.tsx</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (2) <code> +22 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>login.2fa.e2e.ts<code>Exercise backup-code copy and download actions</code> <code>+21/-0</code></summary>
<br/>
>Exercise backup-code copy and download actions
>
><pre>
>• Extends the 2FA enablement test to verify the backup-code download filename, copy confirmation toast, and completion action. Follow-up coverage for login and disablement is noted.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-de1b3aba5dd9a73281afdde333f219f5b2306345654c658b99d248c445af6ca7'>apps/web/playwright/login.2fa.e2e.ts</a>
</details>
<details>
<summary>builder.ts<code>Include backup codes in user fixtures</code> <code>+1/-0</code></summary>
<br/>
>Include backup codes in user fixtures
>
><pre>
>• Initializes the new nullable backup-code field in generated user test data.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-2c46fed0f1530feca8413d53dfc710c023bcf310af0f0e23ef285c852192d6cd'>packages/lib/test/builder.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Documentation (1) <code> +7 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>common.json<code>Add English backup-code translations</code> <code>+7/-0</code></summary>
<br/>
>Add English backup-code translations
>
><pre>
>• Adds labels, instructions, success feedback, lost-access text, and validation errors for backup-code workflows.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-57de4b8e5231f1d699891d98b0381d56e9e24537b0ca5420d1fba4f0597370bc'>apps/web/public/static/locales/en/common.json</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Other (2) <code> +3 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>migration.sql<code>Add backup-code storage column</code> <code>+2/-0</code></summary>
<br/>
>Add backup-code storage column
>
><pre>
>• Adds a nullable text column to the users table for encrypted backup-code collections.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-c527544914b6811a3002daaed212a6fcd36415f0a8f7a960719b66e5c6ff6b9a'>packages/prisma/migrations/20230804153419_add_backup_codes/migration.sql</a>
</details>
<details>
<summary>schema.prisma<code>Model backup-code persistence</code> <code>+1/-0</code></summary>
<br/>
>Model backup-code persistence
>
><pre>
>• Adds the nullable 'backupCodes' property to the Prisma user model.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-56fa4d384ba6fb94b130e9eb42c5cad00734b025ebd6c197f76873469725ae87'>packages/prisma/schema.prisma</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (5)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<br/>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
<details>
<summary> 1. One backup code can authenticate twice <code>🐞 Bug</code> <code>⛨ Security</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The backup-code branch in <b><i>authorize</i></b> validates a decrypted local snapshot, nulls the matched entry
>in memory, and replaces the entire encrypted <b><i>backupCodes</i></b> value using an update conditioned only on
>the user ID. Concurrent requests can therefore validate the same code before either write commits,
>while requests using different codes can overwrite each other’s consumption updates and restore a
>previously used code.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/features/auth/lib/next-auth-options.ts[R139-144]](https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-7ef688f60d6f93fa0eee89348a1e0a565c362ad1e278f540849505dc495d815bR139-R144)</code>
>
>```diff
>+ const backupCodes = JSON.parse(
>+ symmetricDecrypt(user.backupCodes, process.env.CALENDSO_ENCRYPTION_KEY)
>+ );
>+
>+ // check if user-supplied code matches one
>+ const index = backupCodes.indexOf(credentials.backupCode.replaceAll("-", ""));
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The user record and encrypted backup-code list are loaded before validation, after which the branch
>modifies the decrypted array locally and writes the complete encrypted array using only the user ID.
>Because there is no transaction, lock, version check, or condition matching the previously read
><b><i>backupCodes</i></b> ciphertext, multiple requests can validate the same stale snapshot before either
>update completes, and a later full-list write can replace an earlier consumption update.
></pre>
>
> <code>[packages/features/auth/lib/next-auth-options.ts[73-102]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/packages/features/auth/lib/next-auth-options.ts/#L73-L102)</code>
> <code>[packages/features/auth/lib/next-auth-options.ts[139-156]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/packages/features/auth/lib/next-auth-options.ts/#L139-L156)</code>
> <code>[apps/web/pages/api/auth/two-factor/totp/setup.ts[60-78]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/pages/api/auth/two-factor/totp/setup.ts/#L60-L78)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Backup-code validation and consumption use an unprotected, non-atomic read-modify-write sequence, allowing concurrent requests to authenticate with the same code or overwrite another request’s consumed-code update.
>
>## Fix Focus Areas
>- packages/features/auth/lib/next-auth-options.ts[139-156]
>
>## Recommended Fix
>Consume the backup code using an optimistic compare-and-swap or a serializable transaction. Make the database update conditional on the encrypted `backupCodes` value originally read, or lock the user row, and verify that exactly one row was updated. Only return the authenticated user after atomic consumption succeeds; if a concurrent write changed the stored value, reload and revalidate, retry as appropriate, or reject the request.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 2. Failed copies still report success <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The backup-code Copy handler starts <b><i>navigator.clipboard.writeText</i></b> without awaiting or handling its
>promise and immediately emits a success toast. Missing clipboard support or a denied clipboard
>permission therefore produces a rejection while telling the user that their recovery codes were
>copied.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[apps/web/components/settings/EnableTwoFactorModal.tsx[R276-279]](https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-bebe4bf2a7ced0af5675743bb75af731fc763e2a2503b1162f771c5f3af5a333R276-R279)</code>
>
>```diff
>+ onClick={(e) => {
>+ e.preventDefault();
>+ navigator.clipboard.writeText(backupCodes.map(formatBackupCode).join("\n"));
>+ showToast(t("backup_codes_copied"), "success");
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The clipboard promise is neither awaited nor returned, and the success toast executes
>unconditionally on the next line. No failure branch exists around the operation.
></pre>
>
> <code>[apps/web/components/settings/EnableTwoFactorModal.tsx[273-280]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/settings/EnableTwoFactorModal.tsx/#L273-L280)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The backup-code copy action reports success before the asynchronous clipboard write has succeeded and does not handle rejection.
>
>## Fix Focus Areas
>- apps/web/components/settings/EnableTwoFactorModal.tsx[273-280]
>
>## Recommended Fix
>Make the click handler asynchronous, await `navigator.clipboard.writeText`, and show the success toast only after fulfillment. Handle unavailable clipboard support and rejected writes with an error toast.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 3. Screen readers cannot name backup codes <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>BackupCode</i></b> renders its visible <b><i>Label</i></b> without an association and passes an empty label to
><b><i>TextField</i></b>. Because the explicit <b><i>id="backup-code"</i></b> also replaces the field's generated input ID,
>assistive technology receives no useful accessible name in either the login or disable flow.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[apps/web/components/auth/BackupCode.tsx[R17-20]](https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-9685941f53518b52a0df53e19f02b8fc3c9b732eabc97565129b1e42f00fc1d2R17-R20)</code>
>
>```diff
>+ <TextField
>+ id="backup-code"
>+ label=""
>+ defaultValue=""
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The standalone label has no <b><i>htmlFor</i></b>, while the field explicitly receives an empty label and an
>overriding ID. The field implementation builds its label association around a generated ID before
>spreading the explicit input properties.
></pre>
>
> <code>[apps/web/components/auth/BackupCode.tsx[12-25]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/auth/BackupCode.tsx/#L12-L25)</code>
> <code>[packages/ui/components/form/inputs/TextField.tsx[53-64]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/packages/ui/components/form/inputs/TextField.tsx/#L53-L64)</code>
> <code>[packages/ui/components/form/inputs/TextField.tsx[152-165]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/packages/ui/components/form/inputs/TextField.tsx/#L152-L165)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The shared backup-code input has a visible label but no programmatic label association, leaving it unnamed for assistive technology.
>
>## Fix Focus Areas
>- apps/web/components/auth/BackupCode.tsx[12-25]
>
>## Recommended Fix
>Provide `backup_code` as the `TextField` label and remove the separate unassociated label, or connect that label to the final input ID with `htmlFor`. Do not pass an empty field label.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 4. Keyboard users cannot reveal passwords <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>PasswordField</i></b> now assigns <b><i>tabIndex={-1}</i></b> to its visibility toggle, removing the control from
>sequential keyboard navigation. Keyboard-only users consequently cannot focus the eye button to
>inspect passwords in every form using this shared component, including the modified two-factor setup
>flow.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/ui/components/form/inputs/Input.tsx[R47-50]](https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-81bcd4a4451f9e94b8bf86f92909396dd2dd9dd0598ae8ff185b7d0a29f9320cR47-R50)</code>
>
>```diff
>+ <button
>+ className="text-emphasis h-9"
>+ tabIndex={-1}
>+ type="button"
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The newly added negative tab index explicitly excludes the visibility button from normal Tab
>navigation. The same shared <b><i>PasswordField</i></b> is now used by the two-factor enable modal and is also
>used throughout other password forms.
></pre>
>
> <code>[packages/ui/components/form/inputs/Input.tsx[44-52]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/packages/ui/components/form/inputs/Input.tsx/#L44-L52)</code>
> <code>[apps/web/components/settings/EnableTwoFactorModal.tsx[171-179]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/settings/EnableTwoFactorModal.tsx/#L171-L179)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The password visibility control is removed from the keyboard tab order even though it remains an interactive button.
>
>## Fix Focus Areas
>- packages/ui/components/form/inputs/Input.tsx[44-52]
>
>## Recommended Fix
>Remove `tabIndex={-1}` so the native button remains keyboard-focusable. Preserve its `type="button"` behavior to prevent form submission.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details><summary><ins><strong>View medium (1)</strong></ins></summary><br/>
<details>
<summary> 5. The settings page still shows two-factor off <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>On successful TOTP verification, <b><i>handleEnable</i></b> advances only to <b><i>DisplayBackupCodes</i></b> and defers
><b><i>onEnable</i></b>, the parent callback that closes the modal and invalidates the viewer query, until the
>dedicated Close button is clicked. If the dialog is instead dismissed through Escape, the backdrop,
>or its normal close control, the server has already enabled two-factor authentication while the
>settings page retains its previous cached value and the still-mounted modal retains its step and
>backup-code state when reopened.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[apps/web/components/settings/EnableTwoFactorModal.tsx[R134-136]](https://github.com/drape-io/crbench-qodo-2026-09/pull/16/files#diff-bebe4bf2a7ced0af5675743bb75af731fc763e2a2503b1162f771c5f3af5a333R134-R136)</code>
>
>```diff
> if (response.status === 200) {
>- onEnable();
>+ setStep(SetupStep.DisplayBackupCodes);
> return;
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The enable API persists <b><i>twoFactorEnabled: true</i></b> before returning, but its success handler only
>changes the modal's local step. The parent refresh through <b><i>onEnable</i></b> is invoked solely by the
>backup-code Close button, while other dismissal events flow through the controlled dialog's
>open-change callback, which only toggles visibility; because the modal remains mounted, those paths
>neither invalidate the account data nor reset the retained step and backup-code state.
></pre>
>
> <code>[apps/web/pages/api/auth/two-factor/totp/enable.ts[51-65]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/pages/api/auth/two-factor/totp/enable.ts/#L51-L65)</code>
> <code>[apps/web/components/settings/EnableTwoFactorModal.tsx[130-136]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/settings/EnableTwoFactorModal.tsx/#L130-L136)</code>
> <code>[apps/web/components/settings/EnableTwoFactorModal.tsx[263-270]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/settings/EnableTwoFactorModal.tsx/#L263-L270)</code>
> <code>[apps/web/pages/settings/security/two-factor-auth.tsx[62-71]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/pages/settings/security/two-factor-auth.tsx/#L62-L71)</code>
> <code>[packages/ui/components/dialog/Dialog.tsx[27-70]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/packages/ui/components/dialog/Dialog.tsx/#L27-L70)</code>
> <code>[apps/web/components/settings/EnableTwoFactorModal.tsx[131-137]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/settings/EnableTwoFactorModal.tsx/#L131-L137)</code>
> <code>[apps/web/components/settings/EnableTwoFactorModal.tsx[166-170]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/components/settings/EnableTwoFactorModal.tsx/#L166-L170)</code>
> <code>[apps/web/pages/settings/security/two-factor-auth.tsx[62-72]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4ac47869ec44e28ea0b467788ac52067d7689375/apps/web/pages/settings/security/two-factor-auth.tsx/#L62-L72)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>After the enable API succeeds, the modal postpones parent data invalidation and local-state cleanup until the dedicated backup-code Close button is clicked. Other supported dialog dismissal paths bypass that completion flow, leaving cached account data stale and preserving the modal's completed step and backup-code state, while cancellation before successful enablement must remain distinct.
>
>## Fix Focus Areas
>- apps/web/components/settings/EnableTwoFactorModal.tsx[134-170]
>- apps/web/components/settings/EnableTwoFactorModal.tsx[261-270]
>- apps/web/pages/settings/security/two-factor-auth.tsx[62-71]
>
>## Recommended Fix
>Track whether enablement has succeeded and wrap `onOpenChange` so every subsequent close path performs the same completion cleanup as the backup-code Close button while preserving the backup-code screen until dismissal. On closing a confirmed-enable modal, reset its local state and invalidate the viewer data; keep pre-success dismissal on the cancellation path, and separate query invalidation from the callback that closes the modal if necessary to avoid conflating those responsibilities.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-context:start -->
<details><summary><strong>Context sources</strong></summary>
<div>Review mode: <code>🧠 Deep</code>: This introduces security-sensitive backup-code authentication and 2FA flows across many independent frontend, API, persistence, and session paths, creating a dense set of easy-to-miss correctness and security defects.</div>
<!-- qodo-context:end -->
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/4ac47869ec44e28ea0b467788ac52067d7689375 -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>