@prosopo/procaptcha-frictionless 2.18.6 → 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 (52) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +6 -9
  2. package/.turbo/turbo-build$colon$tsc.log +24 -27
  3. package/.turbo/turbo-build.log +6 -12
  4. package/CHANGELOG.md +73 -0
  5. package/LICENSE +201 -0
  6. package/dist/authenticatedBadge.d.ts +7 -0
  7. package/dist/authenticatedBadge.d.ts.map +1 -1
  8. package/dist/authenticatedBadge.js +14 -11
  9. package/dist/authenticatedBadge.js.map +1 -1
  10. package/dist/cjs/authenticatedBadge.cjs +14 -11
  11. package/dist/cjs/customDetectBot.cjs +3 -3
  12. package/dist/cjs/procaptchaFrictionless.cjs +16 -4
  13. package/dist/customDetectBot.d.ts.map +1 -1
  14. package/dist/customDetectBot.js +3 -3
  15. package/dist/customDetectBot.js.map +1 -1
  16. package/dist/procaptchaFrictionless.d.ts.map +1 -1
  17. package/dist/procaptchaFrictionless.js +17 -5
  18. package/dist/procaptchaFrictionless.js.map +1 -1
  19. package/dist/tests/authenticatedBadge.unit.test.d.ts +2 -0
  20. package/dist/tests/authenticatedBadge.unit.test.d.ts.map +1 -0
  21. package/dist/tests/authenticatedBadge.unit.test.js +66 -0
  22. package/dist/tests/authenticatedBadge.unit.test.js.map +1 -0
  23. package/dist/tests/procaptchaFrictionless.test.js +33 -2
  24. package/dist/tests/procaptchaFrictionless.test.js.map +1 -1
  25. package/dist/tests/sessionInvalidatedRemint.test.js +26 -0
  26. package/dist/tests/sessionInvalidatedRemint.test.js.map +1 -1
  27. package/package.json +70 -69
  28. package/src/authenticatedBadge.ts +0 -151
  29. package/src/customDetectBot.ts +0 -392
  30. package/src/detectorLoader.ts +0 -133
  31. package/src/detectorPrefetch.ts +0 -115
  32. package/src/frictionlessResultGuard.ts +0 -110
  33. package/src/index.ts +0 -15
  34. package/src/procaptchaFrictionless.ts +0 -613
  35. package/src/sessionInvalidatedRecovery.ts +0 -110
  36. package/src/tests/customDetectBot.test.ts +0 -77
  37. package/src/tests/customDetectBotAssignTimeout.test.ts +0 -185
  38. package/src/tests/customDetectBotSimd.test.ts +0 -173
  39. package/src/tests/detectorLoader.test.ts +0 -108
  40. package/src/tests/detectorPrefetch.test.ts +0 -114
  41. package/src/tests/escalationClientSession.test.ts +0 -216
  42. package/src/tests/escalationHandoff.integration.test.ts +0 -356
  43. package/src/tests/executeBeforeMount.test.ts +0 -233
  44. package/src/tests/frictionlessResultGuard.test.ts +0 -179
  45. package/src/tests/manualStart.test.ts +0 -391
  46. package/src/tests/procaptchaFrictionless.test.ts +0 -408
  47. package/src/tests/sessionInvalidatedRecovery.test.ts +0 -181
  48. package/src/tests/sessionInvalidatedRemint.test.ts +0 -272
  49. package/tsconfig.cjs.json +0 -41
  50. package/tsconfig.json +0 -49
  51. package/tsconfig.tsbuildinfo +0 -1
  52. package/tsconfig.types.json +0 -9
@@ -1,233 +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 Account,
18
- type BotDetectionFunction,
19
- type BotDetectionFunctionResult,
20
- CaptchaType,
21
- ModeEnum,
22
- type ProcaptchaClientConfigOutput,
23
- type ProcaptchaProps,
24
- type RandomProvider,
25
- StartModeEnum,
26
- } from "@prosopo/types";
27
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
28
-
29
- const EXECUTE_EVENT = "procaptcha:execute";
30
-
31
- const mocks = vi.hoisted(() => {
32
- const executes: ("container" | "document")[] = [];
33
- // Listens the way the real inner widgets do: on the container in either
34
- // mode, and on document only when invisible.
35
- const listeningWidget = (host: HTMLElement, props: ProcaptchaProps) => {
36
- const { container } = props;
37
- const invisible = "invisible" === props.config.mode;
38
- const onContainer = () => executes.push("container");
39
- const onDocument = () => executes.push("document");
40
- container?.addEventListener(EXECUTE_EVENT, onContainer);
41
- if (invisible) document.addEventListener(EXECUTE_EVENT, onDocument);
42
- const element = host.ownerDocument.createElement("div");
43
- element.setAttribute("data-widget", "image");
44
- host.appendChild(element);
45
- return {
46
- destroy: () => {
47
- container?.removeEventListener(EXECUTE_EVENT, onContainer);
48
- if (invisible) document.removeEventListener(EXECUTE_EVENT, onDocument);
49
- element.remove();
50
- },
51
- };
52
- };
53
- return { executes, listeningWidget };
54
- });
55
-
56
- vi.mock("@prosopo/procaptcha-react", () => ({
57
- mountProcaptchaImageWidget: mocks.listeningWidget,
58
- }));
59
- vi.mock("@prosopo/procaptcha-pow", () => ({
60
- mountProcaptchaPowWidget: mocks.listeningWidget,
61
- }));
62
- vi.mock("@prosopo/procaptcha-puzzle", () => ({
63
- mountProcaptchaPuzzleWidget: mocks.listeningWidget,
64
- }));
65
-
66
- // jsdom serves the suite over http, so the widget's own HTTPS guard would
67
- // short-circuit every test before detection ran.
68
- vi.mock("@prosopo/procaptcha-common", async (importOriginal) => ({
69
- ...(await importOriginal<typeof import("@prosopo/procaptcha-common")>()),
70
- isSecureBrowserContext: () => true,
71
- }));
72
-
73
- const { mountProcaptchaFrictionless } = await import(
74
- "../procaptchaFrictionless.js"
75
- );
76
-
77
- const config = (
78
- overrides: Partial<ProcaptchaClientConfigOutput> = {},
79
- ): ProcaptchaClientConfigOutput =>
80
- ({
81
- account: { address: "5siteKey" },
82
- userAccountAddress: "",
83
- web2: true,
84
- theme: "light",
85
- mode: ModeEnum.invisible,
86
- startMode: StartModeEnum.auto,
87
- ...overrides,
88
- }) as unknown as ProcaptchaClientConfigOutput;
89
-
90
- const i18nStub = {
91
- isInitialized: true,
92
- language: "en",
93
- t: (key: string) => key,
94
- changeLanguage: vi.fn(),
95
- } as unknown as Ti18n;
96
-
97
- const detectionResult = (): BotDetectionFunctionResult =>
98
- ({
99
- status: "ok",
100
- captchaType: CaptchaType.image,
101
- sessionId: "provider-session",
102
- provider: { provider: { url: "https://provider.test" } } as RandomProvider,
103
- userAccount: { account: { address: "5FakeUserAccountAddress" } } as Account,
104
- }) as unknown as BotDetectionFunctionResult;
105
-
106
- const settle = async (): Promise<void> => {
107
- await new Promise<void>((resolve: () => void) => setTimeout(resolve, 0));
108
- await Promise.resolve();
109
- };
110
-
111
- interface HeldDetection {
112
- detectBot: ReturnType<typeof vi.fn<BotDetectionFunction>>;
113
- finish: () => Promise<void>;
114
- }
115
-
116
- const heldDetection = (): HeldDetection => {
117
- let resolve: ((result: BotDetectionFunctionResult) => void) | undefined;
118
- const detectBot = vi.fn<BotDetectionFunction>().mockImplementation(
119
- () =>
120
- new Promise<BotDetectionFunctionResult>((r) => {
121
- resolve = r;
122
- }),
123
- );
124
- const finish = async () => {
125
- resolve?.(detectionResult());
126
- await settle();
127
- };
128
- return { detectBot, finish };
129
- };
130
-
131
- let host: HTMLDivElement;
132
- let container: HTMLDivElement;
133
- let widget: { destroy: () => void } | undefined;
134
-
135
- const mountWrapper = async (
136
- detectBot: BotDetectionFunction,
137
- overrides: Partial<ProcaptchaClientConfigOutput> = {},
138
- ): Promise<void> => {
139
- widget = mountProcaptchaFrictionless(host, {
140
- config: config(overrides),
141
- callbacks: {},
142
- restart: vi.fn(),
143
- i18n: i18nStub,
144
- detectBot,
145
- container,
146
- });
147
- await settle();
148
- };
149
-
150
- const dispatch = async (target: EventTarget): Promise<void> => {
151
- target.dispatchEvent(new CustomEvent(EXECUTE_EVENT));
152
- await settle();
153
- };
154
-
155
- beforeEach(() => {
156
- mocks.executes.length = 0;
157
- widget = undefined;
158
- host = document.createElement("div");
159
- container = document.createElement("div");
160
- document.body.append(host, container);
161
- });
162
-
163
- afterEach(() => {
164
- widget?.destroy();
165
- widget = undefined;
166
- host.remove();
167
- container.remove();
168
- vi.clearAllMocks();
169
- });
170
-
171
- describe("execute() before the inner widget is listening", () => {
172
- it("replays a bare execute() once the invisible widget mounts", async () => {
173
- const { detectBot, finish } = heldDetection();
174
- await mountWrapper(detectBot);
175
-
176
- await dispatch(document);
177
- expect(mocks.executes).toEqual([]);
178
-
179
- await finish();
180
-
181
- expect(mocks.executes).toEqual(["container"]);
182
- });
183
-
184
- it("replays a targeted execute() in visible mode", async () => {
185
- const { detectBot, finish } = heldDetection();
186
- await mountWrapper(detectBot, { mode: ModeEnum.visible });
187
-
188
- await dispatch(container);
189
- await finish();
190
-
191
- expect(mocks.executes).toEqual(["container"]);
192
- });
193
-
194
- it("replays repeated early calls only once", async () => {
195
- const { detectBot, finish } = heldDetection();
196
- await mountWrapper(detectBot);
197
-
198
- await dispatch(document);
199
- await dispatch(document);
200
- await finish();
201
-
202
- expect(mocks.executes).toEqual(["container"]);
203
- });
204
-
205
- it("does not start the widget when execute() was never called", async () => {
206
- const { detectBot, finish } = heldDetection();
207
- await mountWrapper(detectBot);
208
-
209
- await finish();
210
-
211
- expect(mocks.executes).toEqual([]);
212
- });
213
-
214
- it("leaves an execute() after mount to the widget alone", async () => {
215
- const { detectBot, finish } = heldDetection();
216
- await mountWrapper(detectBot);
217
- await finish();
218
-
219
- await dispatch(document);
220
-
221
- expect(mocks.executes).toEqual(["document"]);
222
- });
223
-
224
- it("ignores a bare execute() in visible mode, as the widgets do", async () => {
225
- const { detectBot, finish } = heldDetection();
226
- await mountWrapper(detectBot, { mode: ModeEnum.visible });
227
-
228
- await dispatch(document);
229
- await finish();
230
-
231
- expect(mocks.executes).toEqual([]);
232
- });
233
- });
@@ -1,179 +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
- MISSING_CAPTCHA_TYPE_MESSAGE,
18
- evaluateFrictionlessResult,
19
- } from "../frictionlessResultGuard.js";
20
-
21
- // This guard exists so a `/frictionless` response with no `captchaType`
22
- // (the shape emitted by request-time short-circuits — access-policy
23
- // hard-block, decision-machine autoBan, domain / header middleware
24
- // rejections — whose `{ error: "..." }` bare-string bodies slip past
25
- // `error.message` inspection) cannot fall through into
26
- // `renderForCaptchaType(undefined, ...)` and mount ProcaptchaPow with an
27
- // undefined sessionId, which the provider then rejects as
28
- // API.INCORRECT_CAPTCHA_TYPE for a frictionless sitekey.
29
-
30
- describe("evaluateFrictionlessResult", () => {
31
- it("passes a well-formed response with a captchaType", () => {
32
- expect(
33
- evaluateFrictionlessResult({
34
- captchaType: "pow",
35
- }),
36
- ).toEqual({ kind: "pass" });
37
- });
38
-
39
- it("passes when a captchaType is present even if error is a bare undefined", () => {
40
- expect(
41
- evaluateFrictionlessResult({
42
- captchaType: "image",
43
- error: undefined,
44
- }),
45
- ).toEqual({ kind: "pass" });
46
- });
47
-
48
- it("returns a structured error when the server emits `{ error: { message } }`", () => {
49
- expect(
50
- evaluateFrictionlessResult({
51
- captchaType: "pow",
52
- error: { message: "Boom", key: "API.SOMETHING" },
53
- }),
54
- ).toEqual({
55
- kind: "error",
56
- message: "Boom",
57
- key: "API.SOMETHING",
58
- retryable: true,
59
- });
60
- });
61
-
62
- it("omits key from the outcome when the server error carries no key", () => {
63
- const outcome = evaluateFrictionlessResult({
64
- captchaType: "pow",
65
- error: { message: "Boom" },
66
- });
67
- expect(outcome.kind).toBe("error");
68
- if (outcome.kind !== "error") throw new Error("expected error outcome");
69
- expect(outcome.message).toBe("Boom");
70
- expect("key" in outcome).toBe(false);
71
- });
72
-
73
- it("halts when captchaType is missing (bare-string 401 body shape from access-policy / autoBan / middleware)", () => {
74
- // Access-policy hard-block / decision-machine autoBan / domain
75
- // middleware all return `{"error":"Unauthorized"}` — a bare
76
- // string, not `{message}`, so `error.message` is undefined and
77
- // would slip past the earlier error check. HttpClientBase does
78
- // not throw on 4xx JSON so the widget receives this as a
79
- // valid-looking result.
80
- expect(
81
- evaluateFrictionlessResult({
82
- // Simulating the JSON parse: `error` came in as a string on
83
- // the wire but is not the object shape the guard reads.
84
- error: undefined,
85
- }),
86
- ).toEqual({
87
- kind: "error",
88
- message: MISSING_CAPTCHA_TYPE_MESSAGE,
89
- retryable: false,
90
- });
91
- });
92
-
93
- it("halts when both captchaType and error are absent (opaque parse failure)", () => {
94
- expect(evaluateFrictionlessResult({})).toEqual({
95
- kind: "error",
96
- message: MISSING_CAPTCHA_TYPE_MESSAGE,
97
- retryable: false,
98
- });
99
- });
100
-
101
- it("prefers the structured error over the missing-captchaType message when both apply", () => {
102
- // If the server ever emits BOTH a structured error and no captchaType,
103
- // the structured error is the more informative signal.
104
- expect(
105
- evaluateFrictionlessResult({
106
- error: { message: "Server error", key: "API.SERVER_ERROR" },
107
- }),
108
- ).toEqual({
109
- kind: "error",
110
- message: "Server error",
111
- key: "API.SERVER_ERROR",
112
- retryable: true,
113
- });
114
- });
115
-
116
- describe("retryable classification", () => {
117
- const retryableOf = (key?: string): boolean => {
118
- const outcome = evaluateFrictionlessResult({
119
- error: { message: "msg", ...(key !== undefined && { key }) },
120
- });
121
- if (outcome.kind !== "error") throw new Error("expected error outcome");
122
- return outcome.retryable;
123
- };
124
-
125
- it.each([
126
- "API.SITE_KEY_NOT_REGISTERED",
127
- "API.INVALID_SITE_KEY",
128
- "API.UNAUTHORIZED_ORIGIN_URL",
129
- "API.INCORRECT_CAPTCHA_TYPE",
130
- ])("shows integration fault %s rather than re-rolling", (key: string) => {
131
- // Another provider returns the same answer, and the text is what
132
- // tells the site owner what to change.
133
- expect(retryableOf(key)).toBe(false);
134
- });
135
-
136
- it.each([
137
- "API.ACCESS_POLICY_BLOCK",
138
- "API.ABUSER_BLOCKED",
139
- "API.CRAWLER_BLOCKED",
140
- "API.DATACENTER_BLOCKED",
141
- "API.DISALLOWED_WEBVIEW",
142
- "API.MOBILE_BLOCKED",
143
- "API.PROXY_BLOCKED",
144
- "API.SATELLITE_BLOCKED",
145
- "API.TOR_BLOCKED",
146
- "API.VPN_BLOCKED",
147
- "API.FORBIDDEN",
148
- "API.UNAUTHORIZED",
149
- ])("does not re-roll policy denial %s", (key: string) => {
150
- // Every provider shares the decision; retrying would hammer the
151
- // fleet on behalf of traffic already refused.
152
- expect(retryableOf(key)).toBe(false);
153
- });
154
-
155
- it("leaves CAPTCHA.NO_SESSION_FOUND to its own restart timer", () => {
156
- expect(retryableOf("CAPTCHA.NO_SESSION_FOUND")).toBe(false);
157
- });
158
-
159
- it("re-rolls API.BAD_REQUEST, which is what an unhandled provider throw becomes", () => {
160
- // An unhandled throw in a handler serialises to this with a 400, and
161
- // the client does not throw on a 400 with a JSON body — so without
162
- // re-rolling, one unhealthy provider stranded the user on the first
163
- // response while the rest of the fleet was up.
164
- expect(retryableOf("API.BAD_REQUEST")).toBe(true);
165
- });
166
-
167
- it.each(["API.UNKNOWN", "API.INTERNAL_SERVER_ERROR", "DATABASE.UNKNOWN"])(
168
- "re-rolls unrecognised provider fault %s",
169
- (key: string) => {
170
- expect(retryableOf(key)).toBe(true);
171
- },
172
- );
173
-
174
- it("does not re-roll an error with no key at all", () => {
175
- // Hard blocks arrive as a bare `{ error: "..." }` string with no key.
176
- expect(retryableOf(undefined)).toBe(false);
177
- });
178
- });
179
- });