@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,110 +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
- // Shared, unit-testable pieces of the ProcaptchaFrictionless recovery path
16
- // for CAPTCHA.NO_SESSION_FOUND on the inner widget. The React component
17
- // mutates refs directly; these helpers isolate the logic that decides how a
18
- // re-mount should be parameterised so it can be exercised without a renderer.
19
-
20
- export type RetryCoords = { x: number; y: number };
21
-
22
- /**
23
- * Ref-like container used by ProcaptchaFrictionless. Extracted so tests
24
- * can pass a plain `{current}` object.
25
- */
26
- export type MutableRef<T> = { current: T };
27
-
28
- /**
29
- * The checkbox click position a re-mounted widget should start from, or
30
- * `null` when there isn't a real one to carry over.
31
- *
32
- * - Coords are kept only for a real trusted checkbox click. A partial
33
- * pair (only x or only y numeric) is treated as "no coords" so we
34
- * never accidentally embed `NaN` into the solution salt.
35
- * - `(0, 0)` is treated as "no coords" too — that's what the widgets
36
- * emit for an `autoStart` mount (post-PoW escalation) or an untrusted
37
- * pointer event on the checkbox, neither of which is a real click. The
38
- * resumed widget re-uses the same default and the outcome on the wire
39
- * is identical; we discard the pair here so future readers can tell
40
- * the two apart.
41
- */
42
- export const normaliseRetryCoords = (
43
- x: number | undefined,
44
- y: number | undefined,
45
- ): RetryCoords | null => {
46
- if (typeof x !== "number" || typeof y !== "number") return null;
47
- if (x === 0 && y === 0) return null;
48
- return { x, y };
49
- };
50
-
51
- /**
52
- * How many times a single outer widget will re-mint a session in response to
53
- * `CAPTCHA.NO_SESSION_FOUND` on the inner widget before giving up and handing
54
- * over to the terminal fallback.
55
- *
56
- * This used to be one-shot per outer widget lifetime, which stranded users:
57
- * the inner widget always takes the `onSessionInvalidated` branch (its own
58
- * guard ref is fresh on every re-mount, because the outer widget bumps its
59
- * mount key) and returns without touching its own `restart()` fallback. Once
60
- * the outer one-shot was spent nothing at all handled the second failure, so
61
- * the checkbox sat on "No session found" forever. A widget legitimately mints
62
- * many sessions over its lifetime — every reload press is a new one — so a
63
- * single lifetime-wide attempt is far too coarse a bound.
64
- */
65
- export const MAX_SESSION_INVALIDATED_RETRIES = 3;
66
-
67
- /**
68
- * Semantics of the outer recovery handler. Returns whether the caller should
69
- * proceed to re-run the frictionless flow (`start()`), and mutates the passed
70
- * refs to record the attempt + pending coords.
71
- *
72
- * Bounded rather than one-shot: a persistently broken session still stops
73
- * looping, but the caller is told (`exhausted`) so it can fall back visibly
74
- * instead of silently doing nothing.
75
- */
76
- export const handleSessionInvalidated = (
77
- x: number | undefined,
78
- y: number | undefined,
79
- attemptsRef: MutableRef<number>,
80
- pendingCoordsRef: MutableRef<RetryCoords | null>,
81
- maxAttempts: number = MAX_SESSION_INVALIDATED_RETRIES,
82
- ): { shouldRestart: boolean; exhausted: boolean } => {
83
- if (attemptsRef.current >= maxAttempts) {
84
- return { shouldRestart: false, exhausted: true };
85
- }
86
- attemptsRef.current += 1;
87
- pendingCoordsRef.current = normaliseRetryCoords(x, y);
88
- return { shouldRestart: true, exhausted: false };
89
- };
90
-
91
- /**
92
- * Compute the props a resumed inner widget mounts with. Consumes the
93
- * pending coords ref (sets it back to `null`) so the next render doesn't
94
- * accidentally re-inject stale coords into a fresh escalation.
95
- *
96
- * `escalationAutoStart` reflects the caller's own `autoStart` argument to
97
- * `renderForCaptchaType` — post-PoW escalations keep the historic
98
- * autoStart=true behaviour when no retry coords are pending.
99
- */
100
- export const consumeRetryMountProps = (
101
- pendingCoordsRef: MutableRef<RetryCoords | null>,
102
- escalationAutoStart: boolean,
103
- ): { autoStart: boolean; startCoords: RetryCoords | undefined } => {
104
- const startCoords = pendingCoordsRef.current ?? undefined;
105
- pendingCoordsRef.current = null;
106
- return {
107
- autoStart: escalationAutoStart || Boolean(startCoords),
108
- startCoords,
109
- };
110
- };
@@ -1,101 +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 { Account, RandomProvider } from "@prosopo/types";
16
- import { darkTheme, lightTheme } from "@prosopo/widget-skeleton";
17
- import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
18
- import {
19
- type AuthenticatedBadgeProps,
20
- mountAuthenticatedBadge,
21
- } from "../authenticatedBadge.js";
22
-
23
- const account: Account = { account: { address: "user-address" } };
24
- const provider: RandomProvider = {
25
- providerAccount: "provider-account",
26
- provider: { url: "https://provider.one" },
27
- };
28
-
29
- let container: HTMLDivElement;
30
- let destroy: (() => void) | undefined;
31
-
32
- const mount = (
33
- overrides: Partial<AuthenticatedBadgeProps> = {},
34
- ): HTMLElement => {
35
- const badge = mountAuthenticatedBadge(container, {
36
- sessionId: "session-1",
37
- dapp: "site-key",
38
- userAccount: account,
39
- provider,
40
- callbacks: { onHuman: vi.fn<(token: string) => void>() },
41
- ...overrides,
42
- });
43
- destroy = badge.destroy;
44
- const element = container.querySelector<HTMLElement>('[role="status"]');
45
- if (!element) throw new Error("expected the badge to render");
46
- return element;
47
- };
48
-
49
- /** jsdom reports inline colours as rgb(), the theme holds hex. */
50
- const asRgb = (hex: string): string => {
51
- const probe = document.createElement("span");
52
- probe.style.color = hex;
53
- return probe.style.color;
54
- };
55
-
56
- beforeEach(() => {
57
- container = document.createElement("div");
58
- document.body.appendChild(container);
59
- });
60
-
61
- afterEach(() => {
62
- destroy?.();
63
- destroy = undefined;
64
- container.remove();
65
- });
66
-
67
- describe("authenticated badge", () => {
68
- test("follows the dark theme", () => {
69
- const badge = mount({ theme: darkTheme });
70
- expect(badge.style.background).toBe(
71
- asRgb(darkTheme.palette.primaryContainer.main),
72
- );
73
- expect(badge.style.color).toBe(
74
- asRgb(darkTheme.palette.primaryContainer.contrastText),
75
- );
76
- });
77
-
78
- test("defaults to the light theme", () => {
79
- const badge = mount();
80
- expect(badge.style.background).toBe(
81
- asRgb(lightTheme.palette.primaryContainer.main),
82
- );
83
- });
84
-
85
- test("shows the translated text it is given", () => {
86
- const badge = mount({
87
- agent: "https://agent.example/",
88
- labels: {
89
- verifiedAgent: "Verifizierter Agent",
90
- trustedRequest: "Vertrauenswürdige Anfrage",
91
- },
92
- });
93
- expect(badge.textContent).toContain("Verifizierter Agent: agent.example");
94
- });
95
-
96
- test("is read out by its visible text, not a fixed label", () => {
97
- const badge = mount();
98
- expect(badge.hasAttribute("aria-label")).toBe(false);
99
- expect(badge.textContent).toContain("Trusted request");
100
- });
101
- });
@@ -1,77 +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 { ProsopoEnvError } from "@prosopo/common";
16
- import { describe, expect, it, vi } from "vitest";
17
- import { withTimeout } from "../customDetectBot.js";
18
-
19
- describe("withTimeout", () => {
20
- it("should resolve with the promise result when promise resolves before timeout", async () => {
21
- const result = "success";
22
- const promise = Promise.resolve(result);
23
-
24
- const response = await withTimeout(promise, 1000);
25
-
26
- expect(response).toBe(result);
27
- });
28
-
29
- it("should reject with original error when promise rejects before timeout", async () => {
30
- const errorMessage = "Original error";
31
- const promise = Promise.reject(new Error(errorMessage));
32
-
33
- await expect(withTimeout(promise, 1000)).rejects.toThrow(errorMessage);
34
- });
35
-
36
- it("should reject with timeout error when promise does not resolve within the timeout", async () => {
37
- const promise = new Promise((resolve) => {
38
- setTimeout(resolve, 500);
39
- });
40
-
41
- vi.useFakeTimers();
42
-
43
- const timeoutPromise = withTimeout(promise, 100);
44
-
45
- vi.advanceTimersByTime(200);
46
-
47
- await expect(timeoutPromise).rejects.toThrow(ProsopoEnvError);
48
- await expect(timeoutPromise).rejects.toEqual(
49
- expect.objectContaining({
50
- message: "API.UNKNOWN",
51
- translationKey: "API.UNKNOWN",
52
- }),
53
- );
54
-
55
- vi.useRealTimers();
56
- });
57
-
58
- it("should respect the provided timeout duration", async () => {
59
- vi.useFakeTimers();
60
-
61
- const fastResolve = Promise.resolve("success");
62
- const fastResult = withTimeout(fastResolve, 1000);
63
-
64
- const slowPromise = new Promise((resolve) => {
65
- setTimeout(() => resolve("slow"), 2000);
66
- });
67
- const slowWithTimeout = withTimeout(slowPromise, 1000);
68
-
69
- vi.advanceTimersByTime(500);
70
- expect(await fastResult).toBe("success");
71
-
72
- vi.advanceTimersByTime(600);
73
- await expect(slowWithTimeout).rejects.toThrow(ProsopoEnvError);
74
-
75
- vi.useRealTimers();
76
- });
77
- });
@@ -1,185 +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
- /**
16
- * A slow detector assignment must still be used. Under the old 2000 ms cap on
17
- * both the assign POST and the blob import, a cold-connection assign (measured
18
- * at 6.7s against staging: fresh DNS + TLS + CORS preflight before ~215 KB of
19
- * bundle) blew the deadline, the surrounding catch swallowed it, and the
20
- * frictionless POST went out with an empty token and no detectorSessionId.
21
- */
22
-
23
- import type { AssignDetectorBundleResponse } from "@prosopo/types";
24
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
25
-
26
- // `vi.mock` is hoisted; share state via `vi.hoisted` so the factories can
27
- // reference the same spies the tests assert against.
28
- const mocks = vi.hoisted(() => ({
29
- getFrictionlessCaptcha: vi.fn(),
30
- getProcaptchaRandomActiveProvider: vi.fn(),
31
- assignDetectorBundle: vi.fn(),
32
- detectorLoaderFromScript: vi.fn(),
33
- detect: vi.fn(),
34
- }));
35
-
36
- vi.mock("@prosopo/api", () => ({
37
- // customDetectBot does `new ProviderApi(...)`, so the implementation has to
38
- // be constructible — an arrow function has no [[Construct]] slot.
39
- ProviderApi: vi.fn(function () {
40
- return {
41
- getFrictionlessCaptcha: mocks.getFrictionlessCaptcha,
42
- assignDetectorBundle: mocks.assignDetectorBundle,
43
- };
44
- }),
45
- }));
46
-
47
- vi.mock("@prosopo/procaptcha-common", () => ({
48
- ExtensionLoader: vi.fn(async () => {
49
- return class FakeExtension {
50
- getAccount() {
51
- return Promise.resolve({
52
- account: { address: "5FakeUserAccountAddress" },
53
- });
54
- }
55
- };
56
- }),
57
- getProcaptchaRandomActiveProvider: mocks.getProcaptchaRandomActiveProvider,
58
- pickIpMode: vi.fn(() => undefined),
59
- // Nothing here runs Protect, so the real function would return the site's
60
- // own value unchanged.
61
- resolveClientSessionId: vi.fn(
62
- (clientSessionId?: string): string | undefined => clientSessionId,
63
- ),
64
- }));
65
-
66
- vi.mock("../detectorLoader.js", () => ({
67
- DetectorLoaderFromScript: mocks.detectorLoaderFromScript,
68
- }));
69
-
70
- import customDetectBot from "../customDetectBot.js";
71
-
72
- const baseConfig = {
73
- account: { address: "5CcNvLUdiXFpzKDMjThGLSK9rhWHA1H4EF3zrgkpkjAdqmuP" },
74
- defaultEnvironment: "staging" as const,
75
- web2: true,
76
- mode: "visible" as const,
77
- } as unknown as Parameters<typeof customDetectBot>[0];
78
-
79
- const assignResponse: AssignDetectorBundleResponse = {
80
- useProviderBundle: true,
81
- detectorSessionId: "det-5cad2419-43c0-41b7-a9b8-0117767624bc",
82
- detectorScript: "SELF_CONTAINED_ESM",
83
- status: "ok",
84
- };
85
-
86
- const detectionResult = {
87
- token: "ENCRYPTED_TOKEN",
88
- encryptHeadHash: "ENCRYPTED_HEAD_HASH",
89
- userAccount: { account: { address: "5FakeUserAccountAddress" } },
90
- shadowDomCleanup: () => undefined,
91
- };
92
-
93
- const captchaResponse = {
94
- captchaType: "pow",
95
- sessionId: "SID",
96
- status: "ok",
97
- };
98
-
99
- // The measured cold-connection assign against staging.
100
- const SLOW_MS = 6700;
101
-
102
- const resolveAfter = <T>(ms: number, value: T): Promise<T> =>
103
- new Promise<T>((resolve) => {
104
- setTimeout(() => resolve(value), ms);
105
- });
106
-
107
- // The token the frictionless POST was actually called with (first positional
108
- // arg of `getFrictionlessCaptcha`).
109
- const postedToken = (): string | undefined => {
110
- const call = mocks.getFrictionlessCaptcha.mock.calls[0];
111
- return call?.[0] as string | undefined;
112
- };
113
-
114
- const postedDetectorSessionId = (): string | undefined => {
115
- const call = mocks.getFrictionlessCaptcha.mock.calls[0];
116
- return call?.[6] as string | undefined;
117
- };
118
-
119
- beforeEach(() => {
120
- vi.useFakeTimers();
121
- mocks.getFrictionlessCaptcha.mockReset();
122
- mocks.getProcaptchaRandomActiveProvider.mockReset();
123
- mocks.assignDetectorBundle.mockReset();
124
- mocks.detectorLoaderFromScript.mockReset();
125
- mocks.detect.mockReset();
126
-
127
- mocks.getProcaptchaRandomActiveProvider.mockResolvedValue({
128
- providerAccount: "dns-routed",
129
- provider: { url: "https://staging-pronode3.prosopo.io" },
130
- });
131
- mocks.detect.mockResolvedValue(detectionResult);
132
- mocks.detectorLoaderFromScript.mockResolvedValue(mocks.detect);
133
- mocks.assignDetectorBundle.mockResolvedValue(assignResponse);
134
- mocks.getFrictionlessCaptcha.mockResolvedValue(captchaResponse);
135
- });
136
-
137
- afterEach(() => {
138
- vi.useRealTimers();
139
- });
140
-
141
- const runDetection = async (): Promise<void> => {
142
- const pending = customDetectBot(baseConfig, undefined, () => undefined);
143
- await vi.advanceTimersByTimeAsync(SLOW_MS + 1000);
144
- await pending;
145
- };
146
-
147
- describe("customDetectBot detector-assignment deadline", () => {
148
- it("uses a bundle whose assign POST is slow", async () => {
149
- mocks.assignDetectorBundle.mockImplementation(() =>
150
- resolveAfter(SLOW_MS, assignResponse),
151
- );
152
-
153
- await runDetection();
154
-
155
- expect(mocks.detectorLoaderFromScript).toHaveBeenCalledWith(
156
- assignResponse.detectorScript,
157
- );
158
- expect(postedToken()).toBe("ENCRYPTED_TOKEN");
159
- expect(postedDetectorSessionId()).toBe(assignResponse.detectorSessionId);
160
- });
161
-
162
- it("uses a bundle whose blob import is slow", async () => {
163
- mocks.detectorLoaderFromScript.mockImplementation(() =>
164
- resolveAfter(SLOW_MS, mocks.detect),
165
- );
166
-
167
- await runDetection();
168
-
169
- expect(postedToken()).toBe("ENCRYPTED_TOKEN");
170
- expect(postedDetectorSessionId()).toBe(assignResponse.detectorSessionId);
171
- });
172
-
173
- it("still sends an empty token when the provider has no bundle to assign", async () => {
174
- mocks.assignDetectorBundle.mockResolvedValue({
175
- useProviderBundle: false,
176
- status: "ok",
177
- } satisfies AssignDetectorBundleResponse);
178
-
179
- await runDetection();
180
-
181
- expect(mocks.detectorLoaderFromScript).not.toHaveBeenCalled();
182
- expect(postedToken()).toBeUndefined();
183
- expect(postedDetectorSessionId()).toBeUndefined();
184
- });
185
- });
@@ -1,173 +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 { beforeEach, describe, expect, it, vi } from "vitest";
16
-
17
- // `vi.mock` is hoisted; share state via `vi.hoisted` so the factories can
18
- // reference the same spies the tests assert against.
19
- const mocks = vi.hoisted(() => ({
20
- getFrictionlessCaptcha: vi.fn(),
21
- getProcaptchaRandomActiveProvider: vi.fn(),
22
- assignDetectorBundle: vi.fn(),
23
- detect: vi.fn(),
24
- }));
25
-
26
- vi.mock("@prosopo/api", () => ({
27
- // customDetectBot does `new ProviderApi(...)`, so the implementation has to
28
- // be constructible. vitest 3 tolerated an arrow function here; under vitest 4
29
- // it throws "is not a constructor" — arrows have no [[Construct]] slot.
30
- ProviderApi: vi.fn(function () {
31
- return {
32
- getFrictionlessCaptcha: mocks.getFrictionlessCaptcha,
33
- assignDetectorBundle: mocks.assignDetectorBundle,
34
- };
35
- }),
36
- }));
37
-
38
- vi.mock("@prosopo/procaptcha-common", () => ({
39
- ExtensionLoader: vi.fn(async () => {
40
- return class FakeExtension {
41
- getAccount() {
42
- return Promise.resolve({
43
- account: { address: "5FakeUserAccountAddress" },
44
- });
45
- }
46
- };
47
- }),
48
- getProcaptchaRandomActiveProvider: mocks.getProcaptchaRandomActiveProvider,
49
- pickIpMode: vi.fn(() => undefined),
50
- // Nothing here runs Protect, so the real function would return the site's
51
- // own value unchanged.
52
- resolveClientSessionId: vi.fn(
53
- (clientSessionId?: string): string | undefined => clientSessionId,
54
- ),
55
- }));
56
-
57
- vi.mock("../detectorLoader.js", () => ({
58
- DetectorLoaderFromScript: vi.fn(async () => mocks.detect),
59
- }));
60
-
61
- import customDetectBot from "../customDetectBot.js";
62
-
63
- const baseConfig = {
64
- account: { address: "5FakeSiteKey" },
65
- defaultEnvironment: "production" as const,
66
- web2: true,
67
- mode: "frictionless" as const,
68
- } as unknown as Parameters<typeof customDetectBot>[0];
69
-
70
- const makeDetectionResult = (
71
- getSimdReadings?: (timeoutMs: number) => Promise<string | undefined>,
72
- ) => ({
73
- token: "TOKEN",
74
- encryptHeadHash: "HASH",
75
- userAccount: { account: { address: "5FakeUserAccountAddress" } },
76
- getSimdReadings,
77
- mouseTracker: undefined,
78
- touchTracker: undefined,
79
- clickTracker: undefined,
80
- });
81
-
82
- const captchaResponse = {
83
- captchaType: "pow",
84
- sessionId: "SID",
85
- status: "ok",
86
- };
87
-
88
- beforeEach(() => {
89
- mocks.getFrictionlessCaptcha.mockReset();
90
- mocks.getProcaptchaRandomActiveProvider.mockReset();
91
- mocks.assignDetectorBundle.mockReset();
92
- mocks.detect.mockReset();
93
- mocks.getProcaptchaRandomActiveProvider.mockResolvedValue({
94
- providerAccount: "dns-routed",
95
- provider: { url: "https://provider.test" },
96
- });
97
- // Provider serves a per-session detector bundle (the only detector source).
98
- mocks.assignDetectorBundle.mockResolvedValue({
99
- useProviderBundle: true,
100
- detectorSessionId: "det-1",
101
- detectorScript: "SELF_CONTAINED_ESM",
102
- status: "ok",
103
- });
104
- mocks.getFrictionlessCaptcha.mockResolvedValue(captchaResponse);
105
- });
106
-
107
- describe("customDetectBot SIMD deferral", () => {
108
- it("passes simdReadings as undefined to the frictionless POST even when getSimdReadings would return a value", async () => {
109
- const getSimdReadings = vi.fn().mockResolvedValue("ENCODED_SIMD");
110
- mocks.detect.mockResolvedValue(makeDetectionResult(getSimdReadings));
111
-
112
- await customDetectBot(baseConfig, undefined, () => undefined);
113
-
114
- expect(mocks.getFrictionlessCaptcha).toHaveBeenCalledTimes(1);
115
- const args = mocks.getFrictionlessCaptcha.mock.calls[0];
116
- // args: token, headHash, dappAccount, userAccount, mode, simdReadings, currentUrl, iframeUrl
117
- expect(args?.[5]).toBeUndefined();
118
- });
119
-
120
- it("fires getSimdReadings after the frictionless POST is initiated (fire-and-forget)", async () => {
121
- const callOrder: string[] = [];
122
- mocks.getFrictionlessCaptcha.mockImplementation(() => {
123
- callOrder.push("captcha-call");
124
- return Promise.resolve(captchaResponse);
125
- });
126
- const getSimdReadings = vi.fn().mockImplementation(() => {
127
- callOrder.push("simd-call");
128
- return Promise.resolve("ENCODED_SIMD");
129
- });
130
- mocks.detect.mockResolvedValue(makeDetectionResult(getSimdReadings));
131
-
132
- await customDetectBot(baseConfig, undefined, () => undefined);
133
-
134
- expect(getSimdReadings).toHaveBeenCalledTimes(1);
135
- // SIMD trigger must come AFTER the frictionless POST is initiated.
136
- expect(callOrder.indexOf("captcha-call")).toBeLessThan(
137
- callOrder.indexOf("simd-call"),
138
- );
139
- });
140
-
141
- it("does not block the frictionless POST on a slow getSimdReadings", async () => {
142
- let simdResolve!: (v: string) => void;
143
- const simdPromise = new Promise<string>((resolve) => {
144
- simdResolve = resolve;
145
- });
146
- const getSimdReadings = vi.fn().mockReturnValue(simdPromise);
147
- mocks.detect.mockResolvedValue(makeDetectionResult(getSimdReadings));
148
-
149
- // If the POST awaited getSimdReadings, this would hang forever.
150
- const result = await customDetectBot(
151
- baseConfig,
152
- undefined,
153
- () => undefined,
154
- );
155
-
156
- expect(result.sessionId).toBe("SID");
157
- // Resolve afterwards so the unhandled promise doesn't leak.
158
- simdResolve("ENCODED_SIMD");
159
- });
160
-
161
- it("skips the SIMD trigger when the detector doesn't expose getSimdReadings", async () => {
162
- mocks.detect.mockResolvedValue(makeDetectionResult(undefined));
163
-
164
- const result = await customDetectBot(
165
- baseConfig,
166
- undefined,
167
- () => undefined,
168
- );
169
-
170
- expect(result.sessionId).toBe("SID");
171
- expect(mocks.getFrictionlessCaptcha).toHaveBeenCalledTimes(1);
172
- });
173
- });