@prosopo/procaptcha-frictionless 2.18.7 → 2.19.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 (42) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +4 -7
  2. package/.turbo/turbo-build$colon$tsc.log +24 -27
  3. package/.turbo/turbo-build.log +5 -11
  4. package/CHANGELOG.md +32 -0
  5. package/LICENSE +201 -0
  6. package/dist/cjs/customDetectBot.cjs +3 -3
  7. package/dist/cjs/procaptchaFrictionless.cjs +4 -1
  8. package/dist/customDetectBot.d.ts.map +1 -1
  9. package/dist/customDetectBot.js +3 -3
  10. package/dist/customDetectBot.js.map +1 -1
  11. package/dist/procaptchaFrictionless.d.ts.map +1 -1
  12. package/dist/procaptchaFrictionless.js +4 -1
  13. package/dist/procaptchaFrictionless.js.map +1 -1
  14. package/dist/tests/sessionInvalidatedRemint.test.js +26 -0
  15. package/dist/tests/sessionInvalidatedRemint.test.js.map +1 -1
  16. package/package.json +70 -69
  17. package/src/authenticatedBadge.ts +0 -170
  18. package/src/customDetectBot.ts +0 -392
  19. package/src/detectorLoader.ts +0 -133
  20. package/src/detectorPrefetch.ts +0 -115
  21. package/src/frictionlessResultGuard.ts +0 -110
  22. package/src/index.ts +0 -15
  23. package/src/procaptchaFrictionless.ts +0 -626
  24. package/src/sessionInvalidatedRecovery.ts +0 -110
  25. package/src/tests/authenticatedBadge.unit.test.ts +0 -101
  26. package/src/tests/customDetectBot.test.ts +0 -77
  27. package/src/tests/customDetectBotAssignTimeout.test.ts +0 -185
  28. package/src/tests/customDetectBotSimd.test.ts +0 -173
  29. package/src/tests/detectorLoader.test.ts +0 -108
  30. package/src/tests/detectorPrefetch.test.ts +0 -114
  31. package/src/tests/escalationClientSession.test.ts +0 -216
  32. package/src/tests/escalationHandoff.integration.test.ts +0 -356
  33. package/src/tests/executeBeforeMount.test.ts +0 -233
  34. package/src/tests/frictionlessResultGuard.test.ts +0 -179
  35. package/src/tests/manualStart.test.ts +0 -391
  36. package/src/tests/procaptchaFrictionless.test.ts +0 -468
  37. package/src/tests/sessionInvalidatedRecovery.test.ts +0 -181
  38. package/src/tests/sessionInvalidatedRemint.test.ts +0 -272
  39. package/tsconfig.cjs.json +0 -41
  40. package/tsconfig.json +0 -49
  41. package/tsconfig.tsbuildinfo +0 -1
  42. package/tsconfig.types.json +0 -9
@@ -1,626 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { loadI18next, localiseErrorMessage } from "@prosopo/locale";
16
- import {
17
- type CheckboxProps,
18
- type Component,
19
- type StaticComponent,
20
- Teardown,
21
- clearElement,
22
- createElement,
23
- getDefaultEvents,
24
- getRestartDelayMs,
25
- isSecureBrowserContext,
26
- mountCheckbox,
27
- mountTestModeBanner,
28
- providerRetry,
29
- } from "@prosopo/procaptcha-common";
30
- import {
31
- CaptchaType,
32
- type FrictionlessState,
33
- ModeEnum,
34
- type ModeType,
35
- PROCAPTCHA_START_EVENT,
36
- ProcaptchaConfigSchema,
37
- type ProcaptchaFrictionlessProps,
38
- type ProcaptchaProps,
39
- type ProcaptchaStartEventDetail,
40
- StartModeEnum,
41
- } from "@prosopo/types";
42
- import { darkTheme, lightTheme } from "@prosopo/widget-skeleton";
43
- import { mountAuthenticatedBadge } from "./authenticatedBadge.js";
44
- import customDetectBot from "./customDetectBot.js";
45
- import { evaluateFrictionlessResult } from "./frictionlessResultGuard.js";
46
- import {
47
- type MutableRef,
48
- type RetryCoords,
49
- consumeRetryMountProps,
50
- handleSessionInvalidated,
51
- normaliseRetryCoords,
52
- } from "./sessionInvalidatedRecovery.js";
53
-
54
- const NO_SESSION_FOUND_KEY = "CAPTCHA.NO_SESSION_FOUND";
55
-
56
- const PROCAPTCHA_EXECUTE_EVENT = "procaptcha:execute";
57
-
58
- // Each session uses exactly one solver — chosen by the /frictionless response.
59
- const ProcaptchaLoader = async () =>
60
- (await import("@prosopo/procaptcha-react")).mountProcaptchaImageWidget;
61
- const ProcaptchaPuzzleLoader = async () =>
62
- (await import("@prosopo/procaptcha-puzzle")).mountProcaptchaPuzzleWidget;
63
- const ProcaptchaPowLoader = async () =>
64
- (await import("@prosopo/procaptcha-pow")).mountProcaptchaPowWidget;
65
-
66
- /** A mounted solver widget. All three solvers expose the same teardown. */
67
- interface SolverHandle {
68
- destroy(): void;
69
- }
70
-
71
- export interface ProcaptchaFrictionlessHandle {
72
- destroy(): void;
73
- }
74
-
75
- type FrictionlessLoadingState = {
76
- loading: boolean;
77
- attemptCount: number;
78
- errorMessage?: string;
79
- };
80
-
81
- const defaultLoadingState = (
82
- attemptCount: number,
83
- ): FrictionlessLoadingState => ({
84
- loading: false,
85
- attemptCount,
86
- });
87
-
88
- export const mountProcaptchaFrictionless = (
89
- container: HTMLElement,
90
- props: ProcaptchaFrictionlessProps,
91
- ): ProcaptchaFrictionlessHandle => {
92
- const {
93
- config,
94
- callbacks,
95
- restart,
96
- i18n,
97
- detectBot = customDetectBot,
98
- container: widgetContainer,
99
- } = props;
100
-
101
- const teardown = new Teardown();
102
- const events = getDefaultEvents(callbacks);
103
-
104
- let state = defaultLoadingState(0);
105
- let destroyed = false;
106
-
107
- // Coords carried over from an `onSessionInvalidated` event on the inner
108
- // widget. Consumed once by the next `renderForCaptchaType` — the resumed
109
- // widget mounts with `autoStart` + `startCoords` so the user doesn't have
110
- // to click the checkbox a second time and the checkbox click position is
111
- // preserved in the eventual solution salt.
112
- const pendingRetryCoords: MutableRef<RetryCoords | null> = { current: null };
113
- // Bounded outer guard so a persistently broken session doesn't loop. Each
114
- // re-mint costs a /frictionless round trip, so the count is capped — but
115
- // it is a count rather than a one-shot, because a widget legitimately
116
- // mints a new session every time the user presses reload. `onReload`
117
- // clears it for the same reason. When the budget is spent we fall over
118
- // visibly (see `onSessionInvalidated`) instead of leaving the user on a
119
- // dead "No session found" checkbox.
120
- const sessionInvalidatedAttempts: MutableRef<number> = { current: 0 };
121
- // Escalation sessions we have already mounted a widget for. The provider
122
- // mints exactly one escalation session per PoW solution and consumes it on
123
- // the first challenge fetch, so a repeat handoff for the same id can only
124
- // produce a widget that 400s with NO_SESSION_FOUND. The PoW manager fires
125
- // `onEscalate` from inside its `providerRetry`-wrapped `submit()`, so a
126
- // throw anywhere after the handoff re-runs submit and escalates a second
127
- // time on the same envelope.
128
- const escalatedSessionIds = new Set<string>();
129
- // Set when the next mount must open its challenge without waiting for a
130
- // checkbox click. Held here rather than passed through `start()` because
131
- // `providerRetry` re-invokes `start` with no arguments, which would
132
- // otherwise drop the flag on the first provider retry.
133
- let nextMountAutoStart = false;
134
- // Set when the re-mint was triggered by a wrong puzzle answer rather than a
135
- // reload press, so the replacement challenge still tells the user they
136
- // missed. Held alongside `nextMountAutoStart` for the same reason.
137
- // Also seeded by a full restart after a rejected image answer.
138
- let nextMountShowRetry = true === props.startShowRetry;
139
- const manualStart = StartModeEnum.manual === config.startMode;
140
- let manualStarted = false;
141
- // The inner widget only listens for `procaptcha:execute` once /frictionless
142
- // has answered, its chunk has loaded and it has mounted. An execute() in
143
- // that window (e.g. a fast form submit) would otherwise be dropped and the
144
- // challenge never open, so it is held here and replayed on mount.
145
- let pendingExecute = false;
146
- const banner: StaticComponent = mountTestModeBanner(container, {
147
- siteKey: config.account?.address ?? "",
148
- });
149
-
150
- // The solver (or the placeholder checkbox) renders here. Swapping the slot's
151
- // contents replaces what the React version did by putting an element in
152
- // state and letting the reconciler diff it.
153
- const slot = createElement("div");
154
- container.appendChild(slot);
155
-
156
- let solver: SolverHandle | undefined;
157
- let placeholder: Component<CheckboxProps> | undefined;
158
-
159
- const clearSlot = () => {
160
- solver?.destroy();
161
- solver = undefined;
162
- placeholder?.destroy();
163
- placeholder = undefined;
164
- clearElement(slot);
165
- };
166
-
167
- const renderPlaceholder = (
168
- mode: ModeType,
169
- errorMessage: string | undefined,
170
- loading: boolean,
171
- onChange?: CheckboxProps["onChange"],
172
- ) => {
173
- clearSlot();
174
-
175
- if ("invisible" === mode) {
176
- return;
177
- }
178
-
179
- placeholder = mountCheckbox(slot, {
180
- theme: "light" === config.theme ? lightTheme : darkTheme,
181
- // Inert unless the site asked for a manual start: this checkbox
182
- // stands in until detection picks a solver, and clicking it must
183
- // not start anything of its own.
184
- onChange: onChange ?? (() => undefined),
185
- checked: false,
186
- labelText: i18n.isInitialized ? i18n.t("WIDGET.I_AM_HUMAN") : "",
187
- error: errorMessage,
188
- loadingText: i18n.isInitialized ? i18n.t("WIDGET.CHECKING") : undefined,
189
- loading,
190
- });
191
- };
192
-
193
- // `??`, not `||`: every caller that wants the counter back at zero passes
194
- // literal 0, and `0 || current` silently kept the old count. `start()` then
195
- // tripped its own `attemptCount >= 5` fall-over after five *cumulative*
196
- // runs in a widget lifetime — five reload presses were enough to strand the
197
- // user on the error placeholder even though every one of them succeeded.
198
- const resetState = (attemptCount?: number) => {
199
- state = defaultLoadingState(attemptCount ?? state.attemptCount);
200
- };
201
-
202
- // How many silent restarts this widget has already run. Drives the backoff
203
- // so a client whose session keeps going missing costs the fleet a request
204
- // every two minutes rather than every ten seconds, forever.
205
- let restartCount = 0;
206
-
207
- const restartComponentTimeout = () => {
208
- const delay = getRestartDelayMs(restartCount);
209
- restartCount += 1;
210
- const timer = setTimeout(() => {
211
- resetState(0);
212
- events.onReset();
213
- restart();
214
- }, delay);
215
- teardown.add(() => clearTimeout(timer));
216
- };
217
-
218
- const cannotLoadText = (): string =>
219
- i18n.isInitialized ? i18n.t("WIDGET.CANNOT_LOAD") : "Cannot load CAPTCHA";
220
-
221
- const fallOverWithStyle = (errorMessage?: string, errorKey?: string) => {
222
- // We could always re-render here after a period but this will result in
223
- // never-ending requests to Providers when settings are incorrect, or the
224
- // user is not human. We need to selectively re-render for events like
225
- // `no session found` but not for other errors.
226
- //
227
- // NO_SESSION_FOUND is ours to fix and not the user's to read: the
228
- // session behind the challenge is gone, the only way forward is a new
229
- // one, and we are already minting it. Leave the checkbox in its loading
230
- // state and re-mint behind it, rather than parking a support code on a
231
- // widget that is about to start working again.
232
- if ("CAPTCHA.NO_SESSION_FOUND" === errorKey) {
233
- restartComponentTimeout();
234
- renderPlaceholder(config.mode, undefined, true);
235
- return;
236
- }
237
- renderPlaceholder(
238
- config.mode,
239
- errorMessage
240
- ? localiseErrorMessage(i18n, { message: errorMessage, key: errorKey })
241
- : cannotLoadText(),
242
- false,
243
- );
244
- };
245
-
246
- // The inner widget is now listening, so an execute() that arrived while
247
- // /frictionless was still in flight can be delivered. It goes to the
248
- // container, not document, so other widgets on the page don't run twice.
249
- const replayPendingExecute = () => {
250
- if (!pendingExecute) {
251
- return;
252
- }
253
- pendingExecute = false;
254
- (widgetContainer ?? document).dispatchEvent(
255
- new CustomEvent(PROCAPTCHA_EXECUTE_EVENT),
256
- );
257
- };
258
-
259
- // Mount the captcha widget that matches the chosen type. Used both for the
260
- // initial frictionless decision and for the post-pow escalation handoff —
261
- // in the latter case the FrictionlessState carries the new sessionId minted
262
- // by the provider when it decided PoW alone wasn't enough.
263
- const renderForCaptchaType = async (
264
- captchaType: string,
265
- frictionlessState: FrictionlessState,
266
- autoStart = false,
267
- escalationCoords?: RetryCoords,
268
- ): Promise<void> => {
269
- const onEscalate = (
270
- next: CaptchaType.image | CaptchaType.puzzle,
271
- newSessionId: string,
272
- coords?: RetryCoords,
273
- ) => {
274
- // Idempotent per escalation session — see `escalatedSessionIds`.
275
- // Without this a re-run of the PoW widget's `submit()` mounts a
276
- // second widget against the session the first one already spent,
277
- // which the provider answers with 400 CAPTCHA.NO_SESSION_FOUND.
278
- if (escalatedSessionIds.has(newSessionId)) return;
279
- escalatedSessionIds.add(newSessionId);
280
- void renderForCaptchaType(
281
- next,
282
- {
283
- ...frictionlessState,
284
- sessionId: newSessionId,
285
- },
286
- true,
287
- coords,
288
- );
289
- };
290
-
291
- // The provider returned NO_SESSION_FOUND on the inner widget's
292
- // challenge fetch — the sessionId minted upstream is no longer usable
293
- // (a duplicate /captcha/{type} POST consumed it first, or the widget
294
- // re-sent an id it had already spent). Re-run the frictionless flow to
295
- // mint a fresh session, then re-mount the inner widget with the
296
- // preserved checkbox click coords so the user is not asked to click a
297
- // second time.
298
- //
299
- // The inner widget cannot recover on its own here: it always takes
300
- // this branch and returns before its own `frictionlessState.restart()`
301
- // fallback, and it is rebuilt from scratch on every re-mount. So
302
- // whatever this handler declines to do, nothing else does — hence the
303
- // terminal `fallOverWithStyle` rather than a silent return once the
304
- // retry budget is spent.
305
- const onSessionInvalidated = (x?: number, y?: number) => {
306
- const { shouldRestart } = handleSessionInvalidated(
307
- x,
308
- y,
309
- sessionInvalidatedAttempts,
310
- pendingRetryCoords,
311
- );
312
- if (shouldRestart) {
313
- resetState(0);
314
- void start();
315
- return;
316
- }
317
- // Budget spent. Surface the error on the checkbox and let
318
- // `fallOverWithStyle`'s NO_SESSION_FOUND branch schedule the
319
- // 10-second full restart, so the user always has a way back.
320
- const message = i18n.isInitialized
321
- ? i18n.t(NO_SESSION_FOUND_KEY)
322
- : "No session found";
323
- events.onError(new Error(message));
324
- fallOverWithStyle(message, NO_SESSION_FOUND_KEY);
325
- };
326
-
327
- // The widget wants a replacement challenge — the user pressed reload, or
328
- // the puzzle rejected their answer. The provider consumed this session
329
- // when it issued the challenge, so there is no way to ask it for another
330
- // one — mint a new session by re-running frictionless and re-mount the
331
- // widget with `autoStart`, which is what makes a new challenge appear
332
- // instead of the modal simply closing. Not one-shot: the user may keep
333
- // asking for a different challenge, and at a low `puzzleTolerance` they
334
- // may well miss several in a row.
335
- const onReload = (
336
- x?: number,
337
- y?: number,
338
- options?: { showRetry?: boolean },
339
- ) => {
340
- pendingRetryCoords.current = normaliseRetryCoords(x, y);
341
- nextMountAutoStart = true;
342
- nextMountShowRetry = true === options?.showRetry;
343
- // A reload mints a genuinely new session, so the invalidation
344
- // budget for the *previous* one shouldn't count against it.
345
- sessionInvalidatedAttempts.current = 0;
346
- resetState(0);
347
- void start();
348
- };
349
-
350
- // Consume any pending retry coords now — the resumed widget owns them
351
- // for exactly one auto-fired `manager.start(x, y)`. Cleared so a
352
- // subsequent escalation/re-render doesn't accidentally re-inject.
353
- // Escalation coords (from a PoW→image/puzzle handoff) take precedence
354
- // over pending retry coords when both are present, because escalation
355
- // is the current transition and the pending retry belongs to a prior
356
- // widget instance that never got to consume them.
357
- const forcedAutoStart = nextMountAutoStart;
358
- nextMountAutoStart = false;
359
- const startShowRetry = nextMountShowRetry;
360
- nextMountShowRetry = false;
361
- const { autoStart: resumedAutoStart, startCoords: retryStartCoords } =
362
- consumeRetryMountProps(pendingRetryCoords, autoStart || forcedAutoStart);
363
- const startCoords = escalationCoords ?? retryStartCoords;
364
-
365
- const widgetProps: ProcaptchaProps = {
366
- config,
367
- callbacks,
368
- frictionlessState,
369
- i18n,
370
- autoStart: resumedAutoStart,
371
- startCoords,
372
- startShowRetry,
373
- onSessionInvalidated,
374
- container: widgetContainer,
375
- };
376
-
377
- if (CaptchaType.authenticated === captchaType) {
378
- // Web Bot Auth pre-verified pass-through. No challenge, no
379
- // interaction — the badge encodes and fires the token on mount.
380
- // Skip the loader chain the other branches use because there is no
381
- // captcha module to lazy-import here.
382
- if (!frictionlessState.sessionId) {
383
- events.onError(
384
- new Error(
385
- "authenticated captcha response missing sessionId — provider is misbehaving",
386
- ),
387
- );
388
- fallOverWithStyle();
389
- return;
390
- }
391
- clearSlot();
392
- solver = mountAuthenticatedBadge(slot, {
393
- sessionId: frictionlessState.sessionId,
394
- agent: frictionlessState.agent,
395
- dapp: config.account.address ?? "",
396
- userAccount: frictionlessState.userAccount,
397
- provider: frictionlessState.provider,
398
- callbacks,
399
- theme: "light" === config.theme ? lightTheme : darkTheme,
400
- labels: i18n.isInitialized
401
- ? {
402
- verifiedAgent: i18n.t("WIDGET.VERIFIED_AGENT"),
403
- trustedRequest: i18n.t("WIDGET.TRUSTED_REQUEST"),
404
- }
405
- : undefined,
406
- });
407
- return;
408
- }
409
-
410
- if (CaptchaType.image === captchaType) {
411
- const mount = await ProcaptchaLoader();
412
- if (destroyed) return;
413
- clearSlot();
414
- solver = mount(slot, { ...widgetProps, onReload });
415
- replayPendingExecute();
416
- return;
417
- }
418
-
419
- if (CaptchaType.puzzle === captchaType) {
420
- const mount = await ProcaptchaPuzzleLoader();
421
- if (destroyed) return;
422
- clearSlot();
423
- solver = mount(slot, { ...widgetProps, onReload });
424
- replayPendingExecute();
425
- return;
426
- }
427
-
428
- const mount = await ProcaptchaPowLoader();
429
- if (destroyed) return;
430
- clearSlot();
431
- solver = mount(slot, { ...widgetProps, onEscalate });
432
- replayPendingExecute();
433
- };
434
-
435
- const start = async (): Promise<void> => {
436
- // Procaptcha cannot run over plain HTTP (no SubtleCrypto etc.), which
437
- // would otherwise fail later with a cryptic provider-selection error.
438
- // Surface a clear, non-retrying message instead.
439
- if (!isSecureBrowserContext()) {
440
- const errorMessage = i18n.isInitialized
441
- ? i18n.t("WIDGET.INSECURE_CONTEXT")
442
- : "Procaptcha requires a secure (HTTPS) connection";
443
- events.onError(new Error(errorMessage));
444
- fallOverWithStyle(errorMessage, "WIDGET.INSECURE_CONTEXT");
445
- return;
446
- }
447
-
448
- await providerRetry(
449
- async () => {
450
- state.attemptCount += 1;
451
-
452
- const configOutput = ProcaptchaConfigSchema.parse(config);
453
- // After the first attempt, tell detection this is a retry so it
454
- // re-selects a random provider from the list rather than re-using
455
- // the DNS-routed pronode that just failed.
456
- const result = await detectBot(configOutput, widgetContainer, restart, {
457
- attempt: state.attemptCount,
458
- });
459
-
460
- const guard = evaluateFrictionlessResult(result);
461
- if ("error" === guard.kind) {
462
- // Throwing hands this to providerRetry, which re-rolls onto a
463
- // different provider. The client does not throw on a 400 with a
464
- // JSON body, so without this an unrecognised provider-side
465
- // failure stranded the user on the first response even when
466
- // every other node was healthy.
467
- if (guard.retryable) {
468
- throw new Error(guard.message);
469
- }
470
- state = {
471
- ...state,
472
- loading: false,
473
- errorMessage: guard.message,
474
- };
475
- events.onError(new Error(guard.message));
476
- fallOverWithStyle(guard.message, guard.key);
477
- return;
478
- }
479
-
480
- const frictionlessState: FrictionlessState = {
481
- provider: result.provider,
482
- sessionId: result.sessionId,
483
- userAccount: result.userAccount,
484
- restart, // Pass restart function
485
- behaviorCollector1: result.behaviorCollector1,
486
- behaviorCollector2: result.behaviorCollector2,
487
- behaviorCollector3: result.behaviorCollector3,
488
- behaviorCollector4: result.behaviorCollector4,
489
- deviceCapability: result.deviceCapability,
490
- encryptBehavioralData: result.encryptBehavioralData,
491
- getSimdReadings: result.getSimdReadings,
492
- hp: result.hp,
493
- agent: result.agent,
494
- };
495
-
496
- await renderForCaptchaType(result.captchaType, frictionlessState);
497
-
498
- state = {
499
- ...state,
500
- loading: false,
501
- };
502
- },
503
- start,
504
- resetState,
505
- state.attemptCount,
506
- 5,
507
- ).finally(() => {
508
- if (state.attemptCount >= 5) {
509
- // Retries swallow the underlying error, so without this a site's
510
- // error callback never fires for a failure that retried — it would
511
- // have fired immediately before retrying was introduced.
512
- events.onError(new Error("Cannot load CAPTCHA"));
513
- fallOverWithStyle();
514
- restartComponentTimeout();
515
- }
516
- });
517
- };
518
-
519
- /**
520
- * `startMode: "manual"` defers the whole frictionless flow until the site
521
- * (or the user, via the placeholder checkbox) asks for it. One-shot: the
522
- * flow runs at most once per widget lifetime, however many triggers fire.
523
- */
524
- const startManually = async (
525
- autoStart: boolean,
526
- coords?: RetryCoords,
527
- ): Promise<void> => {
528
- if (manualStarted) return;
529
- manualStarted = true;
530
- pendingRetryCoords.current = coords ?? null;
531
- nextMountAutoStart = autoStart;
532
- renderPlaceholder(config.mode, state.errorMessage, true);
533
- await start();
534
- };
535
-
536
- if (config.language) {
537
- if (i18n) {
538
- if (i18n.language !== config.language) {
539
- void i18n.changeLanguage(config.language);
540
- }
541
- } else {
542
- // Direct consumers don't go through WidgetFactory, so pass the language
543
- // into loadI18next — first init boots with the right language (skipping
544
- // browser detection), and subsequent calls reconcile via changeLanguage
545
- // inside loadI18next.
546
- void loadI18next(false, config.language);
547
- }
548
- }
549
-
550
- const manualCheckboxHandler: CheckboxProps["onChange"] = async (
551
- event: MouseEvent | KeyboardEvent | TouchEvent,
552
- ): Promise<void> => {
553
- let x = 0;
554
- let y = 0;
555
- if ("clientX" in event && "clientY" in event) {
556
- x = event.clientX;
557
- y = event.clientY;
558
- }
559
- await startManually(true, normaliseRetryCoords(x, y) ?? undefined);
560
- };
561
-
562
- // Initial paint: the loading placeholder, before detection resolves. Under
563
- // manual start there is nothing in flight yet, so the box is idle and
564
- // clickable rather than spinning.
565
- renderPlaceholder(
566
- config.mode,
567
- state.errorMessage,
568
- !manualStart,
569
- manualStart ? manualCheckboxHandler : undefined,
570
- );
571
-
572
- if (manualStart) {
573
- teardown.addEventListener(document, PROCAPTCHA_START_EVENT, (event) => {
574
- const detail = (event as CustomEvent<ProcaptchaStartEventDetail>).detail;
575
- if (
576
- detail?.element &&
577
- widgetContainer &&
578
- !detail.element.contains(widgetContainer)
579
- ) {
580
- return;
581
- }
582
- void startManually(false);
583
- });
584
- teardown.addEventListener(document, PROCAPTCHA_EXECUTE_EVENT, () => {
585
- void startManually(true);
586
- });
587
- } else {
588
- // Mirrors the inner widgets' own listeners: a targeted execute() arrives
589
- // on the container in either mode, a bare one on document in invisible
590
- // mode. Either is held until a widget exists to receive it.
591
- const holdExecute = () => {
592
- if (!solver) pendingExecute = true;
593
- };
594
- if (widgetContainer) {
595
- teardown.addEventListener(
596
- widgetContainer,
597
- PROCAPTCHA_EXECUTE_EVENT,
598
- holdExecute,
599
- );
600
- }
601
- if (ModeEnum.invisible === config.mode) {
602
- teardown.addEventListener(
603
- document,
604
- PROCAPTCHA_EXECUTE_EVENT,
605
- holdExecute,
606
- );
607
- }
608
-
609
- // One mount, one frictionless call. The React version needed a
610
- // started-for-identity ref here because a host page recreating
611
- // `callbacks` (or the whole `config`) on every render re-fired the
612
- // effect; there is no re-render to guard against now, so mounting is
613
- // the trigger.
614
- void start();
615
- }
616
-
617
- return {
618
- destroy: () => {
619
- destroyed = true;
620
- teardown.run();
621
- clearSlot();
622
- banner.destroy();
623
- slot.parentNode?.removeChild(slot);
624
- },
625
- };
626
- };