@prosopo/procaptcha-frictionless 2.18.7 → 2.20.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 (55) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +18 -17
  2. package/.turbo/turbo-build$colon$tsc.log +32 -29
  3. package/.turbo/turbo-build.log +19 -21
  4. package/CHANGELOG.md +87 -0
  5. package/LICENSE +201 -0
  6. package/dist/cjs/customDetectBot.cjs +6 -4
  7. package/dist/cjs/procaptchaFrictionless.cjs +79 -40
  8. package/dist/customDetectBot.d.ts.map +1 -1
  9. package/dist/customDetectBot.js +6 -4
  10. package/dist/customDetectBot.js.map +1 -1
  11. package/dist/procaptchaFrictionless.d.ts.map +1 -1
  12. package/dist/procaptchaFrictionless.js +80 -41
  13. package/dist/procaptchaFrictionless.js.map +1 -1
  14. package/dist/tests/clickWhileSolverLoads.test.d.ts +2 -0
  15. package/dist/tests/clickWhileSolverLoads.test.d.ts.map +1 -0
  16. package/dist/tests/clickWhileSolverLoads.test.js +93 -0
  17. package/dist/tests/clickWhileSolverLoads.test.js.map +1 -0
  18. package/dist/tests/procaptchaFrictionless.test.js +104 -1
  19. package/dist/tests/procaptchaFrictionless.test.js.map +1 -1
  20. package/dist/tests/sessionInvalidatedRemint.test.js +26 -0
  21. package/dist/tests/sessionInvalidatedRemint.test.js.map +1 -1
  22. package/dist/tests/startMode.test.d.ts +2 -0
  23. package/dist/tests/startMode.test.d.ts.map +1 -0
  24. package/dist/tests/{manualStart.test.js → startMode.test.js} +68 -1
  25. package/dist/tests/startMode.test.js.map +1 -0
  26. package/package.json +72 -69
  27. package/dist/tests/manualStart.test.d.ts +0 -2
  28. package/dist/tests/manualStart.test.d.ts.map +0 -1
  29. package/dist/tests/manualStart.test.js.map +0 -1
  30. package/src/authenticatedBadge.ts +0 -170
  31. package/src/customDetectBot.ts +0 -392
  32. package/src/detectorLoader.ts +0 -133
  33. package/src/detectorPrefetch.ts +0 -115
  34. package/src/frictionlessResultGuard.ts +0 -110
  35. package/src/index.ts +0 -15
  36. package/src/procaptchaFrictionless.ts +0 -626
  37. package/src/sessionInvalidatedRecovery.ts +0 -110
  38. package/src/tests/authenticatedBadge.unit.test.ts +0 -101
  39. package/src/tests/customDetectBot.test.ts +0 -77
  40. package/src/tests/customDetectBotAssignTimeout.test.ts +0 -185
  41. package/src/tests/customDetectBotSimd.test.ts +0 -173
  42. package/src/tests/detectorLoader.test.ts +0 -108
  43. package/src/tests/detectorPrefetch.test.ts +0 -114
  44. package/src/tests/escalationClientSession.test.ts +0 -216
  45. package/src/tests/escalationHandoff.integration.test.ts +0 -356
  46. package/src/tests/executeBeforeMount.test.ts +0 -233
  47. package/src/tests/frictionlessResultGuard.test.ts +0 -179
  48. package/src/tests/manualStart.test.ts +0 -391
  49. package/src/tests/procaptchaFrictionless.test.ts +0 -468
  50. package/src/tests/sessionInvalidatedRecovery.test.ts +0 -181
  51. package/src/tests/sessionInvalidatedRemint.test.ts +0 -272
  52. package/tsconfig.cjs.json +0 -41
  53. package/tsconfig.json +0 -49
  54. package/tsconfig.tsbuildinfo +0 -1
  55. package/tsconfig.types.json +0 -9
@@ -1,468 +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 type { Ti18n, TranslateOptions } from "@prosopo/locale";
16
- import {
17
- type BotDetectionFunction,
18
- type BotDetectionFunctionResult,
19
- CaptchaType,
20
- type ProcaptchaClientConfigOutput,
21
- type ProcaptchaFrictionlessProps,
22
- type ProcaptchaProps,
23
- } from "@prosopo/types";
24
- import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
25
-
26
- /**
27
- * The orchestrator decides which solver to mount, tears the previous one down,
28
- * and owns the recovery paths. Each solver package is stubbed to a probe so a
29
- * test can read the props it was handed and assert the mount/unmount ordering
30
- * that used to come free from the reconciler.
31
- */
32
- const mocks = vi.hoisted(() => {
33
- const mounted: { solver: string; props: ProcaptchaProps }[] = [];
34
- const destroyed: string[] = [];
35
- const probe =
36
- (solver: string) => (container: HTMLElement, props: ProcaptchaProps) => {
37
- mounted.push({ solver, props });
38
- const element = container.ownerDocument.createElement("div");
39
- element.setAttribute("data-solver", solver);
40
- container.appendChild(element);
41
- return {
42
- destroy: () => {
43
- element.remove();
44
- destroyed.push(solver);
45
- },
46
- };
47
- };
48
- return { mounted, destroyed, probe };
49
- });
50
-
51
- // jsdom serves the suite over http, so the widget's own HTTPS guard would
52
- // short-circuit every test before detection ran.
53
- vi.mock("@prosopo/procaptcha-common", async (importOriginal) => ({
54
- ...(await importOriginal<typeof import("@prosopo/procaptcha-common")>()),
55
- isSecureBrowserContext: () => true,
56
- }));
57
-
58
- vi.mock("@prosopo/procaptcha-react", () => ({
59
- mountProcaptchaImageWidget: mocks.probe("image"),
60
- }));
61
- vi.mock("@prosopo/procaptcha-puzzle", () => ({
62
- mountProcaptchaPuzzleWidget: mocks.probe("puzzle"),
63
- }));
64
- vi.mock("@prosopo/procaptcha-pow", () => ({
65
- mountProcaptchaPowWidget: mocks.probe("pow"),
66
- }));
67
-
68
- const { mountProcaptchaFrictionless } = await import(
69
- "../procaptchaFrictionless.js"
70
- );
71
- const { MAX_SESSION_INVALIDATED_RETRIES } = await import(
72
- "../sessionInvalidatedRecovery.js"
73
- );
74
-
75
- const SITE_KEY = "5CcNvLUdiXFpzKDMjThGLSK9rhWHA1H4EF3zrgkpkjAdqmuP";
76
-
77
- const config = (): ProcaptchaClientConfigOutput =>
78
- ({
79
- account: { address: SITE_KEY },
80
- defaultEnvironment: "staging",
81
- mode: "visible",
82
- theme: "light",
83
- }) as unknown as ProcaptchaClientConfigOutput;
84
-
85
- const i18n = (catalogue: Record<string, string> = {}): Ti18n =>
86
- ({
87
- isInitialized: true,
88
- t: (key: string, options?: TranslateOptions) =>
89
- catalogue[key] ?? options?.defaultValue ?? key,
90
- language: "en",
91
- changeLanguage: () => Promise.resolve(),
92
- }) as unknown as Ti18n;
93
-
94
- const detection = (
95
- captchaType: CaptchaType,
96
- overrides: Partial<BotDetectionFunctionResult> = {},
97
- ): BotDetectionFunctionResult =>
98
- ({
99
- captchaType,
100
- sessionId: "session-1",
101
- provider: { providerAccount: "acc", provider: { url: "https://p.one" } },
102
- userAccount: { account: { address: "user" } },
103
- ...overrides,
104
- }) as unknown as BotDetectionFunctionResult;
105
-
106
- let container: HTMLDivElement;
107
- let widget: { destroy: () => void } | undefined;
108
-
109
- const props = (
110
- detectBot: BotDetectionFunction,
111
- overrides: Partial<ProcaptchaFrictionlessProps> = {},
112
- ): ProcaptchaFrictionlessProps => ({
113
- config: config(),
114
- callbacks: {},
115
- i18n: i18n(),
116
- restart: () => undefined,
117
- detectBot,
118
- ...overrides,
119
- });
120
-
121
- const settle = async (): Promise<void> => {
122
- await new Promise<void>((resolve: () => void) => setTimeout(resolve, 0));
123
- await Promise.resolve();
124
- };
125
-
126
- const waitFor = async (condition: () => boolean): Promise<void> => {
127
- for (let poll = 0; poll < 100 && !condition(); poll++) {
128
- await new Promise<void>((resolve: () => void) => setTimeout(resolve, 20));
129
- }
130
- };
131
-
132
- const solvers = (): string[] =>
133
- Array.from(container.querySelectorAll("[data-solver]")).map(
134
- (element: Element) => element.getAttribute("data-solver") ?? "",
135
- );
136
-
137
- beforeEach(() => {
138
- mocks.mounted.length = 0;
139
- mocks.destroyed.length = 0;
140
- widget = undefined;
141
- container = document.createElement("div");
142
- document.body.appendChild(container);
143
- });
144
-
145
- afterEach(() => {
146
- widget?.destroy();
147
- widget = undefined;
148
- container.remove();
149
- });
150
-
151
- describe("choosing a solver", () => {
152
- test("mounts the image widget when the provider asks for one", async () => {
153
- widget = mountProcaptchaFrictionless(
154
- container,
155
- props(() => Promise.resolve(detection(CaptchaType.image))),
156
- );
157
- await settle();
158
- expect(solvers()).toEqual(["image"]);
159
- });
160
-
161
- test("mounts the puzzle widget when the provider asks for one", async () => {
162
- widget = mountProcaptchaFrictionless(
163
- container,
164
- props(() => Promise.resolve(detection(CaptchaType.puzzle))),
165
- );
166
- await settle();
167
- expect(solvers()).toEqual(["puzzle"]);
168
- });
169
-
170
- test("falls through to PoW for anything else", async () => {
171
- widget = mountProcaptchaFrictionless(
172
- container,
173
- props(() => Promise.resolve(detection(CaptchaType.pow))),
174
- );
175
- await settle();
176
- expect(solvers()).toEqual(["pow"]);
177
- });
178
-
179
- test("passes a restart's wrong-answer notice on to the first solver", async () => {
180
- widget = mountProcaptchaFrictionless(
181
- container,
182
- props(() => Promise.resolve(detection(CaptchaType.image)), {
183
- startShowRetry: true,
184
- }),
185
- );
186
- await settle();
187
- expect(mocks.mounted[0]?.props.startShowRetry).toBe(true);
188
- });
189
-
190
- test("mounts an ordinary solver without the notice", async () => {
191
- widget = mountProcaptchaFrictionless(
192
- container,
193
- props(() => Promise.resolve(detection(CaptchaType.image))),
194
- );
195
- await settle();
196
- expect(mocks.mounted[0]?.props.startShowRetry).toBe(false);
197
- });
198
-
199
- test("hands the solver the session the frictionless call minted", async () => {
200
- widget = mountProcaptchaFrictionless(
201
- container,
202
- props(() => Promise.resolve(detection(CaptchaType.image))),
203
- );
204
- await settle();
205
- expect(mocks.mounted[0]?.props.frictionlessState).toMatchObject({
206
- sessionId: "session-1",
207
- });
208
- });
209
-
210
- test("only PoW is given an escalation handler", async () => {
211
- widget = mountProcaptchaFrictionless(
212
- container,
213
- props(() => Promise.resolve(detection(CaptchaType.pow))),
214
- );
215
- await settle();
216
- expect(mocks.mounted[0]?.props.onEscalate).toBeTypeOf("function");
217
- });
218
- });
219
-
220
- describe("the loading placeholder", () => {
221
- test("shows a checkbox before detection resolves", () => {
222
- widget = mountProcaptchaFrictionless(
223
- container,
224
- props(() => new Promise<BotDetectionFunctionResult>(() => undefined)),
225
- );
226
- // The spinner is the checkbox's loading state; either way there must be
227
- // something widget-shaped on the page while the round trip is in flight.
228
- expect(container.querySelector('[role="status"]')).not.toBe(null);
229
- });
230
-
231
- test("is replaced by the solver, not left behind it", async () => {
232
- widget = mountProcaptchaFrictionless(
233
- container,
234
- props(() => Promise.resolve(detection(CaptchaType.image))),
235
- );
236
- await settle();
237
- expect(container.querySelector('[role="status"]')).toBeNull();
238
- expect(solvers()).toEqual(["image"]);
239
- });
240
-
241
- test("shows a terminal detection error instead of a solver", async () => {
242
- const onError = vi.fn<(error: Error) => void>();
243
- widget = mountProcaptchaFrictionless(
244
- container,
245
- props(
246
- () =>
247
- Promise.resolve(
248
- detection(CaptchaType.image, {
249
- error: {
250
- message: "site key not registered",
251
- key: "API.SITE_KEY_NOT_REGISTERED",
252
- },
253
- } as Partial<BotDetectionFunctionResult>),
254
- ),
255
- { callbacks: { onError } },
256
- ),
257
- );
258
- await settle();
259
- expect(solvers()).toEqual([]);
260
- expect(container.textContent).toContain("site key not registered");
261
- expect(onError).toHaveBeenCalledWith(expect.any(Error));
262
- });
263
-
264
- test("shows a provider error in the widget's language, not the one the provider answered in", async () => {
265
- // The provider translates for the browser's Accept-Language, so a German
266
- // widget in an English browser used to show English errors.
267
- widget = mountProcaptchaFrictionless(
268
- container,
269
- props(
270
- () =>
271
- Promise.resolve(
272
- detection(CaptchaType.image, {
273
- error: {
274
- message: "Invalid site key",
275
- key: "API.INVALID_SITE_KEY",
276
- },
277
- } as Partial<BotDetectionFunctionResult>),
278
- ),
279
- {
280
- i18n: i18n({ "API.INVALID_SITE_KEY": "Ungültiger Site-Schlüssel" }),
281
- },
282
- ),
283
- );
284
- await settle();
285
- expect(container.textContent).toContain("Ungültiger Site-Schlüssel");
286
- expect(container.textContent).not.toContain("Invalid site key");
287
- });
288
-
289
- test("re-rolls onto another provider for a failure that is not the caller's fault", async () => {
290
- // An unrecognised key means the provider broke in a way it has no
291
- // vocabulary for; another node may well be healthy, so the user should
292
- // not be stranded on the first answer.
293
- const detectBot = vi
294
- .fn<BotDetectionFunction>()
295
- .mockResolvedValueOnce(
296
- detection(CaptchaType.image, {
297
- error: { message: "no capacity", key: "API.UNKNOWN_ERROR" },
298
- } as Partial<BotDetectionFunctionResult>),
299
- )
300
- .mockResolvedValue(detection(CaptchaType.image));
301
- widget = mountProcaptchaFrictionless(container, props(detectBot));
302
- // providerRetry backs off before re-rolling, so the second call lands a
303
- // randomised delay later rather than on the next tick.
304
- await waitFor(() => detectBot.mock.calls.length > 1);
305
- await settle();
306
- expect(solvers()).toEqual(["image"]);
307
- });
308
-
309
- test("shows the cannot-load message in the widget's language", async () => {
310
- widget = mountProcaptchaFrictionless(
311
- container,
312
- props(() =>
313
- Promise.resolve(
314
- detection(CaptchaType.authenticated, { sessionId: undefined }),
315
- ),
316
- ),
317
- );
318
- await settle();
319
- expect(container.textContent).toContain("WIDGET.CANNOT_LOAD");
320
- expect(container.textContent).not.toContain("Cannot load CAPTCHA");
321
- });
322
-
323
- test("refuses to mount anything when the response names no captcha type", async () => {
324
- // A hard block short-circuits the request and answers with a bare
325
- // `{ error: "..." }`; mounting the PoW default against it only earns an
326
- // API.INCORRECT_CAPTCHA_TYPE from the next call.
327
- const onError = vi.fn<(error: Error) => void>();
328
- widget = mountProcaptchaFrictionless(
329
- container,
330
- props(
331
- () =>
332
- Promise.resolve({
333
- sessionId: "session-1",
334
- } as unknown as BotDetectionFunctionResult),
335
- { callbacks: { onError } },
336
- ),
337
- );
338
- await settle();
339
- expect(solvers()).toEqual([]);
340
- expect(onError).toHaveBeenCalledWith(expect.any(Error));
341
- });
342
- });
343
-
344
- describe("escalating from PoW", () => {
345
- test("swaps PoW for the escalated solver rather than stacking them", async () => {
346
- // Nothing reconciles this for us: without the explicit teardown the page
347
- // ends up with two live widgets, two modals and two sets of document
348
- // listeners.
349
- widget = mountProcaptchaFrictionless(
350
- container,
351
- props(() => Promise.resolve(detection(CaptchaType.pow))),
352
- );
353
- await settle();
354
-
355
- mocks.mounted[0]?.props.onEscalate?.(CaptchaType.image, "session-2", {
356
- x: 4,
357
- y: 5,
358
- });
359
- await settle();
360
-
361
- expect(solvers()).toEqual(["image"]);
362
- expect(mocks.destroyed).toContain("pow");
363
- });
364
-
365
- test("carries the new session and the original click into the escalation", async () => {
366
- widget = mountProcaptchaFrictionless(
367
- container,
368
- props(() => Promise.resolve(detection(CaptchaType.pow))),
369
- );
370
- await settle();
371
-
372
- mocks.mounted[0]?.props.onEscalate?.(CaptchaType.image, "session-2", {
373
- x: 4,
374
- y: 5,
375
- });
376
- await settle();
377
-
378
- expect(mocks.mounted[1]?.props).toMatchObject({
379
- autoStart: true,
380
- startCoords: { x: 4, y: 5 },
381
- });
382
- expect(mocks.mounted[1]?.props.frictionlessState).toMatchObject({
383
- sessionId: "session-2",
384
- });
385
- });
386
- });
387
-
388
- describe("recovering an invalidated session", () => {
389
- test("re-runs detection and remounts with the preserved coordinates", async () => {
390
- const detectBot = vi
391
- .fn<BotDetectionFunction>()
392
- .mockResolvedValueOnce(detection(CaptchaType.image))
393
- .mockResolvedValue(
394
- detection(CaptchaType.image, {
395
- sessionId: "session-2",
396
- } as Partial<BotDetectionFunctionResult>),
397
- );
398
- widget = mountProcaptchaFrictionless(container, props(detectBot));
399
- await settle();
400
-
401
- mocks.mounted[0]?.props.onSessionInvalidated?.(11, 22);
402
- await settle();
403
-
404
- expect(detectBot).toHaveBeenCalledTimes(2);
405
- expect(solvers()).toEqual(["image"]);
406
- expect(mocks.mounted[1]?.props).toMatchObject({
407
- autoStart: true,
408
- startCoords: { x: 11, y: 22 },
409
- });
410
- });
411
-
412
- test("stops re-minting once the budget is spent, so a persistently broken session cannot loop", async () => {
413
- const detectBot = vi
414
- .fn<BotDetectionFunction>()
415
- .mockResolvedValue(detection(CaptchaType.image));
416
- widget = mountProcaptchaFrictionless(container, props(detectBot));
417
- await settle();
418
-
419
- // One more failure than the budget allows; the last one falls over
420
- // visibly rather than asking for yet another session.
421
- for (
422
- let attempt = 0;
423
- attempt <= MAX_SESSION_INVALIDATED_RETRIES;
424
- attempt++
425
- ) {
426
- mocks.mounted.at(-1)?.props.onSessionInvalidated?.(11, 22);
427
- await settle();
428
- }
429
-
430
- expect(detectBot).toHaveBeenCalledTimes(
431
- MAX_SESSION_INVALIDATED_RETRIES + 1,
432
- );
433
- });
434
- });
435
-
436
- describe("tearing down", () => {
437
- test("takes the mounted solver with it", async () => {
438
- widget = mountProcaptchaFrictionless(
439
- container,
440
- props(() => Promise.resolve(detection(CaptchaType.image))),
441
- );
442
- await settle();
443
- widget.destroy();
444
- widget = undefined;
445
- expect(mocks.destroyed).toContain("image");
446
- expect(container.querySelector("[data-solver]")).toBeNull();
447
- });
448
-
449
- test("does not mount a solver that resolves after destroy", async () => {
450
- let release: (result: BotDetectionFunctionResult) => void = () => undefined;
451
- widget = mountProcaptchaFrictionless(
452
- container,
453
- props(
454
- () =>
455
- new Promise<BotDetectionFunctionResult>(
456
- (resolve: (result: BotDetectionFunctionResult) => void) => {
457
- release = resolve;
458
- },
459
- ),
460
- ),
461
- );
462
- widget.destroy();
463
- widget = undefined;
464
- release(detection(CaptchaType.image));
465
- await settle();
466
- expect(mocks.mounted).toHaveLength(0);
467
- });
468
- });
@@ -1,181 +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 { describe, expect, it } from "vitest";
16
- import {
17
- MAX_SESSION_INVALIDATED_RETRIES,
18
- type MutableRef,
19
- type RetryCoords,
20
- consumeRetryMountProps,
21
- handleSessionInvalidated,
22
- normaliseRetryCoords,
23
- } from "../sessionInvalidatedRecovery.js";
24
-
25
- const ref = <T>(initial: T): MutableRef<T> => ({ current: initial });
26
-
27
- describe("handleSessionInvalidated", () => {
28
- it("records both coords and signals a restart on the first fire", () => {
29
- const attemptsRef = ref(0);
30
- const coordsRef = ref<RetryCoords | null>(null);
31
-
32
- const result = handleSessionInvalidated(120, 340, attemptsRef, coordsRef);
33
-
34
- expect(result).toEqual({ shouldRestart: true, exhausted: false });
35
- expect(attemptsRef.current).toBe(1);
36
- expect(coordsRef.current).toEqual({ x: 120, y: 340 });
37
- });
38
-
39
- it("treats (0, 0) as 'no coords' — that's the autoStart / untrusted-event default, not a real click", () => {
40
- const attemptsRef = ref(0);
41
- const coordsRef = ref<RetryCoords | null>(null);
42
-
43
- const result = handleSessionInvalidated(0, 0, attemptsRef, coordsRef);
44
-
45
- expect(result).toEqual({ shouldRestart: true, exhausted: false });
46
- expect(coordsRef.current).toBeNull();
47
- });
48
-
49
- it("carries a real click even if only one axis is at the origin", () => {
50
- const attemptsRef = ref(0);
51
- const coordsRef = ref<RetryCoords | null>(null);
52
-
53
- handleSessionInvalidated(0, 340, attemptsRef, coordsRef);
54
-
55
- expect(coordsRef.current).toEqual({ x: 0, y: 340 });
56
- });
57
-
58
- it("stores no coords when x or y is undefined (autoStart / non-trusted event)", () => {
59
- const attemptsRef = ref(0);
60
- const coordsRef = ref<RetryCoords | null>(null);
61
-
62
- const result = handleSessionInvalidated(
63
- undefined,
64
- undefined,
65
- attemptsRef,
66
- coordsRef,
67
- );
68
-
69
- expect(result).toEqual({ shouldRestart: true, exhausted: false });
70
- expect(attemptsRef.current).toBe(1);
71
- expect(coordsRef.current).toBeNull();
72
- });
73
-
74
- it("stores no coords when only one axis is present — never emit NaN into the salt", () => {
75
- const attemptsRef = ref(0);
76
- const coordsRef = ref<RetryCoords | null>(null);
77
-
78
- handleSessionInvalidated(120, undefined, attemptsRef, coordsRef);
79
-
80
- expect(coordsRef.current).toBeNull();
81
- });
82
-
83
- it("keeps re-minting up to the retry budget — a reload press is a legitimate new session", () => {
84
- const attemptsRef = ref(0);
85
- const coordsRef = ref<RetryCoords | null>(null);
86
-
87
- for (let i = 0; i < MAX_SESSION_INVALIDATED_RETRIES; i++) {
88
- expect(
89
- handleSessionInvalidated(100 + i, 200 + i, attemptsRef, coordsRef),
90
- ).toEqual({ shouldRestart: true, exhausted: false });
91
- }
92
-
93
- expect(attemptsRef.current).toBe(MAX_SESSION_INVALIDATED_RETRIES);
94
- });
95
-
96
- it("reports exhausted once the budget is spent so the caller can fall over visibly", () => {
97
- const attemptsRef = ref(MAX_SESSION_INVALIDATED_RETRIES);
98
- const coordsRef = ref<RetryCoords | null>({ x: 100, y: 200 });
99
-
100
- const result = handleSessionInvalidated(500, 600, attemptsRef, coordsRef);
101
-
102
- expect(result).toEqual({ shouldRestart: false, exhausted: true });
103
- // An exhausted call must not overwrite the pending attempt's coords.
104
- expect(coordsRef.current).toEqual({ x: 100, y: 200 });
105
- expect(attemptsRef.current).toBe(MAX_SESSION_INVALIDATED_RETRIES);
106
- });
107
-
108
- it("honours a caller-supplied budget", () => {
109
- const attemptsRef = ref(0);
110
- const coordsRef = ref<RetryCoords | null>(null);
111
-
112
- expect(handleSessionInvalidated(1, 2, attemptsRef, coordsRef, 1)).toEqual({
113
- shouldRestart: true,
114
- exhausted: false,
115
- });
116
- expect(handleSessionInvalidated(3, 4, attemptsRef, coordsRef, 1)).toEqual({
117
- shouldRestart: false,
118
- exhausted: true,
119
- });
120
- });
121
- });
122
-
123
- describe("consumeRetryMountProps", () => {
124
- it("returns pending retry coords and forces autoStart", () => {
125
- const coordsRef = ref<RetryCoords | null>({ x: 42, y: 99 });
126
-
127
- const mount = consumeRetryMountProps(coordsRef, false);
128
-
129
- expect(mount).toEqual({
130
- autoStart: true,
131
- startCoords: { x: 42, y: 99 },
132
- });
133
- });
134
-
135
- it("clears the coords ref so a subsequent render doesn't re-inject stale values", () => {
136
- const coordsRef = ref<RetryCoords | null>({ x: 42, y: 99 });
137
-
138
- consumeRetryMountProps(coordsRef, false);
139
-
140
- expect(coordsRef.current).toBeNull();
141
- });
142
-
143
- it("propagates escalationAutoStart when no retry is pending (post-PoW escalation path)", () => {
144
- const coordsRef = ref<RetryCoords | null>(null);
145
-
146
- const mount = consumeRetryMountProps(coordsRef, true);
147
-
148
- expect(mount).toEqual({ autoStart: true, startCoords: undefined });
149
- });
150
-
151
- it("returns autoStart=false, startCoords=undefined for the initial checkbox mount", () => {
152
- const coordsRef = ref<RetryCoords | null>(null);
153
-
154
- const mount = consumeRetryMountProps(coordsRef, false);
155
-
156
- expect(mount).toEqual({ autoStart: false, startCoords: undefined });
157
- });
158
- });
159
-
160
- describe("normaliseRetryCoords", () => {
161
- it("keeps a real click", () => {
162
- expect(normaliseRetryCoords(120, 340)).toEqual({ x: 120, y: 340 });
163
- });
164
-
165
- it("keeps a click that sits on one axis", () => {
166
- expect(normaliseRetryCoords(0, 340)).toEqual({ x: 0, y: 340 });
167
- });
168
-
169
- it("drops (0, 0) — the autoStart / untrusted-event default, not a click", () => {
170
- expect(normaliseRetryCoords(0, 0)).toBeNull();
171
- });
172
-
173
- it("drops a half-pair rather than letting NaN reach the salt", () => {
174
- expect(normaliseRetryCoords(120, undefined)).toBeNull();
175
- expect(normaliseRetryCoords(undefined, 340)).toBeNull();
176
- });
177
-
178
- it("drops a missing pair", () => {
179
- expect(normaliseRetryCoords(undefined, undefined)).toBeNull();
180
- });
181
- });