@aientrophy/sdk 0.3.0 â 0.3.1
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/dist/npm/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __defProp=Object.defineProperty,__publicField=(e,t,i)=>((e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const CONFIG_RSA_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class CryptoUtils{static async init(){if(!this.sessionKey)try{await this.initECDH()}catch(e){await this.initRSA()}}static async initECDH(){const e=await window.crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=await window.crypto.subtle.exportKey("raw",e.publicKey);this.ecdhPublicKeyBase64=this.arrayBufferToBase64(t);const i=(window.__securitySDKEndpoint||"").replace(/\/events$/,""),s=await fetch(`${i}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!s.ok)throw new Error("Key exchange failed");const{serverPublicKey:n,salt:a}=await s.json(),r=this.base64ToArrayBuffer(n),o=await window.crypto.subtle.importKey("raw",r,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},e.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(a);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const e=await this.importRSAPublicKey(CONFIG_RSA_PUBLIC_KEY),t=await window.crypto.subtle.exportKey("raw",this.sessionKey),i=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);this.encryptedSessionKey=this.arrayBufferToBase64(i),this.protocolVersion=1}static async encrypt(e){this.sessionKey||await this.init();const t=JSON.stringify(e),i=(new TextEncoder).encode(t),s=window.crypto.getRandomValues(new Uint8Array(12)),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.sessionKey,i),a=new Uint8Array(n),r=a.slice(0,a.length-16),o=a.slice(a.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}static async decrypt(e){if(!this.sessionKey)throw new Error("Session key not initialized");const t=this.base64ToArrayBuffer(e.d),i=this.base64ToArrayBuffer(e.iv),s=this.base64ToArrayBuffer(e.tag),n=new Uint8Array(t.byteLength+s.byteLength);n.set(new Uint8Array(t),0),n.set(new Uint8Array(s),t.byteLength);const a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.sessionKey,n),r=(new TextDecoder).decode(a);return JSON.parse(r)}static setEndpoint(e){window.__securitySDKEndpoint=e}static async importRSAPublicKey(e){const t=window.atob(e),i=this.str2ab(t);return await window.crypto.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(e){const t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let s=0,n=e.length;s<n;s++)i[s]=e.charCodeAt(s);return t}static arrayBufferToBase64(e){let t="";const i=new Uint8Array(e),s=i.byteLength;for(let n=0;n<s;n++)t+=String.fromCharCode(i[n]);return window.btoa(t)}static base64ToArrayBuffer(e){const t=window.atob(e),i=t.length,s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=t.charCodeAt(n);return s.buffer}}__publicField(CryptoUtils,"sessionKey",null),__publicField(CryptoUtils,"ecdhPublicKeyBase64",null),__publicField(CryptoUtils,"encryptedSessionKey",null),__publicField(CryptoUtils,"protocolVersion",2);const THREAT_EVENTS=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe"]);class CallbackManager{constructor(){__publicField(this,"handlers",new Map),__publicField(this,"configCallbacks",{})}setConfigCallbacks(e){this.configCallbacks=e}on(e,t){this.addHandler(e,t,!1)}once(e,t){this.addHandler(e,t,!0)}off(e,t){const i=this.handlers.get(e);if(!i)return;const s=i.filter(e=>e.handler!==t);0===s.length?this.handlers.delete(e):this.handlers.set(e,s)}emit(e,...t){this.callHandlers(e,t);const i=e.indexOf(":");if(-1!==i){const s=e.substring(0,i);this.callHandlers(s,t)}this.callConfigCallback(e,t)}emitChallenge(e){return new Promise(t=>{let i=!1;const s=e=>{i||(i=!0,t(e))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[e,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[e,s]),setTimeout(()=>{i||(i=!0,t(!1))},5e3)):t(!1)})}addHandler(e,t,i){this.handlers.has(e)||this.handlers.set(e,[]),this.handlers.get(e).push({handler:t,once:i})}callHandlers(e,t){const i=this.handlers.get(e);if(!i||0===i.length)return;const s=[];for(let n=0;n<i.length;n++)this.safeCall(i[n].handler,t),i[n].once&&s.push(n);for(let n=s.length-1;n>=0;n--)i.splice(s[n],1);0===i.length&&this.handlers.delete(e)}callConfigCallback(e,t){if(e.startsWith("threat:")||"threat"===e)return void(e.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,t));const i={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[e];i&&this.configCallbacks[i]&&this.safeCall(this.configCallbacks[i],t)}safeCall(e,t){try{e(...t)}catch(i){}}}class Transmitter{constructor(){__publicField(this,"endpoint",""),__publicField(this,"clientKey",""),__publicField(this,"encryptionRequired",!1),__publicField(this,"currentNonce",""),__publicField(this,"buffer",[]),__publicField(this,"batchSize",20),__publicField(this,"flushInterval",5e3),__publicField(this,"intervalId"),__publicField(this,"responseHandler",null),__publicField(this,"callbackManager",null),__publicField(this,"flushing",!1),__publicField(this,"pendingFlush",!1),__publicField(this,"backoffMs",0),__publicField(this,"maxBackoffMs",6e4),__publicField(this,"_lastBackoffStart",0),this.startFlushInterval()}setConfig(e){var t,i;this.endpoint=e.endpoint,this.clientKey=e.clientKey,this.encryptionRequired=(null==(t=e.serverConfig)?void 0:t.encryptionRequired)??!1,this.currentNonce=(null==(i=e.serverConfig)?void 0:i.initialNonce)??"",CryptoUtils.setEndpoint(e.endpoint)}setResponseHandler(e){this.responseHandler=e}setCallbackManager(e){this.callbackManager=e}send(e,t={}){const i=Date.now();if(this.buffer.push({type:e,data:t,timestamp:i}),this.callbackManager)if(THREAT_EVENTS.has(e)){const s={type:e,data:t,timestamp:i};this.callbackManager.emit(`threat:${e}`,s)}else this.callbackManager.emit(`data:${e}`,{type:e,data:t,timestamp:i});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.backoffMs>0){const e=Date.now();if(this._lastBackoffStart||(this._lastBackoffStart=e),e-this._lastBackoffStart<this.backoffMs)return;this._lastBackoffStart=0}if(this.flushing)return void(this.pendingFlush=!0);this.flushing=!0;const e=this.buffer;this.buffer=[];try{let s;if(this.encryptionRequired){const t=await CryptoUtils.encrypt(e);s=JSON.stringify(t)}else s=JSON.stringify(e);const n={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(n["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const i=await fetch(this.endpoint,{method:"POST",body:s,headers:n,keepalive:!0});if(429===i.status)return this.buffer=e.concat(this.buffer).slice(0,500),this.backoffMs=0===this.backoffMs?5e3:Math.min(2*this.backoffMs,this.maxBackoffMs),void(this._lastBackoffStart=Date.now());if(this.backoffMs=0,i.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),i.ok)try{const e=await i.json();let t=e;this.encryptionRequired&&(t=await CryptoUtils.decrypt(e)),(null==t?void 0:t.nonce)&&(this.currentNonce=t.nonce),this.responseHandler&&this.responseHandler(t)}catch(t){}}catch(i){this.callbackManager&&this.callbackManager.emit("error",{code:"NETWORK_ERROR",message:"Failed to send security events"})}}catch(t){this.callbackManager&&this.callbackManager.emit("error",{code:"PAYLOAD_ERROR",message:"Failed to prepare security payload"})}finally{this.flushing=!1,this.pendingFlush&&(this.pendingFlush=!1,this.flush())}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.flush()}startFlushInterval(){this.intervalId=setInterval(()=>{this.flush()},this.flushInterval)}}class BehaviorCollector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"isCollecting",!1),this.transmitter=e}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}class RapidClickDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"clickHistory",[]),__publicField(this,"THRESHOLD_COUNT",3),__publicField(this,"THRESHOLD_TIME",500),this.transmitter=e,this.init()}init(){document.addEventListener("click",e=>this.handleClick(e),!0)}handleClick(e){const t=Date.now();if(this.clickHistory.push(t),this.clickHistory=this.clickHistory.filter(e=>t-e<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const i=e.target,s={tagName:i.tagName,id:i.id,className:i.className,x:e.clientX,y:e.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:s,timestamp:t}),this.clickHistory=[]}}}class Honeypot{constructor(e){__publicField(this,"transmitter"),__publicField(this,"element",null),this.transmitter=e}start(){this.element=document.createElement("input"),this.element.type="text";const e=["website","email_confirm","url","homepage","fax_number","address_line_2"],t=e[Math.floor(Math.random()*e.length)],i=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${t}-${i}`,this.element.autocomplete="off",Object.assign(this.element.style,{position:"absolute",opacity:"0",top:"0",left:"-9999px",height:"1px",width:"1px",zIndex:"-1",border:"none"}),this.element.tabIndex=-1,this.element.setAttribute("aria-hidden","true"),this.element.setAttribute("role","presentation");const s=e=>{var t;this.transmitter.send("honeypot_triggered",{eventType:e.type,value:null==(t=this.element)?void 0:t.value,timestamp:Date.now()})};this.element.addEventListener("input",s),this.element.addEventListener("focus",s),this.element.addEventListener("click",s),document.body.appendChild(this.element)}stop(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class MouseTracker{constructor(e,t){__publicField(this,"transmitter"),__publicField(this,"wasmService"),__publicField(this,"buffer",[]),__publicField(this,"BUFFER_SIZE",50),__publicField(this,"SAMPLE_INTERVAL",100),__publicField(this,"SEND_COOLDOWN",5e3),__publicField(this,"lastSampleTime",0),__publicField(this,"lastSendTime",0),__publicField(this,"handleMouseMove",e=>{const t=Date.now();t-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=t,this.buffer.push({x:e.clientX,y:e.clientY,time:t}),this.buffer.length>this.BUFFER_SIZE&&this.buffer.shift(),this.buffer.length>=this.BUFFER_SIZE&&t-this.lastSendTime>=this.SEND_COOLDOWN&&(this.analyze(),this.lastSendTime=t))}),this.transmitter=e,this.wasmService=t}start(){"undefined"!=typeof document&&document.addEventListener("mousemove",this.handleMouseMove)}stop(){"undefined"!=typeof document&&document.removeEventListener("mousemove",this.handleMouseMove)}analyze(){if(this.buffer.length<20)return;const e=this.wasmService.calculateEntropy(this.buffer),t=this.calculateSpeedVariance(),i=this.buffer.map(e=>({x:e.x,y:e.y,t:e.time}));this.transmitter.send("behavior_metrics",{entropy:e,speedVariance:t,sampleSize:this.buffer.length,timestamp:Date.now(),rawTrajectory:i})}calculateSpeedVariance(){const e=[];for(let i=1;i<this.buffer.length;i++){const t=this.buffer[i-1],s=this.buffer[i],n=Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2)),a=s.time-t.time;a>0&&e.push(n/a)}if(e.length<2)return 1;const t=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length}}class InputTracker{constructor(e){__publicField(this,"lastInteractionTime",0),__publicField(this,"lastInteractionType","none"),__publicField(this,"transmitter"),__publicField(this,"isMobile",!1),__publicField(this,"keyPressTimes",new Map),__publicField(this,"lastKeyUpTime",0),__publicField(this,"flightTimes",[]),__publicField(this,"dwellTimes",[]),__publicField(this,"suspiciousFocusCount",0),__publicField(this,"suspiciousFocusResetTimer",null),__publicField(this,"rawKeystrokes",[]),this.transmitter=e,this.isMobile=this.detectMobile()}start(){this.initListeners()}detectMobile(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)}initListeners(){if("undefined"==typeof document)return;["mousedown","keydown","touchstart","touchend"].forEach(e=>{document.addEventListener(e,e=>{this.lastInteractionTime=Date.now(),this.lastInteractionType=e.type},{passive:!0,capture:!0})}),document.addEventListener("focus",e=>{const t=e.target;"INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName||(this.checkFocusIntegrity(),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",e=>{const t=e.target;if("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName)return;const i=Date.now();if(this.keyPressTimes.set(e.code,i),this.rawKeystrokes.push({code:e.code,t:i,type:"down"}),this.lastKeyUpTime>0){const e=i-this.lastKeyUpTime;e<2e3&&this.flightTimes.push(e)}},{passive:!0,capture:!0}),document.addEventListener("keyup",e=>{const t=e.target;if("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName)return;const i=Date.now();this.lastKeyUpTime=i,this.rawKeystrokes.push({code:e.code,t:i,type:"up"});const s=this.keyPressTimes.get(e.code);if(s){const t=i-s;this.dwellTimes.push(t),this.keyPressTimes.delete(e.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(t)},{passive:!0,capture:!0}),document.addEventListener("blur",e=>{const t=e.target;("INPUT"===t.tagName||"TEXTAREA"===t.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(t)},{capture:!0})}checkFocusIntegrity(){const e=Date.now(),t=e-this.lastInteractionTime;performance.now()<5e3||(t>200?(this.suspiciousFocusCount++,clearTimeout(this.suspiciousFocusResetTimer),this.suspiciousFocusResetTimer=setTimeout(()=>{this.suspiciousFocusCount=0},3e3),this.transmitter.send("behavior_metrics",{type:"suspicious_focus",timeSinceInteraction:t,lastInteraction:this.lastInteractionType,consecutiveCount:this.suspiciousFocusCount,timestamp:e})):this.suspiciousFocusCount=0)}reportKeystrokeDynamics(e){const t=this.average(this.flightTimes),i=this.variance(this.flightTimes,t),s=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:e.id||e.tagName,flight:{avg:t,variance:i,samples:this.flightTimes.length},dwell:{avg:s,variance:n},isMobile:this.isMobile,timestamp:Date.now(),rawKeystrokes:[...this.rawKeystrokes]}),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[]}average(e){return 0===e.length?0:e.reduce((e,t)=>e+t,0)/e.length}variance(e,t){return 0===e.length?0:e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length}}class WasmService{constructor(){__publicField(this,"wasmModule",null),__publicField(this,"memory",null),__publicField(this,"instance",null)}async load(e){try{const t=await fetch(`${e}/sdk/core.wasm`);if(!t.ok)throw new Error(`HTTP ${t.status}`);const i={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const e=await WebAssembly.instantiateStreaming(t,i);this.instance=e.instance}else{const e=await t.arrayBuffer(),s=await WebAssembly.instantiate(e,i);this.instance=s.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(t){}}isLoaded(){return!!this.instance}calculateEntropy(e){if(!this.instance||!this.wasmModule)return 0;const t=2*e.length,i=8*t;try{const s=this.wasmModule.__new(i,0),n=new Float64Array(this.memory.buffer,s,t);for(let t=0;t<e.length;t++)n[2*t]=e[t].x,n[2*t+1]=e[t].y;return this.wasmModule.calculateEntropy(s,t)}catch(s){return 0}}simpleHash(e){if(!this.instance||!this.wasmModule)return 0;try{const t=(new TextEncoder).encode(e),i=t.length,s=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,s,i).set(t),this.wasmModule.simpleHash(s,i)}catch(t){return 0}}}class CanvasFingerprinter{constructor(e,t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof document||setTimeout(async()=>{const e=await this.generateFingerprint(),t=this.collectWebGLFingerprint(),i=this.collectAudioFingerprint();this.transmitter.send("fingerprint_collected",{hash:e,webgl:t,audio:i}),this.hasRun=!0},500)}async generateFingerprint(){try{const e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return"unknown";t.textBaseline="top",t.font='14px "Arial"',t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("aientrophy Security đ",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("aientrophy Security đ",4,17),t.globalCompositeOperation="multiply",t.fillStyle="rgb(255,0,255)",t.beginPath(),t.arc(50,50,50,0,2*Math.PI,!0),t.closePath(),t.fill(),t.fillStyle="rgb(0,255,255)",t.beginPath(),t.arc(100,50,50,0,2*Math.PI,!0),t.closePath(),t.fill(),t.fillStyle="rgb(255,255,0)",t.beginPath(),t.arc(75,100,50,0,2*Math.PI,!0),t.closePath(),t.fill();const i=e.toDataURL();return await this.sha256(i)}catch(e){return"error"}}async sha256(e){const t=(new TextEncoder).encode(e),i=await window.crypto.subtle.digest("SHA-256",t),s=new Uint8Array(i);return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}collectWebGLFingerprint(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{available:!1};const i=t,s={available:!0},n=i.getExtension("WEBGL_debug_renderer_info");return n&&(s.renderer=i.getParameter(n.UNMASKED_RENDERER_WEBGL),s.vendor=i.getParameter(n.UNMASKED_VENDOR_WEBGL)),s.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE),s.maxViewportDims=Array.from(i.getParameter(i.MAX_VIEWPORT_DIMS)),s.maxRenderbufferSize=i.getParameter(i.MAX_RENDERBUFFER_SIZE),s.maxVertexAttribs=i.getParameter(i.MAX_VERTEX_ATTRIBS),s.extensions=(i.getSupportedExtensions()||[]).length,s}catch(e){return{available:!1,error:!0}}}collectAudioFingerprint(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return{available:!1};const t=new e,i={available:!0,sampleRate:t.sampleRate,state:t.state,maxChannels:t.destination.maxChannelCount};return t.close(),i}catch(e){return{available:!1}}}}class ChallengeHandler{constructor(e){__publicField(this,"originalFetch"),__publicField(this,"endpoint"),__publicField(this,"callbackManager",null),__publicField(this,"challengeInProgress",null),this.endpoint=e,this.originalFetch=window.fetch.bind(window)}setCallbackManager(e){this.callbackManager=e}start(){window.fetch=async(e,t)=>{var i;const s=await this.originalFetch(e,t);if(403===s.status){const a=s.clone();try{const n=await a.json();if("challenge"===n.action&&"captcha"===(null==(i=n.metadata)?void 0:i.type)){const i={action:"challenge",score:n.score,metadata:n.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(i))return this.originalFetch(e,t)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(e,t):s}"block"===n.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:n.score,metadata:n.metadata})}catch(n){}}return s}}async showCaptchaModal(){return new Promise(e=>{const t=document.createElement("div");t.id="sec-sdk-challenge-host",t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.width="100vw",t.style.height="100vh",t.style.zIndex="999999",t.style.backgroundColor="rgba(0,0,0,0.5)",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center";const i=t.attachShadow({mode:"open"}),s=document.createElement("div");s.style.background="white",s.style.padding="20px",s.style.borderRadius="8px",s.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)",s.style.textAlign="center",s.style.fontFamily="system-ui, sans-serif";const n=document.createElement("h3");n.textContent="Security Check",n.style.margin="0 0 16px 0";const a=document.createElement("p");a.textContent="Unusual activity detected. Please verify you are human.",a.style.marginBottom="16px",a.style.fontSize="14px",a.style.color="#666";const r=document.createElement("div");r.innerHTML="Loading...",r.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",s.appendChild(n),s.appendChild(a),s.appendChild(r),s.appendChild(o),s.appendChild(c),s.appendChild(l),i.appendChild(s),document.body.appendChild(t);let h="";const u=async()=>{try{const e=await this.originalFetch(`${this.endpoint}/challenge`),t=await e.json();h=t.id,r.innerHTML=t.svg}catch(e){r.textContent="Error loading CAPTCHA"}},d=async()=>{l.style.display="none",c.textContent="Verifying...";try{const i=o.value,s=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:i})});(await s.json()).success?(document.body.removeChild(t),e(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",u())}catch(i){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=d,o.onkeydown=e=>{"Enter"===e.key&&d()},u()})}}class InvisibleInteraction{constructor(e){__publicField(this,"transmitter"),__publicField(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),__publicField(this,"handleEvent",e=>{const t=e.target;if(!(t&&t instanceof HTMLElement))return;if(t===document.body||t===document.documentElement)return;const i=this.checkVisibility(t,e);if(i){const s=t.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:e.type,target:t.tagName,id:t.id,reason:i,timestamp:Date.now(),isTrusted:e.isTrusted,coordinates:{x:e instanceof MouseEvent?e.clientX:0,y:e instanceof MouseEvent?e.clientY:0},viewport:{width:window.innerWidth,height:window.innerHeight},scroll:{x:window.scrollX,y:window.scrollY},docDim:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},elementRect:{top:s.top,left:s.left,width:s.width,height:s.height}})}}),this.transmitter=e}start(){this.eventsToWatch.forEach(e=>{document.addEventListener(e,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(e=>{document.removeEventListener(e,this.handleEvent,{capture:!0})})}checkVisibility(e,t){var i,s;const n=window.getComputedStyle(e);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=e.getBoundingClientRect();if(a.width<=0||a.height<=0)return"zero_size";const r=a.right<0||a.left>window.innerWidth,o=a.bottom<0||a.top>window.innerHeight;if(r||o)return"off_screen";if(t instanceof MouseEvent||t instanceof TouchEvent){let n,a;if(t instanceof MouseEvent?(n=t.clientX,a=t.clientY):(n=(null==(i=t.touches[0])?void 0:i.clientX)||0,a=(null==(s=t.touches[0])?void 0:s.clientY)||0),n>=0&&n<=window.innerWidth&&a>=0&&a<=window.innerHeight){const i=document.elementFromPoint(n,a);if(i&&i!==e&&!e.contains(i)&&!i.contains(e)&&0===n&&0===a&&t.isTrusted)return null}}return null}}class AutomationDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(setTimeout(()=>this.detect(),1500),this.hasRun=!0)}detect(){var e,t;const i={};let s=0;!0===navigator.webdriver&&(i.webdriver=!0,s+=40);try{this.detectCDP()&&(i.cdp=!0,s+=50)}catch(c){}const n=this.detectAutomationGlobals();n.length>0&&(i.automationGlobals=n,s+=30);const a=this.checkWebGL();a.suspicious&&(i.webgl=a,s+=25);const r=this.checkInconsistencies();r.length>0&&(i.inconsistencies=r,s+=15);const o=this.checkHeadless();o.score>0&&(i.headless=o.flags,s+=o.score),s>0&&this.transmitter.send("automation_detected",{signals:i,score:s,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(e=navigator.plugins)?void 0:e.length)??0,languages:(null==(t=navigator.languages)?void 0:t.length)??0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,maxTouchPoints:navigator.maxTouchPoints,webglRenderer:a.renderer,webglVendor:a.vendor,timestamp:Date.now()})}detectCDP(){const e=console.debug;return console.debug=e,!1}detectAutomationGlobals(){const e=[],t=[["selenium",()=>!!window._selenium],["selenium_unwrapped",()=>!!document.__selenium_unwrapped],["driver_evaluate",()=>!!document.__driver_evaluate],["webdriver_evaluate",()=>!!document.__webdriver_evaluate],["driver_unwrapped",()=>!!document.__driver_unwrapped],["fxdriver",()=>!!document.__fxdriver_evaluate],["playwright",()=>!!window.__playwright],["playwright_binding",()=>!!window.__playwright__binding__],["pwInitScripts",()=>!!window.__pwInitScripts],["puppeteer",()=>!!window.__puppeteer_evaluation_script__],["phantom",()=>!!window.callPhantom||!!window._phantom],["nightmare",()=>!!window.__nightmare],["cdc",()=>Object.keys(document).some(e=>e.startsWith("cdc_")||e.startsWith("$cdc_"))]];for(const[s,n]of t)try{n()&&e.push(s)}catch(i){}return e}checkWebGL(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{suspicious:!1,renderer:"unavailable",vendor:"unavailable"};const i=t.getExtension("WEBGL_debug_renderer_info");if(!i)return{suspicious:!1,renderer:"no_debug_info",vendor:"no_debug_info"};const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",n=t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(s)||/Mesa OffScreen/i.test(s)||/llvmpipe/i.test(s),renderer:s,vendor:n}}catch(e){return{suspicious:!1,renderer:"error",vendor:"error"}}}checkInconsistencies(){const e=[];try{const t=navigator.userAgent,i=navigator.platform;/Windows/.test(t)&&/Mac/.test(i)&&e.push("ua_platform_mismatch_win_mac"),/Macintosh/.test(t)&&/Win/.test(i)&&e.push("ua_platform_mismatch_mac_win"),/Mobile|Android|iPhone/.test(t)&&0===navigator.maxTouchPoints&&e.push("mobile_ua_no_touch"),/Chrome/.test(t)&&navigator.plugins&&0===navigator.plugins.length&&e.push("chrome_no_plugins"),navigator.languages&&0!==navigator.languages.length||e.push("no_languages")}catch(t){}return e}checkHeadless(){const e=[];let t=0;try{if(/HeadlessChrome/.test(navigator.userAgent)&&(e.push("headless_ua"),t+=40),/Chrome/.test(navigator.userAgent)&&!window.chrome&&(e.push("chrome_ua_no_chrome_obj"),t+=15),window.screen&&800===window.screen.width&&600===window.screen.height&&(e.push("default_screen_size"),t+=10),"Notification"in window){"denied"===window.Notification.permission&&navigator.userAgent.includes("Chrome")&&(e.push("notification_denied_default"),t+=5)}const i=navigator.connection;i&&0===i.rtt&&(e.push("zero_rtt"),t+=10)}catch(i){}return{score:t,flags:e}}}class SessionAnalyzer{constructor(e){__publicField(this,"transmitter"),__publicField(this,"sessionStart",0),__publicField(this,"pageTransitions",[]),__publicField(this,"interactionTimestamps",[]),__publicField(this,"lastPageUrl",""),__publicField(this,"formStartTimes",new Map),__publicField(this,"reportInterval",null),this.transmitter=e}start(){if("undefined"==typeof window)return;this.sessionStart=Date.now(),this.lastPageUrl=window.location.href;["mousedown","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>500&&this.interactionTimestamps.shift()},{passive:!0,capture:!0})}),this.observeNavigation(),this.observeForms(),this.reportInterval=setInterval(()=>this.report(),15e3)}observeNavigation(){const e=history.pushState,t=history.replaceState,i=this;history.pushState=function(t,s,n){e.call(this,t,s,n),i.onPageTransition()},history.replaceState=function(e,s,n){t.call(this,e,s,n),i.onPageTransition()},window.addEventListener("popstate",()=>this.onPageTransition())}onPageTransition(){const e=Date.now(),t=window.location.href;t!==this.lastPageUrl&&(this.pageTransitions.push(e),this.lastPageUrl=t)}observeForms(){document.addEventListener("focus",e=>{const t=e.target;if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName){const e=t.closest("form"),i=(null==e?void 0:e.id)||(null==e?void 0:e.action)||"anonymous_form";this.formStartTimes.has(i)||this.formStartTimes.set(i,Date.now())}},{capture:!0}),document.addEventListener("submit",e=>{const t=e.target,i=t.id||t.action||"anonymous_form",s=this.formStartTimes.get(i);if(s){const e=Date.now()-s;this.transmitter.send("session_metrics",{type:"form_completion",formId:i,duration:e,timestamp:Date.now()}),this.formStartTimes.delete(i)}},{capture:!0})}report(){const e=Date.now(),t=e-this.sessionStart;if(this.interactionTimestamps.length<10)return;const i=this.calculateIntervals(this.interactionTimestamps),s=this.analyzeTimingDistribution(i),n=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:t,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:s,pages:n,timestamp:e})}calculateIntervals(e){const t=[];for(let i=1;i<e.length;i++)t.push(e[i]-e[i-1]);return t}analyzeTimingDistribution(e){if(e.length<5)return{samples:e.length};const t=e.reduce((e,t)=>e+t,0)/e.length,i=e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length,s=Math.sqrt(i),n=t>0?s/t:0,a=this.shannonEntropy(e,50),r=this.autocorrelation(e);return{mean:Math.round(t),stdDev:Math.round(s),cv:parseFloat(n.toFixed(4)),entropy:parseFloat(a.toFixed(4)),autocorrelation:parseFloat(r.toFixed(4)),samples:e.length}}analyzePageTransitions(){if(this.pageTransitions.length<2)return{count:this.pageTransitions.length};const e=this.calculateIntervals(this.pageTransitions),t=e.reduce((e,t)=>e+t,0)/e.length,i=e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length,s=t>0?Math.sqrt(i)/t:0;return{count:this.pageTransitions.length,avgInterval:Math.round(t),cv:parseFloat(s.toFixed(4))}}shannonEntropy(e,t){const i=new Map;for(const a of e){const e=Math.floor(a/t);i.set(e,(i.get(e)||0)+1)}const s=e.length;let n=0;for(const a of i.values()){const e=a/s;e>0&&(n-=e*Math.log2(e))}return n}autocorrelation(e){if(e.length<3)return 0;const t=e.reduce((e,t)=>e+t,0)/e.length;let i=0,s=0;for(let n=0;n<e.length-1;n++)i+=(e[n]-t)*(e[n+1]-t);for(let n=0;n<e.length;n++)s+=Math.pow(e[n]-t,2);return 0===s?0:i/s}}class TabNavigationAnalyzer{constructor(e){__publicField(this,"transmitter"),__publicField(this,"tabTimestamps",[]),__publicField(this,"shiftTabCount",0),__publicField(this,"tabCount",0),__publicField(this,"isShiftDown",!1),__publicField(this,"BURST_THRESHOLD_MS",80),__publicField(this,"reportInterval",null),__publicField(this,"REPORT_INTERVAL_MS",1e4),__publicField(this,"MIN_TABS_TO_REPORT",5),__publicField(this,"TAB_TRIGGER_COUNT",20),__publicField(this,"onKeyDown",e=>{if("Shift"!==e.key){if("Tab"===e.key){const e=Date.now();this.isShiftDown?this.shiftTabCount++:(this.tabCount++,this.tabTimestamps.push(e),this.tabTimestamps.length>100&&this.tabTimestamps.shift()),this.tabCount+this.shiftTabCount>=this.TAB_TRIGGER_COUNT&&this.report()}}else this.isShiftDown=!0}),__publicField(this,"onKeyUp",e=>{"Shift"===e.key&&(this.isShiftDown=!1)}),this.transmitter=e}start(){"undefined"!=typeof document&&(document.addEventListener("keydown",this.onKeyDown,{passive:!0,capture:!0}),document.addEventListener("keyup",this.onKeyUp,{passive:!0,capture:!0}),this.reportInterval=setInterval(()=>this.report(),this.REPORT_INTERVAL_MS))}stop(){"undefined"!=typeof document&&(document.removeEventListener("keydown",this.onKeyDown,{capture:!0}),document.removeEventListener("keyup",this.onKeyUp,{capture:!0}),this.reportInterval&&(clearInterval(this.reportInterval),this.reportInterval=null),this.report())}report(){const e=this.tabCount+this.shiftTabCount;if(e<this.MIN_TABS_TO_REPORT)return;const t=this.calculateIntervals(this.tabTimestamps);if(t.length<3)return void this.resetBuffers();const i=this.analyzeIntervals(t),s=this.analyzeBursts(t),n=e>0?this.shiftTabCount/e:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(n.toFixed(4)),intervals:i,bursts:s,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(e){const t=[];for(let i=1;i<e.length;i++){const s=e[i]-e[i-1];s<5e3&&t.push(s)}return t}analyzeIntervals(e){if(0===e.length)return{avg:0,variance:0,cv:0,min:0,samples:0};const t=e.reduce((e,t)=>e+t,0)/e.length,i=e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length,s=Math.sqrt(i),n=t>0?s/t:0,a=Math.min(...e);return{avg:parseFloat(t.toFixed(2)),variance:parseFloat(i.toFixed(2)),cv:parseFloat(n.toFixed(4)),min:a,samples:e.length}}analyzeBursts(e){let t=0,i=0,s=0,n=0,a=0;for(const r of e)r<this.BURST_THRESHOLD_MS?(i++,n+=r,a++):(i>=3&&(t++,s+=i),i=0);return i>=3&&(t++,s+=i),{count:t,avgLength:t>0?parseFloat((s/t).toFixed(1)):0,avgInterval:a>0?parseFloat((n/a).toFixed(2)):0}}}class CloudEnvironmentDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{const e=this.analyzeGPU(),t=this.analyzeHardware(),i=this.analyzeScreen(),s=await this.analyzeMedia(),n=this.benchmarkCanvas();let a=0;"virtual_gpu"!==e.category&&"software_render"!==e.category&&"cloud_gpu"!==e.category||(a+=2),t.cores<=2&&a++,null!==t.memory&&t.memory<=2&&a++,24===t.colorDepth&&a++,1===t.pixelRatio&&a++,i.noTaskbar&&a++,i.isVMResolution&&a++,0===s.cameras&&0===s.microphones&&a++,s.hasBluetooth||s.hasUSB||a++,n.canvasRenderTime>50&&a++;const{classification:r,confidence:o}=this.classify(e,t,a);this.transmitter.send("cloud_environment",{classification:r,confidence:o,signals:{gpu:{renderer:e.renderer,vendor:e.vendor,category:e.category},hardware:t,screen:i,media:s,performance:n},vmIndicatorCount:a,timestamp:Date.now()})}catch(e){}}analyzeGPU(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{renderer:"unavailable",vendor:"unavailable",category:"unknown"};const i=t.getExtension("WEBGL_debug_renderer_info");if(!i)return{renderer:"no_debug_info",vendor:"no_debug_info",category:"unknown"};const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",n=t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{renderer:s,vendor:n,category:this.categorizeGPU(s,n)}}catch(e){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(e,t){const i=e.toLowerCase(),s=t.toLowerCase();return/swiftshader|llvmpipe|mesa offscreen|softpipe/.test(i)?"software_render":/svga3d|svga|vmware/.test(i)||/virtualbox/.test(i)||/parallels/.test(i)||/qxl|virtio|red hat|spice/.test(i)||/hyper-v|microsoft basic render/i.test(i)||/citrix/.test(i)?"virtual_gpu":/amazon|elastic|aws/.test(i)||/amazon|elastic|aws/.test(s)||/google cloud|gce/.test(i)||/google cloud|gce/.test(s)||/azure/.test(i)||/azure/.test(s)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const e=screen.width,t=screen.height,i=screen.availHeight,s=t===i&&t===window.innerHeight,n=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([i,s])=>e===i&&t===s&&!(1920===i&&1080===s));return{width:e,height:t,availHeight:i,noTaskbar:s,isVMResolution:n}}async analyzeMedia(){let e=-1,t=-1;try{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){const i=await navigator.mediaDevices.enumerateDevices();e=i.filter(e=>"videoinput"===e.kind).length,t=i.filter(e=>"audioinput"===e.kind).length}}catch(a){}const i=!!navigator.bluetooth,s=!!navigator.usb;let n=null;try{if(navigator.getBattery){const e=await navigator.getBattery();n=!(e.charging&&1===e.level&&0===e.chargingTime)}}catch(a){}return{cameras:e,microphones:t,hasBluetooth:i,hasUSB:s,hasBattery:n}}benchmarkCanvas(){try{const e=document.createElement("canvas");e.width=200,e.height=200;const t=e.getContext("2d");if(!t)return{canvasRenderTime:-1};const i=performance.now();for(let n=0;n<500;n++)t.fillStyle=`rgb(${n%256},${3*n%256},${7*n%256})`,t.fillRect(13*n%200,7*n%200,10,10);t.getImageData(0,0,1,1);const s=performance.now()-i;return{canvasRenderTime:Math.round(100*s)/100}}catch(e){return{canvasRenderTime:-1}}}classify(e,t,i){return"virtual_gpu"===e.category?24===t.colorDepth?{classification:"rdp_likely",confidence:.85}:{classification:"vm_detected",confidence:.95}:"cloud_gpu"===e.category?{classification:"cloud_likely",confidence:.9}:"software_render"===e.category?{classification:"vm_detected",confidence:.9}:i>=5?{classification:"vm_likely",confidence:.8}:i>=3?{classification:"vm_likely",confidence:.6}:{classification:"physical",confidence:1-.1*i}}}class CrossContextDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2500))}async detect(){var e,t;const i={};let s=0;const n={webdriver:!!navigator.webdriver,languages:(null==(e=navigator.languages)?void 0:e.join(","))||"",platform:navigator.platform||"",hardwareConcurrency:navigator.hardwareConcurrency||0,userAgent:navigator.userAgent||"",pluginsLength:(null==(t=navigator.plugins)?void 0:t.length)??0},a=this.checkIframe(n);a.score>0&&(i.iframe=a.mismatches,s+=a.score);try{const e=await this.checkWorker(n);e.score>0&&(i.worker=e.mismatches,s+=e.score)}catch(r){}s>0&&this.transmitter.send("cross_context_mismatch",{signals:i,score:s,timestamp:Date.now()})}checkIframe(e){var t,i;const s=[];let n=0;try{const a=document.createElement("iframe");a.style.display="none",a.sandbox="allow-same-origin",document.body.appendChild(a);const r=a.contentWindow;if(!r)return document.body.removeChild(a),{score:0,mismatches:[]};const o=r.navigator;o.webdriver!==navigator.webdriver&&(s.push("webdriver_mismatch"),n+=40),navigator.webdriver||!0!==o.webdriver||(s.push("webdriver_spoofed_in_main"),n+=30);((null==(t=o.languages)?void 0:t.join(","))||"")!==e.languages&&(s.push("languages_mismatch"),n+=15),o.platform!==e.platform&&(s.push("platform_mismatch"),n+=15);((null==(i=o.plugins)?void 0:i.length)??0)!==e.pluginsLength&&(s.push("plugins_mismatch"),n+=10),document.body.removeChild(a)}catch(a){}return{score:n,mismatches:s}}checkWorker(e){return new Promise(t=>{try{const i=new Blob(["\n self.onmessage = function() {\n var nav = self.navigator;\n self.postMessage({\n webdriver: !!nav.webdriver,\n languages: (nav.languages || []).join(','),\n platform: nav.platform || '',\n hardwareConcurrency: nav.hardwareConcurrency || 0,\n userAgent: nav.userAgent || ''\n });\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(i),n=new Worker(s),a=setTimeout(()=>{n.terminate(),URL.revokeObjectURL(s),t({score:0,mismatches:[]})},3e3);n.onmessage=i=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(s);const r=i.data,o=[];let c=0;r.webdriver!==e.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),r.languages!==e.languages&&(o.push("worker_languages_mismatch"),c+=15),r.platform!==e.platform&&(o.push("worker_platform_mismatch"),c+=15),r.hardwareConcurrency!==e.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),r.userAgent!==e.userAgent&&(o.push("worker_ua_mismatch"),c+=20),t({score:c,mismatches:o})},n.onerror=()=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(s),t({score:0,mismatches:[]})},n.postMessage("check")}catch(i){t({score:0,mismatches:[]})}})}}class HeadlessProbeDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){const e={};let t=0;const i=await this.checkBrokenImage();i.suspicious&&(e.brokenImage=i,t+=25);const s=await this.checkClientHints();s.suspicious&&(e.clientHints=s,t+=20);const n=this.checkCDPMouseSignature();n.suspicious&&(e.cdpMouse=n,t+=30);const a=this.checkHairlineSupport();a.suspicious&&(e.hairline=a,t+=10);const r=this.checkExtraFrameworks();r.length>0&&(e.extraFrameworks=r,t+=20);(await this.checkWorkerCDP()).suspicious&&(e.workerCDP=!0,t+=35),t>0&&this.transmitter.send("headless_probe",{signals:e,score:t,timestamp:Date.now()})}checkBrokenImage(){return new Promise(e=>{try{const t=document.createElement("img");t.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==___invalid";const i=setTimeout(()=>{e({suspicious:!1,width:-1,height:-1})},2e3);t.onerror=()=>{clearTimeout(i);const s=t.width,n=t.height;e({suspicious:0===s&&0===n,width:s,height:n})},t.onload=()=>{clearTimeout(i),e({suspicious:!1,width:t.width,height:t.height})},t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),setTimeout(()=>{try{document.body.removeChild(t)}catch(e){}},100)}catch(t){e({suspicious:!1,width:-1,height:-1})}})}async checkClientHints(){const e=[];try{const t=navigator.userAgentData;if(!t)return{suspicious:!1,mismatches:[]};const i=navigator.userAgent,s=(t.brands||[]).map(e=>e.brand);/Chrome\/\d/.test(i)&&!s.some(e=>/Chromium|Google Chrome|Chrome/.test(e))&&e.push("ua_chrome_no_brand"),t.platform&&(/Windows/.test(i)&&"Windows"!==t.platform&&e.push("ua_windows_brand_mismatch"),/Macintosh/.test(i)&&"macOS"!==t.platform&&e.push("ua_mac_brand_mismatch"),/Linux/.test(i)&&!/Linux|Android|ChromeOS/.test(t.platform)&&e.push("ua_linux_brand_mismatch")),/Mobile/.test(i)&&!1===t.mobile&&e.push("ua_mobile_brand_mismatch")}catch(t){}return{suspicious:e.length>0,mismatches:e}}checkCDPMouseSignature(){let e=0,t=0,i=!1;try{const s=[],n=i=>{s.push(i),t++,0===i.movementX&&0===i.movementY&&e++};document.addEventListener("mousemove",n,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",n)},5e3),t>10&&e/t>.9&&(i=!0)}catch(s){}return{suspicious:i,zeroMovementCount:e,totalEvents:t}}checkHairlineSupport(){try{const e=document.createElement("div");e.style.border=".5px solid transparent",e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e);const t=e.offsetHeight;return document.body.removeChild(e),{suspicious:0===t,offsetHeight:t}}catch(e){return{suspicious:!1,offsetHeight:-1}}}checkExtraFrameworks(){const e=[];try{const i=window.external;if(i&&"function"==typeof i.toString)try{const t=i.toString();/Sequentum/i.test(t)&&e.push("sequentum")}catch(t){}const s=["__webdriver_script_fn","__webdriver_script_func","__webdriver_evaluate","__selenium_evaluate","__fxdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__selenium_unwrapped","__fxdriver_unwrapped","__driver_unwrapped","_Selenium_IDE_Recorder","_selenium","calledSelenium","_WEBDRIVER_ELEM_CACHE","ChromeDriverw","driver-hierarchical","__$webdriverAsyncExecutor","__lastWatirAlert","__lastWatirConfirm","__lastWatirPrompt","_WEBDRIVER_ELEM_CACHE","webdriver","_phantom","__nightmare","_selenium"];for(const t of s)(t in document||t in window)&&e.push(`global_${t}`);const n=Object.getOwnPropertyNames(navigator);for(const t of n)/webdriver|selenium|puppeteer|playwright|phantom/i.test(t)&&e.push(`nav_${t}`)}catch(t){}return e}checkWorkerCDP(){return new Promise(e=>{try{const t=new Blob(["\n self.onmessage = function() {\n var detected = false;\n try {\n var marker = {};\n Object.defineProperty(marker, 'stack', {\n get: function() { detected = true; return ''; }\n });\n console.debug(marker);\n } catch(e) {}\n self.postMessage({ cdp: detected });\n };\n "],{type:"application/javascript"}),i=URL.createObjectURL(t),s=new Worker(i),n=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(i),e({suspicious:!1})},3e3);s.onmessage=t=>{clearTimeout(n),s.terminate(),URL.revokeObjectURL(i),e({suspicious:!0===t.data.cdp})},s.onerror=()=>{clearTimeout(n),s.terminate(),URL.revokeObjectURL(i),e({suspicious:!1})},s.postMessage("check")}catch(t){e({suspicious:!1})}})}}class CrawlProtect{constructor(e){__publicField(this,"config"),__publicField(this,"renewTimer",null),__publicField(this,"verified",!1),this.config=e}async start(){const e=this.getToken();if(e&&!this.isExpired(e))return this.verified=!0,this.scheduleRenewal(e),this.revealContent(),this.config.debug,!0;this.hideContent();const t=await this.solveChallenge();return t?(this.verified=!0,this.revealContent()):this.config.insertHoneypot&&this.insertHoneypotData(),t}isVerified(){return this.verified}stop(){this.renewTimer&&(clearTimeout(this.renewTimer),this.renewTimer=null)}async solveChallenge(){try{const e=await fetch(`${this.config.apiBase}/crawl-protect/challenge`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId}});if(!e.ok)return!1;const{id:t,challenges:i}=await e.json(),s=[];for(const c of i)if("math"===c.type){const e="add"===c.op?c.a+c.b:c.a*c.b;s.push(String(e))}else if("crypto"===c.type){const e=await this.sha256(c.nonce);s.push(e.slice(0,8))}const n=s.join(":"),a=await this.getFingerprint(),r=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:t,solution:n,fingerprint:a}),credentials:"include"});if(!r.ok)return!1;const o=await r.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(e){return this.config.debug,!1}}hideContent(){var e;if(null==(e=this.config.protectSelectors)?void 0:e.length)for(const t of this.config.protectSelectors){document.querySelectorAll(t).forEach(e=>{e.dataset.aieOrigDisplay=e.style.display,e.style.display="none"})}}revealContent(){var e;if(null==(e=this.config.protectSelectors)?void 0:e.length)for(const t of this.config.protectSelectors){document.querySelectorAll(t).forEach(e=>{e.style.display=e.dataset.aieOrigDisplay||"",delete e.dataset.aieOrigDisplay})}}insertHoneypotData(){const e=document.createElement("div");e.style.cssText="position:absolute;left:-9999px;top:-9999px;opacity:0;pointer-events:none;",e.setAttribute("aria-hidden","true"),e.innerHTML='\n <span class="price" data-aie-honeypot="1">âŠ999,999,999</span>\n <span class="stock" data-aie-honeypot="1">ěŹęł : 0ę°</span>\n <a href="mailto:honeypot@aientrophy.com" data-aie-honeypot="1">contact</a>\n ',document.body.appendChild(e)}getToken(){const e=document.cookie.match(new RegExp("(?:^|; )__aie_token=([^;]*)"));return e?decodeURIComponent(e[1]):null}setToken(e){const t=new Date(Date.now()+18e5).toUTCString();document.cookie=`__aie_token=${encodeURIComponent(e)};path=/;expires=${t};SameSite=None;Secure`}isExpired(e){try{const[t]=e.split("."),i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")));return Date.now()>i.exp}catch{return!0}}scheduleRenewal(e){try{const[t]=e.split("."),i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/"))),s=i.exp-3e5-Date.now();s>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),s))}catch{}}async sha256(e){const t=new TextEncoder,i=await crypto.subtle.digest("SHA-256",t.encode(e));return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}async getFingerprint(){const e=[navigator.userAgent,navigator.language,screen.width+"x"+screen.height,Intl.DateTimeFormat().resolvedOptions().timeZone];return this.sha256(e.join("|"))}}const securitySDK=new class{constructor(){__publicField(this,"transmitter"),__publicField(this,"behaviorCollector"),__publicField(this,"rapidClickDetector"),__publicField(this,"honeypot"),__publicField(this,"mouseTracker"),__publicField(this,"canvasFingerprinter"),__publicField(this,"inputTracker"),__publicField(this,"challengeHandler"),__publicField(this,"invisibleInteraction"),__publicField(this,"automationDetector"),__publicField(this,"sessionAnalyzer"),__publicField(this,"tabNavigationAnalyzer"),__publicField(this,"cloudEnvironmentDetector"),__publicField(this,"crossContextDetector"),__publicField(this,"headlessProbeDetector"),__publicField(this,"crawlProtect",null),__publicField(this,"initialized",!1),__publicField(this,"wasmService"),__publicField(this,"callbackManager"),this.transmitter=new Transmitter,this.wasmService=new WasmService,this.callbackManager=new CallbackManager,this.transmitter.setCallbackManager(this.callbackManager),this.behaviorCollector=new BehaviorCollector(this.transmitter),this.rapidClickDetector=new RapidClickDetector(this.transmitter),this.honeypot=new Honeypot(this.transmitter),this.mouseTracker=new MouseTracker(this.transmitter,this.wasmService),this.canvasFingerprinter=new CanvasFingerprinter(this.transmitter,this.wasmService),this.inputTracker=new InputTracker(this.transmitter),this.invisibleInteraction=new InvisibleInteraction(this.transmitter),this.automationDetector=new AutomationDetector(this.transmitter),this.sessionAnalyzer=new SessionAnalyzer(this.transmitter),this.tabNavigationAnalyzer=new TabNavigationAnalyzer(this.transmitter),this.cloudEnvironmentDetector=new CloudEnvironmentDetector(this.transmitter),this.crossContextDetector=new CrossContextDetector(this.transmitter),this.headlessProbeDetector=new HeadlessProbeDetector(this.transmitter)}async init(e){var t,i;if(this.initialized)return;e.callbacks&&this.callbackManager.setConfigCallbacks(e.callbacks);const s=e.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(s),this.startDetectors(),this.transmitter.setConfig(e),this.challengeHandler=new ChallengeHandler(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(t=e.serverConfig)?void 0:t.captchaEnabled)&&this.challengeHandler.start();((null==(i=e.serverConfig)?void 0:i.devtoolsDetection)??!e.debug)&&Promise.resolve().then(()=>require("../anti-debug-CYwG4s7P.cjs")).then(({AntiDebug:e})=>{e.start(),Promise.resolve().then(()=>require("../console-aIpHQlgP.cjs")).then(({ConsoleDetector:e})=>{new e(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),e.crawlProtect&&(this.crawlProtect=new CrawlProtect({apiBase:s,clientId:e.clientKey,protectSelectors:e.crawlProtect.protectSelectors,insertHoneypot:e.crawlProtect.insertHoneypot,debug:e.debug}),this.crawlProtect.start().catch(t=>{e.debug})),this.initialized=!0,e.debug,this.callbackManager.emit("ready")}catch(n){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==n?void 0:n.message})}}on(e,t){this.callbackManager.on(e,t)}off(e,t){this.callbackManager.off(e,t)}once(e,t){this.callbackManager.once(e,t)}startDetectors(){this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start()}};"undefined"!=typeof window&&(window.SecuritySDK=securitySDK);exports.Aientrophy=class{constructor(e){__publicField(this,"config"),this.config=e}async protect(){const e=this.config.endpoint||"https://api.aientrophy.com/api/v1/events";let t={};try{const s=e.replace(/\/events$/,""),n=await fetch(`${s}/sdk/payload?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(n.ok){t=(await n.json()).config||{}}if(t.nonceValidation)try{const e=await fetch(`${s}/sdk/nonce?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(e.ok){const i=await e.json();i.nonce&&(t.initialNonce=i.nonce)}}catch(i){this.config.debug}}catch(i){this.config.debug}await securitySDK.init({endpoint:e,clientKey:this.config.clientKey,debug:this.config.debug,callbacks:this.config.callbacks,serverConfig:t})}on(e,t){securitySDK.on(e,t)}off(e,t){securitySDK.off(e,t)}once(e,t){securitySDK.once(e,t)}};
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__publicField=(e,t,i)=>((e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const CONFIG_RSA_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class CryptoUtils{static async init(){if(!this.sessionKey)try{await this.initECDH()}catch(e){await this.initRSA()}}static async initECDH(){const e=await window.crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=await window.crypto.subtle.exportKey("raw",e.publicKey);this.ecdhPublicKeyBase64=this.arrayBufferToBase64(t);const i=(window.__securitySDKEndpoint||"").replace(/\/events$/,""),s=await fetch(`${i}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!s.ok)throw new Error("Key exchange failed");const{serverPublicKey:n,salt:a}=await s.json(),r=this.base64ToArrayBuffer(n),o=await window.crypto.subtle.importKey("raw",r,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},e.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(a);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const e=await this.importRSAPublicKey(CONFIG_RSA_PUBLIC_KEY),t=await window.crypto.subtle.exportKey("raw",this.sessionKey),i=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);this.encryptedSessionKey=this.arrayBufferToBase64(i),this.protocolVersion=1}static async encrypt(e){this.sessionKey||await this.init();const t=JSON.stringify(e),i=(new TextEncoder).encode(t),s=window.crypto.getRandomValues(new Uint8Array(12)),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.sessionKey,i),a=new Uint8Array(n),r=a.slice(0,a.length-16),o=a.slice(a.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}static async decrypt(e){if(!this.sessionKey)throw new Error("Session key not initialized");const t=this.base64ToArrayBuffer(e.d),i=this.base64ToArrayBuffer(e.iv),s=this.base64ToArrayBuffer(e.tag),n=new Uint8Array(t.byteLength+s.byteLength);n.set(new Uint8Array(t),0),n.set(new Uint8Array(s),t.byteLength);const a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.sessionKey,n),r=(new TextDecoder).decode(a);return JSON.parse(r)}static setEndpoint(e){window.__securitySDKEndpoint=e}static async importRSAPublicKey(e){const t=window.atob(e),i=this.str2ab(t);return await window.crypto.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(e){const t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let s=0,n=e.length;s<n;s++)i[s]=e.charCodeAt(s);return t}static arrayBufferToBase64(e){let t="";const i=new Uint8Array(e),s=i.byteLength;for(let n=0;n<s;n++)t+=String.fromCharCode(i[n]);return window.btoa(t)}static base64ToArrayBuffer(e){const t=window.atob(e),i=t.length,s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=t.charCodeAt(n);return s.buffer}}__publicField(CryptoUtils,"sessionKey",null),__publicField(CryptoUtils,"ecdhPublicKeyBase64",null),__publicField(CryptoUtils,"encryptedSessionKey",null),__publicField(CryptoUtils,"protocolVersion",2);const THREAT_EVENTS=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe"]);class CallbackManager{constructor(){__publicField(this,"handlers",new Map),__publicField(this,"configCallbacks",{})}setConfigCallbacks(e){this.configCallbacks=e}on(e,t){this.addHandler(e,t,!1)}once(e,t){this.addHandler(e,t,!0)}off(e,t){const i=this.handlers.get(e);if(!i)return;const s=i.filter(e=>e.handler!==t);0===s.length?this.handlers.delete(e):this.handlers.set(e,s)}emit(e,...t){this.callHandlers(e,t);const i=e.indexOf(":");if(-1!==i){const s=e.substring(0,i);this.callHandlers(s,t)}this.callConfigCallback(e,t)}emitChallenge(e){return new Promise(t=>{let i=!1;const s=e=>{i||(i=!0,t(e))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[e,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[e,s]),setTimeout(()=>{i||(i=!0,t(!1))},5e3)):t(!1)})}addHandler(e,t,i){this.handlers.has(e)||this.handlers.set(e,[]),this.handlers.get(e).push({handler:t,once:i})}callHandlers(e,t){const i=this.handlers.get(e);if(!i||0===i.length)return;const s=[];for(let n=0;n<i.length;n++)this.safeCall(i[n].handler,t),i[n].once&&s.push(n);for(let n=s.length-1;n>=0;n--)i.splice(s[n],1);0===i.length&&this.handlers.delete(e)}callConfigCallback(e,t){if(e.startsWith("threat:")||"threat"===e)return void(e.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,t));const i={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[e];i&&this.configCallbacks[i]&&this.safeCall(this.configCallbacks[i],t)}safeCall(e,t){try{e(...t)}catch(i){}}}class Transmitter{constructor(){__publicField(this,"endpoint",""),__publicField(this,"clientKey",""),__publicField(this,"encryptionRequired",!1),__publicField(this,"currentNonce",""),__publicField(this,"buffer",[]),__publicField(this,"batchSize",20),__publicField(this,"flushInterval",5e3),__publicField(this,"intervalId"),__publicField(this,"responseHandler",null),__publicField(this,"callbackManager",null),__publicField(this,"flushing",!1),__publicField(this,"pendingFlush",!1),__publicField(this,"backoffMs",0),__publicField(this,"maxBackoffMs",6e4),__publicField(this,"_lastBackoffStart",0),this.startFlushInterval()}setConfig(e){var t,i;this.endpoint=e.endpoint,this.clientKey=e.clientKey,this.encryptionRequired=(null==(t=e.serverConfig)?void 0:t.encryptionRequired)??!1,this.currentNonce=(null==(i=e.serverConfig)?void 0:i.initialNonce)??"",CryptoUtils.setEndpoint(e.endpoint)}setResponseHandler(e){this.responseHandler=e}setCallbackManager(e){this.callbackManager=e}send(e,t={}){const i=Date.now();if(this.buffer.push({type:e,data:t,timestamp:i}),this.callbackManager)if(THREAT_EVENTS.has(e)){const s={type:e,data:t,timestamp:i};this.callbackManager.emit(`threat:${e}`,s)}else this.callbackManager.emit(`data:${e}`,{type:e,data:t,timestamp:i});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.backoffMs>0){const e=Date.now();if(this._lastBackoffStart||(this._lastBackoffStart=e),e-this._lastBackoffStart<this.backoffMs)return;this._lastBackoffStart=0}if(this.flushing)return void(this.pendingFlush=!0);this.flushing=!0;const e=this.buffer;this.buffer=[];try{let s;if(this.encryptionRequired){const t=await CryptoUtils.encrypt(e);s=JSON.stringify(t)}else s=JSON.stringify(e);const n={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(n["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const i=await fetch(this.endpoint,{method:"POST",body:s,headers:n,keepalive:!0});if(429===i.status)return this.buffer=e.concat(this.buffer).slice(0,500),this.backoffMs=0===this.backoffMs?5e3:Math.min(2*this.backoffMs,this.maxBackoffMs),void(this._lastBackoffStart=Date.now());if(this.backoffMs=0,i.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),i.ok)try{const e=await i.json();let t=e;this.encryptionRequired&&(t=await CryptoUtils.decrypt(e)),(null==t?void 0:t.nonce)&&(this.currentNonce=t.nonce),this.responseHandler&&this.responseHandler(t)}catch(t){}}catch(i){this.callbackManager&&this.callbackManager.emit("error",{code:"NETWORK_ERROR",message:"Failed to send security events"})}}catch(t){this.callbackManager&&this.callbackManager.emit("error",{code:"PAYLOAD_ERROR",message:"Failed to prepare security payload"})}finally{this.flushing=!1,this.pendingFlush&&(this.pendingFlush=!1,this.flush())}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.flush()}startFlushInterval(){this.intervalId=setInterval(()=>{this.flush()},this.flushInterval)}}class BehaviorCollector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"isCollecting",!1),this.transmitter=e}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}class RapidClickDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"clickHistory",[]),__publicField(this,"THRESHOLD_COUNT",3),__publicField(this,"THRESHOLD_TIME",500),this.transmitter=e,this.init()}init(){document.addEventListener("click",e=>this.handleClick(e),!0)}handleClick(e){const t=Date.now();if(this.clickHistory.push(t),this.clickHistory=this.clickHistory.filter(e=>t-e<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const i=e.target,s={tagName:i.tagName,id:i.id,className:i.className,x:e.clientX,y:e.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:s,timestamp:t}),this.clickHistory=[]}}}class Honeypot{constructor(e){__publicField(this,"transmitter"),__publicField(this,"element",null),this.transmitter=e}start(){this.element=document.createElement("input"),this.element.type="text";const e=["website","email_confirm","url","homepage","fax_number","address_line_2"],t=e[Math.floor(Math.random()*e.length)],i=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${t}-${i}`,this.element.autocomplete="off",Object.assign(this.element.style,{position:"absolute",opacity:"0",top:"0",left:"-9999px",height:"1px",width:"1px",zIndex:"-1",border:"none"}),this.element.tabIndex=-1,this.element.setAttribute("aria-hidden","true"),this.element.setAttribute("role","presentation");const s=e=>{var t;this.transmitter.send("honeypot_triggered",{eventType:e.type,value:null==(t=this.element)?void 0:t.value,timestamp:Date.now()})};this.element.addEventListener("input",s),this.element.addEventListener("focus",s),this.element.addEventListener("click",s),document.body.appendChild(this.element)}stop(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class MouseTracker{constructor(e,t){__publicField(this,"transmitter"),__publicField(this,"wasmService"),__publicField(this,"buffer",[]),__publicField(this,"BUFFER_SIZE",50),__publicField(this,"SAMPLE_INTERVAL",100),__publicField(this,"SEND_COOLDOWN",5e3),__publicField(this,"lastSampleTime",0),__publicField(this,"lastSendTime",0),__publicField(this,"handleMouseMove",e=>{const t=Date.now();t-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=t,this.buffer.push({x:e.clientX,y:e.clientY,time:t}),this.buffer.length>this.BUFFER_SIZE&&this.buffer.shift(),this.buffer.length>=this.BUFFER_SIZE&&t-this.lastSendTime>=this.SEND_COOLDOWN&&(this.analyze(),this.lastSendTime=t))}),this.transmitter=e,this.wasmService=t}start(){"undefined"!=typeof document&&document.addEventListener("mousemove",this.handleMouseMove)}stop(){"undefined"!=typeof document&&document.removeEventListener("mousemove",this.handleMouseMove)}analyze(){if(this.buffer.length<20)return;const e=this.wasmService.calculateEntropy(this.buffer),t=this.calculateSpeedVariance(),i=this.buffer.map(e=>({x:e.x,y:e.y,t:e.time}));this.transmitter.send("behavior_metrics",{entropy:e,speedVariance:t,sampleSize:this.buffer.length,timestamp:Date.now(),rawTrajectory:i})}calculateSpeedVariance(){const e=[];for(let i=1;i<this.buffer.length;i++){const t=this.buffer[i-1],s=this.buffer[i],n=Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2)),a=s.time-t.time;a>0&&e.push(n/a)}if(e.length<2)return 1;const t=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length}}class InputTracker{constructor(e){__publicField(this,"lastInteractionTime",0),__publicField(this,"lastInteractionType","none"),__publicField(this,"transmitter"),__publicField(this,"isMobile",!1),__publicField(this,"keyPressTimes",new Map),__publicField(this,"lastKeyUpTime",0),__publicField(this,"flightTimes",[]),__publicField(this,"dwellTimes",[]),__publicField(this,"suspiciousFocusCount",0),__publicField(this,"suspiciousFocusResetTimer",null),__publicField(this,"rawKeystrokes",[]),this.transmitter=e,this.isMobile=this.detectMobile()}start(){this.initListeners()}detectMobile(){return"undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0)}initListeners(){if("undefined"==typeof document)return;["mousedown","keydown","touchstart","touchend"].forEach(e=>{document.addEventListener(e,e=>{this.lastInteractionTime=Date.now(),this.lastInteractionType=e.type},{passive:!0,capture:!0})}),document.addEventListener("focus",e=>{const t=e.target;"INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName||(this.checkFocusIntegrity(),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",e=>{const t=e.target;if("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName)return;const i=Date.now();if(this.keyPressTimes.set(e.code,i),this.rawKeystrokes.push({code:e.code,t:i,type:"down"}),this.lastKeyUpTime>0){const e=i-this.lastKeyUpTime;e<2e3&&this.flightTimes.push(e)}},{passive:!0,capture:!0}),document.addEventListener("keyup",e=>{const t=e.target;if("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName)return;const i=Date.now();this.lastKeyUpTime=i,this.rawKeystrokes.push({code:e.code,t:i,type:"up"});const s=this.keyPressTimes.get(e.code);if(s){const t=i-s;this.dwellTimes.push(t),this.keyPressTimes.delete(e.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(t)},{passive:!0,capture:!0}),document.addEventListener("blur",e=>{const t=e.target;("INPUT"===t.tagName||"TEXTAREA"===t.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(t)},{capture:!0})}checkFocusIntegrity(){const e=Date.now(),t=e-this.lastInteractionTime;performance.now()<5e3||(t>200?(this.suspiciousFocusCount++,clearTimeout(this.suspiciousFocusResetTimer),this.suspiciousFocusResetTimer=setTimeout(()=>{this.suspiciousFocusCount=0},3e3),this.transmitter.send("behavior_metrics",{type:"suspicious_focus",timeSinceInteraction:t,lastInteraction:this.lastInteractionType,consecutiveCount:this.suspiciousFocusCount,timestamp:e})):this.suspiciousFocusCount=0)}reportKeystrokeDynamics(e){const t=this.average(this.flightTimes),i=this.variance(this.flightTimes,t),s=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:e.id||e.tagName,flight:{avg:t,variance:i,samples:this.flightTimes.length},dwell:{avg:s,variance:n},isMobile:this.isMobile,timestamp:Date.now(),rawKeystrokes:[...this.rawKeystrokes]}),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[]}average(e){return 0===e.length?0:e.reduce((e,t)=>e+t,0)/e.length}variance(e,t){return 0===e.length?0:e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length}}class WasmService{constructor(){__publicField(this,"wasmModule",null),__publicField(this,"memory",null),__publicField(this,"instance",null)}async load(e){try{const t=await fetch(`${e}/sdk/core.wasm`);if(!t.ok)throw new Error(`HTTP ${t.status}`);const i={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const e=await WebAssembly.instantiateStreaming(t,i);this.instance=e.instance}else{const e=await t.arrayBuffer(),s=await WebAssembly.instantiate(e,i);this.instance=s.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(t){}}isLoaded(){return!!this.instance}calculateEntropy(e){if(!this.instance||!this.wasmModule)return 0;const t=2*e.length,i=8*t;try{const s=this.wasmModule.__new(i,0),n=new Float64Array(this.memory.buffer,s,t);for(let t=0;t<e.length;t++)n[2*t]=e[t].x,n[2*t+1]=e[t].y;return this.wasmModule.calculateEntropy(s,t)}catch(s){return 0}}simpleHash(e){if(!this.instance||!this.wasmModule)return 0;try{const t=(new TextEncoder).encode(e),i=t.length,s=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,s,i).set(t),this.wasmModule.simpleHash(s,i)}catch(t){return 0}}}class CanvasFingerprinter{constructor(e,t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof document||setTimeout(async()=>{const e=await this.generateFingerprint(),t=this.collectWebGLFingerprint(),i=this.collectAudioFingerprint();this.transmitter.send("fingerprint_collected",{hash:e,webgl:t,audio:i}),this.hasRun=!0},500)}async generateFingerprint(){try{const e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return"unknown";t.textBaseline="top",t.font='14px "Arial"',t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("aientrophy Security đ",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("aientrophy Security đ",4,17),t.globalCompositeOperation="multiply",t.fillStyle="rgb(255,0,255)",t.beginPath(),t.arc(50,50,50,0,2*Math.PI,!0),t.closePath(),t.fill(),t.fillStyle="rgb(0,255,255)",t.beginPath(),t.arc(100,50,50,0,2*Math.PI,!0),t.closePath(),t.fill(),t.fillStyle="rgb(255,255,0)",t.beginPath(),t.arc(75,100,50,0,2*Math.PI,!0),t.closePath(),t.fill();const i=e.toDataURL();return await this.sha256(i)}catch(e){return"error"}}async sha256(e){const t=(new TextEncoder).encode(e),i=await window.crypto.subtle.digest("SHA-256",t),s=new Uint8Array(i);return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}collectWebGLFingerprint(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{available:!1};const i=t,s={available:!0},n=i.getExtension("WEBGL_debug_renderer_info");return n&&(s.renderer=i.getParameter(n.UNMASKED_RENDERER_WEBGL),s.vendor=i.getParameter(n.UNMASKED_VENDOR_WEBGL)),s.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE),s.maxViewportDims=Array.from(i.getParameter(i.MAX_VIEWPORT_DIMS)),s.maxRenderbufferSize=i.getParameter(i.MAX_RENDERBUFFER_SIZE),s.maxVertexAttribs=i.getParameter(i.MAX_VERTEX_ATTRIBS),s.extensions=(i.getSupportedExtensions()||[]).length,s}catch(e){return{available:!1,error:!0}}}collectAudioFingerprint(){try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return{available:!1};const t=new e,i={available:!0,sampleRate:t.sampleRate,state:t.state,maxChannels:t.destination.maxChannelCount};return t.close(),i}catch(e){return{available:!1}}}}class ChallengeHandler{constructor(e){__publicField(this,"originalFetch"),__publicField(this,"endpoint"),__publicField(this,"callbackManager",null),__publicField(this,"challengeInProgress",null),this.endpoint=e,this.originalFetch=window.fetch.bind(window)}setCallbackManager(e){this.callbackManager=e}start(){window.fetch=async(e,t)=>{var i;const s=await this.originalFetch(e,t);if(403===s.status){const a=s.clone();try{const n=await a.json();if("challenge"===n.action&&"captcha"===(null==(i=n.metadata)?void 0:i.type)){const i={action:"challenge",score:n.score,metadata:n.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(i))return this.originalFetch(e,t)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(e,t):s}"block"===n.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:n.score,metadata:n.metadata})}catch(n){}}return s}}async showCaptchaModal(){return new Promise(e=>{const t=document.createElement("div");t.id="sec-sdk-challenge-host",t.style.position="fixed",t.style.top="0",t.style.left="0",t.style.width="100vw",t.style.height="100vh",t.style.zIndex="999999",t.style.backgroundColor="rgba(0,0,0,0.5)",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center";const i=t.attachShadow({mode:"open"}),s=document.createElement("div");s.style.background="white",s.style.padding="20px",s.style.borderRadius="8px",s.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)",s.style.textAlign="center",s.style.fontFamily="system-ui, sans-serif";const n=document.createElement("h3");n.textContent="Security Check",n.style.margin="0 0 16px 0";const a=document.createElement("p");a.textContent="Unusual activity detected. Please verify you are human.",a.style.marginBottom="16px",a.style.fontSize="14px",a.style.color="#666";const r=document.createElement("div");r.innerHTML="Loading...",r.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",s.appendChild(n),s.appendChild(a),s.appendChild(r),s.appendChild(o),s.appendChild(c),s.appendChild(l),i.appendChild(s),document.body.appendChild(t);let h="";const u=async()=>{try{const e=await this.originalFetch(`${this.endpoint}/challenge`),t=await e.json();h=t.id,r.innerHTML=t.svg}catch(e){r.textContent="Error loading CAPTCHA"}},d=async()=>{l.style.display="none",c.textContent="Verifying...";try{const i=o.value,s=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:i})});(await s.json()).success?(document.body.removeChild(t),e(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",u())}catch(i){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=d,o.onkeydown=e=>{"Enter"===e.key&&d()},u()})}}class InvisibleInteraction{constructor(e){__publicField(this,"transmitter"),__publicField(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),__publicField(this,"handleEvent",e=>{const t=e.target;if(!(t&&t instanceof HTMLElement))return;if(t===document.body||t===document.documentElement)return;const i=this.checkVisibility(t,e);if(i){const s=t.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:e.type,target:t.tagName,id:t.id,reason:i,timestamp:Date.now(),isTrusted:e.isTrusted,coordinates:{x:e instanceof MouseEvent?e.clientX:0,y:e instanceof MouseEvent?e.clientY:0},viewport:{width:window.innerWidth,height:window.innerHeight},scroll:{x:window.scrollX,y:window.scrollY},docDim:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},elementRect:{top:s.top,left:s.left,width:s.width,height:s.height}})}}),this.transmitter=e}start(){this.eventsToWatch.forEach(e=>{document.addEventListener(e,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(e=>{document.removeEventListener(e,this.handleEvent,{capture:!0})})}checkVisibility(e,t){var i,s;const n=window.getComputedStyle(e);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=e.getBoundingClientRect();if(a.width<=0||a.height<=0)return"zero_size";const r=a.right<0||a.left>window.innerWidth,o=a.bottom<0||a.top>window.innerHeight;if(r||o)return"off_screen";if(t instanceof MouseEvent||t instanceof TouchEvent){let n,a;if(t instanceof MouseEvent?(n=t.clientX,a=t.clientY):(n=(null==(i=t.touches[0])?void 0:i.clientX)||0,a=(null==(s=t.touches[0])?void 0:s.clientY)||0),n>=0&&n<=window.innerWidth&&a>=0&&a<=window.innerHeight){const i=document.elementFromPoint(n,a);if(i&&i!==e&&!e.contains(i)&&!i.contains(e)&&0===n&&0===a&&t.isTrusted)return null}}return null}}class AutomationDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(setTimeout(()=>this.detect(),1500),this.hasRun=!0)}detect(){var e,t;const i={};let s=0;!0===navigator.webdriver&&(i.webdriver=!0,s+=40);try{this.detectCDP()&&(i.cdp=!0,s+=50)}catch(c){}const n=this.detectAutomationGlobals();n.length>0&&(i.automationGlobals=n,s+=30);const a=this.checkWebGL();a.suspicious&&(i.webgl=a,s+=25);const r=this.checkInconsistencies();r.length>0&&(i.inconsistencies=r,s+=15);const o=this.checkHeadless();o.score>0&&(i.headless=o.flags,s+=o.score),s>0&&this.transmitter.send("automation_detected",{signals:i,score:s,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(e=navigator.plugins)?void 0:e.length)??0,languages:(null==(t=navigator.languages)?void 0:t.length)??0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,maxTouchPoints:navigator.maxTouchPoints,webglRenderer:a.renderer,webglVendor:a.vendor,timestamp:Date.now()})}detectCDP(){const e=console.debug;return console.debug=e,!1}detectAutomationGlobals(){const e=[],t=[["selenium",()=>!!window._selenium],["selenium_unwrapped",()=>!!document.__selenium_unwrapped],["driver_evaluate",()=>!!document.__driver_evaluate],["webdriver_evaluate",()=>!!document.__webdriver_evaluate],["driver_unwrapped",()=>!!document.__driver_unwrapped],["fxdriver",()=>!!document.__fxdriver_evaluate],["playwright",()=>!!window.__playwright],["playwright_binding",()=>!!window.__playwright__binding__],["pwInitScripts",()=>!!window.__pwInitScripts],["puppeteer",()=>!!window.__puppeteer_evaluation_script__],["phantom",()=>!!window.callPhantom||!!window._phantom],["nightmare",()=>!!window.__nightmare],["cdc",()=>Object.keys(document).some(e=>e.startsWith("cdc_")||e.startsWith("$cdc_"))]];for(const[s,n]of t)try{n()&&e.push(s)}catch(i){}return e}checkWebGL(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{suspicious:!1,renderer:"unavailable",vendor:"unavailable"};const i=t.getExtension("WEBGL_debug_renderer_info");if(!i)return{suspicious:!1,renderer:"no_debug_info",vendor:"no_debug_info"};const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",n=t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(s)||/Mesa OffScreen/i.test(s)||/llvmpipe/i.test(s),renderer:s,vendor:n}}catch(e){return{suspicious:!1,renderer:"error",vendor:"error"}}}checkInconsistencies(){const e=[];try{const t=navigator.userAgent,i=navigator.platform;/Windows/.test(t)&&/Mac/.test(i)&&e.push("ua_platform_mismatch_win_mac"),/Macintosh/.test(t)&&/Win/.test(i)&&e.push("ua_platform_mismatch_mac_win"),/Mobile|Android|iPhone/.test(t)&&0===navigator.maxTouchPoints&&e.push("mobile_ua_no_touch"),/Chrome/.test(t)&&navigator.plugins&&0===navigator.plugins.length&&e.push("chrome_no_plugins"),navigator.languages&&0!==navigator.languages.length||e.push("no_languages")}catch(t){}return e}checkHeadless(){const e=[];let t=0;try{if(/HeadlessChrome/.test(navigator.userAgent)&&(e.push("headless_ua"),t+=40),/Chrome/.test(navigator.userAgent)&&!window.chrome&&(e.push("chrome_ua_no_chrome_obj"),t+=15),window.screen&&800===window.screen.width&&600===window.screen.height&&(e.push("default_screen_size"),t+=10),"Notification"in window){"denied"===window.Notification.permission&&navigator.userAgent.includes("Chrome")&&(e.push("notification_denied_default"),t+=5)}const i=navigator.connection;i&&0===i.rtt&&(e.push("zero_rtt"),t+=10)}catch(i){}return{score:t,flags:e}}}class SessionAnalyzer{constructor(e){__publicField(this,"transmitter"),__publicField(this,"sessionStart",0),__publicField(this,"pageTransitions",[]),__publicField(this,"interactionTimestamps",[]),__publicField(this,"lastPageUrl",""),__publicField(this,"formStartTimes",new Map),__publicField(this,"reportInterval",null),this.transmitter=e}start(){if("undefined"==typeof window)return;this.sessionStart=Date.now(),this.lastPageUrl=window.location.href;["mousedown","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>500&&this.interactionTimestamps.shift()},{passive:!0,capture:!0})}),this.observeNavigation(),this.observeForms(),this.reportInterval=setInterval(()=>this.report(),15e3)}observeNavigation(){const e=history.pushState,t=history.replaceState,i=this;history.pushState=function(t,s,n){e.call(this,t,s,n),i.onPageTransition()},history.replaceState=function(e,s,n){t.call(this,e,s,n),i.onPageTransition()},window.addEventListener("popstate",()=>this.onPageTransition())}onPageTransition(){const e=Date.now(),t=window.location.href;t!==this.lastPageUrl&&(this.pageTransitions.push(e),this.lastPageUrl=t)}observeForms(){document.addEventListener("focus",e=>{const t=e.target;if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName){const e=t.closest("form"),i=(null==e?void 0:e.id)||(null==e?void 0:e.action)||"anonymous_form";this.formStartTimes.has(i)||this.formStartTimes.set(i,Date.now())}},{capture:!0}),document.addEventListener("submit",e=>{const t=e.target,i=t.id||t.action||"anonymous_form",s=this.formStartTimes.get(i);if(s){const e=Date.now()-s;this.transmitter.send("session_metrics",{type:"form_completion",formId:i,duration:e,timestamp:Date.now()}),this.formStartTimes.delete(i)}},{capture:!0})}report(){const e=Date.now(),t=e-this.sessionStart;if(this.interactionTimestamps.length<10)return;const i=this.calculateIntervals(this.interactionTimestamps),s=this.analyzeTimingDistribution(i),n=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:t,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:s,pages:n,timestamp:e})}calculateIntervals(e){const t=[];for(let i=1;i<e.length;i++)t.push(e[i]-e[i-1]);return t}analyzeTimingDistribution(e){if(e.length<5)return{samples:e.length};const t=e.reduce((e,t)=>e+t,0)/e.length,i=e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length,s=Math.sqrt(i),n=t>0?s/t:0,a=this.shannonEntropy(e,50),r=this.autocorrelation(e);return{mean:Math.round(t),stdDev:Math.round(s),cv:parseFloat(n.toFixed(4)),entropy:parseFloat(a.toFixed(4)),autocorrelation:parseFloat(r.toFixed(4)),samples:e.length}}analyzePageTransitions(){if(this.pageTransitions.length<2)return{count:this.pageTransitions.length};const e=this.calculateIntervals(this.pageTransitions),t=e.reduce((e,t)=>e+t,0)/e.length,i=e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length,s=t>0?Math.sqrt(i)/t:0;return{count:this.pageTransitions.length,avgInterval:Math.round(t),cv:parseFloat(s.toFixed(4))}}shannonEntropy(e,t){const i=new Map;for(const a of e){const e=Math.floor(a/t);i.set(e,(i.get(e)||0)+1)}const s=e.length;let n=0;for(const a of i.values()){const e=a/s;e>0&&(n-=e*Math.log2(e))}return n}autocorrelation(e){if(e.length<3)return 0;const t=e.reduce((e,t)=>e+t,0)/e.length;let i=0,s=0;for(let n=0;n<e.length-1;n++)i+=(e[n]-t)*(e[n+1]-t);for(let n=0;n<e.length;n++)s+=Math.pow(e[n]-t,2);return 0===s?0:i/s}}class TabNavigationAnalyzer{constructor(e){__publicField(this,"transmitter"),__publicField(this,"tabTimestamps",[]),__publicField(this,"shiftTabCount",0),__publicField(this,"tabCount",0),__publicField(this,"isShiftDown",!1),__publicField(this,"BURST_THRESHOLD_MS",80),__publicField(this,"reportInterval",null),__publicField(this,"REPORT_INTERVAL_MS",1e4),__publicField(this,"MIN_TABS_TO_REPORT",5),__publicField(this,"TAB_TRIGGER_COUNT",20),__publicField(this,"onKeyDown",e=>{if("Shift"!==e.key){if("Tab"===e.key){const e=Date.now();this.isShiftDown?this.shiftTabCount++:(this.tabCount++,this.tabTimestamps.push(e),this.tabTimestamps.length>100&&this.tabTimestamps.shift()),this.tabCount+this.shiftTabCount>=this.TAB_TRIGGER_COUNT&&this.report()}}else this.isShiftDown=!0}),__publicField(this,"onKeyUp",e=>{"Shift"===e.key&&(this.isShiftDown=!1)}),this.transmitter=e}start(){"undefined"!=typeof document&&(document.addEventListener("keydown",this.onKeyDown,{passive:!0,capture:!0}),document.addEventListener("keyup",this.onKeyUp,{passive:!0,capture:!0}),this.reportInterval=setInterval(()=>this.report(),this.REPORT_INTERVAL_MS))}stop(){"undefined"!=typeof document&&(document.removeEventListener("keydown",this.onKeyDown,{capture:!0}),document.removeEventListener("keyup",this.onKeyUp,{capture:!0}),this.reportInterval&&(clearInterval(this.reportInterval),this.reportInterval=null),this.report())}report(){const e=this.tabCount+this.shiftTabCount;if(e<this.MIN_TABS_TO_REPORT)return;const t=this.calculateIntervals(this.tabTimestamps);if(t.length<3)return void this.resetBuffers();const i=this.analyzeIntervals(t),s=this.analyzeBursts(t),n=e>0?this.shiftTabCount/e:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(n.toFixed(4)),intervals:i,bursts:s,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(e){const t=[];for(let i=1;i<e.length;i++){const s=e[i]-e[i-1];s<5e3&&t.push(s)}return t}analyzeIntervals(e){if(0===e.length)return{avg:0,variance:0,cv:0,min:0,samples:0};const t=e.reduce((e,t)=>e+t,0)/e.length,i=e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length,s=Math.sqrt(i),n=t>0?s/t:0,a=Math.min(...e);return{avg:parseFloat(t.toFixed(2)),variance:parseFloat(i.toFixed(2)),cv:parseFloat(n.toFixed(4)),min:a,samples:e.length}}analyzeBursts(e){let t=0,i=0,s=0,n=0,a=0;for(const r of e)r<this.BURST_THRESHOLD_MS?(i++,n+=r,a++):(i>=3&&(t++,s+=i),i=0);return i>=3&&(t++,s+=i),{count:t,avgLength:t>0?parseFloat((s/t).toFixed(1)):0,avgInterval:a>0?parseFloat((n/a).toFixed(2)):0}}}class CloudEnvironmentDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{const e=this.analyzeGPU(),t=this.analyzeHardware(),i=this.analyzeScreen(),s=await this.analyzeMedia(),n=this.benchmarkCanvas();let a=0;"virtual_gpu"!==e.category&&"software_render"!==e.category&&"cloud_gpu"!==e.category||(a+=2),t.cores<=2&&a++,null!==t.memory&&t.memory<=2&&a++,24===t.colorDepth&&a++,1===t.pixelRatio&&a++,i.noTaskbar&&a++,i.isVMResolution&&a++,0===s.cameras&&0===s.microphones&&a++,s.hasBluetooth||s.hasUSB||a++,n.canvasRenderTime>50&&a++;const{classification:r,confidence:o}=this.classify(e,t,a);this.transmitter.send("cloud_environment",{classification:r,confidence:o,signals:{gpu:{renderer:e.renderer,vendor:e.vendor,category:e.category},hardware:t,screen:i,media:s,performance:n},vmIndicatorCount:a,timestamp:Date.now()})}catch(e){}}analyzeGPU(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return{renderer:"unavailable",vendor:"unavailable",category:"unknown"};const i=t.getExtension("WEBGL_debug_renderer_info");if(!i)return{renderer:"no_debug_info",vendor:"no_debug_info",category:"unknown"};const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",n=t.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{renderer:s,vendor:n,category:this.categorizeGPU(s,n)}}catch(e){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(e,t){const i=e.toLowerCase(),s=t.toLowerCase();return/swiftshader|llvmpipe|mesa offscreen|softpipe/.test(i)?"software_render":/svga3d|svga|vmware/.test(i)||/virtualbox/.test(i)||/parallels/.test(i)||/qxl|virtio|red hat|spice/.test(i)||/hyper-v|microsoft basic render/i.test(i)||/citrix/.test(i)?"virtual_gpu":/amazon|elastic|aws/.test(i)||/amazon|elastic|aws/.test(s)||/google cloud|gce/.test(i)||/google cloud|gce/.test(s)||/azure/.test(i)||/azure/.test(s)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const e=screen.width,t=screen.height,i=screen.availHeight,s=t===i&&t===window.innerHeight,n=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([i,s])=>e===i&&t===s&&!(1920===i&&1080===s));return{width:e,height:t,availHeight:i,noTaskbar:s,isVMResolution:n}}async analyzeMedia(){let e=-1,t=-1;try{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){const i=await navigator.mediaDevices.enumerateDevices();e=i.filter(e=>"videoinput"===e.kind).length,t=i.filter(e=>"audioinput"===e.kind).length}}catch(a){}const i=!!navigator.bluetooth,s=!!navigator.usb;let n=null;try{if(navigator.getBattery){const e=await navigator.getBattery();n=!(e.charging&&1===e.level&&0===e.chargingTime)}}catch(a){}return{cameras:e,microphones:t,hasBluetooth:i,hasUSB:s,hasBattery:n}}benchmarkCanvas(){try{const e=document.createElement("canvas");e.width=200,e.height=200;const t=e.getContext("2d");if(!t)return{canvasRenderTime:-1};const i=performance.now();for(let n=0;n<500;n++)t.fillStyle=`rgb(${n%256},${3*n%256},${7*n%256})`,t.fillRect(13*n%200,7*n%200,10,10);t.getImageData(0,0,1,1);const s=performance.now()-i;return{canvasRenderTime:Math.round(100*s)/100}}catch(e){return{canvasRenderTime:-1}}}classify(e,t,i){return"virtual_gpu"===e.category?24===t.colorDepth?{classification:"rdp_likely",confidence:.85}:{classification:"vm_detected",confidence:.95}:"cloud_gpu"===e.category?{classification:"cloud_likely",confidence:.9}:"software_render"===e.category?{classification:"vm_detected",confidence:.9}:i>=5?{classification:"vm_likely",confidence:.8}:i>=3?{classification:"vm_likely",confidence:.6}:{classification:"physical",confidence:1-.1*i}}}class CrossContextDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2500))}async detect(){var e,t;const i={};let s=0;const n={webdriver:!!navigator.webdriver,languages:(null==(e=navigator.languages)?void 0:e.join(","))||"",platform:navigator.platform||"",hardwareConcurrency:navigator.hardwareConcurrency||0,userAgent:navigator.userAgent||"",pluginsLength:(null==(t=navigator.plugins)?void 0:t.length)??0},a=this.checkIframe(n);a.score>0&&(i.iframe=a.mismatches,s+=a.score);try{const e=await this.checkWorker(n);e.score>0&&(i.worker=e.mismatches,s+=e.score)}catch(r){}s>0&&this.transmitter.send("cross_context_mismatch",{signals:i,score:s,timestamp:Date.now()})}checkIframe(e){var t,i;const s=[];let n=0;try{const a=document.createElement("iframe");a.style.display="none",a.sandbox="allow-same-origin",document.body.appendChild(a);const r=a.contentWindow;if(!r)return document.body.removeChild(a),{score:0,mismatches:[]};const o=r.navigator;o.webdriver!==navigator.webdriver&&(s.push("webdriver_mismatch"),n+=40),navigator.webdriver||!0!==o.webdriver||(s.push("webdriver_spoofed_in_main"),n+=30);((null==(t=o.languages)?void 0:t.join(","))||"")!==e.languages&&(s.push("languages_mismatch"),n+=15),o.platform!==e.platform&&(s.push("platform_mismatch"),n+=15);((null==(i=o.plugins)?void 0:i.length)??0)!==e.pluginsLength&&(s.push("plugins_mismatch"),n+=10),document.body.removeChild(a)}catch(a){}return{score:n,mismatches:s}}checkWorker(e){return new Promise(t=>{try{const i=new Blob(["\n self.onmessage = function() {\n var nav = self.navigator;\n self.postMessage({\n webdriver: !!nav.webdriver,\n languages: (nav.languages || []).join(','),\n platform: nav.platform || '',\n hardwareConcurrency: nav.hardwareConcurrency || 0,\n userAgent: nav.userAgent || ''\n });\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(i),n=new Worker(s),a=setTimeout(()=>{n.terminate(),URL.revokeObjectURL(s),t({score:0,mismatches:[]})},3e3);n.onmessage=i=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(s);const r=i.data,o=[];let c=0;r.webdriver!==e.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),r.languages!==e.languages&&(o.push("worker_languages_mismatch"),c+=15),r.platform!==e.platform&&(o.push("worker_platform_mismatch"),c+=15),r.hardwareConcurrency!==e.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),r.userAgent!==e.userAgent&&(o.push("worker_ua_mismatch"),c+=20),t({score:c,mismatches:o})},n.onerror=()=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(s),t({score:0,mismatches:[]})},n.postMessage("check")}catch(i){t({score:0,mismatches:[]})}})}}class HeadlessProbeDetector{constructor(e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=e}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){const e={};let t=0;const i=await this.checkBrokenImage();i.suspicious&&(e.brokenImage=i,t+=25);const s=await this.checkClientHints();s.suspicious&&(e.clientHints=s,t+=20);const n=this.checkCDPMouseSignature();n.suspicious&&(e.cdpMouse=n,t+=30);const a=this.checkHairlineSupport();a.suspicious&&(e.hairline=a,t+=10);const r=this.checkExtraFrameworks();r.length>0&&(e.extraFrameworks=r,t+=20);(await this.checkWorkerCDP()).suspicious&&(e.workerCDP=!0,t+=35),t>0&&this.transmitter.send("headless_probe",{signals:e,score:t,timestamp:Date.now()})}checkBrokenImage(){return new Promise(e=>{try{const t=document.createElement("img");t.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==___invalid";const i=setTimeout(()=>{e({suspicious:!1,width:-1,height:-1})},2e3);t.onerror=()=>{clearTimeout(i);const s=t.width,n=t.height;e({suspicious:0===s&&0===n,width:s,height:n})},t.onload=()=>{clearTimeout(i),e({suspicious:!1,width:t.width,height:t.height})},t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),setTimeout(()=>{try{document.body.removeChild(t)}catch(e){}},100)}catch(t){e({suspicious:!1,width:-1,height:-1})}})}async checkClientHints(){const e=[];try{const t=navigator.userAgentData;if(!t)return{suspicious:!1,mismatches:[]};const i=navigator.userAgent,s=(t.brands||[]).map(e=>e.brand);/Chrome\/\d/.test(i)&&!s.some(e=>/Chromium|Google Chrome|Chrome/.test(e))&&e.push("ua_chrome_no_brand"),t.platform&&(/Windows/.test(i)&&"Windows"!==t.platform&&e.push("ua_windows_brand_mismatch"),/Macintosh/.test(i)&&"macOS"!==t.platform&&e.push("ua_mac_brand_mismatch"),/Linux/.test(i)&&!/Linux|Android|ChromeOS/.test(t.platform)&&e.push("ua_linux_brand_mismatch")),/Mobile/.test(i)&&!1===t.mobile&&e.push("ua_mobile_brand_mismatch")}catch(t){}return{suspicious:e.length>0,mismatches:e}}checkCDPMouseSignature(){let e=0,t=0,i=!1;try{const s=[],n=i=>{s.push(i),t++,0===i.movementX&&0===i.movementY&&e++};document.addEventListener("mousemove",n,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",n)},5e3),t>10&&e/t>.9&&(i=!0)}catch(s){}return{suspicious:i,zeroMovementCount:e,totalEvents:t}}checkHairlineSupport(){try{const e=document.createElement("div");e.style.border=".5px solid transparent",e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e);const t=e.offsetHeight;return document.body.removeChild(e),{suspicious:0===t,offsetHeight:t}}catch(e){return{suspicious:!1,offsetHeight:-1}}}checkExtraFrameworks(){const e=[];try{const i=window.external;if(i&&"function"==typeof i.toString)try{const t=i.toString();/Sequentum/i.test(t)&&e.push("sequentum")}catch(t){}const s=["__webdriver_script_fn","__webdriver_script_func","__webdriver_evaluate","__selenium_evaluate","__fxdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__selenium_unwrapped","__fxdriver_unwrapped","__driver_unwrapped","_Selenium_IDE_Recorder","_selenium","calledSelenium","_WEBDRIVER_ELEM_CACHE","ChromeDriverw","driver-hierarchical","__$webdriverAsyncExecutor","__lastWatirAlert","__lastWatirConfirm","__lastWatirPrompt","_WEBDRIVER_ELEM_CACHE","webdriver","_phantom","__nightmare","_selenium"];for(const t of s)(t in document||t in window)&&e.push(`global_${t}`);const n=Object.getOwnPropertyNames(navigator);for(const t of n)/webdriver|selenium|puppeteer|playwright|phantom/i.test(t)&&e.push(`nav_${t}`)}catch(t){}return e}checkWorkerCDP(){return new Promise(e=>{try{const t=new Blob(["\n self.onmessage = function() {\n var detected = false;\n try {\n var marker = {};\n Object.defineProperty(marker, 'stack', {\n get: function() { detected = true; return ''; }\n });\n console.debug(marker);\n } catch(e) {}\n self.postMessage({ cdp: detected });\n };\n "],{type:"application/javascript"}),i=URL.createObjectURL(t),s=new Worker(i),n=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(i),e({suspicious:!1})},3e3);s.onmessage=t=>{clearTimeout(n),s.terminate(),URL.revokeObjectURL(i),e({suspicious:!0===t.data.cdp})},s.onerror=()=>{clearTimeout(n),s.terminate(),URL.revokeObjectURL(i),e({suspicious:!1})},s.postMessage("check")}catch(t){e({suspicious:!1})}})}}class CrawlProtect{constructor(e){__publicField(this,"config"),__publicField(this,"renewTimer",null),__publicField(this,"verified",!1),this.config=e}async start(){const e=this.getToken();if(e&&!this.isExpired(e))return this.verified=!0,this.scheduleRenewal(e),this.revealContent(),this.config.debug,!0;this.hideContent();const t=await this.solveChallenge();return t?(this.verified=!0,this.revealContent()):this.config.insertHoneypot&&this.insertHoneypotData(),t}isVerified(){return this.verified}stop(){this.renewTimer&&(clearTimeout(this.renewTimer),this.renewTimer=null)}async solveChallenge(){try{const e=await fetch(`${this.config.apiBase}/crawl-protect/challenge`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId}});if(!e.ok)return!1;const{id:t,challenges:i}=await e.json(),s=[];for(const c of i)if("math"===c.type){const e="add"===c.op?c.a+c.b:c.a*c.b;s.push(String(e))}else if("crypto"===c.type){const e=await this.sha256(c.nonce);s.push(e.slice(0,8))}const n=s.join(":"),a=await this.getFingerprint(),r=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:t,solution:n,fingerprint:a}),credentials:"include"});if(!r.ok)return!1;const o=await r.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(e){return this.config.debug,!1}}hideContent(){var e;if(null==(e=this.config.protectSelectors)?void 0:e.length)for(const t of this.config.protectSelectors){document.querySelectorAll(t).forEach(e=>{e.dataset.aieOrigDisplay=e.style.display,e.style.display="none"})}}revealContent(){var e;if(null==(e=this.config.protectSelectors)?void 0:e.length)for(const t of this.config.protectSelectors){document.querySelectorAll(t).forEach(e=>{e.style.display=e.dataset.aieOrigDisplay||"",delete e.dataset.aieOrigDisplay})}}insertHoneypotData(){const e=document.createElement("div");e.style.cssText="position:absolute;left:-9999px;top:-9999px;opacity:0;pointer-events:none;",e.setAttribute("aria-hidden","true"),e.innerHTML='\n <span class="price" data-aie-honeypot="1">âŠ999,999,999</span>\n <span class="stock" data-aie-honeypot="1">ěŹęł : 0ę°</span>\n <a href="mailto:honeypot@aientrophy.com" data-aie-honeypot="1">contact</a>\n ',document.body.appendChild(e)}getToken(){const e=document.cookie.match(new RegExp("(?:^|; )__aie_token=([^;]*)"));return e?decodeURIComponent(e[1]):null}setToken(e){const t=new Date(Date.now()+18e5).toUTCString();document.cookie=`__aie_token=${encodeURIComponent(e)};path=/;expires=${t};SameSite=None;Secure`}isExpired(e){try{const[t]=e.split("."),i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")));return Date.now()>i.exp}catch{return!0}}scheduleRenewal(e){try{const[t]=e.split("."),i=JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/"))),s=i.exp-3e5-Date.now();s>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),s))}catch{}}async sha256(e){const t=new TextEncoder,i=await crypto.subtle.digest("SHA-256",t.encode(e));return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}async getFingerprint(){const e=[navigator.userAgent,navigator.language,screen.width+"x"+screen.height,Intl.DateTimeFormat().resolvedOptions().timeZone];return this.sha256(e.join("|"))}}const securitySDK=new class{constructor(){__publicField(this,"transmitter"),__publicField(this,"behaviorCollector"),__publicField(this,"rapidClickDetector"),__publicField(this,"honeypot"),__publicField(this,"mouseTracker"),__publicField(this,"canvasFingerprinter"),__publicField(this,"inputTracker"),__publicField(this,"challengeHandler"),__publicField(this,"invisibleInteraction"),__publicField(this,"automationDetector"),__publicField(this,"sessionAnalyzer"),__publicField(this,"tabNavigationAnalyzer"),__publicField(this,"cloudEnvironmentDetector"),__publicField(this,"crossContextDetector"),__publicField(this,"headlessProbeDetector"),__publicField(this,"crawlProtect",null),__publicField(this,"initialized",!1),__publicField(this,"wasmService"),__publicField(this,"callbackManager"),this.transmitter=new Transmitter,this.wasmService=new WasmService,this.callbackManager=new CallbackManager,this.transmitter.setCallbackManager(this.callbackManager),this.behaviorCollector=new BehaviorCollector(this.transmitter),this.rapidClickDetector=new RapidClickDetector(this.transmitter),this.honeypot=new Honeypot(this.transmitter),this.mouseTracker=new MouseTracker(this.transmitter,this.wasmService),this.canvasFingerprinter=new CanvasFingerprinter(this.transmitter,this.wasmService),this.inputTracker=new InputTracker(this.transmitter),this.invisibleInteraction=new InvisibleInteraction(this.transmitter),this.automationDetector=new AutomationDetector(this.transmitter),this.sessionAnalyzer=new SessionAnalyzer(this.transmitter),this.tabNavigationAnalyzer=new TabNavigationAnalyzer(this.transmitter),this.cloudEnvironmentDetector=new CloudEnvironmentDetector(this.transmitter),this.crossContextDetector=new CrossContextDetector(this.transmitter),this.headlessProbeDetector=new HeadlessProbeDetector(this.transmitter)}async init(e){var t,i;if(this.initialized)return;e.callbacks&&this.callbackManager.setConfigCallbacks(e.callbacks);const s=e.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(s),this.startDetectors(),this.transmitter.setConfig(e),this.challengeHandler=new ChallengeHandler(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(t=e.serverConfig)?void 0:t.captchaEnabled)&&this.challengeHandler.start();((null==(i=e.serverConfig)?void 0:i.devtoolsDetection)??!e.debug)&&Promise.resolve().then(()=>require("../anti-debug-CYwG4s7P.cjs")).then(({AntiDebug:e})=>{e.start(),Promise.resolve().then(()=>require("../console-aIpHQlgP.cjs")).then(({ConsoleDetector:e})=>{new e(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),e.crawlProtect&&(this.crawlProtect=new CrawlProtect({apiBase:s,clientId:e.clientKey,protectSelectors:e.crawlProtect.protectSelectors,insertHoneypot:e.crawlProtect.insertHoneypot,debug:e.debug}),this.crawlProtect.start().catch(t=>{e.debug})),this.initialized=!0,e.debug,this.callbackManager.emit("ready")}catch(n){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==n?void 0:n.message})}}on(e,t){this.callbackManager.on(e,t)}off(e,t){this.callbackManager.off(e,t)}once(e,t){this.callbackManager.once(e,t)}startDetectors(){this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start()}};"undefined"!=typeof window&&(window.SecuritySDK=securitySDK);exports.Aientrophy=class{constructor(e){__publicField(this,"config"),this.config=e}async protect(){const e=this.config.endpoint||"https://api.aientrophy.com/api/v1/events";let t={};try{const s=e.replace(/\/events$/,""),n=await fetch(`${s}/sdk/payload?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(n.ok){t=(await n.json()).config||{}}if(t.nonceValidation)try{const e=await fetch(`${s}/sdk/nonce?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(e.ok){const i=await e.json();i.nonce&&(t.initialNonce=i.nonce)}}catch(i){this.config.debug}}catch(i){this.config.debug}await securitySDK.init({endpoint:e,clientKey:this.config.clientKey,debug:this.config.debug,callbacks:this.config.callbacks,crawlProtect:this.config.crawlProtect,serverConfig:t})}on(e,t){securitySDK.on(e,t)}off(e,t){securitySDK.off(e,t)}once(e,t){securitySDK.once(e,t)}};
|
package/dist/npm/index.es.js
CHANGED
package/package.json
CHANGED