@webdecoy/client 0.18.5 → 0.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.
- package/README.md +73 -2
- package/dist/index.d.mts +41 -1
- package/dist/index.d.ts +41 -1
- package/dist/index.js +122 -0
- package/dist/index.mjs +122 -0
- package/dist/webdecoy.global.js +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -87,8 +87,8 @@ edge validator continue to verify every token and enforce revocation.
|
|
|
87
87
|
The cookie is Secure, SameSite Lax and host-only. Accepted interaction aggregates
|
|
88
88
|
remain on renewal requests, and the server evaluates them again; pass
|
|
89
89
|
`behavior: false` to disable the behavioral upgrade. The client does not intercept
|
|
90
|
-
or retry application fetch/XHR requests
|
|
91
|
-
|
|
90
|
+
or retry application fetch/XHR requests globally. An edge API challenge is a JSON
|
|
91
|
+
403; the opt-in helper below handles safe reads through your application’s flow.
|
|
92
92
|
|
|
93
93
|
## What it collects
|
|
94
94
|
|
|
@@ -131,3 +131,74 @@ and Next.js adapters and the full detection/scoring reference.
|
|
|
131
131
|
## License
|
|
132
132
|
|
|
133
133
|
MIT
|
|
134
|
+
|
|
135
|
+
## API challenge recovery
|
|
136
|
+
|
|
137
|
+
With `@webdecoy/client` **0.19.0 or later** and an updated edge validator, opt in
|
|
138
|
+
for the API reads your application wants to recover:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { createClearanceFetch } from '@webdecoy/client';
|
|
142
|
+
import { earnClearance } from './clearance-flow'; // your application's flow
|
|
143
|
+
|
|
144
|
+
const fetchProtected = createClearanceFetch({
|
|
145
|
+
origin: location.origin,
|
|
146
|
+
timeoutMs: 10_000,
|
|
147
|
+
recover: ({ origin, challenge, signal }) =>
|
|
148
|
+
earnClearance({ origin, reason: challenge.reason, signal }),
|
|
149
|
+
onEvent: event => console.debug(event.type, event.status),
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const controller = new AbortController();
|
|
153
|
+
const response = await fetchProtected('/api/catalog', {
|
|
154
|
+
credentials: 'same-origin',
|
|
155
|
+
signal: controller.signal, // your application's AbortController
|
|
156
|
+
});
|
|
157
|
+
// Handle response.ok/status/body just as with native fetch.
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`earnClearance` is application code, not an SDK export. It must earn and install
|
|
161
|
+
the host's `wd_clearance` cookie through your configured issuance/verification
|
|
162
|
+
flow and return `true` only when ready to retry. `startClearance()` returns
|
|
163
|
+
`void`; awaiting it does not wait for a token. A self-hosted captcha widget token
|
|
164
|
+
is not a clearance cookie. A stronger-grade response needs a flow that earns the
|
|
165
|
+
route's required grade; simply replacing a token cannot grant that grade.
|
|
166
|
+
|
|
167
|
+
The helper retries **GET/HEAD once** after a recognized recoverable challenge.
|
|
168
|
+
Concurrent calls through one adapter share one recovery callback for its
|
|
169
|
+
configured origin; that callback receives the first challenge's reason. Use one
|
|
170
|
+
adapter for each origin/recovery flow. The edge evaluates every retry again.
|
|
171
|
+
POST/PATCH/PUT/DELETE and other methods pass through once with their original
|
|
172
|
+
body. There is no mutation replay opt-in and no XHR interception. The standalone
|
|
173
|
+
script exposes the same helpers at `window.WebDecoyClearance`.
|
|
174
|
+
|
|
175
|
+
Recovery and the retry share a deadline after the first challenge: 10 seconds by
|
|
176
|
+
default, configurable from 1 ms to 60 seconds. Refusal, resolver rejection,
|
|
177
|
+
offline state, or deadline expiry returns the original readable challenge
|
|
178
|
+
response. Caller cancellation and fetch network errors reject as native fetch
|
|
179
|
+
does. One cancelled caller does not cancel other callers waiting for the shared
|
|
180
|
+
flow; when none remain, the recovery signal aborts. Your flow must stop network
|
|
181
|
+
work and close its UI on that signal. If it ignores cancellation, later calls
|
|
182
|
+
remain attached to that stopped attempt until it settles, rather than opening
|
|
183
|
+
overlapping recovery dialogs. Browsers without `AbortSignal.any()` return the
|
|
184
|
+
challenge without attempting recovery.
|
|
185
|
+
|
|
186
|
+
Only version-1 responses with the exact WebDecoy challenge headers qualify.
|
|
187
|
+
Ordinary application 403s, unsupported/malformed contracts, revoked sessions,
|
|
188
|
+
crawler-policy refusals and agent impersonation do not trigger recovery.
|
|
189
|
+
Redirected responses, different origins and `credentials: 'omit'` also do not.
|
|
190
|
+
The helper preserves request options and leaves response bodies/streams unread.
|
|
191
|
+
It adds no request headers or CORS permission. Cross-origin calls need
|
|
192
|
+
`credentials: 'include'`, the protected host's cookie, and an application-approved
|
|
193
|
+
CORS policy that exposes the four challenge headers; otherwise the browser
|
|
194
|
+
cannot identify the response. A cookie set on the page's host does not clear a
|
|
195
|
+
different API host.
|
|
196
|
+
|
|
197
|
+
`onEvent` reports `challenge-served`, `recovery-attempted`,
|
|
198
|
+
`recovery-succeeded`/`recovery-failed`, and the retried `enforcement-outcome`
|
|
199
|
+
(status). Attempts are per waiting request; count callback invocations separately
|
|
200
|
+
for shared flows. Success means the retry returned an OK response, not a new
|
|
201
|
+
trust grade. These local observations send no telemetry automatically and must
|
|
202
|
+
remain distinct from the validator's verdict counts. Observation failures cannot
|
|
203
|
+
change the request. Interactive application flows must provide keyboard access,
|
|
204
|
+
focus restoration, an announced status and cancellation; the helper renders no UI.
|
package/dist/index.d.mts
CHANGED
|
@@ -560,6 +560,46 @@ interface ClearanceOptions {
|
|
|
560
560
|
*/
|
|
561
561
|
declare function startClearance(opts: ClearanceOptions): void;
|
|
562
562
|
|
|
563
|
+
/** An explicit fetch adapter. Does not replace window.fetch or intercept XHR. */
|
|
564
|
+
type ClearanceChallengeReason = 'missing' | 'invalid' | 'insufficient-trust' | 'revoked' | 'crawler-refused' | 'agent-impersonation' | 'denied';
|
|
565
|
+
interface ClearanceChallenge {
|
|
566
|
+
version: 1;
|
|
567
|
+
reason: ClearanceChallengeReason;
|
|
568
|
+
recoverable: boolean;
|
|
569
|
+
}
|
|
570
|
+
interface ClearanceRecoveryContext {
|
|
571
|
+
origin: string;
|
|
572
|
+
challenge: ClearanceChallenge;
|
|
573
|
+
/** Recovery UI/network work must stop when this signal aborts. */
|
|
574
|
+
signal: AbortSignal;
|
|
575
|
+
}
|
|
576
|
+
interface ClearanceFetchEvent {
|
|
577
|
+
type: 'challenge-served' | 'recovery-attempted' | 'recovery-succeeded' | 'recovery-failed' | 'enforcement-outcome';
|
|
578
|
+
origin: string;
|
|
579
|
+
method: string;
|
|
580
|
+
challenge: ClearanceChallenge;
|
|
581
|
+
status?: number;
|
|
582
|
+
}
|
|
583
|
+
interface ClearanceFetchOptions {
|
|
584
|
+
/** One explicitly trusted protected origin. Use one adapter per origin/recovery flow. */
|
|
585
|
+
origin: string;
|
|
586
|
+
/** Earn and install clearance for this origin; true permits one safe-read retry. */
|
|
587
|
+
recover(context: ClearanceRecoveryContext): Promise<boolean>;
|
|
588
|
+
/** Recovery and retry deadline after the challenge; default 10s, maximum 60s. */
|
|
589
|
+
timeoutMs?: number;
|
|
590
|
+
fetch?: typeof fetch;
|
|
591
|
+
/** Local observation hook; no telemetry is sent automatically. */
|
|
592
|
+
onEvent?(event: ClearanceFetchEvent): void;
|
|
593
|
+
}
|
|
594
|
+
/** Header-only recognition keeps the application response body/stream untouched. */
|
|
595
|
+
declare function readClearanceChallenge(response: Response): ClearanceChallenge | null;
|
|
596
|
+
/**
|
|
597
|
+
* GET/HEAD only, at most one retry per call. A callback's success is not trust:
|
|
598
|
+
* the validator re-evaluates the retried request. Refusal/timeout returns the
|
|
599
|
+
* original challenge response; caller cancellation and fetch errors reject.
|
|
600
|
+
*/
|
|
601
|
+
declare function createClearanceFetch(options: ClearanceFetchOptions): typeof fetch;
|
|
602
|
+
|
|
563
603
|
/**
|
|
564
604
|
* Behavioral human-likelihood for clearance minting .
|
|
565
605
|
*
|
|
@@ -626,4 +666,4 @@ declare function summarizeBehavior(collector: BehavioralCollector): BehaviorAggr
|
|
|
626
666
|
*/
|
|
627
667
|
declare function watchInteraction(onReady: (b: BehaviorAggregate) => void): () => void;
|
|
628
668
|
|
|
629
|
-
export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceOptions, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, getFormAnalyzer, getPoWManager, hasEnoughInteraction, sha256, startClearance, summarizeBehavior, watchInteraction };
|
|
669
|
+
export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceChallenge, type ClearanceChallengeReason, type ClearanceFetchEvent, type ClearanceFetchOptions, type ClearanceOptions, type ClearanceRecoveryContext, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, createClearanceFetch, getFormAnalyzer, getPoWManager, hasEnoughInteraction, readClearanceChallenge, sha256, startClearance, summarizeBehavior, watchInteraction };
|
package/dist/index.d.ts
CHANGED
|
@@ -560,6 +560,46 @@ interface ClearanceOptions {
|
|
|
560
560
|
*/
|
|
561
561
|
declare function startClearance(opts: ClearanceOptions): void;
|
|
562
562
|
|
|
563
|
+
/** An explicit fetch adapter. Does not replace window.fetch or intercept XHR. */
|
|
564
|
+
type ClearanceChallengeReason = 'missing' | 'invalid' | 'insufficient-trust' | 'revoked' | 'crawler-refused' | 'agent-impersonation' | 'denied';
|
|
565
|
+
interface ClearanceChallenge {
|
|
566
|
+
version: 1;
|
|
567
|
+
reason: ClearanceChallengeReason;
|
|
568
|
+
recoverable: boolean;
|
|
569
|
+
}
|
|
570
|
+
interface ClearanceRecoveryContext {
|
|
571
|
+
origin: string;
|
|
572
|
+
challenge: ClearanceChallenge;
|
|
573
|
+
/** Recovery UI/network work must stop when this signal aborts. */
|
|
574
|
+
signal: AbortSignal;
|
|
575
|
+
}
|
|
576
|
+
interface ClearanceFetchEvent {
|
|
577
|
+
type: 'challenge-served' | 'recovery-attempted' | 'recovery-succeeded' | 'recovery-failed' | 'enforcement-outcome';
|
|
578
|
+
origin: string;
|
|
579
|
+
method: string;
|
|
580
|
+
challenge: ClearanceChallenge;
|
|
581
|
+
status?: number;
|
|
582
|
+
}
|
|
583
|
+
interface ClearanceFetchOptions {
|
|
584
|
+
/** One explicitly trusted protected origin. Use one adapter per origin/recovery flow. */
|
|
585
|
+
origin: string;
|
|
586
|
+
/** Earn and install clearance for this origin; true permits one safe-read retry. */
|
|
587
|
+
recover(context: ClearanceRecoveryContext): Promise<boolean>;
|
|
588
|
+
/** Recovery and retry deadline after the challenge; default 10s, maximum 60s. */
|
|
589
|
+
timeoutMs?: number;
|
|
590
|
+
fetch?: typeof fetch;
|
|
591
|
+
/** Local observation hook; no telemetry is sent automatically. */
|
|
592
|
+
onEvent?(event: ClearanceFetchEvent): void;
|
|
593
|
+
}
|
|
594
|
+
/** Header-only recognition keeps the application response body/stream untouched. */
|
|
595
|
+
declare function readClearanceChallenge(response: Response): ClearanceChallenge | null;
|
|
596
|
+
/**
|
|
597
|
+
* GET/HEAD only, at most one retry per call. A callback's success is not trust:
|
|
598
|
+
* the validator re-evaluates the retried request. Refusal/timeout returns the
|
|
599
|
+
* original challenge response; caller cancellation and fetch errors reject.
|
|
600
|
+
*/
|
|
601
|
+
declare function createClearanceFetch(options: ClearanceFetchOptions): typeof fetch;
|
|
602
|
+
|
|
563
603
|
/**
|
|
564
604
|
* Behavioral human-likelihood for clearance minting .
|
|
565
605
|
*
|
|
@@ -626,4 +666,4 @@ declare function summarizeBehavior(collector: BehavioralCollector): BehaviorAggr
|
|
|
626
666
|
*/
|
|
627
667
|
declare function watchInteraction(onReady: (b: BehaviorAggregate) => void): () => void;
|
|
628
668
|
|
|
629
|
-
export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceOptions, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, getFormAnalyzer, getPoWManager, hasEnoughInteraction, sha256, startClearance, summarizeBehavior, watchInteraction };
|
|
669
|
+
export { type BehaviorAggregate, BehavioralCollector, CLEARANCE_COOKIE, CaptchaWidget, type Challenge, type ClearanceChallenge, type ClearanceChallengeReason, type ClearanceFetchEvent, type ClearanceFetchOptions, type ClearanceOptions, type ClearanceRecoveryContext, type CollectedSignals, DEFAULT_INGEST_URL, type DeviceFPInputs, EnvironmentalCollector, FP_VERSION, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, computeDeviceFP, createClearanceFetch, getFormAnalyzer, getPoWManager, hasEnoughInteraction, readClearanceChallenge, sha256, startClearance, summarizeBehavior, watchInteraction };
|
package/dist/index.js
CHANGED
|
@@ -33,9 +33,11 @@ __export(src_exports, {
|
|
|
33
33
|
TemporalCollector: () => TemporalCollector,
|
|
34
34
|
WebDecoyCaptcha: () => WebDecoyCaptcha,
|
|
35
35
|
computeDeviceFP: () => computeDeviceFP,
|
|
36
|
+
createClearanceFetch: () => createClearanceFetch,
|
|
36
37
|
getFormAnalyzer: () => getFormAnalyzer,
|
|
37
38
|
getPoWManager: () => getPoWManager,
|
|
38
39
|
hasEnoughInteraction: () => hasEnoughInteraction,
|
|
40
|
+
readClearanceChallenge: () => readClearanceChallenge,
|
|
39
41
|
sha256: () => sha256,
|
|
40
42
|
startClearance: () => startClearance,
|
|
41
43
|
summarizeBehavior: () => summarizeBehavior,
|
|
@@ -2666,3 +2668,123 @@ function startClearance(opts) {
|
|
|
2666
2668
|
startBehavioralUpgrade(session);
|
|
2667
2669
|
}
|
|
2668
2670
|
}
|
|
2671
|
+
|
|
2672
|
+
// src/clearance-fetch.ts
|
|
2673
|
+
var reasons = ["missing", "invalid", "insufficient-trust", "revoked", "crawler-refused", "agent-impersonation", "denied"];
|
|
2674
|
+
var recoverableReasons = ["missing", "invalid", "insufficient-trust"];
|
|
2675
|
+
function readClearanceChallenge(response) {
|
|
2676
|
+
if (response.status !== 403 || response.headers.get("x-wd-clearance") !== "challenged" || response.headers.get("x-wd-challenge") !== "1") return null;
|
|
2677
|
+
const reason = response.headers.get("x-wd-challenge-reason");
|
|
2678
|
+
const recovery = response.headers.get("x-wd-challenge-recoverable");
|
|
2679
|
+
if (!reason || !reasons.includes(reason) || recovery !== "true" && recovery !== "false") return null;
|
|
2680
|
+
return { version: 1, reason, recoverable: recovery === "true" && recoverableReasons.includes(reason) };
|
|
2681
|
+
}
|
|
2682
|
+
function abortError(signal) {
|
|
2683
|
+
var _a;
|
|
2684
|
+
return (_a = signal.reason) != null ? _a : new DOMException("The operation was aborted", "AbortError");
|
|
2685
|
+
}
|
|
2686
|
+
function abortable(promise, signal) {
|
|
2687
|
+
return new Promise((resolve, reject) => {
|
|
2688
|
+
if (signal.aborted) {
|
|
2689
|
+
reject(abortError(signal));
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
const onAbort = () => reject(abortError(signal));
|
|
2693
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2694
|
+
void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
2695
|
+
});
|
|
2696
|
+
}
|
|
2697
|
+
function createClearanceFetch(options) {
|
|
2698
|
+
var _a, _b;
|
|
2699
|
+
const parsedOrigin = new URL(options.origin);
|
|
2700
|
+
if (!["http:", "https:"].includes(parsedOrigin.protocol) || parsedOrigin.username || parsedOrigin.password || parsedOrigin.pathname !== "/" || parsedOrigin.search || parsedOrigin.hash) throw new TypeError("A protected HTTP(S) origin is required");
|
|
2701
|
+
const origin = parsedOrigin.origin;
|
|
2702
|
+
const timeoutMs = (_a = options.timeoutMs) != null ? _a : 1e4;
|
|
2703
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e4) throw new RangeError("timeoutMs must be between 1 and 60000");
|
|
2704
|
+
const nativeFetch = (_b = options.fetch) != null ? _b : globalThis.fetch.bind(globalThis);
|
|
2705
|
+
let recovery;
|
|
2706
|
+
function observe(type, method, challenge, status) {
|
|
2707
|
+
var _a2;
|
|
2708
|
+
try {
|
|
2709
|
+
(_a2 = options.onEvent) == null ? void 0 : _a2.call(options, { type, origin, method, challenge, status });
|
|
2710
|
+
} catch {
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
function joinRecovery(challenge) {
|
|
2714
|
+
if (!recovery) {
|
|
2715
|
+
const controller = new AbortController();
|
|
2716
|
+
const entry = { controller, users: 0, promise: Promise.resolve(false) };
|
|
2717
|
+
recovery = entry;
|
|
2718
|
+
const timer = setTimeout(() => controller.abort(new DOMException("Clearance recovery timed out", "TimeoutError")), timeoutMs);
|
|
2719
|
+
controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
|
|
2720
|
+
const actual = Promise.resolve().then(() => options.recover({ origin, challenge, signal: controller.signal }));
|
|
2721
|
+
entry.promise = abortable(actual, controller.signal).then((value) => value === true, () => false);
|
|
2722
|
+
const settled = () => {
|
|
2723
|
+
clearTimeout(timer);
|
|
2724
|
+
if (recovery === entry) recovery = void 0;
|
|
2725
|
+
};
|
|
2726
|
+
void actual.then(settled, settled);
|
|
2727
|
+
}
|
|
2728
|
+
recovery.users++;
|
|
2729
|
+
return recovery;
|
|
2730
|
+
}
|
|
2731
|
+
return async (input, init) => {
|
|
2732
|
+
var _a2, _b2;
|
|
2733
|
+
const method = ((_a2 = init == null ? void 0 : init.method) != null ? _a2 : input instanceof Request ? input.method : "GET").toUpperCase();
|
|
2734
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
2735
|
+
const response2 = await nativeFetch(input, init);
|
|
2736
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
2737
|
+
const target = new URL(url, typeof document !== "undefined" ? document.baseURI : void 0);
|
|
2738
|
+
const challenge2 = readClearanceChallenge(response2);
|
|
2739
|
+
if (challenge2 && target.origin === origin && !response2.redirected && (!response2.url || new URL(response2.url).origin === origin)) observe("challenge-served", method, challenge2, response2.status);
|
|
2740
|
+
return response2;
|
|
2741
|
+
}
|
|
2742
|
+
const requestInput = input instanceof Request ? input : new URL(String(input), typeof document !== "undefined" ? document.baseURI : void 0).href;
|
|
2743
|
+
const request = new Request(requestInput, init);
|
|
2744
|
+
const response = await nativeFetch(request);
|
|
2745
|
+
const challenge = readClearanceChallenge(response);
|
|
2746
|
+
if (!challenge || new URL(request.url).origin !== origin || response.redirected || response.url && new URL(response.url).origin !== origin) return response;
|
|
2747
|
+
observe("challenge-served", method, challenge, response.status);
|
|
2748
|
+
const pageOrigin = typeof location !== "undefined" ? location.origin : origin;
|
|
2749
|
+
if (!challenge.recoverable || request.credentials === "omit" || pageOrigin !== origin && request.credentials !== "include" || typeof navigator !== "undefined" && navigator.onLine === false || typeof AbortSignal.any !== "function") return response;
|
|
2750
|
+
if (request.signal.aborted) throw abortError(request.signal);
|
|
2751
|
+
const controller = new AbortController();
|
|
2752
|
+
let timedOut = false;
|
|
2753
|
+
const onAbort = () => controller.abort(abortError(request.signal));
|
|
2754
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
2755
|
+
const timer = setTimeout(() => {
|
|
2756
|
+
timedOut = true;
|
|
2757
|
+
controller.abort(new DOMException("Clearance recovery timed out", "TimeoutError"));
|
|
2758
|
+
}, timeoutMs);
|
|
2759
|
+
const entry = joinRecovery(challenge);
|
|
2760
|
+
observe("recovery-attempted", method, challenge);
|
|
2761
|
+
let released = false;
|
|
2762
|
+
const release = () => {
|
|
2763
|
+
if (released) return;
|
|
2764
|
+
released = true;
|
|
2765
|
+
if (--entry.users === 0) entry.controller.abort();
|
|
2766
|
+
};
|
|
2767
|
+
try {
|
|
2768
|
+
const ready = await abortable(entry.promise, controller.signal);
|
|
2769
|
+
release();
|
|
2770
|
+
if (!ready || controller.signal.aborted) {
|
|
2771
|
+
observe("recovery-failed", method, challenge);
|
|
2772
|
+
return response;
|
|
2773
|
+
}
|
|
2774
|
+
const retrySignal = AbortSignal.any([request.signal, controller.signal]);
|
|
2775
|
+
const retried = await abortable(nativeFetch(new Request(request, { signal: retrySignal })), controller.signal);
|
|
2776
|
+
observe("enforcement-outcome", method, (_b2 = readClearanceChallenge(retried)) != null ? _b2 : challenge, retried.status);
|
|
2777
|
+
observe(retried.ok ? "recovery-succeeded" : "recovery-failed", method, challenge, retried.status);
|
|
2778
|
+
return retried;
|
|
2779
|
+
} catch (error) {
|
|
2780
|
+
observe("recovery-failed", method, challenge);
|
|
2781
|
+
if (request.signal.aborted) throw abortError(request.signal);
|
|
2782
|
+
if (timedOut) return response;
|
|
2783
|
+
throw error;
|
|
2784
|
+
} finally {
|
|
2785
|
+
release();
|
|
2786
|
+
clearTimeout(timer);
|
|
2787
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
2788
|
+
}
|
|
2789
|
+
};
|
|
2790
|
+
}
|
package/dist/index.mjs
CHANGED
|
@@ -2621,6 +2621,126 @@ function startClearance(opts) {
|
|
|
2621
2621
|
startBehavioralUpgrade(session);
|
|
2622
2622
|
}
|
|
2623
2623
|
}
|
|
2624
|
+
|
|
2625
|
+
// src/clearance-fetch.ts
|
|
2626
|
+
var reasons = ["missing", "invalid", "insufficient-trust", "revoked", "crawler-refused", "agent-impersonation", "denied"];
|
|
2627
|
+
var recoverableReasons = ["missing", "invalid", "insufficient-trust"];
|
|
2628
|
+
function readClearanceChallenge(response) {
|
|
2629
|
+
if (response.status !== 403 || response.headers.get("x-wd-clearance") !== "challenged" || response.headers.get("x-wd-challenge") !== "1") return null;
|
|
2630
|
+
const reason = response.headers.get("x-wd-challenge-reason");
|
|
2631
|
+
const recovery = response.headers.get("x-wd-challenge-recoverable");
|
|
2632
|
+
if (!reason || !reasons.includes(reason) || recovery !== "true" && recovery !== "false") return null;
|
|
2633
|
+
return { version: 1, reason, recoverable: recovery === "true" && recoverableReasons.includes(reason) };
|
|
2634
|
+
}
|
|
2635
|
+
function abortError(signal) {
|
|
2636
|
+
var _a;
|
|
2637
|
+
return (_a = signal.reason) != null ? _a : new DOMException("The operation was aborted", "AbortError");
|
|
2638
|
+
}
|
|
2639
|
+
function abortable(promise, signal) {
|
|
2640
|
+
return new Promise((resolve, reject) => {
|
|
2641
|
+
if (signal.aborted) {
|
|
2642
|
+
reject(abortError(signal));
|
|
2643
|
+
return;
|
|
2644
|
+
}
|
|
2645
|
+
const onAbort = () => reject(abortError(signal));
|
|
2646
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2647
|
+
void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
2648
|
+
});
|
|
2649
|
+
}
|
|
2650
|
+
function createClearanceFetch(options) {
|
|
2651
|
+
var _a, _b;
|
|
2652
|
+
const parsedOrigin = new URL(options.origin);
|
|
2653
|
+
if (!["http:", "https:"].includes(parsedOrigin.protocol) || parsedOrigin.username || parsedOrigin.password || parsedOrigin.pathname !== "/" || parsedOrigin.search || parsedOrigin.hash) throw new TypeError("A protected HTTP(S) origin is required");
|
|
2654
|
+
const origin = parsedOrigin.origin;
|
|
2655
|
+
const timeoutMs = (_a = options.timeoutMs) != null ? _a : 1e4;
|
|
2656
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e4) throw new RangeError("timeoutMs must be between 1 and 60000");
|
|
2657
|
+
const nativeFetch = (_b = options.fetch) != null ? _b : globalThis.fetch.bind(globalThis);
|
|
2658
|
+
let recovery;
|
|
2659
|
+
function observe(type, method, challenge, status) {
|
|
2660
|
+
var _a2;
|
|
2661
|
+
try {
|
|
2662
|
+
(_a2 = options.onEvent) == null ? void 0 : _a2.call(options, { type, origin, method, challenge, status });
|
|
2663
|
+
} catch {
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
function joinRecovery(challenge) {
|
|
2667
|
+
if (!recovery) {
|
|
2668
|
+
const controller = new AbortController();
|
|
2669
|
+
const entry = { controller, users: 0, promise: Promise.resolve(false) };
|
|
2670
|
+
recovery = entry;
|
|
2671
|
+
const timer = setTimeout(() => controller.abort(new DOMException("Clearance recovery timed out", "TimeoutError")), timeoutMs);
|
|
2672
|
+
controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
|
|
2673
|
+
const actual = Promise.resolve().then(() => options.recover({ origin, challenge, signal: controller.signal }));
|
|
2674
|
+
entry.promise = abortable(actual, controller.signal).then((value) => value === true, () => false);
|
|
2675
|
+
const settled = () => {
|
|
2676
|
+
clearTimeout(timer);
|
|
2677
|
+
if (recovery === entry) recovery = void 0;
|
|
2678
|
+
};
|
|
2679
|
+
void actual.then(settled, settled);
|
|
2680
|
+
}
|
|
2681
|
+
recovery.users++;
|
|
2682
|
+
return recovery;
|
|
2683
|
+
}
|
|
2684
|
+
return async (input, init) => {
|
|
2685
|
+
var _a2, _b2;
|
|
2686
|
+
const method = ((_a2 = init == null ? void 0 : init.method) != null ? _a2 : input instanceof Request ? input.method : "GET").toUpperCase();
|
|
2687
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
2688
|
+
const response2 = await nativeFetch(input, init);
|
|
2689
|
+
const url = input instanceof Request ? input.url : String(input);
|
|
2690
|
+
const target = new URL(url, typeof document !== "undefined" ? document.baseURI : void 0);
|
|
2691
|
+
const challenge2 = readClearanceChallenge(response2);
|
|
2692
|
+
if (challenge2 && target.origin === origin && !response2.redirected && (!response2.url || new URL(response2.url).origin === origin)) observe("challenge-served", method, challenge2, response2.status);
|
|
2693
|
+
return response2;
|
|
2694
|
+
}
|
|
2695
|
+
const requestInput = input instanceof Request ? input : new URL(String(input), typeof document !== "undefined" ? document.baseURI : void 0).href;
|
|
2696
|
+
const request = new Request(requestInput, init);
|
|
2697
|
+
const response = await nativeFetch(request);
|
|
2698
|
+
const challenge = readClearanceChallenge(response);
|
|
2699
|
+
if (!challenge || new URL(request.url).origin !== origin || response.redirected || response.url && new URL(response.url).origin !== origin) return response;
|
|
2700
|
+
observe("challenge-served", method, challenge, response.status);
|
|
2701
|
+
const pageOrigin = typeof location !== "undefined" ? location.origin : origin;
|
|
2702
|
+
if (!challenge.recoverable || request.credentials === "omit" || pageOrigin !== origin && request.credentials !== "include" || typeof navigator !== "undefined" && navigator.onLine === false || typeof AbortSignal.any !== "function") return response;
|
|
2703
|
+
if (request.signal.aborted) throw abortError(request.signal);
|
|
2704
|
+
const controller = new AbortController();
|
|
2705
|
+
let timedOut = false;
|
|
2706
|
+
const onAbort = () => controller.abort(abortError(request.signal));
|
|
2707
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
2708
|
+
const timer = setTimeout(() => {
|
|
2709
|
+
timedOut = true;
|
|
2710
|
+
controller.abort(new DOMException("Clearance recovery timed out", "TimeoutError"));
|
|
2711
|
+
}, timeoutMs);
|
|
2712
|
+
const entry = joinRecovery(challenge);
|
|
2713
|
+
observe("recovery-attempted", method, challenge);
|
|
2714
|
+
let released = false;
|
|
2715
|
+
const release = () => {
|
|
2716
|
+
if (released) return;
|
|
2717
|
+
released = true;
|
|
2718
|
+
if (--entry.users === 0) entry.controller.abort();
|
|
2719
|
+
};
|
|
2720
|
+
try {
|
|
2721
|
+
const ready = await abortable(entry.promise, controller.signal);
|
|
2722
|
+
release();
|
|
2723
|
+
if (!ready || controller.signal.aborted) {
|
|
2724
|
+
observe("recovery-failed", method, challenge);
|
|
2725
|
+
return response;
|
|
2726
|
+
}
|
|
2727
|
+
const retrySignal = AbortSignal.any([request.signal, controller.signal]);
|
|
2728
|
+
const retried = await abortable(nativeFetch(new Request(request, { signal: retrySignal })), controller.signal);
|
|
2729
|
+
observe("enforcement-outcome", method, (_b2 = readClearanceChallenge(retried)) != null ? _b2 : challenge, retried.status);
|
|
2730
|
+
observe(retried.ok ? "recovery-succeeded" : "recovery-failed", method, challenge, retried.status);
|
|
2731
|
+
return retried;
|
|
2732
|
+
} catch (error) {
|
|
2733
|
+
observe("recovery-failed", method, challenge);
|
|
2734
|
+
if (request.signal.aborted) throw abortError(request.signal);
|
|
2735
|
+
if (timedOut) return response;
|
|
2736
|
+
throw error;
|
|
2737
|
+
} finally {
|
|
2738
|
+
release();
|
|
2739
|
+
clearTimeout(timer);
|
|
2740
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
2741
|
+
}
|
|
2742
|
+
};
|
|
2743
|
+
}
|
|
2624
2744
|
export {
|
|
2625
2745
|
BehavioralCollector,
|
|
2626
2746
|
CLEARANCE_COOKIE,
|
|
@@ -2635,9 +2755,11 @@ export {
|
|
|
2635
2755
|
TemporalCollector,
|
|
2636
2756
|
WebDecoyCaptcha,
|
|
2637
2757
|
computeDeviceFP,
|
|
2758
|
+
createClearanceFetch,
|
|
2638
2759
|
getFormAnalyzer,
|
|
2639
2760
|
getPoWManager,
|
|
2640
2761
|
hasEnoughInteraction,
|
|
2762
|
+
readClearanceChallenge,
|
|
2641
2763
|
sha256,
|
|
2642
2764
|
startClearance,
|
|
2643
2765
|
summarizeBehavior,
|
package/dist/webdecoy.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var WebDecoyCaptchaBundle=(()=>{var j=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ae=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var le=(r,e)=>{for(var t in e)j(r,t,{get:e[t],enumerable:!0})},ue=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ae(e))!ce.call(r,i)&&i!==t&&j(r,i,{get:()=>e[i],enumerable:!(n=se(e,i))||n.enumerable});return r};var he=r=>ue(j({},"__esModule",{value:!0}),r);var Se={};le(Se,{WebDecoyCaptcha:()=>V});var M=class{constructor(){this.mousePositions=[],this.mouseVelocities=[],this.mouseAccelerations=[],this.scrollEvents=[],this.keyEvents=[],this.touchEvents=[],this.touchMultiTouchSeen=!1,this.touchIdentifiers=new Set,this.pointerPoints=[],this.focusEvents=[],this.clickData=null,this.startTime=Date.now(),this.lastMousePos=null,this.lastMouseTime=null,this.lastVelocity=null,this.eventDeltas=[]}recordMouseMove(e){let t=performance.now(),n={x:e.clientX,y:e.clientY,t};if(this.mousePositions.push(n),this.lastMousePos&&this.lastMouseTime){let i=t-this.lastMouseTime;if(i>0){let o=e.clientX-this.lastMousePos.x,s=e.clientY-this.lastMousePos.y,c=Math.sqrt(o*o+s*s)/i;if(this.mouseVelocities.push({v:c,t}),this.eventDeltas.push(i),this.lastVelocity!==null){let l=(c-this.lastVelocity)/i;this.mouseAccelerations.push({a:l,t})}this.lastVelocity=c}}this.lastMousePos={x:e.clientX,y:e.clientY},this.lastMouseTime=t,this.mousePositions.length>500&&(this.mousePositions.shift(),this.mouseVelocities.length>500&&this.mouseVelocities.shift(),this.mouseAccelerations.length>500&&this.mouseAccelerations.shift())}recordMouseDown(e){this.clickData={x:e.clientX,y:e.clientY,button:e.button,downTime:performance.now()}}recordMouseUp(e){this.clickData&&(this.clickData.upTime=performance.now(),this.clickData.holdDuration=this.clickData.upTime-this.clickData.downTime)}recordScroll(e){this.scrollEvents.push({x:window.scrollX,y:window.scrollY,t:performance.now()}),this.scrollEvents.length>100&&this.scrollEvents.shift()}recordKeyEvent(e){this.keyEvents.push({type:e.type,keyLength:e.key?e.key.length:0,t:performance.now()})}recordTouch(e){let t=e.touches&&e.touches.length?e.touches:e.changedTouches;if(!t||t.length===0)return;t.length>1&&(this.touchMultiTouchSeen=!0);let n=t[0];typeof n.identifier=="number"&&this.touchIdentifiers.add(n.identifier),this.touchEvents.push({x:n.clientX,y:n.clientY,t:performance.now(),force:typeof n.force=="number"?n.force:0,radiusX:typeof n.radiusX=="number"?n.radiusX:0,radiusY:typeof n.radiusY=="number"?n.radiusY:0,rotationAngle:typeof n.rotationAngle=="number"?n.rotationAngle:0,identifier:typeof n.identifier=="number"?n.identifier:-1,touchCount:t.length}),this.touchEvents.length>500&&this.touchEvents.shift()}recordPointer(e){this.pointerPoints.push({x:e.clientX,y:e.clientY,t:performance.now(),type:e.type,pressure:typeof e.pressure=="number"?e.pressure:0,tiltX:typeof e.tiltX=="number"?e.tiltX:0,tiltY:typeof e.tiltY=="number"?e.tiltY:0,tangentialPressure:typeof e.tangentialPressure=="number"?e.tangentialPressure:0,pointerType:e.pointerType||"unknown"}),this.pointerPoints.length>500&&this.pointerPoints.shift()}recordFocus(e){var t;this.focusEvents.push({type:e.type,target:(t=e.target)==null?void 0:t.tagName,t:performance.now()})}analyze(){let e=this.mousePositions,t=this.mouseVelocities,n=this.mouseAccelerations;if(e.length<10)return this._getEmptyAnalysis();let i=0,o=0;t.length>0&&(i=t.reduce((f,d)=>f+d.v,0)/t.length,o=t.reduce((f,d)=>f+Math.pow(d.v-i,2),0)/t.length);let s=0,a=0;if(n.length>0){s=n.reduce((m,f)=>m+f.a,0)/n.length;for(let m=1;m<n.length;m++)Math.sign(n[m].a)!==Math.sign(n[m-1].a)&&a++}let c=this._detectMicroTremor(e),l=this._calculateStraightLineRatio(e),u=0;for(let m=1;m<e.length;m++){let f=Math.abs(e[m].x-e[m-1].x),d=Math.abs(e[m].y-e[m-1].y);f<3&&d<3&&(f>0||d>0)&&u++}let h=this._countDirectionChanges(e),v=this._variance(this.eventDeltas),p=e.length>1?e.length/((e[e.length-1].t-e[0].t)/1e3):0,b=0;for(let m=1;m<e.length;m++){let f=e[m].x-e[m-1].x,d=e[m].y-e[m-1].y;b+=Math.sqrt(f*f+d*d)}let E=this._analyzeTouchPoints(this.touchEvents),S=this._analyzePointerPoints(this.pointerPoints);return{totalPoints:e.length,trajectoryLength:b,avgVelocity:i,velocityVariance:o,avgAcceleration:s,accelerationChanges:a,microTremorScore:c,straightLineRatio:l,microMovements:u,directionChanges:h,eventDeltas:this.eventDeltas.slice(-50),eventDeltaVariance:v,mouseEventRate:p,scrollEvents:this.scrollEvents.length,keyEvents:this.keyEvents.length,touchEvents:this.touchEvents.length,focusEvents:this.focusEvents.length,clickData:this.clickData,interactionDuration:Date.now()-this.startTime,...E,...S}}_analyzeTouchPoints(e){if(!e||e.length===0)return{touchTotalPoints:0,touchTrajectoryLength:0,touchAvgVelocity:0,touchVelocityVariance:0,touchMicroTremorScore:0,touchStraightLineRatio:0,touchDirectionChanges:0,touchForceMin:0,touchForceMax:0,touchForceVariance:0,touchRadiusMin:0,touchRadiusMax:0,touchRadiusVariance:0,touchMultiTouchSeen:this.touchMultiTouchSeen,touchUniqueIdentifiers:this.touchIdentifiers.size,touchForceAllZero:!1,touchForceAllOne:!1};let t=0,n=[];for(let l=1;l<e.length;l++){let u=e[l].x-e[l-1].x,h=e[l].y-e[l-1].y,v=Math.sqrt(u*u+h*h);t+=v;let p=e[l].t-e[l-1].t;p>0&&n.push(v/p)}let i=n.length>0?n.reduce((l,u)=>l+u,0)/n.length:0,o=e.map(l=>l.force),s=e.map(l=>Math.max(l.radiusX||0,l.radiusY||0)),a=o.length>0&&o.every(l=>l===0),c=o.length>0&&o.every(l=>l===1);return{touchTotalPoints:e.length,touchTrajectoryLength:t,touchAvgVelocity:i,touchVelocityVariance:this._variance(n),touchMicroTremorScore:this._detectMicroTremor(e),touchStraightLineRatio:this._calculateStraightLineRatio(e),touchDirectionChanges:this._countDirectionChanges(e),touchForceMin:o.length>0?Math.min(...o):0,touchForceMax:o.length>0?Math.max(...o):0,touchForceVariance:this._variance(o),touchRadiusMin:s.length>0?Math.min(...s):0,touchRadiusMax:s.length>0?Math.max(...s):0,touchRadiusVariance:this._variance(s),touchMultiTouchSeen:this.touchMultiTouchSeen,touchUniqueIdentifiers:this.touchIdentifiers.size,touchForceAllZero:a,touchForceAllOne:c}}_analyzePointerPoints(e){if(!e||e.length===0)return{pointerEvents:0,pointerAvgPressure:0,pointerPressureVariance:0,pointerMaxTilt:0,pointerHasNonMouseType:!1,pointerTypes:[]};let t=e.map(s=>s.pressure),n=t.length>0?t.reduce((s,a)=>s+a,0)/t.length:0,i=0,o=new Set;for(let s of e){let a=Math.abs(s.tiltX||0)+Math.abs(s.tiltY||0);a>i&&(i=a),s.pointerType&&o.add(s.pointerType)}return{pointerEvents:e.length,pointerAvgPressure:n,pointerPressureVariance:this._variance(t),pointerMaxTilt:i,pointerHasNonMouseType:Array.from(o).some(s=>s!=="mouse"&&s!=="unknown"),pointerTypes:Array.from(o)}}analyzeClick(e,t,n){let i=this.mousePositions;if(i.length<5)return this._getEmptyClickAnalysis();let o=i.slice(-20),s=n.left+n.width/2,a=n.top+n.height/2,c=Math.sqrt(Math.pow(e-s,2)+Math.pow(t-a,2)),l=0,u=0;for(let d=1;d<i.length;d++){let g=Math.sqrt(Math.pow(i[d].x-i[d-1].x,2)+Math.pow(i[d].y-i[d-1].y,2));u+=g,i[d].x>=n.left&&i[d].x<=n.right&&i[d].y>=n.top&&i[d].y<=n.bottom||(l+=g)}let h=u>0?l/u:0,v=0,p=!1,b=!1;for(let d of o){let g=d.x>=n.left&&d.x<=n.right&&d.y>=n.top&&d.y<=n.bottom;p&&!g&&(b=!0),b&&g&&(v++,b=!1),p=g}let E=0;for(let d=o.length-1;d>=0;d--){let g=o[d],O=g.x>=n.left&&g.x<=n.right&&g.y>=n.top&&g.y<=n.bottom;if(O&&d<o.length-1)E=o[o.length-1].t-g.t;else if(!O)break}let S=Math.sqrt(Math.pow(o[o.length-1].x-o[0].x,2)+Math.pow(o[o.length-1].y-o[0].y,2)),m=0;for(let d=1;d<o.length;d++)m+=Math.sqrt(Math.pow(o[d].x-o[d-1].x,2)+Math.pow(o[d].y-o[d-1].y,2));let f=m>0?S/m:1;return{clickPrecision:c,explorationRatio:h,overshootCorrections:v,hoverTime:E,approachDirectness:f,approachPoints:o.length}}_detectMicroTremor(e){if(e.length<20)return .5;let t=5,n=0;for(let o=t;o<e.length-t;o++){let s=0,a=0;for(let l=o-t;l<=o+t;l++)s+=e[l].x,a+=e[l].y;s/=t*2+1,a/=t*2+1;let c=Math.sqrt(Math.pow(e[o].x-s,2)+Math.pow(e[o].y-a,2));n+=c}let i=n/(e.length-t*2);return Math.min(1,i/2)}_calculateStraightLineRatio(e){if(e.length<3)return 0;let t=0,n=0;for(let i=2;i<e.length;i++){let o=e[i-2],s=e[i-1],a=e[i],c=Math.atan2(s.y-o.y,s.x-o.x),l=Math.atan2(a.y-s.y,a.x-s.x),u=Math.abs(l-c);n++,u<.1&&t++}return n>0?t/n:0}_countDirectionChanges(e){let t=0;for(let n=2;n<e.length;n++){let i=Math.atan2(e[n-1].y-e[n-2].y,e[n-1].x-e[n-2].x),o=Math.atan2(e[n].y-e[n-1].y,e[n].x-e[n-1].x);Math.abs(o-i)>Math.PI/6&&t++}return t}_variance(e){if(e.length===0)return 0;let t=e.reduce((n,i)=>n+i,0)/e.length;return e.reduce((n,i)=>n+Math.pow(i-t,2),0)/e.length}_getEmptyAnalysis(){return{totalPoints:0,trajectoryLength:0,avgVelocity:0,velocityVariance:0,avgAcceleration:0,accelerationChanges:0,microTremorScore:.5,straightLineRatio:0,microMovements:0,directionChanges:0,eventDeltas:[],eventDeltaVariance:0,mouseEventRate:0,scrollEvents:this.scrollEvents.length,keyEvents:this.keyEvents.length,touchEvents:this.touchEvents.length,focusEvents:this.focusEvents.length,clickData:this.clickData,interactionDuration:Date.now()-this.startTime,...this._analyzeTouchPoints(this.touchEvents),...this._analyzePointerPoints(this.pointerPoints)}}_getEmptyClickAnalysis(){return{clickPrecision:0,explorationRatio:0,overshootCorrections:0,hoverTime:0,approachDirectness:1,approachPoints:0}}};var _=class{collect(){return{webdriver:this._detectWebdriver(),automationFlags:this._getAutomationFlags(),cdp:this._detectCDP(),playwright:this._detectPlaywright(),canvasHash:this._getCanvasHash(),webglInfo:this._getWebGLInfo(),audioInfo:this._getAudioInfo(),headlessIndicators:this._getHeadlessIndicators(),screen:this._getScreenInfo(),navigator:this._getNavigatorInfo(),jsExecutionTime:this._measureJSExecution(),mathFingerprint:this._getMathFingerprint(),errorFingerprint:this._getErrorFingerprint(),domRectFingerprint:this._getDOMRectFingerprint(),cssMediaQueries:this._getCSSMediaQueries(),permissionsInfo:this._getPermissionsInfo(),fontsInfo:this._getFontsInfo(),lieDetection:this._getLieDetection()}}async collectAsync(){let[e,t,n]=await Promise.all([this._getSpeechInfo(),this._getWebRTCInfo(),this._checkWorkerConsistency()]);return{speechInfo:e,webrtcInfo:t,workerConsistency:n}}_detectWebdriver(){let e=navigator,t=window;return!!(e.webdriver||t.document.__webdriver_evaluate||t.document.__selenium_evaluate||t.document.__webdriver_script_fn||t.document.__webdriver_script_func||t.document.__webdriver_script_function||t.document.$cdc_asdjflasutopfhvcZLmcfl_||t.document.$wdc_||t._Selenium_IDE_Recorder||t._phantom||t.__nightmare||t.callPhantom||t._phantom)}_getAutomationFlags(){let e=navigator,t=window;return{webdriver:!!e.webdriver,domAutomation:!!t.domAutomation,domAutomationController:!!t.domAutomationController,_selenium:!!t._selenium,__webdriver_script_fn:!!t.__webdriver_script_fn,__driver_evaluate:!!t.__driver_evaluate,__webdriver_evaluate:!!t.__webdriver_evaluate,__fxdriver_evaluate:!!t.__fxdriver_evaluate,__driver_unwrapped:!!t.__driver_unwrapped,__webdriver_unwrapped:!!t.__webdriver_unwrapped,__fxdriver_unwrapped:!!t.__fxdriver_unwrapped,_Selenium_IDE_Recorder:!!t._Selenium_IDE_Recorder,calledSelenium:!!t.calledSelenium,$chrome_asyncScriptInfo:!!t.$chrome_asyncScriptInfo,$cdc_asdjflasutopfhvcZLmcfl_:!!t.$cdc_asdjflasutopfhvcZLmcfl_,_phantom:!!t._phantom,callPhantom:!!t.callPhantom,__nightmare:!!t.__nightmare,__lastWatirAlert:!!t.__lastWatirAlert,__lastWatirConfirm:!!t.__lastWatirConfirm,__lastWatirPrompt:!!t.__lastWatirPrompt,plugins:navigator.plugins?navigator.plugins.length:0,languages:navigator.languages&&navigator.languages.length>0,mimeTypes:navigator.mimeTypes?navigator.mimeTypes.length:0,cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,chrome:!!t.chrome,chromeRuntime:!!(t.chrome&&t.chrome.runtime&&t.chrome.runtime.id),permissionsAPI:!!navigator.permissions}}_detectPlaywright(){try{let e=[];Object.getOwnPropertyNames(window).filter(o=>o.startsWith("__pw")||o.startsWith("__playwright")).length>0&&e.push("playwright_globals");let n=Object.getPrototypeOf(navigator);return Object.getOwnPropertyDescriptor(n,"webdriver")||e.push("webdriver_deleted"),{detected:e.length>0,signals:e}}catch{return{detected:!1,signals:[]}}}_detectCDP(){try{let e=[];Object.keys(window).filter(n=>n.startsWith("cdc_")).length>0&&e.push("chromedriver_cdc"),"__webdriver_evaluate"in window&&e.push("selenium_evaluate"),"__driver_evaluate"in window&&e.push("selenium_driver_evaluate"),"__webdriver_unwrapped"in window&&e.push("selenium_unwrapped"),"__driver_unwrapped"in window&&e.push("selenium_driver_unwrapped"),"__selenium_evaluate"in window&&e.push("selenium_direct"),"__fxdriver_evaluate"in window&&e.push("firefox_driver"),"__fxdriver_unwrapped"in window&&e.push("firefox_driver_unwrapped"),"__puppeteer_evaluation_script__"in window&&e.push("puppeteer_eval"),document.__webdriver_script_fn&&e.push("cdp_script_injection");try{let n=Object.getOwnPropertyDescriptor(navigator,"webdriver");n&&typeof n.get=="function"&&n.get.toString().indexOf("[native code]")===-1&&e.push("webdriver_getter_modified")}catch{}return{detected:e.length>0,signals:e}}catch{return{detected:!1,signals:[]}}}_getCanvasHash(){try{let e=document.createElement("canvas");e.width=200,e.height=50;let t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("FCaptcha",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("FCaptcha",4,17);let n=e.toDataURL(),i=0;for(let o=0;o<n.length;o++)i=(i<<5)-i+n.charCodeAt(o),i=i&i;return{hash:i.toString(16),dataLength:n.length,supported:!0}}catch{return{error:!0,supported:!1}}}_getWebGLInfo(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{supported:!1};let n=t.getExtension("WEBGL_debug_renderer_info"),i=n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown",o=n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown",s=o.toLowerCase(),a=s.includes("swiftshader")||s.includes("llvmpipe")||s.includes("softpipe")||s.includes("virtualbox")||s.includes("vmware");return{supported:!0,vendor:i,renderer:o,version:t.getParameter(t.VERSION),shadingVersion:t.getParameter(t.SHADING_LANGUAGE_VERSION),suspiciousRenderer:a}}catch{return{supported:!1,error:!0}}}_getAudioInfo(){try{let e=window,t=e.AudioContext||e.webkitAudioContext;if(!t)return{supported:!1};let n=new t,i={supported:!0,sampleRate:n.sampleRate,state:n.state,baseLatency:n.baseLatency};return n.close().catch(()=>{}),i}catch{return{supported:!1,error:!0}}}_getLieDetection(){try{let e=window,t=[],n=o=>{try{return typeof o=="function"&&o.toString().indexOf("[native code]")===-1}catch{return!1}},i=(o,s)=>{n(o)&&t.push(s)};i(Function.prototype.toString,"Function.prototype.toString"),i(navigator.permissions&&navigator.permissions.query,"navigator.permissions.query"),i(e.Notification&&e.Notification.requestPermission,"Notification.requestPermission"),i(e.HTMLCanvasElement&&e.HTMLCanvasElement.prototype.toDataURL,"HTMLCanvasElement.toDataURL"),i(e.WebGLRenderingContext&&e.WebGLRenderingContext.prototype.getParameter,"WebGLRenderingContext.getParameter"),i(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices,"mediaDevices.enumerateDevices");try{let o=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(navigator),"webdriver")||Object.getOwnPropertyDescriptor(navigator,"webdriver");o&&typeof o.get=="function"&&o.get.toString().indexOf("[native code]")===-1&&t.push("navigator.webdriver getter")}catch{}return{supported:!0,patched:t,patchedCount:t.length}}catch{return{supported:!1}}}_getHeadlessIndicators(){let e=navigator;return{hasOuterDimensions:window.outerWidth>0&&window.outerHeight>0,innerEqualsOuter:window.innerWidth===window.outerWidth&&window.innerHeight===window.outerHeight,screenColorDepth:window.screen.colorDepth,screenPixelDepth:window.screen.pixelDepth,connectionType:e.connection?e.connection.type:"unknown",connectionRtt:e.connection?e.connection.rtt:-1,notificationPermission:typeof Notification!="undefined"?Notification.permission:"unsupported",hasBattery:"getBattery"in navigator,hasCredentials:"credentials"in navigator,hasMediaDevices:"mediaDevices"in navigator}}_getScreenInfo(){return{width:screen.width,height:screen.height,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio,availWidth:screen.availWidth,availHeight:screen.availHeight,innerWidth:window.innerWidth,innerHeight:window.innerHeight}}_getNavigatorInfo(){var t;let e=navigator;return{language:navigator.language,languageCount:((t=navigator.languages)==null?void 0:t.length)||0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:e.deviceMemory,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()}}_measureJSExecution(){let e={},t=performance.now(),n=0;for(let s=0;s<1e3;s++)n+=Math.sqrt(s)*Math.sin(s);e.mathOps=performance.now()-t,e.mathSink=n,t=performance.now();let i=[];for(let s=0;s<1e3;s++)i.push(s);e.arrayOps=performance.now()-t,e.arrayLen=i.length,t=performance.now();let o="";for(let s=0;s<100;s++)o+="a";return e.stringOps=performance.now()-t,e.stringLen=o.length,e}async measureRAFConsistency(){return new Promise(e=>{let t=[],n=0,i=10;function o(s){if(t.push(s),n++,n<i)requestAnimationFrame(o);else{let a=[];for(let u=1;u<t.length;u++)a.push(t[u]-t[u-1]);let c=a.reduce((u,h)=>u+h,0)/a.length,l=a.reduce((u,h)=>u+Math.pow(h-c,2),0)/a.length;e({avgFrameTime:c,frameTimeVariance:l,frames:i})}}requestAnimationFrame(o)})}_getMathFingerprint(){try{let e={acos:Math.acos(.123456789),acosh:Math.acosh(1e308),asin:Math.asin(.123456789),asinh:Math.asinh(1),atanh:Math.atanh(.5),cbrt:Math.cbrt(100),cosh:Math.cosh(1),expm1:Math.expm1(1),log1p:Math.log1p(10),sinh:Math.sinh(1),tan:Math.tan(-1e308),tanh:Math.tanh(1),pow:Math.pow(Math.PI,-100),sin:Math.sin(Math.PI)},t=Object.values(e).map(i=>String(i)).join(","),n=0;for(let i=0;i<t.length;i++)n=(n<<5)-n+t.charCodeAt(i),n=n&n;return{hash:n.toString(16),sinPi:e.sin,tanLarge:e.tan,supported:!0}}catch{return{supported:!1,error:!0}}}_getErrorFingerprint(){try{let e={};try{null.foo}catch(i){e.typeError=i.message}try{[].length=-1}catch(i){e.rangeError=i.message}try{decodeURIComponent("%")}catch(i){e.uriError=i.message}try{({}).undefinedMethod()}catch(i){e.refTypeError=i.message}let t=Object.values(e).join("|"),n=0;for(let i=0;i<t.length;i++)n=(n<<5)-n+t.charCodeAt(i),n=n&n;return{hash:n.toString(16),typeError:e.typeError,supported:!0}}catch{return{supported:!1,error:!0}}}_getDOMRectFingerprint(){try{let e=document.createElement("div");e.style.cssText="position:absolute;left:-9999px;font-size:16px;font-family:Arial,sans-serif;";let t=document.createElement("span");t.textContent="FCaptcha Test String 123",e.appendChild(t);let n=document.createElement("span");n.style.cssText="letter-spacing:1px;word-spacing:2px;",n.textContent="WWWW 0000",e.appendChild(n),document.body.appendChild(e);let i=t.getBoundingClientRect(),o=n.getBoundingClientRect(),s=document.createRange();s.selectNode(t);let a=s.getBoundingClientRect();document.body.removeChild(e);let l=[i.width,i.height,i.x,i.y,o.width,o.height,a.width,a.height].map(h=>h.toFixed(6)).join(","),u=0;for(let h=0;h<l.length;h++)u=(u<<5)-u+l.charCodeAt(h),u=u&u;return{hash:u.toString(16),rectAWidth:i.width,rectBWidth:o.width,rangeWidth:a.width,supported:!0}}catch{return{supported:!1,error:!0}}}_getCSSMediaQueries(){try{return{...{prefersColorScheme:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",prefersReducedMotion:window.matchMedia("(prefers-reduced-motion: reduce)").matches,prefersReducedTransparency:window.matchMedia("(prefers-reduced-transparency: reduce)").matches,prefersContrast:window.matchMedia("(prefers-contrast: more)").matches?"more":window.matchMedia("(prefers-contrast: less)").matches?"less":"no-preference",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":window.matchMedia("(any-pointer: coarse)").matches?"coarse":"none",hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":window.matchMedia("(pointer: coarse)").matches?"coarse":"none",colorGamut:window.matchMedia("(color-gamut: p3)").matches?"p3":window.matchMedia("(color-gamut: srgb)").matches?"srgb":"none",displayMode:window.matchMedia("(display-mode: standalone)").matches?"standalone":window.matchMedia("(display-mode: fullscreen)").matches?"fullscreen":"browser",orientation:window.matchMedia("(orientation: portrait)").matches?"portrait":"landscape",dynamicRange:window.matchMedia("(dynamic-range: high)").matches?"high":"standard",forcedColors:window.matchMedia("(forced-colors: active)").matches},supported:!0}}catch{return{supported:!1,error:!0}}}_getPermissionsInfo(){try{return{hasPermissionsAPI:"permissions"in navigator,hasClipboard:"clipboard"in navigator,hasShare:"share"in navigator,hasCredentials:"credentials"in navigator,hasBluetooth:"bluetooth"in navigator,hasUsb:"usb"in navigator,hasSerial:"serial"in navigator,hasHid:"hid"in navigator,hasXR:"xr"in navigator,hasGeolocation:"geolocation"in navigator,hasMIDI:"requestMIDIAccess"in navigator,supported:!0}}catch{return{supported:!1,error:!0}}}_getFontsInfo(){try{let e=["monospace","sans-serif","serif"],t=["Arial","Helvetica","Times New Roman","Courier New","Georgia","Verdana","Trebuchet MS","Comic Sans MS","Impact","Lucida Console","Menlo","Monaco","SF Pro","Helvetica Neue","Segoe UI","Consolas","Calibri","Cambria","DejaVu Sans","Liberation Sans","Ubuntu","Cantarell","MS Gothic","Meiryo","SimHei","Microsoft YaHei"],n=document.createElement("canvas");n.width=400,n.height=40;let i=n.getContext("2d"),o="mmMWWLLiiff00",s="72px",a={};for(let h of e)i.font=s+" "+h,a[h]=i.measureText(o).width;let c=[];for(let h of t){let v=!1;for(let p of e)if(i.font=s+' "'+h+'", '+p,i.measureText(o).width!==a[p]){v=!0;break}v&&c.push(h)}let l=c.join(","),u=0;for(let h=0;h<l.length;h++)u=(u<<5)-u+l.charCodeAt(h),u=u&u;return{hash:u.toString(16),count:c.length,hasArial:c.includes("Arial"),hasTimesNewRoman:c.includes("Times New Roman"),hasSegoeUI:c.includes("Segoe UI"),hasSFPro:c.includes("SF Pro"),hasDejaVuSans:c.includes("DejaVu Sans"),supported:!0}}catch{return{supported:!1,error:!0}}}async _getSpeechInfo(){try{if(!("speechSynthesis"in window))return{supported:!1};let t=await new Promise(c=>{let l=speechSynthesis.getVoices();if(l.length>0){c(l);return}let u=setTimeout(()=>c([]),1e3);speechSynthesis.onvoiceschanged=()=>{clearTimeout(u),c(speechSynthesis.getVoices())}}),n=t.filter(c=>c.localService),i=t.find(c=>c.default),o=[...new Set(t.map(c=>c.lang))],s=t.map(c=>c.name).sort().join(","),a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c),a=a&a;return{hash:a.toString(16),totalVoices:t.length,localVoices:n.length,languages:o.length,defaultVoiceLang:(i==null?void 0:i.lang)||null,hasGoogleVoices:t.some(c=>c.name.includes("Google")),hasMicrosoftVoices:t.some(c=>c.name.includes("Microsoft")),hasAppleVoices:t.some(c=>c.name.includes("Samantha")||c.name.includes("Alex")),supported:!0}}catch{return{supported:!1,error:!0}}}async _getWebRTCInfo(){try{let e={supported:"RTCPeerConnection"in window,mediaDevices:{supported:!1},localIPs:[]};if(!e.supported)return e;if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices)try{let t=await navigator.mediaDevices.enumerateDevices();e.mediaDevices={supported:!0,audioInputs:t.filter(n=>n.kind==="audioinput").length,audioOutputs:t.filter(n=>n.kind==="audiooutput").length,videoInputs:t.filter(n=>n.kind==="videoinput").length,totalDevices:t.length}}catch{e.mediaDevices={supported:!1,error:!0}}try{let t=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}),n=new Set;t.onicecandidate=i=>{if(i.candidate){let o=i.candidate.candidate,s=/([0-9]{1,3}\.){3}[0-9]{1,3}/g,a=o.match(s);a&&a.forEach(c=>{(c.startsWith("192.168.")||c.startsWith("10.")||c.startsWith("172.")||c.startsWith("169.254."))&&n.add(c)})}},t.createDataChannel(""),await t.createOffer().then(i=>t.setLocalDescription(i)),await new Promise(i=>setTimeout(i,500)),e.localIPs=Array.from(n),e.hasLocalIP=n.size>0,t.close()}catch{e.localIPError=!0}return e}catch{return{supported:!1,error:!0}}}async _checkWorkerConsistency(){try{if(typeof Worker=="undefined")return{supported:!1};let e=navigator,t=`
|
|
1
|
+
"use strict";var WebDecoyCaptchaBundle=(()=>{var G=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var be=Object.prototype.hasOwnProperty;var _e=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},Ee=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of we(e))!be.call(r,o)&&o!==t&&G(r,o,{get:()=>e[o],enumerable:!(n=ye(e,o))||n.enumerable});return r};var xe=r=>Ee(G({},"__esModule",{value:!0}),r);var Ke={};_e(Ke,{WebDecoyCaptcha:()=>z,createClearanceFetch:()=>te,readClearanceChallenge:()=>H});var M=class{constructor(){this.mousePositions=[],this.mouseVelocities=[],this.mouseAccelerations=[],this.scrollEvents=[],this.keyEvents=[],this.touchEvents=[],this.touchMultiTouchSeen=!1,this.touchIdentifiers=new Set,this.pointerPoints=[],this.focusEvents=[],this.clickData=null,this.startTime=Date.now(),this.lastMousePos=null,this.lastMouseTime=null,this.lastVelocity=null,this.eventDeltas=[]}recordMouseMove(e){let t=performance.now(),n={x:e.clientX,y:e.clientY,t};if(this.mousePositions.push(n),this.lastMousePos&&this.lastMouseTime){let o=t-this.lastMouseTime;if(o>0){let i=e.clientX-this.lastMousePos.x,s=e.clientY-this.lastMousePos.y,c=Math.sqrt(i*i+s*s)/o;if(this.mouseVelocities.push({v:c,t}),this.eventDeltas.push(o),this.lastVelocity!==null){let l=(c-this.lastVelocity)/o;this.mouseAccelerations.push({a:l,t})}this.lastVelocity=c}}this.lastMousePos={x:e.clientX,y:e.clientY},this.lastMouseTime=t,this.mousePositions.length>500&&(this.mousePositions.shift(),this.mouseVelocities.length>500&&this.mouseVelocities.shift(),this.mouseAccelerations.length>500&&this.mouseAccelerations.shift())}recordMouseDown(e){this.clickData={x:e.clientX,y:e.clientY,button:e.button,downTime:performance.now()}}recordMouseUp(e){this.clickData&&(this.clickData.upTime=performance.now(),this.clickData.holdDuration=this.clickData.upTime-this.clickData.downTime)}recordScroll(e){this.scrollEvents.push({x:window.scrollX,y:window.scrollY,t:performance.now()}),this.scrollEvents.length>100&&this.scrollEvents.shift()}recordKeyEvent(e){this.keyEvents.push({type:e.type,keyLength:e.key?e.key.length:0,t:performance.now()})}recordTouch(e){let t=e.touches&&e.touches.length?e.touches:e.changedTouches;if(!t||t.length===0)return;t.length>1&&(this.touchMultiTouchSeen=!0);let n=t[0];typeof n.identifier=="number"&&this.touchIdentifiers.add(n.identifier),this.touchEvents.push({x:n.clientX,y:n.clientY,t:performance.now(),force:typeof n.force=="number"?n.force:0,radiusX:typeof n.radiusX=="number"?n.radiusX:0,radiusY:typeof n.radiusY=="number"?n.radiusY:0,rotationAngle:typeof n.rotationAngle=="number"?n.rotationAngle:0,identifier:typeof n.identifier=="number"?n.identifier:-1,touchCount:t.length}),this.touchEvents.length>500&&this.touchEvents.shift()}recordPointer(e){this.pointerPoints.push({x:e.clientX,y:e.clientY,t:performance.now(),type:e.type,pressure:typeof e.pressure=="number"?e.pressure:0,tiltX:typeof e.tiltX=="number"?e.tiltX:0,tiltY:typeof e.tiltY=="number"?e.tiltY:0,tangentialPressure:typeof e.tangentialPressure=="number"?e.tangentialPressure:0,pointerType:e.pointerType||"unknown"}),this.pointerPoints.length>500&&this.pointerPoints.shift()}recordFocus(e){var t;this.focusEvents.push({type:e.type,target:(t=e.target)==null?void 0:t.tagName,t:performance.now()})}analyze(){let e=this.mousePositions,t=this.mouseVelocities,n=this.mouseAccelerations;if(e.length<10)return this._getEmptyAnalysis();let o=0,i=0;t.length>0&&(o=t.reduce((v,d)=>v+d.v,0)/t.length,i=t.reduce((v,d)=>v+Math.pow(d.v-o,2),0)/t.length);let s=0,a=0;if(n.length>0){s=n.reduce((m,v)=>m+v.a,0)/n.length;for(let m=1;m<n.length;m++)Math.sign(n[m].a)!==Math.sign(n[m-1].a)&&a++}let c=this._detectMicroTremor(e),l=this._calculateStraightLineRatio(e),u=0;for(let m=1;m<e.length;m++){let v=Math.abs(e[m].x-e[m-1].x),d=Math.abs(e[m].y-e[m-1].y);v<3&&d<3&&(v>0||d>0)&&u++}let h=this._countDirectionChanges(e),g=this._variance(this.eventDeltas),f=e.length>1?e.length/((e[e.length-1].t-e[0].t)/1e3):0,p=0;for(let m=1;m<e.length;m++){let v=e[m].x-e[m-1].x,d=e[m].y-e[m-1].y;p+=Math.sqrt(v*v+d*d)}let y=this._analyzeTouchPoints(this.touchEvents),w=this._analyzePointerPoints(this.pointerPoints);return{totalPoints:e.length,trajectoryLength:p,avgVelocity:o,velocityVariance:i,avgAcceleration:s,accelerationChanges:a,microTremorScore:c,straightLineRatio:l,microMovements:u,directionChanges:h,eventDeltas:this.eventDeltas.slice(-50),eventDeltaVariance:g,mouseEventRate:f,scrollEvents:this.scrollEvents.length,keyEvents:this.keyEvents.length,touchEvents:this.touchEvents.length,focusEvents:this.focusEvents.length,clickData:this.clickData,interactionDuration:Date.now()-this.startTime,...y,...w}}_analyzeTouchPoints(e){if(!e||e.length===0)return{touchTotalPoints:0,touchTrajectoryLength:0,touchAvgVelocity:0,touchVelocityVariance:0,touchMicroTremorScore:0,touchStraightLineRatio:0,touchDirectionChanges:0,touchForceMin:0,touchForceMax:0,touchForceVariance:0,touchRadiusMin:0,touchRadiusMax:0,touchRadiusVariance:0,touchMultiTouchSeen:this.touchMultiTouchSeen,touchUniqueIdentifiers:this.touchIdentifiers.size,touchForceAllZero:!1,touchForceAllOne:!1};let t=0,n=[];for(let l=1;l<e.length;l++){let u=e[l].x-e[l-1].x,h=e[l].y-e[l-1].y,g=Math.sqrt(u*u+h*h);t+=g;let f=e[l].t-e[l-1].t;f>0&&n.push(g/f)}let o=n.length>0?n.reduce((l,u)=>l+u,0)/n.length:0,i=e.map(l=>l.force),s=e.map(l=>Math.max(l.radiusX||0,l.radiusY||0)),a=i.length>0&&i.every(l=>l===0),c=i.length>0&&i.every(l=>l===1);return{touchTotalPoints:e.length,touchTrajectoryLength:t,touchAvgVelocity:o,touchVelocityVariance:this._variance(n),touchMicroTremorScore:this._detectMicroTremor(e),touchStraightLineRatio:this._calculateStraightLineRatio(e),touchDirectionChanges:this._countDirectionChanges(e),touchForceMin:i.length>0?Math.min(...i):0,touchForceMax:i.length>0?Math.max(...i):0,touchForceVariance:this._variance(i),touchRadiusMin:s.length>0?Math.min(...s):0,touchRadiusMax:s.length>0?Math.max(...s):0,touchRadiusVariance:this._variance(s),touchMultiTouchSeen:this.touchMultiTouchSeen,touchUniqueIdentifiers:this.touchIdentifiers.size,touchForceAllZero:a,touchForceAllOne:c}}_analyzePointerPoints(e){if(!e||e.length===0)return{pointerEvents:0,pointerAvgPressure:0,pointerPressureVariance:0,pointerMaxTilt:0,pointerHasNonMouseType:!1,pointerTypes:[]};let t=e.map(s=>s.pressure),n=t.length>0?t.reduce((s,a)=>s+a,0)/t.length:0,o=0,i=new Set;for(let s of e){let a=Math.abs(s.tiltX||0)+Math.abs(s.tiltY||0);a>o&&(o=a),s.pointerType&&i.add(s.pointerType)}return{pointerEvents:e.length,pointerAvgPressure:n,pointerPressureVariance:this._variance(t),pointerMaxTilt:o,pointerHasNonMouseType:Array.from(i).some(s=>s!=="mouse"&&s!=="unknown"),pointerTypes:Array.from(i)}}analyzeClick(e,t,n){let o=this.mousePositions;if(o.length<5)return this._getEmptyClickAnalysis();let i=o.slice(-20),s=n.left+n.width/2,a=n.top+n.height/2,c=Math.sqrt(Math.pow(e-s,2)+Math.pow(t-a,2)),l=0,u=0;for(let d=1;d<o.length;d++){let b=Math.sqrt(Math.pow(o[d].x-o[d-1].x,2)+Math.pow(o[d].y-o[d-1].y,2));u+=b,o[d].x>=n.left&&o[d].x<=n.right&&o[d].y>=n.top&&o[d].y<=n.bottom||(l+=b)}let h=u>0?l/u:0,g=0,f=!1,p=!1;for(let d of i){let b=d.x>=n.left&&d.x<=n.right&&d.y>=n.top&&d.y<=n.bottom;f&&!b&&(p=!0),p&&b&&(g++,p=!1),f=b}let y=0;for(let d=i.length-1;d>=0;d--){let b=i[d],P=b.x>=n.left&&b.x<=n.right&&b.y>=n.top&&b.y<=n.bottom;if(P&&d<i.length-1)y=i[i.length-1].t-b.t;else if(!P)break}let w=Math.sqrt(Math.pow(i[i.length-1].x-i[0].x,2)+Math.pow(i[i.length-1].y-i[0].y,2)),m=0;for(let d=1;d<i.length;d++)m+=Math.sqrt(Math.pow(i[d].x-i[d-1].x,2)+Math.pow(i[d].y-i[d-1].y,2));let v=m>0?w/m:1;return{clickPrecision:c,explorationRatio:h,overshootCorrections:g,hoverTime:y,approachDirectness:v,approachPoints:i.length}}_detectMicroTremor(e){if(e.length<20)return .5;let t=5,n=0;for(let i=t;i<e.length-t;i++){let s=0,a=0;for(let l=i-t;l<=i+t;l++)s+=e[l].x,a+=e[l].y;s/=t*2+1,a/=t*2+1;let c=Math.sqrt(Math.pow(e[i].x-s,2)+Math.pow(e[i].y-a,2));n+=c}let o=n/(e.length-t*2);return Math.min(1,o/2)}_calculateStraightLineRatio(e){if(e.length<3)return 0;let t=0,n=0;for(let o=2;o<e.length;o++){let i=e[o-2],s=e[o-1],a=e[o],c=Math.atan2(s.y-i.y,s.x-i.x),l=Math.atan2(a.y-s.y,a.x-s.x),u=Math.abs(l-c);n++,u<.1&&t++}return n>0?t/n:0}_countDirectionChanges(e){let t=0;for(let n=2;n<e.length;n++){let o=Math.atan2(e[n-1].y-e[n-2].y,e[n-1].x-e[n-2].x),i=Math.atan2(e[n].y-e[n-1].y,e[n].x-e[n-1].x);Math.abs(i-o)>Math.PI/6&&t++}return t}_variance(e){if(e.length===0)return 0;let t=e.reduce((n,o)=>n+o,0)/e.length;return e.reduce((n,o)=>n+Math.pow(o-t,2),0)/e.length}_getEmptyAnalysis(){return{totalPoints:0,trajectoryLength:0,avgVelocity:0,velocityVariance:0,avgAcceleration:0,accelerationChanges:0,microTremorScore:.5,straightLineRatio:0,microMovements:0,directionChanges:0,eventDeltas:[],eventDeltaVariance:0,mouseEventRate:0,scrollEvents:this.scrollEvents.length,keyEvents:this.keyEvents.length,touchEvents:this.touchEvents.length,focusEvents:this.focusEvents.length,clickData:this.clickData,interactionDuration:Date.now()-this.startTime,...this._analyzeTouchPoints(this.touchEvents),...this._analyzePointerPoints(this.pointerPoints)}}_getEmptyClickAnalysis(){return{clickPrecision:0,explorationRatio:0,overshootCorrections:0,hoverTime:0,approachDirectness:1,approachPoints:0}}};var T=class{collect(){return{webdriver:this._detectWebdriver(),automationFlags:this._getAutomationFlags(),cdp:this._detectCDP(),playwright:this._detectPlaywright(),canvasHash:this._getCanvasHash(),webglInfo:this._getWebGLInfo(),audioInfo:this._getAudioInfo(),headlessIndicators:this._getHeadlessIndicators(),screen:this._getScreenInfo(),navigator:this._getNavigatorInfo(),jsExecutionTime:this._measureJSExecution(),mathFingerprint:this._getMathFingerprint(),errorFingerprint:this._getErrorFingerprint(),domRectFingerprint:this._getDOMRectFingerprint(),cssMediaQueries:this._getCSSMediaQueries(),permissionsInfo:this._getPermissionsInfo(),fontsInfo:this._getFontsInfo(),lieDetection:this._getLieDetection()}}async collectAsync(){let[e,t,n]=await Promise.all([this._getSpeechInfo(),this._getWebRTCInfo(),this._checkWorkerConsistency()]);return{speechInfo:e,webrtcInfo:t,workerConsistency:n}}_detectWebdriver(){let e=navigator,t=window;return!!(e.webdriver||t.document.__webdriver_evaluate||t.document.__selenium_evaluate||t.document.__webdriver_script_fn||t.document.__webdriver_script_func||t.document.__webdriver_script_function||t.document.$cdc_asdjflasutopfhvcZLmcfl_||t.document.$wdc_||t._Selenium_IDE_Recorder||t._phantom||t.__nightmare||t.callPhantom||t._phantom)}_getAutomationFlags(){let e=navigator,t=window;return{webdriver:!!e.webdriver,domAutomation:!!t.domAutomation,domAutomationController:!!t.domAutomationController,_selenium:!!t._selenium,__webdriver_script_fn:!!t.__webdriver_script_fn,__driver_evaluate:!!t.__driver_evaluate,__webdriver_evaluate:!!t.__webdriver_evaluate,__fxdriver_evaluate:!!t.__fxdriver_evaluate,__driver_unwrapped:!!t.__driver_unwrapped,__webdriver_unwrapped:!!t.__webdriver_unwrapped,__fxdriver_unwrapped:!!t.__fxdriver_unwrapped,_Selenium_IDE_Recorder:!!t._Selenium_IDE_Recorder,calledSelenium:!!t.calledSelenium,$chrome_asyncScriptInfo:!!t.$chrome_asyncScriptInfo,$cdc_asdjflasutopfhvcZLmcfl_:!!t.$cdc_asdjflasutopfhvcZLmcfl_,_phantom:!!t._phantom,callPhantom:!!t.callPhantom,__nightmare:!!t.__nightmare,__lastWatirAlert:!!t.__lastWatirAlert,__lastWatirConfirm:!!t.__lastWatirConfirm,__lastWatirPrompt:!!t.__lastWatirPrompt,plugins:navigator.plugins?navigator.plugins.length:0,languages:navigator.languages&&navigator.languages.length>0,mimeTypes:navigator.mimeTypes?navigator.mimeTypes.length:0,cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,chrome:!!t.chrome,chromeRuntime:!!(t.chrome&&t.chrome.runtime&&t.chrome.runtime.id),permissionsAPI:!!navigator.permissions}}_detectPlaywright(){try{let e=[];Object.getOwnPropertyNames(window).filter(i=>i.startsWith("__pw")||i.startsWith("__playwright")).length>0&&e.push("playwright_globals");let n=Object.getPrototypeOf(navigator);return Object.getOwnPropertyDescriptor(n,"webdriver")||e.push("webdriver_deleted"),{detected:e.length>0,signals:e}}catch{return{detected:!1,signals:[]}}}_detectCDP(){try{let e=[];Object.keys(window).filter(n=>n.startsWith("cdc_")).length>0&&e.push("chromedriver_cdc"),"__webdriver_evaluate"in window&&e.push("selenium_evaluate"),"__driver_evaluate"in window&&e.push("selenium_driver_evaluate"),"__webdriver_unwrapped"in window&&e.push("selenium_unwrapped"),"__driver_unwrapped"in window&&e.push("selenium_driver_unwrapped"),"__selenium_evaluate"in window&&e.push("selenium_direct"),"__fxdriver_evaluate"in window&&e.push("firefox_driver"),"__fxdriver_unwrapped"in window&&e.push("firefox_driver_unwrapped"),"__puppeteer_evaluation_script__"in window&&e.push("puppeteer_eval"),document.__webdriver_script_fn&&e.push("cdp_script_injection");try{let n=Object.getOwnPropertyDescriptor(navigator,"webdriver");n&&typeof n.get=="function"&&n.get.toString().indexOf("[native code]")===-1&&e.push("webdriver_getter_modified")}catch{}return{detected:e.length>0,signals:e}}catch{return{detected:!1,signals:[]}}}_getCanvasHash(){try{let e=document.createElement("canvas");e.width=200,e.height=50;let t=e.getContext("2d");t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("FCaptcha",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("FCaptcha",4,17);let n=e.toDataURL(),o=0;for(let i=0;i<n.length;i++)o=(o<<5)-o+n.charCodeAt(i),o=o&o;return{hash:o.toString(16),dataLength:n.length,supported:!0}}catch{return{error:!0,supported:!1}}}_getWebGLInfo(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{supported:!1};let n=t.getExtension("WEBGL_debug_renderer_info"),o=n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown",i=n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown",s=i.toLowerCase(),a=s.includes("swiftshader")||s.includes("llvmpipe")||s.includes("softpipe")||s.includes("virtualbox")||s.includes("vmware");return{supported:!0,vendor:o,renderer:i,version:t.getParameter(t.VERSION),shadingVersion:t.getParameter(t.SHADING_LANGUAGE_VERSION),suspiciousRenderer:a}}catch{return{supported:!1,error:!0}}}_getAudioInfo(){try{let e=window,t=e.AudioContext||e.webkitAudioContext;if(!t)return{supported:!1};let n=new t,o={supported:!0,sampleRate:n.sampleRate,state:n.state,baseLatency:n.baseLatency};return n.close().catch(()=>{}),o}catch{return{supported:!1,error:!0}}}_getLieDetection(){try{let e=window,t=[],n=i=>{try{return typeof i=="function"&&i.toString().indexOf("[native code]")===-1}catch{return!1}},o=(i,s)=>{n(i)&&t.push(s)};o(Function.prototype.toString,"Function.prototype.toString"),o(navigator.permissions&&navigator.permissions.query,"navigator.permissions.query"),o(e.Notification&&e.Notification.requestPermission,"Notification.requestPermission"),o(e.HTMLCanvasElement&&e.HTMLCanvasElement.prototype.toDataURL,"HTMLCanvasElement.toDataURL"),o(e.WebGLRenderingContext&&e.WebGLRenderingContext.prototype.getParameter,"WebGLRenderingContext.getParameter"),o(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices,"mediaDevices.enumerateDevices");try{let i=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(navigator),"webdriver")||Object.getOwnPropertyDescriptor(navigator,"webdriver");i&&typeof i.get=="function"&&i.get.toString().indexOf("[native code]")===-1&&t.push("navigator.webdriver getter")}catch{}return{supported:!0,patched:t,patchedCount:t.length}}catch{return{supported:!1}}}_getHeadlessIndicators(){let e=navigator;return{hasOuterDimensions:window.outerWidth>0&&window.outerHeight>0,innerEqualsOuter:window.innerWidth===window.outerWidth&&window.innerHeight===window.outerHeight,screenColorDepth:window.screen.colorDepth,screenPixelDepth:window.screen.pixelDepth,connectionType:e.connection?e.connection.type:"unknown",connectionRtt:e.connection?e.connection.rtt:-1,notificationPermission:typeof Notification!="undefined"?Notification.permission:"unsupported",hasBattery:"getBattery"in navigator,hasCredentials:"credentials"in navigator,hasMediaDevices:"mediaDevices"in navigator}}_getScreenInfo(){return{width:screen.width,height:screen.height,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio,availWidth:screen.availWidth,availHeight:screen.availHeight,innerWidth:window.innerWidth,innerHeight:window.innerHeight}}_getNavigatorInfo(){var t;let e=navigator;return{language:navigator.language,languageCount:((t=navigator.languages)==null?void 0:t.length)||0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:e.deviceMemory,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()}}_measureJSExecution(){let e={},t=performance.now(),n=0;for(let s=0;s<1e3;s++)n+=Math.sqrt(s)*Math.sin(s);e.mathOps=performance.now()-t,e.mathSink=n,t=performance.now();let o=[];for(let s=0;s<1e3;s++)o.push(s);e.arrayOps=performance.now()-t,e.arrayLen=o.length,t=performance.now();let i="";for(let s=0;s<100;s++)i+="a";return e.stringOps=performance.now()-t,e.stringLen=i.length,e}async measureRAFConsistency(){return new Promise(e=>{let t=[],n=0,o=10;function i(s){if(t.push(s),n++,n<o)requestAnimationFrame(i);else{let a=[];for(let u=1;u<t.length;u++)a.push(t[u]-t[u-1]);let c=a.reduce((u,h)=>u+h,0)/a.length,l=a.reduce((u,h)=>u+Math.pow(h-c,2),0)/a.length;e({avgFrameTime:c,frameTimeVariance:l,frames:o})}}requestAnimationFrame(i)})}_getMathFingerprint(){try{let e={acos:Math.acos(.123456789),acosh:Math.acosh(1e308),asin:Math.asin(.123456789),asinh:Math.asinh(1),atanh:Math.atanh(.5),cbrt:Math.cbrt(100),cosh:Math.cosh(1),expm1:Math.expm1(1),log1p:Math.log1p(10),sinh:Math.sinh(1),tan:Math.tan(-1e308),tanh:Math.tanh(1),pow:Math.pow(Math.PI,-100),sin:Math.sin(Math.PI)},t=Object.values(e).map(o=>String(o)).join(","),n=0;for(let o=0;o<t.length;o++)n=(n<<5)-n+t.charCodeAt(o),n=n&n;return{hash:n.toString(16),sinPi:e.sin,tanLarge:e.tan,supported:!0}}catch{return{supported:!1,error:!0}}}_getErrorFingerprint(){try{let e={};try{null.foo}catch(o){e.typeError=o.message}try{[].length=-1}catch(o){e.rangeError=o.message}try{decodeURIComponent("%")}catch(o){e.uriError=o.message}try{({}).undefinedMethod()}catch(o){e.refTypeError=o.message}let t=Object.values(e).join("|"),n=0;for(let o=0;o<t.length;o++)n=(n<<5)-n+t.charCodeAt(o),n=n&n;return{hash:n.toString(16),typeError:e.typeError,supported:!0}}catch{return{supported:!1,error:!0}}}_getDOMRectFingerprint(){try{let e=document.createElement("div");e.style.cssText="position:absolute;left:-9999px;font-size:16px;font-family:Arial,sans-serif;";let t=document.createElement("span");t.textContent="FCaptcha Test String 123",e.appendChild(t);let n=document.createElement("span");n.style.cssText="letter-spacing:1px;word-spacing:2px;",n.textContent="WWWW 0000",e.appendChild(n),document.body.appendChild(e);let o=t.getBoundingClientRect(),i=n.getBoundingClientRect(),s=document.createRange();s.selectNode(t);let a=s.getBoundingClientRect();document.body.removeChild(e);let l=[o.width,o.height,o.x,o.y,i.width,i.height,a.width,a.height].map(h=>h.toFixed(6)).join(","),u=0;for(let h=0;h<l.length;h++)u=(u<<5)-u+l.charCodeAt(h),u=u&u;return{hash:u.toString(16),rectAWidth:o.width,rectBWidth:i.width,rangeWidth:a.width,supported:!0}}catch{return{supported:!1,error:!0}}}_getCSSMediaQueries(){try{return{...{prefersColorScheme:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",prefersReducedMotion:window.matchMedia("(prefers-reduced-motion: reduce)").matches,prefersReducedTransparency:window.matchMedia("(prefers-reduced-transparency: reduce)").matches,prefersContrast:window.matchMedia("(prefers-contrast: more)").matches?"more":window.matchMedia("(prefers-contrast: less)").matches?"less":"no-preference",anyHover:window.matchMedia("(any-hover: hover)").matches,anyPointer:window.matchMedia("(any-pointer: fine)").matches?"fine":window.matchMedia("(any-pointer: coarse)").matches?"coarse":"none",hover:window.matchMedia("(hover: hover)").matches,pointer:window.matchMedia("(pointer: fine)").matches?"fine":window.matchMedia("(pointer: coarse)").matches?"coarse":"none",colorGamut:window.matchMedia("(color-gamut: p3)").matches?"p3":window.matchMedia("(color-gamut: srgb)").matches?"srgb":"none",displayMode:window.matchMedia("(display-mode: standalone)").matches?"standalone":window.matchMedia("(display-mode: fullscreen)").matches?"fullscreen":"browser",orientation:window.matchMedia("(orientation: portrait)").matches?"portrait":"landscape",dynamicRange:window.matchMedia("(dynamic-range: high)").matches?"high":"standard",forcedColors:window.matchMedia("(forced-colors: active)").matches},supported:!0}}catch{return{supported:!1,error:!0}}}_getPermissionsInfo(){try{return{hasPermissionsAPI:"permissions"in navigator,hasClipboard:"clipboard"in navigator,hasShare:"share"in navigator,hasCredentials:"credentials"in navigator,hasBluetooth:"bluetooth"in navigator,hasUsb:"usb"in navigator,hasSerial:"serial"in navigator,hasHid:"hid"in navigator,hasXR:"xr"in navigator,hasGeolocation:"geolocation"in navigator,hasMIDI:"requestMIDIAccess"in navigator,supported:!0}}catch{return{supported:!1,error:!0}}}_getFontsInfo(){try{let e=["monospace","sans-serif","serif"],t=["Arial","Helvetica","Times New Roman","Courier New","Georgia","Verdana","Trebuchet MS","Comic Sans MS","Impact","Lucida Console","Menlo","Monaco","SF Pro","Helvetica Neue","Segoe UI","Consolas","Calibri","Cambria","DejaVu Sans","Liberation Sans","Ubuntu","Cantarell","MS Gothic","Meiryo","SimHei","Microsoft YaHei"],n=document.createElement("canvas");n.width=400,n.height=40;let o=n.getContext("2d"),i="mmMWWLLiiff00",s="72px",a={};for(let h of e)o.font=s+" "+h,a[h]=o.measureText(i).width;let c=[];for(let h of t){let g=!1;for(let f of e)if(o.font=s+' "'+h+'", '+f,o.measureText(i).width!==a[f]){g=!0;break}g&&c.push(h)}let l=c.join(","),u=0;for(let h=0;h<l.length;h++)u=(u<<5)-u+l.charCodeAt(h),u=u&u;return{hash:u.toString(16),count:c.length,hasArial:c.includes("Arial"),hasTimesNewRoman:c.includes("Times New Roman"),hasSegoeUI:c.includes("Segoe UI"),hasSFPro:c.includes("SF Pro"),hasDejaVuSans:c.includes("DejaVu Sans"),supported:!0}}catch{return{supported:!1,error:!0}}}async _getSpeechInfo(){try{if(!("speechSynthesis"in window))return{supported:!1};let t=await new Promise(c=>{let l=speechSynthesis.getVoices();if(l.length>0){c(l);return}let u=setTimeout(()=>c([]),1e3);speechSynthesis.onvoiceschanged=()=>{clearTimeout(u),c(speechSynthesis.getVoices())}}),n=t.filter(c=>c.localService),o=t.find(c=>c.default),i=[...new Set(t.map(c=>c.lang))],s=t.map(c=>c.name).sort().join(","),a=0;for(let c=0;c<s.length;c++)a=(a<<5)-a+s.charCodeAt(c),a=a&a;return{hash:a.toString(16),totalVoices:t.length,localVoices:n.length,languages:i.length,defaultVoiceLang:(o==null?void 0:o.lang)||null,hasGoogleVoices:t.some(c=>c.name.includes("Google")),hasMicrosoftVoices:t.some(c=>c.name.includes("Microsoft")),hasAppleVoices:t.some(c=>c.name.includes("Samantha")||c.name.includes("Alex")),supported:!0}}catch{return{supported:!1,error:!0}}}async _getWebRTCInfo(){try{let e={supported:"RTCPeerConnection"in window,mediaDevices:{supported:!1},localIPs:[]};if(!e.supported)return e;if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices)try{let t=await navigator.mediaDevices.enumerateDevices();e.mediaDevices={supported:!0,audioInputs:t.filter(n=>n.kind==="audioinput").length,audioOutputs:t.filter(n=>n.kind==="audiooutput").length,videoInputs:t.filter(n=>n.kind==="videoinput").length,totalDevices:t.length}}catch{e.mediaDevices={supported:!1,error:!0}}try{let t=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}),n=new Set;t.onicecandidate=o=>{if(o.candidate){let i=o.candidate.candidate,s=/([0-9]{1,3}\.){3}[0-9]{1,3}/g,a=i.match(s);a&&a.forEach(c=>{(c.startsWith("192.168.")||c.startsWith("10.")||c.startsWith("172.")||c.startsWith("169.254."))&&n.add(c)})}},t.createDataChannel(""),await t.createOffer().then(o=>t.setLocalDescription(o)),await new Promise(o=>setTimeout(o,500)),e.localIPs=Array.from(n),e.hasLocalIP=n.size>0,t.close()}catch{e.localIPError=!0}return e}catch{return{supported:!1,error:!0}}}async _checkWorkerConsistency(){try{if(typeof Worker=="undefined")return{supported:!1};let e=navigator,t=`
|
|
2
2
|
self.onmessage = function() {
|
|
3
3
|
const data = {
|
|
4
4
|
userAgent: navigator.userAgent,
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
};
|
|
13
13
|
self.postMessage(data);
|
|
14
14
|
};
|
|
15
|
-
`,n=new Blob([t],{type:"application/javascript"}),
|
|
15
|
+
`,n=new Blob([t],{type:"application/javascript"}),o=new Worker(URL.createObjectURL(n)),i=await new Promise((c,l)=>{let u=setTimeout(()=>l(new Error("timeout")),2e3);o.onmessage=h=>{clearTimeout(u),c(h.data)},o.onerror=()=>{clearTimeout(u),l(new Error("worker error"))},o.postMessage("collect")});o.terminate();let s={userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[],platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:e.deviceMemory,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()},a=[];return i.userAgent!==s.userAgent&&a.push("userAgent"),i.language!==s.language&&a.push("language"),i.platform!==s.platform&&a.push("platform"),i.hardwareConcurrency!==s.hardwareConcurrency&&a.push("hardwareConcurrency"),i.deviceMemory!==s.deviceMemory&&a.push("deviceMemory"),i.timezone!==s.timezone&&a.push("timezone"),i.timezoneOffset!==s.timezoneOffset&&a.push("timezoneOffset"),JSON.stringify(i.languages)!==JSON.stringify(s.languages)&&a.push("languages"),{supported:!0,consistent:a.length===0,mismatches:a,mismatchCount:a.length}}catch{return{supported:!1,error:!0}}}};var R=class{constructor(){this.motionEvents=[],this.orientationEvents=[],this._motionHandler=e=>this._recordMotion(e),this._orientationHandler=e=>this._recordOrientation(e),this._attached=!1}attach(){if(!this._attached){this._attached=!0;try{window.addEventListener("devicemotion",this._motionHandler,{passive:!0}),window.addEventListener("deviceorientation",this._orientationHandler,{passive:!0})}catch{}}}detach(){if(this._attached){this._attached=!1;try{window.removeEventListener("devicemotion",this._motionHandler),window.removeEventListener("deviceorientation",this._orientationHandler)}catch{}}}_recordMotion(e){let t=e.accelerationIncludingGravity||e.acceleration||{};this.motionEvents.push({x:typeof t.x=="number"?t.x:0,y:typeof t.y=="number"?t.y:0,z:typeof t.z=="number"?t.z:0,t:performance.now()}),this.motionEvents.length>300&&this.motionEvents.shift()}_recordOrientation(e){this.orientationEvents.push({alpha:typeof e.alpha=="number"?e.alpha:0,beta:typeof e.beta=="number"?e.beta:0,gamma:typeof e.gamma=="number"?e.gamma:0,t:performance.now()}),this.orientationEvents.length>300&&this.orientationEvents.shift()}analyze(){let e=this.motionEvents,t=this.orientationEvents,n=0,o=0;if(e.length>1){let s=e.map(a=>Math.sqrt(a.x*a.x+a.y*a.y+a.z*a.z));o=s.reduce((a,c)=>a+c,0)/s.length,n=s.reduce((a,c)=>a+(c-o)*(c-o),0)/s.length}let i=0;if(t.length>1){let s=t.map(c=>Math.abs(c.beta)+Math.abs(c.gamma)),a=s.reduce((c,l)=>c+l,0)/s.length;i=s.reduce((c,l)=>c+(l-a)*(l-a),0)/s.length}return{motionEventCount:e.length,motionAccelAvg:o,motionAccelVariance:n,orientationEventCount:t.length,orientationVariance:i,hasSensorSupport:typeof window.DeviceMotionEvent!="undefined"}}};var Y=class{constructor(){this.pageLoadTime=performance.now(),this.firstInteractionTime=null,this.lastInteractionTime=null,this.totalEvents=0,this.eventLog=[],this.textareaStats=new Map,this.submitData=null,this._setupListeners()}_setupListeners(){["mousedown","keydown","touchstart","scroll"].forEach(t=>{document.addEventListener(t,n=>this._recordInteraction(n),{passive:!0})}),document.addEventListener("keydown",t=>this._recordTextareaKey(t),{passive:!0}),document.addEventListener("keyup",t=>this._recordTextareaKey(t),{passive:!0}),document.addEventListener("submit",t=>this._recordSubmit(t),{capture:!0}),this._interceptFormSubmit()}_recordInteraction(e){var n;let t=performance.now();this.firstInteractionTime===null&&(this.firstInteractionTime=t),this.lastInteractionTime=t,this.totalEvents++,this.eventLog.push({type:e.type,time:t,target:((n=e.target)==null?void 0:n.tagName)||"unknown"}),this.eventLog.length>50&&this.eventLog.shift()}_recordTextareaKey(e){let t=e.target;if((t==null?void 0:t.tagName)!=="TEXTAREA")return;let n=t.id||t.name||"unnamed";this.textareaStats.has(n)||this.textareaStats.set(n,{keydowns:[],keyups:[],intervals:[],lastKeyTime:null,inputWithoutKey:0,pasteCount:0,dwellTimes:[],rollovers:0,activeKeyCount:0,pendingKeydowns:[]});let o=this.textareaStats.get(n),i=performance.now(),s=["Shift","Control","Alt","Meta","CapsLock","NumLock","ScrollLock"].includes(e.key);if(e.type==="keydown")o.keydowns.push(i),o.lastKeyTime!==null&&o.intervals.push(i-o.lastKeyTime),o.lastKeyTime=i,!s&&!e.repeat&&(o.activeKeyCount>0&&o.rollovers++,o.activeKeyCount++,o.pendingKeydowns.push(i)),o.keydowns.length>200&&o.keydowns.shift(),o.intervals.length>200&&o.intervals.shift();else if(e.type==="keyup"&&(o.keyups.push(i),o.keyups.length>200&&o.keyups.shift(),!s&&o.activeKeyCount>0&&(o.activeKeyCount--,o.pendingKeydowns.length>0))){let a=o.pendingKeydowns.shift(),c=i-a;c>0&&c<2e3&&(o.dwellTimes.push(c),o.dwellTimes.length>100&&o.dwellTimes.shift())}}_interceptFormSubmit(){let e=n=>this._recordProgrammaticSubmit(n),t=HTMLFormElement.prototype.submit;HTMLFormElement.prototype.submit=function(...n){return e(this),t.apply(this,n)}}_recordProgrammaticSubmit(e){let t=performance.now();this.submitData={method:"programmatic",time:t,timeSincePageLoad:t-this.pageLoadTime,timeSinceFirstInteraction:this.firstInteractionTime?t-this.firstInteractionTime:null,timeSinceLastInteraction:this.lastInteractionTime?t-this.lastInteractionTime:null,eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:!1}}_recordSubmit(e){let t=performance.now(),n=this.eventLog.slice(-5),o=n.find(a=>a.type==="keydown"&&t-a.time<100),i=n.find(a=>a.type==="mousedown"&&t-a.time<100),s="unknown";o?s="keyboard":i?s="mouse":this.submitData||(s="programmatic_click"),(!this.submitData||this.submitData.method==="programmatic")&&(this.submitData={method:s,time:t,timeSincePageLoad:t-this.pageLoadTime,timeSinceFirstInteraction:this.firstInteractionTime?t-this.firstInteractionTime:null,timeSinceLastInteraction:this.lastInteractionTime?t-this.lastInteractionTime:null,eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:s==="keyboard"||s==="mouse"})}analyze(){let e=performance.now(),t={};return this.textareaStats.forEach((o,i)=>{let s=o.intervals,a=0,c=0;s.length>0&&(a=s.reduce((l,u)=>l+u,0)/s.length,c=s.reduce((l,u)=>l+Math.pow(u-a,2),0)/s.length),t[i]={keyCount:o.keydowns.length,avgKeyInterval:a,keyIntervalVariance:c,keydownUpRatio:o.keyups.length>0?o.keydowns.length/o.keyups.length:0,pasteCount:o.pasteCount,intervals:o.intervals.slice(-100),dwellTimes:o.dwellTimes.slice(-100),rollovers:o.rollovers}}),document.querySelectorAll("textarea").forEach(o=>{let i=o.id||o.name||"unnamed",s=(o.value||"").length;s>0&&(t[i]?(t[i].contentLength=s,t[i].noKeyboardEvents=t[i].keyCount===0):t[i]={keyCount:0,avgKeyInterval:0,keyIntervalVariance:0,keydownUpRatio:0,pasteCount:0,contentLength:s,noKeyboardEvents:!0})}),{pageLoadToFirstInteraction:this.firstInteractionTime?this.firstInteractionTime-this.pageLoadTime:null,pageLoadToNow:e-this.pageLoadTime,totalInteractionEvents:this.totalEvents,submit:this.submitData||{method:"none",eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:!1},textareaKeyboard:Object.keys(t).length>0?t:null}}recordPaste(e){let t=e.target;if((t==null?void 0:t.tagName)!=="TEXTAREA")return;let n=t.id||t.name||"unnamed";this.textareaStats.has(n)&&this.textareaStats.get(n).pasteCount++}},j=null;function A(){return j||(j=new Y,document.addEventListener("paste",r=>j.recordPaste(r),{passive:!0})),j}typeof document!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>A()):A());async function C(r){let e=new TextEncoder().encode(r),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}var I=class{constructor(){this.firstInteractionTime=null;this.powResult=null;this.pageLoadTime=performance.now()}recordFirstInteraction(){this.firstInteractionTime||(this.firstInteractionTime=performance.now())}async performProofOfWork(e=4){let t=`${Date.now()}:${Math.random().toString(36).slice(2)}`,n="0".repeat(e),o=performance.now(),i=0,s=0;for(;;){let a=await C(`${t}:${i}`);if(s++,a.startsWith(n))return this.powResult={prefix:t,nonce:i,hash:a,iterations:s,duration:performance.now()-o,difficulty:e},this.powResult;i++,s%1e3===0&&await new Promise(c=>setTimeout(c,0))}}collect(e){let t={};if(performance.timing){let n=performance.timing;t.dnsLookup=n.domainLookupEnd-n.domainLookupStart,t.tcpConnection=n.connectEnd-n.connectStart,t.serverResponse=n.responseEnd-n.requestStart,t.domLoad=n.domContentLoadedEventEnd-n.navigationStart,t.fullLoad=n.loadEventEnd-n.navigationStart}return{pageLoadToFirstInteraction:this.firstInteractionTime?this.firstInteractionTime-this.pageLoadTime:null,firstInteractionToClick:this.firstInteractionTime&&e?e-this.firstInteractionTime:null,totalSessionTime:performance.now()-this.pageLoadTime,performanceTiming:t,pow:this.powResult}}};var ae=null,ce="/__webdecoy";function S(){return ae}function B(r){ae=r}function O(){return ce}function le(r){ce=r.replace(/\/$/,"")}var K=class{constructor(){this.workers=[];this.challenge=null;this.solution=null;this.solving=!1;this.solvePromise=null;this.startTime=null}_createWorker(){let e=`
|
|
16
16
|
async function sha256(message) {
|
|
17
17
|
const msgBuffer = new TextEncoder().encode(message);
|
|
18
18
|
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
});
|
|
55
55
|
}
|
|
56
56
|
};
|
|
57
|
-
`,t=new Blob([e],{type:"application/javascript"});return new Worker(URL.createObjectURL(t))}_threadCount(){let e=typeof navigator!="undefined"&&navigator.hardwareConcurrency||1;return Math.max(1,Math.floor(e/2))}_terminateWorkers(){for(let e of this.workers)try{e.terminate()}catch{}this.workers=[]}async fetchChallenge(e){let t=
|
|
57
|
+
`,t=new Blob([e],{type:"application/javascript"});return new Worker(URL.createObjectURL(t))}_threadCount(){let e=typeof navigator!="undefined"&&navigator.hardwareConcurrency||1;return Math.max(1,Math.floor(e/2))}_terminateWorkers(){for(let e of this.workers)try{e.terminate()}catch{}this.workers=[]}async fetchChallenge(e){let t=S();if(!t)return this._generateLocalChallenge();try{let n=await fetch(`${t}${O()}/challenge?siteKey=${encodeURIComponent(e||"default")}`);return n.ok?(this.challenge=await n.json(),this.challenge):(console.warn(`PoW challenge fetch failed (status ${n.status}), using local challenge`),this._generateLocalChallenge())}catch(n){return console.warn("PoW challenge fetch failed, using local challenge:",n),this._generateLocalChallenge()}}_generateLocalChallenge(){let e=Math.random().toString(36).slice(2)+Date.now().toString(36);return this.challenge={challengeId:e,prefix:`${e}:${Date.now()}:4`,difficulty:4,expiresAt:Date.now()+3e5,local:!0},this.challenge}async startSolving(e){return this._solve(e,null)}async solveWithSignalsHash(e,t){return this._solve(e,t)}async _solve(e,t){if(this.solving&&this.solvePromise)return this.solvePromise;this.challenge||await this.fetchChallenge(e);let n=this.challenge;return this.solving=!0,this.startTime=performance.now(),this.solvePromise=new Promise((o,i)=>{let s=this._threadCount(),a=!1,c=(l,u)=>{a||(a=!0,this.solving=!1,this._terminateWorkers(),l(u))};for(let l=0;l<s;l++){let u=this._createWorker();u.onmessage=h=>{h.data.found&&(this.solution={challengeId:n.challengeId,nonce:h.data.nonce,hash:h.data.hash,iterations:h.data.iterations,duration:h.data.duration,difficulty:n.difficulty,signalsHash:t||null,local:n.local||!1},c(o,this.solution))},u.onerror=h=>{c(i,h)},u.postMessage({prefix:n.prefix,difficulty:n.difficulty,signalsHash:t||null,startNonce:l,stride:s,batchSize:5e3}),this.workers.push(u)}}),this.solvePromise}async getSolution(e){return this.solution?this.solution:this.solving&&this.solvePromise?this.solvePromise:this.startSolving(e)}reset(){this._terminateWorkers(),this.challenge=null,this.solution=null,this.solving=!1,this.solvePromise=null}},J=null;function ue(){return J||(J=new K),J}var F=class{constructor(e,t){this.token=null;this.verified=!1;let n=typeof e=="string"?document.getElementById(e):e;if(!n)throw new Error("WebDecoy captcha: container element not found");this.container=n,this.options=Object.assign({siteKey:null,theme:"light",size:"normal",callback:null,errorCallback:null,expiredCallback:null,powDifficulty:4},t),this.id="webdecoy_"+Math.random().toString(36).slice(2,11),this.behavioral=new M,this.environmental=new T,this.temporal=new I,this.sensor=new R,this.powManager=ue(),this._init()}_init(){this._createWidget(),this._attachListeners(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(e){console.warn("PoW challenge fetch failed:",e)}}_createWidget(){let e=this.options.theme==="dark";this.container.innerHTML=`
|
|
58
58
|
<div class="webdecoy-widget ${e?"webdecoy-dark":""}" id="${this.id}">
|
|
59
59
|
<style>
|
|
60
60
|
.webdecoy-widget {
|
|
@@ -107,4 +107,4 @@
|
|
|
107
107
|
<span class="webdecoy-brand">WebDecoy</span>
|
|
108
108
|
</div>
|
|
109
109
|
</div>
|
|
110
|
-
`,this.checkbox=this.container.querySelector(".webdecoy-checkbox"),this.spinner=this.container.querySelector(".webdecoy-spinner"),this.label=this.container.querySelector(".webdecoy-label")}_attachListeners(){document.addEventListener("mousemove",t=>this.behavioral.recordMouseMove(t),{passive:!0}),document.addEventListener("mousedown",t=>this.behavioral.recordMouseDown(t),{passive:!0}),document.addEventListener("mouseup",t=>this.behavioral.recordMouseUp(t),{passive:!0}),document.addEventListener("scroll",t=>this.behavioral.recordScroll(t),{passive:!0}),document.addEventListener("keydown",t=>this.behavioral.recordKeyEvent(t),{passive:!0}),document.addEventListener("keyup",t=>this.behavioral.recordKeyEvent(t),{passive:!0}),document.addEventListener("touchstart",t=>this.behavioral.recordTouch(t),{passive:!0}),document.addEventListener("touchmove",t=>this.behavioral.recordTouch(t),{passive:!0}),document.addEventListener("pointermove",t=>this.behavioral.recordPointer(t),{passive:!0}),document.addEventListener("pointerdown",t=>this.behavioral.recordPointer(t),{passive:!0}),document.addEventListener("pointerup",t=>this.behavioral.recordPointer(t),{passive:!0}),document.addEventListener("focus",t=>this.behavioral.recordFocus(t),{passive:!0,capture:!0}),document.addEventListener("blur",t=>this.behavioral.recordFocus(t),{passive:!0,capture:!0}),this.sensor.attach();let e=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",e,{once:!0}),document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("keydown",e,{once:!0}),this.checkbox.addEventListener("click",t=>{this._handleClick(t)}),this.checkbox.addEventListener("keydown",t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this._handleClick(t))})}async _handleClick(e){var i,o,s;if(this.verified||this.checkbox.classList.contains("loading"))return;let t=performance.now(),n=this.checkbox.getBoundingClientRect();this.checkbox.classList.add("loading"),this.spinner.style.display="block",this.label.textContent="Verifying...";try{let a=this.behavioral.analyze(),c="clientX"in e?e.clientX:n.left,l="clientY"in e?e.clientY:n.top,u=this.behavioral.analyzeClick(c,l,n),h=this.environmental.collect(),[v,p]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),b=this.temporal.collect(t),E=D().analyze(),S=this.sensor.analyze(),m={behavioral:{...a,...u},environmental:{...h,rafConsistency:v,...p,sensor:S},temporal:b,formAnalysis:E,meta:{widgetId:this.id,siteKey:this.options.siteKey,challengeNonce:((i=this.powManager.challenge)==null?void 0:i.nonce)||null,timestamp:Date.now(),userAgent:navigator.userAgent,screenSize:`${screen.width}x${screen.height}`,viewportSize:`${window.innerWidth}x${window.innerHeight}`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}},f=JSON.stringify(m),d=await T(f),g=await this.powManager.solveWithSignalsHash(this.options.siteKey,d),O={duration:g.duration,iterations:g.iterations,difficulty:g.difficulty},U=await this._verify(m,g,f,d,O);U.success?this._showSuccess((o=U.token)!=null?o:""):this._showFailure((s=U.message)!=null?s:void 0)}catch(a){console.error("WebDecoy captcha error:",a),this._showFailure("Verification failed. Please try again.")}}async _verify(e,t,n,i,o){let s=x();if(!s)return this._clientSideVerify(e);try{return await(await fetch(s+L()+"/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:e,signalsJson:n||null,powSolution:t?{challengeId:t.challengeId,nonce:t.nonce,hash:t.hash,signalsHash:i||null}:null,powTiming:o||null})})).json()}catch{return console.warn("Server unavailable, using client-side verification"),this._clientSideVerify(e)}}_clientSideVerify(e){let t=0,n=e.behavioral,i=e.environmental,o=e.temporal,s=(n.touchEvents||0)>=3,a=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!s&&!a?t+=.35:n.totalPoints<10&&!s&&!a&&n.trajectoryLength<30&&(t+=.15),n.microTremorScore<.2&&(t+=.12),n.velocityVariance<.03&&(t+=.1),n.explorationRatio<.05&&(t+=.08),n.overshootCorrections===0&&n.trajectoryLength>100&&(t+=.05),n.clickPrecision<2&&(t+=.05),n.straightLineRatio>.8&&(t+=.08),n.microMovements<5&&n.totalPoints>50&&(t+=.06),i.webdriver&&(t+=.25),i.automationFlags&&i.automationFlags.plugins===0&&(t+=.05),i.webglInfo&&i.webglInfo.suspiciousRenderer&&(t+=.1),i.headlessIndicators&&!i.headlessIndicators.hasOuterDimensions&&(t+=.12),i.headlessIndicators&&i.headlessIndicators.innerEqualsOuter&&(t+=.05),o.pow&&o.pow.duration<50&&(t+=.1),n.eventDeltaVariance<3&&(t+=.08),n.interactionDuration<300&&(t+=.07);let c=t<.5;return{success:c,score:t,token:c?btoa(JSON.stringify({timestamp:Date.now(),score:t,id:this.id})):null,message:c?null:"Verification failed"}}_showSuccess(e){this.verified=!0,this.token=e,this.checkbox.classList.remove("loading"),this.checkbox.classList.add("verified"),this.checkbox.setAttribute("aria-checked","true"),this.spinner.style.display="none",this.label.textContent="Verified",this.options.callback&&this.options.callback(e),this.container.dispatchEvent(new CustomEvent("webdecoy:verified",{detail:{token:e}}))}_showFailure(e){this.checkbox.classList.remove("loading"),this.checkbox.classList.add("failed"),this.spinner.style.display="none",this.label.textContent=e||"Verification failed",this.options.errorCallback&&this.options.errorCallback(e),setTimeout(()=>{this.checkbox.classList.remove("failed"),this.label.textContent="I'm not a robot"},3e3)}getToken(){return this.token}reset(){this.verified=!1,this.token=null,this.behavioral=new M,this.temporal=new P,this.sensor&&this.sensor.detach(),this.sensor=new C,this.sensor.attach(),this.powManager.reset(),this.checkbox.classList.remove("verified","failed","loading"),this.checkbox.setAttribute("aria-checked","false"),this.spinner.style.display="none",this.label.textContent="I'm not a robot",this._fetchChallenge()}};var F=class{constructor(e){this.lastScore=null;this.listeners=[];this.options=Object.assign({siteKey:null,serverUrl:null,minCollectionTime:2e3,autoScore:!0,scoreThreshold:.5,powDifficulty:3},e),this.id="webdecoy_inv_"+Math.random().toString(36).slice(2,11),this.behavioral=new M,this.environmental=new _,this.temporal=new P,this.sensor=new C,this.powManager=new W,this.startTime=Date.now(),this._init()}_init(){this._attachListeners();let e=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",e,{once:!0}),document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("keydown",e,{once:!0}),document.addEventListener("scroll",e,{once:!0}),this.options.autoScore&&this._attachToForms(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(e){console.warn("PoW challenge fetch failed:",e)}}_attachListeners(){let e={mousemove:t=>this.behavioral.recordMouseMove(t),mousedown:t=>this.behavioral.recordMouseDown(t),mouseup:t=>this.behavioral.recordMouseUp(t),scroll:t=>this.behavioral.recordScroll(t),keydown:t=>this.behavioral.recordKeyEvent(t),keyup:t=>this.behavioral.recordKeyEvent(t),touchmove:t=>this.behavioral.recordTouch(t),touchstart:t=>this.behavioral.recordTouch(t),pointermove:t=>this.behavioral.recordPointer(t),pointerdown:t=>this.behavioral.recordPointer(t),pointerup:t=>this.behavioral.recordPointer(t),focus:t=>this.behavioral.recordFocus(t),blur:t=>this.behavioral.recordFocus(t)};for(let[t,n]of Object.entries(e)){let i=t==="focus"||t==="blur"?{passive:!0,capture:!0}:{passive:!0};document.addEventListener(t,n,i),this.listeners.push({event:t,handler:n,opts:i})}this.sensor.attach()}_attachToForms(){document.addEventListener("submit",e=>{let t=e.target;if(t.dataset.webdecoyIgnore)return;let n=t.querySelector('input[name="webdecoy_token"]');n||(n=document.createElement("input"),n.type="hidden",n.name="webdecoy_token",t.appendChild(n)),!this.lastScore||Date.now()-this.lastScore.timestamp>6e4?(e.preventDefault(),this._scoreThenSubmit(t,n)):n.value=this.lastScore.token||""})}async _scoreThenSubmit(e,t){try{let n=await this.execute(e.dataset.webdecoyAction||"form_submit");t.value=n.token||"",n.success?e.submit():document.dispatchEvent(new CustomEvent("webdecoy:blocked",{detail:{score:n.score,form:e}}))}catch(n){console.error("WebDecoy captcha error:",n),e.submit()}}async execute(e=""){var S;let t=Date.now()-this.startTime;t<this.options.minCollectionTime&&await new Promise(m=>setTimeout(m,this.options.minCollectionTime-t));let n=this.behavioral.analyze(),i=this.environmental.collect(),o=this.temporal.collect(Date.now()),[s,a]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),c=D().analyze(),l=this.sensor.analyze(),u={behavioral:n,environmental:{...i,rafConsistency:s,...a,sensor:l},temporal:o,formAnalysis:c,meta:{sessionId:this.id,siteKey:this.options.siteKey,action:e,challengeNonce:((S=this.powManager.challenge)==null?void 0:S.nonce)||null,timestamp:Date.now(),userAgent:navigator.userAgent,screenSize:`${screen.width}x${screen.height}`,viewportSize:`${window.innerWidth}x${window.innerHeight}`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,sessionDuration:Date.now()-this.startTime,invisible:!0}},h=JSON.stringify(u),v=await T(h),p=await this.powManager.solveWithSignalsHash(this.options.siteKey,v),b={duration:p.duration,iterations:p.iterations,difficulty:p.difficulty},E=await this._score(u,e,p,h,v,b);return this.lastScore={...E,timestamp:Date.now()},E}async _score(e,t,n,i,o,s){let a=this.options.serverUrl||x();if(!a)return this._clientSideScore(e);try{return await(await fetch(a+L()+"/score",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:e,signalsJson:i||null,action:t,powSolution:n?{challengeId:n.challengeId,nonce:n.nonce,hash:n.hash,signalsHash:o||null}:null,powTiming:s||null})})).json()}catch{return console.warn("WebDecoy server unavailable, using client-side scoring"),this._clientSideScore(e)}}_clientSideScore(e){let t=0,n=e.behavioral,i=e.environmental,o=e.temporal,s=e.meta,a=(n.touchEvents||0)>=3,c=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!a&&!c?t+=.35:n.totalPoints<10&&!a&&!c&&n.trajectoryLength<30&&(t+=.15),n.microTremorScore<.2&&(t+=.12),n.velocityVariance<.03&&(t+=.1),n.totalPoints<10&&s.sessionDuration>5e3&&(t+=.08),n.scrollEvents===0&&n.keyEvents===0&&s.sessionDuration>1e4&&(t+=.06),n.eventDeltaVariance<3&&(t+=.08),n.straightLineRatio>.8&&(t+=.08),i.webdriver&&(t+=.25),i.automationFlags&&i.automationFlags.plugins===0&&(t+=.06),i.headlessIndicators&&!i.headlessIndicators.hasOuterDimensions&&(t+=.12),i.webglInfo&&i.webglInfo.suspiciousRenderer&&(t+=.1),o.pow&&o.pow.duration<30&&(t+=.1),s.sessionDuration<500&&(t+=.12),s.sessionDuration<1e3&&n.totalPoints<5&&(t+=.15);let l=t<this.options.scoreThreshold;return{success:l,score:Math.min(1,t),action:s.action,token:l?btoa(JSON.stringify({timestamp:Date.now(),score:t,action:s.action,id:this.id})):null}}getScore(){return this.lastScore}destroy(){for(let{event:e,handler:t,opts:n}of this.listeners)document.removeEventListener(e,t,n);this.listeners=[],this.powManager&&this.powManager.reset()}};var V={widgets:new Map,get serverUrl(){return x()},set serverUrl(r){K(r)},configure(r){r.serverUrl&&K(r.serverUrl),r.basePath&&J(r.basePath)},render(r,e){let t=new I(r,e);return this.widgets.set(t.id,t),t.id},getResponse(r){let e=this.widgets.get(r);return e&&e instanceof I?e.getToken():null},reset(r){let e=this.widgets.get(r);e instanceof I&&e.reset()},invisible(r){let e=new F(r);return this.widgets.set(e.id,e),e},async execute(r,e={}){let t=new F({siteKey:r,serverUrl:x(),minCollectionTime:e.minTime||1e3,autoScore:!1,powDifficulty:e.powDifficulty||3}),n=await t.execute(e.action||"");return t.destroy(),n},getSignals(){return{environmental:new _().collect()}},autoInit(){document.querySelectorAll("[data-webdecoy]").forEach(r=>{let e=r.dataset.sitekey||r.dataset.webdecoy,t=r.dataset.theme||"light",n=r.dataset.endpoint,i=r.dataset.callback,o=i?window[i]:void 0;n&&K(n),this.render(r,{siteKey:e,theme:t,callback:o!=null?o:null})})}};var de=24,me=8,pe=750,ge=1500;function w(r){return typeof r=="number"&&Number.isFinite(r)?r:0}function Q(r){let e=r.mousePositions;return!e||e.length<2?0:Math.max(0,Math.round(e[e.length-1].t-e[0].t))}function ee(r){let e=r.mousePositions.length>=de&&Q(r)>=pe,t=r.touchEvents.length>=me;return e||t}function fe(r){if(!ee(r))return null;let e=r.analyze(),t=r.clickData;return{samples:w(e.totalPoints),duration_ms:Q(r),tremor:w(e.microTremorScore),straight_ratio:w(e.straightLineRatio),velocity_var:w(e.velocityVariance),delta_var:w(e.eventDeltaVariance),dir_changes:w(e.directionChanges),micro_moves:w(e.microMovements),hold_ms:w(t==null?void 0:t.holdDuration),touch_points:w(e.touchTotalPoints),touch_force_var:w(e.touchForceVariance),pointer_nonmouse:e.pointerHasNonMouseType===!0,scrolls:w(e.scrollEvents),keys:w(e.keyEvents)}}function te(r){if(typeof document=="undefined")return()=>{};let e=new M,t=null,n=!1,i={mousemove:a=>e.recordMouseMove(a),mousedown:a=>e.recordMouseDown(a),mouseup:a=>e.recordMouseUp(a),scroll:a=>e.recordScroll(a),keydown:a=>e.recordKeyEvent(a),touchstart:a=>e.recordTouch(a),touchmove:a=>e.recordTouch(a),pointerdown:a=>e.recordPointer(a)},o=()=>{if(!n){n=!0,t&&clearTimeout(t);for(let[a,c]of Object.entries(i))document.removeEventListener(a,c)}},s=()=>{n||t||ee(e)&&(t=setTimeout(()=>{t=null;let a=fe(e);o(),a&&r(a)},ge))};for(let[a,c]of Object.entries(i)){let l=u=>{c(u),s()};i[a]=l,document.addEventListener(a,l,{passive:!0})}return o}var q="wd_clearance",ve="wdfp1",ie="https://ingest.webdecoy.com";async function ye(r){let e=r.canvasHash,t=e&&e.supported?String(e.hash):"na",n=r.webglInfo,i=n&&n.supported?String(n.renderer)+"~"+String(n.vendor):"na",o=`${screen.width}x${screen.height}x${screen.colorDepth}`,s="na";try{s=Intl.DateTimeFormat().resolvedOptions().timeZone||"na"}catch{}let a=navigator.platform||"na",c=navigator.language||"na";return T([ve,t,i,o,s,a,c].join("|"))}var z=12e4,R=6e4,we=18e5,be=1e4;async function _e(r,e,t,n,i){let o=new AbortController,s=setTimeout(()=>o.abort(),be);try{let a=await fetch(r.replace(/\/$/,"")+"/api/v1/clearance",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({aid:e,fp:t,scope:n,ua:navigator.userAgent,webdriver:navigator.webdriver===!0,headless:/HeadlessChrome/.test(navigator.userAgent),...i?{behavior:i}:{}}),signal:o.signal});if(!a.ok)return null;let c=await a.json();if(c.granted&&c.token){let l=c.expires_in;return{token:c.token,expiresIn:typeof l=="number"&&Number.isFinite(l)&&l>0?Math.min(l,1800):1800}}if(c.granted===!1)return{denied:!0}}catch{}finally{clearTimeout(s)}return null}function ne(r){for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(!(t<0)&&e.slice(0,t).trim()===r)return e.slice(t+1).trim()||null}return null}function Ee(r,e){document.cookie=`${q}=${r}; path=/; secure; samesite=lax; max-age=${e}`}function Me(r){let e=window.requestIdleCallback;typeof e=="function"?e.call(window,r,{timeout:1200}):setTimeout(r,1200)}var X=!1,y;function xe(r){try{let e=r.split(".")[0];if(e.length>8192)return Date.now()+R+z;let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t)).exp;if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Math.min(n*1e3,Date.now()+we)}catch{}return Date.now()+R+z}function A(r,e){r.timer!==void 0&&clearTimeout(r.timer),!(r!==y||r.stopped)&&(r.timer=setTimeout(()=>{r.timer=void 0,N(r)},Math.max(1e3,e)))}async function N(r){if(r!==y||r.stopped||r.running)return;let e=ne(q);if(e!==r.token&&(r.token=e,r.expiresAt=e?xe(e):0,r.renewAt=r.expiresAt-Math.min(z,Math.max(0,r.expiresAt-Date.now())/3)),r.retryAt>Date.now()){A(r,r.retryAt-Date.now());return}if(!r.behavior&&e&&r.renewAt>Date.now()){A(r,Math.min(R,r.renewAt-Date.now()));return}r.running=!0;let t=r.behavior;r.behavior=void 0;try{r.fingerprint||(r.fingerprint=(async()=>{let o=new _;return ye({canvasHash:o._getCanvasHash(),webglInfo:o._getWebGLInfo()})})());let n=await r.fingerprint,i=await _e(r.opts.ingestUrl||ie,r.opts.siteKey,n,r.opts.scope||"",t||r.lastBehavior);if(r!==y)return;if(i&&"token"in i)Ee(i.token,i.expiresIn),r.token=ne(q),r.expiresAt=Date.now()+i.expiresIn*1e3,r.renewAt=r.expiresAt-Math.min(z,i.expiresIn*1e3/3),r.failures=0,t&&(r.lastBehavior=t),r.retryAt=0,A(r,Math.min(R,r.renewAt-Date.now()));else if(i&&"denied"in i)r.stopped=!0,r.timer!==void 0&&clearTimeout(r.timer);else{r.failures++;let o=Math.min(3e5,R*Math.pow(2,Math.min(r.failures-1,3)));r.retryAt=Date.now()+o,A(r,o)}}catch{r.fingerprint=void 0,r.failures++;let n=Math.min(3e5,R*Math.pow(2,Math.min(r.failures-1,3)));r.retryAt=Date.now()+n,A(r,n)}finally{r.running=!1,r.behavior&&!r.stopped&&r===y&&A(r,1e3)}}function ke(r){X||(X=!0,te(e=>{r!==y||r.stopped||(r.behavior=e,N(r))}))}function oe(r){if(!r.siteKey||typeof document=="undefined")return;let e=r.ingestUrl||ie,t=JSON.stringify([e.replace(/\/$/,""),r.siteKey,r.scope||""]);if(!y||y.key!==t){y&&(y.timer!==void 0&&clearTimeout(y.timer),document.removeEventListener("visibilitychange",y.wake)),X=!1;let n={key:t,opts:{...r},token:null,expiresAt:0,renewAt:0,retryAt:0,running:!1,stopped:!1,failures:0,wake:()=>{document.visibilityState==="visible"&&N(n)}};y=n,document.addEventListener("visibilitychange",n.wake),Me(()=>{N(n)})}r.behavior!==!1&&ke(y)}var k=document.currentScript;window.WebDecoyCaptcha=V;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>V.autoInit()):V.autoInit();var re=k==null?void 0:k.getAttribute("data-site-key");re&&oe({siteKey:re,ingestUrl:(k==null?void 0:k.getAttribute("data-ingest"))||void 0,scope:(k==null?void 0:k.getAttribute("data-scope"))||void 0});return he(Se);})();
|
|
110
|
+
`,this.checkbox=this.container.querySelector(".webdecoy-checkbox"),this.spinner=this.container.querySelector(".webdecoy-spinner"),this.label=this.container.querySelector(".webdecoy-label")}_attachListeners(){document.addEventListener("mousemove",t=>this.behavioral.recordMouseMove(t),{passive:!0}),document.addEventListener("mousedown",t=>this.behavioral.recordMouseDown(t),{passive:!0}),document.addEventListener("mouseup",t=>this.behavioral.recordMouseUp(t),{passive:!0}),document.addEventListener("scroll",t=>this.behavioral.recordScroll(t),{passive:!0}),document.addEventListener("keydown",t=>this.behavioral.recordKeyEvent(t),{passive:!0}),document.addEventListener("keyup",t=>this.behavioral.recordKeyEvent(t),{passive:!0}),document.addEventListener("touchstart",t=>this.behavioral.recordTouch(t),{passive:!0}),document.addEventListener("touchmove",t=>this.behavioral.recordTouch(t),{passive:!0}),document.addEventListener("pointermove",t=>this.behavioral.recordPointer(t),{passive:!0}),document.addEventListener("pointerdown",t=>this.behavioral.recordPointer(t),{passive:!0}),document.addEventListener("pointerup",t=>this.behavioral.recordPointer(t),{passive:!0}),document.addEventListener("focus",t=>this.behavioral.recordFocus(t),{passive:!0,capture:!0}),document.addEventListener("blur",t=>this.behavioral.recordFocus(t),{passive:!0,capture:!0}),this.sensor.attach();let e=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",e,{once:!0}),document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("keydown",e,{once:!0}),this.checkbox.addEventListener("click",t=>{this._handleClick(t)}),this.checkbox.addEventListener("keydown",t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this._handleClick(t))})}async _handleClick(e){var o,i,s;if(this.verified||this.checkbox.classList.contains("loading"))return;let t=performance.now(),n=this.checkbox.getBoundingClientRect();this.checkbox.classList.add("loading"),this.spinner.style.display="block",this.label.textContent="Verifying...";try{let a=this.behavioral.analyze(),c="clientX"in e?e.clientX:n.left,l="clientY"in e?e.clientY:n.top,u=this.behavioral.analyzeClick(c,l,n),h=this.environmental.collect(),[g,f]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),p=this.temporal.collect(t),y=A().analyze(),w=this.sensor.analyze(),m={behavioral:{...a,...u},environmental:{...h,rafConsistency:g,...f,sensor:w},temporal:p,formAnalysis:y,meta:{widgetId:this.id,siteKey:this.options.siteKey,challengeNonce:((o=this.powManager.challenge)==null?void 0:o.nonce)||null,timestamp:Date.now(),userAgent:navigator.userAgent,screenSize:`${screen.width}x${screen.height}`,viewportSize:`${window.innerWidth}x${window.innerHeight}`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}},v=JSON.stringify(m),d=await C(v),b=await this.powManager.solveWithSignalsHash(this.options.siteKey,d),P={duration:b.duration,iterations:b.iterations,difficulty:b.difficulty},L=await this._verify(m,b,v,d,P);L.success?this._showSuccess((i=L.token)!=null?i:""):this._showFailure((s=L.message)!=null?s:void 0)}catch(a){console.error("WebDecoy captcha error:",a),this._showFailure("Verification failed. Please try again.")}}async _verify(e,t,n,o,i){let s=S();if(!s)return this._clientSideVerify(e);try{return await(await fetch(s+O()+"/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:e,signalsJson:n||null,powSolution:t?{challengeId:t.challengeId,nonce:t.nonce,hash:t.hash,signalsHash:o||null}:null,powTiming:i||null})})).json()}catch{return console.warn("Server unavailable, using client-side verification"),this._clientSideVerify(e)}}_clientSideVerify(e){let t=0,n=e.behavioral,o=e.environmental,i=e.temporal,s=(n.touchEvents||0)>=3,a=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!s&&!a?t+=.35:n.totalPoints<10&&!s&&!a&&n.trajectoryLength<30&&(t+=.15),n.microTremorScore<.2&&(t+=.12),n.velocityVariance<.03&&(t+=.1),n.explorationRatio<.05&&(t+=.08),n.overshootCorrections===0&&n.trajectoryLength>100&&(t+=.05),n.clickPrecision<2&&(t+=.05),n.straightLineRatio>.8&&(t+=.08),n.microMovements<5&&n.totalPoints>50&&(t+=.06),o.webdriver&&(t+=.25),o.automationFlags&&o.automationFlags.plugins===0&&(t+=.05),o.webglInfo&&o.webglInfo.suspiciousRenderer&&(t+=.1),o.headlessIndicators&&!o.headlessIndicators.hasOuterDimensions&&(t+=.12),o.headlessIndicators&&o.headlessIndicators.innerEqualsOuter&&(t+=.05),i.pow&&i.pow.duration<50&&(t+=.1),n.eventDeltaVariance<3&&(t+=.08),n.interactionDuration<300&&(t+=.07);let c=t<.5;return{success:c,score:t,token:c?btoa(JSON.stringify({timestamp:Date.now(),score:t,id:this.id})):null,message:c?null:"Verification failed"}}_showSuccess(e){this.verified=!0,this.token=e,this.checkbox.classList.remove("loading"),this.checkbox.classList.add("verified"),this.checkbox.setAttribute("aria-checked","true"),this.spinner.style.display="none",this.label.textContent="Verified",this.options.callback&&this.options.callback(e),this.container.dispatchEvent(new CustomEvent("webdecoy:verified",{detail:{token:e}}))}_showFailure(e){this.checkbox.classList.remove("loading"),this.checkbox.classList.add("failed"),this.spinner.style.display="none",this.label.textContent=e||"Verification failed",this.options.errorCallback&&this.options.errorCallback(e),setTimeout(()=>{this.checkbox.classList.remove("failed"),this.label.textContent="I'm not a robot"},3e3)}getToken(){return this.token}reset(){this.verified=!1,this.token=null,this.behavioral=new M,this.temporal=new I,this.sensor&&this.sensor.detach(),this.sensor=new R,this.sensor.attach(),this.powManager.reset(),this.checkbox.classList.remove("verified","failed","loading"),this.checkbox.setAttribute("aria-checked","false"),this.spinner.style.display="none",this.label.textContent="I'm not a robot",this._fetchChallenge()}};var U=class{constructor(e){this.lastScore=null;this.listeners=[];this.options=Object.assign({siteKey:null,serverUrl:null,minCollectionTime:2e3,autoScore:!0,scoreThreshold:.5,powDifficulty:3},e),this.id="webdecoy_inv_"+Math.random().toString(36).slice(2,11),this.behavioral=new M,this.environmental=new T,this.temporal=new I,this.sensor=new R,this.powManager=new K,this.startTime=Date.now(),this._init()}_init(){this._attachListeners();let e=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",e,{once:!0}),document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("keydown",e,{once:!0}),document.addEventListener("scroll",e,{once:!0}),this.options.autoScore&&this._attachToForms(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(e){console.warn("PoW challenge fetch failed:",e)}}_attachListeners(){let e={mousemove:t=>this.behavioral.recordMouseMove(t),mousedown:t=>this.behavioral.recordMouseDown(t),mouseup:t=>this.behavioral.recordMouseUp(t),scroll:t=>this.behavioral.recordScroll(t),keydown:t=>this.behavioral.recordKeyEvent(t),keyup:t=>this.behavioral.recordKeyEvent(t),touchmove:t=>this.behavioral.recordTouch(t),touchstart:t=>this.behavioral.recordTouch(t),pointermove:t=>this.behavioral.recordPointer(t),pointerdown:t=>this.behavioral.recordPointer(t),pointerup:t=>this.behavioral.recordPointer(t),focus:t=>this.behavioral.recordFocus(t),blur:t=>this.behavioral.recordFocus(t)};for(let[t,n]of Object.entries(e)){let o=t==="focus"||t==="blur"?{passive:!0,capture:!0}:{passive:!0};document.addEventListener(t,n,o),this.listeners.push({event:t,handler:n,opts:o})}this.sensor.attach()}_attachToForms(){document.addEventListener("submit",e=>{let t=e.target;if(t.dataset.webdecoyIgnore)return;let n=t.querySelector('input[name="webdecoy_token"]');n||(n=document.createElement("input"),n.type="hidden",n.name="webdecoy_token",t.appendChild(n)),!this.lastScore||Date.now()-this.lastScore.timestamp>6e4?(e.preventDefault(),this._scoreThenSubmit(t,n)):n.value=this.lastScore.token||""})}async _scoreThenSubmit(e,t){try{let n=await this.execute(e.dataset.webdecoyAction||"form_submit");t.value=n.token||"",n.success?e.submit():document.dispatchEvent(new CustomEvent("webdecoy:blocked",{detail:{score:n.score,form:e}}))}catch(n){console.error("WebDecoy captcha error:",n),e.submit()}}async execute(e=""){var w;let t=Date.now()-this.startTime;t<this.options.minCollectionTime&&await new Promise(m=>setTimeout(m,this.options.minCollectionTime-t));let n=this.behavioral.analyze(),o=this.environmental.collect(),i=this.temporal.collect(Date.now()),[s,a]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),c=A().analyze(),l=this.sensor.analyze(),u={behavioral:n,environmental:{...o,rafConsistency:s,...a,sensor:l},temporal:i,formAnalysis:c,meta:{sessionId:this.id,siteKey:this.options.siteKey,action:e,challengeNonce:((w=this.powManager.challenge)==null?void 0:w.nonce)||null,timestamp:Date.now(),userAgent:navigator.userAgent,screenSize:`${screen.width}x${screen.height}`,viewportSize:`${window.innerWidth}x${window.innerHeight}`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,sessionDuration:Date.now()-this.startTime,invisible:!0}},h=JSON.stringify(u),g=await C(h),f=await this.powManager.solveWithSignalsHash(this.options.siteKey,g),p={duration:f.duration,iterations:f.iterations,difficulty:f.difficulty},y=await this._score(u,e,f,h,g,p);return this.lastScore={...y,timestamp:Date.now()},y}async _score(e,t,n,o,i,s){let a=this.options.serverUrl||S();if(!a)return this._clientSideScore(e);try{return await(await fetch(a+O()+"/score",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:e,signalsJson:o||null,action:t,powSolution:n?{challengeId:n.challengeId,nonce:n.nonce,hash:n.hash,signalsHash:i||null}:null,powTiming:s||null})})).json()}catch{return console.warn("WebDecoy server unavailable, using client-side scoring"),this._clientSideScore(e)}}_clientSideScore(e){let t=0,n=e.behavioral,o=e.environmental,i=e.temporal,s=e.meta,a=(n.touchEvents||0)>=3,c=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!a&&!c?t+=.35:n.totalPoints<10&&!a&&!c&&n.trajectoryLength<30&&(t+=.15),n.microTremorScore<.2&&(t+=.12),n.velocityVariance<.03&&(t+=.1),n.totalPoints<10&&s.sessionDuration>5e3&&(t+=.08),n.scrollEvents===0&&n.keyEvents===0&&s.sessionDuration>1e4&&(t+=.06),n.eventDeltaVariance<3&&(t+=.08),n.straightLineRatio>.8&&(t+=.08),o.webdriver&&(t+=.25),o.automationFlags&&o.automationFlags.plugins===0&&(t+=.06),o.headlessIndicators&&!o.headlessIndicators.hasOuterDimensions&&(t+=.12),o.webglInfo&&o.webglInfo.suspiciousRenderer&&(t+=.1),i.pow&&i.pow.duration<30&&(t+=.1),s.sessionDuration<500&&(t+=.12),s.sessionDuration<1e3&&n.totalPoints<5&&(t+=.15);let l=t<this.options.scoreThreshold;return{success:l,score:Math.min(1,t),action:s.action,token:l?btoa(JSON.stringify({timestamp:Date.now(),score:t,action:s.action,id:this.id})):null}}getScore(){return this.lastScore}destroy(){for(let{event:e,handler:t,opts:n}of this.listeners)document.removeEventListener(e,t,n);this.listeners=[],this.powManager&&this.powManager.reset()}};var z={widgets:new Map,get serverUrl(){return S()},set serverUrl(r){B(r)},configure(r){r.serverUrl&&B(r.serverUrl),r.basePath&&le(r.basePath)},render(r,e){let t=new F(r,e);return this.widgets.set(t.id,t),t.id},getResponse(r){let e=this.widgets.get(r);return e&&e instanceof F?e.getToken():null},reset(r){let e=this.widgets.get(r);e instanceof F&&e.reset()},invisible(r){let e=new U(r);return this.widgets.set(e.id,e),e},async execute(r,e={}){let t=new U({siteKey:r,serverUrl:S(),minCollectionTime:e.minTime||1e3,autoScore:!1,powDifficulty:e.powDifficulty||3}),n=await t.execute(e.action||"");return t.destroy(),n},getSignals(){return{environmental:new T().collect()}},autoInit(){document.querySelectorAll("[data-webdecoy]").forEach(r=>{let e=r.dataset.sitekey||r.dataset.webdecoy,t=r.dataset.theme||"light",n=r.dataset.endpoint,o=r.dataset.callback,i=o?window[o]:void 0;n&&B(n),this.render(r,{siteKey:e,theme:t,callback:i!=null?i:null})})}};var Te=24,Me=8,Se=750,ke=1500;function E(r){return typeof r=="number"&&Number.isFinite(r)?r:0}function he(r){let e=r.mousePositions;return!e||e.length<2?0:Math.max(0,Math.round(e[e.length-1].t-e[0].t))}function de(r){let e=r.mousePositions.length>=Te&&he(r)>=Se,t=r.touchEvents.length>=Me;return e||t}function Ce(r){if(!de(r))return null;let e=r.analyze(),t=r.clickData;return{samples:E(e.totalPoints),duration_ms:he(r),tremor:E(e.microTremorScore),straight_ratio:E(e.straightLineRatio),velocity_var:E(e.velocityVariance),delta_var:E(e.eventDeltaVariance),dir_changes:E(e.directionChanges),micro_moves:E(e.microMovements),hold_ms:E(t==null?void 0:t.holdDuration),touch_points:E(e.touchTotalPoints),touch_force_var:E(e.touchForceVariance),pointer_nonmouse:e.pointerHasNonMouseType===!0,scrolls:E(e.scrollEvents),keys:E(e.keyEvents)}}function me(r){if(typeof document=="undefined")return()=>{};let e=new M,t=null,n=!1,o={mousemove:a=>e.recordMouseMove(a),mousedown:a=>e.recordMouseDown(a),mouseup:a=>e.recordMouseUp(a),scroll:a=>e.recordScroll(a),keydown:a=>e.recordKeyEvent(a),touchstart:a=>e.recordTouch(a),touchmove:a=>e.recordTouch(a),pointerdown:a=>e.recordPointer(a)},i=()=>{if(!n){n=!0,t&&clearTimeout(t);for(let[a,c]of Object.entries(o))document.removeEventListener(a,c)}},s=()=>{n||t||de(e)&&(t=setTimeout(()=>{t=null;let a=Ce(e);i(),a&&r(a)},ke))};for(let[a,c]of Object.entries(o)){let l=u=>{c(u),s()};o[a]=l,document.addEventListener(a,l,{passive:!0})}return i}var Z="wd_clearance",Pe="wdfp1",pe="https://ingest.webdecoy.com";async function Le(r){let e=r.canvasHash,t=e&&e.supported?String(e.hash):"na",n=r.webglInfo,o=n&&n.supported?String(n.renderer)+"~"+String(n.vendor):"na",i=`${screen.width}x${screen.height}x${screen.colorDepth}`,s="na";try{s=Intl.DateTimeFormat().resolvedOptions().timeZone||"na"}catch{}let a=navigator.platform||"na",c=navigator.language||"na";return C([Pe,t,o,i,s,a,c].join("|"))}var q=12e4,V=6e4,De=18e5,Re=1e4;async function Ie(r,e,t,n,o){let i=new AbortController,s=setTimeout(()=>i.abort(),Re);try{let a=await fetch(r.replace(/\/$/,"")+"/api/v1/clearance",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({aid:e,fp:t,scope:n,ua:navigator.userAgent,webdriver:navigator.webdriver===!0,headless:/HeadlessChrome/.test(navigator.userAgent),...o?{behavior:o}:{}}),signal:i.signal});if(!a.ok)return null;let c=await a.json();if(c.granted&&c.token){let l=c.expires_in;return{token:c.token,expiresIn:typeof l=="number"&&Number.isFinite(l)&&l>0?Math.min(l,1800):1800}}if(c.granted===!1)return{denied:!0}}catch{}finally{clearTimeout(s)}return null}function ge(r){for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(!(t<0)&&e.slice(0,t).trim()===r)return e.slice(t+1).trim()||null}return null}function Ae(r,e){document.cookie=`${Z}=${r}; path=/; secure; samesite=lax; max-age=${e}`}function Oe(r){let e=window.requestIdleCallback;typeof e=="function"?e.call(window,r,{timeout:1200}):setTimeout(r,1200)}var Q=!1,_;function Fe(r){try{let e=r.split(".")[0];if(e.length>8192)return Date.now()+V+q;let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t)).exp;if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Math.min(n*1e3,Date.now()+De)}catch{}return Date.now()+V+q}function W(r,e){r.timer!==void 0&&clearTimeout(r.timer),!(r!==_||r.stopped)&&(r.timer=setTimeout(()=>{r.timer=void 0,$(r)},Math.max(1e3,e)))}async function $(r){if(r!==_||r.stopped||r.running)return;let e=ge(Z);if(e!==r.token&&(r.token=e,r.expiresAt=e?Fe(e):0,r.renewAt=r.expiresAt-Math.min(q,Math.max(0,r.expiresAt-Date.now())/3)),r.retryAt>Date.now()){W(r,r.retryAt-Date.now());return}if(!r.behavior&&e&&r.renewAt>Date.now()){W(r,Math.min(V,r.renewAt-Date.now()));return}r.running=!0;let t=r.behavior;r.behavior=void 0;try{r.fingerprint||(r.fingerprint=(async()=>{let i=new T;return Le({canvasHash:i._getCanvasHash(),webglInfo:i._getWebGLInfo()})})());let n=await r.fingerprint,o=await Ie(r.opts.ingestUrl||pe,r.opts.siteKey,n,r.opts.scope||"",t||r.lastBehavior);if(r!==_)return;if(o&&"token"in o)Ae(o.token,o.expiresIn),r.token=ge(Z),r.expiresAt=Date.now()+o.expiresIn*1e3,r.renewAt=r.expiresAt-Math.min(q,o.expiresIn*1e3/3),r.failures=0,t&&(r.lastBehavior=t),r.retryAt=0,W(r,Math.min(V,r.renewAt-Date.now()));else if(o&&"denied"in o)r.stopped=!0,r.timer!==void 0&&clearTimeout(r.timer);else{r.failures++;let i=Math.min(3e5,V*Math.pow(2,Math.min(r.failures-1,3)));r.retryAt=Date.now()+i,W(r,i)}}catch{r.fingerprint=void 0,r.failures++;let n=Math.min(3e5,V*Math.pow(2,Math.min(r.failures-1,3)));r.retryAt=Date.now()+n,W(r,n)}finally{r.running=!1,r.behavior&&!r.stopped&&r===_&&W(r,1e3)}}function We(r){Q||(Q=!0,me(e=>{r!==_||r.stopped||(r.behavior=e,$(r))}))}function fe(r){if(!r.siteKey||typeof document=="undefined")return;let e=r.ingestUrl||pe,t=JSON.stringify([e.replace(/\/$/,""),r.siteKey,r.scope||""]);if(!_||_.key!==t){_&&(_.timer!==void 0&&clearTimeout(_.timer),document.removeEventListener("visibilitychange",_.wake)),Q=!1;let n={key:t,opts:{...r},token:null,expiresAt:0,renewAt:0,retryAt:0,running:!1,stopped:!1,failures:0,wake:()=>{document.visibilityState==="visible"&&$(n)}};_=n,document.addEventListener("visibilitychange",n.wake),Oe(()=>{$(n)})}r.behavior!==!1&&We(_)}var Ve=["missing","invalid","insufficient-trust","revoked","crawler-refused","agent-impersonation","denied"],He=["missing","invalid","insufficient-trust"];function H(r){if(r.status!==403||r.headers.get("x-wd-clearance")!=="challenged"||r.headers.get("x-wd-challenge")!=="1")return null;let e=r.headers.get("x-wd-challenge-reason"),t=r.headers.get("x-wd-challenge-recoverable");return!e||!Ve.includes(e)||t!=="true"&&t!=="false"?null:{version:1,reason:e,recoverable:t==="true"&&He.includes(e)}}function N(r){var e;return(e=r.reason)!=null?e:new DOMException("The operation was aborted","AbortError")}function ee(r,e){return new Promise((t,n)=>{if(e.aborted){n(N(e));return}let o=()=>n(N(e));e.addEventListener("abort",o,{once:!0}),r.then(t,n).finally(()=>e.removeEventListener("abort",o))})}function te(r){var c,l;let e=new URL(r.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw new TypeError("A protected HTTP(S) origin is required");let t=e.origin,n=(c=r.timeoutMs)!=null?c:1e4;if(!Number.isFinite(n)||n<1||n>6e4)throw new RangeError("timeoutMs must be between 1 and 60000");let o=(l=r.fetch)!=null?l:globalThis.fetch.bind(globalThis),i;function s(u,h,g,f){var p;try{(p=r.onEvent)==null||p.call(r,{type:u,origin:t,method:h,challenge:g,status:f})}catch{}}function a(u){if(!i){let h=new AbortController,g={controller:h,users:0,promise:Promise.resolve(!1)};i=g;let f=setTimeout(()=>h.abort(new DOMException("Clearance recovery timed out","TimeoutError")),n);h.signal.addEventListener("abort",()=>clearTimeout(f),{once:!0});let p=Promise.resolve().then(()=>r.recover({origin:t,challenge:u,signal:h.signal}));g.promise=ee(p,h.signal).then(w=>w===!0,()=>!1);let y=()=>{clearTimeout(f),i===g&&(i=void 0)};p.then(y,y)}return i.users++,i}return async(u,h)=>{var re,ie;let g=((re=h==null?void 0:h.method)!=null?re:u instanceof Request?u.method:"GET").toUpperCase();if(g!=="GET"&&g!=="HEAD"){let x=await o(u,h),X=u instanceof Request?u.url:String(u),D=new URL(X,typeof document!="undefined"?document.baseURI:void 0),se=H(x);return se&&D.origin===t&&!x.redirected&&(!x.url||new URL(x.url).origin===t)&&s("challenge-served",g,se,x.status),x}let f=u instanceof Request?u:new URL(String(u),typeof document!="undefined"?document.baseURI:void 0).href,p=new Request(f,h),y=await o(p),w=H(y);if(!w||new URL(p.url).origin!==t||y.redirected||y.url&&new URL(y.url).origin!==t)return y;s("challenge-served",g,w,y.status);let m=typeof location!="undefined"?location.origin:t;if(!w.recoverable||p.credentials==="omit"||m!==t&&p.credentials!=="include"||typeof navigator!="undefined"&&navigator.onLine===!1||typeof AbortSignal.any!="function")return y;if(p.signal.aborted)throw N(p.signal);let v=new AbortController,d=!1,b=()=>v.abort(N(p.signal));p.signal.addEventListener("abort",b,{once:!0});let P=setTimeout(()=>{d=!0,v.abort(new DOMException("Clearance recovery timed out","TimeoutError"))},n),L=a(w);s("recovery-attempted",g,w);let ne=!1,oe=()=>{ne||(ne=!0,--L.users===0&&L.controller.abort())};try{let x=await ee(L.promise,v.signal);if(oe(),!x||v.signal.aborted)return s("recovery-failed",g,w),y;let X=AbortSignal.any([p.signal,v.signal]),D=await ee(o(new Request(p,{signal:X})),v.signal);return s("enforcement-outcome",g,(ie=H(D))!=null?ie:w,D.status),s(D.ok?"recovery-succeeded":"recovery-failed",g,w,D.status),D}catch(x){if(s("recovery-failed",g,w),p.signal.aborted)throw N(p.signal);if(d)return y;throw x}finally{oe(),clearTimeout(P),p.signal.removeEventListener("abort",b)}}}var k=document.currentScript;window.WebDecoyCaptcha=z;window.WebDecoyClearance={createClearanceFetch:te,readClearanceChallenge:H};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>z.autoInit()):z.autoInit();var ve=k==null?void 0:k.getAttribute("data-site-key");ve&&fe({siteKey:ve,ingestUrl:(k==null?void 0:k.getAttribute("data-ingest"))||void 0,scope:(k==null?void 0:k.getAttribute("data-scope"))||void 0});return xe(Ke);})();
|