diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..4db3705 --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +__e2e__/host/ diff --git a/Example.App.js b/Example.App.js index bda46e0..0698285 100644 --- a/Example.App.js +++ b/Example.App.js @@ -46,13 +46,14 @@ const App = () => { // userJourney={true} /> { captchaForm.current.show(); }}> Click to launch {code && ( - + {'passcode or status: '} {code} diff --git a/Hcaptcha.d.ts b/Hcaptcha.d.ts index 8268b70..7c09d71 100644 --- a/Hcaptcha.d.ts +++ b/Hcaptcha.d.ts @@ -38,6 +38,11 @@ export type HcaptchaProps = { * Whether to show a loading indicator while the hCaptcha web content loads */ showLoading?: boolean; + /** + * Load the SDK on mount without fetching a token. Call execute() to verify. + * Default: false. + */ + prewarm?: boolean; /** * Allow user to cancel hcaptcha during loading by touch loader overlay */ @@ -118,7 +123,14 @@ export type HcaptchaProps = { interface CustomWebViewMessageEvent extends WebViewMessageEvent { success: boolean; reset: () => void; + /** Releases the WebView and cancels verification/timers. execute() recreates it. Retained event.reset() hooks become inert. */ + destroy: () => void; markUsed?: () => void; } -export default class Hcaptcha extends React.Component {} +export default class Hcaptcha extends React.Component { + /** Queues verification until the SDK is ready. */ + execute: () => void; + /** Cancels pending verification and resets the widget without executing. */ + reset: () => void; +} diff --git a/Hcaptcha.js b/Hcaptcha.js index 2936b4c..528a359 100644 --- a/Hcaptcha.js +++ b/Hcaptcha.js @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; +import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react'; import hCaptchaLoaderInlineScript from '@hcaptcha/loader/inline'; import WebView from 'react-native-webview'; import { ActivityIndicator, Linking, Platform, StyleSheet, TouchableWithoutFeedback, View } from 'react-native'; @@ -28,6 +28,8 @@ const patchPostMessageJsCode = `(${String(function () { })})();`; const HCAPTCHA_READY_EVENT = '__hcaptcha_ready__'; +const HCAPTCHA_REQUEST_EVENT = '__hcaptcha_request__:'; +const HCAPTCHA_LOAD_ERROR_EVENT = '__hcaptcha_load_error__:'; const serializeForInlineScript = (value) => JSON.stringify(value) @@ -133,8 +135,8 @@ const buildVerifyData = ({ return data; }; -const buildVerifyInjectionScript = (payload, resetFirst = false) => - `try { ${resetFirst ? 'reset(); ' : ''}setData(${serializeForInlineScript(payload)}); execute(); } catch (e) { window.ReactNativeWebView.postMessage((e && e.name) || 'error'); } true;`; +const buildVerifyInjectionScript = (payload, resetFirst = false, requestId) => + `try { ${resetFirst ? 'reset(); ' : ''}${requestId === undefined ? '' : `setRequest(${requestId}); `}setData(${serializeForInlineScript(payload)}); execute(); } catch (e) { window.ReactNativeWebView.postMessage((e && e.name) || 'error'); } true;`; const getHcaptchaHost = (host, siteKey) => { if (host) { @@ -199,8 +201,9 @@ function buildHcaptchaLoaderConfig({ * @param {string} phoneNumber: Optional full phone number in E.164 format ("+44123..."), for use in MFA. * @param {boolean} userJourney: Enable automatic user journey injection * @param {object} verifyParams: Verification payload overrides + * @param {boolean} prewarm: Load the SDK on mount and defer verification until execute() */ -const Hcaptcha = ({ +const Hcaptcha = forwardRef(({ onMessage, size, siteKey, @@ -226,14 +229,52 @@ const Hcaptcha = ({ phoneNumber, userJourney, verifyParams, + prewarm = false, _journeyManagedExternally, -}) => { + _onRequestChange, + _onTokenTimerChange, +}, ref) => { const tokenTimeout = 120000; const loadingTimeout = 15000; const [isLoading, setIsLoading] = useState(true); + const [webViewGeneration, setWebViewGeneration] = useState(0); + const [destroyed, setDestroyed] = useState(false); + const destroyedRef = useRef(false); + const lifetimeRef = useRef({}); + const lifetime = lifetimeRef.current; const isLoadingRef = useRef(true); const journeyEnabled = Boolean(userJourney); const hasJourneyConsumerRef = useRef(false); + const readyRef = useRef(false); + const loadStartedRef = useRef(false); + const executeRequestedRef = useRef(!prewarm); + const requestIdRef = useRef(0); + const prewarmRef = useRef(prewarm); + const hasExecutedRef = useRef(false); + const loadFailedRef = useRef(false); + const webViewRef = useRef(null); + const documentRef = useRef(null); + const loadingTimerRef = useRef(null); + const tokenTimerRef = useRef(null); + const clearTokenTimer = useCallback(() => { + clearTimeout(tokenTimerRef.current); + _onTokenTimerChange?.(tokenTimerRef.current, false); + }, [_onTokenTimerChange]); + const onMessageRef = useRef(onMessage); + const resetRef = useRef(null); + const mountedRef = useRef(true); + onMessageRef.current = onMessage; + prewarmRef.current = prewarm; + const setExecuteRequested = useCallback((requested) => { + executeRequestedRef.current = requested; + _onRequestChange?.(requested); + }, [_onRequestChange]); + // Retained reset hooks follow renders, but cannot cross explicit destruction. + const reset = useCallback(() => { + if (mountedRef.current && lifetimeRef.current === lifetime) { + resetRef.current(); + } + }, [lifetime]); const normalizedTheme = useMemo(() => normalizeTheme(theme), [theme]); const normalizedSize = useMemo(() => normalizeSize(size), [size]); const loaderConfig = useMemo( @@ -289,22 +330,48 @@ const Hcaptcha = ({ ${hCaptchaLoaderInlineScript}