Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/libs/Navigation/AppNavigator/AppNavigator.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, {lazy, memo, Suspense} from 'react';
import LoadingIndicator from '@components/LoadingIndicator';
import lazyRetry from '@src/utils/lazyRetry';

const AuthScreens = lazy(() => lazyRetry(() => import(/* webpackChunkName: "authScreens.prefetch" */ './AuthScreens'), 'authScreens'));
Expand All @@ -11,16 +12,17 @@ type AppNavigatorProps = {

function AppNavigator({authenticated}: AppNavigatorProps) {
if (authenticated) {
// These are the protected screens and only accessible when an authToken is present
// Protected screens, only accessible with an authToken. Show a loader (not a blank
// screen) while the lazy AuthScreens chunk downloads during the sign-in swap.
return (
<Suspense fallback={null}>
<Suspense fallback={<LoadingIndicator reasonAttributes={{context: 'AppNavigator.AuthScreens'}} />}>

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 is the highest-risk change and it affects all users, not the magic-link flow.

AuthScreens is lazy(... "authScreens.prefetch"). On a cold start, before the prefetch resolves, this top-level Suspense now renders a LoadingIndicator instead of null. Previously null let the native splash cover the gap silently. There's a real risk of a spinner flash after the splash hides on native cold start, or a double-loader against the existing app-level loading state. This needs native cold-start testing on a slow device — the PR's screenshots only cover the magic-link flow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@mkhutornyi I agree. This is risky. But without this we have a blank page between two loading spinner pages as mentioned here #90488 (comment)

<AuthScreens />
</Suspense>
);
}

return (
<Suspense fallback={null}>
<Suspense fallback={<LoadingIndicator reasonAttributes={{context: 'AppNavigator.PublicScreens'}} />}>
<PublicScreens />
</Suspense>
);
Expand Down
33 changes: 14 additions & 19 deletions src/libs/Navigation/NavigationRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ import NAVIGATORS from '@src/NAVIGATORS';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Route} from '@src/ROUTES';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
import AppNavigator from './AppNavigator';
import {cleanPreservedNavigatorStates} from './AppNavigator/createSplitNavigator/usePreserveNavigatorState';
import getNavigationBaseTheme from './getNavigationBaseTheme';
import getActiveTabName from './helpers/getActiveTabName';
import getAdaptedStateFromPath from './helpers/getAdaptedStateFromPath';
import getPathFromState from './helpers/getPathFromState';
import getStateToResetAfterLogout from './helpers/getStateToResetAfterLogout';
import {isSplitNavigatorName} from './helpers/isNavigatorName';
import {saveSettingsTabPathToSessionStorage, saveWorkspacesTabPathToSessionStorage} from './helpers/lastVisitedTabPathUtils';
import {linkingConfig} from './linkingConfig';
Expand Down Expand Up @@ -215,33 +217,26 @@ function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: N
}, [shouldUseNarrowLayout]);

useEffect(() => {
// Since the NAVIGATORS.REPORTS_SPLIT_NAVIGATOR url is "/" and it has to be used as an URL for SignInPage,
// this navigator should be the only one in the navigation state after logout.
// After logout, reset the nav state so a logged-out user can't stay on a protected or
// consumed route.
const hasUserLoggedOut = !authenticated && !!previousAuthenticated;
if (!hasUserLoggedOut || !navigationRef.isReady()) {
return;
}

const rootState = navigationRef.getRootState();
const lastRoute = rootState.routes.at(-1);
if (!lastRoute) {
const stateToReset = getStateToResetAfterLogout(navigationRef.getRootState());
if (!stateToReset) {
return;
}

// REPORTS_SPLIT_NAVIGATOR will persist after user logout, because it is used both for logged-in and logged-out users
// That's why for ReportsSplit we need to explicitly clear params when resetting navigation state,
// However in case other routes (related to login/logout) appear in nav state, then we want to preserve params for those
const isReportSplitNavigatorMounted = lastRoute.name === NAVIGATORS.REPORTS_SPLIT_NAVIGATOR;
navigationRef.reset({
...rootState,
index: 0,
routes: [
{
...lastRoute,
params: isReportSplitNavigatorMounted ? undefined : lastRoute.params,
},
],
});
try {
navigationRef.reset(stateToReset);
} catch (error) {
// A synthesized reset state can be rejected by RN; fall back to a known-valid
// SCREENS.HOME (PublicScreens maps "/" → SignInPage) instead of leaving a blank screen.
Log.alert('[NavigationRoot] Post-logout navigation reset failed', {error: String(error)});
navigationRef.reset({index: 0, routes: [{name: SCREENS.HOME}]});
}
}, [authenticated, previousAuthenticated]);

const handleStateChange = (state: NavigationState | undefined) => {
Expand Down
32 changes: 32 additions & 0 deletions src/libs/Navigation/helpers/getStateToResetAfterLogout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type {NavigationState, PartialState} from '@react-navigation/native';
import NAVIGATORS from '@src/NAVIGATORS';
import SCREENS from '@src/SCREENS';

/**
* Pure decision logic for the NavigationRoot post-logout reset (kept out of the effect so it
* stays unit-testable). Returns the state to pass to `navigationRef.reset`, or
* `undefined` when there is nothing to reset.
*/
function getStateToResetAfterLogout(rootState: NavigationState | undefined): NavigationState | PartialState<NavigationState> | undefined {
const lastRoute = rootState?.routes.at(-1);
if (!rootState || !lastRoute) {
return undefined;
}

// ValidateLogin's /v/ code is spent by logout; keeping it strands the user. Reset to
// SCREENS.HOME — this runs only post-logout (NavigationRoot gates on !authenticated), when
// PublicScreens is mounted and HOME (SignInPage) is its top-level route.
if (lastRoute.name === SCREENS.VALIDATE_LOGIN) {
return {index: 0, routes: [{name: SCREENS.HOME}]};
}

// ReportsSplit is shared between logged-in & logged-out; its params can carry stale auth.
const shouldClearParams = lastRoute.name === NAVIGATORS.REPORTS_SPLIT_NAVIGATOR;
return {
...rootState,
index: 0,
routes: [{...lastRoute, params: shouldClearParams ? undefined : lastRoute.params}],
};
}

export default getStateToResetAfterLogout;
57 changes: 50 additions & 7 deletions src/pages/ValidateLoginPage/index.web.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import React, {useEffect, useState} from 'react';
import {useFocusEffect} from '@react-navigation/native';
import React, {useCallback, useEffect, useState} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import ExpiredValidateCodeModal from '@components/ValidateCode/ExpiredValidateCodeModal';
import JustSignedInModal from '@components/ValidateCode/JustSignedInModal';
import ValidateCodeModal from '@components/ValidateCode/ValidateCodeModal';
import useOnyx from '@hooks/useOnyx';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import {isValidValidateCode} from '@libs/ValidationUtils';
import {handleExitToNavigation, initAutoAuthState, signInWithValidateCode} from '@userActions/Session';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Session as SessionType} from '@src/types/onyx';
import type ValidateLoginPageProps from './types';

const autoAuthStateSelector = (session: OnyxEntry<SessionType>) => session?.autoAuthState;

/** If a separate-session magic-link sign-in hasn't completed in this long, it's likely stuck. */
const STUCK_DIRECT_SIGN_IN_TIMEOUT_MS = 30 * 1000;

function ValidateLoginPage({
route: {
params: {accountID, validateCode, exitTo},
Expand All @@ -38,16 +44,22 @@ function ValidateLoginPage({
const isUserClickedSignIn = !login && isSignedIn && (autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.SIGNING_IN || autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN);
const shouldStartSignInWithValidateCode = !isUserClickedSignIn && !isSignedIn && (!!login || !!exitTo) && isValidValidateCode(validateCode);
const isNavigatingToExitTo = isSignedIn && !!exitTo;
// Fresh-session magic-link sign-in. Not gated on `isSignedIn` because `autoAuthState` lands
// before `authToken` (separate Onyx broadcasts); that gap would otherwise flash a blank page.
// Keeps the loader up across SIGNING_IN → JUST_SIGNED_IN until the redirect unmounts the page.
// Excludes 2FA: it can't complete from here, so the 2FA modal (below) handles it instead of an
// indefinite loader.
const isCompletingDirectSignIn =
!exitTo && !login && !is2FARequired && (autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.SIGNING_IN || autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN);
Comment thread
mukhrr marked this conversation as resolved.
Resolved
const [preferredLocale] = useOnyx(ONYXKEYS.NVP_PREFERRED_LOCALE);

useEffect(() => {
setHasInitialized(true);

if (isUserClickedSignIn) {
// The user clicked the option to sign in the current tab
Navigation.isNavigationReady().then(() => {
Navigation.goBack();
Comment on lines -47 to -49

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.

@MelvinBot which PR introduced goBack logic?

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.

The explicit Navigation.goBack() here was introduced by #35850 ("fix: sign-in here navigating to abracadabra page", merged 2024-02-05). That PR replaced a no-arg Navigation.navigate() with Navigation.isNavigationReady().then(() => Navigation.goBack()) in both effects of the web page — commit 94800c6.

The isUserClickedSignIn redirect flow itself is older — it came from #15505 ("Add 'sign in here' option", 2023), which originally used Navigation.navigate(ROUTES.REPORT). So the lineage is: navigate(ROUTES.REPORT) → no-arg navigate() → goBack() (this last step is #35850).

The goBack() currently on main lives at ValidateLoginPage/index.web.tsx:46-51.

🤖 Generated by MelvinBot

});
// Just signed in via the magic link with no cached `login` (separate-session sign-in).
// The redirect Home lives in the focus effect below (not here) so returning to the
// consumed `/v/...` via browser Back re-fires it instead of getting stuck on the loader.
return;
}
initAutoAuthState(autoAuthStateWithDefault);
Expand All @@ -65,6 +77,22 @@ function ValidateLoginPage({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// Redirect Home after a separate-session magic-link sign-in. On a focus effect (not mount-only)
// so that returning to the consumed `/v/...` via browser Back re-fires it — the route can linger
// in the stack when forceReplace is downgraded to a push, and a mount-only effect wouldn't re-run.
useFocusEffect(
useCallback(() => {
if (!isUserClickedSignIn) {
return;
}
// Wait for protected routes (HOME mounts async); forceReplace so Home doesn't stack on the
// consumed `/v/...` route.
Navigation.waitForProtectedRoutes().then(() => {
Navigation.navigate(ROUTES.HOME, {forceReplace: true});
});
}, [isUserClickedSignIn]),
);

useEffect(() => {
if (!!login || !cachedAccountID || !is2FARequired) {
if (exitTo) {
Expand All @@ -79,10 +107,24 @@ function ValidateLoginPage({
});
}, [login, cachedAccountID, is2FARequired, exitTo]);

// waitForProtectedRoutes()/authToken can hang (lazy AuthScreens chunk fails, token
// never lands). We can't recover the consumed code here, but surface a stuck sign-in to
// Sentry/Log instead of leaving an indefinitely silent spinner. Observability only — no
// navigation/UX change. Cleared on unmount (successful redirect) or when the state changes.
useEffect(() => {
if (!isCompletingDirectSignIn) {
return;
}
const timeoutID = setTimeout(() => {
Log.alert('[ValidateLoginPage] Magic-link sign-in appears stuck (protected routes / authToken not ready)', {autoAuthState: autoAuthStateWithDefault});
}, STUCK_DIRECT_SIGN_IN_TIMEOUT_MS);
return () => clearTimeout(timeoutID);
}, [isCompletingDirectSignIn, autoAuthStateWithDefault]);

return (
<>
{autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.FAILED && !is2FARequired && <ExpiredValidateCodeModal />}
{(autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN || autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.FAILED) && is2FARequired && !isSignedIn && !!login && (
{(autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN || autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.FAILED) && is2FARequired && !isSignedIn && (
<JustSignedInModal is2FARequired />
)}
{autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN && isSignedIn && !exitTo && !!login && <JustSignedInModal is2FARequired={false} />}
Expand All @@ -93,8 +135,9 @@ function ValidateLoginPage({
code={validateCode}
/>
)}
{(!effectiveAutoAuthState ? shouldStartSignInWithValidateCode : autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.SIGNING_IN) && (
{((!effectiveAutoAuthState ? shouldStartSignInWithValidateCode : autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.SIGNING_IN) || isCompletingDirectSignIn) && (
<FullScreenLoadingIndicator
testID="validate-login-loading"
reasonAttributes={{
context: 'ValidateLoginPage',
isSigningIn: autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.SIGNING_IN,
Expand Down
114 changes: 114 additions & 0 deletions tests/ui/ValidateLoginPageTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,35 @@ import {NavigationContainer} from '@react-navigation/native';
import {act, render, screen} from '@testing-library/react-native';
import React from 'react';
import Onyx from 'react-native-onyx';
import Navigation from '@libs/Navigation/Navigation';
import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator';
import type {PublicScreensParamList} from '@libs/Navigation/types';
import ValidateLoginPage from '@pages/ValidateLoginPage/index.web';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import SCREENS from '@src/SCREENS';
import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct';

// Controllable deferred so tests can assert the *ordering* guarantee (navigate only after
// protected routes are available) — not just the final args.
const mockWaitForProtectedRoutes = {resolve: () => {}};

jest.mock('@libs/Navigation/Navigation', () => ({
navigate: jest.fn(),
goBack: jest.fn(),
isNavigationReady: jest.fn(() => Promise.resolve()),
waitForProtectedRoutes: jest.fn(
() =>
new Promise<void>((resolve) => {
mockWaitForProtectedRoutes.resolve = resolve;
}),
),
getActiveRoute: jest.fn(() => ''),
getActiveRouteWithoutParams: jest.fn(() => ''),
isActiveRoute: jest.fn(() => false),
}));

const RootStack = createPlatformStackNavigator<PublicScreensParamList>();

const renderPage = (initialParams: PublicScreensParamList[typeof SCREENS.VALIDATE_LOGIN]) => {
Expand All @@ -35,6 +56,7 @@ describe('ValidateLoginPage', () => {

beforeEach(async () => {
jest.clearAllMocks();
mockWaitForProtectedRoutes.resolve = () => {};
await act(async () => {
await Onyx.clear();
});
Expand Down Expand Up @@ -67,4 +89,96 @@ describe('ValidateLoginPage', () => {

expect(screen.queryByTestId('validate-code')).toBeNull();
});

it('Should navigate to home only AFTER protected routes are available (separate-session magic link)', async () => {
await act(async () => {
await Onyx.set(ONYXKEYS.SESSION, {
authToken: 'abcd',
autoAuthState: CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN,
});
await Onyx.set(ONYXKEYS.CREDENTIALS, {
accountID: 1,
validateCode: '123456',
});
});

renderPage({accountID: '1', validateCode: '123456'});
await waitForBatchedUpdatesWithAct();

// Protected routes have not mounted yet: navigating now is the exact race,
// so navigate must NOT have been called. (This assertion fails for both the old
// isNavigationReady().then(goBack) and an unguarded navigate.)
expect(Navigation.navigate).not.toHaveBeenCalled();

await act(async () => {
mockWaitForProtectedRoutes.resolve();
await Promise.resolve();
});
await waitForBatchedUpdatesWithAct();

expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.HOME, {forceReplace: true});
});

it('Should not navigate to home when a signed-in session opens /v/ to view the code (autoAuthState !== JUST_SIGNED_IN)', async () => {
await act(async () => {
await Onyx.set(ONYXKEYS.SESSION, {
authToken: 'abcd',
autoAuthState: CONST.AUTO_AUTH_STATE.NOT_STARTED,
});
});

renderPage({accountID: '1', validateCode: '123456'});
await waitForBatchedUpdatesWithAct();

expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.HOME, {forceReplace: true});
expect(screen.getByTestId('validate-code')).toBeOnTheScreen();
});

it('Should keep the loading indicator (not blank) when JUST_SIGNED_IN but authToken has not landed yet', async () => {
// autoAuthState arrives before authToken (separate Onyx broadcasts), so there is a tick
// where autoAuthState === JUST_SIGNED_IN but isSignedIn is false. Without the fix every
// guard fails and the page is blank; the loader must stay up.
await act(async () => {
await Onyx.set(ONYXKEYS.CREDENTIALS, {
accountID: 1,
validateCode: '123456',
});
});

// Mount first (autoAuthState NOT_STARTED → shows the magic-code screen).
renderPage({accountID: '1', validateCode: '123456'});
await waitForBatchedUpdatesWithAct();
expect(screen.getByTestId('validate-code')).toBeOnTheScreen();

// First cross-tab broadcast: autoAuthState flips, authToken not delivered yet.
await act(async () => {
await Onyx.merge(ONYXKEYS.SESSION, {
autoAuthState: CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN,
});
});
await waitForBatchedUpdatesWithAct();

expect(screen.getByTestId('validate-login-loading')).toBeOnTheScreen();
expect(screen.queryByTestId('validate-code')).toBeNull();
// Not signed in yet, so we must not redirect prematurely.
expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.HOME, {forceReplace: true});
});

it('Should show the 2FA-required prompt (not an infinite loader) for a separate-session sign-in needing 2FA', async () => {
// Separate session: no cached `login`, signed in via the link but 2FA is required so authToken
// never lands. Without the fix isCompletingDirectSignIn keeps the loader up forever; instead we
// must surface the "2FA required" prompt and never redirect Home.
await act(async () => {
await Onyx.set(ONYXKEYS.ACCOUNT, {requiresTwoFactorAuth: true});
await Onyx.set(ONYXKEYS.SESSION, {
autoAuthState: CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN,
});
});

renderPage({accountID: '1', validateCode: '123456'});
await waitForBatchedUpdatesWithAct();

expect(screen.queryByTestId('validate-login-loading')).toBeNull();
expect(Navigation.navigate).not.toHaveBeenCalledWith(ROUTES.HOME, {forceReplace: true});
});
});
Loading
Loading