@prosopo/procaptcha-frictionless 2.16.5 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +7 -7
  2. package/.turbo/turbo-build$colon$tsc.log +24 -24
  3. package/.turbo/turbo-build.log +12 -12
  4. package/CHANGELOG.md +69 -0
  5. package/dist/{AuthenticatedBadge.d.ts → authenticatedBadge.d.ts} +3 -3
  6. package/dist/authenticatedBadge.d.ts.map +1 -0
  7. package/dist/authenticatedBadge.js +79 -0
  8. package/dist/authenticatedBadge.js.map +1 -0
  9. package/dist/cjs/authenticatedBadge.cjs +79 -0
  10. package/dist/cjs/customDetectBot.cjs +3 -2
  11. package/dist/cjs/detectorPrefetch.cjs +2 -2
  12. package/dist/cjs/index.cjs +2 -2
  13. package/dist/cjs/procaptchaFrictionless.cjs +269 -0
  14. package/dist/customDetectBot.d.ts.map +1 -1
  15. package/dist/customDetectBot.js +4 -3
  16. package/dist/customDetectBot.js.map +1 -1
  17. package/dist/detectorPrefetch.js +2 -2
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +2 -2
  20. package/dist/procaptchaFrictionless.d.ts +6 -0
  21. package/dist/procaptchaFrictionless.d.ts.map +1 -0
  22. package/dist/procaptchaFrictionless.js +269 -0
  23. package/dist/procaptchaFrictionless.js.map +1 -0
  24. package/dist/tests/customDetectBotAssignTimeout.test.js +1 -0
  25. package/dist/tests/customDetectBotAssignTimeout.test.js.map +1 -1
  26. package/dist/tests/customDetectBotSimd.test.js +1 -0
  27. package/dist/tests/customDetectBotSimd.test.js.map +1 -1
  28. package/dist/tests/escalationClientSession.test.d.ts +0 -3
  29. package/dist/tests/escalationClientSession.test.d.ts.map +1 -1
  30. package/dist/tests/escalationClientSession.test.js +52 -61
  31. package/dist/tests/escalationClientSession.test.js.map +1 -1
  32. package/dist/tests/escalationHandoff.integration.test.d.ts +0 -3
  33. package/dist/tests/escalationHandoff.integration.test.d.ts.map +1 -1
  34. package/dist/tests/escalationHandoff.integration.test.js +62 -61
  35. package/dist/tests/escalationHandoff.integration.test.js.map +1 -1
  36. package/dist/tests/executeBeforeMount.test.d.ts +0 -3
  37. package/dist/tests/executeBeforeMount.test.d.ts.map +1 -1
  38. package/dist/tests/executeBeforeMount.test.js +53 -49
  39. package/dist/tests/executeBeforeMount.test.js.map +1 -1
  40. package/dist/tests/manualStart.test.d.ts +0 -3
  41. package/dist/tests/manualStart.test.d.ts.map +1 -1
  42. package/dist/tests/manualStart.test.js +55 -52
  43. package/dist/tests/manualStart.test.js.map +1 -1
  44. package/dist/tests/procaptchaFrictionless.test.d.ts +2 -0
  45. package/dist/tests/procaptchaFrictionless.test.d.ts.map +1 -0
  46. package/dist/tests/procaptchaFrictionless.test.js +244 -0
  47. package/dist/tests/procaptchaFrictionless.test.js.map +1 -0
  48. package/dist/tests/sessionInvalidatedRemint.test.d.ts +0 -3
  49. package/dist/tests/sessionInvalidatedRemint.test.d.ts.map +1 -1
  50. package/dist/tests/sessionInvalidatedRemint.test.js +49 -43
  51. package/dist/tests/sessionInvalidatedRemint.test.js.map +1 -1
  52. package/package.json +11 -13
  53. package/src/authenticatedBadge.ts +151 -0
  54. package/src/customDetectBot.ts +11 -2
  55. package/src/detectorPrefetch.ts +2 -2
  56. package/src/index.ts +1 -1
  57. package/src/{ProcaptchaFrictionless.tsx → procaptchaFrictionless.ts} +285 -314
  58. package/src/tests/customDetectBotAssignTimeout.test.ts +5 -0
  59. package/src/tests/customDetectBotSimd.test.ts +5 -0
  60. package/src/tests/{escalationClientSession.test.tsx → escalationClientSession.test.ts} +83 -92
  61. package/src/tests/{escalationHandoff.integration.test.tsx → escalationHandoff.integration.test.ts} +110 -108
  62. package/src/tests/{executeBeforeMount.test.tsx → executeBeforeMount.test.ts} +79 -77
  63. package/src/tests/{manualStart.test.tsx → manualStart.test.ts} +87 -83
  64. package/src/tests/procaptchaFrictionless.test.ts +408 -0
  65. package/src/tests/{sessionInvalidatedRemint.test.tsx → sessionInvalidatedRemint.test.ts} +67 -64
  66. package/tsconfig.cjs.json +1 -2
  67. package/tsconfig.tsbuildinfo +1 -1
  68. package/dist/AuthenticatedBadge.d.ts.map +0 -1
  69. package/dist/AuthenticatedBadge.js +0 -75
  70. package/dist/AuthenticatedBadge.js.map +0 -1
  71. package/dist/ProcaptchaFrictionless.d.ts +0 -3
  72. package/dist/ProcaptchaFrictionless.d.ts.map +0 -1
  73. package/dist/ProcaptchaFrictionless.js +0 -287
  74. package/dist/ProcaptchaFrictionless.js.map +0 -1
  75. package/dist/cjs/AuthenticatedBadge.cjs +0 -75
  76. package/dist/cjs/ProcaptchaFrictionless.cjs +0 -287
  77. package/src/AuthenticatedBadge.tsx +0 -141
@@ -14,10 +14,16 @@
14
14
 
15
15
  import { loadI18next } from "@prosopo/locale";
16
16
  import {
17
- Checkbox,
18
- TestModeBanner,
17
+ type CheckboxProps,
18
+ type Component,
19
+ type StaticComponent,
20
+ Teardown,
21
+ clearElement,
22
+ createElement,
19
23
  getDefaultEvents,
20
24
  isSecureBrowserContext,
25
+ mountCheckbox,
26
+ mountTestModeBanner,
21
27
  providerRetry,
22
28
  } from "@prosopo/procaptcha-common";
23
29
  import {
@@ -28,16 +34,16 @@ import {
28
34
  PROCAPTCHA_START_EVENT,
29
35
  ProcaptchaConfigSchema,
30
36
  type ProcaptchaFrictionlessProps,
37
+ type ProcaptchaProps,
31
38
  type ProcaptchaStartEventDetail,
32
39
  StartModeEnum,
33
40
  } from "@prosopo/types";
34
41
  import { darkTheme, lightTheme } from "@prosopo/widget-skeleton";
35
- import type { KeyboardEvent, MouseEvent, TouchEvent } from "react";
36
- import { useEffect, useRef, useState } from "react";
37
- import { AuthenticatedBadge } from "./AuthenticatedBadge.js";
42
+ import { mountAuthenticatedBadge } from "./authenticatedBadge.js";
38
43
  import customDetectBot from "./customDetectBot.js";
39
44
  import { evaluateFrictionlessResult } from "./frictionlessResultGuard.js";
40
45
  import {
46
+ type MutableRef,
41
47
  type RetryCoords,
42
48
  consumeRetryMountProps,
43
49
  handleSessionInvalidated,
@@ -46,50 +52,24 @@ import {
46
52
 
47
53
  const NO_SESSION_FOUND_KEY = "CAPTCHA.NO_SESSION_FOUND";
48
54
 
55
+ const PROCAPTCHA_EXECUTE_EVENT = "procaptcha:execute";
56
+
49
57
  // Each session uses exactly one solver — chosen by the /frictionless response.
50
58
  const ProcaptchaLoader = async () =>
51
- (await import("@prosopo/procaptcha-react")).Procaptcha;
59
+ (await import("@prosopo/procaptcha-react")).mountProcaptchaImageWidget;
52
60
  const ProcaptchaPuzzleLoader = async () =>
53
- (await import("@prosopo/procaptcha-puzzle")).ProcaptchaPuzzle;
61
+ (await import("@prosopo/procaptcha-puzzle")).mountProcaptchaPuzzleWidget;
54
62
  const ProcaptchaPowLoader = async () =>
55
- (await import("@prosopo/procaptcha-pow")).ProcaptchaPow;
56
-
57
- const PROCAPTCHA_EXECUTE_EVENT = "procaptcha:execute";
58
-
59
- type CheckboxEvent = MouseEvent | TouchEvent | KeyboardEvent;
60
-
61
- const noopCheckboxHandler = async (_event: CheckboxEvent): Promise<void> => {};
63
+ (await import("@prosopo/procaptcha-pow")).mountProcaptchaPowWidget;
62
64
 
63
- const renderPlaceholder = (
64
- theme: string | undefined,
65
- mode: ModeType,
66
- errorMessage: string | undefined,
67
- isTranslationLoaded: boolean,
68
- translationFn: (key: string) => string,
69
- loading: boolean,
70
- onChange: (event: CheckboxEvent) => Promise<void> = noopCheckboxHandler,
71
- ) => {
72
- const checkboxTheme = "light" === theme ? lightTheme : darkTheme;
65
+ /** A mounted solver widget. All three solvers expose the same teardown. */
66
+ interface SolverHandle {
67
+ destroy(): void;
68
+ }
73
69
 
74
- if (mode === "invisible") {
75
- return null;
76
- }
77
-
78
- return (
79
- <Checkbox
80
- theme={checkboxTheme}
81
- onChange={onChange}
82
- checked={false}
83
- labelText={isTranslationLoaded ? translationFn("WIDGET.I_AM_HUMAN") : ""}
84
- error={errorMessage}
85
- aria-label="human checkbox"
86
- loading={loading}
87
- loadingText={
88
- isTranslationLoaded ? translationFn("WIDGET.CHECKING") : undefined
89
- }
90
- />
91
- );
92
- };
70
+ export interface ProcaptchaFrictionlessHandle {
71
+ destroy(): void;
72
+ }
93
73
 
94
74
  type FrictionlessLoadingState = {
95
75
  loading: boolean;
@@ -104,22 +84,31 @@ const defaultLoadingState = (
104
84
  attemptCount,
105
85
  });
106
86
 
107
- export const ProcaptchaFrictionless = ({
108
- config,
109
- callbacks,
110
- restart,
111
- i18n,
112
- detectBot = customDetectBot,
113
- container,
114
- }: ProcaptchaFrictionlessProps) => {
115
- const stateRef = useRef(defaultLoadingState(0));
87
+ export const mountProcaptchaFrictionless = (
88
+ container: HTMLElement,
89
+ props: ProcaptchaFrictionlessProps,
90
+ ): ProcaptchaFrictionlessHandle => {
91
+ const {
92
+ config,
93
+ callbacks,
94
+ restart,
95
+ i18n,
96
+ detectBot = customDetectBot,
97
+ container: widgetContainer,
98
+ } = props;
99
+
100
+ const teardown = new Teardown();
116
101
  const events = getDefaultEvents(callbacks);
102
+
103
+ let state = defaultLoadingState(0);
104
+ let destroyed = false;
105
+
117
106
  // Coords carried over from an `onSessionInvalidated` event on the inner
118
107
  // widget. Consumed once by the next `renderForCaptchaType` — the resumed
119
108
  // widget mounts with `autoStart` + `startCoords` so the user doesn't have
120
109
  // to click the checkbox a second time and the checkbox click position is
121
110
  // preserved in the eventual solution salt.
122
- const pendingRetryCoordsRef = useRef<RetryCoords | null>(null);
111
+ const pendingRetryCoords: MutableRef<RetryCoords | null> = { current: null };
123
112
  // Bounded outer guard so a persistently broken session doesn't loop. Each
124
113
  // re-mint costs a /frictionless round trip, so the count is capped — but
125
114
  // it is a count rather than a one-shot, because a widget legitimately
@@ -127,7 +116,7 @@ export const ProcaptchaFrictionless = ({
127
116
  // clears it for the same reason. When the budget is spent we fall over
128
117
  // visibly (see `onSessionInvalidated`) instead of leaving the user on a
129
118
  // dead "No session found" checkbox.
130
- const sessionInvalidatedAttemptsRef = useRef(0);
119
+ const sessionInvalidatedAttempts: MutableRef<number> = { current: 0 };
131
120
  // Escalation sessions we have already mounted a widget for. The provider
132
121
  // mints exactly one escalation session per PoW solution and consumes it on
133
122
  // the first challenge fetch, so a repeat handoff for the same id can only
@@ -135,57 +124,65 @@ export const ProcaptchaFrictionless = ({
135
124
  // `onEscalate` from inside its `providerRetry`-wrapped `submit()`, so a
136
125
  // throw anywhere after the handoff re-runs submit and escalates a second
137
126
  // time on the same envelope.
138
- const escalatedSessionIdsRef = useRef(new Set<string>());
139
- // Bumped on every mount so the replacement widget gets a fresh React
140
- // `key`. Without it a re-render for the same captcha type reconciles onto
141
- // the existing element, and the inner widget keeps the manager it built on
142
- // first mount — still closed over the sessionId we've just replaced.
143
- const mountCountRef = useRef(0);
127
+ const escalatedSessionIds = new Set<string>();
144
128
  // Set when the next mount must open its challenge without waiting for a
145
- // checkbox click. Held in a ref rather than passed down through `start()`
146
- // because `providerRetry` re-invokes `start` with no arguments, which would
129
+ // checkbox click. Held here rather than passed through `start()` because
130
+ // `providerRetry` re-invokes `start` with no arguments, which would
147
131
  // otherwise drop the flag on the first provider retry.
148
- const nextMountAutoStartRef = useRef(false);
149
- const manualStart = config.startMode === StartModeEnum.manual;
150
- const manualStartedRef = useRef(false);
151
- // The placeholder is built before `start()` exists in this scope.
152
- const manualCheckboxHandlerRef = useRef(noopCheckboxHandler);
132
+ let nextMountAutoStart = false;
133
+ const manualStart = StartModeEnum.manual === config.startMode;
134
+ let manualStarted = false;
153
135
  // The inner widget only listens for `procaptcha:execute` once /frictionless
154
136
  // has answered, its chunk has loaded and it has mounted. An execute() in
155
137
  // that window (e.g. a fast form submit) would otherwise be dropped and the
156
138
  // challenge never open, so it is held here and replayed on mount.
157
- const innerWidgetRenderedRef = useRef(false);
158
- const innerWidgetListeningRef = useRef(false);
159
- const pendingExecuteRef = useRef(false);
139
+ let pendingExecute = false;
140
+ const banner: StaticComponent = mountTestModeBanner(container, {
141
+ siteKey: config.account?.address ?? "",
142
+ });
143
+
144
+ // The solver (or the placeholder checkbox) renders here. Swapping the slot's
145
+ // contents replaces what the React version did by putting an element in
146
+ // state and letting the reconciler diff it.
147
+ const slot = createElement("div");
148
+ container.appendChild(slot);
149
+
150
+ let solver: SolverHandle | undefined;
151
+ let placeholder: Component<CheckboxProps> | undefined;
152
+
153
+ const clearSlot = () => {
154
+ solver?.destroy();
155
+ solver = undefined;
156
+ placeholder?.destroy();
157
+ placeholder = undefined;
158
+ clearElement(slot);
159
+ };
160
160
 
161
- useEffect(() => {
162
- if (!config.language) return;
163
- if (i18n) {
164
- if (i18n.language !== config.language) {
165
- void i18n.changeLanguage(config.language);
166
- }
161
+ const renderPlaceholder = (
162
+ mode: ModeType,
163
+ errorMessage: string | undefined,
164
+ loading: boolean,
165
+ onChange?: CheckboxProps["onChange"],
166
+ ) => {
167
+ clearSlot();
168
+
169
+ if ("invisible" === mode) {
167
170
  return;
168
171
  }
169
- // Direct-React consumers don't go through WidgetFactory, so pass the
170
- // language into loadI18next — first init boots with the right language
171
- // (skipping browser detection), and subsequent calls reconcile via
172
- // changeLanguage inside loadI18next.
173
- void loadI18next(false, config.language);
174
- }, [i18n, config.language]);
175
-
176
- const [componentToRender, setComponentToRender] = useState(
177
- renderPlaceholder(
178
- config.theme,
179
- config.mode,
180
- stateRef.current.errorMessage,
181
- i18n.isInitialized,
182
- i18n.t,
183
- !manualStart,
184
- manualStart
185
- ? (event: CheckboxEvent) => manualCheckboxHandlerRef.current(event)
186
- : undefined,
187
- ),
188
- );
172
+
173
+ placeholder = mountCheckbox(slot, {
174
+ theme: "light" === config.theme ? lightTheme : darkTheme,
175
+ // Inert unless the site asked for a manual start: this checkbox
176
+ // stands in until detection picks a solver, and clicking it must
177
+ // not start anything of its own.
178
+ onChange: onChange ?? (() => undefined),
179
+ checked: false,
180
+ labelText: i18n.isInitialized ? i18n.t("WIDGET.I_AM_HUMAN") : "",
181
+ error: errorMessage,
182
+ loadingText: i18n.isInitialized ? i18n.t("WIDGET.CHECKING") : undefined,
183
+ loading,
184
+ });
185
+ };
189
186
 
190
187
  // `??`, not `||`: every caller that wants the counter back at zero passes
191
188
  // literal 0, and `0 || current` silently kept the old count. `start()` then
@@ -193,40 +190,48 @@ export const ProcaptchaFrictionless = ({
193
190
  // runs in a widget lifetime — five reload presses were enough to strand the
194
191
  // user on the error placeholder even though every one of them succeeded.
195
192
  const resetState = (attemptCount?: number) => {
196
- stateRef.current = defaultLoadingState(
197
- attemptCount ?? stateRef.current.attemptCount,
198
- );
193
+ state = defaultLoadingState(attemptCount ?? state.attemptCount);
194
+ };
195
+
196
+ const restartComponentTimeout = () => {
197
+ const timer = setTimeout(() => {
198
+ resetState(0);
199
+ events.onReset();
200
+ // `restart` frictionless widget after 10 seconds
201
+ restart();
202
+ }, 10000);
203
+ teardown.add(() => clearTimeout(timer));
199
204
  };
200
205
 
201
206
  const fallOverWithStyle = (errorMessage?: string, errorKey?: string) => {
202
- // We could always re-render here after a period but this will result in never-ending requests to Providers when
203
- // settings are incorrect, or the user is not human. We need to selectively re-render for events like
207
+ // We could always re-render here after a period but this will result in
208
+ // never-ending requests to Providers when settings are incorrect, or the
209
+ // user is not human. We need to selectively re-render for events like
204
210
  // `no session found` but not for other errors.
205
- if (errorKey === "CAPTCHA.NO_SESSION_FOUND") {
206
- setTimeout(() => {
211
+ if ("CAPTCHA.NO_SESSION_FOUND" === errorKey) {
212
+ const timer = setTimeout(() => {
207
213
  restartComponentTimeout();
208
214
  }, 0);
215
+ teardown.add(() => clearTimeout(timer));
209
216
  }
210
- innerWidgetRenderedRef.current = false;
211
- setComponentToRender(
212
- renderPlaceholder(
213
- config.theme,
214
- config.mode,
215
- errorMessage || "Cannot load CAPTCHA",
216
- i18n.isInitialized,
217
- i18n.t,
218
- false,
219
- ),
217
+ renderPlaceholder(
218
+ config.mode,
219
+ errorMessage || "Cannot load CAPTCHA",
220
+ false,
220
221
  );
221
222
  };
222
223
 
223
- const restartComponentTimeout = () => {
224
- setTimeout(() => {
225
- resetState(0);
226
- events.onReset();
227
- // `restart` frictionless widget after 10 seconds
228
- restart();
229
- }, 10000);
224
+ // The inner widget is now listening, so an execute() that arrived while
225
+ // /frictionless was still in flight can be delivered. It goes to the
226
+ // container, not document, so other widgets on the page don't run twice.
227
+ const replayPendingExecute = () => {
228
+ if (!pendingExecute) {
229
+ return;
230
+ }
231
+ pendingExecute = false;
232
+ (widgetContainer ?? document).dispatchEvent(
233
+ new CustomEvent(PROCAPTCHA_EXECUTE_EVENT),
234
+ );
230
235
  };
231
236
 
232
237
  // Mount the captcha widget that matches the chosen type. Used both for the
@@ -238,18 +243,18 @@ export const ProcaptchaFrictionless = ({
238
243
  frictionlessState: FrictionlessState,
239
244
  autoStart = false,
240
245
  escalationCoords?: RetryCoords,
241
- ) => {
246
+ ): Promise<void> => {
242
247
  const onEscalate = (
243
248
  next: CaptchaType.image | CaptchaType.puzzle,
244
249
  newSessionId: string,
245
250
  coords?: RetryCoords,
246
251
  ) => {
247
- // Idempotent per escalation session — see `escalatedSessionIdsRef`.
252
+ // Idempotent per escalation session — see `escalatedSessionIds`.
248
253
  // Without this a re-run of the PoW widget's `submit()` mounts a
249
254
  // second widget against the session the first one already spent,
250
255
  // which the provider answers with 400 CAPTCHA.NO_SESSION_FOUND.
251
- if (escalatedSessionIdsRef.current.has(newSessionId)) return;
252
- escalatedSessionIdsRef.current.add(newSessionId);
256
+ if (escalatedSessionIds.has(newSessionId)) return;
257
+ escalatedSessionIds.add(newSessionId);
253
258
  void renderForCaptchaType(
254
259
  next,
255
260
  {
@@ -271,16 +276,16 @@ export const ProcaptchaFrictionless = ({
271
276
  //
272
277
  // The inner widget cannot recover on its own here: it always takes
273
278
  // this branch and returns before its own `frictionlessState.restart()`
274
- // fallback, and its guard ref is fresh on every re-mount. So whatever
275
- // this handler declines to do, nothing else does — hence the terminal
276
- // `fallOverWithStyle` rather than a silent return once the retry
277
- // budget is spent.
279
+ // fallback, and it is rebuilt from scratch on every re-mount. So
280
+ // whatever this handler declines to do, nothing else does — hence the
281
+ // terminal `fallOverWithStyle` rather than a silent return once the
282
+ // retry budget is spent.
278
283
  const onSessionInvalidated = (x?: number, y?: number) => {
279
284
  const { shouldRestart } = handleSessionInvalidated(
280
285
  x,
281
286
  y,
282
- sessionInvalidatedAttemptsRef,
283
- pendingRetryCoordsRef,
287
+ sessionInvalidatedAttempts,
288
+ pendingRetryCoords,
284
289
  );
285
290
  if (shouldRestart) {
286
291
  resetState(0);
@@ -304,11 +309,11 @@ export const ProcaptchaFrictionless = ({
304
309
  // challenge appear instead of the modal simply closing. Not one-shot:
305
310
  // the user may keep asking for a different challenge.
306
311
  const onReload = (x?: number, y?: number) => {
307
- pendingRetryCoordsRef.current = normaliseRetryCoords(x, y);
308
- nextMountAutoStartRef.current = true;
312
+ pendingRetryCoords.current = normaliseRetryCoords(x, y);
313
+ nextMountAutoStart = true;
309
314
  // A reload mints a genuinely new session, so the invalidation
310
315
  // budget for the *previous* one shouldn't count against it.
311
- sessionInvalidatedAttemptsRef.current = 0;
316
+ sessionInvalidatedAttempts.current = 0;
312
317
  resetState(0);
313
318
  void start();
314
319
  };
@@ -320,23 +325,28 @@ export const ProcaptchaFrictionless = ({
320
325
  // over pending retry coords when both are present, because escalation
321
326
  // is the current transition and the pending retry belongs to a prior
322
327
  // widget instance that never got to consume them.
323
- const forcedAutoStart = nextMountAutoStartRef.current;
324
- nextMountAutoStartRef.current = false;
328
+ const forcedAutoStart = nextMountAutoStart;
329
+ nextMountAutoStart = false;
325
330
  const { autoStart: resumedAutoStart, startCoords: retryStartCoords } =
326
- consumeRetryMountProps(
327
- pendingRetryCoordsRef,
328
- autoStart || forcedAutoStart,
329
- );
331
+ consumeRetryMountProps(pendingRetryCoords, autoStart || forcedAutoStart);
330
332
  const startCoords = escalationCoords ?? retryStartCoords;
331
- mountCountRef.current += 1;
332
- const mountKey = mountCountRef.current;
333
- innerWidgetRenderedRef.current = true;
334
333
 
335
- if (captchaType === CaptchaType.authenticated) {
334
+ const widgetProps: ProcaptchaProps = {
335
+ config,
336
+ callbacks,
337
+ frictionlessState,
338
+ i18n,
339
+ autoStart: resumedAutoStart,
340
+ startCoords,
341
+ onSessionInvalidated,
342
+ container: widgetContainer,
343
+ };
344
+
345
+ if (CaptchaType.authenticated === captchaType) {
336
346
  // Web Bot Auth pre-verified pass-through. No challenge, no
337
- // interaction — the badge component encodes and fires the token
338
- // on mount. Skip the loader chain the other branches use because
339
- // there is no captcha module to lazy-import here.
347
+ // interaction — the badge encodes and fires the token on mount.
348
+ // Skip the loader chain the other branches use because there is no
349
+ // captcha module to lazy-import here.
340
350
  if (!frictionlessState.sessionId) {
341
351
  events.onError(
342
352
  new Error(
@@ -346,67 +356,44 @@ export const ProcaptchaFrictionless = ({
346
356
  fallOverWithStyle();
347
357
  return;
348
358
  }
349
- setComponentToRender(
350
- <AuthenticatedBadge
351
- sessionId={frictionlessState.sessionId}
352
- agent={frictionlessState.agent}
353
- dapp={config.account.address ?? ""}
354
- userAccount={frictionlessState.userAccount}
355
- provider={frictionlessState.provider}
356
- callbacks={callbacks}
357
- />,
358
- );
359
- } else if (captchaType === CaptchaType.image) {
360
- const Procaptcha = await ProcaptchaLoader();
361
- setComponentToRender(
362
- <Procaptcha
363
- key={mountKey}
364
- config={config}
365
- callbacks={callbacks}
366
- frictionlessState={frictionlessState}
367
- i18n={i18n}
368
- autoStart={resumedAutoStart}
369
- startCoords={startCoords}
370
- onSessionInvalidated={onSessionInvalidated}
371
- container={container}
372
- onReload={onReload}
373
- />,
374
- );
375
- } else if (captchaType === CaptchaType.puzzle) {
376
- const ProcaptchaPuzzle = await ProcaptchaPuzzleLoader();
377
- setComponentToRender(
378
- <ProcaptchaPuzzle
379
- key={mountKey}
380
- config={config}
381
- callbacks={callbacks}
382
- frictionlessState={frictionlessState}
383
- i18n={i18n}
384
- autoStart={resumedAutoStart}
385
- startCoords={startCoords}
386
- onSessionInvalidated={onSessionInvalidated}
387
- container={container}
388
- />,
389
- );
390
- } else {
391
- const ProcaptchaPow = await ProcaptchaPowLoader();
392
- setComponentToRender(
393
- <ProcaptchaPow
394
- key={mountKey}
395
- config={config}
396
- callbacks={callbacks}
397
- frictionlessState={frictionlessState}
398
- i18n={i18n}
399
- onEscalate={onEscalate}
400
- autoStart={resumedAutoStart}
401
- startCoords={startCoords}
402
- onSessionInvalidated={onSessionInvalidated}
403
- container={container}
404
- />,
405
- );
359
+ clearSlot();
360
+ solver = mountAuthenticatedBadge(slot, {
361
+ sessionId: frictionlessState.sessionId,
362
+ agent: frictionlessState.agent,
363
+ dapp: config.account.address ?? "",
364
+ userAccount: frictionlessState.userAccount,
365
+ provider: frictionlessState.provider,
366
+ callbacks,
367
+ });
368
+ return;
369
+ }
370
+
371
+ if (CaptchaType.image === captchaType) {
372
+ const mount = await ProcaptchaLoader();
373
+ if (destroyed) return;
374
+ clearSlot();
375
+ solver = mount(slot, { ...widgetProps, onReload });
376
+ replayPendingExecute();
377
+ return;
378
+ }
379
+
380
+ if (CaptchaType.puzzle === captchaType) {
381
+ const mount = await ProcaptchaPuzzleLoader();
382
+ if (destroyed) return;
383
+ clearSlot();
384
+ solver = mount(slot, widgetProps);
385
+ replayPendingExecute();
386
+ return;
406
387
  }
388
+
389
+ const mount = await ProcaptchaPowLoader();
390
+ if (destroyed) return;
391
+ clearSlot();
392
+ solver = mount(slot, { ...widgetProps, onEscalate });
393
+ replayPendingExecute();
407
394
  };
408
395
 
409
- const start = async () => {
396
+ const start = async (): Promise<void> => {
410
397
  // Procaptcha cannot run over plain HTTP (no SubtleCrypto etc.), which
411
398
  // would otherwise fail later with a cryptic provider-selection error.
412
399
  // Surface a clear, non-retrying message instead.
@@ -421,18 +408,18 @@ export const ProcaptchaFrictionless = ({
421
408
 
422
409
  await providerRetry(
423
410
  async () => {
424
- stateRef.current.attemptCount += 1;
411
+ state.attemptCount += 1;
425
412
 
426
413
  const configOutput = ProcaptchaConfigSchema.parse(config);
427
414
  // After the first attempt, tell detection this is a retry so it
428
415
  // re-selects a random provider from the list rather than re-using
429
416
  // the DNS-routed pronode that just failed.
430
- const result = await detectBot(configOutput, container, restart, {
431
- attempt: stateRef.current.attemptCount,
417
+ const result = await detectBot(configOutput, widgetContainer, restart, {
418
+ attempt: state.attemptCount,
432
419
  });
433
420
 
434
421
  const guard = evaluateFrictionlessResult(result);
435
- if (guard.kind === "error") {
422
+ if ("error" === guard.kind) {
436
423
  // Throwing hands this to providerRetry, which re-rolls onto a
437
424
  // different provider. The client does not throw on a 400 with a
438
425
  // JSON body, so without this an unrecognised provider-side
@@ -441,8 +428,8 @@ export const ProcaptchaFrictionless = ({
441
428
  if (guard.retryable) {
442
429
  throw new Error(guard.message);
443
430
  }
444
- stateRef.current = {
445
- ...stateRef.current,
431
+ state = {
432
+ ...state,
446
433
  loading: false,
447
434
  errorMessage: guard.message,
448
435
  };
@@ -468,17 +455,17 @@ export const ProcaptchaFrictionless = ({
468
455
 
469
456
  await renderForCaptchaType(result.captchaType, frictionlessState);
470
457
 
471
- stateRef.current = {
472
- ...stateRef.current,
458
+ state = {
459
+ ...state,
473
460
  loading: false,
474
461
  };
475
462
  },
476
463
  start,
477
464
  resetState,
478
- stateRef.current.attemptCount,
465
+ state.attemptCount,
479
466
  5,
480
467
  ).finally(() => {
481
- if (stateRef.current.attemptCount >= 5) {
468
+ if (state.attemptCount >= 5) {
482
469
  // Retries swallow the underlying error, so without this a site's
483
470
  // error callback never fires for a failure that retried — it would
484
471
  // have fired immediately before retrying was introduced.
@@ -489,127 +476,111 @@ export const ProcaptchaFrictionless = ({
489
476
  });
490
477
  };
491
478
 
479
+ /**
480
+ * `startMode: "manual"` defers the whole frictionless flow until the site
481
+ * (or the user, via the placeholder checkbox) asks for it. One-shot: the
482
+ * flow runs at most once per widget lifetime, however many triggers fire.
483
+ */
492
484
  const startManually = async (
493
485
  autoStart: boolean,
494
486
  coords?: RetryCoords,
495
487
  ): Promise<void> => {
496
- if (manualStartedRef.current) return;
497
- manualStartedRef.current = true;
498
- pendingRetryCoordsRef.current = coords ?? null;
499
- nextMountAutoStartRef.current = autoStart;
500
- innerWidgetRenderedRef.current = false;
501
- setComponentToRender(
502
- renderPlaceholder(
503
- config.theme,
504
- config.mode,
505
- stateRef.current.errorMessage,
506
- i18n.isInitialized,
507
- i18n.t,
508
- true,
509
- ),
510
- );
488
+ if (manualStarted) return;
489
+ manualStarted = true;
490
+ pendingRetryCoords.current = coords ?? null;
491
+ nextMountAutoStart = autoStart;
492
+ renderPlaceholder(config.mode, state.errorMessage, true);
511
493
  await start();
512
494
  };
513
495
 
514
- manualCheckboxHandlerRef.current = async (event: CheckboxEvent) => {
496
+ if (config.language) {
497
+ if (i18n) {
498
+ if (i18n.language !== config.language) {
499
+ void i18n.changeLanguage(config.language);
500
+ }
501
+ } else {
502
+ // Direct consumers don't go through WidgetFactory, so pass the language
503
+ // into loadI18next — first init boots with the right language (skipping
504
+ // browser detection), and subsequent calls reconcile via changeLanguage
505
+ // inside loadI18next.
506
+ void loadI18next(false, config.language);
507
+ }
508
+ }
509
+
510
+ const manualCheckboxHandler: CheckboxProps["onChange"] = async (
511
+ event: MouseEvent | KeyboardEvent | TouchEvent,
512
+ ): Promise<void> => {
515
513
  let x = 0;
516
514
  let y = 0;
517
- const nativeEvent = event.nativeEvent;
518
- if ("clientX" in nativeEvent && "clientY" in nativeEvent) {
519
- x = nativeEvent.clientX;
520
- y = nativeEvent.clientY;
515
+ if ("clientX" in event && "clientY" in event) {
516
+ x = event.clientX;
517
+ y = event.clientY;
521
518
  }
522
519
  await startManually(true, normaliseRetryCoords(x, y) ?? undefined);
523
520
  };
524
521
 
525
- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional — `startManually` captures the mount-time `start()`, as the auto-mode effect below does.
526
- useEffect(() => {
527
- if (!manualStart) return;
528
- const onStartEvent = (event: Event) => {
522
+ // Initial paint: the loading placeholder, before detection resolves. Under
523
+ // manual start there is nothing in flight yet, so the box is idle and
524
+ // clickable rather than spinning.
525
+ renderPlaceholder(
526
+ config.mode,
527
+ state.errorMessage,
528
+ !manualStart,
529
+ manualStart ? manualCheckboxHandler : undefined,
530
+ );
531
+
532
+ if (manualStart) {
533
+ teardown.addEventListener(document, PROCAPTCHA_START_EVENT, (event) => {
529
534
  const detail = (event as CustomEvent<ProcaptchaStartEventDetail>).detail;
530
- if (detail?.element && container && !detail.element.contains(container)) {
535
+ if (
536
+ detail?.element &&
537
+ widgetContainer &&
538
+ !detail.element.contains(widgetContainer)
539
+ ) {
531
540
  return;
532
541
  }
533
542
  void startManually(false);
534
- };
535
- const onExecuteEvent = () => {
543
+ });
544
+ teardown.addEventListener(document, PROCAPTCHA_EXECUTE_EVENT, () => {
536
545
  void startManually(true);
546
+ });
547
+ } else {
548
+ // Mirrors the inner widgets' own listeners: a targeted execute() arrives
549
+ // on the container in either mode, a bare one on document in invisible
550
+ // mode. Either is held until a widget exists to receive it.
551
+ const holdExecute = () => {
552
+ if (!solver) pendingExecute = true;
537
553
  };
538
- document.addEventListener(PROCAPTCHA_START_EVENT, onStartEvent);
539
- document.addEventListener(PROCAPTCHA_EXECUTE_EVENT, onExecuteEvent);
540
- return () => {
541
- document.removeEventListener(PROCAPTCHA_START_EVENT, onStartEvent);
542
- document.removeEventListener(PROCAPTCHA_EXECUTE_EVENT, onExecuteEvent);
543
- };
544
- }, [manualStart, container]);
545
-
546
- // Mirrors the inner widgets' own listeners: a targeted execute() arrives on
547
- // the container in either mode, a bare one on document in invisible mode.
548
- // Manual start has its own listener above that defers the whole flow.
549
- useEffect(() => {
550
- if (manualStart) return;
551
- const invisible = config.mode === ModeEnum.invisible;
552
- const onExecuteEvent = () => {
553
- if (!innerWidgetListeningRef.current) pendingExecuteRef.current = true;
554
- };
555
- container?.addEventListener(PROCAPTCHA_EXECUTE_EVENT, onExecuteEvent);
556
- if (invisible) {
557
- document.addEventListener(PROCAPTCHA_EXECUTE_EVENT, onExecuteEvent);
554
+ if (widgetContainer) {
555
+ teardown.addEventListener(
556
+ widgetContainer,
557
+ PROCAPTCHA_EXECUTE_EVENT,
558
+ holdExecute,
559
+ );
560
+ }
561
+ if (ModeEnum.invisible === config.mode) {
562
+ teardown.addEventListener(
563
+ document,
564
+ PROCAPTCHA_EXECUTE_EVENT,
565
+ holdExecute,
566
+ );
558
567
  }
559
- return () => {
560
- container?.removeEventListener(PROCAPTCHA_EXECUTE_EVENT, onExecuteEvent);
561
- if (invisible) {
562
- document.removeEventListener(PROCAPTCHA_EXECUTE_EVENT, onExecuteEvent);
563
- }
564
- };
565
- }, [manualStart, config.mode, container]);
566
568
 
567
- // Child effects run before this one, so a newly mounted inner widget is
568
- // already listening when the held execute() is replayed. It goes to the
569
- // container, not document, so other widgets on the page don't run twice.
570
- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional — must run after every commit that swaps the rendered widget.
571
- useEffect(() => {
572
- innerWidgetListeningRef.current = innerWidgetRenderedRef.current;
573
- if (!innerWidgetListeningRef.current || !pendingExecuteRef.current) return;
574
- pendingExecuteRef.current = false;
575
- (container ?? document).dispatchEvent(
576
- new CustomEvent(PROCAPTCHA_EXECUTE_EVENT),
577
- );
578
- }, [componentToRender, container]);
579
-
580
- // Track which config identity has already been started for. Host
581
- // pages often recreate the `callbacks` object (and sometimes the whole
582
- // `config`) on every render, which — before this guard — re-fired
583
- // the outer effect on every parent re-render and triggered a fresh
584
- // `/frictionless` call each time. On the 2026-07-01 iPhone WKWebView
585
- // incident we saw three frictionless calls fan out in 3 ms for the
586
- // same user and site key, each carrying its own sessionId, producing
587
- // "No session found" cascades and eventually an image-escalation
588
- // storm.
589
- //
590
- // Dep list is now the primitive identity of the widget (site key +
591
- // language + mode); the per-identity ref guard makes React StrictMode
592
- // double-invocation and same-identity re-renders idempotent.
593
- // `callbacks` and `detectBot` intentionally do NOT participate —
594
- // they're read via the closure captured by `start()` at call time,
595
- // so the latest values are still visible without triggering effect
596
- // re-runs.
597
- const startedForKeyRef = useRef<string | null>(null);
598
- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional — see comment above.
599
- useEffect(() => {
600
- const key = `${config.account?.address ?? ""}|${config.language ?? ""}|${
601
- config.mode ?? ""
602
- }`;
603
- if (startedForKeyRef.current === key) return;
604
- startedForKeyRef.current = key;
605
- if (manualStart) return;
569
+ // One mount, one frictionless call. The React version needed a
570
+ // started-for-identity ref here because a host page recreating
571
+ // `callbacks` (or the whole `config`) on every render re-fired the
572
+ // effect; there is no re-render to guard against now, so mounting is
573
+ // the trigger.
606
574
  void start();
607
- }, [config.account?.address, config.language, config.mode]);
575
+ }
608
576
 
609
- return (
610
- <>
611
- <TestModeBanner siteKey={config.account?.address ?? ""} />
612
- {componentToRender}
613
- </>
614
- );
577
+ return {
578
+ destroy: () => {
579
+ destroyed = true;
580
+ teardown.run();
581
+ clearSlot();
582
+ banner.destroy();
583
+ slot.parentNode?.removeChild(slot);
584
+ },
585
+ };
615
586
  };