All files / src/sections/PayBuilder/Checkout/hooks usePaymentCaptchaChallenge.ts

90.1% Statements 82/91
88.46% Branches 23/26
86.66% Functions 13/15
90% Lines 81/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174                                          397x 397x 397x 397x 397x 397x 397x 397x 397x 397x   397x   397x 2x         2x 1x 1x       397x 20x 20x   2x 2x 2x 2x 1x 1x   1x 1x     7x 7x 7x 7x         397x 4x 4x 4x 4x         4x 4x     397x 4x 4x 1x 1x 1x 1x       3x 2x   1x 1x 1x             397x       397x               397x 50x   50x       50x 50x 50x 50x 50x 50x 50x 10x         397x 1x     397x 19x 19x 3x   16x 16x 16x     397x 5x     5x 1x 1x   4x 4x 4x     397x                      
import { useEffect, useRef } from "react";
import NiceModal from "@ebay/nice-modal-react";
import * as Sentry from "@sentry/react";
import { showMessage } from "@common/Toast";
import { RECAPTCHA_CHALLENGE_MODAL } from "modals/modal_names";
import { bumpIdempotencySalt } from "@services/api";
import { CHECKOUT_ERROR_MESSAGES } from "@sections/PayBuilder/constants";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { MAX_PAYMENT_CAPTCHA_CHALLENGES } from "@utils/errorHandling";
import { getRecaptchaToken } from "@utils/getRecaptchaToken";
import type { CheckoutCaptchaPayload } from "../types";
 
type UsePaymentCaptchaChallengeOptions<T> = {
  onRetry: (data: T) => void;
  onGiveUp: () => void;
};
 
export function usePaymentCaptchaChallenge<T>({
  onRetry,
  onGiveUp,
}: UsePaymentCaptchaChallengeOptions<T>) {
  const { isDesktopView } = useCustomThemeV2();
  const pendingRef = useRef<T | null>(null);
  const challengeTokenRef = useRef<string | null>(null);
  const challengeAttemptsRef = useRef(0);
  const challengeRequiredRef = useRef(false);
  const cappedRef = useRef(false);
  const onRetryRef = useRef(onRetry);
  onRetryRef.current = onRetry;
  const onGiveUpRef = useRef(onGiveUp);
  onGiveUpRef.current = onGiveUp;
 
  const hasChallengeToken = () => Boolean(challengeTokenRef.current);
 
  const resetAttemptsUnlessRetry = () => {
    Iif (challengeTokenRef.current) {
      return;
    }
    // After a cap, a new Pay may try the checkbox again. The latch stays set
    // so attachToken still will not mint a CHECKOUT score token.
    if (cappedRef.current) {
      challengeAttemptsRef.current = 0;
      cappedRef.current = false;
    }
  };
 
  const showChallenge = (pending: T) => {
    pendingRef.current = pending;
    NiceModal.show(RECAPTCHA_CHALLENGE_MODAL, {
      onVerify: (token: string) => {
        const data = pendingRef.current;
        pendingRef.current = null;
        NiceModal.hide(RECAPTCHA_CHALLENGE_MODAL);
        if (!data) {
          onGiveUpRef.current();
          return;
        }
        challengeTokenRef.current = token;
        onRetryRef.current(data);
      },
      onDismiss: () => {
        pendingRef.current = null;
        challengeTokenRef.current = null;
        NiceModal.hide(RECAPTCHA_CHALLENGE_MODAL);
        onGiveUpRef.current();
      },
    });
  };
 
  const capChallenge = (): "capped" => {
    cappedRef.current = true;
    pendingRef.current = null;
    NiceModal.hide(RECAPTCHA_CHALLENGE_MODAL);
    showMessage(
      "Error",
      CHECKOUT_ERROR_MESSAGES.CAPTCHA_RETRY_LIMIT,
      isDesktopView,
    );
    onGiveUpRef.current();
    return "capped";
  };
 
  const attachToken = async (payload: CheckoutCaptchaPayload) => {
    try {
      if (challengeTokenRef.current) {
        payload.captchaToken = challengeTokenRef.current;
        payload.captchaAction = "CHECKOUT_CHALLENGE";
        bumpIdempotencySalt();
        return;
      }
      // API already demanded the checkbox. Do not mint a score token that
      // can AUTH after the challenge was dismissed.
      if (challengeRequiredRef.current) {
        return;
      }
      const token = await getRecaptchaToken("CHECKOUT");
      Eif (token) {
        payload.captchaToken = token;
      }
    } catch (err) {
      Sentry.captureException(err);
    }
  };
 
  const consumeToken = () => {
    challengeTokenRef.current = null;
  };
 
  const reset = () => {
    challengeAttemptsRef.current = 0;
    pendingRef.current = null;
    challengeTokenRef.current = null;
    challengeRequiredRef.current = false;
    cappedRef.current = false;
  };
 
  useEffect(() => {
    return () => {
      const hadChallenge =
        pendingRef.current !== null ||
        challengeTokenRef.current !== null ||
        challengeRequiredRef.current ||
        challengeAttemptsRef.current > 0;
      pendingRef.current = null;
      challengeTokenRef.current = null;
      challengeAttemptsRef.current = 0;
      challengeRequiredRef.current = false;
      cappedRef.current = false;
      NiceModal.hide(RECAPTCHA_CHALLENGE_MODAL);
      if (hadChallenge) {
        onGiveUpRef.current();
      }
    };
  }, []);
 
  const clearPending = () => {
    pendingRef.current = null;
  };
 
  const requestChallenge = (pending: T): "shown" | "capped" => {
    challengeRequiredRef.current = true;
    if (challengeAttemptsRef.current >= MAX_PAYMENT_CAPTCHA_CHALLENGES) {
      return capChallenge();
    }
    challengeAttemptsRef.current += 1;
    showChallenge(pending);
    return "shown";
  };
 
  const reopenIfRequired = (pending: T): boolean => {
    Iif (!challengeRequiredRef.current || challengeTokenRef.current) {
      return false;
    }
    if (challengeAttemptsRef.current >= MAX_PAYMENT_CAPTCHA_CHALLENGES) {
      capChallenge();
      return true;
    }
    challengeAttemptsRef.current += 1;
    showChallenge(pending);
    return true;
  };
 
  return {
    hasChallengeToken,
    resetAttemptsUnlessRetry,
    attachToken,
    consumeToken,
    reset,
    clearPending,
    requestChallenge,
    reopenIfRequired,
  };
}