All files / components/auth Turnstile.tsx

94.8% Statements 73/77
94.44% Branches 17/18
100% Functions 6/6
94.8% Lines 73/77

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 1361x                                                                     1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x     11x 10x 10x 10x 11x   11x   10x     10x 9x 9x 9x 9x 9x 9x 9x     10x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     10x 7x 10x   3x         3x     3x   3x 3x 3x 3x 3x     7x 7x 7x 7x 7x 7x 7x 11x   11x 11x         1x 6x 3x 1x 1x 6x   6x 6x  
'use client';
 
import { useEffect, useRef, useCallback } from 'react';
 
declare global {
  interface Window {
    turnstile?: {
      render: (
        container: HTMLElement,
        options: {
          sitekey: string;
          callback: (token: string) => void;
          'expired-callback'?: () => void;
          'error-callback'?: () => void;
          theme?: 'light' | 'dark' | 'auto';
          size?: 'normal' | 'compact' | 'invisible';
          appearance?: 'always' | 'execute' | 'interaction-only';
        }
      ) => string;
      reset: (widgetId: string) => void;
      remove: (widgetId: string) => void;
    };
  }
}
 
interface TurnstileProps {
  siteKey: string;
  onVerify: (token: string) => void;
  onExpire?: () => void;
  onError?: () => void;
  theme?: 'light' | 'dark' | 'auto';
  size?: 'normal' | 'compact' | 'invisible';
  className?: string;
}
 
export function Turnstile({
  siteKey,
  onVerify,
  onExpire,
  onError,
  theme = 'auto',
  size = 'normal',
  className,
}: TurnstileProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);
  const isRenderedRef = useRef(false);
 
  // Store callbacks in refs to avoid re-renders causing widget recreation
  const onVerifyRef = useRef(onVerify);
  const onExpireRef = useRef(onExpire);
  const onErrorRef = useRef(onError);
 
  // Update refs when callbacks change
  useEffect(() => {
    onVerifyRef.current = onVerify;
    onExpireRef.current = onExpire;
    onErrorRef.current = onError;
  }, [onVerify, onExpire, onError]);
 
  useEffect(() => {
    // Prevent multiple renders
    if (isRenderedRef.current) return;
 
    // Load Turnstile script if not already loaded
    if (!document.getElementById('turnstile-script')) {
      const script = document.createElement('script');
      script.id = 'turnstile-script';
      script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
      script.async = true;
      script.defer = true;
      document.head.appendChild(script);
    }
 
    // Wait for script to load and render widget
    const renderWidget = () => {
      if (window.turnstile && containerRef.current && !widgetIdRef.current) {
        isRenderedRef.current = true;
        widgetIdRef.current = window.turnstile.render(containerRef.current, {
          sitekey: siteKey,
          callback: (token: string) => onVerifyRef.current(token),
          'expired-callback': () => onExpireRef.current?.(),
          'error-callback': () => onErrorRef.current?.(),
          theme,
          size,
        });
      }
    };
 
    // Check if script is already loaded
    if (window.turnstile) {
      renderWidget();
    } else {
      // Wait for script to load
      const checkInterval = setInterval(() => {
        if (window.turnstile) {
          clearInterval(checkInterval);
          renderWidget();
        }
      }, 100);
 
      // Cleanup interval after 10 seconds
      const timeout = setTimeout(() => clearInterval(checkInterval), 10000);
 
      return () => {
        clearInterval(checkInterval);
        clearTimeout(timeout);
      };
    }
 
    // Cleanup on unmount
    return () => {
      if (widgetIdRef.current && window.turnstile) {
        window.turnstile.remove(widgetIdRef.current);
        widgetIdRef.current = null;
        isRenderedRef.current = false;
      }
    };
  }, [siteKey, theme, size]); // Only re-render if these change, not callbacks
 
  return <div ref={containerRef} className={className} />;
}
 
/**
 * Hook to reset Turnstile widget
 */
export function useTurnstileReset() {
  const reset = useCallback((widgetId: string) => {
    if (window.turnstile && widgetId) {
      window.turnstile.reset(widgetId);
    }
  }, []);
 
  return reset;
}