All files / src/hooks/useTurnstile useTurnstile.ts

69.09% Statements 38/55
76.92% Branches 20/26
78.57% Functions 11/14
72% Lines 36/50

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                                                      6x 6x             1x 1x     1x 1x                   1x                                       9x 9x 9x   9x 9x   9x   9x 9x   1x   1x   1x   1x         1x 1x               1x 1x       9x 3x 1x     2x 2x   1x 1x     1x 1x       9x 3x 1x       9x    
/**
 * useTurnstile hook — Story 10.31 (AC7)
 *
 * Loads the Cloudflare Turnstile invisible widget from CDN (no npm package).
 * When disabled (features.turnstile=false) getToken() returns null immediately.
 */
 
import { useRef, useEffect, useCallback } from 'react';
import { useOptionalConfig } from '@/contexts/useConfig';
 
declare global {
  interface Window {
    turnstile: {
      render: (el: HTMLElement, opts: object) => string;
      execute: (widgetId: string) => void;
      reset: (widgetId: string) => void;
    };
  }
}
 
export interface UseTurnstileReturn {
  getToken: () => Promise<string | null>;
  resetWidget: () => void;
  widgetRef: React.RefObject<HTMLDivElement | null>;
}
 
const TURNSTILE_SCRIPT_URL =
  'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
const TURNSTILE_SCRIPT_ID = 'cf-turnstile-script';
 
/**
 * Injects the Cloudflare Turnstile script once per page load.
 * Returns a Promise that resolves when the script is ready.
 */
function loadTurnstileScript(): Promise<void> {
  return new Promise((resolve, reject) => {
    Eif (document.getElementById(TURNSTILE_SCRIPT_ID)) {
      // Already injected — resolve immediately if window.turnstile is present,
      // or wait for onload event via the existing script element.
      if (window.turnstile) {
        resolve();
      } else E{
        const existing = document.getElementById(TURNSTILE_SCRIPT_ID) as HTMLScriptElement | null;
        if (existing) {
          existing.addEventListener('load', () => resolve());
          existing.addEventListener('error', reject);
        } else {
          resolve();
        }
      }
      return;
    }
 
    const script = document.createElement('script');
    script.id = TURNSTILE_SCRIPT_ID;
    script.src = TURNSTILE_SCRIPT_URL;
    script.async = true;
    script.defer = true;
    script.onload = () => resolve();
    script.onerror = reject;
    document.head.appendChild(script);
  });
}
 
export function useTurnstile(): UseTurnstileReturn {
  // useOptionalConfig (not useConfig) so the hook never throws if it somehow renders
  // before runtime config has loaded. In practice the only public-path consumer is the
  // lazily-loaded, below-the-fold newsletter widget, which mounts well after config is
  // ready — but treating null as "turnstile not ready / disabled" is the correct,
  // crash-proof default and the hook re-renders when config arrives.
  const config = useOptionalConfig();
  const enabled = config?.features.turnstile ?? false;
  const siteKey = config?.turnstile?.siteKey ?? '';
 
  const widgetRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);
  // Pending resolve callbacks for getToken() calls during execute
  const pendingResolversRef = useRef<Array<(token: string) => void>>([]);
 
  useEffect(() => {
    if (!enabled || !widgetRef.current) return;
 
    let cancelled = false;
 
    loadTurnstileScript()
      .then(() => {
        Iif (cancelled || !widgetRef.current) return;
 
        widgetIdRef.current = window.turnstile.render(widgetRef.current, {
          sitekey: siteKey,
          size: 'invisible',
          callback: (token: string) => {
            // Resolve all pending getToken() promises
            const resolvers = pendingResolversRef.current.splice(0);
            resolvers.forEach((resolve) => resolve(token));
          },
        });
      })
      .catch((err) => {
        console.error('[useTurnstile] Failed to load Turnstile script:', err);
      });
 
    return () => {
      cancelled = true;
    };
  }, [enabled, siteKey]);
 
  const getToken = useCallback((): Promise<string | null> => {
    if (!enabled) {
      return Promise.resolve(null);
    }
 
    return new Promise<string | null>((resolve) => {
      if (!widgetIdRef.current) {
        // Widget not yet rendered — resolve null (fail-open on frontend)
        resolve(null);
        return;
      }
 
      pendingResolversRef.current.push(resolve as (token: string) => void);
      window.turnstile.execute(widgetIdRef.current);
    });
  }, [enabled]);
 
  const resetWidget = useCallback(() => {
    if (enabled && widgetIdRef.current) {
      window.turnstile.reset(widgetIdRef.current);
    }
  }, [enabled]);
 
  return { getToken, resetWidget, widgetRef };
}