@webdecoy/client 0.4.1 → 0.6.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @webdecoy/client
2
2
 
3
- Browser widget for [WebDecoy](https://github.com/WebDecoy/node-sdk) captcha — collects behavioral, environmental, and fingerprint signals, solves a SHA-256 proof-of-work, and submits to your WebDecoy-protected server.
3
+ Browser widget for [WebDecoy](https://github.com/WebDecoy/node) captcha — collects behavioral, environmental, and fingerprint signals, solves a SHA-256 proof-of-work, and submits to your WebDecoy-protected server.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@webdecoy/client.svg)](https://www.npmjs.com/package/@webdecoy/client)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
package/dist/index.d.mts CHANGED
@@ -473,4 +473,149 @@ declare function getFormAnalyzer(): FormAnalyzer;
473
473
  /** Async SHA-256 hex digest via the Web Crypto API. */
474
474
  declare function sha256(message: string): Promise<string>;
475
475
 
476
- export { BehavioralCollector, CaptchaWidget, type Challenge, type CollectedSignals, EnvironmentalCollector, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, getFormAnalyzer, getPoWManager, sha256 };
476
+ /**
477
+ * wd_clearance minting (WAF Enforcement PRD FR6 / closes the #124 loop).
478
+ *
479
+ * Real browsers earn a signed clearance token from WebDecoy's ingest service and
480
+ * carry it in a first-party cookie. The edge validator (FR7) lets tokened
481
+ * sessions through; a decoy hit denies the token's fp (deny-at-mint + live-token
482
+ * revocation). This is the *allow-and-observe* path — it mints silently during
483
+ * normal browsing so the loop covers monitor mode, not just the enforce-mode
484
+ * challenge interstitial.
485
+ *
486
+ * PERFORMANCE: the mint is deferred to idle, runs at most once per session (skips
487
+ * when a fresh cookie already exists), and never solves a proof-of-work. The only
488
+ * device-tier work — one canvas + one WebGL read — is done by the collector, once.
489
+ * computeDeviceFP itself does NO canvas/WebGL: it consumes the collector's output.
490
+ */
491
+ declare const CLEARANCE_COOKIE = "wd_clearance";
492
+ /**
493
+ * Canonical device-fp algorithm version. This fp is the ENFORCEMENT identity —
494
+ * the clearance token binds to it and the deny-list keys on it — so the string
495
+ * is a CONTRACT. Three implementations must agree byte-for-byte:
496
+ *
497
+ * 1. this function
498
+ * 2. app repo `edge/clearance-worker/src/device-fp.ts` (the interstitial)
499
+ * 3. app repo `cdn/pro/bot-detection-pro.js` computeClearanceFP()
500
+ *
501
+ * If two of them computed different fps for the same browser, a decoy-triggered
502
+ * deny would catch one and not the other — the lockout would leak, silently.
503
+ * All three are pinned to the same golden vector (see clearance.test.ts here,
504
+ * and the device-fp tests in the app repo).
505
+ *
506
+ * Do NOT confuse this with the `device_fp` the scoring pipeline composes
507
+ * server-side: that is a correlation key that works without any token, this is
508
+ * what a deny actually locks out. They are different identity spaces.
509
+ *
510
+ * Bump the version prefix (never edit in place) to evolve the algorithm.
511
+ */
512
+ declare const FP_VERSION = "wdfp1";
513
+ /** Default WebDecoy ingest origin (issuance endpoint host). */
514
+ declare const DEFAULT_INGEST_URL = "https://ingest.webdecoy.com";
515
+ interface DeviceFPInputs {
516
+ /** Collector _getCanvasHash() output — { hash, supported } or { supported:false }. */
517
+ canvasHash: Record<string, unknown> | null;
518
+ /** Collector _getWebGLInfo() output — { renderer, vendor, supported } or { supported:false }. */
519
+ webglInfo: Record<string, unknown> | null;
520
+ }
521
+ /**
522
+ * Stable device fingerprint the clearance token binds to. PURE: the caller passes
523
+ * the collector's already-computed canvas/WebGL signals; this function performs no
524
+ * canvas/WebGL work of its own (only cheap synchronous property reads). Uses the
525
+ * stable device subset — canvas, WebGL, screen, timezone, platform, language — and
526
+ * deliberately excludes User-Agent (churns on browser auto-update) and any
527
+ * behavioral/session signal (would change per load).
528
+ */
529
+ declare function computeDeviceFP(env: DeviceFPInputs): Promise<string>;
530
+ interface ClearanceOptions {
531
+ siteKey: string;
532
+ /** WebDecoy ingest origin. Defaults to DEFAULT_INGEST_URL. */
533
+ ingestUrl?: string;
534
+ /** Route-group scope; '' = tenant-wide (default), valid on every route. */
535
+ scope?: string;
536
+ /**
537
+ * Collect interaction aggregates and upgrade the token to a graded
538
+ * 'human-likely' trust level once the visitor actually interacts (#328).
539
+ * Default true. Set false to mint clean tokens only — routes that require a
540
+ * minimum trust level will then always challenge.
541
+ *
542
+ * See clearance-behavior.ts for exactly what is collected; it is aggregate
543
+ * counts and variances, never coordinates, keys or content.
544
+ */
545
+ behavior?: boolean;
546
+ }
547
+ /**
548
+ * Start silent clearance minting. Idempotent guard, deferred to idle, at most once
549
+ * per session: if a fresh cookie already exists it only schedules a refresh; only
550
+ * an absent/near-expiry cookie triggers a collect + mint. Never blocks paint or
551
+ * interaction; failures are swallowed (the edge validator fails open regardless).
552
+ */
553
+ declare function startClearance(opts: ClearanceOptions): void;
554
+
555
+ /**
556
+ * Behavioral human-likelihood for clearance minting (app repo #328, PRD FR10).
557
+ *
558
+ * A wd_clearance token normally says only "this is a real browser that hasn't
559
+ * tripped deception". This module lets a session also present POSITIVE evidence
560
+ * that a human is driving it, which the mint turns into a graded 'human-likely'
561
+ * token — the grade a route can require for its most sensitive paths.
562
+ *
563
+ * WHAT LEAVES THE BROWSER (this is the whole list):
564
+ * counts — how many pointer samples, scrolls, keystrokes, touches
565
+ * durations — the observation window, and how long a click was held
566
+ * variances — of pointer velocity, of inter-event timing, of touch force
567
+ * ratios — micro-tremor and collinearity of the pointer path, 0–1
568
+ *
569
+ * WHAT NEVER LEAVES THE BROWSER: pointer coordinates, the keys pressed, form
570
+ * values, element or page content, URLs, screenshots, and any kind of replayable
571
+ * event stream. Nothing here can reconstruct what a person typed, read, clicked
572
+ * or looked at — the aggregates describe HOW the session moved, never WHAT it
573
+ * did. That is the whole difference between this and a session-replay vendor,
574
+ * and it is why the collection contract is published rather than buried.
575
+ *
576
+ * The scoring itself is deliberately NOT done here: the browser reports
577
+ * observations, the server decides what they earn. A client that fabricates
578
+ * flattering aggregates gains nothing it could not gain by lying about its
579
+ * fingerprint, and the mint caps any grade by the actor's threat score.
580
+ */
581
+
582
+ /** The wire shape posted as `behavior` on a clearance mint. */
583
+ interface BehaviorAggregate {
584
+ samples: number;
585
+ duration_ms: number;
586
+ tremor: number;
587
+ straight_ratio: number;
588
+ velocity_var: number;
589
+ delta_var: number;
590
+ dir_changes: number;
591
+ micro_moves: number;
592
+ hold_ms: number;
593
+ touch_points: number;
594
+ touch_force_var: number;
595
+ pointer_nonmouse: boolean;
596
+ scrolls: number;
597
+ keys: number;
598
+ }
599
+ /** Whether the session has enough interaction to be worth summarizing. */
600
+ declare function hasEnoughInteraction(collector: BehavioralCollector): boolean;
601
+ /**
602
+ * Reduce a collector to the published aggregate set. Returns null when the
603
+ * session has too little interaction to describe — an unscored mint is a clean
604
+ * token, which is exactly what a keyboard-only or assistive-technology session
605
+ * should get rather than a low score it never earned.
606
+ */
607
+ declare function summarizeBehavior(collector: BehavioralCollector): BehaviorAggregate | null;
608
+ /**
609
+ * Watch the session until it has enough interaction to summarize, then hand the
610
+ * aggregate over ONCE and stop listening.
611
+ *
612
+ * All listeners are passive (they never delay scrolling or input) and are
613
+ * removed as soon as the summary is delivered, so the steady-state cost of a
614
+ * cleared session is zero. A session that never interacts never fires, never
615
+ * posts, and keeps the clean token it already has.
616
+ *
617
+ * Returns a cancel function for callers that unmount.
618
+ */
619
+ declare function watchInteraction(onReady: (b: BehaviorAggregate) => void): () => void;
620
+
621
+ 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 };
package/dist/index.d.ts CHANGED
@@ -473,4 +473,149 @@ declare function getFormAnalyzer(): FormAnalyzer;
473
473
  /** Async SHA-256 hex digest via the Web Crypto API. */
474
474
  declare function sha256(message: string): Promise<string>;
475
475
 
476
- export { BehavioralCollector, CaptchaWidget, type Challenge, type CollectedSignals, EnvironmentalCollector, FormAnalyzer, type InvisibleOptions, InvisibleSession, PoWManager, type PoWSolution, SensorCollector, TemporalCollector, type VerifyResponse, WebDecoyCaptcha, type WebDecoyCaptchaAPI, type WidgetOptions, getFormAnalyzer, getPoWManager, sha256 };
476
+ /**
477
+ * wd_clearance minting (WAF Enforcement PRD FR6 / closes the #124 loop).
478
+ *
479
+ * Real browsers earn a signed clearance token from WebDecoy's ingest service and
480
+ * carry it in a first-party cookie. The edge validator (FR7) lets tokened
481
+ * sessions through; a decoy hit denies the token's fp (deny-at-mint + live-token
482
+ * revocation). This is the *allow-and-observe* path — it mints silently during
483
+ * normal browsing so the loop covers monitor mode, not just the enforce-mode
484
+ * challenge interstitial.
485
+ *
486
+ * PERFORMANCE: the mint is deferred to idle, runs at most once per session (skips
487
+ * when a fresh cookie already exists), and never solves a proof-of-work. The only
488
+ * device-tier work — one canvas + one WebGL read — is done by the collector, once.
489
+ * computeDeviceFP itself does NO canvas/WebGL: it consumes the collector's output.
490
+ */
491
+ declare const CLEARANCE_COOKIE = "wd_clearance";
492
+ /**
493
+ * Canonical device-fp algorithm version. This fp is the ENFORCEMENT identity —
494
+ * the clearance token binds to it and the deny-list keys on it — so the string
495
+ * is a CONTRACT. Three implementations must agree byte-for-byte:
496
+ *
497
+ * 1. this function
498
+ * 2. app repo `edge/clearance-worker/src/device-fp.ts` (the interstitial)
499
+ * 3. app repo `cdn/pro/bot-detection-pro.js` computeClearanceFP()
500
+ *
501
+ * If two of them computed different fps for the same browser, a decoy-triggered
502
+ * deny would catch one and not the other — the lockout would leak, silently.
503
+ * All three are pinned to the same golden vector (see clearance.test.ts here,
504
+ * and the device-fp tests in the app repo).
505
+ *
506
+ * Do NOT confuse this with the `device_fp` the scoring pipeline composes
507
+ * server-side: that is a correlation key that works without any token, this is
508
+ * what a deny actually locks out. They are different identity spaces.
509
+ *
510
+ * Bump the version prefix (never edit in place) to evolve the algorithm.
511
+ */
512
+ declare const FP_VERSION = "wdfp1";
513
+ /** Default WebDecoy ingest origin (issuance endpoint host). */
514
+ declare const DEFAULT_INGEST_URL = "https://ingest.webdecoy.com";
515
+ interface DeviceFPInputs {
516
+ /** Collector _getCanvasHash() output — { hash, supported } or { supported:false }. */
517
+ canvasHash: Record<string, unknown> | null;
518
+ /** Collector _getWebGLInfo() output — { renderer, vendor, supported } or { supported:false }. */
519
+ webglInfo: Record<string, unknown> | null;
520
+ }
521
+ /**
522
+ * Stable device fingerprint the clearance token binds to. PURE: the caller passes
523
+ * the collector's already-computed canvas/WebGL signals; this function performs no
524
+ * canvas/WebGL work of its own (only cheap synchronous property reads). Uses the
525
+ * stable device subset — canvas, WebGL, screen, timezone, platform, language — and
526
+ * deliberately excludes User-Agent (churns on browser auto-update) and any
527
+ * behavioral/session signal (would change per load).
528
+ */
529
+ declare function computeDeviceFP(env: DeviceFPInputs): Promise<string>;
530
+ interface ClearanceOptions {
531
+ siteKey: string;
532
+ /** WebDecoy ingest origin. Defaults to DEFAULT_INGEST_URL. */
533
+ ingestUrl?: string;
534
+ /** Route-group scope; '' = tenant-wide (default), valid on every route. */
535
+ scope?: string;
536
+ /**
537
+ * Collect interaction aggregates and upgrade the token to a graded
538
+ * 'human-likely' trust level once the visitor actually interacts (#328).
539
+ * Default true. Set false to mint clean tokens only — routes that require a
540
+ * minimum trust level will then always challenge.
541
+ *
542
+ * See clearance-behavior.ts for exactly what is collected; it is aggregate
543
+ * counts and variances, never coordinates, keys or content.
544
+ */
545
+ behavior?: boolean;
546
+ }
547
+ /**
548
+ * Start silent clearance minting. Idempotent guard, deferred to idle, at most once
549
+ * per session: if a fresh cookie already exists it only schedules a refresh; only
550
+ * an absent/near-expiry cookie triggers a collect + mint. Never blocks paint or
551
+ * interaction; failures are swallowed (the edge validator fails open regardless).
552
+ */
553
+ declare function startClearance(opts: ClearanceOptions): void;
554
+
555
+ /**
556
+ * Behavioral human-likelihood for clearance minting (app repo #328, PRD FR10).
557
+ *
558
+ * A wd_clearance token normally says only "this is a real browser that hasn't
559
+ * tripped deception". This module lets a session also present POSITIVE evidence
560
+ * that a human is driving it, which the mint turns into a graded 'human-likely'
561
+ * token — the grade a route can require for its most sensitive paths.
562
+ *
563
+ * WHAT LEAVES THE BROWSER (this is the whole list):
564
+ * counts — how many pointer samples, scrolls, keystrokes, touches
565
+ * durations — the observation window, and how long a click was held
566
+ * variances — of pointer velocity, of inter-event timing, of touch force
567
+ * ratios — micro-tremor and collinearity of the pointer path, 0–1
568
+ *
569
+ * WHAT NEVER LEAVES THE BROWSER: pointer coordinates, the keys pressed, form
570
+ * values, element or page content, URLs, screenshots, and any kind of replayable
571
+ * event stream. Nothing here can reconstruct what a person typed, read, clicked
572
+ * or looked at — the aggregates describe HOW the session moved, never WHAT it
573
+ * did. That is the whole difference between this and a session-replay vendor,
574
+ * and it is why the collection contract is published rather than buried.
575
+ *
576
+ * The scoring itself is deliberately NOT done here: the browser reports
577
+ * observations, the server decides what they earn. A client that fabricates
578
+ * flattering aggregates gains nothing it could not gain by lying about its
579
+ * fingerprint, and the mint caps any grade by the actor's threat score.
580
+ */
581
+
582
+ /** The wire shape posted as `behavior` on a clearance mint. */
583
+ interface BehaviorAggregate {
584
+ samples: number;
585
+ duration_ms: number;
586
+ tremor: number;
587
+ straight_ratio: number;
588
+ velocity_var: number;
589
+ delta_var: number;
590
+ dir_changes: number;
591
+ micro_moves: number;
592
+ hold_ms: number;
593
+ touch_points: number;
594
+ touch_force_var: number;
595
+ pointer_nonmouse: boolean;
596
+ scrolls: number;
597
+ keys: number;
598
+ }
599
+ /** Whether the session has enough interaction to be worth summarizing. */
600
+ declare function hasEnoughInteraction(collector: BehavioralCollector): boolean;
601
+ /**
602
+ * Reduce a collector to the published aggregate set. Returns null when the
603
+ * session has too little interaction to describe — an unscored mint is a clean
604
+ * token, which is exactly what a keyboard-only or assistive-technology session
605
+ * should get rather than a low score it never earned.
606
+ */
607
+ declare function summarizeBehavior(collector: BehavioralCollector): BehaviorAggregate | null;
608
+ /**
609
+ * Watch the session until it has enough interaction to summarize, then hand the
610
+ * aggregate over ONCE and stop listening.
611
+ *
612
+ * All listeners are passive (they never delay scrolling or input) and are
613
+ * removed as soon as the summary is delivered, so the steady-state cost of a
614
+ * cleared session is zero. A session that never interacts never fires, never
615
+ * posts, and keeps the clean token it already has.
616
+ *
617
+ * Returns a cancel function for callers that unmount.
618
+ */
619
+ declare function watchInteraction(onReady: (b: BehaviorAggregate) => void): () => void;
620
+
621
+ 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 };
package/dist/index.js CHANGED
@@ -21,17 +21,25 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  BehavioralCollector: () => BehavioralCollector,
24
+ CLEARANCE_COOKIE: () => CLEARANCE_COOKIE,
24
25
  CaptchaWidget: () => CaptchaWidget,
26
+ DEFAULT_INGEST_URL: () => DEFAULT_INGEST_URL,
25
27
  EnvironmentalCollector: () => EnvironmentalCollector,
28
+ FP_VERSION: () => FP_VERSION,
26
29
  FormAnalyzer: () => FormAnalyzer,
27
30
  InvisibleSession: () => InvisibleSession,
28
31
  PoWManager: () => PoWManager,
29
32
  SensorCollector: () => SensorCollector,
30
33
  TemporalCollector: () => TemporalCollector,
31
34
  WebDecoyCaptcha: () => WebDecoyCaptcha,
35
+ computeDeviceFP: () => computeDeviceFP,
32
36
  getFormAnalyzer: () => getFormAnalyzer,
33
37
  getPoWManager: () => getPoWManager,
34
- sha256: () => sha256
38
+ hasEnoughInteraction: () => hasEnoughInteraction,
39
+ sha256: () => sha256,
40
+ startClearance: () => startClearance,
41
+ summarizeBehavior: () => summarizeBehavior,
42
+ watchInteraction: () => watchInteraction
35
43
  });
36
44
  module.exports = __toCommonJS(src_exports);
37
45
 
@@ -2370,3 +2378,195 @@ var WebDecoyCaptcha = {
2370
2378
  });
2371
2379
  }
2372
2380
  };
2381
+
2382
+ // src/clearance-behavior.ts
2383
+ var MIN_POINTER_SAMPLES = 24;
2384
+ var MIN_TOUCH_POINTS = 8;
2385
+ var MIN_WINDOW_MS = 750;
2386
+ var SETTLE_MS = 1500;
2387
+ function num(v) {
2388
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
2389
+ }
2390
+ function pointerWindowMs(collector) {
2391
+ const p = collector.mousePositions;
2392
+ if (!p || p.length < 2) return 0;
2393
+ return Math.max(0, Math.round(p[p.length - 1].t - p[0].t));
2394
+ }
2395
+ function hasEnoughInteraction(collector) {
2396
+ const pointerReady = collector.mousePositions.length >= MIN_POINTER_SAMPLES && pointerWindowMs(collector) >= MIN_WINDOW_MS;
2397
+ const touchReady = collector.touchEvents.length >= MIN_TOUCH_POINTS;
2398
+ return pointerReady || touchReady;
2399
+ }
2400
+ function summarizeBehavior(collector) {
2401
+ if (!hasEnoughInteraction(collector)) return null;
2402
+ const a = collector.analyze();
2403
+ const click = collector.clickData;
2404
+ return {
2405
+ samples: num(a.totalPoints),
2406
+ duration_ms: pointerWindowMs(collector),
2407
+ tremor: num(a.microTremorScore),
2408
+ straight_ratio: num(a.straightLineRatio),
2409
+ velocity_var: num(a.velocityVariance),
2410
+ delta_var: num(a.eventDeltaVariance),
2411
+ dir_changes: num(a.directionChanges),
2412
+ micro_moves: num(a.microMovements),
2413
+ hold_ms: num(click == null ? void 0 : click.holdDuration),
2414
+ touch_points: num(a.touchTotalPoints),
2415
+ touch_force_var: num(a.touchForceVariance),
2416
+ pointer_nonmouse: a.pointerHasNonMouseType === true,
2417
+ scrolls: num(a.scrollEvents),
2418
+ keys: num(a.keyEvents)
2419
+ };
2420
+ }
2421
+ function watchInteraction(onReady) {
2422
+ if (typeof document === "undefined") return () => {
2423
+ };
2424
+ const collector = new BehavioralCollector();
2425
+ let settleTimer = null;
2426
+ let done = false;
2427
+ const handlers = {
2428
+ mousemove: (e) => collector.recordMouseMove(e),
2429
+ mousedown: (e) => collector.recordMouseDown(e),
2430
+ mouseup: (e) => collector.recordMouseUp(e),
2431
+ scroll: (e) => collector.recordScroll(e),
2432
+ keydown: (e) => collector.recordKeyEvent(e),
2433
+ touchstart: (e) => collector.recordTouch(e),
2434
+ touchmove: (e) => collector.recordTouch(e),
2435
+ pointerdown: (e) => collector.recordPointer(e)
2436
+ };
2437
+ const stop = () => {
2438
+ if (done) return;
2439
+ done = true;
2440
+ if (settleTimer) clearTimeout(settleTimer);
2441
+ for (const [event, handler] of Object.entries(handlers)) {
2442
+ document.removeEventListener(event, handler);
2443
+ }
2444
+ };
2445
+ const check = () => {
2446
+ if (done || settleTimer) return;
2447
+ if (!hasEnoughInteraction(collector)) return;
2448
+ settleTimer = setTimeout(() => {
2449
+ settleTimer = null;
2450
+ const summary = summarizeBehavior(collector);
2451
+ stop();
2452
+ if (summary) onReady(summary);
2453
+ }, SETTLE_MS);
2454
+ };
2455
+ for (const [event, handler] of Object.entries(handlers)) {
2456
+ const wrapped = (e) => {
2457
+ handler(e);
2458
+ check();
2459
+ };
2460
+ handlers[event] = wrapped;
2461
+ document.addEventListener(event, wrapped, { passive: true });
2462
+ }
2463
+ return stop;
2464
+ }
2465
+
2466
+ // src/clearance.ts
2467
+ var CLEARANCE_COOKIE = "wd_clearance";
2468
+ var FP_VERSION = "wdfp1";
2469
+ var DEFAULT_INGEST_URL = "https://ingest.webdecoy.com";
2470
+ async function computeDeviceFP(env) {
2471
+ const ch = env.canvasHash;
2472
+ const canvas = ch && ch.supported ? String(ch.hash) : "na";
2473
+ const wg = env.webglInfo;
2474
+ const webgl = wg && wg.supported ? String(wg.renderer) + "~" + String(wg.vendor) : "na";
2475
+ const scr = `${screen.width}x${screen.height}x${screen.colorDepth}`;
2476
+ let tz = "na";
2477
+ try {
2478
+ tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "na";
2479
+ } catch {
2480
+ }
2481
+ const plat = navigator.platform || "na";
2482
+ const lang = navigator.language || "na";
2483
+ return sha256([FP_VERSION, canvas, webgl, scr, tz, plat, lang].join("|"));
2484
+ }
2485
+ async function mint(ingestUrl, siteKey, fp, scope, behavior) {
2486
+ try {
2487
+ const res = await fetch(ingestUrl.replace(/\/$/, "") + "/api/v1/clearance", {
2488
+ method: "POST",
2489
+ headers: { "Content-Type": "application/json" },
2490
+ body: JSON.stringify({
2491
+ aid: siteKey,
2492
+ fp,
2493
+ scope,
2494
+ ua: navigator.userAgent,
2495
+ webdriver: navigator.webdriver === true,
2496
+ headless: /HeadlessChrome/.test(navigator.userAgent),
2497
+ ...behavior ? { behavior } : {}
2498
+ })
2499
+ });
2500
+ const out = await res.json();
2501
+ if (out.granted && out.token) {
2502
+ return { token: out.token, expiresIn: out.expires_in || 1800 };
2503
+ }
2504
+ } catch {
2505
+ }
2506
+ return null;
2507
+ }
2508
+ function readCookie(name) {
2509
+ for (const part of document.cookie.split(";")) {
2510
+ const eq = part.indexOf("=");
2511
+ if (eq < 0) continue;
2512
+ if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim() || null;
2513
+ }
2514
+ return null;
2515
+ }
2516
+ function setClearanceCookie(token, maxAgeSec) {
2517
+ document.cookie = `${CLEARANCE_COOKIE}=${token}; path=/; secure; samesite=lax; max-age=${maxAgeSec}`;
2518
+ }
2519
+ function whenIdle(fn) {
2520
+ const ric = window.requestIdleCallback;
2521
+ if (typeof ric === "function") {
2522
+ ric(fn);
2523
+ } else {
2524
+ setTimeout(fn, 1200);
2525
+ }
2526
+ }
2527
+ var upgradeStarted = false;
2528
+ function startBehavioralUpgrade(ingestUrl, siteKey, scope) {
2529
+ if (upgradeStarted) return;
2530
+ upgradeStarted = true;
2531
+ watchInteraction((behavior) => {
2532
+ void (async () => {
2533
+ try {
2534
+ const env = new EnvironmentalCollector();
2535
+ const fp = await computeDeviceFP({
2536
+ canvasHash: env._getCanvasHash(),
2537
+ webglInfo: env._getWebGLInfo()
2538
+ });
2539
+ const minted = await mint(ingestUrl, siteKey, fp, scope, behavior);
2540
+ if (minted) setClearanceCookie(minted.token, minted.expiresIn);
2541
+ } catch {
2542
+ }
2543
+ })();
2544
+ });
2545
+ }
2546
+ function startClearance(opts) {
2547
+ if (!opts.siteKey || typeof document === "undefined") return;
2548
+ const ingestUrl = opts.ingestUrl || DEFAULT_INGEST_URL;
2549
+ const scope = opts.scope || "";
2550
+ const run = async () => {
2551
+ if (readCookie(CLEARANCE_COOKIE)) {
2552
+ return;
2553
+ }
2554
+ const env = new EnvironmentalCollector();
2555
+ const fp = await computeDeviceFP({
2556
+ canvasHash: env._getCanvasHash(),
2557
+ webglInfo: env._getWebGLInfo()
2558
+ });
2559
+ const minted = await mint(ingestUrl, opts.siteKey, fp, scope);
2560
+ if (minted) {
2561
+ setClearanceCookie(minted.token, minted.expiresIn);
2562
+ const refreshMs = Math.max(6e4, (minted.expiresIn - 120) * 1e3);
2563
+ setTimeout(() => startClearance(opts), refreshMs);
2564
+ }
2565
+ };
2566
+ whenIdle(() => {
2567
+ void run();
2568
+ });
2569
+ if (opts.behavior !== false) {
2570
+ startBehavioralUpgrade(ingestUrl, opts.siteKey, scope);
2571
+ }
2572
+ }
package/dist/index.mjs CHANGED
@@ -2333,17 +2333,217 @@ var WebDecoyCaptcha = {
2333
2333
  });
2334
2334
  }
2335
2335
  };
2336
+
2337
+ // src/clearance-behavior.ts
2338
+ var MIN_POINTER_SAMPLES = 24;
2339
+ var MIN_TOUCH_POINTS = 8;
2340
+ var MIN_WINDOW_MS = 750;
2341
+ var SETTLE_MS = 1500;
2342
+ function num(v) {
2343
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
2344
+ }
2345
+ function pointerWindowMs(collector) {
2346
+ const p = collector.mousePositions;
2347
+ if (!p || p.length < 2) return 0;
2348
+ return Math.max(0, Math.round(p[p.length - 1].t - p[0].t));
2349
+ }
2350
+ function hasEnoughInteraction(collector) {
2351
+ const pointerReady = collector.mousePositions.length >= MIN_POINTER_SAMPLES && pointerWindowMs(collector) >= MIN_WINDOW_MS;
2352
+ const touchReady = collector.touchEvents.length >= MIN_TOUCH_POINTS;
2353
+ return pointerReady || touchReady;
2354
+ }
2355
+ function summarizeBehavior(collector) {
2356
+ if (!hasEnoughInteraction(collector)) return null;
2357
+ const a = collector.analyze();
2358
+ const click = collector.clickData;
2359
+ return {
2360
+ samples: num(a.totalPoints),
2361
+ duration_ms: pointerWindowMs(collector),
2362
+ tremor: num(a.microTremorScore),
2363
+ straight_ratio: num(a.straightLineRatio),
2364
+ velocity_var: num(a.velocityVariance),
2365
+ delta_var: num(a.eventDeltaVariance),
2366
+ dir_changes: num(a.directionChanges),
2367
+ micro_moves: num(a.microMovements),
2368
+ hold_ms: num(click == null ? void 0 : click.holdDuration),
2369
+ touch_points: num(a.touchTotalPoints),
2370
+ touch_force_var: num(a.touchForceVariance),
2371
+ pointer_nonmouse: a.pointerHasNonMouseType === true,
2372
+ scrolls: num(a.scrollEvents),
2373
+ keys: num(a.keyEvents)
2374
+ };
2375
+ }
2376
+ function watchInteraction(onReady) {
2377
+ if (typeof document === "undefined") return () => {
2378
+ };
2379
+ const collector = new BehavioralCollector();
2380
+ let settleTimer = null;
2381
+ let done = false;
2382
+ const handlers = {
2383
+ mousemove: (e) => collector.recordMouseMove(e),
2384
+ mousedown: (e) => collector.recordMouseDown(e),
2385
+ mouseup: (e) => collector.recordMouseUp(e),
2386
+ scroll: (e) => collector.recordScroll(e),
2387
+ keydown: (e) => collector.recordKeyEvent(e),
2388
+ touchstart: (e) => collector.recordTouch(e),
2389
+ touchmove: (e) => collector.recordTouch(e),
2390
+ pointerdown: (e) => collector.recordPointer(e)
2391
+ };
2392
+ const stop = () => {
2393
+ if (done) return;
2394
+ done = true;
2395
+ if (settleTimer) clearTimeout(settleTimer);
2396
+ for (const [event, handler] of Object.entries(handlers)) {
2397
+ document.removeEventListener(event, handler);
2398
+ }
2399
+ };
2400
+ const check = () => {
2401
+ if (done || settleTimer) return;
2402
+ if (!hasEnoughInteraction(collector)) return;
2403
+ settleTimer = setTimeout(() => {
2404
+ settleTimer = null;
2405
+ const summary = summarizeBehavior(collector);
2406
+ stop();
2407
+ if (summary) onReady(summary);
2408
+ }, SETTLE_MS);
2409
+ };
2410
+ for (const [event, handler] of Object.entries(handlers)) {
2411
+ const wrapped = (e) => {
2412
+ handler(e);
2413
+ check();
2414
+ };
2415
+ handlers[event] = wrapped;
2416
+ document.addEventListener(event, wrapped, { passive: true });
2417
+ }
2418
+ return stop;
2419
+ }
2420
+
2421
+ // src/clearance.ts
2422
+ var CLEARANCE_COOKIE = "wd_clearance";
2423
+ var FP_VERSION = "wdfp1";
2424
+ var DEFAULT_INGEST_URL = "https://ingest.webdecoy.com";
2425
+ async function computeDeviceFP(env) {
2426
+ const ch = env.canvasHash;
2427
+ const canvas = ch && ch.supported ? String(ch.hash) : "na";
2428
+ const wg = env.webglInfo;
2429
+ const webgl = wg && wg.supported ? String(wg.renderer) + "~" + String(wg.vendor) : "na";
2430
+ const scr = `${screen.width}x${screen.height}x${screen.colorDepth}`;
2431
+ let tz = "na";
2432
+ try {
2433
+ tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "na";
2434
+ } catch {
2435
+ }
2436
+ const plat = navigator.platform || "na";
2437
+ const lang = navigator.language || "na";
2438
+ return sha256([FP_VERSION, canvas, webgl, scr, tz, plat, lang].join("|"));
2439
+ }
2440
+ async function mint(ingestUrl, siteKey, fp, scope, behavior) {
2441
+ try {
2442
+ const res = await fetch(ingestUrl.replace(/\/$/, "") + "/api/v1/clearance", {
2443
+ method: "POST",
2444
+ headers: { "Content-Type": "application/json" },
2445
+ body: JSON.stringify({
2446
+ aid: siteKey,
2447
+ fp,
2448
+ scope,
2449
+ ua: navigator.userAgent,
2450
+ webdriver: navigator.webdriver === true,
2451
+ headless: /HeadlessChrome/.test(navigator.userAgent),
2452
+ ...behavior ? { behavior } : {}
2453
+ })
2454
+ });
2455
+ const out = await res.json();
2456
+ if (out.granted && out.token) {
2457
+ return { token: out.token, expiresIn: out.expires_in || 1800 };
2458
+ }
2459
+ } catch {
2460
+ }
2461
+ return null;
2462
+ }
2463
+ function readCookie(name) {
2464
+ for (const part of document.cookie.split(";")) {
2465
+ const eq = part.indexOf("=");
2466
+ if (eq < 0) continue;
2467
+ if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim() || null;
2468
+ }
2469
+ return null;
2470
+ }
2471
+ function setClearanceCookie(token, maxAgeSec) {
2472
+ document.cookie = `${CLEARANCE_COOKIE}=${token}; path=/; secure; samesite=lax; max-age=${maxAgeSec}`;
2473
+ }
2474
+ function whenIdle(fn) {
2475
+ const ric = window.requestIdleCallback;
2476
+ if (typeof ric === "function") {
2477
+ ric(fn);
2478
+ } else {
2479
+ setTimeout(fn, 1200);
2480
+ }
2481
+ }
2482
+ var upgradeStarted = false;
2483
+ function startBehavioralUpgrade(ingestUrl, siteKey, scope) {
2484
+ if (upgradeStarted) return;
2485
+ upgradeStarted = true;
2486
+ watchInteraction((behavior) => {
2487
+ void (async () => {
2488
+ try {
2489
+ const env = new EnvironmentalCollector();
2490
+ const fp = await computeDeviceFP({
2491
+ canvasHash: env._getCanvasHash(),
2492
+ webglInfo: env._getWebGLInfo()
2493
+ });
2494
+ const minted = await mint(ingestUrl, siteKey, fp, scope, behavior);
2495
+ if (minted) setClearanceCookie(minted.token, minted.expiresIn);
2496
+ } catch {
2497
+ }
2498
+ })();
2499
+ });
2500
+ }
2501
+ function startClearance(opts) {
2502
+ if (!opts.siteKey || typeof document === "undefined") return;
2503
+ const ingestUrl = opts.ingestUrl || DEFAULT_INGEST_URL;
2504
+ const scope = opts.scope || "";
2505
+ const run = async () => {
2506
+ if (readCookie(CLEARANCE_COOKIE)) {
2507
+ return;
2508
+ }
2509
+ const env = new EnvironmentalCollector();
2510
+ const fp = await computeDeviceFP({
2511
+ canvasHash: env._getCanvasHash(),
2512
+ webglInfo: env._getWebGLInfo()
2513
+ });
2514
+ const minted = await mint(ingestUrl, opts.siteKey, fp, scope);
2515
+ if (minted) {
2516
+ setClearanceCookie(minted.token, minted.expiresIn);
2517
+ const refreshMs = Math.max(6e4, (minted.expiresIn - 120) * 1e3);
2518
+ setTimeout(() => startClearance(opts), refreshMs);
2519
+ }
2520
+ };
2521
+ whenIdle(() => {
2522
+ void run();
2523
+ });
2524
+ if (opts.behavior !== false) {
2525
+ startBehavioralUpgrade(ingestUrl, opts.siteKey, scope);
2526
+ }
2527
+ }
2336
2528
  export {
2337
2529
  BehavioralCollector,
2530
+ CLEARANCE_COOKIE,
2338
2531
  CaptchaWidget,
2532
+ DEFAULT_INGEST_URL,
2339
2533
  EnvironmentalCollector,
2534
+ FP_VERSION,
2340
2535
  FormAnalyzer,
2341
2536
  InvisibleSession,
2342
2537
  PoWManager,
2343
2538
  SensorCollector,
2344
2539
  TemporalCollector,
2345
2540
  WebDecoyCaptcha,
2541
+ computeDeviceFP,
2346
2542
  getFormAnalyzer,
2347
2543
  getPoWManager,
2348
- sha256
2544
+ hasEnoughInteraction,
2545
+ sha256,
2546
+ startClearance,
2547
+ summarizeBehavior,
2548
+ watchInteraction
2349
2549
  };
@@ -1,4 +1,4 @@
1
- "use strict";var WebDecoyCaptchaBundle=(()=>{var O=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var $=(h,t)=>{for(var e in t)O(h,e,{get:t[e],enumerable:!0})},X=(h,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of B(t))!q.call(h,i)&&i!==e&&O(h,i,{get:()=>t[i],enumerable:!(n=N(t,i))||n.enumerable});return h};var Y=h=>X(O({},"__esModule",{value:!0}),h);var G={};$(G,{WebDecoyCaptcha:()=>R});var S=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(t){let e=performance.now(),n={x:t.clientX,y:t.clientY,t:e};if(this.mousePositions.push(n),this.lastMousePos&&this.lastMouseTime){let i=e-this.lastMouseTime;if(i>0){let o=t.clientX-this.lastMousePos.x,r=t.clientY-this.lastMousePos.y,a=Math.sqrt(o*o+r*r)/i;if(this.mouseVelocities.push({v:a,t:e}),this.eventDeltas.push(i),this.lastVelocity!==null){let c=(a-this.lastVelocity)/i;this.mouseAccelerations.push({a:c,t:e})}this.lastVelocity=a}}this.lastMousePos={x:t.clientX,y:t.clientY},this.lastMouseTime=e,this.mousePositions.length>500&&(this.mousePositions.shift(),this.mouseVelocities.length>500&&this.mouseVelocities.shift(),this.mouseAccelerations.length>500&&this.mouseAccelerations.shift())}recordMouseDown(t){this.clickData={x:t.clientX,y:t.clientY,button:t.button,downTime:performance.now()}}recordMouseUp(t){this.clickData&&(this.clickData.upTime=performance.now(),this.clickData.holdDuration=this.clickData.upTime-this.clickData.downTime)}recordScroll(t){this.scrollEvents.push({x:window.scrollX,y:window.scrollY,t:performance.now()}),this.scrollEvents.length>100&&this.scrollEvents.shift()}recordKeyEvent(t){this.keyEvents.push({type:t.type,keyLength:t.key?t.key.length:0,t:performance.now()})}recordTouch(t){let e=t.touches&&t.touches.length?t.touches:t.changedTouches;if(!e||e.length===0)return;e.length>1&&(this.touchMultiTouchSeen=!0);let n=e[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:e.length}),this.touchEvents.length>500&&this.touchEvents.shift()}recordPointer(t){this.pointerPoints.push({x:t.clientX,y:t.clientY,t:performance.now(),type:t.type,pressure:typeof t.pressure=="number"?t.pressure:0,tiltX:typeof t.tiltX=="number"?t.tiltX:0,tiltY:typeof t.tiltY=="number"?t.tiltY:0,tangentialPressure:typeof t.tangentialPressure=="number"?t.tangentialPressure:0,pointerType:t.pointerType||"unknown"}),this.pointerPoints.length>500&&this.pointerPoints.shift()}recordFocus(t){var e;this.focusEvents.push({type:t.type,target:(e=t.target)==null?void 0:e.tagName,t:performance.now()})}analyze(){let t=this.mousePositions,e=this.mouseVelocities,n=this.mouseAccelerations;if(t.length<10)return this._getEmptyAnalysis();let i=0,o=0;e.length>0&&(i=e.reduce((f,d)=>f+d.v,0)/e.length,o=e.reduce((f,d)=>f+Math.pow(d.v-i,2),0)/e.length);let r=0,s=0;if(n.length>0){r=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)&&s++}let a=this._detectMicroTremor(t),c=this._calculateStraightLineRatio(t),l=0;for(let m=1;m<t.length;m++){let f=Math.abs(t[m].x-t[m-1].x),d=Math.abs(t[m].y-t[m-1].y);f<3&&d<3&&(f>0||d>0)&&l++}let u=this._countDirectionChanges(t),v=this._variance(this.eventDeltas),p=t.length>1?t.length/((t[t.length-1].t-t[0].t)/1e3):0,y=0;for(let m=1;m<t.length;m++){let f=t[m].x-t[m-1].x,d=t[m].y-t[m-1].y;y+=Math.sqrt(f*f+d*d)}let w=this._analyzeTouchPoints(this.touchEvents),_=this._analyzePointerPoints(this.pointerPoints);return{totalPoints:t.length,trajectoryLength:y,avgVelocity:i,velocityVariance:o,avgAcceleration:r,accelerationChanges:s,microTremorScore:a,straightLineRatio:c,microMovements:l,directionChanges:u,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,...w,..._}}_analyzeTouchPoints(t){if(!t||t.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 e=0,n=[];for(let c=1;c<t.length;c++){let l=t[c].x-t[c-1].x,u=t[c].y-t[c-1].y,v=Math.sqrt(l*l+u*u);e+=v;let p=t[c].t-t[c-1].t;p>0&&n.push(v/p)}let i=n.length>0?n.reduce((c,l)=>c+l,0)/n.length:0,o=t.map(c=>c.force),r=t.map(c=>Math.max(c.radiusX||0,c.radiusY||0)),s=o.length>0&&o.every(c=>c===0),a=o.length>0&&o.every(c=>c===1);return{touchTotalPoints:t.length,touchTrajectoryLength:e,touchAvgVelocity:i,touchVelocityVariance:this._variance(n),touchMicroTremorScore:this._detectMicroTremor(t),touchStraightLineRatio:this._calculateStraightLineRatio(t),touchDirectionChanges:this._countDirectionChanges(t),touchForceMin:o.length>0?Math.min(...o):0,touchForceMax:o.length>0?Math.max(...o):0,touchForceVariance:this._variance(o),touchRadiusMin:r.length>0?Math.min(...r):0,touchRadiusMax:r.length>0?Math.max(...r):0,touchRadiusVariance:this._variance(r),touchMultiTouchSeen:this.touchMultiTouchSeen,touchUniqueIdentifiers:this.touchIdentifiers.size,touchForceAllZero:s,touchForceAllOne:a}}_analyzePointerPoints(t){if(!t||t.length===0)return{pointerEvents:0,pointerAvgPressure:0,pointerPressureVariance:0,pointerMaxTilt:0,pointerHasNonMouseType:!1,pointerTypes:[]};let e=t.map(r=>r.pressure),n=e.length>0?e.reduce((r,s)=>r+s,0)/e.length:0,i=0,o=new Set;for(let r of t){let s=Math.abs(r.tiltX||0)+Math.abs(r.tiltY||0);s>i&&(i=s),r.pointerType&&o.add(r.pointerType)}return{pointerEvents:t.length,pointerAvgPressure:n,pointerPressureVariance:this._variance(e),pointerMaxTilt:i,pointerHasNonMouseType:Array.from(o).some(r=>r!=="mouse"&&r!=="unknown"),pointerTypes:Array.from(o)}}analyzeClick(t,e,n){let i=this.mousePositions;if(i.length<5)return this._getEmptyClickAnalysis();let o=i.slice(-20),r=n.left+n.width/2,s=n.top+n.height/2,a=Math.sqrt(Math.pow(t-r,2)+Math.pow(e-s,2)),c=0,l=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));l+=g,i[d].x>=n.left&&i[d].x<=n.right&&i[d].y>=n.top&&i[d].y<=n.bottom||(c+=g)}let u=l>0?c/l:0,v=0,p=!1,y=!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&&(y=!0),y&&g&&(v++,y=!1),p=g}let w=0;for(let d=o.length-1;d>=0;d--){let g=o[d],L=g.x>=n.left&&g.x<=n.right&&g.y>=n.top&&g.y<=n.bottom;if(L&&d<o.length-1)w=o[o.length-1].t-g.t;else if(!L)break}let _=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?_/m:1;return{clickPrecision:a,explorationRatio:u,overshootCorrections:v,hoverTime:w,approachDirectness:f,approachPoints:o.length}}_detectMicroTremor(t){if(t.length<20)return .5;let e=5,n=0;for(let o=e;o<t.length-e;o++){let r=0,s=0;for(let c=o-e;c<=o+e;c++)r+=t[c].x,s+=t[c].y;r/=e*2+1,s/=e*2+1;let a=Math.sqrt(Math.pow(t[o].x-r,2)+Math.pow(t[o].y-s,2));n+=a}let i=n/(t.length-e*2);return Math.min(1,i/2)}_calculateStraightLineRatio(t){if(t.length<3)return 0;let e=0,n=0;for(let i=2;i<t.length;i++){let o=t[i-2],r=t[i-1],s=t[i],a=Math.atan2(r.y-o.y,r.x-o.x),c=Math.atan2(s.y-r.y,s.x-r.x),l=Math.abs(c-a);n++,l<.1&&e++}return n>0?e/n:0}_countDirectionChanges(t){let e=0;for(let n=2;n<t.length;n++){let i=Math.atan2(t[n-1].y-t[n-2].y,t[n-1].x-t[n-2].x),o=Math.atan2(t[n].y-t[n-1].y,t[n].x-t[n-1].x);Math.abs(o-i)>Math.PI/6&&e++}return e}_variance(t){if(t.length===0)return 0;let e=t.reduce((n,i)=>n+i,0)/t.length;return t.reduce((n,i)=>n+Math.pow(i-e,2),0)/t.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 E=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[t,e,n]=await Promise.all([this._getSpeechInfo(),this._getWebRTCInfo(),this._checkWorkerConsistency()]);return{speechInfo:t,webrtcInfo:e,workerConsistency:n}}_detectWebdriver(){let t=navigator,e=window;return!!(t.webdriver||e.document.__webdriver_evaluate||e.document.__selenium_evaluate||e.document.__webdriver_script_fn||e.document.__webdriver_script_func||e.document.__webdriver_script_function||e.document.$cdc_asdjflasutopfhvcZLmcfl_||e.document.$wdc_||e._Selenium_IDE_Recorder||e._phantom||e.__nightmare||e.callPhantom||e._phantom)}_getAutomationFlags(){let t=navigator,e=window;return{webdriver:!!t.webdriver,domAutomation:!!e.domAutomation,domAutomationController:!!e.domAutomationController,_selenium:!!e._selenium,__webdriver_script_fn:!!e.__webdriver_script_fn,__driver_evaluate:!!e.__driver_evaluate,__webdriver_evaluate:!!e.__webdriver_evaluate,__fxdriver_evaluate:!!e.__fxdriver_evaluate,__driver_unwrapped:!!e.__driver_unwrapped,__webdriver_unwrapped:!!e.__webdriver_unwrapped,__fxdriver_unwrapped:!!e.__fxdriver_unwrapped,_Selenium_IDE_Recorder:!!e._Selenium_IDE_Recorder,calledSelenium:!!e.calledSelenium,$chrome_asyncScriptInfo:!!e.$chrome_asyncScriptInfo,$cdc_asdjflasutopfhvcZLmcfl_:!!e.$cdc_asdjflasutopfhvcZLmcfl_,_phantom:!!e._phantom,callPhantom:!!e.callPhantom,__nightmare:!!e.__nightmare,__lastWatirAlert:!!e.__lastWatirAlert,__lastWatirConfirm:!!e.__lastWatirConfirm,__lastWatirPrompt:!!e.__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:!!e.chrome,chromeRuntime:!!(e.chrome&&e.chrome.runtime&&e.chrome.runtime.id),permissionsAPI:!!navigator.permissions}}_detectPlaywright(){try{let t=window,e=[];Object.getOwnPropertyNames(window).filter(r=>r.startsWith("__pw")||r.startsWith("__playwright")).length>0&&e.push("playwright_globals");let i=Object.getPrototypeOf(navigator);return Object.getOwnPropertyDescriptor(i,"webdriver")||e.push("webdriver_deleted"),{detected:e.length>0,signals:e}}catch{return{detected:!1,signals:[]}}}_detectCDP(){try{let t=window,e=[];Object.keys(window).filter(i=>i.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 i=Object.getOwnPropertyDescriptor(navigator,"webdriver");i&&typeof i.get=="function"&&i.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 t=document.createElement("canvas");t.width=200,t.height=50;let e=t.getContext("2d");e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("FCaptcha",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("FCaptcha",4,17);let n=t.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 t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{supported:!1};let n=e.getExtension("WEBGL_debug_renderer_info"),i=n?e.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown",o=n?e.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown",r=o.toLowerCase(),s=r.includes("swiftshader")||r.includes("llvmpipe")||r.includes("softpipe")||r.includes("virtualbox")||r.includes("vmware");return{supported:!0,vendor:i,renderer:o,version:e.getParameter(e.VERSION),shadingVersion:e.getParameter(e.SHADING_LANGUAGE_VERSION),suspiciousRenderer:s}}catch{return{supported:!1,error:!0}}}_getAudioInfo(){try{let t=window,e=t.AudioContext||t.webkitAudioContext;if(!e)return{supported:!1};let n=new e,i={supported:!0,sampleRate:n.sampleRate,state:n.state,baseLatency:n.baseLatency};return n.close(),i}catch{return{supported:!1,error:!0}}}_getLieDetection(){try{let t=window,e=[],n=o=>{try{return typeof o=="function"&&o.toString().indexOf("[native code]")===-1}catch{return!1}},i=(o,r)=>{n(o)&&e.push(r)};i(Function.prototype.toString,"Function.prototype.toString"),i(navigator.permissions&&navigator.permissions.query,"navigator.permissions.query"),i(t.Notification&&t.Notification.requestPermission,"Notification.requestPermission"),i(t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.toDataURL,"HTMLCanvasElement.toDataURL"),i(t.WebGLRenderingContext&&t.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&&e.push("navigator.webdriver getter")}catch{}return{supported:!0,patched:e,patchedCount:e.length}}catch{return{supported:!1}}}_getHeadlessIndicators(){let t=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:t.connection?t.connection.type:"unknown",connectionRtt:t.connection?t.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 e;let t=navigator;return{language:navigator.language,languageCount:((e=navigator.languages)==null?void 0:e.length)||0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:t.deviceMemory,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()}}_measureJSExecution(){let t={},e=performance.now();for(let o=0;o<1e3;o++)Math.sqrt(o)*Math.sin(o);t.mathOps=performance.now()-e,e=performance.now();let n=[];for(let o=0;o<1e3;o++)n.push(o);t.arrayOps=performance.now()-e,t.arrayLen=n.length,e=performance.now();let i="";for(let o=0;o<100;o++)i+="a";return t.stringOps=performance.now()-e,t}async measureRAFConsistency(){return new Promise(t=>{let e=[],n=0,i=10;function o(r){if(e.push(r),n++,n<i)requestAnimationFrame(o);else{let s=[];for(let l=1;l<e.length;l++)s.push(e[l]-e[l-1]);let 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({avgFrameTime:a,frameTimeVariance:c,frames:i})}}requestAnimationFrame(o)})}_getMathFingerprint(){try{let t={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)},e=Object.values(t).map(i=>String(i)).join(","),n=0;for(let i=0;i<e.length;i++)n=(n<<5)-n+e.charCodeAt(i),n=n&n;return{hash:n.toString(16),sinPi:t.sin,tanLarge:t.tan,supported:!0}}catch{return{supported:!1,error:!0}}}_getErrorFingerprint(){try{let t={};try{null.foo}catch(i){t.typeError=i.message}try{[].length=-1}catch(i){t.rangeError=i.message}try{decodeURIComponent("%")}catch(i){t.uriError=i.message}try{({}).undefinedMethod()}catch(i){t.refTypeError=i.message}let e=Object.values(t).join("|"),n=0;for(let i=0;i<e.length;i++)n=(n<<5)-n+e.charCodeAt(i),n=n&n;return{hash:n.toString(16),typeError:t.typeError,supported:!0}}catch{return{supported:!1,error:!0}}}_getDOMRectFingerprint(){try{let t=document.createElement("div");t.style.cssText="position:absolute;left:-9999px;font-size:16px;font-family:Arial,sans-serif;";let e=document.createElement("span");e.textContent="FCaptcha Test String 123",t.appendChild(e);let n=document.createElement("span");n.style.cssText="letter-spacing:1px;word-spacing:2px;",n.textContent="WWWW 0000",t.appendChild(n),document.body.appendChild(t);let i=e.getBoundingClientRect(),o=n.getBoundingClientRect(),r=document.createRange();r.selectNode(e);let s=r.getBoundingClientRect();document.body.removeChild(t);let c=[i.width,i.height,i.x,i.y,o.width,o.height,s.width,s.height].map(u=>u.toFixed(6)).join(","),l=0;for(let u=0;u<c.length;u++)l=(l<<5)-l+c.charCodeAt(u),l=l&l;return{hash:l.toString(16),rectAWidth:i.width,rectBWidth:o.width,rangeWidth:s.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 t=["monospace","sans-serif","serif"],e=["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",r="72px",s={};for(let u of t)i.font=r+" "+u,s[u]=i.measureText(o).width;let a=[];for(let u of e){let v=!1;for(let p of t)if(i.font=r+' "'+u+'", '+p,i.measureText(o).width!==s[p]){v=!0;break}v&&a.push(u)}let c=a.join(","),l=0;for(let u=0;u<c.length;u++)l=(l<<5)-l+c.charCodeAt(u),l=l&l;return{hash:l.toString(16),count:a.length,hasArial:a.includes("Arial"),hasTimesNewRoman:a.includes("Times New Roman"),hasSegoeUI:a.includes("Segoe UI"),hasSFPro:a.includes("SF Pro"),hasDejaVuSans:a.includes("DejaVu Sans"),supported:!0}}catch{return{supported:!1,error:!0}}}async _getSpeechInfo(){try{if(!("speechSynthesis"in window))return{supported:!1};let e=await new Promise(a=>{let c=speechSynthesis.getVoices();if(c.length>0){a(c);return}let l=setTimeout(()=>a([]),1e3);speechSynthesis.onvoiceschanged=()=>{clearTimeout(l),a(speechSynthesis.getVoices())}}),n=e.filter(a=>a.localService),i=e.find(a=>a.default),o=[...new Set(e.map(a=>a.lang))],r=e.map(a=>a.name).sort().join(","),s=0;for(let a=0;a<r.length;a++)s=(s<<5)-s+r.charCodeAt(a),s=s&s;return{hash:s.toString(16),totalVoices:e.length,localVoices:n.length,languages:o.length,defaultVoiceLang:(i==null?void 0:i.lang)||null,hasGoogleVoices:e.some(a=>a.name.includes("Google")),hasMicrosoftVoices:e.some(a=>a.name.includes("Microsoft")),hasAppleVoices:e.some(a=>a.name.includes("Samantha")||a.name.includes("Alex")),supported:!0}}catch{return{supported:!1,error:!0}}}async _getWebRTCInfo(){try{let t={supported:"RTCPeerConnection"in window,mediaDevices:{supported:!1},localIPs:[]};if(!t.supported)return t;if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices)try{let e=await navigator.mediaDevices.enumerateDevices();t.mediaDevices={supported:!0,audioInputs:e.filter(n=>n.kind==="audioinput").length,audioOutputs:e.filter(n=>n.kind==="audiooutput").length,videoInputs:e.filter(n=>n.kind==="videoinput").length,totalDevices:e.length}}catch{t.mediaDevices={supported:!1,error:!0}}try{let e=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}),n=new Set;e.onicecandidate=i=>{if(i.candidate){let o=i.candidate.candidate,r=/([0-9]{1,3}\.){3}[0-9]{1,3}/g,s=o.match(r);s&&s.forEach(a=>{(a.startsWith("192.168.")||a.startsWith("10.")||a.startsWith("172.")||a.startsWith("169.254."))&&n.add(a)})}},e.createDataChannel(""),await e.createOffer().then(i=>e.setLocalDescription(i)),await new Promise(i=>setTimeout(i,500)),t.localIPs=Array.from(n),t.hasLocalIP=n.size>0,e.close()}catch{t.localIPError=!0}return t}catch{return{supported:!1,error:!0}}}async _checkWorkerConsistency(){try{if(typeof Worker=="undefined")return{supported:!1};let t=navigator,e=`
1
+ "use strict";var WebDecoyCaptchaBundle=(()=>{var H=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ie=Object.prototype.hasOwnProperty;var re=(c,t)=>{for(var e in t)H(c,e,{get:t[e],enumerable:!0})},se=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of oe(t))!ie.call(c,o)&&o!==e&&H(c,o,{get:()=>t[o],enumerable:!(n=ne(t,o))||n.enumerable});return c};var ae=c=>se(H({},"__esModule",{value:!0}),c);var ye={};re(ye,{WebDecoyCaptcha:()=>W});var E=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(t){let e=performance.now(),n={x:t.clientX,y:t.clientY,t:e};if(this.mousePositions.push(n),this.lastMousePos&&this.lastMouseTime){let o=e-this.lastMouseTime;if(o>0){let i=t.clientX-this.lastMousePos.x,r=t.clientY-this.lastMousePos.y,a=Math.sqrt(i*i+r*r)/o;if(this.mouseVelocities.push({v:a,t:e}),this.eventDeltas.push(o),this.lastVelocity!==null){let l=(a-this.lastVelocity)/o;this.mouseAccelerations.push({a:l,t:e})}this.lastVelocity=a}}this.lastMousePos={x:t.clientX,y:t.clientY},this.lastMouseTime=e,this.mousePositions.length>500&&(this.mousePositions.shift(),this.mouseVelocities.length>500&&this.mouseVelocities.shift(),this.mouseAccelerations.length>500&&this.mouseAccelerations.shift())}recordMouseDown(t){this.clickData={x:t.clientX,y:t.clientY,button:t.button,downTime:performance.now()}}recordMouseUp(t){this.clickData&&(this.clickData.upTime=performance.now(),this.clickData.holdDuration=this.clickData.upTime-this.clickData.downTime)}recordScroll(t){this.scrollEvents.push({x:window.scrollX,y:window.scrollY,t:performance.now()}),this.scrollEvents.length>100&&this.scrollEvents.shift()}recordKeyEvent(t){this.keyEvents.push({type:t.type,keyLength:t.key?t.key.length:0,t:performance.now()})}recordTouch(t){let e=t.touches&&t.touches.length?t.touches:t.changedTouches;if(!e||e.length===0)return;e.length>1&&(this.touchMultiTouchSeen=!0);let n=e[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:e.length}),this.touchEvents.length>500&&this.touchEvents.shift()}recordPointer(t){this.pointerPoints.push({x:t.clientX,y:t.clientY,t:performance.now(),type:t.type,pressure:typeof t.pressure=="number"?t.pressure:0,tiltX:typeof t.tiltX=="number"?t.tiltX:0,tiltY:typeof t.tiltY=="number"?t.tiltY:0,tangentialPressure:typeof t.tangentialPressure=="number"?t.tangentialPressure:0,pointerType:t.pointerType||"unknown"}),this.pointerPoints.length>500&&this.pointerPoints.shift()}recordFocus(t){var e;this.focusEvents.push({type:t.type,target:(e=t.target)==null?void 0:e.tagName,t:performance.now()})}analyze(){let t=this.mousePositions,e=this.mouseVelocities,n=this.mouseAccelerations;if(t.length<10)return this._getEmptyAnalysis();let o=0,i=0;e.length>0&&(o=e.reduce((v,d)=>v+d.v,0)/e.length,i=e.reduce((v,d)=>v+Math.pow(d.v-o,2),0)/e.length);let r=0,s=0;if(n.length>0){r=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)&&s++}let a=this._detectMicroTremor(t),l=this._calculateStraightLineRatio(t),u=0;for(let m=1;m<t.length;m++){let v=Math.abs(t[m].x-t[m-1].x),d=Math.abs(t[m].y-t[m-1].y);v<3&&d<3&&(v>0||d>0)&&u++}let h=this._countDirectionChanges(t),f=this._variance(this.eventDeltas),g=t.length>1?t.length/((t[t.length-1].t-t[0].t)/1e3):0,w=0;for(let m=1;m<t.length;m++){let v=t[m].x-t[m-1].x,d=t[m].y-t[m-1].y;w+=Math.sqrt(v*v+d*d)}let _=this._analyzeTouchPoints(this.touchEvents),S=this._analyzePointerPoints(this.pointerPoints);return{totalPoints:t.length,trajectoryLength:w,avgVelocity:o,velocityVariance:i,avgAcceleration:r,accelerationChanges:s,microTremorScore:a,straightLineRatio:l,microMovements:u,directionChanges:h,eventDeltas:this.eventDeltas.slice(-50),eventDeltaVariance:f,mouseEventRate:g,scrollEvents:this.scrollEvents.length,keyEvents:this.keyEvents.length,touchEvents:this.touchEvents.length,focusEvents:this.focusEvents.length,clickData:this.clickData,interactionDuration:Date.now()-this.startTime,..._,...S}}_analyzeTouchPoints(t){if(!t||t.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 e=0,n=[];for(let l=1;l<t.length;l++){let u=t[l].x-t[l-1].x,h=t[l].y-t[l-1].y,f=Math.sqrt(u*u+h*h);e+=f;let g=t[l].t-t[l-1].t;g>0&&n.push(f/g)}let o=n.length>0?n.reduce((l,u)=>l+u,0)/n.length:0,i=t.map(l=>l.force),r=t.map(l=>Math.max(l.radiusX||0,l.radiusY||0)),s=i.length>0&&i.every(l=>l===0),a=i.length>0&&i.every(l=>l===1);return{touchTotalPoints:t.length,touchTrajectoryLength:e,touchAvgVelocity:o,touchVelocityVariance:this._variance(n),touchMicroTremorScore:this._detectMicroTremor(t),touchStraightLineRatio:this._calculateStraightLineRatio(t),touchDirectionChanges:this._countDirectionChanges(t),touchForceMin:i.length>0?Math.min(...i):0,touchForceMax:i.length>0?Math.max(...i):0,touchForceVariance:this._variance(i),touchRadiusMin:r.length>0?Math.min(...r):0,touchRadiusMax:r.length>0?Math.max(...r):0,touchRadiusVariance:this._variance(r),touchMultiTouchSeen:this.touchMultiTouchSeen,touchUniqueIdentifiers:this.touchIdentifiers.size,touchForceAllZero:s,touchForceAllOne:a}}_analyzePointerPoints(t){if(!t||t.length===0)return{pointerEvents:0,pointerAvgPressure:0,pointerPressureVariance:0,pointerMaxTilt:0,pointerHasNonMouseType:!1,pointerTypes:[]};let e=t.map(r=>r.pressure),n=e.length>0?e.reduce((r,s)=>r+s,0)/e.length:0,o=0,i=new Set;for(let r of t){let s=Math.abs(r.tiltX||0)+Math.abs(r.tiltY||0);s>o&&(o=s),r.pointerType&&i.add(r.pointerType)}return{pointerEvents:t.length,pointerAvgPressure:n,pointerPressureVariance:this._variance(e),pointerMaxTilt:o,pointerHasNonMouseType:Array.from(i).some(r=>r!=="mouse"&&r!=="unknown"),pointerTypes:Array.from(i)}}analyzeClick(t,e,n){let o=this.mousePositions;if(o.length<5)return this._getEmptyClickAnalysis();let i=o.slice(-20),r=n.left+n.width/2,s=n.top+n.height/2,a=Math.sqrt(Math.pow(t-r,2)+Math.pow(e-s,2)),l=0,u=0;for(let d=1;d<o.length;d++){let p=Math.sqrt(Math.pow(o[d].x-o[d-1].x,2)+Math.pow(o[d].y-o[d-1].y,2));u+=p,o[d].x>=n.left&&o[d].x<=n.right&&o[d].y>=n.top&&o[d].y<=n.bottom||(l+=p)}let h=u>0?l/u:0,f=0,g=!1,w=!1;for(let d of i){let p=d.x>=n.left&&d.x<=n.right&&d.y>=n.top&&d.y<=n.bottom;g&&!p&&(w=!0),w&&p&&(f++,w=!1),g=p}let _=0;for(let d=i.length-1;d>=0;d--){let p=i[d],I=p.x>=n.left&&p.x<=n.right&&p.y>=n.top&&p.y<=n.bottom;if(I&&d<i.length-1)_=i[i.length-1].t-p.t;else if(!I)break}let S=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?S/m:1;return{clickPrecision:a,explorationRatio:h,overshootCorrections:f,hoverTime:_,approachDirectness:v,approachPoints:i.length}}_detectMicroTremor(t){if(t.length<20)return .5;let e=5,n=0;for(let i=e;i<t.length-e;i++){let r=0,s=0;for(let l=i-e;l<=i+e;l++)r+=t[l].x,s+=t[l].y;r/=e*2+1,s/=e*2+1;let a=Math.sqrt(Math.pow(t[i].x-r,2)+Math.pow(t[i].y-s,2));n+=a}let o=n/(t.length-e*2);return Math.min(1,o/2)}_calculateStraightLineRatio(t){if(t.length<3)return 0;let e=0,n=0;for(let o=2;o<t.length;o++){let i=t[o-2],r=t[o-1],s=t[o],a=Math.atan2(r.y-i.y,r.x-i.x),l=Math.atan2(s.y-r.y,s.x-r.x),u=Math.abs(l-a);n++,u<.1&&e++}return n>0?e/n:0}_countDirectionChanges(t){let e=0;for(let n=2;n<t.length;n++){let o=Math.atan2(t[n-1].y-t[n-2].y,t[n-1].x-t[n-2].x),i=Math.atan2(t[n].y-t[n-1].y,t[n].x-t[n-1].x);Math.abs(i-o)>Math.PI/6&&e++}return e}_variance(t){if(t.length===0)return 0;let e=t.reduce((n,o)=>n+o,0)/t.length;return t.reduce((n,o)=>n+Math.pow(o-e,2),0)/t.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 b=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[t,e,n]=await Promise.all([this._getSpeechInfo(),this._getWebRTCInfo(),this._checkWorkerConsistency()]);return{speechInfo:t,webrtcInfo:e,workerConsistency:n}}_detectWebdriver(){let t=navigator,e=window;return!!(t.webdriver||e.document.__webdriver_evaluate||e.document.__selenium_evaluate||e.document.__webdriver_script_fn||e.document.__webdriver_script_func||e.document.__webdriver_script_function||e.document.$cdc_asdjflasutopfhvcZLmcfl_||e.document.$wdc_||e._Selenium_IDE_Recorder||e._phantom||e.__nightmare||e.callPhantom||e._phantom)}_getAutomationFlags(){let t=navigator,e=window;return{webdriver:!!t.webdriver,domAutomation:!!e.domAutomation,domAutomationController:!!e.domAutomationController,_selenium:!!e._selenium,__webdriver_script_fn:!!e.__webdriver_script_fn,__driver_evaluate:!!e.__driver_evaluate,__webdriver_evaluate:!!e.__webdriver_evaluate,__fxdriver_evaluate:!!e.__fxdriver_evaluate,__driver_unwrapped:!!e.__driver_unwrapped,__webdriver_unwrapped:!!e.__webdriver_unwrapped,__fxdriver_unwrapped:!!e.__fxdriver_unwrapped,_Selenium_IDE_Recorder:!!e._Selenium_IDE_Recorder,calledSelenium:!!e.calledSelenium,$chrome_asyncScriptInfo:!!e.$chrome_asyncScriptInfo,$cdc_asdjflasutopfhvcZLmcfl_:!!e.$cdc_asdjflasutopfhvcZLmcfl_,_phantom:!!e._phantom,callPhantom:!!e.callPhantom,__nightmare:!!e.__nightmare,__lastWatirAlert:!!e.__lastWatirAlert,__lastWatirConfirm:!!e.__lastWatirConfirm,__lastWatirPrompt:!!e.__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:!!e.chrome,chromeRuntime:!!(e.chrome&&e.chrome.runtime&&e.chrome.runtime.id),permissionsAPI:!!navigator.permissions}}_detectPlaywright(){try{let t=window,e=[];Object.getOwnPropertyNames(window).filter(r=>r.startsWith("__pw")||r.startsWith("__playwright")).length>0&&e.push("playwright_globals");let o=Object.getPrototypeOf(navigator);return Object.getOwnPropertyDescriptor(o,"webdriver")||e.push("webdriver_deleted"),{detected:e.length>0,signals:e}}catch{return{detected:!1,signals:[]}}}_detectCDP(){try{let t=window,e=[];Object.keys(window).filter(o=>o.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 o=Object.getOwnPropertyDescriptor(navigator,"webdriver");o&&typeof o.get=="function"&&o.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 t=document.createElement("canvas");t.width=200,t.height=50;let e=t.getContext("2d");e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("FCaptcha",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("FCaptcha",4,17);let n=t.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 t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{supported:!1};let n=e.getExtension("WEBGL_debug_renderer_info"),o=n?e.getParameter(n.UNMASKED_VENDOR_WEBGL):"unknown",i=n?e.getParameter(n.UNMASKED_RENDERER_WEBGL):"unknown",r=i.toLowerCase(),s=r.includes("swiftshader")||r.includes("llvmpipe")||r.includes("softpipe")||r.includes("virtualbox")||r.includes("vmware");return{supported:!0,vendor:o,renderer:i,version:e.getParameter(e.VERSION),shadingVersion:e.getParameter(e.SHADING_LANGUAGE_VERSION),suspiciousRenderer:s}}catch{return{supported:!1,error:!0}}}_getAudioInfo(){try{let t=window,e=t.AudioContext||t.webkitAudioContext;if(!e)return{supported:!1};let n=new e,o={supported:!0,sampleRate:n.sampleRate,state:n.state,baseLatency:n.baseLatency};return n.close(),o}catch{return{supported:!1,error:!0}}}_getLieDetection(){try{let t=window,e=[],n=i=>{try{return typeof i=="function"&&i.toString().indexOf("[native code]")===-1}catch{return!1}},o=(i,r)=>{n(i)&&e.push(r)};o(Function.prototype.toString,"Function.prototype.toString"),o(navigator.permissions&&navigator.permissions.query,"navigator.permissions.query"),o(t.Notification&&t.Notification.requestPermission,"Notification.requestPermission"),o(t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.toDataURL,"HTMLCanvasElement.toDataURL"),o(t.WebGLRenderingContext&&t.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&&e.push("navigator.webdriver getter")}catch{}return{supported:!0,patched:e,patchedCount:e.length}}catch{return{supported:!1}}}_getHeadlessIndicators(){let t=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:t.connection?t.connection.type:"unknown",connectionRtt:t.connection?t.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 e;let t=navigator;return{language:navigator.language,languageCount:((e=navigator.languages)==null?void 0:e.length)||0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:t.deviceMemory,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()}}_measureJSExecution(){let t={},e=performance.now();for(let i=0;i<1e3;i++)Math.sqrt(i)*Math.sin(i);t.mathOps=performance.now()-e,e=performance.now();let n=[];for(let i=0;i<1e3;i++)n.push(i);t.arrayOps=performance.now()-e,t.arrayLen=n.length,e=performance.now();let o="";for(let i=0;i<100;i++)o+="a";return t.stringOps=performance.now()-e,t}async measureRAFConsistency(){return new Promise(t=>{let e=[],n=0,o=10;function i(r){if(e.push(r),n++,n<o)requestAnimationFrame(i);else{let s=[];for(let u=1;u<e.length;u++)s.push(e[u]-e[u-1]);let a=s.reduce((u,h)=>u+h,0)/s.length,l=s.reduce((u,h)=>u+Math.pow(h-a,2),0)/s.length;t({avgFrameTime:a,frameTimeVariance:l,frames:o})}}requestAnimationFrame(i)})}_getMathFingerprint(){try{let t={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)},e=Object.values(t).map(o=>String(o)).join(","),n=0;for(let o=0;o<e.length;o++)n=(n<<5)-n+e.charCodeAt(o),n=n&n;return{hash:n.toString(16),sinPi:t.sin,tanLarge:t.tan,supported:!0}}catch{return{supported:!1,error:!0}}}_getErrorFingerprint(){try{let t={};try{null.foo}catch(o){t.typeError=o.message}try{[].length=-1}catch(o){t.rangeError=o.message}try{decodeURIComponent("%")}catch(o){t.uriError=o.message}try{({}).undefinedMethod()}catch(o){t.refTypeError=o.message}let e=Object.values(t).join("|"),n=0;for(let o=0;o<e.length;o++)n=(n<<5)-n+e.charCodeAt(o),n=n&n;return{hash:n.toString(16),typeError:t.typeError,supported:!0}}catch{return{supported:!1,error:!0}}}_getDOMRectFingerprint(){try{let t=document.createElement("div");t.style.cssText="position:absolute;left:-9999px;font-size:16px;font-family:Arial,sans-serif;";let e=document.createElement("span");e.textContent="FCaptcha Test String 123",t.appendChild(e);let n=document.createElement("span");n.style.cssText="letter-spacing:1px;word-spacing:2px;",n.textContent="WWWW 0000",t.appendChild(n),document.body.appendChild(t);let o=e.getBoundingClientRect(),i=n.getBoundingClientRect(),r=document.createRange();r.selectNode(e);let s=r.getBoundingClientRect();document.body.removeChild(t);let l=[o.width,o.height,o.x,o.y,i.width,i.height,s.width,s.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:s.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 t=["monospace","sans-serif","serif"],e=["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",r="72px",s={};for(let h of t)o.font=r+" "+h,s[h]=o.measureText(i).width;let a=[];for(let h of e){let f=!1;for(let g of t)if(o.font=r+' "'+h+'", '+g,o.measureText(i).width!==s[g]){f=!0;break}f&&a.push(h)}let l=a.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:a.length,hasArial:a.includes("Arial"),hasTimesNewRoman:a.includes("Times New Roman"),hasSegoeUI:a.includes("Segoe UI"),hasSFPro:a.includes("SF Pro"),hasDejaVuSans:a.includes("DejaVu Sans"),supported:!0}}catch{return{supported:!1,error:!0}}}async _getSpeechInfo(){try{if(!("speechSynthesis"in window))return{supported:!1};let e=await new Promise(a=>{let l=speechSynthesis.getVoices();if(l.length>0){a(l);return}let u=setTimeout(()=>a([]),1e3);speechSynthesis.onvoiceschanged=()=>{clearTimeout(u),a(speechSynthesis.getVoices())}}),n=e.filter(a=>a.localService),o=e.find(a=>a.default),i=[...new Set(e.map(a=>a.lang))],r=e.map(a=>a.name).sort().join(","),s=0;for(let a=0;a<r.length;a++)s=(s<<5)-s+r.charCodeAt(a),s=s&s;return{hash:s.toString(16),totalVoices:e.length,localVoices:n.length,languages:i.length,defaultVoiceLang:(o==null?void 0:o.lang)||null,hasGoogleVoices:e.some(a=>a.name.includes("Google")),hasMicrosoftVoices:e.some(a=>a.name.includes("Microsoft")),hasAppleVoices:e.some(a=>a.name.includes("Samantha")||a.name.includes("Alex")),supported:!0}}catch{return{supported:!1,error:!0}}}async _getWebRTCInfo(){try{let t={supported:"RTCPeerConnection"in window,mediaDevices:{supported:!1},localIPs:[]};if(!t.supported)return t;if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices)try{let e=await navigator.mediaDevices.enumerateDevices();t.mediaDevices={supported:!0,audioInputs:e.filter(n=>n.kind==="audioinput").length,audioOutputs:e.filter(n=>n.kind==="audiooutput").length,videoInputs:e.filter(n=>n.kind==="videoinput").length,totalDevices:e.length}}catch{t.mediaDevices={supported:!1,error:!0}}try{let e=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}),n=new Set;e.onicecandidate=o=>{if(o.candidate){let i=o.candidate.candidate,r=/([0-9]{1,3}\.){3}[0-9]{1,3}/g,s=i.match(r);s&&s.forEach(a=>{(a.startsWith("192.168.")||a.startsWith("10.")||a.startsWith("172.")||a.startsWith("169.254."))&&n.add(a)})}},e.createDataChannel(""),await e.createOffer().then(o=>e.setLocalDescription(o)),await new Promise(o=>setTimeout(o,500)),t.localIPs=Array.from(n),t.hasLocalIP=n.size>0,e.close()}catch{t.localIPError=!0}return t}catch{return{supported:!1,error:!0}}}async _checkWorkerConsistency(){try{if(typeof Worker=="undefined")return{supported:!1};let t=navigator,e=`
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([e],{type:"application/javascript"}),i=new Worker(URL.createObjectURL(n)),o=await new Promise((a,c)=>{let l=setTimeout(()=>c(new Error("timeout")),2e3);i.onmessage=u=>{clearTimeout(l),a(u.data)},i.onerror=()=>{clearTimeout(l),c(new Error("worker error"))},i.postMessage("collect")});i.terminate();let r={userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[],platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:t.deviceMemory,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()},s=[];return o.userAgent!==r.userAgent&&s.push("userAgent"),o.language!==r.language&&s.push("language"),o.platform!==r.platform&&s.push("platform"),o.hardwareConcurrency!==r.hardwareConcurrency&&s.push("hardwareConcurrency"),o.deviceMemory!==r.deviceMemory&&s.push("deviceMemory"),o.timezone!==r.timezone&&s.push("timezone"),o.timezoneOffset!==r.timezoneOffset&&s.push("timezoneOffset"),JSON.stringify(o.languages)!==JSON.stringify(r.languages)&&s.push("languages"),{supported:!0,consistent:s.length===0,mismatches:s,mismatchCount:s.length}}catch{return{supported:!1,error:!0}}}};var x=class{constructor(){this.motionEvents=[],this.orientationEvents=[],this._motionHandler=t=>this._recordMotion(t),this._orientationHandler=t=>this._recordOrientation(t),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(t){let e=t.accelerationIncludingGravity||t.acceleration||{};this.motionEvents.push({x:typeof e.x=="number"?e.x:0,y:typeof e.y=="number"?e.y:0,z:typeof e.z=="number"?e.z:0,t:performance.now()}),this.motionEvents.length>300&&this.motionEvents.shift()}_recordOrientation(t){this.orientationEvents.push({alpha:typeof t.alpha=="number"?t.alpha:0,beta:typeof t.beta=="number"?t.beta:0,gamma:typeof t.gamma=="number"?t.gamma:0,t:performance.now()}),this.orientationEvents.length>300&&this.orientationEvents.shift()}analyze(){let t=this.motionEvents,e=this.orientationEvents,n=0,i=0;if(t.length>1){let r=t.map(s=>Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z));i=r.reduce((s,a)=>s+a,0)/r.length,n=r.reduce((s,a)=>s+(a-i)*(a-i),0)/r.length}let o=0;if(e.length>1){let r=e.map(a=>Math.abs(a.beta)+Math.abs(a.gamma)),s=r.reduce((a,c)=>a+c,0)/r.length;o=r.reduce((a,c)=>a+(c-s)*(c-s),0)/r.length}return{motionEventCount:t.length,motionAccelAvg:i,motionAccelVariance:n,orientationEventCount:e.length,orientationVariance:o,hasSensorSupport:typeof window.DeviceMotionEvent!="undefined"}}};var V=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(e=>{document.addEventListener(e,n=>this._recordInteraction(n),{passive:!0})}),document.addEventListener("keydown",e=>this._recordTextareaKey(e),{passive:!0}),document.addEventListener("keyup",e=>this._recordTextareaKey(e),{passive:!0}),document.addEventListener("submit",e=>this._recordSubmit(e),{capture:!0}),this._interceptFormSubmit()}_recordInteraction(t){var n;let e=performance.now();this.firstInteractionTime===null&&(this.firstInteractionTime=e),this.lastInteractionTime=e,this.totalEvents++,this.eventLog.push({type:t.type,time:e,target:((n=t.target)==null?void 0:n.tagName)||"unknown"}),this.eventLog.length>50&&this.eventLog.shift()}_recordTextareaKey(t){let e=t.target;if((e==null?void 0:e.tagName)!=="TEXTAREA")return;let n=e.id||e.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 i=this.textareaStats.get(n),o=performance.now(),r=["Shift","Control","Alt","Meta","CapsLock","NumLock","ScrollLock"].includes(t.key);if(t.type==="keydown")i.keydowns.push(o),i.lastKeyTime!==null&&i.intervals.push(o-i.lastKeyTime),i.lastKeyTime=o,!r&&!t.repeat&&(i.activeKeyCount>0&&i.rollovers++,i.activeKeyCount++,i.pendingKeydowns.push(o)),i.keydowns.length>200&&i.keydowns.shift(),i.intervals.length>200&&i.intervals.shift();else if(t.type==="keyup"&&(i.keyups.push(o),i.keyups.length>200&&i.keyups.shift(),!r&&i.activeKeyCount>0&&(i.activeKeyCount--,i.pendingKeydowns.length>0))){let s=i.pendingKeydowns.shift(),a=o-s;a>0&&a<2e3&&(i.dwellTimes.push(a),i.dwellTimes.length>100&&i.dwellTimes.shift())}}_interceptFormSubmit(){let t=this,e=HTMLFormElement.prototype.submit;HTMLFormElement.prototype.submit=function(){return t._recordProgrammaticSubmit(this),e.apply(this,arguments)}}_recordProgrammaticSubmit(t){let e=performance.now();this.submitData={method:"programmatic",time:e,timeSincePageLoad:e-this.pageLoadTime,timeSinceFirstInteraction:this.firstInteractionTime?e-this.firstInteractionTime:null,timeSinceLastInteraction:this.lastInteractionTime?e-this.lastInteractionTime:null,eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:!1}}_recordSubmit(t){let e=performance.now(),n=this.eventLog.slice(-5),i=n.find(s=>s.type==="keydown"&&e-s.time<100),o=n.find(s=>s.type==="mousedown"&&e-s.time<100),r="unknown";i?r="keyboard":o?r="mouse":this.submitData||(r="programmatic_click"),(!this.submitData||this.submitData.method==="programmatic")&&(this.submitData={method:r,time:e,timeSincePageLoad:e-this.pageLoadTime,timeSinceFirstInteraction:this.firstInteractionTime?e-this.firstInteractionTime:null,timeSinceLastInteraction:this.lastInteractionTime?e-this.lastInteractionTime:null,eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:r==="keyboard"||r==="mouse"})}analyze(){let t=performance.now(),e={};return this.textareaStats.forEach((i,o)=>{let r=i.intervals,s=0,a=0;r.length>0&&(s=r.reduce((c,l)=>c+l,0)/r.length,a=r.reduce((c,l)=>c+Math.pow(l-s,2),0)/r.length),e[o]={keyCount:i.keydowns.length,avgKeyInterval:s,keyIntervalVariance:a,keydownUpRatio:i.keyups.length>0?i.keydowns.length/i.keyups.length:0,pasteCount:i.pasteCount,intervals:i.intervals.slice(-100),dwellTimes:i.dwellTimes.slice(-100),rollovers:i.rollovers}}),document.querySelectorAll("textarea").forEach(i=>{let o=i.id||i.name||"unnamed",r=(i.value||"").length;r>0&&(e[o]?(e[o].contentLength=r,e[o].noKeyboardEvents=e[o].keyCount===0):e[o]={keyCount:0,avgKeyInterval:0,keyIntervalVariance:0,keydownUpRatio:0,pasteCount:0,contentLength:r,noKeyboardEvents:!0})}),{pageLoadToFirstInteraction:this.firstInteractionTime?this.firstInteractionTime-this.pageLoadTime:null,pageLoadToNow:t-this.pageLoadTime,totalInteractionEvents:this.totalEvents,submit:this.submitData||{method:"none",eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:!1},textareaKeyboard:Object.keys(e).length>0?e:null}}recordPaste(t){let e=t.target;if((e==null?void 0:e.tagName)!=="TEXTAREA")return;let n=e.id||e.name||"unnamed";this.textareaStats.has(n)&&this.textareaStats.get(n).pasteCount++}},A=null;function M(){return A||(A=new V,document.addEventListener("paste",h=>A.recordPaste(h),{passive:!0})),A}typeof document!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>M()):M());async function T(h){let t=new TextEncoder().encode(h),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}var k=class{constructor(){this.firstInteractionTime=null;this.powResult=null;this.pageLoadTime=performance.now()}recordFirstInteraction(){this.firstInteractionTime||(this.firstInteractionTime=performance.now())}async performProofOfWork(t=4){let e=`${Date.now()}:${Math.random().toString(36).slice(2)}`,n="0".repeat(t),i=performance.now(),o=0,r=0;for(;;){let s=await T(`${e}:${o}`);if(r++,s.startsWith(n))return this.powResult={prefix:e,nonce:o,hash:s,iterations:r,duration:performance.now()-i,difficulty:t},this.powResult;o++,r%1e3===0&&await new Promise(a=>setTimeout(a,0))}}collect(t){let e={};if(performance.timing){let n=performance.timing;e.dnsLookup=n.domainLookupEnd-n.domainLookupStart,e.tcpConnection=n.connectEnd-n.connectStart,e.serverResponse=n.responseEnd-n.requestStart,e.domLoad=n.domContentLoadedEventEnd-n.navigationStart,e.fullLoad=n.loadEventEnd-n.navigationStart}return{pageLoadToFirstInteraction:this.firstInteractionTime?this.firstInteractionTime-this.pageLoadTime:null,firstInteractionToClick:this.firstInteractionTime&&t?t-this.firstInteractionTime:null,totalSessionTime:performance.now()-this.pageLoadTime,performanceTiming:e,pow:this.powResult}}};var z=null,K="/__webdecoy";function b(){return z}function W(h){z=h}function P(){return K}function U(h){K=h.replace(/\/$/,"")}var D=class{constructor(){this.workers=[];this.challenge=null;this.solution=null;this.solving=!1;this.solvePromise=null;this.startTime=null}_createWorker(){let t=`
15
+ `,n=new Blob([e],{type:"application/javascript"}),o=new Worker(URL.createObjectURL(n)),i=await new Promise((a,l)=>{let u=setTimeout(()=>l(new Error("timeout")),2e3);o.onmessage=h=>{clearTimeout(u),a(h.data)},o.onerror=()=>{clearTimeout(u),l(new Error("worker error"))},o.postMessage("collect")});o.terminate();let r={userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[],platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:t.deviceMemory,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset()},s=[];return i.userAgent!==r.userAgent&&s.push("userAgent"),i.language!==r.language&&s.push("language"),i.platform!==r.platform&&s.push("platform"),i.hardwareConcurrency!==r.hardwareConcurrency&&s.push("hardwareConcurrency"),i.deviceMemory!==r.deviceMemory&&s.push("deviceMemory"),i.timezone!==r.timezone&&s.push("timezone"),i.timezoneOffset!==r.timezoneOffset&&s.push("timezoneOffset"),JSON.stringify(i.languages)!==JSON.stringify(r.languages)&&s.push("languages"),{supported:!0,consistent:s.length===0,mismatches:s,mismatchCount:s.length}}catch{return{supported:!1,error:!0}}}};var T=class{constructor(){this.motionEvents=[],this.orientationEvents=[],this._motionHandler=t=>this._recordMotion(t),this._orientationHandler=t=>this._recordOrientation(t),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(t){let e=t.accelerationIncludingGravity||t.acceleration||{};this.motionEvents.push({x:typeof e.x=="number"?e.x:0,y:typeof e.y=="number"?e.y:0,z:typeof e.z=="number"?e.z:0,t:performance.now()}),this.motionEvents.length>300&&this.motionEvents.shift()}_recordOrientation(t){this.orientationEvents.push({alpha:typeof t.alpha=="number"?t.alpha:0,beta:typeof t.beta=="number"?t.beta:0,gamma:typeof t.gamma=="number"?t.gamma:0,t:performance.now()}),this.orientationEvents.length>300&&this.orientationEvents.shift()}analyze(){let t=this.motionEvents,e=this.orientationEvents,n=0,o=0;if(t.length>1){let r=t.map(s=>Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z));o=r.reduce((s,a)=>s+a,0)/r.length,n=r.reduce((s,a)=>s+(a-o)*(a-o),0)/r.length}let i=0;if(e.length>1){let r=e.map(a=>Math.abs(a.beta)+Math.abs(a.gamma)),s=r.reduce((a,l)=>a+l,0)/r.length;i=r.reduce((a,l)=>a+(l-s)*(l-s),0)/r.length}return{motionEventCount:t.length,motionAccelAvg:o,motionAccelVariance:n,orientationEventCount:e.length,orientationVariance:i,hasSensorSupport:typeof window.DeviceMotionEvent!="undefined"}}};var K=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(e=>{document.addEventListener(e,n=>this._recordInteraction(n),{passive:!0})}),document.addEventListener("keydown",e=>this._recordTextareaKey(e),{passive:!0}),document.addEventListener("keyup",e=>this._recordTextareaKey(e),{passive:!0}),document.addEventListener("submit",e=>this._recordSubmit(e),{capture:!0}),this._interceptFormSubmit()}_recordInteraction(t){var n;let e=performance.now();this.firstInteractionTime===null&&(this.firstInteractionTime=e),this.lastInteractionTime=e,this.totalEvents++,this.eventLog.push({type:t.type,time:e,target:((n=t.target)==null?void 0:n.tagName)||"unknown"}),this.eventLog.length>50&&this.eventLog.shift()}_recordTextareaKey(t){let e=t.target;if((e==null?void 0:e.tagName)!=="TEXTAREA")return;let n=e.id||e.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(),r=["Shift","Control","Alt","Meta","CapsLock","NumLock","ScrollLock"].includes(t.key);if(t.type==="keydown")o.keydowns.push(i),o.lastKeyTime!==null&&o.intervals.push(i-o.lastKeyTime),o.lastKeyTime=i,!r&&!t.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(t.type==="keyup"&&(o.keyups.push(i),o.keyups.length>200&&o.keyups.shift(),!r&&o.activeKeyCount>0&&(o.activeKeyCount--,o.pendingKeydowns.length>0))){let s=o.pendingKeydowns.shift(),a=i-s;a>0&&a<2e3&&(o.dwellTimes.push(a),o.dwellTimes.length>100&&o.dwellTimes.shift())}}_interceptFormSubmit(){let t=this,e=HTMLFormElement.prototype.submit;HTMLFormElement.prototype.submit=function(){return t._recordProgrammaticSubmit(this),e.apply(this,arguments)}}_recordProgrammaticSubmit(t){let e=performance.now();this.submitData={method:"programmatic",time:e,timeSincePageLoad:e-this.pageLoadTime,timeSinceFirstInteraction:this.firstInteractionTime?e-this.firstInteractionTime:null,timeSinceLastInteraction:this.lastInteractionTime?e-this.lastInteractionTime:null,eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:!1}}_recordSubmit(t){let e=performance.now(),n=this.eventLog.slice(-5),o=n.find(s=>s.type==="keydown"&&e-s.time<100),i=n.find(s=>s.type==="mousedown"&&e-s.time<100),r="unknown";o?r="keyboard":i?r="mouse":this.submitData||(r="programmatic_click"),(!this.submitData||this.submitData.method==="programmatic")&&(this.submitData={method:r,time:e,timeSincePageLoad:e-this.pageLoadTime,timeSinceFirstInteraction:this.firstInteractionTime?e-this.firstInteractionTime:null,timeSinceLastInteraction:this.lastInteractionTime?e-this.lastInteractionTime:null,eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:r==="keyboard"||r==="mouse"})}analyze(){let t=performance.now(),e={};return this.textareaStats.forEach((o,i)=>{let r=o.intervals,s=0,a=0;r.length>0&&(s=r.reduce((l,u)=>l+u,0)/r.length,a=r.reduce((l,u)=>l+Math.pow(u-s,2),0)/r.length),e[i]={keyCount:o.keydowns.length,avgKeyInterval:s,keyIntervalVariance:a,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",r=(o.value||"").length;r>0&&(e[i]?(e[i].contentLength=r,e[i].noKeyboardEvents=e[i].keyCount===0):e[i]={keyCount:0,avgKeyInterval:0,keyIntervalVariance:0,keydownUpRatio:0,pasteCount:0,contentLength:r,noKeyboardEvents:!0})}),{pageLoadToFirstInteraction:this.firstInteractionTime?this.firstInteractionTime-this.pageLoadTime:null,pageLoadToNow:t-this.pageLoadTime,totalInteractionEvents:this.totalEvents,submit:this.submitData||{method:"none",eventsBeforeSubmit:this.totalEvents,hadTriggerEvent:!1},textareaKeyboard:Object.keys(e).length>0?e:null}}recordPaste(t){let e=t.target;if((e==null?void 0:e.tagName)!=="TEXTAREA")return;let n=e.id||e.name||"unnamed";this.textareaStats.has(n)&&this.textareaStats.get(n).pasteCount++}},O=null;function P(){return O||(O=new K,document.addEventListener("paste",c=>O.recordPaste(c),{passive:!0})),O}typeof document!="undefined"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>P()):P());async function M(c){let t=new TextEncoder().encode(c),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}var C=class{constructor(){this.firstInteractionTime=null;this.powResult=null;this.pageLoadTime=performance.now()}recordFirstInteraction(){this.firstInteractionTime||(this.firstInteractionTime=performance.now())}async performProofOfWork(t=4){let e=`${Date.now()}:${Math.random().toString(36).slice(2)}`,n="0".repeat(t),o=performance.now(),i=0,r=0;for(;;){let s=await M(`${e}:${i}`);if(r++,s.startsWith(n))return this.powResult={prefix:e,nonce:i,hash:s,iterations:r,duration:performance.now()-o,difficulty:t},this.powResult;i++,r%1e3===0&&await new Promise(a=>setTimeout(a,0))}}collect(t){let e={};if(performance.timing){let n=performance.timing;e.dnsLookup=n.domainLookupEnd-n.domainLookupStart,e.tcpConnection=n.connectEnd-n.connectStart,e.serverResponse=n.responseEnd-n.requestStart,e.domLoad=n.domContentLoadedEventEnd-n.navigationStart,e.fullLoad=n.loadEventEnd-n.navigationStart}return{pageLoadToFirstInteraction:this.firstInteractionTime?this.firstInteractionTime-this.pageLoadTime:null,firstInteractionToClick:this.firstInteractionTime&&t?t-this.firstInteractionTime:null,totalSessionTime:performance.now()-this.pageLoadTime,performanceTiming:e,pow:this.powResult}}};var N=null,j="/__webdecoy";function x(){return N}function F(c){N=c}function L(){return j}function B(c){j=c.replace(/\/$/,"")}var R=class{constructor(){this.workers=[];this.challenge=null;this.solution=null;this.solving=!1;this.solvePromise=null;this.startTime=null}_createWorker(){let t=`
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
- `,e=new Blob([t],{type:"application/javascript"});return new Worker(URL.createObjectURL(e))}_threadCount(){let t=typeof navigator!="undefined"&&navigator.hardwareConcurrency||1;return Math.max(1,Math.floor(t/2))}_terminateWorkers(){for(let t of this.workers)try{t.terminate()}catch{}this.workers=[]}async fetchChallenge(t){let e=b();if(!e)return this._generateLocalChallenge();try{let n=await fetch(`${e}${P()}/challenge?siteKey=${encodeURIComponent(t||"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 t=Math.random().toString(36).slice(2)+Date.now().toString(36);return this.challenge={challengeId:t,prefix:`${t}:${Date.now()}:4`,difficulty:4,expiresAt:Date.now()+3e5,local:!0},this.challenge}async startSolving(t){return this._solve(t,null)}async solveWithSignalsHash(t,e){return this._solve(t,e)}async _solve(t,e){if(this.solving&&this.solvePromise)return this.solvePromise;this.challenge||await this.fetchChallenge(t);let n=this.challenge;return this.solving=!0,this.startTime=performance.now(),this.solvePromise=new Promise((i,o)=>{let r=this._threadCount(),s=!1,a=(c,l)=>{s||(s=!0,this.solving=!1,this._terminateWorkers(),c(l))};for(let c=0;c<r;c++){let l=this._createWorker();l.onmessage=u=>{u.data.found&&(this.solution={challengeId:n.challengeId,nonce:u.data.nonce,hash:u.data.hash,iterations:u.data.iterations,duration:u.data.duration,difficulty:n.difficulty,signalsHash:e||null,local:n.local||!1},a(i,this.solution))},l.onerror=u=>{a(o,u)},l.postMessage({prefix:n.prefix,difficulty:n.difficulty,signalsHash:e||null,startNonce:c,stride:r,batchSize:5e3}),this.workers.push(l)}}),this.solvePromise}async getSolution(t){return this.solution?this.solution:this.solving&&this.solvePromise?this.solvePromise:this.startSolving(t)}reset(){this._terminateWorkers(),this.challenge=null,this.solution=null,this.solving=!1,this.solvePromise=null}},H=null;function j(){return H||(H=new D),H}var C=class{constructor(t,e){this.token=null;this.verified=!1;let n=typeof t=="string"?document.getElementById(t):t;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},e),this.id="webdecoy_"+Math.random().toString(36).slice(2,11),this.behavioral=new S,this.environmental=new E,this.temporal=new k,this.sensor=new x,this.powManager=j(),this._init()}_init(){this._createWidget(),this._attachListeners(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(t){console.warn("PoW challenge fetch failed:",t)}}_createWidget(){let t=this.options.theme==="dark";this.container.innerHTML=`
57
+ `,e=new Blob([t],{type:"application/javascript"});return new Worker(URL.createObjectURL(e))}_threadCount(){let t=typeof navigator!="undefined"&&navigator.hardwareConcurrency||1;return Math.max(1,Math.floor(t/2))}_terminateWorkers(){for(let t of this.workers)try{t.terminate()}catch{}this.workers=[]}async fetchChallenge(t){let e=x();if(!e)return this._generateLocalChallenge();try{let n=await fetch(`${e}${L()}/challenge?siteKey=${encodeURIComponent(t||"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 t=Math.random().toString(36).slice(2)+Date.now().toString(36);return this.challenge={challengeId:t,prefix:`${t}:${Date.now()}:4`,difficulty:4,expiresAt:Date.now()+3e5,local:!0},this.challenge}async startSolving(t){return this._solve(t,null)}async solveWithSignalsHash(t,e){return this._solve(t,e)}async _solve(t,e){if(this.solving&&this.solvePromise)return this.solvePromise;this.challenge||await this.fetchChallenge(t);let n=this.challenge;return this.solving=!0,this.startTime=performance.now(),this.solvePromise=new Promise((o,i)=>{let r=this._threadCount(),s=!1,a=(l,u)=>{s||(s=!0,this.solving=!1,this._terminateWorkers(),l(u))};for(let l=0;l<r;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:e||null,local:n.local||!1},a(o,this.solution))},u.onerror=h=>{a(i,h)},u.postMessage({prefix:n.prefix,difficulty:n.difficulty,signalsHash:e||null,startNonce:l,stride:r,batchSize:5e3}),this.workers.push(u)}}),this.solvePromise}async getSolution(t){return this.solution?this.solution:this.solving&&this.solvePromise?this.solvePromise:this.startSolving(t)}reset(){this._terminateWorkers(),this.challenge=null,this.solution=null,this.solving=!1,this.solvePromise=null}},z=null;function $(){return z||(z=new R),z}var D=class{constructor(t,e){this.token=null;this.verified=!1;let n=typeof t=="string"?document.getElementById(t):t;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},e),this.id="webdecoy_"+Math.random().toString(36).slice(2,11),this.behavioral=new E,this.environmental=new b,this.temporal=new C,this.sensor=new T,this.powManager=$(),this._init()}_init(){this._createWidget(),this._attachListeners(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(t){console.warn("PoW challenge fetch failed:",t)}}_createWidget(){let t=this.options.theme==="dark";this.container.innerHTML=`
58
58
  <div class="webdecoy-widget ${t?"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",e=>this.behavioral.recordMouseMove(e),{passive:!0}),document.addEventListener("mousedown",e=>this.behavioral.recordMouseDown(e),{passive:!0}),document.addEventListener("mouseup",e=>this.behavioral.recordMouseUp(e),{passive:!0}),document.addEventListener("scroll",e=>this.behavioral.recordScroll(e),{passive:!0}),document.addEventListener("keydown",e=>this.behavioral.recordKeyEvent(e),{passive:!0}),document.addEventListener("keyup",e=>this.behavioral.recordKeyEvent(e),{passive:!0}),document.addEventListener("touchstart",e=>this.behavioral.recordTouch(e),{passive:!0}),document.addEventListener("touchmove",e=>this.behavioral.recordTouch(e),{passive:!0}),document.addEventListener("pointermove",e=>this.behavioral.recordPointer(e),{passive:!0}),document.addEventListener("pointerdown",e=>this.behavioral.recordPointer(e),{passive:!0}),document.addEventListener("pointerup",e=>this.behavioral.recordPointer(e),{passive:!0}),document.addEventListener("focus",e=>this.behavioral.recordFocus(e),{passive:!0,capture:!0}),document.addEventListener("blur",e=>this.behavioral.recordFocus(e),{passive:!0,capture:!0}),this.sensor.attach();let t=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0}),this.checkbox.addEventListener("click",e=>{this._handleClick(e)}),this.checkbox.addEventListener("keydown",e=>{(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),this._handleClick(e))})}async _handleClick(t){var i,o,r;if(this.verified||this.checkbox.classList.contains("loading"))return;let e=performance.now(),n=this.checkbox.getBoundingClientRect();this.checkbox.classList.add("loading"),this.spinner.style.display="block",this.label.textContent="Verifying...";try{let s=this.behavioral.analyze(),a="clientX"in t?t.clientX:n.left,c="clientY"in t?t.clientY:n.top,l=this.behavioral.analyzeClick(a,c,n),u=this.environmental.collect(),[v,p]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),y=this.temporal.collect(e),w=M().analyze(),_=this.sensor.analyze(),m={behavioral:{...s,...l},environmental:{...u,rafConsistency:v,...p,sensor:_},temporal:y,formAnalysis:w,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),L={duration:g.duration,iterations:g.iterations,difficulty:g.difficulty},F=await this._verify(m,g,f,d,L);F.success?this._showSuccess((o=F.token)!=null?o:""):this._showFailure((r=F.message)!=null?r:void 0)}catch(s){console.error("WebDecoy captcha error:",s),this._showFailure("Verification failed. Please try again.")}}async _verify(t,e,n,i,o){let r=b();if(!r)return this._clientSideVerify(t);try{return await(await fetch(r+P()+"/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:t,signalsJson:n||null,powSolution:e?{challengeId:e.challengeId,nonce:e.nonce,hash:e.hash,signalsHash:i||null}:null,powTiming:o||null})})).json()}catch{return console.warn("Server unavailable, using client-side verification"),this._clientSideVerify(t)}}_clientSideVerify(t){let e=0,n=t.behavioral,i=t.environmental,o=t.temporal,r=(n.touchEvents||0)>=3,s=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!r&&!s?e+=.35:n.totalPoints<10&&!r&&!s&&n.trajectoryLength<30&&(e+=.15),n.microTremorScore<.2&&(e+=.12),n.velocityVariance<.03&&(e+=.1),n.explorationRatio<.05&&(e+=.08),n.overshootCorrections===0&&n.trajectoryLength>100&&(e+=.05),n.clickPrecision<2&&(e+=.05),n.straightLineRatio>.8&&(e+=.08),n.microMovements<5&&n.totalPoints>50&&(e+=.06),i.webdriver&&(e+=.25),i.automationFlags&&i.automationFlags.plugins===0&&(e+=.05),i.webglInfo&&i.webglInfo.suspiciousRenderer&&(e+=.1),i.headlessIndicators&&!i.headlessIndicators.hasOuterDimensions&&(e+=.12),i.headlessIndicators&&i.headlessIndicators.innerEqualsOuter&&(e+=.05),o.pow&&o.pow.duration<50&&(e+=.1),n.eventDeltaVariance<3&&(e+=.08),n.interactionDuration<300&&(e+=.07);let a=e<.5;return{success:a,score:e,token:a?btoa(JSON.stringify({timestamp:Date.now(),score:e,id:this.id})):null,message:a?null:"Verification failed"}}_showSuccess(t){this.verified=!0,this.token=t,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(t),this.container.dispatchEvent(new CustomEvent("webdecoy:verified",{detail:{token:t}}))}_showFailure(t){this.checkbox.classList.remove("loading"),this.checkbox.classList.add("failed"),this.spinner.style.display="none",this.label.textContent=t||"Verification failed",this.options.errorCallback&&this.options.errorCallback(t),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 S,this.temporal=new k,this.sensor&&this.sensor.detach(),this.sensor=new x,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 I=class{constructor(t){this.lastScore=null;this.listeners=[];this.options=Object.assign({siteKey:null,serverUrl:null,minCollectionTime:2e3,autoScore:!0,scoreThreshold:.5,powDifficulty:3},t),this.id="webdecoy_inv_"+Math.random().toString(36).slice(2,11),this.behavioral=new S,this.environmental=new E,this.temporal=new k,this.sensor=new x,this.powManager=new D,this.startTime=Date.now(),this._init()}_init(){this._attachListeners();let t=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0}),document.addEventListener("scroll",t,{once:!0}),this.options.autoScore&&this._attachToForms(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(t){console.warn("PoW challenge fetch failed:",t)}}_attachListeners(){let t={mousemove:e=>this.behavioral.recordMouseMove(e),mousedown:e=>this.behavioral.recordMouseDown(e),mouseup:e=>this.behavioral.recordMouseUp(e),scroll:e=>this.behavioral.recordScroll(e),keydown:e=>this.behavioral.recordKeyEvent(e),keyup:e=>this.behavioral.recordKeyEvent(e),touchmove:e=>this.behavioral.recordTouch(e),touchstart:e=>this.behavioral.recordTouch(e),pointermove:e=>this.behavioral.recordPointer(e),pointerdown:e=>this.behavioral.recordPointer(e),pointerup:e=>this.behavioral.recordPointer(e),focus:e=>this.behavioral.recordFocus(e),blur:e=>this.behavioral.recordFocus(e)};for(let[e,n]of Object.entries(t)){let i=e==="focus"||e==="blur"?{passive:!0,capture:!0}:{passive:!0};document.addEventListener(e,n,i),this.listeners.push({event:e,handler:n,opts:i})}this.sensor.attach()}_attachToForms(){document.addEventListener("submit",async t=>{let e=t.target;if(e.dataset.webdecoyIgnore)return;let n=e.querySelector('input[name="webdecoy_token"]');if(n||(n=document.createElement("input"),n.type="hidden",n.name="webdecoy_token",e.appendChild(n)),!this.lastScore||Date.now()-this.lastScore.timestamp>6e4){t.preventDefault();try{let i=await this.execute(e.dataset.webdecoyAction||"form_submit");n.value=i.token||"",i.success?e.submit():document.dispatchEvent(new CustomEvent("webdecoy:blocked",{detail:{score:i.score,form:e}}))}catch(i){console.error("WebDecoy captcha error:",i),e.submit()}}else n.value=this.lastScore.token||""})}async execute(t=""){var _;let e=Date.now()-this.startTime;e<this.options.minCollectionTime&&await new Promise(m=>setTimeout(m,this.options.minCollectionTime-e));let n=this.behavioral.analyze(),i=this.environmental.collect(),o=this.temporal.collect(Date.now()),[r,s]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),a=M().analyze(),c=this.sensor.analyze(),l={behavioral:n,environmental:{...i,rafConsistency:r,...s,sensor:c},temporal:o,formAnalysis:a,meta:{sessionId:this.id,siteKey:this.options.siteKey,action:t,challengeNonce:((_=this.powManager.challenge)==null?void 0:_.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}},u=JSON.stringify(l),v=await T(u),p=await this.powManager.solveWithSignalsHash(this.options.siteKey,v),y={duration:p.duration,iterations:p.iterations,difficulty:p.difficulty},w=await this._score(l,t,p,u,v,y);return this.lastScore={...w,timestamp:Date.now()},w}async _score(t,e,n,i,o,r){let s=this.options.serverUrl||b();if(!s)return this._clientSideScore(t);try{return await(await fetch(s+P()+"/score",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:t,signalsJson:i||null,action:e,powSolution:n?{challengeId:n.challengeId,nonce:n.nonce,hash:n.hash,signalsHash:o||null}:null,powTiming:r||null})})).json()}catch{return console.warn("WebDecoy server unavailable, using client-side scoring"),this._clientSideScore(t)}}_clientSideScore(t){let e=0,n=t.behavioral,i=t.environmental,o=t.temporal,r=t.meta,s=(n.touchEvents||0)>=3,a=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!s&&!a?e+=.35:n.totalPoints<10&&!s&&!a&&n.trajectoryLength<30&&(e+=.15),n.microTremorScore<.2&&(e+=.12),n.velocityVariance<.03&&(e+=.1),n.totalPoints<10&&r.sessionDuration>5e3&&(e+=.08),n.scrollEvents===0&&n.keyEvents===0&&r.sessionDuration>1e4&&(e+=.06),n.eventDeltaVariance<3&&(e+=.08),n.straightLineRatio>.8&&(e+=.08),i.webdriver&&(e+=.25),i.automationFlags&&i.automationFlags.plugins===0&&(e+=.06),i.headlessIndicators&&!i.headlessIndicators.hasOuterDimensions&&(e+=.12),i.webglInfo&&i.webglInfo.suspiciousRenderer&&(e+=.1),o.pow&&o.pow.duration<30&&(e+=.1),r.sessionDuration<500&&(e+=.12),r.sessionDuration<1e3&&n.totalPoints<5&&(e+=.15);let c=e<this.options.scoreThreshold;return{success:c,score:Math.min(1,e),action:r.action,token:c?btoa(JSON.stringify({timestamp:Date.now(),score:e,action:r.action,id:this.id})):null}}getScore(){return this.lastScore}destroy(){for(let{event:t,handler:e,opts:n}of this.listeners)document.removeEventListener(t,e,n);this.listeners=[],this.powManager&&this.powManager.reset()}};var R={widgets:new Map,get serverUrl(){return b()},set serverUrl(h){W(h)},configure(h){h.serverUrl&&W(h.serverUrl),h.basePath&&U(h.basePath)},render(h,t){let e=new C(h,t);return this.widgets.set(e.id,e),e.id},getResponse(h){let t=this.widgets.get(h);return t&&t instanceof C?t.getToken():null},reset(h){let t=this.widgets.get(h);t instanceof C&&t.reset()},invisible(h){let t=new I(h);return this.widgets.set(t.id,t),t},async execute(h,t={}){let e=new I({siteKey:h,serverUrl:b(),minCollectionTime:t.minTime||1e3,autoScore:!1,powDifficulty:t.powDifficulty||3}),n=await e.execute(t.action||"");return e.destroy(),n},getSignals(){return{environmental:new E().collect()}},autoInit(){document.querySelectorAll("[data-webdecoy]").forEach(h=>{let t=h.dataset.sitekey||h.dataset.webdecoy,e=h.dataset.theme||"light",n=h.dataset.endpoint,i=h.dataset.callback,o=i?window[i]:void 0;n&&W(n),this.render(h,{siteKey:t,theme:e,callback:o!=null?o:null})})}};window.WebDecoyCaptcha=R;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>R.autoInit()):R.autoInit();return Y(G);})();
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",e=>this.behavioral.recordMouseMove(e),{passive:!0}),document.addEventListener("mousedown",e=>this.behavioral.recordMouseDown(e),{passive:!0}),document.addEventListener("mouseup",e=>this.behavioral.recordMouseUp(e),{passive:!0}),document.addEventListener("scroll",e=>this.behavioral.recordScroll(e),{passive:!0}),document.addEventListener("keydown",e=>this.behavioral.recordKeyEvent(e),{passive:!0}),document.addEventListener("keyup",e=>this.behavioral.recordKeyEvent(e),{passive:!0}),document.addEventListener("touchstart",e=>this.behavioral.recordTouch(e),{passive:!0}),document.addEventListener("touchmove",e=>this.behavioral.recordTouch(e),{passive:!0}),document.addEventListener("pointermove",e=>this.behavioral.recordPointer(e),{passive:!0}),document.addEventListener("pointerdown",e=>this.behavioral.recordPointer(e),{passive:!0}),document.addEventListener("pointerup",e=>this.behavioral.recordPointer(e),{passive:!0}),document.addEventListener("focus",e=>this.behavioral.recordFocus(e),{passive:!0,capture:!0}),document.addEventListener("blur",e=>this.behavioral.recordFocus(e),{passive:!0,capture:!0}),this.sensor.attach();let t=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0}),this.checkbox.addEventListener("click",e=>{this._handleClick(e)}),this.checkbox.addEventListener("keydown",e=>{(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),this._handleClick(e))})}async _handleClick(t){var o,i,r;if(this.verified||this.checkbox.classList.contains("loading"))return;let e=performance.now(),n=this.checkbox.getBoundingClientRect();this.checkbox.classList.add("loading"),this.spinner.style.display="block",this.label.textContent="Verifying...";try{let s=this.behavioral.analyze(),a="clientX"in t?t.clientX:n.left,l="clientY"in t?t.clientY:n.top,u=this.behavioral.analyzeClick(a,l,n),h=this.environmental.collect(),[f,g]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),w=this.temporal.collect(e),_=P().analyze(),S=this.sensor.analyze(),m={behavioral:{...s,...u},environmental:{...h,rafConsistency:f,...g,sensor:S},temporal:w,formAnalysis:_,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 M(v),p=await this.powManager.solveWithSignalsHash(this.options.siteKey,d),I={duration:p.duration,iterations:p.iterations,difficulty:p.difficulty},V=await this._verify(m,p,v,d,I);V.success?this._showSuccess((i=V.token)!=null?i:""):this._showFailure((r=V.message)!=null?r:void 0)}catch(s){console.error("WebDecoy captcha error:",s),this._showFailure("Verification failed. Please try again.")}}async _verify(t,e,n,o,i){let r=x();if(!r)return this._clientSideVerify(t);try{return await(await fetch(r+L()+"/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:t,signalsJson:n||null,powSolution:e?{challengeId:e.challengeId,nonce:e.nonce,hash:e.hash,signalsHash:o||null}:null,powTiming:i||null})})).json()}catch{return console.warn("Server unavailable, using client-side verification"),this._clientSideVerify(t)}}_clientSideVerify(t){let e=0,n=t.behavioral,o=t.environmental,i=t.temporal,r=(n.touchEvents||0)>=3,s=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!r&&!s?e+=.35:n.totalPoints<10&&!r&&!s&&n.trajectoryLength<30&&(e+=.15),n.microTremorScore<.2&&(e+=.12),n.velocityVariance<.03&&(e+=.1),n.explorationRatio<.05&&(e+=.08),n.overshootCorrections===0&&n.trajectoryLength>100&&(e+=.05),n.clickPrecision<2&&(e+=.05),n.straightLineRatio>.8&&(e+=.08),n.microMovements<5&&n.totalPoints>50&&(e+=.06),o.webdriver&&(e+=.25),o.automationFlags&&o.automationFlags.plugins===0&&(e+=.05),o.webglInfo&&o.webglInfo.suspiciousRenderer&&(e+=.1),o.headlessIndicators&&!o.headlessIndicators.hasOuterDimensions&&(e+=.12),o.headlessIndicators&&o.headlessIndicators.innerEqualsOuter&&(e+=.05),i.pow&&i.pow.duration<50&&(e+=.1),n.eventDeltaVariance<3&&(e+=.08),n.interactionDuration<300&&(e+=.07);let a=e<.5;return{success:a,score:e,token:a?btoa(JSON.stringify({timestamp:Date.now(),score:e,id:this.id})):null,message:a?null:"Verification failed"}}_showSuccess(t){this.verified=!0,this.token=t,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(t),this.container.dispatchEvent(new CustomEvent("webdecoy:verified",{detail:{token:t}}))}_showFailure(t){this.checkbox.classList.remove("loading"),this.checkbox.classList.add("failed"),this.spinner.style.display="none",this.label.textContent=t||"Verification failed",this.options.errorCallback&&this.options.errorCallback(t),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 E,this.temporal=new C,this.sensor&&this.sensor.detach(),this.sensor=new T,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 A=class{constructor(t){this.lastScore=null;this.listeners=[];this.options=Object.assign({siteKey:null,serverUrl:null,minCollectionTime:2e3,autoScore:!0,scoreThreshold:.5,powDifficulty:3},t),this.id="webdecoy_inv_"+Math.random().toString(36).slice(2,11),this.behavioral=new E,this.environmental=new b,this.temporal=new C,this.sensor=new T,this.powManager=new R,this.startTime=Date.now(),this._init()}_init(){this._attachListeners();let t=()=>this.temporal.recordFirstInteraction();document.addEventListener("mousemove",t,{once:!0}),document.addEventListener("touchstart",t,{once:!0}),document.addEventListener("keydown",t,{once:!0}),document.addEventListener("scroll",t,{once:!0}),this.options.autoScore&&this._attachToForms(),this._fetchChallenge()}async _fetchChallenge(){try{await this.powManager.fetchChallenge(this.options.siteKey)}catch(t){console.warn("PoW challenge fetch failed:",t)}}_attachListeners(){let t={mousemove:e=>this.behavioral.recordMouseMove(e),mousedown:e=>this.behavioral.recordMouseDown(e),mouseup:e=>this.behavioral.recordMouseUp(e),scroll:e=>this.behavioral.recordScroll(e),keydown:e=>this.behavioral.recordKeyEvent(e),keyup:e=>this.behavioral.recordKeyEvent(e),touchmove:e=>this.behavioral.recordTouch(e),touchstart:e=>this.behavioral.recordTouch(e),pointermove:e=>this.behavioral.recordPointer(e),pointerdown:e=>this.behavioral.recordPointer(e),pointerup:e=>this.behavioral.recordPointer(e),focus:e=>this.behavioral.recordFocus(e),blur:e=>this.behavioral.recordFocus(e)};for(let[e,n]of Object.entries(t)){let o=e==="focus"||e==="blur"?{passive:!0,capture:!0}:{passive:!0};document.addEventListener(e,n,o),this.listeners.push({event:e,handler:n,opts:o})}this.sensor.attach()}_attachToForms(){document.addEventListener("submit",async t=>{let e=t.target;if(e.dataset.webdecoyIgnore)return;let n=e.querySelector('input[name="webdecoy_token"]');if(n||(n=document.createElement("input"),n.type="hidden",n.name="webdecoy_token",e.appendChild(n)),!this.lastScore||Date.now()-this.lastScore.timestamp>6e4){t.preventDefault();try{let o=await this.execute(e.dataset.webdecoyAction||"form_submit");n.value=o.token||"",o.success?e.submit():document.dispatchEvent(new CustomEvent("webdecoy:blocked",{detail:{score:o.score,form:e}}))}catch(o){console.error("WebDecoy captcha error:",o),e.submit()}}else n.value=this.lastScore.token||""})}async execute(t=""){var S;let e=Date.now()-this.startTime;e<this.options.minCollectionTime&&await new Promise(m=>setTimeout(m,this.options.minCollectionTime-e));let n=this.behavioral.analyze(),o=this.environmental.collect(),i=this.temporal.collect(Date.now()),[r,s]=await Promise.all([this.environmental.measureRAFConsistency(),this.environmental.collectAsync()]),a=P().analyze(),l=this.sensor.analyze(),u={behavioral:n,environmental:{...o,rafConsistency:r,...s,sensor:l},temporal:i,formAnalysis:a,meta:{sessionId:this.id,siteKey:this.options.siteKey,action:t,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),f=await M(h),g=await this.powManager.solveWithSignalsHash(this.options.siteKey,f),w={duration:g.duration,iterations:g.iterations,difficulty:g.difficulty},_=await this._score(u,t,g,h,f,w);return this.lastScore={..._,timestamp:Date.now()},_}async _score(t,e,n,o,i,r){let s=this.options.serverUrl||x();if(!s)return this._clientSideScore(t);try{return await(await fetch(s+L()+"/score",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({siteKey:this.options.siteKey,signals:t,signalsJson:o||null,action:e,powSolution:n?{challengeId:n.challengeId,nonce:n.nonce,hash:n.hash,signalsHash:i||null}:null,powTiming:r||null})})).json()}catch{return console.warn("WebDecoy server unavailable, using client-side scoring"),this._clientSideScore(t)}}_clientSideScore(t){let e=0,n=t.behavioral,o=t.environmental,i=t.temporal,r=t.meta,s=(n.touchEvents||0)>=3,a=(n.keyEvents||0)>0&&n.totalPoints===0;n.totalPoints<5&&n.trajectoryLength<10&&!s&&!a?e+=.35:n.totalPoints<10&&!s&&!a&&n.trajectoryLength<30&&(e+=.15),n.microTremorScore<.2&&(e+=.12),n.velocityVariance<.03&&(e+=.1),n.totalPoints<10&&r.sessionDuration>5e3&&(e+=.08),n.scrollEvents===0&&n.keyEvents===0&&r.sessionDuration>1e4&&(e+=.06),n.eventDeltaVariance<3&&(e+=.08),n.straightLineRatio>.8&&(e+=.08),o.webdriver&&(e+=.25),o.automationFlags&&o.automationFlags.plugins===0&&(e+=.06),o.headlessIndicators&&!o.headlessIndicators.hasOuterDimensions&&(e+=.12),o.webglInfo&&o.webglInfo.suspiciousRenderer&&(e+=.1),i.pow&&i.pow.duration<30&&(e+=.1),r.sessionDuration<500&&(e+=.12),r.sessionDuration<1e3&&n.totalPoints<5&&(e+=.15);let l=e<this.options.scoreThreshold;return{success:l,score:Math.min(1,e),action:r.action,token:l?btoa(JSON.stringify({timestamp:Date.now(),score:e,action:r.action,id:this.id})):null}}getScore(){return this.lastScore}destroy(){for(let{event:t,handler:e,opts:n}of this.listeners)document.removeEventListener(t,e,n);this.listeners=[],this.powManager&&this.powManager.reset()}};var W={widgets:new Map,get serverUrl(){return x()},set serverUrl(c){F(c)},configure(c){c.serverUrl&&F(c.serverUrl),c.basePath&&B(c.basePath)},render(c,t){let e=new D(c,t);return this.widgets.set(e.id,e),e.id},getResponse(c){let t=this.widgets.get(c);return t&&t instanceof D?t.getToken():null},reset(c){let t=this.widgets.get(c);t instanceof D&&t.reset()},invisible(c){let t=new A(c);return this.widgets.set(t.id,t),t},async execute(c,t={}){let e=new A({siteKey:c,serverUrl:x(),minCollectionTime:t.minTime||1e3,autoScore:!1,powDifficulty:t.powDifficulty||3}),n=await e.execute(t.action||"");return e.destroy(),n},getSignals(){return{environmental:new b().collect()}},autoInit(){document.querySelectorAll("[data-webdecoy]").forEach(c=>{let t=c.dataset.sitekey||c.dataset.webdecoy,e=c.dataset.theme||"light",n=c.dataset.endpoint,o=c.dataset.callback,i=o?window[o]:void 0;n&&F(n),this.render(c,{siteKey:t,theme:e,callback:i!=null?i:null})})}};var ce=24,le=8,ue=750,he=1500;function y(c){return typeof c=="number"&&Number.isFinite(c)?c:0}function q(c){let t=c.mousePositions;return!t||t.length<2?0:Math.max(0,Math.round(t[t.length-1].t-t[0].t))}function X(c){let t=c.mousePositions.length>=ce&&q(c)>=ue,e=c.touchEvents.length>=le;return t||e}function de(c){if(!X(c))return null;let t=c.analyze(),e=c.clickData;return{samples:y(t.totalPoints),duration_ms:q(c),tremor:y(t.microTremorScore),straight_ratio:y(t.straightLineRatio),velocity_var:y(t.velocityVariance),delta_var:y(t.eventDeltaVariance),dir_changes:y(t.directionChanges),micro_moves:y(t.microMovements),hold_ms:y(e==null?void 0:e.holdDuration),touch_points:y(t.touchTotalPoints),touch_force_var:y(t.touchForceVariance),pointer_nonmouse:t.pointerHasNonMouseType===!0,scrolls:y(t.scrollEvents),keys:y(t.keyEvents)}}function Y(c){if(typeof document=="undefined")return()=>{};let t=new E,e=null,n=!1,o={mousemove:s=>t.recordMouseMove(s),mousedown:s=>t.recordMouseDown(s),mouseup:s=>t.recordMouseUp(s),scroll:s=>t.recordScroll(s),keydown:s=>t.recordKeyEvent(s),touchstart:s=>t.recordTouch(s),touchmove:s=>t.recordTouch(s),pointerdown:s=>t.recordPointer(s)},i=()=>{if(!n){n=!0,e&&clearTimeout(e);for(let[s,a]of Object.entries(o))document.removeEventListener(s,a)}},r=()=>{n||e||X(t)&&(e=setTimeout(()=>{e=null;let s=de(t);i(),s&&c(s)},he))};for(let[s,a]of Object.entries(o)){let l=u=>{a(u),r()};o[s]=l,document.addEventListener(s,l,{passive:!0})}return i}var J="wd_clearance",me="wdfp1",ge="https://ingest.webdecoy.com";async function Z(c){let t=c.canvasHash,e=t&&t.supported?String(t.hash):"na",n=c.webglInfo,o=n&&n.supported?String(n.renderer)+"~"+String(n.vendor):"na",i=`${screen.width}x${screen.height}x${screen.colorDepth}`,r="na";try{r=Intl.DateTimeFormat().resolvedOptions().timeZone||"na"}catch{}let s=navigator.platform||"na",a=navigator.language||"na";return M([me,e,o,i,r,s,a].join("|"))}async function Q(c,t,e,n,o){try{let r=await(await fetch(c.replace(/\/$/,"")+"/api/v1/clearance",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({aid:t,fp:e,scope:n,ua:navigator.userAgent,webdriver:navigator.webdriver===!0,headless:/HeadlessChrome/.test(navigator.userAgent),...o?{behavior:o}:{}})})).json();if(r.granted&&r.token)return{token:r.token,expiresIn:r.expires_in||1800}}catch{}return null}function pe(c){for(let t of document.cookie.split(";")){let e=t.indexOf("=");if(!(e<0)&&t.slice(0,e).trim()===c)return t.slice(e+1).trim()||null}return null}function ee(c,t){document.cookie=`${J}=${c}; path=/; secure; samesite=lax; max-age=${t}`}function ve(c){let t=window.requestIdleCallback;typeof t=="function"?t(c):setTimeout(c,1200)}var G=!1;function fe(c,t,e){G||(G=!0,Y(n=>{(async()=>{try{let o=new b,i=await Z({canvasHash:o._getCanvasHash(),webglInfo:o._getWebGLInfo()}),r=await Q(c,t,i,e,n);r&&ee(r.token,r.expiresIn)}catch{}})()}))}function U(c){if(!c.siteKey||typeof document=="undefined")return;let t=c.ingestUrl||ge,e=c.scope||"",n=async()=>{if(pe(J))return;let o=new b,i=await Z({canvasHash:o._getCanvasHash(),webglInfo:o._getWebGLInfo()}),r=await Q(t,c.siteKey,i,e);if(r){ee(r.token,r.expiresIn);let s=Math.max(6e4,(r.expiresIn-120)*1e3);setTimeout(()=>U(c),s)}};ve(()=>{n()}),c.behavior!==!1&&fe(t,c.siteKey,e)}var k=document.currentScript;window.WebDecoyCaptcha=W;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>W.autoInit()):W.autoInit();var te=k==null?void 0:k.getAttribute("data-site-key");te&&U({siteKey:te,ingestUrl:(k==null?void 0:k.getAttribute("data-ingest"))||void 0,scope:(k==null?void 0:k.getAttribute("data-scope"))||void 0});return ae(ye);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/client",
3
- "version": "0.4.1",
3
+ "version": "0.6.0",
4
4
  "description": "Web Decoy browser widget - signal collection, proof-of-work, and captcha UI",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -34,14 +34,14 @@
34
34
  ],
35
35
  "author": "Web Decoy",
36
36
  "license": "MIT",
37
- "homepage": "https://github.com/WebDecoy/node-sdk#readme",
37
+ "homepage": "https://github.com/WebDecoy/node#readme",
38
38
  "repository": {
39
39
  "type": "git",
40
- "url": "git+https://github.com/WebDecoy/node-sdk.git",
40
+ "url": "git+https://github.com/WebDecoy/node.git",
41
41
  "directory": "packages/client"
42
42
  },
43
43
  "bugs": {
44
- "url": "https://github.com/WebDecoy/node-sdk/issues"
44
+ "url": "https://github.com/WebDecoy/node/issues"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/jest": "^29.5.11",