@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
package/package.json CHANGED
@@ -1,70 +1,71 @@
1
1
  {
2
- "name": "@prosopo/procaptcha-frictionless",
3
- "version": "2.18.6",
4
- "author": "PROSOPO LIMITED <info@prosopo.io>",
5
- "license": "Apache-2.0",
6
- "main": "dist/index.js",
7
- "type": "module",
8
- "sideEffects": false,
9
- "engines": {
10
- "node": "^24",
11
- "npm": "^11"
12
- },
13
- "exports": {
14
- ".": {
15
- "types": "./dist/index.d.ts",
16
- "import": "./dist/index.js",
17
- "require": "./dist/cjs/index.cjs"
18
- }
19
- },
20
- "types": "dist/index.d.ts",
21
- "source": "./src/index.ts",
22
- "scripts": {
23
- "clean": "del-cli --verbose dist tsconfig.tsbuildinfo",
24
- "test": "NODE_ENV=${NODE_ENV:-test}; npx vitest run --config ./vite.test.config.ts",
25
- "build": "npm run build:cross-env -- --mode ${NODE_ENV:-development}",
26
- "build:cross-env": "vite build --config vite.esm.config.ts",
27
- "build:tsc": "tsc --build --verbose",
28
- "build:cjs": "NODE_ENV=${NODE_ENV:-development}; vite build --config vite.cjs.config.ts --mode $NODE_ENV",
29
- "typecheck": "tsc --project tsconfig.types.json"
30
- },
31
- "browserslist": ["> 0.5%, last 2 versions, not dead"],
32
- "dependencies": {
33
- "@prosopo/api": "4.3.7",
34
- "@prosopo/common": "3.1.60",
35
- "@prosopo/locale": "3.6.1",
36
- "@prosopo/procaptcha-common": "2.18.1",
37
- "@prosopo/procaptcha-pow": "2.13.6",
38
- "@prosopo/procaptcha-puzzle": "2.14.6",
39
- "@prosopo/procaptcha-react": "2.13.5",
40
- "@prosopo/types": "5.11.1",
41
- "@prosopo/widget-skeleton": "2.10.0",
42
- "dotenv": "16.4.5"
43
- },
44
- "devDependencies": {
45
- "@prosopo/config": "3.4.2",
46
- "@types/node": "22.10.2",
47
- "@vitest/coverage-v8": "4.1.11",
48
- "concurrently": "9.0.1",
49
- "del-cli": "6.0.0",
50
- "npm-run-all": "4.1.5",
51
- "tslib": "2.7.0",
52
- "tsx": "4.20.3",
53
- "typescript": "5.6.2",
54
- "vite": "8.1.5",
55
- "vitest": "4.1.11"
56
- },
57
- "repository": {
58
- "type": "git",
59
- "url": "git+https://github.com/prosopo/captcha.git",
60
- "directory": "packages/procaptcha-frictionless"
61
- },
62
- "bugs": {
63
- "url": "https://github.com/prosopo/captcha/issues"
64
- },
65
- "homepage": "https://github.com/prosopo/captcha#readme",
66
- "description": "",
67
- "publishConfig": {
68
- "registry": "https://registry.npmjs.org"
69
- }
70
- }
2
+ "name": "@prosopo/procaptcha-frictionless",
3
+ "version": "2.19.0",
4
+ "author": "PROSOPO LIMITED <info@prosopo.io>",
5
+ "license": "Apache-2.0",
6
+ "main": "dist/index.js",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "engines": {
10
+ "node": "^24"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/cjs/index.cjs"
17
+ }
18
+ },
19
+ "types": "dist/index.d.ts",
20
+ "source": "./src/index.ts",
21
+ "browserslist": [
22
+ "> 0.5%, last 2 versions, not dead"
23
+ ],
24
+ "dependencies": {
25
+ "@prosopo/api": "4.4.0",
26
+ "@prosopo/common": "3.1.62",
27
+ "@prosopo/locale": "3.7.0",
28
+ "@prosopo/procaptcha-common": "2.19.0",
29
+ "@prosopo/procaptcha-pow": "2.13.8",
30
+ "@prosopo/procaptcha-puzzle": "2.15.0",
31
+ "@prosopo/procaptcha-react": "2.13.7",
32
+ "@prosopo/types": "5.13.0",
33
+ "@prosopo/widget-skeleton": "2.10.1",
34
+ "dotenv": "16.4.5"
35
+ },
36
+ "devDependencies": {
37
+ "@prosopo/config": "3.4.3",
38
+ "@types/node": "22.10.2",
39
+ "@vitest/coverage-v8": "4.1.11",
40
+ "concurrently": "9.0.1",
41
+ "del-cli": "6.0.0",
42
+ "npm-run-all": "4.1.5",
43
+ "tslib": "2.7.0",
44
+ "tsx": "4.20.3",
45
+ "typescript": "5.6.2",
46
+ "vite": "8.1.5",
47
+ "vitest": "4.1.11"
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/prosopo/captcha.git",
52
+ "directory": "packages/procaptcha-frictionless"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/prosopo/captcha/issues"
56
+ },
57
+ "homepage": "https://github.com/prosopo/captcha#readme",
58
+ "description": "",
59
+ "publishConfig": {
60
+ "registry": "https://registry.npmjs.org"
61
+ },
62
+ "scripts": {
63
+ "clean": "del-cli --verbose dist tsconfig.tsbuildinfo",
64
+ "test": "NODE_ENV=${NODE_ENV:-test}; pnpm exec vitest run --config ./vite.test.config.ts",
65
+ "build": "pnpm run build:cross-env --mode ${NODE_ENV:-development}",
66
+ "build:cross-env": "vite build --config vite.esm.config.ts",
67
+ "build:tsc": "tsc --build --verbose",
68
+ "build:cjs": "NODE_ENV=${NODE_ENV:-development}; vite build --config vite.cjs.config.ts --mode $NODE_ENV",
69
+ "typecheck": "tsc --project tsconfig.types.json"
70
+ }
71
+ }
@@ -1,151 +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
- // Widget for the `authenticated` captcha outcome — no user-facing challenge,
16
- // just a visible acknowledgement that Web Bot Auth verification succeeded.
17
- // Mounts once, immediately encodes a ProcaptchaToken with the sessionId as
18
- // its commitmentId (matching what /client/authenticated/verify decodes) and
19
- // fires `onHuman`. The badge itself is purely presentational; the token
20
- // submission happens on mount.
21
- //
22
- // The token carries empty signature bags (`{provider: {}, user: {}}`) — the
23
- // authenticated verify endpoint does not check the token's user or provider
24
- // signatures because there was no captcha challenge to sign. Only the dApp
25
- // server's signature on the timestamp is checked at verify time, and that
26
- // is applied by the dApp on the way to /verify (not by the widget here).
27
-
28
- import {
29
- type StaticComponent,
30
- createElement,
31
- createSvgElement,
32
- getDefaultEvents,
33
- } from "@prosopo/procaptcha-common";
34
- import {
35
- type Account,
36
- ApiParams,
37
- CaptchaType,
38
- type ProcaptchaCallbacks,
39
- type RandomProvider,
40
- encodeProcaptchaOutput,
41
- } from "@prosopo/types";
42
-
43
- export type AuthenticatedBadgeProps = {
44
- sessionId: string;
45
- agent?: string;
46
- dapp: string;
47
- userAccount: Account;
48
- provider: RandomProvider;
49
- callbacks: ProcaptchaCallbacks;
50
- };
51
-
52
- const displayHost = (agent?: string): string => {
53
- if (!agent) return "unknown";
54
- try {
55
- return new URL(agent).hostname;
56
- } catch {
57
- return agent;
58
- }
59
- };
60
-
61
- const buildLabel = (agent?: string): HTMLElement => {
62
- if (!agent) {
63
- // No Signature-Agent URL on the response — the operator's Allow rule
64
- // matched on a non-Web-Bot-Auth condition (IP CIDR, JA4, UA substring,
65
- // ASN, country). Fall back to generic copy so the operator isn't misled
66
- // about which qualifier fired.
67
- return createElement("span", {
68
- children: [createElement("strong", { text: "Trusted request" })],
69
- });
70
- }
71
- return createElement("span", {
72
- children: [
73
- createElement("strong", { text: "Verified agent" }),
74
- document.createTextNode(`: ${displayHost(agent)}`),
75
- ],
76
- });
77
- };
78
-
79
- const buildTick = (): SVGSVGElement => {
80
- const title = createSvgElement("title");
81
- title.textContent = "Verified";
82
- return createSvgElement("svg", {
83
- attributes: {
84
- width: "16",
85
- height: "16",
86
- viewBox: "0 0 24 24",
87
- fill: "none",
88
- stroke: "currentColor",
89
- "stroke-width": "2.5",
90
- "stroke-linecap": "round",
91
- "stroke-linejoin": "round",
92
- "aria-hidden": "true",
93
- },
94
- children: [
95
- title,
96
- createSvgElement("path", { attributes: { d: "M20 6L9 17l-5-5" } }),
97
- ],
98
- });
99
- };
100
-
101
- export const mountAuthenticatedBadge = (
102
- container: HTMLElement,
103
- props: AuthenticatedBadgeProps,
104
- ): StaticComponent => {
105
- const { sessionId, agent, dapp, userAccount, provider, callbacks } = props;
106
-
107
- const badge = createElement("div", {
108
- style: {
109
- display: "inline-flex",
110
- alignItems: "center",
111
- gap: "8px",
112
- padding: "8px 12px",
113
- borderRadius: "6px",
114
- background: "#eef2ff",
115
- border: "1px solid #c7d2fe",
116
- color: "#3730a3",
117
- fontFamily:
118
- "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
119
- fontSize: "13px",
120
- lineHeight: 1.4,
121
- },
122
- attributes: { role: "status", "aria-label": "Verified agent" },
123
- children: [buildTick(), buildLabel(agent)],
124
- });
125
-
126
- container.appendChild(badge);
127
-
128
- const events = getDefaultEvents(callbacks);
129
- const token = encodeProcaptchaOutput({
130
- [ApiParams.providerUrl]: provider.provider.url,
131
- [ApiParams.user]: userAccount.account.address,
132
- [ApiParams.dapp]: dapp,
133
- // Verify endpoint reads commitmentId as the sessionId — reusing the
134
- // existing slot avoids a token codec bump for this one flow.
135
- [ApiParams.commitmentId]: sessionId,
136
- [ApiParams.timestamp]: Date.now().toString(),
137
- [ApiParams.signature]: {
138
- [ApiParams.provider]: {},
139
- [ApiParams.user]: {},
140
- },
141
- [ApiParams.captchaType]: CaptchaType.authenticated,
142
- });
143
- events.onHuman(token);
144
-
145
- return {
146
- update: () => undefined,
147
- destroy: () => {
148
- badge.parentNode?.removeChild(badge);
149
- },
150
- };
151
- };
@@ -1,392 +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 { ProviderApi } from "@prosopo/api";
16
- import { ProsopoEnvError } from "@prosopo/common";
17
- import {
18
- ExtensionLoader,
19
- getProcaptchaRandomActiveProvider,
20
- pickIpMode,
21
- resolveClientSessionId,
22
- } from "@prosopo/procaptcha-common";
23
- import type {
24
- BotDetectionFunction,
25
- ProcaptchaClientConfigOutput,
26
- ProviderSelectRetryContext,
27
- } from "@prosopo/types";
28
- import type { BotDetectionFunctionResult } from "@prosopo/types";
29
- import {
30
- DetectorLoaderFromScript,
31
- type DetectorOptions,
32
- type DetectorType,
33
- } from "./detectorLoader.js";
34
- import {
35
- type PrefetchedDetector,
36
- takePrefetchedDetector,
37
- } from "./detectorPrefetch.js";
38
-
39
- // Upper bound on the assign POST, which serves the detector bundle inline
40
- // (~215 KB gzipped). The hop is always cold — /healthz pins a different
41
- // hostname, so it pays fresh DNS + TLS + a CORS preflight before the download
42
- // even starts, measured at 6.7s against staging. Anything tighter silently
43
- // drops the detector and sends an empty token.
44
- const ASSIGN_TIMEOUT_MS = 10_000;
45
-
46
- // The page(s) the widget is rendered on, reduced to origin + path.
47
- // Deliberately built from `origin` + `pathname` (never `href`) so the query
48
- // string, fragment, and any embedded `user:pass@` credentials never leave the
49
- // browser — sites routinely carry tokens / session ids / reset codes in those
50
- // parts.
51
- //
52
- // Returns two fields:
53
- // - `currentUrl`: the top-frame URL as best we can determine it. Same-origin
54
- // iframes read it directly; cross-origin iframes fall back to
55
- // `document.referrer`, which the browser fills with the embedding page URL
56
- // subject to Referrer-Policy. When neither is available the field falls
57
- // back to the local (iframe) URL so the provider still sees a value.
58
- // - `iframeUrl`: the widget's own frame URL when we're embedded. Undefined
59
- // when the widget IS the top frame — nothing to distinguish. Emitted so
60
- // downstream analytics can separate "Protect's site-wide iframe endpoint"
61
- // from "the page the user was actually on".
62
- //
63
- // Both fields are undefined in non-browser contexts (SSR / tests) or for
64
- // opaque origins.
65
- const sanitiseHref = (href: string): string | undefined => {
66
- try {
67
- const u = new URL(href);
68
- if (!u.origin || u.origin === "null") return undefined;
69
- return `${u.origin}${u.pathname || ""}`;
70
- } catch {
71
- return undefined;
72
- }
73
- };
74
-
75
- type PageUrls = {
76
- currentUrl: string | undefined;
77
- iframeUrl: string | undefined;
78
- };
79
-
80
- const getCurrentPageUrls = (): PageUrls => {
81
- if (typeof window === "undefined" || !window.location) {
82
- return { currentUrl: undefined, iframeUrl: undefined };
83
- }
84
- const local = (() => {
85
- const { origin, pathname } = window.location;
86
- if (!origin || origin === "null") return undefined;
87
- return `${origin}${pathname || ""}`;
88
- })();
89
-
90
- // Top window — no iframe distinction, report the local URL only.
91
- if (window === window.top) {
92
- return { currentUrl: local, iframeUrl: undefined };
93
- }
94
-
95
- // Same-origin iframe — read the top URL directly.
96
- try {
97
- const topHref = window.top?.location?.href;
98
- const sanitised = topHref ? sanitiseHref(topHref) : undefined;
99
- if (sanitised) return { currentUrl: sanitised, iframeUrl: local };
100
- } catch {
101
- /* cross-origin — fall through */
102
- }
103
-
104
- // Cross-origin iframe — the embedding page URL comes via referrer,
105
- // subject to the parent's Referrer-Policy header.
106
- if (typeof document !== "undefined" && document.referrer) {
107
- const fromReferrer = sanitiseHref(document.referrer);
108
- if (fromReferrer) return { currentUrl: fromReferrer, iframeUrl: local };
109
- }
110
-
111
- // Referrer unavailable — fall back to the iframe URL for `currentUrl` so
112
- // the provider still sees a value, and echo it as `iframeUrl` so
113
- // downstream can tell the top frame was not observed.
114
- return { currentUrl: local, iframeUrl: local };
115
- };
116
-
117
- export const withTimeout = async <T>(
118
- promise: Promise<T>,
119
- ms: number,
120
- ): Promise<T> => {
121
- let timeoutId: NodeJS.Timeout | undefined;
122
- const timeoutPromise = new Promise<never>((_, reject) => {
123
- timeoutId = setTimeout(() => {
124
- reject(new ProsopoEnvError("API.UNKNOWN"));
125
- }, ms);
126
- });
127
-
128
- try {
129
- const result = await Promise.race([promise, timeoutPromise]);
130
- if (timeoutId) {
131
- clearTimeout(timeoutId);
132
- }
133
- return result;
134
- } catch (error) {
135
- if (timeoutId) {
136
- clearTimeout(timeoutId);
137
- }
138
- throw error;
139
- }
140
- };
141
-
142
- const customDetectBot: BotDetectionFunction = async (
143
- config: ProcaptchaClientConfigOutput,
144
- container: HTMLElement | undefined,
145
- restartFn: () => void,
146
- retryContext?: ProviderSelectRetryContext,
147
- ): Promise<BotDetectionFunctionResult> => {
148
- if (!config.account.address) {
149
- throw new ProsopoEnvError("GENERAL.SITE_KEY_MISSING");
150
- }
151
-
152
- const ipMode = pickIpMode(config);
153
-
154
- // Start the extension/account module load now rather than after the bundle
155
- // assignment. It depends on nothing above, so it overlaps the provider-pin
156
- // `/healthz` round-trip and the assign request for free; it is awaited below
157
- // at the point `ExtClass` is first needed.
158
- //
159
- // This is what survives of main's parallel-pin optimisation. That change
160
- // warmed BOTH `pinPromiseCache` keys — with and without ipMode — because the
161
- // catcher-internal provider selector called with no ipMode while the awaited
162
- // call passed one. The 3-arg detector has no provider selector at all, so
163
- // only the `(env, ipMode)` key is ever used now and warming the bare-env key
164
- // would just issue a healthz request nothing consumes. Nor can the pin be
165
- // moved off the critical path the way it was before: the detector now comes
166
- // FROM the provider, so resolving the provider is a hard prerequisite of
167
- // having anything to run, not something that can proceed alongside it.
168
- const extClassPromise = ExtensionLoader(config.web2);
169
-
170
- // On the first attempt this resolves the static DNS endpoint for this env —
171
- // the DNS layer load-balances across the pronode fleet. On a retry
172
- // (`retryContext.attempt > 1`) the previously used pronode errored, so we
173
- // pick a random provider straight from the list instead of re-pinning the
174
- // same one. `pickIpMode(config)` honours the dapp's data-ipv4 / data-ipv6
175
- // preference so frictionless and the subsequent captcha hops stay on the
176
- // same stack. Resolved up front — before detection rather than alongside it —
177
- // because the detector bundle is served BY this provider.
178
- // The bundle entry starts provider resolution + assign as soon as it has read
179
- // the site key off the DOM, which is well before this widget has mounted.
180
- // Claim that in-flight work if it exists rather than repeating it.
181
- // Only valid on a first attempt: a retry is retrying *because* the pinned
182
- // pronode failed, so it must re-resolve.
183
- const isFirstAttempt = !retryContext || retryContext.attempt <= 1;
184
- const prefetched = isFirstAttempt
185
- ? takePrefetchedDetector(
186
- config.defaultEnvironment,
187
- ipMode,
188
- config.account.address,
189
- )
190
- : undefined;
191
-
192
- // A prefetch that failed must not fail the flow — it is an optimisation, and
193
- // the normal path below handles provider selection and assign failure
194
- // already. So swallow it and re-resolve.
195
- let prefetchedResult: PrefetchedDetector | undefined;
196
- if (prefetched) {
197
- try {
198
- prefetchedResult = await prefetched;
199
- } catch {
200
- prefetchedResult = undefined;
201
- }
202
- }
203
-
204
- const provider =
205
- prefetchedResult?.provider ??
206
- (await getProcaptchaRandomActiveProvider(
207
- config.defaultEnvironment,
208
- ipMode,
209
- retryContext,
210
- ));
211
-
212
- const providerApi = new ProviderApi(
213
- provider.provider.url,
214
- config.account.address,
215
- );
216
-
217
- // Ask the provider for a per-session detector bundle. The detector lives ONLY
218
- // in the provider-served pool: when the provider has a populated pool it
219
- // returns the obfuscated detector (each with its own keys + inner cipher)
220
- // plus a detectorSessionId. When it cannot (no pool, network, decode, or
221
- // timeout) we have NO detector to run and there is no bundled fallback.
222
- let detectorSessionId: string | undefined;
223
- let providerDetect: DetectorType | undefined;
224
- let detectorOptions: DetectorOptions | undefined;
225
- try {
226
- // Reuse the prefetched assignment when the entry already fetched one for
227
- // this provider; otherwise issue it now.
228
- const assigned =
229
- prefetchedResult?.assigned ??
230
- (await withTimeout(
231
- providerApi.assignDetectorBundle(config.account.address),
232
- ASSIGN_TIMEOUT_MS,
233
- ));
234
- if (assigned.useProviderBundle && assigned.detectorScript) {
235
- // Deliberately untimed: this is a local parse + evaluate, so a timer
236
- // cannot rescue a stalled main thread — it can only throw away a bundle
237
- // we are already holding.
238
- providerDetect = await DetectorLoaderFromScript(assigned.detectorScript);
239
- detectorSessionId = assigned.detectorSessionId;
240
- detectorOptions = {
241
- clientUrl: assigned.clientUrl,
242
- assetOrigin: assigned.assetOrigin,
243
- };
244
- }
245
- } catch (err) {
246
- // No detector available — fall through to the PoW request below.
247
- //
248
- // Report it. Falling back is by design, but the reasons are not equal: a
249
- // slow network is routine, whereas a bundle that throws on import means
250
- // every session on this provider silently degrades to an image captcha
251
- // with nothing in the client or provider logs to say why. That failure
252
- // mode shipped undetected once already — an obfuscator seed emitted a
253
- // bundle that died with "Class constructor X cannot be invoked without
254
- // 'new'", and the only way to see it was to reproduce the import by hand.
255
- // The catch stays broad; it just no longer hides what it caught.
256
- console.error(
257
- "Procaptcha: no detector bundle available, falling back to a server-chosen captcha:",
258
- err,
259
- );
260
- }
261
-
262
- const ExtClass = await extClassPromise;
263
- const ext = new ExtClass();
264
-
265
- // Sent on this hop as well as on solution submit, so a session that is
266
- // allowed frictionlessly — or abandoned before a solve — still correlates
267
- // back to the site's (or Protect's) session. Undefined when Protect has not
268
- // finished initialising yet; the solve-time read then supplies it.
269
- const clientSessionId = resolveClientSessionId(config.clientSessionId);
270
-
271
- // No provider detector ⇒ no detection is possible, so there is nothing to
272
- // send. The request goes out with an empty token and the provider decides
273
- // what to serve; the client gets no say in that.
274
- if (providerDetect === undefined) {
275
- const userAccount = await ext.getAccount(config);
276
- const { currentUrl: fallbackUrl, iframeUrl: fallbackIframeUrl } =
277
- getCurrentPageUrls();
278
- const captcha = await withTimeout(
279
- providerApi.getFrictionlessCaptcha(
280
- undefined,
281
- undefined,
282
- config.account.address,
283
- userAccount.account.address,
284
- config.mode,
285
- undefined,
286
- undefined,
287
- fallbackUrl,
288
- fallbackIframeUrl,
289
- clientSessionId,
290
- ),
291
- 10000,
292
- );
293
- if (captcha.dns_url) {
294
- try {
295
- void fetch(captcha.dns_url, {
296
- method: "GET",
297
- mode: "no-cors",
298
- credentials: "omit",
299
- keepalive: true,
300
- cache: "no-store",
301
- }).catch(() => undefined);
302
- } catch {
303
- /* swallow */
304
- }
305
- }
306
- return {
307
- captchaType: captcha.captchaType,
308
- sessionId: captcha.sessionId,
309
- provider: provider,
310
- status: captcha.status,
311
- userAccount: userAccount,
312
- error: captcha.error,
313
- hp: captcha.hp,
314
- agent: captcha.agent,
315
- };
316
- }
317
-
318
- const detect: DetectorType = providerDetect;
319
-
320
- const detectionResult = await detect(
321
- container,
322
- restartFn,
323
- () => ext.getAccount(config),
324
- detectorOptions,
325
- );
326
-
327
- const userAccount = detectionResult.userAccount;
328
-
329
- // SIMD readings deliberately omitted from the frictionless hop. The WASM
330
- // benchmark is a CPU-bound loop that contends with BotScoreWorker if it
331
- // runs during detection; deferring it until after the POST is in flight
332
- // lets it complete in the worker thread while the network round-trip
333
- // burns. Readings still attach on the challenge GET and on solution
334
- // submit (first-hop-wins server-side).
335
- const { currentUrl, iframeUrl } = getCurrentPageUrls();
336
- const captchaPromise = providerApi.getFrictionlessCaptcha(
337
- detectionResult.token,
338
- detectionResult.encryptHeadHash,
339
- config.account.address,
340
- userAccount.account.address,
341
- config.mode,
342
- undefined,
343
- detectorSessionId,
344
- currentUrl,
345
- iframeUrl,
346
- clientSessionId,
347
- );
348
- if (detectionResult.getSimdReadings) {
349
- // Fire-and-forget: triggers the memoised prefetch inside the catcher
350
- // so the next hop sees a hot benchmark. We never await the result here.
351
- void detectionResult.getSimdReadings(60_000).catch(() => undefined);
352
- }
353
- const captcha = await withTimeout(captchaPromise, 10000);
354
-
355
- // Fire-and-forget DNS observation beacon. Failures swallowed —
356
- // observation must never break the captcha flow.
357
- if (captcha.dns_url) {
358
- try {
359
- void fetch(captcha.dns_url, {
360
- method: "GET",
361
- mode: "no-cors",
362
- credentials: "omit",
363
- keepalive: true,
364
- cache: "no-store",
365
- }).catch(() => undefined);
366
- } catch {
367
- /* swallow */
368
- }
369
- }
370
-
371
- return {
372
- captchaType: captcha.captchaType,
373
- sessionId: captcha.sessionId,
374
- provider: provider,
375
- status: captcha.status,
376
- userAccount: userAccount,
377
- error: captcha.error,
378
- hp: captcha.hp,
379
- agent: captcha.agent,
380
- // Map specific trackers to generic behavioral collectors
381
- behaviorCollector1: detectionResult.mouseTracker,
382
- behaviorCollector2: detectionResult.touchTracker,
383
- behaviorCollector3: detectionResult.clickTracker,
384
- behaviorCollector4: detectionResult.scrollTracker,
385
- deviceCapability: detectionResult.hasTouchSupport,
386
- encryptBehavioralData: detectionResult.encryptBehavioralData,
387
- packBehavioralData: detectionResult.packBehavioralData,
388
- getSimdReadings: detectionResult.getSimdReadings,
389
- };
390
- };
391
-
392
- export default customDetectBot;