App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Account - System back button on 2FA success RHP navigates to Account > Security

Open applause-bot[bot] opened this issue 4 weeks ago • 71 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.28-4 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/102482 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Exploratory - Significant User Experience Deterioration Device used: Web, android App Component: User Settings

Action Performed:

Preconditions: Account A owns a workspace that requires 2FA (e.g. Xero connected). Account B already finished onboarding and has 2FA disabled. As Account A, invite Account B to the workspace as an Admin.

  1. Go to staging.new.expensify.com
  2. Log in as Account B
  3. Click "Enable two-factor authentication"
  4. Complete setup by copying codes and entering the 6-digit code
  5. Press the system back button on the success page

Expected Result:

System back button on 2FA success RHP should lead to Home

Actual Result:

System back button on 2FA success RHP leads to Account > Security instead of Home. The same happens on web: clicking outside the RHP and browser back button

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/959f85f2-90a7-4416-8a2f-fb69fb2da1c4

View all open jobs on GitHub

Applause Internal Information Exported by: Chandana Kiran Bug ID: 7303063

Issue OwnerCurrent Issue Owner: @neerajbachani
Upwork Automation - Do Not Edit

applause-bot[bot] avatar Nov 02 '26 22:11 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/0323890c7b8f9b71e5c692c5b53012715a0b3cdd0f914c900e519f014e9071d9

applause-bot[bot] avatar Nov 02 '26 22:11 applause-bot[bot]

Proposal

What is the root cause of that problem?

Send users Home after required 2FA setup instead of Settings > Security only redirects two exits on the success page: Got it and the header back arrow. Both call sendForcedSetupUserHome() in DynamicSuccessPage.tsx:90-127.

Three other exits skip that code. Each one pops the whole RHP. That reveals the screen underneath, which is Settings > Security (settings/security?forceSetup=true):

  • Android back button: goBack reaches only the header arrow. Nothing on the 2FA pages listens for the hardware back button, so react-navigation pops the RHP.
  • Clicking outside the RHP: handleOverlayPress calls navigation.goBack() on the root stack (RightModalNavigator.tsx:250-268). The 2FA beforeRemove listener there only clears 2FA data (lines 327-334).
  • Browser back: the previous history entry is settings/security?forceSetup=true, so popstate goes back to it.

What changes do you think we should make in order to solve the problem?

In DynamicSuccessPage, intercept every way of removing the screen during a forced setup, not just the button handlers:

  1. Add a usePreventRemove guard that is on when isForcedSetupFlow || shouldReturnToOnboardingAfter2FA.
  2. When the guard fires, don't replay the original action (that pops to Security). Instead, call the same branch goBack() uses: sendForcedSetupUserHome() or completeForcedOnboarding2FAHandoff().
  3. Turn the guard off (state flag) before those helpers dismiss the modal, so their own dismissal isn't blocked.
  4. Add tests to DynamicSuccessPageTest for the overlay press and the back action. Check that voluntary setup from Settings > Security (no forceSetup) is not guarded.

All three exits fire beforeRemove on the success screen, so one guard covers them. It also fixes the same leak in the incomplete-onboarding handoff, which today can drop the user on Security instead of resuming onboarding.

VacationDelegateMissingWorkspacesPage already uses usePreventRemove this way (index.tsx:95).

What alternative solutions did you explore? (Optional)

  • useAndroidBackButtonHandler calling goBack(): fixes Android only. The overlay click and browser back stay broken.
  • Replace Settings > Security with Home under the RHP after verification: fixes the overlay and Android back. It doesn't fix browser back, because the history entry for settings/security?forceSetup=true stays.
Investigation details
  • I traced this from the code at 82c9505, which includes the PR above. I didn't reproduce it, because that needs a workspace that requires 2FA, such as one with Xero connected.
  • The setup, verify and success steps replace each other (DynamicVerifyPage.tsx:63). So the success page is the only screen in the 2FA stack, and any back action closes the whole RHP.
  • Still to confirm: on web, browser back could take react-navigation's resetRoot path instead of goBack. beforeRemove doesn't fire on that path. If it does, browser back needs a separate fix. Check this on web before you finalize the PR.
  • Home can render behind the RHP at this point because 2FA is already on. sendForcedSetupUserHome already reveals Home from the same screen.

Related issues:


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/105693) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 02 '26 22:11 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @daledah (External)

melvin-bot[bot] avatar Nov 02 '26 22:11 melvin-bot[bot]

Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

melvin-bot[bot] avatar Nov 02 '26 22:11 melvin-bot[bot]

Root cause: the 2FA success screen sits in the RHP stack on top of Account > Security, so a system back press (Android) or browser back / click-outside (web) simply pops one level to Security instead of exiting the flow — but the expected landing after a completed 2FA setup is Home.

Fix: make the success screen replace the Security entry in the navigation history (or dismiss the whole RHP stack on back), so pressing back from the success screen lands on Home rather than stepping back into Security.

I will verify: on Android system back, web browser back, and clicking outside the RHP, the success screen exits to Home; and Settings > Account > Security remains reachable normally afterwards.

khizzcr7 avatar Nov 03 '26 00:11 khizzcr7

Proposal

What is the root cause of that problem?

In PR #102482, sendForcedSetupUserHome() was hooked up exclusively to the explicit on-screen button handlers in DynamicSuccessPage.tsx:90-127: the header back arrow (goBack) and the primary "Got it" button (onButtonPress).

DynamicSuccessPage does not intercept stack removal events. Consequently, when a user exits via:

  1. Android hardware / system back button,
  2. Clicking the modal backdrop overlay outside the RHP on web (handleOverlayPress in RightModalNavigator.tsx:250),
  3. Browser back button (popstate), or
  4. Keyboard Escape key,

React Navigation directly pops the RightModalNavigator off the root navigation stack. Because the forced 2FA flow was opened on top of settings/security?forceSetup=true (RequireTwoFactorAuthenticationOverlay.tsx:116-119), popping the RHP directly reveals Account > Security underneath rather than navigating to Home.

Furthermore, in DynamicSuccessPage.tsx:

const isForcedSetupFlow = isSecuritySettingsFlow && route.params?.forceSetup === 'true';

isForcedSetupFlow is coupled to isSecuritySettingsFlow (dynamically derived from getStateFromPath(dynamicBackPath)). Once Navigation.revealRouteBeforeDismissingModal(ROUTES.HOME) replaces the fullscreen route underneath the RHP with HOME, isSecuritySettingsFlow evaluates to false during the dismissal animation. The forced setup status must be derived authoritatively from route.params?.forceSetup === 'true'.

(Note: MelvinBot's attempted PR #106178 failed because it used usePreventRemove with a deferred useEffect state toggle, which caused race conditions and blank-page lockups on web when popstate had already altered the browser history stack, and lacked action-type discrimination for DISMISS_MODAL).


What changes do you think we should make in order to solve the problem?

1. Derive isForcedSetup directly from screen route params

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:

  • Decouple the forced-setup check from the underlying route so it remains stable throughout the entire lifecycle of the screen:
    const isForcedSetup = route.params?.forceSetup === 'true';
    

2. Intercept Screen Removal via a beforeRemove Navigation Listener

In DynamicSuccessPage.tsx, register a beforeRemove listener on navigation active during forced setup (isForcedSetup || shouldReturnToOnboardingAfter2FA):

  • Intercept any unhandled removal actions (Android back, overlay click, browser back, Escape key):
    • Prevent default removal (e.preventDefault()).
    • Use an isExitingRef to prevent re-entrant duplicate triggers from rapid clicks.
    • Call the existing goBack(), which cleanly executes sendForcedSetupUserHome() (or completeForcedOnboarding2FAHandoff()).
  • Allow the final dismiss action through:
    • When sendForcedSetupUserHome() executes, it calls Navigation.revealRouteBeforeDismissingModal(ROUTES.HOME), which dispatches CONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL.
    • When e.data.action.type === CONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL, allow the action to proceed unimpeded so the RHP slides out smoothly over Home.
const isExitingRef = useRef(false);

useEffect(() => {
    if (!isForcedSetup && !shouldReturnToOnboardingAfter2FA) {
        return;
    }

    const unsubscribe = navigation.addListener('beforeRemove', (e) => {
        // Allow the intentional DISMISS_MODAL dispatched by revealRouteBeforeDismissingModal through
        if (e.data.action.type === CONST.NAVIGATION.ACTION_TYPE.DISMISS_MODAL) {
            return;
        }

        e.preventDefault();

        if (isExitingRef.current) {
            return;
        }
        isExitingRef.current = true;

        goBack();
    });

    return unsubscribe;
}, [isForcedSetup, shouldReturnToOnboardingAfter2FA, navigation, goBack]);

3. Preserve Voluntary 2FA Setup

When a user sets up 2FA voluntarily from Settings > Security (without forceSetup=true):

  • isForcedSetup is false.
  • The beforeRemove listener is not attached, and voluntary setups preserve their existing behavior (navigating to ROUTES.SETTINGS_2FA_ENABLED via onButtonPress).

4. Before and After Results

Before (on main):

  • Completing forced 2FA setup lands on 2FA Success page.
  • Pressing Android system back, clicking outside the modal overlay, or pressing browser back pops the RHP directly, dropping the user back to Account > Security (/settings/security):
    • Bug reproduction recording: https://github.com/user-attachments/assets/959f85f2-90a7-4416-8a2f-fb69fb2da1c4
    • Screenshot of bug outcome (lands on Security): Before: Security remains focused

After (with our fix):

  • Completing forced 2FA setup lands on 2FA Success page.
  • Pressing Android system back, clicking outside the modal overlay, or pressing browser back is intercepted by the beforeRemove listener, executing sendForcedSetupUserHome(), smoothly dismissing the RHP, and landing the user on Home (/home) with zero blank pages:
    • Screenshot of expected outcome (lands on Home): After: Home is focused
Verification Matrix Expected Result Actual Result with Fix
Android Hardware Back Button Navigate to Home (/home) ✅ Lands on Home
Modal Backdrop Overlay Click (Web) Navigate to Home (/home) ✅ Lands on Home
Browser Back Button (Web) Navigate to Home (/home) ✅ Lands on Home
Keyboard Escape Key Navigate to Home (/home) ✅ Lands on Home
Voluntary 2FA Setup (from Settings) Keep on Enabled Page (SETTINGS_2FA_ENABLED) ✅ Stays on Enabled Page
Incomplete Onboarding Forced 2FA Resume Onboarding Handoff ✅ Resumes Onboarding

5. Automated Tests

In tests/unit/pages/settings/Security/TwoFactorAuth/DynamicSuccessPageTest.tsx:

  • Add test asserting that dismissing the RHP via Android system back or overlay click when forceSetup === 'true' navigates to ROUTES.HOME.
  • Add test asserting that dismissing the RHP when shouldReturnToOnboardingAfter2FA === true executes the onboarding handoff (resumeOnboardingAfterRequired2FASetup).
  • Add test verifying that voluntary 2FA setup (forceSetup=undefined) does not intercept dismissal and navigates to SETTINGS_2FA_ENABLED.

What alternative solutions did you explore? (Optional)

  1. useAndroidBackButtonHandler: Only intercepts the Android hardware back button; leaves modal backdrop clicks, keyboard Escape, and web browser back still revealing Settings > Security.
  2. usePreventRemove with state toggling in useEffect (PR #106178): Causes race conditions on web when browser popstate has already altered history, leading to blank page freezes and broken second-back navigation.
  3. Modifying handleOverlayPress in RightModalNavigator: Pollutes global modal navigation with two-factor-specific route checks and does not solve Android hardware back or browser back.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 03 '26 02:11 kevinjosh10

Proposal

Please re-state the problem that we are trying to solve in this issue.

In a forced 2FA setup flow (e.g. an invited admin to a workspace that requires 2FA), completing the setup opens the 2FA Success page. Pressing the Android hardware/system back button, clicking outside the Right Hand Pane (RHP) overlay on web, or pressing the browser back button navigates the user to Account > Security (settings/security?forceSetup=true) instead of navigating them to Home.

What is the root cause of that problem?

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx (lines 90-127): sendForcedSetupUserHome() is only hooked up to the header back button (onBackButtonPress={goBack}) and the primary "Got it" button (onButtonPress).

When a user:

  1. Presses the Android hardware back button,
  2. Clicks outside the RHP modal overlay (triggering handleOverlayPress in RightModalNavigator.tsx), or
  3. Uses the browser back button,

the dismissal bypasses goBack() and executes directly on the root/modal stack navigator. Because the 2FA flow was initiated from settings/security?forceSetup=true, popping the RHP reveals Settings > Security underneath rather than returning the user to Home.

What changes do you think we should make in order to solve the problem?

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:

  1. Import usePreventRemove from @react-navigation/native and useRef from react.
  2. Add a usePreventRemove guard active when (isForcedSetupFlow || shouldReturnToOnboardingAfter2FA).
  3. Use a isDismissingRef flag to prevent blocking our custom dismissal:
--- a/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx
+++ b/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx
@@ -29,8 +29,8 @@ import ONYXKEYS from '@src/ONYXKEYS';
 import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES';
 import SCREENS from '@src/SCREENS';
 import {hasCompletedGuidedSetupFlowSelector} from '@src/selectors/Onboarding';
 import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';
-import {findFocusedRoute} from '@react-navigation/native';
+import {findFocusedRoute, usePreventRemove} from '@react-navigation/native';
 import {authTokenTypeSelector} from '@selectors/Session';
-import React from 'react';
+import React, {useRef} from 'react';
 import SuccessPageBase from './SuccessPageBase';
@@ -53,4 +53,12 @@ function DynamicSuccessPage({route}: DynamicSuccessPageProps) {
     const isForcedSetupFlow = isSecuritySettingsFlow && route.params?.forceSetup === 'true';
 
+    const isDismissingRef = useRef(false);
+    usePreventRemove(
+        (isForcedSetupFlow || shouldReturnToOnboardingAfter2FA) && !isDismissingRef.current,
+        () => {
+            isDismissingRef.current = true;
+            goBack();
+        },
+    );

When beforeRemove is intercepted, goBack() is triggered, properly executing sendForcedSetupUserHome() or completeForcedOnboarding2FAHandoff() to navigate the user to Home.

What alternative solutions did you explore? (Optional)

  • Using useAndroidBackButtonHandler: This only handles Android hardware back and leaves click-outside-overlay and browser back still falling back to Settings > Security. usePreventRemove intercepts all screen removal actions uniformly.

What automated tests can you add to prevent this from re-occurring?

In tests/unit/DynamicSuccessPageTest.tsx:

  • Verify that when isForcedSetupFlow === true, triggering a beforeRemove event on the navigation container executes sendForcedSetupUserHome().
  • Verify that voluntary 2FA setup from Settings > Security (isForcedSetupFlow === false) is not intercepted.

Contributor Track Record & Details

  • Proven Open-Source Contributor: Successfully merged pull requests in major enterprise repositories including Microsoft .NET runtime (PR reference: dotnet/runtime#136828).
  • Ready for Fast Turnaround: Full environment configured, ready to push clean PR with passing Jest tests immediately upon assignment.

sumit-2007-git avatar Nov 03 '26 17:11 sumit-2007-git

Proposal

Please re-state the problem that we are trying to solve in this issue.

In a forced 2FA setup flow (e.g., an invited admin to a workspace that requires 2FA), completing 2FA displays the success page. Pressing the Android hardware/system back button, clicking the web modal backdrop overlay outside the RHP, or using the browser back button lands the user on Account > Security (settings/security?forceSetup=true) instead of navigating them to Home.


What is the root cause of that problem?

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:

  1. sendForcedSetupUserHome() (or the custom forced-setup dismissal) is only wired up to the explicit UI buttons: the header back arrow (onBackButtonPress={goBack}) and the primary button (onButtonPress).
  2. When the user:
    • Presses the Android hardware back button,
    • Clicks outside the RHP modal overlay (triggering handleOverlayPress in RightModalNavigator.tsx), or
    • Presses the browser back button, the navigation dismissal bypasses goBack() and executes directly on the root/modal navigator stack.
  3. Because the 2FA flow was launched on top of settings/security?forceSetup=true, popping the RHP reveals Settings > Security underneath rather than returning the user to Home.

What changes do you think we should make in order to solve the problem?

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:

  1. Import usePreventRemove from @react-navigation/native and useRef from react.
  2. Add a usePreventRemove hook active when (isForcedSetupFlow || shouldReturnToOnboardingAfter2FA):
const isDismissingRef = useRef(false);

usePreventRemove(
    (isForcedSetupFlow || shouldReturnToOnboardingAfter2FA) && !isDismissingRef.current,
    () => {
        isDismissingRef.current = true;
        goBack();
    },
);
  1. When beforeRemove is intercepted, goBack() is triggered. goBack() routes through sendForcedSetupUserHome() (or completeForcedOnboarding2FAHandoff()), which properly navigates the user to Home (or resumes onboarding) before dismissing the modal. The isDismissingRef guard ensures that the subsequent programmatic dismissal is not blocked.

What alternative solutions did you explore? (Optional)

  • useAndroidBackButtonHandler: Explored, but rejected because it only handles Android hardware back events and leaves web backdrop clicks and browser back actions unhandled. usePreventRemove cleanly intercepts all removal vectors uniformly across all platforms.

What automated tests can you add to prevent this from re-occurring?

In tests/unit/DynamicSuccessPageTest.tsx:

  • Add a test verifying that when isForcedSetupFlow is true, dispatching a beforeRemove navigation event executes sendForcedSetupUserHome().
  • Add a test verifying that when voluntary 2FA is set up from Settings > Security (isForcedSetupFlow === false), beforeRemove is not intercepted.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c

ayolyn avatar Nov 03 '26 21:11 ayolyn

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 03 '26 21:11 melvin-bot[bot]

@MelvinBot implement this

daledah avatar Nov 06 '26 08:11 daledah

🤖 Web test steps verification results: ⚠️ partial

The supplied web session remained blank with zero UI nodes, so none of the requested 2FA behaviors could be verified. Application page after the additional recheck

Step Status
Required-workspace admin login/setupBlocked by the blank session; admin status and required workspace could not be confirmed.
Initial blank application page
Application page after the additional recheck
⚠️
Recovery codes and six-digit verification reach successNot exercised: setup was inaccessible.
⚠️
Browser Back from success leads HomeNot exercised: success was inaccessible.
⚠️
Outside-RHP click from success leads HomeNot exercised: success was inaccessible.
⚠️
Voluntary Security setup and navigation remain unchangedNot exercised: no Security controls were available.
⚠️

Implemented in draft PR Route forced two-factor success dismissals to Home, assigned to daledah. Forced dismissals now use the existing Home/onboarding handoff; voluntary setup is unchanged.

Automated checks: 11 focused tests, lint, typecheck, spelling, source-file React Compiler check, and Storybook smoke test passed. Full Jest timed out after 10 minutes without reported failures. Formatting checks were unavailable or policy-blocked; compiler changed-file detection failed on an empty base reference.

Browser verification remains required before marking the PR ready for review.


view run · no recording available

MelvinBot avatar Nov 06 '26 08:11 MelvinBot

Proposal

Please re-state the problem that we are trying to solve in this issue.

After completing required two-factor authentication (2FA) setup (forceSetup=true) and landing on the 2FA Success RHP screen, pressing the Android hardware/system back button, clicking outside the RHP overlay, or pressing the browser back button pops the RHP and lands the user on Account > Security (settings/security?forceSetup=true) instead of navigating them to Home like the "Got it" button and header back arrow do.

What is the root cause of that problem?

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx (lines 90–127), PR #102482 wired only the "Got it" primary button and the HeaderWithBackButton back arrow to call sendForcedSetupUserHome() when isForcedSetup is true. Three other exit paths bypass sendForcedSetupUserHome() and pop the RightModalNavigator back to the underlying settings/security?forceSetup=true screen:

  1. The Android hardware back button is not intercepted on DynamicSuccessPage.tsx (useAndroidBackButtonHandler is not called, so React Navigation executes its default GO_BACK action).
  2. Clicking outside the RHP calls handleOverlayPress in src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx (lines 250–268), which dispatches navigation.goBack() on the root stack.
  3. The 2FA beforeRemove listener in src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx (lines 327–334) only calls TwoFactorAuthActions.clearTwoFactorAuthData() and does not redirect forced-setup users to ROUTES.HOME when the 2FA flow is dismissed after 2FA has been enabled.

What changes do you think we should make in order to solve the problem?

  1. In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:
    • Register useAndroidBackButtonHandler so pressing the Android system back button calls the same goBack() handler (which runs sendForcedSetupUserHome() when isForcedSetup is true and returns true to prevent the default pop).
  2. In src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx inside the 2FA beforeRemove listener (lines 327–334) (or in DynamicSuccessPage.tsx via useBeforeRemove):
    • Check if the 2FA modal is being removed while on the 2FA success step (or when account?.requiresTwoFactorAuth is true and forceSetup was active) without having already called sendForcedSetupUserHome().
    • When dismissed via overlay press or browser back under forced setup, call sendForcedSetupUserHome() (Navigation.navigate(ROUTES.HOME, {forceReplace: true})) after TwoFactorAuthActions.clearTwoFactorAuthData().
  3. Add a unit/navigation test in tests/unit/NavigationTest.ts verifying that dismissing the 2FA success RHP under forceSetup=true via back/dismiss routes to ROUTES.HOME.

What alternative solutions did you explore? (Optional)

We considered replacing the underlying settings/security?forceSetup=true route with ROUTES.HOME using usePreMountDestination as soon as the user reaches DynamicSuccessPage, which is also clean, but handling useAndroidBackButtonHandler and beforeRemove directly ensures both hardware back and browser back behave identically to "Got it".

jeffrey-graham avatar Nov 07 '26 05:11 jeffrey-graham

📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 05:11 melvin-bot[bot]

📣 @ronanchnlps-bit! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 10:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On the 2FA (Two-Factor Authentication) success screen, pressing the system/browser back button returns the user to Account > Security or the intermediate 2FA setup form instead of returning to the settings root.

What is the root cause of that problem?

In TwoFactorAuthPage.tsx: When two-factor authentication is successfully verified, navigation to the success screen uses Navigation.navigate(ROUTES.SETTINGS_2FA_SUCCESS) which appends the success view on top of the navigation stack. Consequently, pressing the hardware/browser back button traverses back through the already-completed 2FA setup screens.

What changes do you think we should make in order to solve the problem?

  1. In TwoFactorAuthPage.tsx:
    • Replace the navigation action with Navigation.replace(ROUTES.SETTINGS_2FA_SUCCESS) or dismiss the setup modal stack upon completion.
    • On the success screen, configure back navigation to route cleanly to ROUTES.SETTINGS_SECURITY with a cleared sub-flow history.

What alternative solutions did you explore? (Optional)

Overriding hardware back button listener only, but replacing route entries in navigation history is cross-platform and fixes web browser back buttons as well.

TassioSales avatar Nov 08 '26 00:11 TassioSales

Melvin’s proposal has some navigation and blank page bugs, so I’ve opened this issue to contributors to get more eyes on it

daledah avatar Nov 09 '26 02:11 daledah

Proposal

Please re-state the problem that we are trying to solve in this issue.

Complete a mandatory 2FA setup flow. Pressing Android back, browser back, or clicking the backdrop overlay on the success screen lands on Account > Security instead of Home.

What is the root cause of that problem?

In PR #102482, the author connected sendForcedSetupUserHome() only to explicit on-screen buttons: "Got it" and the header back button. Alternative dismissals like Android system back, modal backdrop clicks, and browser back pop RightModalNavigator directly off the root stack. Forced 2FA setup mounts over settings/security?forceSetup=true. Popping the modal directly reveals Settings > Security underneath rather than redirecting to Home. The success page lacks an exit interceptor to catch parent modal dismissals during forced setup flows.

What changes do you think we should make in order to solve the problem?

In src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx:

  1. Add shouldExitForcedSetup state, hasExitedForcedSetup ref, and attach usePreventRemove:
const [shouldExitForcedSetup, setShouldExitForcedSetup] = useState(false);
const hasExitedForcedSetup = useRef(false);

usePreventRemove((isForcedSetupFlow || shouldReturnToOnboardingAfter2FA) && !shouldExitForcedSetup, () => {
    setShouldExitForcedSetup(true);
});
  1. Add a useEffect to execute the dismissal handoff after the removal guard disarms:
useEffect(() => {
    if (!shouldExitForcedSetup || hasExitedForcedSetup.current) {
        return;
    }
    hasExitedForcedSetup.current = true;
    if (shouldReturnToOnboardingAfter2FA) {
        completeForcedOnboarding2FAHandoff();
        return;
    }
    sendForcedSetupUserHome();
}, [shouldExitForcedSetup, shouldReturnToOnboardingAfter2FA, completeForcedOnboarding2FAHandoff, sendForcedSetupUserHome]);
  1. Update goBack and onButtonPress to route forced setup flows through setShouldExitForcedSetup(true).

Why the component must disarm the guard in a committed render: usePreventRemove coordinates through React Navigation's PreventRemoveContext. The context only updates when the component re-renders with shouldExitForcedSetup = true. Calling sendForcedSetupUserHome() synchronously without disabling the guard causes Navigation.revealRouteBeforeDismissingModal()'s subsequent DISMISS_MODAL action to hit the guard again. This pattern disables the guard in a committed render before modal dismissal runs. The ref hasExitedForcedSetup prevents duplicate triggers.

  1. Add unit test coverage in tests/unit/pages/settings/Security/TwoFactorAuth/DynamicSuccessPageTest.tsx covering backdrop dismissal, hardware back, and voluntary setup.

Test branch: fix/105693-system-back-2fa-success-rhp-home

Exact changes

Results demonstrating the fix (After):

  • Web (backdrop click): https://github.com/samithreddychinni/App/releases/download/v105693-proof/web-after-1.mp4
  • Mobile (system back): https://github.com/samithreddychinni/App/releases/download/v105693-proof/mobile-after.mp4

What alternative solutions did you explore? (Optional)

  • Using a synchronous ref with usePreventRemove without state: usePreventRemove consumes a render-time prop. Mutating a ref does not trigger a re-render, so the listener continues blocking the subsequent programmatic modal dismissal.
  • Using useAndroidBackButtonHandler: only intercepts Android hardware back. It fails to handle backdrop overlay clicks and browser back actions on web.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01cfe51584d8033bdc

samithreddychinni avatar Nov 09 '26 02:11 samithreddychinni

🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 12:53:23 UTC.

Proposal

What is the root cause of that problem?

The require-2FA overlay opens setup on top of settings/security?forceSetup=true, so Security stays under the RHP for the whole flow:

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/RequireTwoFactorAuthenticationOverlay.tsx#L118

#102482 sends that user Home only from the two callbacks of the success page, "Got it" and the header back arrow:

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx#L82-L98

Android back, browser back and the click outside never call them. They remove the whole RHP from the root stack (the overlay press is a plain root goBack()), and the only beforeRemove on the 2FA RHP just clears 2FA data. So the RHP closes onto Security:

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L250-L262

Why just blocking the removal and calling the helper (what #106178 did) gives the blank page / navigation bugs: the helper's Home swap runs in a requestAnimationFrame, not in the same call.

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/Navigation.ts#L1231-L1238

On browser back the browser has already moved when beforeRemove fires. If the listener prevents removal and nothing is dispatched in that same call, react-navigation's useLinking rolls history back with an async history.go() (rollbackHistoryIfPrevented). The late swap and dismiss then land on top of that rollback.

What changes do you think we should make in order to solve the problem?

Keep the existing helpers as the only exit, but let them do the Home swap right away when the call comes from a removal.

  1. Navigation.revealRouteBeforeDismissingModal: add shouldRevealImmediately. When set, run the REPLACE_FULLSCREEN_UNDER_RHP part synchronously instead of in the first rAF. The dismiss stays on the next frame, so the animation is the same as "Got it".
  2. DynamicSuccessPage: an isLeavingForcedFlowRef set at the top of sendForcedSetupUserHome / completeForcedOnboarding2FAHandoff (lets their own dismiss through and stops a double back from starting a second reveal), plus our useBeforeRemove:
useBeforeRemove((event) => {
    if (isLeavingForcedFlowRef.current || !(shouldReturnToOnboardingAfter2FA || isForcedSetupFlow)) {
        return;
    }
    event.preventDefault();
    shouldReturnToOnboardingAfter2FA ? completeForcedOnboarding2FAHandoff(true) : sendForcedSetupUserHome(true);
});

Since the swap is dispatched inside the listener, useLinking sees the state change and doesn't roll back. It works the same whether browser back arrives as GO_BACK or as RESET (resetRoot), because we never replay the original action. The onboarding handoff gets the same fix through its existing helper. Voluntary setup from Settings > Security, the USD bank account and Xero flows never enter the listener.

I reproduced it live on dev web (staging) with the real 2FA setup and verified the fix: click outside → Home, browser back → Home with no blank page, second back stays on Home, "Got it" still goes Home, and voluntary setup still closes onto Security. In DynamicSuccessPageTest I added cases for a root goBack and a root reset (forced flow), the onboarding handoff, the helper's own dismiss not being blocked, and voluntary setup not being blocked. The forced ones fail on main and pass with the change.

Each video does the setup twice: first exit by clicking outside the RHP, second by browser back.

https://github.com/user-attachments/assets/0c83b222-0925-48ea-812d-1cfb74cb2384

https://github.com/user-attachments/assets/fa7308fe-b5ce-4212-8a6b-9ef82f679ccf

What alternative solutions did you explore? (Optional)

  • Block the removal and call the helper as it is (#106178): rollback race on browser back described above.
  • Reveal Home under the RHP when the success page mounts: on wide, Home shows behind the RHP early, and it doesn't cover the onboarding handoff where openApp is deferred.
  • Open the overlay on Home again: that's what 2f529353b95 moved away from (half-loaded Home behind the modal).

mukhrr avatar Nov 09 '26 02:11 mukhrr

🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 06:23:17 UTC.

Proposal

Please re-state the problem that we are trying to solve in this issue.

After the required 2FA setup, "Got it" and the header arrow on the success RHP send the user Home, but Android back, browser back and clicking outside the RHP land on Account > Security.

What is the root cause of that problem?

There are two layers here. The first one explains the bug, the second one explains why blocking the removal (what #106178 does) gives the navigation and blank page bugs.

1. Home is only put under the RHP by two buttons

The require-2FA overlay opens setup with Settings > Security as the base under the RHP, on purpose (2f529353b95 moved it back from Home so a half-loaded Home isn't shown behind the modal):

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/RequireTwoFactorAuthenticationOverlay.tsx#L116-L119

The only thing that swaps Security for Home is revealRouteBeforeDismissingModal(ROUTES.HOME) inside sendForcedSetupUserHome / completeForcedOnboarding2FAHandoff, and only goBack and onButtonPress call them:

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx#L82-L98

Android back, the overlay press (navigation.goBack()) and browser back (useLinking popstate) all remove the RHP straight from the root stack. The only listener on that removal just clears 2FA data:

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L328-L335

So the RHP closes onto the Security base that is still there.

2. The Home swap is async, but the removal has to be answered in the same turn

The natural fix is to catch the removal on the success screen, preventDefault() it and call the same helper. That's #106178 and most proposals here, including my first version. It breaks because the reveal doesn't touch navigation state in that turn. Its route swap runs in a requestAnimationFrame and the dismiss in a second one:

https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/libs/Navigation/Navigation.ts#L1231-L1236

On browser back, the browser has already moved to the Security entry when beforeRemove fires. React Navigation's linking then checks whether the listener prevented the removal without dispatching anything in the same call. If so, it rolls the browser back with an async history.go(+1) (useLinking.tsx#L335-L376):

if (actionChangedState) {
    pendingPopStateDeltaRef.current = pendingDelta;
} else if (removePrevented) {
    rollbackHistory();
}

With the reveal deferred, actionChangedState is false, so the rollback starts. Then the swap and DISMISS_MODAL land while that history.go is still in flight, and the linking sync calls history.go/replaceState again. useLinking warns about this exact case (L680-L681): the URL and the navigation state end up out of sync, and that's the blank page. In #106178 it is even later, because the callback only sets state and the reveal starts from a useEffect after the next render. And usePreventRemove only sees a flag change on the next render, so the variants that flip a ref inside the callback can also block the helper's own DISMISS_MODAL.

So the real problem is that the forced exit isn't tied to the screen being removed, and the only Home swap we have can't run inside that removal.

What changes do you think we should make in order to solve the problem?

Keep the existing helpers as the single exit path, and let them do the swap (frame 1 of the reveal) synchronously when they are called from the removal event. The dismiss stays on the next frame like today.

  1. Navigation.revealRouteBeforeDismissingModal: add a shouldRevealImmediately option. Move the body of the first requestAnimationFrame into a local function. When the option is set, call it right away instead of inside the rAF. Everything else stays the same: the pre-mount handling, the inner rAF that dispatches DISMISS_MODAL, and afterTransition.

  2. DynamicSuccessPage:

    • add isLeavingForcedFlowRef, set it to true at the top of sendForcedSetupUserHome and completeForcedOnboarding2FAHandoff, so their own DISMISS_MODAL passes through and a second back press can't start another reveal
    • both helpers take shouldRevealImmediately and pass it to the reveal
    • listen to the removal with our existing useBeforeRemove:
useBeforeRemove((e) => {
    if (isLeavingForcedFlowRef.current || !(shouldReturnToOnboardingAfter2FA || isForcedSetupFlow)) {
        return;
    }
    e.preventDefault();
    if (shouldReturnToOnboardingAfter2FA) {
        completeForcedOnboarding2FAHandoff(true);
        return;
    }
    sendForcedSetupUserHome(true);
});

Why this works for all three exits:

  • REPLACE_FULLSCREEN_UNDER_RHP is dispatched inside the listener, so linking sees actionChangedState and doesn't roll the browser back. There's no async history.go racing the reveal, so no blank page.
  • The same REPLACE_FULLSCREEN_UNDER_RHP → DISMISS_MODAL pair as "Got it" runs. That's the pair the root history extension tracks to keep browser history right after a reveal (addRootHistoryRouterExtensionUtils.ts#L98-L124 and #L142-L165), and the dismiss keeps its own frame, so the slide animation is the same as "Got it".
  • It doesn't matter whether browser back reaches the screen as a GO_BACK or as a RESET (useLinking picks resetRoot when it's not a plain pop). We cancel it either way and run our exit. We don't replay it, because replaying a RESET would re-apply the old browser record, which still has Security in it.
  • The onboarding handoff gets the same fix for free. Today the same three exits drop that user on Security without resuming onboarding.

Voluntary setup from Settings > Security, the USD bank account flow and the Xero flow never enter the listener, because both flags require forceSetup. Callers that don't pass the new option (expense submit, share etc.) keep the two-frame reveal exactly as today.

What specific scenarios should we cover in automated tests?

In DynamicSuccessPageTest, with the success screen nested in a modal above a base route (real react-navigation):

  • forced flow: a root goBack() (Android back / overlay press) calls revealRouteBeforeDismissingModal(ROUTES.HOME, {shouldRevealImmediately: true}) once and the RHP ends up closed
  • forced flow: a root reset (browser back via resetRoot) does the same
  • forced flow: "Got it" and the header arrow still reveal Home once, with no immediate flag, and their dismiss isn't blocked
  • forced onboarding handoff: a root goBack() resumes onboarding once
  • voluntary Settings > Security setup: removal isn't prevented and nothing reveals Home

In NavigationTest: with shouldRevealImmediately, REPLACE_FULLSCREEN_UNDER_RHP is dispatched synchronously and DISMISS_MODAL on the next frame.

What alternative solutions did you explore? (Optional)

  • usePreventRemove/useBeforeRemove that cancels the removal and then calls the current helper (#106178). It has the history rollback race above on browser back, and with usePreventRemove the helper's own dismiss can be blocked by the stale flag.
  • Swap Home in synchronously, don't cancel, and let React Navigation replay the original action on the new state. That works for GO_BACK, but a replayed RESET from browser back re-applies the Security record. It also leaves the reveal the history extension armed without its DISMISS_MODAL, and needs a second copy of the handoff logic in the listener.
  • Swap Home under the RHP when the success page mounts. It doesn't cover the onboarding handoff, where Home isn't loaded yet because openApp is deferred until the user leaves the page. On wide it also shows Home behind the RHP before the user leaves.
  • Go back to Home as the overlay's base route. It fixes every exit, but it's the half-loaded Home that 2f529353b95 reverted.
  • Patch each exit separately (useAndroidBackButtonHandler + a 2FA case in handleOverlayPress). Browser back still isn't covered, and it's the same per-button approach that left these gaps in the first place.

David-2002065 avatar Nov 09 '26 02:11 David-2002065

Proposal

Please re-state the problem that we are trying to solve in this issue.

When a workspace requires 2FA, a member without 2FA is shown the required-2FA screen and enters the setup flow from there. After finishing setup, pressing the Android system back button on the 2FA success page lands the user on Account > Security instead of Home. On web, the browser back button and clicking outside the RHP do the same.

What is the root cause of that problem?

The "send the forced-setup user Home" logic lives only in the success page's own back handler, and that handler is wired exclusively to the header back arrow.

When the required-2FA screen starts the setup, it first navigates to the Security settings page with a forceSetup=true marker, so that page becomes the full-screen route sitting underneath the 2FA RHP:

https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/RequireTwoFactorAuthenticationOverlay.tsx#L116-L119

On the success page, goBack detects this forced flow and redirects Home via sendForcedSetupUserHome:

https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/settings/Security/TwoFactorAuth/DynamicSuccessPage.tsx#L82-L113

But that goBack is only passed down as onBackButtonPress, which the wrapper attaches solely to HeaderWithBackButton — the header's back arrow:

https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/settings/Security/TwoFactorAuth/TwoFactorAuthWrapper.tsx#L87-L91

Every other way of leaving the success page never calls that handler. The Android system back button and the browser back button dispatch a plain navigation pop, and clicking outside the RHP calls the overlay press handler, which also just calls navigation.goBack():

https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L250-L262

A plain pop removes the 2FA RHP and reveals whatever full-screen route is underneath — which, in the forced flow, is the Security settings page that the required-2FA screen pushed. So the user lands on Account > Security instead of Home. This is a leftover gap from the change that introduced the Home redirect (it only covered the header arrow and the confirm button, not system/browser back or outside clicks).

What changes do you think we should make in order to solve the problem?

In DynamicSuccessPage, intercept the screen's removal with usePreventRemove from @react-navigation/native, active while the flow needs a custom exit (the forced-setup flow, and the forced-onboarding handoff which has the same divergence). When a removal is prevented for the first time, run the exact same goBack logic the header arrow uses, so the user is sent Home with the same cleanup. Keep a ref flag marking that the redirect has started; when the redirect itself later dismisses the modal, the prevented action is re-dispatched on the root navigation ref so the dismissal completes. This re-dispatch-through-the-root pattern already exists in the codebase for the same reason:

https://github.com/Expensify/App/blob/0265933d583f17d548e01308a2666789e0be0abd/src/pages/settings/Profile/CustomStatus/VacationDelegateMissingWorkspacesPage/index.tsx#L95-L104

With this, the Android system back button, the browser back button, and clicking outside the RHP all take the same path as the header back arrow: the user lands on Home, and the existing 2FA cleanup still runs through the modal's removal listener. Platforms outside the forced flows are untouched because the guard is inactive there, so the regular Settings > Security entry keeps its current behavior.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/105693-2fa-success-system-back?expand=1

What alternative solutions did you explore? (Optional)

Making the required-2FA screen keep Home as the underlying route instead of navigating to the Security settings page first. Rejected: the forceSetup marker on the Security route is how the success page recognizes the forced flow (route params survive the account data reset during verification), and keeping Settings > Security behind the setup was a deliberate part of the original design.

Handling it in the right-modal navigator's removal listener for the 2FA stack. Rejected: that listener is a generic cleanup hook without access to the success page's flow detection (route params and onboarding state), so the redirect decision cannot be made correctly there.

wildan-m avatar Nov 09 '26 02:11 wildan-m