Repository navigation
Let users solve Cloudflare challenges with Turnstile on NewDot web - #105571
ShridharGoel wants to merge 10 commits into
Conversation
|
Hey, I noticed you changed If you want to automatically generate translations for other locales, an Expensify employee will have to:
Alternatively, if you are an external contributor, you can run the translation script locally with your own OpenAI API key. To learn more, try running: npx bun ./scripts/generateTranslations.ts --helpTypically, you'd want to translate only what you changed by running |
Codecov Report✅ Changes either increased or maintained existing code coverage, great job!
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@arosiclair 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] |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11c73dde1e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // set a cf_clearance cookie that satisfies the rule. | ||
| if (response.headers?.get(CONST.CLOUDFLARE_CHALLENGE.MITIGATED_HEADER) === CONST.CLOUDFLARE_CHALLENGE.MITIGATED.CHALLENGE) { | ||
| endSpan(downloadSpanId); | ||
| return requestCloudflareChallengeResolution().then(() => processHTTPRequest<TKey>(url, method, body, abortSignal, true, 'same-origin')); |
There was a problem hiding this comment.
Should we mark the request as already retried?
There was a problem hiding this comment.
yeah this should be updated to fail after a retry or at least have some way of getting out of here
| // set a cf_clearance cookie that satisfies the rule. | ||
| if (response.headers?.get(CONST.CLOUDFLARE_CHALLENGE.MITIGATED_HEADER) === CONST.CLOUDFLARE_CHALLENGE.MITIGATED.CHALLENGE) { | ||
| endSpan(downloadSpanId); | ||
| return requestCloudflareChallengeResolution().then(() => processHTTPRequest<TKey>(url, method, body, abortSignal, true, 'same-origin')); |
There was a problem hiding this comment.
I don't think this will work with same-origin, no?
There was a problem hiding this comment.
I'm not sure it even works cross origin since the API request is cross origin itself
There was a problem hiding this comment.
Updated to ensure cross-origin challenged requests fail fast with the normal error
justinpersaud
left a comment
There was a problem hiding this comment.
I'm not sure how this would work. don't we need to setup challenges to at least test this out?
| // set a cf_clearance cookie that satisfies the rule. | ||
| if (response.headers?.get(CONST.CLOUDFLARE_CHALLENGE.MITIGATED_HEADER) === CONST.CLOUDFLARE_CHALLENGE.MITIGATED.CHALLENGE) { | ||
| endSpan(downloadSpanId); | ||
| return requestCloudflareChallengeResolution().then(() => processHTTPRequest<TKey>(url, method, body, abortSignal, true, 'same-origin')); |
There was a problem hiding this comment.
I'm not sure it even works cross origin since the API request is cross origin itself
| // set a cf_clearance cookie that satisfies the rule. | ||
| if (response.headers?.get(CONST.CLOUDFLARE_CHALLENGE.MITIGATED_HEADER) === CONST.CLOUDFLARE_CHALLENGE.MITIGATED.CHALLENGE) { | ||
| endSpan(downloadSpanId); | ||
| return requestCloudflareChallengeResolution().then(() => processHTTPRequest<TKey>(url, method, body, abortSignal, true, 'same-origin')); |
There was a problem hiding this comment.
yeah this should be updated to fail after a retry or at least have some way of getting out of here
|
Is it better now? |
|
One comment from me, I think we can remove the first line of copy from the modal so it's just: Heading: We don't need to explain why this is being presented, just what they need to do |
|
@ShridharGoel Tested this end to end on staging, so we can move forward. For NewDot, staging and AdHoc builds can now read the |
There was a problem hiding this comment.
I think we can substantially simplify this code by removing the pub/sub and Onyx middle-man layer:
example diff
diff --git a/src/GlobalModals.tsx b/src/GlobalModals.tsx
index c1daaa342af..faab4b7fc0f 100644
--- a/src/GlobalModals.tsx
+++ b/src/GlobalModals.tsx
@@ -1,6 +1,6 @@
import React, {startTransition, useEffect, useState} from 'react';
-import CloudflareChallengeModal from './components/CloudflareChallengeModal';
+import useCloudflareChallengeModal from './components/CloudflareChallengeModal/useCloudflareChallengeModal';
import DelegateNoAccessModalProvider from './components/DelegateNoAccessModalProvider';
import EmojiPicker from './components/EmojiPicker/EmojiPicker';
import ExpenseAddedGrowl from './components/ExpenseAddedGrowl';
@@ -26,6 +26,7 @@ function GlobalModals() {
const [shouldRenderContextMenu, setShouldRenderContextMenu] = useState(false);
const [shouldRenderDeferredModals, setShouldRenderDeferredModals] = useState(false);
const isAuthenticated = useIsAuthenticated();
+ useCloudflareChallengeModal();
// Defer loading the context menu and rare-condition modals until after startup to avoid
// pulling in their dependencies (ContextMenuActions, ReportUtils, ModifiedExpenseMessage,
@@ -53,7 +54,6 @@ function GlobalModals() {
<>
<GrowlNotification ref={growlRef} />
{isAuthenticated && <ExpenseAddedGrowl />}
- <CloudflareChallengeModal />
<DelegateNoAccessModalProvider>
{shouldRenderContextMenu && (
<LazyModalSlot>
diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts
index 202f03cab79..4517c9b25c3 100755
--- a/src/ONYXKEYS.ts
+++ b/src/ONYXKEYS.ts
@@ -589,9 +589,6 @@ const ONYXKEYS = {
*/
RAM_ONLY_IS_CHECKING_PENDING_WALLET_APPROVAL: 'isCheckingPendingWalletApproval',
- /** Whether the modal with the Turnstile check is currently shown. RAM only, so it never persists across launches */
- RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN: 'isCloudflareChallengeModalOpen',
-
/** The report ID of the public room that the user is currently viewing */
VIEWING_PUBLIC_ROOM_REPORT_ID: 'ViewingPublicRoomReportID',
@@ -2062,7 +2059,6 @@ type OnyxValuesMapping = {
[ONYXKEYS.LAST_ACCESSED_WORKSPACE_POLICY_ID]: string;
[ONYXKEYS.RAM_ONLY_IS_CHECKING_PUBLIC_ROOM]: boolean;
[ONYXKEYS.RAM_ONLY_IS_CHECKING_PENDING_WALLET_APPROVAL]: boolean;
- [ONYXKEYS.RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN]: boolean;
[ONYXKEYS.VIEWING_PUBLIC_ROOM_REPORT_ID]: string;
[ONYXKEYS.MY_DOMAIN_SECURITY_GROUPS]: Record<string, OnyxTypes.DomainSecurityGroupMembership>;
[ONYXKEYS.RAM_ONLY_DOMAIN_MEMBERS_SELECTED_FOR_MOVE]: string[];
diff --git a/src/components/CloudflareChallengeModal/CloudflareChallengeModal.tsx b/src/components/CloudflareChallengeModal/CloudflareChallengeModal.tsx
new file mode 100644
index 00000000000..e75623a9cbb
--- /dev/null
+++ b/src/components/CloudflareChallengeModal/CloudflareChallengeModal.tsx
@@ -0,0 +1,45 @@
+import HeaderTitle from '@components/HeaderTitle';
+import Modal from '@components/Modal';
+import type {ModalProps} from '@components/Modal/Global/ModalContext';
+import Text from '@components/Text';
+
+import useLocalize from '@hooks/useLocalize';
+import useThemeStyles from '@hooks/useThemeStyles';
+
+import CONST from '@src/CONST';
+
+import React from 'react';
+import {View} from 'react-native';
+
+import TurnstileWidget from './TurnstileWidget';
+
+type CloudflareChallengeModalProps = ModalProps & {
+ onSuccess: () => void;
+ onDismiss: () => void;
+};
+
+function CloudflareChallengeModal({onSuccess, onDismiss}: CloudflareChallengeModalProps) {
+ const {translate} = useLocalize();
+ const styles = useThemeStyles();
+
+ return (
+ <Modal
+ type={CONST.MODAL.MODAL_TYPE.CONFIRM}
+ isVisible
+ onClose={onDismiss}
+ >
+ <View style={[styles.p5]}>
+ <HeaderTitle>
+ <HeaderTitle.Text style={[styles.mb2]}>{translate('cloudflareChallengeModal.title')}</HeaderTitle.Text>
+ </HeaderTitle>
+ <Text style={[styles.mb4]}>{translate('cloudflareChallengeModal.body')}</Text>
+ <TurnstileWidget
+ onSuccess={onSuccess}
+ onLoadFailure={onDismiss}
+ />
+ </View>
+ </Modal>
+ );
+}
+
+export default CloudflareChallengeModal;
diff --git a/src/components/CloudflareChallengeModal/TurnstileWidget/index.native.ts b/src/components/CloudflareChallengeModal/TurnstileWidget/index.native.ts
new file mode 100644
index 00000000000..d6af10b3566
--- /dev/null
+++ b/src/components/CloudflareChallengeModal/TurnstileWidget/index.native.ts
@@ -0,0 +1,6 @@
+// Turnstile needs a browser DOM, so native does not render a widget.
+function TurnstileWidget() {
+ return null;
+}
+
+export default TurnstileWidget;
diff --git a/src/components/CloudflareChallengeModal/TurnstileWidget/index.ts b/src/components/CloudflareChallengeModal/TurnstileWidget/index.ts
new file mode 100644
index 00000000000..e616efa6480
--- /dev/null
+++ b/src/components/CloudflareChallengeModal/TurnstileWidget/index.ts
@@ -0,0 +1,86 @@
+/** Owns the Turnstile script and ties the widget's lifetime to its DOM container. */
+import Log from '@libs/Log';
+
+import CONST from '@src/CONST';
+
+import {createElement} from 'react';
+
+let turnstileScriptLoadPromise: Promise<TurnstileApi> | undefined;
+
+/**
+ * Explicit rendering lets us wait for the widget's container. Failed loads aren't cached so a later challenge can retry.
+ */
+function loadTurnstileScript(): Promise<TurnstileApi> {
+ if (turnstileScriptLoadPromise) {
+ return turnstileScriptLoadPromise;
+ }
+ const scriptLoadPromise = new Promise<TurnstileApi>((resolve, reject) => {
+ const script = document.createElement('script');
+ script.src = `${CONST.CLOUDFLARE_CHALLENGE.TURNSTILE.SCRIPT_URL}?render=explicit`;
+ script.async = true;
+ const failToLoad = () => {
+ script.remove();
+ reject(new Error('Failed to load the Turnstile script'));
+ };
+ script.onload = () => {
+ if (!window.turnstile) {
+ failToLoad();
+ return;
+ }
+ resolve(window.turnstile);
+ };
+ script.onerror = failToLoad;
+ document.head.appendChild(script);
+ });
+ scriptLoadPromise.catch(() => {
+ turnstileScriptLoadPromise = undefined;
+ });
+ turnstileScriptLoadPromise = scriptLoadPromise;
+ return scriptLoadPromise;
+}
+
+type TurnstileWidgetProps = {
+ onSuccess: () => void;
+ onLoadFailure: () => void;
+};
+
+function TurnstileWidget({onSuccess, onLoadFailure}: TurnstileWidgetProps) {
+ function mountWidget(widgetContainer: HTMLDivElement | null) {
+ if (!widgetContainer) {
+ return;
+ }
+ let isDetached = false;
+ let removeWidget: (() => void) | undefined;
+ loadTurnstileScript()
+ .then((turnstile) => {
+ if (isDetached) {
+ return;
+ }
+ const widgetID = turnstile.render(widgetContainer, {
+ sitekey: CONST.CLOUDFLARE_CHALLENGE.TURNSTILE.SITEKEY,
+ callback: onSuccess,
+ // The widget shows its own error state and retry option, so these only record what happened
+ // eslint-disable-next-line @typescript-eslint/naming-convention -- Cloudflare uses these names
+ 'error-callback': (errorCode: string) => Log.hmmm('Turnstile widget failed', {errorCode}),
+ // eslint-disable-next-line @typescript-eslint/naming-convention -- Cloudflare uses these names
+ 'expired-callback': () => Log.hmmm('Turnstile widget token expired'),
+ });
+ removeWidget = () => turnstile.remove(widgetID);
+ })
+ .catch((error: unknown) => {
+ if (isDetached) {
+ return;
+ }
+ Log.hmmm('Turnstile widget failed to initialize', {error});
+ onLoadFailure();
+ });
+ return () => {
+ isDetached = true;
+ removeWidget?.();
+ };
+ }
+
+ return createElement('div', {ref: mountWidget});
+}
+
+export default TurnstileWidget;
diff --git a/src/components/CloudflareChallengeModal/index.tsx b/src/components/CloudflareChallengeModal/index.tsx
deleted file mode 100644
index 39a790994e1..00000000000
--- a/src/components/CloudflareChallengeModal/index.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-// Only browsers can show the Turnstile check, so challenged requests on native fail before this modal could open.
-// Keeping the no-op component lets shared code import CloudflareChallengeModal on every platform.
-function CloudflareChallengeModal() {
- return null;
-}
-
-export default CloudflareChallengeModal;
diff --git a/src/components/CloudflareChallengeModal/index.web.tsx b/src/components/CloudflareChallengeModal/index.web.tsx
deleted file mode 100644
index c317c92d89b..00000000000
--- a/src/components/CloudflareChallengeModal/index.web.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import HeaderTitle from '@components/HeaderTitle';
-import Modal from '@components/Modal';
-import Text from '@components/Text';
-
-import useLocalize from '@hooks/useLocalize';
-import useOnyx from '@hooks/useOnyx';
-import useThemeStyles from '@hooks/useThemeStyles';
-
-import {rejectCloudflareChallenge, resolveCloudflareChallenge, setIsChallengeModalMounted} from '@libs/actions/CloudflareChallenge';
-import Log from '@libs/Log';
-
-import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-import viewRef from '@src/types/utils/viewRef';
-
-import React, {useEffect, useRef} from 'react';
-import {View} from 'react-native';
-
-let turnstileScriptLoadPromise: Promise<void> | undefined;
-
-/**
- * Loads the Turnstile script once. Explicit rendering keeps control over when and where the widget appears, so the
- * modal opens before any third-party code runs. A failed load is dropped from the cache so the next challenged
- * request can try again instead of inheriting the rejection.
- */
-function loadTurnstileScript(): Promise<void> {
- if (turnstileScriptLoadPromise) {
- return turnstileScriptLoadPromise;
- }
- const scriptLoadPromise = new Promise<void>((resolve, reject) => {
- const script = document.createElement('script');
- script.src = `${CONST.CLOUDFLARE_CHALLENGE.TURNSTILE.SCRIPT_URL}?render=explicit`;
- script.async = true;
- script.onload = () => resolve();
- script.onerror = () => {
- script.remove();
- reject(new Error('Failed to load the Turnstile script'));
- };
- document.head.appendChild(script);
- });
- scriptLoadPromise.catch(() => {
- turnstileScriptLoadPromise = undefined;
- });
- turnstileScriptLoadPromise = scriptLoadPromise;
- return scriptLoadPromise;
-}
-
-/**
- * Modal with the Turnstile check. Cloudflare challenged a request, and passing the check sets a cf_clearance cookie
- * that lets the challenged request retry successfully.
- */
-function CloudflareChallengeModal() {
- const [isCloudflareChallengeModalOpen = false] = useOnyx(ONYXKEYS.RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN);
- const {translate} = useLocalize();
- const styles = useThemeStyles();
- const widgetContainerRef = useRef<HTMLDivElement>(null);
-
- // Requests challenged while the modal is not mounted must fail instead of waiting for a promise nothing resolves
- useEffect(() => {
- setIsChallengeModalMounted(true);
- return () => setIsChallengeModalMounted(false);
- }, []);
-
- useEffect(() => {
- if (!isCloudflareChallengeModalOpen) {
- return;
- }
- let isEffectCleanedUp = false;
- let widgetId: string | undefined;
- loadTurnstileScript()
- .then(() => {
- if (isEffectCleanedUp) {
- return;
- }
- const widgetContainer = widgetContainerRef.current;
- if (!widgetContainer || !window.turnstile) {
- return;
- }
- const turnstileOptions: TurnstileRenderOptions = {
- sitekey: CONST.CLOUDFLARE_CHALLENGE.TURNSTILE.SITEKEY,
- callback: () => resolveCloudflareChallenge(),
- // The widget shows its own error state and retry option, so these only record what happened
- // eslint-disable-next-line @typescript-eslint/naming-convention -- Cloudflare uses these names
- 'error-callback': (errorCode: string) => Log.hmmm('Turnstile widget failed', {errorCode}),
- // eslint-disable-next-line @typescript-eslint/naming-convention -- Cloudflare uses these names
- 'expired-callback': () => Log.hmmm('Turnstile widget token expired'),
- };
- widgetId = window.turnstile.render(widgetContainer, turnstileOptions);
- })
- .catch((error: unknown) => {
- if (isEffectCleanedUp) {
- return;
- }
- Log.hmmm('Turnstile script failed to load', {error});
- rejectCloudflareChallenge();
- });
- return () => {
- isEffectCleanedUp = true;
- if (widgetId) {
- window.turnstile?.remove(widgetId);
- }
- };
- }, [isCloudflareChallengeModalOpen]);
-
- return (
- <Modal
- type={CONST.MODAL.MODAL_TYPE.CONFIRM}
- isVisible={isCloudflareChallengeModalOpen}
- onClose={rejectCloudflareChallenge}
- >
- <View style={[styles.p5]}>
- <HeaderTitle>
- <HeaderTitle.Text style={[styles.mb2]}>{translate('cloudflareChallengeModal.title')}</HeaderTitle.Text>
- </HeaderTitle>
- <Text style={[styles.mb4]}>{translate('cloudflareChallengeModal.body')}</Text>
- <View
- ref={viewRef(widgetContainerRef)}
- style={[styles.w100]}
- />
- </View>
- </Modal>
- );
-}
-
-export default CloudflareChallengeModal;
diff --git a/src/components/CloudflareChallengeModal/useCloudflareChallengeModal/index.native.ts b/src/components/CloudflareChallengeModal/useCloudflareChallengeModal/index.native.ts
new file mode 100644
index 00000000000..3a6798100c9
--- /dev/null
+++ b/src/components/CloudflareChallengeModal/useCloudflareChallengeModal/index.native.ts
@@ -0,0 +1,4 @@
+// Native cannot present the browser-only Turnstile widget.
+function useCloudflareChallengeModal() {}
+
+export default useCloudflareChallengeModal;
diff --git a/src/components/CloudflareChallengeModal/useCloudflareChallengeModal/index.ts b/src/components/CloudflareChallengeModal/useCloudflareChallengeModal/index.ts
new file mode 100644
index 00000000000..91ca95d44fc
--- /dev/null
+++ b/src/components/CloudflareChallengeModal/useCloudflareChallengeModal/index.ts
@@ -0,0 +1,47 @@
+/** Lets HTTP actions open the challenge through the global modal stack. */
+import CloudflareChallengeModal from '@components/CloudflareChallengeModal/CloudflareChallengeModal';
+import {ModalActions, useModal} from '@components/Modal/Global/ModalContext';
+
+import {cloudflareChallengeModalRef} from '@libs/actions/CloudflareChallenge';
+
+import {useEffect, useImperativeHandle, useRef} from 'react';
+
+let nextChallengeID = 0;
+
+function useCloudflareChallengeModal() {
+ const modal = useModal();
+ const dismissRef = useRef<(() => void) | undefined>(undefined);
+
+ function show() {
+ nextChallengeID += 1;
+ // Scope widget callbacks to this entry so a late callback cannot close a newer modal.
+ const id = `cloudflare-challenge-${nextChallengeID}`;
+ const result = modal.showModal({
+ component: CloudflareChallengeModal,
+ id,
+ props: {
+ onSuccess: () => modal.closeModalByID(id, {action: ModalActions.CONFIRM}),
+ onDismiss: () => modal.closeModalByID(id),
+ },
+ });
+
+ // If the host unmounts, the provider might unmount too and never process the close.
+ const cancelled = Promise.withResolvers<boolean>();
+ const dismiss = () => {
+ cancelled.resolve(false);
+ modal.closeModalByID(id);
+ };
+ dismissRef.current = dismiss;
+ return Promise.race([result.then(({action}) => action === ModalActions.CONFIRM), cancelled.promise]).finally(() => {
+ if (dismissRef.current !== dismiss) {
+ return;
+ }
+ dismissRef.current = undefined;
+ });
+ }
+
+ useImperativeHandle(cloudflareChallengeModalRef, () => ({show, dismiss: () => dismissRef.current?.()}));
+ useEffect(() => () => dismissRef.current?.(), []);
+}
+
+export default useCloudflareChallengeModal;
diff --git a/src/libs/ExportOnyxState/masking.ts b/src/libs/ExportOnyxState/masking.ts
index f56e37c1376..c5c46a1e61b 100644
--- a/src/libs/ExportOnyxState/masking.ts
+++ b/src/libs/ExportOnyxState/masking.ts
@@ -390,7 +390,6 @@ const safeOnyxKeys = new Set<string>([
ONYXKEYS.RAM_ONLY_IS_AUTHENTICATING_WITH_SHORT_LIVED_TOKEN,
ONYXKEYS.RAM_ONLY_IS_CHECKING_PENDING_WALLET_APPROVAL,
ONYXKEYS.RAM_ONLY_IS_CHECKING_PUBLIC_ROOM,
- ONYXKEYS.RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN,
ONYXKEYS.RAM_ONLY_IS_LOADING_DEPOSIT_ACCOUNT_SETUP,
ONYXKEYS.RAM_ONLY_IS_LOADING_SEARCH_FILTERS_CARD_DATA,
ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS,
diff --git a/src/libs/HttpUtils.ts b/src/libs/HttpUtils.ts
index cec9e42b4af..b768ce51382 100644
--- a/src/libs/HttpUtils.ts
+++ b/src/libs/HttpUtils.ts
@@ -217,7 +217,7 @@ function attemptRequest<TKey extends OnyxKey>(
}
return response;
})
- .then((response) => {
+ .then<AttemptResult<TKey>>((response) => {
// Test mode where all requests will succeed in the server, but fail to return a response
if (shouldFailAllRequests || shouldForceOffline) {
throw new HttpsError({
diff --git a/src/libs/actions/CloudflareChallenge.ts b/src/libs/actions/CloudflareChallenge.ts
index bdc9e341bc3..642bcc1d58e 100644
--- a/src/libs/actions/CloudflareChallenge.ts
+++ b/src/libs/actions/CloudflareChallenge.ts
@@ -1,35 +1,24 @@
-/**
- * Coordinates the Cloudflare challenge: shows the Turnstile modal and settles every request that was challenged
- * while the check was pending.
- */
+/** Shares a single pending Cloudflare challenge across requests until it is solved or rejected. */
import {READ_COMMANDS} from '@libs/API/types';
import HttpsError from '@libs/Errors/HttpsError';
-import getPlatform from '@libs/getPlatform';
import {registerSessionCleanupCallback} from '@libs/SessionCleanup';
import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-import Onyx from 'react-native-onyx';
+import {createRef} from 'react';
+
+type CloudflareChallengeModalHandle = {
+ show: () => Promise<boolean>;
+ dismiss: () => void;
+};
-let challengeResolution: ReturnType<typeof Promise.withResolvers<void>> | undefined;
+const cloudflareChallengeModalRef = createRef<CloudflareChallengeModalHandle>();
+let pendingChallenge: Promise<void> | undefined;
// Cloudflare keeps challenging BeginSignIn until the cf_clearance cookie is sent.
// This flag lasts until sign-out so later BeginSignIn requests reuse the clearance cookie.
let hasClearedChallenge = false;
-// The modal lives in GlobalModals, which mounts once navigation is ready.
-// Requests challenged before that must fail instead of waiting on a promise that never resolves.
-let isChallengeModalMounted = false;
-
-function setIsChallengeModalMounted(isMounted: boolean) {
- isChallengeModalMounted = isMounted;
-}
-
-function setIsCloudflareChallengeModalOpen(isOpen: boolean) {
- Onyx.merge(ONYXKEYS.RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN, isOpen);
-}
-
/** The error returned when a challenge cannot be solved so callers handle it like a normal failure. */
function createUnsolvedChallengeError(status: number = CONST.HTTP_STATUS.FORBIDDEN) {
return new HttpsError({
@@ -39,17 +28,11 @@ function createUnsolvedChallengeError(status: number = CONST.HTTP_STATUS.FORBIDD
});
}
-/** Rejects the pending challenge with an error matching the HTTP failure the challenge response represents. */
-function rejectCloudflareChallenge() {
- setIsCloudflareChallengeModalOpen(false);
- challengeResolution?.reject(createUnsolvedChallengeError());
- challengeResolution = undefined;
-}
-
/** Clears challenge state on sign-out so a new session starts without stale clearance state. */
function resetCloudflareChallengeState() {
hasClearedChallenge = false;
- rejectCloudflareChallenge();
+ pendingChallenge = undefined;
+ cloudflareChallengeModalRef.current?.dismiss();
}
registerSessionCleanupCallback(resetCloudflareChallengeState);
@@ -59,29 +42,34 @@ function getRequestCredentials(command?: string): RequestCredentials {
return command === READ_COMMANDS.BEGIN_SIGNIN && hasClearedChallenge ? 'include' : 'omit';
}
-/** Resolves the challenge every waiting request shares, because one passed check clears the rule for all of them. */
-function resolveCloudflareChallenge() {
- hasClearedChallenge = true;
- setIsCloudflareChallengeModalOpen(false);
- challengeResolution?.resolve();
- challengeResolution = undefined;
-}
-
/**
- * Waits for the user to pass the Cloudflare challenge. Shows the Turnstile modal, and every request challenged
- * while the check is pending waits on the same promise.
+ * Concurrent requests share the result of the same modal.
*/
function requestCloudflareChallengeResolution(): Promise<void> {
- // The widget needs a browser, and the native cookie jar cannot hold the cf_clearance cookie.
- if (getPlatform() !== CONST.PLATFORM.WEB || !isChallengeModalMounted) {
+ const modal = cloudflareChallengeModalRef.current;
+ if (!modal) {
return Promise.reject(createUnsolvedChallengeError());
}
- if (challengeResolution) {
- return challengeResolution.promise;
+ if (pendingChallenge) {
+ return pendingChallenge;
}
- challengeResolution = Promise.withResolvers<void>();
- setIsCloudflareChallengeModalOpen(true);
- return challengeResolution.promise;
+ const request = modal
+ .show()
+ .then((isSolved) => {
+ // Sign-out can invalidate a result before this callback runs.
+ if (!isSolved || pendingChallenge !== request) {
+ throw createUnsolvedChallengeError();
+ }
+ hasClearedChallenge = true;
+ })
+ .finally(() => {
+ if (pendingChallenge !== request) {
+ return;
+ }
+ pendingChallenge = undefined;
+ });
+ pendingChallenge = request;
+ return request;
}
-export {createUnsolvedChallengeError, getRequestCredentials, rejectCloudflareChallenge, requestCloudflareChallengeResolution, resolveCloudflareChallenge, setIsChallengeModalMounted};
+export {cloudflareChallengeModalRef, createUnsolvedChallengeError, getRequestCredentials, requestCloudflareChallengeResolution};
diff --git a/src/setup/index.ts b/src/setup/index.ts
index 16802b0bc68..7bb9c86880d 100644
--- a/src/setup/index.ts
+++ b/src/setup/index.ts
@@ -129,7 +129,6 @@ export default function () {
ONYXKEYS.RAM_ONLY_WORKSPACE_CATEGORIES_SELECTED_FOR_BULK_EDIT,
ONYXKEYS.RAM_ONLY_HAS_DISMISSED_CONCIERGE_NOTIFICATION_BANNER,
ONYXKEYS.RAM_ONLY_ENABLE_GLOBAL_REIMBURSEMENTS_MODAL,
- ONYXKEYS.RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN,
ONYXKEYS.RAM_ONLY_MEMBERS_NEED_CATEGORY_MODAL,
ONYXKEYS.RAM_ONLY_WISE_ONBOARDING_PENDING_SAVES,
ONYXKEYS.RAM_ONLY_WISE_INTRO_READ_BANK_ACCOUNT_ID,
diff --git a/tests/unit/CloudflareChallengeTest.ts b/tests/unit/CloudflareChallengeTest.ts
index cf64abd78ac..3b81024f298 100644
--- a/tests/unit/CloudflareChallengeTest.ts
+++ b/tests/unit/CloudflareChallengeTest.ts
@@ -1,87 +1,54 @@
-import {
- getRequestCredentials,
- rejectCloudflareChallenge,
- requestCloudflareChallengeResolution,
- resolveCloudflareChallenge,
- setIsChallengeModalMounted,
-} from '@libs/actions/CloudflareChallenge';
+import {cloudflareChallengeModalRef, getRequestCredentials, requestCloudflareChallengeResolution} from '@libs/actions/CloudflareChallenge';
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import {runSessionCleanupCallbacks} from '@libs/SessionCleanup';
import CONST from '@src/CONST';
-import ONYXKEYS from '@src/ONYXKEYS';
-import Onyx from 'react-native-onyx';
-
-import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
-
-const mockGetPlatform = jest.fn<string, []>(() => CONST.PLATFORM.WEB);
-
-jest.mock('@libs/getPlatform', () => ({
- __esModule: true,
- default: () => mockGetPlatform(),
-}));
-
-beforeAll(() => {
- Onyx.init({
- keys: ONYXKEYS,
- });
+let completeChallenge: (isSolved: boolean) => void;
+const show = jest.fn(() => {
+ const {promise, resolve} = Promise.withResolvers<boolean>();
+ completeChallenge = resolve;
+ return promise;
});
-beforeEach(async () => {
- mockGetPlatform.mockReturnValue(CONST.PLATFORM.WEB);
- setIsChallengeModalMounted(true);
+beforeEach(() => {
runSessionCleanupCallbacks();
- await waitForBatchedUpdates();
+ show.mockClear();
+ cloudflareChallengeModalRef.current = {show, dismiss: () => completeChallenge(false)};
});
-afterEach(async () => {
+afterEach(() => {
+ cloudflareChallengeModalRef.current = null;
runSessionCleanupCallbacks();
- setIsChallengeModalMounted(false);
- await waitForBatchedUpdates();
});
describe('CloudflareChallenge', () => {
- it('opens the modal, shares one promise across waiting requests, and enables include credentials only for BeginSignIn', async () => {
- // Given a web session with the challenge modal mounted and no prior clearance
+ it('opens one modal for concurrent requests and enables credentials only for BeginSignIn', async () => {
+ // Given no prior clearance
expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('omit');
- expect(getRequestCredentials(WRITE_COMMANDS.ADD_COMMENT)).toBe('omit');
- // When two requests wait on the Cloudflare challenge concurrently and the user completes it
+ // When two requests are challenged and the user completes the modal
const firstRequest = requestCloudflareChallengeResolution();
const secondRequest = requestCloudflareChallengeResolution();
- await waitForBatchedUpdates();
-
- const isModalOpen = await Onyx.get(ONYXKEYS.RAM_ONLY_IS_CLOUDFLARE_CHALLENGE_MODAL_OPEN);
- expect(isModalOpen).toBe(true);
-
- resolveCloudflareChallenge();
+ completeChallenge(true);
await Promise.all([firstRequest, secondRequest]);
- // Then only BeginSignIn uses include credentials so other commands do not send cookies
+ // Then both requests share one modal, and only BeginSignIn can send the clearance cookie
+ expect(show).toHaveBeenCalledTimes(1);
+ expect(secondRequest).toBe(firstRequest);
expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('include');
expect(getRequestCredentials(WRITE_COMMANDS.ADD_COMMENT)).toBe('omit');
});
- it('rejects immediately on native platforms', async () => {
- // Given a native platform where the Turnstile browser widget cannot run
- mockGetPlatform.mockReturnValue(CONST.PLATFORM.IOS);
+ it('rejects immediately when the modal is unavailable', async () => {
+ // Given that there is no modal to show, as on native or before the browser modal mounts
+ cloudflareChallengeModalRef.current = null;
// When a request asks for challenge resolution
- // Then it rejects with the standard service interrupted error
- await expect(requestCloudflareChallengeResolution()).rejects.toMatchObject({
- message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED,
- status: CONST.HTTP_STATUS.FORBIDDEN.toString(),
- });
- });
-
- it('rejects immediately when the modal is not mounted', async () => {
- // Given the challenge modal has not mounted yet
- setIsChallengeModalMounted(false);
+ const request = requestCloudflareChallengeResolution();
- // When a request asks for challenge resolution
- // Then it rejects instead of waiting forever
- await expect(requestCloudflareChallengeResolution()).rejects.toMatchObject({
+ // Then it fails rather than waiting for the modal
+ await expect(request).rejects.toMatchObject({
message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED,
status: CONST.HTTP_STATUS.FORBIDDEN.toString(),
});
@@ -89,36 +56,42 @@ describe('CloudflareChallenge', () => {
it('rejects pending requests when the challenge is dismissed', async () => {
// Given a pending Cloudflare challenge
- const pendingChallenge = requestCloudflareChallengeResolution();
+ const request = requestCloudflareChallengeResolution();
// When the user closes the modal
- rejectCloudflareChallenge();
+ completeChallenge(false);
- // Then the waiting request rejects and credentials stay omitted
- await expect(pendingChallenge).rejects.toMatchObject({
- message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED,
- status: CONST.HTTP_STATUS.FORBIDDEN.toString(),
- });
+ // Then the waiting request fails and credentials stay omitted
+ await expect(request).rejects.toMatchObject({message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED});
expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('omit');
});
- it('resets clearance state and rejects pending challenges on sign-out', async () => {
- // Given a session that previously cleared a challenge and has a new pending challenge
- const firstChallenge = requestCloudflareChallengeResolution();
- resolveCloudflareChallenge();
- await firstChallenge;
+ it('resets clearance and dismisses any pending challenge on sign-out', async () => {
+ // Given a session that previously cleared a challenge and has a new one pending
+ const firstRequest = requestCloudflareChallengeResolution();
+ completeChallenge(true);
+ await firstRequest;
expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('include');
+ const request = requestCloudflareChallengeResolution();
- const pendingChallenge = requestCloudflareChallengeResolution();
+ // When the user signs out
+ runSessionCleanupCallbacks();
- // When session cleanup runs on sign-out
+ // Then the pending request fails and the next session starts without clearance
+ await expect(request).rejects.toMatchObject({message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED});
+ expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('omit');
+ });
+
+ it('ignores a success result that has not been handled when the user signs out', async () => {
+ // Given a challenge that has just been solved
+ const request = requestCloudflareChallengeResolution();
+ completeChallenge(true);
+
+ // When the user signs out before the request observes the modal result
runSessionCleanupCallbacks();
- // Then the pending challenge rejects and BeginSignIn returns to omit credentials
- await expect(pendingChallenge).rejects.toMatchObject({
- message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED,
- status: CONST.HTTP_STATUS.FORBIDDEN.toString(),
- });
+ // Then the previous session's success cannot restore clearance
+ await expect(request).rejects.toMatchObject({message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED});
expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('omit');
});
});
diff --git a/tests/unit/components/CloudflareChallengeModalTest.tsx b/tests/unit/components/CloudflareChallengeModalTest.tsx
new file mode 100644
index 00000000000..05e0cf030d5
--- /dev/null
+++ b/tests/unit/components/CloudflareChallengeModalTest.tsx
@@ -0,0 +1,138 @@
+import type TurnstileWidget from '@components/CloudflareChallengeModal/TurnstileWidget';
+import {ModalProvider} from '@components/Modal/Global/ModalContext';
+
+import {getRequestCredentials, requestCloudflareChallengeResolution} from '@libs/actions/CloudflareChallenge';
+import {READ_COMMANDS} from '@libs/API/types';
+import {runSessionCleanupCallbacks} from '@libs/SessionCleanup';
+
+import CONST from '@src/CONST';
+
+import type {ReactNode} from 'react';
+import type {Root} from 'react-dom/client';
+
+import React, {act} from 'react';
+import {createRoot} from 'react-dom/client';
+
+/* eslint-disable testing-library/no-unnecessary-act -- This test drives a React DOM root directly. */
+
+let mockSetAreModalChildrenMounted: (isMounted: boolean) => void;
+let mockDismissModal: (() => void) | undefined;
+
+jest.mock('@components/Modal', () => {
+ const {useState} = jest.requireActual<typeof React>('react');
+ return function DeferredModal({isVisible, children, onClose}: {isVisible: boolean; children: ReactNode; onClose?: () => void}) {
+ const [areChildrenMounted, setAreChildrenMounted] = useState(false);
+ mockSetAreModalChildrenMounted = setAreChildrenMounted;
+ mockDismissModal = onClose;
+ return isVisible && areChildrenMounted ? children : null;
+ };
+});
+jest.mock('@components/HeaderTitle', () => Object.assign(({children}: {children: ReactNode}) => children, {Text: ({children}: {children: ReactNode}) => children}));
+jest.mock(
+ '@components/Text',
+ () =>
+ ({children}: {children: ReactNode}) =>
+ children,
+);
+jest.mock('@hooks/useLocalize', () => () => ({translate: (key: string) => key}));
+jest.mock('@hooks/useThemeStyles', () => () => ({}));
+
+// Jest selects the native entry point by default, but this test exercises the browser widget.
+jest.mock('@components/CloudflareChallengeModal/TurnstileWidget', () =>
+ jest.requireActual<{default: typeof TurnstileWidget}>('@components/CloudflareChallengeModal/TurnstileWidget/index.ts'),
+);
+
+const useCloudflareChallengeModal = jest.requireActual<{default: () => void}>('@components/CloudflareChallengeModal/useCloudflareChallengeModal/index.ts').default;
+
+function ChallengeModalHost() {
+ useCloudflareChallengeModal();
+ return null;
+}
+
+describe('CloudflareChallengeModal on web', () => {
+ let root: Root;
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ mockDismissModal = undefined;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root.render(
+ <ModalProvider>
+ <ChallengeModalHost />
+ </ModalProvider>,
+ );
+ });
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ delete window.turnstile;
+ document.querySelector(`script[src^="${CONST.CLOUDFLARE_CHALLENGE.TURNSTILE.SCRIPT_URL}"]`)?.remove();
+ runSessionCleanupCallbacks();
+ });
+
+ it('renders again from the cached script when the modal mounts its content after opening', async () => {
+ // Given a widget that has loaded once and whose challenge has been dismissed
+ const renderWidget = jest.fn<string, [HTMLElement, TurnstileRenderOptions]>().mockReturnValueOnce('first-widget').mockReturnValueOnce('second-widget');
+ const removeWidget = jest.fn();
+ window.turnstile = {render: renderWidget, remove: removeWidget};
+ expect(mockDismissModal).toBeUndefined();
+ let firstRequest: Promise<void> | undefined;
+ act(() => {
+ firstRequest = startChallenge();
+ });
+ act(() => mockSetAreModalChildrenMounted(true));
+ const script = document.querySelector(`script[src^="${CONST.CLOUDFLARE_CHALLENGE.TURNSTILE.SCRIPT_URL}"]`);
+ expect(script).not.toBeNull();
+ await act(async () => {
+ script?.dispatchEvent(new Event('load'));
+ });
+ expect(renderWidget).toHaveBeenCalledTimes(1);
+
+ const firstRejection = expect(firstRequest).rejects.toMatchObject({message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED});
+ act(() => mockDismissModal?.());
+ await firstRejection;
+ expect(removeWidget).toHaveBeenCalledWith('first-widget');
+
+ // When another challenge opens before the modal has mounted its children
+ let secondRequest: Promise<void> | undefined;
+ await act(async () => {
+ secondRequest = startChallenge();
+ });
+ expect(renderWidget).toHaveBeenCalledTimes(1);
+ await act(async () => mockSetAreModalChildrenMounted(true));
+
+ // Then the widget renders once its container exists, and only its own callback settles the request
+ expect(renderWidget).toHaveBeenCalledTimes(2);
+ expect(container.contains(renderWidget.mock.calls.at(1)?.[0] ?? null)).toBe(true);
+ await act(async () => renderWidget.mock.calls.at(0)?.[1].callback('stale-token'));
+ expect(getRequestCredentials(READ_COMMANDS.BEGIN_SIGNIN)).toBe('omit');
+ act(() => renderWidget.mock.calls.at(1)?.[1].callback('current-token'));
+ await expect(secondRequest).resolves.toBeUndefined();
+ });
+
+ it('rejects pending requests if the modal host unmounts', async () => {
+ // Given a pending request before the widget mounts
+ let request: Promise<void> | undefined;
+ act(() => {
+ request = startChallenge();
+ });
+
+ // When the modal host unmounts
+ act(() => root.render(null));
+
+ // Then requests waiting for the modal result fail
+ await expect(request).rejects.toMatchObject({message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED});
+ });
+});
+
+function startChallenge() {
+ const request = requestCloudflareChallengeResolution();
+ // Keep test teardown from masking a failed assertion with an unhandled rejection.
+ request.catch(() => {});
+ return request;
+}
roryabraham
left a comment
There was a problem hiding this comment.
@ShridharGoel I see you just requested another review from me, but I think you haven't addressed my previous review yet
|
@roryabraham Just pushed the change |
|
I had noticed the comment only after requesting for a review (I thought the "Requested changes" status was from some older review) 😅 |
roryabraham
left a comment
There was a problem hiding this comment.
@ShridharGoel sorry, I had edited my previous comment to change the diff such that the CloudflareChallengeModal isn't rendered at all until it's needed. You applied the diff before my edit. Can you check the updated diff plz?
|
@carlosmiceli back to you |
Explanation of Change
When a Cloudflare rule answers a
BeginSignInrequest with a managed challenge, the browser gets an HTML challenge page instead of JSON. Because the request is afetch, the user never sees the challenge, so they hit a dead-end error with no way to recover.This PR adds the NewDot web side of the Turnstile fix from the linked issue:
HttpUtils.tschecks for thecf-mitigated: challengeresponse header onBeginSignInrequests.useCloudflareChallengeModalopensCloudflareChallengeModalon demand throughModalContextwith the Turnstile widget (sitekey0x4AAAAAAFnSe7JVSGF7kNTA, pre-clearance enabled). Concurrent challenged requests wait on the same modal.cf_clearancecookie. The originalBeginSignInrequest retries once withcredentials: 'include', and laterBeginSignInrequests keep sendingcredentials: 'include'until sign-out resets the state. All other API commands keepcredentials: 'omit'.Native platforms keep the current behavior, because the Turnstile widget needs a browser and the native cookie jar cannot hold the
cf_clearancecookie. That follow-up is tracked in the open questions of the linked issue, along with the OldDot (Web-Expensify) part.Fixed Issues
For https://github.com/Expensify/Expensify/issues/689666
PROPOSAL:
Tests
BeginSignIn(via a staging Cloudflare rule or by mocking a 403 response withcf-mitigated: challengein DevTools).Security checkmodal opens with the Turnstile widget.BeginSignInretries withcredentials: 'include'.BeginSignInreturns tocredentials: 'omit'.Offline tests
QA Steps
PR Author Checklist
### Fixed Issuessection aboveTestssectionOffline stepssectionQA stepssectionAvatar, I verified the components usingAvatarare working as expected)npm run compress-svg)Avataris modified, I verifiedAvataris working as expected in all cases)Designlabel and/or tagged@Expensify/designso the design team can review the changes.mainbranch was merged into this PR after a review, I tested again and verified the outcome was still expected according to theTeststeps.Screenshots/Videos
MacOS: Chrome / Safari
Screen.Recording.2026-12-05.at.12.51.24.AM.mov