@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,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;
@@ -1,133 +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 {
16
- Account,
17
- BehavioralData,
18
- ClickEventPoint,
19
- MouseMovementPoint,
20
- PackedBehavioralData,
21
- ScrollEventPoint,
22
- TouchEventPoint,
23
- } from "@prosopo/types";
24
-
25
- // The detector is NOT bundled into the widget — it lives only in the
26
- // provider-served pool bundles, loaded at runtime via a blob URL below. So the
27
- // signature is declared locally here (mirroring `@prosopo/detector`'s default
28
- // export) from shared @prosopo/types primitives, rather than importing the
29
- // detector package as a build-time type dependency.
30
- export type DetectorOptions = {
31
- clientUrl?: string;
32
- assetOrigin?: string;
33
- };
34
-
35
- export type DetectorType = (
36
- container: HTMLElement | undefined,
37
- restart: () => void,
38
- accountGenerator: () => Promise<Account>,
39
- options?: DetectorOptions,
40
- ) => Promise<{
41
- token: string;
42
- shadowDomCleanup: () => void;
43
- encryptHeadHash: string;
44
- mouseTracker?: {
45
- start: () => void;
46
- stop: () => void;
47
- getData: () => MouseMovementPoint[];
48
- clear: () => void;
49
- };
50
- touchTracker?: {
51
- start: () => void;
52
- stop: () => void;
53
- getData: () => TouchEventPoint[];
54
- clear: () => void;
55
- };
56
- clickTracker?: {
57
- start: () => void;
58
- stop: () => void;
59
- getData: () => ClickEventPoint[];
60
- clear: () => void;
61
- };
62
- scrollTracker?: {
63
- start: () => void;
64
- stop: () => void;
65
- getData: () => ScrollEventPoint[];
66
- clear: () => void;
67
- };
68
- hasTouchSupport?: string;
69
- encryptBehavioralData?: (data: string) => Promise<string>;
70
- packBehavioralData?: (behavioralData: BehavioralData) => PackedBehavioralData;
71
- getSimdReadings?: (timeoutMs?: number) => Promise<string | undefined>;
72
- userAccount: Account;
73
- }>;
74
-
75
- interface LoaderAttempt {
76
- readonly url: string;
77
- readonly release: () => void;
78
- }
79
-
80
- const blobAttempt = (script: string): LoaderAttempt => {
81
- const url = URL.createObjectURL(
82
- new Blob([script], { type: "text/javascript" }),
83
- );
84
- return { url, release: (): void => URL.revokeObjectURL(url) };
85
- };
86
-
87
- const dataAttempt = (script: string): LoaderAttempt => ({
88
- url: `data:text/javascript;charset=utf-8,${encodeURIComponent(script)}`,
89
- release: (): void => undefined,
90
- });
91
-
92
- /** Injection point for tests; real callers never pass this. */
93
- export type ModuleImporter = (url: string) => Promise<unknown>;
94
-
95
- const defaultImporter: ModuleImporter = (url) =>
96
- import(/* @vite-ignore */ /* webpackIgnore: true */ url);
97
-
98
- /**
99
- * Loads a detector from a provider-served obfuscated ESM string (the
100
- * per-session pool bundle). The module is self-contained, so a dynamic
101
- * `import()` yields its default export.
102
- *
103
- * A blob URL is tried first, then a `data:` URL. The two are gated by
104
- * different CSP directives and sites commonly allow one without the other — a
105
- * `script-src` of `*` matches neither, and a policy listing `data:` for
106
- * scripts and `blob:` only for workers blocks the blob path outright. Without
107
- * the fallback every session on such a site loses the detector, sends an empty
108
- * token, and can never pass frictionlessly.
109
- *
110
- * A blocked attempt logs a CSP violation before the import rejects. That noise
111
- * is the cost of recovering the session.
112
- */
113
- export const DetectorLoaderFromScript = async (
114
- script: string,
115
- importModule: ModuleImporter = defaultImporter,
116
- ): Promise<DetectorType> => {
117
- let lastError: unknown = new Error("no loader attempt ran");
118
- for (const build of [blobAttempt, dataAttempt]) {
119
- let attempt: LoaderAttempt | undefined;
120
- try {
121
- attempt = build(script);
122
- const mod = (await importModule(attempt.url)) as {
123
- default: DetectorType;
124
- };
125
- return mod.default;
126
- } catch (err) {
127
- lastError = err;
128
- } finally {
129
- attempt?.release();
130
- }
131
- }
132
- throw lastError;
133
- };
@@ -1,115 +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
- * Detector bundle prefetch.
17
- *
18
- * Since the detector moved into the provider-served pool, the frictionless flow
19
- * cannot start until `/detector/assign` has returned. That request is issued by
20
- * `customDetectBot`, which only runs once the widget has mounted — and
21
- * that mount sits behind the bundle's dynamic-import chain. Measured on a
22
- * staging demo page the assign request did not leave the browser until 1513 ms,
23
- * of which ~700 ms was purely waiting for chunks to arrive in sequence.
24
- *
25
- * Nothing in the request depends on the widget, i18n or its config: it needs
26
- * the site key (a DOM attribute, readable immediately), the environment (a
27
- * build-time constant) and the IP-mode flags (DOM attributes). So the entry
28
- * point kicks it off as soon as it has read those, and `customDetectBot` picks
29
- * up the in-flight promise instead of starting its own.
30
- *
31
- * The cache is deliberately single-use. A provider pin is only valid for the
32
- * attempt it was made for — on a retry the previous pronode is the one that
33
- * just failed — so a consumed entry is dropped and the retry re-resolves.
34
- */
35
-
36
- import { ProviderApi } from "@prosopo/api";
37
- import { getProcaptchaRandomActiveProvider } from "@prosopo/procaptcha-common";
38
- import type {
39
- AssignDetectorBundleResponse,
40
- EnvironmentTypes,
41
- RandomProvider,
42
- } from "@prosopo/types";
43
-
44
- // `IpMode` is declared in @prosopo/load-balancer, which this package does not
45
- // depend on. Derive it from the selector we already call rather than adding a
46
- // dependency (and a matching tsconfig project reference) for one type alias —
47
- // this also cannot drift from the function's real signature.
48
- type IpModeParam = Parameters<typeof getProcaptchaRandomActiveProvider>[1];
49
-
50
- export interface PrefetchedDetector {
51
- provider: RandomProvider;
52
- assigned: AssignDetectorBundleResponse;
53
- }
54
-
55
- const inFlight = new Map<string, Promise<PrefetchedDetector>>();
56
-
57
- const keyOf = (
58
- environment: EnvironmentTypes,
59
- ipMode: IpModeParam,
60
- siteKey: string,
61
- ): string => `${environment}|${ipMode ?? "auto"}|${siteKey}`;
62
-
63
- /**
64
- * Start resolving a provider and assigning a detector bundle. Safe to call more
65
- * than once for the same key — subsequent calls join the in-flight request.
66
- *
67
- * Never rejects to the caller: a failed prefetch is indistinguishable from
68
- * never having prefetched, and `customDetectBot` already handles assign failure
69
- * by falling back to PoW. Returning a rejected promise here would surface as an
70
- * unhandled rejection in the host page.
71
- */
72
- export const prefetchDetector = (
73
- environment: EnvironmentTypes,
74
- ipMode: IpModeParam,
75
- siteKey: string,
76
- ): void => {
77
- const key = keyOf(environment, ipMode, siteKey);
78
- if (inFlight.has(key)) return;
79
-
80
- const promise = (async (): Promise<PrefetchedDetector> => {
81
- const provider = await getProcaptchaRandomActiveProvider(
82
- environment,
83
- ipMode,
84
- );
85
- const providerApi = new ProviderApi(provider.provider.url, siteKey);
86
- const assigned = await providerApi.assignDetectorBundle(siteKey);
87
- return { provider, assigned };
88
- })();
89
-
90
- // Attach a no-op catch so a failed prefetch never becomes an unhandled
91
- // rejection. `takePrefetchedDetector`'s consumer still sees the rejection on
92
- // the original promise and falls back.
93
- promise.catch(() => undefined);
94
- inFlight.set(key, promise);
95
- };
96
-
97
- /**
98
- * Claim a prefetched assignment, if one was started for this exact key. The
99
- * entry is removed, so a retry does not reuse a pin that may have just failed.
100
- */
101
- export const takePrefetchedDetector = (
102
- environment: EnvironmentTypes,
103
- ipMode: IpModeParam,
104
- siteKey: string,
105
- ): Promise<PrefetchedDetector> | undefined => {
106
- const key = keyOf(environment, ipMode, siteKey);
107
- const promise = inFlight.get(key);
108
- if (promise) inFlight.delete(key);
109
- return promise;
110
- };
111
-
112
- /** Test seam — drops any in-flight prefetches. */
113
- export const clearPrefetchedDetectors = (): void => {
114
- inFlight.clear();
115
- };