@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,108 +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
- // @vitest-environment jsdom
16
-
17
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
18
- import {
19
- DetectorLoaderFromScript,
20
- type DetectorType,
21
- type ModuleImporter,
22
- } from "../detectorLoader.js";
23
-
24
- const SCRIPT = "export default () => ({ token: 'x' });";
25
-
26
- const detector = (() => undefined) as unknown as DetectorType;
27
-
28
- describe("DetectorLoaderFromScript", () => {
29
- const created: string[] = [];
30
- const revoked: string[] = [];
31
-
32
- beforeEach(() => {
33
- created.length = 0;
34
- revoked.length = 0;
35
- let counter = 0;
36
- URL.createObjectURL = vi.fn((): string => {
37
- const url = `blob:https://example.test/${counter++}`;
38
- created.push(url);
39
- return url;
40
- });
41
- URL.revokeObjectURL = vi.fn((url: string): void => {
42
- revoked.push(url);
43
- });
44
- });
45
-
46
- afterEach(() => {
47
- vi.restoreAllMocks();
48
- });
49
-
50
- it("uses a blob URL when the import succeeds", async () => {
51
- const seen: string[] = [];
52
- const importer: ModuleImporter = async (url) => {
53
- seen.push(url);
54
- return { default: detector };
55
- };
56
-
57
- await expect(DetectorLoaderFromScript(SCRIPT, importer)).resolves.toBe(
58
- detector,
59
- );
60
-
61
- expect(seen).toHaveLength(1);
62
- expect(seen[0]).toMatch(/^blob:/);
63
- expect(revoked).toEqual(created);
64
- });
65
-
66
- it("falls back to a data URL when the blob import is blocked by CSP", async () => {
67
- const seen: string[] = [];
68
- const importer: ModuleImporter = async (url) => {
69
- seen.push(url);
70
- if (url.startsWith("blob:")) {
71
- // What Chrome throws when script-src omits blob:
72
- throw new TypeError("Failed to fetch dynamically imported module");
73
- }
74
- return { default: detector };
75
- };
76
-
77
- await expect(DetectorLoaderFromScript(SCRIPT, importer)).resolves.toBe(
78
- detector,
79
- );
80
-
81
- expect(seen).toHaveLength(2);
82
- expect(seen[0]).toMatch(/^blob:/);
83
- expect(seen[1]).toMatch(/^data:text\/javascript;charset=utf-8,/);
84
- expect(decodeURIComponent(seen[1]?.split(",")[1] ?? "")).toBe(SCRIPT);
85
- });
86
-
87
- it("revokes the blob URL even when its import fails", async () => {
88
- const importer: ModuleImporter = async (url) => {
89
- if (url.startsWith("blob:")) throw new Error("blocked");
90
- return { default: detector };
91
- };
92
-
93
- await DetectorLoaderFromScript(SCRIPT, importer);
94
-
95
- expect(revoked).toEqual(created);
96
- });
97
-
98
- it("rethrows the last error when both schemes are blocked", async () => {
99
- const importer: ModuleImporter = async (url) => {
100
- throw new Error(`blocked: ${url.slice(0, 5)}`);
101
- };
102
-
103
- await expect(DetectorLoaderFromScript(SCRIPT, importer)).rejects.toThrow(
104
- "blocked: data:",
105
- );
106
- expect(revoked).toEqual(created);
107
- });
108
- });
@@ -1,114 +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 { EnvironmentTypes } from "@prosopo/types";
16
- import { afterEach, describe, expect, it, vi } from "vitest";
17
-
18
- const assignDetectorBundle = vi.fn();
19
- const getProcaptchaRandomActiveProvider = vi.fn();
20
-
21
- vi.mock("@prosopo/api", () => ({
22
- ProviderApi: class {
23
- assignDetectorBundle = assignDetectorBundle;
24
- },
25
- }));
26
-
27
- vi.mock("@prosopo/procaptcha-common", () => ({
28
- getProcaptchaRandomActiveProvider: (
29
- ...args: [EnvironmentTypes, string | undefined]
30
- ) => getProcaptchaRandomActiveProvider(...args),
31
- }));
32
-
33
- const { prefetchDetector, takePrefetchedDetector, clearPrefetchedDetectors } =
34
- await import("../detectorPrefetch.js");
35
-
36
- const ENV = "staging" as EnvironmentTypes;
37
- const SITE_KEY = "5CcNvLUdiXFpzKDMjThGLSK9rhWHA1H4EF3zrgkpkjAdqmuP";
38
-
39
- const provider = { provider: { url: "https://pronode.example" } };
40
-
41
- afterEach(() => {
42
- clearPrefetchedDetectors();
43
- vi.clearAllMocks();
44
- });
45
-
46
- describe("detectorPrefetch", () => {
47
- it("returns undefined when nothing was prefetched", () => {
48
- expect(takePrefetchedDetector(ENV, undefined, SITE_KEY)).toBeUndefined();
49
- });
50
-
51
- it("resolves the provider and assigns a bundle", async () => {
52
- getProcaptchaRandomActiveProvider.mockResolvedValue(provider);
53
- assignDetectorBundle.mockResolvedValue({ useProviderBundle: true });
54
-
55
- prefetchDetector(ENV, undefined, SITE_KEY);
56
- const claimed = takePrefetchedDetector(ENV, undefined, SITE_KEY);
57
- expect(claimed).toBeDefined();
58
-
59
- const result = await (claimed as Promise<unknown>);
60
- expect(result).toStrictEqual({
61
- provider,
62
- assigned: { useProviderBundle: true },
63
- });
64
- expect(assignDetectorBundle).toHaveBeenCalledWith(SITE_KEY);
65
- });
66
-
67
- it("is single-use, so a retry does not reuse a stale provider pin", async () => {
68
- getProcaptchaRandomActiveProvider.mockResolvedValue(provider);
69
- assignDetectorBundle.mockResolvedValue({ useProviderBundle: true });
70
-
71
- prefetchDetector(ENV, undefined, SITE_KEY);
72
- const first = takePrefetchedDetector(ENV, undefined, SITE_KEY);
73
- await (first as Promise<unknown>);
74
-
75
- expect(takePrefetchedDetector(ENV, undefined, SITE_KEY)).toBeUndefined();
76
- });
77
-
78
- it("does not start a second request for the same key", () => {
79
- getProcaptchaRandomActiveProvider.mockResolvedValue(provider);
80
- assignDetectorBundle.mockResolvedValue({ useProviderBundle: true });
81
-
82
- prefetchDetector(ENV, undefined, SITE_KEY);
83
- prefetchDetector(ENV, undefined, SITE_KEY);
84
-
85
- expect(getProcaptchaRandomActiveProvider).toHaveBeenCalledTimes(1);
86
- });
87
-
88
- it("keys on site key and ip mode, so a different widget does not claim it", () => {
89
- getProcaptchaRandomActiveProvider.mockResolvedValue(provider);
90
- assignDetectorBundle.mockResolvedValue({ useProviderBundle: true });
91
-
92
- prefetchDetector(ENV, "ipv4", SITE_KEY);
93
-
94
- expect(takePrefetchedDetector(ENV, "ipv6", SITE_KEY)).toBeUndefined();
95
- expect(takePrefetchedDetector(ENV, undefined, SITE_KEY)).toBeUndefined();
96
- expect(takePrefetchedDetector(ENV, "ipv4", "other-key")).toBeUndefined();
97
- expect(takePrefetchedDetector(ENV, "ipv4", SITE_KEY)).toBeDefined();
98
- });
99
-
100
- it("surfaces failure to the claimant without an unhandled rejection", async () => {
101
- getProcaptchaRandomActiveProvider.mockRejectedValue(
102
- new Error("no providers"),
103
- );
104
-
105
- prefetchDetector(ENV, undefined, SITE_KEY);
106
- const claimed = takePrefetchedDetector(ENV, undefined, SITE_KEY);
107
- expect(claimed).toBeDefined();
108
-
109
- // customDetectBot awaits this inside a try/catch and falls back; the point
110
- // here is that it rejects rather than hanging, and that the no-op catch
111
- // attached at prefetch time did not swallow it for the real consumer.
112
- await expect(claimed as Promise<unknown>).rejects.toThrow("no providers");
113
- });
114
- });
@@ -1,216 +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 } from "@prosopo/locale";
16
- import {
17
- type BotDetectionFunction,
18
- CaptchaType,
19
- type FrictionlessState,
20
- ModeEnum,
21
- type ProcaptchaClientConfigOutput,
22
- type ProcaptchaProps,
23
- type RandomProvider,
24
- } from "@prosopo/types";
25
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
26
-
27
- // Every widget the frictionless wrapper can mount records the props it was
28
- // handed, so a test can assert on the config that reached the *second* mount
29
- // after an escalation without rendering a real captcha.
30
- const mocks = vi.hoisted(() => {
31
- const mounts: {
32
- widget: "pow" | "image" | "puzzle";
33
- props: ProcaptchaProps;
34
- }[] = [];
35
- const stub =
36
- (widget: "pow" | "image" | "puzzle") =>
37
- (host: HTMLElement, props: ProcaptchaProps) => {
38
- mounts.push({ widget, props });
39
- const element = host.ownerDocument.createElement("div");
40
- element.setAttribute("data-widget", widget);
41
- host.appendChild(element);
42
- return { destroy: () => element.remove() };
43
- };
44
- return { mounts, stub };
45
- });
46
-
47
- vi.mock("@prosopo/procaptcha-pow", () => ({
48
- mountProcaptchaPowWidget: mocks.stub("pow"),
49
- }));
50
- vi.mock("@prosopo/procaptcha-react", () => ({
51
- mountProcaptchaImageWidget: mocks.stub("image"),
52
- }));
53
- vi.mock("@prosopo/procaptcha-puzzle", () => ({
54
- mountProcaptchaPuzzleWidget: mocks.stub("puzzle"),
55
- }));
56
-
57
- // The wrapper refuses to run outside a secure context, and jsdom's
58
- // `isSecureContext` is not reliably true across environments. Everything else
59
- // from procaptcha-common (the checkbox, getDefaultEvents, providerRetry) is
60
- // the real implementation.
61
- vi.mock("@prosopo/procaptcha-common", async (importOriginal) => ({
62
- ...(await importOriginal<typeof import("@prosopo/procaptcha-common")>()),
63
- isSecureBrowserContext: () => true,
64
- }));
65
-
66
- // Imported after the mocks so the lazy loaders inside resolve to the stubs.
67
- const { mountProcaptchaFrictionless } = await import(
68
- "../procaptchaFrictionless.js"
69
- );
70
-
71
- const SITE_KEY = "5siteKey";
72
- const CLIENT_SESSION_ID = "jti-from-the-site";
73
- const FIRST_SESSION_ID = "provider-session-1";
74
- const ESCALATED_SESSION_ID = "provider-session-2";
75
-
76
- const config = (): ProcaptchaClientConfigOutput =>
77
- ({
78
- account: { address: SITE_KEY },
79
- userAccountAddress: "",
80
- web2: true,
81
- theme: "light",
82
- mode: ModeEnum.visible,
83
- // What the site set via data-sessionid / renderOptions.sessionId.
84
- clientSessionId: CLIENT_SESSION_ID,
85
- }) as unknown as ProcaptchaClientConfigOutput;
86
-
87
- const i18nStub = {
88
- isInitialized: true,
89
- language: "en",
90
- t: (key: string) => key,
91
- changeLanguage: vi.fn(),
92
- } as unknown as Ti18n;
93
-
94
- // Minimal shape of what customDetectBot resolves to; only the fields the
95
- // wrapper reads on the happy path need to be present.
96
- const detectBotReturning = (captchaType: CaptchaType) =>
97
- vi.fn<BotDetectionFunction>().mockResolvedValue({
98
- captchaType,
99
- sessionId: FIRST_SESSION_ID,
100
- provider: { provider: { url: "https://provider.test" } } as RandomProvider,
101
- userAccount: "userAccount",
102
- } as unknown as Awaited<ReturnType<BotDetectionFunction>>);
103
-
104
- let container: HTMLDivElement;
105
- let widget: { destroy: () => void } | undefined;
106
-
107
- const settle = async (): Promise<void> => {
108
- await new Promise<void>((resolve: () => void) => setTimeout(resolve, 0));
109
- await Promise.resolve();
110
- };
111
-
112
- const mountWrapper = async (
113
- captchaType: CaptchaType,
114
- configOverrides: Partial<ProcaptchaClientConfigOutput> = {},
115
- ): Promise<void> => {
116
- widget = mountProcaptchaFrictionless(container, {
117
- config: { ...config(), ...configOverrides },
118
- callbacks: {},
119
- restart: vi.fn(),
120
- i18n: i18nStub,
121
- detectBot: detectBotReturning(captchaType),
122
- });
123
- await settle();
124
- };
125
-
126
- const lastMountOf = (target: "pow" | "image" | "puzzle") => {
127
- const mount = mocks.mounts.filter((m) => m.widget === target).at(-1);
128
- if (!mount) throw new Error(`expected the ${target} widget to have mounted`);
129
- return mount;
130
- };
131
-
132
- const escalate = async (to: CaptchaType): Promise<void> => {
133
- const { onEscalate } = lastMountOf("pow").props;
134
- onEscalate?.(
135
- to as CaptchaType.image | CaptchaType.puzzle,
136
- ESCALATED_SESSION_ID,
137
- );
138
- await settle();
139
- };
140
-
141
- beforeEach(() => {
142
- mocks.mounts.length = 0;
143
- widget = undefined;
144
- container = document.createElement("div");
145
- document.body.appendChild(container);
146
- });
147
-
148
- afterEach(() => {
149
- widget?.destroy();
150
- widget = undefined;
151
- container.remove();
152
- vi.clearAllMocks();
153
- });
154
-
155
- // The PoW -> image/puzzle escalation is the one flow where a user solves a
156
- // second captcha under a *different* provider session. The client session id
157
- // has to survive that handoff, or the dapp server's verify call would be
158
- // correlated against an escalated record that never carried it and every
159
- // escalated user would be rejected.
160
- describe("client session id across a PoW escalation", () => {
161
- it("reaches the PoW widget on the first mount", async () => {
162
- await mountWrapper(CaptchaType.pow);
163
-
164
- expect(lastMountOf("pow").props.config.clientSessionId).toBe(
165
- CLIENT_SESSION_ID,
166
- );
167
- });
168
-
169
- it("survives the handoff to the escalated image widget", async () => {
170
- await mountWrapper(CaptchaType.pow);
171
-
172
- // The provider accepted the PoW but wants a visual challenge; the PoW
173
- // widget calls back with the replacement session the provider minted.
174
- await escalate(CaptchaType.image);
175
-
176
- expect(lastMountOf("image").props.config.clientSessionId).toBe(
177
- CLIENT_SESSION_ID,
178
- );
179
- });
180
-
181
- it("survives the handoff to the escalated puzzle widget", async () => {
182
- await mountWrapper(CaptchaType.pow);
183
-
184
- await escalate(CaptchaType.puzzle);
185
-
186
- expect(lastMountOf("puzzle").props.config.clientSessionId).toBe(
187
- CLIENT_SESSION_ID,
188
- );
189
- });
190
-
191
- it("swaps the provider session id but not the client one", async () => {
192
- await mountWrapper(CaptchaType.pow);
193
-
194
- const powState = lastMountOf("pow").props
195
- .frictionlessState as FrictionlessState;
196
- expect(powState.sessionId).toBe(FIRST_SESSION_ID);
197
-
198
- await escalate(CaptchaType.image);
199
-
200
- const imageMount = lastMountOf("image").props;
201
- const imageState = imageMount.frictionlessState as FrictionlessState;
202
- // These are different identifiers and must not be conflated: the
203
- // provider session rotates on escalation, the site's own session does
204
- // not. The verify-time correlation keys off the latter.
205
- expect(imageState.sessionId).toBe(ESCALATED_SESSION_ID);
206
- expect(imageMount.config.clientSessionId).toBe(CLIENT_SESSION_ID);
207
- });
208
-
209
- it("carries no client session id when the site rendered without one", async () => {
210
- await mountWrapper(CaptchaType.pow, { clientSessionId: undefined });
211
-
212
- await escalate(CaptchaType.image);
213
-
214
- expect(lastMountOf("image").props.config.clientSessionId).toBeUndefined();
215
- });
216
- });