@prosopo/procaptcha-puzzle 2.14.6 → 2.15.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 (47) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +5 -8
  2. package/.turbo/turbo-build$colon$tsc.log +19 -22
  3. package/.turbo/turbo-build.log +6 -12
  4. package/CHANGELOG.md +68 -0
  5. package/LICENSE +201 -0
  6. package/dist/cjs/components/procaptchaWidget.cjs +20 -5
  7. package/dist/cjs/components/puzzleCanvas.cjs +25 -4
  8. package/dist/cjs/services/Manager.cjs +18 -2
  9. package/dist/components/procaptchaWidget.d.ts.map +1 -1
  10. package/dist/components/procaptchaWidget.js +21 -6
  11. package/dist/components/procaptchaWidget.js.map +1 -1
  12. package/dist/components/puzzleCanvas.d.ts +2 -1
  13. package/dist/components/puzzleCanvas.d.ts.map +1 -1
  14. package/dist/components/puzzleCanvas.js +26 -5
  15. package/dist/components/puzzleCanvas.js.map +1 -1
  16. package/dist/services/Manager.d.ts +1 -0
  17. package/dist/services/Manager.d.ts.map +1 -1
  18. package/dist/services/Manager.js +18 -2
  19. package/dist/services/Manager.js.map +1 -1
  20. package/dist/tests/invisibleCanvasVisibility.unit.test.js +3 -1
  21. package/dist/tests/invisibleCanvasVisibility.unit.test.js.map +1 -1
  22. package/dist/tests/manager.unit.test.js +16 -0
  23. package/dist/tests/manager.unit.test.js.map +1 -1
  24. package/dist/tests/procaptchaPuzzle.test-d.js +1 -1
  25. package/dist/tests/procaptchaPuzzle.test-d.js.map +1 -1
  26. package/dist/tests/procaptchaWidget.unit.test.js +73 -0
  27. package/dist/tests/procaptchaWidget.unit.test.js.map +1 -1
  28. package/dist/tests/puzzleCanvas.unit.test.js +33 -0
  29. package/dist/tests/puzzleCanvas.unit.test.js.map +1 -1
  30. package/package.json +72 -71
  31. package/src/components/procaptchaPuzzle.ts +0 -54
  32. package/src/components/procaptchaWidget.ts +0 -422
  33. package/src/components/puzzleCanvas.ts +0 -658
  34. package/src/index.ts +0 -16
  35. package/src/services/Manager.ts +0 -508
  36. package/src/tests/domHarness.ts +0 -122
  37. package/src/tests/invisibleCanvasVisibility.unit.test.ts +0 -179
  38. package/src/tests/manager.unit.test.ts +0 -822
  39. package/src/tests/managerHarness.ts +0 -169
  40. package/src/tests/procaptchaPuzzle.test-d.ts +0 -212
  41. package/src/tests/procaptchaPuzzle.unit.test.ts +0 -138
  42. package/src/tests/procaptchaWidget.unit.test.ts +0 -765
  43. package/src/tests/puzzleCanvas.unit.test.ts +0 -662
  44. package/tsconfig.cjs.json +0 -43
  45. package/tsconfig.json +0 -44
  46. package/tsconfig.tsbuildinfo +0 -1
  47. package/tsconfig.types.json +0 -9
@@ -1,422 +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 { createTranslator, loadI18next } from "@prosopo/locale";
16
- import {
17
- type CheckboxProps,
18
- type Component,
19
- type HoneypotComponent,
20
- type ProcaptchaStateHandle,
21
- Teardown,
22
- buildUpdateState,
23
- createElement,
24
- createProcaptchaState,
25
- createRenderScheduler,
26
- isEventTrusted,
27
- mountCheckbox,
28
- mountHoneypot,
29
- } from "@prosopo/procaptcha-common";
30
- import {
31
- type GetPuzzleCaptchaResponse,
32
- ModeEnum,
33
- type ProcaptchaProps,
34
- type ProcaptchaState,
35
- type PuzzleEvent,
36
- } from "@prosopo/types";
37
- import { darkTheme, lightTheme } from "@prosopo/widget-skeleton";
38
- import { Manager } from "../services/Manager.js";
39
- import { type PuzzleCanvasProps, mountPuzzleCanvas } from "./puzzleCanvas.js";
40
-
41
- // Define the same event name as in the bundle for consistency
42
- const PROCAPTCHA_EXECUTE_EVENT = "procaptcha:execute";
43
-
44
- type PuzzlePhase = "checkbox" | "dragging" | "submitting";
45
-
46
- export interface ProcaptchaPuzzleHandle {
47
- destroy(): void;
48
- }
49
-
50
- export const mountProcaptchaPuzzleWidget = (
51
- container: HTMLElement,
52
- props: ProcaptchaProps,
53
- ): ProcaptchaPuzzleHandle => {
54
- const teardown = new Teardown();
55
- const config = props.config;
56
- const i18n = props.i18n;
57
- const frictionlessState = props.frictionlessState; // Set up Session ID and Provider if they exist
58
- const callbacks = props.callbacks || {};
59
- const translator = createTranslator(i18n);
60
- const isInvisible = ModeEnum.invisible === config.mode;
61
-
62
- const store: ProcaptchaStateHandle = createProcaptchaState();
63
- let loading = false;
64
- let puzzlePhase: PuzzlePhase = "checkbox";
65
- let challengeData: GetPuzzleCaptchaResponse | null = null;
66
- // A re-mint after a wrong answer builds a brand new widget, so the miss is
67
- // only still on screen if the wrapper hands it back to us.
68
- let showRetry = true === props.startShowRetry;
69
- let lastError: ProcaptchaState["error"] = store.state.error;
70
- // See procaptcha-pow's widget — same session-invalidation recovery contract
71
- // with coords preservation across a re-mint.
72
- let lastCoords: { x: number; y: number } | null = null;
73
- let sessionInvalidatedFired = false;
74
-
75
- let honeypot: HoneypotComponent | undefined;
76
- let checkbox: Component<CheckboxProps> | undefined;
77
- let puzzle: Component<PuzzleCanvasProps> | undefined;
78
-
79
- // get the state update mechanism
80
- const updateState = buildUpdateState(store.state, store.update);
81
-
82
- const manager = Manager(
83
- config,
84
- store.state,
85
- updateState,
86
- callbacks,
87
- frictionlessState,
88
- () => honeypot?.getValue(),
89
- );
90
-
91
- const root = createElement("div");
92
- container.appendChild(root);
93
-
94
- if (frictionlessState?.hp) {
95
- honeypot = mountHoneypot(root, { encodedQuestion: frictionlessState.hp });
96
- }
97
-
98
- const handlePuzzleComplete = async (
99
- finalX: number,
100
- finalY: number,
101
- puzzleEvents: PuzzleEvent[],
102
- ): Promise<void> => {
103
- puzzlePhase = "submitting";
104
- scheduler.schedule();
105
-
106
- let verified = false;
107
- try {
108
- verified = await manager.submitSolution(finalX, finalY, puzzleEvents);
109
- } catch (error) {
110
- callbacks.onError?.(
111
- error instanceof Error ? error : new Error(String(error)),
112
- );
113
- }
114
-
115
- if (verified) {
116
- puzzlePhase = "checkbox";
117
- challengeData = null;
118
- showRetry = false;
119
- loading = false;
120
- scheduler.schedule();
121
- return;
122
- }
123
-
124
- // Failed — show retry message and fetch a new challenge
125
- showRetry = true;
126
- puzzlePhase = "dragging";
127
- scheduler.schedule();
128
-
129
- // A frictionless session is single-use: the provider consumed it when it
130
- // issued the puzzle the user just got wrong, so asking `manager.start()`
131
- // for a replacement on the same sessionId can only ever come back
132
- // CAPTCHA.NO_SESSION_FOUND — a wasted round trip that surfaces an error
133
- // on the checkbox before the wrapper recovers. Go straight to the
134
- // re-mint instead; the wrapper mints a new session and re-mounts us with
135
- // `autoStart`, so a fresh puzzle appears in place.
136
- if (frictionlessState?.sessionId && props.onReload) {
137
- puzzlePhase = "submitting";
138
- scheduler.schedule();
139
- props.onReload(lastCoords?.x, lastCoords?.y, { showRetry: true });
140
- return;
141
- }
142
-
143
- try {
144
- const newChallenge = await manager.start();
145
- if (newChallenge) {
146
- challengeData = newChallenge;
147
- } else {
148
- // Couldn't get new challenge, fall back to checkbox
149
- puzzlePhase = "checkbox";
150
- challengeData = null;
151
- showRetry = false;
152
- }
153
- } catch {
154
- puzzlePhase = "checkbox";
155
- challengeData = null;
156
- showRetry = false;
157
- }
158
- loading = false;
159
- scheduler.schedule();
160
- };
161
-
162
- // Dismissing returns to the checkbox; clicking away is not a wrong answer.
163
- const handleDismiss = () => {
164
- puzzlePhase = "checkbox";
165
- challengeData = null;
166
- showRetry = false;
167
- loading = false;
168
- scheduler.schedule();
169
- };
170
-
171
- const puzzleProps = (
172
- challenge: GetPuzzleCaptchaResponse,
173
- ): PuzzleCanvasProps => ({
174
- originX: challenge.originX,
175
- originY: challenge.originY,
176
- background: challenge.background,
177
- piece: challenge.piece,
178
- pieceSize: challenge.pieceSize,
179
- onComplete: (finalX: number, finalY: number, events: PuzzleEvent[]) => {
180
- void handlePuzzleComplete(finalX, finalY, events);
181
- },
182
- showRetry,
183
- submitting: "submitting" === puzzlePhase,
184
- theme: "light" === config.theme ? lightTheme : darkTheme,
185
- translator,
186
- placement: config.placement,
187
- anchor: props.container,
188
- onDismiss: handleDismiss,
189
- });
190
-
191
- const runErrorEffect = () => {
192
- if (store.state.error === lastError) {
193
- return;
194
- }
195
- lastError = store.state.error;
196
- if (!store.state.error) {
197
- return;
198
- }
199
- loading = false;
200
- puzzlePhase = "checkbox";
201
- challengeData = null;
202
- showRetry = false;
203
- if ("CAPTCHA.NO_SESSION_FOUND" !== store.state.error.key) {
204
- return;
205
- }
206
- // Suppressed only when something is actually going to re-mint: this is
207
- // an internal recovery signal, not something the user should read, so
208
- // hold the spinner rather than paint a support code that is about to
209
- // stop being true. Clearing it re-enters this effect once, which returns
210
- // at the `!error` guard. With no recovery route the error stands — a
211
- // spinner that never resolves is worse than a message.
212
- const willRecover =
213
- (props.onSessionInvalidated && !sessionInvalidatedFired) ||
214
- undefined !== frictionlessState;
215
- if (willRecover) {
216
- loading = true;
217
- store.update({ error: undefined });
218
- }
219
- if (props.onSessionInvalidated && !sessionInvalidatedFired) {
220
- sessionInvalidatedFired = true;
221
- props.onSessionInvalidated(lastCoords?.x, lastCoords?.y);
222
- return;
223
- }
224
- if (frictionlessState) {
225
- const timer = setTimeout(() => {
226
- frictionlessState.restart();
227
- }, 100);
228
- teardown.add(() => clearTimeout(timer));
229
- }
230
- };
231
-
232
- const render = () => {
233
- runErrorEffect();
234
-
235
- // Puzzle overlay — shown in both visible and invisible modes once a
236
- // challenge has been fetched; puzzle is inherently interactive.
237
- const showOverlay =
238
- ("dragging" === puzzlePhase || "submitting" === puzzlePhase) &&
239
- null !== challengeData;
240
-
241
- if (showOverlay && null !== challengeData) {
242
- if (undefined === puzzle) {
243
- puzzle = mountPuzzleCanvas(puzzleProps(challengeData));
244
- } else {
245
- puzzle.update(puzzleProps(challengeData));
246
- }
247
- } else {
248
- puzzle?.destroy();
249
- puzzle = undefined;
250
- }
251
-
252
- checkbox?.update(checkboxProps());
253
- };
254
-
255
- const scheduler = createRenderScheduler(render);
256
-
257
- const checkboxProps = (): CheckboxProps => ({
258
- checked: store.state.isHuman,
259
- theme: "light" === config.theme ? lightTheme : darkTheme,
260
- labelText: translator.isReady() ? translator.t("WIDGET.I_AM_HUMAN") : "",
261
- error: store.state.error?.message,
262
- loadingText: translator.t("WIDGET.CHECKING", {
263
- defaultValue: "Checking that you are human",
264
- }),
265
- loading: loading || "submitting" === puzzlePhase,
266
- onChange: async (
267
- event: MouseEvent | KeyboardEvent | TouchEvent,
268
- ): Promise<void> => {
269
- if (loading) {
270
- return;
271
- }
272
- loading = true;
273
- showRetry = false;
274
- scheduler.schedule();
275
-
276
- // Capture click coordinates (mirrors the PoW widget) so the puzzle
277
- // solution salt records the entry-point telemetry.
278
- let x = 0;
279
- let y = 0;
280
- if (!isEventTrusted(event)) {
281
- // Don't capture coordinates for non-trusted events
282
- } else if ("touches" in event && event.touches.length > 0) {
283
- const touch = event.touches[0];
284
- if (touch) {
285
- x = touch.clientX;
286
- y = touch.clientY;
287
- }
288
- } else if ("clientX" in event && "clientY" in event) {
289
- x = event.clientX;
290
- y = event.clientY;
291
- }
292
-
293
- lastCoords = { x, y };
294
- try {
295
- const challenge = await manager.start(x, y);
296
-
297
- if (challenge) {
298
- challengeData = challenge;
299
- puzzlePhase = "dragging";
300
- }
301
- } catch (error) {
302
- // The manager reports failures through state.error; rethrowing here
303
- // only produces an unhandled rejection, since nothing awaits this
304
- // handler.
305
- callbacks.onError?.(
306
- error instanceof Error ? error : new Error(String(error)),
307
- );
308
- } finally {
309
- // A rejected start would otherwise leave the spinner up for good,
310
- // with no way back to the checkbox for the user.
311
- loading = false;
312
- scheduler.schedule();
313
- }
314
- },
315
- });
316
-
317
- // Checkbox — only in visible mode. Invisible mode is driven by the host
318
- // page's execute() call (e.g. on form submit).
319
- if (!isInvisible) {
320
- checkbox = mountCheckbox(root, checkboxProps());
321
- }
322
-
323
- teardown.add(scheduler.cancel);
324
- teardown.add(store.subscribe(scheduler.schedule));
325
- teardown.add(translator.subscribe(scheduler.schedule));
326
-
327
- // A bare execute() reaches every invisible widget via document. A targeted
328
- // execute() is dispatched on this widget's container and works in either
329
- // mode, which is what lets a bound button drive a visible widget. Either
330
- // way it fetches a challenge and drives the puzzle UI through the same
331
- // phase transitions as the visible checkbox flow.
332
- const handleExecute = () => {
333
- void (async () => {
334
- if (loading) {
335
- return;
336
- }
337
- loading = true;
338
- showRetry = false;
339
- scheduler.schedule();
340
- try {
341
- const challenge = await manager.start();
342
- if (challenge) {
343
- challengeData = challenge;
344
- puzzlePhase = "dragging";
345
- }
346
- } catch (error) {
347
- callbacks.onError?.(
348
- error instanceof Error ? error : new Error(String(error)),
349
- );
350
- } finally {
351
- loading = false;
352
- scheduler.schedule();
353
- }
354
- })();
355
- };
356
-
357
- if (props.container) {
358
- teardown.addEventListener(
359
- props.container,
360
- PROCAPTCHA_EXECUTE_EVENT,
361
- handleExecute,
362
- );
363
- }
364
- if (isInvisible) {
365
- teardown.addEventListener(
366
- document,
367
- PROCAPTCHA_EXECUTE_EVENT,
368
- handleExecute,
369
- );
370
- }
371
-
372
- if (config.language) {
373
- if (i18n) {
374
- if (i18n.language !== config.language) {
375
- void i18n.changeLanguage(config.language);
376
- }
377
- } else {
378
- // Direct consumers don't go through WidgetFactory, so pass the language
379
- // into loadI18next — first init boots with the right language (skipping
380
- // browser detection), and subsequent calls reconcile via changeLanguage
381
- // inside loadI18next.
382
- void loadI18next(false, config.language);
383
- }
384
- }
385
-
386
- if (props.autoStart) {
387
- loading = true;
388
- // Deliberately not cleared: an autoStart mount is how a re-mint after a
389
- // wrong answer arrives, and `startShowRetry` says whether it was one.
390
- const coords = props.startCoords;
391
- lastCoords = coords ?? null;
392
- scheduler.schedule();
393
- manager.start(coords?.x ?? 0, coords?.y ?? 0).then(
394
- (challenge: GetPuzzleCaptchaResponse | undefined) => {
395
- if (challenge) {
396
- challengeData = challenge;
397
- puzzlePhase = "dragging";
398
- }
399
- loading = false;
400
- scheduler.schedule();
401
- },
402
- () => {
403
- loading = false;
404
- scheduler.schedule();
405
- },
406
- );
407
- }
408
-
409
- render();
410
-
411
- return {
412
- destroy: () => {
413
- teardown.run();
414
- puzzle?.destroy();
415
- checkbox?.destroy();
416
- honeypot?.destroy();
417
- root.parentNode?.removeChild(root);
418
- },
419
- };
420
- };
421
-
422
- export default mountProcaptchaPuzzleWidget;