From 92ba84e70999d53dc9baa1132e49425a27ae70d9 Mon Sep 17 00:00:00 2001 From: e271828- Date: Thu, 22 Oct 2026 17:25:27 -0400 Subject: [PATCH 01/15] feat: add opt-in WebView prewarming and deferred execution --- .eslintignore | 1 + Hcaptcha.d.ts | 12 +- Hcaptcha.js | 182 +++++++++-- MAINTAINER.md | 48 ++- README.md | 47 ++- __e2e__/PrewarmAuthApp.js | 236 ++++++++++++++ __e2e__/auth-server.js | 243 ++++++++++++++ __e2e__/authFlow.harness.js | 100 ++++++ __e2e__/jest.network.config.mjs | 5 + __e2e__/jest.perf.config.mjs | 6 + __e2e__/native-metrics.js | 107 +++++++ __e2e__/network-proxy.js | 55 ++++ __e2e__/prewarm.harness.js | 108 +++++++ __e2e__/prewarmEdges.profile.js | 130 ++++++++ __e2e__/prewarmNetwork.profile.js | 92 ++++++ __e2e__/prewarmPerf.profile.js | 152 +++++++++ __e2e__/rn-harness.config.mjs | 2 +- __mocks__/global.js | 9 - __scripts__/configure-e2e-network.js | 70 ++++ __scripts__/run-e2e.js | 95 ++++++ __scripts__/setup-e2e-host.js | 4 + __tests__/ConfirmHcaptcha.test.js | 141 +++++++- __tests__/Hcaptcha.test.js | 300 +++++++++++++++++- .../ConfirmHcaptcha.test.js.snap | 6 +- __tests__/__snapshots__/Hcaptcha.test.js.snap | 5 +- index.d.ts | 4 + index.js | 99 +++++- package.json | 11 +- 28 files changed, 2202 insertions(+), 68 deletions(-) create mode 100644 .eslintignore create mode 100644 __e2e__/PrewarmAuthApp.js create mode 100644 __e2e__/auth-server.js create mode 100644 __e2e__/authFlow.harness.js create mode 100644 __e2e__/jest.network.config.mjs create mode 100644 __e2e__/jest.perf.config.mjs create mode 100644 __e2e__/native-metrics.js create mode 100644 __e2e__/network-proxy.js create mode 100644 __e2e__/prewarm.harness.js create mode 100644 __e2e__/prewarmEdges.profile.js create mode 100644 __e2e__/prewarmNetwork.profile.js create mode 100644 __e2e__/prewarmPerf.profile.js create mode 100644 __scripts__/configure-e2e-network.js create mode 100644 __scripts__/run-e2e.js 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/Hcaptcha.d.ts b/Hcaptcha.d.ts index 8268b70..c9c00ee 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 */ @@ -121,4 +126,9 @@ interface CustomWebViewMessageEvent extends WebViewMessageEvent { 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..9d438ae 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'; @@ -199,8 +199,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 +227,31 @@ const Hcaptcha = ({ phoneNumber, userJourney, verifyParams, + prewarm = false, _journeyManagedExternally, -}) => { +}, ref) => { const tokenTimeout = 120000; const loadingTimeout = 15000; const [isLoading, setIsLoading] = useState(true); + const [webViewGeneration, setWebViewGeneration] = useState(0); 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 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 onMessageRef = useRef(onMessage); + const resetRef = useRef(null); + const mountedRef = useRef(true); + onMessageRef.current = onMessage; + prewarmRef.current = prewarm; const normalizedTheme = useMemo(() => normalizeTheme(theme), [theme]); const normalizedSize = useMemo(() => normalizeSize(size), [size]); const loaderConfig = useMemo( @@ -262,15 +280,12 @@ const Hcaptcha = ({ loaderConfig, backgroundColor: backgroundColor ?? '', debugInfo, - phoneNumber: phoneNumber ?? null, - phonePrefix: phonePrefix ?? null, orientation: orientation ?? null, - rqdata: rqdata ?? null, siteKey: siteKey || '', size: normalizedSize, theme: normalizedTheme, }), - [loaderConfig, backgroundColor, debugInfo, normalizedSize, normalizedTheme, orientation, phoneNumber, phonePrefix, rqdata, siteKey] + [loaderConfig, backgroundColor, debugInfo, normalizedSize, normalizedTheme, orientation, siteKey] ); const generateTheWebViewContent = useMemo( @@ -383,22 +398,54 @@ const Hcaptcha = ({ }; }, [_journeyManagedExternally, journeyEnabled]); - useEffect(() => { - const timeoutId = setTimeout(() => { + const startLoadingTimeout = useCallback(() => { + clearTimeout(loadingTimerRef.current); + loadingTimerRef.current = setTimeout(() => { if (isLoadingRef.current) { - onMessage({ nativeEvent: { data: 'error', description: 'loading timeout' } }); + isLoadingRef.current = false; + loadFailedRef.current = 'timeout'; + if (prewarmRef.current) { + executeRequestedRef.current = false; + } + setIsLoading(false); + onMessageRef.current({ nativeEvent: { data: 'error', description: 'loading timeout' } }); } }, loadingTimeout); + }, []); + + const documentKey = useMemo(() => JSON.stringify([serializedWebViewConfig, url, webViewGeneration]), [serializedWebViewConfig, url, webViewGeneration]); + useLayoutEffect(() => { + documentRef.current = documentKey; + loadStartedRef.current = false; + readyRef.current = false; + hasExecutedRef.current = false; + loadFailedRef.current = false; + isLoadingRef.current = true; + setIsLoading(true); + startLoadingTimeout(); + }, [documentKey, startLoadingTimeout]); - return () => clearTimeout(timeoutId); - }, [onMessage]); + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + documentRef.current = null; + clearTimeout(loadingTimerRef.current); + }; + }, []); + + useEffect(() => () => { + if (prewarm) { + clearTimeout(tokenTimerRef.current); + } + }, [prewarm]); - const webViewRef = useRef(null); const injectVerifyData = (resetFirst = false) => { if (!webViewRef.current) { return; } + hasExecutedRef.current = true; webViewRef.current.injectJavaScript(buildVerifyInjectionScript(buildVerifyData({ phoneNumber, phonePrefix, @@ -417,8 +464,28 @@ const Hcaptcha = ({ ); - const reset = () => { - injectVerifyData(true); + // Event hooks can be retained across renders while a token is held. + const reset = useCallback(() => resetRef.current(), []); + resetRef.current = () => { + executeRequestedRef.current = true; + if (readyRef.current) { + injectVerifyData(true); + } else if (loadFailedRef.current) { + retryApiLoad(); + } + }; + + const reloadWebView = () => { + if (!mountedRef.current || documentRef.current !== documentKey) { + return; + } + readyRef.current = false; + hasExecutedRef.current = false; + isLoadingRef.current = true; + setIsLoading(true); + startLoadingTimeout(); + // WKWebView.reload() can lose inline HTML after its content process dies. + setWebViewGeneration((generation) => generation + 1); }; const retryApiLoad = () => { @@ -426,12 +493,42 @@ const Hcaptcha = ({ return; } - webViewRef.current.injectJavaScript('loadApiScript(); true;'); + const timedOut = loadFailedRef.current === 'timeout'; + loadFailedRef.current = false; + if (timedOut) { + reloadWebView(); + } else { + isLoadingRef.current = true; + setIsLoading(true); + startLoadingTimeout(); + webViewRef.current.injectJavaScript('loadApiScript(); true;'); + } }; + useImperativeHandle(ref, () => ({ + execute: () => { + if (executeRequestedRef.current && !loadFailedRef.current) { + return; + } + executeRequestedRef.current = true; + if (readyRef.current) { + injectVerifyData(hasExecutedRef.current); + } else if (loadFailedRef.current) { + retryApiLoad(); + } + }, + reset: () => { + executeRequestedRef.current = false; + if (readyRef.current) { + webViewRef.current?.injectJavaScript("try { reset(); } catch (e) { window.ReactNativeWebView.postMessage((e && e.name) || 'error'); } true;"); + } + }, + })); + return ( { @@ -454,16 +551,50 @@ const Hcaptcha = ({ return true; }} mixedContentMode={'always'} - onMessage={(e) => { + onContentProcessDidTerminate={reloadWebView} + onRenderProcessGone={reloadWebView} + onLoadStart={() => { + if (documentRef.current !== documentKey) { + return; + } + // Android can deliver the initial load event after SDK readiness. + if (!loadStartedRef.current) { + loadStartedRef.current = true; + return; + } + readyRef.current = false; + hasExecutedRef.current = false; + loadFailedRef.current = false; + isLoadingRef.current = true; + setIsLoading(true); + startLoadingTimeout(); + }} + onMessage={(event) => { + if (documentRef.current !== documentKey) { + return; + } + // Native events can be pooled with custom fields from an earlier token. + const e = Object.assign(Object.create(Object.getPrototypeOf(event)), event, { + nativeEvent: { ...event.nativeEvent }, + }); + e.markUsed = undefined; + clearTimeout(loadingTimerRef.current); isLoadingRef.current = false; setIsLoading(false); if (e.nativeEvent.data === HCAPTCHA_READY_EVENT) { - injectVerifyData(); + if (!readyRef.current) { + readyRef.current = true; + loadFailedRef.current = false; + if (executeRequestedRef.current) { + injectVerifyData(); + } + } return; } if (e.nativeEvent.data === 'script-error') { + loadFailedRef.current = true; e.reset = retryApiLoad; } else { e.reset = reset; @@ -471,12 +602,21 @@ const Hcaptcha = ({ e.success = true; if (e.nativeEvent.data === 'open') { } else if (e.nativeEvent.data.length > 35) { - const expiredTokenTimerId = setTimeout(() => onMessage({ nativeEvent: { data: 'expired' }, success: false, reset }), tokenTimeout); + if (prewarm && !executeRequestedRef.current) { + return; + } + executeRequestedRef.current = false; + clearTimeout(tokenTimerRef.current); + const expiredTokenTimerId = setTimeout(() => onMessageRef.current({ nativeEvent: { data: 'expired' }, success: false, reset }), tokenTimeout); + tokenTimerRef.current = expiredTokenTimerId; e.markUsed = () => clearTimeout(expiredTokenTimerId); if (journeyEnabled) { clearJourneyEvents(); } } else /* error */ { + if (readyRef.current) { + executeRequestedRef.current = false; + } e.success = false; } onMessage(e); @@ -493,7 +633,9 @@ const Hcaptcha = ({ {showLoading && isLoading && renderLoading()} ); -}; +}); + +Hcaptcha.displayName = 'Hcaptcha'; const styles = StyleSheet.create({ container: { diff --git a/MAINTAINER.md b/MAINTAINER.md index c253f7e..c860116 100644 --- a/MAINTAINER.md +++ b/MAINTAINER.md @@ -17,8 +17,8 @@ PATCH: bugfix only. - verify: - `npm test` - `npm run lint` - - `CI=1 npm run test:e2e` to confirm CI skips local-only device E2E cleanly - - `npm run test:e2e:android-local` if you want the full Android emulator verification locally + - `npm run test:e2e:android` on a booted Android emulator + - `npm run test:e2e:ios` on a booted iOS simulator - commit `package.json` and `package-lock.json` - commit any maintainer or release-documentation updates in the same PR - open the PR for review @@ -54,12 +54,46 @@ For `react-native` test app - `yarn example` - `yarn android` or `npm run android` -For the local Android emulator regression E2E added in this repo: +For native E2E, generate and build the host once with `npm run test:e2e:setup` (requires Node 22.11+, Android SDK, and Xcode/CocoaPods for iOS). Use `-- --platform android` or `-- --platform ios` to build one platform. Setup recreates `__e2e__/host`. -- `cd react-native-hcaptcha` -- ensure Android SDK, emulator, and an AVD are installed -- run `npm run test:e2e:android-local` -- inspect artifacts in [`output/android-e2e`](./output/android-e2e) if the run fails +Boot the selected device, then run the prewarm suites: + +```sh +HARNESS_AVD_NAME=Medium_Phone npm run test:e2e:android -- --testPathPattern 'authFlow|prewarm' +HARNESS_IOS_DEVICE='iPhone 17 Pro' HARNESS_IOS_VERSION=26.0 npm run test:e2e:ios -- --testPathPattern 'authFlow|prewarm' +``` + +Use the names and runtime versions installed locally. The runner refreshes the host's JS, installs the existing native binary, starts a disposable backend on `127.0.0.1:8766`, forwards that port on Android, and stops the backend on exit. The generated host and harness use Metro port `18081`, avoiding the common Docker/Metro port. Run platforms sequentially because they share backend state. The live suites require internet access. + +`__e2e__/PrewarmAuthApp.js` is a three-screen signup/login app: email entry, credentials, and account confirmation. It keeps one captcha mounted at the root, executes on the credentials screen, stores a token snapshot while the user edits, submits it to the backend, then logs out and repeats login using the same WebView. The backend redirects `/1/api.js` to the live SDK and verifies tokens through hCaptcha's `siteverify` API using its public test secret. The local base URL avoids mixed-content restrictions in WKWebView. + +The suites cover visible/passive presentation, one SDK load across both auth attempts, delayed submission, successful server verification, cancellation before SDK readiness, and retry after rejected credentials. Public test keys auto-pass; visual challenge solving is outside these tests. `prewarm.harness.js` separately uses an SDK fixture to assert native widget reuse, payload updates without a reload, and document replacement after a theme change. + +The bridge copies pooled native events before attaching token hooks, preventing a previous token's `markUsed` from leaking onto an `open` or error event. Keep cached tokens as `{ token: event.nativeEvent.data, markUsed: event.markUsed }` and discard them after backend consumption, including rejected credentials. + +For latency and stall profiling on the same booted devices: + +```sh +HARNESS_AVD_NAME=Medium_Phone npm run test:e2e:perf:android +HARNESS_IOS_DEVICE='iPhone 17 Pro' HARNESS_IOS_VERSION=26.0 npm run test:e2e:perf:ios +``` + +The profile alternates five cold and five prewarmed screen-2 executions, runs 30 signup/login cycles in one warm WebView, checks idle JS frames and memory, holds an SDK request through its loading timeout, and deliberately terminates the test renderer to verify recovery. A small observer wraps the live SDK's `render()` to detect readiness; it does not replace token generation or server verification. These longer suites run serially with a ten-minute bridge deadline. + +`--testPathPattern prewarmEdges` selects lifecycle tests: actual app background/resume, 125-second token expiry, expiry while an auth response is held, navigation away during submission, cancellation after the live SDK produces a token, renderer termination during pending verification, and switching prewarm/presentation modes with a pending request. The deferred-token observer holds the SDK's real callback for ten seconds to expose cancellation and renderer races. iOS renderer fault injection terminates WebContent processes belonging to the disposable harness simulator, including any retained by Safari during background tests. + +Results are written to `output/prewarm-perf-android.json` and `output/prewarm-perf-ios.json`. Frame gaps measure the React Native JS thread; Android additionally records cumulative native rendering stats. Android memory is summed PSS; iOS memory is summed RSS for the app and its simulator WebKit processes, so the totals are not directly comparable. Debug emulators and public test keys do not establish production device frame rates, challenge latency, battery use, or long-term leak freedom. + +For transport failures, rebuild the generated host with the network hooks, then run: + +```sh +HARNESS_AVD_NAME=Medium_Phone npm run test:e2e:network:android +HARNESS_IOS_DEVICE='iPhone 17 Pro' HARNESS_IOS_VERSION=26.0 npm run test:e2e:network:ios +``` + +These four cases cover offline prewarm, execute queued while offline, and interrupted challenge execution plus background/resume in both presentation modes. An app-scoped WebView proxy closes existing TLS connections and rejects new connections; it does not decrypt TLS, replace the SDK, change host networking, or simulate OS reachability events. The harness/control backend stays connected. Network tests are excluded from performance profiles so proxy overhead cannot affect their measurements. + +The execution cases use the public key from `https://accounts.hcaptcha.com/demo`, assert `network-error`, restore transport, and reopen a challenge in the same warmed SDK. No visual challenge is solved. They finish backend verification using the public auto-pass test key. Recovered visible challenge screenshots are saved as `output/prewarm-network-{android,ios}.png`; Android uses compositor capture because software View snapshots can omit accelerated canvas content. The iOS proxy hook requires iOS 17+ and is enabled only for the network runner. Android's app-private flag is removed after the run and before normal runs. For iOS instead the last step do: diff --git a/README.md b/README.md index 3e0c5eb..5900d11 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,50 @@ export default function Example() { } ``` +### Prewarming a multi-step flow + +Set `prewarm` to load the WebView and SDK on mount without fetching a token. It defaults to `false`, preserving the existing mount-on-`show()` behavior. + +Mount `ConfirmHcaptcha` once at the app root, after your navigation/content, inside a full-screen `View`. Keep it mounted across screens. Call `captchaRef.current.execute()` when screen 2 loads; `show()` is equivalent. Calls made before SDK readiness are queued. `hide()` cancels pending verification and keeps the WebView warm for reuse. + +```js + + {/* screens */} + { + if (event.markUsed) { + // Store the token and markUsed callback for form submission. + tokenRef.current = { token: event.nativeEvent.data, markUsed: event.markUsed }; + captchaRef.current.hide(); + } else if (event.nativeEvent.data === 'expired') { + tokenRef.current = null; + } + }} + /> + + +// Screen 2 load: +captchaRef.current.execute(); + +// On form submit, retain a snapshot across the async request: +const token = tokenRef.current; +await submitForm({ captchaToken: token.token }); +token.markUsed(); +``` + +Submit `tokenRef.current.token` to your backend. Keep the token and its `markUsed` callback together for delayed submission. Tokens expire after 120 seconds by default; request a replacement if the form outlives the token. Loading errors can arrive during prewarming through `onMessage`. + +Verification payload updates (`verifyParams` or legacy `rqdata`/phone props) preserve the warm SDK. If the backend rejects credentials after consuming a token, discard it and execute again before retrying the form. + +Prewarm mode uses a persistent app-level overlay so showing the challenge preserves the native WebView. It covers its parent view and cannot appear above another native `Modal`. Android back-button and backdrop cancellation remain supported. With `passiveSiteKey`, it stays hidden during verification too. + +The WebView and SDK retain memory until the component unmounts. SDK loading has a 15-second timeout independent of form re-renders. A later `execute()` can retry a timed-out load; terminated WebView processes are recreated automatically. + +The inline `Hcaptcha` export also supports `prewarm`, `ref.current.execute()`, and `ref.current.reset()` (cancel/reset without executing). The caller controls its visibility. + ### Verification payloads with `verifyParams` Use `verifyParams` for request data passed to `hcaptcha.setData(...)` immediately before each verification attempt. @@ -241,7 +285,7 @@ If your app encounters an `error` event, you can reset the hCaptcha SDK flow by The SDK automatically retries loading `api.js` after transient failures. If all attempts fail, `script-error` is sent via `onMessage`. -The 15-second `loading timeout` message does not stop initialization and should not be treated as a terminal loading failure. +With `prewarm`, the 15-second `loading timeout` message cancels the pending verification. Initialization can still finish in the background; call `execute()` again to retry. Without `prewarm`, initialization and the pending verification continue after the timeout, preserving existing behavior. ## Dependencies @@ -349,6 +393,7 @@ For new code, prefer: | onMessage | Function (see [here](https://github.com/react-native-webview/react-native-webview/blob/master/src/WebViewTypes.ts#L299)) | Required. Runs after receiving a response, error, or when user cancels. | | languageCode | string | Default language for hCaptcha; overrides phone defaults. A complete list of supported languages and their codes can be found [here](https://docs.hcaptcha.com/languages/) | | showLoading | boolean | Whether to show a loading indicator while the hCaptcha web content loads | +| prewarm | boolean | Load the WebView and SDK on mount; defer verification until `execute()` or `show()`. Default: `false`. Keep mounted across screens; see prewarming usage above. | | closableLoading | boolean | Allow user to cancel hcaptcha during loading by touch loader overlay | | loadingIndicatorColor | string | Color of the ActivityIndicator | | backgroundColor | string | The background color code that will be applied to the main HTML element | diff --git a/__e2e__/PrewarmAuthApp.js b/__e2e__/PrewarmAuthApp.js new file mode 100644 index 0000000..98e3b52 --- /dev/null +++ b/__e2e__/PrewarmAuthApp.js @@ -0,0 +1,236 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { AppState, Button, Keyboard, SafeAreaView, StyleSheet, Text, TextInput, View } from 'react-native'; +import ConfirmHcaptcha from '@hcaptcha/react-native-hcaptcha'; + +export const authServer = 'http://127.0.0.1:8766'; + +export default function PrewarmAuthApp({ passiveSiteKey = false, slowSdk = false, deferredToken = false, prewarm = true, hideOnError = true, networkTest = false, siteKey = '10000000-ffff-ffff-ffff-000000000001', host, measurements }) { + const captchaRef = useRef(null); + const tokenRef = useRef(null); + const flowRef = useRef(0); + const sourceNonce = useRef(Date.now()).current; + const [page, setPage] = useState('welcome'); + const [mode, setMode] = useState('signup'); + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [tokenCount, setTokenCount] = useState(0); + const [status, setStatus] = useState('Security check prewarming'); + const [submitting, setSubmitting] = useState(false); + let sdkPrefix = ''; + if (slowSdk) { + sdkPrefix = '/slow'; + } else if (networkTest) { + sdkPrefix = `/network/${sourceNonce}`; + } else if (deferredToken) { + sdkPrefix = '/deferred'; + } else if (measurements) { + sdkPrefix = '/measured'; + } + const titles = { + welcome: 'Your next chapter starts here', + credentials: mode === 'signup' ? 'Create your account' : 'Welcome back', + account: 'You’re in', + }; + + const verify = useCallback(() => { + setStatus('Verifying'); + measurements?.attempts.push({ startedAt: global.performance.now() }); + captchaRef.current.execute(); + }, [measurements]); + + useEffect(() => { + if (page === 'credentials') { + verify(); + } + }, [page, verify]); + + useEffect(() => { + const subscription = AppState.addEventListener('change', (state) => measurements?.appStates?.push(state)); + return () => subscription.remove(); + }, [measurements]); + + const onMessage = (event) => { + if (event.markUsed) { + if (measurements?.consumeTokens) { + event.markUsed(); + } + if (measurements) { + const attempt = measurements.attempts[measurements.attempts.length - 1]; + attempt.tokenMs = global.performance.now() - attempt.startedAt; + } + tokenRef.current = { + token: event.nativeEvent.data, + markUsed: event.markUsed, + }; + setTokenCount((count) => count + 1); + setStatus('Token ready'); + captchaRef.current.hide(); + } else if (event.nativeEvent.data === 'open') { + if (measurements) { + measurements.opens = (measurements.opens || 0) + 1; + } + } else { + console.warn('Auth fixture captcha:', event.nativeEvent.data); + measurements?.errors.push({ data: event.nativeEvent.data, description: event.nativeEvent.description }); + tokenRef.current = null; + setStatus(event.nativeEvent.data); + if (hideOnError) { + captchaRef.current.hide(); + } + } + }; + + const leave = () => { + flowRef.current++; + captchaRef.current.hide(); + tokenRef.current?.markUsed(); + tokenRef.current = null; + setPassword(''); + setSubmitting(false); + setPage('welcome'); + }; + + const submit = async () => { + Keyboard.dismiss(); + const token = tokenRef.current; + const flow = flowRef.current; + setSubmitting(true); + try { + const response = await fetch(`${authServer}/${mode}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + email, + password, + token: token.token, + }), + }); + const result = await response.json(); + // The backend may consume the captcha even when credentials are rejected. + token.markUsed(); + if (flow !== flowRef.current) { + return; + } + tokenRef.current = null; + if (!response.ok) { + measurements?.authErrors?.push(result.error); + setPassword(''); + setStatus(result.error); + return; + } + setPage('account'); + } catch (error) { + if (flow === flowRef.current) { + token.markUsed(); + tokenRef.current = null; + setStatus(error.message); + } + } finally { + if (flow === flowRef.current) { + setSubmitting(false); + } + } + }; + + return ( + + + + Acorn + + {titles[page]} + + {page === 'welcome' && ( + <> + Email address + + {['signup', 'login'].map((action) => ( +