Skip to content

Require an emailed magic code before turning on 2FA - #107174

Open
neil-marcellini wants to merge 11 commits into
mainfrom
neil/2fa-email-code
Open

neil-marcellini wants to merge 11 commits into
mainfrom
neil/2fa-email-code

Conversation

@neil-marcellini

@neil-marcellini neil-marcellini commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

(Neil's AI agent)

Before 2FA turns on, NewDot now asks for a security code emailed to the account. Someone holding only a stolen session token can't finish 2FA setup with their own authenticator app and lock the owner out.

How the setup changes (Settings > Security, and the setup a domain forces on its members). It now has three steps:

  1. Security code: it emails a security code (ResendValidateCode with the new enable_two_factor_auth reason) and shows the existing security code form. The secret and recovery codes are only created after the user enters it. The server checks it on the verify step, together with the authenticator code. The code is kept in memory only, never in the URL or in stored Onyx data.
  2. Recovery codes: as before.
  3. Verify: the QR code and authenticator code input show as before. TwoFactorAuth_Validate sends both codes (twoFactorAuthCode + new validateCode). The security code comes before the authenticator code because authenticator codes expire after about a minute, and checking email can take longer.

Errors:

  • Wrong authenticator code: same error as today, and the security code is kept, since the server checks the authenticator code first and doesn't use up the security code.
  • Wrong or expired security code (jsonCode 451): the verify step shows the security code form again with "That security code didn't work, so we sent you a new one." and a new code is emailed. The form also shows there if the app reloaded and lost the code from step 1.

Required setup fix (the bug is also on main): the setup a domain forces on its members got stuck on the verify step after a correct authenticator code. For a new account, the TwoFactorAuth_Validate response follows a server update the app hasn't received yet, so the app holds the response until it fetches that update. The required setup clears Onyx right away, which erased the held response, so the secret key was never removed and the verify page never moved to the success screen. It now removes the secret key and recovery codes before clearing Onyx.

enable_two_factor_auth isn't in expensify-common yet, so it lives in App's CONST, the same way APPROVE_DIGITAL_WALLET_VALIDATE_CODE_REASON does.

Deploy order: Auth PR 26820 must deploy first, because Auth rejects unknown reason codes. Web-Expensify PR 58701, which passes validateCode through to Auth and returns 451 for a bad security code, must also be on production. Until Auth requires the code, a missing code is still accepted, so older app versions keep working. Related Expensify Classic PR: https://github.com/Expensify/Mobile-Expensify/pull/14238

Fixed Issues

$ https://github.com/Expensify/Expensify/issues/700473
PROPOSAL:

Tests

(Neil's AI agent)

Automated: npx jest tests/actions/SessionTest.ts tests/ui/BaseTwoFactorAuthFormTest.tsx tests/ui/DynamicTwoFactorAuthPageTest.tsx. The new tests check that both codes are sent, that only a 451 response asks for a new security code, that the setup form passes the security code through, that the first step asks for the security code before the recovery codes are created, and that the required setup removes the secret key even when the validate response is held behind a missing update. They fail without the change.

Manual (needs the Auth and Web-Expensify changes on your backend):

  1. Sign in to an account without 2FA.
  2. Go to Settings > Security > Two-factor authentication.
  3. Confirm "Step 1 of 3: Security code" shows first and a security code email arrives.
  4. Enter a wrong security code and tap Next.
  5. Confirm "Step 2 of 3: Recovery codes" shows, then copy the recovery codes and tap Download codes.
  6. Scan the QR code, enter the authenticator code and tap Next.
  7. Confirm the security code form shows again with "That security code didn't work, so we sent you a new one." and a new email arrives.
  8. Enter the new security code and tap Next.
  9. Enter a wrong authenticator code and tap Next.
  10. Confirm the authenticator code error shows and you stay on the QR code screen.
  11. Enter a fresh, correct authenticator code and tap Next.
  12. Confirm 2FA turns on and the success screen shows.
  13. Repeat with an account in a domain that requires 2FA, signing in to trigger the required setup, and confirm it starts with the security code step and finishes.

See above.

Screenshots

Steps 2-3: Settings > Security > Two-factor authentication opens on "Step 1 of 3: Security code", and the security code is emailed.

01-step1

Steps 4-5: after entering a wrong security code (111111), "Step 2 of 3: Recovery codes" shows.

02-step2

Step 6: "Step 3 of 3: Verify" with the QR code and secret key.

03-step3

Step 7: after a correct authenticator code, the server rejects the wrong security code (451), so the security code form shows "That security code didn't work, so we sent you a new one." under the code input, and a new code is emailed.

05-security-code-rejected

Step 8: after entering the new security code, the QR code screen shows again.

06-after-security-code

Steps 9-10: a wrong authenticator code shows the invalid code error and stays on the QR code screen.

07-wrong-authenticator

Steps 11-12: a correct authenticator code turns on 2FA and the success screen shows.

08-success

Step 13: a new member of a domain that requires 2FA signs in and gets the "Two-factor authentication required" prompt.

09-domain-signin

Step 13: tapping Enable starts the required setup on "Step 1 of 3: Security code".

10-domain-step1

Step 13: after the security code and recovery codes, "Step 3 of 3: Verify" shows. The "Please enter your two-factor authentication code" error on arrival also shows on main.

11-domain-step3

Step 13: after a correct authenticator code, 2FA turns on and the success screen shows. I ran it on two new accounts and both finished. Before the fix it got stuck on Step 3 on all 4 runs.

16-required-setup-success

Step 13 on main, for comparison: the required setup gets stuck on "Step 2 of 2: Verify" after a successful validate. This PR fixes that.

14-main-domain-after-validate

Offline: going offline on the security code step shows the offline blocking view.

15-offline

Offline tests

(Neil's AI agent)

  1. Start 2FA setup and reach the security code step.
  2. Go offline.
  3. Confirm the page shows the offline blocking view, as the rest of the 2FA setup already does.

QA Steps

(Neil's AI agent)

Same as the manual tests above, on staging after the Auth and Web-Expensify changes are on production.

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified any copy / text that was added to the app is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

Adds the enable_two_factor_auth validate code reason, sends validateCode
on TwoFactorAuth_Validate, and reports a rejected magic code (451) so the
caller can ask for a new one.
The verify step first emails a magic code and collects it, then shows the
QR code and authenticator code input, and sends both codes together. If the
server rejects the magic code, the step emails a new one and asks again.
@neil-marcellini
neil-marcellini marked this pull request as ready for review November 17, 2026 21:27
@neil-marcellini
neil-marcellini requested review from a team as code owners November 17, 2026 21:27
@expensify-chore-bot
expensify-chore-bot Bot requested review from parasharrajat and removed request for a team November 17, 2026 21:27
@expensify-chore-bot

Copy link
Copy Markdown

@parasharrajat Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T21:41:24.632943Z 6b79a95 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@expensify-chore-bot
expensify-chore-bot Bot requested review from joekaufmanexpensify and removed request for a team November 17, 2026 21:28
@OSBotify

Copy link
Copy Markdown
Contributor

🦜 Polyglot Parrot! 🦜

Squawk! Looks like you added some shiny new English strings. Allow me to parrot them back to you in other tongues:

View the translation diff
diff --git a/src/languages/de.ts b/src/languages/de.ts
index 64b36dfe..6a8caa77 100644
--- a/src/languages/de.ts
+++ b/src/languages/de.ts
@@ -2732,8 +2732,8 @@ const translations: TranslationDeepObject<typeof en> = {
         errorStepCodes: 'Bitte kopiere oder lade die Codes herunter, bevor du fortfährst',
         stepVerify: 'Bestätigen',
         enterSecurityCode: (contactMethod: string) =>
-            `Bitte geben Sie den Sicherheitscode ein, der an ${contactMethod} gesendet wurde, um die Zwei-Faktor-Authentifizierung einzurichten. Er sollte innerhalb ein bis zwei Minuten ankommen.`,
-        securityCodeRejected: 'Dieser Sicherheitscode hat nicht funktioniert, daher haben wir Ihnen einen neuen gesendet.',
+            `Bitte geben Sie den Sicherheitscode ein, der an ${contactMethod} gesendet wurde, um die Zwei-Faktor-Authentifizierung einzurichten. Er sollte innerhalb von ein bis zwei Minuten ankommen.`,
+        securityCodeRejected: 'Dieser Sicherheitscode hat nicht funktioniert, daher haben wir Ihnen einen neuen geschickt.',
         scanCode: 'Scanne den QR-Code mit deinem',
         authenticatorApp: 'Authentifizierungs-App',
         addKey: 'Oder füge diesen geheimen Schlüssel zu deiner Authentifizierungs-App hinzu:',
diff --git a/src/languages/el.ts b/src/languages/el.ts
index 6c5dc613..52a5da6f 100644
--- a/src/languages/el.ts
+++ b/src/languages/el.ts
@@ -2789,8 +2789,8 @@ const translations: TranslationDeepObject<typeof en> = {
         errorStepCodes: 'Παρακαλούμε αντιγράψτε ή κατεβάστε τους κωδικούς πριν συνεχίσετε',
         stepVerify: 'Επιβεβαίωση',
         enterSecurityCode: (contactMethod: string) =>
-            `Παρακαλούμε εισαγάγετε τον κωδικό ασφαλείας που στάλθηκε στο ${contactMethod} για να ρυθμίσετε τον έλεγχο ταυτότητας δύο παραγόντων. Θα πρέπει να φτάσει μέσα σε ένα-δύο λεπτά.`,
-        securityCodeRejected: 'Αυτός ο κωδικός ασφαλείας δεν λειτούργησε, γι’ αυτό σας στείλαμε έναν νέο.',
+            `Παρακαλούμε εισαγάγετε τον κωδικό ασφαλείας που στάλθηκε στο ${contactMethod} για να ρυθμίσετε τον έλεγχο ταυτότητας δύο παραγόντων. Θα πρέπει να φτάσει μέσα σε ένα-δυο λεπτά.`,
+        securityCodeRejected: 'Αυτός ο κωδικός ασφαλείας δεν λειτούργησε, οπότε σας στείλαμε έναν νέο.',
         scanCode: 'Σαρώστε τον κωδικό QR χρησιμοποιώντας το',
         authenticatorApp: 'εφαρμογή ελέγχου ταυτότητας',
         addKey: 'Ή προσθέστε αυτό το μυστικό κλειδί στην εφαρμογή ελέγχου ταυτότητάς σας:',
diff --git a/src/languages/es.ts b/src/languages/es.ts
index 93ee3508..62626b6a 100644
--- a/src/languages/es.ts
+++ b/src/languages/es.ts
@@ -2713,7 +2713,7 @@ const translations: TranslationDeepObject<typeof en> = {
         stepVerify: 'Verificar',
         enterSecurityCode: (contactMethod: string) =>
             `Introduce el código de seguridad enviado a ${contactMethod} para configurar la autenticación de dos factores. Debería llegar en uno o dos minutos.`,
-        securityCodeRejected: 'Ese código de seguridad no funcionó, así que te enviamos uno nuevo.',
+        securityCodeRejected: 'Ese código de seguridad no funcionó, así que te hemos enviado uno nuevo.',
         scanCode: 'Escanea el código QR usando tu',
         authenticatorApp: 'aplicación de autenticación',
         addKey: 'O añade esta clave secreta a tu aplicación de autenticación:',
diff --git a/src/languages/ja.ts b/src/languages/ja.ts
index 4f80f3f2..61c84ebd 100644
--- a/src/languages/ja.ts
+++ b/src/languages/ja.ts
@@ -2703,8 +2703,8 @@ const translations: TranslationDeepObject<typeof en> = {
         `),
         errorStepCodes: '続行する前にコードをコピーまたはダウンロードしてください',
         stepVerify: '確認',
-        enterSecurityCode: (contactMethod: string) => `2要素認証を設定するために、${contactMethod} に送信されたセキュリティコードを入力してください。1~2分以内に届きます。`,
-        securityCodeRejected: 'そのセキュリティコードは使用できなかったため、新しいコードを送信しました。',
+        enterSecurityCode: (contactMethod: string) => `2 要素認証を設定するために、${contactMethod} に送信されたセキュリティコードを入力してください。1~2 分以内に届きます。`,
+        securityCodeRejected: 'そのセキュリティコードは有効ではなかったため、新しいコードをお送りしました。',
         scanCode: '次の端末でQRコードをスキャンしてください:',
         authenticatorApp: '認証アプリ',
         addKey: 'または、この秘密キーを認証アプリに追加してください:',
diff --git a/src/languages/nl.ts b/src/languages/nl.ts
index e4139755..35ebfe3c 100644
--- a/src/languages/nl.ts
+++ b/src/languages/nl.ts
@@ -2721,7 +2721,7 @@ const translations: TranslationDeepObject<typeof en> = {
         errorStepCodes: 'Kopieer of download de codes voordat je verdergaat',
         stepVerify: 'Verifiëren',
         enterSecurityCode: (contactMethod: string) =>
-            `Voer de beveiligingscode in die is verstuurd naar ${contactMethod} om tweeledige verificatie in te stellen. Die zou binnen één à twee minuten moeten aankomen.`,
+            `Vul de beveiligingscode in die naar ${contactMethod} is gestuurd om tweefactorauthenticatie in te stellen. Die zou binnen een of twee minuten moeten aankomen.`,
         securityCodeRejected: 'Die beveiligingscode werkte niet, dus we hebben je een nieuwe gestuurd.',
         scanCode: 'Scan de QR-code met je',
         authenticatorApp: 'authenticator-app',
diff --git a/src/languages/pl.ts b/src/languages/pl.ts
index 30b0aadd..7c787266 100644
--- a/src/languages/pl.ts
+++ b/src/languages/pl.ts
@@ -2769,7 +2769,7 @@ const translations: TranslationDeepObject<typeof en> = {
         stepVerify: 'Zweryfikuj',
         enterSecurityCode: (contactMethod: string) =>
             `Wpisz kod bezpieczeństwa wysłany na ${contactMethod}, aby skonfigurować uwierzytelnianie dwuskładnikowe. Powinien dotrzeć w ciągu minuty lub dwóch.`,
-        securityCodeRejected: 'Ten kod bezpieczeństwa nie zadziałał, więc wysłaliśmy Ci nowy.',
+        securityCodeRejected: 'Ten kod zabezpieczający nie zadziałał, więc wysłaliśmy ci nowy.',
         scanCode: 'Zeskanuj kod QR za pomocą swojego',
         authenticatorApp: 'aplikacja uwierzytelniająca',
         addKey: 'Lub dodaj ten tajny klucz do swojej aplikacji uwierzytelniającej:',
diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts
index e810e4da..714a8595 100644
--- a/src/languages/pt-BR.ts
+++ b/src/languages/pt-BR.ts
@@ -2726,7 +2726,7 @@ const translations: TranslationDeepObject<typeof en> = {
         errorStepCodes: 'Copie ou faça o download dos códigos antes de continuar',
         stepVerify: 'Verificar',
         enterSecurityCode: (contactMethod: string) =>
-            `Digite o código de segurança enviado para ${contactMethod} para configurar a autenticação de dois fatores. Ele deve chegar em um ou dois minutos.`,
+            `Insira o código de segurança enviado para ${contactMethod} para configurar a autenticação em duas etapas. Ele deve chegar em um ou dois minutos.`,
         securityCodeRejected: 'Esse código de segurança não funcionou, então enviamos um novo para você.',
         scanCode: 'Escaneie o código QR usando seu',
         authenticatorApp: 'aplicativo autenticador',
diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts
index 1b5d017d..53390f93 100644
--- a/src/languages/zh-hans.ts
+++ b/src/languages/zh-hans.ts
@@ -2624,8 +2624,8 @@ const translations: TranslationDeepObject<typeof en> = {
         `),
         errorStepCodes: '请在继续之前复制或下载这些代码',
         stepVerify: '验证',
-        enterSecurityCode: (contactMethod: string) => `请输入发送到 ${contactMethod} 的安全码以设置双重身份验证。验证码应会在一两分钟内送达。`,
-        securityCodeRejected: '该安全码无效,我们已向您发送了新的安全码。',
+        enterSecurityCode: (contactMethod: string) => `请输入发送到 ${contactMethod} 的安全验证码,以设置双重验证。验证码应在一两分钟内到达。`,
+        securityCodeRejected: '该安全码无效,我们已向你发送了新的安全码。',
         scanCode: '使用你的 扫描二维码',
         authenticatorApp: '身份验证器应用',
         addKey: '或者将此密钥添加到你的验证器应用:',

Note

You can apply these changes to your branch by copying the patch to your clipboard, then running pbpaste | git apply 😉

View workflow run

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/CONST/index.ts 96.37% <ø> (ø)
src/components/ValidateCodeActionForm/index.tsx 100.00% <100.00%> (ø)
...ionModal/ValidateCodeForm/BaseValidateCodeForm.tsx 83.79% <100.00%> (+0.75%) ⬆️
src/libs/actions/Session/index.ts 76.22% <100.00%> (+1.48%) ⬆️
...ecurity/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx 93.91% <100.00%> (+0.45%) ⬆️
...Security/TwoFactorAuth/ToggleTwoFactorAuthForm.tsx 95.83% <100.00%> (+4.16%) ⬆️
...ty/TwoFactorAuth/TwoFactorAuthSecurityCodeStep.tsx 95.23% <95.23%> (ø)
src/libs/actions/TwoFactorAuthActions.ts 52.94% <20.00%> (-13.73%) ⬇️
...tings/Security/TwoFactorAuth/DynamicVerifyPage.tsx 0.00% <0.00%> (ø)
... and 7523 files with indirect coverage changes

@joekaufmanexpensify joekaufmanexpensify left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change makes sense to me from a product perspective.

@parasharrajat

Copy link
Copy Markdown
Member

Is the backend PRs merged?

@neil-marcellini neil-marcellini changed the title Require an emailed magic code before turning on 2FA [HOLD] Require an emailed magic code before turning on 2FA Nov 23, 2026
@neil-marcellini

Copy link
Copy Markdown
Contributor Author

No not yet, I'll let you know when.

@neil-marcellini neil-marcellini changed the title [HOLD] Require an emailed magic code before turning on 2FA [HOLD Web-E#58701] Require an emailed magic code before turning on 2FA Nov 23, 2026
The first step only stores the code, so it does not prove the user can read their email before the recovery codes are created.
@neil-marcellini neil-marcellini changed the title [HOLD Web-E#58701] Require an emailed magic code before turning on 2FA Require an emailed magic code before turning on 2FA Dec 3, 2026
Use the same spot and style as the form's own validation errors, instead of a red description line above the input.
The form clears its input when a code is sent, which also cleared the error explaining why a new code was sent.
When the validate response arrives behind a server update the app hasn't received, the app holds it until it fetches that update. The required setup's Onyx clear erased the held response, so the secret stayed and the verify page never moved to the success screen.
# Conflicts:
#	src/components/ValidateCodeActionForm/index.tsx
#	src/components/ValidateCodeActionForm/type.ts
#	src/components/ValidateCodeActionModal/ValidateCodeForm/BaseValidateCodeForm.tsx
#	src/libs/API/parameters/ResendValidateCodeParams.ts
#	src/types/onyx/VerifyValidateCodeAction.ts
#	tests/ui/DynamicTwoFactorAuthPageTest.tsx

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants